My build of nnn with minor changes
 
 
 
 
 
 

5716 lines
124 KiB

  1. /*
  2. * BSD 2-Clause License
  3. *
  4. * Copyright (C) 2014-2016, Lazaros Koromilas <lostd@2f30.org>
  5. * Copyright (C) 2014-2016, Dimitris Papastamos <sin@2f30.org>
  6. * Copyright (C) 2016-2019, Arun Prakash Jana <engineerarun@gmail.com>
  7. * All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions are met:
  11. *
  12. * * Redistributions of source code must retain the above copyright notice, this
  13. * list of conditions and the following disclaimer.
  14. *
  15. * * Redistributions in binary form must reproduce the above copyright notice,
  16. * this list of conditions and the following disclaimer in the documentation
  17. * and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  26. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  27. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #ifdef __linux__
  31. #ifndef _GNU_SOURCE
  32. #define _GNU_SOURCE
  33. #endif
  34. #if defined(__arm__) || defined(__i386__)
  35. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit */
  36. #endif
  37. #include <sys/inotify.h>
  38. #define LINUX_INOTIFY
  39. #if !defined(__GLIBC__)
  40. #include <sys/types.h>
  41. #endif
  42. #endif
  43. #include <sys/resource.h>
  44. #include <sys/stat.h>
  45. #include <sys/statvfs.h>
  46. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  47. #include <sys/types.h>
  48. #include <sys/event.h>
  49. #include <sys/time.h>
  50. #define BSD_KQUEUE
  51. #else
  52. #include <sys/sysmacros.h>
  53. #endif
  54. #include <sys/wait.h>
  55. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  56. #ifndef NCURSES_WIDECHAR
  57. #define NCURSES_WIDECHAR 1
  58. #endif
  59. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(__sun)
  60. #ifndef _XOPEN_SOURCE_EXTENDED
  61. #define _XOPEN_SOURCE_EXTENDED
  62. #endif
  63. #endif
  64. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  65. #define __USE_XOPEN
  66. #endif
  67. #include <dirent.h>
  68. #include <errno.h>
  69. #include <fcntl.h>
  70. #include <libgen.h>
  71. #include <limits.h>
  72. #ifdef __gnu_hurd__
  73. #define PATH_MAX 4096
  74. #endif
  75. #ifndef NOLOCALE
  76. #include <locale.h>
  77. #endif
  78. #include <stdio.h>
  79. #ifndef NORL
  80. #include <readline/history.h>
  81. #include <readline/readline.h>
  82. #endif
  83. #include <regex.h>
  84. #include <signal.h>
  85. #include <stdarg.h>
  86. #include <stdlib.h>
  87. #ifdef __sun
  88. #include <alloca.h>
  89. #endif
  90. #include <string.h>
  91. #include <strings.h>
  92. #include <time.h>
  93. #include <unistd.h>
  94. #ifndef __USE_XOPEN_EXTENDED
  95. #define __USE_XOPEN_EXTENDED 1
  96. #endif
  97. #include <ftw.h>
  98. #include <wchar.h>
  99. #include "nnn.h"
  100. #include "dbg.h"
  101. /* Macro definitions */
  102. #define VERSION "2.7"
  103. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  104. #define SESSIONS_VERSION 0
  105. #ifndef S_BLKSIZE
  106. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  107. #endif
  108. #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
  109. #define DOUBLECLICK_INTERVAL_NS 400000000
  110. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  111. #undef MIN
  112. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  113. #undef MAX
  114. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  115. #define ISODD(x) ((x) & 1)
  116. #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
  117. #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  118. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  119. #define READLINE_MAX 128
  120. #define FILTER '/'
  121. #define MSGWAIT '$'
  122. #define REGEX_MAX 48
  123. #define BM_MAX 10
  124. #define PLUGIN_MAX 15
  125. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  126. #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
  127. #define DESCRIPTOR_LEN 32
  128. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  129. #define _ALIGNMENT_MASK 0xF
  130. #define TMP_LEN_MAX 64
  131. #define CTX_MAX 4
  132. #define DOT_FILTER_LEN 7
  133. #define ASCII_MAX 128
  134. #define EXEC_ARGS_MAX 8
  135. #define SCROLLOFF 3
  136. #define MIN_DISPLAY_COLS 10
  137. #define LONG_SIZE sizeof(ulong)
  138. #define ARCHIVE_CMD_LEN 16
  139. #define BLK_SHIFT_512 9
  140. /* Program return codes */
  141. #define _SUCCESS 0
  142. #define _FAILURE !_SUCCESS
  143. /* Entry flags */
  144. #define DIR_OR_LINK_TO_DIR 0x1
  145. #define FILE_SELECTED 0x10
  146. /* Macros to define process spawn behaviour as flags */
  147. #define F_NONE 0x00 /* no flag set */
  148. #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
  149. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  150. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  151. #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
  152. #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
  153. #define F_CLI (F_NORMAL | F_MULTI)
  154. #define F_SILENT (F_CLI | F_NOTRACE)
  155. /* Version compare macros */
  156. /*
  157. * states: S_N: normal, S_I: comparing integral part, S_F: comparing
  158. * fractional parts, S_Z: idem but with leading Zeroes only
  159. */
  160. #define S_N 0x0
  161. #define S_I 0x3
  162. #define S_F 0x6
  163. #define S_Z 0x9
  164. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  165. #define VCMP 2
  166. #define VLEN 3
  167. /* Volume info */
  168. #define FREE 0
  169. #define CAPACITY 1
  170. /* TYPE DEFINITIONS */
  171. typedef unsigned long ulong;
  172. typedef unsigned int uint;
  173. typedef unsigned char uchar;
  174. typedef unsigned short ushort;
  175. typedef long long ll;
  176. /* STRUCTURES */
  177. /* Directory entry */
  178. typedef struct entry {
  179. char *name;
  180. time_t t;
  181. off_t size;
  182. blkcnt_t blocks; /* number of 512B blocks allocated */
  183. mode_t mode;
  184. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  185. uchar flags; /* Flags specific to the file */
  186. } *pEntry;
  187. /* Key-value pairs from env */
  188. typedef struct {
  189. int key;
  190. char *val;
  191. } kv;
  192. typedef struct {
  193. const regex_t *regex;
  194. const char *str;
  195. } fltrexp_t;
  196. /*
  197. * Settings
  198. * NOTE: update default values if changing order
  199. */
  200. typedef struct {
  201. uint filtermode : 1; /* Set to enter filter mode */
  202. uint mtimeorder : 1; /* Set to sort by time modified */
  203. uint sizeorder : 1; /* Set to sort by file size */
  204. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  205. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  206. uint extnorder : 1; /* Order by extension */
  207. uint showhidden : 1; /* Set to show hidden files */
  208. uint selmode : 1; /* Set when selecting files */
  209. uint showdetail : 1; /* Clear to show fewer file info */
  210. uint ctxactive : 1; /* Context active or not */
  211. uint reserved : 5;
  212. /* The following settings are global */
  213. uint curctx : 2; /* Current context number */
  214. uint dircolor : 1; /* Current status of dir color */
  215. uint picker : 1; /* Write selection to user-specified file */
  216. uint pickraw : 1; /* Write selection to sdtout before exit */
  217. uint nonavopen : 1; /* Open file on right arrow or `l` */
  218. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  219. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  220. uint useeditor : 1; /* Use VISUAL to open text files */
  221. uint runplugin : 1; /* Choose plugin mode */
  222. uint runctx : 2; /* The context in which plugin is to be run */
  223. uint filter_re : 1; /* Use regex filters */
  224. uint filtercmd : 1; /* Run filter as command on no match */
  225. uint trash : 1; /* Move removed files to trash */
  226. uint mtime : 1; /* Use modification time (else access time) */
  227. uint cliopener : 1; /* All-CLI app opener */
  228. } settings;
  229. /* Contexts or workspaces */
  230. typedef struct {
  231. char c_path[PATH_MAX]; /* Current dir */
  232. char c_last[PATH_MAX]; /* Last visited dir */
  233. char c_name[NAME_MAX + 1]; /* Current file name */
  234. char c_fltr[REGEX_MAX]; /* Current filter */
  235. settings c_cfg; /* Current configuration */
  236. uint color; /* Color code for directories */
  237. } context;
  238. typedef struct {
  239. size_t ver;
  240. size_t pathln[CTX_MAX];
  241. size_t lastln[CTX_MAX];
  242. size_t nameln[CTX_MAX];
  243. size_t fltrln[CTX_MAX];
  244. } session_header_t;
  245. /* GLOBALS */
  246. /* Configuration, contexts */
  247. static settings cfg = {
  248. 0, /* filtermode */
  249. 0, /* mtimeorder */
  250. 0, /* sizeorder */
  251. 0, /* apparentsz */
  252. 0, /* blkorder */
  253. 0, /* extnorder */
  254. 0, /* showhidden */
  255. 0, /* selmode */
  256. 0, /* showdetail */
  257. 1, /* ctxactive */
  258. 0, /* reserved */
  259. 0, /* curctx */
  260. 0, /* dircolor */
  261. 0, /* picker */
  262. 0, /* pickraw */
  263. 0, /* nonavopen */
  264. 1, /* autoselect */
  265. 0, /* metaviewer */
  266. 0, /* useeditor */
  267. 0, /* runplugin */
  268. 0, /* runctx */
  269. 1, /* filter_re */
  270. 0, /* filtercmd */
  271. 0, /* trash */
  272. 1, /* mtime */
  273. 0, /* cliopener */
  274. };
  275. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  276. static int ndents, cur, curscroll, total_dents = ENTRY_INCR;
  277. static int xlines, xcols;
  278. static int nselected;
  279. static uint idle;
  280. static uint idletimeout, selbufpos, selbuflen;
  281. static char *bmstr;
  282. static char *pluginstr;
  283. static char *opener;
  284. static char *copier;
  285. static char *editor;
  286. static char *pager;
  287. static char *shell;
  288. static char *home;
  289. static char *initpath;
  290. static char *cfgdir;
  291. static char *g_selpath;
  292. static char *plugindir;
  293. static char *sessiondir;
  294. static char *pnamebuf, *pselbuf;
  295. static struct entry *dents;
  296. static blkcnt_t ent_blocks;
  297. static blkcnt_t dir_blocks;
  298. static ulong num_files;
  299. static kv bookmark[BM_MAX];
  300. static kv plug[PLUGIN_MAX];
  301. static uchar g_tmpfplen;
  302. static uchar blk_shift = BLK_SHIFT_512;
  303. static bool interrupted = FALSE;
  304. /* Retain old signal handlers */
  305. #ifdef __linux__
  306. static sighandler_t oldsighup; /* old value of hangup signal */
  307. static sighandler_t oldsigtstp; /* old value of SIGTSTP */
  308. #else
  309. /* note: no sig_t on Solaris-derivs */
  310. static void (*oldsighup)(int);
  311. static void (*oldsigtstp)(int);
  312. #endif
  313. /* For use in functions which are isolated and don't return the buffer */
  314. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  315. /* Buffer to store tmp file path to show selection, file stats and help */
  316. static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
  317. /* Buffer to store plugins control pipe location */
  318. static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
  319. /* Plugin control initialization status */
  320. static bool g_plinit = FALSE;
  321. /* Options to identify file mime */
  322. #if defined(__APPLE__)
  323. #define FILE_MIME_OPTS "-bIL"
  324. #elif !defined(__sun) /* no mime option for 'file' */
  325. #define FILE_MIME_OPTS "-biL"
  326. #endif
  327. /* Macros for utilities */
  328. #define OPENER 0
  329. #define ATOOL 1
  330. #define BSDTAR 2
  331. #define UNZIP 3
  332. #define TAR 4
  333. #define LOCKER 5
  334. #define CMATRIX 6
  335. #define NLAUNCH 7
  336. #define SH_EXEC 8
  337. /* Utilities to open files, run actions */
  338. static char * const utils[] = {
  339. #ifdef __APPLE__
  340. "/usr/bin/open",
  341. #elif defined __CYGWIN__
  342. "cygstart",
  343. #else
  344. "xdg-open",
  345. #endif
  346. "atool",
  347. "bsdtar",
  348. "unzip",
  349. "tar",
  350. #ifdef __APPLE__
  351. "bashlock",
  352. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  353. "lock",
  354. #else
  355. "vlock",
  356. #endif
  357. "cmatrix",
  358. "nlaunch",
  359. "sh -c",
  360. };
  361. #ifdef __linux__
  362. static char cp[] = "cpg -giRp";
  363. static char mv[] = "mvg -gi";
  364. #else
  365. static char cp[] = "cp -iRp";
  366. static char mv[] = "mv -i";
  367. #endif
  368. /* Common strings */
  369. #define STR_INPUT_ID 0
  370. #define STR_INVBM_KEY 1
  371. #define STR_DATE_ID 2
  372. #define STR_TMPFILE 3
  373. #define NONE_SELECTED 4
  374. #define UTIL_MISSING 5
  375. #define OPERATION_FAILED 6
  376. #define SESSION_NAME 7
  377. static const char * const messages[] = {
  378. "no traversal",
  379. "invalid key",
  380. "%F %T %z",
  381. "/.nnnXXXXXX",
  382. "0 selected",
  383. "missing dep",
  384. "failed!",
  385. "session name: ",
  386. };
  387. /* Supported configuration environment variables */
  388. #define NNN_BMS 0
  389. #define NNN_OPENER 1
  390. #define NNN_CONTEXT_COLORS 2
  391. #define NNN_IDLE_TIMEOUT 3
  392. #define NNN_COPIER 4
  393. #define NNNLVL 5
  394. #define NNN_PIPE 6 /* strings end here */
  395. #define NNN_USE_EDITOR 7 /* flags begin here */
  396. #define NNN_TRASH 8
  397. static const char * const env_cfg[] = {
  398. "NNN_BMS",
  399. "NNN_OPENER",
  400. "NNN_CONTEXT_COLORS",
  401. "NNN_IDLE_TIMEOUT",
  402. "NNN_COPIER",
  403. "NNNLVL",
  404. "NNN_PIPE",
  405. "NNN_USE_EDITOR",
  406. "NNN_TRASH",
  407. };
  408. /* Required environment variables */
  409. #define SHELL 0
  410. #define VISUAL 1
  411. #define EDITOR 2
  412. #define PAGER 3
  413. #define NCUR 4
  414. static const char * const envs[] = {
  415. "SHELL",
  416. "VISUAL",
  417. "EDITOR",
  418. "PAGER",
  419. "NNN",
  420. };
  421. /* Event handling */
  422. #ifdef LINUX_INOTIFY
  423. #define NUM_EVENT_SLOTS 8 /* Make room for 8 events */
  424. #define EVENT_SIZE (sizeof(struct inotify_event))
  425. #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
  426. static int inotify_fd, inotify_wd = -1;
  427. static uint INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
  428. | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  429. #elif defined(BSD_KQUEUE)
  430. #define NUM_EVENT_SLOTS 1
  431. #define NUM_EVENT_FDS 1
  432. static int kq, event_fd = -1;
  433. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  434. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
  435. | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  436. static struct timespec gtimeout;
  437. #endif
  438. /* Function macros */
  439. #define tolastln() move(xlines - 1, 0)
  440. #define exitcurses() endwin()
  441. #define clearprompt() printmsg("")
  442. #define printwarn(presel) printwait(strerror(errno), presel)
  443. #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
  444. #define copycurname() xstrlcpy(lastname, dents[cur].name, NAME_MAX + 1)
  445. #define settimeout() timeout(1000)
  446. #define cleartimeout() timeout(-1)
  447. #define errexit() printerr(__LINE__)
  448. #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (dir_changed = TRUE))
  449. /* We don't care about the return value from strcmp() */
  450. #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
  451. /* A faster version of xisdigit */
  452. #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
  453. #define xerror() perror(xitoa(__LINE__))
  454. /* Forward declarations */
  455. static void redraw(char *path);
  456. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag);
  457. static int (*nftw_fn)(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  458. static int dentfind(const char *fname, int n);
  459. static void move_cursor(int target, int ignore_scrolloff);
  460. static inline bool getutil(char *util);
  461. /* Functions */
  462. static void sigint_handler(int sig)
  463. {
  464. (void) sig;
  465. interrupted = TRUE;
  466. }
  467. static uint xatoi(const char *str)
  468. {
  469. int val = 0;
  470. if (!str)
  471. return 0;
  472. while (xisdigit(*str)) {
  473. val = val * 10 + (*str - '0');
  474. ++str;
  475. }
  476. return val;
  477. }
  478. static char *xitoa(uint val)
  479. {
  480. static char ascbuf[32] = {0};
  481. int i = 30;
  482. if (!val)
  483. return "0";
  484. for (; val && i; --i, val /= 10)
  485. ascbuf[i] = '0' + (val % 10);
  486. return &ascbuf[++i];
  487. }
  488. #ifdef KEY_RESIZE
  489. /* Clear the old prompt */
  490. static inline void clearoldprompt(void)
  491. {
  492. tolastln();
  493. clrtoeol();
  494. }
  495. #endif
  496. /* Messages show up at the bottom */
  497. static inline void printmsg(const char *msg)
  498. {
  499. tolastln();
  500. addstr(msg);
  501. addch('\n');
  502. }
  503. static void printwait(const char *msg, int *presel)
  504. {
  505. printmsg(msg);
  506. if (presel)
  507. *presel = MSGWAIT;
  508. }
  509. /* Kill curses and display error before exiting */
  510. static void printerr(int linenum)
  511. {
  512. exitcurses();
  513. perror(xitoa(linenum));
  514. if (!cfg.picker && g_selpath)
  515. unlink(g_selpath);
  516. free(pselbuf);
  517. exit(1);
  518. }
  519. /* Print prompt on the last line */
  520. static void printprompt(const char *str)
  521. {
  522. clearprompt();
  523. addstr(str);
  524. }
  525. static int get_input(const char *prompt)
  526. {
  527. int r = KEY_RESIZE;
  528. if (prompt)
  529. printprompt(prompt);
  530. cleartimeout();
  531. #ifdef KEY_RESIZE
  532. while (r == KEY_RESIZE) {
  533. r = getch();
  534. if (r == KEY_RESIZE && prompt) {
  535. clearoldprompt();
  536. xlines = LINES;
  537. printprompt(prompt);
  538. }
  539. };
  540. #else
  541. r = getch();
  542. #endif
  543. settimeout();
  544. return r;
  545. }
  546. static void xdelay(void)
  547. {
  548. refresh();
  549. usleep(350000); /* 350 ms delay */
  550. }
  551. static char confirm_force(bool selection)
  552. {
  553. char str[64];
  554. int r;
  555. snprintf(str, 64, "forcibly remove %s file%s (unrecoverable)? [y/Y confirms]",
  556. (selection ? xitoa(nselected) : "current"), (selection ? "(s)" : ""));
  557. r = get_input(str);
  558. if (r == 'y' || r == 'Y')
  559. return 'f'; /* forceful */
  560. return 'i'; /* interactive */
  561. }
  562. /* Increase the limit on open file descriptors, if possible */
  563. static rlim_t max_openfds(void)
  564. {
  565. struct rlimit rl;
  566. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  567. if (limit != 0)
  568. return 32;
  569. limit = rl.rlim_cur;
  570. rl.rlim_cur = rl.rlim_max;
  571. /* Return ~75% of max possible */
  572. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  573. limit = rl.rlim_max - (rl.rlim_max >> 2);
  574. /*
  575. * 20K is arbitrary. If the limit is set to max possible
  576. * value, the memory usage increases to more than double.
  577. */
  578. return limit > 20480 ? 20480 : limit;
  579. }
  580. return limit;
  581. }
  582. /*
  583. * Wrapper to realloc()
  584. * Frees current memory if realloc() fails and returns NULL.
  585. *
  586. * As per the docs, the *alloc() family is supposed to be memory aligned:
  587. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  588. * macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  589. */
  590. static void *xrealloc(void *pcur, size_t len)
  591. {
  592. void *pmem = realloc(pcur, len);
  593. if (!pmem)
  594. free(pcur);
  595. return pmem;
  596. }
  597. /*
  598. * Just a safe strncpy(3)
  599. * Always null ('\0') terminates if both src and dest are valid pointers.
  600. * Returns the number of bytes copied including terminating null byte.
  601. */
  602. static size_t xstrlcpy(char *dest, const char *src, size_t n)
  603. {
  604. if (!src || !dest || !n)
  605. return 0;
  606. ulong *s, *d;
  607. size_t len = strlen(src) + 1, blocks;
  608. const uint _WSHIFT = (LONG_SIZE == 8) ? 3 : 2;
  609. if (n > len)
  610. n = len;
  611. else if (len > n)
  612. /* Save total number of bytes to copy in len */
  613. len = n;
  614. /*
  615. * To enable -O3 ensure src and dest are 16-byte aligned
  616. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  617. */
  618. if ((n >= LONG_SIZE) && (((ulong)src & _ALIGNMENT_MASK) == 0 &&
  619. ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  620. s = (ulong *)src;
  621. d = (ulong *)dest;
  622. blocks = n >> _WSHIFT;
  623. n &= LONG_SIZE - 1;
  624. while (blocks) {
  625. *d = *s; // NOLINT
  626. ++d, ++s;
  627. --blocks;
  628. }
  629. if (!n) {
  630. dest = (char *)d;
  631. *--dest = '\0';
  632. return len;
  633. }
  634. src = (char *)s;
  635. dest = (char *)d;
  636. }
  637. while (--n && (*dest = *src)) // NOLINT
  638. ++dest, ++src;
  639. if (!n)
  640. *dest = '\0';
  641. return len;
  642. }
  643. static bool is_suffix(const char *str, const char *suffix)
  644. {
  645. if (!str || !suffix)
  646. return FALSE;
  647. size_t lenstr = strlen(str);
  648. size_t lensuffix = strlen(suffix);
  649. if (lensuffix > lenstr)
  650. return FALSE;
  651. return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
  652. }
  653. /*
  654. * The poor man's implementation of memrchr(3).
  655. * We are only looking for '/' in this program.
  656. * And we are NOT expecting a '/' at the end.
  657. * Ideally 0 < n <= strlen(s).
  658. */
  659. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  660. {
  661. if (!s || !n)
  662. return NULL;
  663. uchar *ptr = s + n;
  664. do {
  665. --ptr;
  666. if (*ptr == ch)
  667. return ptr;
  668. } while (s != ptr);
  669. return NULL;
  670. }
  671. static char *xbasename(char *path)
  672. {
  673. char *base = xmemrchr((uchar *)path, '/', strlen(path)); // NOLINT
  674. return base ? base + 1 : path;
  675. }
  676. static int create_tmp_file(void)
  677. {
  678. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - g_tmpfplen);
  679. int fd = mkstemp(g_tmpfpath);
  680. if (fd == -1) {
  681. DPRINTF_S(strerror(errno));
  682. }
  683. return fd;
  684. }
  685. /* Writes buflen char(s) from buf to a file */
  686. static void writesel(const char *buf, const size_t buflen)
  687. {
  688. if (cfg.pickraw || !g_selpath)
  689. return;
  690. FILE *fp = fopen(g_selpath, "w");
  691. if (fp) {
  692. if (fwrite(buf, 1, buflen, fp) != buflen)
  693. printwarn(NULL);
  694. fclose(fp);
  695. } else
  696. printwarn(NULL);
  697. }
  698. static void appendfpath(const char *path, const size_t len)
  699. {
  700. if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
  701. selbuflen += PATH_MAX;
  702. pselbuf = xrealloc(pselbuf, selbuflen);
  703. if (!pselbuf)
  704. errexit();
  705. }
  706. selbufpos += xstrlcpy(pselbuf + selbufpos, path, len);
  707. }
  708. /* Write selected file paths to fd, linefeed separated */
  709. static size_t seltofile(int fd, uint *pcount)
  710. {
  711. uint lastpos, count = 0;
  712. char *pbuf = pselbuf;
  713. size_t pos = 0, len;
  714. ssize_t r;
  715. if (pcount)
  716. *pcount = 0;
  717. if (!selbufpos)
  718. return 0;
  719. lastpos = selbufpos - 1;
  720. while (pos <= lastpos) {
  721. len = strlen(pbuf);
  722. pos += len;
  723. r = write(fd, pbuf, len);
  724. if (r != (ssize_t)len)
  725. return pos;
  726. if (pos <= lastpos) {
  727. if (write(fd, "\n", 1) != 1)
  728. return pos;
  729. pbuf += len + 1;
  730. }
  731. ++pos;
  732. ++count;
  733. }
  734. if (pcount)
  735. *pcount = count;
  736. return pos;
  737. }
  738. /* List selection from selection buffer */
  739. static bool listselbuf(void)
  740. {
  741. int fd;
  742. size_t pos;
  743. if (!selbufpos)
  744. return FALSE;
  745. fd = create_tmp_file();
  746. if (fd == -1)
  747. return FALSE;
  748. pos = seltofile(fd, NULL);
  749. close(fd);
  750. if (pos && pos == selbufpos)
  751. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  752. unlink(g_tmpfpath);
  753. return TRUE;
  754. }
  755. /* List selection from selection file (another instance) */
  756. static bool listselfile(void)
  757. {
  758. struct stat sb;
  759. if (stat(g_selpath, &sb) == -1)
  760. return FALSE;
  761. /* Nothing selected if file size is 0 */
  762. if (!sb.st_size)
  763. return FALSE;
  764. snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", g_selpath);
  765. spawn(utils[SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
  766. return TRUE;
  767. }
  768. /* Reset selection indicators */
  769. static void resetselind(void)
  770. {
  771. int r = 0;
  772. for (; r < ndents; ++r)
  773. if (dents[r].flags & FILE_SELECTED)
  774. dents[r].flags &= ~FILE_SELECTED;
  775. }
  776. static void startselection(void)
  777. {
  778. if (!cfg.selmode) {
  779. cfg.selmode = 1;
  780. nselected = 0;
  781. if (selbufpos) {
  782. resetselind();
  783. writesel(NULL, 0);
  784. selbufpos = 0;
  785. }
  786. }
  787. }
  788. /* Finish selection procedure before an operation */
  789. static void endselection(void)
  790. {
  791. if (cfg.selmode) {
  792. cfg.selmode = 0;
  793. if (selbufpos) { /* File path(s) written to the buffer */
  794. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  795. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  796. }
  797. }
  798. }
  799. static void clearselection(void)
  800. {
  801. nselected = 0;
  802. selbufpos = 0;
  803. cfg.selmode = 0;
  804. writesel(NULL, 0);
  805. }
  806. static bool editselection(void)
  807. {
  808. bool ret = FALSE;
  809. int fd, lines = 0;
  810. ssize_t count;
  811. struct stat sb;
  812. if (!selbufpos) {
  813. DPRINTF_S("empty selection");
  814. return FALSE;
  815. }
  816. fd = create_tmp_file();
  817. if (fd == -1) {
  818. DPRINTF_S("couldn't create tmp file");
  819. return FALSE;
  820. }
  821. seltofile(fd, NULL);
  822. close(fd);
  823. spawn(editor, g_tmpfpath, NULL, NULL, F_CLI);
  824. fd = open(g_tmpfpath, O_RDONLY);
  825. if (fd == -1) {
  826. DPRINTF_S("couldn't read tmp file");
  827. unlink(g_tmpfpath);
  828. return FALSE;
  829. }
  830. fstat(fd, &sb);
  831. if (sb.st_size > selbufpos) {
  832. DPRINTF_S("edited buffer larger than pervious");
  833. goto emptyedit;
  834. }
  835. count = read(fd, pselbuf, selbuflen);
  836. close(fd);
  837. unlink(g_tmpfpath);
  838. if (!count) {
  839. ret = TRUE;
  840. goto emptyedit;
  841. }
  842. if (count < 0) {
  843. DPRINTF_S("error reading tmp file");
  844. goto emptyedit;
  845. }
  846. resetselind();
  847. selbufpos = count;
  848. /* The last character should be '\n' */
  849. pselbuf[--count] = '\0';
  850. for (--count; count > 0; --count) {
  851. /* Replace every '\n' that separates two paths */
  852. if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
  853. ++lines;
  854. pselbuf[count] = '\0';
  855. }
  856. }
  857. /* Add a line for the last file */
  858. ++lines;
  859. if (lines > nselected) {
  860. DPRINTF_S("files added to selection");
  861. goto emptyedit;
  862. }
  863. nselected = lines;
  864. writesel(pselbuf, selbufpos - 1);
  865. spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  866. return TRUE;
  867. emptyedit:
  868. resetselind();
  869. clearselection();
  870. return ret;
  871. }
  872. static bool selsafe(void)
  873. {
  874. /* Fail if selection file path not generated */
  875. if (!g_selpath) {
  876. printmsg("selection file not found");
  877. return FALSE;
  878. }
  879. /* Fail if selection file path isn't accessible */
  880. if (access(g_selpath, R_OK | W_OK) == -1) {
  881. errno == ENOENT ? printmsg(messages[NONE_SELECTED]) : printwarn(NULL);
  882. return FALSE;
  883. }
  884. return TRUE;
  885. }
  886. /* Initialize curses mode */
  887. static bool initcurses(mmask_t *oldmask)
  888. {
  889. short i;
  890. if (cfg.picker) {
  891. if (!newterm(NULL, stderr, stdin)) {
  892. fprintf(stderr, "newterm!\n");
  893. return FALSE;
  894. }
  895. } else if (!initscr()) {
  896. fprintf(stderr, "initscr!\n");
  897. DPRINTF_S(getenv("TERM"));
  898. return FALSE;
  899. }
  900. cbreak();
  901. noecho();
  902. nonl();
  903. //intrflush(stdscr, FALSE);
  904. keypad(stdscr, TRUE);
  905. #if NCURSES_MOUSE_VERSION <= 1
  906. mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED, oldmask);
  907. #else
  908. mousemask(BUTTON1_PRESSED | BUTTON4_PRESSED | BUTTON5_PRESSED,
  909. oldmask);
  910. #endif
  911. mouseinterval(0);
  912. curs_set(FALSE); /* Hide cursor */
  913. start_color();
  914. use_default_colors();
  915. /* Initialize default colors */
  916. for (i = 0; i < CTX_MAX; ++i)
  917. init_pair(i + 1, g_ctx[i].color, -1);
  918. settimeout(); /* One second */
  919. set_escdelay(25);
  920. return TRUE;
  921. }
  922. /* No NULL check here as spawn() guards against it */
  923. static int parseargs(char *line, char **argv)
  924. {
  925. int count = 0;
  926. argv[count++] = line;
  927. while (*line) { // NOLINT
  928. if (ISBLANK(*line)) {
  929. *line++ = '\0';
  930. if (!*line) // NOLINT
  931. return count;
  932. argv[count++] = line;
  933. if (count == EXEC_ARGS_MAX)
  934. return -1;
  935. }
  936. ++line;
  937. }
  938. return count;
  939. }
  940. static pid_t xfork(uchar flag)
  941. {
  942. pid_t p = fork();
  943. if (p > 0) {
  944. /* the parent ignores the interrupt, quit and hangup signals */
  945. oldsighup = signal(SIGHUP, SIG_IGN);
  946. oldsigtstp = signal(SIGTSTP, SIG_DFL);
  947. } else if (p == 0) {
  948. /* so they can be used to stop the child */
  949. signal(SIGHUP, SIG_DFL);
  950. signal(SIGINT, SIG_DFL);
  951. signal(SIGQUIT, SIG_DFL);
  952. signal(SIGTSTP, SIG_DFL);
  953. if (flag & F_NOWAIT)
  954. setsid();
  955. }
  956. if (p == -1)
  957. perror("fork");
  958. return p;
  959. }
  960. static int join(pid_t p, uchar flag)
  961. {
  962. int status = 0xFFFF;
  963. if (!(flag & F_NOWAIT)) {
  964. /* wait for the child to exit */
  965. do {
  966. } while (waitpid(p, &status, 0) == -1);
  967. if (WIFEXITED(status)) {
  968. status = WEXITSTATUS(status);
  969. DPRINTF_D(status);
  970. }
  971. }
  972. /* restore parent's signal handling */
  973. signal(SIGHUP, oldsighup);
  974. signal(SIGTSTP, oldsigtstp);
  975. return status;
  976. }
  977. /*
  978. * Spawns a child process. Behaviour can be controlled using flag.
  979. * Limited to 2 arguments to a program, flag works on bit set.
  980. */
  981. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag)
  982. {
  983. pid_t pid;
  984. int status, retstatus = 0xFFFF;
  985. char *argv[EXEC_ARGS_MAX] = {0};
  986. char *cmd = NULL;
  987. if (!file || !*file)
  988. return retstatus;
  989. /* Swap args if the first arg is NULL and second isn't */
  990. if (!arg1 && arg2) {
  991. arg1 = arg2;
  992. arg2 = NULL;
  993. }
  994. if (flag & F_MULTI) {
  995. size_t len = strlen(file) + 1;
  996. cmd = (char *)malloc(len);
  997. if (!cmd) {
  998. DPRINTF_S("malloc()!");
  999. return retstatus;
  1000. }
  1001. xstrlcpy(cmd, file, len);
  1002. status = parseargs(cmd, argv);
  1003. if (status == -1 || status > (EXEC_ARGS_MAX - 3)) { /* arg1, arg2 and last NULL */
  1004. free(cmd);
  1005. DPRINTF_S("NULL or too many args");
  1006. return retstatus;
  1007. }
  1008. argv[status++] = arg1;
  1009. argv[status] = arg2;
  1010. } else {
  1011. argv[0] = file;
  1012. argv[1] = arg1;
  1013. argv[2] = arg2;
  1014. }
  1015. if (flag & F_NORMAL)
  1016. exitcurses();
  1017. pid = xfork(flag);
  1018. if (pid == 0) {
  1019. if (dir && chdir(dir) == -1)
  1020. _exit(1);
  1021. /* Suppress stdout and stderr */
  1022. if (flag & F_NOTRACE) {
  1023. int fd = open("/dev/null", O_WRONLY, 0200);
  1024. dup2(fd, 1);
  1025. dup2(fd, 2);
  1026. close(fd);
  1027. }
  1028. execvp(*argv, argv);
  1029. _exit(1);
  1030. } else {
  1031. retstatus = join(pid, flag);
  1032. DPRINTF_D(pid);
  1033. if (flag & F_NORMAL) {
  1034. if (flag & F_CONFIRM) {
  1035. printf("\nPress Enter to continue");
  1036. getchar();
  1037. }
  1038. refresh();
  1039. }
  1040. free(cmd);
  1041. }
  1042. return retstatus;
  1043. }
  1044. static void prompt_run(char *cmd, const char *cur, const char *path)
  1045. {
  1046. setenv(envs[NCUR], cur, 1);
  1047. spawn(shell, "-c", cmd, path, F_CLI | F_CONFIRM);
  1048. }
  1049. /* Get program name from env var, else return fallback program */
  1050. static char *xgetenv(const char *name, char *fallback)
  1051. {
  1052. char *value = getenv(name);
  1053. return value && value[0] ? value : fallback;
  1054. }
  1055. /* Checks if an env variable is set to 1 */
  1056. static bool xgetenv_set(const char *name)
  1057. {
  1058. char *value = getenv(name);
  1059. if (value && value[0] == '1' && !value[1])
  1060. return TRUE;
  1061. return FALSE;
  1062. }
  1063. /* Check if a dir exists, IS a dir and is readable */
  1064. static bool xdiraccess(const char *path)
  1065. {
  1066. DIR *dirp = opendir(path);
  1067. if (!dirp) {
  1068. printwarn(NULL);
  1069. return FALSE;
  1070. }
  1071. closedir(dirp);
  1072. return TRUE;
  1073. }
  1074. static void opstr(char *buf, char *op)
  1075. {
  1076. snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s $0 $@ . < /dev/tty' < %s", op, g_selpath);
  1077. }
  1078. static void rmmulstr(char *buf)
  1079. {
  1080. if (cfg.trash) {
  1081. snprintf(buf, CMD_LEN_MAX, "xargs -0 trash-put < %s", g_selpath);
  1082. } else {
  1083. snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr $0 $@ < /dev/tty' < %s", confirm_force(TRUE), g_selpath);
  1084. }
  1085. }
  1086. static void xrm(char *path)
  1087. {
  1088. if (cfg.trash)
  1089. spawn("trash-put", path, NULL, NULL, F_NORMAL);
  1090. else {
  1091. char rm_opts[] = "-ir";
  1092. rm_opts[1] = confirm_force(FALSE);
  1093. spawn("rm", rm_opts, path, NULL, F_NORMAL);
  1094. }
  1095. }
  1096. static uint lines_in_file(int fd, char *buf, size_t buflen)
  1097. {
  1098. ssize_t len;
  1099. uint count = 0;
  1100. while ((len = read(fd, buf, buflen)) > 0)
  1101. while (len)
  1102. count += (buf[--len] == '\n');
  1103. /* For all use cases 0 linecount is considered as error */
  1104. return ((len < 0) ? 0 : count);
  1105. }
  1106. static bool cpmv_rename(int choice, const char *path)
  1107. {
  1108. int fd;
  1109. uint count = 0, lines = 0;
  1110. bool ret = FALSE;
  1111. char *cmd = (choice == 'c' ? cp : mv);
  1112. static const char formatcmd[] = "sed -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s";
  1113. static const char renamecmd[] = "sed 's|^\\([^#][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' %s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s $0 $@ < /dev/tty'";
  1114. char buf[sizeof(renamecmd) + sizeof(cmd) + (PATH_MAX << 1)];
  1115. fd = create_tmp_file();
  1116. if (fd == -1)
  1117. return ret;
  1118. /* selsafe() returned TRUE for this to be called */
  1119. if (!selbufpos) {
  1120. snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", g_selpath, g_tmpfpath);
  1121. spawn(utils[SH_EXEC], buf, NULL, NULL, F_CLI);
  1122. count = lines_in_file(fd, buf, sizeof(buf));
  1123. if (!count)
  1124. goto finish;
  1125. } else
  1126. seltofile(fd, &count);
  1127. close(fd);
  1128. snprintf(buf, sizeof(buf), formatcmd, g_tmpfpath);
  1129. spawn(utils[SH_EXEC], buf, NULL, path, F_CLI);
  1130. spawn(editor, g_tmpfpath, NULL, path, F_CLI);
  1131. fd = open(g_tmpfpath, O_RDONLY);
  1132. if (fd == -1)
  1133. goto finish;
  1134. lines = lines_in_file(fd, buf, sizeof(buf));
  1135. DPRINTF_U(count);
  1136. DPRINTF_U(lines);
  1137. if (!lines || (2 * count != lines)) {
  1138. DPRINTF_S("num mismatch");
  1139. goto finish;
  1140. }
  1141. snprintf(buf, sizeof(buf), renamecmd, path, g_tmpfpath, cmd);
  1142. spawn(utils[SH_EXEC], buf, NULL, path, F_CLI);
  1143. ret = TRUE;
  1144. finish:
  1145. if (fd >= 0)
  1146. close(fd);
  1147. return ret;
  1148. }
  1149. static bool cpmvrm_selection(enum action sel, char *path, int *presel)
  1150. {
  1151. int r;
  1152. endselection();
  1153. if (!selsafe()) {
  1154. *presel = MSGWAIT;
  1155. return FALSE;
  1156. }
  1157. switch (sel) {
  1158. case SEL_CP:
  1159. opstr(g_buf, cp);
  1160. break;
  1161. case SEL_MV:
  1162. opstr(g_buf, mv);
  1163. break;
  1164. case SEL_CPMVAS:
  1165. r = get_input("'c'p / 'm'v as?");
  1166. if (r != 'c' && r != 'm') {
  1167. if (cfg.filtermode)
  1168. *presel = FILTER;
  1169. return FALSE;
  1170. }
  1171. if (!cpmv_rename(r, path)) {
  1172. printwait(messages[OPERATION_FAILED], presel);
  1173. return FALSE;
  1174. }
  1175. break;
  1176. default: /* SEL_RMMUL */
  1177. rmmulstr(g_buf);
  1178. break;
  1179. }
  1180. if (sel != SEL_CPMVAS)
  1181. spawn(utils[SH_EXEC], g_buf, NULL, path, F_CLI);
  1182. /* Clear selection on move or delete */
  1183. if (sel != SEL_CP)
  1184. clearselection();
  1185. if (cfg.filtermode)
  1186. *presel = FILTER;
  1187. return TRUE;
  1188. }
  1189. static bool batch_rename(const char *path)
  1190. {
  1191. int fd1, fd2, i;
  1192. uint count = 0, lines = 0;
  1193. bool dir = FALSE, ret = FALSE;
  1194. static const char renamecmd[] = "paste -d'\n' %s %s | sed 'N; /^\\(.*\\)\\n\\1$/!p;d' | tr '\n' '\\0' | xargs -0 -n2 mv 2>/dev/null";
  1195. char foriginal[TMP_LEN_MAX] = {0};
  1196. char buf[sizeof(renamecmd) + (PATH_MAX << 1)];
  1197. fd1 = create_tmp_file();
  1198. if (fd1 == -1)
  1199. return ret;
  1200. xstrlcpy(foriginal, g_tmpfpath, strlen(g_tmpfpath)+1);
  1201. fd2 = create_tmp_file();
  1202. if (fd2 == -1) {
  1203. unlink(foriginal);
  1204. close(fd1);
  1205. return ret;
  1206. }
  1207. if (selbufpos) {
  1208. i = get_input("rename selection? [y/Y confirms]");
  1209. if (i != 'y' && i != 'Y') {
  1210. if (!ndents)
  1211. return TRUE;
  1212. selbufpos = 0; /* Clear the selection */
  1213. dir = TRUE;
  1214. }
  1215. } else
  1216. dir = TRUE; /* Rename entries in dir */
  1217. if (dir)
  1218. for (i = 0; i < ndents; ++i)
  1219. appendfpath(dents[i].name, NAME_MAX);
  1220. seltofile(fd1, &count);
  1221. seltofile(fd2, NULL);
  1222. close(fd2);
  1223. if (dir) /* Don't retain dir entries in selection */
  1224. selbufpos = 0;
  1225. spawn(editor, g_tmpfpath, NULL, path, F_CLI);
  1226. /* Reopen file descriptor to get updated contents */
  1227. fd2 = open(g_tmpfpath, O_RDONLY);
  1228. if (fd2 == -1)
  1229. goto finish;
  1230. lines = lines_in_file(fd2, buf, sizeof(buf));
  1231. DPRINTF_U(count);
  1232. DPRINTF_U(lines);
  1233. if (!lines || (count != lines)) {
  1234. DPRINTF_S("cannot delete files");
  1235. goto finish;
  1236. }
  1237. snprintf(buf, sizeof(buf), renamecmd, foriginal, g_tmpfpath);
  1238. spawn(utils[SH_EXEC], buf, NULL, path, F_CLI);
  1239. ret = TRUE;
  1240. finish:
  1241. if (fd1 >= 0)
  1242. close(fd1);
  1243. unlink(foriginal);
  1244. if (fd2 >= 0)
  1245. close(fd2);
  1246. unlink(g_tmpfpath);
  1247. return ret;
  1248. }
  1249. static void get_archive_cmd(char *cmd, char *archive)
  1250. {
  1251. if (getutil(utils[ATOOL]))
  1252. xstrlcpy(cmd, "atool -a", ARCHIVE_CMD_LEN);
  1253. else if (getutil(utils[BSDTAR]))
  1254. xstrlcpy(cmd, "bsdtar -acvf", ARCHIVE_CMD_LEN);
  1255. else if (is_suffix(archive, ".zip"))
  1256. xstrlcpy(cmd, "zip -r", ARCHIVE_CMD_LEN);
  1257. else
  1258. xstrlcpy(cmd, "tar -acvf", ARCHIVE_CMD_LEN);
  1259. }
  1260. static void archive_selection(const char *cmd, const char *archive, const char *curpath)
  1261. {
  1262. char *buf = (char *)malloc(CMD_LEN_MAX * sizeof(char));
  1263. snprintf(buf, CMD_LEN_MAX,
  1264. #ifdef __linux__
  1265. "sed -ze 's|^%s/||' '%s' | xargs -0 %s %s", curpath, g_selpath, cmd, archive);
  1266. #else
  1267. "tr '\\0' '\n' < '%s' | sed -e 's|^%s/||' | tr '\n' '\\0' | xargs -0 %s %s",
  1268. g_selpath, curpath, cmd, archive);
  1269. #endif
  1270. spawn(utils[SH_EXEC], buf, NULL, curpath, F_CLI);
  1271. free(buf);
  1272. }
  1273. static bool write_lastdir(const char *curpath)
  1274. {
  1275. bool ret = TRUE;
  1276. size_t len = strlen(cfgdir);
  1277. xstrlcpy(cfgdir + len, "/.lastd", 8);
  1278. DPRINTF_S(cfgdir);
  1279. FILE *fp = fopen(cfgdir, "w");
  1280. if (fp) {
  1281. if (fprintf(fp, "cd \"%s\"", curpath) < 0)
  1282. ret = FALSE;
  1283. fclose(fp);
  1284. } else
  1285. ret = FALSE;
  1286. return ret;
  1287. }
  1288. /*
  1289. * We assume none of the strings are NULL.
  1290. *
  1291. * Let's have the logic to sort numeric names in numeric order.
  1292. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  1293. *
  1294. * If the absolute numeric values are same, we fallback to alphasort.
  1295. */
  1296. static int xstricmp(const char * const s1, const char * const s2)
  1297. {
  1298. char *p1, *p2;
  1299. ll v1 = strtoll(s1, &p1, 10);
  1300. ll v2 = strtoll(s2, &p2, 10);
  1301. /* Check if at least 1 string is numeric */
  1302. if (s1 != p1 || s2 != p2) {
  1303. /* Handle both pure numeric */
  1304. if (s1 != p1 && s2 != p2) {
  1305. if (v2 > v1)
  1306. return -1;
  1307. if (v1 > v2)
  1308. return 1;
  1309. }
  1310. /* Only first string non-numeric */
  1311. if (s1 == p1)
  1312. return 1;
  1313. /* Only second string non-numeric */
  1314. if (s2 == p2)
  1315. return -1;
  1316. }
  1317. /* Handle 1. all non-numeric and 2. both same numeric value cases */
  1318. #ifndef NOLOCALE
  1319. return strcoll(s1, s2);
  1320. #else
  1321. return strcasecmp(s1, s2);
  1322. #endif
  1323. }
  1324. /*
  1325. * Version comparison
  1326. *
  1327. * The code for version compare is a modified version of the GLIBC
  1328. * and uClibc implementation of strverscmp(). The source is here:
  1329. * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
  1330. */
  1331. /*
  1332. * Compare S1 and S2 as strings holding indices/version numbers,
  1333. * returning less than, equal to or greater than zero if S1 is less than,
  1334. * equal to or greater than S2 (for more info, see the texinfo doc).
  1335. *
  1336. * Ignores case.
  1337. */
  1338. static int xstrverscasecmp(const char * const s1, const char * const s2)
  1339. {
  1340. const uchar *p1 = (const uchar *)s1;
  1341. const uchar *p2 = (const uchar *)s2;
  1342. int state, diff;
  1343. uchar c1, c2;
  1344. /*
  1345. * Symbol(s) 0 [1-9] others
  1346. * Transition (10) 0 (01) d (00) x
  1347. */
  1348. static const uint8_t next_state[] = {
  1349. /* state x d 0 */
  1350. /* S_N */ S_N, S_I, S_Z,
  1351. /* S_I */ S_N, S_I, S_I,
  1352. /* S_F */ S_N, S_F, S_F,
  1353. /* S_Z */ S_N, S_F, S_Z
  1354. };
  1355. static const int8_t result_type[] __attribute__ ((aligned)) = {
  1356. /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
  1357. /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
  1358. /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
  1359. /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
  1360. /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
  1361. };
  1362. if (p1 == p2)
  1363. return 0;
  1364. c1 = TOUPPER(*p1);
  1365. ++p1;
  1366. c2 = TOUPPER(*p2);
  1367. ++p2;
  1368. /* Hint: '0' is a digit too. */
  1369. state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
  1370. while ((diff = c1 - c2) == 0) {
  1371. if (c1 == '\0')
  1372. return diff;
  1373. state = next_state[state];
  1374. c1 = TOUPPER(*p1);
  1375. ++p1;
  1376. c2 = TOUPPER(*p2);
  1377. ++p2;
  1378. state += (c1 == '0') + (xisdigit(c1) != 0);
  1379. }
  1380. state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))];
  1381. switch (state) {
  1382. case VCMP:
  1383. return diff;
  1384. case VLEN:
  1385. while (xisdigit(*p1++))
  1386. if (!xisdigit(*p2++))
  1387. return 1;
  1388. return xisdigit(*p2) ? -1 : diff;
  1389. default:
  1390. return state;
  1391. }
  1392. }
  1393. static int (*cmpfn)(const char * const s1, const char * const s2) = &xstricmp;
  1394. /* Return the integer value of a char representing HEX */
  1395. static char xchartohex(char c)
  1396. {
  1397. if (xisdigit(c))
  1398. return c - '0';
  1399. c = TOUPPER(c);
  1400. if (c >= 'A' && c <= 'F')
  1401. return c - 'A' + 10;
  1402. return c;
  1403. }
  1404. static int setfilter(regex_t *regex, const char *filter)
  1405. {
  1406. int r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  1407. if (r != 0 && filter && filter[0] != '\0')
  1408. mvprintw(xlines - 1, 0, "regex error: %d\n", r);
  1409. return r;
  1410. }
  1411. static int visible_re(const fltrexp_t *fltrexp, const char *fname)
  1412. {
  1413. return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
  1414. }
  1415. static int visible_str(const fltrexp_t *fltrexp, const char *fname)
  1416. {
  1417. return strcasestr(fname, fltrexp->str) != NULL;
  1418. }
  1419. static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_re;
  1420. static int entrycmp(const void *va, const void *vb)
  1421. {
  1422. const struct entry *pa = (pEntry)va;
  1423. const struct entry *pb = (pEntry)vb;
  1424. if ((pb->flags & DIR_OR_LINK_TO_DIR) != (pa->flags & DIR_OR_LINK_TO_DIR)) {
  1425. if (pb->flags & DIR_OR_LINK_TO_DIR)
  1426. return 1;
  1427. return -1;
  1428. }
  1429. /* Sort based on specified order */
  1430. if (cfg.mtimeorder) {
  1431. if (pb->t > pa->t)
  1432. return 1;
  1433. if (pb->t < pa->t)
  1434. return -1;
  1435. } else if (cfg.sizeorder) {
  1436. if (pb->size > pa->size)
  1437. return 1;
  1438. if (pb->size < pa->size)
  1439. return -1;
  1440. } else if (cfg.blkorder) {
  1441. if (pb->blocks > pa->blocks)
  1442. return 1;
  1443. if (pb->blocks < pa->blocks)
  1444. return -1;
  1445. } else if (cfg.extnorder && !(pb->flags & DIR_OR_LINK_TO_DIR)) {
  1446. char *extna = xmemrchr((uchar *)pa->name, '.', strlen(pa->name));
  1447. char *extnb = xmemrchr((uchar *)pb->name, '.', strlen(pb->name));
  1448. if (extna || extnb) {
  1449. if (!extna)
  1450. return 1;
  1451. if (!extnb)
  1452. return -1;
  1453. int ret = strcasecmp(extna, extnb);
  1454. if (ret)
  1455. return ret;
  1456. }
  1457. }
  1458. return cmpfn(pa->name, pb->name);
  1459. }
  1460. /*
  1461. * Returns SEL_* if key is bound and 0 otherwise.
  1462. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  1463. * The next keyboard input can be simulated by presel.
  1464. */
  1465. static int nextsel(int presel)
  1466. {
  1467. int c = presel;
  1468. uint i;
  1469. const uint len = LEN(bindings);
  1470. #ifdef LINUX_INOTIFY
  1471. struct inotify_event *event;
  1472. char inotify_buf[EVENT_BUF_LEN];
  1473. memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
  1474. #elif defined(BSD_KQUEUE)
  1475. struct kevent event_data[NUM_EVENT_SLOTS];
  1476. memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
  1477. #endif
  1478. if (c == 0 || c == MSGWAIT) {
  1479. c = getch();
  1480. DPRINTF_D(c);
  1481. if (presel == MSGWAIT) {
  1482. if (cfg.filtermode)
  1483. c = FILTER;
  1484. else
  1485. c = CONTROL('L');
  1486. }
  1487. }
  1488. if (c == -1) {
  1489. ++idle;
  1490. /*
  1491. * Do not check for directory changes in du mode.
  1492. * A redraw forces du calculation.
  1493. * Check for changes every odd second.
  1494. */
  1495. #ifdef LINUX_INOTIFY
  1496. if (!cfg.selmode && !cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
  1497. i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
  1498. if (i > 0) {
  1499. char *ptr;
  1500. for (ptr = inotify_buf;
  1501. ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
  1502. ptr += sizeof(struct inotify_event) + event->len) {
  1503. event = (struct inotify_event *) ptr;
  1504. DPRINTF_D(event->wd);
  1505. DPRINTF_D(event->mask);
  1506. if (!event->wd)
  1507. break;
  1508. if (event->mask & INOTIFY_MASK) {
  1509. c = CONTROL('L');
  1510. DPRINTF_S("issue refresh");
  1511. break;
  1512. }
  1513. }
  1514. DPRINTF_S("inotify read done");
  1515. }
  1516. }
  1517. #elif defined(BSD_KQUEUE)
  1518. if (!cfg.selmode && !cfg.blkorder && event_fd >= 0 && idle & 1
  1519. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1520. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1521. c = CONTROL('L');
  1522. #endif
  1523. } else
  1524. idle = 0;
  1525. for (i = 0; i < len; ++i)
  1526. if (c == bindings[i].sym)
  1527. return bindings[i].act;
  1528. return 0;
  1529. }
  1530. static inline void swap_ent(int id1, int id2)
  1531. {
  1532. struct entry _dent, *pdent1 = &dents[id1], *pdent2 = &dents[id2];
  1533. *(&_dent) = *pdent1;
  1534. *pdent1 = *pdent2;
  1535. *pdent2 = *(&_dent);
  1536. }
  1537. /*
  1538. * Move non-matching entries to the end
  1539. */
  1540. static int fill(const char *fltr, regex_t *re)
  1541. {
  1542. int count = 0;
  1543. fltrexp_t fltrexp = { .regex = re, .str = fltr };
  1544. for (; count < ndents; ++count) {
  1545. if (filterfn(&fltrexp, dents[count].name) == 0) {
  1546. if (count != --ndents) {
  1547. swap_ent(count, ndents);
  1548. --count;
  1549. }
  1550. continue;
  1551. }
  1552. }
  1553. return ndents;
  1554. }
  1555. static int matches(const char *fltr)
  1556. {
  1557. regex_t re;
  1558. /* Search filter */
  1559. if (cfg.filter_re && setfilter(&re, fltr) != 0)
  1560. return -1;
  1561. ndents = fill(fltr, &re);
  1562. if (cfg.filter_re)
  1563. regfree(&re);
  1564. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1565. return ndents;
  1566. }
  1567. static int filterentries(char *path)
  1568. {
  1569. wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
  1570. char *ln = g_ctx[cfg.curctx].c_fltr;
  1571. wint_t ch[2] = {0};
  1572. int r, total = ndents, oldcur = cur, len;
  1573. char *pln = g_ctx[cfg.curctx].c_fltr + 1;
  1574. cur = 0;
  1575. if (ndents && ln[0] == FILTER && *pln) {
  1576. if (matches(pln) != -1)
  1577. redraw(path);
  1578. len = mbstowcs(wln, ln, REGEX_MAX);
  1579. } else {
  1580. ln[0] = wln[0] = FILTER;
  1581. ln[1] = wln[1] = '\0';
  1582. len = 1;
  1583. }
  1584. cleartimeout();
  1585. curs_set(TRUE);
  1586. printprompt(ln);
  1587. while ((r = get_wch(ch)) != ERR) {
  1588. switch (*ch) {
  1589. #ifdef KEY_RESIZE
  1590. case KEY_RESIZE:
  1591. clearoldprompt();
  1592. if (len == 1) {
  1593. cur = oldcur;
  1594. redraw(path);
  1595. cur = 0;
  1596. } else
  1597. redraw(path);
  1598. printprompt(ln);
  1599. continue;
  1600. #endif
  1601. case KEY_DC: // fallthrough
  1602. case KEY_BACKSPACE: // fallthrough
  1603. case '\b': // fallthrough
  1604. case CONTROL('L'): // fallthrough
  1605. case 127: /* handle DEL */
  1606. if (len == 1 && *ch != CONTROL('L')) {
  1607. cur = oldcur;
  1608. *ch = CONTROL('L');
  1609. goto end;
  1610. }
  1611. if (*ch == CONTROL('L'))
  1612. while (len > 1)
  1613. wln[--len] = '\0';
  1614. else
  1615. wln[--len] = '\0';
  1616. if (len == 1)
  1617. cur = oldcur;
  1618. wcstombs(ln, wln, REGEX_MAX);
  1619. ndents = total;
  1620. if (matches(pln) != -1)
  1621. redraw(path);
  1622. printprompt(ln);
  1623. continue;
  1624. case KEY_MOUSE: // fallthrough
  1625. case 27: /* Exit filter mode on Escape */
  1626. if (len == 1)
  1627. cur = oldcur;
  1628. goto end;
  1629. }
  1630. if (r == OK) {
  1631. /* Handle all control chars in main loop */
  1632. if ((*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
  1633. || (*ch == ']' && len == 1)) {
  1634. DPRINTF_D(*ch);
  1635. DPRINTF_S(keyname(*ch));
  1636. /* If there's a filter, try a command on ^P */
  1637. if (cfg.filtercmd && *ch == CONTROL('P') && len > 1) {
  1638. prompt_run(pln, (ndents ? dents[cur].name : ""), path);
  1639. /* Clear the prompt */
  1640. while (len > 1)
  1641. wln[--len] = '\0';
  1642. wcstombs(ln, wln, REGEX_MAX);
  1643. ndents = total;
  1644. if (matches(pln) != -1)
  1645. redraw(path);
  1646. printprompt(ln);
  1647. continue;
  1648. }
  1649. if (len == 1)
  1650. cur = oldcur;
  1651. goto end;
  1652. }
  1653. switch (*ch) {
  1654. case '/': /* works as Leader key in filter mode */
  1655. *ch = CONTROL('_'); // fallthrough
  1656. case ':':
  1657. case ';':
  1658. if (len == 1)
  1659. cur = oldcur;
  1660. goto end;
  1661. case '?': /* '?' is an invalid regex, show help instead */
  1662. if (len == 1) {
  1663. cur = oldcur;
  1664. goto end;
  1665. } // fallthrough
  1666. default:
  1667. /* Reset cur in case it's a repeat search */
  1668. if (len == 1)
  1669. cur = 0;
  1670. if (len == REGEX_MAX - 1)
  1671. break;
  1672. wln[len] = (wchar_t)*ch;
  1673. wln[++len] = '\0';
  1674. wcstombs(ln, wln, REGEX_MAX);
  1675. /* Forward-filtering optimization:
  1676. * - new matches can only be a subset of current matches.
  1677. */
  1678. /* ndents = total; */
  1679. if (matches(pln) == -1)
  1680. continue;
  1681. /* If the only match is a dir, auto-select and cd into it */
  1682. if (ndents == 1 && cfg.filtermode
  1683. && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  1684. *ch = KEY_ENTER;
  1685. cur = 0;
  1686. goto end;
  1687. }
  1688. /*
  1689. * redraw() should be above the auto-select optimization, for
  1690. * the case where there's an issue with dir auto-select, say,
  1691. * due to a permission problem. The transition is _jumpy_ in
  1692. * case of such an error. However, we optimize for successful
  1693. * cases where the dir has permissions. This skips a redraw().
  1694. */
  1695. redraw(path);
  1696. printprompt(ln);
  1697. }
  1698. } else {
  1699. if (len == 1)
  1700. cur = oldcur;
  1701. goto end;
  1702. }
  1703. }
  1704. end:
  1705. if (*ch != '\t')
  1706. g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  1707. move_cursor(cur, 0);
  1708. curs_set(FALSE);
  1709. settimeout();
  1710. /* Return keys for navigation etc. */
  1711. return *ch;
  1712. }
  1713. /* Show a prompt with input string and return the changes */
  1714. static char *xreadline(const char *prefill, const char *prompt)
  1715. {
  1716. size_t len, pos;
  1717. int x, r;
  1718. const int WCHAR_T_WIDTH = sizeof(wchar_t);
  1719. wint_t ch[2] = {0};
  1720. wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
  1721. if (!buf)
  1722. errexit();
  1723. cleartimeout();
  1724. printprompt(prompt);
  1725. if (prefill) {
  1726. DPRINTF_S(prefill);
  1727. len = pos = mbstowcs(buf, prefill, READLINE_MAX);
  1728. } else
  1729. len = (size_t)-1;
  1730. if (len == (size_t)-1) {
  1731. buf[0] = '\0';
  1732. len = pos = 0;
  1733. }
  1734. x = getcurx(stdscr);
  1735. curs_set(TRUE);
  1736. while (1) {
  1737. buf[len] = ' ';
  1738. mvaddnwstr(xlines - 1, x, buf, len + 1);
  1739. move(xlines - 1, x + wcswidth(buf, pos));
  1740. r = get_wch(ch);
  1741. if (r != ERR) {
  1742. if (r == OK) {
  1743. switch (*ch) {
  1744. case KEY_ENTER: // fallthrough
  1745. case '\n': // fallthrough
  1746. case '\r':
  1747. goto END;
  1748. case 127: // fallthrough
  1749. case '\b': /* rhel25 sends '\b' for backspace */
  1750. if (pos > 0) {
  1751. memmove(buf + pos - 1, buf + pos,
  1752. (len - pos) * WCHAR_T_WIDTH);
  1753. --len, --pos;
  1754. } // fallthrough
  1755. case '\t': /* TAB breaks cursor position, ignore it */
  1756. continue;
  1757. case CONTROL('L'):
  1758. printprompt(prompt);
  1759. len = pos = 0;
  1760. continue;
  1761. case CONTROL('A'):
  1762. pos = 0;
  1763. continue;
  1764. case CONTROL('E'):
  1765. pos = len;
  1766. continue;
  1767. case CONTROL('U'):
  1768. printprompt(prompt);
  1769. memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
  1770. len -= pos;
  1771. pos = 0;
  1772. continue;
  1773. case 27: /* Exit prompt on Escape */
  1774. len = 0;
  1775. goto END;
  1776. }
  1777. /* Filter out all other control chars */
  1778. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  1779. continue;
  1780. if (pos < READLINE_MAX - 1) {
  1781. memmove(buf + pos + 1, buf + pos,
  1782. (len - pos) * WCHAR_T_WIDTH);
  1783. buf[pos] = *ch;
  1784. ++len, ++pos;
  1785. continue;
  1786. }
  1787. } else {
  1788. switch (*ch) {
  1789. #ifdef KEY_RESIZE
  1790. case KEY_RESIZE:
  1791. clearoldprompt();
  1792. xlines = LINES;
  1793. printprompt(prompt);
  1794. break;
  1795. #endif
  1796. case KEY_LEFT:
  1797. if (pos > 0)
  1798. --pos;
  1799. break;
  1800. case KEY_RIGHT:
  1801. if (pos < len)
  1802. ++pos;
  1803. break;
  1804. case KEY_BACKSPACE:
  1805. if (pos > 0) {
  1806. memmove(buf + pos - 1, buf + pos,
  1807. (len - pos) * WCHAR_T_WIDTH);
  1808. --len, --pos;
  1809. }
  1810. break;
  1811. case KEY_DC:
  1812. if (pos < len) {
  1813. memmove(buf + pos, buf + pos + 1,
  1814. (len - pos - 1) * WCHAR_T_WIDTH);
  1815. --len;
  1816. }
  1817. break;
  1818. case KEY_END:
  1819. pos = len;
  1820. break;
  1821. case KEY_HOME:
  1822. pos = 0;
  1823. break;
  1824. default:
  1825. break;
  1826. }
  1827. }
  1828. }
  1829. }
  1830. END:
  1831. curs_set(FALSE);
  1832. settimeout();
  1833. clearprompt();
  1834. buf[len] = '\0';
  1835. pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
  1836. if (pos >= READLINE_MAX - 1)
  1837. g_buf[READLINE_MAX - 1] = '\0';
  1838. free(buf);
  1839. return g_buf;
  1840. }
  1841. #ifndef NORL
  1842. /*
  1843. * Caller should check the value of presel to confirm if it needs to wait to show warning
  1844. */
  1845. static char *getreadline(char *prompt, char *path, char *curpath, int *presel)
  1846. {
  1847. /* Switch to current path for readline(3) */
  1848. if (chdir(path) == -1) {
  1849. printwarn(presel);
  1850. return NULL;
  1851. }
  1852. exitcurses();
  1853. char *input = readline(prompt);
  1854. refresh();
  1855. if (chdir(curpath) == -1) {
  1856. printwarn(presel);
  1857. free(input);
  1858. return NULL;
  1859. }
  1860. if (input && input[0]) {
  1861. add_history(input);
  1862. xstrlcpy(g_buf, input, CMD_LEN_MAX);
  1863. free(input);
  1864. return g_buf;
  1865. }
  1866. free(input);
  1867. return NULL;
  1868. }
  1869. #endif
  1870. /*
  1871. * Updates out with "dir/name or "/name"
  1872. * Returns the number of bytes copied including the terminating NULL byte
  1873. */
  1874. static size_t mkpath(const char *dir, const char *name, char *out)
  1875. {
  1876. size_t len;
  1877. /* Handle absolute path */
  1878. if (name[0] == '/')
  1879. return xstrlcpy(out, name, PATH_MAX);
  1880. /* Handle root case */
  1881. if (istopdir(dir))
  1882. len = 1;
  1883. else
  1884. len = xstrlcpy(out, dir, PATH_MAX);
  1885. out[len - 1] = '/'; // NOLINT
  1886. return (xstrlcpy(out + len, name, PATH_MAX - len) + len);
  1887. }
  1888. /*
  1889. * Create symbolic/hard link(s) to file(s) in selection list
  1890. * Returns the number of links created
  1891. */
  1892. static int xlink(char *suffix, char *path, char *buf, int *presel, int type)
  1893. {
  1894. int count = 0;
  1895. char *pbuf = pselbuf, *fname;
  1896. size_t pos = 0, len, r;
  1897. int (*link_fn)(const char *, const char *) = NULL;
  1898. /* Check if selection is empty */
  1899. if (!selbufpos) {
  1900. printwait(messages[NONE_SELECTED], presel);
  1901. return -1;
  1902. }
  1903. endselection();
  1904. if (type == 's') /* symbolic link */
  1905. link_fn = &symlink;
  1906. else /* hard link */
  1907. link_fn = &link;
  1908. while (pos < selbufpos) {
  1909. len = strlen(pbuf);
  1910. fname = xbasename(pbuf);
  1911. r = mkpath(path, fname, buf);
  1912. xstrlcpy(buf + r - 1, suffix, PATH_MAX - r - 1);
  1913. if (!link_fn(pbuf, buf))
  1914. ++count;
  1915. pos += len + 1;
  1916. pbuf += len + 1;
  1917. }
  1918. if (!count)
  1919. printwait("none created", presel);
  1920. return count;
  1921. }
  1922. static bool parsekvpair(kv *kvarr, char **envcpy, const char *cfgstr, uchar maxitems)
  1923. {
  1924. int i = 0;
  1925. char *nextkey;
  1926. char *ptr = getenv(cfgstr);
  1927. if (!ptr || !*ptr)
  1928. return TRUE;
  1929. *envcpy = strdup(ptr);
  1930. ptr = *envcpy;
  1931. nextkey = ptr;
  1932. while (*ptr && i < maxitems) {
  1933. if (ptr == nextkey) {
  1934. kvarr[i].key = *ptr;
  1935. if (*++ptr != ':')
  1936. return FALSE;
  1937. if (*++ptr == '\0')
  1938. return FALSE;
  1939. kvarr[i].val = ptr;
  1940. ++i;
  1941. }
  1942. if (*ptr == ';') {
  1943. /* Remove trailing space */
  1944. if (i > 0 && *(ptr - 1) == '/')
  1945. *(ptr - 1) = '\0';
  1946. *ptr = '\0';
  1947. nextkey = ptr + 1;
  1948. }
  1949. ++ptr;
  1950. }
  1951. if (i < maxitems) {
  1952. if (*kvarr[i - 1].val == '\0')
  1953. return FALSE;
  1954. kvarr[i].key = '\0';
  1955. }
  1956. return TRUE;
  1957. }
  1958. /*
  1959. * Get the value corresponding to a key
  1960. *
  1961. * NULL is returned in case of no match, path resolution failure etc.
  1962. * buf would be modified, so check return value before access
  1963. */
  1964. static char *get_kv_val(kv *kvarr, char *buf, int key, uchar max, bool path)
  1965. {
  1966. int r = 0;
  1967. for (; kvarr[r].key && r < max; ++r) {
  1968. if (kvarr[r].key == key) {
  1969. if (!path)
  1970. return kvarr[r].val;
  1971. if (kvarr[r].val[0] == '~') {
  1972. ssize_t len = strlen(home);
  1973. ssize_t loclen = strlen(kvarr[r].val);
  1974. if (!buf)
  1975. buf = (char *)malloc(len + loclen);
  1976. xstrlcpy(buf, home, len + 1);
  1977. xstrlcpy(buf + len, kvarr[r].val + 1, loclen);
  1978. return buf;
  1979. }
  1980. return realpath(kvarr[r].val, buf);
  1981. }
  1982. }
  1983. DPRINTF_S("Invalid key");
  1984. return NULL;
  1985. }
  1986. static inline void resetdircolor(int flags)
  1987. {
  1988. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  1989. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  1990. cfg.dircolor = 0;
  1991. }
  1992. }
  1993. /*
  1994. * Replace escape characters in a string with '?'
  1995. * Adjust string length to maxcols if > 0;
  1996. * Max supported str length: NAME_MAX;
  1997. *
  1998. * Interestingly, note that unescape() uses g_buf. What happens if
  1999. * str also points to g_buf? In this case we assume that the caller
  2000. * acknowledges that it's OK to lose the data in g_buf after this
  2001. * call to unescape().
  2002. * The API, on its part, first converts str to multibyte (after which
  2003. * it doesn't touch str anymore). Only after that it starts modifying
  2004. * g_buf. This is a phased operation.
  2005. */
  2006. static char *unescape(const char *str, uint maxcols, wchar_t **wstr)
  2007. {
  2008. static wchar_t wbuf[NAME_MAX + 1] __attribute__ ((aligned));
  2009. wchar_t *buf = wbuf;
  2010. size_t lencount = 0;
  2011. #ifdef NOLOCALE
  2012. memset(wbuf, 0, sizeof(wbuf));
  2013. #endif
  2014. /* Convert multi-byte to wide char */
  2015. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  2016. while (*buf && lencount <= maxcols) {
  2017. if (*buf <= '\x1f' || *buf == '\x7f')
  2018. *buf = '\?';
  2019. ++buf;
  2020. ++lencount;
  2021. }
  2022. len = lencount = wcswidth(wbuf, len);
  2023. /* Reduce number of wide chars to max columns */
  2024. if (len > maxcols) {
  2025. lencount = maxcols + 1;
  2026. /* Reduce wide chars one by one till it fits */
  2027. while (len > maxcols)
  2028. len = wcswidth(wbuf, --lencount);
  2029. wbuf[lencount] = L'\0';
  2030. }
  2031. if (wstr) {
  2032. *wstr = wbuf;
  2033. return NULL;
  2034. }
  2035. /* Convert wide char to multi-byte */
  2036. wcstombs(g_buf, wbuf, NAME_MAX);
  2037. return g_buf;
  2038. }
  2039. static char *coolsize(off_t size)
  2040. {
  2041. const char * const U = "BKMGTPEZY";
  2042. static char size_buf[12]; /* Buffer to hold human readable size */
  2043. off_t rem = 0;
  2044. size_t ret;
  2045. int i = 0;
  2046. while (size >= 1024) {
  2047. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  2048. size >>= 10;
  2049. ++i;
  2050. }
  2051. if (i == 1) {
  2052. rem = (rem * 1000) >> 10;
  2053. rem /= 10;
  2054. if (rem % 10 >= 5) {
  2055. rem = (rem / 10) + 1;
  2056. if (rem == 10) {
  2057. ++size;
  2058. rem = 0;
  2059. }
  2060. } else
  2061. rem /= 10;
  2062. } else if (i == 2) {
  2063. rem = (rem * 1000) >> 10;
  2064. if (rem % 10 >= 5) {
  2065. rem = (rem / 10) + 1;
  2066. if (rem == 100) {
  2067. ++size;
  2068. rem = 0;
  2069. }
  2070. } else
  2071. rem /= 10;
  2072. } else if (i > 0) {
  2073. rem = (rem * 10000) >> 10;
  2074. if (rem % 10 >= 5) {
  2075. rem = (rem / 10) + 1;
  2076. if (rem == 1000) {
  2077. ++size;
  2078. rem = 0;
  2079. }
  2080. } else
  2081. rem /= 10;
  2082. }
  2083. if (i > 0 && i < 6 && rem) {
  2084. ret = xstrlcpy(size_buf, xitoa(size), 12);
  2085. size_buf[ret - 1] = '.';
  2086. char *frac = xitoa(rem);
  2087. size_t toprint = i > 3 ? 3 : i;
  2088. size_t len = strlen(frac);
  2089. if (len < toprint) {
  2090. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  2091. xstrlcpy(size_buf + ret + (toprint - len), frac, len + 1);
  2092. } else
  2093. xstrlcpy(size_buf + ret, frac, toprint + 1);
  2094. ret += toprint;
  2095. } else {
  2096. ret = xstrlcpy(size_buf, size ? xitoa(size) : "0", 12);
  2097. --ret;
  2098. }
  2099. size_buf[ret] = U[i];
  2100. size_buf[ret + 1] = '\0';
  2101. return size_buf;
  2102. }
  2103. static char get_fileind(mode_t mode)
  2104. {
  2105. char c = '\0';
  2106. switch (mode & S_IFMT) {
  2107. case S_IFREG:
  2108. c = '-';
  2109. break;
  2110. case S_IFDIR:
  2111. c = 'd';
  2112. break;
  2113. case S_IFLNK:
  2114. c = 'l';
  2115. break;
  2116. case S_IFSOCK:
  2117. c = 's';
  2118. break;
  2119. case S_IFIFO:
  2120. c = 'p';
  2121. break;
  2122. case S_IFBLK:
  2123. c = 'b';
  2124. break;
  2125. case S_IFCHR:
  2126. c = 'c';
  2127. break;
  2128. default:
  2129. c = '?';
  2130. break;
  2131. }
  2132. return c;
  2133. }
  2134. /* Convert a mode field into "ls -l" type perms field. */
  2135. static char *get_lsperms(mode_t mode)
  2136. {
  2137. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  2138. static char bits[11] = {'\0'};
  2139. bits[0] = get_fileind(mode);
  2140. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  2141. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  2142. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  2143. if (mode & S_ISUID)
  2144. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  2145. if (mode & S_ISGID)
  2146. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  2147. if (mode & S_ISVTX)
  2148. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  2149. return bits;
  2150. }
  2151. static void printent(const struct entry *ent, int sel, uint namecols)
  2152. {
  2153. wchar_t *wstr;
  2154. char ind = '\0';
  2155. switch (ent->mode & S_IFMT) {
  2156. case S_IFREG:
  2157. if (ent->mode & 0100)
  2158. ind = '*';
  2159. break;
  2160. case S_IFDIR:
  2161. ind = '/';
  2162. break;
  2163. case S_IFLNK:
  2164. ind = '@';
  2165. break;
  2166. case S_IFSOCK:
  2167. ind = '=';
  2168. break;
  2169. case S_IFIFO:
  2170. ind = '|';
  2171. break;
  2172. case S_IFBLK: // fallthrough
  2173. case S_IFCHR:
  2174. break;
  2175. default:
  2176. ind = '?';
  2177. break;
  2178. }
  2179. if (!ind)
  2180. ++namecols;
  2181. unescape(ent->name, namecols, &wstr);
  2182. /* Directories are always shown on top */
  2183. resetdircolor(ent->flags);
  2184. if (sel)
  2185. attron(A_REVERSE);
  2186. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2187. addwstr(wstr);
  2188. if (ind)
  2189. addch(ind);
  2190. addch('\n');
  2191. if (sel)
  2192. attroff(A_REVERSE);
  2193. }
  2194. static void printent_long(const struct entry *ent, int sel, uint namecols)
  2195. {
  2196. char timebuf[24], permbuf[4], ind1 = '\0', ind2[] = "\0\0";
  2197. const char cp = (ent->flags & FILE_SELECTED) ? '+' : ' ';
  2198. /* Timestamp */
  2199. strftime(timebuf, sizeof(timebuf), "%F %R", localtime(&ent->t));
  2200. timebuf[sizeof(timebuf)-1] = '\0';
  2201. /* Permissions */
  2202. permbuf[0] = '0' + ((ent->mode >> 6) & 7);
  2203. permbuf[1] = '0' + ((ent->mode >> 3) & 7);
  2204. permbuf[2] = '0' + (ent->mode & 7);
  2205. permbuf[3] = '\0';
  2206. /* Add a column if no indicator is needed */
  2207. if (S_ISREG(ent->mode) && !(ent->mode & 0100))
  2208. ++namecols;
  2209. /* Trim escape chars from name */
  2210. const char *pname = unescape(ent->name, namecols, NULL);
  2211. /* Directories are always shown on top */
  2212. resetdircolor(ent->flags);
  2213. if (sel)
  2214. attron(A_REVERSE);
  2215. switch (ent->mode & S_IFMT) {
  2216. case S_IFREG:
  2217. if (ent->mode & 0100)
  2218. printw("%c%-16.16s %s %8.8s* %s*\n", cp, timebuf, permbuf,
  2219. coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size), pname);
  2220. else
  2221. printw("%c%-16.16s %s %8.8s %s\n", cp, timebuf, permbuf,
  2222. coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size), pname);
  2223. break;
  2224. case S_IFDIR:
  2225. printw("%c%-16.16s %s %8.8s %s/\n", cp, timebuf, permbuf,
  2226. coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size), pname);
  2227. break;
  2228. case S_IFLNK:
  2229. printw("%c%-16.16s %s @ %s@\n", cp, timebuf, permbuf, pname);
  2230. break;
  2231. case S_IFSOCK:
  2232. ind1 = ind2[0] = '='; // fallthrough
  2233. case S_IFIFO:
  2234. if (!ind1)
  2235. ind1 = ind2[0] = '|'; // fallthrough
  2236. case S_IFBLK:
  2237. if (!ind1)
  2238. ind1 = 'b'; // fallthrough
  2239. case S_IFCHR:
  2240. if (!ind1)
  2241. ind1 = 'c'; // fallthrough
  2242. default:
  2243. if (!ind1)
  2244. ind1 = ind2[0] = '?';
  2245. printw("%c%-16.16s %s %c %s%s\n", cp, timebuf, permbuf, ind1, pname, ind2);
  2246. break;
  2247. }
  2248. if (sel)
  2249. attroff(A_REVERSE);
  2250. }
  2251. static void (*printptr)(const struct entry *ent, int sel, uint namecols) = &printent;
  2252. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2253. {
  2254. settings cfg = *curcfg;
  2255. bool selmode = cfg.selmode ? TRUE : FALSE;
  2256. /* Save current context */
  2257. xstrlcpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2258. g_ctx[cfg.curctx].c_cfg = cfg;
  2259. if (g_ctx[r].c_cfg.ctxactive) { /* Switch to saved context */
  2260. /* Switch light/detail mode */
  2261. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  2262. /* set the reverse */
  2263. printptr = cfg.showdetail ? &printent : &printent_long;
  2264. cfg = g_ctx[r].c_cfg;
  2265. } else { /* Setup a new context from current context */
  2266. g_ctx[r].c_cfg.ctxactive = 1;
  2267. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2268. g_ctx[r].c_last[0] = '\0';
  2269. xstrlcpy(g_ctx[r].c_name, curname, NAME_MAX + 1);
  2270. g_ctx[r].c_fltr[0] = g_ctx[r].c_fltr[1] = '\0';
  2271. g_ctx[r].c_cfg = cfg;
  2272. g_ctx[r].c_cfg.runplugin = 0;
  2273. }
  2274. /* Continue selection mode */
  2275. cfg.selmode = selmode;
  2276. cfg.curctx = r;
  2277. *curcfg = cfg;
  2278. }
  2279. static void save_session(bool last_session, int *presel)
  2280. {
  2281. char spath[PATH_MAX];
  2282. int i;
  2283. session_header_t header;
  2284. FILE *fsession;
  2285. char *sname;
  2286. bool status = FALSE;
  2287. header.ver = SESSIONS_VERSION;
  2288. for (i = 0; i < CTX_MAX; ++i) {
  2289. if (!g_ctx[i].c_cfg.ctxactive) {
  2290. header.pathln[i] = header.nameln[i]
  2291. = header.lastln[i] = header.fltrln[i] = 0;
  2292. } else {
  2293. header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
  2294. header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
  2295. header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
  2296. header.fltrln[i] = strnlen(g_ctx[i].c_fltr, REGEX_MAX) + 1;
  2297. }
  2298. }
  2299. sname = !last_session ? xreadline(NULL, messages[SESSION_NAME]) : "@";
  2300. if (!sname[0])
  2301. return;
  2302. mkpath(sessiondir, sname, spath);
  2303. fsession = fopen(spath, "wb");
  2304. if (!fsession) {
  2305. printwait("failed to open session file", presel);
  2306. return;
  2307. }
  2308. if ((fwrite(&header, sizeof(header), 1, fsession) != 1)
  2309. || (fwrite(&cfg, sizeof(cfg), 1, fsession) != 1))
  2310. goto END;
  2311. for (i = 0; i < CTX_MAX; ++i)
  2312. if ((fwrite(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2313. || (fwrite(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2314. || (header.nameln[i] > 0 && fwrite(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2315. || (header.lastln[i] > 0 && fwrite(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2316. || (header.fltrln[i] > 0 && fwrite(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2317. || (header.pathln[i] > 0 && fwrite(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2318. goto END;
  2319. status = TRUE;
  2320. END:
  2321. fclose(fsession);
  2322. if (!status)
  2323. printwait("failed to write session data", presel);
  2324. }
  2325. static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
  2326. {
  2327. char spath[PATH_MAX];
  2328. int i = 0;
  2329. session_header_t header;
  2330. FILE *fsession;
  2331. bool has_loaded_dynamically = !(sname || restore);
  2332. bool status = FALSE;
  2333. if (!restore) {
  2334. sname = sname ? sname : xreadline(NULL, messages[SESSION_NAME]);
  2335. if (!sname[0])
  2336. return FALSE;
  2337. mkpath(sessiondir, sname, spath);
  2338. } else
  2339. mkpath(sessiondir, "@", spath);
  2340. if (has_loaded_dynamically)
  2341. save_session(TRUE, NULL);
  2342. fsession = fopen(spath, "rb");
  2343. if (!fsession) {
  2344. printmsg("failed to open session file");
  2345. xdelay();
  2346. return FALSE;
  2347. }
  2348. if ((fread(&header, sizeof(header), 1, fsession) != 1)
  2349. || (header.ver != SESSIONS_VERSION)
  2350. || (fread(&cfg, sizeof(cfg), 1, fsession) != 1))
  2351. goto END;
  2352. g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
  2353. = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  2354. for (; i < CTX_MAX; ++i)
  2355. if ((fread(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2356. || (fread(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2357. || (header.nameln[i] > 0 && fread(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2358. || (header.lastln[i] > 0 && fread(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2359. || (header.fltrln[i] > 0 && fread(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2360. || (header.pathln[i] > 0 && fread(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2361. goto END;
  2362. *path = g_ctx[cfg.curctx].c_path;
  2363. *lastdir = g_ctx[cfg.curctx].c_last;
  2364. *lastname = g_ctx[cfg.curctx].c_name;
  2365. status = TRUE;
  2366. END:
  2367. fclose(fsession);
  2368. if (!status) {
  2369. printmsg("failed to read session data");
  2370. xdelay();
  2371. }
  2372. return status;
  2373. }
  2374. /*
  2375. * Gets only a single line (that's what we need
  2376. * for now) or shows full command output in pager.
  2377. *
  2378. * If page is valid, returns NULL
  2379. */
  2380. static char *get_output(char *buf, const size_t bytes, const char *file,
  2381. const char *arg1, const char *arg2, const bool page)
  2382. {
  2383. pid_t pid;
  2384. int pipefd[2];
  2385. FILE *pf;
  2386. int tmp, flags;
  2387. char *ret = NULL;
  2388. if (pipe(pipefd) == -1)
  2389. errexit();
  2390. for (tmp = 0; tmp < 2; ++tmp) {
  2391. /* Get previous flags */
  2392. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2393. /* Set bit for non-blocking flag */
  2394. flags |= O_NONBLOCK;
  2395. /* Change flags on fd */
  2396. fcntl(pipefd[tmp], F_SETFL, flags);
  2397. }
  2398. pid = fork();
  2399. if (pid == 0) {
  2400. /* In child */
  2401. close(pipefd[0]);
  2402. dup2(pipefd[1], STDOUT_FILENO);
  2403. dup2(pipefd[1], STDERR_FILENO);
  2404. close(pipefd[1]);
  2405. execlp(file, file, arg1, arg2, NULL);
  2406. _exit(1);
  2407. }
  2408. /* In parent */
  2409. waitpid(pid, &tmp, 0);
  2410. close(pipefd[1]);
  2411. if (!page) {
  2412. pf = fdopen(pipefd[0], "r");
  2413. if (pf) {
  2414. ret = fgets(buf, bytes, pf);
  2415. close(pipefd[0]);
  2416. }
  2417. return ret;
  2418. }
  2419. pid = fork();
  2420. if (pid == 0) {
  2421. /* Show in pager in child */
  2422. dup2(pipefd[0], STDIN_FILENO);
  2423. close(pipefd[0]);
  2424. spawn(pager, NULL, NULL, NULL, F_CLI);
  2425. _exit(1);
  2426. }
  2427. /* In parent */
  2428. waitpid(pid, &tmp, 0);
  2429. close(pipefd[0]);
  2430. return NULL;
  2431. }
  2432. static inline bool getutil(char *util)
  2433. {
  2434. return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
  2435. }
  2436. static void pipetof(char *cmd, FILE *fout)
  2437. {
  2438. FILE *fin = popen(cmd, "r");
  2439. if (fin) {
  2440. while (fgets(g_buf, CMD_LEN_MAX - 1, fin))
  2441. fprintf(fout, "%s", g_buf);
  2442. pclose(fin);
  2443. }
  2444. }
  2445. /*
  2446. * Follows the stat(1) output closely
  2447. */
  2448. static bool show_stats(const char *fpath, const struct stat *sb)
  2449. {
  2450. int fd;
  2451. FILE *fp;
  2452. char *p, *begin = g_buf;
  2453. size_t r;
  2454. fd = create_tmp_file();
  2455. if (fd == -1)
  2456. return FALSE;
  2457. r = xstrlcpy(g_buf, "stat \"", PATH_MAX);
  2458. r += xstrlcpy(g_buf + r - 1, fpath, PATH_MAX);
  2459. g_buf[r - 2] = '\"';
  2460. g_buf[r - 1] = '\0';
  2461. DPRINTF_S(g_buf);
  2462. fp = fdopen(fd, "w");
  2463. if (!fp) {
  2464. close(fd);
  2465. return FALSE;
  2466. }
  2467. pipetof(g_buf, fp);
  2468. if (S_ISREG(sb->st_mode)) {
  2469. /* Show file(1) output */
  2470. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  2471. if (p) {
  2472. fprintf(fp, "\n\n ");
  2473. while (*p) {
  2474. if (*p == ',') {
  2475. *p = '\0';
  2476. fprintf(fp, " %s\n", begin);
  2477. begin = p + 1;
  2478. }
  2479. ++p;
  2480. }
  2481. fprintf(fp, " %s", begin);
  2482. }
  2483. }
  2484. fprintf(fp, "\n\n");
  2485. fclose(fp);
  2486. close(fd);
  2487. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  2488. unlink(g_tmpfpath);
  2489. return TRUE;
  2490. }
  2491. static size_t get_fs_info(const char *path, bool type)
  2492. {
  2493. struct statvfs svb;
  2494. if (statvfs(path, &svb) == -1)
  2495. return 0;
  2496. if (type == CAPACITY)
  2497. return svb.f_blocks << ffs((int)(svb.f_bsize >> 1));
  2498. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  2499. }
  2500. /* List or extract archive */
  2501. static void handle_archive(char *fpath, const char *dir, char op)
  2502. {
  2503. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  2504. char *util;
  2505. if (getutil(utils[ATOOL])) {
  2506. util = utils[ATOOL];
  2507. arg[1] = op;
  2508. arg[2] = '\0';
  2509. } else if (getutil(utils[BSDTAR])) {
  2510. util = utils[BSDTAR];
  2511. if (op == 'x')
  2512. arg[1] = op;
  2513. } else if (is_suffix(fpath, ".zip")) {
  2514. util = utils[UNZIP];
  2515. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  2516. arg[2] = '\0';
  2517. } else {
  2518. util = utils[TAR];
  2519. if (op == 'x')
  2520. arg[1] = op;
  2521. }
  2522. if (op == 'x') { /* extract */
  2523. spawn(util, arg, fpath, dir, F_NORMAL);
  2524. } else { /* list */
  2525. exitcurses();
  2526. get_output(NULL, 0, util, arg, fpath, TRUE);
  2527. refresh();
  2528. }
  2529. }
  2530. static char *visit_parent(char *path, char *newpath, int *presel)
  2531. {
  2532. char *dir;
  2533. /* There is no going back */
  2534. if (istopdir(path)) {
  2535. /* Continue in navigate-as-you-type mode, if enabled */
  2536. if (cfg.filtermode)
  2537. *presel = FILTER;
  2538. return NULL;
  2539. }
  2540. /* Use a copy as dirname() may change the string passed */
  2541. xstrlcpy(newpath, path, PATH_MAX);
  2542. dir = dirname(newpath);
  2543. if (access(dir, R_OK) == -1) {
  2544. printwarn(presel);
  2545. return NULL;
  2546. }
  2547. return dir;
  2548. }
  2549. static void find_accessible_parent(char *path, char *newpath, char *lastname, int *presel)
  2550. {
  2551. char *dir;
  2552. /* Save history */
  2553. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  2554. xstrlcpy(newpath, path, PATH_MAX);
  2555. while (true) {
  2556. dir = visit_parent(path, newpath, presel);
  2557. if (istopdir(path) || istopdir(newpath)) {
  2558. if (!dir)
  2559. dir = dirname(newpath);
  2560. break;
  2561. }
  2562. if (!dir) {
  2563. xstrlcpy(path, newpath, PATH_MAX);
  2564. continue;
  2565. }
  2566. break;
  2567. }
  2568. xstrlcpy(path, dir, PATH_MAX);
  2569. printmsg("cannot access dir");
  2570. xdelay();
  2571. }
  2572. static bool execute_file(int cur, char *path, char *newpath, int *presel)
  2573. {
  2574. if (!ndents)
  2575. return FALSE;
  2576. /* Check if this is a directory */
  2577. if (!S_ISREG(dents[cur].mode)) {
  2578. printwait("not regular file", presel);
  2579. return FALSE;
  2580. }
  2581. /* Check if file is executable */
  2582. if (!(dents[cur].mode & 0100)) {
  2583. printwait("permission denied", presel);
  2584. return FALSE;
  2585. }
  2586. mkpath(path, dents[cur].name, newpath);
  2587. spawn(newpath, NULL, NULL, path, F_NORMAL);
  2588. return TRUE;
  2589. }
  2590. /* Create non-existent parents and a file or dir */
  2591. static bool xmktree(char* path, bool dir)
  2592. {
  2593. char* p = path;
  2594. char *slash = path;
  2595. if (!p || !*p)
  2596. return FALSE;
  2597. /* Skip the first '/' */
  2598. ++p;
  2599. while (*p != '\0') {
  2600. if (*p == '/') {
  2601. slash = p;
  2602. *p = '\0';
  2603. } else {
  2604. ++p;
  2605. continue;
  2606. }
  2607. /* Create folder from path to '\0' inserted at p */
  2608. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  2609. DPRINTF_S("mkdir1!");
  2610. DPRINTF_S(strerror(errno));
  2611. *slash = '/';
  2612. return FALSE;
  2613. }
  2614. /* Restore path */
  2615. *slash = '/';
  2616. ++p;
  2617. }
  2618. if (dir) {
  2619. if(mkdir(path, 0777) == -1 && errno != EEXIST) {
  2620. DPRINTF_S("mkdir2!");
  2621. DPRINTF_S(strerror(errno));
  2622. return FALSE;
  2623. }
  2624. } else {
  2625. int fd = open(path, O_CREAT, 0666);
  2626. if (fd == -1 && errno != EEXIST) {
  2627. DPRINTF_S("open!");
  2628. DPRINTF_S(strerror(errno));
  2629. return FALSE;
  2630. }
  2631. close(fd);
  2632. }
  2633. return TRUE;
  2634. }
  2635. static bool archive_mount(char *name, char *path, char *newpath, int *presel)
  2636. {
  2637. char *dir, *cmd = "archivemount";
  2638. size_t len;
  2639. if (!getutil(cmd)) {
  2640. printwait(messages[UTIL_MISSING], presel);
  2641. return FALSE;
  2642. }
  2643. dir = strdup(name);
  2644. if (!dir)
  2645. return FALSE;
  2646. len = strlen(dir);
  2647. while (len > 1)
  2648. if (dir[--len] == '.') {
  2649. dir[len] = '\0';
  2650. break;
  2651. }
  2652. DPRINTF_S(dir);
  2653. /* Create the mount point */
  2654. mkpath(cfgdir, dir, newpath);
  2655. free(dir);
  2656. if (!xmktree(newpath, TRUE)) {
  2657. printwait(strerror(errno), presel);
  2658. return FALSE;
  2659. }
  2660. /* Mount archive */
  2661. DPRINTF_S(name);
  2662. DPRINTF_S(newpath);
  2663. if (spawn(cmd, name, newpath, path, F_NORMAL)) {
  2664. printwait(messages[OPERATION_FAILED], presel);
  2665. return FALSE;
  2666. }
  2667. return TRUE;
  2668. }
  2669. static bool sshfs_mount(char *newpath, int *presel)
  2670. {
  2671. uchar flag = F_NORMAL;
  2672. int r;
  2673. char *tmp, *env, *cmd = "sshfs";
  2674. if (!getutil(cmd)) {
  2675. printwait(messages[UTIL_MISSING], presel);
  2676. return FALSE;
  2677. }
  2678. tmp = xreadline(NULL, "host: ");
  2679. if (!tmp[0])
  2680. return FALSE;
  2681. /* Create the mount point */
  2682. mkpath(cfgdir, tmp, newpath);
  2683. if (!xmktree(newpath, TRUE)) {
  2684. printwait(strerror(errno), presel);
  2685. return FALSE;
  2686. }
  2687. /* Convert "Host" to "Host:" */
  2688. r = strlen(tmp);
  2689. tmp[r] = ':';
  2690. tmp[r + 1] = '\0';
  2691. env = getenv("NNN_SSHFS_OPTS");
  2692. if (env)
  2693. flag |= F_MULTI;
  2694. else
  2695. env = cmd;
  2696. /* Connect to remote */
  2697. if (spawn(env, tmp, newpath, NULL, flag)) {
  2698. printwait(messages[OPERATION_FAILED], presel);
  2699. return FALSE;
  2700. }
  2701. return TRUE;
  2702. }
  2703. /*
  2704. * Unmounts if the directory represented by name is a mount point.
  2705. * Otherwise, asks for hostname
  2706. */
  2707. static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
  2708. {
  2709. char cmd[] = "fusermount3"; /* Arch Linux utility */
  2710. static bool found = FALSE;
  2711. char *tmp = name;
  2712. struct stat sb, psb;
  2713. bool child = false;
  2714. bool parent = false;
  2715. /* On Ubuntu it's fusermount */
  2716. if (!found && !getutil(cmd)) {
  2717. cmd[10] = '\0';
  2718. found = TRUE;
  2719. }
  2720. if (tmp && strcmp(cfgdir, currentpath) == 0) {
  2721. mkpath(cfgdir, tmp, newpath);
  2722. child = lstat(newpath, &sb) != -1;
  2723. parent = lstat(dirname(newpath), &psb) != -1;
  2724. if (!child && !parent) {
  2725. *presel = MSGWAIT;
  2726. return FALSE;
  2727. }
  2728. }
  2729. if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
  2730. tmp = xreadline(NULL, "host: ");
  2731. if (!tmp[0])
  2732. return FALSE;
  2733. }
  2734. /* Create the mount point */
  2735. mkpath(cfgdir, tmp, newpath);
  2736. if (!xdiraccess(newpath)) {
  2737. *presel = MSGWAIT;
  2738. return FALSE;
  2739. }
  2740. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  2741. printwait(messages[OPERATION_FAILED], presel);
  2742. return FALSE;
  2743. }
  2744. return TRUE;
  2745. }
  2746. static void lock_terminal(void)
  2747. {
  2748. char *tmp = utils[LOCKER];
  2749. if (!getutil(tmp))
  2750. tmp = utils[CMATRIX];
  2751. spawn(tmp, NULL, NULL, NULL, F_NORMAL);
  2752. }
  2753. static void printkv(kv *kvarr, FILE *fp, uchar max)
  2754. {
  2755. uchar i = 0;
  2756. for (; i < max && kvarr[i].key; ++i)
  2757. fprintf(fp, " %c: %s\n", (char)kvarr[i].key, kvarr[i].val);
  2758. }
  2759. /*
  2760. * The help string tokens (each line) start with a HEX value
  2761. * which indicates the number of spaces to print before the
  2762. * particular token. This method was chosen instead of a flat
  2763. * string because the number of bytes in help was increasing
  2764. * the binary size by around a hundred bytes. This would only
  2765. * have increased as we keep adding new options.
  2766. */
  2767. static void show_help(const char *path)
  2768. {
  2769. int i, fd;
  2770. FILE *fp;
  2771. const char *start, *end;
  2772. const char helpstr[] = {
  2773. "0\n"
  2774. "1NAVIGATION\n"
  2775. "9Up k Up PgUp ^U Scroll up\n"
  2776. "7Down j Down PgDn ^D Scroll down\n"
  2777. "7Left h Parent ~ ` @ - HOME, /, start, last\n"
  2778. "2Ret Right l Open . Toggle show hidden\n"
  2779. "9g ^A First entry G ^E Last entry\n"
  2780. "cb Pin current dir ^B Go to pinned dir\n"
  2781. "6(Sh)Tab Cycle context d Toggle detail view\n"
  2782. "9, ^/ Lead key N LeadN Context N\n"
  2783. "c/ Filter/Lead Ins ^N Toggle nav-as-you-type\n"
  2784. "aEsc Exit prompt ^L F5 Redraw/clear prompt\n"
  2785. "c? Help, conf ' Lead' First file\n"
  2786. "9Q ^Q Quit ^G QuitCD q Quit context\n"
  2787. "1FILES\n"
  2788. "b^O Open with... n Create new/link\n"
  2789. "cD File details ^R F2 Rename/duplicate\n"
  2790. "3Space ^J/a Select entry/all r Batch rename\n"
  2791. "9m ^K Sel range, clear M List selection\n"
  2792. "cP Copy selection K Edit, flush sel\n"
  2793. "cV Move selection w Copy/move sel as\n"
  2794. "cX Del selection ^X Del entry\n"
  2795. "cf Create archive T Mount archive\n"
  2796. "b^F Extract archive F List archive\n"
  2797. "ce Edit in EDITOR p Open in PAGER\n"
  2798. "1ORDER TOGGLES\n"
  2799. "cA Apparent du S du\n"
  2800. "cz Size E Extn t Time\n"
  2801. "1MISC\n"
  2802. "9! ^] Shell ;K :K xK Execute plugin K\n"
  2803. "cC Execute entry R ^V Pick plugin\n"
  2804. "cU Manage session = Launch\n"
  2805. "cc SSHFS mount u Unmount\n"
  2806. "9] ^P Prompt/run cmd L Lock\n"};
  2807. fd = create_tmp_file();
  2808. if (fd == -1)
  2809. return;
  2810. fp = fdopen(fd, "w");
  2811. if (!fp) {
  2812. close(fd);
  2813. return;
  2814. }
  2815. start = end = helpstr;
  2816. while (*end) {
  2817. if (*end == '\n') {
  2818. fprintf(fp, "%*c%.*s",
  2819. xchartohex(*start), ' ', (int)(end - start), start + 1);
  2820. start = end + 1;
  2821. }
  2822. ++end;
  2823. }
  2824. fprintf(fp, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  2825. fprintf(fp, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  2826. if (bookmark[0].val) {
  2827. fprintf(fp, "BOOKMARKS\n");
  2828. printkv(bookmark, fp, BM_MAX);
  2829. fprintf(fp, "\n");
  2830. }
  2831. if (plug[0].val) {
  2832. fprintf(fp, "PLUGIN KEYS\n");
  2833. printkv(plug, fp, PLUGIN_MAX);
  2834. fprintf(fp, "\n");
  2835. }
  2836. for (i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  2837. start = getenv(env_cfg[i]);
  2838. if (start)
  2839. fprintf(fp, "%s: %s\n", env_cfg[i], start);
  2840. }
  2841. if (g_selpath)
  2842. fprintf(fp, "SELECTION FILE: %s\n", g_selpath);
  2843. fprintf(fp, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  2844. fclose(fp);
  2845. close(fd);
  2846. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  2847. unlink(g_tmpfpath);
  2848. }
  2849. static bool plctrl_init(void)
  2850. {
  2851. snprintf(g_buf, CMD_LEN_MAX, "nnn-pipe.%d", getpid());
  2852. /* g_tmpfpath is used to generate tmp file names */
  2853. g_tmpfpath[g_tmpfplen - 1] = '\0';
  2854. mkpath(g_tmpfpath, g_buf, g_pipepath);
  2855. unlink(g_pipepath);
  2856. if (mkfifo(g_pipepath, 0600) != 0)
  2857. return _FAILURE;
  2858. setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
  2859. return _SUCCESS;
  2860. }
  2861. static bool run_selected_plugin(char **path, const char *file, char *newpath, char *runfile, char **lastname, char **lastdir)
  2862. {
  2863. int fd;
  2864. size_t len;
  2865. if (!g_plinit) {
  2866. plctrl_init();
  2867. g_plinit = TRUE;
  2868. }
  2869. fd = open(g_pipepath, O_RDONLY | O_NONBLOCK);
  2870. if (fd == -1)
  2871. return FALSE;
  2872. /* Generate absolute path to plugin */
  2873. mkpath(plugindir, file, newpath);
  2874. if (runfile && runfile[0]) {
  2875. xstrlcpy(*lastname, runfile, NAME_MAX);
  2876. spawn(newpath, *lastname, *path, *path, F_NORMAL);
  2877. } else
  2878. spawn(newpath, NULL, *path, *path, F_NORMAL);
  2879. len = read(fd, g_buf, PATH_MAX);
  2880. g_buf[len] = '\0';
  2881. close(fd);
  2882. if (len > 1) {
  2883. int ctx = g_buf[0] - '0';
  2884. if (ctx == 0 || ctx == cfg.curctx + 1) {
  2885. xstrlcpy(*lastdir, *path, PATH_MAX);
  2886. xstrlcpy(*path, g_buf + 1, PATH_MAX);
  2887. } else if (ctx >= 1 && ctx <= CTX_MAX) {
  2888. int r = ctx - 1;
  2889. g_ctx[r].c_cfg.ctxactive = 0;
  2890. savecurctx(&cfg, g_buf + 1, dents[cur].name, r);
  2891. *path = g_ctx[r].c_path;
  2892. *lastdir = g_ctx[r].c_last;
  2893. *lastname = g_ctx[r].c_name;
  2894. }
  2895. }
  2896. return TRUE;
  2897. }
  2898. static int sum_bsizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  2899. {
  2900. (void) fpath;
  2901. (void) ftwbuf;
  2902. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  2903. ent_blocks += sb->st_blocks;
  2904. ++num_files;
  2905. return 0;
  2906. }
  2907. static int sum_sizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  2908. {
  2909. (void) fpath;
  2910. (void) ftwbuf;
  2911. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  2912. ent_blocks += sb->st_size;
  2913. ++num_files;
  2914. return 0;
  2915. }
  2916. static void dentfree(void)
  2917. {
  2918. free(pnamebuf);
  2919. free(dents);
  2920. }
  2921. static int dentfill(char *path, struct entry **dents)
  2922. {
  2923. static uint open_max;
  2924. int n = 0, count, flags = 0;
  2925. ulong num_saved;
  2926. struct dirent *dp;
  2927. char *namep, *pnb, *buf = NULL;
  2928. struct entry *dentp;
  2929. size_t off = 0, namebuflen = NAMEBUF_INCR;
  2930. struct stat sb_path, sb;
  2931. DIR *dirp = opendir(path);
  2932. if (!dirp)
  2933. return 0;
  2934. int fd = dirfd(dirp);
  2935. if (cfg.blkorder) {
  2936. num_files = 0;
  2937. dir_blocks = 0;
  2938. buf = (char *)alloca(strlen(path) + NAME_MAX + 2);
  2939. if (fstatat(fd, path, &sb_path, 0) == -1) {
  2940. closedir(dirp);
  2941. printwarn(NULL);
  2942. return 0;
  2943. }
  2944. /* Increase current open file descriptor limit */
  2945. if (!open_max)
  2946. open_max = max_openfds();
  2947. }
  2948. #if _POSIX_C_SOURCE >= 200112L
  2949. posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
  2950. #endif
  2951. dp = readdir(dirp);
  2952. if (!dp)
  2953. goto exit;
  2954. #ifdef __sun
  2955. if (cfg.blkorder) { /* no d_type */
  2956. #else
  2957. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  2958. #endif
  2959. /*
  2960. * Optimization added for filesystems which support dirent.d_type
  2961. * see readdir(3)
  2962. * Known drawbacks:
  2963. * - the symlink size is set to 0
  2964. * - the modification time of the symlink is set to that of the target file
  2965. */
  2966. flags = AT_SYMLINK_NOFOLLOW;
  2967. }
  2968. do {
  2969. namep = dp->d_name;
  2970. /* Skip self and parent */
  2971. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  2972. continue;
  2973. if (!cfg.showhidden && namep[0] == '.') {
  2974. if (!cfg.blkorder)
  2975. continue;
  2976. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  2977. continue;
  2978. if (S_ISDIR(sb.st_mode)) {
  2979. if (sb_path.st_dev == sb.st_dev) {
  2980. ent_blocks = 0;
  2981. mkpath(path, namep, buf);
  2982. tolastln();
  2983. addstr(xbasename(buf));
  2984. addstr(" [^C aborts]\n");
  2985. refresh();
  2986. if (nftw(buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) < 0) {
  2987. DPRINTF_S("nftw failed");
  2988. dir_blocks += (cfg.apparentsz
  2989. ? sb.st_size
  2990. : sb.st_blocks);
  2991. } else
  2992. dir_blocks += ent_blocks;
  2993. if (interrupted) {
  2994. closedir(dirp);
  2995. return n;
  2996. }
  2997. }
  2998. } else {
  2999. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3000. ++num_files;
  3001. }
  3002. continue;
  3003. }
  3004. if (fstatat(fd, namep, &sb, flags) == -1) {
  3005. /* List a symlink with target missing */
  3006. if (!flags && errno == ENOENT) {
  3007. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  3008. DPRINTF_S(namep);
  3009. DPRINTF_S(strerror(errno));
  3010. continue;
  3011. }
  3012. } else {
  3013. DPRINTF_S(namep);
  3014. DPRINTF_S(strerror(errno));
  3015. continue;
  3016. }
  3017. }
  3018. if (n == total_dents) {
  3019. total_dents += ENTRY_INCR;
  3020. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  3021. if (!*dents) {
  3022. free(pnamebuf);
  3023. closedir(dirp);
  3024. errexit();
  3025. }
  3026. DPRINTF_P(*dents);
  3027. }
  3028. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  3029. if (namebuflen - off < NAME_MAX + 1) {
  3030. namebuflen += NAMEBUF_INCR;
  3031. pnb = pnamebuf;
  3032. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  3033. if (!pnamebuf) {
  3034. free(*dents);
  3035. closedir(dirp);
  3036. errexit();
  3037. }
  3038. DPRINTF_P(pnamebuf);
  3039. /* realloc() may result in memory move, we must re-adjust if that happens */
  3040. if (pnb != pnamebuf) {
  3041. dentp = *dents;
  3042. dentp->name = pnamebuf;
  3043. for (count = 1; count < n; ++dentp, ++count)
  3044. /* Current filename starts at last filename start + length */
  3045. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  3046. }
  3047. }
  3048. dentp = *dents + n;
  3049. /* Selection file name */
  3050. dentp->name = (char *)((size_t)pnamebuf + off);
  3051. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  3052. off += dentp->nlen;
  3053. /* Copy other fields */
  3054. dentp->t = cfg.mtime ? sb.st_mtime : sb.st_atime;
  3055. #ifndef __sun
  3056. if (!flags && dp->d_type == DT_LNK) {
  3057. /* Do not add sizes for links */
  3058. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  3059. dentp->size = 0;
  3060. } else {
  3061. dentp->mode = sb.st_mode;
  3062. dentp->size = sb.st_size;
  3063. }
  3064. #else
  3065. dentp->mode = sb.st_mode;
  3066. dentp->size = sb.st_size;
  3067. #endif
  3068. dentp->flags = 0;
  3069. if (cfg.blkorder) {
  3070. if (S_ISDIR(sb.st_mode)) {
  3071. ent_blocks = 0;
  3072. num_saved = num_files + 1;
  3073. mkpath(path, namep, buf);
  3074. tolastln();
  3075. addstr(xbasename(buf));
  3076. addstr(" [^C aborts]\n");
  3077. refresh();
  3078. if (nftw(buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) < 0) {
  3079. DPRINTF_S("nftw failed");
  3080. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3081. } else
  3082. dentp->blocks = ent_blocks;
  3083. if (sb_path.st_dev == sb.st_dev) // NOLINT
  3084. dir_blocks += dentp->blocks;
  3085. else
  3086. num_files = num_saved;
  3087. if (interrupted) {
  3088. closedir(dirp);
  3089. return n;
  3090. }
  3091. } else {
  3092. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3093. dir_blocks += dentp->blocks;
  3094. ++num_files;
  3095. }
  3096. }
  3097. if (flags) {
  3098. /* Flag if this is a dir or symlink to a dir */
  3099. if (S_ISLNK(sb.st_mode)) {
  3100. sb.st_mode = 0;
  3101. fstatat(fd, namep, &sb, 0);
  3102. }
  3103. if (S_ISDIR(sb.st_mode))
  3104. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3105. #ifndef __sun /* no d_type */
  3106. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode))) {
  3107. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3108. #endif
  3109. }
  3110. ++n;
  3111. } while ((dp = readdir(dirp)));
  3112. exit:
  3113. /* Should never be null */
  3114. if (closedir(dirp) == -1) {
  3115. dentfree();
  3116. errexit();
  3117. }
  3118. return n;
  3119. }
  3120. /*
  3121. * Return the position of the matching entry or 0 otherwise
  3122. * Note there's no NULL check for fname
  3123. */
  3124. static int dentfind(const char *fname, int n)
  3125. {
  3126. int i = 0;
  3127. for (; i < n; ++i)
  3128. if (xstrcmp(fname, dents[i].name) == 0)
  3129. return i;
  3130. return 0;
  3131. }
  3132. static void populate(char *path, char *lastname)
  3133. {
  3134. #ifdef DBGMODE
  3135. struct timespec ts1, ts2;
  3136. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  3137. #endif
  3138. ndents = dentfill(path, &dents);
  3139. if (!ndents)
  3140. return;
  3141. qsort(dents, ndents, sizeof(*dents), entrycmp);
  3142. #ifdef DBGMODE
  3143. clock_gettime(CLOCK_REALTIME, &ts2);
  3144. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  3145. #endif
  3146. /* Find cur from history */
  3147. /* No NULL check for lastname, always points to an array */
  3148. if (!*lastname)
  3149. move_cursor(0, 0);
  3150. else
  3151. move_cursor(dentfind(lastname, ndents), 0);
  3152. }
  3153. static void move_cursor(int target, int ignore_scrolloff)
  3154. {
  3155. int delta, scrolloff, onscreen = xlines - 4;
  3156. target = MAX(0, MIN(ndents - 1, target));
  3157. delta = target - cur;
  3158. cur = target;
  3159. if (!ignore_scrolloff) {
  3160. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  3161. /*
  3162. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  3163. * margin area, but when ignore_scrolloff is 0, act like a boa
  3164. * constrictor and squeeze the cursor towards the middle region of the
  3165. * screen by allowing it to move inward and disallowing it to move
  3166. * outward (deeper into the scrolloff margin area).
  3167. */
  3168. if (((cur < (curscroll + scrolloff)) && delta < 0)
  3169. || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
  3170. curscroll += delta;
  3171. }
  3172. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  3173. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  3174. }
  3175. static void handle_screen_move(enum action sel)
  3176. {
  3177. int onscreen;
  3178. switch (sel) {
  3179. case SEL_NEXT:
  3180. if (ndents)
  3181. move_cursor((cur + 1) % ndents, 0);
  3182. break;
  3183. case SEL_PREV:
  3184. if (ndents)
  3185. move_cursor((cur + ndents - 1) % ndents, 0);
  3186. break;
  3187. case SEL_PGDN:
  3188. onscreen = xlines - 4;
  3189. move_cursor(curscroll + (onscreen - 1), 1);
  3190. curscroll += onscreen - 1;
  3191. break;
  3192. case SEL_CTRL_D:
  3193. onscreen = xlines - 4;
  3194. move_cursor(curscroll + (onscreen - 1), 1);
  3195. curscroll += onscreen >> 1;
  3196. break;
  3197. case SEL_PGUP: // fallthrough
  3198. onscreen = xlines - 4;
  3199. move_cursor(curscroll, 1);
  3200. curscroll -= onscreen - 1;
  3201. break;
  3202. case SEL_CTRL_U:
  3203. onscreen = xlines - 4;
  3204. move_cursor(curscroll, 1);
  3205. curscroll -= onscreen >> 1;
  3206. break;
  3207. case SEL_HOME:
  3208. move_cursor(0, 1);
  3209. break;
  3210. default: /* case SEL_END: */
  3211. move_cursor(ndents - 1, 1);
  3212. break;
  3213. }
  3214. }
  3215. static void redraw(char *path)
  3216. {
  3217. xlines = LINES;
  3218. xcols = COLS;
  3219. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  3220. int lastln = xlines - 1, onscreen = xlines - 4;
  3221. int i, attrs;
  3222. char buf[24];
  3223. char c;
  3224. char *ptr = path, *base;
  3225. /* Clear screen */
  3226. erase();
  3227. /* Enforce scroll/cursor invariants */
  3228. move_cursor(cur, 1);
  3229. /* Fail redraw if < than 10 columns, context info prints 10 chars */
  3230. if (ncols < MIN_DISPLAY_COLS) {
  3231. printmsg("too few columns!");
  3232. return;
  3233. }
  3234. DPRINTF_D(cur);
  3235. DPRINTF_S(path);
  3236. addch('[');
  3237. for (i = 0; i < CTX_MAX; ++i) {
  3238. if (!g_ctx[i].c_cfg.ctxactive) {
  3239. addch(i + '1');
  3240. addch(' ');
  3241. } else {
  3242. if (cfg.curctx != i)
  3243. /* Underline active contexts */
  3244. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE;
  3245. else
  3246. /* Print current context in reverse */
  3247. attrs = COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE;
  3248. attron(attrs);
  3249. addch(i + '1');
  3250. attroff(attrs);
  3251. addch(' ');
  3252. }
  3253. }
  3254. addstr("\b] "); /* 10 chars printed for contexts - "[1 2 3 4] " */
  3255. attron(A_UNDERLINE);
  3256. /* Print path */
  3257. i = (int)strlen(path);
  3258. if ((i + MIN_DISPLAY_COLS) <= ncols)
  3259. addnstr(path, ncols - MIN_DISPLAY_COLS);
  3260. else {
  3261. base = xbasename(path);
  3262. if ((base - ptr) <= 1)
  3263. addnstr(path, ncols - MIN_DISPLAY_COLS);
  3264. else {
  3265. i = 0;
  3266. --base;
  3267. while (ptr < base) {
  3268. if (*ptr == '/') {
  3269. i += 2; /* 2 characters added */
  3270. if (ncols < i + MIN_DISPLAY_COLS) {
  3271. base = NULL; /* Can't print more characters */
  3272. break;
  3273. }
  3274. addch(*ptr);
  3275. addch(*(++ptr));
  3276. }
  3277. ++ptr;
  3278. }
  3279. addnstr(base, ncols - (MIN_DISPLAY_COLS + i));
  3280. }
  3281. }
  3282. /* Go to first entry */
  3283. move(2, 0);
  3284. attroff(A_UNDERLINE);
  3285. /* Calculate the number of cols available to print entry name */
  3286. if (cfg.showdetail) {
  3287. /* Fallback to light mode if less than 35 columns */
  3288. if (ncols < 36) {
  3289. cfg.showdetail ^= 1;
  3290. printptr = &printent;
  3291. ncols -= 3; /* Preceding space, indicator, newline */
  3292. } else
  3293. ncols -= 35;
  3294. } else
  3295. ncols -= 3; /* Preceding space, indicator, newline */
  3296. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  3297. cfg.dircolor = 1;
  3298. /* Print listing */
  3299. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i)
  3300. printptr(&dents[i], i == cur, ncols);
  3301. /* Must reset e.g. no files in dir */
  3302. if (cfg.dircolor) {
  3303. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  3304. cfg.dircolor = 0;
  3305. }
  3306. if (ndents) {
  3307. char sort[] = "\0 ";
  3308. pEntry pent = &dents[cur];
  3309. if (cfg.mtimeorder)
  3310. sort[0] = cfg.mtime ? 'T' : 'A';
  3311. else if (cfg.sizeorder)
  3312. sort[0] = 'Z';
  3313. else if (cfg.extnorder)
  3314. sort[0] = 'E';
  3315. /* Get the file extension for regular files */
  3316. if (S_ISREG(pent->mode)) {
  3317. i = (int)strlen(pent->name);
  3318. ptr = xmemrchr((uchar *)pent->name, '.', i);
  3319. if (ptr)
  3320. attrs = ptr - pent->name; /* attrs used as tmp var */
  3321. if (!ptr || (i - attrs) > 5 || (i - attrs) < 2)
  3322. ptr = "\b";
  3323. } else
  3324. ptr = "\b";
  3325. if (cfg.blkorder) { /* du mode */
  3326. xstrlcpy(buf, coolsize(dir_blocks << blk_shift), 12);
  3327. c = cfg.apparentsz ? 'a' : 'd';
  3328. mvprintw(lastln, 0, "%d/%d [%d:%s] %cu:%s free:%s files:%lu %lldB %s",
  3329. cur + 1, ndents, cfg.selmode, (nselected ? xitoa(nselected) : ""),
  3330. c, buf, coolsize(get_fs_info(path, FREE)), num_files,
  3331. (ll)pent->blocks << blk_shift, ptr);
  3332. } else { /* light or detail mode */
  3333. /* Show filename as it may be truncated in directory listing */
  3334. /* Get the unescaped file name */
  3335. base = unescape(pent->name, NAME_MAX, NULL);
  3336. /* Timestamp */
  3337. strftime(buf, sizeof(buf), "%Y-%b-%d %R", localtime(&pent->t));
  3338. buf[sizeof(buf)-1] = '\0';
  3339. mvprintw(lastln, 0, "%d/%d [%d:%s] %s%s %s %s %s [%s]",
  3340. cur + 1, ndents, cfg.selmode, (nselected ? xitoa(nselected) : ""),
  3341. sort, buf, get_lsperms(pent->mode), coolsize(pent->size), ptr, base);
  3342. }
  3343. } else
  3344. printmsg("0/0");
  3345. }
  3346. static void browse(char *ipath, const char *session)
  3347. {
  3348. char newpath[PATH_MAX] __attribute__ ((aligned));
  3349. char mark[PATH_MAX] __attribute__ ((aligned));
  3350. char rundir[PATH_MAX] __attribute__ ((aligned));
  3351. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  3352. uchar opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOWAIT));
  3353. int r = -1, fd, presel, selstartid = 0, selendid = 0;
  3354. ino_t inode = 0;
  3355. enum action sel;
  3356. bool dir_changed = FALSE, rangesel = FALSE;
  3357. struct stat sb;
  3358. char *path, *lastdir, *lastname, *dir, *tmp;
  3359. MEVENT event;
  3360. struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
  3361. bool currentmouse = 1;
  3362. atexit(dentfree);
  3363. xlines = LINES;
  3364. xcols = COLS;
  3365. /* setup first context */
  3366. if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
  3367. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  3368. path = g_ctx[0].c_path;
  3369. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = '\0';
  3370. lastdir = g_ctx[0].c_last; /* last visited directory */
  3371. lastname = g_ctx[0].c_name; /* last visited filename */
  3372. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  3373. g_ctx[0].c_cfg = cfg; /* current configuration */
  3374. }
  3375. newpath[0] = rundir[0] = runfile[0] = mark[0] = '\0';
  3376. presel = cfg.filtermode ? FILTER : 0;
  3377. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  3378. if (!dents)
  3379. errexit();
  3380. /* Allocate buffer to hold names */
  3381. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  3382. if (!pnamebuf)
  3383. errexit();
  3384. begin:
  3385. #ifdef LINUX_INOTIFY
  3386. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  3387. inotify_rm_watch(inotify_fd, inotify_wd);
  3388. inotify_wd = -1;
  3389. dir_changed = FALSE;
  3390. }
  3391. #elif defined(BSD_KQUEUE)
  3392. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  3393. close(event_fd);
  3394. event_fd = -1;
  3395. dir_changed = FALSE;
  3396. }
  3397. #endif
  3398. /* Can fail when permissions change while browsing.
  3399. * It's assumed that path IS a directory when we are here.
  3400. */
  3401. if (access(path, R_OK) == -1)
  3402. printwarn(&presel);
  3403. populate(path, lastname);
  3404. if (interrupted) {
  3405. interrupted = FALSE;
  3406. cfg.apparentsz = 0;
  3407. cfg.blkorder = 0;
  3408. blk_shift = BLK_SHIFT_512;
  3409. presel = CONTROL('L');
  3410. }
  3411. #ifdef LINUX_INOTIFY
  3412. if (presel != FILTER && inotify_wd == -1)
  3413. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  3414. #elif defined(BSD_KQUEUE)
  3415. if (presel != FILTER && event_fd == -1) {
  3416. #if defined(O_EVTONLY)
  3417. event_fd = open(path, O_EVTONLY);
  3418. #else
  3419. event_fd = open(path, O_RDONLY);
  3420. #endif
  3421. if (event_fd >= 0)
  3422. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  3423. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  3424. }
  3425. #endif
  3426. while (1) {
  3427. redraw(path);
  3428. nochange:
  3429. /* Exit if parent has exited */
  3430. if (getppid() == 1)
  3431. _exit(0);
  3432. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  3433. if (access(path, F_OK)) {
  3434. DPRINTF_S("directory inaccessible");
  3435. find_accessible_parent(path, newpath, lastname, &presel);
  3436. setdirwatch();
  3437. goto begin;
  3438. }
  3439. /* If STDIN is no longer a tty (closed) we should exit */
  3440. if (!isatty(STDIN_FILENO) && !cfg.picker)
  3441. return;
  3442. sel = nextsel(presel);
  3443. if (presel)
  3444. presel = 0;
  3445. switch (sel) {
  3446. case SEL_CLICK:
  3447. if (getmouse(&event) != OK)
  3448. goto nochange; // fallthrough
  3449. case SEL_BACK:
  3450. /* Handle clicking on a context at the top */
  3451. if (sel == SEL_CLICK && event.bstate == BUTTON1_PRESSED && event.y == 0) {
  3452. /* Get context from: "[1 2 3 4]..." */
  3453. r = event.x >> 1;
  3454. /* If clicked after contexts, go to parent */
  3455. if (r >= CTX_MAX)
  3456. sel = SEL_BACK;
  3457. else if (r >= 0 && r < CTX_MAX && r != cfg.curctx) {
  3458. savecurctx(&cfg, path, dents[cur].name, r);
  3459. /* Reset the pointers */
  3460. path = g_ctx[r].c_path;
  3461. lastdir = g_ctx[r].c_last;
  3462. lastname = g_ctx[r].c_name;
  3463. setdirwatch();
  3464. goto begin;
  3465. }
  3466. }
  3467. if (sel == SEL_BACK) {
  3468. dir = visit_parent(path, newpath, &presel);
  3469. if (!dir)
  3470. goto nochange;
  3471. /* Save last working directory */
  3472. xstrlcpy(lastdir, path, PATH_MAX);
  3473. /* Save history */
  3474. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  3475. xstrlcpy(path, dir, PATH_MAX);
  3476. setdirwatch();
  3477. goto begin;
  3478. }
  3479. #if NCURSES_MOUSE_VERSION > 1
  3480. /* Scroll up */
  3481. if (event.bstate == BUTTON4_PRESSED && ndents) {
  3482. move_cursor((cur + ndents - 1) % ndents, 0);
  3483. break;
  3484. }
  3485. /* Scroll down */
  3486. if (event.bstate == BUTTON5_PRESSED && ndents) {
  3487. move_cursor((cur + 1) % ndents, 0);
  3488. break;
  3489. }
  3490. #endif
  3491. /* Toggle filter mode on left click on last 2 lines */
  3492. if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
  3493. cfg.filtermode ^= 1;
  3494. if (cfg.filtermode) {
  3495. presel = FILTER;
  3496. goto nochange;
  3497. }
  3498. /* Start watching the directory */
  3499. dir_changed = TRUE;
  3500. if (ndents)
  3501. copycurname();
  3502. goto begin;
  3503. }
  3504. /* Handle clicking on a file */
  3505. if (event.y >= 2 && event.y <= ndents + 1 && event.bstate == BUTTON1_PRESSED) {
  3506. r = curscroll + (event.y - 2);
  3507. move_cursor(r, 1);
  3508. currentmouse ^= 1;
  3509. clock_gettime(
  3510. #if defined(CLOCK_MONOTONIC_RAW)
  3511. CLOCK_MONOTONIC_RAW,
  3512. #elif defined(CLOCK_MONOTONIC)
  3513. CLOCK_MONOTONIC,
  3514. #else
  3515. CLOCK_REALTIME,
  3516. #endif
  3517. &mousetimings[currentmouse]);
  3518. /*Single click just selects, double click also opens */
  3519. if (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
  3520. + (mousetimings[0].tv_nsec - mousetimings[1].tv_nsec))
  3521. > DOUBLECLICK_INTERVAL_NS)
  3522. break;
  3523. mousetimings[currentmouse].tv_sec = 0;
  3524. } else {
  3525. if (cfg.filtermode)
  3526. presel = FILTER;
  3527. goto nochange; // fallthrough
  3528. }
  3529. case SEL_NAV_IN: // fallthrough
  3530. case SEL_GOIN:
  3531. /* Cannot descend in empty directories */
  3532. if (!ndents)
  3533. goto begin;
  3534. mkpath(path, dents[cur].name, newpath);
  3535. DPRINTF_S(newpath);
  3536. /* Cannot use stale data in entry, file may be missing by now */
  3537. if (stat(newpath, &sb) == -1) {
  3538. printwarn(&presel);
  3539. goto nochange;
  3540. }
  3541. DPRINTF_U(sb.st_mode);
  3542. switch (sb.st_mode & S_IFMT) {
  3543. case S_IFDIR:
  3544. if (access(newpath, R_OK) == -1) {
  3545. printwarn(&presel);
  3546. goto nochange;
  3547. }
  3548. /* Save last working directory */
  3549. xstrlcpy(lastdir, path, PATH_MAX);
  3550. xstrlcpy(path, newpath, PATH_MAX);
  3551. lastname[0] = '\0';
  3552. setdirwatch();
  3553. goto begin;
  3554. case S_IFREG:
  3555. {
  3556. /* If opened as vim plugin and Enter/^M pressed, pick */
  3557. if (cfg.picker && sel == SEL_GOIN) {
  3558. r = mkpath(path, dents[cur].name, newpath);
  3559. appendfpath(newpath, r);
  3560. writesel(pselbuf, selbufpos - 1);
  3561. return;
  3562. }
  3563. /* If open file is disabled on right arrow or `l`, return */
  3564. if (cfg.nonavopen && sel == SEL_NAV_IN)
  3565. continue;
  3566. /* Handle plugin selection mode */
  3567. if (cfg.runplugin) {
  3568. cfg.runplugin = 0;
  3569. /* Must be in plugin dir and same context to select plugin */
  3570. if ((cfg.runctx != cfg.curctx)
  3571. || (strcmp(path, plugindir) != 0))
  3572. ; /* We are somewhere else, continue as usual */
  3573. else {
  3574. /* Copy path so we can return back to earlier dir */
  3575. xstrlcpy(path, rundir, PATH_MAX);
  3576. rundir[0] = '\0';
  3577. if (!run_selected_plugin(&path, dents[cur].name,
  3578. newpath, runfile, &lastname,
  3579. &lastdir)) {
  3580. DPRINTF_S("plugin failed!");
  3581. }
  3582. if (runfile[0])
  3583. runfile[0] = '\0';
  3584. setdirwatch();
  3585. goto begin;
  3586. }
  3587. }
  3588. /* If NNN_USE_EDITOR is set, open text in EDITOR */
  3589. if (cfg.useeditor &&
  3590. #ifdef FILE_MIME_OPTS
  3591. get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, newpath, FALSE)
  3592. && !strncmp(g_buf, "text/", 5)) {
  3593. #else
  3594. /* no mime option; guess from description instead */
  3595. get_output(g_buf, CMD_LEN_MAX, "file", "-b", newpath, FALSE)
  3596. && strstr(g_buf, "text")) {
  3597. #endif
  3598. spawn(editor, newpath, NULL, path, F_CLI);
  3599. continue;
  3600. }
  3601. if (!sb.st_size) {
  3602. printwait("empty: use edit or open with", &presel);
  3603. goto nochange;
  3604. }
  3605. /* Invoke desktop opener as last resort */
  3606. spawn(opener, newpath, NULL, NULL, opener_flags);
  3607. continue;
  3608. }
  3609. default:
  3610. printwait("unsupported file", &presel);
  3611. goto nochange;
  3612. }
  3613. case SEL_NEXT: // fallthrough
  3614. case SEL_PREV: // fallthrough
  3615. case SEL_PGDN: // fallthrough
  3616. case SEL_CTRL_D: // fallthrough
  3617. case SEL_PGUP: // fallthrough
  3618. case SEL_CTRL_U: // fallthrough
  3619. case SEL_HOME: // fallthrough
  3620. case SEL_END:
  3621. handle_screen_move(sel);
  3622. break;
  3623. case SEL_CDHOME: // fallthrough
  3624. case SEL_CDBEGIN: // fallthrough
  3625. case SEL_CDLAST: // fallthrough
  3626. case SEL_CDROOT: // fallthrough
  3627. case SEL_VISIT:
  3628. switch (sel) {
  3629. case SEL_CDHOME:
  3630. dir = home;
  3631. break;
  3632. case SEL_CDBEGIN:
  3633. dir = ipath;
  3634. break;
  3635. case SEL_CDLAST:
  3636. dir = lastdir;
  3637. break;
  3638. case SEL_CDROOT:
  3639. dir = "/";
  3640. break;
  3641. default: /* case SEL_VISIT */
  3642. dir = mark;
  3643. break;
  3644. }
  3645. if (dir[0] == '\0') {
  3646. printwait("not set", &presel);
  3647. goto nochange;
  3648. }
  3649. if (!xdiraccess(dir)) {
  3650. presel = MSGWAIT;
  3651. goto nochange;
  3652. }
  3653. if (strcmp(path, dir) == 0)
  3654. goto nochange;
  3655. /* SEL_CDLAST: dir pointing to lastdir */
  3656. xstrlcpy(newpath, dir, PATH_MAX);
  3657. /* Save last working directory */
  3658. xstrlcpy(lastdir, path, PATH_MAX);
  3659. xstrlcpy(path, newpath, PATH_MAX);
  3660. lastname[0] = '\0';
  3661. DPRINTF_S(path);
  3662. setdirwatch();
  3663. goto begin;
  3664. case SEL_LEADER: // fallthrough
  3665. case SEL_CYCLE: // fallthrough
  3666. case SEL_CYCLER: // fallthrough
  3667. case SEL_FIRST: // fallthrough
  3668. case SEL_CTX1: // fallthrough
  3669. case SEL_CTX2: // fallthrough
  3670. case SEL_CTX3: // fallthrough
  3671. case SEL_CTX4:
  3672. switch (sel) {
  3673. case SEL_CYCLE:
  3674. fd = '\t';
  3675. break;
  3676. case SEL_CYCLER:
  3677. fd = KEY_BTAB;
  3678. break;
  3679. case SEL_FIRST:
  3680. fd = '\'';
  3681. break;
  3682. case SEL_CTX1: // fallthrough
  3683. case SEL_CTX2: // fallthrough
  3684. case SEL_CTX3: // fallthrough
  3685. case SEL_CTX4:
  3686. fd = sel - SEL_CTX1 + '1';
  3687. break;
  3688. default:
  3689. fd = get_input(NULL);
  3690. }
  3691. switch (fd) {
  3692. case '~': // fallthrough
  3693. case '`': // fallthrough
  3694. case '-': // fallthrough
  3695. case '@':
  3696. presel = fd;
  3697. goto nochange;
  3698. case '\'': /* jump to first file in the directory */
  3699. for (r = 0; r < ndents; ++r) {
  3700. if (!(dents[r].flags & DIR_OR_LINK_TO_DIR)) {
  3701. move_cursor((r) % ndents, 0);
  3702. break;
  3703. }
  3704. }
  3705. if (r != ndents)
  3706. continue;
  3707. goto nochange;
  3708. case '.':
  3709. cfg.showhidden ^= 1;
  3710. setdirwatch();
  3711. if (ndents)
  3712. copycurname();
  3713. goto begin;
  3714. case '\t': // fallthrough
  3715. case KEY_BTAB:
  3716. /* visit next and previous contexts */
  3717. r = cfg.curctx;
  3718. if (fd == '\t')
  3719. do
  3720. r = (r + 1) & ~CTX_MAX;
  3721. while (!g_ctx[r].c_cfg.ctxactive);
  3722. else
  3723. do
  3724. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3725. while (!g_ctx[r].c_cfg.ctxactive);
  3726. fd = '1' + r; // fallthrough
  3727. case '1': // fallthrough
  3728. case '2': // fallthrough
  3729. case '3': // fallthrough
  3730. case '4':
  3731. r = fd - '1'; /* Save the next context id */
  3732. if (cfg.curctx == r) {
  3733. if (sel != SEL_CYCLE)
  3734. continue;
  3735. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3736. snprintf(newpath, PATH_MAX,
  3737. "Create context %d? [Enter]", r + 1);
  3738. fd = get_input(newpath);
  3739. if (fd != '\r')
  3740. continue;
  3741. }
  3742. savecurctx(&cfg, path, dents[cur].name, r);
  3743. /* Reset the pointers */
  3744. path = g_ctx[r].c_path;
  3745. lastdir = g_ctx[r].c_last;
  3746. lastname = g_ctx[r].c_name;
  3747. setdirwatch();
  3748. goto begin;
  3749. }
  3750. if (!get_kv_val(bookmark, newpath, fd, BM_MAX, TRUE)) {
  3751. printwait(messages[STR_INVBM_KEY], &presel);
  3752. goto nochange;
  3753. }
  3754. if (!xdiraccess(newpath))
  3755. goto nochange;
  3756. if (strcmp(path, newpath) == 0)
  3757. break;
  3758. lastname[0] = '\0';
  3759. /* Save last working directory */
  3760. xstrlcpy(lastdir, path, PATH_MAX);
  3761. /* Save the newly opted dir in path */
  3762. xstrlcpy(path, newpath, PATH_MAX);
  3763. DPRINTF_S(path);
  3764. setdirwatch();
  3765. goto begin;
  3766. case SEL_PIN:
  3767. xstrlcpy(mark, path, PATH_MAX);
  3768. printwait(mark, &presel);
  3769. goto nochange;
  3770. case SEL_FLTR:
  3771. /* Unwatch dir if we are still in a filtered view */
  3772. #ifdef LINUX_INOTIFY
  3773. if (inotify_wd >= 0) {
  3774. inotify_rm_watch(inotify_fd, inotify_wd);
  3775. inotify_wd = -1;
  3776. }
  3777. #elif defined(BSD_KQUEUE)
  3778. if (event_fd >= 0) {
  3779. close(event_fd);
  3780. event_fd = -1;
  3781. }
  3782. #endif
  3783. presel = filterentries(path);
  3784. /* Save current */
  3785. if (ndents)
  3786. copycurname();
  3787. if (presel == 27) {
  3788. presel = 0;
  3789. break;
  3790. }
  3791. goto nochange;
  3792. case SEL_MFLTR: // fallthrough
  3793. case SEL_TOGGLEDOT: // fallthrough
  3794. case SEL_DETAIL: // fallthrough
  3795. case SEL_FSIZE: // fallthrough
  3796. case SEL_ASIZE: // fallthrough
  3797. case SEL_BSIZE: // fallthrough
  3798. case SEL_EXTN: // fallthrough
  3799. case SEL_MTIME:
  3800. switch (sel) {
  3801. case SEL_MFLTR:
  3802. cfg.filtermode ^= 1;
  3803. if (cfg.filtermode) {
  3804. presel = FILTER;
  3805. goto nochange;
  3806. }
  3807. /* Start watching the directory */
  3808. dir_changed = TRUE;
  3809. break;
  3810. case SEL_TOGGLEDOT:
  3811. cfg.showhidden ^= 1;
  3812. setdirwatch();
  3813. break;
  3814. case SEL_DETAIL:
  3815. cfg.showdetail ^= 1;
  3816. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  3817. cfg.blkorder = 0;
  3818. continue;
  3819. case SEL_FSIZE:
  3820. cfg.sizeorder ^= 1;
  3821. cfg.mtimeorder = 0;
  3822. cfg.apparentsz = 0;
  3823. cfg.blkorder = 0;
  3824. cfg.extnorder = 0;
  3825. cfg.selmode = 0;
  3826. break;
  3827. case SEL_ASIZE:
  3828. cfg.apparentsz ^= 1;
  3829. if (cfg.apparentsz) {
  3830. nftw_fn = &sum_sizes;
  3831. cfg.blkorder = 1;
  3832. blk_shift = 0;
  3833. } else
  3834. cfg.blkorder = 0; // fallthrough
  3835. case SEL_BSIZE:
  3836. if (sel == SEL_BSIZE) {
  3837. if (!cfg.apparentsz)
  3838. cfg.blkorder ^= 1;
  3839. nftw_fn = &sum_bsizes;
  3840. cfg.apparentsz = 0;
  3841. blk_shift = ffs(S_BLKSIZE) - 1;
  3842. }
  3843. if (cfg.blkorder) {
  3844. cfg.showdetail = 1;
  3845. printptr = &printent_long;
  3846. }
  3847. cfg.mtimeorder = 0;
  3848. cfg.sizeorder = 0;
  3849. cfg.extnorder = 0;
  3850. cfg.selmode = 0;
  3851. break;
  3852. case SEL_EXTN:
  3853. cfg.extnorder ^= 1;
  3854. cfg.sizeorder = 0;
  3855. cfg.mtimeorder = 0;
  3856. cfg.apparentsz = 0;
  3857. cfg.blkorder = 0;
  3858. cfg.selmode = 0;
  3859. break;
  3860. default: /* SEL_MTIME */
  3861. cfg.mtimeorder ^= 1;
  3862. cfg.sizeorder = 0;
  3863. cfg.apparentsz = 0;
  3864. cfg.blkorder = 0;
  3865. cfg.extnorder = 0;
  3866. cfg.selmode = 0;
  3867. break;
  3868. }
  3869. /* Save current */
  3870. if (ndents)
  3871. copycurname();
  3872. goto begin;
  3873. case SEL_STATS:
  3874. if (ndents) {
  3875. mkpath(path, dents[cur].name, newpath);
  3876. if (lstat(newpath, &sb) == -1 || !show_stats(newpath, &sb)) {
  3877. printwarn(&presel);
  3878. goto nochange;
  3879. }
  3880. }
  3881. break;
  3882. case SEL_ARCHIVELS: // fallthrough
  3883. case SEL_EXTRACT: // fallthrough
  3884. case SEL_REDRAW: // fallthrough
  3885. case SEL_RENAMEMUL: // fallthrough
  3886. case SEL_HELP: // fallthrough
  3887. case SEL_RUNEDIT: // fallthrough
  3888. case SEL_RUNPAGE: // fallthrough
  3889. case SEL_LOCK:
  3890. {
  3891. bool refresh = FALSE;
  3892. if (ndents)
  3893. mkpath(path, dents[cur].name, newpath);
  3894. else if (sel == SEL_ARCHIVELS || sel == SEL_EXTRACT
  3895. || sel == SEL_RUNEDIT || sel == SEL_RUNPAGE)
  3896. break;
  3897. switch (sel) {
  3898. case SEL_ARCHIVELS:
  3899. handle_archive(newpath, path, 'l');
  3900. refresh = TRUE;
  3901. break;
  3902. case SEL_EXTRACT:
  3903. handle_archive(newpath, path, 'x');
  3904. refresh = TRUE;
  3905. break;
  3906. case SEL_REDRAW:
  3907. refresh = TRUE;
  3908. break;
  3909. case SEL_RENAMEMUL:
  3910. endselection();
  3911. if (!batch_rename(path)) {
  3912. printwait(messages[OPERATION_FAILED], &presel);
  3913. goto nochange;
  3914. }
  3915. refresh = TRUE;
  3916. break;
  3917. case SEL_HELP:
  3918. show_help(path);
  3919. continue;
  3920. case SEL_RUNEDIT:
  3921. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  3922. continue;
  3923. case SEL_RUNPAGE:
  3924. spawn(pager, dents[cur].name, NULL, path, F_CLI);
  3925. continue;
  3926. default: /* SEL_LOCK */
  3927. lock_terminal();
  3928. break;
  3929. }
  3930. /* In case of successful operation, reload contents */
  3931. /* Continue in navigate-as-you-type mode, if enabled */
  3932. if (cfg.filtermode && !refresh)
  3933. break;
  3934. /* Save current */
  3935. if (ndents)
  3936. copycurname();
  3937. /* Repopulate as directory content may have changed */
  3938. goto begin;
  3939. }
  3940. case SEL_SEL:
  3941. if (!ndents)
  3942. goto nochange;
  3943. startselection();
  3944. if (rangesel)
  3945. rangesel = FALSE;
  3946. /* Do not select if already selected */
  3947. if (!(dents[cur].flags & FILE_SELECTED)) {
  3948. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  3949. ++nselected;
  3950. dents[cur].flags |= FILE_SELECTED;
  3951. }
  3952. /* move cursor to the next entry if this is not the last entry */
  3953. if (!cfg.picker && cur != ndents - 1)
  3954. move_cursor((cur + 1) % ndents, 0);
  3955. break;
  3956. case SEL_SELMUL:
  3957. if (!ndents)
  3958. goto nochange;
  3959. startselection();
  3960. rangesel ^= TRUE;
  3961. if (stat(path, &sb) == -1) {
  3962. printwarn(&presel);
  3963. goto nochange;
  3964. }
  3965. if (rangesel) { /* Range selection started */
  3966. inode = sb.st_ino;
  3967. selstartid = cur;
  3968. printmsg("range selection on");
  3969. xdelay();
  3970. continue;
  3971. }
  3972. #ifndef DIR_LIMITED_SELECTION
  3973. if (inode != sb.st_ino) {
  3974. printwait("dir changed, range selection off", &presel);
  3975. goto nochange;
  3976. }
  3977. #endif
  3978. if (cur < selstartid) {
  3979. selendid = selstartid;
  3980. selstartid = cur;
  3981. } else
  3982. selendid = cur;
  3983. /* Clear selection on repeat on same file */
  3984. if (selstartid == selendid) {
  3985. resetselind();
  3986. clearselection();
  3987. break;
  3988. } // fallthrough
  3989. case SEL_SELALL:
  3990. if (sel == SEL_SELALL) {
  3991. if (!ndents)
  3992. goto nochange;
  3993. startselection();
  3994. if (rangesel)
  3995. rangesel = FALSE;
  3996. selstartid = 0;
  3997. selendid = ndents - 1;
  3998. }
  3999. for (r = selstartid; r <= selendid; ++r)
  4000. if (!(dents[r].flags & FILE_SELECTED)) {
  4001. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  4002. dents[r].flags |= FILE_SELECTED;
  4003. ++nselected;
  4004. }
  4005. /* Show the range count */
  4006. //r = selendid - selstartid + 1;
  4007. //mvprintw(xlines - 1, 0, "+%d\n", r);
  4008. //xdelay();
  4009. //writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4010. //spawn(copier, NULL, NULL, NULL, F_NOTRACE);
  4011. continue;
  4012. case SEL_SELLST:
  4013. if (listselbuf() || listselfile()) {
  4014. if (cfg.filtermode)
  4015. presel = FILTER;
  4016. break;
  4017. }
  4018. printwait(messages[NONE_SELECTED], &presel);
  4019. goto nochange;
  4020. case SEL_SELEDIT:
  4021. if (!editselection()) {
  4022. printwait(messages[OPERATION_FAILED], &presel);
  4023. goto nochange;
  4024. }
  4025. break;
  4026. case SEL_CP: // fallthrough
  4027. case SEL_MV: // fallthrough
  4028. case SEL_CPMVAS: // fallthrough
  4029. case SEL_RMMUL:
  4030. {
  4031. if (!cpmvrm_selection(sel, path, &presel))
  4032. goto nochange;
  4033. if (ndents)
  4034. copycurname();
  4035. goto begin;
  4036. }
  4037. case SEL_RM:
  4038. {
  4039. if (!ndents)
  4040. break;
  4041. mkpath(path, dents[cur].name, newpath);
  4042. xrm(newpath);
  4043. /* Don't optimize cur if filtering is on */
  4044. if (cur && access(newpath, F_OK) == -1)
  4045. move_cursor(cur - 1, 0);
  4046. /* We reduce cur only if it is > 0, so it's at least 0 */
  4047. copycurname();
  4048. goto begin;
  4049. }
  4050. case SEL_ARCHIVE: // fallthrough
  4051. case SEL_OPENWITH: // fallthrough
  4052. case SEL_NEW: // fallthrough
  4053. case SEL_RENAME:
  4054. {
  4055. int dup = 'n';
  4056. if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
  4057. break;
  4058. switch (sel) {
  4059. case SEL_ARCHIVE:
  4060. r = get_input("archive selection (else current)? [y/Y confirms]");
  4061. if (r == 'y' || r == 'Y') {
  4062. endselection();
  4063. if (!selsafe()) {
  4064. presel = MSGWAIT;
  4065. goto nochange;
  4066. }
  4067. tmp = NULL;
  4068. } else if (!ndents) {
  4069. printwait("no files", &presel);
  4070. goto nochange;
  4071. } else
  4072. tmp = dents[cur].name;
  4073. tmp = xreadline(tmp, "archive name: ");
  4074. break;
  4075. case SEL_OPENWITH:
  4076. #ifdef NORL
  4077. tmp = xreadline(NULL, "open with: ");
  4078. #else
  4079. presel = 0;
  4080. tmp = getreadline("open with: ", path, ipath, &presel);
  4081. if (presel == MSGWAIT)
  4082. goto nochange;
  4083. #endif
  4084. break;
  4085. case SEL_NEW:
  4086. r = get_input("create 'f'(ile) / 'd'(ir) / 's'(ym) / 'h'(ard)?");
  4087. if (r == 'f' || r == 'd')
  4088. tmp = xreadline(NULL, "relative path: ");
  4089. else if (r == 's' || r == 'h')
  4090. tmp = xreadline(NULL, "link suffix [@ for none]: ");
  4091. else
  4092. tmp = NULL;
  4093. break;
  4094. default: /* SEL_RENAME */
  4095. tmp = xreadline(dents[cur].name, "");
  4096. break;
  4097. }
  4098. if (!tmp || !*tmp)
  4099. break;
  4100. /* Allow only relative, same dir paths */
  4101. if (tmp[0] == '/'
  4102. || ((r != 'f' && r != 'd') && (xstrcmp(xbasename(tmp), tmp) != 0))) {
  4103. printwait(messages[STR_INPUT_ID], &presel);
  4104. goto nochange;
  4105. }
  4106. /* Confirm if app is CLI or GUI */
  4107. if (sel == SEL_OPENWITH) {
  4108. r = get_input("cli mode? [y/Y confirms]");
  4109. (r == 'y' || r == 'Y') ? (r = F_CLI)
  4110. : (r = F_NOWAIT | F_NOTRACE | F_MULTI);
  4111. }
  4112. switch (sel) {
  4113. case SEL_ARCHIVE:
  4114. {
  4115. char cmd[ARCHIVE_CMD_LEN];
  4116. get_archive_cmd(cmd, tmp);
  4117. (r == 'y' || r == 'Y') ? archive_selection(cmd, tmp, path)
  4118. : spawn(cmd, tmp, dents[cur].name,
  4119. path, F_NORMAL | F_MULTI);
  4120. break;
  4121. }
  4122. case SEL_OPENWITH:
  4123. mkpath(path, dents[cur].name, newpath);
  4124. spawn(tmp, newpath, NULL, path, r);
  4125. break;
  4126. case SEL_RENAME:
  4127. /* Skip renaming to same name */
  4128. if (strcmp(tmp, dents[cur].name) == 0) {
  4129. tmp = xreadline(dents[cur].name, "copy name: ");
  4130. if (strcmp(tmp, dents[cur].name) == 0)
  4131. goto nochange;
  4132. dup = 'd';
  4133. }
  4134. break;
  4135. default:
  4136. break;
  4137. }
  4138. /* Complete OPEN, LAUNCH, ARCHIVE operations */
  4139. if (sel != SEL_NEW && sel != SEL_RENAME) {
  4140. /* Continue in navigate-as-you-type mode, if enabled */
  4141. if (cfg.filtermode)
  4142. presel = FILTER;
  4143. /* Save current */
  4144. copycurname();
  4145. /* Repopulate as directory content may have changed */
  4146. goto begin;
  4147. }
  4148. /* Open the descriptor to currently open directory */
  4149. #ifdef O_DIRECTORY
  4150. fd = open(path, O_RDONLY | O_DIRECTORY);
  4151. #else
  4152. fd = open(path, O_RDONLY);
  4153. #endif
  4154. if (fd == -1) {
  4155. printwarn(&presel);
  4156. goto nochange;
  4157. }
  4158. /* Check if another file with same name exists */
  4159. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  4160. if (sel == SEL_RENAME) {
  4161. /* Overwrite file with same name? */
  4162. r = get_input("overwrite? [y/Y confirms]");
  4163. if (r != 'y' && r != 'Y') {
  4164. close(fd);
  4165. break;
  4166. }
  4167. } else {
  4168. /* Do nothing in case of NEW */
  4169. close(fd);
  4170. printwait("entry exists", &presel);
  4171. goto nochange;
  4172. }
  4173. }
  4174. if (sel == SEL_RENAME) {
  4175. /* Rename the file */
  4176. if (dup == 'd')
  4177. spawn("cp -rp", dents[cur].name, tmp, path, F_SILENT);
  4178. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  4179. close(fd);
  4180. printwarn(&presel);
  4181. goto nochange;
  4182. }
  4183. } else {
  4184. /* Check if it's a dir or file */
  4185. if (r == 'f') {
  4186. mkpath(path, tmp, newpath);
  4187. r = xmktree(newpath, FALSE);
  4188. } else if (r == 'd') {
  4189. mkpath(path, tmp, newpath);
  4190. r = xmktree(newpath, TRUE);
  4191. } else if (r == 's' || r == 'h') {
  4192. if (tmp[0] == '@' && tmp[1] == '\0')
  4193. tmp[0] = '\0';
  4194. r = xlink(tmp, path, newpath, &presel, r);
  4195. close(fd);
  4196. if (r <= 0)
  4197. goto nochange;
  4198. if (cfg.filtermode)
  4199. presel = FILTER;
  4200. if (ndents)
  4201. copycurname();
  4202. goto begin;
  4203. } else {
  4204. close(fd);
  4205. break;
  4206. }
  4207. /* Check if file creation failed */
  4208. if (r == -1) {
  4209. printwarn(&presel);
  4210. close(fd);
  4211. goto nochange;
  4212. }
  4213. }
  4214. close(fd);
  4215. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  4216. goto begin;
  4217. }
  4218. case SEL_EXEC: // fallthrough
  4219. case SEL_SHELL: // fallthrough
  4220. case SEL_PLUGKEY: // fallthrough
  4221. case SEL_PLUGIN: // fallthrough
  4222. case SEL_LAUNCH: // fallthrough
  4223. case SEL_RUNCMD:
  4224. endselection();
  4225. switch (sel) {
  4226. case SEL_EXEC:
  4227. if (!execute_file(cur, path, newpath, &presel))
  4228. goto nochange;
  4229. break;
  4230. case SEL_SHELL:
  4231. setenv(envs[NCUR], (ndents ? dents[cur].name : ""), 1);
  4232. spawn(shell, NULL, NULL, path, F_CLI);
  4233. break;
  4234. case SEL_PLUGKEY: // fallthrough
  4235. case SEL_PLUGIN:
  4236. /* Check if directory is accessible */
  4237. if (!xdiraccess(plugindir)) {
  4238. printwarn(&presel);
  4239. goto nochange;
  4240. }
  4241. if (sel == SEL_PLUGKEY) {
  4242. r = get_input("");
  4243. tmp = get_kv_val(plug, NULL, r, PLUGIN_MAX, FALSE);
  4244. if (!tmp)
  4245. goto nochange;
  4246. if (tmp[0] == '_' && tmp[1]) {
  4247. xstrlcpy(newpath, ++tmp, PATH_MAX);
  4248. if (is_suffix(newpath, " $NNN")) {
  4249. tmp = (ndents ? dents[cur].name : NULL);
  4250. /* Set `\0` to clear ' $NNN' suffix */
  4251. newpath[strlen(newpath) - 5] = '\0';
  4252. } else
  4253. tmp = NULL;
  4254. spawn(newpath, tmp, NULL, path, F_CLI | F_CONFIRM);
  4255. } else {
  4256. if (!run_selected_plugin(&path, tmp, newpath,
  4257. (ndents ? dents[cur].name : NULL),
  4258. &lastname, &lastdir)) {
  4259. printwait(messages[OPERATION_FAILED],
  4260. &presel);
  4261. goto nochange;
  4262. }
  4263. }
  4264. if (ndents)
  4265. copycurname();
  4266. } else {
  4267. cfg.runplugin ^= 1;
  4268. if (!cfg.runplugin && rundir[0]) {
  4269. /*
  4270. * If toggled, and still in the plugin dir,
  4271. * switch to original directory
  4272. */
  4273. if (strcmp(path, plugindir) == 0) {
  4274. xstrlcpy(path, rundir, PATH_MAX);
  4275. xstrlcpy(lastname, runfile, NAME_MAX);
  4276. rundir[0] = runfile[0] = '\0';
  4277. setdirwatch();
  4278. goto begin;
  4279. }
  4280. break;
  4281. }
  4282. xstrlcpy(rundir, path, PATH_MAX);
  4283. xstrlcpy(path, plugindir, PATH_MAX);
  4284. if (ndents)
  4285. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  4286. cfg.runctx = cfg.curctx;
  4287. lastname[0] = '\0';
  4288. }
  4289. setdirwatch();
  4290. goto begin;
  4291. case SEL_LAUNCH:
  4292. if (getutil(utils[NLAUNCH])) {
  4293. spawn(utils[NLAUNCH], "0", NULL, path, F_NORMAL);
  4294. break;
  4295. } // fallthrough
  4296. default: /* SEL_RUNCMD */
  4297. #ifndef NORL
  4298. if (cfg.picker) {
  4299. #endif
  4300. tmp = xreadline(NULL, "> ");
  4301. #ifndef NORL
  4302. } else {
  4303. presel = 0;
  4304. tmp = getreadline("> ", path, ipath, &presel);
  4305. if (presel == MSGWAIT)
  4306. goto nochange;
  4307. }
  4308. #endif
  4309. if (tmp && tmp[0]) // NOLINT
  4310. prompt_run(tmp, (ndents ? dents[cur].name : ""), path);
  4311. }
  4312. /* Continue in navigate-as-you-type mode, if enabled */
  4313. if (cfg.filtermode)
  4314. presel = FILTER;
  4315. /* Save current */
  4316. if (ndents)
  4317. copycurname();
  4318. /* Repopulate as directory content may have changed */
  4319. goto begin;
  4320. case SEL_ARCHIVEMNT:
  4321. if (!ndents || !archive_mount(dents[cur].name, path, newpath, &presel))
  4322. goto nochange; // fallthrough
  4323. case SEL_SSHFS:
  4324. if (sel == SEL_SSHFS && !sshfs_mount(newpath, &presel))
  4325. goto nochange;
  4326. lastname[0] = '\0';
  4327. /* Save last working directory */
  4328. xstrlcpy(lastdir, path, PATH_MAX);
  4329. /* Switch to mount point */
  4330. xstrlcpy(path, newpath, PATH_MAX);
  4331. setdirwatch();
  4332. goto begin;
  4333. case SEL_UMOUNT:
  4334. tmp = ndents ? dents[cur].name : NULL;
  4335. unmount(tmp, newpath, &presel, path);
  4336. goto nochange;
  4337. case SEL_SESSIONS:
  4338. r = get_input("'s'(ave) / 'l'(oad) / 'r'(estore) session?");
  4339. if (r == 's') {
  4340. save_session(FALSE, &presel);
  4341. goto nochange;
  4342. }
  4343. if (r == 'l' || r == 'r') {
  4344. if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
  4345. setdirwatch();
  4346. goto begin;
  4347. }
  4348. presel = MSGWAIT;
  4349. goto nochange;
  4350. }
  4351. break;
  4352. case SEL_QUITCTX: // fallthrough
  4353. case SEL_QUITCD: // fallthrough
  4354. case SEL_QUIT:
  4355. if (sel == SEL_QUITCTX) {
  4356. fd = cfg.curctx; /* fd used as tmp var */
  4357. for (r = (fd + 1) & ~CTX_MAX;
  4358. (r != fd) && !g_ctx[r].c_cfg.ctxactive;
  4359. r = ((r + 1) & ~CTX_MAX)) {
  4360. };
  4361. if (r != fd) {
  4362. bool selmode = cfg.selmode ? TRUE : FALSE;
  4363. g_ctx[fd].c_cfg.ctxactive = 0;
  4364. /* Switch to next active context */
  4365. path = g_ctx[r].c_path;
  4366. lastdir = g_ctx[r].c_last;
  4367. lastname = g_ctx[r].c_name;
  4368. /* Switch light/detail mode */
  4369. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  4370. /* Set the reverse */
  4371. printptr = cfg.showdetail ?
  4372. &printent : &printent_long;
  4373. cfg = g_ctx[r].c_cfg;
  4374. /* Continue selection mode */
  4375. cfg.selmode = selmode;
  4376. cfg.curctx = r;
  4377. setdirwatch();
  4378. goto begin;
  4379. }
  4380. } else {
  4381. for (r = 0; r < CTX_MAX; ++r)
  4382. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  4383. r = get_input("Quit all contexts? [Enter]");
  4384. break;
  4385. }
  4386. if (!(r == CTX_MAX || r == '\r'))
  4387. break; // fallthrough
  4388. }
  4389. if (sel == SEL_QUITCD || getenv("NNN_TMPFILE")) {
  4390. /* In vim picker mode, clear selection and exit */
  4391. if (cfg.picker) {
  4392. /* Picker mode: reset buffer or clear file */
  4393. selbufpos = 0;
  4394. } else if (!write_lastdir(path)) {
  4395. presel = MSGWAIT;
  4396. goto nochange;
  4397. }
  4398. }
  4399. return;
  4400. default:
  4401. if (xlines != LINES || xcols != COLS) {
  4402. idle = 0;
  4403. setdirwatch();
  4404. if (ndents)
  4405. copycurname();
  4406. goto begin;
  4407. }
  4408. /* Locker */
  4409. if (idletimeout && idle == idletimeout) {
  4410. idle = 0;
  4411. lock_terminal();
  4412. if (ndents)
  4413. copycurname();
  4414. goto begin;
  4415. }
  4416. goto nochange;
  4417. } /* switch (sel) */
  4418. }
  4419. }
  4420. static void check_key_collision(void)
  4421. {
  4422. int key;
  4423. ulong i = 0;
  4424. bool bitmap[KEY_MAX] = {FALSE};
  4425. for (; i < sizeof(bindings) / sizeof(struct key); ++i) {
  4426. key = bindings[i].sym;
  4427. if (bitmap[key])
  4428. fprintf(stdout, "collision detected: key [%s]\n", keyname(key));
  4429. else
  4430. bitmap[key] = TRUE;
  4431. }
  4432. }
  4433. static void usage(void)
  4434. {
  4435. fprintf(stdout,
  4436. "%s: nnn [OPTIONS] [PATH]\n\n"
  4437. "The missing terminal file manager for X.\n\n"
  4438. "positional args:\n"
  4439. " PATH start dir [default: .]\n\n"
  4440. "optional args:\n"
  4441. " -a use access time\n"
  4442. " -b key open bookmark key\n"
  4443. " -c cli-only opener\n"
  4444. " -d detail mode\n"
  4445. " -e name load session by name\n"
  4446. " -f run filter as cmd on prompt key\n"
  4447. " -H show hidden files\n"
  4448. " -i nav-as-you-type mode\n"
  4449. " -K detect key collision\n"
  4450. " -n version sort\n"
  4451. " -o open files on Enter\n"
  4452. " -p file selection file [stdout if '-']\n"
  4453. " -r use advcpmv patched cp, mv\n"
  4454. " -s string filters [default: regex]\n"
  4455. " -S du mode\n"
  4456. " -t disable dir auto-select\n"
  4457. " -v show version\n"
  4458. " -h show help\n\n"
  4459. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  4460. }
  4461. static bool setup_config(void)
  4462. {
  4463. size_t r, len;
  4464. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  4465. bool xdg = FALSE;
  4466. /* Set up configuration file paths */
  4467. if (xdgcfg && xdgcfg[0]) {
  4468. DPRINTF_S(xdgcfg);
  4469. if (xdgcfg[0] == '~') {
  4470. r = xstrlcpy(g_buf, home, PATH_MAX);
  4471. xstrlcpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  4472. xdgcfg = g_buf;
  4473. DPRINTF_S(xdgcfg);
  4474. }
  4475. if (!xdiraccess(xdgcfg)) {
  4476. xerror();
  4477. return FALSE;
  4478. }
  4479. len = strlen(xdgcfg) + 1 + 13; /* add length of "/nnn/sessions" */
  4480. xdg = TRUE;
  4481. }
  4482. if (!xdg)
  4483. len = strlen(home) + 1 + 21; /* add length of "/.config/nnn/sessions" */
  4484. cfgdir = (char *)malloc(len);
  4485. plugindir = (char *)malloc(len);
  4486. sessiondir = (char *)malloc(len);
  4487. if (!cfgdir || !plugindir || !sessiondir) {
  4488. xerror();
  4489. return FALSE;
  4490. }
  4491. if (xdg) {
  4492. xstrlcpy(cfgdir, xdgcfg, len);
  4493. r = len - 13; /* subtract length of "/nnn/sessions" */
  4494. } else {
  4495. r = xstrlcpy(cfgdir, home, len);
  4496. /* Create ~/.config */
  4497. xstrlcpy(cfgdir + r - 1, "/.config", len - r);
  4498. DPRINTF_S(cfgdir);
  4499. r += 8; /* length of "/.config" */
  4500. }
  4501. /* Create ~/.config/nnn */
  4502. xstrlcpy(cfgdir + r - 1, "/nnn", len - r);
  4503. DPRINTF_S(cfgdir);
  4504. /* Create ~/.config/nnn/plugins */
  4505. xstrlcpy(cfgdir + r + 4 - 1, "/plugins", 9); /* subtract length of "/nnn" (4) */
  4506. DPRINTF_S(cfgdir);
  4507. xstrlcpy(plugindir, cfgdir, len);
  4508. DPRINTF_S(plugindir);
  4509. if (!xmktree(cfgdir, TRUE)) {
  4510. xerror();
  4511. return FALSE;
  4512. }
  4513. /* Create ~/.config/nnn/sessions */
  4514. xstrlcpy(cfgdir + r + 4 - 1, "/sessions", 10); /* subtract length of "/nnn" (4) */
  4515. DPRINTF_S(cfgdir);
  4516. xstrlcpy(sessiondir, cfgdir, len);
  4517. DPRINTF_S(sessiondir);
  4518. if (!xmktree(cfgdir, TRUE)) {
  4519. xerror();
  4520. return FALSE;
  4521. }
  4522. /* Reset to config path */
  4523. cfgdir[r + 3] = '\0';
  4524. DPRINTF_S(cfgdir);
  4525. /* Set selection file path */
  4526. if (!cfg.picker) {
  4527. /* Length of "/.config/nnn/.selection" */
  4528. g_selpath = (char *)malloc(len + 3);
  4529. r = xstrlcpy(g_selpath, cfgdir, len + 3);
  4530. xstrlcpy(g_selpath + r - 1, "/.selection", 12);
  4531. DPRINTF_S(g_selpath);
  4532. }
  4533. return TRUE;
  4534. }
  4535. static bool set_tmp_path(void)
  4536. {
  4537. char *path;
  4538. if (xdiraccess("/tmp"))
  4539. g_tmpfplen = (uchar)xstrlcpy(g_tmpfpath, "/tmp", TMP_LEN_MAX);
  4540. else {
  4541. path = getenv("TMPDIR");
  4542. if (path)
  4543. g_tmpfplen = (uchar)xstrlcpy(g_tmpfpath, path, TMP_LEN_MAX);
  4544. else {
  4545. fprintf(stderr, "set TMPDIR\n");
  4546. return FALSE;
  4547. }
  4548. }
  4549. return TRUE;
  4550. }
  4551. static void cleanup(void)
  4552. {
  4553. free(g_selpath);
  4554. free(plugindir);
  4555. free(sessiondir);
  4556. free(cfgdir);
  4557. free(initpath);
  4558. free(bmstr);
  4559. free(pluginstr);
  4560. unlink(g_pipepath);
  4561. #ifdef DBGMODE
  4562. disabledbg();
  4563. #endif
  4564. }
  4565. int main(int argc, char *argv[])
  4566. {
  4567. mmask_t mask;
  4568. char *arg = NULL;
  4569. char *session = NULL;
  4570. int opt;
  4571. #ifdef __linux__
  4572. bool progress = FALSE;
  4573. #endif
  4574. while ((opt = getopt(argc, argv, "HSKiab:cde:fnop:rstvh")) != -1) {
  4575. switch (opt) {
  4576. case 'S':
  4577. cfg.blkorder = 1;
  4578. nftw_fn = sum_bsizes;
  4579. blk_shift = ffs(S_BLKSIZE) - 1; // fallthrough
  4580. case 'd':
  4581. cfg.showdetail = 1;
  4582. printptr = &printent_long;
  4583. break;
  4584. case 'i':
  4585. cfg.filtermode = 1;
  4586. break;
  4587. case 'a':
  4588. cfg.mtime = 0;
  4589. break;
  4590. case 'b':
  4591. arg = optarg;
  4592. break;
  4593. case 'c':
  4594. cfg.cliopener = 1;
  4595. break;
  4596. case 'e':
  4597. session = optarg;
  4598. break;
  4599. case 'f':
  4600. cfg.filtercmd = 1;
  4601. break;
  4602. case 'H':
  4603. cfg.showhidden = 1;
  4604. break;
  4605. case 'n':
  4606. cmpfn = &xstrverscasecmp;
  4607. break;
  4608. case 'o':
  4609. cfg.nonavopen = 1;
  4610. break;
  4611. case 'p':
  4612. cfg.picker = 1;
  4613. if (optarg[0] == '-' && optarg[1] == '\0')
  4614. cfg.pickraw = 1;
  4615. else {
  4616. int fd = open(optarg, O_WRONLY | O_CREAT, 0600);
  4617. if (fd == -1) {
  4618. xerror();
  4619. return _FAILURE;
  4620. }
  4621. close(fd);
  4622. g_selpath = realpath(optarg, NULL);
  4623. unlink(g_selpath);
  4624. }
  4625. break;
  4626. case 'r':
  4627. #ifdef __linux__
  4628. progress = TRUE;
  4629. #endif
  4630. break;
  4631. case 's':
  4632. cfg.filter_re = 0;
  4633. filterfn = &visible_str;
  4634. break;
  4635. case 't':
  4636. cfg.autoselect = 0;
  4637. break;
  4638. case 'K':
  4639. check_key_collision();
  4640. return _SUCCESS;
  4641. case 'v':
  4642. fprintf(stdout, "%s\n", VERSION);
  4643. return _SUCCESS;
  4644. case 'h':
  4645. usage();
  4646. return _SUCCESS;
  4647. default:
  4648. usage();
  4649. return _FAILURE;
  4650. }
  4651. }
  4652. /* Confirm we are in a terminal */
  4653. if (!cfg.picker && !(isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)))
  4654. exit(1);
  4655. /* Get the context colors; copier used as tmp var */
  4656. copier = xgetenv(env_cfg[NNN_CONTEXT_COLORS], "4444");
  4657. opt = 0;
  4658. while (opt < CTX_MAX) {
  4659. if (*copier) {
  4660. if (*copier < '0' || *copier > '7') {
  4661. fprintf(stderr, "0 <= code <= 7\n");
  4662. return _FAILURE;
  4663. }
  4664. g_ctx[opt].color = *copier - '0';
  4665. ++copier;
  4666. } else
  4667. g_ctx[opt].color = 4;
  4668. ++opt;
  4669. }
  4670. #ifdef DBGMODE
  4671. enabledbg();
  4672. DPRINTF_S(VERSION);
  4673. #endif
  4674. atexit(cleanup);
  4675. home = getenv("HOME");
  4676. if (!home) {
  4677. fprintf(stderr, "set HOME\n");
  4678. return _FAILURE;
  4679. }
  4680. DPRINTF_S(home);
  4681. if (!setup_config())
  4682. return _FAILURE;
  4683. /* Get custom opener, if set */
  4684. opener = xgetenv(env_cfg[NNN_OPENER], utils[OPENER]);
  4685. DPRINTF_S(opener);
  4686. /* Parse bookmarks string */
  4687. if (!parsekvpair(bookmark, &bmstr, env_cfg[NNN_BMS], BM_MAX)) {
  4688. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  4689. return _FAILURE;
  4690. }
  4691. /* Parse plugins string */
  4692. if (!parsekvpair(plug, &pluginstr, "NNN_PLUG", PLUGIN_MAX)) {
  4693. fprintf(stderr, "%s\n", "NNN_PLUG");
  4694. return _FAILURE;
  4695. }
  4696. if (arg) { /* Open a bookmark directly */
  4697. if (!arg[1]) /* Bookmarks keys are single char */
  4698. initpath = get_kv_val(bookmark, NULL, *arg, BM_MAX, TRUE);
  4699. if (!initpath) {
  4700. fprintf(stderr, "%s\n", messages[STR_INVBM_KEY]);
  4701. return _FAILURE;
  4702. }
  4703. } else if (argc == optind) {
  4704. /* Start in the current directory */
  4705. initpath = getcwd(NULL, PATH_MAX);
  4706. if (!initpath)
  4707. initpath = "/";
  4708. } else {
  4709. arg = argv[optind];
  4710. if (strlen(arg) > 7 && !strncmp(arg, "file://", 7))
  4711. arg = arg + 7;
  4712. initpath = realpath(arg, NULL);
  4713. DPRINTF_S(initpath);
  4714. if (!initpath) {
  4715. xerror();
  4716. return _FAILURE;
  4717. }
  4718. /*
  4719. * If nnn is set as the file manager, applications may try to open
  4720. * files by invoking nnn. In that case pass the file path to the
  4721. * desktop opener and exit.
  4722. */
  4723. struct stat sb;
  4724. if (stat(initpath, &sb) == -1) {
  4725. xerror();
  4726. return _FAILURE;
  4727. }
  4728. if (S_ISREG(sb.st_mode)) {
  4729. spawn(opener, arg, NULL, NULL, F_NOWAIT);
  4730. return _SUCCESS;
  4731. }
  4732. }
  4733. /* Edit text in EDITOR if opted (and opener is not all-CLI) */
  4734. if (!cfg.cliopener && xgetenv_set(env_cfg[NNN_USE_EDITOR]))
  4735. cfg.useeditor = 1;
  4736. /* Get VISUAL/EDITOR */
  4737. editor = xgetenv(envs[VISUAL], xgetenv(envs[EDITOR], "vi"));
  4738. DPRINTF_S(getenv(envs[VISUAL]));
  4739. DPRINTF_S(getenv(envs[EDITOR]));
  4740. DPRINTF_S(editor);
  4741. /* Get PAGER */
  4742. pager = xgetenv(envs[PAGER], "less");
  4743. DPRINTF_S(pager);
  4744. /* Get SHELL */
  4745. shell = xgetenv(envs[SHELL], "sh");
  4746. DPRINTF_S(shell);
  4747. DPRINTF_S(getenv("PWD"));
  4748. #ifdef LINUX_INOTIFY
  4749. /* Initialize inotify */
  4750. inotify_fd = inotify_init1(IN_NONBLOCK);
  4751. if (inotify_fd < 0) {
  4752. xerror();
  4753. return _FAILURE;
  4754. }
  4755. #elif defined(BSD_KQUEUE)
  4756. kq = kqueue();
  4757. if (kq < 0) {
  4758. xerror();
  4759. return _FAILURE;
  4760. }
  4761. #endif
  4762. /* Set nnn nesting level, idletimeout used as tmp var */
  4763. idletimeout = xatoi(getenv(env_cfg[NNNLVL]));
  4764. setenv(env_cfg[NNNLVL], xitoa(++idletimeout), 1);
  4765. /* Get locker wait time, if set */
  4766. idletimeout = xatoi(getenv(env_cfg[NNN_IDLE_TIMEOUT]));
  4767. DPRINTF_U(idletimeout);
  4768. if (xgetenv_set(env_cfg[NNN_TRASH]))
  4769. cfg.trash = 1;
  4770. /* Prefix for temporary files */
  4771. if (!set_tmp_path())
  4772. return _FAILURE;
  4773. /* Get the clipboard copier, if set */
  4774. copier = getenv(env_cfg[NNN_COPIER]);
  4775. #ifdef __linux__
  4776. if (!progress) {
  4777. cp[5] = cp[4];
  4778. cp[2] = cp[4] = ' ';
  4779. mv[5] = mv[4];
  4780. mv[2] = mv[4] = ' ';
  4781. }
  4782. #endif
  4783. /* Ignore/handle certain signals */
  4784. struct sigaction act = {.sa_handler = sigint_handler};
  4785. if (sigaction(SIGINT, &act, NULL) < 0) {
  4786. xerror();
  4787. return _FAILURE;
  4788. }
  4789. signal(SIGQUIT, SIG_IGN);
  4790. /* Test initial path */
  4791. if (!xdiraccess(initpath)) {
  4792. xerror();
  4793. return _FAILURE;
  4794. }
  4795. #ifndef NOLOCALE
  4796. /* Set locale */
  4797. setlocale(LC_ALL, "");
  4798. #endif
  4799. #ifndef NORL
  4800. #if RL_READLINE_VERSION >= 0x0603
  4801. /* readline would overwrite the WINCH signal hook */
  4802. rl_change_environment = 0;
  4803. #endif
  4804. /* Bind TAB to cycling */
  4805. rl_variable_bind("completion-ignore-case", "on");
  4806. #ifdef __linux__
  4807. rl_bind_key('\t', rl_menu_complete);
  4808. #else
  4809. rl_bind_key('\t', rl_complete);
  4810. #endif
  4811. mkpath(cfgdir, ".history", g_buf);
  4812. read_history(g_buf);
  4813. #endif
  4814. if (!initcurses(&mask))
  4815. return _FAILURE;
  4816. browse(initpath, session);
  4817. mousemask(mask, NULL);
  4818. exitcurses();
  4819. #ifndef NORL
  4820. mkpath(cfgdir, ".history", g_buf);
  4821. write_history(g_buf);
  4822. #endif
  4823. if (cfg.pickraw) {
  4824. if (selbufpos) {
  4825. opt = seltofile(1, NULL);
  4826. if (opt != (int)(selbufpos))
  4827. xerror();
  4828. }
  4829. } else if (cfg.picker) {
  4830. if (selbufpos)
  4831. writesel(pselbuf, selbufpos - 1);
  4832. } else if (!cfg.picker && g_selpath)
  4833. unlink(g_selpath);
  4834. /* Free the selection buffer */
  4835. free(pselbuf);
  4836. #ifdef LINUX_INOTIFY
  4837. /* Shutdown inotify */
  4838. if (inotify_wd >= 0)
  4839. inotify_rm_watch(inotify_fd, inotify_wd);
  4840. close(inotify_fd);
  4841. #elif defined(BSD_KQUEUE)
  4842. if (event_fd >= 0)
  4843. close(event_fd);
  4844. close(kq);
  4845. #endif
  4846. return _SUCCESS;
  4847. }