My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

5645 lignes
122 KiB

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