-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnnn.c
6142 lines (5208 loc) · 135 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
/*
* BSD 2-Clause License
*
* Copyright (C) 2014-2016, Lazaros Koromilas <[email protected]>
* Copyright (C) 2014-2016, Dimitris Papastamos <[email protected]>
* Copyright (C) 2016-2020, Arun Prakash Jana <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __linux__
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#if defined(__arm__) || defined(__i386__)
#define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
#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
#elif defined(__HAIKU__)
#include "../misc/haiku/haiku_interop.h"
#define HAIKU_NM
#else
#include <sys/sysmacros.h>
#endif
#include <sys/wait.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__) || defined(__sun)
#ifndef _XOPEN_SOURCE_EXTENDED
#define _XOPEN_SOURCE_EXTENDED
#endif
#endif
#ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
#define __USE_XOPEN
#endif
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#ifdef __gnu_hurd__
#define PATH_MAX 4096
#endif
#ifndef NOLOCALE
#include <locale.h>
#endif
#include <stdio.h>
#ifndef NORL
#include <readline/history.h>
#include <readline/readline.h>
#endif
#include <regex.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#ifdef __sun
#include <alloca.h>
#endif
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#ifndef __USE_XOPEN_EXTENDED
#define __USE_XOPEN_EXTENDED 1
#endif
#include <ftw.h>
#include <wchar.h>
#include "nnn.h"
#include "dbg.h"
/* Macro definitions */
#define VERSION "2.8.1"
#define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
#define SESSIONS_VERSION 1
#ifndef S_BLKSIZE
#define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
#endif
#define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
#define DOUBLECLICK_INTERVAL_NS (400000000)
#define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
#define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
#undef MIN
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#undef MAX
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define ISODD(x) ((x) & 1)
#define ISBLANK(x) ((x) == ' ' || (x) == '\t')
#define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
#define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
#define READLINE_MAX 128
#define FILTER '/'
#define RFILTER '\\'
#define CASE ':'
#define MSGWAIT '$'
#define REGEX_MAX 48
#define BM_MAX 10
#define PLUGIN_MAX 15
#define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
#define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
#define DESCRIPTOR_LEN 32
#define _ALIGNMENT 0x10 /* 16-byte alignment */
#define _ALIGNMENT_MASK 0xF
#define TMP_LEN_MAX 64
#define CTX_MAX 4
#define DOT_FILTER_LEN 7
#define ASCII_MAX 128
#define EXEC_ARGS_MAX 8
#define SCROLLOFF 3
#define MIN_DISPLAY_COLS 10
#define LONG_SIZE sizeof(ulong)
#define ARCHIVE_CMD_LEN 16
#define BLK_SHIFT_512 9
/* Program return codes */
#define _SUCCESS 0
#define _FAILURE !_SUCCESS
/* Entry flags */
#define DIR_OR_LINK_TO_DIR 0x1
#define FILE_SELECTED 0x10
/* Macros to define process spawn behaviour as flags */
#define F_NONE 0x00 /* no flag set */
#define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
#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_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
#define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
#define F_CLI (F_NORMAL | F_MULTI)
#define F_SILENT (F_CLI | F_NOTRACE)
/* Version compare macros */
/*
* states: S_N: normal, S_I: comparing integral part, S_F: comparing
* fractional parts, S_Z: idem but with leading Zeroes only
*/
#define S_N 0x0
#define S_I 0x3
#define S_F 0x6
#define S_Z 0x9
/* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
#define VCMP 2
#define VLEN 3
/* Volume info */
#define FREE 0
#define CAPACITY 1
/* TYPE DEFINITIONS */
typedef unsigned long ulong;
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef long long ll;
/* 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;
ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
uchar flags; /* Flags specific to the file */
} *pEntry;
/* Key-value pairs from env */
typedef struct {
int key;
char *val;
} kv;
typedef struct {
const regex_t *regex;
const char *str;
} fltrexp_t;
/*
* Settings
* NOTE: update default values if changing order
*/
typedef struct {
uint filtermode : 1; /* Set to enter filter mode */
uint mtimeorder : 1; /* Set to sort by time modified */
uint sizeorder : 1; /* Set to sort by file size */
uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
uint extnorder : 1; /* Order by extension */
uint showhidden : 1; /* Set to show hidden files */
uint selmode : 1; /* Set when selecting files */
uint showdetail : 1; /* Clear to show fewer file info */
uint ctxactive : 1; /* Context active or not */
uint reserved : 2;
/* The following settings are global */
uint forcequit : 1; /* Do not confirm when quitting program */
uint curctx : 2; /* Current context number */
uint dircolor : 1; /* Current status of dir color */
uint picker : 1; /* Write selection to user-specified file */
uint pickraw : 1; /* Write selection to sdtout before exit */
uint nonavopen : 1; /* Open file on right arrow or `l` */
uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
uint metaviewer : 1; /* Index of metadata viewer in utils[] */
uint useeditor : 1; /* Use VISUAL to open text files */
uint runplugin : 1; /* Choose plugin mode */
uint runctx : 2; /* The context in which plugin is to be run */
uint regex : 1; /* Use regex filters */
uint x11 : 1; /* Copy to system clipboard and show notis */
uint trash : 1; /* Move removed files to trash */
uint mtime : 1; /* Use modification time (else access time) */
uint cliopener : 1; /* All-CLI app opener */
uint waitedit : 1; /* For ops that can't be detached, used EDITOR */
uint rollover : 1; /* Roll over at edges */
} settings;
/* Contexts or workspaces */
typedef struct {
char c_path[PATH_MAX]; /* Current dir */
char c_last[PATH_MAX]; /* Last visited dir */
char c_name[NAME_MAX + 1]; /* Current file name */
char c_fltr[REGEX_MAX]; /* Current filter */
settings c_cfg; /* Current configuration */
uint color; /* Color code for directories */
} context;
typedef struct {
size_t ver;
size_t pathln[CTX_MAX];
size_t lastln[CTX_MAX];
size_t nameln[CTX_MAX];
size_t fltrln[CTX_MAX];
} session_header_t;
/* GLOBALS */
/* Configuration, contexts */
static settings cfg = {
0, /* filtermode */
0, /* mtimeorder */
0, /* sizeorder */
0, /* apparentsz */
0, /* blkorder */
0, /* extnorder */
0, /* showhidden */
0, /* selmode */
0, /* showdetail */
1, /* ctxactive */
0, /* reserved */
0, /* forcequit */
0, /* curctx */
0, /* dircolor */
0, /* picker */
0, /* pickraw */
0, /* nonavopen */
1, /* autoselect */
0, /* metaviewer */
0, /* useeditor */
0, /* runplugin */
0, /* runctx */
0, /* regex */
0, /* x11 */
0, /* trash */
1, /* mtime */
0, /* cliopener */
0, /* waitedit */
1, /* rollover */
};
static context g_ctx[CTX_MAX] __attribute__ ((aligned));
static int ndents, cur, curscroll, total_dents = ENTRY_INCR;
static int xlines, xcols;
static int nselected;
static uint idle;
static uint idletimeout, selbufpos, lastappendpos, selbuflen;
static char *bmstr;
static char *pluginstr;
static char *opener;
static char *editor;
static char *enveditor;
static char *pager;
static char *shell;
static char *home;
static char *initpath;
static char *cfgdir;
static char *g_selpath;
static char *plugindir;
static char *sessiondir;
static char *pnamebuf, *pselbuf;
static struct entry *dents;
static blkcnt_t ent_blocks;
static blkcnt_t dir_blocks;
static ulong num_files;
static kv bookmark[BM_MAX];
static kv plug[PLUGIN_MAX];
static uchar g_tmpfplen;
static uchar blk_shift = BLK_SHIFT_512;
static regex_t archive_re;
/* Retain old signal handlers */
#ifdef __linux__
static sighandler_t oldsighup; /* old value of hangup signal */
static sighandler_t oldsigtstp; /* old value of SIGTSTP */
#else
/* note: no sig_t on Solaris-derivs */
static void (*oldsighup)(int);
static void (*oldsigtstp)(int);
#endif
/* For use in functions which are isolated and don't return the buffer */
static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
/* Buffer to store tmp file path to show selection, file stats and help */
static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
/* Buffer to store plugins control pipe location */
static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
/* MISC NON-PERSISTENT INTERNAL BINARY STATES */
/* Plugin control initialization status */
#define STATE_PLUGIN_INIT 0x1
#define STATE_INTERRUPTED 0x2
#define STATE_RANGESEL 0x4
static uchar g_states;
/* Options to identify file mime */
#if defined(__APPLE__)
#define FILE_MIME_OPTS "-bIL"
#elif !defined(__sun) /* no mime option for 'file' */
#define FILE_MIME_OPTS "-biL"
#endif
/* Macros for utilities */
#define UTIL_OPENER 0
#define UTIL_ATOOL 1
#define UTIL_BSDTAR 2
#define UTIL_UNZIP 3
#define UTIL_TAR 4
#define UTIL_LOCKER 5
#define UTIL_CMATRIX 6
#define UTIL_LAUNCH 7
#define UTIL_SH_EXEC 8
#define UTIL_ARCHIVEMOUNT 9
#define UTIL_SSHFS 10
#define UTIL_RCLONE 11
#define UTIL_VI 12
#define UTIL_LESS 13
#define UTIL_SH 14
#define UTIL_FZF 15
#define UTIL_FZY 16
#define UTIL_NTFY 17
#define UTIL_CBCP 18
/* Utilities to open files, run actions */
static char * const utils[] = {
#ifdef __APPLE__
"/usr/bin/open",
#elif defined __CYGWIN__
"cygstart",
#elif defined __HAIKU__
"open",
#else
"xdg-open",
#endif
"atool",
"bsdtar",
"unzip",
"tar",
#ifdef __APPLE__
"bashlock",
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
"lock",
#elif defined __HAIKU__
"peaclock",
#else
"vlock",
#endif
"cmatrix",
"launch",
"sh -c",
"archivemount",
"sshfs",
"rclone",
"vi",
"less",
"sh",
"fzf",
"fzy",
".ntfy",
".cbcp",
};
/* Common strings */
#define MSG_NO_TRAVERSAL 0
#define MSG_INVALID_KEY 1
#define STR_TMPFILE 2
#define MSG_0_SELECTED 3
#define MSG_UTIL_MISSING 4
#define MSG_FAILED 5
#define MSG_SSN_NAME 6
#define MSG_CP_MV_AS 7
#define MSG_CUR_SEL_OPTS 8
#define MSG_FORCE_RM 9
#define MSG_CREATE_CTX 10
#define MSG_NEW_OPTS 11
#define MSG_CLI_MODE 12
#define MSG_OVERWRITE 13
#define MSG_SSN_OPTS 14
#define MSG_QUIT_ALL 15
#define MSG_HOSTNAME 16
#define MSG_ARCHIVE_NAME 17
#define MSG_OPEN_WITH 18
#define MSG_REL_PATH 19
#define MSG_LINK_PREFIX 20
#define MSG_COPY_NAME 21
#define MSG_CONTINUE 22
#define MSG_SEL_MISSING 23
#define MSG_ACCESS 24
#define MSG_EMPTY_FILE 25
#define MSG_UNSUPPORTED 26
#define MSG_NOT_SET 27
#define MSG_DIR_CHANGED 28
#define MSG_EXISTS 29
#define MSG_FEW_COLUMNS 30
#define MSG_REMOTE_OPTS 31
#define MSG_RCLONE_DELAY 32
#define MSG_APP_NAME 33
#define MSG_ARCHIVE_OPTS 34
#define MSG_PLUGIN_KEYS 35
#define MSG_BOOKMARK_KEYS 36
#define MSG_INVALID_REG 37
static const char * const messages[] = {
"no traversal",
"invalid key",
"/.nnnXXXXXX",
"0 selected",
"missing util",
"failed!",
"session name: ",
"'c'p / 'm'v as?",
"'c'urrent / 's'el?",
"forcibly remove %s file%s (unrecoverable)?",
"create context %d?",
"'f'ile / 'd'ir / 's'ym / 'h'ard?",
"'c'li / 'g'ui?",
"overwrite?",
"'s'ave / 'l'oad / 'r'estore?",
"Quit all contexts?",
"remote name: ",
"archive name: ",
"open with: ",
"relative path: ",
"link prefix [@ for none]: ",
"copy name: ",
"\nPress Enter to continue",
"open failed",
"dir inaccessible",
"empty: edit or open with",
"unsupported file",
"not set",
"dir changed, range sel off",
"entry exists",
"too few columns!",
"'s'shfs / 'r'clone?",
"may take a while, try refresh",
"app name: ",
"'d'efault, e'x'tract / 'l'ist / 'm'ount?",
"plugin keys:",
"bookmark keys:",
"invalid regex",
};
/* Supported configuration environment variables */
#define NNN_BMS 0
#define NNN_OPENER 1
#define NNN_CONTEXT_COLORS 2
#define NNN_IDLE_TIMEOUT 3
#define NNNLVL 4
#define NNN_PIPE 5
#define NNN_ARCHIVE 6 /* strings end here */
#define NNN_USE_EDITOR 7 /* flags begin here */
#define NNN_TRASH 8
static const char * const env_cfg[] = {
"NNN_BMS",
"NNN_OPENER",
"NNN_CONTEXT_COLORS",
"NNN_IDLE_TIMEOUT",
"NNNLVL",
"NNN_PIPE",
"NNN_ARCHIVE",
"NNN_USE_EDITOR",
"NNN_TRASH",
};
/* Required environment variables */
#define ENV_SHELL 0
#define ENV_VISUAL 1
#define ENV_EDITOR 2
#define ENV_PAGER 3
#define ENV_NCUR 4
static const char * const envs[] = {
"SHELL",
"VISUAL",
"EDITOR",
"PAGER",
"nnn",
};
#ifdef __linux__
static char cp[] = "cpg -giRp";
static char mv[] = "mvg -gi";
#else
static char cp[] = "cp -iRp";
static char mv[] = "mv -i";
#endif
static const char cpmvformatcmd[] = "sed -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s";
static const char cpmvrenamecmd[] = "sed 's|^\\([^#][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' %s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'";
static const char batchrenamecmd[] = "paste -d'\n' %s %s | sed 'N; /^\\(.*\\)\\n\\1$/!p;d' | tr '\n' '\\0' | xargs -0 -n2 mv 2>/dev/null";
static const char archive_regex[] ="\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$";
/* Event handling */
#ifdef LINUX_INOTIFY
#define NUM_EVENT_SLOTS 8 /* Make room for 8 events */
#define EVENT_SIZE (sizeof(struct inotify_event))
#define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
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)
#define NUM_EVENT_SLOTS 1
#define NUM_EVENT_FDS 1
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;
#elif defined(HAIKU_NM)
static bool haiku_nm_active = FALSE;
static haiku_nm_h haiku_hnd = NULL;
#endif
/* Function macros */
#define tolastln() move(xlines - 1, 0)
#define exitcurses() endwin()
#define clearprompt() printmsg("")
#define printwarn(presel) printwait(strerror(errno), presel)
#define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
#define copycurname() xstrlcpy(lastname, dents[cur].name, NAME_MAX + 1)
#define settimeout() timeout(1000)
#define cleartimeout() timeout(-1)
#define errexit() printerr(__LINE__)
#define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (dir_changed = TRUE))
/* We don't care about the return value from strcmp() */
#define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
/* A faster version of xisdigit */
#define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
#define xerror() perror(xitoa(__LINE__))
/* Forward declarations */
static void redraw(char *path);
static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag);
static int (*nftw_fn)(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
static int dentfind(const char *fname, int n);
static void move_cursor(int target, int ignore_scrolloff);
static inline bool getutil(char *util);
static size_t mkpath(const char *dir, const char *name, char *out);
static char *xgetenv(const char *name, char *fallback);
static void plugscript(const char *plugin, char *newpath, uchar flags);
/* Functions */
static void sigint_handler(int sig)
{
(void) sig;
g_states |= STATE_INTERRUPTED;
}
static uint xatoi(const char *str)
{
int val = 0;
if (!str)
return 0;
while (xisdigit(*str)) {
val = val * 10 + (*str - '0');
++str;
}
return val;
}
static char *xitoa(uint val)
{
static char ascbuf[32] = {0};
int i = 30;
if (!val)
return "0";
for (; val && i; --i, val /= 10)
ascbuf[i] = '0' + (val % 10);
return &ascbuf[++i];
}
#ifdef KEY_RESIZE
/* Clear the old prompt */
static void clearoldprompt(void)
{
tolastln();
clrtoeol();
}
#endif
/* Messages show up at the bottom */
static void printmsg(const char *msg)
{
tolastln();
addstr(msg);
addch('\n');
}
static void printwait(const char *msg, int *presel)
{
printmsg(msg);
if (presel)
*presel = MSGWAIT;
}
/* Kill curses and display error before exiting */
static void printerr(int linenum)
{
exitcurses();
perror(xitoa(linenum));
if (!cfg.picker && g_selpath)
unlink(g_selpath);
free(pselbuf);
exit(1);
}
/* Print prompt on the last line */
static void printprompt(const char *str)
{
clearprompt();
addstr(str);
}
static void clearinfoln(void)
{
move(xlines - 2, 0);
addstr("");
}
static void printinfoln(const char *str)
{
clearinfoln();
mvaddstr(xlines - 2, xcols - strlen(str), str);
}
static int get_input(const char *prompt)
{
int r = KEY_RESIZE;
if (prompt)
printprompt(prompt);
cleartimeout();
#ifdef KEY_RESIZE
while (r == KEY_RESIZE) {
r = getch();
if (r == KEY_RESIZE && prompt) {
clearoldprompt();
xlines = LINES;
printprompt(prompt);
}
};
#else
r = getch();
#endif
settimeout();
return r;
}
static int get_cur_or_sel()
{
if (selbufpos && ndents) {
int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
return ((choice == 'c' || choice == 's') ? choice : 0);
}
if (selbufpos)
return 's';
if (ndents)
return 'c';
return 0;
}
static void xdelay(useconds_t delay)
{
refresh();
usleep(delay);
}
static char confirm_force(bool selection)
{
char str[64];
int r;
snprintf(str, 64, messages[MSG_FORCE_RM],
(selection ? xitoa(nselected) : "current"), (selection ? "(s)" : ""));
r = get_input(str);
if (r == 'y' || r == 'Y')
return 'f'; /* forceful */
return 'i'; /* interactive */
}
/* Increase the limit on open file descriptors, if possible */
static rlim_t max_openfds(void)
{
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
* macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
*/
static void *xrealloc(void *pcur, size_t len)
{
void *pmem = realloc(pcur, len);
if (!pmem)
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)
{
if (!src || !dest || !n)
return 0;
ulong *s, *d;
size_t len = strlen(src) + 1, blocks;
const uint _WSHIFT = (LONG_SIZE == 8) ? 3 : 2;
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 >= LONG_SIZE) && (((ulong)src & _ALIGNMENT_MASK) == 0 &&
((ulong)dest & _ALIGNMENT_MASK) == 0)) {
s = (ulong *)src;
d = (ulong *)dest;
blocks = n >> _WSHIFT;
n &= LONG_SIZE - 1;
while (blocks) {
*d = *s; // NOLINT
++d, ++s;
--blocks;
}
if (!n) {
dest = (char *)d;
*--dest = '\0';
return len;
}
src = (char *)s;
dest = (char *)d;
}
while (--n && (*dest = *src)) // NOLINT
++dest, ++src;
if (!n)
*dest = '\0';
return len;
}
static bool is_suffix(const char *str, const char *suffix)
{
if (!str || !suffix)
return FALSE;
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr)
return FALSE;
return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
}
/*
* 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)
{
if (!s || !n)
return NULL;
uchar *ptr = s + n;
do {
--ptr;
if (*ptr == ch)
return ptr;
} while (s != ptr);
return NULL;
}
static char *xbasename(char *path)
{
char *base = xmemrchr((uchar *)path, '/', strlen(path)); // NOLINT
return base ? base + 1 : path;
}
static int create_tmp_file(void)
{
xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - g_tmpfplen);
int fd = mkstemp(g_tmpfpath);
if (fd == -1) {
DPRINTF_S(strerror(errno));
}
return fd;
}
/* Writes buflen char(s) from buf to a file */
static void writesel(const char *buf, const size_t buflen)
{
if (cfg.pickraw || !g_selpath)
return;
FILE *fp = fopen(g_selpath, "w");
if (fp) {
if (fwrite(buf, 1, buflen, fp) != buflen)
printwarn(NULL);
fclose(fp);
} else
printwarn(NULL);
}
static void appendfpath(const char *path, const size_t len)
{
if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
selbuflen += PATH_MAX;
pselbuf = xrealloc(pselbuf, selbuflen);
if (!pselbuf)
errexit();
}
selbufpos += xstrlcpy(pselbuf + selbufpos, path, len);
}
/* Write selected file paths to fd, linefeed separated */
static size_t seltofile(int fd, uint *pcount)
{
uint lastpos, count = 0;
char *pbuf = pselbuf;
size_t pos = 0, len;
ssize_t r;
if (pcount)
*pcount = 0;
if (!selbufpos)
return 0;
lastpos = selbufpos - 1;
while (pos <= lastpos) {
len = strlen(pbuf);
pos += len;
r = write(fd, pbuf, len);
if (r != (ssize_t)len)
return pos;
if (pos <= lastpos) {
if (write(fd, "\n", 1) != 1)
return pos;
pbuf += len + 1;
}
++pos;
++count;
}
if (pcount)
*pcount = count;
return pos;
}
/* List selection from selection buffer */
static bool listselbuf()
{
int fd;
size_t pos;
uint oldpos = selbufpos;
if (!selbufpos)
return FALSE;