My build of nnn with minor changes
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

3540 wiersze
78 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-2018, 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. #ifdef __i386__
  32. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
  33. #endif
  34. #include <sys/inotify.h>
  35. #define LINUX_INOTIFY
  36. #if !defined(__GLIBC__)
  37. #include <sys/types.h>
  38. #endif
  39. #endif
  40. #include <sys/resource.h>
  41. #include <sys/stat.h>
  42. #include <sys/statvfs.h>
  43. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  44. #include <sys/types.h>
  45. #include <sys/event.h>
  46. #include <sys/time.h>
  47. #define BSD_KQUEUE
  48. #else
  49. #include <sys/sysmacros.h>
  50. #endif
  51. #include <sys/wait.h>
  52. #include <ctype.h>
  53. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  54. #ifndef NCURSES_WIDECHAR
  55. #define NCURSES_WIDECHAR 1
  56. #endif
  57. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  58. #ifndef _XOPEN_SOURCE_EXTENDED
  59. #define _XOPEN_SOURCE_EXTENDED
  60. #endif
  61. #endif
  62. #ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  63. #define __USE_XOPEN
  64. #endif
  65. #include <curses.h>
  66. #include <dirent.h>
  67. #include <errno.h>
  68. #include <fcntl.h>
  69. #include <grp.h>
  70. #include <libgen.h>
  71. #include <limits.h>
  72. #ifdef __gnu_hurd__
  73. #define PATH_MAX 4096
  74. #endif
  75. #include <locale.h>
  76. #include <pwd.h>
  77. #include <regex.h>
  78. #include <signal.h>
  79. #include <stdarg.h>
  80. #include <stdio.h>
  81. #include <stdlib.h>
  82. #include <string.h>
  83. #include <strings.h>
  84. #include <time.h>
  85. #include <unistd.h>
  86. #ifndef __USE_XOPEN_EXTENDED
  87. #define __USE_XOPEN_EXTENDED 1
  88. #endif
  89. #include <ftw.h>
  90. #include <wchar.h>
  91. #include "nnn.h"
  92. #ifdef DEBUGMODE
  93. static int DEBUG_FD;
  94. static int
  95. xprintf(int fd, const char *fmt, ...)
  96. {
  97. char buf[BUFSIZ];
  98. int r;
  99. va_list ap;
  100. va_start(ap, fmt);
  101. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  102. if (r > 0)
  103. r = write(fd, buf, r);
  104. va_end(ap);
  105. return r;
  106. }
  107. static int
  108. enabledbg()
  109. {
  110. FILE *fp = fopen("/tmp/nnn_debug", "w");
  111. if (!fp) {
  112. fprintf(stderr, "debug: open failed! (1)\n");
  113. fp = fopen("./nnn_debug", "w");
  114. if (!fp) {
  115. fprintf(stderr, "debug: open failed! (2)\n");
  116. return -1;
  117. }
  118. }
  119. DEBUG_FD = fileno(fp);
  120. if (DEBUG_FD == -1) {
  121. fprintf(stderr, "debug: open fd failed!\n");
  122. return -1;
  123. }
  124. return 0;
  125. }
  126. static void
  127. disabledbg()
  128. {
  129. close(DEBUG_FD);
  130. }
  131. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  132. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  133. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  134. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  135. #else
  136. #define DPRINTF_D(x)
  137. #define DPRINTF_U(x)
  138. #define DPRINTF_S(x)
  139. #define DPRINTF_P(x)
  140. #endif /* DEBUGMODE */
  141. /* Macro definitions */
  142. #define VERSION "2.0"
  143. #define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
  144. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  145. #undef MIN
  146. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  147. #define ISODD(x) ((x) & 1)
  148. #define TOUPPER(ch) \
  149. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  150. #define MAX_CMD_LEN 5120
  151. #define CURSR " > "
  152. #define EMPTY " "
  153. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  154. #define FILTER '/'
  155. #define REGEX_MAX 128
  156. #define BM_MAX 10
  157. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  158. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
  159. #define DESCRIPTOR_LEN 32
  160. #define _ALIGNMENT 0x10
  161. #define _ALIGNMENT_MASK 0xF
  162. #define SYMLINK_TO_DIR 0x1
  163. #define MAX_HOME_LEN 64
  164. /* Macros to define process spawn behaviour as flags */
  165. #define F_NONE 0x00 /* no flag set */
  166. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  167. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  168. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  169. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  170. #define F_NORMAL 0x80 /* spawn child process in non-curses regular CLI mode */
  171. /* CRC8 macros */
  172. #define WIDTH (sizeof(unsigned char) << 3)
  173. #define TOPBIT (1 << (WIDTH - 1))
  174. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  175. #define CRC8_TABLE_LEN 256
  176. /* Volume info */
  177. #define FREE 0
  178. #define CAPACITY 1
  179. /* Function macros */
  180. #define exitcurses() endwin()
  181. #define clearprompt() printmsg("")
  182. #define printwarn() printmsg(strerror(errno))
  183. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  184. #define copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
  185. #define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
  186. #define settimeout() timeout(1000)
  187. #define cleartimeout() timeout(-1)
  188. #define errexit() printerr(__LINE__)
  189. #ifdef LINUX_INOTIFY
  190. #define EVENT_SIZE (sizeof(struct inotify_event))
  191. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  192. #elif defined(BSD_KQUEUE)
  193. #define NUM_EVENT_SLOTS 1
  194. #define NUM_EVENT_FDS 1
  195. #endif
  196. /* TYPE DEFINITIONS */
  197. typedef unsigned long ulong;
  198. typedef unsigned int uint;
  199. typedef unsigned char uchar;
  200. typedef unsigned short ushort;
  201. /* STRUCTURES */
  202. /* Directory entry */
  203. typedef struct entry {
  204. char *name;
  205. time_t t;
  206. off_t size;
  207. blkcnt_t blocks; /* number of 512B blocks allocated */
  208. mode_t mode;
  209. ushort nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  210. uchar flags; /* Flags specific to the file */
  211. } __attribute__ ((packed, aligned(_ALIGNMENT))) *pEntry;
  212. /* Bookmark */
  213. typedef struct {
  214. char *key;
  215. char *loc;
  216. } bm;
  217. /* Settings */
  218. typedef struct {
  219. uint filtermode : 1; /* Set to enter filter mode */
  220. uint mtimeorder : 1; /* Set to sort by time modified */
  221. uint sizeorder : 1; /* Set to sort by file size */
  222. uint apparentsz : 1; /* Set to sort by apparent size (disk usage) */
  223. uint blkorder : 1; /* Set to sort by blocks used (disk usage) */
  224. uint showhidden : 1; /* Set to show hidden files */
  225. uint copymode : 1; /* Set when copying files */
  226. uint autoselect : 1; /* Auto-select dir in nav-as-you-type mode */
  227. uint showdetail : 1; /* Clear to show fewer file info */
  228. uint showcolor : 1; /* Set to show dirs in blue */
  229. uint dircolor : 1; /* Current status of dir color */
  230. uint metaviewer : 1; /* Index of metadata viewer in utils[] */
  231. uint quote : 1; /* Copy paths within quotes */
  232. uint noxdisplay : 1; /* X11 is not available */
  233. uint color : 3; /* Color code for directories */
  234. uint reserved : 15;
  235. } settings;
  236. /* GLOBALS */
  237. /* Configuration */
  238. static settings cfg = {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 4, 0};
  239. static struct entry *dents;
  240. static char *pnamebuf, *pcopybuf;
  241. static int ndents, cur, total_dents = ENTRY_INCR;
  242. static uint idle;
  243. static uint idletimeout, copybufpos, copybuflen;
  244. static char *player;
  245. static char *copier;
  246. static char *editor;
  247. static char *dmanager; /* desktop file manager */
  248. static blkcnt_t ent_blocks;
  249. static blkcnt_t dir_blocks;
  250. static ulong num_files;
  251. static uint open_max;
  252. static bm bookmark[BM_MAX];
  253. static size_t g_tmpfplen; /* path to tmp files for copy without X, keybind help and file stats */
  254. static uchar g_crc;
  255. static uchar BLK_SHIFT = 9;
  256. /* CRC data */
  257. static uchar crc8table[CRC8_TABLE_LEN] __attribute__ ((aligned));
  258. /* For use in functions which are isolated and don't return the buffer */
  259. static char g_buf[MAX_CMD_LEN] __attribute__ ((aligned));
  260. /* Buffer for file path copy file */
  261. static char g_cppath[MAX_HOME_LEN] __attribute__ ((aligned));
  262. /* Buffer to store tmp file path */
  263. static char g_tmpfpath[MAX_HOME_LEN] __attribute__ ((aligned));
  264. #ifdef LINUX_INOTIFY
  265. static int inotify_fd, inotify_wd = -1;
  266. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  267. #elif defined(BSD_KQUEUE)
  268. static int kq, event_fd = -1;
  269. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  270. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  271. static struct timespec gtimeout;
  272. #endif
  273. /* Macros for utilities */
  274. #define MEDIAINFO 0
  275. #define EXIFTOOL 1
  276. #define OPENER 2
  277. #define NLAY 3
  278. #define ATOOL 4
  279. #define APACK 5
  280. #define VIDIR 6
  281. #define UNKNOWN 7
  282. /* Utilities to open files, run actions */
  283. static char * const utils[] = {
  284. "mediainfo",
  285. "exiftool",
  286. #ifdef __APPLE__
  287. "/usr/bin/open",
  288. #elif defined __CYGWIN__
  289. "cygstart",
  290. #else
  291. "xdg-open",
  292. #endif
  293. "nlay",
  294. "atool",
  295. "apack",
  296. "vidir",
  297. "UNKNOWN"
  298. };
  299. /* Common strings */
  300. #define STR_NFTWFAIL_ID 0
  301. #define STR_NOHOME_ID 1
  302. #define STR_INPUT_ID 2
  303. #define STR_INVBM_ID 3
  304. #define STR_COPY_ID 4
  305. #define STR_DATE_ID 5
  306. static const char messages[][16] = {
  307. "nftw failed",
  308. "HOME not set",
  309. "no traversal",
  310. "invalid key",
  311. "copy not set",
  312. "%F %T %z",
  313. };
  314. /* Forward declarations */
  315. static void redraw(char *path);
  316. static char *get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager);
  317. int (*nftw_fn) (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf);
  318. /* Functions */
  319. /*
  320. * CRC8 source:
  321. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  322. */
  323. static void crc8init()
  324. {
  325. uchar remainder, bit;
  326. uint dividend;
  327. /* Compute the remainder of each possible dividend */
  328. for (dividend = 0; dividend < CRC8_TABLE_LEN; ++dividend) {
  329. /* Start with the dividend followed by zeros */
  330. remainder = dividend << (WIDTH - 8);
  331. /* Perform modulo-2 division, a bit at a time */
  332. for (bit = 8; bit > 0; --bit) {
  333. /* Try to divide the current data bit */
  334. if (remainder & TOPBIT)
  335. remainder = (remainder << 1) ^ POLYNOMIAL;
  336. else
  337. remainder = (remainder << 1);
  338. }
  339. /* Store the result into the table */
  340. crc8table[dividend] = remainder;
  341. }
  342. }
  343. static uchar crc8fast(uchar const message[], size_t n)
  344. {
  345. static uchar data, remainder;
  346. static size_t byte;
  347. /* Divide the message by the polynomial, a byte at a time */
  348. for (remainder = byte = 0; byte < n; ++byte) {
  349. data = message[byte] ^ (remainder >> (WIDTH - 8));
  350. remainder = crc8table[data] ^ (remainder << 8);
  351. }
  352. /* The final remainder is the CRC */
  353. return remainder;
  354. }
  355. /* Messages show up at the bottom */
  356. static void printmsg(const char *msg)
  357. {
  358. mvprintw(LINES - 1, 0, "%s\n", msg);
  359. }
  360. /* Kill curses and display error before exiting */
  361. static void printerr(int linenum)
  362. {
  363. exitcurses();
  364. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  365. if (cfg.noxdisplay && g_cppath[0])
  366. unlink(g_cppath);
  367. exit(1);
  368. }
  369. /* Print prompt on the last line */
  370. static void printprompt(char *str)
  371. {
  372. clearprompt();
  373. printw(str);
  374. }
  375. /* Increase the limit on open file descriptors, if possible */
  376. static rlim_t max_openfds()
  377. {
  378. struct rlimit rl;
  379. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  380. if (limit != 0)
  381. return 32;
  382. limit = rl.rlim_cur;
  383. rl.rlim_cur = rl.rlim_max;
  384. /* Return ~75% of max possible */
  385. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  386. limit = rl.rlim_max - (rl.rlim_max >> 2);
  387. /*
  388. * 20K is arbitrary. If the limit is set to max possible
  389. * value, the memory usage increases to more than double.
  390. */
  391. return limit > 20480 ? 20480 : limit;
  392. }
  393. return limit;
  394. }
  395. /*
  396. * Wrapper to realloc()
  397. * Frees current memory if realloc() fails and returns NULL.
  398. *
  399. * As per the docs, the *alloc() family is supposed to be memory aligned:
  400. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  401. * OS X: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  402. */
  403. static void *xrealloc(void *pcur, size_t len)
  404. {
  405. static void *pmem;
  406. pmem = realloc(pcur, len);
  407. if (!pmem)
  408. free(pcur);
  409. return pmem;
  410. }
  411. /*
  412. * Just a safe strncpy(3)
  413. * Always null ('\0') terminates if both src and dest are valid pointers.
  414. * Returns the number of bytes copied including terminating null byte.
  415. */
  416. static size_t xstrlcpy(char *dest, const char *src, size_t n)
  417. {
  418. static ulong *s, *d;
  419. static size_t len, blocks;
  420. static const uint lsize = sizeof(ulong);
  421. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  422. if (!src || !dest || !n)
  423. return 0;
  424. len = strlen(src) + 1;
  425. if (n > len)
  426. n = len;
  427. else if (len > n)
  428. /* Save total number of bytes to copy in len */
  429. len = n;
  430. /*
  431. * To enable -O3 ensure src and dest are 16-byte aligned
  432. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  433. */
  434. if ((n >= lsize) && (((ulong)src & _ALIGNMENT_MASK) == 0 && ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  435. s = (ulong *)src;
  436. d = (ulong *)dest;
  437. blocks = n >> _WSHIFT;
  438. n &= lsize - 1;
  439. while (blocks) {
  440. *d = *s;
  441. ++d, ++s;
  442. --blocks;
  443. }
  444. if (!n) {
  445. dest = (char *)d;
  446. *--dest = '\0';
  447. return len;
  448. }
  449. src = (char *)s;
  450. dest = (char *)d;
  451. }
  452. while (--n && (*dest = *src))
  453. ++dest, ++src;
  454. if (!n)
  455. *dest = '\0';
  456. return len;
  457. }
  458. /*
  459. * The poor man's implementation of memrchr(3).
  460. * We are only looking for '/' in this program.
  461. * And we are NOT expecting a '/' at the end.
  462. * Ideally 0 < n <= strlen(s).
  463. */
  464. static void *xmemrchr(uchar *s, uchar ch, size_t n)
  465. {
  466. static uchar *ptr;
  467. if (!s || !n)
  468. return NULL;
  469. ptr = s + n;
  470. do {
  471. --ptr;
  472. if (*ptr == ch)
  473. return ptr;
  474. } while (s != ptr);
  475. return NULL;
  476. }
  477. /*
  478. * The following dirname(3) implementation does not
  479. * modify the input. We use a copy of the original.
  480. *
  481. * Modified from the glibc (GNU LGPL) version.
  482. */
  483. static char *xdirname(const char *path)
  484. {
  485. static char * const buf = g_buf, *last_slash, *runp;
  486. xstrlcpy(buf, path, PATH_MAX);
  487. /* Find last '/'. */
  488. last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
  489. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  490. /* Determine whether all remaining characters are slashes. */
  491. for (runp = last_slash; runp != buf; --runp)
  492. if (runp[-1] != '/')
  493. break;
  494. /* The '/' is the last character, we have to look further. */
  495. if (runp != buf)
  496. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  497. }
  498. if (last_slash != NULL) {
  499. /* Determine whether all remaining characters are slashes. */
  500. for (runp = last_slash; runp != buf; --runp)
  501. if (runp[-1] != '/')
  502. break;
  503. /* Terminate the buffer. */
  504. if (runp == buf) {
  505. /* The last slash is the first character in the string.
  506. * We have to return "/". As a special case we have to
  507. * return "//" if there are exactly two slashes at the
  508. * beginning of the string. See XBD 4.10 Path Name
  509. * Resolution for more information.
  510. */
  511. if (last_slash == buf + 1)
  512. ++last_slash;
  513. else
  514. last_slash = buf + 1;
  515. } else
  516. last_slash = runp;
  517. last_slash[0] = '\0';
  518. } else {
  519. /* This assignment is ill-designed but the XPG specs require to
  520. * return a string containing "." in any case no directory part
  521. * is found and so a static and constant string is required.
  522. */
  523. buf[0] = '.';
  524. buf[1] = '\0';
  525. }
  526. return buf;
  527. }
  528. static char *xbasename(char *path)
  529. {
  530. static char *base;
  531. base = xmemrchr((uchar *)path, '/', strlen(path));
  532. return base ? base + 1 : path;
  533. }
  534. /* Writes buflen char(s) from buf to a file */
  535. static void writecp(const char *buf, const size_t buflen)
  536. {
  537. if (!g_cppath[0])
  538. return;
  539. FILE *fp = fopen(g_cppath, "w");
  540. if (fp) {
  541. fwrite(buf, 1, buflen, fp);
  542. fclose(fp);
  543. } else
  544. printwarn();
  545. }
  546. static bool appendfpath(const char *path, const size_t len)
  547. {
  548. if ((copybufpos >= copybuflen) || ((len + 3) > (copybuflen - copybufpos))) {
  549. copybuflen += PATH_MAX;
  550. pcopybuf = xrealloc(pcopybuf, copybuflen);
  551. if (!pcopybuf) {
  552. printmsg("no memory!");
  553. return FALSE;
  554. }
  555. }
  556. if (copybufpos) {
  557. pcopybuf[copybufpos - 1] = '\n';
  558. if (cfg.quote) {
  559. pcopybuf[copybufpos] = '\'';
  560. ++copybufpos;
  561. }
  562. } else if (cfg.quote) {
  563. pcopybuf[copybufpos] = '\'';
  564. ++copybufpos;
  565. }
  566. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  567. if (cfg.quote) {
  568. pcopybuf[copybufpos - 1] = '\'';
  569. pcopybuf[copybufpos] = '\0';
  570. ++copybufpos;
  571. }
  572. return TRUE;
  573. }
  574. static bool showcplist()
  575. {
  576. ssize_t len;
  577. if (!copybufpos)
  578. return FALSE;
  579. if (g_tmpfpath[0])
  580. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  581. else {
  582. printmsg(messages[STR_NOHOME_ID]);
  583. return -1;
  584. }
  585. int fd = mkstemp(g_tmpfpath);
  586. if (fd == -1)
  587. return FALSE;
  588. len = write(fd, pcopybuf, copybufpos - 1);
  589. close(fd);
  590. exitcurses();
  591. if (len == copybufpos - 1)
  592. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  593. unlink(g_tmpfpath);
  594. refresh();
  595. return TRUE;
  596. }
  597. /*
  598. * Return number of dots if all chars in a string are dots, else 0
  599. */
  600. static int all_dots(const char *path)
  601. {
  602. int count = 0;
  603. if (!path)
  604. return FALSE;
  605. while (*path == '.')
  606. ++count, ++path;
  607. if (*path)
  608. return 0;
  609. return count;
  610. }
  611. /* Initialize curses mode */
  612. static void initcurses(void)
  613. {
  614. if (initscr() == NULL) {
  615. char *term = getenv("TERM");
  616. if (term != NULL)
  617. fprintf(stderr, "error opening TERM: %s\n", term);
  618. else
  619. fprintf(stderr, "initscr() failed\n");
  620. exit(1);
  621. }
  622. cbreak();
  623. noecho();
  624. nonl();
  625. intrflush(stdscr, FALSE);
  626. keypad(stdscr, TRUE);
  627. curs_set(FALSE); /* Hide cursor */
  628. start_color();
  629. use_default_colors();
  630. if (cfg.showcolor)
  631. init_pair(1, cfg.color, -1);
  632. settimeout(); /* One second */
  633. }
  634. /*
  635. * Spawns a child process. Behaviour can be controlled using flag.
  636. * Limited to 2 arguments to a program, flag works on bit set.
  637. */
  638. static void spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  639. {
  640. static char *shlvl;
  641. static pid_t pid;
  642. static int status;
  643. if (flag & F_NORMAL)
  644. exitcurses();
  645. pid = fork();
  646. if (pid == 0) {
  647. if (dir != NULL)
  648. status = chdir(dir);
  649. shlvl = getenv("SHLVL");
  650. /* Show a marker (to indicate nnn spawned shell) */
  651. if (flag & F_MARKER && shlvl != NULL) {
  652. fprintf(stdout, "\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  653. fprintf(stdout, "Next shell level: %d\n", atoi(shlvl) + 1);
  654. }
  655. /* Suppress stdout and stderr */
  656. if (flag & F_NOTRACE) {
  657. int fd = open("/dev/null", O_WRONLY, 0200);
  658. dup2(fd, 1);
  659. dup2(fd, 2);
  660. close(fd);
  661. }
  662. if (flag & F_NOWAIT) {
  663. signal(SIGHUP, SIG_IGN);
  664. signal(SIGPIPE, SIG_IGN);
  665. setsid();
  666. }
  667. if (flag & F_SIGINT)
  668. signal(SIGINT, SIG_DFL);
  669. execlp(file, file, arg1, arg2, NULL);
  670. _exit(1);
  671. } else {
  672. if (!(flag & F_NOWAIT))
  673. /* Ignore interruptions */
  674. while (waitpid(pid, &status, 0) == -1)
  675. DPRINTF_D(status);
  676. DPRINTF_D(pid);
  677. if (flag & F_NORMAL)
  678. refresh();
  679. }
  680. }
  681. /* Get program name from env var, else return fallback program */
  682. static char *xgetenv(const char *name, char *fallback)
  683. {
  684. static char *value;
  685. if (name == NULL)
  686. return fallback;
  687. value = getenv(name);
  688. return value && value[0] ? value : fallback;
  689. }
  690. /* Check if a dir exists, IS a dir and is readable */
  691. static bool xdiraccess(const char *path)
  692. {
  693. static DIR *dirp;
  694. dirp = opendir(path);
  695. if (dirp == NULL) {
  696. printwarn();
  697. return FALSE;
  698. }
  699. closedir(dirp);
  700. return TRUE;
  701. }
  702. /*
  703. * We assume none of the strings are NULL.
  704. *
  705. * Let's have the logic to sort numeric names in numeric order.
  706. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  707. *
  708. * If the absolute numeric values are same, we fallback to alphasort.
  709. */
  710. static int xstricmp(const char * const s1, const char * const s2)
  711. {
  712. static const char *c1, *c2;
  713. c1 = s1;
  714. while (isspace(*c1))
  715. ++c1;
  716. c2 = s2;
  717. while (isspace(*c2))
  718. ++c2;
  719. if (*c1 == '-' || *c1 == '+')
  720. ++c1;
  721. if (*c2 == '-' || *c2 == '+')
  722. ++c2;
  723. if (isdigit(*c1) && isdigit(*c2)) {
  724. while (*c1 >= '0' && *c1 <= '9')
  725. ++c1;
  726. while (isspace(*c1))
  727. ++c1;
  728. while (*c2 >= '0' && *c2 <= '9')
  729. ++c2;
  730. while (isspace(*c2))
  731. ++c2;
  732. }
  733. if (!*c1 && !*c2) {
  734. static long long num1, num2;
  735. num1 = strtoll(s1, NULL, 10);
  736. num2 = strtoll(s2, NULL, 10);
  737. if (num1 != num2) {
  738. if (num1 > num2)
  739. return 1;
  740. else
  741. return -1;
  742. }
  743. }
  744. return strcoll(s1, s2);
  745. }
  746. /* Return the integer value of a char representing HEX */
  747. static char xchartohex(char c)
  748. {
  749. if (c >= '0' && c <= '9')
  750. return c - '0';
  751. c = TOUPPER(c);
  752. if (c >= 'A' && c <= 'F')
  753. return c - 'A' + 10;
  754. return c;
  755. }
  756. static char *getmime(const char *file)
  757. {
  758. static regex_t regex;
  759. static uint i;
  760. static const uint len = LEN(assocs);
  761. for (i = 0; i < len; ++i) {
  762. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  763. continue;
  764. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  765. regfree(&regex);
  766. return assocs[i].mime;
  767. }
  768. }
  769. regfree(&regex);
  770. return NULL;
  771. }
  772. static int setfilter(regex_t *regex, char *filter)
  773. {
  774. static size_t len;
  775. static int r;
  776. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  777. if (r != 0 && filter && filter[0] != '\0') {
  778. len = COLS;
  779. if (len > NAME_MAX)
  780. len = NAME_MAX;
  781. regerror(r, regex, g_buf, len);
  782. printmsg(g_buf);
  783. }
  784. return r;
  785. }
  786. static void initfilter(int dot, char **ifilter)
  787. {
  788. *ifilter = dot ? "." : "^[^.]";
  789. }
  790. static int visible(regex_t *regex, char *file)
  791. {
  792. return regexec(regex, file, 0, NULL, 0) == 0;
  793. }
  794. static int entrycmp(const void *va, const void *vb)
  795. {
  796. static pEntry pa, pb;
  797. pa = (pEntry)va;
  798. pb = (pEntry)vb;
  799. /* Sort directories first */
  800. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  801. return 1;
  802. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  803. return -1;
  804. /* Do the actual sorting */
  805. if (cfg.mtimeorder)
  806. return pb->t - pa->t;
  807. if (cfg.sizeorder) {
  808. if (pb->size > pa->size)
  809. return 1;
  810. else if (pb->size < pa->size)
  811. return -1;
  812. }
  813. if (cfg.blkorder) {
  814. if (pb->blocks > pa->blocks)
  815. return 1;
  816. else if (pb->blocks < pa->blocks)
  817. return -1;
  818. }
  819. return xstricmp(pa->name, pb->name);
  820. }
  821. /*
  822. * Returns SEL_* if key is bound and 0 otherwise.
  823. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  824. * The next keyboard input can be simulated by presel.
  825. */
  826. static int nextsel(char **run, char **env, int *presel)
  827. {
  828. static int c;
  829. static uint i;
  830. static const uint len = LEN(bindings);
  831. #ifdef LINUX_INOTIFY
  832. static char inotify_buf[EVENT_BUF_LEN];
  833. #elif defined(BSD_KQUEUE)
  834. static struct kevent event_data[NUM_EVENT_SLOTS];
  835. #endif
  836. c = *presel;
  837. if (c == 0)
  838. c = getch();
  839. else {
  840. *presel = 0;
  841. /* Unwatch dir if we are still in a filtered view */
  842. #ifdef LINUX_INOTIFY
  843. if (inotify_wd >= 0) {
  844. inotify_rm_watch(inotify_fd, inotify_wd);
  845. inotify_wd = -1;
  846. }
  847. #elif defined(BSD_KQUEUE)
  848. if (event_fd >= 0) {
  849. close(event_fd);
  850. event_fd = -1;
  851. }
  852. #endif
  853. }
  854. if (c == -1) {
  855. ++idle;
  856. /* Do not check for directory changes in du
  857. * mode. A redraw forces du calculation.
  858. * Check for changes every odd second.
  859. */
  860. #ifdef LINUX_INOTIFY
  861. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  862. #elif defined(BSD_KQUEUE)
  863. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  864. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  865. #endif
  866. c = CONTROL('L');
  867. } else
  868. idle = 0;
  869. for (i = 0; i < len; ++i)
  870. if (c == bindings[i].sym) {
  871. *run = bindings[i].run;
  872. *env = bindings[i].env;
  873. return bindings[i].act;
  874. }
  875. return 0;
  876. }
  877. /*
  878. * Move non-matching entries to the end
  879. */
  880. static int fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  881. {
  882. static int count;
  883. static struct entry _dent, *pdent1, *pdent2;
  884. for (count = 0; count < ndents; ++count) {
  885. if (filter(re, (*dents)[count].name) == 0) {
  886. if (count != --ndents) {
  887. pdent1 = &(*dents)[count];
  888. pdent2 = &(*dents)[ndents];
  889. *(&_dent) = *pdent1;
  890. *pdent1 = *pdent2;
  891. *pdent2 = *(&_dent);
  892. --count;
  893. }
  894. continue;
  895. }
  896. }
  897. return ndents;
  898. }
  899. static int matches(char *fltr)
  900. {
  901. static regex_t re;
  902. /* Search filter */
  903. if (setfilter(&re, fltr) != 0)
  904. return -1;
  905. ndents = fill(&dents, visible, &re);
  906. regfree(&re);
  907. if (!ndents)
  908. return 0;
  909. qsort(dents, ndents, sizeof(*dents), entrycmp);
  910. return 0;
  911. }
  912. static int filterentries(char *path)
  913. {
  914. static char ln[REGEX_MAX] __attribute__ ((aligned));
  915. static wchar_t wln[REGEX_MAX] __attribute__ ((aligned));
  916. static wint_t ch[2] = {0};
  917. int r, total = ndents, oldcur = cur, len = 1;
  918. char *pln = ln + 1;
  919. ln[0] = wln[0] = FILTER;
  920. ln[1] = wln[1] = '\0';
  921. cur = 0;
  922. cleartimeout();
  923. curs_set(TRUE);
  924. printprompt(ln);
  925. while ((r = get_wch(ch)) != ERR) {
  926. switch (*ch) {
  927. case KEY_DC: // fallthrough
  928. case KEY_BACKSPACE: // fallthrough
  929. case '\b': // fallthrough
  930. case CONTROL('L'): // fallthrough
  931. case 127: /* handle DEL */
  932. if (len == 1 && *ch != CONTROL('L')) {
  933. cur = oldcur;
  934. *ch = CONTROL('L');
  935. goto end;
  936. }
  937. if (*ch == CONTROL('L'))
  938. while (len > 1)
  939. wln[--len] = '\0';
  940. else
  941. wln[--len] = '\0';
  942. if (len == 1)
  943. cur = oldcur;
  944. wcstombs(ln, wln, REGEX_MAX);
  945. ndents = total;
  946. if (matches(pln) != -1)
  947. redraw(path);
  948. printprompt(ln);
  949. continue;
  950. case 27: /* Exit filter mode on Escape */
  951. cur = oldcur;
  952. *ch = CONTROL('L');
  953. goto end;
  954. }
  955. if (r == OK) {
  956. /* Handle all control chars in main loop */
  957. if (keyname(*ch)[0] == '^') {
  958. if (len == 1)
  959. cur = oldcur;
  960. goto end;
  961. }
  962. switch (*ch) {
  963. case '\r': // with nonl(), this is ENTER key value
  964. if (len == 1) {
  965. cur = oldcur;
  966. goto end;
  967. }
  968. if (matches(pln) == -1)
  969. goto end;
  970. redraw(path);
  971. goto end;
  972. case '?': // '?' is an invalid regex, show help instead
  973. if (len == 1) {
  974. cur = oldcur;
  975. goto end;
  976. } // fallthrough
  977. default:
  978. /* Reset cur in case it's a repeat search */
  979. if (len == 1)
  980. cur = 0;
  981. if (len == REGEX_MAX - 1)
  982. break;
  983. wln[len] = (wchar_t)*ch;
  984. wln[++len] = '\0';
  985. wcstombs(ln, wln, REGEX_MAX);
  986. /* Forward-filtering optimization:
  987. * - new matches can only be a subset of current matches.
  988. */
  989. /* ndents = total; */
  990. if (matches(pln) == -1)
  991. continue;
  992. /* If the only match is a dir, auto-select and cd into it */
  993. if (ndents == 1 && cfg.filtermode && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  994. *ch = KEY_ENTER;
  995. cur = 0;
  996. goto end;
  997. }
  998. /*
  999. * redraw() should be above the auto-select optimization, for
  1000. * the case where there's an issue with dir auto-select, say,
  1001. * due to a permission problem. The transition is jumpy in
  1002. * case of such an error. However, we optimize for successful
  1003. * cases where the dir has permissions. This skips a redraw().
  1004. */
  1005. redraw(path);
  1006. printprompt(ln);
  1007. }
  1008. } else {
  1009. if (len == 1)
  1010. cur = oldcur;
  1011. goto end;
  1012. }
  1013. }
  1014. end:
  1015. curs_set(FALSE);
  1016. settimeout();
  1017. /* Return keys for navigation etc. */
  1018. return *ch;
  1019. }
  1020. /* Show a prompt with input string and return the changes */
  1021. static char *xreadline(char *fname, char *prompt)
  1022. {
  1023. size_t len, pos;
  1024. int x, y, r;
  1025. wint_t ch[2] = {0};
  1026. static wchar_t * const buf = (wchar_t *)g_buf;
  1027. printprompt(prompt);
  1028. if (fname) {
  1029. DPRINTF_S(fname);
  1030. len = pos = mbstowcs(buf, fname, NAME_MAX);
  1031. } else
  1032. len = (size_t)-1;
  1033. if (len == (size_t)-1) {
  1034. buf[0] = '\0';
  1035. len = pos = 0;
  1036. }
  1037. getyx(stdscr, y, x);
  1038. curs_set(TRUE);
  1039. cleartimeout();
  1040. while (1) {
  1041. buf[len] = ' ';
  1042. mvaddnwstr(y, x, buf, len + 1);
  1043. move(y, x + wcswidth(buf, pos));
  1044. r = get_wch(ch);
  1045. if (r != ERR) {
  1046. if (r == OK) {
  1047. switch (*ch) {
  1048. case KEY_ENTER: //fallthrough
  1049. case '\n': //fallthrough
  1050. case '\r':
  1051. goto END;
  1052. case '\b': /* some old curses (e.g. rhel25) still send '\b' for backspace */
  1053. if (pos > 0) {
  1054. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1055. --len, --pos;
  1056. } //fallthrough
  1057. case '\t': /* TAB breaks cursor position, ignore it */
  1058. continue;
  1059. case CONTROL('L'):
  1060. clearprompt();
  1061. printprompt(prompt);
  1062. len = pos = 0;
  1063. continue;
  1064. case CONTROL('A'):
  1065. pos = 0;
  1066. continue;
  1067. case CONTROL('E'):
  1068. pos = len;
  1069. continue;
  1070. case CONTROL('U'):
  1071. clearprompt();
  1072. printprompt(prompt);
  1073. memmove(buf, buf + pos, (len - pos) << 2);
  1074. len -= pos;
  1075. pos = 0;
  1076. continue;
  1077. case 27: /* Exit prompt on Escape */
  1078. len = 0;
  1079. goto END;
  1080. }
  1081. /* Filter out all other control chars */
  1082. if (keyname(*ch)[0] == '^')
  1083. continue;
  1084. if (pos < NAME_MAX - 1) {
  1085. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1086. buf[pos] = *ch;
  1087. ++len, ++pos;
  1088. continue;
  1089. }
  1090. } else {
  1091. switch (*ch) {
  1092. case KEY_LEFT:
  1093. if (pos > 0)
  1094. --pos;
  1095. break;
  1096. case KEY_RIGHT:
  1097. if (pos < len)
  1098. ++pos;
  1099. break;
  1100. case KEY_BACKSPACE:
  1101. if (pos > 0) {
  1102. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1103. --len, --pos;
  1104. }
  1105. break;
  1106. case KEY_DC:
  1107. if (pos < len) {
  1108. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1109. --len;
  1110. }
  1111. break;
  1112. default:
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. }
  1118. END:
  1119. buf[len] = '\0';
  1120. curs_set(FALSE);
  1121. settimeout();
  1122. DPRINTF_S(buf);
  1123. wcstombs(g_buf, buf, NAME_MAX);
  1124. clearprompt();
  1125. return g_buf;
  1126. }
  1127. /*
  1128. * Updates out with "dir/name or "/name"
  1129. * Returns the number of bytes copied including the terminating NULL byte
  1130. */
  1131. static size_t mkpath(char *dir, char *name, char *out, size_t n)
  1132. {
  1133. static size_t len;
  1134. /* Handle absolute path */
  1135. if (name[0] == '/')
  1136. return xstrlcpy(out, name, n);
  1137. /* Handle root case */
  1138. if (istopdir(dir))
  1139. len = 1;
  1140. else
  1141. len = xstrlcpy(out, dir, n);
  1142. out[len - 1] = '/';
  1143. return (xstrlcpy(out + len, name, n - len) + len);
  1144. }
  1145. static void parsebmstr()
  1146. {
  1147. int i = 0;
  1148. char *bms = getenv("NNN_BMS");
  1149. if (!bms)
  1150. return;
  1151. while (*bms && i < BM_MAX) {
  1152. bookmark[i].key = bms;
  1153. ++bms;
  1154. while (*bms && *bms != ':')
  1155. ++bms;
  1156. if (!*bms) {
  1157. bookmark[i].key = NULL;
  1158. break;
  1159. }
  1160. *bms = '\0';
  1161. bookmark[i].loc = ++bms;
  1162. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1163. bookmark[i].key = NULL;
  1164. break;
  1165. }
  1166. while (*bms && *bms != ';')
  1167. ++bms;
  1168. if (*bms)
  1169. *bms = '\0';
  1170. else
  1171. break;
  1172. ++bms;
  1173. ++i;
  1174. }
  1175. }
  1176. /*
  1177. * Get the real path to a bookmark
  1178. *
  1179. * NULL is returned in case of no match, path resolution failure etc.
  1180. * buf would be modified, so check return value before access
  1181. */
  1182. static char *get_bm_loc(char *key, char *buf)
  1183. {
  1184. int r;
  1185. if (!key || !key[0])
  1186. return NULL;
  1187. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1188. if (strcmp(bookmark[r].key, key) == 0) {
  1189. if (bookmark[r].loc[0] == '~') {
  1190. char *home = getenv("HOME");
  1191. if (!home) {
  1192. DPRINTF_S(messages[STR_NOHOME_ID]);
  1193. return NULL;
  1194. }
  1195. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1196. } else
  1197. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1198. return buf;
  1199. }
  1200. }
  1201. DPRINTF_S("Invalid key");
  1202. return NULL;
  1203. }
  1204. static void resetdircolor(mode_t mode)
  1205. {
  1206. if (cfg.dircolor && !S_ISDIR(mode)) {
  1207. attroff(COLOR_PAIR(1) | A_BOLD);
  1208. cfg.dircolor = 0;
  1209. }
  1210. }
  1211. /*
  1212. * Replace escape characters in a string with '?'
  1213. * Adjust string length to maxcols if > 0;
  1214. *
  1215. * Interestingly, note that unescape() uses g_buf. What happens if
  1216. * str also points to g_buf? In this case we assume that the caller
  1217. * acknowledges that it's OK to lose the data in g_buf after this
  1218. * call to unescape().
  1219. * The API, on its part, first converts str to multibyte (after which
  1220. * it doesn't touch str anymore). Only after that it starts modifying
  1221. * g_buf. This is a phased operation.
  1222. */
  1223. static char *unescape(const char *str, uint maxcols)
  1224. {
  1225. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1226. static wchar_t *buf;
  1227. static size_t len;
  1228. /* Convert multi-byte to wide char */
  1229. len = mbstowcs(wbuf, str, PATH_MAX);
  1230. g_buf[0] = '\0';
  1231. buf = wbuf;
  1232. if (maxcols && len > maxcols) {
  1233. len = wcswidth(wbuf, len);
  1234. if (len > maxcols)
  1235. wbuf[maxcols] = 0;
  1236. }
  1237. while (*buf) {
  1238. if (*buf <= '\x1f' || *buf == '\x7f')
  1239. *buf = '\?';
  1240. ++buf;
  1241. }
  1242. /* Convert wide char to multi-byte */
  1243. wcstombs(g_buf, wbuf, PATH_MAX);
  1244. return g_buf;
  1245. }
  1246. static char *coolsize(off_t size)
  1247. {
  1248. static const char * const U = "BKMGTPEZY";
  1249. static char size_buf[12]; /* Buffer to hold human readable size */
  1250. static off_t rem;
  1251. static int i;
  1252. i = 0;
  1253. rem = 0;
  1254. while (size > 1024) {
  1255. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1256. size >>= 10;
  1257. ++i;
  1258. }
  1259. if (i == 1) {
  1260. rem = (rem * 1000) >> 10;
  1261. rem /= 10;
  1262. if (rem % 10 >= 5) {
  1263. rem = (rem / 10) + 1;
  1264. if (rem == 10) {
  1265. ++size;
  1266. rem = 0;
  1267. }
  1268. } else
  1269. rem /= 10;
  1270. } else if (i == 2) {
  1271. rem = (rem * 1000) >> 10;
  1272. if (rem % 10 >= 5) {
  1273. rem = (rem / 10) + 1;
  1274. if (rem == 100) {
  1275. ++size;
  1276. rem = 0;
  1277. }
  1278. } else
  1279. rem /= 10;
  1280. } else if (i > 0) {
  1281. rem = (rem * 10000) >> 10;
  1282. if (rem % 10 >= 5) {
  1283. rem = (rem / 10) + 1;
  1284. if (rem == 1000) {
  1285. ++size;
  1286. rem = 0;
  1287. }
  1288. } else
  1289. rem /= 10;
  1290. }
  1291. if (i > 0)
  1292. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1293. else
  1294. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1295. return size_buf;
  1296. }
  1297. static char *get_file_sym(mode_t mode)
  1298. {
  1299. static char ind[2] = "\0\0";
  1300. if (S_ISDIR(mode))
  1301. ind[0] = '/';
  1302. else if (S_ISLNK(mode))
  1303. ind[0] = '@';
  1304. else if (S_ISSOCK(mode))
  1305. ind[0] = '=';
  1306. else if (S_ISFIFO(mode))
  1307. ind[0] = '|';
  1308. else if (mode & 0100)
  1309. ind[0] = '*';
  1310. else
  1311. ind[0] = '\0';
  1312. return ind;
  1313. }
  1314. static void printent(struct entry *ent, int sel, uint namecols)
  1315. {
  1316. static char *pname;
  1317. pname = unescape(ent->name, namecols);
  1318. /* Directories are always shown on top */
  1319. resetdircolor(ent->mode);
  1320. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1321. }
  1322. static void printent_long(struct entry *ent, int sel, uint namecols)
  1323. {
  1324. static char buf[18], *pname;
  1325. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1326. pname = unescape(ent->name, namecols);
  1327. /* Directories are always shown on top */
  1328. resetdircolor(ent->mode);
  1329. if (sel)
  1330. attron(A_REVERSE);
  1331. if (S_ISDIR(ent->mode)) {
  1332. if (cfg.blkorder)
  1333. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1334. else
  1335. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1336. } else if (S_ISLNK(ent->mode)) {
  1337. if (ent->flags & SYMLINK_TO_DIR)
  1338. printw("%s%-16.16s @/ %s@\n", CURSYM(sel), buf, pname);
  1339. else
  1340. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1341. } else if (S_ISSOCK(ent->mode))
  1342. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1343. else if (S_ISFIFO(ent->mode))
  1344. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1345. else if (S_ISBLK(ent->mode))
  1346. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1347. else if (S_ISCHR(ent->mode))
  1348. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1349. else if (ent->mode & 0100) {
  1350. if (cfg.blkorder)
  1351. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1352. else
  1353. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1354. } else {
  1355. if (cfg.blkorder)
  1356. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1357. else
  1358. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1359. }
  1360. if (sel)
  1361. attroff(A_REVERSE);
  1362. }
  1363. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1364. static char get_fileind(mode_t mode, char *desc)
  1365. {
  1366. static char c;
  1367. if (S_ISREG(mode)) {
  1368. c = '-';
  1369. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1370. if (mode & 0100)
  1371. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1372. } else if (S_ISDIR(mode)) {
  1373. c = 'd';
  1374. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1375. } else if (S_ISBLK(mode)) {
  1376. c = 'b';
  1377. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1378. } else if (S_ISCHR(mode)) {
  1379. c = 'c';
  1380. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1381. #ifdef S_ISFIFO
  1382. } else if (S_ISFIFO(mode)) {
  1383. c = 'p';
  1384. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1385. #endif /* S_ISFIFO */
  1386. #ifdef S_ISLNK
  1387. } else if (S_ISLNK(mode)) {
  1388. c = 'l';
  1389. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1390. #endif /* S_ISLNK */
  1391. #ifdef S_ISSOCK
  1392. } else if (S_ISSOCK(mode)) {
  1393. c = 's';
  1394. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1395. #endif /* S_ISSOCK */
  1396. #ifdef S_ISDOOR
  1397. /* Solaris 2.6, etc. */
  1398. } else if (S_ISDOOR(mode)) {
  1399. c = 'D';
  1400. desc[0] = '\0';
  1401. #endif /* S_ISDOOR */
  1402. } else {
  1403. /* Unknown type -- possibly a regular file? */
  1404. c = '?';
  1405. desc[0] = '\0';
  1406. }
  1407. return c;
  1408. }
  1409. /* Convert a mode field into "ls -l" type perms field. */
  1410. static char *get_lsperms(mode_t mode, char *desc)
  1411. {
  1412. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1413. static char bits[11] = {'\0'};
  1414. bits[0] = get_fileind(mode, desc);
  1415. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1416. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1417. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1418. if (mode & S_ISUID)
  1419. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1420. if (mode & S_ISGID)
  1421. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1422. if (mode & S_ISVTX)
  1423. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1424. return bits;
  1425. }
  1426. /*
  1427. * Gets only a single line (that's what we need
  1428. * for now) or shows full command output in pager.
  1429. *
  1430. * If pager is valid, returns NULL
  1431. */
  1432. static char *get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1433. {
  1434. pid_t pid;
  1435. int pipefd[2];
  1436. FILE *pf;
  1437. int tmp, flags;
  1438. char *ret = NULL;
  1439. if (pipe(pipefd) == -1)
  1440. errexit();
  1441. for (tmp = 0; tmp < 2; ++tmp) {
  1442. /* Get previous flags */
  1443. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1444. /* Set bit for non-blocking flag */
  1445. flags |= O_NONBLOCK;
  1446. /* Change flags on fd */
  1447. fcntl(pipefd[tmp], F_SETFL, flags);
  1448. }
  1449. pid = fork();
  1450. if (pid == 0) {
  1451. /* In child */
  1452. close(pipefd[0]);
  1453. dup2(pipefd[1], STDOUT_FILENO);
  1454. dup2(pipefd[1], STDERR_FILENO);
  1455. close(pipefd[1]);
  1456. execlp(file, file, arg1, arg2, NULL);
  1457. _exit(1);
  1458. }
  1459. /* In parent */
  1460. waitpid(pid, &tmp, 0);
  1461. close(pipefd[1]);
  1462. if (!pager) {
  1463. pf = fdopen(pipefd[0], "r");
  1464. if (pf) {
  1465. ret = fgets(buf, bytes, pf);
  1466. close(pipefd[0]);
  1467. }
  1468. return ret;
  1469. }
  1470. pid = fork();
  1471. if (pid == 0) {
  1472. /* Show in pager in child */
  1473. dup2(pipefd[0], STDIN_FILENO);
  1474. close(pipefd[0]);
  1475. execlp("less", "less", NULL);
  1476. _exit(1);
  1477. }
  1478. /* In parent */
  1479. waitpid(pid, &tmp, 0);
  1480. close(pipefd[0]);
  1481. return NULL;
  1482. }
  1483. static char *xgetpwuid(uid_t uid)
  1484. {
  1485. struct passwd *pwd = getpwuid(uid);
  1486. if (!pwd)
  1487. return utils[UNKNOWN];
  1488. return pwd->pw_name;
  1489. }
  1490. static char *xgetgrgid(gid_t gid)
  1491. {
  1492. struct group *grp = getgrgid(gid);
  1493. if (!grp)
  1494. return utils[UNKNOWN];
  1495. return grp->gr_name;
  1496. }
  1497. /*
  1498. * Follows the stat(1) output closely
  1499. */
  1500. static int show_stats(char *fpath, char *fname, struct stat *sb)
  1501. {
  1502. char desc[DESCRIPTOR_LEN];
  1503. char *perms = get_lsperms(sb->st_mode, desc);
  1504. char *p, *begin = g_buf;
  1505. if (g_tmpfpath[0])
  1506. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  1507. else {
  1508. printmsg(messages[STR_NOHOME_ID]);
  1509. return -1;
  1510. }
  1511. int fd = mkstemp(g_tmpfpath);
  1512. if (fd == -1)
  1513. return -1;
  1514. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1515. /* Show file name or 'symlink' -> 'target' */
  1516. if (perms[0] == 'l') {
  1517. /* Note that MAX_CMD_LEN > PATH_MAX */
  1518. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1519. if (len != -1) {
  1520. struct stat tgtsb;
  1521. if (!stat(fpath, &tgtsb) && S_ISDIR(tgtsb.st_mode))
  1522. g_buf[len++] = '/';
  1523. g_buf[len] = '\0';
  1524. /*
  1525. * We pass g_buf but unescape() operates on g_buf too!
  1526. * Read the API notes for information on how this works.
  1527. */
  1528. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1529. }
  1530. }
  1531. /* Show size, blocks, file type */
  1532. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1533. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1534. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1535. #else
  1536. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1537. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1538. #endif
  1539. /* Show containing device, inode, hardlink count */
  1540. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1541. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1542. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1543. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1544. #else
  1545. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1546. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1547. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1548. #endif
  1549. /* Show major, minor number for block or char device */
  1550. if (perms[0] == 'b' || perms[0] == 'c')
  1551. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1552. /* Show permissions, owner, group */
  1553. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)", (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1554. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid), sb->st_gid, xgetgrgid(sb->st_gid));
  1555. /* Show last access time */
  1556. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1557. dprintf(fd, "\n\n Access: %s", g_buf);
  1558. /* Show last modification time */
  1559. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1560. dprintf(fd, "\n Modify: %s", g_buf);
  1561. /* Show last status change time */
  1562. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1563. dprintf(fd, "\n Change: %s", g_buf);
  1564. if (S_ISREG(sb->st_mode)) {
  1565. /* Show file(1) output */
  1566. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1567. if (p) {
  1568. dprintf(fd, "\n\n ");
  1569. while (*p) {
  1570. if (*p == ',') {
  1571. *p = '\0';
  1572. dprintf(fd, " %s\n", begin);
  1573. begin = p + 1;
  1574. }
  1575. ++p;
  1576. }
  1577. dprintf(fd, " %s", begin);
  1578. }
  1579. dprintf(fd, "\n\n");
  1580. } else
  1581. dprintf(fd, "\n\n\n");
  1582. close(fd);
  1583. exitcurses();
  1584. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  1585. unlink(g_tmpfpath);
  1586. refresh();
  1587. return 0;
  1588. }
  1589. static size_t get_fs_info(const char *path, bool type)
  1590. {
  1591. static struct statvfs svb;
  1592. if (statvfs(path, &svb) == -1)
  1593. return 0;
  1594. if (type == CAPACITY)
  1595. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1596. else
  1597. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1598. }
  1599. static int show_mediainfo(char *fpath, char *arg)
  1600. {
  1601. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1602. return -1;
  1603. exitcurses();
  1604. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1605. refresh();
  1606. return 0;
  1607. }
  1608. static int handle_archive(char *fpath, char *arg, char *dir)
  1609. {
  1610. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1611. return -1;
  1612. if (arg[1] == 'x')
  1613. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1614. else {
  1615. exitcurses();
  1616. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1617. refresh();
  1618. }
  1619. return 0;
  1620. }
  1621. /*
  1622. * The help string tokens (each line) start with a HEX value
  1623. * which indicates the number of spaces to print before the
  1624. * particular token. This method was chosen instead of a flat
  1625. * string because the number of bytes in help was increasing
  1626. * the binary size by around a hundred bytes. This would only
  1627. * have increased as we keep adding new options.
  1628. */
  1629. static int show_help(char *path)
  1630. {
  1631. if (g_tmpfpath[0])
  1632. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  1633. else {
  1634. printmsg(messages[STR_NOHOME_ID]);
  1635. return -1;
  1636. }
  1637. int i = 0, fd = mkstemp(g_tmpfpath);
  1638. char *start, *end;
  1639. static char helpstr[] = {
  1640. "cKey Desc\n"
  1641. "e----\n"
  1642. "7↑, k, ^P Up\n"
  1643. "7↓, j, ^N Down\n"
  1644. "7PgUp, ^U Scroll up\n"
  1645. "7PgDn, ^D Scroll down\n"
  1646. "1Home, g, ^, ^A First entry\n"
  1647. "2End, G, $, ^E Last entry\n"
  1648. "4→, ↵, l, ^M Open file/enter dir\n"
  1649. "1←, Bksp, h, ^H Parent dir\n"
  1650. "d^O Open with...\n"
  1651. "5Insert, ^I Toggle nav-as-you-type\n"
  1652. "e~ Go HOME\n"
  1653. "e& Start dir\n"
  1654. "e- Last visited dir\n"
  1655. "e/ Filter entries\n"
  1656. "e. Toggle show hidden\n"
  1657. "d^B Bookmark prompt\n"
  1658. "eb Pin current dir\n"
  1659. "d^V Go to pinned dir\n"
  1660. "ec cd prompt\n"
  1661. "ed Toggle detail view\n"
  1662. "eD File details\n"
  1663. "bm, M Brief/full media info\n"
  1664. "en Create new\n"
  1665. "d^R Rename entry\n"
  1666. "er Open dir in vidir\n"
  1667. "es Toggle sort by size\n"
  1668. "eS Toggle apparent size\n"
  1669. "d^J Toggle du mode\n"
  1670. "et Toggle sort by mtime\n"
  1671. "a!, ^] Spawn SHELL in dir\n"
  1672. "eR Run custom script\n"
  1673. "ee Edit in EDITOR\n"
  1674. "ep Open in PAGER\n"
  1675. "ef Archive entry\n"
  1676. "eF List archive\n"
  1677. "d^F Extract archive\n"
  1678. "6Space, ^K Copy file path\n"
  1679. "d^Y Toggle multi-copy\n"
  1680. "ey Show copy buffer\n"
  1681. "d^T Toggle path quote\n"
  1682. "d^L Redraw, clear prompt\n"
  1683. "cEsc Exit prompt\n"
  1684. "eL Lock terminal\n"
  1685. "eo Open DE filemanager\n"
  1686. "d^/ Open DE search app\n"
  1687. "e? Help, settings\n"
  1688. "aQ, ^G Quit and cd\n"
  1689. "aq, ^X Quit\n\n"};
  1690. if (fd == -1)
  1691. return -1;
  1692. start = end = helpstr;
  1693. while (*end) {
  1694. while (*end != '\n')
  1695. ++end;
  1696. if (start == end) {
  1697. ++end;
  1698. continue;
  1699. }
  1700. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1701. start = ++end;
  1702. }
  1703. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_info(path, FREE)));
  1704. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  1705. if (getenv("NNN_BMS")) {
  1706. dprintf(fd, "BOOKMARKS\n");
  1707. for (; i < BM_MAX; ++i)
  1708. if (bookmark[i].key)
  1709. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1710. else
  1711. break;
  1712. dprintf(fd, "\n");
  1713. }
  1714. if (editor)
  1715. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1716. if (dmanager)
  1717. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", dmanager);
  1718. if (idletimeout)
  1719. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1720. if (copier)
  1721. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1722. if (getenv("NNN_NO_X"))
  1723. dprintf(fd, "NNN_NO_X: %s (%s)\n", getenv("NNN_NO_X"), g_cppath);
  1724. if (getenv("NNN_SCRIPT"))
  1725. dprintf(fd, "NNN_SCRIPT: %s\n", getenv("NNN_SCRIPT"));
  1726. if (getenv("NNN_MULTISCRIPT"))
  1727. dprintf(fd, "NNN_MULTISCRIPT: %s\n", getenv("NNN_MULTISCRIPT"));
  1728. if (getenv("NNN_SHOW_HIDDEN"))
  1729. dprintf(fd, "NNN_SHOW_HIDDEN: %s\n", getenv("NNN_SHOW_HIDDEN"));
  1730. dprintf(fd, "\n");
  1731. if (getenv("PWD"))
  1732. dprintf(fd, "PWD: %s\n", getenv("PWD"));
  1733. if (getenv("SHELL"))
  1734. dprintf(fd, "SHELL: %s\n", getenv("SHELL"));
  1735. if (getenv("SHLVL"))
  1736. dprintf(fd, "SHLVL: %s\n", getenv("SHLVL"));
  1737. if (getenv("VISUAL"))
  1738. dprintf(fd, "VISUAL: %s\n", getenv("VISUAL"));
  1739. else if (getenv("EDITOR"))
  1740. dprintf(fd, "EDITOR: %s\n", getenv("EDITOR"));
  1741. if (getenv("PAGER"))
  1742. dprintf(fd, "PAGER: %s\n", getenv("PAGER"));
  1743. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1744. close(fd);
  1745. exitcurses();
  1746. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  1747. unlink(g_tmpfpath);
  1748. refresh();
  1749. return 0;
  1750. }
  1751. static int sum_bsizes(const char *fpath, const struct stat *sb,
  1752. int typeflag, struct FTW *ftwbuf)
  1753. {
  1754. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1755. ent_blocks += sb->st_blocks;
  1756. ++num_files;
  1757. return 0;
  1758. }
  1759. static int sum_sizes(const char *fpath, const struct stat *sb,
  1760. int typeflag, struct FTW *ftwbuf)
  1761. {
  1762. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  1763. ent_blocks += sb->st_size;
  1764. ++num_files;
  1765. return 0;
  1766. }
  1767. static void dentfree(struct entry *dents)
  1768. {
  1769. free(pnamebuf);
  1770. free(dents);
  1771. }
  1772. static int dentfill(char *path, struct entry **dents,
  1773. int (*filter)(regex_t *, char *), regex_t *re)
  1774. {
  1775. static DIR *dirp;
  1776. static struct dirent *dp;
  1777. static char *namep, *pnb;
  1778. static struct entry *dentp;
  1779. static size_t off, namebuflen = NAMEBUF_INCR;
  1780. static ulong num_saved;
  1781. static int fd, n, count;
  1782. static struct stat sb_path, sb;
  1783. off = 0;
  1784. dirp = opendir(path);
  1785. if (dirp == NULL)
  1786. return 0;
  1787. fd = dirfd(dirp);
  1788. n = 0;
  1789. if (cfg.blkorder) {
  1790. num_files = 0;
  1791. dir_blocks = 0;
  1792. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1793. printwarn();
  1794. return 0;
  1795. }
  1796. }
  1797. while ((dp = readdir(dirp)) != NULL) {
  1798. namep = dp->d_name;
  1799. if (filter(re, namep) == 0) {
  1800. if (!cfg.blkorder)
  1801. continue;
  1802. /* Skip self and parent */
  1803. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1804. continue;
  1805. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1806. continue;
  1807. if (S_ISDIR(sb.st_mode)) {
  1808. if (sb_path.st_dev == sb.st_dev) {
  1809. ent_blocks = 0;
  1810. mkpath(path, namep, g_buf, PATH_MAX);
  1811. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1812. printmsg(messages[STR_NFTWFAIL_ID]);
  1813. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1814. } else
  1815. dir_blocks += ent_blocks;
  1816. }
  1817. } else {
  1818. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1819. ++num_files;
  1820. }
  1821. continue;
  1822. }
  1823. /* Skip self and parent */
  1824. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1825. (namep[1] == '.' && namep[2] == '\0'))))
  1826. continue;
  1827. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1828. DPRINTF_S(namep);
  1829. continue;
  1830. }
  1831. if (n == total_dents) {
  1832. total_dents += ENTRY_INCR;
  1833. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1834. if (*dents == NULL) {
  1835. free(pnamebuf);
  1836. errexit();
  1837. }
  1838. DPRINTF_P(*dents);
  1839. }
  1840. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1841. if (namebuflen - off < NAME_MAX + 1) {
  1842. namebuflen += NAMEBUF_INCR;
  1843. pnb = pnamebuf;
  1844. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1845. if (pnamebuf == NULL) {
  1846. free(*dents);
  1847. errexit();
  1848. }
  1849. DPRINTF_P(pnamebuf);
  1850. /* realloc() may result in memory move, we must re-adjust if that happens */
  1851. if (pnb != pnamebuf) {
  1852. dentp = *dents;
  1853. dentp->name = pnamebuf;
  1854. for (count = 1; count < n; ++dentp, ++count)
  1855. /* Current filename starts at last filename start + length */
  1856. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1857. }
  1858. }
  1859. dentp = *dents + n;
  1860. /* Copy file name */
  1861. dentp->name = (char *)((size_t)pnamebuf + off);
  1862. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1863. off += dentp->nlen;
  1864. /* Copy other fields */
  1865. dentp->mode = sb.st_mode;
  1866. dentp->t = sb.st_mtime;
  1867. dentp->size = sb.st_size;
  1868. if (cfg.blkorder) {
  1869. if (S_ISDIR(sb.st_mode)) {
  1870. ent_blocks = 0;
  1871. num_saved = num_files + 1;
  1872. mkpath(path, namep, g_buf, PATH_MAX);
  1873. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1874. printmsg(messages[STR_NFTWFAIL_ID]);
  1875. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1876. } else
  1877. dentp->blocks = ent_blocks;
  1878. if (sb_path.st_dev == sb.st_dev)
  1879. dir_blocks += dentp->blocks;
  1880. else
  1881. num_files = num_saved;
  1882. } else {
  1883. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1884. dir_blocks += dentp->blocks;
  1885. ++num_files;
  1886. }
  1887. }
  1888. /* Flag if this is a symlink to a dir */
  1889. if (S_ISLNK(sb.st_mode))
  1890. if (!fstatat(fd, namep, &sb, 0)) {
  1891. if (S_ISDIR(sb.st_mode))
  1892. dentp->flags |= SYMLINK_TO_DIR;
  1893. else
  1894. dentp->flags &= ~SYMLINK_TO_DIR;
  1895. }
  1896. ++n;
  1897. }
  1898. /* Should never be null */
  1899. if (closedir(dirp) == -1) {
  1900. dentfree(*dents);
  1901. errexit();
  1902. }
  1903. return n;
  1904. }
  1905. /* Return the position of the matching entry or 0 otherwise */
  1906. static int dentfind(struct entry *dents, const char *fname, int n)
  1907. {
  1908. static int i;
  1909. if (!fname)
  1910. return 0;
  1911. DPRINTF_S(fname);
  1912. for (i = 0; i < n; ++i)
  1913. if (strcmp(fname, dents[i].name) == 0)
  1914. return i;
  1915. return 0;
  1916. }
  1917. static int populate(char *path, char *oldname, char *fltr)
  1918. {
  1919. static regex_t re;
  1920. /* Can fail when permissions change while browsing.
  1921. * It's assumed that path IS a directory when we are here.
  1922. */
  1923. if (access(path, R_OK) == -1)
  1924. return -1;
  1925. /* Search filter */
  1926. if (setfilter(&re, fltr) != 0)
  1927. return -1;
  1928. if (cfg.blkorder) {
  1929. printmsg("calculating...");
  1930. refresh();
  1931. }
  1932. #ifdef DEBUGMODE
  1933. struct timespec ts1, ts2;
  1934. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1935. #endif
  1936. ndents = dentfill(path, &dents, visible, &re);
  1937. regfree(&re);
  1938. if (!ndents)
  1939. return 0;
  1940. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1941. #ifdef DEBUGMODE
  1942. clock_gettime(CLOCK_REALTIME, &ts2);
  1943. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1944. #endif
  1945. /* Find cur from history */
  1946. cur = dentfind(dents, oldname, ndents);
  1947. return 0;
  1948. }
  1949. static void redraw(char *path)
  1950. {
  1951. static char buf[NAME_MAX + 65] __attribute__ ((aligned));
  1952. static size_t ncols;
  1953. static int nlines, i;
  1954. static bool mode_changed;
  1955. mode_changed = FALSE;
  1956. nlines = MIN(LINES - 4, ndents);
  1957. /* Clean screen */
  1958. erase();
  1959. if (cfg.copymode)
  1960. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1961. cfg.copymode = 0;
  1962. DPRINTF_S("copymode off");
  1963. }
  1964. /* Fail redraw if < than 10 columns */
  1965. if (COLS < 10) {
  1966. printmsg("too few columns!");
  1967. return;
  1968. }
  1969. /* Strip trailing slashes */
  1970. for (i = strlen(path) - 1; i > 0; --i)
  1971. if (path[i] == '/')
  1972. path[i] = '\0';
  1973. else
  1974. break;
  1975. DPRINTF_D(cur);
  1976. DPRINTF_S(path);
  1977. if (!realpath(path, g_buf)) {
  1978. printwarn();
  1979. return;
  1980. }
  1981. ncols = COLS;
  1982. if (ncols > PATH_MAX)
  1983. ncols = PATH_MAX;
  1984. attron(A_UNDERLINE);
  1985. /* No text wrapping in cwd line */
  1986. g_buf[ncols - 1] = '\0';
  1987. printw("%s\n\n", g_buf);
  1988. attroff(A_UNDERLINE);
  1989. /* Fallback to light mode if less than 35 columns */
  1990. if (ncols < 35 && cfg.showdetail) {
  1991. cfg.showdetail ^= 1;
  1992. printptr = &printent;
  1993. mode_changed = TRUE;
  1994. }
  1995. /* Calculate the number of cols available to print entry name */
  1996. if (cfg.showdetail)
  1997. ncols -= 32;
  1998. else
  1999. ncols -= 5;
  2000. if (cfg.showcolor) {
  2001. attron(COLOR_PAIR(1) | A_BOLD);
  2002. cfg.dircolor = 1;
  2003. }
  2004. /* Print listing */
  2005. if (cur < (nlines >> 1)) {
  2006. for (i = 0; i < nlines; ++i)
  2007. printptr(&dents[i], i == cur, ncols);
  2008. } else if (cur >= ndents - (nlines >> 1)) {
  2009. for (i = ndents - nlines; i < ndents; ++i)
  2010. printptr(&dents[i], i == cur, ncols);
  2011. } else {
  2012. static int odd;
  2013. odd = ISODD(nlines);
  2014. nlines >>= 1;
  2015. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2016. printptr(&dents[i], i == cur, ncols);
  2017. }
  2018. /* Must reset e.g. no files in dir */
  2019. if (cfg.dircolor) {
  2020. attroff(COLOR_PAIR(1) | A_BOLD);
  2021. cfg.dircolor = 0;
  2022. }
  2023. if (cfg.showdetail) {
  2024. if (ndents) {
  2025. static char sort[9];
  2026. if (cfg.mtimeorder)
  2027. xstrlcpy(sort, "by time ", 9);
  2028. else if (cfg.sizeorder)
  2029. xstrlcpy(sort, "by size ", 9);
  2030. else
  2031. sort[0] = '\0';
  2032. /* We need to show filename as it may be truncated in directory listing */
  2033. if (!cfg.blkorder)
  2034. snprintf(buf, NAME_MAX + 65, "%d/%d %s[%s%s]",
  2035. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2036. else {
  2037. i = snprintf(buf, 64, "%d/%d ", cur + 1, ndents);
  2038. if (cfg.apparentsz)
  2039. buf[i++] = 'a';
  2040. else
  2041. buf[i++] = 'd';
  2042. i += snprintf(buf + i, 64, "u: %s (%lu files) ", coolsize(dir_blocks << BLK_SHIFT), num_files);
  2043. snprintf(buf + i, NAME_MAX, "vol: %s free [%s%s]",
  2044. coolsize(get_fs_info(path, FREE)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2045. }
  2046. printmsg(buf);
  2047. } else
  2048. printmsg("0 items");
  2049. }
  2050. if (mode_changed) {
  2051. cfg.showdetail ^= 1;
  2052. printptr = &printent_long;
  2053. }
  2054. }
  2055. static void browse(char *ipath, char *ifilter)
  2056. {
  2057. static char path[PATH_MAX] __attribute__ ((aligned));
  2058. static char newpath[PATH_MAX] __attribute__ ((aligned));
  2059. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  2060. static char mark[PATH_MAX] __attribute__ ((aligned));
  2061. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  2062. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  2063. char *dir, *tmp, *run = NULL, *env = NULL;
  2064. struct stat sb;
  2065. int r, fd, truecd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2066. enum action sel = SEL_RUNARG + 1;
  2067. bool dir_changed = FALSE;
  2068. xstrlcpy(path, ipath, PATH_MAX);
  2069. copyfilter();
  2070. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  2071. if (cfg.filtermode)
  2072. presel = FILTER;
  2073. else
  2074. presel = 0;
  2075. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2076. if (dents == NULL)
  2077. errexit();
  2078. DPRINTF_P(dents);
  2079. /* Allocate buffer to hold names */
  2080. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2081. if (pnamebuf == NULL) {
  2082. free(dents);
  2083. errexit();
  2084. }
  2085. DPRINTF_P(pnamebuf);
  2086. begin:
  2087. #ifdef LINUX_INOTIFY
  2088. if (dir_changed && inotify_wd >= 0) {
  2089. inotify_rm_watch(inotify_fd, inotify_wd);
  2090. inotify_wd = -1;
  2091. dir_changed = FALSE;
  2092. }
  2093. #elif defined(BSD_KQUEUE)
  2094. if (dir_changed && event_fd >= 0) {
  2095. close(event_fd);
  2096. event_fd = -1;
  2097. dir_changed = FALSE;
  2098. }
  2099. #endif
  2100. if (populate(path, oldname, fltr) == -1) {
  2101. printwarn();
  2102. goto nochange;
  2103. }
  2104. #ifdef LINUX_INOTIFY
  2105. if (inotify_wd == -1)
  2106. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2107. #elif defined(BSD_KQUEUE)
  2108. if (event_fd == -1) {
  2109. #if defined(O_EVTONLY)
  2110. event_fd = open(path, O_EVTONLY);
  2111. #else
  2112. event_fd = open(path, O_RDONLY);
  2113. #endif
  2114. if (event_fd >= 0)
  2115. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2116. }
  2117. #endif
  2118. for (;;) {
  2119. redraw(path);
  2120. nochange:
  2121. /* Exit if parent has exited */
  2122. if (getppid() == 1)
  2123. _exit(0);
  2124. sel = nextsel(&run, &env, &presel);
  2125. switch (sel) {
  2126. case SEL_BACK:
  2127. /* There is no going back */
  2128. if (istopdir(path)) {
  2129. /* Continue in navigate-as-you-type mode, if enabled */
  2130. if (cfg.filtermode)
  2131. presel = FILTER;
  2132. goto nochange;
  2133. }
  2134. dir = xdirname(path);
  2135. if (access(dir, R_OK) == -1) {
  2136. printwarn();
  2137. goto nochange;
  2138. }
  2139. /* Save history */
  2140. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2141. /* Save last working directory */
  2142. xstrlcpy(lastdir, path, PATH_MAX);
  2143. dir_changed = TRUE;
  2144. xstrlcpy(path, dir, PATH_MAX);
  2145. /* Reset filter */
  2146. copyfilter();
  2147. if (cfg.filtermode)
  2148. presel = FILTER;
  2149. goto begin;
  2150. case SEL_GOIN:
  2151. /* Cannot descend in empty directories */
  2152. if (!ndents)
  2153. goto begin;
  2154. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2155. DPRINTF_S(newpath);
  2156. /* Get path info */
  2157. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2158. if (fd == -1) {
  2159. printwarn();
  2160. goto nochange;
  2161. }
  2162. if (fstat(fd, &sb) == -1) {
  2163. printwarn();
  2164. close(fd);
  2165. goto nochange;
  2166. }
  2167. close(fd);
  2168. DPRINTF_U(sb.st_mode);
  2169. switch (sb.st_mode & S_IFMT) {
  2170. case S_IFDIR:
  2171. if (access(newpath, R_OK) == -1) {
  2172. printwarn();
  2173. goto nochange;
  2174. }
  2175. /* Save last working directory */
  2176. xstrlcpy(lastdir, path, PATH_MAX);
  2177. dir_changed = TRUE;
  2178. xstrlcpy(path, newpath, PATH_MAX);
  2179. oldname[0] = '\0';
  2180. /* Reset filter */
  2181. copyfilter();
  2182. if (cfg.filtermode)
  2183. presel = FILTER;
  2184. goto begin;
  2185. case S_IFREG:
  2186. {
  2187. /* If NNN_USE_EDITOR is set,
  2188. * open text in EDITOR
  2189. */
  2190. if (editor) {
  2191. if (getmime(dents[cur].name)) {
  2192. spawn(editor, newpath, NULL, path, F_NORMAL);
  2193. continue;
  2194. }
  2195. /* Recognize and open plain
  2196. * text files with vi
  2197. */
  2198. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2199. continue;
  2200. if (strstr(g_buf, "text/") == g_buf) {
  2201. spawn(editor, newpath, NULL, path, F_NORMAL);
  2202. continue;
  2203. }
  2204. }
  2205. /* Invoke desktop opener as last resort */
  2206. spawn(utils[OPENER], newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2207. continue;
  2208. }
  2209. default:
  2210. printmsg("unsupported file");
  2211. goto nochange;
  2212. }
  2213. case SEL_NEXT:
  2214. if (cur < ndents - 1)
  2215. ++cur;
  2216. else if (ndents)
  2217. /* Roll over, set cursor to first entry */
  2218. cur = 0;
  2219. break;
  2220. case SEL_PREV:
  2221. if (cur > 0)
  2222. --cur;
  2223. else if (ndents)
  2224. /* Roll over, set cursor to last entry */
  2225. cur = ndents - 1;
  2226. break;
  2227. case SEL_PGDN:
  2228. if (cur < ndents - 1)
  2229. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2230. break;
  2231. case SEL_PGUP:
  2232. if (cur > 0)
  2233. cur -= MIN((LINES - 4) / 2, cur);
  2234. break;
  2235. case SEL_HOME:
  2236. cur = 0;
  2237. break;
  2238. case SEL_END:
  2239. cur = ndents - 1;
  2240. break;
  2241. case SEL_CD:
  2242. truecd = 0;
  2243. tmp = xreadline(NULL, "cd: ");
  2244. if (tmp == NULL || tmp[0] == '\0')
  2245. break;
  2246. if (tmp[0] == '~') {
  2247. /* Expand ~ to HOME absolute path */
  2248. dir = getenv("HOME");
  2249. if (dir)
  2250. snprintf(newpath, PATH_MAX, "%s%s", dir, tmp + 1);
  2251. else {
  2252. printmsg(messages[STR_NOHOME_ID]);
  2253. goto nochange;
  2254. }
  2255. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2256. if (lastdir[0] == '\0')
  2257. break;
  2258. /* Switch to last visited dir */
  2259. xstrlcpy(newpath, lastdir, PATH_MAX);
  2260. truecd = 1;
  2261. } else if ((r = all_dots(tmp))) {
  2262. if (r == 1)
  2263. /* Always in the current dir */
  2264. break;
  2265. /* Show a message if already at / */
  2266. if (istopdir(path)) {
  2267. /* Continue in navigate-as-you-type mode, if enabled */
  2268. if (cfg.filtermode)
  2269. presel = FILTER;
  2270. goto nochange;
  2271. }
  2272. --r; /* One . for the current dir */
  2273. dir = path;
  2274. /* Note: fd is used as a tmp variable here */
  2275. for (fd = 0; fd < r; ++fd) {
  2276. /* Reached / ? */
  2277. if (istopdir(path)) {
  2278. /* Can't cd beyond / */
  2279. break;
  2280. }
  2281. dir = xdirname(dir);
  2282. if (access(dir, R_OK) == -1) {
  2283. printwarn();
  2284. goto nochange;
  2285. }
  2286. }
  2287. truecd = 1;
  2288. /* Save the path in case of cd ..
  2289. * We mark the current dir in parent dir
  2290. */
  2291. if (r == 1) {
  2292. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2293. truecd = 2;
  2294. }
  2295. xstrlcpy(newpath, dir, PATH_MAX);
  2296. } else
  2297. mkpath(path, tmp, newpath, PATH_MAX);
  2298. if (!xdiraccess(newpath))
  2299. goto nochange;
  2300. if (truecd == 0) {
  2301. /* Probable change in dir */
  2302. /* No-op if it's the same directory */
  2303. if (strcmp(path, newpath) == 0)
  2304. break;
  2305. oldname[0] = '\0';
  2306. } else if (truecd == 1)
  2307. /* Sure change in dir */
  2308. oldname[0] = '\0';
  2309. /* Save last working directory */
  2310. xstrlcpy(lastdir, path, PATH_MAX);
  2311. dir_changed = TRUE;
  2312. /* Save the newly opted dir in path */
  2313. xstrlcpy(path, newpath, PATH_MAX);
  2314. /* Reset filter */
  2315. copyfilter();
  2316. DPRINTF_S(path);
  2317. if (cfg.filtermode)
  2318. presel = FILTER;
  2319. goto begin;
  2320. case SEL_CDHOME:
  2321. dir = getenv("HOME");
  2322. if (dir == NULL) {
  2323. clearprompt();
  2324. goto nochange;
  2325. } // fallthrough
  2326. case SEL_CDBEGIN:
  2327. if (sel == SEL_CDBEGIN)
  2328. dir = ipath;
  2329. if (!xdiraccess(dir))
  2330. goto nochange;
  2331. if (strcmp(path, dir) == 0)
  2332. break;
  2333. /* Save last working directory */
  2334. xstrlcpy(lastdir, path, PATH_MAX);
  2335. dir_changed = TRUE;
  2336. xstrlcpy(path, dir, PATH_MAX);
  2337. oldname[0] = '\0';
  2338. /* Reset filter */
  2339. copyfilter();
  2340. DPRINTF_S(path);
  2341. if (cfg.filtermode)
  2342. presel = FILTER;
  2343. goto begin;
  2344. case SEL_CDLAST: // fallthrough
  2345. case SEL_VISIT:
  2346. if (sel == SEL_VISIT) {
  2347. if (strcmp(mark, path) == 0)
  2348. break;
  2349. tmp = mark;
  2350. } else
  2351. tmp = lastdir;
  2352. if (tmp[0] == '\0') {
  2353. printmsg("not set...");
  2354. goto nochange;
  2355. }
  2356. if (!xdiraccess(tmp))
  2357. goto nochange;
  2358. xstrlcpy(newpath, tmp, PATH_MAX);
  2359. xstrlcpy(lastdir, path, PATH_MAX);
  2360. dir_changed = TRUE;
  2361. xstrlcpy(path, newpath, PATH_MAX);
  2362. oldname[0] = '\0';
  2363. /* Reset filter */
  2364. copyfilter();
  2365. DPRINTF_S(path);
  2366. if (cfg.filtermode)
  2367. presel = FILTER;
  2368. goto begin;
  2369. case SEL_CDBM:
  2370. tmp = xreadline(NULL, "key: ");
  2371. if (tmp == NULL || tmp[0] == '\0')
  2372. break;
  2373. /* Interpret ~, - and & keys */
  2374. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2375. presel = tmp[0];
  2376. goto begin;
  2377. }
  2378. if (get_bm_loc(tmp, newpath) == NULL) {
  2379. printmsg(messages[STR_INVBM_ID]);
  2380. goto nochange;
  2381. }
  2382. if (!xdiraccess(newpath))
  2383. goto nochange;
  2384. if (strcmp(path, newpath) == 0)
  2385. break;
  2386. oldname[0] = '\0';
  2387. /* Save last working directory */
  2388. xstrlcpy(lastdir, path, PATH_MAX);
  2389. dir_changed = TRUE;
  2390. /* Save the newly opted dir in path */
  2391. xstrlcpy(path, newpath, PATH_MAX);
  2392. /* Reset filter */
  2393. copyfilter();
  2394. DPRINTF_S(path);
  2395. if (cfg.filtermode)
  2396. presel = FILTER;
  2397. goto begin;
  2398. case SEL_PIN:
  2399. xstrlcpy(mark, path, PATH_MAX);
  2400. printmsg(mark);
  2401. goto nochange;
  2402. case SEL_FLTR:
  2403. presel = filterentries(path);
  2404. copyfilter();
  2405. DPRINTF_S(fltr);
  2406. /* Save current */
  2407. if (ndents)
  2408. copycurname();
  2409. goto nochange;
  2410. case SEL_MFLTR:
  2411. cfg.filtermode ^= 1;
  2412. if (cfg.filtermode)
  2413. presel = FILTER;
  2414. else {
  2415. /* Save current */
  2416. if (ndents)
  2417. copycurname();
  2418. /* Start watching the directory */
  2419. goto begin;
  2420. }
  2421. goto nochange;
  2422. case SEL_SEARCH:
  2423. spawn(player, path, "search", NULL, F_NORMAL);
  2424. break;
  2425. case SEL_TOGGLEDOT:
  2426. cfg.showhidden ^= 1;
  2427. initfilter(cfg.showhidden, &ifilter);
  2428. copyfilter();
  2429. goto begin;
  2430. case SEL_DETAIL:
  2431. cfg.showdetail ^= 1;
  2432. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2433. /* Save current */
  2434. if (ndents)
  2435. copycurname();
  2436. goto begin;
  2437. case SEL_STATS:
  2438. if (!ndents)
  2439. break;
  2440. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2441. if (lstat(newpath, &sb) == -1) {
  2442. dentfree(dents);
  2443. errexit();
  2444. }
  2445. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2446. printwarn();
  2447. goto nochange;
  2448. }
  2449. break;
  2450. case SEL_LIST: // fallthrough
  2451. case SEL_EXTRACT: // fallthrough
  2452. case SEL_MEDIA: // fallthrough
  2453. case SEL_FMEDIA:
  2454. if (!ndents)
  2455. break;
  2456. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2457. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2458. r = show_mediainfo(newpath, run);
  2459. else
  2460. r = handle_archive(newpath, run, path);
  2461. if (r == -1) {
  2462. xstrlcpy(newpath, "missing ", PATH_MAX);
  2463. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2464. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2465. else
  2466. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2467. printmsg(newpath);
  2468. goto nochange;
  2469. }
  2470. /* In case of successful archive extract, reload contents */
  2471. if (sel == SEL_EXTRACT) {
  2472. /* Continue in navigate-as-you-type mode, if enabled */
  2473. if (cfg.filtermode)
  2474. presel = FILTER;
  2475. /* Save current */
  2476. copycurname();
  2477. /* Repopulate as directory content may have changed */
  2478. goto begin;
  2479. }
  2480. break;
  2481. case SEL_DFB:
  2482. if (!dmanager) {
  2483. printmsg("set NNN_DE_FILE_MANAGER");
  2484. goto nochange;
  2485. }
  2486. spawn(dmanager, path, NULL, path, F_NOWAIT | F_NOTRACE);
  2487. break;
  2488. case SEL_FSIZE:
  2489. cfg.sizeorder ^= 1;
  2490. cfg.mtimeorder = 0;
  2491. cfg.apparentsz = 0;
  2492. cfg.blkorder = 0;
  2493. cfg.copymode = 0;
  2494. /* Save current */
  2495. if (ndents)
  2496. copycurname();
  2497. goto begin;
  2498. case SEL_ASIZE:
  2499. cfg.apparentsz ^= 1;
  2500. if (cfg.apparentsz) {
  2501. nftw_fn = &sum_sizes;
  2502. cfg.blkorder = 1;
  2503. BLK_SHIFT = 0;
  2504. } else
  2505. cfg.blkorder = 0; // fallthrough
  2506. case SEL_BSIZE:
  2507. if (sel == SEL_BSIZE) {
  2508. if (!cfg.apparentsz)
  2509. cfg.blkorder ^= 1;
  2510. nftw_fn = &sum_bsizes;
  2511. cfg.apparentsz = 0;
  2512. BLK_SHIFT = 9;
  2513. }
  2514. if (cfg.blkorder) {
  2515. cfg.showdetail = 1;
  2516. printptr = &printent_long;
  2517. }
  2518. cfg.mtimeorder = 0;
  2519. cfg.sizeorder = 0;
  2520. cfg.copymode = 0;
  2521. /* Save current */
  2522. if (ndents)
  2523. copycurname();
  2524. goto begin;
  2525. case SEL_MTIME:
  2526. cfg.mtimeorder ^= 1;
  2527. cfg.sizeorder = 0;
  2528. cfg.apparentsz = 0;
  2529. cfg.blkorder = 0;
  2530. cfg.copymode = 0;
  2531. /* Save current */
  2532. if (ndents)
  2533. copycurname();
  2534. goto begin;
  2535. case SEL_REDRAW:
  2536. /* Save current */
  2537. if (ndents)
  2538. copycurname();
  2539. goto begin;
  2540. case SEL_COPY:
  2541. if (!(cfg.noxdisplay || copier)) {
  2542. printmsg(messages[STR_COPY_ID]);
  2543. goto nochange;
  2544. }
  2545. if (!ndents)
  2546. goto nochange;
  2547. if (cfg.copymode) {
  2548. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2549. if (!appendfpath(newpath, r))
  2550. goto nochange;
  2551. ++ncp;
  2552. printmsg(newpath);
  2553. } else if (cfg.quote) {
  2554. g_buf[0] = '\'';
  2555. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2556. g_buf[r] = '\'';
  2557. g_buf[r + 1] = '\0';
  2558. if (cfg.noxdisplay)
  2559. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2560. else
  2561. spawn(copier, g_buf, NULL, NULL, F_NOTRACE);
  2562. g_buf[r] = '\0';
  2563. printmsg(g_buf + 1);
  2564. } else {
  2565. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2566. if (cfg.noxdisplay)
  2567. writecp(newpath, r - 1); /* Truncate NULL from end */
  2568. else
  2569. spawn(copier, newpath, NULL, NULL, F_NOTRACE);
  2570. printmsg(newpath);
  2571. }
  2572. goto nochange;
  2573. case SEL_COPYMUL:
  2574. if (!(cfg.noxdisplay || copier)) {
  2575. printmsg(messages[STR_COPY_ID]);
  2576. goto nochange;
  2577. }
  2578. if (!ndents)
  2579. goto nochange;
  2580. cfg.copymode ^= 1;
  2581. if (cfg.copymode) {
  2582. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2583. copystartid = cur;
  2584. copybufpos = 0;
  2585. ncp = 0;
  2586. printmsg("multi-copy on");
  2587. DPRINTF_S("copymode on");
  2588. goto nochange;
  2589. }
  2590. if (!ncp) { /* Handle range selection */
  2591. if (cur < copystartid) {
  2592. copyendid = copystartid;
  2593. copystartid = cur;
  2594. } else
  2595. copyendid = cur;
  2596. if (copystartid < copyendid) {
  2597. for (r = copystartid; r <= copyendid; ++r)
  2598. if (!appendfpath(newpath, mkpath(path, dents[r].name, newpath, PATH_MAX)))
  2599. goto nochange;
  2600. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2601. printmsg(newpath);
  2602. }
  2603. }
  2604. if (copybufpos) { /* File path(s) written to the buffer */
  2605. if (cfg.noxdisplay)
  2606. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2607. else
  2608. spawn(copier, pcopybuf, NULL, NULL, F_NOTRACE);
  2609. if (ncp) { /* Some files cherry picked */
  2610. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2611. printmsg(newpath);
  2612. }
  2613. } else
  2614. printmsg("multi-copy off");
  2615. goto nochange;
  2616. case SEL_COPYLIST:
  2617. if (cfg.copymode)
  2618. showcplist();
  2619. else
  2620. printmsg("multi-copy off");
  2621. goto nochange;
  2622. case SEL_QUOTE:
  2623. cfg.quote ^= 1;
  2624. DPRINTF_D(cfg.quote);
  2625. if (cfg.quote)
  2626. printmsg("quotes on");
  2627. else
  2628. printmsg("quotes off");
  2629. goto nochange;
  2630. case SEL_OPEN: // fallthrough
  2631. case SEL_ARCHIVE:
  2632. if (!ndents)
  2633. break; // fallthrough
  2634. case SEL_NEW:
  2635. if (sel == SEL_OPEN)
  2636. tmp = xreadline(NULL, "open with: ");
  2637. else if (sel == SEL_ARCHIVE)
  2638. tmp = xreadline(dents[cur].name, "name: ");
  2639. else
  2640. tmp = xreadline(NULL, "name: ");
  2641. if (tmp == NULL || tmp[0] == '\0')
  2642. break;
  2643. /* Allow only relative, same dir paths */
  2644. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2645. printmsg(messages[STR_INPUT_ID]);
  2646. goto nochange;
  2647. }
  2648. if (sel == SEL_OPEN) {
  2649. printprompt("press 'c' for cli mode");
  2650. cleartimeout();
  2651. r = getch();
  2652. settimeout();
  2653. if (r == 'c')
  2654. r = F_NORMAL;
  2655. else
  2656. r = F_NOWAIT | F_NOTRACE;
  2657. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2658. spawn(tmp, newpath, NULL, path, r);
  2659. continue;
  2660. } else if (sel == SEL_ARCHIVE) {
  2661. /* newpath is used as temporary buffer */
  2662. if (!get_output(newpath, PATH_MAX, "which", utils[APACK], NULL, 0)) {
  2663. printmsg("apack missing");
  2664. continue;
  2665. }
  2666. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2667. /* Continue in navigate-as-you-type mode, if enabled */
  2668. if (cfg.filtermode)
  2669. presel = FILTER;
  2670. /* Save current */
  2671. copycurname();
  2672. /* Repopulate as directory content may have changed */
  2673. goto begin;
  2674. }
  2675. /* Open the descriptor to currently open directory */
  2676. fd = open(path, O_RDONLY | O_DIRECTORY);
  2677. if (fd == -1) {
  2678. printwarn();
  2679. goto nochange;
  2680. }
  2681. /* Check if another file with same name exists */
  2682. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2683. printmsg("entry exists");
  2684. goto nochange;
  2685. }
  2686. /* Check if it's a dir or file */
  2687. printprompt("press 'f'(ile) or 'd'(ir)");
  2688. cleartimeout();
  2689. r = getch();
  2690. settimeout();
  2691. if (r == 'f') {
  2692. r = openat(fd, tmp, O_CREAT, 0666);
  2693. close(r);
  2694. } else if (r == 'd')
  2695. r = mkdirat(fd, tmp, 0777);
  2696. else {
  2697. close(fd);
  2698. break;
  2699. }
  2700. if (r == -1) {
  2701. printwarn();
  2702. close(fd);
  2703. goto nochange;
  2704. }
  2705. close(fd);
  2706. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2707. goto begin;
  2708. case SEL_RENAME:
  2709. if (!ndents)
  2710. break;
  2711. tmp = xreadline(dents[cur].name, "");
  2712. if (tmp == NULL || tmp[0] == '\0')
  2713. break;
  2714. /* Allow only relative, same dir paths */
  2715. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2716. printmsg(messages[STR_INPUT_ID]);
  2717. goto nochange;
  2718. }
  2719. /* Skip renaming to same name */
  2720. if (strcmp(tmp, dents[cur].name) == 0)
  2721. break;
  2722. /* Open the descriptor to currently open directory */
  2723. fd = open(path, O_RDONLY | O_DIRECTORY);
  2724. if (fd == -1) {
  2725. printwarn();
  2726. goto nochange;
  2727. }
  2728. /* Check if another file with same name exists */
  2729. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2730. /* File with the same name exists */
  2731. printprompt("press 'y' to overwrite");
  2732. cleartimeout();
  2733. r = getch();
  2734. settimeout();
  2735. if (r != 'y') {
  2736. close(fd);
  2737. break;
  2738. }
  2739. }
  2740. /* Rename the file */
  2741. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2742. printwarn();
  2743. close(fd);
  2744. goto nochange;
  2745. }
  2746. close(fd);
  2747. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2748. goto begin;
  2749. case SEL_RENAMEALL:
  2750. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2751. printmsg("vidir missing");
  2752. goto nochange;
  2753. }
  2754. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2755. /* Save current */
  2756. if (ndents)
  2757. copycurname();
  2758. goto begin;
  2759. case SEL_HELP:
  2760. show_help(path);
  2761. /* Continue in navigate-as-you-type mode, if enabled */
  2762. if (cfg.filtermode)
  2763. presel = FILTER;
  2764. break;
  2765. case SEL_RUN: // fallthrough
  2766. case SEL_RUNSCRIPT:
  2767. run = xgetenv(env, run);
  2768. if (sel == SEL_RUNSCRIPT) {
  2769. tmp = getenv("NNN_SCRIPT");
  2770. if (tmp) {
  2771. if (getenv("NNN_MULTISCRIPT")) {
  2772. size_t _len = xstrlcpy(newpath, tmp, PATH_MAX);
  2773. tmp = xreadline(NULL, "script suffix: ");
  2774. if (tmp && tmp[0])
  2775. xstrlcpy(newpath + _len - 1, tmp, PATH_MAX - _len);
  2776. tmp = newpath;
  2777. }
  2778. char *curfile = NULL;
  2779. if (ndents)
  2780. curfile = dents[cur].name;
  2781. spawn(run, tmp, curfile, path, F_NORMAL | F_SIGINT);
  2782. } else
  2783. printmsg("set NNN_SCRIPT");
  2784. } else {
  2785. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2786. /* Continue in navigate-as-you-type mode, if enabled */
  2787. if (cfg.filtermode)
  2788. presel = FILTER;
  2789. }
  2790. /* Save current */
  2791. if (ndents)
  2792. copycurname();
  2793. /* Repopulate as directory content may have changed */
  2794. goto begin;
  2795. case SEL_RUNARG:
  2796. run = xgetenv(env, run);
  2797. if ((!run || !run[0]) && (strcmp("VISUAL", env) == 0))
  2798. run = editor ? editor : xgetenv("EDITOR", "vi");
  2799. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2800. break;
  2801. case SEL_LOCK:
  2802. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2803. break;
  2804. case SEL_CDQUIT:
  2805. {
  2806. tmp = getenv("NNN_TMPFILE");
  2807. if (!tmp) {
  2808. printmsg("set NNN_TMPFILE");
  2809. goto nochange;
  2810. }
  2811. FILE *fp = fopen(tmp, "w");
  2812. if (fp) {
  2813. fprintf(fp, "cd \"%s\"", path);
  2814. fclose(fp);
  2815. }
  2816. /* Fall through to exit */
  2817. } // fallthrough
  2818. case SEL_QUIT:
  2819. dentfree(dents);
  2820. return;
  2821. } /* switch (sel) */
  2822. /* Screensaver */
  2823. if (idletimeout != 0 && idle == idletimeout) {
  2824. idle = 0;
  2825. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2826. }
  2827. }
  2828. }
  2829. static void usage(void)
  2830. {
  2831. fprintf(stdout,
  2832. "usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n"
  2833. " [-p nlay] [-S] [-v] [-h] [PATH]\n\n"
  2834. "The missing terminal file manager for X.\n\n"
  2835. "positional args:\n"
  2836. " PATH start dir [default: current dir]\n\n"
  2837. "optional args:\n"
  2838. " -b key bookmark key to open\n"
  2839. " -c N dir color, disables if N>7\n"
  2840. " -e use exiftool instead of mediainfo\n"
  2841. " -i start in navigate-as-you-type mode\n"
  2842. " -l start in light mode\n"
  2843. " -p nlay path to custom nlay\n"
  2844. " -S start in disk usage analyser mode\n"
  2845. " -v show program version\n"
  2846. " -h show this help\n\n"
  2847. "Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2848. exit(0);
  2849. }
  2850. int main(int argc, char *argv[])
  2851. {
  2852. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2853. char *ipath = NULL, *ifilter;
  2854. int opt;
  2855. /* Confirm we are in a terminal */
  2856. if (!isatty(0) || !isatty(1)) {
  2857. fprintf(stderr, "stdin or stdout is not a tty\n");
  2858. exit(1);
  2859. }
  2860. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2861. switch (opt) {
  2862. case 'S':
  2863. cfg.blkorder = 1;
  2864. nftw_fn = sum_bsizes;
  2865. break;
  2866. case 'l':
  2867. cfg.showdetail = 0;
  2868. printptr = &printent;
  2869. break;
  2870. case 'i':
  2871. cfg.filtermode = 1;
  2872. break;
  2873. case 'b':
  2874. ipath = optarg;
  2875. break;
  2876. case 'c':
  2877. if (atoi(optarg) > 7)
  2878. cfg.showcolor = 0;
  2879. else
  2880. cfg.color = (uchar)atoi(optarg);
  2881. break;
  2882. case 'e':
  2883. cfg.metaviewer = EXIFTOOL;
  2884. break;
  2885. case 'p':
  2886. player = optarg;
  2887. break;
  2888. case 'v':
  2889. fprintf(stdout, "%s\n", VERSION);
  2890. return 0;
  2891. case 'h': // fallthrough
  2892. default:
  2893. usage();
  2894. }
  2895. }
  2896. /* Parse bookmarks string */
  2897. parsebmstr();
  2898. if (ipath) { /* Open a bookmark directly */
  2899. if (get_bm_loc(ipath, cwd) == NULL) {
  2900. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2901. exit(1);
  2902. }
  2903. ipath = cwd;
  2904. } else if (argc == optind) {
  2905. /* Start in the current directory */
  2906. ipath = getcwd(cwd, PATH_MAX);
  2907. if (ipath == NULL)
  2908. ipath = "/";
  2909. } else {
  2910. ipath = realpath(argv[optind], cwd);
  2911. if (!ipath) {
  2912. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2913. exit(1);
  2914. }
  2915. }
  2916. /* Increase current open file descriptor limit */
  2917. open_max = max_openfds();
  2918. if (getuid() == 0 || getenv("NNN_SHOW_HIDDEN"))
  2919. cfg.showhidden = 1;
  2920. initfilter(cfg.showhidden, &ifilter);
  2921. #ifdef LINUX_INOTIFY
  2922. /* Initialize inotify */
  2923. inotify_fd = inotify_init1(IN_NONBLOCK);
  2924. if (inotify_fd < 0) {
  2925. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2926. exit(1);
  2927. }
  2928. #elif defined(BSD_KQUEUE)
  2929. kq = kqueue();
  2930. if (kq < 0) {
  2931. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2932. exit(1);
  2933. }
  2934. #endif
  2935. /* Edit text in EDITOR, if opted */
  2936. if (getenv("NNN_USE_EDITOR")) {
  2937. editor = xgetenv("VISUAL", NULL);
  2938. if (!editor)
  2939. editor = xgetenv("EDITOR", "vi");
  2940. }
  2941. /* Set player if not set already */
  2942. if (!player)
  2943. player = utils[NLAY];
  2944. /* Get the desktop file manager, if set */
  2945. dmanager = getenv("NNN_DE_FILE_MANAGER");
  2946. /* Get screensaver wait time, if set; copier used as tmp var */
  2947. copier = getenv("NNN_IDLE_TIMEOUT");
  2948. if (copier) {
  2949. opt = atoi(copier);
  2950. idletimeout = opt * ((opt > 0) - (opt < 0));
  2951. }
  2952. /* Get the default copier, if set */
  2953. copier = getenv("NNN_COPIER");
  2954. /* Enable quotes if opted */
  2955. if (getenv("NNN_QUOTE_ON"))
  2956. cfg.quote = 1;
  2957. if (getenv("HOME"))
  2958. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("HOME"), MAX_HOME_LEN);
  2959. else if (getenv("TMPDIR"))
  2960. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("TMPDIR"), MAX_HOME_LEN);
  2961. else if (xdiraccess("/tmp"))
  2962. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", MAX_HOME_LEN);
  2963. /* Check if X11 is available */
  2964. if (!copier && g_tmpfplen && getenv("NNN_NO_X")) {
  2965. cfg.noxdisplay = 1;
  2966. xstrlcpy(g_cppath, g_tmpfpath, MAX_HOME_LEN);
  2967. xstrlcpy(g_cppath + g_tmpfplen - 1, "/.nnncp", MAX_HOME_LEN - g_tmpfplen);
  2968. }
  2969. /* Disable auto-select if opted */
  2970. if (getenv("NNN_NO_AUTOSELECT"))
  2971. cfg.autoselect = 0;
  2972. signal(SIGINT, SIG_IGN);
  2973. /* Test initial path */
  2974. if (!xdiraccess(ipath)) {
  2975. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2976. exit(1);
  2977. }
  2978. /* Set locale */
  2979. setlocale(LC_ALL, "");
  2980. crc8init();
  2981. #ifdef DEBUGMODE
  2982. enabledbg();
  2983. #endif
  2984. initcurses();
  2985. browse(ipath, ifilter);
  2986. exitcurses();
  2987. if (cfg.noxdisplay && g_cppath[0])
  2988. unlink(g_cppath);
  2989. #ifdef LINUX_INOTIFY
  2990. /* Shutdown inotify */
  2991. if (inotify_wd >= 0)
  2992. inotify_rm_watch(inotify_fd, inotify_wd);
  2993. close(inotify_fd);
  2994. #elif defined(BSD_KQUEUE)
  2995. if (event_fd >= 0)
  2996. close(event_fd);
  2997. close(kq);
  2998. #endif
  2999. #ifdef DEBUGMODE
  3000. disabledbg();
  3001. #endif
  3002. exit(0);
  3003. }