My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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