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

6946 lines
150 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-2020, 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. #elif defined(__HAIKU__)
  52. #include "../misc/haiku/haiku_interop.h"
  53. #define HAIKU_NM
  54. #else
  55. #include <sys/sysmacros.h>
  56. #endif
  57. #include <sys/wait.h>
  58. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  59. #ifndef NCURSES_WIDECHAR
  60. #define NCURSES_WIDECHAR 1
  61. #endif
  62. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(__sun)
  63. #ifndef _XOPEN_SOURCE_EXTENDED
  64. #define _XOPEN_SOURCE_EXTENDED
  65. #endif
  66. #endif
  67. #ifndef __USE_XOPEN /* Fix wcswidth() failure, ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  68. #define __USE_XOPEN
  69. #endif
  70. #include <dirent.h>
  71. #include <errno.h>
  72. #include <fcntl.h>
  73. #include <libgen.h>
  74. #include <limits.h>
  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. #ifdef PCRE
  84. #include <pcre.h>
  85. #else
  86. #include <regex.h>
  87. #endif
  88. #include <signal.h>
  89. #include <stdarg.h>
  90. #include <stdlib.h>
  91. #ifdef __sun
  92. #include <alloca.h>
  93. #endif
  94. #include <string.h>
  95. #include <strings.h>
  96. #include <time.h>
  97. #include <unistd.h>
  98. #ifndef __USE_XOPEN_EXTENDED
  99. #define __USE_XOPEN_EXTENDED 1
  100. #endif
  101. #include <ftw.h>
  102. #include <wchar.h>
  103. #include "nnn.h"
  104. #include "dbg.h"
  105. /* Macro definitions */
  106. #define VERSION "3.0"
  107. #define GENERAL_INFO "BSD 2-Clause\nhttps://github.com/jarun/nnn"
  108. #define SESSIONS_VERSION 1
  109. #ifndef S_BLKSIZE
  110. #define S_BLKSIZE 512 /* S_BLKSIZE is missing on Android NDK (Termux) */
  111. #endif
  112. /*
  113. * NAME_MAX and PATH_MAX may not exist, e.g. with dirent.c_name being a
  114. * flexible array on Illumos. Use somewhat accomodating fallback values.
  115. */
  116. #ifndef NAME_MAX
  117. #define NAME_MAX 255
  118. #endif
  119. #ifndef PATH_MAX
  120. #define PATH_MAX 4096
  121. #endif
  122. #define _ABSSUB(N, M) (((N) <= (M)) ? ((M) - (N)) : ((N) - (M)))
  123. #define DOUBLECLICK_INTERVAL_NS (400000000)
  124. #define XDELAY_INTERVAL_MS (350000) /* 350 ms delay */
  125. #define ELEMENTS(x) (sizeof(x) / sizeof(*(x)))
  126. #undef MIN
  127. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  128. #undef MAX
  129. #define MAX(x, y) ((x) > (y) ? (x) : (y))
  130. #define ISODD(x) ((x) & 1)
  131. #define ISBLANK(x) ((x) == ' ' || (x) == '\t')
  132. #define TOUPPER(ch) (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  133. #define CMD_LEN_MAX (PATH_MAX + ((NAME_MAX + 1) << 1))
  134. #define READLINE_MAX 256
  135. #define FILTER '/'
  136. #define RFILTER '\\'
  137. #define CASE ':'
  138. #define MSGWAIT '$'
  139. #define REGEX_MAX 48
  140. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  141. #define NAMEBUF_INCR 0x800 /* 64 dir entries at once, avg. 32 chars per filename = 64*32B = 2KB */
  142. #define DESCRIPTOR_LEN 32
  143. #define _ALIGNMENT 0x10 /* 16-byte alignment */
  144. #define _ALIGNMENT_MASK 0xF
  145. #define TMP_LEN_MAX 64
  146. #define CTX_MAX 4
  147. #define DOT_FILTER_LEN 7
  148. #define ASCII_MAX 128
  149. #define EXEC_ARGS_MAX 8
  150. #define LIST_FILES_MAX (1 << 16)
  151. #define SCROLLOFF 3
  152. #define MIN_DISPLAY_COLS 10
  153. #define LONG_SIZE sizeof(ulong)
  154. #define ARCHIVE_CMD_LEN 16
  155. #define BLK_SHIFT_512 9
  156. /* Detect hardlinks in du */
  157. #define HASH_BITS (0xFFFFFF)
  158. #define HASH_OCTETS (HASH_BITS >> 6) /* 2^6 = 64 */
  159. /* Program return codes */
  160. #define _SUCCESS 0
  161. #define _FAILURE !_SUCCESS
  162. /* Entry flags */
  163. #define DIR_OR_LINK_TO_DIR 0x01
  164. #define HARD_LINK 0x02
  165. #define FILE_SELECTED 0x10
  166. /* Macros to define process spawn behaviour as flags */
  167. #define F_NONE 0x00 /* no flag set */
  168. #define F_MULTI 0x01 /* first arg can be combination of args; to be used with F_NORMAL */
  169. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  170. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  171. #define F_NORMAL 0x08 /* spawn child process in non-curses regular CLI mode */
  172. #define F_CONFIRM 0x10 /* run command - show results before exit (must have F_NORMAL) */
  173. #define F_CLI (F_NORMAL | F_MULTI)
  174. #define F_SILENT (F_CLI | F_NOTRACE)
  175. /* Version compare macros */
  176. /*
  177. * states: S_N: normal, S_I: comparing integral part, S_F: comparing
  178. * fractional parts, S_Z: idem but with leading Zeroes only
  179. */
  180. #define S_N 0x0
  181. #define S_I 0x3
  182. #define S_F 0x6
  183. #define S_Z 0x9
  184. /* result_type: VCMP: return diff; VLEN: compare using len_diff/diff */
  185. #define VCMP 2
  186. #define VLEN 3
  187. /* Volume info */
  188. #define FREE 0
  189. #define CAPACITY 1
  190. /* TYPE DEFINITIONS */
  191. typedef unsigned long ulong;
  192. typedef unsigned int uint;
  193. typedef unsigned char uchar;
  194. typedef unsigned short ushort;
  195. typedef long long ll;
  196. typedef unsigned long long ull;
  197. /* STRUCTURES */
  198. /* Directory entry */
  199. typedef struct entry {
  200. char *name;
  201. time_t t;
  202. off_t size;
  203. blkcnt_t blocks; /* number of 512B blocks allocated */
  204. mode_t mode;
  205. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  206. uchar flags; /* Flags specific to the file */
  207. } *pEntry;
  208. /* Key-value pairs from env */
  209. typedef struct {
  210. int key;
  211. char *val;
  212. } kv;
  213. typedef struct {
  214. #ifdef PCRE
  215. const pcre *pcrex;
  216. #else
  217. const regex_t *regex;
  218. #endif
  219. const char *str;
  220. } fltrexp_t;
  221. /*
  222. * Settings
  223. * NOTE: update default values if changing order
  224. */
  225. typedef struct {
  226. uint filtermode : 1; /* Set to enter filter mode */
  227. uint mtimeorder : 1; /* Set to sort by time modified */
  228. uint sizeorder : 1; /* Set to sort by file size */
  229. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  230. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  231. uint extnorder : 1; /* Order by extension */
  232. uint showhidden : 1; /* Set to show hidden files */
  233. uint selmode : 1; /* Set when selecting files */
  234. uint showdetail : 1; /* Clear to show fewer file info */
  235. uint ctxactive : 1; /* Context active or not */
  236. uint reserved1 : 2;
  237. /* The following settings are global */
  238. uint forcequit : 1; /* Do not confirm when quitting program */
  239. uint curctx : 2; /* Current context number */
  240. uint dircolor : 1; /* Current status of dir color */
  241. uint picker : 1; /* Write selection to user-specified file */
  242. uint pickraw : 1; /* Write selection to sdtout before exit */
  243. uint nonavopen : 1; /* Open file on right arrow or `l` */
  244. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  245. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  246. uint useeditor : 1; /* Use VISUAL to open text files */
  247. uint runplugin : 1; /* Choose plugin mode */
  248. uint runctx : 2; /* The context in which plugin is to be run */
  249. uint regex : 1; /* Use regex filters */
  250. uint x11 : 1; /* Copy to system clipboard and show notis */
  251. uint reserved2 : 1;
  252. uint mtime : 1; /* Use modification time (else access time) */
  253. uint cliopener : 1; /* All-CLI app opener */
  254. uint waitedit : 1; /* For ops that can't be detached, used EDITOR */
  255. uint rollover : 1; /* Roll over at edges */
  256. } settings;
  257. /* Contexts or workspaces */
  258. typedef struct {
  259. char c_path[PATH_MAX]; /* Current dir */
  260. char c_last[PATH_MAX]; /* Last visited dir */
  261. char c_name[NAME_MAX + 1]; /* Current file name */
  262. char c_fltr[REGEX_MAX]; /* Current filter */
  263. settings c_cfg; /* Current configuration */
  264. uint color; /* Color code for directories */
  265. } context;
  266. typedef struct {
  267. size_t ver;
  268. size_t pathln[CTX_MAX];
  269. size_t lastln[CTX_MAX];
  270. size_t nameln[CTX_MAX];
  271. size_t fltrln[CTX_MAX];
  272. } session_header_t;
  273. /* GLOBALS */
  274. /* Configuration, contexts */
  275. static settings cfg = {
  276. 0, /* filtermode */
  277. 0, /* mtimeorder */
  278. 0, /* sizeorder */
  279. 0, /* apparentsz */
  280. 0, /* blkorder */
  281. 0, /* extnorder */
  282. 0, /* showhidden */
  283. 0, /* selmode */
  284. 0, /* showdetail */
  285. 1, /* ctxactive */
  286. 0, /* reserved1 */
  287. 0, /* forcequit */
  288. 0, /* curctx */
  289. 0, /* dircolor */
  290. 0, /* picker */
  291. 0, /* pickraw */
  292. 0, /* nonavopen */
  293. 1, /* autoselect */
  294. 0, /* metaviewer */
  295. 0, /* useeditor */
  296. 0, /* runplugin */
  297. 0, /* runctx */
  298. 0, /* regex */
  299. 0, /* x11 */
  300. 0, /* reserved2 */
  301. 1, /* mtime */
  302. 0, /* cliopener */
  303. 0, /* waitedit */
  304. 1, /* rollover */
  305. };
  306. static context g_ctx[CTX_MAX] __attribute__ ((aligned));
  307. static int ndents, cur, last, curscroll, last_curscroll, total_dents = ENTRY_INCR;
  308. static ushort xlines, xcols;
  309. static int nselected;
  310. static uint idletimeout, selbufpos, lastappendpos, selbuflen;
  311. static ushort idle;
  312. static ushort maxbm, maxplug;
  313. static char *bmstr;
  314. static char *pluginstr;
  315. static char *opener;
  316. static char *editor;
  317. static char *enveditor;
  318. static char *pager;
  319. static char *shell;
  320. static char *home;
  321. static char *initpath;
  322. static char *cfgdir;
  323. static char *g_selpath;
  324. static char *g_listpath;
  325. static char *g_prefixpath;
  326. static char *plugindir;
  327. static char *sessiondir;
  328. static char *pnamebuf, *pselbuf;
  329. static ull *ihashbmp;
  330. static struct entry *dents;
  331. static blkcnt_t ent_blocks;
  332. static blkcnt_t dir_blocks;
  333. static ulong num_files;
  334. static kv *bookmark;
  335. static kv *plug;
  336. static uchar g_tmpfplen;
  337. static uchar blk_shift = BLK_SHIFT_512;
  338. static const uint _WSHIFT = (LONG_SIZE == 8) ? 3 : 2;
  339. #ifdef PCRE
  340. static pcre *archive_pcre;
  341. #else
  342. static regex_t archive_re;
  343. #endif
  344. /* Retain old signal handlers */
  345. #ifdef __linux__
  346. static sighandler_t oldsighup; /* old value of hangup signal */
  347. static sighandler_t oldsigtstp; /* old value of SIGTSTP */
  348. #else
  349. /* note: no sig_t on Solaris-derivs */
  350. static void (*oldsighup)(int);
  351. static void (*oldsigtstp)(int);
  352. #endif
  353. /* For use in functions which are isolated and don't return the buffer */
  354. static char g_buf[CMD_LEN_MAX] __attribute__ ((aligned));
  355. /* Buffer to store tmp file path to show selection, file stats and help */
  356. static char g_tmpfpath[TMP_LEN_MAX] __attribute__ ((aligned));
  357. /* Buffer to store plugins control pipe location */
  358. static char g_pipepath[TMP_LEN_MAX] __attribute__ ((aligned));
  359. /* MISC NON-PERSISTENT INTERNAL BINARY STATES */
  360. /* Plugin control initialization status */
  361. #define STATE_PLUGIN_INIT 0x1
  362. #define STATE_INTERRUPTED 0x2
  363. #define STATE_RANGESEL 0x4
  364. #define STATE_MOVE_OP 0x8
  365. #define STATE_AUTONEXT 0x10
  366. #define STATE_MSG 0x20
  367. #define STATE_TRASH 0x40
  368. static uchar g_states;
  369. /* Options to identify file mime */
  370. #if defined(__APPLE__)
  371. #define FILE_MIME_OPTS "-bIL"
  372. #elif !defined(__sun) /* no mime option for 'file' */
  373. #define FILE_MIME_OPTS "-biL"
  374. #endif
  375. /* Macros for utilities */
  376. #define UTIL_OPENER 0
  377. #define UTIL_ATOOL 1
  378. #define UTIL_BSDTAR 2
  379. #define UTIL_UNZIP 3
  380. #define UTIL_TAR 4
  381. #define UTIL_LOCKER 5
  382. #define UTIL_CMATRIX 6
  383. #define UTIL_LAUNCH 7
  384. #define UTIL_SH_EXEC 8
  385. #define UTIL_ARCHIVEMOUNT 9
  386. #define UTIL_SSHFS 10
  387. #define UTIL_RCLONE 11
  388. #define UTIL_VI 12
  389. #define UTIL_LESS 13
  390. #define UTIL_SH 14
  391. #define UTIL_FZF 15
  392. #define UTIL_FZY 16
  393. #define UTIL_NTFY 17
  394. #define UTIL_CBCP 18
  395. /* Utilities to open files, run actions */
  396. static char * const utils[] = {
  397. #ifdef __APPLE__
  398. "/usr/bin/open",
  399. #elif defined __CYGWIN__
  400. "cygstart",
  401. #elif defined __HAIKU__
  402. "open",
  403. #else
  404. "xdg-open",
  405. #endif
  406. "atool",
  407. "bsdtar",
  408. "unzip",
  409. "tar",
  410. #ifdef __APPLE__
  411. "bashlock",
  412. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
  413. "lock",
  414. #elif defined __HAIKU__
  415. "peaclock",
  416. #else
  417. "vlock",
  418. #endif
  419. "cmatrix",
  420. "launch",
  421. "sh -c",
  422. "archivemount",
  423. "sshfs",
  424. "rclone",
  425. "vi",
  426. "less",
  427. "sh",
  428. "fzf",
  429. "fzy",
  430. ".ntfy",
  431. ".cbcp",
  432. };
  433. /* Common strings */
  434. #define MSG_NO_TRAVERSAL 0
  435. #define MSG_INVALID_KEY 1
  436. #define STR_TMPFILE 2
  437. #define MSG_0_SELECTED 3
  438. #define MSG_UTIL_MISSING 4
  439. #define MSG_FAILED 5
  440. #define MSG_SSN_NAME 6
  441. #define MSG_CP_MV_AS 7
  442. #define MSG_CUR_SEL_OPTS 8
  443. #define MSG_FORCE_RM 9
  444. #define MSG_CREATE_CTX 10
  445. #define MSG_NEW_OPTS 11
  446. #define MSG_CLI_MODE 12
  447. #define MSG_OVERWRITE 13
  448. #define MSG_SSN_OPTS 14
  449. #define MSG_QUIT_ALL 15
  450. #define MSG_HOSTNAME 16
  451. #define MSG_ARCHIVE_NAME 17
  452. #define MSG_OPEN_WITH 18
  453. #define MSG_REL_PATH 19
  454. #define MSG_LINK_PREFIX 20
  455. #define MSG_COPY_NAME 21
  456. #define MSG_CONTINUE 22
  457. #define MSG_SEL_MISSING 23
  458. #define MSG_ACCESS 24
  459. #define MSG_EMPTY_FILE 25
  460. #define MSG_UNSUPPORTED 26
  461. #define MSG_NOT_SET 27
  462. #define MSG_EXISTS 28
  463. #define MSG_FEW_COLUMNS 29
  464. #define MSG_REMOTE_OPTS 30
  465. #define MSG_RCLONE_DELAY 31
  466. #define MSG_APP_NAME 32
  467. #define MSG_ARCHIVE_OPTS 33
  468. #define MSG_PLUGIN_KEYS 34
  469. #define MSG_BOOKMARK_KEYS 35
  470. #define MSG_INVALID_REG 36
  471. #define MSG_ORDER 37
  472. #define MSG_LAZY 38
  473. #define MSG_IGNORED 39
  474. #ifndef DIR_LIMITED_SELECTION
  475. #define MSG_DIR_CHANGED 40 /* Must be the last entry */
  476. #endif
  477. static const char * const messages[] = {
  478. "no traversal",
  479. "invalid key",
  480. "/.nnnXXXXXX",
  481. "0 selected",
  482. "missing util",
  483. "failed!",
  484. "session name: ",
  485. "'c'p / 'm'v as?",
  486. "'c'urrent / 's'el?",
  487. "forcibly remove %s file%s (unrecoverable)?",
  488. "create context %d?",
  489. "'f'ile / 'd'ir / 's'ym / 'h'ard?",
  490. "'c'li / 'g'ui?",
  491. "overwrite?",
  492. "'s'ave / 'l'oad / 'r'estore?",
  493. "Quit all contexts?",
  494. "remote name: ",
  495. "archive name: ",
  496. "open with: ",
  497. "relative path: ",
  498. "link prefix [@ for none]: ",
  499. "copy name: ",
  500. "\nPress Enter to continue",
  501. "open failed",
  502. "dir inaccessible",
  503. "empty: edit or open with",
  504. "unsupported file",
  505. "not set",
  506. "entry exists",
  507. "too few columns!",
  508. "'s'shfs / 'r'clone?",
  509. "may take a while, try refresh",
  510. "app name: ",
  511. "'d'efault / e'x'tract / 'l'ist / 'm'ount?",
  512. "plugin keys:",
  513. "bookmark keys:",
  514. "invalid regex",
  515. "toggle 'a'u / 'd'u / 'e'xtn / 'r'everse / 's'ize / 't'ime / 'v'ersion?",
  516. "unmount failed! try lazy?",
  517. "ignoring invalid paths...",
  518. #ifndef DIR_LIMITED_SELECTION
  519. "dir changed, range sel off", /* Must be the last entry */
  520. #endif
  521. };
  522. /* Supported configuration environment variables */
  523. #define NNN_OPTS 0
  524. #define NNN_BMS 1
  525. #define NNN_PLUG 2
  526. #define NNN_OPENER 3
  527. #define NNN_COLORS 4
  528. #define NNNLVL 5
  529. #define NNN_PIPE 6
  530. #define NNN_ARCHIVE 7 /* strings end here */
  531. #define NNN_TRASH 8 /* flags begin here */
  532. static const char * const env_cfg[] = {
  533. "NNN_OPTS",
  534. "NNN_BMS",
  535. "NNN_PLUG",
  536. "NNN_OPENER",
  537. "NNN_COLORS",
  538. "NNNLVL",
  539. "NNN_PIPE",
  540. "NNN_ARCHIVE",
  541. "NNN_TRASH",
  542. };
  543. /* Required environment variables */
  544. #define ENV_SHELL 0
  545. #define ENV_VISUAL 1
  546. #define ENV_EDITOR 2
  547. #define ENV_PAGER 3
  548. #define ENV_NCUR 4
  549. static const char * const envs[] = {
  550. "SHELL",
  551. "VISUAL",
  552. "EDITOR",
  553. "PAGER",
  554. "nnn",
  555. };
  556. #ifdef __linux__
  557. static char cp[] = "cp -iRp";
  558. static char mv[] = "mv -i";
  559. #else
  560. static char cp[] = "cp -iRp";
  561. static char mv[] = "mv -i";
  562. #endif
  563. /* Patterns */
  564. #define P_CPMVFMT 0
  565. #define P_CPMVRNM 1
  566. #define P_BATCHRNM 2
  567. #define P_ARCHIVE 3
  568. #define P_REPLACE 4
  569. static const char * const patterns[] = {
  570. "sed -i 's|^\\(\\(.*/\\)\\(.*\\)$\\)|#\\1\\n\\3|' %s",
  571. "sed 's|^\\([^#][^/]\\?.*\\)$|%s/\\1|;s|^#\\(/.*\\)$|\\1|' "
  572. "%s | tr '\\n' '\\0' | xargs -0 -n2 sh -c '%s \"$0\" \"$@\" < /dev/tty'",
  573. "paste -d'\n' %s %s | sed 'N; /^\\(.*\\)\\n\\1$/!p;d' | "
  574. "tr '\n' '\\0' | xargs -0 -n2 mv 2>/dev/null",
  575. "\\.(bz|bz2|gz|tar|taz|tbz|tbz2|tgz|z|zip)$",
  576. "sed -i 's|^%s\\(.*\\)$|%s\\1|' %s",
  577. };
  578. /* Event handling */
  579. #ifdef LINUX_INOTIFY
  580. #define NUM_EVENT_SLOTS 8 /* Make room for 8 events */
  581. #define EVENT_SIZE (sizeof(struct inotify_event))
  582. #define EVENT_BUF_LEN (EVENT_SIZE * NUM_EVENT_SLOTS)
  583. static int inotify_fd, inotify_wd = -1;
  584. static uint INOTIFY_MASK = /* IN_ATTRIB | */ IN_CREATE | IN_DELETE | IN_DELETE_SELF
  585. | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  586. #elif defined(BSD_KQUEUE)
  587. #define NUM_EVENT_SLOTS 1
  588. #define NUM_EVENT_FDS 1
  589. static int kq, event_fd = -1;
  590. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  591. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK
  592. | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  593. static struct timespec gtimeout;
  594. #elif defined(HAIKU_NM)
  595. static bool haiku_nm_active = FALSE;
  596. static haiku_nm_h haiku_hnd;
  597. #endif
  598. /* Function macros */
  599. #define tolastln() move(xlines - 1, 0)
  600. #define exitcurses() endwin()
  601. #define clearprompt() printmsg("")
  602. #define printwarn(presel) printwait(strerror(errno), presel)
  603. #define istopdir(path) ((path)[1] == '\0' && (path)[0] == '/')
  604. #define copycurname() xstrlcpy(lastname, dents[cur].name, NAME_MAX + 1)
  605. #define settimeout() timeout(1000)
  606. #define cleartimeout() timeout(-1)
  607. #define errexit() printerr(__LINE__)
  608. #define setdirwatch() (cfg.filtermode ? (presel = FILTER) : (dir_changed = TRUE))
  609. /* We don't care about the return value from strcmp() */
  610. #define xstrcmp(a, b) (*(a) != *(b) ? -1 : strcmp((a), (b)))
  611. /* A faster version of xisdigit */
  612. #define xisdigit(c) ((unsigned int) (c) - '0' <= 9)
  613. #define xerror() perror(xitoa(__LINE__))
  614. #define xconfirm(c) ((c) == 'y' || (c) == 'Y')
  615. #ifdef __GNUC__
  616. #define UNUSED(x) UNUSED_##x __attribute__((__unused__))
  617. #else
  618. #define UNUSED(x) UNUSED_##x
  619. #endif /* __GNUC__ */
  620. /* Forward declarations */
  621. static void redraw(char *path);
  622. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag);
  623. static int (*nftw_fn)(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  624. static int dentfind(const char *fname, int n);
  625. static void move_cursor(int target, int ignore_scrolloff);
  626. static inline bool getutil(char *util);
  627. static size_t mkpath(const char *dir, const char *name, char *out);
  628. static char *xgetenv(const char *name, char *fallback);
  629. static void plugscript(const char *plugin, char *newpath, uchar flags);
  630. /* Functions */
  631. static void sigint_handler(int UNUSED(sig))
  632. {
  633. g_states |= STATE_INTERRUPTED;
  634. }
  635. static char *xitoa(uint val)
  636. {
  637. static char ascbuf[32] = {0};
  638. int i = 30;
  639. uint rem;
  640. if (!val)
  641. return "0";
  642. while (val && i) {
  643. rem = val / 10;
  644. ascbuf[i] = '0' + (val - (rem * 10));
  645. val = rem;
  646. --i;
  647. }
  648. return &ascbuf[++i];
  649. }
  650. /*
  651. * Source: https://elixir.bootlin.com/linux/latest/source/arch/alpha/include/asm/bitops.h
  652. */
  653. static bool test_set_bit(uint nr)
  654. {
  655. nr &= HASH_BITS;
  656. ull *m = ((ull *)ihashbmp) + (nr >> 6);
  657. if (*m & (1 << (nr & 63)))
  658. return FALSE;
  659. *m |= 1 << (nr & 63);
  660. return TRUE;
  661. }
  662. #if 0
  663. static bool test_clear_bit(uint nr)
  664. {
  665. nr &= HASH_BITS;
  666. ull *m = ((ull *) ihashbmp) + (nr >> 6);
  667. if (!(*m & (1 << (nr & 63))))
  668. return FALSE;
  669. *m &= ~(1 << (nr & 63));
  670. return TRUE;
  671. }
  672. #endif
  673. static void clear_hash()
  674. {
  675. ulong i = 0;
  676. ull *addr = ihashbmp;
  677. for (; i < HASH_OCTETS; ++i, ++addr)
  678. if (*addr)
  679. *addr = 0;
  680. }
  681. static void clearinfoln(void)
  682. {
  683. move(xlines - 2, 0);
  684. addch('\n');
  685. }
  686. #ifdef KEY_RESIZE
  687. /* Clear the old prompt */
  688. static void clearoldprompt(void)
  689. {
  690. clearinfoln();
  691. tolastln();
  692. addch('\n');
  693. }
  694. #endif
  695. /* Messages show up at the bottom */
  696. static void printmsg(const char *msg)
  697. {
  698. tolastln();
  699. addstr(msg);
  700. addch('\n');
  701. }
  702. static void printwait(const char *msg, int *presel)
  703. {
  704. printmsg(msg);
  705. if (presel)
  706. *presel = MSGWAIT;
  707. }
  708. /* Kill curses and display error before exiting */
  709. static void printerr(int linenum)
  710. {
  711. exitcurses();
  712. perror(xitoa(linenum));
  713. if (!cfg.picker && g_selpath)
  714. unlink(g_selpath);
  715. free(pselbuf);
  716. exit(1);
  717. }
  718. /* Print prompt on the last line */
  719. static void printprompt(const char *str)
  720. {
  721. clearprompt();
  722. addstr(str);
  723. }
  724. static void printinfoln(const char *str)
  725. {
  726. clearinfoln();
  727. mvaddstr(xlines - 2, xcols - strlen(str), str);
  728. }
  729. static int get_input(const char *prompt)
  730. {
  731. int r;
  732. if (prompt)
  733. printprompt(prompt);
  734. cleartimeout();
  735. #ifdef KEY_RESIZE
  736. do {
  737. r = getch();
  738. if (r == KEY_RESIZE && prompt) {
  739. clearoldprompt();
  740. xlines = LINES;
  741. printprompt(prompt);
  742. }
  743. } while (r == KEY_RESIZE);
  744. #else
  745. r = getch();
  746. #endif
  747. settimeout();
  748. return r;
  749. }
  750. static int get_cur_or_sel(void)
  751. {
  752. if (selbufpos && ndents) {
  753. int choice = get_input(messages[MSG_CUR_SEL_OPTS]);
  754. return ((choice == 'c' || choice == 's') ? choice : 0);
  755. }
  756. if (selbufpos)
  757. return 's';
  758. if (ndents)
  759. return 'c';
  760. return 0;
  761. }
  762. static void xdelay(useconds_t delay)
  763. {
  764. refresh();
  765. usleep(delay);
  766. }
  767. static char confirm_force(bool selection)
  768. {
  769. char str[64];
  770. int r;
  771. snprintf(str, 64, messages[MSG_FORCE_RM],
  772. (selection ? xitoa(nselected) : "current"), (selection ? "(s)" : ""));
  773. r = get_input(str);
  774. if (xconfirm(r))
  775. return 'f'; /* forceful */
  776. return 'i'; /* interactive */
  777. }
  778. /* Increase the limit on open file descriptors, if possible */
  779. static rlim_t max_openfds(void)
  780. {
  781. struct rlimit rl;
  782. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  783. if (limit != 0)
  784. return 32;
  785. limit = rl.rlim_cur;
  786. rl.rlim_cur = rl.rlim_max;
  787. /* Return ~75% of max possible */
  788. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  789. limit = rl.rlim_max - (rl.rlim_max >> 2);
  790. /*
  791. * 20K is arbitrary. If the limit is set to max possible
  792. * value, the memory usage increases to more than double.
  793. */
  794. return limit > 20480 ? 20480 : limit;
  795. }
  796. return limit;
  797. }
  798. /*
  799. * Wrapper to realloc()
  800. * Frees current memory if realloc() fails and returns NULL.
  801. *
  802. * As per the docs, the *alloc() family is supposed to be memory aligned:
  803. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  804. * macOS: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  805. */
  806. static void *xrealloc(void *pcur, size_t len)
  807. {
  808. void *pmem = realloc(pcur, len);
  809. if (!pmem)
  810. free(pcur);
  811. return pmem;
  812. }
  813. /*
  814. * Just a safe strncpy(3)
  815. * Always null ('\0') terminates if both src and dest are valid pointers.
  816. * Returns the number of bytes copied including terminating null byte.
  817. */
  818. static size_t xstrlcpy(char *dest, const char *src, size_t n)
  819. {
  820. if (!src || !dest || !n)
  821. return 0;
  822. ulong *s, *d;
  823. size_t len = strlen(src) + 1, blocks;
  824. if (n > len)
  825. n = len;
  826. else if (len > n)
  827. /* Save total number of bytes to copy in len */
  828. len = n;
  829. /*
  830. * To enable -O3 ensure src and dest are 16-byte aligned
  831. * More info: https://www.felixcloutier.com/x86/MOVDQA:VMOVDQA32:VMOVDQA64
  832. */
  833. if ((n >= LONG_SIZE) && (((ulong)src & _ALIGNMENT_MASK) == 0 &&
  834. ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  835. s = (ulong *)src;
  836. d = (ulong *)dest;
  837. blocks = n >> _WSHIFT;
  838. n &= LONG_SIZE - 1;
  839. while (blocks) {
  840. *d = *s; // NOLINT
  841. ++d, ++s;
  842. --blocks;
  843. }
  844. if (!n) {
  845. dest = (char *)d;
  846. *--dest = '\0';
  847. return len;
  848. }
  849. src = (char *)s;
  850. dest = (char *)d;
  851. }
  852. while (--n && (*dest = *src)) // NOLINT
  853. ++dest, ++src;
  854. if (!n)
  855. *dest = '\0';
  856. return len;
  857. }
  858. static bool is_suffix(const char *str, const char *suffix)
  859. {
  860. if (!str || !suffix)
  861. return FALSE;
  862. size_t lenstr = strlen(str);
  863. size_t lensuffix = strlen(suffix);
  864. if (lensuffix > lenstr)
  865. return FALSE;
  866. return (xstrcmp(str + (lenstr - lensuffix), suffix) == 0);
  867. }
  868. /*
  869. * The poor man's implementation of memrchr(3).
  870. * We are only looking for '/' in this program.
  871. * And we are NOT expecting a '/' at the end.
  872. * Ideally 0 < n <= strlen(s).
  873. */
  874. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  875. {
  876. if (!s || !n)
  877. return NULL;
  878. uchar *ptr = s + n;
  879. do
  880. if (*--ptr == ch)
  881. return ptr;
  882. while (s != ptr);
  883. return NULL;
  884. }
  885. /* Assumes both the paths passed are directories */
  886. static char *common_prefix(const char *path, char *prefix)
  887. {
  888. const char *x = path, *y = prefix;
  889. char *sep;
  890. if (!path || !*path || !prefix)
  891. return NULL;
  892. if (!*prefix) {
  893. xstrlcpy(prefix, path, PATH_MAX);
  894. return prefix;
  895. }
  896. while (*x && *y && (*x == *y))
  897. ++x, ++y;
  898. /* Strings are same */
  899. if (!*x && !*y)
  900. return prefix;
  901. /* Path is shorter */
  902. if (!*x && *y == '/') {
  903. xstrlcpy(prefix, path, y - path);
  904. return prefix;
  905. }
  906. /* Prefix is shorter */
  907. if (!*y && *x == '/')
  908. return prefix;
  909. /* Shorten prefix */
  910. prefix[y - prefix] = '\0';
  911. sep = xmemrchr((uchar *)prefix, '/', y - prefix);
  912. if (sep != prefix)
  913. *sep = '\0';
  914. else /* Just '/' */
  915. prefix[1] = '\0';
  916. return prefix;
  917. }
  918. /*
  919. * The library function realpath() resolves symlinks.
  920. * If there's a symlink in file list we want to show the symlink not what it's points to.
  921. */
  922. static char *abspath(const char *path, const char *cwd)
  923. {
  924. if (!path || !cwd)
  925. return NULL;
  926. size_t dst_size = 0, src_size = strlen(path), cwd_size = strlen(cwd);
  927. const char *src, *next;
  928. char *dst;
  929. char *resolved_path = malloc(src_size + (*path == '/' ? 0 : cwd_size) + 1);
  930. if (!resolved_path)
  931. return NULL;
  932. /* Turn relative paths into absolute */
  933. if (path[0] != '/')
  934. dst_size = xstrlcpy(resolved_path, cwd, cwd_size + 1) - 1;
  935. else
  936. resolved_path[0] = '\0';
  937. src = path;
  938. dst = resolved_path + dst_size;
  939. for (next = NULL; next != path + src_size;) {
  940. next = strchr(src, '/');
  941. if (!next)
  942. next = path + src_size;
  943. if (next - src == 2 && src[0] == '.' && src[1] == '.') {
  944. if (dst - resolved_path) {
  945. dst = xmemrchr((uchar *)resolved_path, '/', dst - resolved_path);
  946. *dst = '\0';
  947. }
  948. } else if (next - src == 1 && src[0] == '.') {
  949. /* NOP */
  950. } else if (next - src) {
  951. *(dst++) = '/';
  952. xstrlcpy(dst, src, next - src + 1);
  953. dst += next - src;
  954. }
  955. src = next + 1;
  956. }
  957. if (*resolved_path == '\0') {
  958. resolved_path[0] = '/';
  959. resolved_path[1] = '\0';
  960. }
  961. return resolved_path;
  962. }
  963. static char *xbasename(char *path)
  964. {
  965. char *base = xmemrchr((uchar *)path, '/', strlen(path)); // NOLINT
  966. return base ? base + 1 : path;
  967. }
  968. static int create_tmp_file(void)
  969. {
  970. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, messages[STR_TMPFILE], TMP_LEN_MAX - g_tmpfplen);
  971. int fd = mkstemp(g_tmpfpath);
  972. if (fd == -1) {
  973. DPRINTF_S(strerror(errno));
  974. }
  975. return fd;
  976. }
  977. /* Writes buflen char(s) from buf to a file */
  978. static void writesel(const char *buf, const size_t buflen)
  979. {
  980. if (cfg.pickraw || !g_selpath)
  981. return;
  982. FILE *fp = fopen(g_selpath, "w");
  983. if (fp) {
  984. if (fwrite(buf, 1, buflen, fp) != buflen)
  985. printwarn(NULL);
  986. fclose(fp);
  987. } else
  988. printwarn(NULL);
  989. }
  990. static void appendfpath(const char *path, const size_t len)
  991. {
  992. if ((selbufpos >= selbuflen) || ((len + 3) > (selbuflen - selbufpos))) {
  993. selbuflen += PATH_MAX;
  994. pselbuf = xrealloc(pselbuf, selbuflen);
  995. if (!pselbuf)
  996. errexit();
  997. }
  998. selbufpos += xstrlcpy(pselbuf + selbufpos, path, len);
  999. }
  1000. /* Write selected file paths to fd, linefeed separated */
  1001. static size_t seltofile(int fd, uint *pcount)
  1002. {
  1003. uint lastpos, count = 0;
  1004. char *pbuf = pselbuf;
  1005. size_t pos = 0, len;
  1006. ssize_t r;
  1007. if (pcount)
  1008. *pcount = 0;
  1009. if (!selbufpos)
  1010. return 0;
  1011. lastpos = selbufpos - 1;
  1012. while (pos <= lastpos) {
  1013. len = strlen(pbuf);
  1014. pos += len;
  1015. r = write(fd, pbuf, len);
  1016. if (r != (ssize_t)len)
  1017. return pos;
  1018. if (pos <= lastpos) {
  1019. if (write(fd, "\n", 1) != 1)
  1020. return pos;
  1021. pbuf += len + 1;
  1022. }
  1023. ++pos;
  1024. ++count;
  1025. }
  1026. if (pcount)
  1027. *pcount = count;
  1028. return pos;
  1029. }
  1030. /* List selection from selection file (another instance) */
  1031. static bool listselfile(void)
  1032. {
  1033. struct stat sb;
  1034. if (stat(g_selpath, &sb) == -1)
  1035. return FALSE;
  1036. /* Nothing selected if file size is 0 */
  1037. if (!sb.st_size)
  1038. return FALSE;
  1039. snprintf(g_buf, CMD_LEN_MAX, "tr \'\\0\' \'\\n\' < %s", g_selpath);
  1040. spawn(utils[UTIL_SH_EXEC], g_buf, NULL, NULL, F_CLI | F_CONFIRM);
  1041. return TRUE;
  1042. }
  1043. /* Reset selection indicators */
  1044. static void resetselind(void)
  1045. {
  1046. int r = 0;
  1047. for (; r < ndents; ++r)
  1048. if (dents[r].flags & FILE_SELECTED)
  1049. dents[r].flags &= ~FILE_SELECTED;
  1050. }
  1051. static void startselection(void)
  1052. {
  1053. if (!cfg.selmode) {
  1054. cfg.selmode = 1;
  1055. nselected = 0;
  1056. if (selbufpos) {
  1057. resetselind();
  1058. writesel(NULL, 0);
  1059. selbufpos = 0;
  1060. }
  1061. lastappendpos = 0;
  1062. }
  1063. }
  1064. static void updateselbuf(const char *path, char *newpath)
  1065. {
  1066. int i = 0;
  1067. size_t r;
  1068. for (; i < ndents; ++i)
  1069. if (dents[i].flags & FILE_SELECTED) {
  1070. r = mkpath(path, dents[i].name, newpath);
  1071. appendfpath(newpath, r);
  1072. }
  1073. }
  1074. /* Finish selection procedure before an operation */
  1075. static void endselection(void)
  1076. {
  1077. int fd;
  1078. ssize_t count;
  1079. char buf[sizeof(patterns[P_REPLACE]) + PATH_MAX + (TMP_LEN_MAX << 1)];
  1080. if (cfg.selmode)
  1081. cfg.selmode = 0;
  1082. if (!g_listpath || !selbufpos)
  1083. return;
  1084. fd = create_tmp_file();
  1085. if (fd == -1) {
  1086. DPRINTF_S("couldn't create tmp file");
  1087. return;
  1088. }
  1089. seltofile(fd, NULL);
  1090. if (close(fd)) {
  1091. DPRINTF_S(strerror(errno));
  1092. printwarn(NULL);
  1093. return;
  1094. }
  1095. snprintf(buf, sizeof(buf), patterns[P_REPLACE], g_listpath, g_prefixpath, g_tmpfpath);
  1096. spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
  1097. fd = open(g_tmpfpath, O_RDONLY);
  1098. if (fd == -1) {
  1099. DPRINTF_S(strerror(errno));
  1100. printwarn(NULL);
  1101. if (unlink(g_tmpfpath)) {
  1102. DPRINTF_S(strerror(errno));
  1103. printwarn(NULL);
  1104. }
  1105. return;
  1106. }
  1107. count = read(fd, pselbuf, selbuflen);
  1108. if (count < 0) {
  1109. DPRINTF_S(strerror(errno));
  1110. printwarn(NULL);
  1111. if (close(fd) || unlink(g_tmpfpath)) {
  1112. DPRINTF_S(strerror(errno));
  1113. }
  1114. return;
  1115. }
  1116. if (close(fd) || unlink(g_tmpfpath)) {
  1117. DPRINTF_S(strerror(errno));
  1118. printwarn(NULL);
  1119. return;
  1120. }
  1121. selbufpos = count;
  1122. pselbuf[--count] = '\0';
  1123. for (--count; count > 0; --count)
  1124. if (pselbuf[count] == '\n' && pselbuf[count+1] == '/')
  1125. pselbuf[count] = '\0';
  1126. writesel(pselbuf, selbufpos - 1);
  1127. }
  1128. static void clearselection(void)
  1129. {
  1130. nselected = 0;
  1131. selbufpos = 0;
  1132. cfg.selmode = 0;
  1133. writesel(NULL, 0);
  1134. }
  1135. /* Returns: 1 - success, 0 - none selected, -1 - other failure */
  1136. static int editselection(void)
  1137. {
  1138. int ret = -1;
  1139. int fd, lines = 0;
  1140. ssize_t count;
  1141. struct stat sb;
  1142. time_t mtime;
  1143. if (!selbufpos)
  1144. return listselfile();
  1145. fd = create_tmp_file();
  1146. if (fd == -1) {
  1147. DPRINTF_S("couldn't create tmp file");
  1148. return -1;
  1149. }
  1150. seltofile(fd, NULL);
  1151. if (close(fd)) {
  1152. DPRINTF_S(strerror(errno));
  1153. return -1;
  1154. }
  1155. /* Save the last modification time */
  1156. if (stat(g_tmpfpath, &sb)) {
  1157. DPRINTF_S(strerror(errno));
  1158. unlink(g_tmpfpath);
  1159. return -1;
  1160. }
  1161. mtime = sb.st_mtime;
  1162. spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, NULL, F_CLI);
  1163. fd = open(g_tmpfpath, O_RDONLY);
  1164. if (fd == -1) {
  1165. DPRINTF_S(strerror(errno));
  1166. unlink(g_tmpfpath);
  1167. return -1;
  1168. }
  1169. fstat(fd, &sb);
  1170. if (mtime == sb.st_mtime) {
  1171. DPRINTF_S("selection is not modified");
  1172. unlink(g_tmpfpath);
  1173. return 1;
  1174. }
  1175. if (sb.st_size > selbufpos) {
  1176. DPRINTF_S("edited buffer larger than previous");
  1177. unlink(g_tmpfpath);
  1178. goto emptyedit;
  1179. }
  1180. count = read(fd, pselbuf, selbuflen);
  1181. if (count < 0) {
  1182. DPRINTF_S(strerror(errno));
  1183. printwarn(NULL);
  1184. if (close(fd) || unlink(g_tmpfpath)) {
  1185. DPRINTF_S(strerror(errno));
  1186. printwarn(NULL);
  1187. }
  1188. goto emptyedit;
  1189. }
  1190. if (close(fd) || unlink(g_tmpfpath)) {
  1191. DPRINTF_S(strerror(errno));
  1192. printwarn(NULL);
  1193. goto emptyedit;
  1194. }
  1195. if (!count) {
  1196. ret = 1;
  1197. goto emptyedit;
  1198. }
  1199. resetselind();
  1200. selbufpos = count;
  1201. /* The last character should be '\n' */
  1202. pselbuf[--count] = '\0';
  1203. for (--count; count > 0; --count) {
  1204. /* Replace every '\n' that separates two paths */
  1205. if (pselbuf[count] == '\n' && pselbuf[count + 1] == '/') {
  1206. ++lines;
  1207. pselbuf[count] = '\0';
  1208. }
  1209. }
  1210. /* Add a line for the last file */
  1211. ++lines;
  1212. if (lines > nselected) {
  1213. DPRINTF_S("files added to selection");
  1214. goto emptyedit;
  1215. }
  1216. nselected = lines;
  1217. writesel(pselbuf, selbufpos - 1);
  1218. return 1;
  1219. emptyedit:
  1220. resetselind();
  1221. clearselection();
  1222. return ret;
  1223. }
  1224. static bool selsafe(void)
  1225. {
  1226. /* Fail if selection file path not generated */
  1227. if (!g_selpath) {
  1228. printmsg(messages[MSG_SEL_MISSING]);
  1229. return FALSE;
  1230. }
  1231. /* Fail if selection file path isn't accessible */
  1232. if (access(g_selpath, R_OK | W_OK) == -1) {
  1233. errno == ENOENT ? printmsg(messages[MSG_0_SELECTED]) : printwarn(NULL);
  1234. return FALSE;
  1235. }
  1236. return TRUE;
  1237. }
  1238. /* Initialize curses mode */
  1239. static bool initcurses(void *oldmask)
  1240. {
  1241. short i;
  1242. char *colors = xgetenv(env_cfg[NNN_COLORS], "4444");
  1243. #ifdef NOMOUSE
  1244. (void) oldmask;
  1245. #endif
  1246. if (cfg.picker) {
  1247. if (!newterm(NULL, stderr, stdin)) {
  1248. fprintf(stderr, "newterm!\n");
  1249. return FALSE;
  1250. }
  1251. } else if (!initscr()) {
  1252. fprintf(stderr, "initscr!\n");
  1253. DPRINTF_S(getenv("TERM"));
  1254. return FALSE;
  1255. }
  1256. cbreak();
  1257. noecho();
  1258. nonl();
  1259. //intrflush(stdscr, FALSE);
  1260. keypad(stdscr, TRUE);
  1261. #ifndef NOMOUSE
  1262. #if NCURSES_MOUSE_VERSION <= 1
  1263. mousemask(BUTTON1_PRESSED | BUTTON1_DOUBLE_CLICKED, (mmask_t *)oldmask);
  1264. #else
  1265. mousemask(BUTTON1_PRESSED | BUTTON4_PRESSED | BUTTON5_PRESSED, (mmask_t *)oldmask);
  1266. #endif
  1267. mouseinterval(0);
  1268. #endif
  1269. curs_set(FALSE); /* Hide cursor */
  1270. start_color();
  1271. use_default_colors();
  1272. /* Get and set the context colors */
  1273. for (i = 0; i < CTX_MAX; ++i) {
  1274. if (*colors) {
  1275. g_ctx[i].color = (*colors < '0' || *colors > '7') ? 4 : *colors - '0';
  1276. ++colors;
  1277. } else
  1278. g_ctx[i].color = 4;
  1279. init_pair(i + 1, g_ctx[i].color, -1);
  1280. g_ctx[i].c_fltr[REGEX_MAX - 1] = '\0';
  1281. }
  1282. settimeout(); /* One second */
  1283. set_escdelay(25);
  1284. return TRUE;
  1285. }
  1286. /* No NULL check here as spawn() guards against it */
  1287. static int parseargs(char *line, char **argv)
  1288. {
  1289. int count = 0;
  1290. argv[count++] = line;
  1291. while (*line) { // NOLINT
  1292. if (ISBLANK(*line)) {
  1293. *line++ = '\0';
  1294. if (!*line) // NOLINT
  1295. return count;
  1296. argv[count++] = line;
  1297. if (count == EXEC_ARGS_MAX)
  1298. return -1;
  1299. }
  1300. ++line;
  1301. }
  1302. return count;
  1303. }
  1304. static pid_t xfork(uchar flag)
  1305. {
  1306. int status;
  1307. pid_t p = fork();
  1308. if (p > 0) {
  1309. /* the parent ignores the interrupt, quit and hangup signals */
  1310. oldsighup = signal(SIGHUP, SIG_IGN);
  1311. oldsigtstp = signal(SIGTSTP, SIG_DFL);
  1312. } else if (p == 0) {
  1313. /* We create a grandchild to detach */
  1314. if (flag & F_NOWAIT) {
  1315. p = fork();
  1316. if (p > 0)
  1317. _exit(0);
  1318. else if (p == 0) {
  1319. signal(SIGHUP, SIG_DFL);
  1320. signal(SIGINT, SIG_DFL);
  1321. signal(SIGQUIT, SIG_DFL);
  1322. signal(SIGTSTP, SIG_DFL);
  1323. setsid();
  1324. return p;
  1325. }
  1326. perror("fork");
  1327. _exit(0);
  1328. }
  1329. /* so they can be used to stop the child */
  1330. signal(SIGHUP, SIG_DFL);
  1331. signal(SIGINT, SIG_DFL);
  1332. signal(SIGQUIT, SIG_DFL);
  1333. signal(SIGTSTP, SIG_DFL);
  1334. }
  1335. /* This is the parent waiting for the child to create grandchild*/
  1336. if (flag & F_NOWAIT)
  1337. waitpid(p, &status, 0);
  1338. if (p == -1)
  1339. perror("fork");
  1340. return p;
  1341. }
  1342. static int join(pid_t p, uchar flag)
  1343. {
  1344. int status = 0xFFFF;
  1345. if (!(flag & F_NOWAIT)) {
  1346. /* wait for the child to exit */
  1347. do {
  1348. } while (waitpid(p, &status, 0) == -1);
  1349. if (WIFEXITED(status)) {
  1350. status = WEXITSTATUS(status);
  1351. DPRINTF_D(status);
  1352. }
  1353. }
  1354. /* restore parent's signal handling */
  1355. signal(SIGHUP, oldsighup);
  1356. signal(SIGTSTP, oldsigtstp);
  1357. return status;
  1358. }
  1359. /*
  1360. * Spawns a child process. Behaviour can be controlled using flag.
  1361. * Limited to 2 arguments to a program, flag works on bit set.
  1362. */
  1363. static int spawn(char *file, char *arg1, char *arg2, const char *dir, uchar flag)
  1364. {
  1365. pid_t pid;
  1366. int status, retstatus = 0xFFFF;
  1367. char *argv[EXEC_ARGS_MAX] = {0};
  1368. char *cmd = NULL;
  1369. if (!file || !*file)
  1370. return retstatus;
  1371. /* Swap args if the first arg is NULL and second isn't */
  1372. if (!arg1 && arg2) {
  1373. arg1 = arg2;
  1374. arg2 = NULL;
  1375. }
  1376. if (flag & F_MULTI) {
  1377. size_t len = strlen(file) + 1;
  1378. cmd = (char *)malloc(len);
  1379. if (!cmd) {
  1380. DPRINTF_S("malloc()!");
  1381. return retstatus;
  1382. }
  1383. xstrlcpy(cmd, file, len);
  1384. status = parseargs(cmd, argv);
  1385. if (status == -1 || status > (EXEC_ARGS_MAX - 3)) { /* arg1, arg2 and last NULL */
  1386. free(cmd);
  1387. DPRINTF_S("NULL or too many args");
  1388. return retstatus;
  1389. }
  1390. argv[status++] = arg1;
  1391. argv[status] = arg2;
  1392. } else {
  1393. argv[0] = file;
  1394. argv[1] = arg1;
  1395. argv[2] = arg2;
  1396. }
  1397. if (flag & F_NORMAL)
  1398. exitcurses();
  1399. pid = xfork(flag);
  1400. if (pid == 0) {
  1401. if (dir && chdir(dir) == -1)
  1402. _exit(1);
  1403. /* Suppress stdout and stderr */
  1404. if (flag & F_NOTRACE) {
  1405. int fd = open("/dev/null", O_WRONLY, 0200);
  1406. dup2(fd, 1);
  1407. dup2(fd, 2);
  1408. close(fd);
  1409. }
  1410. execvp(*argv, argv);
  1411. _exit(1);
  1412. } else {
  1413. retstatus = join(pid, flag);
  1414. DPRINTF_D(pid);
  1415. if (flag & F_NORMAL) {
  1416. if (flag & F_CONFIRM) {
  1417. printf("%s", messages[MSG_CONTINUE]);
  1418. while (getchar() != '\n');
  1419. }
  1420. refresh();
  1421. }
  1422. free(cmd);
  1423. }
  1424. return retstatus;
  1425. }
  1426. static void prompt_run(char *cmd, const char *cur, const char *path)
  1427. {
  1428. setenv(envs[ENV_NCUR], cur, 1);
  1429. spawn(shell, "-c", cmd, path, F_CLI | F_CONFIRM);
  1430. }
  1431. /* Get program name from env var, else return fallback program */
  1432. static char *xgetenv(const char * const name, char *fallback)
  1433. {
  1434. char *value = getenv(name);
  1435. return value && value[0] ? value : fallback;
  1436. }
  1437. /* Checks if an env variable is set to 1 */
  1438. static bool xgetenv_set(const char *name)
  1439. {
  1440. char *value = getenv(name);
  1441. if (value && value[0] == '1' && !value[1])
  1442. return TRUE;
  1443. return FALSE;
  1444. }
  1445. /* Check if a dir exists, IS a dir and is readable */
  1446. static bool xdiraccess(const char *path)
  1447. {
  1448. DIR *dirp = opendir(path);
  1449. if (!dirp) {
  1450. printwarn(NULL);
  1451. return FALSE;
  1452. }
  1453. closedir(dirp);
  1454. return TRUE;
  1455. }
  1456. static void opstr(char *buf, char *op)
  1457. {
  1458. snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c '%s \"$0\" \"$@\" . < /dev/tty' < %s",
  1459. op, g_selpath);
  1460. }
  1461. static void rmmulstr(char *buf)
  1462. {
  1463. if (g_states & STATE_TRASH)
  1464. snprintf(buf, CMD_LEN_MAX, "xargs -0 trash-put < %s", g_selpath);
  1465. else
  1466. snprintf(buf, CMD_LEN_MAX, "xargs -0 sh -c 'rm -%cr \"$0\" \"$@\" < /dev/tty' < %s",
  1467. confirm_force(TRUE), g_selpath);
  1468. }
  1469. static void xrm(char *path)
  1470. {
  1471. if (g_states & STATE_TRASH)
  1472. spawn("trash-put", path, NULL, NULL, F_NORMAL);
  1473. else {
  1474. char rm_opts[] = "-ir";
  1475. rm_opts[1] = confirm_force(FALSE);
  1476. spawn("rm", rm_opts, path, NULL, F_NORMAL);
  1477. }
  1478. }
  1479. static uint lines_in_file(int fd, char *buf, size_t buflen)
  1480. {
  1481. ssize_t len;
  1482. uint count = 0;
  1483. while ((len = read(fd, buf, buflen)) > 0)
  1484. while (len)
  1485. count += (buf[--len] == '\n');
  1486. /* For all use cases 0 linecount is considered as error */
  1487. return ((len < 0) ? 0 : count);
  1488. }
  1489. static bool cpmv_rename(int choice, const char *path)
  1490. {
  1491. int fd;
  1492. uint count = 0, lines = 0;
  1493. bool ret = FALSE;
  1494. char *cmd = (choice == 'c' ? cp : mv);
  1495. char buf[sizeof(patterns[P_CPMVRNM]) + sizeof(cmd) + (PATH_MAX << 1)];
  1496. fd = create_tmp_file();
  1497. if (fd == -1)
  1498. return ret;
  1499. /* selsafe() returned TRUE for this to be called */
  1500. if (!selbufpos) {
  1501. snprintf(buf, sizeof(buf), "tr '\\0' '\\n' < %s > %s", g_selpath, g_tmpfpath);
  1502. spawn(utils[UTIL_SH_EXEC], buf, NULL, NULL, F_CLI);
  1503. count = lines_in_file(fd, buf, sizeof(buf));
  1504. if (!count)
  1505. goto finish;
  1506. } else
  1507. seltofile(fd, &count);
  1508. close(fd);
  1509. snprintf(buf, sizeof(buf), patterns[P_CPMVFMT], g_tmpfpath);
  1510. spawn(utils[UTIL_SH_EXEC], buf, NULL, path, F_CLI);
  1511. spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, path, F_CLI);
  1512. fd = open(g_tmpfpath, O_RDONLY);
  1513. if (fd == -1)
  1514. goto finish;
  1515. lines = lines_in_file(fd, buf, sizeof(buf));
  1516. DPRINTF_U(count);
  1517. DPRINTF_U(lines);
  1518. if (!lines || (2 * count != lines)) {
  1519. DPRINTF_S("num mismatch");
  1520. goto finish;
  1521. }
  1522. snprintf(buf, sizeof(buf), patterns[P_CPMVRNM], path, g_tmpfpath, cmd);
  1523. spawn(utils[UTIL_SH_EXEC], buf, NULL, path, F_CLI);
  1524. ret = TRUE;
  1525. finish:
  1526. if (fd >= 0)
  1527. close(fd);
  1528. return ret;
  1529. }
  1530. static bool cpmvrm_selection(enum action sel, char *path, int *presel)
  1531. {
  1532. int r;
  1533. if (!selsafe()) {
  1534. *presel = MSGWAIT;
  1535. return FALSE;
  1536. }
  1537. switch (sel) {
  1538. case SEL_CP:
  1539. opstr(g_buf, cp);
  1540. break;
  1541. case SEL_MV:
  1542. opstr(g_buf, mv);
  1543. break;
  1544. case SEL_CPMVAS:
  1545. r = get_input(messages[MSG_CP_MV_AS]);
  1546. if (r != 'c' && r != 'm') {
  1547. printwait(messages[MSG_INVALID_KEY], presel);
  1548. return FALSE;
  1549. }
  1550. if (!cpmv_rename(r, path)) {
  1551. printwait(messages[MSG_FAILED], presel);
  1552. return FALSE;
  1553. }
  1554. break;
  1555. default: /* SEL_RM */
  1556. rmmulstr(g_buf);
  1557. break;
  1558. }
  1559. if (sel != SEL_CPMVAS)
  1560. spawn(utils[UTIL_SH_EXEC], g_buf, NULL, path, F_CLI);
  1561. /* Clear selection on move or delete */
  1562. if (sel != SEL_CP)
  1563. clearselection();
  1564. if (cfg.filtermode)
  1565. *presel = FILTER;
  1566. return TRUE;
  1567. }
  1568. static bool batch_rename(const char *path)
  1569. {
  1570. int fd1, fd2, i;
  1571. uint count = 0, lines = 0;
  1572. bool dir = FALSE, ret = FALSE;
  1573. char foriginal[TMP_LEN_MAX] = {0};
  1574. char buf[sizeof(patterns[P_BATCHRNM]) + (PATH_MAX << 1)];
  1575. i = get_cur_or_sel();
  1576. if (!i)
  1577. return ret;
  1578. if (i == 'c') { /* Rename entries in current dir */
  1579. selbufpos = 0;
  1580. dir = TRUE;
  1581. }
  1582. fd1 = create_tmp_file();
  1583. if (fd1 == -1)
  1584. return ret;
  1585. xstrlcpy(foriginal, g_tmpfpath, strlen(g_tmpfpath)+1);
  1586. fd2 = create_tmp_file();
  1587. if (fd2 == -1) {
  1588. unlink(foriginal);
  1589. close(fd1);
  1590. return ret;
  1591. }
  1592. if (dir)
  1593. for (i = 0; i < ndents; ++i)
  1594. appendfpath(dents[i].name, NAME_MAX);
  1595. seltofile(fd1, &count);
  1596. seltofile(fd2, NULL);
  1597. close(fd2);
  1598. if (dir) /* Don't retain dir entries in selection */
  1599. selbufpos = 0;
  1600. spawn((cfg.waitedit ? enveditor : editor), g_tmpfpath, NULL, path, F_CLI);
  1601. /* Reopen file descriptor to get updated contents */
  1602. fd2 = open(g_tmpfpath, O_RDONLY);
  1603. if (fd2 == -1)
  1604. goto finish;
  1605. lines = lines_in_file(fd2, buf, sizeof(buf));
  1606. DPRINTF_U(count);
  1607. DPRINTF_U(lines);
  1608. if (!lines || (count != lines)) {
  1609. DPRINTF_S("cannot delete files");
  1610. goto finish;
  1611. }
  1612. snprintf(buf, sizeof(buf), patterns[P_BATCHRNM], foriginal, g_tmpfpath);
  1613. spawn(utils[UTIL_SH_EXEC], buf, NULL, path, F_CLI);
  1614. ret = TRUE;
  1615. finish:
  1616. if (fd1 >= 0)
  1617. close(fd1);
  1618. unlink(foriginal);
  1619. if (fd2 >= 0)
  1620. close(fd2);
  1621. unlink(g_tmpfpath);
  1622. return ret;
  1623. }
  1624. static void get_archive_cmd(char *cmd, char *archive)
  1625. {
  1626. if (getutil(utils[UTIL_ATOOL]))
  1627. xstrlcpy(cmd, "atool -a", ARCHIVE_CMD_LEN);
  1628. else if (getutil(utils[UTIL_BSDTAR]))
  1629. xstrlcpy(cmd, "bsdtar -acvf", ARCHIVE_CMD_LEN);
  1630. else if (is_suffix(archive, ".zip"))
  1631. xstrlcpy(cmd, "zip -r", ARCHIVE_CMD_LEN);
  1632. else
  1633. xstrlcpy(cmd, "tar -acvf", ARCHIVE_CMD_LEN);
  1634. }
  1635. static void archive_selection(const char *cmd, const char *archive, const char *curpath)
  1636. {
  1637. /* The 70 comes from the string below */
  1638. char *buf = (char *)malloc((70 + strlen(cmd) + strlen(archive)
  1639. + strlen(curpath) + strlen(g_selpath)) * sizeof(char));
  1640. if (!buf) {
  1641. DPRINTF_S(strerror(errno));
  1642. printwarn(NULL);
  1643. return;
  1644. }
  1645. snprintf(buf, CMD_LEN_MAX,
  1646. #ifdef __linux__
  1647. "sed -ze 's|^%s/||' '%s' | xargs -0 %s %s", curpath, g_selpath, cmd, archive);
  1648. #else
  1649. "tr '\\0' '\n' < '%s' | sed -e 's|^%s/||' | tr '\n' '\\0' | xargs -0 %s %s",
  1650. g_selpath, curpath, cmd, archive);
  1651. #endif
  1652. spawn(utils[UTIL_SH_EXEC], buf, NULL, curpath, F_CLI);
  1653. free(buf);
  1654. }
  1655. static bool write_lastdir(const char *curpath)
  1656. {
  1657. bool ret = TRUE;
  1658. size_t len = strlen(cfgdir);
  1659. xstrlcpy(cfgdir + len, "/.lastd", 8);
  1660. DPRINTF_S(cfgdir);
  1661. FILE *fp = fopen(cfgdir, "w");
  1662. if (fp) {
  1663. if (fprintf(fp, "cd \"%s\"", curpath) < 0)
  1664. ret = FALSE;
  1665. fclose(fp);
  1666. } else
  1667. ret = FALSE;
  1668. return ret;
  1669. }
  1670. /*
  1671. * We assume none of the strings are NULL.
  1672. *
  1673. * Let's have the logic to sort numeric names in numeric order.
  1674. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  1675. *
  1676. * If the absolute numeric values are same, we fallback to alphasort.
  1677. */
  1678. static int xstricmp(const char * const s1, const char * const s2)
  1679. {
  1680. char *p1, *p2;
  1681. ll v1 = strtoll(s1, &p1, 10);
  1682. ll v2 = strtoll(s2, &p2, 10);
  1683. /* Check if at least 1 string is numeric */
  1684. if (s1 != p1 || s2 != p2) {
  1685. /* Handle both pure numeric */
  1686. if (s1 != p1 && s2 != p2) {
  1687. if (v2 > v1)
  1688. return -1;
  1689. if (v1 > v2)
  1690. return 1;
  1691. }
  1692. /* Only first string non-numeric */
  1693. if (s1 == p1)
  1694. return 1;
  1695. /* Only second string non-numeric */
  1696. if (s2 == p2)
  1697. return -1;
  1698. }
  1699. /* Handle 1. all non-numeric and 2. both same numeric value cases */
  1700. #ifndef NOLOCALE
  1701. return strcoll(s1, s2);
  1702. #else
  1703. return strcasecmp(s1, s2);
  1704. #endif
  1705. }
  1706. /*
  1707. * Version comparison
  1708. *
  1709. * The code for version compare is a modified version of the GLIBC
  1710. * and uClibc implementation of strverscmp(). The source is here:
  1711. * https://elixir.bootlin.com/uclibc-ng/latest/source/libc/string/strverscmp.c
  1712. */
  1713. /*
  1714. * Compare S1 and S2 as strings holding indices/version numbers,
  1715. * returning less than, equal to or greater than zero if S1 is less than,
  1716. * equal to or greater than S2 (for more info, see the texinfo doc).
  1717. *
  1718. * Ignores case.
  1719. */
  1720. static int xstrverscasecmp(const char * const s1, const char * const s2)
  1721. {
  1722. const uchar *p1 = (const uchar *)s1;
  1723. const uchar *p2 = (const uchar *)s2;
  1724. int state, diff;
  1725. uchar c1, c2;
  1726. /*
  1727. * Symbol(s) 0 [1-9] others
  1728. * Transition (10) 0 (01) d (00) x
  1729. */
  1730. static const uint8_t next_state[] = {
  1731. /* state x d 0 */
  1732. /* S_N */ S_N, S_I, S_Z,
  1733. /* S_I */ S_N, S_I, S_I,
  1734. /* S_F */ S_N, S_F, S_F,
  1735. /* S_Z */ S_N, S_F, S_Z
  1736. };
  1737. static const int8_t result_type[] __attribute__ ((aligned)) = {
  1738. /* state x/x x/d x/0 d/x d/d d/0 0/x 0/d 0/0 */
  1739. /* S_N */ VCMP, VCMP, VCMP, VCMP, VLEN, VCMP, VCMP, VCMP, VCMP,
  1740. /* S_I */ VCMP, -1, -1, 1, VLEN, VLEN, 1, VLEN, VLEN,
  1741. /* S_F */ VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP, VCMP,
  1742. /* S_Z */ VCMP, 1, 1, -1, VCMP, VCMP, -1, VCMP, VCMP
  1743. };
  1744. if (p1 == p2)
  1745. return 0;
  1746. c1 = TOUPPER(*p1);
  1747. ++p1;
  1748. c2 = TOUPPER(*p2);
  1749. ++p2;
  1750. /* Hint: '0' is a digit too. */
  1751. state = S_N + ((c1 == '0') + (xisdigit(c1) != 0));
  1752. while ((diff = c1 - c2) == 0) {
  1753. if (c1 == '\0')
  1754. return diff;
  1755. state = next_state[state];
  1756. c1 = TOUPPER(*p1);
  1757. ++p1;
  1758. c2 = TOUPPER(*p2);
  1759. ++p2;
  1760. state += (c1 == '0') + (xisdigit(c1) != 0);
  1761. }
  1762. state = result_type[state * 3 + (((c2 == '0') + (xisdigit(c2) != 0)))];
  1763. switch (state) {
  1764. case VCMP:
  1765. return diff;
  1766. case VLEN:
  1767. while (xisdigit(*p1++))
  1768. if (!xisdigit(*p2++))
  1769. return 1;
  1770. return xisdigit(*p2) ? -1 : diff;
  1771. default:
  1772. return state;
  1773. }
  1774. }
  1775. static int (*namecmpfn)(const char * const s1, const char * const s2) = &xstricmp;
  1776. /* Return the integer value of a char representing HEX */
  1777. static char xchartohex(char c)
  1778. {
  1779. if (xisdigit(c))
  1780. return c - '0';
  1781. if (c >= 'a' && c <= 'f')
  1782. return c - 'a' + 10;
  1783. if (c >= 'A' && c <= 'F')
  1784. return c - 'A' + 10;
  1785. return c;
  1786. }
  1787. static char * (*fnstrstr)(const char *haystack, const char *needle) = &strcasestr;
  1788. #ifdef PCRE
  1789. static const unsigned char *tables;
  1790. static int pcreflags = PCRE_NO_AUTO_CAPTURE | PCRE_EXTENDED | PCRE_CASELESS | PCRE_UTF8;
  1791. #else
  1792. static int regflags = REG_NOSUB | REG_EXTENDED | REG_ICASE;
  1793. #endif
  1794. #ifdef PCRE
  1795. static int setfilter(pcre **pcrex, const char *filter)
  1796. {
  1797. const char *errstr = NULL;
  1798. int erroffset = 0;
  1799. *pcrex = pcre_compile(filter, pcreflags, &errstr, &erroffset, tables);
  1800. return errstr ? -1 : 0;
  1801. }
  1802. #else
  1803. static int setfilter(regex_t *regex, const char *filter)
  1804. {
  1805. return regcomp(regex, filter, regflags);
  1806. }
  1807. #endif
  1808. static int visible_re(const fltrexp_t *fltrexp, const char *fname)
  1809. {
  1810. #ifdef PCRE
  1811. return pcre_exec(fltrexp->pcrex, NULL, fname, strlen(fname), 0, 0, NULL, 0) == 0;
  1812. #else
  1813. return regexec(fltrexp->regex, fname, 0, NULL, 0) == 0;
  1814. #endif
  1815. }
  1816. static int visible_str(const fltrexp_t *fltrexp, const char *fname)
  1817. {
  1818. return fnstrstr(fname, fltrexp->str) != NULL;
  1819. }
  1820. static int (*filterfn)(const fltrexp_t *fltr, const char *fname) = &visible_str;
  1821. static void clearfilter(void)
  1822. {
  1823. char *fltr = g_ctx[cfg.curctx].c_fltr;
  1824. if (fltr[1]) {
  1825. fltr[REGEX_MAX - 1] = fltr[1];
  1826. fltr[1] = '\0';
  1827. }
  1828. }
  1829. static int entrycmp(const void *va, const void *vb)
  1830. {
  1831. const struct entry *pa = (pEntry)va;
  1832. const struct entry *pb = (pEntry)vb;
  1833. if ((pb->flags & DIR_OR_LINK_TO_DIR) != (pa->flags & DIR_OR_LINK_TO_DIR)) {
  1834. if (pb->flags & DIR_OR_LINK_TO_DIR)
  1835. return 1;
  1836. return -1;
  1837. }
  1838. /* Sort based on specified order */
  1839. if (cfg.mtimeorder) {
  1840. if (pb->t > pa->t)
  1841. return 1;
  1842. if (pb->t < pa->t)
  1843. return -1;
  1844. } else if (cfg.sizeorder) {
  1845. if (pb->size > pa->size)
  1846. return 1;
  1847. if (pb->size < pa->size)
  1848. return -1;
  1849. } else if (cfg.blkorder) {
  1850. if (pb->blocks > pa->blocks)
  1851. return 1;
  1852. if (pb->blocks < pa->blocks)
  1853. return -1;
  1854. } else if (cfg.extnorder && !(pb->flags & DIR_OR_LINK_TO_DIR)) {
  1855. char *extna = xmemrchr((uchar *)pa->name, '.', pa->nlen - 1);
  1856. char *extnb = xmemrchr((uchar *)pb->name, '.', pb->nlen - 1);
  1857. if (extna || extnb) {
  1858. if (!extna)
  1859. return -1;
  1860. if (!extnb)
  1861. return 1;
  1862. int ret = strcasecmp(extna, extnb);
  1863. if (ret)
  1864. return ret;
  1865. }
  1866. }
  1867. return namecmpfn(pa->name, pb->name);
  1868. }
  1869. static int reventrycmp(const void *va, const void *vb)
  1870. {
  1871. if ((((pEntry)vb)->flags & DIR_OR_LINK_TO_DIR)
  1872. != (((pEntry)va)->flags & DIR_OR_LINK_TO_DIR)) {
  1873. if (((pEntry)vb)->flags & DIR_OR_LINK_TO_DIR)
  1874. return 1;
  1875. return -1;
  1876. }
  1877. return -entrycmp(va, vb);
  1878. }
  1879. static int (*entrycmpfn)(const void *va, const void *vb) = &entrycmp;
  1880. /*
  1881. * Returns SEL_* if key is bound and 0 otherwise.
  1882. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  1883. * The next keyboard input can be simulated by presel.
  1884. */
  1885. static int nextsel(int presel)
  1886. {
  1887. int c = presel;
  1888. uint i;
  1889. #ifdef LINUX_INOTIFY
  1890. struct inotify_event *event;
  1891. char inotify_buf[EVENT_BUF_LEN];
  1892. memset((void *)inotify_buf, 0x0, EVENT_BUF_LEN);
  1893. #elif defined(BSD_KQUEUE)
  1894. struct kevent event_data[NUM_EVENT_SLOTS];
  1895. memset((void *)event_data, 0x0, sizeof(struct kevent) * NUM_EVENT_SLOTS);
  1896. #elif defined(HAIKU_NM)
  1897. // TODO: Do some Haiku declarations
  1898. #endif
  1899. if (c == 0 || c == MSGWAIT) {
  1900. c = getch();
  1901. //DPRINTF_D(c);
  1902. //DPRINTF_S(keyname(c));
  1903. if (c == ERR && presel == MSGWAIT)
  1904. c = (cfg.filtermode) ? FILTER : CONTROL('L');
  1905. else if (c == FILTER || c == CONTROL('L'))
  1906. /* Clear previous filter when manually starting */
  1907. clearfilter();
  1908. }
  1909. if (c == -1) {
  1910. ++idle;
  1911. /*
  1912. * Do not check for directory changes in du mode.
  1913. * A redraw forces du calculation.
  1914. * Check for changes every odd second.
  1915. */
  1916. #ifdef LINUX_INOTIFY
  1917. if (!cfg.selmode && !cfg.blkorder && inotify_wd >= 0 && (idle & 1)) {
  1918. i = read(inotify_fd, inotify_buf, EVENT_BUF_LEN);
  1919. if (i > 0) {
  1920. char *ptr;
  1921. for (ptr = inotify_buf;
  1922. ptr + ((struct inotify_event *)ptr)->len < inotify_buf + i;
  1923. ptr += sizeof(struct inotify_event) + event->len) {
  1924. event = (struct inotify_event *) ptr;
  1925. DPRINTF_D(event->wd);
  1926. DPRINTF_D(event->mask);
  1927. if (!event->wd)
  1928. break;
  1929. if (event->mask & INOTIFY_MASK) {
  1930. c = CONTROL('L');
  1931. DPRINTF_S("issue refresh");
  1932. break;
  1933. }
  1934. }
  1935. DPRINTF_S("inotify read done");
  1936. }
  1937. }
  1938. #elif defined(BSD_KQUEUE)
  1939. if (!cfg.selmode && !cfg.blkorder && event_fd >= 0 && idle & 1
  1940. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS,
  1941. event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  1942. c = CONTROL('L');
  1943. #elif defined(HAIKU_NM)
  1944. if (!cfg.selmode && !cfg.blkorder && haiku_nm_active && idle & 1 && haiku_is_update_needed(haiku_hnd))
  1945. c = CONTROL('L');
  1946. #endif
  1947. } else
  1948. idle = 0;
  1949. for (i = 0; i < (int)ELEMENTS(bindings); ++i)
  1950. if (c == bindings[i].sym)
  1951. return bindings[i].act;
  1952. return 0;
  1953. }
  1954. static int getorderstr(char *sort)
  1955. {
  1956. int i = 0;
  1957. if (cfg.mtimeorder)
  1958. sort[0] = cfg.mtime ? 'T' : 'A';
  1959. else if (cfg.sizeorder)
  1960. sort[0] = 'S';
  1961. else if (cfg.extnorder)
  1962. sort[0] = 'E';
  1963. if (sort[i])
  1964. ++i;
  1965. if (entrycmpfn == &reventrycmp) {
  1966. sort[i] = 'R';
  1967. ++i;
  1968. }
  1969. if (namecmpfn == &xstrverscasecmp) {
  1970. sort[i] = 'V';
  1971. ++i;
  1972. }
  1973. if (i)
  1974. sort[i] = ' ';
  1975. return i;
  1976. }
  1977. static void showfilterinfo(void)
  1978. {
  1979. int i = 0;
  1980. char info[REGEX_MAX] = "\0\0\0\0";
  1981. i = getorderstr(info);
  1982. snprintf(info + i, REGEX_MAX - i - 1, " %s [/], %s [:]",
  1983. (cfg.regex ? "regex" : "str"),
  1984. ((fnstrstr == &strcasestr) ? "ic" : "noic"));
  1985. printinfoln(info);
  1986. }
  1987. static void showfilter(char *str)
  1988. {
  1989. showfilterinfo();
  1990. printprompt(str);
  1991. }
  1992. static inline void swap_ent(int id1, int id2)
  1993. {
  1994. struct entry _dent, *pdent1 = &dents[id1], *pdent2 = &dents[id2];
  1995. *(&_dent) = *pdent1;
  1996. *pdent1 = *pdent2;
  1997. *pdent2 = *(&_dent);
  1998. }
  1999. #ifdef PCRE
  2000. static int fill(const char *fltr, pcre *pcrex)
  2001. #else
  2002. static int fill(const char *fltr, regex_t *re)
  2003. #endif
  2004. {
  2005. int count = 0;
  2006. #ifdef PCRE
  2007. fltrexp_t fltrexp = { .pcrex = pcrex, .str = fltr };
  2008. #else
  2009. fltrexp_t fltrexp = { .regex = re, .str = fltr };
  2010. #endif
  2011. for (; count < ndents; ++count) {
  2012. if (filterfn(&fltrexp, dents[count].name) == 0) {
  2013. if (count != --ndents) {
  2014. swap_ent(count, ndents);
  2015. --count;
  2016. }
  2017. continue;
  2018. }
  2019. }
  2020. return ndents;
  2021. }
  2022. static int matches(const char *fltr)
  2023. {
  2024. #ifdef PCRE
  2025. pcre *pcrex = NULL;
  2026. /* Search filter */
  2027. if (cfg.regex && setfilter(&pcrex, fltr))
  2028. return -1;
  2029. ndents = fill(fltr, pcrex);
  2030. if (cfg.regex)
  2031. pcre_free(pcrex);
  2032. #else
  2033. regex_t re;
  2034. /* Search filter */
  2035. if (cfg.regex && setfilter(&re, fltr))
  2036. return -1;
  2037. ndents = fill(fltr, &re);
  2038. if (cfg.regex)
  2039. regfree(&re);
  2040. #endif
  2041. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  2042. return ndents;
  2043. }
  2044. static int filterentries(char *path, char *lastname)
  2045. {
  2046. wchar_t *wln = (wchar_t *)alloca(sizeof(wchar_t) * REGEX_MAX);
  2047. char *ln = g_ctx[cfg.curctx].c_fltr;
  2048. wint_t ch[2] = {0};
  2049. int r, total = ndents, len;
  2050. char *pln = g_ctx[cfg.curctx].c_fltr + 1;
  2051. if (ndents && (ln[0] == FILTER || ln[0] == RFILTER) && *pln) {
  2052. if (matches(pln) != -1) {
  2053. move_cursor(dentfind(lastname, ndents), 0);
  2054. redraw(path);
  2055. }
  2056. len = mbstowcs(wln, ln, REGEX_MAX);
  2057. } else {
  2058. ln[0] = wln[0] = cfg.regex ? RFILTER : FILTER;
  2059. ln[1] = wln[1] = '\0';
  2060. len = 1;
  2061. }
  2062. cleartimeout();
  2063. curs_set(TRUE);
  2064. showfilter(ln);
  2065. while ((r = get_wch(ch)) != ERR) {
  2066. //DPRINTF_D(*ch);
  2067. //DPRINTF_S(keyname(*ch));
  2068. switch (*ch) {
  2069. #ifdef KEY_RESIZE
  2070. case KEY_RESIZE:
  2071. clearoldprompt();
  2072. redraw(path);
  2073. showfilter(ln);
  2074. continue;
  2075. #endif
  2076. case KEY_DC: // fallthrough
  2077. case KEY_BACKSPACE: // fallthrough
  2078. case '\b': // fallthrough
  2079. case 127: /* handle DEL */
  2080. if (len != 1) {
  2081. wln[--len] = '\0';
  2082. wcstombs(ln, wln, REGEX_MAX);
  2083. ndents = total;
  2084. } else
  2085. continue;
  2086. // fallthrough
  2087. case CONTROL('L'):
  2088. if (*ch == CONTROL('L')) {
  2089. if (wln[1]) {
  2090. ln[REGEX_MAX - 1] = ln[1];
  2091. ln[1] = wln[1] = '\0';
  2092. len = 1;
  2093. ndents = total;
  2094. } else if (ln[REGEX_MAX - 1]) { /* Show the previous filter */
  2095. ln[1] = ln[REGEX_MAX - 1];
  2096. ln[REGEX_MAX - 1] = '\0';
  2097. len = mbstowcs(wln, ln, REGEX_MAX);
  2098. }
  2099. }
  2100. /* Go to the top, we don't know if the hovered file will match the filter */
  2101. cur = 0;
  2102. if (matches(pln) != -1)
  2103. redraw(path);
  2104. showfilter(ln);
  2105. continue;
  2106. #ifndef NOMOUSE
  2107. case KEY_MOUSE: // fallthrough
  2108. #endif
  2109. case 27: /* Exit filter mode on Escape */
  2110. goto end;
  2111. }
  2112. if (r != OK) /* Handle Fn keys in main loop */
  2113. break;
  2114. /* Handle all control chars in main loop */
  2115. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^' && *ch != '^')
  2116. goto end;
  2117. if (len == 1) {
  2118. if (*ch == '?') /* Help and config key, '?' is an invalid regex */
  2119. goto end;
  2120. if (cfg.filtermode) {
  2121. switch (*ch) {
  2122. case '\'': // fallthrough /* Go to first non-dir file */
  2123. case '+': // fallthrough /* Toggle proceed on open */
  2124. case ',': // fallthrough /* Pin CWD */
  2125. case '-': // fallthrough /* Visit last visited dir */
  2126. case '.': // fallthrough /* Show hidden files */
  2127. case ';': // fallthrough /* Run plugin key */
  2128. case '=': // fallthrough /* Launch app */
  2129. case '@': // fallthrough /* Visit start dir */
  2130. case ']': // fallthorugh /* Prompt key */
  2131. case '`': // fallthrough /* Visit / */
  2132. case '~': /* Go HOME */
  2133. goto end;
  2134. }
  2135. }
  2136. /* Toggle case-sensitivity */
  2137. if (*ch == CASE) {
  2138. fnstrstr = (fnstrstr == &strcasestr) ? &strstr : &strcasestr;
  2139. #ifdef PCRE
  2140. pcreflags ^= PCRE_CASELESS;
  2141. #else
  2142. regflags ^= REG_ICASE;
  2143. #endif
  2144. showfilter(ln);
  2145. continue;
  2146. }
  2147. /* toggle string or regex filter */
  2148. if (*ch == FILTER) {
  2149. wln[0] = ln[0] = (ln[0] == FILTER) ? RFILTER : FILTER;
  2150. cfg.regex ^= 1;
  2151. filterfn = (filterfn == &visible_str) ? &visible_re : &visible_str;
  2152. showfilter(ln);
  2153. continue;
  2154. }
  2155. }
  2156. /* Reset cur in case it's a repeat search */
  2157. if (len == 1)
  2158. cur = 0;
  2159. if (len == REGEX_MAX - 1)
  2160. break;
  2161. wln[len] = (wchar_t)*ch;
  2162. wln[++len] = '\0';
  2163. wcstombs(ln, wln, REGEX_MAX);
  2164. /* Forward-filtering optimization:
  2165. * - new matches can only be a subset of current matches.
  2166. */
  2167. /* ndents = total; */
  2168. if (matches(pln) == -1) {
  2169. showfilter(ln);
  2170. continue;
  2171. }
  2172. /* If the only match is a dir, auto-select and cd into it */
  2173. if (ndents == 1 && cfg.filtermode
  2174. && cfg.autoselect && (dents[0].flags & DIR_OR_LINK_TO_DIR)) {
  2175. *ch = KEY_ENTER;
  2176. cur = 0;
  2177. goto end;
  2178. }
  2179. /*
  2180. * redraw() should be above the auto-select optimization, for
  2181. * the case where there's an issue with dir auto-select, say,
  2182. * due to a permission problem. The transition is _jumpy_ in
  2183. * case of such an error. However, we optimize for successful
  2184. * cases where the dir has permissions. This skips a redraw().
  2185. */
  2186. redraw(path);
  2187. showfilter(ln);
  2188. }
  2189. end:
  2190. clearinfoln();
  2191. /* Save last working filter in-filter */
  2192. if (ln[1])
  2193. ln[REGEX_MAX - 1] = ln[1];
  2194. if (*ch != 27 && *ch != '\t' && *ch != KEY_UP && *ch != KEY_DOWN && *ch != CONTROL('T')) {
  2195. ln[0] = ln[1] = '\0';
  2196. move_cursor(cur, 0);
  2197. }
  2198. /* Save current */
  2199. if (ndents)
  2200. copycurname();
  2201. curs_set(FALSE);
  2202. settimeout();
  2203. /* Return keys for navigation etc. */
  2204. return *ch;
  2205. }
  2206. /* Show a prompt with input string and return the changes */
  2207. static char *xreadline(const char *prefill, const char *prompt)
  2208. {
  2209. size_t len, pos;
  2210. int x, r;
  2211. const int WCHAR_T_WIDTH = sizeof(wchar_t);
  2212. wint_t ch[2] = {0};
  2213. wchar_t * const buf = malloc(sizeof(wchar_t) * READLINE_MAX);
  2214. if (!buf)
  2215. errexit();
  2216. cleartimeout();
  2217. printprompt(prompt);
  2218. if (prefill) {
  2219. DPRINTF_S(prefill);
  2220. len = pos = mbstowcs(buf, prefill, READLINE_MAX);
  2221. } else
  2222. len = (size_t)-1;
  2223. if (len == (size_t)-1) {
  2224. buf[0] = '\0';
  2225. len = pos = 0;
  2226. }
  2227. x = getcurx(stdscr);
  2228. curs_set(TRUE);
  2229. while (1) {
  2230. buf[len] = ' ';
  2231. mvaddnwstr(xlines - 1, x, buf, len + 1);
  2232. move(xlines - 1, x + wcswidth(buf, pos));
  2233. r = get_wch(ch);
  2234. if (r == ERR)
  2235. continue;
  2236. if (r == OK) {
  2237. switch (*ch) {
  2238. case KEY_ENTER: // fallthrough
  2239. case '\n': // fallthrough
  2240. case '\r':
  2241. goto END;
  2242. case CONTROL('D'):
  2243. if (pos < len)
  2244. ++pos;
  2245. else if (!(pos || len)) { /* Exit on ^D at empty prompt */
  2246. len = 0;
  2247. goto END;
  2248. } else
  2249. continue;
  2250. // fallthrough
  2251. case 127: // fallthrough
  2252. case '\b': /* rhel25 sends '\b' for backspace */
  2253. if (pos > 0) {
  2254. memmove(buf + pos - 1, buf + pos,
  2255. (len - pos) * WCHAR_T_WIDTH);
  2256. --len, --pos;
  2257. } // fallthrough
  2258. case '\t': /* TAB breaks cursor position, ignore it */
  2259. continue;
  2260. case CONTROL('F'):
  2261. if (pos < len)
  2262. ++pos;
  2263. continue;
  2264. case CONTROL('B'):
  2265. if (pos > 0)
  2266. --pos;
  2267. continue;
  2268. case CONTROL('W'):
  2269. printprompt(prompt);
  2270. do {
  2271. if (pos == 0)
  2272. break;
  2273. memmove(buf + pos - 1, buf + pos,
  2274. (len - pos) * WCHAR_T_WIDTH);
  2275. --pos, --len;
  2276. } while (buf[pos - 1] != ' ' && buf[pos - 1] != '/'); // NOLINT
  2277. continue;
  2278. case CONTROL('K'):
  2279. printprompt(prompt);
  2280. len = pos;
  2281. continue;
  2282. case CONTROL('L'):
  2283. printprompt(prompt);
  2284. len = pos = 0;
  2285. continue;
  2286. case CONTROL('A'):
  2287. pos = 0;
  2288. continue;
  2289. case CONTROL('E'):
  2290. pos = len;
  2291. continue;
  2292. case CONTROL('U'):
  2293. printprompt(prompt);
  2294. memmove(buf, buf + pos, (len - pos) * WCHAR_T_WIDTH);
  2295. len -= pos;
  2296. pos = 0;
  2297. continue;
  2298. case 27: /* Exit prompt on Escape */
  2299. len = 0;
  2300. goto END;
  2301. }
  2302. /* Filter out all other control chars */
  2303. if (*ch < ASCII_MAX && keyname(*ch)[0] == '^')
  2304. continue;
  2305. if (pos < READLINE_MAX - 1) {
  2306. memmove(buf + pos + 1, buf + pos,
  2307. (len - pos) * WCHAR_T_WIDTH);
  2308. buf[pos] = *ch;
  2309. ++len, ++pos;
  2310. continue;
  2311. }
  2312. } else {
  2313. switch (*ch) {
  2314. #ifdef KEY_RESIZE
  2315. case KEY_RESIZE:
  2316. clearoldprompt();
  2317. xlines = LINES;
  2318. printprompt(prompt);
  2319. break;
  2320. #endif
  2321. case KEY_LEFT:
  2322. if (pos > 0)
  2323. --pos;
  2324. break;
  2325. case KEY_RIGHT:
  2326. if (pos < len)
  2327. ++pos;
  2328. break;
  2329. case KEY_BACKSPACE:
  2330. if (pos > 0) {
  2331. memmove(buf + pos - 1, buf + pos,
  2332. (len - pos) * WCHAR_T_WIDTH);
  2333. --len, --pos;
  2334. }
  2335. break;
  2336. case KEY_DC:
  2337. if (pos < len) {
  2338. memmove(buf + pos, buf + pos + 1,
  2339. (len - pos - 1) * WCHAR_T_WIDTH);
  2340. --len;
  2341. }
  2342. break;
  2343. case KEY_END:
  2344. pos = len;
  2345. break;
  2346. case KEY_HOME:
  2347. pos = 0;
  2348. break;
  2349. default:
  2350. break;
  2351. }
  2352. }
  2353. }
  2354. END:
  2355. curs_set(FALSE);
  2356. settimeout();
  2357. clearprompt();
  2358. buf[len] = '\0';
  2359. pos = wcstombs(g_buf, buf, READLINE_MAX - 1);
  2360. if (pos >= READLINE_MAX - 1)
  2361. g_buf[READLINE_MAX - 1] = '\0';
  2362. free(buf);
  2363. return g_buf;
  2364. }
  2365. #ifndef NORL
  2366. /*
  2367. * Caller should check the value of presel to confirm if it needs to wait to show warning
  2368. */
  2369. static char *getreadline(const char *prompt, char *path, char *curpath, int *presel)
  2370. {
  2371. /* Switch to current path for readline(3) */
  2372. if (chdir(path) == -1) {
  2373. printwarn(presel);
  2374. return NULL;
  2375. }
  2376. exitcurses();
  2377. char *input = readline(prompt);
  2378. refresh();
  2379. if (chdir(curpath) == -1)
  2380. printwarn(presel);
  2381. else if (input && input[0]) {
  2382. add_history(input);
  2383. xstrlcpy(g_buf, input, CMD_LEN_MAX);
  2384. free(input);
  2385. return g_buf;
  2386. }
  2387. free(input);
  2388. return NULL;
  2389. }
  2390. #endif
  2391. /*
  2392. * Updates out with "dir/name or "/name"
  2393. * Returns the number of bytes copied including the terminating NULL byte
  2394. */
  2395. static size_t mkpath(const char *dir, const char *name, char *out)
  2396. {
  2397. size_t len;
  2398. /* Handle absolute path */
  2399. if (name[0] == '/')
  2400. return xstrlcpy(out, name, PATH_MAX);
  2401. /* Handle root case */
  2402. if (istopdir(dir))
  2403. len = 1;
  2404. else
  2405. len = xstrlcpy(out, dir, PATH_MAX);
  2406. out[len - 1] = '/'; // NOLINT
  2407. return (xstrlcpy(out + len, name, PATH_MAX - len) + len);
  2408. }
  2409. /*
  2410. * Create symbolic/hard link(s) to file(s) in selection list
  2411. * Returns the number of links created, -1 on error
  2412. */
  2413. static int xlink(char *prefix, char *path, char *curfname, char *buf, int *presel, int type)
  2414. {
  2415. int count = 0, choice;
  2416. char *psel = pselbuf, *fname;
  2417. size_t pos = 0, len, r;
  2418. int (*link_fn)(const char *, const char *) = NULL;
  2419. char lnpath[PATH_MAX];
  2420. choice = get_cur_or_sel();
  2421. if (!choice)
  2422. return -1;
  2423. if (type == 's') /* symbolic link */
  2424. link_fn = &symlink;
  2425. else /* hard link */
  2426. link_fn = &link;
  2427. if (choice == 'c') {
  2428. r = xstrlcpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
  2429. xstrlcpy(buf + r - 1, curfname, NAME_MAX - r); /* Suffix target file name */
  2430. mkpath(path, buf, lnpath); /* Generate link path */
  2431. mkpath(path, curfname, buf); /* Generate target file path */
  2432. if (!link_fn(buf, lnpath))
  2433. return 1; /* One link created */
  2434. printwarn(presel);
  2435. return -1;
  2436. }
  2437. while (pos < selbufpos) {
  2438. len = strlen(psel);
  2439. fname = xbasename(psel);
  2440. r = xstrlcpy(buf, prefix, NAME_MAX + 1); /* Copy prefix */
  2441. xstrlcpy(buf + r - 1, fname, NAME_MAX - r); /* Suffix target file name */
  2442. mkpath(path, buf, lnpath); /* Generate link path */
  2443. if (!link_fn(psel, lnpath))
  2444. ++count;
  2445. pos += len + 1;
  2446. psel += len + 1;
  2447. }
  2448. return count;
  2449. }
  2450. static bool parsekvpair(kv **arr, char **envcpy, const uchar id, ushort *items)
  2451. {
  2452. uint maxitems = 0, i = 0;
  2453. char *nextkey;
  2454. char *ptr = getenv(env_cfg[id]);
  2455. kv *kvarr;
  2456. if (!ptr || !*ptr)
  2457. return TRUE;
  2458. nextkey = ptr;
  2459. while (*nextkey) {
  2460. if (*nextkey == ':')
  2461. ++maxitems;
  2462. ++nextkey;
  2463. }
  2464. if (!maxitems)
  2465. return FALSE;
  2466. *arr = calloc(maxitems, sizeof(kv));
  2467. if (!arr) {
  2468. xerror();
  2469. return FALSE;
  2470. }
  2471. kvarr = *arr;
  2472. *envcpy = strdup(ptr);
  2473. if (!*envcpy) {
  2474. xerror();
  2475. return FALSE;
  2476. }
  2477. if (nextkey - ptr > 1) {
  2478. --nextkey;
  2479. /* Clear trailing ; or / */
  2480. if (*nextkey == ';' || (*nextkey == '/' && *(nextkey - 1) != ':'))
  2481. *(*envcpy + (nextkey - ptr)) = '\0';
  2482. }
  2483. ptr = *envcpy;
  2484. nextkey = ptr;
  2485. while (*ptr && i < maxitems) {
  2486. if (ptr == nextkey) {
  2487. kvarr[i].key = *ptr;
  2488. if (*++ptr != ':')
  2489. return FALSE;
  2490. if (*++ptr == '\0')
  2491. return FALSE;
  2492. if (*ptr == ';') /* Empty location */
  2493. return FALSE;
  2494. kvarr[i].val = ptr;
  2495. ++i;
  2496. }
  2497. if (*ptr == ';') {
  2498. /* Remove trailing space */
  2499. if (i > 0 && *(ptr - 1) == '/')
  2500. *(ptr - 1) = '\0';
  2501. *ptr = '\0';
  2502. nextkey = ptr + 1;
  2503. }
  2504. ++ptr;
  2505. }
  2506. maxitems = i;
  2507. if (kvarr[i - 1].val && *kvarr[i - 1].val == '\0')
  2508. return FALSE;
  2509. for (i = 0; i < maxitems && kvarr[i].key; ++i)
  2510. if (strlen(kvarr[i].val) >= PATH_MAX)
  2511. return FALSE;
  2512. *items = maxitems;
  2513. return TRUE;
  2514. }
  2515. /*
  2516. * Get the value corresponding to a key
  2517. *
  2518. * NULL is returned in case of no match, path resolution failure etc.
  2519. * buf would be modified, so check return value before access
  2520. */
  2521. static char *get_kv_val(kv *kvarr, char *buf, int key, uchar max, bool path)
  2522. {
  2523. int r = 0;
  2524. if (!kvarr)
  2525. return NULL;
  2526. for (; kvarr[r].key && r < max; ++r) {
  2527. if (kvarr[r].key == key) {
  2528. if (!path)
  2529. return kvarr[r].val;
  2530. if (kvarr[r].val[0] == '~') {
  2531. ssize_t len = strlen(home);
  2532. ssize_t loclen = strlen(kvarr[r].val);
  2533. if (!buf) {
  2534. buf = (char *)malloc(len + loclen);
  2535. if (!buf) {
  2536. DPRINTF_S(strerror(errno));
  2537. return NULL;
  2538. }
  2539. }
  2540. xstrlcpy(buf, home, len + 1);
  2541. xstrlcpy(buf + len, kvarr[r].val + 1, loclen);
  2542. return buf;
  2543. }
  2544. return realpath(kvarr[r].val, buf);
  2545. }
  2546. }
  2547. DPRINTF_S("Invalid key");
  2548. return NULL;
  2549. }
  2550. static void resetdircolor(int flags)
  2551. {
  2552. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  2553. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2554. cfg.dircolor = 0;
  2555. }
  2556. }
  2557. /*
  2558. * Replace escape characters in a string with '?'
  2559. * Adjust string length to maxcols if > 0;
  2560. * Max supported str length: NAME_MAX;
  2561. */
  2562. static wchar_t *unescape(const char *str, uint maxcols)
  2563. {
  2564. wchar_t * const wbuf = (wchar_t *)g_buf;
  2565. wchar_t *buf = wbuf;
  2566. size_t lencount = 0;
  2567. #ifdef NOLOCALE
  2568. memset(wbuf, 0, sizeof(NAME_MAX + 1) * sizeof(wchar_t));
  2569. #endif
  2570. /* Convert multi-byte to wide char */
  2571. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  2572. len = wcswidth(wbuf, len);
  2573. /* Reduce number of wide chars to max columns */
  2574. if (len > maxcols) {
  2575. while (*buf && lencount <= maxcols) {
  2576. if (*buf <= '\x1f' || *buf == '\x7f')
  2577. *buf = '\?';
  2578. ++buf;
  2579. ++lencount;
  2580. }
  2581. lencount = maxcols + 1;
  2582. /* Reduce wide chars one by one till it fits */
  2583. do
  2584. len = wcswidth(wbuf, --lencount);
  2585. while (len > maxcols);
  2586. wbuf[lencount] = L'\0';
  2587. } else {
  2588. do /* We do not expect a NULL string */
  2589. if (*buf <= '\x1f' || *buf == '\x7f')
  2590. *buf = '\?';
  2591. while (*++buf);
  2592. }
  2593. return wbuf;
  2594. }
  2595. static char *coolsize(off_t size)
  2596. {
  2597. const char * const U = "BKMGTPEZY";
  2598. static char size_buf[12]; /* Buffer to hold human readable size */
  2599. off_t rem = 0;
  2600. size_t ret;
  2601. int i = 0;
  2602. while (size >= 1024) {
  2603. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  2604. size >>= 10;
  2605. ++i;
  2606. }
  2607. if (i == 1) {
  2608. rem = (rem * 1000) >> 10;
  2609. rem /= 10;
  2610. if (rem % 10 >= 5) {
  2611. rem = (rem / 10) + 1;
  2612. if (rem == 10) {
  2613. ++size;
  2614. rem = 0;
  2615. }
  2616. } else
  2617. rem /= 10;
  2618. } else if (i == 2) {
  2619. rem = (rem * 1000) >> 10;
  2620. if (rem % 10 >= 5) {
  2621. rem = (rem / 10) + 1;
  2622. if (rem == 100) {
  2623. ++size;
  2624. rem = 0;
  2625. }
  2626. } else
  2627. rem /= 10;
  2628. } else if (i > 0) {
  2629. rem = (rem * 10000) >> 10;
  2630. if (rem % 10 >= 5) {
  2631. rem = (rem / 10) + 1;
  2632. if (rem == 1000) {
  2633. ++size;
  2634. rem = 0;
  2635. }
  2636. } else
  2637. rem /= 10;
  2638. }
  2639. if (i > 0 && i < 6 && rem) {
  2640. ret = xstrlcpy(size_buf, xitoa(size), 12);
  2641. size_buf[ret - 1] = '.';
  2642. char *frac = xitoa(rem);
  2643. size_t toprint = i > 3 ? 3 : i;
  2644. size_t len = strlen(frac);
  2645. if (len < toprint) {
  2646. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  2647. xstrlcpy(size_buf + ret + (toprint - len), frac, len + 1);
  2648. } else
  2649. xstrlcpy(size_buf + ret, frac, toprint + 1);
  2650. ret += toprint;
  2651. } else {
  2652. ret = xstrlcpy(size_buf, size ? xitoa(size) : "0", 12);
  2653. --ret;
  2654. }
  2655. size_buf[ret] = U[i];
  2656. size_buf[ret + 1] = '\0';
  2657. return size_buf;
  2658. }
  2659. static char get_ind(mode_t mode, bool perms)
  2660. {
  2661. switch (mode & S_IFMT) {
  2662. case S_IFREG:
  2663. if (perms)
  2664. return '-';
  2665. if (mode & 0100)
  2666. return '*';
  2667. return '\0';
  2668. case S_IFDIR:
  2669. return perms ? 'd' : '\0';
  2670. case S_IFLNK:
  2671. return perms ? 'l' : '@';
  2672. case S_IFSOCK:
  2673. return perms ? 's' : '=';
  2674. case S_IFIFO:
  2675. return perms ? 'p' : '|';
  2676. case S_IFBLK:
  2677. return perms ? 'b' : '\0';
  2678. case S_IFCHR:
  2679. return perms ? 'c' : '\0';
  2680. default:
  2681. return '?';
  2682. }
  2683. }
  2684. /* Convert a mode field into "ls -l" type perms field. */
  2685. static char *get_lsperms(mode_t mode)
  2686. {
  2687. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  2688. static char bits[11] = {'\0'};
  2689. bits[0] = get_ind(mode, TRUE);
  2690. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  2691. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  2692. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  2693. if (mode & S_ISUID)
  2694. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  2695. if (mode & S_ISGID)
  2696. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  2697. if (mode & S_ISVTX)
  2698. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  2699. return bits;
  2700. }
  2701. static void print_time(const time_t *timep)
  2702. {
  2703. struct tm *t = localtime(timep);
  2704. printw("%d-%02d-%02d %02d:%02d",
  2705. t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min);
  2706. }
  2707. static void printent(const struct entry *ent, uint namecols, bool sel)
  2708. {
  2709. char ind = get_ind(ent->mode, FALSE);
  2710. int attrs = sel ? A_REVERSE : 0;
  2711. if (ind == '@' || (ent->flags & HARD_LINK))
  2712. attrs |= A_DIM;
  2713. if (!ind)
  2714. ++namecols;
  2715. /* Directories are always shown on top */
  2716. resetdircolor(ent->flags);
  2717. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2718. if (attrs)
  2719. attron(attrs);
  2720. addwstr(unescape(ent->name, namecols));
  2721. if (attrs)
  2722. attroff(attrs);
  2723. if (ind)
  2724. addch(ind);
  2725. addch('\n');
  2726. }
  2727. static void printent_long(const struct entry *ent, uint namecols, bool sel)
  2728. {
  2729. bool ln = FALSE;
  2730. char ind1 = '\0', ind2 = '\0';
  2731. int attrs = sel ? A_REVERSE : 0;
  2732. uint len;
  2733. char *size;
  2734. /* Directories are always shown on top */
  2735. resetdircolor(ent->flags);
  2736. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2737. if (attrs)
  2738. attron(attrs);
  2739. /* Timestamp */
  2740. print_time(&ent->t);
  2741. addstr(" ");
  2742. /* Permissions */
  2743. addch('0' + ((ent->mode >> 6) & 7));
  2744. addch('0' + ((ent->mode >> 3) & 7));
  2745. addch('0' + (ent->mode & 7));
  2746. switch (ent->mode & S_IFMT) {
  2747. case S_IFREG:
  2748. if (ent->flags & HARD_LINK)
  2749. ln = TRUE;
  2750. if (ent->mode & 0100)
  2751. ind2 = '*';
  2752. // fallthrough
  2753. case S_IFDIR:
  2754. if (!ind2) /* Add a column if end indicator is not needed */
  2755. ++namecols;
  2756. size = coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size);
  2757. len = 10 - (uint)strlen(size);
  2758. while (--len)
  2759. addch(' ');
  2760. addstr(size);
  2761. break;
  2762. case S_IFLNK:
  2763. ln = TRUE;
  2764. ind1 = ind2 = '@'; // fallthrough
  2765. case S_IFSOCK:
  2766. if (!ind1)
  2767. ind1 = ind2 = '='; // fallthrough
  2768. case S_IFIFO:
  2769. if (!ind1)
  2770. ind1 = ind2 = '|'; // fallthrough
  2771. case S_IFBLK:
  2772. if (!ind1)
  2773. ind1 = 'b'; // fallthrough
  2774. case S_IFCHR:
  2775. if (!ind1)
  2776. ind1 = 'c'; // fallthrough
  2777. default:
  2778. if (!ind1)
  2779. ind1 = ind2 = '?';
  2780. addstr(" ");
  2781. addch(ind1);
  2782. break;
  2783. }
  2784. addstr(" ");
  2785. if (ln) {
  2786. attron(A_DIM);
  2787. attrs |= A_DIM;
  2788. }
  2789. addwstr(unescape(ent->name, namecols));
  2790. if (attrs)
  2791. attroff(attrs);
  2792. if (ind2)
  2793. addch(ind2);
  2794. addch('\n');
  2795. }
  2796. static void (*printptr)(const struct entry *ent, uint namecols, bool sel) = &printent;
  2797. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2798. {
  2799. settings cfg = *curcfg;
  2800. bool selmode = cfg.selmode ? TRUE : FALSE;
  2801. /* Save current context */
  2802. xstrlcpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2803. g_ctx[cfg.curctx].c_cfg = cfg;
  2804. if (g_ctx[r].c_cfg.ctxactive) { /* Switch to saved context */
  2805. /* Switch light/detail mode */
  2806. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  2807. /* set the reverse */
  2808. printptr = cfg.showdetail ? &printent : &printent_long;
  2809. cfg = g_ctx[r].c_cfg;
  2810. } else { /* Setup a new context from current context */
  2811. g_ctx[r].c_cfg.ctxactive = 1;
  2812. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2813. g_ctx[r].c_last[0] = '\0';
  2814. g_ctx[r].c_name[0] = '\0';
  2815. g_ctx[r].c_fltr[0] = g_ctx[r].c_fltr[1] = '\0';
  2816. g_ctx[r].c_cfg = cfg;
  2817. g_ctx[r].c_cfg.runplugin = 0;
  2818. }
  2819. /* Continue selection mode */
  2820. cfg.selmode = selmode;
  2821. cfg.curctx = r;
  2822. *curcfg = cfg;
  2823. }
  2824. static void save_session(bool last_session, int *presel)
  2825. {
  2826. char spath[PATH_MAX];
  2827. int i;
  2828. session_header_t header;
  2829. FILE *fsession;
  2830. char *sname;
  2831. bool status = FALSE;
  2832. memset(&header, 0, sizeof(session_header_t));
  2833. header.ver = SESSIONS_VERSION;
  2834. for (i = 0; i < CTX_MAX; ++i) {
  2835. if (g_ctx[i].c_cfg.ctxactive) {
  2836. if (cfg.curctx == i && ndents)
  2837. /* Update current file name, arrows don't update it */
  2838. xstrlcpy(g_ctx[i].c_name, dents[cur].name, NAME_MAX + 1);
  2839. header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
  2840. header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
  2841. header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
  2842. header.fltrln[i] = strnlen(g_ctx[i].c_fltr, REGEX_MAX) + 1;
  2843. }
  2844. }
  2845. sname = !last_session ? xreadline(NULL, messages[MSG_SSN_NAME]) : "@";
  2846. if (!sname[0])
  2847. return;
  2848. mkpath(sessiondir, sname, spath);
  2849. fsession = fopen(spath, "wb");
  2850. if (!fsession) {
  2851. printwait(messages[MSG_ACCESS], presel);
  2852. return;
  2853. }
  2854. if ((fwrite(&header, sizeof(header), 1, fsession) != 1)
  2855. || (fwrite(&cfg, sizeof(cfg), 1, fsession) != 1))
  2856. goto END;
  2857. for (i = 0; i < CTX_MAX; ++i)
  2858. if ((fwrite(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2859. || (fwrite(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2860. || (header.nameln[i] > 0
  2861. && fwrite(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2862. || (header.lastln[i] > 0
  2863. && fwrite(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2864. || (header.fltrln[i] > 0
  2865. && fwrite(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2866. || (header.pathln[i] > 0
  2867. && fwrite(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2868. goto END;
  2869. status = TRUE;
  2870. END:
  2871. fclose(fsession);
  2872. if (!status)
  2873. printwait(messages[MSG_FAILED], presel);
  2874. }
  2875. static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
  2876. {
  2877. char spath[PATH_MAX];
  2878. int i = 0;
  2879. session_header_t header;
  2880. FILE *fsession;
  2881. bool has_loaded_dynamically = !(sname || restore);
  2882. bool status = FALSE;
  2883. if (!restore) {
  2884. sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
  2885. if (!sname[0])
  2886. return FALSE;
  2887. mkpath(sessiondir, sname, spath);
  2888. } else
  2889. mkpath(sessiondir, "@", spath);
  2890. if (has_loaded_dynamically)
  2891. save_session(TRUE, NULL);
  2892. fsession = fopen(spath, "rb");
  2893. if (!fsession) {
  2894. printmsg(messages[MSG_ACCESS]);
  2895. xdelay(XDELAY_INTERVAL_MS);
  2896. return FALSE;
  2897. }
  2898. if ((fread(&header, sizeof(header), 1, fsession) != 1)
  2899. || (header.ver != SESSIONS_VERSION)
  2900. || (fread(&cfg, sizeof(cfg), 1, fsession) != 1))
  2901. goto END;
  2902. g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
  2903. = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  2904. for (; i < CTX_MAX; ++i)
  2905. if ((fread(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2906. || (fread(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2907. || (header.nameln[i] > 0
  2908. && fread(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2909. || (header.lastln[i] > 0
  2910. && fread(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2911. || (header.fltrln[i] > 0
  2912. && fread(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2913. || (header.pathln[i] > 0
  2914. && fread(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2915. goto END;
  2916. *path = g_ctx[cfg.curctx].c_path;
  2917. *lastdir = g_ctx[cfg.curctx].c_last;
  2918. *lastname = g_ctx[cfg.curctx].c_name;
  2919. printptr = cfg.showdetail ? &printent_long : &printent;
  2920. status = TRUE;
  2921. END:
  2922. fclose(fsession);
  2923. if (!status) {
  2924. printmsg(messages[MSG_FAILED]);
  2925. xdelay(XDELAY_INTERVAL_MS);
  2926. } else if (restore)
  2927. unlink(spath);
  2928. return status;
  2929. }
  2930. /*
  2931. * Gets only a single line (that's what we need
  2932. * for now) or shows full command output in pager.
  2933. *
  2934. * If page is valid, returns NULL
  2935. */
  2936. static char *get_output(char *buf, const size_t bytes, const char *file,
  2937. const char *arg1, const char *arg2, const bool page)
  2938. {
  2939. pid_t pid;
  2940. int pipefd[2];
  2941. FILE *pf;
  2942. int tmp, flags;
  2943. char *ret = NULL;
  2944. if (pipe(pipefd) == -1)
  2945. errexit();
  2946. for (tmp = 0; tmp < 2; ++tmp) {
  2947. /* Get previous flags */
  2948. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2949. /* Set bit for non-blocking flag */
  2950. flags |= O_NONBLOCK;
  2951. /* Change flags on fd */
  2952. fcntl(pipefd[tmp], F_SETFL, flags);
  2953. }
  2954. pid = fork();
  2955. if (pid == 0) {
  2956. /* In child */
  2957. close(pipefd[0]);
  2958. dup2(pipefd[1], STDOUT_FILENO);
  2959. dup2(pipefd[1], STDERR_FILENO);
  2960. close(pipefd[1]);
  2961. execlp(file, file, arg1, arg2, NULL);
  2962. _exit(1);
  2963. }
  2964. /* In parent */
  2965. waitpid(pid, &tmp, 0);
  2966. close(pipefd[1]);
  2967. if (!page) {
  2968. pf = fdopen(pipefd[0], "r");
  2969. if (pf) {
  2970. ret = fgets(buf, bytes, pf);
  2971. close(pipefd[0]);
  2972. }
  2973. return ret;
  2974. }
  2975. pid = fork();
  2976. if (pid == 0) {
  2977. /* Show in pager in child */
  2978. dup2(pipefd[0], STDIN_FILENO);
  2979. close(pipefd[0]);
  2980. spawn(pager, NULL, NULL, NULL, F_CLI);
  2981. _exit(1);
  2982. }
  2983. /* In parent */
  2984. waitpid(pid, &tmp, 0);
  2985. close(pipefd[0]);
  2986. return NULL;
  2987. }
  2988. static inline bool getutil(char *util)
  2989. {
  2990. return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
  2991. }
  2992. static void pipetof(char *cmd, FILE *fout)
  2993. {
  2994. FILE *fin = popen(cmd, "r");
  2995. if (fin) {
  2996. while (fgets(g_buf, CMD_LEN_MAX - 1, fin))
  2997. fprintf(fout, "%s", g_buf);
  2998. pclose(fin);
  2999. }
  3000. }
  3001. /*
  3002. * Follows the stat(1) output closely
  3003. */
  3004. static bool show_stats(const char *fpath, const struct stat *sb)
  3005. {
  3006. int fd;
  3007. FILE *fp;
  3008. char *p, *begin = g_buf;
  3009. size_t r;
  3010. fd = create_tmp_file();
  3011. if (fd == -1)
  3012. return FALSE;
  3013. r = xstrlcpy(g_buf, "stat \"", PATH_MAX);
  3014. r += xstrlcpy(g_buf + r - 1, fpath, PATH_MAX);
  3015. g_buf[r - 2] = '\"';
  3016. g_buf[r - 1] = '\0';
  3017. DPRINTF_S(g_buf);
  3018. fp = fdopen(fd, "w");
  3019. if (!fp) {
  3020. close(fd);
  3021. return FALSE;
  3022. }
  3023. pipetof(g_buf, fp);
  3024. if (S_ISREG(sb->st_mode)) {
  3025. /* Show file(1) output */
  3026. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  3027. if (p) {
  3028. fprintf(fp, "\n\n ");
  3029. while (*p) {
  3030. if (*p == ',') {
  3031. *p = '\0';
  3032. fprintf(fp, " %s\n", begin);
  3033. begin = p + 1;
  3034. }
  3035. ++p;
  3036. }
  3037. fprintf(fp, " %s\n ", begin);
  3038. /* Show the file mime type */
  3039. get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, fpath, FALSE);
  3040. fprintf(fp, "%s", g_buf);
  3041. }
  3042. }
  3043. fprintf(fp, "\n");
  3044. fclose(fp);
  3045. close(fd);
  3046. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3047. unlink(g_tmpfpath);
  3048. return TRUE;
  3049. }
  3050. static bool xchmod(const char *fpath, mode_t mode)
  3051. {
  3052. /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
  3053. (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
  3054. return (chmod(fpath, mode) == 0);
  3055. }
  3056. static size_t get_fs_info(const char *path, bool type)
  3057. {
  3058. struct statvfs svb;
  3059. if (statvfs(path, &svb) == -1)
  3060. return 0;
  3061. if (type == CAPACITY)
  3062. return svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
  3063. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  3064. }
  3065. /* List or extract archive */
  3066. static void handle_archive(char *fpath, const char *dir, char op)
  3067. {
  3068. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  3069. char *util;
  3070. if (getutil(utils[UTIL_ATOOL])) {
  3071. util = utils[UTIL_ATOOL];
  3072. arg[1] = op;
  3073. arg[2] = '\0';
  3074. } else if (getutil(utils[UTIL_BSDTAR])) {
  3075. util = utils[UTIL_BSDTAR];
  3076. if (op == 'x')
  3077. arg[1] = op;
  3078. } else if (is_suffix(fpath, ".zip")) {
  3079. util = utils[UTIL_UNZIP];
  3080. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  3081. arg[2] = '\0';
  3082. } else {
  3083. util = utils[UTIL_TAR];
  3084. if (op == 'x')
  3085. arg[1] = op;
  3086. }
  3087. if (op == 'x') { /* extract */
  3088. spawn(util, arg, fpath, dir, F_NORMAL);
  3089. } else { /* list */
  3090. exitcurses();
  3091. get_output(NULL, 0, util, arg, fpath, TRUE);
  3092. refresh();
  3093. }
  3094. }
  3095. static char *visit_parent(char *path, char *newpath, int *presel)
  3096. {
  3097. char *dir;
  3098. /* There is no going back */
  3099. if (istopdir(path)) {
  3100. /* Continue in navigate-as-you-type mode, if enabled */
  3101. if (cfg.filtermode)
  3102. *presel = FILTER;
  3103. return NULL;
  3104. }
  3105. /* Use a copy as dirname() may change the string passed */
  3106. xstrlcpy(newpath, path, PATH_MAX);
  3107. dir = dirname(newpath);
  3108. if (access(dir, R_OK) == -1) {
  3109. printwarn(presel);
  3110. return NULL;
  3111. }
  3112. return dir;
  3113. }
  3114. static void find_accessible_parent(char *path, char *newpath, char *lastname, int *presel)
  3115. {
  3116. char *dir;
  3117. /* Save history */
  3118. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  3119. xstrlcpy(newpath, path, PATH_MAX);
  3120. while (true) {
  3121. dir = visit_parent(path, newpath, presel);
  3122. if (istopdir(path) || istopdir(newpath)) {
  3123. if (!dir)
  3124. dir = dirname(newpath);
  3125. break;
  3126. }
  3127. if (!dir) {
  3128. xstrlcpy(path, newpath, PATH_MAX);
  3129. continue;
  3130. }
  3131. break;
  3132. }
  3133. xstrlcpy(path, dir, PATH_MAX);
  3134. printmsg(messages[MSG_ACCESS]);
  3135. xdelay(XDELAY_INTERVAL_MS);
  3136. }
  3137. /* Create non-existent parents and a file or dir */
  3138. static bool xmktree(char *path, bool dir)
  3139. {
  3140. char *p = path;
  3141. char *slash = path;
  3142. if (!p || !*p)
  3143. return FALSE;
  3144. /* Skip the first '/' */
  3145. ++p;
  3146. while (*p != '\0') {
  3147. if (*p == '/') {
  3148. slash = p;
  3149. *p = '\0';
  3150. } else {
  3151. ++p;
  3152. continue;
  3153. }
  3154. /* Create folder from path to '\0' inserted at p */
  3155. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3156. #ifdef __HAIKU__
  3157. // XDG_CONFIG_HOME contains a directory
  3158. // that is read-only, but the full path
  3159. // is writeable.
  3160. // Try to continue and see what happens.
  3161. // TODO: Find a more robust solution.
  3162. if (errno == B_READ_ONLY_DEVICE)
  3163. goto next;
  3164. #endif
  3165. DPRINTF_S("mkdir1!");
  3166. DPRINTF_S(strerror(errno));
  3167. *slash = '/';
  3168. return FALSE;
  3169. }
  3170. #ifdef __HAIKU__
  3171. next:
  3172. #endif
  3173. /* Restore path */
  3174. *slash = '/';
  3175. ++p;
  3176. }
  3177. if (dir) {
  3178. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3179. DPRINTF_S("mkdir2!");
  3180. DPRINTF_S(strerror(errno));
  3181. return FALSE;
  3182. }
  3183. } else {
  3184. int fd = open(path, O_CREAT, 0666);
  3185. if (fd == -1 && errno != EEXIST) {
  3186. DPRINTF_S("open!");
  3187. DPRINTF_S(strerror(errno));
  3188. return FALSE;
  3189. }
  3190. close(fd);
  3191. }
  3192. return TRUE;
  3193. }
  3194. static bool archive_mount(char *name, char *path, char *newpath, int *presel)
  3195. {
  3196. char *dir, *cmd = utils[UTIL_ARCHIVEMOUNT];
  3197. size_t len;
  3198. if (!getutil(cmd)) {
  3199. printwait(messages[MSG_UTIL_MISSING], presel);
  3200. return FALSE;
  3201. }
  3202. dir = strdup(name);
  3203. if (!dir)
  3204. return FALSE;
  3205. len = strlen(dir);
  3206. while (len > 1)
  3207. if (dir[--len] == '.') {
  3208. dir[len] = '\0';
  3209. break;
  3210. }
  3211. DPRINTF_S(dir);
  3212. /* Create the mount point */
  3213. mkpath(cfgdir, dir, newpath);
  3214. free(dir);
  3215. if (!xmktree(newpath, TRUE)) {
  3216. printwarn(presel);
  3217. return FALSE;
  3218. }
  3219. /* Mount archive */
  3220. DPRINTF_S(name);
  3221. DPRINTF_S(newpath);
  3222. if (spawn(cmd, name, newpath, path, F_NORMAL)) {
  3223. printwait(messages[MSG_FAILED], presel);
  3224. return FALSE;
  3225. }
  3226. return TRUE;
  3227. }
  3228. static bool remote_mount(char *newpath, int *presel)
  3229. {
  3230. uchar flag = F_CLI;
  3231. int opt;
  3232. char *tmp, *env, *cmd;
  3233. bool r, s;
  3234. r = getutil(utils[UTIL_RCLONE]);
  3235. s = getutil(utils[UTIL_SSHFS]);
  3236. if (!(r || s))
  3237. return FALSE;
  3238. if (r && s)
  3239. opt = get_input(messages[MSG_REMOTE_OPTS]);
  3240. else
  3241. opt = (!s) ? 'r' : 's';
  3242. if (opt == 's') {
  3243. cmd = utils[UTIL_SSHFS];
  3244. env = xgetenv("NNN_SSHFS", cmd);
  3245. } else if (opt == 'r') {
  3246. flag |= F_NOWAIT | F_NOTRACE;
  3247. cmd = utils[UTIL_RCLONE];
  3248. env = xgetenv("NNN_RCLONE", "rclone mount");
  3249. } else {
  3250. printwait(messages[MSG_INVALID_KEY], presel);
  3251. return FALSE;
  3252. }
  3253. if (!getutil(cmd)) {
  3254. printwait(messages[MSG_UTIL_MISSING], presel);
  3255. return FALSE;
  3256. }
  3257. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3258. if (!tmp[0])
  3259. return FALSE;
  3260. /* Create the mount point */
  3261. mkpath(cfgdir, tmp, newpath);
  3262. if (!xmktree(newpath, TRUE)) {
  3263. printwarn(presel);
  3264. return FALSE;
  3265. }
  3266. /* Convert "Host" to "Host:" */
  3267. size_t len = strlen(tmp);
  3268. if (tmp[len - 1] != ':') { /* Append ':' if missing */
  3269. tmp[len] = ':';
  3270. tmp[len + 1] = '\0';
  3271. }
  3272. /* Connect to remote */
  3273. if (opt == 's') {
  3274. if (spawn(env, tmp, newpath, NULL, flag)) {
  3275. printwait(messages[MSG_FAILED], presel);
  3276. return FALSE;
  3277. }
  3278. } else {
  3279. spawn(env, tmp, newpath, NULL, flag);
  3280. printmsg(messages[MSG_RCLONE_DELAY]);
  3281. xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
  3282. }
  3283. return TRUE;
  3284. }
  3285. /*
  3286. * Unmounts if the directory represented by name is a mount point.
  3287. * Otherwise, asks for hostname
  3288. */
  3289. static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
  3290. {
  3291. #ifdef __APPLE__
  3292. static char cmd[] = "umount";
  3293. #else
  3294. static char cmd[] = "fusermount3"; /* Arch Linux utility */
  3295. static bool found = FALSE;
  3296. #endif
  3297. char *tmp = name;
  3298. struct stat sb, psb;
  3299. bool child = FALSE;
  3300. bool parent = FALSE;
  3301. #ifndef __APPLE__
  3302. /* On Ubuntu it's fusermount */
  3303. if (!found && !getutil(cmd)) {
  3304. cmd[10] = '\0';
  3305. found = TRUE;
  3306. }
  3307. #endif
  3308. if (tmp && strcmp(cfgdir, currentpath) == 0) {
  3309. mkpath(cfgdir, tmp, newpath);
  3310. child = lstat(newpath, &sb) != -1;
  3311. parent = lstat(dirname(newpath), &psb) != -1;
  3312. if (!child && !parent) {
  3313. *presel = MSGWAIT;
  3314. return FALSE;
  3315. }
  3316. }
  3317. if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
  3318. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3319. if (!tmp[0])
  3320. return FALSE;
  3321. }
  3322. /* Create the mount point */
  3323. mkpath(cfgdir, tmp, newpath);
  3324. if (!xdiraccess(newpath)) {
  3325. *presel = MSGWAIT;
  3326. return FALSE;
  3327. }
  3328. #ifdef __APPLE__
  3329. if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
  3330. #else
  3331. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  3332. #endif
  3333. int r = get_input(messages[MSG_LAZY]);
  3334. if (!xconfirm(r))
  3335. return FALSE;
  3336. #ifdef __APPLE__
  3337. if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
  3338. #else
  3339. if (spawn(cmd, "-uz", newpath, NULL, F_NORMAL)) {
  3340. #endif
  3341. printwait(messages[MSG_FAILED], presel);
  3342. return FALSE;
  3343. }
  3344. }
  3345. return TRUE;
  3346. }
  3347. static void lock_terminal(void)
  3348. {
  3349. char *tmp = utils[UTIL_LOCKER];
  3350. if (!getutil(tmp))
  3351. tmp = utils[UTIL_CMATRIX];
  3352. spawn(tmp, NULL, NULL, NULL, F_NORMAL);
  3353. }
  3354. static void printkv(kv *kvarr, FILE *fp, uchar max)
  3355. {
  3356. uchar i = 0;
  3357. for (; i < max && kvarr[i].key; ++i)
  3358. fprintf(fp, " %c: %s\n", (char)kvarr[i].key, kvarr[i].val);
  3359. }
  3360. static void printkeys(kv *kvarr, char *buf, uchar max)
  3361. {
  3362. uchar i = 0;
  3363. for (; i < max && kvarr[i].key; ++i) {
  3364. buf[i << 1] = ' ';
  3365. buf[(i << 1) + 1] = kvarr[i].key;
  3366. }
  3367. buf[i << 1] = '\0';
  3368. }
  3369. /*
  3370. * The help string tokens (each line) start with a HEX value
  3371. * which indicates the number of spaces to print before the
  3372. * particular token. This method was chosen instead of a flat
  3373. * string because the number of bytes in help was increasing
  3374. * the binary size by around a hundred bytes. This would only
  3375. * have increased as we keep adding new options.
  3376. */
  3377. static void show_help(const char *path)
  3378. {
  3379. int i, fd;
  3380. FILE *fp;
  3381. const char *start, *end;
  3382. const char helpstr[] = {
  3383. "0\n"
  3384. "1NAVIGATION\n"
  3385. "9Up k Up%-16cPgUp ^U Scroll up\n"
  3386. "9Dn j Down%-14cPgDn ^D Scroll down\n"
  3387. "9Lt h Parent%-12c~ ` @ - HOME, /, start, last\n"
  3388. "5Ret Rt l Open%-20c' First file\n"
  3389. "9g ^A Top%-18c. F5 Toggle hidden\n"
  3390. "9G ^E End%-21c0 Lock terminal\n"
  3391. "9b ^/ Bookmark key%-12c, Pin CWD\n"
  3392. "a1-4 Context 1-4%-7c(Sh)Tab Cycle context\n"
  3393. "c/ Filter%-17c^N Nav-as-you-type toggle\n"
  3394. "aEsc Exit prompt%-12c^L Redraw/clear prompt\n"
  3395. "c? Help, conf%-14c+ Toggle proceed on open\n"
  3396. "cq Quit context%-11c^G QuitCD\n"
  3397. "b^Q Quit%-20cQ Quit with err\n"
  3398. "1FILES\n"
  3399. "9o ^O Open with...%-12cn Create new/link\n"
  3400. "9f ^F File details%-12cd Detail view toggle\n"
  3401. "b^R Rename/dup%-14cr Batch rename\n"
  3402. "cz Archive%-17ce Edit in EDITOR\n"
  3403. "5Space ^J (Un)select%-11cm ^K Mark range/clear\n"
  3404. "9p ^P Copy sel here%-11ca Select all\n"
  3405. "9v ^V Move sel here%-8cw ^W Copy/move sel as\n"
  3406. "9x ^X Delete%-18cE Edit sel\n"
  3407. "c* Toggle exe%-0c\n"
  3408. "1MISC\n"
  3409. "9; ^S Select plugin%-11c= Launch app\n"
  3410. "9! ^] Shell%-19c] Cmd prompt\n"
  3411. "cc Connect remote%-10cu Unmount\n"
  3412. "9t ^T Sort toggles%-12cs Manage session\n"
  3413. };
  3414. fd = create_tmp_file();
  3415. if (fd == -1)
  3416. return;
  3417. fp = fdopen(fd, "w");
  3418. if (!fp) {
  3419. close(fd);
  3420. return;
  3421. }
  3422. start = end = helpstr;
  3423. while (*end) {
  3424. if (*end == '\n') {
  3425. snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
  3426. xchartohex(*start), ' ', (int)(end - start), start + 1);
  3427. fprintf(fp, g_buf, ' ');
  3428. start = end + 1;
  3429. }
  3430. ++end;
  3431. }
  3432. fprintf(fp, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  3433. fprintf(fp, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  3434. if (bookmark) {
  3435. fprintf(fp, "BOOKMARKS\n");
  3436. printkv(bookmark, fp, maxbm);
  3437. fprintf(fp, "\n");
  3438. }
  3439. if (plug) {
  3440. fprintf(fp, "PLUGIN KEYS\n");
  3441. printkv(plug, fp, maxplug);
  3442. fprintf(fp, "\n");
  3443. }
  3444. for (i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  3445. start = getenv(env_cfg[i]);
  3446. if (start)
  3447. fprintf(fp, "%s: %s\n", env_cfg[i], start);
  3448. }
  3449. if (g_selpath)
  3450. fprintf(fp, "SELECTION FILE: %s\n", g_selpath);
  3451. fprintf(fp, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  3452. fclose(fp);
  3453. close(fd);
  3454. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3455. unlink(g_tmpfpath);
  3456. }
  3457. static bool run_cmd_as_plugin(const char *path, const char *file, char *newpath, char *runfile)
  3458. {
  3459. uchar flags = F_CLI | F_CONFIRM;
  3460. size_t len;
  3461. /* Get rid of preceding _ */
  3462. ++file;
  3463. if (!*file)
  3464. return FALSE;
  3465. /* Check if GUI flags are to be used */
  3466. if (*file == '|') {
  3467. flags = F_NOTRACE | F_NOWAIT;
  3468. ++file;
  3469. if (!*file)
  3470. return FALSE;
  3471. }
  3472. xstrlcpy(newpath, file, PATH_MAX);
  3473. len = strlen(newpath);
  3474. if (len > 1 && newpath[len - 1] == '*') {
  3475. flags &= ~F_CONFIRM; /* Skip user confirmation */
  3476. newpath[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
  3477. --len;
  3478. }
  3479. if (is_suffix(newpath, " $nnn")) {
  3480. /* Set `\0` to clear ' $nnn' suffix */
  3481. newpath[len - 5] = '\0';
  3482. } else
  3483. runfile = NULL;
  3484. spawn(newpath, runfile, NULL, path, flags);
  3485. return TRUE;
  3486. }
  3487. static bool plctrl_init(void)
  3488. {
  3489. snprintf(g_buf, CMD_LEN_MAX, "nnn-pipe.%d", getpid());
  3490. /* g_tmpfpath is used to generate tmp file names */
  3491. g_tmpfpath[g_tmpfplen - 1] = '\0';
  3492. mkpath(g_tmpfpath, g_buf, g_pipepath);
  3493. unlink(g_pipepath);
  3494. if (mkfifo(g_pipepath, 0600) != 0)
  3495. return _FAILURE;
  3496. setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
  3497. return _SUCCESS;
  3498. }
  3499. static bool run_selected_plugin(char **path, const char *file, char *newpath, char *runfile, char **lastname, char **lastdir)
  3500. {
  3501. int fd;
  3502. size_t len;
  3503. if (*file == '_')
  3504. return run_cmd_as_plugin(*path, file, newpath, runfile);
  3505. if (!(g_states & STATE_PLUGIN_INIT)) {
  3506. plctrl_init();
  3507. g_states |= STATE_PLUGIN_INIT;
  3508. }
  3509. fd = open(g_pipepath, O_RDONLY | O_NONBLOCK);
  3510. if (fd == -1)
  3511. return FALSE;
  3512. /* Generate absolute path to plugin */
  3513. mkpath(plugindir, file, newpath);
  3514. if (runfile && runfile[0]) {
  3515. xstrlcpy(*lastname, runfile, NAME_MAX);
  3516. spawn(newpath, *lastname, *path, *path, F_NORMAL);
  3517. } else
  3518. spawn(newpath, NULL, *path, *path, F_NORMAL);
  3519. len = read(fd, g_buf, PATH_MAX);
  3520. g_buf[len] = '\0';
  3521. close(fd);
  3522. if (len > 1) {
  3523. int ctx = g_buf[0] - '0';
  3524. if (ctx == 0 || ctx == cfg.curctx + 1) {
  3525. xstrlcpy(*lastdir, *path, PATH_MAX);
  3526. xstrlcpy(*path, g_buf + 1, PATH_MAX);
  3527. } else if (ctx >= 1 && ctx <= CTX_MAX) {
  3528. int r = ctx - 1;
  3529. g_ctx[r].c_cfg.ctxactive = 0;
  3530. savecurctx(&cfg, g_buf + 1, dents[cur].name, r);
  3531. *path = g_ctx[r].c_path;
  3532. *lastdir = g_ctx[r].c_last;
  3533. *lastname = g_ctx[r].c_name;
  3534. }
  3535. }
  3536. return TRUE;
  3537. }
  3538. static void plugscript(const char *plugin, char *newpath, uchar flags)
  3539. {
  3540. mkpath(plugindir, plugin, newpath);
  3541. if (!access(newpath, X_OK))
  3542. spawn(newpath, NULL, NULL, NULL, flags);
  3543. }
  3544. static void launch_app(const char *path, char *newpath)
  3545. {
  3546. int r = F_NORMAL;
  3547. char *tmp = newpath;
  3548. mkpath(plugindir, utils[UTIL_LAUNCH], newpath);
  3549. if (!(getutil(utils[UTIL_FZF]) || getutil(utils[UTIL_FZY])) || access(newpath, X_OK) < 0) {
  3550. tmp = xreadline(NULL, messages[MSG_APP_NAME]);
  3551. r = F_NOWAIT | F_NOTRACE | F_MULTI;
  3552. }
  3553. if (tmp && *tmp) // NOLINT
  3554. spawn(tmp, "0", NULL, path, r);
  3555. }
  3556. static int sum_bsize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3557. {
  3558. if (sb->st_blocks && (typeflag == FTW_D
  3559. || (typeflag == FTW_F && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))))
  3560. ent_blocks += sb->st_blocks;
  3561. ++num_files;
  3562. return 0;
  3563. }
  3564. static int sum_asize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3565. {
  3566. if (sb->st_size && (typeflag == FTW_D
  3567. || (typeflag == FTW_D && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))))
  3568. ent_blocks += sb->st_size;
  3569. ++num_files;
  3570. return 0;
  3571. }
  3572. static void dentfree(void)
  3573. {
  3574. free(pnamebuf);
  3575. free(dents);
  3576. }
  3577. static blkcnt_t dirwalk(char *path, struct stat *psb)
  3578. {
  3579. static uint open_max;
  3580. /* Increase current open file descriptor limit */
  3581. if (!open_max)
  3582. open_max = max_openfds();
  3583. ent_blocks = 0;
  3584. tolastln();
  3585. addstr(xbasename(path));
  3586. addstr(" [^C aborts]\n");
  3587. refresh();
  3588. if (nftw(path, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) < 0) {
  3589. DPRINTF_S("nftw failed");
  3590. return cfg.apparentsz ? psb->st_size : psb->st_blocks;
  3591. }
  3592. return ent_blocks;
  3593. }
  3594. /* Skip self and parent */
  3595. static bool selforparent(const char *path)
  3596. {
  3597. return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
  3598. }
  3599. static int dentfill(char *path, struct entry **dents)
  3600. {
  3601. int n = 0, count, flags = 0;
  3602. ulong num_saved;
  3603. struct dirent *dp;
  3604. char *namep, *pnb, *buf = NULL;
  3605. struct entry *dentp;
  3606. size_t off = 0, namebuflen = NAMEBUF_INCR;
  3607. struct stat sb_path, sb;
  3608. DIR *dirp = opendir(path);
  3609. if (!dirp)
  3610. return 0;
  3611. int fd = dirfd(dirp);
  3612. if (cfg.blkorder) {
  3613. num_files = 0;
  3614. dir_blocks = 0;
  3615. buf = (char *)alloca(strlen(path) + NAME_MAX + 2);
  3616. if (fstatat(fd, path, &sb_path, 0) == -1)
  3617. goto exit;
  3618. if (!ihashbmp) {
  3619. ihashbmp = calloc(1, HASH_OCTETS << 3);
  3620. if (!ihashbmp)
  3621. goto exit;
  3622. } else
  3623. clear_hash();
  3624. }
  3625. #if _POSIX_C_SOURCE >= 200112L
  3626. posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
  3627. #endif
  3628. dp = readdir(dirp);
  3629. if (!dp)
  3630. goto exit;
  3631. #if defined(__sun) || defined(__HAIKU__)
  3632. flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
  3633. #else
  3634. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  3635. /*
  3636. * Optimization added for filesystems which support dirent.d_type
  3637. * see readdir(3)
  3638. * Known drawbacks:
  3639. * - the symlink size is set to 0
  3640. * - the modification time of the symlink is set to that of the target file
  3641. */
  3642. flags = AT_SYMLINK_NOFOLLOW;
  3643. }
  3644. #endif
  3645. do {
  3646. namep = dp->d_name;
  3647. if (selforparent(namep))
  3648. continue;
  3649. if (!cfg.showhidden && namep[0] == '.') {
  3650. if (!cfg.blkorder)
  3651. continue;
  3652. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  3653. continue;
  3654. if (S_ISDIR(sb.st_mode)) {
  3655. if (sb_path.st_dev == sb.st_dev) {
  3656. mkpath(path, namep, buf);
  3657. dir_blocks += dirwalk(buf, &sb);
  3658. if (g_states & STATE_INTERRUPTED)
  3659. goto exit;
  3660. }
  3661. } else {
  3662. /* Do not recount hard links */
  3663. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3664. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3665. ++num_files;
  3666. }
  3667. continue;
  3668. }
  3669. if (fstatat(fd, namep, &sb, flags) == -1) {
  3670. /* List a symlink with target missing */
  3671. if (flags || (!flags && fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
  3672. DPRINTF_U(flags);
  3673. if (!flags) {
  3674. DPRINTF_S(namep);
  3675. DPRINTF_S(strerror(errno));
  3676. }
  3677. continue;
  3678. }
  3679. }
  3680. if (n == total_dents) {
  3681. total_dents += ENTRY_INCR;
  3682. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  3683. if (!*dents) {
  3684. free(pnamebuf);
  3685. closedir(dirp);
  3686. errexit();
  3687. }
  3688. DPRINTF_P(*dents);
  3689. }
  3690. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  3691. if (namebuflen - off < NAME_MAX + 1) {
  3692. namebuflen += NAMEBUF_INCR;
  3693. pnb = pnamebuf;
  3694. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  3695. if (!pnamebuf) {
  3696. free(*dents);
  3697. closedir(dirp);
  3698. errexit();
  3699. }
  3700. DPRINTF_P(pnamebuf);
  3701. /* realloc() may result in memory move, we must re-adjust if that happens */
  3702. if (pnb != pnamebuf) {
  3703. dentp = *dents;
  3704. dentp->name = pnamebuf;
  3705. for (count = 1; count < n; ++dentp, ++count)
  3706. /* Current filename starts at last filename start + length */
  3707. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  3708. }
  3709. }
  3710. dentp = *dents + n;
  3711. /* Selection file name */
  3712. dentp->name = (char *)((size_t)pnamebuf + off);
  3713. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  3714. off += dentp->nlen;
  3715. /* Copy other fields */
  3716. dentp->t = cfg.mtime ? sb.st_mtime : sb.st_atime;
  3717. #if !(defined(__sun) || defined(__HAIKU__))
  3718. if (!flags && dp->d_type == DT_LNK) {
  3719. /* Do not add sizes for links */
  3720. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  3721. dentp->size = g_listpath ? sb.st_size : 0;
  3722. } else {
  3723. dentp->mode = sb.st_mode;
  3724. dentp->size = sb.st_size;
  3725. }
  3726. #else
  3727. dentp->mode = sb.st_mode;
  3728. dentp->size = sb.st_size;
  3729. #endif
  3730. dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
  3731. DPRINTF_D(dentp->flags);
  3732. if (cfg.blkorder) {
  3733. if (S_ISDIR(sb.st_mode)) {
  3734. num_saved = num_files + 1;
  3735. mkpath(path, namep, buf);
  3736. /* Need to show the disk usage of this dir */
  3737. dentp->blocks = dirwalk(buf, &sb);
  3738. if (sb_path.st_dev == sb.st_dev) // NOLINT
  3739. dir_blocks += dentp->blocks;
  3740. else
  3741. num_files = num_saved;
  3742. if (g_states & STATE_INTERRUPTED)
  3743. goto exit;
  3744. } else {
  3745. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3746. /* Do not recount hard links */
  3747. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3748. dir_blocks += dentp->blocks;
  3749. ++num_files;
  3750. }
  3751. }
  3752. if (flags) {
  3753. /* Flag if this is a dir or symlink to a dir */
  3754. if (S_ISLNK(sb.st_mode)) {
  3755. sb.st_mode = 0;
  3756. fstatat(fd, namep, &sb, 0);
  3757. }
  3758. if (S_ISDIR(sb.st_mode))
  3759. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3760. #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
  3761. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode))) {
  3762. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3763. #endif
  3764. }
  3765. ++n;
  3766. } while ((dp = readdir(dirp)));
  3767. exit:
  3768. /* Should never be null */
  3769. if (closedir(dirp) == -1)
  3770. errexit();
  3771. return n;
  3772. }
  3773. /*
  3774. * Return the position of the matching entry or 0 otherwise
  3775. * Note there's no NULL check for fname
  3776. */
  3777. static int dentfind(const char *fname, int n)
  3778. {
  3779. int i = 0;
  3780. for (; i < n; ++i)
  3781. if (xstrcmp(fname, dents[i].name) == 0)
  3782. return i;
  3783. return 0;
  3784. }
  3785. static void populate(char *path, char *lastname)
  3786. {
  3787. #ifdef DBGMODE
  3788. struct timespec ts1, ts2;
  3789. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  3790. #endif
  3791. ndents = dentfill(path, &dents);
  3792. if (!ndents)
  3793. return;
  3794. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  3795. #ifdef DBGMODE
  3796. clock_gettime(CLOCK_REALTIME, &ts2);
  3797. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  3798. #endif
  3799. /* Find cur from history */
  3800. /* No NULL check for lastname, always points to an array */
  3801. if (!*lastname)
  3802. move_cursor(0, 0);
  3803. else
  3804. move_cursor(dentfind(lastname, ndents), 0);
  3805. // Force full redraw
  3806. last_curscroll = -1;
  3807. }
  3808. static void move_cursor(int target, int ignore_scrolloff)
  3809. {
  3810. int delta, scrolloff, onscreen = xlines - 4;
  3811. last_curscroll = curscroll;
  3812. target = MAX(0, MIN(ndents - 1, target));
  3813. delta = target - cur;
  3814. last = cur;
  3815. cur = target;
  3816. if (!ignore_scrolloff) {
  3817. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  3818. /*
  3819. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  3820. * margin area, but when ignore_scrolloff is 0, act like a boa
  3821. * constrictor and squeeze the cursor towards the middle region of the
  3822. * screen by allowing it to move inward and disallowing it to move
  3823. * outward (deeper into the scrolloff margin area).
  3824. */
  3825. if (((cur < (curscroll + scrolloff)) && delta < 0)
  3826. || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
  3827. curscroll += delta;
  3828. }
  3829. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  3830. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  3831. }
  3832. static void handle_screen_move(enum action sel)
  3833. {
  3834. int onscreen;
  3835. switch (sel) {
  3836. case SEL_NEXT:
  3837. if (ndents && (cfg.rollover || (cur != ndents - 1)))
  3838. move_cursor((cur + 1) % ndents, 0);
  3839. break;
  3840. case SEL_PREV:
  3841. if (ndents && (cfg.rollover || cur))
  3842. move_cursor((cur + ndents - 1) % ndents, 0);
  3843. break;
  3844. case SEL_PGDN:
  3845. onscreen = xlines - 4;
  3846. move_cursor(curscroll + (onscreen - 1), 1);
  3847. curscroll += onscreen - 1;
  3848. break;
  3849. case SEL_CTRL_D:
  3850. onscreen = xlines - 4;
  3851. move_cursor(curscroll + (onscreen - 1), 1);
  3852. curscroll += onscreen >> 1;
  3853. break;
  3854. case SEL_PGUP: // fallthrough
  3855. onscreen = xlines - 4;
  3856. move_cursor(curscroll, 1);
  3857. curscroll -= onscreen - 1;
  3858. break;
  3859. case SEL_CTRL_U:
  3860. onscreen = xlines - 4;
  3861. move_cursor(curscroll, 1);
  3862. curscroll -= onscreen >> 1;
  3863. break;
  3864. case SEL_HOME:
  3865. move_cursor(0, 1);
  3866. break;
  3867. case SEL_END:
  3868. move_cursor(ndents - 1, 1);
  3869. break;
  3870. default: /* case SEL_FIRST */
  3871. {
  3872. int r = 0;
  3873. for (; r < ndents; ++r) {
  3874. if (!(dents[r].flags & DIR_OR_LINK_TO_DIR)) {
  3875. move_cursor((r) % ndents, 0);
  3876. break;
  3877. }
  3878. }
  3879. break;
  3880. }
  3881. }
  3882. }
  3883. static int handle_context_switch(enum action sel, char *newpath)
  3884. {
  3885. int r = -1, input;
  3886. switch (sel) {
  3887. case SEL_CYCLE: // fallthrough
  3888. case SEL_CYCLER:
  3889. /* visit next and previous contexts */
  3890. r = cfg.curctx;
  3891. if (sel == SEL_CYCLE)
  3892. do
  3893. r = (r + 1) & ~CTX_MAX;
  3894. while (!g_ctx[r].c_cfg.ctxactive);
  3895. else
  3896. do
  3897. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3898. while (!g_ctx[r].c_cfg.ctxactive);
  3899. // fallthrough
  3900. default: /* SEL_CTXN */
  3901. if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
  3902. r = sel - SEL_CTX1; /* Save the next context id */
  3903. if (cfg.curctx == r) {
  3904. if (sel != SEL_CYCLE)
  3905. return -1;
  3906. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3907. snprintf(newpath, PATH_MAX, messages[MSG_CREATE_CTX], r + 1);
  3908. input = get_input(newpath);
  3909. if (!xconfirm(input))
  3910. return -1;
  3911. }
  3912. if (cfg.selmode)
  3913. lastappendpos = selbufpos;
  3914. }
  3915. return r;
  3916. }
  3917. static bool set_sort_flags(void)
  3918. {
  3919. int r = get_input(messages[MSG_ORDER]);
  3920. if ((r == 'a' || r == 'd' || r == 'e' || r == 's' || r == 't') && (entrycmpfn == &reventrycmp))
  3921. entrycmpfn = &entrycmp;
  3922. switch (r) {
  3923. case 'a': /* Apparent du */
  3924. cfg.apparentsz ^= 1;
  3925. if (cfg.apparentsz) {
  3926. nftw_fn = &sum_asize;
  3927. cfg.blkorder = 1;
  3928. blk_shift = 0;
  3929. } else
  3930. cfg.blkorder = 0;
  3931. // fallthrough
  3932. case 'd': /* Disk usage */
  3933. if (r == 'd') {
  3934. if (!cfg.apparentsz)
  3935. cfg.blkorder ^= 1;
  3936. nftw_fn = &sum_bsize;
  3937. cfg.apparentsz = 0;
  3938. blk_shift = ffs(S_BLKSIZE) - 1;
  3939. }
  3940. if (cfg.blkorder) {
  3941. cfg.showdetail = 1;
  3942. printptr = &printent_long;
  3943. }
  3944. cfg.mtimeorder = 0;
  3945. cfg.sizeorder = 0;
  3946. cfg.extnorder = 0;
  3947. clearfilter(); /* Reload directory */
  3948. endselection(); /* We are going to reload dir */
  3949. break;
  3950. case 'e': /* File extension */
  3951. cfg.extnorder ^= 1;
  3952. cfg.sizeorder = 0;
  3953. cfg.mtimeorder = 0;
  3954. cfg.apparentsz = 0;
  3955. cfg.blkorder = 0;
  3956. break;
  3957. case 'r': /* Reverse sort */
  3958. entrycmpfn = (entrycmpfn == &entrycmp) ? &reventrycmp : &entrycmp;
  3959. break;
  3960. case 's': /* File size */
  3961. cfg.sizeorder ^= 1;
  3962. cfg.mtimeorder = 0;
  3963. cfg.apparentsz = 0;
  3964. cfg.blkorder = 0;
  3965. cfg.extnorder = 0;
  3966. break;
  3967. case 't': /* Modification or access time */
  3968. cfg.mtimeorder ^= 1;
  3969. cfg.sizeorder = 0;
  3970. cfg.apparentsz = 0;
  3971. cfg.blkorder = 0;
  3972. cfg.extnorder = 0;
  3973. break;
  3974. case 'v': /* Version */
  3975. namecmpfn = (namecmpfn == &xstrverscasecmp) ? &xstricmp : &xstrverscasecmp;
  3976. break;
  3977. default:
  3978. return FALSE;
  3979. }
  3980. return TRUE;
  3981. }
  3982. static void statusbar(char *path)
  3983. {
  3984. int i = 0, extnlen = 0;
  3985. char *ptr;
  3986. pEntry pent = &dents[cur];
  3987. if (!ndents) {
  3988. printmsg("0/0");
  3989. return;
  3990. }
  3991. /* Get the file extension for regular files */
  3992. if (S_ISREG(pent->mode)) {
  3993. i = (int)(pent->nlen - 1);
  3994. ptr = xmemrchr((uchar *)pent->name, '.', i);
  3995. if (ptr) {
  3996. extnlen = ptr - pent->name;
  3997. extnlen = i - extnlen;
  3998. }
  3999. if (!ptr || extnlen > 5 || extnlen < 2)
  4000. ptr = "\b";
  4001. } else
  4002. ptr = "\b";
  4003. tolastln();
  4004. if (cfg.blkorder) { /* du mode */
  4005. char buf[24];
  4006. xstrlcpy(buf, coolsize(dir_blocks << blk_shift), 12);
  4007. printw("%d/%d [%s:%s] %cu:%s free:%s files:%lu %lldB %s",
  4008. cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4009. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4010. (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
  4011. num_files, (ll)pent->blocks << blk_shift, ptr);
  4012. } else { /* light or detail mode */
  4013. char sort[] = "\0\0\0\0";
  4014. getorderstr(sort);
  4015. printw("%d/%d [%s:%s] %s", cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4016. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4017. sort);
  4018. /* Timestamp */
  4019. print_time(&pent->t);
  4020. addch(' ');
  4021. addstr(get_lsperms(pent->mode));
  4022. addch(' ');
  4023. addstr(coolsize(pent->size));
  4024. addch(' ');
  4025. addstr(ptr);
  4026. }
  4027. addch('\n');
  4028. }
  4029. static int adjust_cols(int ncols)
  4030. {
  4031. /* Calculate the number of cols available to print entry name */
  4032. if (cfg.showdetail) {
  4033. /* Fallback to light mode if less than 35 columns */
  4034. if (ncols < 36) {
  4035. cfg.showdetail ^= 1;
  4036. printptr = &printent;
  4037. ncols -= 3; /* Preceding space, indicator, newline */
  4038. } else
  4039. ncols -= 35;
  4040. } else
  4041. ncols -= 3; /* Preceding space, indicator, newline */
  4042. return ncols;
  4043. }
  4044. static void draw_line(char *path, int ncols)
  4045. {
  4046. bool dir = FALSE;
  4047. ncols = adjust_cols(ncols);
  4048. if (dents[last].flags & DIR_OR_LINK_TO_DIR) {
  4049. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4050. dir = TRUE;
  4051. }
  4052. move(2 + last - curscroll, 0);
  4053. printptr(&dents[last], ncols, false);
  4054. if (dents[cur].flags & DIR_OR_LINK_TO_DIR) {
  4055. if (!dir) {/* First file is not a directory */
  4056. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4057. dir = TRUE;
  4058. }
  4059. } else if (dir) { /* Second file is not a directory */
  4060. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4061. dir = FALSE;
  4062. }
  4063. move(2 + cur - curscroll, 0);
  4064. printptr(&dents[cur], ncols, true);
  4065. /* Must reset e.g. no files in dir */
  4066. if (dir)
  4067. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4068. statusbar(path);
  4069. }
  4070. static void redraw(char *path)
  4071. {
  4072. xlines = LINES;
  4073. xcols = COLS;
  4074. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  4075. int onscreen = xlines - 4;
  4076. int i;
  4077. char *ptr = path;
  4078. // Fast redraw
  4079. if (g_states & STATE_MOVE_OP) {
  4080. g_states &= ~STATE_MOVE_OP;
  4081. if (ndents && (last_curscroll == curscroll))
  4082. return draw_line(path, ncols);
  4083. }
  4084. /* Clear screen */
  4085. erase();
  4086. /* Enforce scroll/cursor invariants */
  4087. move_cursor(cur, 1);
  4088. /* Fail redraw if < than 10 columns, context info prints 10 chars */
  4089. if (ncols < MIN_DISPLAY_COLS) {
  4090. printmsg(messages[MSG_FEW_COLUMNS]);
  4091. return;
  4092. }
  4093. //DPRINTF_D(cur);
  4094. DPRINTF_S(path);
  4095. addch('[');
  4096. for (i = 0; i < CTX_MAX; ++i) {
  4097. if (!g_ctx[i].c_cfg.ctxactive) {
  4098. addch(i + '1');
  4099. } else {
  4100. int attrs = (cfg.curctx != i)
  4101. ? (COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE) /* Active */
  4102. : (COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE); /* Current */
  4103. attron(attrs);
  4104. addch(i + '1');
  4105. attroff(attrs);
  4106. }
  4107. addch(' ');
  4108. }
  4109. addstr("\b] "); /* 10 chars printed for contexts - "[1 2 3 4] " */
  4110. attron(A_UNDERLINE);
  4111. /* Print path */
  4112. i = (int)strlen(path);
  4113. if ((i + MIN_DISPLAY_COLS) <= ncols)
  4114. addnstr(path, ncols - MIN_DISPLAY_COLS);
  4115. else {
  4116. char *base = xbasename(path);
  4117. if ((base - ptr) <= 1)
  4118. addnstr(path, ncols - MIN_DISPLAY_COLS);
  4119. else {
  4120. i = 0;
  4121. --base;
  4122. while (ptr < base) {
  4123. if (*ptr == '/') {
  4124. i += 2; /* 2 characters added */
  4125. if (ncols < i + MIN_DISPLAY_COLS) {
  4126. base = NULL; /* Can't print more characters */
  4127. break;
  4128. }
  4129. addch(*ptr);
  4130. addch(*(++ptr));
  4131. }
  4132. ++ptr;
  4133. }
  4134. addnstr(base, ncols - (MIN_DISPLAY_COLS + i));
  4135. }
  4136. }
  4137. /* Go to first entry */
  4138. move(2, 0);
  4139. attroff(A_UNDERLINE);
  4140. ncols = adjust_cols(ncols);
  4141. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4142. cfg.dircolor = 1;
  4143. /* Print listing */
  4144. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i)
  4145. printptr(&dents[i], ncols, i == cur);
  4146. /* Must reset e.g. no files in dir */
  4147. if (cfg.dircolor) {
  4148. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4149. cfg.dircolor = 0;
  4150. }
  4151. statusbar(path);
  4152. }
  4153. static bool browse(char *ipath, const char *session)
  4154. {
  4155. char newpath[PATH_MAX] __attribute__ ((aligned));
  4156. char rundir[PATH_MAX] __attribute__ ((aligned));
  4157. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  4158. char *path, *lastdir, *lastname, *dir, *tmp, *mark = NULL;
  4159. enum action sel;
  4160. struct stat sb;
  4161. int r = -1, fd, presel, selstartid = 0, selendid = 0;
  4162. const uchar opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOWAIT));
  4163. bool dir_changed = FALSE;
  4164. #ifndef NOMOUSE
  4165. MEVENT event;
  4166. struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
  4167. bool currentmouse = 1;
  4168. #endif
  4169. #ifndef DIR_LIMITED_SELECTION
  4170. ino_t inode = 0;
  4171. #endif
  4172. atexit(dentfree);
  4173. xlines = LINES;
  4174. xcols = COLS;
  4175. /* setup first context */
  4176. if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
  4177. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  4178. path = g_ctx[0].c_path;
  4179. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = '\0';
  4180. lastdir = g_ctx[0].c_last; /* last visited directory */
  4181. lastname = g_ctx[0].c_name; /* last visited filename */
  4182. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  4183. g_ctx[0].c_cfg = cfg; /* current configuration */
  4184. }
  4185. newpath[0] = rundir[0] = runfile[0] = '\0';
  4186. presel = cfg.filtermode ? FILTER : 0;
  4187. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  4188. if (!dents)
  4189. errexit();
  4190. /* Allocate buffer to hold names */
  4191. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  4192. if (!pnamebuf)
  4193. errexit();
  4194. begin:
  4195. /* Can fail when permissions change while browsing.
  4196. * It's assumed that path IS a directory when we are here.
  4197. */
  4198. if (access(path, R_OK) == -1) {
  4199. DPRINTF_S("directory inaccessible");
  4200. find_accessible_parent(path, newpath, lastname, &presel);
  4201. setdirwatch();
  4202. }
  4203. if (cfg.selmode && lastdir[0])
  4204. lastappendpos = selbufpos;
  4205. #ifdef LINUX_INOTIFY
  4206. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  4207. inotify_rm_watch(inotify_fd, inotify_wd);
  4208. inotify_wd = -1;
  4209. dir_changed = FALSE;
  4210. }
  4211. #elif defined(BSD_KQUEUE)
  4212. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  4213. close(event_fd);
  4214. event_fd = -1;
  4215. dir_changed = FALSE;
  4216. }
  4217. #elif defined(HAIKU_NM)
  4218. if ((presel == FILTER || dir_changed) && haiku_hnd != NULL) {
  4219. haiku_stop_watch(haiku_hnd);
  4220. haiku_nm_active = FALSE;
  4221. dir_changed = FALSE;
  4222. }
  4223. #endif
  4224. populate(path, lastname);
  4225. if (g_states & STATE_INTERRUPTED) {
  4226. g_states &= ~STATE_INTERRUPTED;
  4227. cfg.apparentsz = 0;
  4228. cfg.blkorder = 0;
  4229. blk_shift = BLK_SHIFT_512;
  4230. presel = CONTROL('L');
  4231. }
  4232. #ifdef LINUX_INOTIFY
  4233. if (presel != FILTER && inotify_wd == -1)
  4234. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  4235. #elif defined(BSD_KQUEUE)
  4236. if (presel != FILTER && event_fd == -1) {
  4237. #if defined(O_EVTONLY)
  4238. event_fd = open(path, O_EVTONLY);
  4239. #else
  4240. event_fd = open(path, O_RDONLY);
  4241. #endif
  4242. if (event_fd >= 0)
  4243. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  4244. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  4245. }
  4246. #elif defined(HAIKU_NM)
  4247. haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == _SUCCESS;
  4248. #endif
  4249. while (1) {
  4250. redraw(path);
  4251. /* Display a one-time message */
  4252. if (g_listpath && (g_states & STATE_MSG)) {
  4253. g_states &= ~STATE_MSG;
  4254. printwait(messages[MSG_IGNORED], &presel);
  4255. }
  4256. nochange:
  4257. /* Exit if parent has exited */
  4258. if (getppid() == 1) {
  4259. free(mark);
  4260. _exit(0);
  4261. }
  4262. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  4263. if (access(path, F_OK))
  4264. goto begin;
  4265. /* If STDIN is no longer a tty (closed) we should exit */
  4266. if (!isatty(STDIN_FILENO) && !cfg.picker) {
  4267. free(mark);
  4268. return _FAILURE;
  4269. }
  4270. sel = nextsel(presel);
  4271. if (presel)
  4272. presel = 0;
  4273. switch (sel) {
  4274. #ifndef NOMOUSE
  4275. case SEL_CLICK:
  4276. if (getmouse(&event) != OK)
  4277. goto nochange;
  4278. /* Handle clicking on a context at the top */
  4279. if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
  4280. /* Get context from: "[1 2 3 4]..." */
  4281. r = event.x >> 1;
  4282. /* If clicked after contexts, go to parent */
  4283. if (r >= CTX_MAX)
  4284. sel = SEL_BACK;
  4285. else if (r >= 0 && r != cfg.curctx) {
  4286. if (cfg.selmode)
  4287. lastappendpos = selbufpos;
  4288. savecurctx(&cfg, path, dents[cur].name, r);
  4289. /* Reset the pointers */
  4290. path = g_ctx[r].c_path;
  4291. lastdir = g_ctx[r].c_last;
  4292. lastname = g_ctx[r].c_name;
  4293. setdirwatch();
  4294. goto begin;
  4295. }
  4296. }
  4297. #endif
  4298. // fallthrough
  4299. case SEL_BACK:
  4300. #ifndef NOMOUSE
  4301. if (sel == SEL_BACK) {
  4302. #endif
  4303. dir = visit_parent(path, newpath, &presel);
  4304. if (!dir)
  4305. goto nochange;
  4306. /* Save last working directory */
  4307. xstrlcpy(lastdir, path, PATH_MAX);
  4308. /* Save history */
  4309. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  4310. clearfilter();
  4311. xstrlcpy(path, dir, PATH_MAX);
  4312. setdirwatch();
  4313. goto begin;
  4314. #ifndef NOMOUSE
  4315. }
  4316. #endif
  4317. #ifndef NOMOUSE
  4318. #if NCURSES_MOUSE_VERSION > 1
  4319. /* Scroll up */
  4320. if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
  4321. move_cursor((cur + ndents - 1) % ndents, 0);
  4322. break;
  4323. }
  4324. /* Scroll down */
  4325. if (event.bstate == BUTTON5_PRESSED && ndents
  4326. && (cfg.rollover || (cur != ndents - 1))) {
  4327. move_cursor((cur + 1) % ndents, 0);
  4328. break;
  4329. }
  4330. #endif
  4331. /* Toggle filter mode on left click on last 2 lines */
  4332. if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
  4333. clearfilter();
  4334. cfg.filtermode ^= 1;
  4335. if (cfg.filtermode) {
  4336. presel = FILTER;
  4337. goto nochange;
  4338. }
  4339. /* Start watching the directory */
  4340. dir_changed = TRUE;
  4341. if (ndents)
  4342. copycurname();
  4343. goto begin;
  4344. }
  4345. /* Handle clicking on a file */
  4346. if (event.y >= 2 && event.y <= ndents + 1 && event.bstate == BUTTON1_PRESSED) {
  4347. r = curscroll + (event.y - 2);
  4348. move_cursor(r, 1);
  4349. currentmouse ^= 1;
  4350. clock_gettime(
  4351. #if defined(CLOCK_MONOTONIC_RAW)
  4352. CLOCK_MONOTONIC_RAW,
  4353. #elif defined(CLOCK_MONOTONIC)
  4354. CLOCK_MONOTONIC,
  4355. #else
  4356. CLOCK_REALTIME,
  4357. #endif
  4358. &mousetimings[currentmouse]);
  4359. /*Single click just selects, double click also opens */
  4360. if (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
  4361. + (mousetimings[0].tv_nsec - mousetimings[1].tv_nsec))
  4362. > DOUBLECLICK_INTERVAL_NS)
  4363. break;
  4364. mousetimings[currentmouse].tv_sec = 0;
  4365. } else {
  4366. if (cfg.filtermode)
  4367. presel = FILTER;
  4368. goto nochange; // fallthrough
  4369. }
  4370. #endif
  4371. case SEL_NAV_IN: // fallthrough
  4372. case SEL_GOIN:
  4373. /* Cannot descend in empty directories */
  4374. if (!ndents)
  4375. goto begin;
  4376. mkpath(path, dents[cur].name, newpath);
  4377. DPRINTF_S(newpath);
  4378. /* Cannot use stale data in entry, file may be missing by now */
  4379. if (stat(newpath, &sb) == -1) {
  4380. printwarn(&presel);
  4381. goto nochange;
  4382. }
  4383. DPRINTF_U(sb.st_mode);
  4384. switch (sb.st_mode & S_IFMT) {
  4385. case S_IFDIR:
  4386. if (access(newpath, R_OK) == -1) {
  4387. printwarn(&presel);
  4388. goto nochange;
  4389. }
  4390. /* Save last working directory */
  4391. xstrlcpy(lastdir, path, PATH_MAX);
  4392. xstrlcpy(path, newpath, PATH_MAX);
  4393. lastname[0] = '\0';
  4394. clearfilter();
  4395. setdirwatch();
  4396. goto begin;
  4397. case S_IFREG:
  4398. {
  4399. /* If opened as vim plugin and Enter/^M pressed, pick */
  4400. if (cfg.picker && sel == SEL_GOIN) {
  4401. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4402. writesel(pselbuf, selbufpos - 1);
  4403. free(mark);
  4404. return _SUCCESS;
  4405. }
  4406. /* If open file is disabled on right arrow or `l`, return */
  4407. if (cfg.nonavopen && sel == SEL_NAV_IN)
  4408. goto nochange;
  4409. /* Handle plugin selection mode */
  4410. if (cfg.runplugin) {
  4411. cfg.runplugin = 0;
  4412. /* Must be in plugin dir and same context to select plugin */
  4413. if ((cfg.runctx == cfg.curctx) && !strcmp(path, plugindir)) {
  4414. endselection();
  4415. /* Copy path so we can return back to earlier dir */
  4416. xstrlcpy(path, rundir, PATH_MAX);
  4417. rundir[0] = '\0';
  4418. if (!run_selected_plugin(&path, dents[cur].name,
  4419. newpath, runfile, &lastname,
  4420. &lastdir)) {
  4421. DPRINTF_S("plugin failed!");
  4422. }
  4423. if (runfile[0])
  4424. runfile[0] = '\0';
  4425. clearfilter();
  4426. setdirwatch();
  4427. goto begin;
  4428. }
  4429. }
  4430. if (cfg.useeditor && (!sb.st_size ||
  4431. #ifdef FILE_MIME_OPTS
  4432. (get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, newpath, FALSE)
  4433. && !strncmp(g_buf, "text/", 5)))) {
  4434. #else
  4435. /* no mime option; guess from description instead */
  4436. (get_output(g_buf, CMD_LEN_MAX, "file", "-b", newpath, FALSE)
  4437. && strstr(g_buf, "text")))) {
  4438. #endif
  4439. spawn(editor, newpath, NULL, path, F_CLI);
  4440. continue;
  4441. }
  4442. if (!sb.st_size) {
  4443. printwait(messages[MSG_EMPTY_FILE], &presel);
  4444. goto nochange;
  4445. }
  4446. #ifdef PCRE
  4447. if (!pcre_exec(archive_pcre, NULL, dents[cur].name,
  4448. strlen(dents[cur].name), 0, 0, NULL, 0)) {
  4449. #else
  4450. if (!regexec(&archive_re, dents[cur].name, 0, NULL, 0)) {
  4451. #endif
  4452. r = get_input(messages[MSG_ARCHIVE_OPTS]);
  4453. if (r == 'l' || r == 'x') {
  4454. mkpath(path, dents[cur].name, newpath);
  4455. handle_archive(newpath, path, r);
  4456. copycurname();
  4457. goto begin;
  4458. }
  4459. if (r == 'm') {
  4460. if (archive_mount(dents[cur].name,
  4461. path, newpath, &presel)) {
  4462. lastname[0] = '\0';
  4463. /* Save last working directory */
  4464. xstrlcpy(lastdir, path, PATH_MAX);
  4465. /* Switch to mount point */
  4466. xstrlcpy(path, newpath, PATH_MAX);
  4467. setdirwatch();
  4468. goto begin;
  4469. } else {
  4470. printwait(messages[MSG_FAILED], &presel);
  4471. goto nochange;
  4472. }
  4473. }
  4474. if (r != 'd') {
  4475. printwait(messages[MSG_INVALID_KEY], &presel);
  4476. goto nochange;
  4477. }
  4478. }
  4479. /* Invoke desktop opener as last resort */
  4480. spawn(opener, newpath, NULL, NULL, opener_flags);
  4481. /* Move cursor to the next entry if not the last entry */
  4482. if ((g_states & STATE_AUTONEXT) && cur != ndents - 1)
  4483. move_cursor((cur + 1) % ndents, 0);
  4484. continue;
  4485. }
  4486. default:
  4487. printwait(messages[MSG_UNSUPPORTED], &presel);
  4488. goto nochange;
  4489. }
  4490. case SEL_NEXT: // fallthrough
  4491. case SEL_PREV: // fallthrough
  4492. case SEL_PGDN: // fallthrough
  4493. case SEL_CTRL_D: // fallthrough
  4494. case SEL_PGUP: // fallthrough
  4495. case SEL_CTRL_U: // fallthrough
  4496. case SEL_HOME: // fallthrough
  4497. case SEL_END: // fallthrough
  4498. case SEL_FIRST:
  4499. g_states |= STATE_MOVE_OP;
  4500. handle_screen_move(sel);
  4501. break;
  4502. case SEL_CDHOME: // fallthrough
  4503. case SEL_CDBEGIN: // fallthrough
  4504. case SEL_CDLAST: // fallthrough
  4505. case SEL_CDROOT:
  4506. switch (sel) {
  4507. case SEL_CDHOME:
  4508. dir = home;
  4509. break;
  4510. case SEL_CDBEGIN:
  4511. dir = ipath;
  4512. break;
  4513. case SEL_CDLAST:
  4514. dir = lastdir;
  4515. break;
  4516. default: /* SEL_CDROOT */
  4517. dir = "/";
  4518. break;
  4519. }
  4520. if (!dir || !*dir) {
  4521. printwait(messages[MSG_NOT_SET], &presel);
  4522. goto nochange;
  4523. }
  4524. if (!xdiraccess(dir)) {
  4525. presel = MSGWAIT;
  4526. goto nochange;
  4527. }
  4528. if (strcmp(path, dir) == 0) {
  4529. if (cfg.filtermode)
  4530. presel = FILTER;
  4531. goto nochange;
  4532. }
  4533. /* SEL_CDLAST: dir pointing to lastdir */
  4534. xstrlcpy(newpath, dir, PATH_MAX);
  4535. /* Save last working directory */
  4536. xstrlcpy(lastdir, path, PATH_MAX);
  4537. xstrlcpy(path, newpath, PATH_MAX);
  4538. lastname[0] = '\0';
  4539. clearfilter();
  4540. DPRINTF_S(path);
  4541. setdirwatch();
  4542. goto begin;
  4543. case SEL_BOOKMARK:
  4544. r = xstrlcpy(g_buf, messages[MSG_BOOKMARK_KEYS], CMD_LEN_MAX);
  4545. if (mark) { /* There is a pinned directory */
  4546. g_buf[--r] = ' ';
  4547. g_buf[++r] = ',';
  4548. g_buf[++r] = '\0';
  4549. ++r;
  4550. }
  4551. printkeys(bookmark, g_buf + r - 1, maxbm);
  4552. printprompt(g_buf);
  4553. fd = get_input(NULL);
  4554. r = FALSE;
  4555. if (fd == ',') /* Visit pinned directory */
  4556. mark ? xstrlcpy(newpath, mark, PATH_MAX) : (r = MSG_NOT_SET);
  4557. else if (!get_kv_val(bookmark, newpath, fd, maxbm, TRUE))
  4558. r = MSG_INVALID_KEY;
  4559. if (!r && !xdiraccess(newpath))
  4560. r = MSG_ACCESS;
  4561. if (r) {
  4562. printwait(messages[r], &presel);
  4563. goto nochange;
  4564. }
  4565. if (strcmp(path, newpath) == 0)
  4566. break;
  4567. lastname[0] = '\0';
  4568. clearfilter();
  4569. /* Save last working directory */
  4570. xstrlcpy(lastdir, path, PATH_MAX);
  4571. /* Save the newly opted dir in path */
  4572. xstrlcpy(path, newpath, PATH_MAX);
  4573. DPRINTF_S(path);
  4574. setdirwatch();
  4575. goto begin;
  4576. case SEL_CYCLE: // fallthrough
  4577. case SEL_CYCLER: // fallthrough
  4578. case SEL_CTX1: // fallthrough
  4579. case SEL_CTX2: // fallthrough
  4580. case SEL_CTX3: // fallthrough
  4581. case SEL_CTX4:
  4582. r = handle_context_switch(sel, newpath);
  4583. if (r < 0)
  4584. continue;
  4585. savecurctx(&cfg, path, dents[cur].name, r);
  4586. /* Reset the pointers */
  4587. path = g_ctx[r].c_path;
  4588. lastdir = g_ctx[r].c_last;
  4589. lastname = g_ctx[r].c_name;
  4590. tmp = g_ctx[r].c_fltr;
  4591. if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
  4592. presel = FILTER;
  4593. else
  4594. dir_changed = TRUE;
  4595. goto begin;
  4596. case SEL_PIN:
  4597. free(mark);
  4598. mark = strdup(path);
  4599. printwait(mark, &presel);
  4600. goto nochange;
  4601. case SEL_FLTR:
  4602. /* Unwatch dir if we are still in a filtered view */
  4603. #ifdef LINUX_INOTIFY
  4604. if (inotify_wd >= 0) {
  4605. inotify_rm_watch(inotify_fd, inotify_wd);
  4606. inotify_wd = -1;
  4607. }
  4608. #elif defined(BSD_KQUEUE)
  4609. if (event_fd >= 0) {
  4610. close(event_fd);
  4611. event_fd = -1;
  4612. }
  4613. #elif defined(HAIKU_NM)
  4614. if (haiku_nm_active) {
  4615. haiku_stop_watch(haiku_hnd);
  4616. haiku_nm_active = FALSE;
  4617. }
  4618. #endif
  4619. presel = filterentries(path, lastname);
  4620. if (presel == 27) {
  4621. presel = 0;
  4622. break;
  4623. }
  4624. goto nochange;
  4625. case SEL_MFLTR: // fallthrough
  4626. case SEL_HIDDEN: // fallthrough
  4627. case SEL_DETAIL: // fallthrough
  4628. case SEL_SORT:
  4629. switch (sel) {
  4630. case SEL_MFLTR:
  4631. cfg.filtermode ^= 1;
  4632. if (cfg.filtermode) {
  4633. presel = FILTER;
  4634. clearfilter();
  4635. goto nochange;
  4636. }
  4637. /* Start watching the directory */
  4638. dir_changed = TRUE;
  4639. break;
  4640. case SEL_HIDDEN:
  4641. cfg.showhidden ^= 1;
  4642. if (ndents)
  4643. copycurname();
  4644. if (cfg.filtermode)
  4645. presel = FILTER;
  4646. clearfilter();
  4647. goto begin;
  4648. case SEL_DETAIL:
  4649. cfg.showdetail ^= 1;
  4650. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  4651. cfg.blkorder = 0;
  4652. continue;
  4653. default: /* SEL_SORT */
  4654. if (!set_sort_flags()) {
  4655. if (cfg.filtermode)
  4656. presel = FILTER;
  4657. printwait(messages[MSG_INVALID_KEY], &presel);
  4658. goto nochange;
  4659. }
  4660. }
  4661. if (cfg.filtermode)
  4662. presel = FILTER;
  4663. /* Save current */
  4664. if (ndents)
  4665. copycurname();
  4666. /* If there's no filter, reload the directory */
  4667. if (!g_ctx[cfg.curctx].c_fltr[1])
  4668. goto begin;
  4669. presel = FILTER; /* If there's a filter, apply it */
  4670. break;
  4671. case SEL_STATS: // fallthrough
  4672. case SEL_CHMODX:
  4673. if (ndents) {
  4674. tmp = (g_listpath && xstrcmp(path, g_listpath) == 0) ? g_prefixpath : path;
  4675. mkpath(tmp, dents[cur].name, newpath);
  4676. if (lstat(newpath, &sb) == -1
  4677. || (sel == SEL_STATS && !show_stats(newpath, &sb))
  4678. || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
  4679. printwarn(&presel);
  4680. goto nochange;
  4681. }
  4682. if (sel == SEL_CHMODX)
  4683. dents[cur].mode ^= 0111;
  4684. }
  4685. break;
  4686. case SEL_REDRAW: // fallthrough
  4687. case SEL_RENAMEMUL: // fallthrough
  4688. case SEL_HELP: // fallthrough
  4689. case SEL_EDIT: // fallthrough
  4690. case SEL_LOCK:
  4691. {
  4692. bool refresh = FALSE;
  4693. if (ndents)
  4694. mkpath(path, dents[cur].name, newpath);
  4695. else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
  4696. goto nochange;
  4697. switch (sel) {
  4698. case SEL_REDRAW:
  4699. refresh = TRUE;
  4700. break;
  4701. case SEL_RENAMEMUL:
  4702. endselection();
  4703. if (!batch_rename(path)) {
  4704. printwait(messages[MSG_FAILED], &presel);
  4705. goto nochange;
  4706. }
  4707. refresh = TRUE;
  4708. break;
  4709. case SEL_HELP:
  4710. show_help(path);
  4711. if (cfg.filtermode)
  4712. presel = FILTER;
  4713. continue;
  4714. case SEL_EDIT:
  4715. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  4716. continue;
  4717. default: /* SEL_LOCK */
  4718. lock_terminal();
  4719. break;
  4720. }
  4721. /* In case of successful operation, reload contents */
  4722. /* Continue in navigate-as-you-type mode, if enabled */
  4723. if (cfg.filtermode && !refresh)
  4724. break;
  4725. /* Save current */
  4726. if (ndents)
  4727. copycurname();
  4728. /* Repopulate as directory content may have changed */
  4729. goto begin;
  4730. }
  4731. case SEL_SEL:
  4732. if (!ndents)
  4733. goto nochange;
  4734. startselection();
  4735. if (g_states & STATE_RANGESEL)
  4736. g_states &= ~STATE_RANGESEL;
  4737. /* Toggle selection status */
  4738. dents[cur].flags ^= FILE_SELECTED;
  4739. if (dents[cur].flags & FILE_SELECTED) {
  4740. ++nselected;
  4741. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4742. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4743. } else {
  4744. selbufpos = lastappendpos;
  4745. if (--nselected) {
  4746. updateselbuf(path, newpath);
  4747. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4748. } else
  4749. writesel(NULL, 0);
  4750. }
  4751. if (cfg.x11)
  4752. plugscript(utils[UTIL_CBCP], newpath, F_NOWAIT | F_NOTRACE);
  4753. if (!nselected)
  4754. unlink(g_selpath);
  4755. /* move cursor to the next entry if this is not the last entry */
  4756. if (!cfg.picker && cur != ndents - 1)
  4757. move_cursor((cur + 1) % ndents, 0);
  4758. break;
  4759. case SEL_SELMUL:
  4760. if (!ndents)
  4761. goto nochange;
  4762. startselection();
  4763. g_states ^= STATE_RANGESEL;
  4764. if (stat(path, &sb) == -1) {
  4765. printwarn(&presel);
  4766. goto nochange;
  4767. }
  4768. if (g_states & STATE_RANGESEL) { /* Range selection started */
  4769. #ifndef DIR_LIMITED_SELECTION
  4770. inode = sb.st_ino;
  4771. #endif
  4772. selstartid = cur;
  4773. continue;
  4774. }
  4775. #ifndef DIR_LIMITED_SELECTION
  4776. if (inode != sb.st_ino) {
  4777. printwait(messages[MSG_DIR_CHANGED], &presel);
  4778. goto nochange;
  4779. }
  4780. #endif
  4781. if (cur < selstartid) {
  4782. selendid = selstartid;
  4783. selstartid = cur;
  4784. } else
  4785. selendid = cur;
  4786. /* Clear selection on repeat on same file */
  4787. if (selstartid == selendid) {
  4788. resetselind();
  4789. clearselection();
  4790. break;
  4791. } // fallthrough
  4792. case SEL_SELALL:
  4793. if (sel == SEL_SELALL) {
  4794. if (!ndents)
  4795. goto nochange;
  4796. startselection();
  4797. if (g_states & STATE_RANGESEL)
  4798. g_states &= ~STATE_RANGESEL;
  4799. selstartid = 0;
  4800. selendid = ndents - 1;
  4801. }
  4802. /* Remember current selection buffer position */
  4803. for (r = selstartid; r <= selendid; ++r)
  4804. if (!(dents[r].flags & FILE_SELECTED)) {
  4805. /* Write the path to selection file to avoid flush */
  4806. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  4807. dents[r].flags |= FILE_SELECTED;
  4808. ++nselected;
  4809. }
  4810. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4811. if (cfg.x11)
  4812. plugscript(utils[UTIL_CBCP], newpath, F_NOWAIT | F_NOTRACE);
  4813. continue;
  4814. case SEL_SELEDIT:
  4815. r = editselection();
  4816. if (r <= 0) {
  4817. r = !r ? MSG_0_SELECTED : MSG_FAILED;
  4818. printwait(messages[r], &presel);
  4819. } else {
  4820. if (cfg.x11)
  4821. plugscript(utils[UTIL_CBCP], newpath, F_NOWAIT | F_NOTRACE);
  4822. cfg.filtermode ? presel = FILTER : statusbar(path);
  4823. }
  4824. goto nochange;
  4825. case SEL_CP: // fallthrough
  4826. case SEL_MV: // fallthrough
  4827. case SEL_CPMVAS: // fallthrough
  4828. case SEL_RM:
  4829. {
  4830. if (sel == SEL_RM) {
  4831. r = get_cur_or_sel();
  4832. if (!r) {
  4833. statusbar(path);
  4834. goto nochange;
  4835. }
  4836. if (r == 'c') {
  4837. tmp = (g_listpath && xstrcmp(path, g_listpath) == 0)
  4838. ? g_prefixpath : path;
  4839. mkpath(tmp, dents[cur].name, newpath);
  4840. xrm(newpath);
  4841. if (cfg.filtermode)
  4842. presel = FILTER;
  4843. if (access(newpath, F_OK) == 0) /* File not removed */
  4844. goto nochange;
  4845. else if (cur) {
  4846. cur += (cur != (ndents - 1)) ? 1 : -1;
  4847. copycurname();
  4848. } else
  4849. lastname[0] = '\0';
  4850. goto begin;
  4851. }
  4852. }
  4853. endselection();
  4854. if (!cpmvrm_selection(sel, path, &presel))
  4855. goto nochange;
  4856. clearfilter();
  4857. /* Show notification on operation complete */
  4858. if (cfg.x11)
  4859. plugscript(utils[UTIL_NTFY], newpath, F_NOWAIT | F_NOTRACE);
  4860. if (ndents)
  4861. copycurname();
  4862. goto begin;
  4863. }
  4864. case SEL_ARCHIVE: // fallthrough
  4865. case SEL_OPENWITH: // fallthrough
  4866. case SEL_NEW: // fallthrough
  4867. case SEL_RENAME:
  4868. {
  4869. int dup = 'n';
  4870. if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
  4871. break;
  4872. if (sel != SEL_OPENWITH)
  4873. endselection();
  4874. switch (sel) {
  4875. case SEL_ARCHIVE:
  4876. r = get_cur_or_sel();
  4877. if (!r) {
  4878. statusbar(path);
  4879. goto nochange;
  4880. }
  4881. if (r == 's') {
  4882. if (!selsafe()) {
  4883. presel = MSGWAIT;
  4884. goto nochange;
  4885. }
  4886. tmp = NULL;
  4887. } else
  4888. tmp = dents[cur].name;
  4889. tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
  4890. break;
  4891. case SEL_OPENWITH:
  4892. #ifdef NORL
  4893. tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
  4894. #else
  4895. presel = 0;
  4896. tmp = getreadline(messages[MSG_OPEN_WITH], path, ipath, &presel);
  4897. if (presel == MSGWAIT)
  4898. goto nochange;
  4899. #endif
  4900. break;
  4901. case SEL_NEW:
  4902. r = get_input(messages[MSG_NEW_OPTS]);
  4903. if (r == 'f' || r == 'd')
  4904. tmp = xreadline(NULL, messages[MSG_REL_PATH]);
  4905. else if (r == 's' || r == 'h')
  4906. tmp = xreadline(NULL, messages[MSG_LINK_PREFIX]);
  4907. else
  4908. tmp = NULL;
  4909. break;
  4910. default: /* SEL_RENAME */
  4911. tmp = xreadline(dents[cur].name, "");
  4912. break;
  4913. }
  4914. if (!tmp || !*tmp)
  4915. break;
  4916. /* Allow only relative, same dir paths */
  4917. if (tmp[0] == '/'
  4918. || ((r != 'f' && r != 'd') && (xstrcmp(xbasename(tmp), tmp) != 0))) {
  4919. printwait(messages[MSG_NO_TRAVERSAL], &presel);
  4920. goto nochange;
  4921. }
  4922. switch (sel) {
  4923. case SEL_ARCHIVE:
  4924. if (r == 'c' && strcmp(tmp, dents[cur].name) == 0)
  4925. goto nochange;
  4926. mkpath(path, tmp, newpath);
  4927. if (access(newpath, F_OK) == 0) {
  4928. fd = get_input(messages[MSG_OVERWRITE]);
  4929. if (!xconfirm(fd)) {
  4930. statusbar(path);
  4931. goto nochange;
  4932. }
  4933. }
  4934. get_archive_cmd(newpath, tmp);
  4935. (r == 's') ? archive_selection(newpath, tmp, path)
  4936. : spawn(newpath, tmp, dents[cur].name,
  4937. path, F_NORMAL | F_MULTI);
  4938. // fallthrough
  4939. case SEL_OPENWITH:
  4940. if (sel == SEL_OPENWITH) {
  4941. /* Confirm if app is CLI or GUI */
  4942. r = get_input(messages[MSG_CLI_MODE]);
  4943. r = (r == 'c' ? F_CLI :
  4944. (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
  4945. if (!r) {
  4946. cfg.filtermode ? presel = FILTER : statusbar(path);
  4947. goto nochange;
  4948. }
  4949. mkpath(path, dents[cur].name, newpath);
  4950. spawn(tmp, newpath, NULL, path, r);
  4951. }
  4952. if (cfg.filtermode)
  4953. presel = FILTER;
  4954. copycurname();
  4955. goto begin;
  4956. case SEL_RENAME:
  4957. /* Skip renaming to same name */
  4958. if (strcmp(tmp, dents[cur].name) == 0) {
  4959. tmp = xreadline(dents[cur].name, messages[MSG_COPY_NAME]);
  4960. if (strcmp(tmp, dents[cur].name) == 0)
  4961. goto nochange;
  4962. dup = 'd';
  4963. }
  4964. break;
  4965. default: /* SEL_NEW */
  4966. break;
  4967. }
  4968. /* Open the descriptor to currently open directory */
  4969. #ifdef O_DIRECTORY
  4970. fd = open(path, O_RDONLY | O_DIRECTORY);
  4971. #else
  4972. fd = open(path, O_RDONLY);
  4973. #endif
  4974. if (fd == -1) {
  4975. printwarn(&presel);
  4976. goto nochange;
  4977. }
  4978. /* Check if another file with same name exists */
  4979. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  4980. if (sel == SEL_RENAME) {
  4981. /* Overwrite file with same name? */
  4982. r = get_input(messages[MSG_OVERWRITE]);
  4983. if (!xconfirm(r)) {
  4984. close(fd);
  4985. break;
  4986. }
  4987. } else {
  4988. /* Do nothing in case of NEW */
  4989. close(fd);
  4990. printwait(messages[MSG_EXISTS], &presel);
  4991. goto nochange;
  4992. }
  4993. }
  4994. if (sel == SEL_RENAME) {
  4995. /* Rename the file */
  4996. if (dup == 'd')
  4997. spawn("cp -rp", dents[cur].name, tmp, path, F_SILENT);
  4998. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  4999. close(fd);
  5000. printwarn(&presel);
  5001. goto nochange;
  5002. }
  5003. close(fd);
  5004. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  5005. } else { /* SEL_NEW */
  5006. close(fd); /* Use fd as tmp var */
  5007. presel = 0;
  5008. /* Check if it's a dir or file */
  5009. if (r == 'f') {
  5010. mkpath(path, tmp, newpath);
  5011. fd = xmktree(newpath, FALSE);
  5012. } else if (r == 'd') {
  5013. mkpath(path, tmp, newpath);
  5014. fd = xmktree(newpath, TRUE);
  5015. } else if (r == 's' || r == 'h') {
  5016. if (tmp[0] == '@' && tmp[1] == '\0')
  5017. tmp[0] = '\0';
  5018. fd = xlink(tmp, path, (ndents ? dents[cur].name : NULL),
  5019. newpath, &presel, r);
  5020. }
  5021. if (!fd)
  5022. printwait(messages[MSG_FAILED], &presel);
  5023. if (fd <= 0)
  5024. goto nochange;
  5025. if (r == 'f' || r == 'd')
  5026. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  5027. else if (ndents) {
  5028. if (cfg.filtermode)
  5029. presel = FILTER;
  5030. copycurname();
  5031. }
  5032. }
  5033. goto begin;
  5034. }
  5035. case SEL_PLUGIN:
  5036. /* Check if directory is accessible */
  5037. if (!xdiraccess(plugindir)) {
  5038. printwarn(&presel);
  5039. goto nochange;
  5040. }
  5041. r = xstrlcpy(g_buf, messages[MSG_PLUGIN_KEYS], CMD_LEN_MAX);
  5042. printkeys(plug, g_buf + r - 1, maxplug);
  5043. printprompt(g_buf);
  5044. r = get_input(NULL);
  5045. if (r != '\r') {
  5046. endselection();
  5047. tmp = get_kv_val(plug, NULL, r, maxplug, FALSE);
  5048. if (!tmp) {
  5049. printwait(messages[MSG_INVALID_KEY], &presel);
  5050. goto nochange;
  5051. }
  5052. if (tmp[0] == '-' && tmp[1]) {
  5053. ++tmp;
  5054. r = FALSE; /* Do not refresh dir after completion */
  5055. } else
  5056. r = TRUE;
  5057. if (!run_selected_plugin(&path, tmp, newpath,
  5058. (ndents ? dents[cur].name : NULL),
  5059. &lastname, &lastdir)) {
  5060. printwait(messages[MSG_FAILED], &presel);
  5061. goto nochange;
  5062. }
  5063. if (ndents)
  5064. copycurname();
  5065. if (!r) {
  5066. cfg.filtermode ? presel = FILTER : statusbar(path);
  5067. goto nochange;
  5068. }
  5069. } else { /* 'Return/Enter' enters the plugin directory */
  5070. cfg.runplugin ^= 1;
  5071. if (!cfg.runplugin && rundir[0]) {
  5072. /*
  5073. * If toggled, and still in the plugin dir,
  5074. * switch to original directory
  5075. */
  5076. if (strcmp(path, plugindir) == 0) {
  5077. xstrlcpy(path, rundir, PATH_MAX);
  5078. xstrlcpy(lastname, runfile, NAME_MAX);
  5079. rundir[0] = runfile[0] = '\0';
  5080. setdirwatch();
  5081. goto begin;
  5082. }
  5083. /* Otherwise, initiate choosing plugin again */
  5084. cfg.runplugin = 1;
  5085. }
  5086. xstrlcpy(rundir, path, PATH_MAX);
  5087. xstrlcpy(path, plugindir, PATH_MAX);
  5088. if (ndents)
  5089. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  5090. cfg.runctx = cfg.curctx;
  5091. lastname[0] = '\0';
  5092. }
  5093. setdirwatch();
  5094. clearfilter();
  5095. goto begin;
  5096. case SEL_SHELL: // fallthrough
  5097. case SEL_LAUNCH: // fallthrough
  5098. case SEL_RUNCMD:
  5099. endselection();
  5100. switch (sel) {
  5101. case SEL_SHELL:
  5102. /* Set nnn nesting level */
  5103. tmp = getenv(env_cfg[NNNLVL]);
  5104. setenv(env_cfg[NNNLVL], xitoa((tmp ? atoi(tmp) : 0) + 1), 1);
  5105. setenv(envs[ENV_NCUR], (ndents ? dents[cur].name : ""), 1);
  5106. spawn(shell, NULL, NULL, path, F_CLI);
  5107. break;
  5108. case SEL_LAUNCH:
  5109. launch_app(path, newpath);
  5110. if (cfg.filtermode)
  5111. presel = FILTER;
  5112. goto nochange;
  5113. default: /* SEL_RUNCMD */
  5114. #ifndef NORL
  5115. if (cfg.picker) {
  5116. #endif
  5117. tmp = xreadline(NULL, ">>> ");
  5118. #ifndef NORL
  5119. } else {
  5120. presel = 0;
  5121. tmp = getreadline(">>> ", path, ipath, &presel);
  5122. if (presel == MSGWAIT)
  5123. goto nochange;
  5124. }
  5125. #endif
  5126. if (tmp && *tmp) // NOLINT
  5127. prompt_run(tmp, (ndents ? dents[cur].name : ""), path);
  5128. else {
  5129. if (cfg.filtermode)
  5130. presel = FILTER;
  5131. goto nochange;
  5132. }
  5133. }
  5134. /* Continue in navigate-as-you-type mode, if enabled */
  5135. if (cfg.filtermode)
  5136. presel = FILTER;
  5137. /* Save current */
  5138. if (ndents)
  5139. copycurname();
  5140. /* Repopulate as directory content may have changed */
  5141. goto begin;
  5142. case SEL_REMOTE:
  5143. if (sel == SEL_REMOTE && !remote_mount(newpath, &presel))
  5144. goto nochange;
  5145. lastname[0] = '\0';
  5146. /* Save last working directory */
  5147. xstrlcpy(lastdir, path, PATH_MAX);
  5148. /* Switch to mount point */
  5149. xstrlcpy(path, newpath, PATH_MAX);
  5150. setdirwatch();
  5151. goto begin;
  5152. case SEL_UMOUNT:
  5153. tmp = ndents ? dents[cur].name : NULL;
  5154. unmount(tmp, newpath, &presel, path);
  5155. goto nochange;
  5156. case SEL_SESSIONS:
  5157. r = get_input(messages[MSG_SSN_OPTS]);
  5158. if (r == 's')
  5159. save_session(FALSE, &presel);
  5160. else if (r == 'l' || r == 'r') {
  5161. if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
  5162. setdirwatch();
  5163. goto begin;
  5164. }
  5165. }
  5166. statusbar(path);
  5167. goto nochange;
  5168. case SEL_AUTONEXT:
  5169. g_states ^= STATE_AUTONEXT;
  5170. if (cfg.filtermode)
  5171. presel = FILTER;
  5172. goto nochange;
  5173. case SEL_QUITCTX: // fallthrough
  5174. case SEL_QUITCD: // fallthrough
  5175. case SEL_QUIT:
  5176. case SEL_QUITFAIL:
  5177. if (sel == SEL_QUITCTX) {
  5178. fd = cfg.curctx; /* fd used as tmp var */
  5179. for (r = (fd + 1) & ~CTX_MAX;
  5180. (r != fd) && !g_ctx[r].c_cfg.ctxactive;
  5181. r = ((r + 1) & ~CTX_MAX)) {
  5182. };
  5183. if (r != fd) {
  5184. bool selmode = cfg.selmode ? TRUE : FALSE;
  5185. g_ctx[fd].c_cfg.ctxactive = 0;
  5186. /* Switch to next active context */
  5187. path = g_ctx[r].c_path;
  5188. lastdir = g_ctx[r].c_last;
  5189. lastname = g_ctx[r].c_name;
  5190. /* Switch light/detail mode */
  5191. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  5192. /* Set the reverse */
  5193. printptr = cfg.showdetail ?
  5194. &printent : &printent_long;
  5195. cfg = g_ctx[r].c_cfg;
  5196. /* Continue selection mode */
  5197. cfg.selmode = selmode;
  5198. cfg.curctx = r;
  5199. setdirwatch();
  5200. goto begin;
  5201. }
  5202. } else if (!cfg.forcequit) {
  5203. for (r = 0; r < CTX_MAX; ++r)
  5204. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  5205. r = get_input(messages[MSG_QUIT_ALL]);
  5206. break;
  5207. }
  5208. if (!(r == CTX_MAX || xconfirm(r)))
  5209. break; // fallthrough
  5210. }
  5211. /* CD on Quit */
  5212. /* In vim picker mode, clear selection and exit */
  5213. /* Picker mode: reset buffer or clear file */
  5214. if (sel == SEL_QUITCD || getenv("NNN_TMPFILE"))
  5215. cfg.picker ? selbufpos = 0 : write_lastdir(path);
  5216. free(mark);
  5217. return sel == SEL_QUITFAIL ? _FAILURE : _SUCCESS;
  5218. default:
  5219. if (xlines != LINES || xcols != COLS)
  5220. setdirwatch(); /* Terminal resized */
  5221. else if (idletimeout && idle == idletimeout)
  5222. lock_terminal(); /* Locker */
  5223. else
  5224. goto nochange;
  5225. idle = 0;
  5226. if (ndents)
  5227. copycurname();
  5228. goto begin;
  5229. } /* switch (sel) */
  5230. }
  5231. }
  5232. static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
  5233. {
  5234. /* tmpdir holds the full path */
  5235. /* tmp holds the path without the tmp dir prefix */
  5236. int err, ignore = 0;
  5237. struct stat sb;
  5238. char *slash, *tmp;
  5239. ssize_t i, len = strlen(prefix);
  5240. char *tmpdir = malloc(sizeof(char) * (PATH_MAX + TMP_LEN_MAX));
  5241. if (!tmpdir) {
  5242. DPRINTF_S(strerror(errno));
  5243. return NULL;
  5244. }
  5245. tmp = tmpdir + g_tmpfplen - 1;
  5246. xstrlcpy(tmpdir, g_tmpfpath, g_tmpfplen);
  5247. xstrlcpy(tmp, "/nnnXXXXXX", 11);
  5248. /* Points right after the base tmp dir */
  5249. tmp += 10;
  5250. if (!mkdtemp(tmpdir)) {
  5251. free(tmpdir);
  5252. DPRINTF_S(strerror(errno));
  5253. return NULL;
  5254. }
  5255. g_listpath = tmpdir;
  5256. for (i = 0; i < entries; ++i) {
  5257. if (!paths[i])
  5258. continue;
  5259. err = stat(paths[i], &sb);
  5260. if (err && errno == ENOENT) {
  5261. ignore = 1;
  5262. continue;
  5263. }
  5264. /* Don't copy the common prefix */
  5265. xstrlcpy(tmp, paths[i] + len, strlen(paths[i]) - len + 1);
  5266. /* Get the dir containing the path */
  5267. slash = xmemrchr((uchar *)tmp, '/', strlen(paths[i]) - len);
  5268. if (slash)
  5269. *slash = '\0';
  5270. xmktree(tmpdir, TRUE);
  5271. if (slash)
  5272. *slash = '/';
  5273. if (symlink(paths[i], tmpdir)) {
  5274. DPRINTF_S(paths[i]);
  5275. DPRINTF_S(strerror(errno));
  5276. }
  5277. }
  5278. if (ignore)
  5279. g_states |= STATE_MSG;
  5280. /* Get the dir in which to start */
  5281. *tmp = '\0';
  5282. return tmpdir;
  5283. }
  5284. static char *load_input()
  5285. {
  5286. /* 512 KiB chunk size */
  5287. ssize_t i, chunk_count = 1, chunk = 512 * 1024, entries = 0;
  5288. char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
  5289. char cwd[PATH_MAX], *next, *tmp;
  5290. size_t offsets[LIST_FILES_MAX];
  5291. char **paths = NULL;
  5292. ssize_t input_read, total_read = 0, off = 0;
  5293. if (!input) {
  5294. DPRINTF_S(strerror(errno));
  5295. return NULL;
  5296. }
  5297. if (!getcwd(cwd, PATH_MAX)) {
  5298. free(input);
  5299. return NULL;
  5300. }
  5301. while (chunk_count < 512) {
  5302. input_read = read(STDIN_FILENO, input + total_read, chunk);
  5303. if (input_read < 0) {
  5304. DPRINTF_S(strerror(errno));
  5305. goto malloc_1;
  5306. }
  5307. if (input_read == 0)
  5308. break;
  5309. total_read += input_read;
  5310. ++chunk_count;
  5311. while (off < total_read) {
  5312. next = memchr(input + off, '\0', total_read - off) + 1;
  5313. if (next == (void *)1)
  5314. break;
  5315. if (next - input == off + 1) {
  5316. off = next - input;
  5317. continue;
  5318. }
  5319. if (entries == LIST_FILES_MAX)
  5320. goto malloc_1;
  5321. offsets[entries++] = off;
  5322. off = next - input;
  5323. }
  5324. if (chunk_count == 512)
  5325. goto malloc_1;
  5326. /* We don't need to allocate another chunk */
  5327. if (chunk_count == (total_read - input_read) / chunk)
  5328. continue;
  5329. chunk_count = total_read / chunk;
  5330. if (total_read % chunk)
  5331. ++chunk_count;
  5332. if (!(input = xrealloc(input, (chunk_count + 1) * chunk)))
  5333. return NULL;
  5334. }
  5335. if (off != total_read) {
  5336. if (entries == LIST_FILES_MAX)
  5337. goto malloc_1;
  5338. offsets[entries++] = off;
  5339. }
  5340. DPRINTF_D(entries);
  5341. DPRINTF_D(total_read);
  5342. DPRINTF_D(chunk_count);
  5343. if (!entries)
  5344. goto malloc_1;
  5345. input[total_read] = '\0';
  5346. paths = malloc(entries * sizeof(char *));
  5347. if (!paths)
  5348. goto malloc_1;
  5349. for (i = 0; i < entries; ++i)
  5350. paths[i] = input + offsets[i];
  5351. g_prefixpath = malloc(sizeof(char) * PATH_MAX);
  5352. if (!g_prefixpath)
  5353. goto malloc_1;
  5354. g_prefixpath[0] = '\0';
  5355. DPRINTF_S(paths[0]);
  5356. for (i = 0; i < entries; ++i) {
  5357. if (paths[i][0] == '\n' || selforparent(paths[i])) {
  5358. paths[i] = NULL;
  5359. continue;
  5360. }
  5361. if (!(paths[i] = abspath(paths[i], cwd))) {
  5362. entries = i; // free from the previous entry
  5363. goto malloc_2;
  5364. }
  5365. DPRINTF_S(paths[i]);
  5366. xstrlcpy(g_buf, paths[i], PATH_MAX);
  5367. if (!common_prefix(dirname(g_buf), g_prefixpath)) {
  5368. entries = i + 1; // free from the current entry
  5369. goto malloc_2;
  5370. }
  5371. DPRINTF_S(g_prefixpath);
  5372. }
  5373. DPRINTF_S(g_prefixpath);
  5374. if (g_prefixpath[0]) {
  5375. if (entries == 1) {
  5376. tmp = xmemrchr((uchar *)g_prefixpath, '/', strlen(g_prefixpath));
  5377. if (!tmp)
  5378. goto malloc_2;
  5379. *(tmp != g_prefixpath ? tmp : tmp + 1) = '\0';
  5380. }
  5381. tmpdir = make_tmp_tree(paths, entries, g_prefixpath);
  5382. }
  5383. malloc_2:
  5384. for (i = entries - 1; i >= 0; --i)
  5385. free(paths[i]);
  5386. malloc_1:
  5387. free(input);
  5388. free(paths);
  5389. return tmpdir;
  5390. }
  5391. static void check_key_collision(void)
  5392. {
  5393. int key;
  5394. ulong i = 0;
  5395. bool bitmap[KEY_MAX] = {FALSE};
  5396. for (; i < sizeof(bindings) / sizeof(struct key); ++i) {
  5397. key = bindings[i].sym;
  5398. if (bitmap[key])
  5399. fprintf(stdout, "key collision! [%s]\n", keyname(key));
  5400. else
  5401. bitmap[key] = TRUE;
  5402. }
  5403. }
  5404. static void usage(void)
  5405. {
  5406. fprintf(stdout,
  5407. "%s: nnn [OPTIONS] [PATH]\n\n"
  5408. "The missing terminal file manager for X.\n\n"
  5409. "positional args:\n"
  5410. " PATH start dir [default: .]\n\n"
  5411. "optional args:\n"
  5412. " -a use access time\n"
  5413. " -A no dir auto-select\n"
  5414. " -b key open bookmark key\n"
  5415. " -c cli-only opener (overrides -e)\n"
  5416. " -d detail mode\n"
  5417. " -e text in $VISUAL ($EDITOR/vi)\n"
  5418. " -E use EDITOR for undetached edits\n"
  5419. " -g regex filters [default: string]\n"
  5420. " -H show hidden files\n"
  5421. " -K detect key collision\n"
  5422. " -n nav-as-you-type mode\n"
  5423. " -o open files only on Enter\n"
  5424. " -p file selection file [stdout if '-']\n"
  5425. " -Q no quit confirmation\n"
  5426. " -r use advcpmv patched cp, mv\n"
  5427. " -R no rollover at edges\n"
  5428. " -s name load session by name\n"
  5429. " -S du mode\n"
  5430. " -t secs timeout to lock\n"
  5431. " -v version sort\n"
  5432. " -V show version\n"
  5433. " -x notis, sel to system clipboard\n"
  5434. " -h show help\n\n"
  5435. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  5436. }
  5437. static bool setup_config(void)
  5438. {
  5439. size_t r, len;
  5440. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  5441. bool xdg = FALSE;
  5442. /* Set up configuration file paths */
  5443. if (xdgcfg && xdgcfg[0]) {
  5444. DPRINTF_S(xdgcfg);
  5445. if (xdgcfg[0] == '~') {
  5446. r = xstrlcpy(g_buf, home, PATH_MAX);
  5447. xstrlcpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  5448. xdgcfg = g_buf;
  5449. DPRINTF_S(xdgcfg);
  5450. }
  5451. if (!xdiraccess(xdgcfg)) {
  5452. xerror();
  5453. return FALSE;
  5454. }
  5455. len = strlen(xdgcfg) + 1 + 13; /* add length of "/nnn/sessions" */
  5456. xdg = TRUE;
  5457. }
  5458. if (!xdg)
  5459. len = strlen(home) + 1 + 21; /* add length of "/.config/nnn/sessions" */
  5460. cfgdir = (char *)malloc(len);
  5461. plugindir = (char *)malloc(len);
  5462. sessiondir = (char *)malloc(len);
  5463. if (!cfgdir || !plugindir || !sessiondir) {
  5464. xerror();
  5465. return FALSE;
  5466. }
  5467. if (xdg) {
  5468. xstrlcpy(cfgdir, xdgcfg, len);
  5469. r = len - 13; /* subtract length of "/nnn/sessions" */
  5470. } else {
  5471. r = xstrlcpy(cfgdir, home, len);
  5472. /* Create ~/.config */
  5473. xstrlcpy(cfgdir + r - 1, "/.config", len - r);
  5474. DPRINTF_S(cfgdir);
  5475. r += 8; /* length of "/.config" */
  5476. }
  5477. /* Create ~/.config/nnn */
  5478. xstrlcpy(cfgdir + r - 1, "/nnn", len - r);
  5479. DPRINTF_S(cfgdir);
  5480. /* Create ~/.config/nnn/plugins */
  5481. xstrlcpy(cfgdir + r + 4 - 1, "/plugins", 9); /* subtract length of "/nnn" (4) */
  5482. DPRINTF_S(cfgdir);
  5483. xstrlcpy(plugindir, cfgdir, len);
  5484. DPRINTF_S(plugindir);
  5485. if (access(plugindir, F_OK) && !xmktree(plugindir, TRUE)) {
  5486. xerror();
  5487. return FALSE;
  5488. }
  5489. /* Create ~/.config/nnn/sessions */
  5490. xstrlcpy(cfgdir + r + 4 - 1, "/sessions", 10); /* subtract length of "/nnn" (4) */
  5491. DPRINTF_S(cfgdir);
  5492. xstrlcpy(sessiondir, cfgdir, len);
  5493. DPRINTF_S(sessiondir);
  5494. if (access(sessiondir, F_OK) && !xmktree(sessiondir, TRUE)) {
  5495. xerror();
  5496. return FALSE;
  5497. }
  5498. /* Reset to config path */
  5499. cfgdir[r + 3] = '\0';
  5500. DPRINTF_S(cfgdir);
  5501. /* Set selection file path */
  5502. if (!cfg.picker) {
  5503. /* Length of "/.config/nnn/.selection" */
  5504. g_selpath = (char *)malloc(len + 3);
  5505. if (!g_selpath) {
  5506. xerror();
  5507. return FALSE;
  5508. }
  5509. r = xstrlcpy(g_selpath, cfgdir, len + 3);
  5510. xstrlcpy(g_selpath + r - 1, "/.selection", 12);
  5511. DPRINTF_S(g_selpath);
  5512. }
  5513. return TRUE;
  5514. }
  5515. static bool set_tmp_path(void)
  5516. {
  5517. char *tmp = "/tmp";
  5518. char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
  5519. if (!path) {
  5520. fprintf(stderr, "set TMPDIR\n");
  5521. return FALSE;
  5522. }
  5523. g_tmpfplen = (uchar)xstrlcpy(g_tmpfpath, path, TMP_LEN_MAX);
  5524. return TRUE;
  5525. }
  5526. static void cleanup(void)
  5527. {
  5528. free(g_selpath);
  5529. free(plugindir);
  5530. free(sessiondir);
  5531. free(cfgdir);
  5532. free(initpath);
  5533. free(bmstr);
  5534. free(pluginstr);
  5535. free(g_prefixpath);
  5536. free(ihashbmp);
  5537. free(bookmark);
  5538. free(plug);
  5539. unlink(g_pipepath);
  5540. #ifdef DBGMODE
  5541. disabledbg();
  5542. #endif
  5543. }
  5544. int main(int argc, char *argv[])
  5545. {
  5546. char *arg = NULL;
  5547. char *session = NULL;
  5548. int opt;
  5549. #ifndef NOMOUSE
  5550. mmask_t mask;
  5551. #endif
  5552. const char* const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
  5553. int env_opts_id = env_opts ? (int)strlen(env_opts) : -1;
  5554. while ((opt = (env_opts_id > 0
  5555. ? env_opts[--env_opts_id]
  5556. : getopt(argc, argv, "aAb:cdeEgHKnop:QrRs:St:vVxh"))) != -1) {
  5557. switch (opt) {
  5558. case 'a':
  5559. cfg.mtime = 0;
  5560. break;
  5561. case 'A':
  5562. cfg.autoselect = 0;
  5563. break;
  5564. case 'b':
  5565. arg = optarg;
  5566. break;
  5567. case 'c':
  5568. cfg.cliopener = 1;
  5569. break;
  5570. case 'S':
  5571. cfg.blkorder = 1;
  5572. nftw_fn = sum_bsize;
  5573. blk_shift = ffs(S_BLKSIZE) - 1; // fallthrough
  5574. case 'd':
  5575. cfg.showdetail = 1;
  5576. printptr = &printent_long;
  5577. break;
  5578. case 'e':
  5579. cfg.useeditor = 1;
  5580. break;
  5581. case 'E':
  5582. cfg.waitedit = 1;
  5583. break;
  5584. case 'g':
  5585. cfg.regex = 1;
  5586. filterfn = &visible_re;
  5587. break;
  5588. case 'H':
  5589. cfg.showhidden = 1;
  5590. break;
  5591. case 'K':
  5592. check_key_collision();
  5593. return _SUCCESS;
  5594. case 'n':
  5595. cfg.filtermode = 1;
  5596. break;
  5597. case 'o':
  5598. cfg.nonavopen = 1;
  5599. break;
  5600. case 'p':
  5601. if (env_opts_id >= 0)
  5602. break;
  5603. cfg.picker = 1;
  5604. if (optarg[0] == '-' && optarg[1] == '\0')
  5605. cfg.pickraw = 1;
  5606. else {
  5607. int fd = open(optarg, O_WRONLY | O_CREAT, 0600);
  5608. if (fd == -1) {
  5609. xerror();
  5610. return _FAILURE;
  5611. }
  5612. close(fd);
  5613. g_selpath = realpath(optarg, NULL);
  5614. unlink(g_selpath);
  5615. }
  5616. break;
  5617. case 'Q':
  5618. cfg.forcequit = 1;
  5619. break;
  5620. case 'r':
  5621. #ifdef __linux__
  5622. cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
  5623. cp[4] = mv[4] = '-';
  5624. #endif
  5625. break;
  5626. case 'R':
  5627. cfg.rollover = 0;
  5628. break;
  5629. case 's':
  5630. if (env_opts_id < 0)
  5631. session = optarg;
  5632. break;
  5633. case 't':
  5634. if (env_opts_id < 0)
  5635. idletimeout = atoi(optarg);
  5636. break;
  5637. case 'v':
  5638. namecmpfn = &xstrverscasecmp;
  5639. break;
  5640. case 'V':
  5641. fprintf(stdout, "%s\n", VERSION);
  5642. return _SUCCESS;
  5643. case 'x':
  5644. cfg.x11 = 1;
  5645. break;
  5646. case 'h':
  5647. usage();
  5648. return _SUCCESS;
  5649. default:
  5650. usage();
  5651. return _FAILURE;
  5652. }
  5653. }
  5654. #ifdef DBGMODE
  5655. enabledbg();
  5656. DPRINTF_S(VERSION);
  5657. #endif
  5658. /* Prefix for temporary files */
  5659. if (!set_tmp_path())
  5660. return _FAILURE;
  5661. atexit(cleanup);
  5662. if (!cfg.picker) {
  5663. /* Confirm we are in a terminal */
  5664. if (!isatty(STDOUT_FILENO))
  5665. exit(1);
  5666. /* Now we are in path list mode */
  5667. if (!isatty(STDIN_FILENO)) {
  5668. /* This is the same as g_listpath */
  5669. initpath = load_input();
  5670. if (!initpath)
  5671. exit(1);
  5672. /* We return to tty */
  5673. dup2(STDOUT_FILENO, STDIN_FILENO);
  5674. }
  5675. }
  5676. home = getenv("HOME");
  5677. if (!home) {
  5678. fprintf(stderr, "set HOME\n");
  5679. return _FAILURE;
  5680. }
  5681. DPRINTF_S(home);
  5682. if (!setup_config())
  5683. return _FAILURE;
  5684. /* Get custom opener, if set */
  5685. opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
  5686. DPRINTF_S(opener);
  5687. /* Parse bookmarks string */
  5688. if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
  5689. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  5690. return _FAILURE;
  5691. }
  5692. /* Parse plugins string */
  5693. if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
  5694. fprintf(stderr, "%s\n", env_cfg[NNN_PLUG]);
  5695. return _FAILURE;
  5696. }
  5697. if (!initpath) {
  5698. if (arg) { /* Open a bookmark directly */
  5699. if (!arg[1]) /* Bookmarks keys are single char */
  5700. initpath = get_kv_val(bookmark, NULL, *arg, maxbm, TRUE);
  5701. if (!initpath) {
  5702. fprintf(stderr, "%s\n", messages[MSG_INVALID_KEY]);
  5703. return _FAILURE;
  5704. }
  5705. } else if (argc == optind) {
  5706. /* Start in the current directory */
  5707. initpath = getcwd(NULL, PATH_MAX);
  5708. if (!initpath)
  5709. initpath = "/";
  5710. } else {
  5711. arg = argv[optind];
  5712. DPRINTF_S(arg);
  5713. if (strlen(arg) > 7 && !strncmp(arg, "file://", 7))
  5714. arg = arg + 7;
  5715. initpath = realpath(arg, NULL);
  5716. DPRINTF_S(initpath);
  5717. if (!initpath) {
  5718. xerror();
  5719. return _FAILURE;
  5720. }
  5721. /*
  5722. * If nnn is set as the file manager, applications may try to open
  5723. * files by invoking nnn. In that case pass the file path to the
  5724. * desktop opener and exit.
  5725. */
  5726. struct stat sb;
  5727. if (stat(initpath, &sb) == -1) {
  5728. xerror();
  5729. return _FAILURE;
  5730. }
  5731. if (S_ISREG(sb.st_mode)) {
  5732. spawn(opener, arg, NULL, NULL, cfg.cliopener ? F_CLI : F_NOTRACE | F_NOWAIT);
  5733. return _SUCCESS;
  5734. }
  5735. }
  5736. }
  5737. /* Set archive handling (enveditor used as tmp var) */
  5738. enveditor = getenv(env_cfg[NNN_ARCHIVE]);
  5739. #ifdef PCRE
  5740. if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5741. #else
  5742. if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5743. #endif
  5744. fprintf(stderr, "%s\n", messages[MSG_INVALID_REG]);
  5745. return _FAILURE;
  5746. }
  5747. /* An all-CLI opener overrides option -e) */
  5748. if (cfg.cliopener)
  5749. cfg.useeditor = 0;
  5750. /* Get VISUAL/EDITOR */
  5751. enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
  5752. editor = xgetenv(envs[ENV_VISUAL], enveditor);
  5753. DPRINTF_S(getenv(envs[ENV_VISUAL]));
  5754. DPRINTF_S(getenv(envs[ENV_EDITOR]));
  5755. DPRINTF_S(editor);
  5756. /* Get PAGER */
  5757. pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
  5758. DPRINTF_S(pager);
  5759. /* Get SHELL */
  5760. shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
  5761. DPRINTF_S(shell);
  5762. DPRINTF_S(getenv("PWD"));
  5763. #ifdef LINUX_INOTIFY
  5764. /* Initialize inotify */
  5765. inotify_fd = inotify_init1(IN_NONBLOCK);
  5766. if (inotify_fd < 0) {
  5767. xerror();
  5768. return _FAILURE;
  5769. }
  5770. #elif defined(BSD_KQUEUE)
  5771. kq = kqueue();
  5772. if (kq < 0) {
  5773. xerror();
  5774. return _FAILURE;
  5775. }
  5776. #elif defined(HAIKU_NM)
  5777. haiku_hnd = haiku_init_nm();
  5778. if (!haiku_hnd) {
  5779. xerror();
  5780. return _FAILURE;
  5781. }
  5782. #endif
  5783. /* Configure trash preference */
  5784. if (xgetenv_set(env_cfg[NNN_TRASH]))
  5785. g_states |= STATE_TRASH;
  5786. /* Ignore/handle certain signals */
  5787. struct sigaction act = {.sa_handler = sigint_handler};
  5788. if (sigaction(SIGINT, &act, NULL) < 0) {
  5789. xerror();
  5790. return _FAILURE;
  5791. }
  5792. signal(SIGQUIT, SIG_IGN);
  5793. #ifndef NOLOCALE
  5794. /* Set locale */
  5795. setlocale(LC_ALL, "");
  5796. #ifdef PCRE
  5797. tables = pcre_maketables();
  5798. #endif
  5799. #endif
  5800. #ifndef NORL
  5801. #if RL_READLINE_VERSION >= 0x0603
  5802. /* readline would overwrite the WINCH signal hook */
  5803. rl_change_environment = 0;
  5804. #endif
  5805. /* Bind TAB to cycling */
  5806. rl_variable_bind("completion-ignore-case", "on");
  5807. #ifdef __linux__
  5808. rl_bind_key('\t', rl_menu_complete);
  5809. #else
  5810. rl_bind_key('\t', rl_complete);
  5811. #endif
  5812. mkpath(cfgdir, ".history", g_buf);
  5813. read_history(g_buf);
  5814. #endif
  5815. #ifndef NOMOUSE
  5816. if (!initcurses(&mask))
  5817. #else
  5818. if (!initcurses(NULL))
  5819. #endif
  5820. return _FAILURE;
  5821. opt = browse(initpath, session);
  5822. #ifndef NOMOUSE
  5823. mousemask(mask, NULL);
  5824. #endif
  5825. if (g_listpath)
  5826. spawn("rm -rf", initpath, NULL, NULL, F_SILENT);
  5827. exitcurses();
  5828. #ifndef NORL
  5829. mkpath(cfgdir, ".history", g_buf);
  5830. write_history(g_buf);
  5831. #endif
  5832. if (cfg.pickraw) {
  5833. if (selbufpos && (seltofile(1, NULL) != (size_t)(selbufpos)))
  5834. xerror();
  5835. } else if (cfg.picker) {
  5836. if (selbufpos)
  5837. writesel(pselbuf, selbufpos - 1);
  5838. } else if (g_selpath)
  5839. unlink(g_selpath);
  5840. /* Free the regex */
  5841. #ifdef PCRE
  5842. pcre_free(archive_pcre);
  5843. #else
  5844. regfree(&archive_re);
  5845. #endif
  5846. /* Free the selection buffer */
  5847. free(pselbuf);
  5848. #ifdef LINUX_INOTIFY
  5849. /* Shutdown inotify */
  5850. if (inotify_wd >= 0)
  5851. inotify_rm_watch(inotify_fd, inotify_wd);
  5852. close(inotify_fd);
  5853. #elif defined(BSD_KQUEUE)
  5854. if (event_fd >= 0)
  5855. close(event_fd);
  5856. close(kq);
  5857. #elif defined(HAIKU_NM)
  5858. haiku_close_nm(haiku_hnd);
  5859. #endif
  5860. return opt;
  5861. }