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.
 
 
 
 
 
 

2990 wiersze
62 KiB

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