My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

5695 lines
124 KiB

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