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.
 
 
 
 
 
 

6926 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. *ch = CONTROL('L');
  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. ptr = *envcpy;
  2478. nextkey = ptr;
  2479. while (*ptr && i < maxitems) {
  2480. if (ptr == nextkey) {
  2481. kvarr[i].key = *ptr;
  2482. if (*++ptr != ':')
  2483. return FALSE;
  2484. if (*++ptr == '\0')
  2485. return FALSE;
  2486. kvarr[i].val = ptr;
  2487. ++i;
  2488. }
  2489. if (*ptr == ';') {
  2490. /* Remove trailing space */
  2491. if (i > 0 && *(ptr - 1) == '/')
  2492. *(ptr - 1) = '\0';
  2493. *ptr = '\0';
  2494. nextkey = ptr + 1;
  2495. }
  2496. ++ptr;
  2497. }
  2498. if (i < maxitems) {
  2499. if (kvarr[i - 1].val && *kvarr[i - 1].val == '\0')
  2500. return FALSE;
  2501. kvarr[i].key = '\0';
  2502. }
  2503. for (i = 0; i < maxitems && kvarr[i].key; ++i)
  2504. if (strlen(kvarr[i].val) >= PATH_MAX)
  2505. return FALSE;
  2506. *items = maxitems;
  2507. return TRUE;
  2508. }
  2509. /*
  2510. * Get the value corresponding to a key
  2511. *
  2512. * NULL is returned in case of no match, path resolution failure etc.
  2513. * buf would be modified, so check return value before access
  2514. */
  2515. static char *get_kv_val(kv *kvarr, char *buf, int key, uchar max, bool path)
  2516. {
  2517. int r = 0;
  2518. for (; kvarr[r].key && r < max; ++r) {
  2519. if (kvarr[r].key == key) {
  2520. if (!path)
  2521. return kvarr[r].val;
  2522. if (kvarr[r].val[0] == '~') {
  2523. ssize_t len = strlen(home);
  2524. ssize_t loclen = strlen(kvarr[r].val);
  2525. if (!buf) {
  2526. buf = (char *)malloc(len + loclen);
  2527. if (!buf) {
  2528. DPRINTF_S(strerror(errno));
  2529. return NULL;
  2530. }
  2531. }
  2532. xstrlcpy(buf, home, len + 1);
  2533. xstrlcpy(buf + len, kvarr[r].val + 1, loclen);
  2534. return buf;
  2535. }
  2536. return realpath(kvarr[r].val, buf);
  2537. }
  2538. }
  2539. DPRINTF_S("Invalid key");
  2540. return NULL;
  2541. }
  2542. static void resetdircolor(int flags)
  2543. {
  2544. if (cfg.dircolor && !(flags & DIR_OR_LINK_TO_DIR)) {
  2545. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  2546. cfg.dircolor = 0;
  2547. }
  2548. }
  2549. /*
  2550. * Replace escape characters in a string with '?'
  2551. * Adjust string length to maxcols if > 0;
  2552. * Max supported str length: NAME_MAX;
  2553. */
  2554. static wchar_t *unescape(const char *str, uint maxcols)
  2555. {
  2556. wchar_t * const wbuf = (wchar_t *)g_buf;
  2557. wchar_t *buf = wbuf;
  2558. size_t lencount = 0;
  2559. #ifdef NOLOCALE
  2560. memset(wbuf, 0, sizeof(NAME_MAX + 1) * sizeof(wchar_t));
  2561. #endif
  2562. /* Convert multi-byte to wide char */
  2563. size_t len = mbstowcs(wbuf, str, NAME_MAX);
  2564. len = wcswidth(wbuf, len);
  2565. /* Reduce number of wide chars to max columns */
  2566. if (len > maxcols) {
  2567. while (*buf && lencount <= maxcols) {
  2568. if (*buf <= '\x1f' || *buf == '\x7f')
  2569. *buf = '\?';
  2570. ++buf;
  2571. ++lencount;
  2572. }
  2573. lencount = maxcols + 1;
  2574. /* Reduce wide chars one by one till it fits */
  2575. do
  2576. len = wcswidth(wbuf, --lencount);
  2577. while (len > maxcols);
  2578. wbuf[lencount] = L'\0';
  2579. } else {
  2580. do /* We do not expect a NULL string */
  2581. if (*buf <= '\x1f' || *buf == '\x7f')
  2582. *buf = '\?';
  2583. while (*++buf);
  2584. }
  2585. return wbuf;
  2586. }
  2587. static char *coolsize(off_t size)
  2588. {
  2589. const char * const U = "BKMGTPEZY";
  2590. static char size_buf[12]; /* Buffer to hold human readable size */
  2591. off_t rem = 0;
  2592. size_t ret;
  2593. int i = 0;
  2594. while (size >= 1024) {
  2595. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  2596. size >>= 10;
  2597. ++i;
  2598. }
  2599. if (i == 1) {
  2600. rem = (rem * 1000) >> 10;
  2601. rem /= 10;
  2602. if (rem % 10 >= 5) {
  2603. rem = (rem / 10) + 1;
  2604. if (rem == 10) {
  2605. ++size;
  2606. rem = 0;
  2607. }
  2608. } else
  2609. rem /= 10;
  2610. } else if (i == 2) {
  2611. rem = (rem * 1000) >> 10;
  2612. if (rem % 10 >= 5) {
  2613. rem = (rem / 10) + 1;
  2614. if (rem == 100) {
  2615. ++size;
  2616. rem = 0;
  2617. }
  2618. } else
  2619. rem /= 10;
  2620. } else if (i > 0) {
  2621. rem = (rem * 10000) >> 10;
  2622. if (rem % 10 >= 5) {
  2623. rem = (rem / 10) + 1;
  2624. if (rem == 1000) {
  2625. ++size;
  2626. rem = 0;
  2627. }
  2628. } else
  2629. rem /= 10;
  2630. }
  2631. if (i > 0 && i < 6 && rem) {
  2632. ret = xstrlcpy(size_buf, xitoa(size), 12);
  2633. size_buf[ret - 1] = '.';
  2634. char *frac = xitoa(rem);
  2635. size_t toprint = i > 3 ? 3 : i;
  2636. size_t len = strlen(frac);
  2637. if (len < toprint) {
  2638. size_buf[ret] = size_buf[ret + 1] = size_buf[ret + 2] = '0';
  2639. xstrlcpy(size_buf + ret + (toprint - len), frac, len + 1);
  2640. } else
  2641. xstrlcpy(size_buf + ret, frac, toprint + 1);
  2642. ret += toprint;
  2643. } else {
  2644. ret = xstrlcpy(size_buf, size ? xitoa(size) : "0", 12);
  2645. --ret;
  2646. }
  2647. size_buf[ret] = U[i];
  2648. size_buf[ret + 1] = '\0';
  2649. return size_buf;
  2650. }
  2651. static char get_ind(mode_t mode, bool perms)
  2652. {
  2653. switch (mode & S_IFMT) {
  2654. case S_IFREG:
  2655. if (perms)
  2656. return '-';
  2657. if (mode & 0100)
  2658. return '*';
  2659. return '\0';
  2660. case S_IFDIR:
  2661. return perms ? 'd' : '\0';
  2662. case S_IFLNK:
  2663. return perms ? 'l' : '@';
  2664. case S_IFSOCK:
  2665. return perms ? 's' : '=';
  2666. case S_IFIFO:
  2667. return perms ? 'p' : '|';
  2668. case S_IFBLK:
  2669. return perms ? 'b' : '\0';
  2670. case S_IFCHR:
  2671. return perms ? 'c' : '\0';
  2672. default:
  2673. return '?';
  2674. }
  2675. }
  2676. /* Convert a mode field into "ls -l" type perms field. */
  2677. static char *get_lsperms(mode_t mode)
  2678. {
  2679. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  2680. static char bits[11] = {'\0'};
  2681. bits[0] = get_ind(mode, TRUE);
  2682. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  2683. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  2684. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  2685. if (mode & S_ISUID)
  2686. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  2687. if (mode & S_ISGID)
  2688. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  2689. if (mode & S_ISVTX)
  2690. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  2691. return bits;
  2692. }
  2693. static void print_time(const time_t *timep)
  2694. {
  2695. struct tm *t = localtime(timep);
  2696. printw("%d-%02d-%02d %02d:%02d",
  2697. t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min);
  2698. }
  2699. static void printent(const struct entry *ent, uint namecols, bool sel)
  2700. {
  2701. char ind = get_ind(ent->mode, FALSE);
  2702. int attrs = sel ? A_REVERSE : 0;
  2703. if (ind == '@' || (ent->flags & HARD_LINK))
  2704. attrs |= A_DIM;
  2705. if (!ind)
  2706. ++namecols;
  2707. /* Directories are always shown on top */
  2708. resetdircolor(ent->flags);
  2709. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2710. if (attrs)
  2711. attron(attrs);
  2712. addwstr(unescape(ent->name, namecols));
  2713. if (attrs)
  2714. attroff(attrs);
  2715. if (ind)
  2716. addch(ind);
  2717. addch('\n');
  2718. }
  2719. static void printent_long(const struct entry *ent, uint namecols, bool sel)
  2720. {
  2721. bool ln = FALSE;
  2722. char ind1 = '\0', ind2 = '\0';
  2723. int attrs = sel ? A_REVERSE : 0;
  2724. uint len;
  2725. char *size;
  2726. /* Directories are always shown on top */
  2727. resetdircolor(ent->flags);
  2728. addch((ent->flags & FILE_SELECTED) ? '+' : ' ');
  2729. if (attrs)
  2730. attron(attrs);
  2731. /* Timestamp */
  2732. print_time(&ent->t);
  2733. addstr(" ");
  2734. /* Permissions */
  2735. addch('0' + ((ent->mode >> 6) & 7));
  2736. addch('0' + ((ent->mode >> 3) & 7));
  2737. addch('0' + (ent->mode & 7));
  2738. switch (ent->mode & S_IFMT) {
  2739. case S_IFREG:
  2740. if (ent->flags & HARD_LINK)
  2741. ln = TRUE;
  2742. if (ent->mode & 0100)
  2743. ind2 = '*';
  2744. // fallthrough
  2745. case S_IFDIR:
  2746. if (!ind2) /* Add a column if end indicator is not needed */
  2747. ++namecols;
  2748. size = coolsize(cfg.blkorder ? ent->blocks << blk_shift : ent->size);
  2749. len = 10 - (uint)strlen(size);
  2750. while (--len)
  2751. addch(' ');
  2752. addstr(size);
  2753. break;
  2754. case S_IFLNK:
  2755. ln = TRUE;
  2756. ind1 = ind2 = '@'; // fallthrough
  2757. case S_IFSOCK:
  2758. if (!ind1)
  2759. ind1 = ind2 = '='; // fallthrough
  2760. case S_IFIFO:
  2761. if (!ind1)
  2762. ind1 = ind2 = '|'; // fallthrough
  2763. case S_IFBLK:
  2764. if (!ind1)
  2765. ind1 = 'b'; // fallthrough
  2766. case S_IFCHR:
  2767. if (!ind1)
  2768. ind1 = 'c'; // fallthrough
  2769. default:
  2770. if (!ind1)
  2771. ind1 = ind2 = '?';
  2772. addstr(" ");
  2773. addch(ind1);
  2774. break;
  2775. }
  2776. addstr(" ");
  2777. if (ln) {
  2778. attron(A_DIM);
  2779. attrs |= A_DIM;
  2780. }
  2781. addwstr(unescape(ent->name, namecols));
  2782. if (attrs)
  2783. attroff(attrs);
  2784. if (ind2)
  2785. addch(ind2);
  2786. addch('\n');
  2787. }
  2788. static void (*printptr)(const struct entry *ent, uint namecols, bool sel) = &printent;
  2789. static void savecurctx(settings *curcfg, char *path, char *curname, int r /* next context num */)
  2790. {
  2791. settings cfg = *curcfg;
  2792. bool selmode = cfg.selmode ? TRUE : FALSE;
  2793. /* Save current context */
  2794. xstrlcpy(g_ctx[cfg.curctx].c_name, curname, NAME_MAX + 1);
  2795. g_ctx[cfg.curctx].c_cfg = cfg;
  2796. if (g_ctx[r].c_cfg.ctxactive) { /* Switch to saved context */
  2797. /* Switch light/detail mode */
  2798. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  2799. /* set the reverse */
  2800. printptr = cfg.showdetail ? &printent : &printent_long;
  2801. cfg = g_ctx[r].c_cfg;
  2802. } else { /* Setup a new context from current context */
  2803. g_ctx[r].c_cfg.ctxactive = 1;
  2804. xstrlcpy(g_ctx[r].c_path, path, PATH_MAX);
  2805. g_ctx[r].c_last[0] = '\0';
  2806. g_ctx[r].c_name[0] = '\0';
  2807. g_ctx[r].c_fltr[0] = g_ctx[r].c_fltr[1] = '\0';
  2808. g_ctx[r].c_cfg = cfg;
  2809. g_ctx[r].c_cfg.runplugin = 0;
  2810. }
  2811. /* Continue selection mode */
  2812. cfg.selmode = selmode;
  2813. cfg.curctx = r;
  2814. *curcfg = cfg;
  2815. }
  2816. static void save_session(bool last_session, int *presel)
  2817. {
  2818. char spath[PATH_MAX];
  2819. int i;
  2820. session_header_t header;
  2821. FILE *fsession;
  2822. char *sname;
  2823. bool status = FALSE;
  2824. memset(&header, 0, sizeof(session_header_t));
  2825. header.ver = SESSIONS_VERSION;
  2826. for (i = 0; i < CTX_MAX; ++i) {
  2827. if (g_ctx[i].c_cfg.ctxactive) {
  2828. if (cfg.curctx == i && ndents)
  2829. /* Update current file name, arrows don't update it */
  2830. xstrlcpy(g_ctx[i].c_name, dents[cur].name, NAME_MAX + 1);
  2831. header.pathln[i] = strnlen(g_ctx[i].c_path, PATH_MAX) + 1;
  2832. header.lastln[i] = strnlen(g_ctx[i].c_last, PATH_MAX) + 1;
  2833. header.nameln[i] = strnlen(g_ctx[i].c_name, NAME_MAX) + 1;
  2834. header.fltrln[i] = strnlen(g_ctx[i].c_fltr, REGEX_MAX) + 1;
  2835. }
  2836. }
  2837. sname = !last_session ? xreadline(NULL, messages[MSG_SSN_NAME]) : "@";
  2838. if (!sname[0])
  2839. return;
  2840. mkpath(sessiondir, sname, spath);
  2841. fsession = fopen(spath, "wb");
  2842. if (!fsession) {
  2843. printwait(messages[MSG_ACCESS], presel);
  2844. return;
  2845. }
  2846. if ((fwrite(&header, sizeof(header), 1, fsession) != 1)
  2847. || (fwrite(&cfg, sizeof(cfg), 1, fsession) != 1))
  2848. goto END;
  2849. for (i = 0; i < CTX_MAX; ++i)
  2850. if ((fwrite(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2851. || (fwrite(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2852. || (header.nameln[i] > 0
  2853. && fwrite(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2854. || (header.lastln[i] > 0
  2855. && fwrite(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2856. || (header.fltrln[i] > 0
  2857. && fwrite(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2858. || (header.pathln[i] > 0
  2859. && fwrite(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2860. goto END;
  2861. status = TRUE;
  2862. END:
  2863. fclose(fsession);
  2864. if (!status)
  2865. printwait(messages[MSG_FAILED], presel);
  2866. }
  2867. static bool load_session(const char *sname, char **path, char **lastdir, char **lastname, bool restore)
  2868. {
  2869. char spath[PATH_MAX];
  2870. int i = 0;
  2871. session_header_t header;
  2872. FILE *fsession;
  2873. bool has_loaded_dynamically = !(sname || restore);
  2874. bool status = FALSE;
  2875. if (!restore) {
  2876. sname = sname ? sname : xreadline(NULL, messages[MSG_SSN_NAME]);
  2877. if (!sname[0])
  2878. return FALSE;
  2879. mkpath(sessiondir, sname, spath);
  2880. } else
  2881. mkpath(sessiondir, "@", spath);
  2882. if (has_loaded_dynamically)
  2883. save_session(TRUE, NULL);
  2884. fsession = fopen(spath, "rb");
  2885. if (!fsession) {
  2886. printmsg(messages[MSG_ACCESS]);
  2887. xdelay(XDELAY_INTERVAL_MS);
  2888. return FALSE;
  2889. }
  2890. if ((fread(&header, sizeof(header), 1, fsession) != 1)
  2891. || (header.ver != SESSIONS_VERSION)
  2892. || (fread(&cfg, sizeof(cfg), 1, fsession) != 1))
  2893. goto END;
  2894. g_ctx[cfg.curctx].c_name[0] = g_ctx[cfg.curctx].c_last[0]
  2895. = g_ctx[cfg.curctx].c_fltr[0] = g_ctx[cfg.curctx].c_fltr[1] = '\0';
  2896. for (; i < CTX_MAX; ++i)
  2897. if ((fread(&g_ctx[i].c_cfg, sizeof(settings), 1, fsession) != 1)
  2898. || (fread(&g_ctx[i].color, sizeof(uint), 1, fsession) != 1)
  2899. || (header.nameln[i] > 0
  2900. && fread(g_ctx[i].c_name, header.nameln[i], 1, fsession) != 1)
  2901. || (header.lastln[i] > 0
  2902. && fread(g_ctx[i].c_last, header.lastln[i], 1, fsession) != 1)
  2903. || (header.fltrln[i] > 0
  2904. && fread(g_ctx[i].c_fltr, header.fltrln[i], 1, fsession) != 1)
  2905. || (header.pathln[i] > 0
  2906. && fread(g_ctx[i].c_path, header.pathln[i], 1, fsession) != 1))
  2907. goto END;
  2908. *path = g_ctx[cfg.curctx].c_path;
  2909. *lastdir = g_ctx[cfg.curctx].c_last;
  2910. *lastname = g_ctx[cfg.curctx].c_name;
  2911. printptr = cfg.showdetail ? &printent_long : &printent;
  2912. status = TRUE;
  2913. END:
  2914. fclose(fsession);
  2915. if (!status) {
  2916. printmsg(messages[MSG_FAILED]);
  2917. xdelay(XDELAY_INTERVAL_MS);
  2918. } else if (restore)
  2919. unlink(spath);
  2920. return status;
  2921. }
  2922. /*
  2923. * Gets only a single line (that's what we need
  2924. * for now) or shows full command output in pager.
  2925. *
  2926. * If page is valid, returns NULL
  2927. */
  2928. static char *get_output(char *buf, const size_t bytes, const char *file,
  2929. const char *arg1, const char *arg2, const bool page)
  2930. {
  2931. pid_t pid;
  2932. int pipefd[2];
  2933. FILE *pf;
  2934. int tmp, flags;
  2935. char *ret = NULL;
  2936. if (pipe(pipefd) == -1)
  2937. errexit();
  2938. for (tmp = 0; tmp < 2; ++tmp) {
  2939. /* Get previous flags */
  2940. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  2941. /* Set bit for non-blocking flag */
  2942. flags |= O_NONBLOCK;
  2943. /* Change flags on fd */
  2944. fcntl(pipefd[tmp], F_SETFL, flags);
  2945. }
  2946. pid = fork();
  2947. if (pid == 0) {
  2948. /* In child */
  2949. close(pipefd[0]);
  2950. dup2(pipefd[1], STDOUT_FILENO);
  2951. dup2(pipefd[1], STDERR_FILENO);
  2952. close(pipefd[1]);
  2953. execlp(file, file, arg1, arg2, NULL);
  2954. _exit(1);
  2955. }
  2956. /* In parent */
  2957. waitpid(pid, &tmp, 0);
  2958. close(pipefd[1]);
  2959. if (!page) {
  2960. pf = fdopen(pipefd[0], "r");
  2961. if (pf) {
  2962. ret = fgets(buf, bytes, pf);
  2963. close(pipefd[0]);
  2964. }
  2965. return ret;
  2966. }
  2967. pid = fork();
  2968. if (pid == 0) {
  2969. /* Show in pager in child */
  2970. dup2(pipefd[0], STDIN_FILENO);
  2971. close(pipefd[0]);
  2972. spawn(pager, NULL, NULL, NULL, F_CLI);
  2973. _exit(1);
  2974. }
  2975. /* In parent */
  2976. waitpid(pid, &tmp, 0);
  2977. close(pipefd[0]);
  2978. return NULL;
  2979. }
  2980. static inline bool getutil(char *util)
  2981. {
  2982. return spawn("which", util, NULL, NULL, F_NORMAL | F_NOTRACE) == 0;
  2983. }
  2984. static void pipetof(char *cmd, FILE *fout)
  2985. {
  2986. FILE *fin = popen(cmd, "r");
  2987. if (fin) {
  2988. while (fgets(g_buf, CMD_LEN_MAX - 1, fin))
  2989. fprintf(fout, "%s", g_buf);
  2990. pclose(fin);
  2991. }
  2992. }
  2993. /*
  2994. * Follows the stat(1) output closely
  2995. */
  2996. static bool show_stats(const char *fpath, const struct stat *sb)
  2997. {
  2998. int fd;
  2999. FILE *fp;
  3000. char *p, *begin = g_buf;
  3001. size_t r;
  3002. fd = create_tmp_file();
  3003. if (fd == -1)
  3004. return FALSE;
  3005. r = xstrlcpy(g_buf, "stat \"", PATH_MAX);
  3006. r += xstrlcpy(g_buf + r - 1, fpath, PATH_MAX);
  3007. g_buf[r - 2] = '\"';
  3008. g_buf[r - 1] = '\0';
  3009. DPRINTF_S(g_buf);
  3010. fp = fdopen(fd, "w");
  3011. if (!fp) {
  3012. close(fd);
  3013. return FALSE;
  3014. }
  3015. pipetof(g_buf, fp);
  3016. if (S_ISREG(sb->st_mode)) {
  3017. /* Show file(1) output */
  3018. p = get_output(g_buf, CMD_LEN_MAX, "file", "-b", fpath, FALSE);
  3019. if (p) {
  3020. fprintf(fp, "\n\n ");
  3021. while (*p) {
  3022. if (*p == ',') {
  3023. *p = '\0';
  3024. fprintf(fp, " %s\n", begin);
  3025. begin = p + 1;
  3026. }
  3027. ++p;
  3028. }
  3029. fprintf(fp, " %s\n ", begin);
  3030. /* Show the file mime type */
  3031. get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, fpath, FALSE);
  3032. fprintf(fp, "%s", g_buf);
  3033. }
  3034. }
  3035. fprintf(fp, "\n");
  3036. fclose(fp);
  3037. close(fd);
  3038. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3039. unlink(g_tmpfpath);
  3040. return TRUE;
  3041. }
  3042. static bool xchmod(const char *fpath, mode_t mode)
  3043. {
  3044. /* (Un)set (S_IXUSR | S_IXGRP | S_IXOTH) */
  3045. (0100 & mode) ? (mode &= ~0111) : (mode |= 0111);
  3046. return (chmod(fpath, mode) == 0);
  3047. }
  3048. static size_t get_fs_info(const char *path, bool type)
  3049. {
  3050. struct statvfs svb;
  3051. if (statvfs(path, &svb) == -1)
  3052. return 0;
  3053. if (type == CAPACITY)
  3054. return svb.f_blocks << ffs((int)(svb.f_frsize >> 1));
  3055. return svb.f_bavail << ffs((int)(svb.f_frsize >> 1));
  3056. }
  3057. /* List or extract archive */
  3058. static void handle_archive(char *fpath, const char *dir, char op)
  3059. {
  3060. char arg[] = "-tvf"; /* options for tar/bsdtar to list files */
  3061. char *util;
  3062. if (getutil(utils[UTIL_ATOOL])) {
  3063. util = utils[UTIL_ATOOL];
  3064. arg[1] = op;
  3065. arg[2] = '\0';
  3066. } else if (getutil(utils[UTIL_BSDTAR])) {
  3067. util = utils[UTIL_BSDTAR];
  3068. if (op == 'x')
  3069. arg[1] = op;
  3070. } else if (is_suffix(fpath, ".zip")) {
  3071. util = utils[UTIL_UNZIP];
  3072. arg[1] = (op == 'l') ? 'v' /* verbose listing */ : '\0';
  3073. arg[2] = '\0';
  3074. } else {
  3075. util = utils[UTIL_TAR];
  3076. if (op == 'x')
  3077. arg[1] = op;
  3078. }
  3079. if (op == 'x') { /* extract */
  3080. spawn(util, arg, fpath, dir, F_NORMAL);
  3081. } else { /* list */
  3082. exitcurses();
  3083. get_output(NULL, 0, util, arg, fpath, TRUE);
  3084. refresh();
  3085. }
  3086. }
  3087. static char *visit_parent(char *path, char *newpath, int *presel)
  3088. {
  3089. char *dir;
  3090. /* There is no going back */
  3091. if (istopdir(path)) {
  3092. /* Continue in navigate-as-you-type mode, if enabled */
  3093. if (cfg.filtermode)
  3094. *presel = FILTER;
  3095. return NULL;
  3096. }
  3097. /* Use a copy as dirname() may change the string passed */
  3098. xstrlcpy(newpath, path, PATH_MAX);
  3099. dir = dirname(newpath);
  3100. if (access(dir, R_OK) == -1) {
  3101. printwarn(presel);
  3102. return NULL;
  3103. }
  3104. return dir;
  3105. }
  3106. static void find_accessible_parent(char *path, char *newpath, char *lastname, int *presel)
  3107. {
  3108. char *dir;
  3109. /* Save history */
  3110. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  3111. xstrlcpy(newpath, path, PATH_MAX);
  3112. while (true) {
  3113. dir = visit_parent(path, newpath, presel);
  3114. if (istopdir(path) || istopdir(newpath)) {
  3115. if (!dir)
  3116. dir = dirname(newpath);
  3117. break;
  3118. }
  3119. if (!dir) {
  3120. xstrlcpy(path, newpath, PATH_MAX);
  3121. continue;
  3122. }
  3123. break;
  3124. }
  3125. xstrlcpy(path, dir, PATH_MAX);
  3126. printmsg(messages[MSG_ACCESS]);
  3127. xdelay(XDELAY_INTERVAL_MS);
  3128. }
  3129. /* Create non-existent parents and a file or dir */
  3130. static bool xmktree(char *path, bool dir)
  3131. {
  3132. char *p = path;
  3133. char *slash = path;
  3134. if (!p || !*p)
  3135. return FALSE;
  3136. /* Skip the first '/' */
  3137. ++p;
  3138. while (*p != '\0') {
  3139. if (*p == '/') {
  3140. slash = p;
  3141. *p = '\0';
  3142. } else {
  3143. ++p;
  3144. continue;
  3145. }
  3146. /* Create folder from path to '\0' inserted at p */
  3147. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3148. #ifdef __HAIKU__
  3149. // XDG_CONFIG_HOME contains a directory
  3150. // that is read-only, but the full path
  3151. // is writeable.
  3152. // Try to continue and see what happens.
  3153. // TODO: Find a more robust solution.
  3154. if (errno == B_READ_ONLY_DEVICE)
  3155. goto next;
  3156. #endif
  3157. DPRINTF_S("mkdir1!");
  3158. DPRINTF_S(strerror(errno));
  3159. *slash = '/';
  3160. return FALSE;
  3161. }
  3162. #ifdef __HAIKU__
  3163. next:
  3164. #endif
  3165. /* Restore path */
  3166. *slash = '/';
  3167. ++p;
  3168. }
  3169. if (dir) {
  3170. if (mkdir(path, 0777) == -1 && errno != EEXIST) {
  3171. DPRINTF_S("mkdir2!");
  3172. DPRINTF_S(strerror(errno));
  3173. return FALSE;
  3174. }
  3175. } else {
  3176. int fd = open(path, O_CREAT, 0666);
  3177. if (fd == -1 && errno != EEXIST) {
  3178. DPRINTF_S("open!");
  3179. DPRINTF_S(strerror(errno));
  3180. return FALSE;
  3181. }
  3182. close(fd);
  3183. }
  3184. return TRUE;
  3185. }
  3186. static bool archive_mount(char *name, char *path, char *newpath, int *presel)
  3187. {
  3188. char *dir, *cmd = utils[UTIL_ARCHIVEMOUNT];
  3189. size_t len;
  3190. if (!getutil(cmd)) {
  3191. printwait(messages[MSG_UTIL_MISSING], presel);
  3192. return FALSE;
  3193. }
  3194. dir = strdup(name);
  3195. if (!dir)
  3196. return FALSE;
  3197. len = strlen(dir);
  3198. while (len > 1)
  3199. if (dir[--len] == '.') {
  3200. dir[len] = '\0';
  3201. break;
  3202. }
  3203. DPRINTF_S(dir);
  3204. /* Create the mount point */
  3205. mkpath(cfgdir, dir, newpath);
  3206. free(dir);
  3207. if (!xmktree(newpath, TRUE)) {
  3208. printwarn(presel);
  3209. return FALSE;
  3210. }
  3211. /* Mount archive */
  3212. DPRINTF_S(name);
  3213. DPRINTF_S(newpath);
  3214. if (spawn(cmd, name, newpath, path, F_NORMAL)) {
  3215. printwait(messages[MSG_FAILED], presel);
  3216. return FALSE;
  3217. }
  3218. return TRUE;
  3219. }
  3220. static bool remote_mount(char *newpath, int *presel)
  3221. {
  3222. uchar flag = F_CLI;
  3223. int opt;
  3224. char *tmp, *env, *cmd;
  3225. bool r, s;
  3226. r = getutil(utils[UTIL_RCLONE]);
  3227. s = getutil(utils[UTIL_SSHFS]);
  3228. if (!(r || s))
  3229. return FALSE;
  3230. if (r && s)
  3231. opt = get_input(messages[MSG_REMOTE_OPTS]);
  3232. else
  3233. opt = (!s) ? 'r' : 's';
  3234. if (opt == 's') {
  3235. cmd = utils[UTIL_SSHFS];
  3236. env = xgetenv("NNN_SSHFS", cmd);
  3237. } else if (opt == 'r') {
  3238. flag |= F_NOWAIT | F_NOTRACE;
  3239. cmd = utils[UTIL_RCLONE];
  3240. env = xgetenv("NNN_RCLONE", "rclone mount");
  3241. } else {
  3242. printwait(messages[MSG_INVALID_KEY], presel);
  3243. return FALSE;
  3244. }
  3245. if (!getutil(cmd)) {
  3246. printwait(messages[MSG_UTIL_MISSING], presel);
  3247. return FALSE;
  3248. }
  3249. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3250. if (!tmp[0])
  3251. return FALSE;
  3252. /* Create the mount point */
  3253. mkpath(cfgdir, tmp, newpath);
  3254. if (!xmktree(newpath, TRUE)) {
  3255. printwarn(presel);
  3256. return FALSE;
  3257. }
  3258. /* Convert "Host" to "Host:" */
  3259. size_t len = strlen(tmp);
  3260. if (tmp[len - 1] != ':') { /* Append ':' if missing */
  3261. tmp[len] = ':';
  3262. tmp[len + 1] = '\0';
  3263. }
  3264. /* Connect to remote */
  3265. if (opt == 's') {
  3266. if (spawn(env, tmp, newpath, NULL, flag)) {
  3267. printwait(messages[MSG_FAILED], presel);
  3268. return FALSE;
  3269. }
  3270. } else {
  3271. spawn(env, tmp, newpath, NULL, flag);
  3272. printmsg(messages[MSG_RCLONE_DELAY]);
  3273. xdelay(XDELAY_INTERVAL_MS << 2); /* Set 4 times the usual delay */
  3274. }
  3275. return TRUE;
  3276. }
  3277. /*
  3278. * Unmounts if the directory represented by name is a mount point.
  3279. * Otherwise, asks for hostname
  3280. */
  3281. static bool unmount(char *name, char *newpath, int *presel, char *currentpath)
  3282. {
  3283. #ifdef __APPLE__
  3284. static char cmd[] = "umount";
  3285. #else
  3286. static char cmd[] = "fusermount3"; /* Arch Linux utility */
  3287. static bool found = FALSE;
  3288. #endif
  3289. char *tmp = name;
  3290. struct stat sb, psb;
  3291. bool child = FALSE;
  3292. bool parent = FALSE;
  3293. #ifndef __APPLE__
  3294. /* On Ubuntu it's fusermount */
  3295. if (!found && !getutil(cmd)) {
  3296. cmd[10] = '\0';
  3297. found = TRUE;
  3298. }
  3299. #endif
  3300. if (tmp && strcmp(cfgdir, currentpath) == 0) {
  3301. mkpath(cfgdir, tmp, newpath);
  3302. child = lstat(newpath, &sb) != -1;
  3303. parent = lstat(dirname(newpath), &psb) != -1;
  3304. if (!child && !parent) {
  3305. *presel = MSGWAIT;
  3306. return FALSE;
  3307. }
  3308. }
  3309. if (!tmp || !child || !S_ISDIR(sb.st_mode) || (child && parent && sb.st_dev == psb.st_dev)) {
  3310. tmp = xreadline(NULL, messages[MSG_HOSTNAME]);
  3311. if (!tmp[0])
  3312. return FALSE;
  3313. }
  3314. /* Create the mount point */
  3315. mkpath(cfgdir, tmp, newpath);
  3316. if (!xdiraccess(newpath)) {
  3317. *presel = MSGWAIT;
  3318. return FALSE;
  3319. }
  3320. #ifdef __APPLE__
  3321. if (spawn(cmd, newpath, NULL, NULL, F_NORMAL)) {
  3322. #else
  3323. if (spawn(cmd, "-u", newpath, NULL, F_NORMAL)) {
  3324. #endif
  3325. int r = get_input(messages[MSG_LAZY]);
  3326. if (!xconfirm(r))
  3327. return FALSE;
  3328. #ifdef __APPLE__
  3329. if (spawn(cmd, "-l", newpath, NULL, F_NORMAL)) {
  3330. #else
  3331. if (spawn(cmd, "-uz", newpath, NULL, F_NORMAL)) {
  3332. #endif
  3333. printwait(messages[MSG_FAILED], presel);
  3334. return FALSE;
  3335. }
  3336. }
  3337. return TRUE;
  3338. }
  3339. static void lock_terminal(void)
  3340. {
  3341. char *tmp = utils[UTIL_LOCKER];
  3342. if (!getutil(tmp))
  3343. tmp = utils[UTIL_CMATRIX];
  3344. spawn(tmp, NULL, NULL, NULL, F_NORMAL);
  3345. }
  3346. static void printkv(kv *kvarr, FILE *fp, uchar max)
  3347. {
  3348. uchar i = 0;
  3349. for (; i < max && kvarr[i].key; ++i)
  3350. fprintf(fp, " %c: %s\n", (char)kvarr[i].key, kvarr[i].val);
  3351. }
  3352. static void printkeys(kv *kvarr, char *buf, uchar max)
  3353. {
  3354. uchar i = 0;
  3355. for (; i < max && kvarr[i].key; ++i) {
  3356. buf[i << 1] = ' ';
  3357. buf[(i << 1) + 1] = kvarr[i].key;
  3358. }
  3359. buf[i << 1] = '\0';
  3360. }
  3361. /*
  3362. * The help string tokens (each line) start with a HEX value
  3363. * which indicates the number of spaces to print before the
  3364. * particular token. This method was chosen instead of a flat
  3365. * string because the number of bytes in help was increasing
  3366. * the binary size by around a hundred bytes. This would only
  3367. * have increased as we keep adding new options.
  3368. */
  3369. static void show_help(const char *path)
  3370. {
  3371. int i, fd;
  3372. FILE *fp;
  3373. const char *start, *end;
  3374. const char helpstr[] = {
  3375. "0\n"
  3376. "1NAVIGATION\n"
  3377. "9Up k Up%-16cPgUp ^U Scroll up\n"
  3378. "9Dn j Down%-14cPgDn ^D Scroll down\n"
  3379. "9Lt h Parent%-12c~ ` @ - HOME, /, start, last\n"
  3380. "5Ret Rt l Open%-20c' First file\n"
  3381. "9g ^A Top%-18c. F5 Toggle hidden\n"
  3382. "9G ^E End%-21c0 Lock terminal\n"
  3383. "9b ^/ Bookmark key%-12c, Pin CWD\n"
  3384. "a1-4 Context 1-4%-7c(Sh)Tab Cycle context\n"
  3385. "c/ Filter%-17c^N Nav-as-you-type toggle\n"
  3386. "aEsc Exit prompt%-12c^L Redraw/clear prompt\n"
  3387. "c? Help, conf%-14c+ Toggle proceed on open\n"
  3388. "cq Quit context%-11c^G QuitCD\n"
  3389. "b^Q Quit%-20cQ Quit with err\n"
  3390. "1FILES\n"
  3391. "9o ^O Open with...%-12cn Create new/link\n"
  3392. "9f ^F File details%-12cd Detail view toggle\n"
  3393. "b^R Rename/dup%-14cr Batch rename\n"
  3394. "cz Archive%-17ce Edit in EDITOR\n"
  3395. "5Space ^J (Un)select%-11cm ^K Mark range/clear\n"
  3396. "9p ^P Copy sel here%-11ca Select all\n"
  3397. "9v ^V Move sel here%-8cw ^W Copy/move sel as\n"
  3398. "9x ^X Delete%-18cE Edit sel\n"
  3399. "c* Toggle exe%-0c\n"
  3400. "1MISC\n"
  3401. "9; ^S Select plugin%-11c= Launch app\n"
  3402. "9! ^] Shell%-19c] Cmd prompt\n"
  3403. "cc Connect remote%-10cu Unmount\n"
  3404. "9t ^T Sort toggles%-12cs Manage session\n"
  3405. };
  3406. fd = create_tmp_file();
  3407. if (fd == -1)
  3408. return;
  3409. fp = fdopen(fd, "w");
  3410. if (!fp) {
  3411. close(fd);
  3412. return;
  3413. }
  3414. start = end = helpstr;
  3415. while (*end) {
  3416. if (*end == '\n') {
  3417. snprintf(g_buf, CMD_LEN_MAX, "%*c%.*s",
  3418. xchartohex(*start), ' ', (int)(end - start), start + 1);
  3419. fprintf(fp, g_buf, ' ');
  3420. start = end + 1;
  3421. }
  3422. ++end;
  3423. }
  3424. fprintf(fp, "\nVOLUME: %s of ", coolsize(get_fs_info(path, FREE)));
  3425. fprintf(fp, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  3426. if (bookmark[0].val) {
  3427. fprintf(fp, "BOOKMARKS\n");
  3428. printkv(bookmark, fp, maxbm);
  3429. fprintf(fp, "\n");
  3430. }
  3431. if (plug[0].val) {
  3432. fprintf(fp, "PLUGIN KEYS\n");
  3433. printkv(plug, fp, maxplug);
  3434. fprintf(fp, "\n");
  3435. }
  3436. for (i = NNN_OPENER; i <= NNN_TRASH; ++i) {
  3437. start = getenv(env_cfg[i]);
  3438. if (start)
  3439. fprintf(fp, "%s: %s\n", env_cfg[i], start);
  3440. }
  3441. if (g_selpath)
  3442. fprintf(fp, "SELECTION FILE: %s\n", g_selpath);
  3443. fprintf(fp, "\nv%s\n%s\n", VERSION, GENERAL_INFO);
  3444. fclose(fp);
  3445. close(fd);
  3446. spawn(pager, g_tmpfpath, NULL, NULL, F_CLI);
  3447. unlink(g_tmpfpath);
  3448. }
  3449. static bool run_cmd_as_plugin(const char *path, const char *file, char *newpath, char *runfile)
  3450. {
  3451. uchar flags = F_CLI | F_CONFIRM;
  3452. size_t len;
  3453. /* Get rid of preceding _ */
  3454. ++file;
  3455. if (!*file)
  3456. return FALSE;
  3457. /* Check if GUI flags are to be used */
  3458. if (*file == '|') {
  3459. flags = F_NOTRACE | F_NOWAIT;
  3460. ++file;
  3461. if (!*file)
  3462. return FALSE;
  3463. }
  3464. xstrlcpy(newpath, file, PATH_MAX);
  3465. len = strlen(newpath);
  3466. if (len > 1 && newpath[len - 1] == '*') {
  3467. flags &= ~F_CONFIRM; /* Skip user confirmation */
  3468. newpath[len - 1] = '\0'; /* Get rid of trailing no confirmation symbol */
  3469. --len;
  3470. }
  3471. if (is_suffix(newpath, " $nnn")) {
  3472. /* Set `\0` to clear ' $nnn' suffix */
  3473. newpath[len - 5] = '\0';
  3474. } else
  3475. runfile = NULL;
  3476. spawn(newpath, runfile, NULL, path, flags);
  3477. return TRUE;
  3478. }
  3479. static bool plctrl_init(void)
  3480. {
  3481. snprintf(g_buf, CMD_LEN_MAX, "nnn-pipe.%d", getpid());
  3482. /* g_tmpfpath is used to generate tmp file names */
  3483. g_tmpfpath[g_tmpfplen - 1] = '\0';
  3484. mkpath(g_tmpfpath, g_buf, g_pipepath);
  3485. unlink(g_pipepath);
  3486. if (mkfifo(g_pipepath, 0600) != 0)
  3487. return _FAILURE;
  3488. setenv(env_cfg[NNN_PIPE], g_pipepath, TRUE);
  3489. return _SUCCESS;
  3490. }
  3491. static bool run_selected_plugin(char **path, const char *file, char *newpath, char *runfile, char **lastname, char **lastdir)
  3492. {
  3493. int fd;
  3494. size_t len;
  3495. if (*file == '_')
  3496. return run_cmd_as_plugin(*path, file, newpath, runfile);
  3497. if (!(g_states & STATE_PLUGIN_INIT)) {
  3498. plctrl_init();
  3499. g_states |= STATE_PLUGIN_INIT;
  3500. }
  3501. fd = open(g_pipepath, O_RDONLY | O_NONBLOCK);
  3502. if (fd == -1)
  3503. return FALSE;
  3504. /* Generate absolute path to plugin */
  3505. mkpath(plugindir, file, newpath);
  3506. if (runfile && runfile[0]) {
  3507. xstrlcpy(*lastname, runfile, NAME_MAX);
  3508. spawn(newpath, *lastname, *path, *path, F_NORMAL);
  3509. } else
  3510. spawn(newpath, NULL, *path, *path, F_NORMAL);
  3511. len = read(fd, g_buf, PATH_MAX);
  3512. g_buf[len] = '\0';
  3513. close(fd);
  3514. if (len > 1) {
  3515. int ctx = g_buf[0] - '0';
  3516. if (ctx == 0 || ctx == cfg.curctx + 1) {
  3517. xstrlcpy(*lastdir, *path, PATH_MAX);
  3518. xstrlcpy(*path, g_buf + 1, PATH_MAX);
  3519. } else if (ctx >= 1 && ctx <= CTX_MAX) {
  3520. int r = ctx - 1;
  3521. g_ctx[r].c_cfg.ctxactive = 0;
  3522. savecurctx(&cfg, g_buf + 1, dents[cur].name, r);
  3523. *path = g_ctx[r].c_path;
  3524. *lastdir = g_ctx[r].c_last;
  3525. *lastname = g_ctx[r].c_name;
  3526. }
  3527. }
  3528. return TRUE;
  3529. }
  3530. static void plugscript(const char *plugin, char *newpath, uchar flags)
  3531. {
  3532. mkpath(plugindir, plugin, newpath);
  3533. if (!access(newpath, X_OK))
  3534. spawn(newpath, NULL, NULL, NULL, flags);
  3535. }
  3536. static void launch_app(const char *path, char *newpath)
  3537. {
  3538. int r = F_NORMAL;
  3539. char *tmp = newpath;
  3540. mkpath(plugindir, utils[UTIL_LAUNCH], newpath);
  3541. if (!(getutil(utils[UTIL_FZF]) || getutil(utils[UTIL_FZY])) || access(newpath, X_OK) < 0) {
  3542. tmp = xreadline(NULL, messages[MSG_APP_NAME]);
  3543. r = F_NOWAIT | F_NOTRACE | F_MULTI;
  3544. }
  3545. if (tmp && *tmp) // NOLINT
  3546. spawn(tmp, "0", NULL, path, r);
  3547. }
  3548. static int sum_bsize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3549. {
  3550. if (sb->st_blocks && (typeflag == FTW_D
  3551. || (typeflag == FTW_F && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))))
  3552. ent_blocks += sb->st_blocks;
  3553. ++num_files;
  3554. return 0;
  3555. }
  3556. static int sum_asize(const char *UNUSED(fpath), const struct stat *sb, int typeflag, struct FTW *UNUSED(ftwbuf))
  3557. {
  3558. if (sb->st_size && (typeflag == FTW_D
  3559. || (typeflag == FTW_D && (sb->st_nlink <= 1 || test_set_bit((uint)sb->st_ino)))))
  3560. ent_blocks += sb->st_size;
  3561. ++num_files;
  3562. return 0;
  3563. }
  3564. static void dentfree(void)
  3565. {
  3566. free(pnamebuf);
  3567. free(dents);
  3568. }
  3569. static blkcnt_t dirwalk(char *path, struct stat *psb)
  3570. {
  3571. static uint open_max;
  3572. /* Increase current open file descriptor limit */
  3573. if (!open_max)
  3574. open_max = max_openfds();
  3575. ent_blocks = 0;
  3576. tolastln();
  3577. addstr(xbasename(path));
  3578. addstr(" [^C aborts]\n");
  3579. refresh();
  3580. if (nftw(path, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) < 0) {
  3581. DPRINTF_S("nftw failed");
  3582. return cfg.apparentsz ? psb->st_size : psb->st_blocks;
  3583. }
  3584. return ent_blocks;
  3585. }
  3586. /* Skip self and parent */
  3587. static bool selforparent(const char *path)
  3588. {
  3589. return path[0] == '.' && (path[1] == '\0' || (path[1] == '.' && path[2] == '\0'));
  3590. }
  3591. static int dentfill(char *path, struct entry **dents)
  3592. {
  3593. int n = 0, count, flags = 0;
  3594. ulong num_saved;
  3595. struct dirent *dp;
  3596. char *namep, *pnb, *buf = NULL;
  3597. struct entry *dentp;
  3598. size_t off = 0, namebuflen = NAMEBUF_INCR;
  3599. struct stat sb_path, sb;
  3600. DIR *dirp = opendir(path);
  3601. if (!dirp)
  3602. return 0;
  3603. int fd = dirfd(dirp);
  3604. if (cfg.blkorder) {
  3605. num_files = 0;
  3606. dir_blocks = 0;
  3607. buf = (char *)alloca(strlen(path) + NAME_MAX + 2);
  3608. if (fstatat(fd, path, &sb_path, 0) == -1)
  3609. goto exit;
  3610. if (!ihashbmp) {
  3611. ihashbmp = calloc(1, HASH_OCTETS << 3);
  3612. if (!ihashbmp)
  3613. goto exit;
  3614. } else
  3615. clear_hash();
  3616. }
  3617. #if _POSIX_C_SOURCE >= 200112L
  3618. posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
  3619. #endif
  3620. dp = readdir(dirp);
  3621. if (!dp)
  3622. goto exit;
  3623. #if defined(__sun) || defined(__HAIKU__)
  3624. flags = AT_SYMLINK_NOFOLLOW; /* no d_type */
  3625. #else
  3626. if (cfg.blkorder || dp->d_type == DT_UNKNOWN) {
  3627. /*
  3628. * Optimization added for filesystems which support dirent.d_type
  3629. * see readdir(3)
  3630. * Known drawbacks:
  3631. * - the symlink size is set to 0
  3632. * - the modification time of the symlink is set to that of the target file
  3633. */
  3634. flags = AT_SYMLINK_NOFOLLOW;
  3635. }
  3636. #endif
  3637. do {
  3638. namep = dp->d_name;
  3639. if (selforparent(namep))
  3640. continue;
  3641. if (!cfg.showhidden && namep[0] == '.') {
  3642. if (!cfg.blkorder)
  3643. continue;
  3644. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  3645. continue;
  3646. if (S_ISDIR(sb.st_mode)) {
  3647. if (sb_path.st_dev == sb.st_dev) {
  3648. mkpath(path, namep, buf);
  3649. dir_blocks += dirwalk(buf, &sb);
  3650. if (g_states & STATE_INTERRUPTED)
  3651. goto exit;
  3652. }
  3653. } else {
  3654. /* Do not recount hard links */
  3655. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3656. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3657. ++num_files;
  3658. }
  3659. continue;
  3660. }
  3661. if (fstatat(fd, namep, &sb, flags) == -1) {
  3662. /* List a symlink with target missing */
  3663. if (flags || (!flags && fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)) {
  3664. DPRINTF_U(flags);
  3665. if (!flags) {
  3666. DPRINTF_S(namep);
  3667. DPRINTF_S(strerror(errno));
  3668. }
  3669. continue;
  3670. }
  3671. }
  3672. if (n == total_dents) {
  3673. total_dents += ENTRY_INCR;
  3674. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  3675. if (!*dents) {
  3676. free(pnamebuf);
  3677. closedir(dirp);
  3678. errexit();
  3679. }
  3680. DPRINTF_P(*dents);
  3681. }
  3682. /* If not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  3683. if (namebuflen - off < NAME_MAX + 1) {
  3684. namebuflen += NAMEBUF_INCR;
  3685. pnb = pnamebuf;
  3686. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  3687. if (!pnamebuf) {
  3688. free(*dents);
  3689. closedir(dirp);
  3690. errexit();
  3691. }
  3692. DPRINTF_P(pnamebuf);
  3693. /* realloc() may result in memory move, we must re-adjust if that happens */
  3694. if (pnb != pnamebuf) {
  3695. dentp = *dents;
  3696. dentp->name = pnamebuf;
  3697. for (count = 1; count < n; ++dentp, ++count)
  3698. /* Current filename starts at last filename start + length */
  3699. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  3700. }
  3701. }
  3702. dentp = *dents + n;
  3703. /* Selection file name */
  3704. dentp->name = (char *)((size_t)pnamebuf + off);
  3705. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  3706. off += dentp->nlen;
  3707. /* Copy other fields */
  3708. dentp->t = cfg.mtime ? sb.st_mtime : sb.st_atime;
  3709. #if !(defined(__sun) || defined(__HAIKU__))
  3710. if (!flags && dp->d_type == DT_LNK) {
  3711. /* Do not add sizes for links */
  3712. dentp->mode = (sb.st_mode & ~S_IFMT) | S_IFLNK;
  3713. dentp->size = g_listpath ? sb.st_size : 0;
  3714. } else {
  3715. dentp->mode = sb.st_mode;
  3716. dentp->size = sb.st_size;
  3717. }
  3718. #else
  3719. dentp->mode = sb.st_mode;
  3720. dentp->size = sb.st_size;
  3721. #endif
  3722. dentp->flags = S_ISDIR(sb.st_mode) ? 0 : ((sb.st_nlink > 1) ? HARD_LINK : 0);
  3723. DPRINTF_D(dentp->flags);
  3724. if (cfg.blkorder) {
  3725. if (S_ISDIR(sb.st_mode)) {
  3726. num_saved = num_files + 1;
  3727. mkpath(path, namep, buf);
  3728. /* Need to show the disk usage of this dir */
  3729. dentp->blocks = dirwalk(buf, &sb);
  3730. if (sb_path.st_dev == sb.st_dev) // NOLINT
  3731. dir_blocks += dentp->blocks;
  3732. else
  3733. num_files = num_saved;
  3734. if (g_states & STATE_INTERRUPTED)
  3735. goto exit;
  3736. } else {
  3737. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  3738. /* Do not recount hard links */
  3739. if (sb.st_nlink <= 1 || test_set_bit((uint)sb.st_ino))
  3740. dir_blocks += dentp->blocks;
  3741. ++num_files;
  3742. }
  3743. }
  3744. if (flags) {
  3745. /* Flag if this is a dir or symlink to a dir */
  3746. if (S_ISLNK(sb.st_mode)) {
  3747. sb.st_mode = 0;
  3748. fstatat(fd, namep, &sb, 0);
  3749. }
  3750. if (S_ISDIR(sb.st_mode))
  3751. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3752. #if !(defined(__sun) || defined(__HAIKU__)) /* no d_type */
  3753. } else if (dp->d_type == DT_DIR || (dp->d_type == DT_LNK && S_ISDIR(sb.st_mode))) {
  3754. dentp->flags |= DIR_OR_LINK_TO_DIR;
  3755. #endif
  3756. }
  3757. ++n;
  3758. } while ((dp = readdir(dirp)));
  3759. exit:
  3760. /* Should never be null */
  3761. if (closedir(dirp) == -1)
  3762. errexit();
  3763. return n;
  3764. }
  3765. /*
  3766. * Return the position of the matching entry or 0 otherwise
  3767. * Note there's no NULL check for fname
  3768. */
  3769. static int dentfind(const char *fname, int n)
  3770. {
  3771. int i = 0;
  3772. for (; i < n; ++i)
  3773. if (xstrcmp(fname, dents[i].name) == 0)
  3774. return i;
  3775. return 0;
  3776. }
  3777. static void populate(char *path, char *lastname)
  3778. {
  3779. #ifdef DBGMODE
  3780. struct timespec ts1, ts2;
  3781. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  3782. #endif
  3783. ndents = dentfill(path, &dents);
  3784. if (!ndents)
  3785. return;
  3786. qsort(dents, ndents, sizeof(*dents), entrycmpfn);
  3787. #ifdef DBGMODE
  3788. clock_gettime(CLOCK_REALTIME, &ts2);
  3789. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  3790. #endif
  3791. /* Find cur from history */
  3792. /* No NULL check for lastname, always points to an array */
  3793. if (!*lastname)
  3794. move_cursor(0, 0);
  3795. else
  3796. move_cursor(dentfind(lastname, ndents), 0);
  3797. // Force full redraw
  3798. last_curscroll = -1;
  3799. }
  3800. static void move_cursor(int target, int ignore_scrolloff)
  3801. {
  3802. int delta, scrolloff, onscreen = xlines - 4;
  3803. last_curscroll = curscroll;
  3804. target = MAX(0, MIN(ndents - 1, target));
  3805. delta = target - cur;
  3806. last = cur;
  3807. cur = target;
  3808. if (!ignore_scrolloff) {
  3809. scrolloff = MIN(SCROLLOFF, onscreen >> 1);
  3810. /*
  3811. * When ignore_scrolloff is 1, the cursor can jump into the scrolloff
  3812. * margin area, but when ignore_scrolloff is 0, act like a boa
  3813. * constrictor and squeeze the cursor towards the middle region of the
  3814. * screen by allowing it to move inward and disallowing it to move
  3815. * outward (deeper into the scrolloff margin area).
  3816. */
  3817. if (((cur < (curscroll + scrolloff)) && delta < 0)
  3818. || ((cur > (curscroll + onscreen - scrolloff - 1)) && delta > 0))
  3819. curscroll += delta;
  3820. }
  3821. curscroll = MIN(curscroll, MIN(cur, ndents - onscreen));
  3822. curscroll = MAX(curscroll, MAX(cur - (onscreen - 1), 0));
  3823. }
  3824. static void handle_screen_move(enum action sel)
  3825. {
  3826. int onscreen;
  3827. switch (sel) {
  3828. case SEL_NEXT:
  3829. if (ndents && (cfg.rollover || (cur != ndents - 1)))
  3830. move_cursor((cur + 1) % ndents, 0);
  3831. break;
  3832. case SEL_PREV:
  3833. if (ndents && (cfg.rollover || cur))
  3834. move_cursor((cur + ndents - 1) % ndents, 0);
  3835. break;
  3836. case SEL_PGDN:
  3837. onscreen = xlines - 4;
  3838. move_cursor(curscroll + (onscreen - 1), 1);
  3839. curscroll += onscreen - 1;
  3840. break;
  3841. case SEL_CTRL_D:
  3842. onscreen = xlines - 4;
  3843. move_cursor(curscroll + (onscreen - 1), 1);
  3844. curscroll += onscreen >> 1;
  3845. break;
  3846. case SEL_PGUP: // fallthrough
  3847. onscreen = xlines - 4;
  3848. move_cursor(curscroll, 1);
  3849. curscroll -= onscreen - 1;
  3850. break;
  3851. case SEL_CTRL_U:
  3852. onscreen = xlines - 4;
  3853. move_cursor(curscroll, 1);
  3854. curscroll -= onscreen >> 1;
  3855. break;
  3856. case SEL_HOME:
  3857. move_cursor(0, 1);
  3858. break;
  3859. case SEL_END:
  3860. move_cursor(ndents - 1, 1);
  3861. break;
  3862. default: /* case SEL_FIRST */
  3863. {
  3864. int r = 0;
  3865. for (; r < ndents; ++r) {
  3866. if (!(dents[r].flags & DIR_OR_LINK_TO_DIR)) {
  3867. move_cursor((r) % ndents, 0);
  3868. break;
  3869. }
  3870. }
  3871. break;
  3872. }
  3873. }
  3874. }
  3875. static int handle_context_switch(enum action sel, char *newpath)
  3876. {
  3877. int r = -1, input;
  3878. switch (sel) {
  3879. case SEL_CYCLE: // fallthrough
  3880. case SEL_CYCLER:
  3881. /* visit next and previous contexts */
  3882. r = cfg.curctx;
  3883. if (sel == SEL_CYCLE)
  3884. do
  3885. r = (r + 1) & ~CTX_MAX;
  3886. while (!g_ctx[r].c_cfg.ctxactive);
  3887. else
  3888. do
  3889. r = (r + (CTX_MAX - 1)) & (CTX_MAX - 1);
  3890. while (!g_ctx[r].c_cfg.ctxactive);
  3891. // fallthrough
  3892. default: /* SEL_CTXN */
  3893. if (sel >= SEL_CTX1) /* CYCLE keys are lesser in value */
  3894. r = sel - SEL_CTX1; /* Save the next context id */
  3895. if (cfg.curctx == r) {
  3896. if (sel != SEL_CYCLE)
  3897. return -1;
  3898. (r == CTX_MAX - 1) ? (r = 0) : ++r;
  3899. snprintf(newpath, PATH_MAX, messages[MSG_CREATE_CTX], r + 1);
  3900. input = get_input(newpath);
  3901. if (!xconfirm(input))
  3902. return -1;
  3903. }
  3904. if (cfg.selmode)
  3905. lastappendpos = selbufpos;
  3906. }
  3907. return r;
  3908. }
  3909. static bool set_sort_flags(void)
  3910. {
  3911. int r = get_input(messages[MSG_ORDER]);
  3912. if ((r == 'a' || r == 'd' || r == 'e' || r == 's' || r == 't') && (entrycmpfn == &reventrycmp))
  3913. entrycmpfn = &entrycmp;
  3914. switch (r) {
  3915. case 'a': /* Apparent du */
  3916. cfg.apparentsz ^= 1;
  3917. if (cfg.apparentsz) {
  3918. nftw_fn = &sum_asize;
  3919. cfg.blkorder = 1;
  3920. blk_shift = 0;
  3921. } else
  3922. cfg.blkorder = 0;
  3923. // fallthrough
  3924. case 'd': /* Disk usage */
  3925. if (r == 'd') {
  3926. if (!cfg.apparentsz)
  3927. cfg.blkorder ^= 1;
  3928. nftw_fn = &sum_bsize;
  3929. cfg.apparentsz = 0;
  3930. blk_shift = ffs(S_BLKSIZE) - 1;
  3931. }
  3932. if (cfg.blkorder) {
  3933. cfg.showdetail = 1;
  3934. printptr = &printent_long;
  3935. }
  3936. cfg.mtimeorder = 0;
  3937. cfg.sizeorder = 0;
  3938. cfg.extnorder = 0;
  3939. clearfilter(); /* Reload directory */
  3940. endselection(); /* We are going to reload dir */
  3941. break;
  3942. case 'e': /* File extension */
  3943. cfg.extnorder ^= 1;
  3944. cfg.sizeorder = 0;
  3945. cfg.mtimeorder = 0;
  3946. cfg.apparentsz = 0;
  3947. cfg.blkorder = 0;
  3948. break;
  3949. case 'r': /* Reverse sort */
  3950. entrycmpfn = (entrycmpfn == &entrycmp) ? &reventrycmp : &entrycmp;
  3951. break;
  3952. case 's': /* File size */
  3953. cfg.sizeorder ^= 1;
  3954. cfg.mtimeorder = 0;
  3955. cfg.apparentsz = 0;
  3956. cfg.blkorder = 0;
  3957. cfg.extnorder = 0;
  3958. break;
  3959. case 't': /* Modification or access time */
  3960. cfg.mtimeorder ^= 1;
  3961. cfg.sizeorder = 0;
  3962. cfg.apparentsz = 0;
  3963. cfg.blkorder = 0;
  3964. cfg.extnorder = 0;
  3965. break;
  3966. case 'v': /* Version */
  3967. namecmpfn = (namecmpfn == &xstrverscasecmp) ? &xstricmp : &xstrverscasecmp;
  3968. break;
  3969. default:
  3970. return FALSE;
  3971. }
  3972. return TRUE;
  3973. }
  3974. static void statusbar(char *path)
  3975. {
  3976. int i = 0, extnlen = 0;
  3977. char *ptr;
  3978. pEntry pent = &dents[cur];
  3979. if (!ndents) {
  3980. printmsg("0/0");
  3981. return;
  3982. }
  3983. /* Get the file extension for regular files */
  3984. if (S_ISREG(pent->mode)) {
  3985. i = (int)(pent->nlen - 1);
  3986. ptr = xmemrchr((uchar *)pent->name, '.', i);
  3987. if (ptr) {
  3988. extnlen = ptr - pent->name;
  3989. extnlen = i - extnlen;
  3990. }
  3991. if (!ptr || extnlen > 5 || extnlen < 2)
  3992. ptr = "\b";
  3993. } else
  3994. ptr = "\b";
  3995. tolastln();
  3996. if (cfg.blkorder) { /* du mode */
  3997. char buf[24];
  3998. xstrlcpy(buf, coolsize(dir_blocks << blk_shift), 12);
  3999. printw("%d/%d [%s:%s] %cu:%s free:%s files:%lu %lldB %s",
  4000. cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4001. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4002. (cfg.apparentsz ? 'a' : 'd'), buf, coolsize(get_fs_info(path, FREE)),
  4003. num_files, (ll)pent->blocks << blk_shift, ptr);
  4004. } else { /* light or detail mode */
  4005. char sort[] = "\0\0\0\0";
  4006. getorderstr(sort);
  4007. printw("%d/%d [%s:%s] %s", cur + 1, ndents, (cfg.selmode ? "s" : ""),
  4008. ((g_states & STATE_RANGESEL) ? "*" : (nselected ? xitoa(nselected) : "")),
  4009. sort);
  4010. /* Timestamp */
  4011. print_time(&pent->t);
  4012. addch(' ');
  4013. addstr(get_lsperms(pent->mode));
  4014. addch(' ');
  4015. addstr(coolsize(pent->size));
  4016. addch(' ');
  4017. addstr(ptr);
  4018. }
  4019. addch('\n');
  4020. }
  4021. static int adjust_cols(int ncols)
  4022. {
  4023. /* Calculate the number of cols available to print entry name */
  4024. if (cfg.showdetail) {
  4025. /* Fallback to light mode if less than 35 columns */
  4026. if (ncols < 36) {
  4027. cfg.showdetail ^= 1;
  4028. printptr = &printent;
  4029. ncols -= 3; /* Preceding space, indicator, newline */
  4030. } else
  4031. ncols -= 35;
  4032. } else
  4033. ncols -= 3; /* Preceding space, indicator, newline */
  4034. return ncols;
  4035. }
  4036. static void draw_line(char *path, int ncols)
  4037. {
  4038. bool dir = FALSE;
  4039. ncols = adjust_cols(ncols);
  4040. if (dents[last].flags & DIR_OR_LINK_TO_DIR) {
  4041. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4042. dir = TRUE;
  4043. }
  4044. move(2 + last - curscroll, 0);
  4045. printptr(&dents[last], ncols, false);
  4046. if (dents[cur].flags & DIR_OR_LINK_TO_DIR) {
  4047. if (!dir) {/* First file is not a directory */
  4048. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4049. dir = TRUE;
  4050. }
  4051. } else if (dir) { /* Second file is not a directory */
  4052. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4053. dir = FALSE;
  4054. }
  4055. move(2 + cur - curscroll, 0);
  4056. printptr(&dents[cur], ncols, true);
  4057. /* Must reset e.g. no files in dir */
  4058. if (dir)
  4059. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4060. statusbar(path);
  4061. }
  4062. static void redraw(char *path)
  4063. {
  4064. xlines = LINES;
  4065. xcols = COLS;
  4066. int ncols = (xcols <= PATH_MAX) ? xcols : PATH_MAX;
  4067. int onscreen = xlines - 4;
  4068. int i;
  4069. char *ptr = path;
  4070. // Fast redraw
  4071. if (g_states & STATE_MOVE_OP) {
  4072. g_states &= ~STATE_MOVE_OP;
  4073. if (ndents && (last_curscroll == curscroll))
  4074. return draw_line(path, ncols);
  4075. }
  4076. /* Clear screen */
  4077. erase();
  4078. /* Enforce scroll/cursor invariants */
  4079. move_cursor(cur, 1);
  4080. /* Fail redraw if < than 10 columns, context info prints 10 chars */
  4081. if (ncols < MIN_DISPLAY_COLS) {
  4082. printmsg(messages[MSG_FEW_COLUMNS]);
  4083. return;
  4084. }
  4085. //DPRINTF_D(cur);
  4086. DPRINTF_S(path);
  4087. addch('[');
  4088. for (i = 0; i < CTX_MAX; ++i) {
  4089. if (!g_ctx[i].c_cfg.ctxactive) {
  4090. addch(i + '1');
  4091. } else {
  4092. int attrs = (cfg.curctx != i)
  4093. ? (COLOR_PAIR(i + 1) | A_BOLD | A_UNDERLINE) /* Active */
  4094. : (COLOR_PAIR(i + 1) | A_BOLD | A_REVERSE); /* Current */
  4095. attron(attrs);
  4096. addch(i + '1');
  4097. attroff(attrs);
  4098. }
  4099. addch(' ');
  4100. }
  4101. addstr("\b] "); /* 10 chars printed for contexts - "[1 2 3 4] " */
  4102. attron(A_UNDERLINE);
  4103. /* Print path */
  4104. i = (int)strlen(path);
  4105. if ((i + MIN_DISPLAY_COLS) <= ncols)
  4106. addnstr(path, ncols - MIN_DISPLAY_COLS);
  4107. else {
  4108. char *base = xbasename(path);
  4109. if ((base - ptr) <= 1)
  4110. addnstr(path, ncols - MIN_DISPLAY_COLS);
  4111. else {
  4112. i = 0;
  4113. --base;
  4114. while (ptr < base) {
  4115. if (*ptr == '/') {
  4116. i += 2; /* 2 characters added */
  4117. if (ncols < i + MIN_DISPLAY_COLS) {
  4118. base = NULL; /* Can't print more characters */
  4119. break;
  4120. }
  4121. addch(*ptr);
  4122. addch(*(++ptr));
  4123. }
  4124. ++ptr;
  4125. }
  4126. addnstr(base, ncols - (MIN_DISPLAY_COLS + i));
  4127. }
  4128. }
  4129. /* Go to first entry */
  4130. move(2, 0);
  4131. attroff(A_UNDERLINE);
  4132. ncols = adjust_cols(ncols);
  4133. attron(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4134. cfg.dircolor = 1;
  4135. /* Print listing */
  4136. for (i = curscroll; i < ndents && i < curscroll + onscreen; ++i)
  4137. printptr(&dents[i], ncols, i == cur);
  4138. /* Must reset e.g. no files in dir */
  4139. if (cfg.dircolor) {
  4140. attroff(COLOR_PAIR(cfg.curctx + 1) | A_BOLD);
  4141. cfg.dircolor = 0;
  4142. }
  4143. statusbar(path);
  4144. }
  4145. static bool browse(char *ipath, const char *session)
  4146. {
  4147. char newpath[PATH_MAX] __attribute__ ((aligned));
  4148. char rundir[PATH_MAX] __attribute__ ((aligned));
  4149. char runfile[NAME_MAX + 1] __attribute__ ((aligned));
  4150. char *path, *lastdir, *lastname, *dir, *tmp, *mark = NULL;
  4151. enum action sel;
  4152. struct stat sb;
  4153. int r = -1, fd, presel, selstartid = 0, selendid = 0;
  4154. const uchar opener_flags = (cfg.cliopener ? F_CLI : (F_NOTRACE | F_NOWAIT));
  4155. bool dir_changed = FALSE;
  4156. #ifndef NOMOUSE
  4157. MEVENT event;
  4158. struct timespec mousetimings[2] = {{.tv_sec = 0, .tv_nsec = 0}, {.tv_sec = 0, .tv_nsec = 0} };
  4159. bool currentmouse = 1;
  4160. #endif
  4161. #ifndef DIR_LIMITED_SELECTION
  4162. ino_t inode = 0;
  4163. #endif
  4164. atexit(dentfree);
  4165. xlines = LINES;
  4166. xcols = COLS;
  4167. /* setup first context */
  4168. if (!session || !load_session(session, &path, &lastdir, &lastname, FALSE)) {
  4169. xstrlcpy(g_ctx[0].c_path, ipath, PATH_MAX); /* current directory */
  4170. path = g_ctx[0].c_path;
  4171. g_ctx[0].c_last[0] = g_ctx[0].c_name[0] = '\0';
  4172. lastdir = g_ctx[0].c_last; /* last visited directory */
  4173. lastname = g_ctx[0].c_name; /* last visited filename */
  4174. g_ctx[0].c_fltr[0] = g_ctx[0].c_fltr[1] = '\0';
  4175. g_ctx[0].c_cfg = cfg; /* current configuration */
  4176. }
  4177. newpath[0] = rundir[0] = runfile[0] = '\0';
  4178. presel = cfg.filtermode ? FILTER : 0;
  4179. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  4180. if (!dents)
  4181. errexit();
  4182. /* Allocate buffer to hold names */
  4183. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  4184. if (!pnamebuf)
  4185. errexit();
  4186. begin:
  4187. /* Can fail when permissions change while browsing.
  4188. * It's assumed that path IS a directory when we are here.
  4189. */
  4190. if (access(path, R_OK) == -1) {
  4191. DPRINTF_S("directory inaccessible");
  4192. find_accessible_parent(path, newpath, lastname, &presel);
  4193. setdirwatch();
  4194. }
  4195. if (cfg.selmode && lastdir[0])
  4196. lastappendpos = selbufpos;
  4197. #ifdef LINUX_INOTIFY
  4198. if ((presel == FILTER || dir_changed) && inotify_wd >= 0) {
  4199. inotify_rm_watch(inotify_fd, inotify_wd);
  4200. inotify_wd = -1;
  4201. dir_changed = FALSE;
  4202. }
  4203. #elif defined(BSD_KQUEUE)
  4204. if ((presel == FILTER || dir_changed) && event_fd >= 0) {
  4205. close(event_fd);
  4206. event_fd = -1;
  4207. dir_changed = FALSE;
  4208. }
  4209. #elif defined(HAIKU_NM)
  4210. if ((presel == FILTER || dir_changed) && haiku_hnd != NULL) {
  4211. haiku_stop_watch(haiku_hnd);
  4212. haiku_nm_active = FALSE;
  4213. dir_changed = FALSE;
  4214. }
  4215. #endif
  4216. populate(path, lastname);
  4217. if (g_states & STATE_INTERRUPTED) {
  4218. g_states &= ~STATE_INTERRUPTED;
  4219. cfg.apparentsz = 0;
  4220. cfg.blkorder = 0;
  4221. blk_shift = BLK_SHIFT_512;
  4222. presel = CONTROL('L');
  4223. }
  4224. #ifdef LINUX_INOTIFY
  4225. if (presel != FILTER && inotify_wd == -1)
  4226. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  4227. #elif defined(BSD_KQUEUE)
  4228. if (presel != FILTER && event_fd == -1) {
  4229. #if defined(O_EVTONLY)
  4230. event_fd = open(path, O_EVTONLY);
  4231. #else
  4232. event_fd = open(path, O_RDONLY);
  4233. #endif
  4234. if (event_fd >= 0)
  4235. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE,
  4236. EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  4237. }
  4238. #elif defined(HAIKU_NM)
  4239. haiku_nm_active = haiku_watch_dir(haiku_hnd, path) == _SUCCESS;
  4240. #endif
  4241. while (1) {
  4242. redraw(path);
  4243. /* Display a one-time message */
  4244. if (g_listpath && (g_states & STATE_MSG)) {
  4245. g_states &= ~STATE_MSG;
  4246. printwait(messages[MSG_IGNORED], &presel);
  4247. }
  4248. nochange:
  4249. /* Exit if parent has exited */
  4250. if (getppid() == 1) {
  4251. free(mark);
  4252. _exit(0);
  4253. }
  4254. /* If CWD is deleted or moved or perms changed, find an accessible parent */
  4255. if (access(path, F_OK))
  4256. goto begin;
  4257. /* If STDIN is no longer a tty (closed) we should exit */
  4258. if (!isatty(STDIN_FILENO) && !cfg.picker) {
  4259. free(mark);
  4260. return _FAILURE;
  4261. }
  4262. sel = nextsel(presel);
  4263. if (presel)
  4264. presel = 0;
  4265. switch (sel) {
  4266. #ifndef NOMOUSE
  4267. case SEL_CLICK:
  4268. if (getmouse(&event) != OK)
  4269. goto nochange;
  4270. /* Handle clicking on a context at the top */
  4271. if (event.bstate == BUTTON1_PRESSED && event.y == 0) {
  4272. /* Get context from: "[1 2 3 4]..." */
  4273. r = event.x >> 1;
  4274. /* If clicked after contexts, go to parent */
  4275. if (r >= CTX_MAX)
  4276. sel = SEL_BACK;
  4277. else if (r >= 0 && r != cfg.curctx) {
  4278. if (cfg.selmode)
  4279. lastappendpos = selbufpos;
  4280. savecurctx(&cfg, path, dents[cur].name, r);
  4281. /* Reset the pointers */
  4282. path = g_ctx[r].c_path;
  4283. lastdir = g_ctx[r].c_last;
  4284. lastname = g_ctx[r].c_name;
  4285. setdirwatch();
  4286. goto begin;
  4287. }
  4288. }
  4289. #endif
  4290. // fallthrough
  4291. case SEL_BACK:
  4292. #ifndef NOMOUSE
  4293. if (sel == SEL_BACK) {
  4294. #endif
  4295. dir = visit_parent(path, newpath, &presel);
  4296. if (!dir)
  4297. goto nochange;
  4298. /* Save last working directory */
  4299. xstrlcpy(lastdir, path, PATH_MAX);
  4300. /* Save history */
  4301. xstrlcpy(lastname, xbasename(path), NAME_MAX + 1);
  4302. clearfilter();
  4303. xstrlcpy(path, dir, PATH_MAX);
  4304. setdirwatch();
  4305. goto begin;
  4306. #ifndef NOMOUSE
  4307. }
  4308. #endif
  4309. #ifndef NOMOUSE
  4310. #if NCURSES_MOUSE_VERSION > 1
  4311. /* Scroll up */
  4312. if (event.bstate == BUTTON4_PRESSED && ndents && (cfg.rollover || cur)) {
  4313. move_cursor((cur + ndents - 1) % ndents, 0);
  4314. break;
  4315. }
  4316. /* Scroll down */
  4317. if (event.bstate == BUTTON5_PRESSED && ndents
  4318. && (cfg.rollover || (cur != ndents - 1))) {
  4319. move_cursor((cur + 1) % ndents, 0);
  4320. break;
  4321. }
  4322. #endif
  4323. /* Toggle filter mode on left click on last 2 lines */
  4324. if (event.y >= xlines - 2 && event.bstate == BUTTON1_PRESSED) {
  4325. clearfilter();
  4326. cfg.filtermode ^= 1;
  4327. if (cfg.filtermode) {
  4328. presel = FILTER;
  4329. goto nochange;
  4330. }
  4331. /* Start watching the directory */
  4332. dir_changed = TRUE;
  4333. if (ndents)
  4334. copycurname();
  4335. goto begin;
  4336. }
  4337. /* Handle clicking on a file */
  4338. if (event.y >= 2 && event.y <= ndents + 1 && event.bstate == BUTTON1_PRESSED) {
  4339. r = curscroll + (event.y - 2);
  4340. move_cursor(r, 1);
  4341. currentmouse ^= 1;
  4342. clock_gettime(
  4343. #if defined(CLOCK_MONOTONIC_RAW)
  4344. CLOCK_MONOTONIC_RAW,
  4345. #elif defined(CLOCK_MONOTONIC)
  4346. CLOCK_MONOTONIC,
  4347. #else
  4348. CLOCK_REALTIME,
  4349. #endif
  4350. &mousetimings[currentmouse]);
  4351. /*Single click just selects, double click also opens */
  4352. if (((_ABSSUB(mousetimings[0].tv_sec, mousetimings[1].tv_sec) << 30)
  4353. + (mousetimings[0].tv_nsec - mousetimings[1].tv_nsec))
  4354. > DOUBLECLICK_INTERVAL_NS)
  4355. break;
  4356. mousetimings[currentmouse].tv_sec = 0;
  4357. } else {
  4358. if (cfg.filtermode)
  4359. presel = FILTER;
  4360. goto nochange; // fallthrough
  4361. }
  4362. #endif
  4363. case SEL_NAV_IN: // fallthrough
  4364. case SEL_GOIN:
  4365. /* Cannot descend in empty directories */
  4366. if (!ndents)
  4367. goto begin;
  4368. mkpath(path, dents[cur].name, newpath);
  4369. DPRINTF_S(newpath);
  4370. /* Cannot use stale data in entry, file may be missing by now */
  4371. if (stat(newpath, &sb) == -1) {
  4372. printwarn(&presel);
  4373. goto nochange;
  4374. }
  4375. DPRINTF_U(sb.st_mode);
  4376. switch (sb.st_mode & S_IFMT) {
  4377. case S_IFDIR:
  4378. if (access(newpath, R_OK) == -1) {
  4379. printwarn(&presel);
  4380. goto nochange;
  4381. }
  4382. /* Save last working directory */
  4383. xstrlcpy(lastdir, path, PATH_MAX);
  4384. xstrlcpy(path, newpath, PATH_MAX);
  4385. lastname[0] = '\0';
  4386. clearfilter();
  4387. setdirwatch();
  4388. goto begin;
  4389. case S_IFREG:
  4390. {
  4391. /* If opened as vim plugin and Enter/^M pressed, pick */
  4392. if (cfg.picker && sel == SEL_GOIN) {
  4393. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4394. writesel(pselbuf, selbufpos - 1);
  4395. free(mark);
  4396. return _SUCCESS;
  4397. }
  4398. /* If open file is disabled on right arrow or `l`, return */
  4399. if (cfg.nonavopen && sel == SEL_NAV_IN)
  4400. goto nochange;
  4401. /* Handle plugin selection mode */
  4402. if (cfg.runplugin) {
  4403. cfg.runplugin = 0;
  4404. /* Must be in plugin dir and same context to select plugin */
  4405. if ((cfg.runctx == cfg.curctx) && !strcmp(path, plugindir)) {
  4406. endselection();
  4407. /* Copy path so we can return back to earlier dir */
  4408. xstrlcpy(path, rundir, PATH_MAX);
  4409. rundir[0] = '\0';
  4410. if (!run_selected_plugin(&path, dents[cur].name,
  4411. newpath, runfile, &lastname,
  4412. &lastdir)) {
  4413. DPRINTF_S("plugin failed!");
  4414. }
  4415. if (runfile[0])
  4416. runfile[0] = '\0';
  4417. clearfilter();
  4418. setdirwatch();
  4419. goto begin;
  4420. }
  4421. }
  4422. if (cfg.useeditor && (!sb.st_size ||
  4423. #ifdef FILE_MIME_OPTS
  4424. (get_output(g_buf, CMD_LEN_MAX, "file", FILE_MIME_OPTS, newpath, FALSE)
  4425. && !strncmp(g_buf, "text/", 5)))) {
  4426. #else
  4427. /* no mime option; guess from description instead */
  4428. (get_output(g_buf, CMD_LEN_MAX, "file", "-b", newpath, FALSE)
  4429. && strstr(g_buf, "text")))) {
  4430. #endif
  4431. spawn(editor, newpath, NULL, path, F_CLI);
  4432. continue;
  4433. }
  4434. if (!sb.st_size) {
  4435. printwait(messages[MSG_EMPTY_FILE], &presel);
  4436. goto nochange;
  4437. }
  4438. #ifdef PCRE
  4439. if (!pcre_exec(archive_pcre, NULL, dents[cur].name,
  4440. strlen(dents[cur].name), 0, 0, NULL, 0)) {
  4441. #else
  4442. if (!regexec(&archive_re, dents[cur].name, 0, NULL, 0)) {
  4443. #endif
  4444. r = get_input(messages[MSG_ARCHIVE_OPTS]);
  4445. if (r == 'l' || r == 'x') {
  4446. mkpath(path, dents[cur].name, newpath);
  4447. handle_archive(newpath, path, r);
  4448. copycurname();
  4449. goto begin;
  4450. }
  4451. if (r == 'm') {
  4452. if (archive_mount(dents[cur].name,
  4453. path, newpath, &presel)) {
  4454. lastname[0] = '\0';
  4455. /* Save last working directory */
  4456. xstrlcpy(lastdir, path, PATH_MAX);
  4457. /* Switch to mount point */
  4458. xstrlcpy(path, newpath, PATH_MAX);
  4459. setdirwatch();
  4460. goto begin;
  4461. } else {
  4462. printwait(messages[MSG_FAILED], &presel);
  4463. goto nochange;
  4464. }
  4465. }
  4466. if (r != 'd') {
  4467. printwait(messages[MSG_INVALID_KEY], &presel);
  4468. goto nochange;
  4469. }
  4470. }
  4471. /* Invoke desktop opener as last resort */
  4472. spawn(opener, newpath, NULL, NULL, opener_flags);
  4473. /* Move cursor to the next entry if not the last entry */
  4474. if ((g_states & STATE_AUTONEXT) && cur != ndents - 1)
  4475. move_cursor((cur + 1) % ndents, 0);
  4476. continue;
  4477. }
  4478. default:
  4479. printwait(messages[MSG_UNSUPPORTED], &presel);
  4480. goto nochange;
  4481. }
  4482. case SEL_NEXT: // fallthrough
  4483. case SEL_PREV: // fallthrough
  4484. case SEL_PGDN: // fallthrough
  4485. case SEL_CTRL_D: // fallthrough
  4486. case SEL_PGUP: // fallthrough
  4487. case SEL_CTRL_U: // fallthrough
  4488. case SEL_HOME: // fallthrough
  4489. case SEL_END: // fallthrough
  4490. case SEL_FIRST:
  4491. g_states |= STATE_MOVE_OP;
  4492. handle_screen_move(sel);
  4493. break;
  4494. case SEL_CDHOME: // fallthrough
  4495. case SEL_CDBEGIN: // fallthrough
  4496. case SEL_CDLAST: // fallthrough
  4497. case SEL_CDROOT:
  4498. switch (sel) {
  4499. case SEL_CDHOME:
  4500. dir = home;
  4501. break;
  4502. case SEL_CDBEGIN:
  4503. dir = ipath;
  4504. break;
  4505. case SEL_CDLAST:
  4506. dir = lastdir;
  4507. break;
  4508. default: /* SEL_CDROOT */
  4509. dir = "/";
  4510. break;
  4511. }
  4512. if (!dir || !*dir) {
  4513. printwait(messages[MSG_NOT_SET], &presel);
  4514. goto nochange;
  4515. }
  4516. if (!xdiraccess(dir)) {
  4517. presel = MSGWAIT;
  4518. goto nochange;
  4519. }
  4520. if (strcmp(path, dir) == 0)
  4521. goto nochange;
  4522. /* SEL_CDLAST: dir pointing to lastdir */
  4523. xstrlcpy(newpath, dir, PATH_MAX);
  4524. /* Save last working directory */
  4525. xstrlcpy(lastdir, path, PATH_MAX);
  4526. xstrlcpy(path, newpath, PATH_MAX);
  4527. lastname[0] = '\0';
  4528. clearfilter();
  4529. DPRINTF_S(path);
  4530. setdirwatch();
  4531. goto begin;
  4532. case SEL_BOOKMARK:
  4533. r = xstrlcpy(g_buf, messages[MSG_BOOKMARK_KEYS], CMD_LEN_MAX);
  4534. if (mark) { /* There is a pinned directory */
  4535. g_buf[--r] = ' ';
  4536. g_buf[++r] = ',';
  4537. g_buf[++r] = '\0';
  4538. ++r;
  4539. }
  4540. printkeys(bookmark, g_buf + r - 1, maxbm);
  4541. printprompt(g_buf);
  4542. fd = get_input(NULL);
  4543. r = FALSE;
  4544. if (fd == ',') /* Visit pinned directory */
  4545. mark ? xstrlcpy(newpath, mark, PATH_MAX) : (r = MSG_NOT_SET);
  4546. else if (!get_kv_val(bookmark, newpath, fd, maxbm, TRUE))
  4547. r = MSG_INVALID_KEY;
  4548. if (!r && !xdiraccess(newpath))
  4549. r = MSG_ACCESS;
  4550. if (r) {
  4551. printwait(messages[r], &presel);
  4552. goto nochange;
  4553. }
  4554. if (strcmp(path, newpath) == 0)
  4555. break;
  4556. lastname[0] = '\0';
  4557. clearfilter();
  4558. /* Save last working directory */
  4559. xstrlcpy(lastdir, path, PATH_MAX);
  4560. /* Save the newly opted dir in path */
  4561. xstrlcpy(path, newpath, PATH_MAX);
  4562. DPRINTF_S(path);
  4563. setdirwatch();
  4564. goto begin;
  4565. case SEL_CYCLE: // fallthrough
  4566. case SEL_CYCLER: // fallthrough
  4567. case SEL_CTX1: // fallthrough
  4568. case SEL_CTX2: // fallthrough
  4569. case SEL_CTX3: // fallthrough
  4570. case SEL_CTX4:
  4571. r = handle_context_switch(sel, newpath);
  4572. if (r < 0)
  4573. continue;
  4574. savecurctx(&cfg, path, dents[cur].name, r);
  4575. /* Reset the pointers */
  4576. path = g_ctx[r].c_path;
  4577. lastdir = g_ctx[r].c_last;
  4578. lastname = g_ctx[r].c_name;
  4579. tmp = g_ctx[r].c_fltr;
  4580. if (cfg.filtermode || ((tmp[0] == FILTER || tmp[0] == RFILTER) && tmp[1]))
  4581. presel = FILTER;
  4582. else
  4583. dir_changed = TRUE;
  4584. goto begin;
  4585. case SEL_PIN:
  4586. free(mark);
  4587. mark = strdup(path);
  4588. printwait(mark, &presel);
  4589. goto nochange;
  4590. case SEL_FLTR:
  4591. /* Unwatch dir if we are still in a filtered view */
  4592. #ifdef LINUX_INOTIFY
  4593. if (inotify_wd >= 0) {
  4594. inotify_rm_watch(inotify_fd, inotify_wd);
  4595. inotify_wd = -1;
  4596. }
  4597. #elif defined(BSD_KQUEUE)
  4598. if (event_fd >= 0) {
  4599. close(event_fd);
  4600. event_fd = -1;
  4601. }
  4602. #elif defined(HAIKU_NM)
  4603. if (haiku_nm_active) {
  4604. haiku_stop_watch(haiku_hnd);
  4605. haiku_nm_active = FALSE;
  4606. }
  4607. #endif
  4608. presel = filterentries(path, lastname);
  4609. if (presel == 27) {
  4610. presel = 0;
  4611. break;
  4612. }
  4613. goto nochange;
  4614. case SEL_MFLTR: // fallthrough
  4615. case SEL_HIDDEN: // fallthrough
  4616. case SEL_DETAIL: // fallthrough
  4617. case SEL_SORT:
  4618. switch (sel) {
  4619. case SEL_MFLTR:
  4620. cfg.filtermode ^= 1;
  4621. if (cfg.filtermode) {
  4622. presel = FILTER;
  4623. clearfilter();
  4624. goto nochange;
  4625. }
  4626. /* Start watching the directory */
  4627. dir_changed = TRUE;
  4628. break;
  4629. case SEL_HIDDEN:
  4630. cfg.showhidden ^= 1;
  4631. if (ndents)
  4632. copycurname();
  4633. if (cfg.filtermode)
  4634. presel = FILTER;
  4635. clearfilter();
  4636. goto begin;
  4637. case SEL_DETAIL:
  4638. cfg.showdetail ^= 1;
  4639. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  4640. cfg.blkorder = 0;
  4641. continue;
  4642. default: /* SEL_SORT */
  4643. if (!set_sort_flags()) {
  4644. if (cfg.filtermode)
  4645. presel = FILTER;
  4646. printwait(messages[MSG_INVALID_KEY], &presel);
  4647. goto nochange;
  4648. }
  4649. }
  4650. if (cfg.filtermode)
  4651. presel = FILTER;
  4652. /* Save current */
  4653. if (ndents)
  4654. copycurname();
  4655. /* If there's no filter, reload the directory */
  4656. if (!g_ctx[cfg.curctx].c_fltr[1])
  4657. goto begin;
  4658. presel = FILTER; /* If there's a filter, apply it */
  4659. break;
  4660. case SEL_STATS: // fallthrough
  4661. case SEL_CHMODX:
  4662. if (ndents) {
  4663. tmp = (g_listpath && xstrcmp(path, g_listpath) == 0) ? g_prefixpath : path;
  4664. mkpath(tmp, dents[cur].name, newpath);
  4665. if (lstat(newpath, &sb) == -1
  4666. || (sel == SEL_STATS && !show_stats(newpath, &sb))
  4667. || (sel == SEL_CHMODX && !xchmod(newpath, sb.st_mode))) {
  4668. printwarn(&presel);
  4669. goto nochange;
  4670. }
  4671. if (sel == SEL_CHMODX)
  4672. dents[cur].mode ^= 0111;
  4673. }
  4674. break;
  4675. case SEL_REDRAW: // fallthrough
  4676. case SEL_RENAMEMUL: // fallthrough
  4677. case SEL_HELP: // fallthrough
  4678. case SEL_EDIT: // fallthrough
  4679. case SEL_LOCK:
  4680. {
  4681. bool refresh = FALSE;
  4682. if (ndents)
  4683. mkpath(path, dents[cur].name, newpath);
  4684. else if (sel == SEL_EDIT) /* Avoid trying to edit a non-existing file */
  4685. goto nochange;
  4686. switch (sel) {
  4687. case SEL_REDRAW:
  4688. refresh = TRUE;
  4689. break;
  4690. case SEL_RENAMEMUL:
  4691. endselection();
  4692. if (!batch_rename(path)) {
  4693. printwait(messages[MSG_FAILED], &presel);
  4694. goto nochange;
  4695. }
  4696. refresh = TRUE;
  4697. break;
  4698. case SEL_HELP:
  4699. show_help(path);
  4700. if (cfg.filtermode)
  4701. presel = FILTER;
  4702. continue;
  4703. case SEL_EDIT:
  4704. spawn(editor, dents[cur].name, NULL, path, F_CLI);
  4705. continue;
  4706. default: /* SEL_LOCK */
  4707. lock_terminal();
  4708. break;
  4709. }
  4710. /* In case of successful operation, reload contents */
  4711. /* Continue in navigate-as-you-type mode, if enabled */
  4712. if (cfg.filtermode && !refresh)
  4713. break;
  4714. /* Save current */
  4715. if (ndents)
  4716. copycurname();
  4717. /* Repopulate as directory content may have changed */
  4718. goto begin;
  4719. }
  4720. case SEL_SEL:
  4721. if (!ndents)
  4722. goto nochange;
  4723. startselection();
  4724. if (g_states & STATE_RANGESEL)
  4725. g_states &= ~STATE_RANGESEL;
  4726. /* Toggle selection status */
  4727. dents[cur].flags ^= FILE_SELECTED;
  4728. if (dents[cur].flags & FILE_SELECTED) {
  4729. ++nselected;
  4730. appendfpath(newpath, mkpath(path, dents[cur].name, newpath));
  4731. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4732. } else {
  4733. selbufpos = lastappendpos;
  4734. if (--nselected) {
  4735. updateselbuf(path, newpath);
  4736. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4737. } else
  4738. writesel(NULL, 0);
  4739. }
  4740. if (cfg.x11)
  4741. plugscript(utils[UTIL_CBCP], newpath, F_NOWAIT | F_NOTRACE);
  4742. if (!nselected)
  4743. unlink(g_selpath);
  4744. /* move cursor to the next entry if this is not the last entry */
  4745. if (!cfg.picker && cur != ndents - 1)
  4746. move_cursor((cur + 1) % ndents, 0);
  4747. break;
  4748. case SEL_SELMUL:
  4749. if (!ndents)
  4750. goto nochange;
  4751. startselection();
  4752. g_states ^= STATE_RANGESEL;
  4753. if (stat(path, &sb) == -1) {
  4754. printwarn(&presel);
  4755. goto nochange;
  4756. }
  4757. if (g_states & STATE_RANGESEL) { /* Range selection started */
  4758. #ifndef DIR_LIMITED_SELECTION
  4759. inode = sb.st_ino;
  4760. #endif
  4761. selstartid = cur;
  4762. continue;
  4763. }
  4764. #ifndef DIR_LIMITED_SELECTION
  4765. if (inode != sb.st_ino) {
  4766. printwait(messages[MSG_DIR_CHANGED], &presel);
  4767. goto nochange;
  4768. }
  4769. #endif
  4770. if (cur < selstartid) {
  4771. selendid = selstartid;
  4772. selstartid = cur;
  4773. } else
  4774. selendid = cur;
  4775. /* Clear selection on repeat on same file */
  4776. if (selstartid == selendid) {
  4777. resetselind();
  4778. clearselection();
  4779. break;
  4780. } // fallthrough
  4781. case SEL_SELALL:
  4782. if (sel == SEL_SELALL) {
  4783. if (!ndents)
  4784. goto nochange;
  4785. startselection();
  4786. if (g_states & STATE_RANGESEL)
  4787. g_states &= ~STATE_RANGESEL;
  4788. selstartid = 0;
  4789. selendid = ndents - 1;
  4790. }
  4791. /* Remember current selection buffer position */
  4792. for (r = selstartid; r <= selendid; ++r)
  4793. if (!(dents[r].flags & FILE_SELECTED)) {
  4794. /* Write the path to selection file to avoid flush */
  4795. appendfpath(newpath, mkpath(path, dents[r].name, newpath));
  4796. dents[r].flags |= FILE_SELECTED;
  4797. ++nselected;
  4798. }
  4799. writesel(pselbuf, selbufpos - 1); /* Truncate NULL from end */
  4800. if (cfg.x11)
  4801. plugscript(utils[UTIL_CBCP], newpath, F_NOWAIT | F_NOTRACE);
  4802. continue;
  4803. case SEL_SELEDIT:
  4804. r = editselection();
  4805. if (r <= 0) {
  4806. r = !r ? MSG_0_SELECTED : MSG_FAILED;
  4807. printwait(messages[r], &presel);
  4808. } else {
  4809. if (cfg.x11)
  4810. plugscript(utils[UTIL_CBCP], newpath, F_NOWAIT | F_NOTRACE);
  4811. cfg.filtermode ? presel = FILTER : statusbar(path);
  4812. }
  4813. goto nochange;
  4814. case SEL_CP: // fallthrough
  4815. case SEL_MV: // fallthrough
  4816. case SEL_CPMVAS: // fallthrough
  4817. case SEL_RM:
  4818. {
  4819. if (sel == SEL_RM) {
  4820. r = get_cur_or_sel();
  4821. if (!r) {
  4822. statusbar(path);
  4823. goto nochange;
  4824. }
  4825. if (r == 'c') {
  4826. tmp = (g_listpath && xstrcmp(path, g_listpath) == 0)
  4827. ? g_prefixpath : path;
  4828. mkpath(tmp, dents[cur].name, newpath);
  4829. xrm(newpath);
  4830. if (cfg.filtermode)
  4831. presel = FILTER;
  4832. if (access(newpath, F_OK) == 0) /* File not removed */
  4833. goto nochange;
  4834. else if (cur) {
  4835. cur += (cur != (ndents - 1)) ? 1 : -1;
  4836. copycurname();
  4837. } else
  4838. lastname[0] = '\0';
  4839. goto begin;
  4840. }
  4841. }
  4842. endselection();
  4843. if (!cpmvrm_selection(sel, path, &presel))
  4844. goto nochange;
  4845. clearfilter();
  4846. /* Show notification on operation complete */
  4847. if (cfg.x11)
  4848. plugscript(utils[UTIL_NTFY], newpath, F_NOWAIT | F_NOTRACE);
  4849. if (ndents)
  4850. copycurname();
  4851. goto begin;
  4852. }
  4853. case SEL_ARCHIVE: // fallthrough
  4854. case SEL_OPENWITH: // fallthrough
  4855. case SEL_NEW: // fallthrough
  4856. case SEL_RENAME:
  4857. {
  4858. int dup = 'n';
  4859. if (!ndents && (sel == SEL_OPENWITH || sel == SEL_RENAME))
  4860. break;
  4861. if (sel != SEL_OPENWITH)
  4862. endselection();
  4863. switch (sel) {
  4864. case SEL_ARCHIVE:
  4865. r = get_cur_or_sel();
  4866. if (!r) {
  4867. statusbar(path);
  4868. goto nochange;
  4869. }
  4870. if (r == 's') {
  4871. if (!selsafe()) {
  4872. presel = MSGWAIT;
  4873. goto nochange;
  4874. }
  4875. tmp = NULL;
  4876. } else
  4877. tmp = dents[cur].name;
  4878. tmp = xreadline(tmp, messages[MSG_ARCHIVE_NAME]);
  4879. break;
  4880. case SEL_OPENWITH:
  4881. #ifdef NORL
  4882. tmp = xreadline(NULL, messages[MSG_OPEN_WITH]);
  4883. #else
  4884. presel = 0;
  4885. tmp = getreadline(messages[MSG_OPEN_WITH], path, ipath, &presel);
  4886. if (presel == MSGWAIT)
  4887. goto nochange;
  4888. #endif
  4889. break;
  4890. case SEL_NEW:
  4891. r = get_input(messages[MSG_NEW_OPTS]);
  4892. if (r == 'f' || r == 'd')
  4893. tmp = xreadline(NULL, messages[MSG_REL_PATH]);
  4894. else if (r == 's' || r == 'h')
  4895. tmp = xreadline(NULL, messages[MSG_LINK_PREFIX]);
  4896. else
  4897. tmp = NULL;
  4898. break;
  4899. default: /* SEL_RENAME */
  4900. tmp = xreadline(dents[cur].name, "");
  4901. break;
  4902. }
  4903. if (!tmp || !*tmp)
  4904. break;
  4905. /* Allow only relative, same dir paths */
  4906. if (tmp[0] == '/'
  4907. || ((r != 'f' && r != 'd') && (xstrcmp(xbasename(tmp), tmp) != 0))) {
  4908. printwait(messages[MSG_NO_TRAVERSAL], &presel);
  4909. goto nochange;
  4910. }
  4911. switch (sel) {
  4912. case SEL_ARCHIVE:
  4913. if (r == 'c' && strcmp(tmp, dents[cur].name) == 0)
  4914. goto nochange;
  4915. mkpath(path, tmp, newpath);
  4916. if (access(newpath, F_OK) == 0) {
  4917. fd = get_input(messages[MSG_OVERWRITE]);
  4918. if (!xconfirm(fd)) {
  4919. statusbar(path);
  4920. goto nochange;
  4921. }
  4922. }
  4923. get_archive_cmd(newpath, tmp);
  4924. (r == 's') ? archive_selection(newpath, tmp, path)
  4925. : spawn(newpath, tmp, dents[cur].name,
  4926. path, F_NORMAL | F_MULTI);
  4927. // fallthrough
  4928. case SEL_OPENWITH:
  4929. if (sel == SEL_OPENWITH) {
  4930. /* Confirm if app is CLI or GUI */
  4931. r = get_input(messages[MSG_CLI_MODE]);
  4932. r = (r == 'c' ? F_CLI :
  4933. (r == 'g' ? F_NOWAIT | F_NOTRACE | F_MULTI : 0));
  4934. if (!r) {
  4935. cfg.filtermode ? presel = FILTER : statusbar(path);
  4936. goto nochange;
  4937. }
  4938. mkpath(path, dents[cur].name, newpath);
  4939. spawn(tmp, newpath, NULL, path, r);
  4940. }
  4941. if (cfg.filtermode)
  4942. presel = FILTER;
  4943. copycurname();
  4944. goto begin;
  4945. case SEL_RENAME:
  4946. /* Skip renaming to same name */
  4947. if (strcmp(tmp, dents[cur].name) == 0) {
  4948. tmp = xreadline(dents[cur].name, messages[MSG_COPY_NAME]);
  4949. if (strcmp(tmp, dents[cur].name) == 0)
  4950. goto nochange;
  4951. dup = 'd';
  4952. }
  4953. break;
  4954. default: /* SEL_NEW */
  4955. break;
  4956. }
  4957. /* Open the descriptor to currently open directory */
  4958. #ifdef O_DIRECTORY
  4959. fd = open(path, O_RDONLY | O_DIRECTORY);
  4960. #else
  4961. fd = open(path, O_RDONLY);
  4962. #endif
  4963. if (fd == -1) {
  4964. printwarn(&presel);
  4965. goto nochange;
  4966. }
  4967. /* Check if another file with same name exists */
  4968. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  4969. if (sel == SEL_RENAME) {
  4970. /* Overwrite file with same name? */
  4971. r = get_input(messages[MSG_OVERWRITE]);
  4972. if (!xconfirm(r)) {
  4973. close(fd);
  4974. break;
  4975. }
  4976. } else {
  4977. /* Do nothing in case of NEW */
  4978. close(fd);
  4979. printwait(messages[MSG_EXISTS], &presel);
  4980. goto nochange;
  4981. }
  4982. }
  4983. if (sel == SEL_RENAME) {
  4984. /* Rename the file */
  4985. if (dup == 'd')
  4986. spawn("cp -rp", dents[cur].name, tmp, path, F_SILENT);
  4987. else if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  4988. close(fd);
  4989. printwarn(&presel);
  4990. goto nochange;
  4991. }
  4992. close(fd);
  4993. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  4994. } else { /* SEL_NEW */
  4995. close(fd); /* Use fd as tmp var */
  4996. presel = 0;
  4997. /* Check if it's a dir or file */
  4998. if (r == 'f') {
  4999. mkpath(path, tmp, newpath);
  5000. fd = xmktree(newpath, FALSE);
  5001. } else if (r == 'd') {
  5002. mkpath(path, tmp, newpath);
  5003. fd = xmktree(newpath, TRUE);
  5004. } else if (r == 's' || r == 'h') {
  5005. if (tmp[0] == '@' && tmp[1] == '\0')
  5006. tmp[0] = '\0';
  5007. fd = xlink(tmp, path, (ndents ? dents[cur].name : NULL),
  5008. newpath, &presel, r);
  5009. }
  5010. if (!fd)
  5011. printwait(messages[MSG_FAILED], &presel);
  5012. if (fd <= 0)
  5013. goto nochange;
  5014. if (r == 'f' || r == 'd')
  5015. xstrlcpy(lastname, tmp, NAME_MAX + 1);
  5016. else if (ndents) {
  5017. if (cfg.filtermode)
  5018. presel = FILTER;
  5019. copycurname();
  5020. }
  5021. }
  5022. goto begin;
  5023. }
  5024. case SEL_PLUGIN:
  5025. /* Check if directory is accessible */
  5026. if (!xdiraccess(plugindir)) {
  5027. printwarn(&presel);
  5028. goto nochange;
  5029. }
  5030. r = xstrlcpy(g_buf, messages[MSG_PLUGIN_KEYS], CMD_LEN_MAX);
  5031. printkeys(plug, g_buf + r - 1, maxplug);
  5032. printprompt(g_buf);
  5033. r = get_input(NULL);
  5034. if (r != '\r') {
  5035. endselection();
  5036. tmp = get_kv_val(plug, NULL, r, maxplug, FALSE);
  5037. if (!tmp) {
  5038. printwait(messages[MSG_INVALID_KEY], &presel);
  5039. goto nochange;
  5040. }
  5041. if (tmp[0] == '-' && tmp[1]) {
  5042. ++tmp;
  5043. r = FALSE; /* Do not refresh dir after completion */
  5044. } else
  5045. r = TRUE;
  5046. if (!run_selected_plugin(&path, tmp, newpath,
  5047. (ndents ? dents[cur].name : NULL),
  5048. &lastname, &lastdir)) {
  5049. printwait(messages[MSG_FAILED], &presel);
  5050. goto nochange;
  5051. }
  5052. if (ndents)
  5053. copycurname();
  5054. if (!r) {
  5055. cfg.filtermode ? presel = FILTER : statusbar(path);
  5056. goto nochange;
  5057. }
  5058. } else { /* 'Return/Enter' enters the plugin directory */
  5059. cfg.runplugin ^= 1;
  5060. if (!cfg.runplugin && rundir[0]) {
  5061. /*
  5062. * If toggled, and still in the plugin dir,
  5063. * switch to original directory
  5064. */
  5065. if (strcmp(path, plugindir) == 0) {
  5066. xstrlcpy(path, rundir, PATH_MAX);
  5067. xstrlcpy(lastname, runfile, NAME_MAX);
  5068. rundir[0] = runfile[0] = '\0';
  5069. setdirwatch();
  5070. goto begin;
  5071. }
  5072. /* Otherwise, initiate choosing plugin again */
  5073. cfg.runplugin = 1;
  5074. }
  5075. xstrlcpy(rundir, path, PATH_MAX);
  5076. xstrlcpy(path, plugindir, PATH_MAX);
  5077. if (ndents)
  5078. xstrlcpy(runfile, dents[cur].name, NAME_MAX);
  5079. cfg.runctx = cfg.curctx;
  5080. lastname[0] = '\0';
  5081. }
  5082. setdirwatch();
  5083. clearfilter();
  5084. goto begin;
  5085. case SEL_SHELL: // fallthrough
  5086. case SEL_LAUNCH: // fallthrough
  5087. case SEL_RUNCMD:
  5088. endselection();
  5089. switch (sel) {
  5090. case SEL_SHELL:
  5091. /* Set nnn nesting level */
  5092. tmp = getenv(env_cfg[NNNLVL]);
  5093. setenv(env_cfg[NNNLVL], xitoa((tmp ? atoi(tmp) : 0) + 1), 1);
  5094. setenv(envs[ENV_NCUR], (ndents ? dents[cur].name : ""), 1);
  5095. spawn(shell, NULL, NULL, path, F_CLI);
  5096. break;
  5097. case SEL_LAUNCH:
  5098. launch_app(path, newpath);
  5099. if (cfg.filtermode)
  5100. presel = FILTER;
  5101. goto nochange;
  5102. default: /* SEL_RUNCMD */
  5103. #ifndef NORL
  5104. if (cfg.picker) {
  5105. #endif
  5106. tmp = xreadline(NULL, ">>> ");
  5107. #ifndef NORL
  5108. } else {
  5109. presel = 0;
  5110. tmp = getreadline(">>> ", path, ipath, &presel);
  5111. if (presel == MSGWAIT)
  5112. goto nochange;
  5113. }
  5114. #endif
  5115. if (tmp && *tmp) // NOLINT
  5116. prompt_run(tmp, (ndents ? dents[cur].name : ""), path);
  5117. else
  5118. goto nochange;
  5119. }
  5120. /* Continue in navigate-as-you-type mode, if enabled */
  5121. if (cfg.filtermode)
  5122. presel = FILTER;
  5123. /* Save current */
  5124. if (ndents)
  5125. copycurname();
  5126. /* Repopulate as directory content may have changed */
  5127. goto begin;
  5128. case SEL_REMOTE:
  5129. if (sel == SEL_REMOTE && !remote_mount(newpath, &presel))
  5130. goto nochange;
  5131. lastname[0] = '\0';
  5132. /* Save last working directory */
  5133. xstrlcpy(lastdir, path, PATH_MAX);
  5134. /* Switch to mount point */
  5135. xstrlcpy(path, newpath, PATH_MAX);
  5136. setdirwatch();
  5137. goto begin;
  5138. case SEL_UMOUNT:
  5139. tmp = ndents ? dents[cur].name : NULL;
  5140. unmount(tmp, newpath, &presel, path);
  5141. goto nochange;
  5142. case SEL_SESSIONS:
  5143. r = get_input(messages[MSG_SSN_OPTS]);
  5144. if (r == 's')
  5145. save_session(FALSE, &presel);
  5146. else if (r == 'l' || r == 'r') {
  5147. if (load_session(NULL, &path, &lastdir, &lastname, r == 'r')) {
  5148. setdirwatch();
  5149. goto begin;
  5150. }
  5151. }
  5152. statusbar(path);
  5153. goto nochange;
  5154. case SEL_AUTONEXT:
  5155. g_states ^= STATE_AUTONEXT;
  5156. goto nochange;
  5157. case SEL_QUITCTX: // fallthrough
  5158. case SEL_QUITCD: // fallthrough
  5159. case SEL_QUIT:
  5160. case SEL_QUITFAIL:
  5161. if (sel == SEL_QUITCTX) {
  5162. fd = cfg.curctx; /* fd used as tmp var */
  5163. for (r = (fd + 1) & ~CTX_MAX;
  5164. (r != fd) && !g_ctx[r].c_cfg.ctxactive;
  5165. r = ((r + 1) & ~CTX_MAX)) {
  5166. };
  5167. if (r != fd) {
  5168. bool selmode = cfg.selmode ? TRUE : FALSE;
  5169. g_ctx[fd].c_cfg.ctxactive = 0;
  5170. /* Switch to next active context */
  5171. path = g_ctx[r].c_path;
  5172. lastdir = g_ctx[r].c_last;
  5173. lastname = g_ctx[r].c_name;
  5174. /* Switch light/detail mode */
  5175. if (cfg.showdetail != g_ctx[r].c_cfg.showdetail)
  5176. /* Set the reverse */
  5177. printptr = cfg.showdetail ?
  5178. &printent : &printent_long;
  5179. cfg = g_ctx[r].c_cfg;
  5180. /* Continue selection mode */
  5181. cfg.selmode = selmode;
  5182. cfg.curctx = r;
  5183. setdirwatch();
  5184. goto begin;
  5185. }
  5186. } else if (!cfg.forcequit) {
  5187. for (r = 0; r < CTX_MAX; ++r)
  5188. if (r != cfg.curctx && g_ctx[r].c_cfg.ctxactive) {
  5189. r = get_input(messages[MSG_QUIT_ALL]);
  5190. break;
  5191. }
  5192. if (!(r == CTX_MAX || xconfirm(r)))
  5193. break; // fallthrough
  5194. }
  5195. /* CD on Quit */
  5196. /* In vim picker mode, clear selection and exit */
  5197. /* Picker mode: reset buffer or clear file */
  5198. if (sel == SEL_QUITCD || getenv("NNN_TMPFILE"))
  5199. cfg.picker ? selbufpos = 0 : write_lastdir(path);
  5200. free(mark);
  5201. return sel == SEL_QUITFAIL ? _FAILURE : _SUCCESS;
  5202. default:
  5203. if (xlines != LINES || xcols != COLS)
  5204. setdirwatch(); /* Terminal resized */
  5205. else if (idletimeout && idle == idletimeout)
  5206. lock_terminal(); /* Locker */
  5207. else
  5208. goto nochange;
  5209. idle = 0;
  5210. if (ndents)
  5211. copycurname();
  5212. goto begin;
  5213. } /* switch (sel) */
  5214. }
  5215. }
  5216. static char *make_tmp_tree(char **paths, ssize_t entries, const char *prefix)
  5217. {
  5218. /* tmpdir holds the full path */
  5219. /* tmp holds the path without the tmp dir prefix */
  5220. int err, ignore = 0;
  5221. struct stat sb;
  5222. char *slash, *tmp;
  5223. ssize_t i, len = strlen(prefix);
  5224. char *tmpdir = malloc(sizeof(char) * (PATH_MAX + TMP_LEN_MAX));
  5225. if (!tmpdir) {
  5226. DPRINTF_S(strerror(errno));
  5227. return NULL;
  5228. }
  5229. tmp = tmpdir + g_tmpfplen - 1;
  5230. xstrlcpy(tmpdir, g_tmpfpath, g_tmpfplen);
  5231. xstrlcpy(tmp, "/nnnXXXXXX", 11);
  5232. /* Points right after the base tmp dir */
  5233. tmp += 10;
  5234. if (!mkdtemp(tmpdir)) {
  5235. free(tmpdir);
  5236. DPRINTF_S(strerror(errno));
  5237. return NULL;
  5238. }
  5239. g_listpath = tmpdir;
  5240. for (i = 0; i < entries; ++i) {
  5241. if (!paths[i])
  5242. continue;
  5243. err = stat(paths[i], &sb);
  5244. if (err && errno == ENOENT) {
  5245. ignore = 1;
  5246. continue;
  5247. }
  5248. /* Don't copy the common prefix */
  5249. xstrlcpy(tmp, paths[i] + len, strlen(paths[i]) - len + 1);
  5250. /* Get the dir containing the path */
  5251. slash = xmemrchr((uchar *)tmp, '/', strlen(paths[i]) - len);
  5252. if (slash)
  5253. *slash = '\0';
  5254. xmktree(tmpdir, TRUE);
  5255. if (slash)
  5256. *slash = '/';
  5257. if (symlink(paths[i], tmpdir)) {
  5258. DPRINTF_S(paths[i]);
  5259. DPRINTF_S(strerror(errno));
  5260. }
  5261. }
  5262. if (ignore)
  5263. g_states |= STATE_MSG;
  5264. /* Get the dir in which to start */
  5265. *tmp = '\0';
  5266. return tmpdir;
  5267. }
  5268. static char *load_input()
  5269. {
  5270. /* 512 KiB chunk size */
  5271. ssize_t i, chunk_count = 1, chunk = 512 * 1024, entries = 0;
  5272. char *input = malloc(sizeof(char) * chunk), *tmpdir = NULL;
  5273. char cwd[PATH_MAX], *next, *tmp;
  5274. size_t offsets[LIST_FILES_MAX];
  5275. char **paths = NULL;
  5276. ssize_t input_read, total_read = 0, off = 0;
  5277. if (!input) {
  5278. DPRINTF_S(strerror(errno));
  5279. return NULL;
  5280. }
  5281. if (!getcwd(cwd, PATH_MAX)) {
  5282. free(input);
  5283. return NULL;
  5284. }
  5285. while (chunk_count < 512) {
  5286. input_read = read(STDIN_FILENO, input + total_read, chunk);
  5287. if (input_read < 0) {
  5288. DPRINTF_S(strerror(errno));
  5289. goto malloc_1;
  5290. }
  5291. if (input_read == 0)
  5292. break;
  5293. total_read += input_read;
  5294. ++chunk_count;
  5295. while (off < total_read) {
  5296. next = memchr(input + off, '\0', total_read - off) + 1;
  5297. if (next == (void *)1)
  5298. break;
  5299. if (next - input == off + 1) {
  5300. off = next - input;
  5301. continue;
  5302. }
  5303. if (entries == LIST_FILES_MAX)
  5304. goto malloc_1;
  5305. offsets[entries++] = off;
  5306. off = next - input;
  5307. }
  5308. if (chunk_count == 512)
  5309. goto malloc_1;
  5310. /* We don't need to allocate another chunk */
  5311. if (chunk_count == (total_read - input_read) / chunk)
  5312. continue;
  5313. chunk_count = total_read / chunk;
  5314. if (total_read % chunk)
  5315. ++chunk_count;
  5316. if (!(input = xrealloc(input, (chunk_count + 1) * chunk)))
  5317. return NULL;
  5318. }
  5319. if (off != total_read) {
  5320. if (entries == LIST_FILES_MAX)
  5321. goto malloc_1;
  5322. offsets[entries++] = off;
  5323. }
  5324. DPRINTF_D(entries);
  5325. DPRINTF_D(total_read);
  5326. DPRINTF_D(chunk_count);
  5327. if (!entries)
  5328. goto malloc_1;
  5329. input[total_read] = '\0';
  5330. paths = malloc(entries * sizeof(char *));
  5331. if (!paths)
  5332. goto malloc_1;
  5333. for (i = 0; i < entries; ++i)
  5334. paths[i] = input + offsets[i];
  5335. g_prefixpath = malloc(sizeof(char) * PATH_MAX);
  5336. if (!g_prefixpath)
  5337. goto malloc_1;
  5338. g_prefixpath[0] = '\0';
  5339. DPRINTF_S(paths[0]);
  5340. for (i = 0; i < entries; ++i) {
  5341. if (paths[i][0] == '\n' || selforparent(paths[i])) {
  5342. paths[i] = NULL;
  5343. continue;
  5344. }
  5345. if (!(paths[i] = abspath(paths[i], cwd))) {
  5346. entries = i; // free from the previous entry
  5347. goto malloc_2;
  5348. }
  5349. DPRINTF_S(paths[i]);
  5350. xstrlcpy(g_buf, paths[i], PATH_MAX);
  5351. if (!common_prefix(dirname(g_buf), g_prefixpath)) {
  5352. entries = i + 1; // free from the current entry
  5353. goto malloc_2;
  5354. }
  5355. DPRINTF_S(g_prefixpath);
  5356. }
  5357. DPRINTF_S(g_prefixpath);
  5358. if (g_prefixpath[0]) {
  5359. if (entries == 1) {
  5360. tmp = xmemrchr((uchar *)g_prefixpath, '/', strlen(g_prefixpath));
  5361. if (!tmp)
  5362. goto malloc_2;
  5363. *(tmp != g_prefixpath ? tmp : tmp + 1) = '\0';
  5364. }
  5365. tmpdir = make_tmp_tree(paths, entries, g_prefixpath);
  5366. }
  5367. malloc_2:
  5368. for (i = entries - 1; i >= 0; --i)
  5369. free(paths[i]);
  5370. malloc_1:
  5371. free(input);
  5372. free(paths);
  5373. return tmpdir;
  5374. }
  5375. static void check_key_collision(void)
  5376. {
  5377. int key;
  5378. ulong i = 0;
  5379. bool bitmap[KEY_MAX] = {FALSE};
  5380. for (; i < sizeof(bindings) / sizeof(struct key); ++i) {
  5381. key = bindings[i].sym;
  5382. if (bitmap[key])
  5383. fprintf(stdout, "key collision! [%s]\n", keyname(key));
  5384. else
  5385. bitmap[key] = TRUE;
  5386. }
  5387. }
  5388. static void usage(void)
  5389. {
  5390. fprintf(stdout,
  5391. "%s: nnn [OPTIONS] [PATH]\n\n"
  5392. "The missing terminal file manager for X.\n\n"
  5393. "positional args:\n"
  5394. " PATH start dir [default: .]\n\n"
  5395. "optional args:\n"
  5396. " -a use access time\n"
  5397. " -A no dir auto-select\n"
  5398. " -b key open bookmark key\n"
  5399. " -c cli-only opener (overrides -e)\n"
  5400. " -d detail mode\n"
  5401. " -e text in $VISUAL ($EDITOR/vi)\n"
  5402. " -E use EDITOR for undetached edits\n"
  5403. " -g regex filters [default: string]\n"
  5404. " -H show hidden files\n"
  5405. " -K detect key collision\n"
  5406. " -n nav-as-you-type mode\n"
  5407. " -o open files only on Enter\n"
  5408. " -p file selection file [stdout if '-']\n"
  5409. " -Q no quit confirmation\n"
  5410. " -r use advcpmv patched cp, mv\n"
  5411. " -R no rollover at edges\n"
  5412. " -s name load session by name\n"
  5413. " -S du mode\n"
  5414. " -t secs timeout to lock\n"
  5415. " -v version sort\n"
  5416. " -V show version\n"
  5417. " -x notis, sel to system clipboard\n"
  5418. " -h show help\n\n"
  5419. "v%s\n%s\n", __func__, VERSION, GENERAL_INFO);
  5420. }
  5421. static bool setup_config(void)
  5422. {
  5423. size_t r, len;
  5424. char *xdgcfg = getenv("XDG_CONFIG_HOME");
  5425. bool xdg = FALSE;
  5426. /* Set up configuration file paths */
  5427. if (xdgcfg && xdgcfg[0]) {
  5428. DPRINTF_S(xdgcfg);
  5429. if (xdgcfg[0] == '~') {
  5430. r = xstrlcpy(g_buf, home, PATH_MAX);
  5431. xstrlcpy(g_buf + r - 1, xdgcfg + 1, PATH_MAX);
  5432. xdgcfg = g_buf;
  5433. DPRINTF_S(xdgcfg);
  5434. }
  5435. if (!xdiraccess(xdgcfg)) {
  5436. xerror();
  5437. return FALSE;
  5438. }
  5439. len = strlen(xdgcfg) + 1 + 13; /* add length of "/nnn/sessions" */
  5440. xdg = TRUE;
  5441. }
  5442. if (!xdg)
  5443. len = strlen(home) + 1 + 21; /* add length of "/.config/nnn/sessions" */
  5444. cfgdir = (char *)malloc(len);
  5445. plugindir = (char *)malloc(len);
  5446. sessiondir = (char *)malloc(len);
  5447. if (!cfgdir || !plugindir || !sessiondir) {
  5448. xerror();
  5449. return FALSE;
  5450. }
  5451. if (xdg) {
  5452. xstrlcpy(cfgdir, xdgcfg, len);
  5453. r = len - 13; /* subtract length of "/nnn/sessions" */
  5454. } else {
  5455. r = xstrlcpy(cfgdir, home, len);
  5456. /* Create ~/.config */
  5457. xstrlcpy(cfgdir + r - 1, "/.config", len - r);
  5458. DPRINTF_S(cfgdir);
  5459. r += 8; /* length of "/.config" */
  5460. }
  5461. /* Create ~/.config/nnn */
  5462. xstrlcpy(cfgdir + r - 1, "/nnn", len - r);
  5463. DPRINTF_S(cfgdir);
  5464. /* Create ~/.config/nnn/plugins */
  5465. xstrlcpy(cfgdir + r + 4 - 1, "/plugins", 9); /* subtract length of "/nnn" (4) */
  5466. DPRINTF_S(cfgdir);
  5467. xstrlcpy(plugindir, cfgdir, len);
  5468. DPRINTF_S(plugindir);
  5469. if (access(plugindir, F_OK) && !xmktree(plugindir, TRUE)) {
  5470. xerror();
  5471. return FALSE;
  5472. }
  5473. /* Create ~/.config/nnn/sessions */
  5474. xstrlcpy(cfgdir + r + 4 - 1, "/sessions", 10); /* subtract length of "/nnn" (4) */
  5475. DPRINTF_S(cfgdir);
  5476. xstrlcpy(sessiondir, cfgdir, len);
  5477. DPRINTF_S(sessiondir);
  5478. if (access(sessiondir, F_OK) && !xmktree(sessiondir, TRUE)) {
  5479. xerror();
  5480. return FALSE;
  5481. }
  5482. /* Reset to config path */
  5483. cfgdir[r + 3] = '\0';
  5484. DPRINTF_S(cfgdir);
  5485. /* Set selection file path */
  5486. if (!cfg.picker) {
  5487. /* Length of "/.config/nnn/.selection" */
  5488. g_selpath = (char *)malloc(len + 3);
  5489. if (!g_selpath) {
  5490. xerror();
  5491. return FALSE;
  5492. }
  5493. r = xstrlcpy(g_selpath, cfgdir, len + 3);
  5494. xstrlcpy(g_selpath + r - 1, "/.selection", 12);
  5495. DPRINTF_S(g_selpath);
  5496. }
  5497. return TRUE;
  5498. }
  5499. static bool set_tmp_path(void)
  5500. {
  5501. char *tmp = "/tmp";
  5502. char *path = xdiraccess(tmp) ? tmp : getenv("TMPDIR");
  5503. if (!path) {
  5504. fprintf(stderr, "set TMPDIR\n");
  5505. return FALSE;
  5506. }
  5507. g_tmpfplen = (uchar)xstrlcpy(g_tmpfpath, path, TMP_LEN_MAX);
  5508. return TRUE;
  5509. }
  5510. static void cleanup(void)
  5511. {
  5512. free(g_selpath);
  5513. free(plugindir);
  5514. free(sessiondir);
  5515. free(cfgdir);
  5516. free(initpath);
  5517. free(bmstr);
  5518. free(pluginstr);
  5519. free(g_prefixpath);
  5520. free(ihashbmp);
  5521. free(bookmark);
  5522. free(plug);
  5523. unlink(g_pipepath);
  5524. #ifdef DBGMODE
  5525. disabledbg();
  5526. #endif
  5527. }
  5528. int main(int argc, char *argv[])
  5529. {
  5530. char *arg = NULL;
  5531. char *session = NULL;
  5532. int opt;
  5533. #ifndef NOMOUSE
  5534. mmask_t mask;
  5535. #endif
  5536. const char* const env_opts = xgetenv(env_cfg[NNN_OPTS], NULL);
  5537. int env_opts_id = env_opts ? (int)strlen(env_opts) : -1;
  5538. while ((opt = (env_opts_id > 0
  5539. ? env_opts[--env_opts_id]
  5540. : getopt(argc, argv, "aAb:cdeEgHKnop:QrRs:St:vVxh"))) != -1) {
  5541. switch (opt) {
  5542. case 'a':
  5543. cfg.mtime = 0;
  5544. break;
  5545. case 'A':
  5546. cfg.autoselect = 0;
  5547. break;
  5548. case 'b':
  5549. arg = optarg;
  5550. break;
  5551. case 'c':
  5552. cfg.cliopener = 1;
  5553. break;
  5554. case 'S':
  5555. cfg.blkorder = 1;
  5556. nftw_fn = sum_bsize;
  5557. blk_shift = ffs(S_BLKSIZE) - 1; // fallthrough
  5558. case 'd':
  5559. cfg.showdetail = 1;
  5560. printptr = &printent_long;
  5561. break;
  5562. case 'e':
  5563. cfg.useeditor = 1;
  5564. break;
  5565. case 'E':
  5566. cfg.waitedit = 1;
  5567. break;
  5568. case 'g':
  5569. cfg.regex = 1;
  5570. filterfn = &visible_re;
  5571. break;
  5572. case 'H':
  5573. cfg.showhidden = 1;
  5574. break;
  5575. case 'K':
  5576. check_key_collision();
  5577. return _SUCCESS;
  5578. case 'n':
  5579. cfg.filtermode = 1;
  5580. break;
  5581. case 'o':
  5582. cfg.nonavopen = 1;
  5583. break;
  5584. case 'p':
  5585. if (env_opts_id >= 0)
  5586. break;
  5587. cfg.picker = 1;
  5588. if (optarg[0] == '-' && optarg[1] == '\0')
  5589. cfg.pickraw = 1;
  5590. else {
  5591. int fd = open(optarg, O_WRONLY | O_CREAT, 0600);
  5592. if (fd == -1) {
  5593. xerror();
  5594. return _FAILURE;
  5595. }
  5596. close(fd);
  5597. g_selpath = realpath(optarg, NULL);
  5598. unlink(g_selpath);
  5599. }
  5600. break;
  5601. case 'Q':
  5602. cfg.forcequit = 1;
  5603. break;
  5604. case 'r':
  5605. #ifdef __linux__
  5606. cp[2] = cp[5] = mv[2] = mv[5] = 'g'; /* cp -iRp -> cpg -giRp */
  5607. cp[4] = mv[4] = '-';
  5608. #endif
  5609. break;
  5610. case 'R':
  5611. cfg.rollover = 0;
  5612. break;
  5613. case 's':
  5614. if (env_opts_id < 0)
  5615. session = optarg;
  5616. break;
  5617. case 't':
  5618. if (env_opts_id < 0)
  5619. idletimeout = atoi(optarg);
  5620. break;
  5621. case 'v':
  5622. namecmpfn = &xstrverscasecmp;
  5623. break;
  5624. case 'V':
  5625. fprintf(stdout, "%s\n", VERSION);
  5626. return _SUCCESS;
  5627. case 'x':
  5628. cfg.x11 = 1;
  5629. break;
  5630. case 'h':
  5631. usage();
  5632. return _SUCCESS;
  5633. default:
  5634. usage();
  5635. return _FAILURE;
  5636. }
  5637. }
  5638. #ifdef DBGMODE
  5639. enabledbg();
  5640. DPRINTF_S(VERSION);
  5641. #endif
  5642. /* Prefix for temporary files */
  5643. if (!set_tmp_path())
  5644. return _FAILURE;
  5645. atexit(cleanup);
  5646. if (!cfg.picker) {
  5647. /* Confirm we are in a terminal */
  5648. if (!isatty(STDOUT_FILENO))
  5649. exit(1);
  5650. /* Now we are in path list mode */
  5651. if (!isatty(STDIN_FILENO)) {
  5652. /* This is the same as g_listpath */
  5653. initpath = load_input();
  5654. if (!initpath)
  5655. exit(1);
  5656. /* We return to tty */
  5657. dup2(STDOUT_FILENO, STDIN_FILENO);
  5658. }
  5659. }
  5660. home = getenv("HOME");
  5661. if (!home) {
  5662. fprintf(stderr, "set HOME\n");
  5663. return _FAILURE;
  5664. }
  5665. DPRINTF_S(home);
  5666. if (!setup_config())
  5667. return _FAILURE;
  5668. /* Get custom opener, if set */
  5669. opener = xgetenv(env_cfg[NNN_OPENER], utils[UTIL_OPENER]);
  5670. DPRINTF_S(opener);
  5671. /* Parse bookmarks string */
  5672. if (!parsekvpair(&bookmark, &bmstr, NNN_BMS, &maxbm)) {
  5673. fprintf(stderr, "%s\n", env_cfg[NNN_BMS]);
  5674. return _FAILURE;
  5675. }
  5676. /* Parse plugins string */
  5677. if (!parsekvpair(&plug, &pluginstr, NNN_PLUG, &maxplug)) {
  5678. fprintf(stderr, "%s\n", env_cfg[NNN_PLUG]);
  5679. return _FAILURE;
  5680. }
  5681. if (!initpath) {
  5682. if (arg) { /* Open a bookmark directly */
  5683. if (!arg[1]) /* Bookmarks keys are single char */
  5684. initpath = get_kv_val(bookmark, NULL, *arg, maxbm, TRUE);
  5685. if (!initpath) {
  5686. fprintf(stderr, "%s\n", messages[MSG_INVALID_KEY]);
  5687. return _FAILURE;
  5688. }
  5689. } else if (argc == optind) {
  5690. /* Start in the current directory */
  5691. initpath = getcwd(NULL, PATH_MAX);
  5692. if (!initpath)
  5693. initpath = "/";
  5694. } else {
  5695. arg = argv[optind];
  5696. DPRINTF_S(arg);
  5697. if (strlen(arg) > 7 && !strncmp(arg, "file://", 7))
  5698. arg = arg + 7;
  5699. initpath = realpath(arg, NULL);
  5700. DPRINTF_S(initpath);
  5701. if (!initpath) {
  5702. xerror();
  5703. return _FAILURE;
  5704. }
  5705. /*
  5706. * If nnn is set as the file manager, applications may try to open
  5707. * files by invoking nnn. In that case pass the file path to the
  5708. * desktop opener and exit.
  5709. */
  5710. struct stat sb;
  5711. if (stat(initpath, &sb) == -1) {
  5712. xerror();
  5713. return _FAILURE;
  5714. }
  5715. if (S_ISREG(sb.st_mode)) {
  5716. spawn(opener, arg, NULL, NULL, cfg.cliopener ? F_CLI : F_NOTRACE | F_NOWAIT);
  5717. return _SUCCESS;
  5718. }
  5719. }
  5720. }
  5721. /* Set archive handling (enveditor used as tmp var) */
  5722. enveditor = getenv(env_cfg[NNN_ARCHIVE]);
  5723. #ifdef PCRE
  5724. if (setfilter(&archive_pcre, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5725. #else
  5726. if (setfilter(&archive_re, (enveditor ? enveditor : patterns[P_ARCHIVE]))) {
  5727. #endif
  5728. fprintf(stderr, "%s\n", messages[MSG_INVALID_REG]);
  5729. return _FAILURE;
  5730. }
  5731. /* An all-CLI opener overrides option -e) */
  5732. if (cfg.cliopener)
  5733. cfg.useeditor = 0;
  5734. /* Get VISUAL/EDITOR */
  5735. enveditor = xgetenv(envs[ENV_EDITOR], utils[UTIL_VI]);
  5736. editor = xgetenv(envs[ENV_VISUAL], enveditor);
  5737. DPRINTF_S(getenv(envs[ENV_VISUAL]));
  5738. DPRINTF_S(getenv(envs[ENV_EDITOR]));
  5739. DPRINTF_S(editor);
  5740. /* Get PAGER */
  5741. pager = xgetenv(envs[ENV_PAGER], utils[UTIL_LESS]);
  5742. DPRINTF_S(pager);
  5743. /* Get SHELL */
  5744. shell = xgetenv(envs[ENV_SHELL], utils[UTIL_SH]);
  5745. DPRINTF_S(shell);
  5746. DPRINTF_S(getenv("PWD"));
  5747. #ifdef LINUX_INOTIFY
  5748. /* Initialize inotify */
  5749. inotify_fd = inotify_init1(IN_NONBLOCK);
  5750. if (inotify_fd < 0) {
  5751. xerror();
  5752. return _FAILURE;
  5753. }
  5754. #elif defined(BSD_KQUEUE)
  5755. kq = kqueue();
  5756. if (kq < 0) {
  5757. xerror();
  5758. return _FAILURE;
  5759. }
  5760. #elif defined(HAIKU_NM)
  5761. haiku_hnd = haiku_init_nm();
  5762. if (!haiku_hnd) {
  5763. xerror();
  5764. return _FAILURE;
  5765. }
  5766. #endif
  5767. /* Configure trash preference */
  5768. if (xgetenv_set(env_cfg[NNN_TRASH]))
  5769. g_states |= STATE_TRASH;
  5770. /* Ignore/handle certain signals */
  5771. struct sigaction act = {.sa_handler = sigint_handler};
  5772. if (sigaction(SIGINT, &act, NULL) < 0) {
  5773. xerror();
  5774. return _FAILURE;
  5775. }
  5776. signal(SIGQUIT, SIG_IGN);
  5777. #ifndef NOLOCALE
  5778. /* Set locale */
  5779. setlocale(LC_ALL, "");
  5780. #ifdef PCRE
  5781. tables = pcre_maketables();
  5782. #endif
  5783. #endif
  5784. #ifndef NORL
  5785. #if RL_READLINE_VERSION >= 0x0603
  5786. /* readline would overwrite the WINCH signal hook */
  5787. rl_change_environment = 0;
  5788. #endif
  5789. /* Bind TAB to cycling */
  5790. rl_variable_bind("completion-ignore-case", "on");
  5791. #ifdef __linux__
  5792. rl_bind_key('\t', rl_menu_complete);
  5793. #else
  5794. rl_bind_key('\t', rl_complete);
  5795. #endif
  5796. mkpath(cfgdir, ".history", g_buf);
  5797. read_history(g_buf);
  5798. #endif
  5799. #ifndef NOMOUSE
  5800. if (!initcurses(&mask))
  5801. #else
  5802. if (!initcurses(NULL))
  5803. #endif
  5804. return _FAILURE;
  5805. opt = browse(initpath, session);
  5806. #ifndef NOMOUSE
  5807. mousemask(mask, NULL);
  5808. #endif
  5809. if (g_listpath)
  5810. spawn("rm -rf", initpath, NULL, NULL, F_SILENT);
  5811. exitcurses();
  5812. #ifndef NORL
  5813. mkpath(cfgdir, ".history", g_buf);
  5814. write_history(g_buf);
  5815. #endif
  5816. if (cfg.pickraw) {
  5817. if (selbufpos && (seltofile(1, NULL) != (size_t)(selbufpos)))
  5818. xerror();
  5819. } else if (cfg.picker) {
  5820. if (selbufpos)
  5821. writesel(pselbuf, selbufpos - 1);
  5822. } else if (g_selpath)
  5823. unlink(g_selpath);
  5824. /* Free the regex */
  5825. #ifdef PCRE
  5826. pcre_free(archive_pcre);
  5827. #else
  5828. regfree(&archive_re);
  5829. #endif
  5830. /* Free the selection buffer */
  5831. free(pselbuf);
  5832. #ifdef LINUX_INOTIFY
  5833. /* Shutdown inotify */
  5834. if (inotify_wd >= 0)
  5835. inotify_rm_watch(inotify_fd, inotify_wd);
  5836. close(inotify_fd);
  5837. #elif defined(BSD_KQUEUE)
  5838. if (event_fd >= 0)
  5839. close(event_fd);
  5840. close(kq);
  5841. #elif defined(HAIKU_NM)
  5842. haiku_close_nm(haiku_hnd);
  5843. #endif
  5844. return opt;
  5845. }