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

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