forked from jarun/nnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnnn.c
3505 lines (2979 loc) · 74.4 KB
/
nnn.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* See LICENSE file for copyright and license details. */
/*
* Visual layout:
* .---------
* | DIR: /mnt/path
* |
* | file0
* | file1
* | > file2
* | file3
* | file4
* ...
* | filen
* |
* | Permission denied
* '------
*/
#ifdef __linux__
#ifdef __i386__
#define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
#endif
#include <sys/inotify.h>
#define LINUX_INOTIFY
#if !defined(__GLIBC__)
#include <sys/types.h>
#endif
#endif
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#define BSD_KQUEUE
#else
#include <sys/sysmacros.h>
#endif
#include <sys/wait.h>
#include <ctype.h>
#ifdef __linux__ /* Fix failure due to mvaddnwstr() */
#ifndef NCURSES_WIDECHAR
#define NCURSES_WIDECHAR 1
#endif
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
#ifndef _XOPEN_SOURCE_EXTENDED
#define _XOPEN_SOURCE_EXTENDED
#endif
#endif
#ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
#define __USE_XOPEN
#endif
#include <curses.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <libgen.h>
#include <limits.h>
#ifdef __gnu_hurd__
#define PATH_MAX 4096
#endif
#include <locale.h>
#include <pwd.h>
#include <regex.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <readline/history.h>
#include <readline/readline.h>
#ifndef __USE_XOPEN_EXTENDED
#define __USE_XOPEN_EXTENDED 1
#endif
#include <ftw.h>
#include <wchar.h>
#include "nnn.h"
#ifdef DEBUGMODE
static int DEBUG_FD;
static int
xprintf(int fd, const char *fmt, ...)
{
char buf[BUFSIZ];
int r;
va_list ap;
va_start(ap, fmt);
r = vsnprintf(buf, sizeof(buf), fmt, ap);
if (r > 0)
r = write(fd, buf, r);
va_end(ap);
return r;
}
static int
enabledbg()
{
FILE *fp = fopen("/tmp/nnn_debug", "w");
if (!fp) {
fprintf(stderr, "Cannot open debug file\n");
return -1;
}
DEBUG_FD = fileno(fp);
if (DEBUG_FD == -1) {
fprintf(stderr, "Cannot open debug file descriptor\n");
return -1;
}
return 0;
}
static void
disabledbg()
{
close(DEBUG_FD);
}
#define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
#define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
#define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
#define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
#else
#define DPRINTF_D(x)
#define DPRINTF_U(x)
#define DPRINTF_S(x)
#define DPRINTF_P(x)
#endif /* DEBUGMODE */
/* Macro definitions */
#define VERSION "1.8"
#define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
#define LEN(x) (sizeof(x) / sizeof(*(x)))
#undef MIN
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#define ISODD(x) ((x) & 1)
#define TOUPPER(ch) \
(((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
#define MAX_CMD_LEN 5120
#define CWD "DIR: "
#define CURSR " > "
#define EMPTY " "
#define CURSYM(flag) (flag ? CURSR : EMPTY)
#define FILTER '/'
#define REGEX_MAX 128
#define BM_MAX 10
#define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
#define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
#define DESCRIPTOR_LEN 32
#define _ALIGNMENT 0x10
#define _ALIGNMENT_MASK 0xF
/* Macros to define process spawn behaviour as flags */
#define F_NONE 0x00 /* no flag set */
#define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
#define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
#define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
#define F_SIGINT 0x08 /* restore default SIGINT handler */
#define F_NORMAL 0x80 /* spawn child process in non-curses regular CLI mode */
/* CRC8 macros */
#define WIDTH (8 * sizeof(unsigned char))
#define TOPBIT (1 << (WIDTH - 1))
#define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
#define CRC8_TABLE_LEN 256
/* Volume info */
#define FREE 0
#define CAPACITY 1
/* Function macros */
#define exitcurses() endwin()
#define clearprompt() printmsg("")
#define printwarn() printmsg(strerror(errno))
#define istopdir(path) (path[1] == '\0' && path[0] == '/')
#define copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
#define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
#define settimeout() timeout(1000)
#define cleartimeout() timeout(-1)
#define errexit() printerr(__LINE__)
#ifdef LINUX_INOTIFY
#define EVENT_SIZE (sizeof(struct inotify_event))
#define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
#elif defined(BSD_KQUEUE)
#define NUM_EVENT_SLOTS 1
#define NUM_EVENT_FDS 1
#endif
/* TYPE DEFINITIONS */
typedef unsigned long ulong;
typedef unsigned int uint;
typedef unsigned char uchar;
/* STRUCTURES */
/* Directory entry */
typedef struct entry {
char *name;
time_t t;
off_t size;
blkcnt_t blocks; /* number of 512B blocks allocated */
mode_t mode;
uint nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
} __attribute__ ((packed, aligned(_ALIGNMENT))) *pEntry;
/* Bookmark */
typedef struct {
char *key;
char *loc;
} bm;
/* Settings */
typedef struct {
ushort filtermode : 1; /* Set to enter filter mode */
ushort mtimeorder : 1; /* Set to sort by time modified */
ushort sizeorder : 1; /* Set to sort by file size */
ushort blkorder : 1; /* Set to sort by blocks used (disk usage) */
ushort showhidden : 1; /* Set to show hidden files */
ushort copymode : 1; /* Set when copying files */
ushort showdetail : 1; /* Clear to show fewer file info */
ushort showcolor : 1; /* Set to show dirs in blue */
ushort dircolor : 1; /* Current status of dir color */
ushort metaviewer : 1; /* Index of metadata viewer in utils[] */
ushort quote : 1; /* Copy paths within quotes */
ushort noxdisplay : 1; /* X11 is not available */
ushort color : 3; /* Color code for directories */
} settings;
/* GLOBALS */
/* Configuration */
static settings cfg = {0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 4};
static struct entry *dents;
static char *pnamebuf, *pcopybuf;
static int ndents, cur, total_dents = ENTRY_INCR;
static uint idle;
static uint idletimeout, copybufpos, copybuflen;
static char *player;
static char *copier;
static char *editor;
static char *desktop_manager;
static blkcnt_t ent_blocks;
static blkcnt_t dir_blocks;
static ulong num_files;
static uint open_max;
static bm bookmark[BM_MAX];
static uchar crc8table[CRC8_TABLE_LEN];
static uchar g_crc;
#ifdef LINUX_INOTIFY
static int inotify_fd, inotify_wd = -1;
static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
#elif defined(BSD_KQUEUE)
static int kq, event_fd = -1;
static struct kevent events_to_monitor[NUM_EVENT_FDS];
static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
static struct timespec gtimeout;
#endif
/* Macros for utilities */
#define MEDIAINFO 0
#define EXIFTOOL 1
#define OPENER 2
#define NLAY 3
#define ATOOL 4
#define APACK 5
#define VIDIR 6
#define UNKNOWN 7
/* Utilities to open files, run actions */
static char * const utils[] = {
"mediainfo",
"exiftool",
#ifdef __APPLE__
"/usr/bin/open",
#elif defined __CYGWIN__
"cygstart",
#else
"xdg-open",
#endif
"nlay",
"atool",
"apack",
"vidir",
"UNKNOWN"
};
/* Common strings */
#define STR_NFTWFAIL_ID 0
#define STR_NOHOME_ID 1
#define STR_INPUT_ID 2
#define STR_INVBM_ID 3
#define STR_COPY_ID 4
#define STR_DATE_ID 5
static const char messages[][16] = {
"nftw failed",
"HOME not set",
"no traversal",
"invalid key",
"copy not set",
"%F %T %z",
};
/* For use in functions which are isolated and don't return the buffer */
static char g_buf[MAX_CMD_LEN] __attribute__ ((aligned));
/* Buffer for file path copy file */
static char g_cppath[48] __attribute__ ((aligned));
/* Forward declarations */
static void redraw(char *path);
/* Functions */
/*
* CRC8 source:
* https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
*/
static void
crc8init()
{
uchar remainder, bit;
uint dividend;
/* Compute the remainder of each possible dividend */
for (dividend = 0; dividend < CRC8_TABLE_LEN; ++dividend) {
/* Start with the dividend followed by zeros */
remainder = dividend << (WIDTH - 8);
/* Perform modulo-2 division, a bit at a time */
for (bit = 8; bit > 0; --bit) {
/* Try to divide the current data bit */
if (remainder & TOPBIT)
remainder = (remainder << 1) ^ POLYNOMIAL;
else
remainder = (remainder << 1);
}
/* Store the result into the table */
crc8table[dividend] = remainder;
}
}
static uchar
crc8fast(uchar const message[], size_t n)
{
static uchar data, remainder;
static size_t byte;
/* Divide the message by the polynomial, a byte at a time */
for (remainder = byte = 0; byte < n; ++byte) {
data = message[byte] ^ (remainder >> (WIDTH - 8));
remainder = crc8table[data] ^ (remainder << 8);
}
/* The final remainder is the CRC */
return remainder;
}
/* Messages show up at the bottom */
static void
printmsg(const char *msg)
{
mvprintw(LINES - 1, 0, "%s\n", msg);
}
/* Kill curses and display error before exiting */
static void
printerr(int linenum)
{
exitcurses();
fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
exit(1);
}
/* Print prompt on the last line */
static void
printprompt(char *str)
{
clearprompt();
printw(str);
}
/* Increase the limit on open file descriptors, if possible */
static rlim_t
max_openfds()
{
struct rlimit rl;
rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
if (limit != 0)
return 32;
limit = rl.rlim_cur;
rl.rlim_cur = rl.rlim_max;
/* Return ~75% of max possible */
if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
limit = rl.rlim_max - (rl.rlim_max >> 2);
/*
* 20K is arbitrary. If the limit is set to max possible
* value, the memory usage increases to more than double.
*/
return limit > 20480 ? 20480 : limit;
}
return limit;
}
/*
* Wrapper to realloc()
* Frees current memory if realloc() fails and returns NULL.
*
* As per the docs, the *alloc() family is supposed to be memory aligned:
* Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
* OS X: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
*/
static void *
xrealloc(void *pcur, size_t len)
{
static void *pmem;
pmem = realloc(pcur, len);
if (!pmem && pcur)
free(pcur);
return pmem;
}
/*
* Just a safe strncpy(3)
* Always null ('\0') terminates if both src and dest are valid pointers.
* Returns the number of bytes copied including terminating null byte.
*/
static size_t
xstrlcpy(char *dest, const char *src, size_t n)
{
static ulong *s, *d;
static size_t len, blocks;
static const uint lsize = sizeof(ulong);
static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
if (!src || !dest || !n)
return 0;
len = strlen(src) + 1;
if (n > len)
n = len;
else if (len > n)
/* Save total number of bytes to copy in len */
len = n;
/*
* To enable -O3 ensure src and dest are 16-byte aligned
* More info: http://www.felixcloutier.com/x86/MOVDQA.html
*/
if ((n >= lsize) && (((ulong)src & _ALIGNMENT_MASK) == 0 && ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
s = (ulong *)src;
d = (ulong *)dest;
blocks = n >> _WSHIFT;
n &= lsize - 1;
while (blocks) {
*d = *s;
++d, ++s;
--blocks;
}
if (!n) {
dest = (char *)d;
*--dest = '\0';
return len;
}
src = (char *)s;
dest = (char *)d;
}
while (--n && (*dest = *src))
++dest, ++src;
if (!n)
*dest = '\0';
return len;
}
/*
* The poor man's implementation of memrchr(3).
* We are only looking for '/' in this program.
* And we are NOT expecting a '/' at the end.
* Ideally 0 < n <= strlen(s).
*/
static void *
xmemrchr(uchar *s, uchar ch, size_t n)
{
static uchar *ptr;
if (!s || !n)
return NULL;
ptr = s + n;
do {
--ptr;
if (*ptr == ch)
return ptr;
} while (s != ptr);
return NULL;
}
/*
* The following dirname(3) implementation does not
* modify the input. We use a copy of the original.
*
* Modified from the glibc (GNU LGPL) version.
*/
static char *
xdirname(const char *path)
{
static char * const buf = g_buf, *last_slash, *runp;
xstrlcpy(buf, path, PATH_MAX);
/* Find last '/'. */
last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
/* Determine whether all remaining characters are slashes. */
for (runp = last_slash; runp != buf; --runp)
if (runp[-1] != '/')
break;
/* The '/' is the last character, we have to look further. */
if (runp != buf)
last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
}
if (last_slash != NULL) {
/* Determine whether all remaining characters are slashes. */
for (runp = last_slash; runp != buf; --runp)
if (runp[-1] != '/')
break;
/* Terminate the buffer. */
if (runp == buf) {
/* The last slash is the first character in the string.
* We have to return "/". As a special case we have to
* return "//" if there are exactly two slashes at the
* beginning of the string. See XBD 4.10 Path Name
* Resolution for more information.
*/
if (last_slash == buf + 1)
++last_slash;
else
last_slash = buf + 1;
} else
last_slash = runp;
last_slash[0] = '\0';
} else {
/* This assignment is ill-designed but the XPG specs require to
* return a string containing "." in any case no directory part
* is found and so a static and constant string is required.
*/
buf[0] = '.';
buf[1] = '\0';
}
return buf;
}
static char *
xbasename(char *path)
{
static char *base;
base = xmemrchr((uchar *)path, '/', strlen(path));
return base ? base + 1 : path;
}
/* Writes buflen char(s) from buf to a file */
static void
writecp(const char *buf, const size_t buflen)
{
FILE *fp = fopen(g_cppath, "w");
if (fp) {
fwrite(buf, 1, buflen, fp);
fclose(fp);
} else
printwarn();
}
static bool
appendfpath(const char *path, const size_t len)
{
if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
copybuflen += PATH_MAX;
pcopybuf = xrealloc(pcopybuf, copybuflen);
if (!pcopybuf) {
printmsg("no memory!");
return FALSE;
}
}
if (copybufpos) {
pcopybuf[copybufpos - 1] = '\n';
if (cfg.quote) {
pcopybuf[copybufpos] = '\'';
++copybufpos;
}
} else if (cfg.quote) {
pcopybuf[copybufpos] = '\'';
++copybufpos;
}
copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
if (cfg.quote) {
pcopybuf[copybufpos - 1] = '\'';
pcopybuf[copybufpos] = '\0';
++copybufpos;
}
return TRUE;
}
/*
* Return number of dots if all chars in a string are dots, else 0
*/
static int
all_dots(const char *path)
{
int count = 0;
if (!path)
return FALSE;
while (*path == '.')
++count, ++path;
if (*path)
return 0;
return count;
}
/* Initialize curses mode */
static void
initcurses(void)
{
if (initscr() == NULL) {
char *term = getenv("TERM");
if (term != NULL)
fprintf(stderr, "error opening TERM: %s\n", term);
else
fprintf(stderr, "initscr() failed\n");
exit(1);
}
cbreak();
noecho();
nonl();
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);
curs_set(FALSE); /* Hide cursor */
start_color();
use_default_colors();
if (cfg.showcolor)
init_pair(1, cfg.color, -1);
settimeout(); /* One second */
}
/*
* Spawns a child process. Behaviour can be controlled using flag.
* Limited to 2 arguments to a program, flag works on bit set.
*/
static void
spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
{
static char *shlvl;
static pid_t pid;
static int status;
if (flag & F_NORMAL)
exitcurses();
pid = fork();
if (pid == 0) {
if (dir != NULL)
status = chdir(dir);
shlvl = getenv("SHLVL");
/* Show a marker (to indicate nnn spawned shell) */
if (flag & F_MARKER && shlvl != NULL) {
printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
printf("Next shell level: %d\n", atoi(shlvl) + 1);
}
/* Suppress stdout and stderr */
if (flag & F_NOTRACE) {
int fd = open("/dev/null", O_WRONLY, 0200);
dup2(fd, 1);
dup2(fd, 2);
close(fd);
}
if (flag & F_NOWAIT) {
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
setsid();
}
if (flag & F_SIGINT)
signal(SIGINT, SIG_DFL);
execlp(file, file, arg1, arg2, NULL);
_exit(1);
} else {
if (!(flag & F_NOWAIT))
/* Ignore interruptions */
while (waitpid(pid, &status, 0) == -1)
DPRINTF_D(status);
DPRINTF_D(pid);
if (flag & F_NORMAL)
refresh();
}
}
/* Get program name from env var, else return fallback program */
static char *
xgetenv(const char *name, char *fallback)
{
static char *value;
if (name == NULL)
return fallback;
value = getenv(name);
return value && value[0] ? value : fallback;
}
/* Check if a dir exists, IS a dir and is readable */
static bool
xdiraccess(const char *path)
{
static DIR *dirp;
dirp = opendir(path);
if (dirp == NULL) {
printwarn();
return FALSE;
}
closedir(dirp);
return TRUE;
}
/*
* We assume none of the strings are NULL.
*
* Let's have the logic to sort numeric names in numeric order.
* E.g., the order '1, 10, 2' doesn't make sense to human eyes.
*
* If the absolute numeric values are same, we fallback to alphasort.
*/
static int
xstricmp(const char * const s1, const char * const s2)
{
static const char *c1, *c2;
c1 = s1;
while (isspace(*c1))
++c1;
c2 = s2;
while (isspace(*c2))
++c2;
if (*c1 == '-' || *c1 == '+')
++c1;
if (*c2 == '-' || *c2 == '+')
++c2;
if (isdigit(*c1) && isdigit(*c2)) {
while (*c1 >= '0' && *c1 <= '9')
++c1;
while (isspace(*c1))
++c1;
while (*c2 >= '0' && *c2 <= '9')
++c2;
while (isspace(*c2))
++c2;
}
if (!*c1 && !*c2) {
static long long num1, num2;
num1 = strtoll(s1, NULL, 10);
num2 = strtoll(s2, NULL, 10);
if (num1 != num2) {
if (num1 > num2)
return 1;
else
return -1;
}
}
return strcoll(s1, s2);
}
/* Return the integer value of a char representing HEX */
static char
xchartohex(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
c = TOUPPER(c);
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return c;
}
/* Trim all whitespace from both ends, / from end */
static char *
strstrip(char *s)
{
if (!s || !*s)
return s;
size_t len = strlen(s) - 1;
while (len != 0 && (isspace(s[len]) || s[len] == '/'))
--len;
s[len + 1] = '\0';
while (*s && isspace(*s))
++s;
return s;
}
static char *
getmime(const char *file)
{
static regex_t regex;
static uint i;
static const uint len = LEN(assocs);
for (i = 0; i < len; ++i) {
if (regcomp(®ex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
continue;
if (regexec(®ex, file, 0, NULL, 0) == 0) {
regfree(®ex);
return assocs[i].mime;
}
}
regfree(®ex);
return NULL;
}
static int
setfilter(regex_t *regex, char *filter)
{
static size_t len;
static int r;
r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
if (r != 0 && filter && filter[0] != '\0') {
len = COLS;
if (len > NAME_MAX)
len = NAME_MAX;
regerror(r, regex, g_buf, len);
printmsg(g_buf);
}
return r;
}
static void
initfilter(int dot, char **ifilter)
{
*ifilter = dot ? "." : "^[^.]";
}
static int
visible(regex_t *regex, char *file)
{
return regexec(regex, file, 0, NULL, 0) == 0;
}
static int
entrycmp(const void *va, const void *vb)
{
static pEntry pa, pb;
pa = (pEntry)va;
pb = (pEntry)vb;
/* Sort directories first */
if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
return 1;
else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
return -1;
/* Do the actual sorting */
if (cfg.mtimeorder)
return pb->t - pa->t;
if (cfg.sizeorder) {
if (pb->size > pa->size)
return 1;
else if (pb->size < pa->size)
return -1;
}
if (cfg.blkorder) {
if (pb->blocks > pa->blocks)
return 1;
else if (pb->blocks < pa->blocks)
return -1;
}
return xstricmp(pa->name, pb->name);
}
/*
* Returns SEL_* if key is bound and 0 otherwise.
* Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
* The next keyboard input can be simulated by presel.
*/
static int
nextsel(char **run, char **env, int *presel)
{
static int c;
static uint i;
static const uint len = LEN(bindings);
#ifdef LINUX_INOTIFY
static char inotify_buf[EVENT_BUF_LEN];
#elif defined(BSD_KQUEUE)
static struct kevent event_data[NUM_EVENT_SLOTS];
#endif
c = *presel;
if (c == 0)
c = getch();
else {
*presel = 0;
/* Unwatch dir if we are still in a filtered view */
#ifdef LINUX_INOTIFY
if (inotify_wd >= 0) {
inotify_rm_watch(inotify_fd, inotify_wd);
inotify_wd = -1;
}
#elif defined(BSD_KQUEUE)
if (event_fd >= 0) {
close(event_fd);
event_fd = -1;
}
#endif
}
if (c == -1) {
++idle;
/* Do not check for directory changes in du
* mode. A redraw forces du calculation.
* Check for changes every odd second.
*/
#ifdef LINUX_INOTIFY
if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)