My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

5680 lines
124 KiB

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