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

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