My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

3537 rindas
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 && pcur)
  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. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE || *ch == '\b') {
  927. if (len == 1) {
  928. cur = oldcur;
  929. *ch = CONTROL('L');
  930. goto end;
  931. }
  932. wln[--len] = '\0';
  933. if (len == 1)
  934. cur = oldcur;
  935. wcstombs(ln, wln, REGEX_MAX);
  936. ndents = total;
  937. if (matches(pln) != -1)
  938. redraw(path);
  939. printprompt(ln);
  940. continue;
  941. }
  942. if (*ch == 27) { /* Exit filter mode on Escape */
  943. cur = oldcur;
  944. *ch = CONTROL('L');
  945. goto end;
  946. }
  947. if (r == OK) {
  948. /* Handle all control chars in main loop */
  949. if (keyname(*ch)[0] == '^') {
  950. if (len == 1)
  951. cur = oldcur;
  952. goto end;
  953. }
  954. switch (*ch) {
  955. case '\r': // with nonl(), this is ENTER key value
  956. if (len == 1) {
  957. cur = oldcur;
  958. goto end;
  959. }
  960. if (matches(pln) == -1)
  961. goto end;
  962. redraw(path);
  963. goto end;
  964. case '?': // '?' is an invalid regex, show help instead
  965. if (len == 1) {
  966. cur = oldcur;
  967. goto end;
  968. } // fallthrough
  969. default:
  970. /* Reset cur in case it's a repeat search */
  971. if (len == 1)
  972. cur = 0;
  973. if (len == REGEX_MAX - 1)
  974. break;
  975. wln[len] = (wchar_t)*ch;
  976. wln[++len] = '\0';
  977. wcstombs(ln, wln, REGEX_MAX);
  978. /* Forward-filtering optimization:
  979. * - new matches can only be a subset of current matches.
  980. */
  981. /* ndents = total; */
  982. if (matches(pln) == -1)
  983. continue;
  984. /* If the only match is a dir, auto-select and cd into it */
  985. if (ndents == 1 && cfg.filtermode && cfg.autoselect && S_ISDIR(dents[0].mode)) {
  986. *ch = KEY_ENTER;
  987. cur = 0;
  988. goto end;
  989. }
  990. /*
  991. * redraw() should be above the auto-select optimization, for
  992. * the case where there's an issue with dir auto-select, say,
  993. * due to a permission problem. The transition is jumpy in
  994. * case of such an error. However, we optimize for successful
  995. * cases where the dir has permissions. This skips a redraw().
  996. */
  997. redraw(path);
  998. printprompt(ln);
  999. }
  1000. } else {
  1001. if (len == 1)
  1002. cur = oldcur;
  1003. goto end;
  1004. }
  1005. }
  1006. end:
  1007. curs_set(FALSE);
  1008. settimeout();
  1009. /* Return keys for navigation etc. */
  1010. return *ch;
  1011. }
  1012. /* Show a prompt with input string and return the changes */
  1013. static char *xreadline(char *fname, char *prompt)
  1014. {
  1015. size_t len, pos;
  1016. int x, y, r;
  1017. wint_t ch[2] = {0};
  1018. static wchar_t * const buf = (wchar_t *)g_buf;
  1019. printprompt(prompt);
  1020. if (fname) {
  1021. DPRINTF_S(fname);
  1022. len = pos = mbstowcs(buf, fname, NAME_MAX);
  1023. } else
  1024. len = (size_t)-1;
  1025. if (len == (size_t)-1) {
  1026. buf[0] = '\0';
  1027. len = pos = 0;
  1028. }
  1029. getyx(stdscr, y, x);
  1030. curs_set(TRUE);
  1031. cleartimeout();
  1032. while (1) {
  1033. buf[len] = ' ';
  1034. mvaddnwstr(y, x, buf, len + 1);
  1035. move(y, x + wcswidth(buf, pos));
  1036. r = get_wch(ch);
  1037. if (r != ERR) {
  1038. if (r == OK) {
  1039. switch (*ch) {
  1040. case KEY_ENTER: //fallthrough
  1041. case '\n': //fallthrough
  1042. case '\r':
  1043. goto END;
  1044. case '\b': /* some old curses (e.g. rhel25) still send '\b' for backspace */
  1045. if (pos > 0) {
  1046. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1047. --len, --pos;
  1048. } //fallthrough
  1049. case '\t': /* TAB breaks cursor position, ignore it */
  1050. continue;
  1051. case CONTROL('L'):
  1052. clearprompt();
  1053. printprompt(prompt);
  1054. len = pos = 0;
  1055. continue;
  1056. case CONTROL('A'):
  1057. pos = 0;
  1058. continue;
  1059. case CONTROL('E'):
  1060. pos = len;
  1061. continue;
  1062. case CONTROL('U'):
  1063. clearprompt();
  1064. printprompt(prompt);
  1065. memmove(buf, buf + pos, (len - pos) << 2);
  1066. len -= pos;
  1067. pos = 0;
  1068. continue;
  1069. case 27: /* Exit prompt on Escape */
  1070. len = 0;
  1071. goto END;
  1072. }
  1073. /* Filter out all other control chars */
  1074. if (keyname(*ch)[0] == '^')
  1075. continue;
  1076. if (pos < NAME_MAX - 1) {
  1077. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1078. buf[pos] = *ch;
  1079. ++len, ++pos;
  1080. continue;
  1081. }
  1082. } else {
  1083. switch (*ch) {
  1084. case KEY_LEFT:
  1085. if (pos > 0)
  1086. --pos;
  1087. break;
  1088. case KEY_RIGHT:
  1089. if (pos < len)
  1090. ++pos;
  1091. break;
  1092. case KEY_BACKSPACE:
  1093. if (pos > 0) {
  1094. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1095. --len, --pos;
  1096. }
  1097. break;
  1098. case KEY_DC:
  1099. if (pos < len) {
  1100. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1101. --len;
  1102. }
  1103. break;
  1104. default:
  1105. break;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. END:
  1111. buf[len] = '\0';
  1112. curs_set(FALSE);
  1113. settimeout();
  1114. DPRINTF_S(buf);
  1115. wcstombs(g_buf, buf, NAME_MAX);
  1116. clearprompt();
  1117. return g_buf;
  1118. }
  1119. /*
  1120. * Updates out with "dir/name or "/name"
  1121. * Returns the number of bytes copied including the terminating NULL byte
  1122. */
  1123. static size_t mkpath(char *dir, char *name, char *out, size_t n)
  1124. {
  1125. static size_t len;
  1126. /* Handle absolute path */
  1127. if (name[0] == '/')
  1128. return xstrlcpy(out, name, n);
  1129. /* Handle root case */
  1130. if (istopdir(dir))
  1131. len = 1;
  1132. else
  1133. len = xstrlcpy(out, dir, n);
  1134. out[len - 1] = '/';
  1135. return (xstrlcpy(out + len, name, n - len) + len);
  1136. }
  1137. static void parsebmstr()
  1138. {
  1139. int i = 0;
  1140. char *bms = getenv("NNN_BMS");
  1141. if (!bms)
  1142. return;
  1143. while (*bms && i < BM_MAX) {
  1144. bookmark[i].key = bms;
  1145. ++bms;
  1146. while (*bms && *bms != ':')
  1147. ++bms;
  1148. if (!*bms) {
  1149. bookmark[i].key = NULL;
  1150. break;
  1151. }
  1152. *bms = '\0';
  1153. bookmark[i].loc = ++bms;
  1154. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1155. bookmark[i].key = NULL;
  1156. break;
  1157. }
  1158. while (*bms && *bms != ';')
  1159. ++bms;
  1160. if (*bms)
  1161. *bms = '\0';
  1162. else
  1163. break;
  1164. ++bms;
  1165. ++i;
  1166. }
  1167. }
  1168. /*
  1169. * Get the real path to a bookmark
  1170. *
  1171. * NULL is returned in case of no match, path resolution failure etc.
  1172. * buf would be modified, so check return value before access
  1173. */
  1174. static char *get_bm_loc(char *key, char *buf)
  1175. {
  1176. int r;
  1177. if (!key || !key[0])
  1178. return NULL;
  1179. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1180. if (strcmp(bookmark[r].key, key) == 0) {
  1181. if (bookmark[r].loc[0] == '~') {
  1182. char *home = getenv("HOME");
  1183. if (!home) {
  1184. DPRINTF_S(messages[STR_NOHOME_ID]);
  1185. return NULL;
  1186. }
  1187. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1188. } else
  1189. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1190. return buf;
  1191. }
  1192. }
  1193. DPRINTF_S("Invalid key");
  1194. return NULL;
  1195. }
  1196. static void resetdircolor(mode_t mode)
  1197. {
  1198. if (cfg.dircolor && !S_ISDIR(mode)) {
  1199. attroff(COLOR_PAIR(1) | A_BOLD);
  1200. cfg.dircolor = 0;
  1201. }
  1202. }
  1203. /*
  1204. * Replace escape characters in a string with '?'
  1205. * Adjust string length to maxcols if > 0;
  1206. *
  1207. * Interestingly, note that unescape() uses g_buf. What happens if
  1208. * str also points to g_buf? In this case we assume that the caller
  1209. * acknowledges that it's OK to lose the data in g_buf after this
  1210. * call to unescape().
  1211. * The API, on its part, first converts str to multibyte (after which
  1212. * it doesn't touch str anymore). Only after that it starts modifying
  1213. * g_buf. This is a phased operation.
  1214. */
  1215. static char *unescape(const char *str, uint maxcols)
  1216. {
  1217. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1218. static wchar_t *buf;
  1219. static size_t len;
  1220. /* Convert multi-byte to wide char */
  1221. len = mbstowcs(wbuf, str, PATH_MAX);
  1222. g_buf[0] = '\0';
  1223. buf = wbuf;
  1224. if (maxcols && len > maxcols) {
  1225. len = wcswidth(wbuf, len);
  1226. if (len > maxcols)
  1227. wbuf[maxcols] = 0;
  1228. }
  1229. while (*buf) {
  1230. if (*buf <= '\x1f' || *buf == '\x7f')
  1231. *buf = '\?';
  1232. ++buf;
  1233. }
  1234. /* Convert wide char to multi-byte */
  1235. wcstombs(g_buf, wbuf, PATH_MAX);
  1236. return g_buf;
  1237. }
  1238. static char *coolsize(off_t size)
  1239. {
  1240. static const char * const U = "BKMGTPEZY";
  1241. static char size_buf[12]; /* Buffer to hold human readable size */
  1242. static off_t rem;
  1243. static int i;
  1244. i = 0;
  1245. rem = 0;
  1246. while (size > 1024) {
  1247. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1248. size >>= 10;
  1249. ++i;
  1250. }
  1251. if (i == 1) {
  1252. rem = (rem * 1000) >> 10;
  1253. rem /= 10;
  1254. if (rem % 10 >= 5) {
  1255. rem = (rem / 10) + 1;
  1256. if (rem == 10) {
  1257. ++size;
  1258. rem = 0;
  1259. }
  1260. } else
  1261. rem /= 10;
  1262. } else if (i == 2) {
  1263. rem = (rem * 1000) >> 10;
  1264. if (rem % 10 >= 5) {
  1265. rem = (rem / 10) + 1;
  1266. if (rem == 100) {
  1267. ++size;
  1268. rem = 0;
  1269. }
  1270. } else
  1271. rem /= 10;
  1272. } else if (i > 0) {
  1273. rem = (rem * 10000) >> 10;
  1274. if (rem % 10 >= 5) {
  1275. rem = (rem / 10) + 1;
  1276. if (rem == 1000) {
  1277. ++size;
  1278. rem = 0;
  1279. }
  1280. } else
  1281. rem /= 10;
  1282. }
  1283. if (i > 0)
  1284. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1285. else
  1286. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1287. return size_buf;
  1288. }
  1289. static char *get_file_sym(mode_t mode)
  1290. {
  1291. static char ind[2] = "\0\0";
  1292. if (S_ISDIR(mode))
  1293. ind[0] = '/';
  1294. else if (S_ISLNK(mode))
  1295. ind[0] = '@';
  1296. else if (S_ISSOCK(mode))
  1297. ind[0] = '=';
  1298. else if (S_ISFIFO(mode))
  1299. ind[0] = '|';
  1300. else if (mode & 0100)
  1301. ind[0] = '*';
  1302. else
  1303. ind[0] = '\0';
  1304. return ind;
  1305. }
  1306. static void printent(struct entry *ent, int sel, uint namecols)
  1307. {
  1308. static char *pname;
  1309. pname = unescape(ent->name, namecols);
  1310. /* Directories are always shown on top */
  1311. resetdircolor(ent->mode);
  1312. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1313. }
  1314. static void printent_long(struct entry *ent, int sel, uint namecols)
  1315. {
  1316. static char buf[18], *pname;
  1317. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1318. pname = unescape(ent->name, namecols);
  1319. /* Directories are always shown on top */
  1320. resetdircolor(ent->mode);
  1321. if (sel)
  1322. attron(A_REVERSE);
  1323. if (S_ISDIR(ent->mode)) {
  1324. if (cfg.blkorder)
  1325. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1326. else
  1327. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1328. } else if (S_ISLNK(ent->mode)) {
  1329. if (ent->flags & SYMLINK_TO_DIR)
  1330. printw("%s%-16.16s @/ %s@\n", CURSYM(sel), buf, pname);
  1331. else
  1332. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1333. } else if (S_ISSOCK(ent->mode))
  1334. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1335. else if (S_ISFIFO(ent->mode))
  1336. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1337. else if (S_ISBLK(ent->mode))
  1338. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1339. else if (S_ISCHR(ent->mode))
  1340. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1341. else if (ent->mode & 0100) {
  1342. if (cfg.blkorder)
  1343. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1344. else
  1345. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1346. } else {
  1347. if (cfg.blkorder)
  1348. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << BLK_SHIFT), pname);
  1349. else
  1350. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1351. }
  1352. if (sel)
  1353. attroff(A_REVERSE);
  1354. }
  1355. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1356. static char get_fileind(mode_t mode, char *desc)
  1357. {
  1358. static char c;
  1359. if (S_ISREG(mode)) {
  1360. c = '-';
  1361. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1362. if (mode & 0100)
  1363. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1364. } else if (S_ISDIR(mode)) {
  1365. c = 'd';
  1366. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1367. } else if (S_ISBLK(mode)) {
  1368. c = 'b';
  1369. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1370. } else if (S_ISCHR(mode)) {
  1371. c = 'c';
  1372. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1373. #ifdef S_ISFIFO
  1374. } else if (S_ISFIFO(mode)) {
  1375. c = 'p';
  1376. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1377. #endif /* S_ISFIFO */
  1378. #ifdef S_ISLNK
  1379. } else if (S_ISLNK(mode)) {
  1380. c = 'l';
  1381. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1382. #endif /* S_ISLNK */
  1383. #ifdef S_ISSOCK
  1384. } else if (S_ISSOCK(mode)) {
  1385. c = 's';
  1386. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1387. #endif /* S_ISSOCK */
  1388. #ifdef S_ISDOOR
  1389. /* Solaris 2.6, etc. */
  1390. } else if (S_ISDOOR(mode)) {
  1391. c = 'D';
  1392. desc[0] = '\0';
  1393. #endif /* S_ISDOOR */
  1394. } else {
  1395. /* Unknown type -- possibly a regular file? */
  1396. c = '?';
  1397. desc[0] = '\0';
  1398. }
  1399. return c;
  1400. }
  1401. /* Convert a mode field into "ls -l" type perms field. */
  1402. static char *get_lsperms(mode_t mode, char *desc)
  1403. {
  1404. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1405. static char bits[11] = {'\0'};
  1406. bits[0] = get_fileind(mode, desc);
  1407. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1408. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1409. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1410. if (mode & S_ISUID)
  1411. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1412. if (mode & S_ISGID)
  1413. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1414. if (mode & S_ISVTX)
  1415. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1416. return bits;
  1417. }
  1418. /*
  1419. * Gets only a single line (that's what we need
  1420. * for now) or shows full command output in pager.
  1421. *
  1422. * If pager is valid, returns NULL
  1423. */
  1424. static char *get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1425. {
  1426. pid_t pid;
  1427. int pipefd[2];
  1428. FILE *pf;
  1429. int tmp, flags;
  1430. char *ret = NULL;
  1431. if (pipe(pipefd) == -1)
  1432. errexit();
  1433. for (tmp = 0; tmp < 2; ++tmp) {
  1434. /* Get previous flags */
  1435. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1436. /* Set bit for non-blocking flag */
  1437. flags |= O_NONBLOCK;
  1438. /* Change flags on fd */
  1439. fcntl(pipefd[tmp], F_SETFL, flags);
  1440. }
  1441. pid = fork();
  1442. if (pid == 0) {
  1443. /* In child */
  1444. close(pipefd[0]);
  1445. dup2(pipefd[1], STDOUT_FILENO);
  1446. dup2(pipefd[1], STDERR_FILENO);
  1447. close(pipefd[1]);
  1448. execlp(file, file, arg1, arg2, NULL);
  1449. _exit(1);
  1450. }
  1451. /* In parent */
  1452. waitpid(pid, &tmp, 0);
  1453. close(pipefd[1]);
  1454. if (!pager) {
  1455. pf = fdopen(pipefd[0], "r");
  1456. if (pf) {
  1457. ret = fgets(buf, bytes, pf);
  1458. close(pipefd[0]);
  1459. }
  1460. return ret;
  1461. }
  1462. pid = fork();
  1463. if (pid == 0) {
  1464. /* Show in pager in child */
  1465. dup2(pipefd[0], STDIN_FILENO);
  1466. close(pipefd[0]);
  1467. execlp("less", "less", NULL);
  1468. _exit(1);
  1469. }
  1470. /* In parent */
  1471. waitpid(pid, &tmp, 0);
  1472. close(pipefd[0]);
  1473. return NULL;
  1474. }
  1475. static char *xgetpwuid(uid_t uid)
  1476. {
  1477. struct passwd *pwd = getpwuid(uid);
  1478. if (!pwd)
  1479. return utils[UNKNOWN];
  1480. return pwd->pw_name;
  1481. }
  1482. static char *xgetgrgid(gid_t gid)
  1483. {
  1484. struct group *grp = getgrgid(gid);
  1485. if (!grp)
  1486. return utils[UNKNOWN];
  1487. return grp->gr_name;
  1488. }
  1489. /*
  1490. * Follows the stat(1) output closely
  1491. */
  1492. static int show_stats(char *fpath, char *fname, struct stat *sb)
  1493. {
  1494. char desc[DESCRIPTOR_LEN];
  1495. char *perms = get_lsperms(sb->st_mode, desc);
  1496. char *p, *begin = g_buf;
  1497. if (g_tmpfpath[0])
  1498. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  1499. else {
  1500. printmsg(messages[STR_NOHOME_ID]);
  1501. return -1;
  1502. }
  1503. int fd = mkstemp(g_tmpfpath);
  1504. if (fd == -1)
  1505. return -1;
  1506. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1507. /* Show file name or 'symlink' -> 'target' */
  1508. if (perms[0] == 'l') {
  1509. /* Note that MAX_CMD_LEN > PATH_MAX */
  1510. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1511. if (len != -1) {
  1512. struct stat tgtsb;
  1513. if (!stat(fpath, &tgtsb) && S_ISDIR(tgtsb.st_mode))
  1514. g_buf[len++] = '/';
  1515. g_buf[len] = '\0';
  1516. /*
  1517. * We pass g_buf but unescape() operates on g_buf too!
  1518. * Read the API notes for information on how this works.
  1519. */
  1520. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1521. }
  1522. }
  1523. /* Show size, blocks, file type */
  1524. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1525. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1526. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1527. #else
  1528. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1529. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1530. #endif
  1531. /* Show containing device, inode, hardlink count */
  1532. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1533. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1534. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1535. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1536. #else
  1537. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1538. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1539. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1540. #endif
  1541. /* Show major, minor number for block or char device */
  1542. if (perms[0] == 'b' || perms[0] == 'c')
  1543. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1544. /* Show permissions, owner, group */
  1545. 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,
  1546. sb->st_mode & 7, perms, sb->st_uid, xgetpwuid(sb->st_uid), sb->st_gid, xgetgrgid(sb->st_gid));
  1547. /* Show last access time */
  1548. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1549. dprintf(fd, "\n\n Access: %s", g_buf);
  1550. /* Show last modification time */
  1551. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1552. dprintf(fd, "\n Modify: %s", g_buf);
  1553. /* Show last status change time */
  1554. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1555. dprintf(fd, "\n Change: %s", g_buf);
  1556. if (S_ISREG(sb->st_mode)) {
  1557. /* Show file(1) output */
  1558. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1559. if (p) {
  1560. dprintf(fd, "\n\n ");
  1561. while (*p) {
  1562. if (*p == ',') {
  1563. *p = '\0';
  1564. dprintf(fd, " %s\n", begin);
  1565. begin = p + 1;
  1566. }
  1567. ++p;
  1568. }
  1569. dprintf(fd, " %s", begin);
  1570. }
  1571. dprintf(fd, "\n\n");
  1572. } else
  1573. dprintf(fd, "\n\n\n");
  1574. close(fd);
  1575. exitcurses();
  1576. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  1577. unlink(g_tmpfpath);
  1578. refresh();
  1579. return 0;
  1580. }
  1581. static size_t get_fs_info(const char *path, bool type)
  1582. {
  1583. static struct statvfs svb;
  1584. if (statvfs(path, &svb) == -1)
  1585. return 0;
  1586. if (type == CAPACITY)
  1587. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1588. else
  1589. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1590. }
  1591. static int show_mediainfo(char *fpath, char *arg)
  1592. {
  1593. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1594. return -1;
  1595. exitcurses();
  1596. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1597. refresh();
  1598. return 0;
  1599. }
  1600. static int handle_archive(char *fpath, char *arg, char *dir)
  1601. {
  1602. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1603. return -1;
  1604. if (arg[1] == 'x')
  1605. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1606. else {
  1607. exitcurses();
  1608. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1609. refresh();
  1610. }
  1611. return 0;
  1612. }
  1613. /*
  1614. * The help string tokens (each line) start with a HEX value
  1615. * which indicates the number of spaces to print before the
  1616. * particular token. This method was chosen instead of a flat
  1617. * string because the number of bytes in help was increasing
  1618. * the binary size by around a hundred bytes. This would only
  1619. * have increased as we keep adding new options.
  1620. */
  1621. static int show_help(char *path)
  1622. {
  1623. if (g_tmpfpath[0])
  1624. xstrlcpy(g_tmpfpath + g_tmpfplen - 1, "/.nnnXXXXXX", MAX_HOME_LEN - g_tmpfplen);
  1625. else {
  1626. printmsg(messages[STR_NOHOME_ID]);
  1627. return -1;
  1628. }
  1629. int i = 0, fd = mkstemp(g_tmpfpath);
  1630. char *start, *end;
  1631. static char helpstr[] = {
  1632. "cKey Desc\n"
  1633. "e----\n"
  1634. "7↑, k, ^P Up\n"
  1635. "7↓, j, ^N Down\n"
  1636. "7PgUp, ^U Scroll up\n"
  1637. "7PgDn, ^D Scroll down\n"
  1638. "1Home, g, ^, ^A First entry\n"
  1639. "2End, G, $, ^E Last entry\n"
  1640. "4→, ↵, l, ^M Open file/enter dir\n"
  1641. "1←, Bksp, h, ^H Parent dir\n"
  1642. "d^O Open with...\n"
  1643. "5Insert, ^I Toggle nav-as-you-type\n"
  1644. "e~ Go HOME\n"
  1645. "e& Start dir\n"
  1646. "e- Last visited dir\n"
  1647. "e/ Filter entries\n"
  1648. "e. Toggle show hidden\n"
  1649. "d^B Bookmark prompt\n"
  1650. "eb Pin current dir\n"
  1651. "d^V Go to pinned dir\n"
  1652. "ec cd prompt\n"
  1653. "ed Toggle detail view\n"
  1654. "eD File details\n"
  1655. "bm, M Brief/full media info\n"
  1656. "en Create new\n"
  1657. "d^R Rename entry\n"
  1658. "er Open dir in vidir\n"
  1659. "es Toggle sort by size\n"
  1660. "eS Toggle apparent size\n"
  1661. "d^J Toggle du mode\n"
  1662. "et Toggle sort by mtime\n"
  1663. "a!, ^] Spawn SHELL in dir\n"
  1664. "eR Run custom script\n"
  1665. "ee Edit in EDITOR\n"
  1666. "ep Open in PAGER\n"
  1667. "ef Archive entry\n"
  1668. "eF List archive\n"
  1669. "d^F Extract archive\n"
  1670. "6Space, ^K Copy file path\n"
  1671. "d^Y Toggle multi-copy\n"
  1672. "ey Show copy buffer\n"
  1673. "d^T Toggle path quote\n"
  1674. "d^L Redraw, clear prompt\n"
  1675. "cEsc Exit prompt\n"
  1676. "eL Lock terminal\n"
  1677. "eo Open DE filemanager\n"
  1678. "d^/ Open DE search app\n"
  1679. "e? Help, settings\n"
  1680. "aQ, ^G Quit and cd\n"
  1681. "aq, ^X Quit\n\n"};
  1682. if (fd == -1)
  1683. return -1;
  1684. start = end = helpstr;
  1685. while (*end) {
  1686. while (*end != '\n')
  1687. ++end;
  1688. if (start == end) {
  1689. ++end;
  1690. continue;
  1691. }
  1692. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1693. start = ++end;
  1694. }
  1695. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_info(path, FREE)));
  1696. dprintf(fd, "%s free\n\n", coolsize(get_fs_info(path, CAPACITY)));
  1697. if (getenv("NNN_BMS")) {
  1698. dprintf(fd, "BOOKMARKS\n");
  1699. for (; i < BM_MAX; ++i)
  1700. if (bookmark[i].key)
  1701. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1702. else
  1703. break;
  1704. dprintf(fd, "\n");
  1705. }
  1706. if (editor)
  1707. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1708. if (dmanager)
  1709. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", dmanager);
  1710. if (idletimeout)
  1711. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1712. if (copier)
  1713. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1714. if (getenv("NNN_NO_X"))
  1715. dprintf(fd, "NNN_NO_X: %s (%s)\n", getenv("NNN_NO_X"), g_cppath);
  1716. if (getenv("NNN_SCRIPT"))
  1717. dprintf(fd, "NNN_SCRIPT: %s\n", getenv("NNN_SCRIPT"));
  1718. if (getenv("NNN_MULTISCRIPT"))
  1719. dprintf(fd, "NNN_MULTISCRIPT: %s\n", getenv("NNN_MULTISCRIPT"));
  1720. if (getenv("NNN_SHOW_HIDDEN"))
  1721. dprintf(fd, "NNN_SHOW_HIDDEN: %s\n", getenv("NNN_SHOW_HIDDEN"));
  1722. dprintf(fd, "\n");
  1723. if (getenv("PWD"))
  1724. dprintf(fd, "PWD: %s\n", getenv("PWD"));
  1725. if (getenv("SHELL"))
  1726. dprintf(fd, "SHELL: %s\n", getenv("SHELL"));
  1727. if (getenv("SHLVL"))
  1728. dprintf(fd, "SHLVL: %s\n", getenv("SHLVL"));
  1729. if (getenv("VISUAL"))
  1730. dprintf(fd, "VISUAL: %s\n", getenv("VISUAL"));
  1731. else if (getenv("EDITOR"))
  1732. dprintf(fd, "EDITOR: %s\n", getenv("EDITOR"));
  1733. if (getenv("PAGER"))
  1734. dprintf(fd, "PAGER: %s\n", getenv("PAGER"));
  1735. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1736. close(fd);
  1737. exitcurses();
  1738. get_output(NULL, 0, "cat", g_tmpfpath, NULL, 1);
  1739. unlink(g_tmpfpath);
  1740. refresh();
  1741. return 0;
  1742. }
  1743. static int sum_bsizes(const char *fpath, const struct stat *sb,
  1744. int typeflag, struct FTW *ftwbuf)
  1745. {
  1746. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1747. ent_blocks += sb->st_blocks;
  1748. ++num_files;
  1749. return 0;
  1750. }
  1751. static int sum_sizes(const char *fpath, const struct stat *sb,
  1752. int typeflag, struct FTW *ftwbuf)
  1753. {
  1754. if (sb->st_size && (typeflag == FTW_F || typeflag == FTW_D))
  1755. ent_blocks += sb->st_size;
  1756. ++num_files;
  1757. return 0;
  1758. }
  1759. static int dentfill(char *path, struct entry **dents,
  1760. int (*filter)(regex_t *, char *), regex_t *re)
  1761. {
  1762. static DIR *dirp;
  1763. static struct dirent *dp;
  1764. static char *namep, *pnb;
  1765. static struct entry *dentp;
  1766. static size_t off, namebuflen = NAMEBUF_INCR;
  1767. static ulong num_saved;
  1768. static int fd, n, count;
  1769. static struct stat sb_path, sb;
  1770. off = 0;
  1771. dirp = opendir(path);
  1772. if (dirp == NULL)
  1773. return 0;
  1774. fd = dirfd(dirp);
  1775. n = 0;
  1776. if (cfg.blkorder) {
  1777. num_files = 0;
  1778. dir_blocks = 0;
  1779. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1780. printwarn();
  1781. return 0;
  1782. }
  1783. }
  1784. while ((dp = readdir(dirp)) != NULL) {
  1785. namep = dp->d_name;
  1786. if (filter(re, namep) == 0) {
  1787. if (!cfg.blkorder)
  1788. continue;
  1789. /* Skip self and parent */
  1790. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1791. continue;
  1792. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1793. continue;
  1794. if (S_ISDIR(sb.st_mode)) {
  1795. if (sb_path.st_dev == sb.st_dev) {
  1796. ent_blocks = 0;
  1797. mkpath(path, namep, g_buf, PATH_MAX);
  1798. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1799. printmsg(messages[STR_NFTWFAIL_ID]);
  1800. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1801. } else
  1802. dir_blocks += ent_blocks;
  1803. }
  1804. } else {
  1805. dir_blocks += (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1806. ++num_files;
  1807. }
  1808. continue;
  1809. }
  1810. /* Skip self and parent */
  1811. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1812. (namep[1] == '.' && namep[2] == '\0'))))
  1813. continue;
  1814. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1815. DPRINTF_S(namep);
  1816. continue;
  1817. }
  1818. if (n == total_dents) {
  1819. total_dents += ENTRY_INCR;
  1820. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1821. if (*dents == NULL) {
  1822. if (pnamebuf)
  1823. free(pnamebuf);
  1824. errexit();
  1825. }
  1826. DPRINTF_P(*dents);
  1827. }
  1828. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1829. if (namebuflen - off < NAME_MAX + 1) {
  1830. namebuflen += NAMEBUF_INCR;
  1831. pnb = pnamebuf;
  1832. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1833. if (pnamebuf == NULL) {
  1834. free(*dents);
  1835. errexit();
  1836. }
  1837. DPRINTF_P(pnamebuf);
  1838. /* realloc() may result in memory move, we must re-adjust if that happens */
  1839. if (pnb != pnamebuf) {
  1840. dentp = *dents;
  1841. dentp->name = pnamebuf;
  1842. for (count = 1; count < n; ++dentp, ++count)
  1843. /* Current filename starts at last filename start + length */
  1844. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1845. }
  1846. }
  1847. dentp = *dents + n;
  1848. /* Copy file name */
  1849. dentp->name = (char *)((size_t)pnamebuf + off);
  1850. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1851. off += dentp->nlen;
  1852. /* Copy other fields */
  1853. dentp->mode = sb.st_mode;
  1854. dentp->t = sb.st_mtime;
  1855. dentp->size = sb.st_size;
  1856. if (cfg.blkorder) {
  1857. if (S_ISDIR(sb.st_mode)) {
  1858. ent_blocks = 0;
  1859. num_saved = num_files + 1;
  1860. mkpath(path, namep, g_buf, PATH_MAX);
  1861. if (nftw(g_buf, nftw_fn, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1862. printmsg(messages[STR_NFTWFAIL_ID]);
  1863. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1864. } else
  1865. dentp->blocks = ent_blocks;
  1866. if (sb_path.st_dev == sb.st_dev)
  1867. dir_blocks += dentp->blocks;
  1868. else
  1869. num_files = num_saved;
  1870. } else {
  1871. dentp->blocks = (cfg.apparentsz ? sb.st_size : sb.st_blocks);
  1872. dir_blocks += dentp->blocks;
  1873. ++num_files;
  1874. }
  1875. }
  1876. /* Flag if this is a symlink to a dir */
  1877. if (S_ISLNK(sb.st_mode))
  1878. if (!fstatat(fd, namep, &sb, 0)) {
  1879. if (S_ISDIR(sb.st_mode))
  1880. dentp->flags |= SYMLINK_TO_DIR;
  1881. else
  1882. dentp->flags &= ~SYMLINK_TO_DIR;
  1883. }
  1884. ++n;
  1885. }
  1886. /* Should never be null */
  1887. if (closedir(dirp) == -1) {
  1888. if (*dents) {
  1889. free(pnamebuf);
  1890. free(*dents);
  1891. }
  1892. errexit();
  1893. }
  1894. return n;
  1895. }
  1896. static void dentfree(struct entry *dents)
  1897. {
  1898. free(pnamebuf);
  1899. free(dents);
  1900. }
  1901. /* Return the position of the matching entry or 0 otherwise */
  1902. static int dentfind(struct entry *dents, const char *fname, int n)
  1903. {
  1904. static int i;
  1905. if (!fname)
  1906. return 0;
  1907. DPRINTF_S(fname);
  1908. for (i = 0; i < n; ++i)
  1909. if (strcmp(fname, dents[i].name) == 0)
  1910. return i;
  1911. return 0;
  1912. }
  1913. static int populate(char *path, char *oldname, char *fltr)
  1914. {
  1915. static regex_t re;
  1916. /* Can fail when permissions change while browsing.
  1917. * It's assumed that path IS a directory when we are here.
  1918. */
  1919. if (access(path, R_OK) == -1)
  1920. return -1;
  1921. /* Search filter */
  1922. if (setfilter(&re, fltr) != 0)
  1923. return -1;
  1924. if (cfg.blkorder) {
  1925. printmsg("calculating...");
  1926. refresh();
  1927. }
  1928. #ifdef DEBUGMODE
  1929. struct timespec ts1, ts2;
  1930. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1931. #endif
  1932. ndents = dentfill(path, &dents, visible, &re);
  1933. regfree(&re);
  1934. if (!ndents)
  1935. return 0;
  1936. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1937. #ifdef DEBUGMODE
  1938. clock_gettime(CLOCK_REALTIME, &ts2);
  1939. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1940. #endif
  1941. /* Find cur from history */
  1942. cur = dentfind(dents, oldname, ndents);
  1943. return 0;
  1944. }
  1945. static void redraw(char *path)
  1946. {
  1947. static char buf[NAME_MAX + 65] __attribute__ ((aligned));
  1948. static size_t ncols;
  1949. static int nlines, i;
  1950. static bool mode_changed;
  1951. mode_changed = FALSE;
  1952. nlines = MIN(LINES - 4, ndents);
  1953. /* Clean screen */
  1954. erase();
  1955. if (cfg.copymode)
  1956. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1957. cfg.copymode = 0;
  1958. DPRINTF_S("copymode off");
  1959. }
  1960. /* Fail redraw if < than 10 columns */
  1961. if (COLS < 10) {
  1962. printmsg("too few columns!");
  1963. return;
  1964. }
  1965. /* Strip trailing slashes */
  1966. for (i = strlen(path) - 1; i > 0; --i)
  1967. if (path[i] == '/')
  1968. path[i] = '\0';
  1969. else
  1970. break;
  1971. DPRINTF_D(cur);
  1972. DPRINTF_S(path);
  1973. if (!realpath(path, g_buf)) {
  1974. printwarn();
  1975. return;
  1976. }
  1977. ncols = COLS;
  1978. if (ncols > PATH_MAX)
  1979. ncols = PATH_MAX;
  1980. attron(A_UNDERLINE);
  1981. /* No text wrapping in cwd line */
  1982. g_buf[ncols - 1] = '\0';
  1983. printw("%s\n\n", g_buf);
  1984. attroff(A_UNDERLINE);
  1985. /* Fallback to light mode if less than 35 columns */
  1986. if (ncols < 35 && cfg.showdetail) {
  1987. cfg.showdetail ^= 1;
  1988. printptr = &printent;
  1989. mode_changed = TRUE;
  1990. }
  1991. /* Calculate the number of cols available to print entry name */
  1992. if (cfg.showdetail)
  1993. ncols -= 32;
  1994. else
  1995. ncols -= 5;
  1996. if (cfg.showcolor) {
  1997. attron(COLOR_PAIR(1) | A_BOLD);
  1998. cfg.dircolor = 1;
  1999. }
  2000. /* Print listing */
  2001. if (cur < (nlines >> 1)) {
  2002. for (i = 0; i < nlines; ++i)
  2003. printptr(&dents[i], i == cur, ncols);
  2004. } else if (cur >= ndents - (nlines >> 1)) {
  2005. for (i = ndents - nlines; i < ndents; ++i)
  2006. printptr(&dents[i], i == cur, ncols);
  2007. } else {
  2008. static int odd;
  2009. odd = ISODD(nlines);
  2010. nlines >>= 1;
  2011. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  2012. printptr(&dents[i], i == cur, ncols);
  2013. }
  2014. /* Must reset e.g. no files in dir */
  2015. if (cfg.dircolor) {
  2016. attroff(COLOR_PAIR(1) | A_BOLD);
  2017. cfg.dircolor = 0;
  2018. }
  2019. if (cfg.showdetail) {
  2020. if (ndents) {
  2021. static char sort[9];
  2022. if (cfg.mtimeorder)
  2023. xstrlcpy(sort, "by time ", 9);
  2024. else if (cfg.sizeorder)
  2025. xstrlcpy(sort, "by size ", 9);
  2026. else
  2027. sort[0] = '\0';
  2028. /* We need to show filename as it may be truncated in directory listing */
  2029. if (!cfg.blkorder)
  2030. snprintf(buf, NAME_MAX + 65, "%d/%d %s[%s%s]",
  2031. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2032. else {
  2033. i = snprintf(buf, 64, "%d/%d ", cur + 1, ndents);
  2034. if (cfg.apparentsz)
  2035. buf[i++] = 'a';
  2036. else
  2037. buf[i++] = 'd';
  2038. i += snprintf(buf + i, 64, "u: %s (%lu files) ", coolsize(dir_blocks << BLK_SHIFT), num_files);
  2039. snprintf(buf + i, NAME_MAX, "vol: %s free [%s%s]",
  2040. coolsize(get_fs_info(path, FREE)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  2041. }
  2042. printmsg(buf);
  2043. } else
  2044. printmsg("0 items");
  2045. }
  2046. if (mode_changed) {
  2047. cfg.showdetail ^= 1;
  2048. printptr = &printent_long;
  2049. }
  2050. }
  2051. static void browse(char *ipath, char *ifilter)
  2052. {
  2053. static char path[PATH_MAX] __attribute__ ((aligned));
  2054. static char newpath[PATH_MAX] __attribute__ ((aligned));
  2055. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  2056. static char mark[PATH_MAX] __attribute__ ((aligned));
  2057. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  2058. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  2059. char *dir, *tmp, *run = NULL, *env = NULL;
  2060. struct stat sb;
  2061. int r, fd, truecd, presel, ncp = 0, copystartid = 0, copyendid = 0;
  2062. enum action sel = SEL_RUNARG + 1;
  2063. bool dir_changed = FALSE;
  2064. xstrlcpy(path, ipath, PATH_MAX);
  2065. copyfilter();
  2066. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  2067. if (cfg.filtermode)
  2068. presel = FILTER;
  2069. else
  2070. presel = 0;
  2071. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  2072. if (dents == NULL)
  2073. errexit();
  2074. DPRINTF_P(dents);
  2075. /* Allocate buffer to hold names */
  2076. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2077. if (pnamebuf == NULL) {
  2078. free(dents);
  2079. errexit();
  2080. }
  2081. DPRINTF_P(pnamebuf);
  2082. begin:
  2083. #ifdef LINUX_INOTIFY
  2084. if (dir_changed && inotify_wd >= 0) {
  2085. inotify_rm_watch(inotify_fd, inotify_wd);
  2086. inotify_wd = -1;
  2087. dir_changed = FALSE;
  2088. }
  2089. #elif defined(BSD_KQUEUE)
  2090. if (dir_changed && event_fd >= 0) {
  2091. close(event_fd);
  2092. event_fd = -1;
  2093. dir_changed = FALSE;
  2094. }
  2095. #endif
  2096. if (populate(path, oldname, fltr) == -1) {
  2097. printwarn();
  2098. goto nochange;
  2099. }
  2100. #ifdef LINUX_INOTIFY
  2101. if (inotify_wd == -1)
  2102. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2103. #elif defined(BSD_KQUEUE)
  2104. if (event_fd == -1) {
  2105. #if defined(O_EVTONLY)
  2106. event_fd = open(path, O_EVTONLY);
  2107. #else
  2108. event_fd = open(path, O_RDONLY);
  2109. #endif
  2110. if (event_fd >= 0)
  2111. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2112. }
  2113. #endif
  2114. for (;;) {
  2115. redraw(path);
  2116. nochange:
  2117. /* Exit if parent has exited */
  2118. if (getppid() == 1)
  2119. _exit(0);
  2120. sel = nextsel(&run, &env, &presel);
  2121. switch (sel) {
  2122. case SEL_BACK:
  2123. /* There is no going back */
  2124. if (istopdir(path)) {
  2125. /* Continue in navigate-as-you-type mode, if enabled */
  2126. if (cfg.filtermode)
  2127. presel = FILTER;
  2128. goto nochange;
  2129. }
  2130. dir = xdirname(path);
  2131. if (access(dir, R_OK) == -1) {
  2132. printwarn();
  2133. goto nochange;
  2134. }
  2135. /* Save history */
  2136. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2137. /* Save last working directory */
  2138. xstrlcpy(lastdir, path, PATH_MAX);
  2139. dir_changed = TRUE;
  2140. xstrlcpy(path, dir, PATH_MAX);
  2141. /* Reset filter */
  2142. copyfilter();
  2143. if (cfg.filtermode)
  2144. presel = FILTER;
  2145. goto begin;
  2146. case SEL_GOIN:
  2147. /* Cannot descend in empty directories */
  2148. if (!ndents)
  2149. goto begin;
  2150. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2151. DPRINTF_S(newpath);
  2152. /* Get path info */
  2153. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2154. if (fd == -1) {
  2155. printwarn();
  2156. goto nochange;
  2157. }
  2158. if (fstat(fd, &sb) == -1) {
  2159. printwarn();
  2160. close(fd);
  2161. goto nochange;
  2162. }
  2163. close(fd);
  2164. DPRINTF_U(sb.st_mode);
  2165. switch (sb.st_mode & S_IFMT) {
  2166. case S_IFDIR:
  2167. if (access(newpath, R_OK) == -1) {
  2168. printwarn();
  2169. goto nochange;
  2170. }
  2171. /* Save last working directory */
  2172. xstrlcpy(lastdir, path, PATH_MAX);
  2173. dir_changed = TRUE;
  2174. xstrlcpy(path, newpath, PATH_MAX);
  2175. oldname[0] = '\0';
  2176. /* Reset filter */
  2177. copyfilter();
  2178. if (cfg.filtermode)
  2179. presel = FILTER;
  2180. goto begin;
  2181. case S_IFREG:
  2182. {
  2183. /* If NNN_USE_EDITOR is set,
  2184. * open text in EDITOR
  2185. */
  2186. if (editor) {
  2187. if (getmime(dents[cur].name)) {
  2188. spawn(editor, newpath, NULL, path, F_NORMAL);
  2189. continue;
  2190. }
  2191. /* Recognize and open plain
  2192. * text files with vi
  2193. */
  2194. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2195. continue;
  2196. if (strstr(g_buf, "text/") == g_buf) {
  2197. spawn(editor, newpath, NULL, path, F_NORMAL);
  2198. continue;
  2199. }
  2200. }
  2201. /* Invoke desktop opener as last resort */
  2202. spawn(utils[OPENER], newpath, NULL, NULL, F_NOWAIT | F_NOTRACE);
  2203. continue;
  2204. }
  2205. default:
  2206. printmsg("unsupported file");
  2207. goto nochange;
  2208. }
  2209. case SEL_NEXT:
  2210. if (cur < ndents - 1)
  2211. ++cur;
  2212. else if (ndents)
  2213. /* Roll over, set cursor to first entry */
  2214. cur = 0;
  2215. break;
  2216. case SEL_PREV:
  2217. if (cur > 0)
  2218. --cur;
  2219. else if (ndents)
  2220. /* Roll over, set cursor to last entry */
  2221. cur = ndents - 1;
  2222. break;
  2223. case SEL_PGDN:
  2224. if (cur < ndents - 1)
  2225. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2226. break;
  2227. case SEL_PGUP:
  2228. if (cur > 0)
  2229. cur -= MIN((LINES - 4) / 2, cur);
  2230. break;
  2231. case SEL_HOME:
  2232. cur = 0;
  2233. break;
  2234. case SEL_END:
  2235. cur = ndents - 1;
  2236. break;
  2237. case SEL_CD:
  2238. truecd = 0;
  2239. tmp = xreadline(NULL, "cd: ");
  2240. if (tmp == NULL || tmp[0] == '\0')
  2241. break;
  2242. if (tmp[0] == '~') {
  2243. /* Expand ~ to HOME absolute path */
  2244. dir = getenv("HOME");
  2245. if (dir)
  2246. snprintf(newpath, PATH_MAX, "%s%s", dir, tmp + 1);
  2247. else {
  2248. printmsg(messages[STR_NOHOME_ID]);
  2249. goto nochange;
  2250. }
  2251. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2252. if (lastdir[0] == '\0')
  2253. break;
  2254. /* Switch to last visited dir */
  2255. xstrlcpy(newpath, lastdir, PATH_MAX);
  2256. truecd = 1;
  2257. } else if ((r = all_dots(tmp))) {
  2258. if (r == 1)
  2259. /* Always in the current dir */
  2260. break;
  2261. /* Show a message if already at / */
  2262. if (istopdir(path)) {
  2263. /* Continue in navigate-as-you-type mode, if enabled */
  2264. if (cfg.filtermode)
  2265. presel = FILTER;
  2266. goto nochange;
  2267. }
  2268. --r; /* One . for the current dir */
  2269. dir = path;
  2270. /* Note: fd is used as a tmp variable here */
  2271. for (fd = 0; fd < r; ++fd) {
  2272. /* Reached / ? */
  2273. if (istopdir(path)) {
  2274. /* Can't cd beyond / */
  2275. break;
  2276. }
  2277. dir = xdirname(dir);
  2278. if (access(dir, R_OK) == -1) {
  2279. printwarn();
  2280. goto nochange;
  2281. }
  2282. }
  2283. truecd = 1;
  2284. /* Save the path in case of cd ..
  2285. * We mark the current dir in parent dir
  2286. */
  2287. if (r == 1) {
  2288. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2289. truecd = 2;
  2290. }
  2291. xstrlcpy(newpath, dir, PATH_MAX);
  2292. } else
  2293. mkpath(path, tmp, newpath, PATH_MAX);
  2294. if (!xdiraccess(newpath))
  2295. goto nochange;
  2296. if (truecd == 0) {
  2297. /* Probable change in dir */
  2298. /* No-op if it's the same directory */
  2299. if (strcmp(path, newpath) == 0)
  2300. break;
  2301. oldname[0] = '\0';
  2302. } else if (truecd == 1)
  2303. /* Sure change in dir */
  2304. oldname[0] = '\0';
  2305. /* Save last working directory */
  2306. xstrlcpy(lastdir, path, PATH_MAX);
  2307. dir_changed = TRUE;
  2308. /* Save the newly opted dir in path */
  2309. xstrlcpy(path, newpath, PATH_MAX);
  2310. /* Reset filter */
  2311. copyfilter();
  2312. DPRINTF_S(path);
  2313. if (cfg.filtermode)
  2314. presel = FILTER;
  2315. goto begin;
  2316. case SEL_CDHOME:
  2317. dir = getenv("HOME");
  2318. if (dir == NULL) {
  2319. clearprompt();
  2320. goto nochange;
  2321. } // fallthrough
  2322. case SEL_CDBEGIN:
  2323. if (sel == SEL_CDBEGIN)
  2324. dir = ipath;
  2325. if (!xdiraccess(dir))
  2326. goto nochange;
  2327. if (strcmp(path, dir) == 0)
  2328. break;
  2329. /* Save last working directory */
  2330. xstrlcpy(lastdir, path, PATH_MAX);
  2331. dir_changed = TRUE;
  2332. xstrlcpy(path, dir, PATH_MAX);
  2333. oldname[0] = '\0';
  2334. /* Reset filter */
  2335. copyfilter();
  2336. DPRINTF_S(path);
  2337. if (cfg.filtermode)
  2338. presel = FILTER;
  2339. goto begin;
  2340. case SEL_CDLAST: // fallthrough
  2341. case SEL_VISIT:
  2342. if (sel == SEL_VISIT) {
  2343. if (strcmp(mark, path) == 0)
  2344. break;
  2345. tmp = mark;
  2346. } else
  2347. tmp = lastdir;
  2348. if (tmp[0] == '\0') {
  2349. printmsg("not set...");
  2350. goto nochange;
  2351. }
  2352. if (!xdiraccess(tmp))
  2353. goto nochange;
  2354. xstrlcpy(newpath, tmp, PATH_MAX);
  2355. xstrlcpy(lastdir, path, PATH_MAX);
  2356. dir_changed = TRUE;
  2357. xstrlcpy(path, newpath, PATH_MAX);
  2358. oldname[0] = '\0';
  2359. /* Reset filter */
  2360. copyfilter();
  2361. DPRINTF_S(path);
  2362. if (cfg.filtermode)
  2363. presel = FILTER;
  2364. goto begin;
  2365. case SEL_CDBM:
  2366. tmp = xreadline(NULL, "key: ");
  2367. if (tmp == NULL || tmp[0] == '\0')
  2368. break;
  2369. /* Interpret ~, - and & keys */
  2370. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2371. presel = tmp[0];
  2372. goto begin;
  2373. }
  2374. if (get_bm_loc(tmp, newpath) == NULL) {
  2375. printmsg(messages[STR_INVBM_ID]);
  2376. goto nochange;
  2377. }
  2378. if (!xdiraccess(newpath))
  2379. goto nochange;
  2380. if (strcmp(path, newpath) == 0)
  2381. break;
  2382. oldname[0] = '\0';
  2383. /* Save last working directory */
  2384. xstrlcpy(lastdir, path, PATH_MAX);
  2385. dir_changed = TRUE;
  2386. /* Save the newly opted dir in path */
  2387. xstrlcpy(path, newpath, PATH_MAX);
  2388. /* Reset filter */
  2389. copyfilter();
  2390. DPRINTF_S(path);
  2391. if (cfg.filtermode)
  2392. presel = FILTER;
  2393. goto begin;
  2394. case SEL_PIN:
  2395. xstrlcpy(mark, path, PATH_MAX);
  2396. printmsg(mark);
  2397. goto nochange;
  2398. case SEL_FLTR:
  2399. presel = filterentries(path);
  2400. copyfilter();
  2401. DPRINTF_S(fltr);
  2402. /* Save current */
  2403. if (ndents)
  2404. copycurname();
  2405. goto nochange;
  2406. case SEL_MFLTR:
  2407. cfg.filtermode ^= 1;
  2408. if (cfg.filtermode)
  2409. presel = FILTER;
  2410. else {
  2411. /* Save current */
  2412. if (ndents)
  2413. copycurname();
  2414. /* Start watching the directory */
  2415. goto begin;
  2416. }
  2417. goto nochange;
  2418. case SEL_SEARCH:
  2419. spawn(player, path, "search", NULL, F_NORMAL);
  2420. break;
  2421. case SEL_TOGGLEDOT:
  2422. cfg.showhidden ^= 1;
  2423. initfilter(cfg.showhidden, &ifilter);
  2424. copyfilter();
  2425. goto begin;
  2426. case SEL_DETAIL:
  2427. cfg.showdetail ^= 1;
  2428. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2429. /* Save current */
  2430. if (ndents)
  2431. copycurname();
  2432. goto begin;
  2433. case SEL_STATS:
  2434. if (!ndents)
  2435. break;
  2436. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2437. if (lstat(newpath, &sb) == -1) {
  2438. if (dents)
  2439. dentfree(dents);
  2440. errexit();
  2441. }
  2442. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2443. printwarn();
  2444. goto nochange;
  2445. }
  2446. break;
  2447. case SEL_LIST: // fallthrough
  2448. case SEL_EXTRACT: // fallthrough
  2449. case SEL_MEDIA: // fallthrough
  2450. case SEL_FMEDIA:
  2451. if (!ndents)
  2452. break;
  2453. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2454. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2455. r = show_mediainfo(newpath, run);
  2456. else
  2457. r = handle_archive(newpath, run, path);
  2458. if (r == -1) {
  2459. xstrlcpy(newpath, "missing ", PATH_MAX);
  2460. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2461. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2462. else
  2463. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2464. printmsg(newpath);
  2465. goto nochange;
  2466. }
  2467. /* In case of successful archive extract, reload contents */
  2468. if (sel == SEL_EXTRACT) {
  2469. /* Continue in navigate-as-you-type mode, if enabled */
  2470. if (cfg.filtermode)
  2471. presel = FILTER;
  2472. /* Save current */
  2473. copycurname();
  2474. /* Repopulate as directory content may have changed */
  2475. goto begin;
  2476. }
  2477. break;
  2478. case SEL_DFB:
  2479. if (!dmanager) {
  2480. printmsg("set NNN_DE_FILE_MANAGER");
  2481. goto nochange;
  2482. }
  2483. spawn(dmanager, path, NULL, path, F_NOWAIT | F_NOTRACE);
  2484. break;
  2485. case SEL_FSIZE:
  2486. cfg.sizeorder ^= 1;
  2487. cfg.mtimeorder = 0;
  2488. cfg.apparentsz = 0;
  2489. cfg.blkorder = 0;
  2490. cfg.copymode = 0;
  2491. /* Save current */
  2492. if (ndents)
  2493. copycurname();
  2494. goto begin;
  2495. case SEL_ASIZE:
  2496. cfg.apparentsz ^= 1;
  2497. if (cfg.apparentsz) {
  2498. nftw_fn = &sum_sizes;
  2499. cfg.blkorder = 1;
  2500. BLK_SHIFT = 0;
  2501. } else
  2502. cfg.blkorder = 0; // fallthrough
  2503. case SEL_BSIZE:
  2504. if (sel == SEL_BSIZE) {
  2505. if (!cfg.apparentsz)
  2506. cfg.blkorder ^= 1;
  2507. nftw_fn = &sum_bsizes;
  2508. cfg.apparentsz = 0;
  2509. BLK_SHIFT = 9;
  2510. }
  2511. if (cfg.blkorder) {
  2512. cfg.showdetail = 1;
  2513. printptr = &printent_long;
  2514. }
  2515. cfg.mtimeorder = 0;
  2516. cfg.sizeorder = 0;
  2517. cfg.copymode = 0;
  2518. /* Save current */
  2519. if (ndents)
  2520. copycurname();
  2521. goto begin;
  2522. case SEL_MTIME:
  2523. cfg.mtimeorder ^= 1;
  2524. cfg.sizeorder = 0;
  2525. cfg.apparentsz = 0;
  2526. cfg.blkorder = 0;
  2527. cfg.copymode = 0;
  2528. /* Save current */
  2529. if (ndents)
  2530. copycurname();
  2531. goto begin;
  2532. case SEL_REDRAW:
  2533. /* Save current */
  2534. if (ndents)
  2535. copycurname();
  2536. goto begin;
  2537. case SEL_COPY:
  2538. if (!(cfg.noxdisplay || copier)) {
  2539. printmsg(messages[STR_COPY_ID]);
  2540. goto nochange;
  2541. }
  2542. if (!ndents)
  2543. goto nochange;
  2544. if (cfg.copymode) {
  2545. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2546. if (!appendfpath(newpath, r))
  2547. goto nochange;
  2548. ++ncp;
  2549. printmsg(newpath);
  2550. } else if (cfg.quote) {
  2551. g_buf[0] = '\'';
  2552. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2553. g_buf[r] = '\'';
  2554. g_buf[r + 1] = '\0';
  2555. if (cfg.noxdisplay)
  2556. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2557. else
  2558. spawn(copier, g_buf, NULL, NULL, F_NOTRACE);
  2559. g_buf[r] = '\0';
  2560. printmsg(g_buf + 1);
  2561. } else {
  2562. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2563. if (cfg.noxdisplay)
  2564. writecp(newpath, r - 1); /* Truncate NULL from end */
  2565. else
  2566. spawn(copier, newpath, NULL, NULL, F_NOTRACE);
  2567. printmsg(newpath);
  2568. }
  2569. goto nochange;
  2570. case SEL_COPYMUL:
  2571. if (!(cfg.noxdisplay || copier)) {
  2572. printmsg(messages[STR_COPY_ID]);
  2573. goto nochange;
  2574. }
  2575. if (!ndents)
  2576. goto nochange;
  2577. cfg.copymode ^= 1;
  2578. if (cfg.copymode) {
  2579. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2580. copystartid = cur;
  2581. copybufpos = 0;
  2582. ncp = 0;
  2583. printmsg("multi-copy on");
  2584. DPRINTF_S("copymode on");
  2585. goto nochange;
  2586. }
  2587. if (!ncp) { /* Handle range selection */
  2588. if (cur < copystartid) {
  2589. copyendid = copystartid;
  2590. copystartid = cur;
  2591. } else
  2592. copyendid = cur;
  2593. if (copystartid < copyendid) {
  2594. for (r = copystartid; r <= copyendid; ++r)
  2595. if (!appendfpath(newpath, mkpath(path, dents[r].name, newpath, PATH_MAX)))
  2596. goto nochange;
  2597. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2598. printmsg(newpath);
  2599. }
  2600. }
  2601. if (copybufpos) { /* File path(s) written to the buffer */
  2602. if (cfg.noxdisplay)
  2603. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2604. else
  2605. spawn(copier, pcopybuf, NULL, NULL, F_NOTRACE);
  2606. if (ncp) { /* Some files cherry picked */
  2607. snprintf(newpath, PATH_MAX, "%d files copied", ncp);
  2608. printmsg(newpath);
  2609. }
  2610. } else
  2611. printmsg("multi-copy off");
  2612. goto nochange;
  2613. case SEL_COPYLIST:
  2614. if (cfg.copymode)
  2615. showcplist();
  2616. else
  2617. printmsg("multi-copy off");
  2618. goto nochange;
  2619. case SEL_QUOTE:
  2620. cfg.quote ^= 1;
  2621. DPRINTF_D(cfg.quote);
  2622. if (cfg.quote)
  2623. printmsg("quotes on");
  2624. else
  2625. printmsg("quotes off");
  2626. goto nochange;
  2627. case SEL_OPEN: // fallthrough
  2628. case SEL_ARCHIVE:
  2629. if (!ndents)
  2630. break; // fallthrough
  2631. case SEL_NEW:
  2632. if (sel == SEL_OPEN)
  2633. tmp = xreadline(NULL, "open with: ");
  2634. else if (sel == SEL_ARCHIVE)
  2635. tmp = xreadline(dents[cur].name, "name: ");
  2636. else
  2637. tmp = xreadline(NULL, "name: ");
  2638. if (tmp == NULL || tmp[0] == '\0')
  2639. break;
  2640. /* Allow only relative, same dir paths */
  2641. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2642. printmsg(messages[STR_INPUT_ID]);
  2643. goto nochange;
  2644. }
  2645. if (sel == SEL_OPEN) {
  2646. printprompt("press 'c' for cli mode");
  2647. cleartimeout();
  2648. r = getch();
  2649. settimeout();
  2650. if (r == 'c')
  2651. r = F_NORMAL;
  2652. else
  2653. r = F_NOWAIT | F_NOTRACE;
  2654. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2655. spawn(tmp, newpath, NULL, path, r);
  2656. continue;
  2657. } else if (sel == SEL_ARCHIVE) {
  2658. /* newpath is used as temporary buffer */
  2659. if (!get_output(newpath, PATH_MAX, "which", utils[APACK], NULL, 0)) {
  2660. printmsg("apack missing");
  2661. continue;
  2662. }
  2663. spawn(utils[APACK], tmp, dents[cur].name, path, F_NORMAL);
  2664. /* Continue in navigate-as-you-type mode, if enabled */
  2665. if (cfg.filtermode)
  2666. presel = FILTER;
  2667. /* Save current */
  2668. copycurname();
  2669. /* Repopulate as directory content may have changed */
  2670. goto begin;
  2671. }
  2672. /* Open the descriptor to currently open directory */
  2673. fd = open(path, O_RDONLY | O_DIRECTORY);
  2674. if (fd == -1) {
  2675. printwarn();
  2676. goto nochange;
  2677. }
  2678. /* Check if another file with same name exists */
  2679. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2680. printmsg("entry exists");
  2681. goto nochange;
  2682. }
  2683. /* Check if it's a dir or file */
  2684. printprompt("press 'f'(ile) or 'd'(ir)");
  2685. cleartimeout();
  2686. r = getch();
  2687. settimeout();
  2688. if (r == 'f') {
  2689. r = openat(fd, tmp, O_CREAT, 0666);
  2690. close(r);
  2691. } else if (r == 'd')
  2692. r = mkdirat(fd, tmp, 0777);
  2693. else {
  2694. close(fd);
  2695. break;
  2696. }
  2697. if (r == -1) {
  2698. printwarn();
  2699. close(fd);
  2700. goto nochange;
  2701. }
  2702. close(fd);
  2703. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2704. goto begin;
  2705. case SEL_RENAME:
  2706. if (!ndents)
  2707. break;
  2708. tmp = xreadline(dents[cur].name, "");
  2709. if (tmp == NULL || tmp[0] == '\0')
  2710. break;
  2711. /* Allow only relative, same dir paths */
  2712. if (tmp[0] == '/' || strcmp(xbasename(tmp), tmp) != 0) {
  2713. printmsg(messages[STR_INPUT_ID]);
  2714. goto nochange;
  2715. }
  2716. /* Skip renaming to same name */
  2717. if (strcmp(tmp, dents[cur].name) == 0)
  2718. break;
  2719. /* Open the descriptor to currently open directory */
  2720. fd = open(path, O_RDONLY | O_DIRECTORY);
  2721. if (fd == -1) {
  2722. printwarn();
  2723. goto nochange;
  2724. }
  2725. /* Check if another file with same name exists */
  2726. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2727. /* File with the same name exists */
  2728. printprompt("press 'y' to overwrite");
  2729. cleartimeout();
  2730. r = getch();
  2731. settimeout();
  2732. if (r != 'y') {
  2733. close(fd);
  2734. break;
  2735. }
  2736. }
  2737. /* Rename the file */
  2738. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2739. printwarn();
  2740. close(fd);
  2741. goto nochange;
  2742. }
  2743. close(fd);
  2744. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2745. goto begin;
  2746. case SEL_RENAMEALL:
  2747. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2748. printmsg("vidir missing");
  2749. goto nochange;
  2750. }
  2751. spawn(utils[VIDIR], ".", NULL, path, F_NORMAL);
  2752. /* Save current */
  2753. if (ndents)
  2754. copycurname();
  2755. goto begin;
  2756. case SEL_HELP:
  2757. show_help(path);
  2758. /* Continue in navigate-as-you-type mode, if enabled */
  2759. if (cfg.filtermode)
  2760. presel = FILTER;
  2761. break;
  2762. case SEL_RUN: // fallthrough
  2763. case SEL_RUNSCRIPT:
  2764. run = xgetenv(env, run);
  2765. if (sel == SEL_RUNSCRIPT) {
  2766. tmp = getenv("NNN_SCRIPT");
  2767. if (tmp) {
  2768. if (getenv("NNN_MULTISCRIPT")) {
  2769. size_t _len = xstrlcpy(newpath, tmp, PATH_MAX);
  2770. tmp = xreadline(NULL, "script suffix: ");
  2771. if (tmp && tmp[0])
  2772. xstrlcpy(newpath + _len - 1, tmp, PATH_MAX - _len);
  2773. tmp = newpath;
  2774. }
  2775. char *curfile = NULL;
  2776. if (ndents)
  2777. curfile = dents[cur].name;
  2778. spawn(run, tmp, curfile, path, F_NORMAL | F_SIGINT);
  2779. } else
  2780. printmsg("set NNN_SCRIPT");
  2781. } else {
  2782. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2783. /* Continue in navigate-as-you-type mode, if enabled */
  2784. if (cfg.filtermode)
  2785. presel = FILTER;
  2786. }
  2787. /* Save current */
  2788. if (ndents)
  2789. copycurname();
  2790. /* Repopulate as directory content may have changed */
  2791. goto begin;
  2792. case SEL_RUNARG:
  2793. run = xgetenv(env, run);
  2794. if ((!run || !run[0]) && (strcmp("VISUAL", env) == 0))
  2795. run = editor ? editor : xgetenv("EDITOR", "vi");
  2796. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2797. break;
  2798. case SEL_LOCK:
  2799. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2800. break;
  2801. case SEL_CDQUIT:
  2802. {
  2803. tmp = getenv("NNN_TMPFILE");
  2804. if (!tmp) {
  2805. printmsg("set NNN_TMPFILE");
  2806. goto nochange;
  2807. }
  2808. FILE *fp = fopen(tmp, "w");
  2809. if (fp) {
  2810. fprintf(fp, "cd \"%s\"", path);
  2811. fclose(fp);
  2812. }
  2813. /* Fall through to exit */
  2814. } // fallthrough
  2815. case SEL_QUIT:
  2816. dentfree(dents);
  2817. return;
  2818. } /* switch (sel) */
  2819. /* Screensaver */
  2820. if (idletimeout != 0 && idle == idletimeout) {
  2821. idle = 0;
  2822. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2823. }
  2824. }
  2825. }
  2826. static void usage(void)
  2827. {
  2828. fprintf(stdout,
  2829. "usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n"
  2830. " [-p nlay] [-S] [-v] [-h] [PATH]\n\n"
  2831. "The missing terminal file manager for X.\n\n"
  2832. "positional args:\n"
  2833. " PATH start dir [default: current dir]\n\n"
  2834. "optional args:\n"
  2835. " -b key bookmark key to open\n"
  2836. " -c N dir color, disables if N>7\n"
  2837. " -e use exiftool instead of mediainfo\n"
  2838. " -i start in navigate-as-you-type mode\n"
  2839. " -l start in light mode\n"
  2840. " -p nlay path to custom nlay\n"
  2841. " -S start in disk usage analyser mode\n"
  2842. " -v show program version\n"
  2843. " -h show this help\n\n"
  2844. "Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2845. exit(0);
  2846. }
  2847. int main(int argc, char *argv[])
  2848. {
  2849. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2850. char *ipath = NULL, *ifilter;
  2851. int opt;
  2852. /* Confirm we are in a terminal */
  2853. if (!isatty(0) || !isatty(1)) {
  2854. fprintf(stderr, "stdin or stdout is not a tty\n");
  2855. exit(1);
  2856. }
  2857. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2858. switch (opt) {
  2859. case 'S':
  2860. cfg.blkorder = 1;
  2861. nftw_fn = sum_bsizes;
  2862. break;
  2863. case 'l':
  2864. cfg.showdetail = 0;
  2865. printptr = &printent;
  2866. break;
  2867. case 'i':
  2868. cfg.filtermode = 1;
  2869. break;
  2870. case 'b':
  2871. ipath = optarg;
  2872. break;
  2873. case 'c':
  2874. if (atoi(optarg) > 7)
  2875. cfg.showcolor = 0;
  2876. else
  2877. cfg.color = (uchar)atoi(optarg);
  2878. break;
  2879. case 'e':
  2880. cfg.metaviewer = EXIFTOOL;
  2881. break;
  2882. case 'p':
  2883. player = optarg;
  2884. break;
  2885. case 'v':
  2886. fprintf(stdout, "%s\n", VERSION);
  2887. return 0;
  2888. case 'h': // fallthrough
  2889. default:
  2890. usage();
  2891. }
  2892. }
  2893. /* Parse bookmarks string */
  2894. parsebmstr();
  2895. if (ipath) { /* Open a bookmark directly */
  2896. if (get_bm_loc(ipath, cwd) == NULL) {
  2897. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2898. exit(1);
  2899. }
  2900. ipath = cwd;
  2901. } else if (argc == optind) {
  2902. /* Start in the current directory */
  2903. ipath = getcwd(cwd, PATH_MAX);
  2904. if (ipath == NULL)
  2905. ipath = "/";
  2906. } else {
  2907. ipath = realpath(argv[optind], cwd);
  2908. if (!ipath) {
  2909. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2910. exit(1);
  2911. }
  2912. }
  2913. /* Increase current open file descriptor limit */
  2914. open_max = max_openfds();
  2915. if (getuid() == 0 || getenv("NNN_SHOW_HIDDEN"))
  2916. cfg.showhidden = 1;
  2917. initfilter(cfg.showhidden, &ifilter);
  2918. #ifdef LINUX_INOTIFY
  2919. /* Initialize inotify */
  2920. inotify_fd = inotify_init1(IN_NONBLOCK);
  2921. if (inotify_fd < 0) {
  2922. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2923. exit(1);
  2924. }
  2925. #elif defined(BSD_KQUEUE)
  2926. kq = kqueue();
  2927. if (kq < 0) {
  2928. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2929. exit(1);
  2930. }
  2931. #endif
  2932. /* Edit text in EDITOR, if opted */
  2933. if (getenv("NNN_USE_EDITOR")) {
  2934. editor = xgetenv("VISUAL", NULL);
  2935. if (!editor)
  2936. editor = xgetenv("EDITOR", "vi");
  2937. }
  2938. /* Set player if not set already */
  2939. if (!player)
  2940. player = utils[NLAY];
  2941. /* Get the desktop file manager, if set */
  2942. dmanager = getenv("NNN_DE_FILE_MANAGER");
  2943. /* Get screensaver wait time, if set; copier used as tmp var */
  2944. copier = getenv("NNN_IDLE_TIMEOUT");
  2945. if (copier) {
  2946. opt = atoi(copier);
  2947. idletimeout = opt * ((opt > 0) - (opt < 0));
  2948. }
  2949. /* Get the default copier, if set */
  2950. copier = getenv("NNN_COPIER");
  2951. /* Enable quotes if opted */
  2952. if (getenv("NNN_QUOTE_ON"))
  2953. cfg.quote = 1;
  2954. if (getenv("HOME"))
  2955. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("HOME"), MAX_HOME_LEN);
  2956. else if (getenv("TMPDIR"))
  2957. g_tmpfplen = xstrlcpy(g_tmpfpath, getenv("TMPDIR"), MAX_HOME_LEN);
  2958. else if (xdiraccess("/tmp"))
  2959. g_tmpfplen = xstrlcpy(g_tmpfpath, "/tmp", MAX_HOME_LEN);
  2960. /* Check if X11 is available */
  2961. if (!copier && g_tmpfplen && getenv("NNN_NO_X")) {
  2962. cfg.noxdisplay = 1;
  2963. xstrlcpy(g_cppath, g_tmpfpath, MAX_HOME_LEN);
  2964. xstrlcpy(g_cppath + g_tmpfplen - 1, "/.nnncp", MAX_HOME_LEN - g_tmpfplen);
  2965. }
  2966. /* Disable auto-select if opted */
  2967. if (getenv("NNN_NO_AUTOSELECT"))
  2968. cfg.autoselect = 0;
  2969. signal(SIGINT, SIG_IGN);
  2970. /* Test initial path */
  2971. if (!xdiraccess(ipath)) {
  2972. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2973. exit(1);
  2974. }
  2975. /* Set locale */
  2976. setlocale(LC_ALL, "");
  2977. crc8init();
  2978. #ifdef DEBUGMODE
  2979. enabledbg();
  2980. #endif
  2981. initcurses();
  2982. browse(ipath, ifilter);
  2983. exitcurses();
  2984. if (cfg.noxdisplay && g_cppath[0])
  2985. unlink(g_cppath);
  2986. #ifdef LINUX_INOTIFY
  2987. /* Shutdown inotify */
  2988. if (inotify_wd >= 0)
  2989. inotify_rm_watch(inotify_fd, inotify_wd);
  2990. close(inotify_fd);
  2991. #elif defined(BSD_KQUEUE)
  2992. if (event_fd >= 0)
  2993. close(event_fd);
  2994. close(kq);
  2995. #endif
  2996. #ifdef DEBUGMODE
  2997. disabledbg();
  2998. #endif
  2999. exit(0);
  3000. }