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

1421 lines
29 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <curses.h>
  6. #include <dirent.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <limits.h>
  10. #include <locale.h>
  11. #include <regex.h>
  12. #include <signal.h>
  13. #include <stdarg.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include <time.h>
  19. #include <pwd.h>
  20. #include <grp.h>
  21. #ifdef DEBUG
  22. #define DEBUG_FD 8
  23. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  24. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  25. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  26. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  27. #else
  28. #define DPRINTF_D(x)
  29. #define DPRINTF_U(x)
  30. #define DPRINTF_S(x)
  31. #define DPRINTF_P(x)
  32. #endif /* DEBUG */
  33. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  34. #undef MIN
  35. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  36. #define ISODD(x) ((x) & 1)
  37. #define CONTROL(c) ((c) ^ 0x40)
  38. #define TOUPPER(ch) \
  39. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  40. #define MAX_CMD_LEN (PATH_MAX << 1)
  41. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  42. struct assoc {
  43. char *regex; /* Regex to match on filename */
  44. char *bin; /* Program */
  45. };
  46. /* Supported actions */
  47. enum action {
  48. SEL_QUIT = 1,
  49. SEL_BACK,
  50. SEL_GOIN,
  51. SEL_FLTR,
  52. SEL_NEXT,
  53. SEL_PREV,
  54. SEL_PGDN,
  55. SEL_PGUP,
  56. SEL_HOME,
  57. SEL_END,
  58. SEL_CD,
  59. SEL_CDHOME,
  60. SEL_TOGGLEDOT,
  61. SEL_DETAIL,
  62. SEL_STATS,
  63. SEL_FSIZE,
  64. SEL_MTIME,
  65. SEL_REDRAW,
  66. SEL_COPY,
  67. SEL_HELP,
  68. SEL_RUN,
  69. SEL_RUNARG,
  70. };
  71. struct key {
  72. int sym; /* Key pressed */
  73. enum action act; /* Action */
  74. char *run; /* Program to run */
  75. char *env; /* Environment variable to run */
  76. };
  77. #include "config.h"
  78. typedef struct entry {
  79. char name[PATH_MAX];
  80. mode_t mode;
  81. time_t t;
  82. off_t size;
  83. } *pEntry;
  84. /* Global context */
  85. static struct entry *dents;
  86. static int ndents, cur;
  87. static int idle;
  88. static char *opener;
  89. static char *fallback_opener;
  90. static char *copier;
  91. static const char* size_units[] = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  92. /*
  93. * Layout:
  94. * .---------
  95. * | cwd: /mnt/path
  96. * |
  97. * | file0
  98. * | file1
  99. * | > file2
  100. * | file3
  101. * | file4
  102. * ...
  103. * | filen
  104. * |
  105. * | Permission denied
  106. * '------
  107. */
  108. static void printmsg(char *);
  109. static void printwarn(void);
  110. static void printerr(int, char *);
  111. static int
  112. xprintf(int fd, const char *fmt, ...)
  113. {
  114. char buf[BUFSIZ];
  115. int r;
  116. va_list ap;
  117. va_start(ap, fmt);
  118. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  119. if (r > 0)
  120. r = write(fd, buf, r);
  121. va_end(ap);
  122. return r;
  123. }
  124. static void *
  125. xrealloc(void *p, size_t size)
  126. {
  127. p = realloc(p, size);
  128. if (p == NULL)
  129. printerr(1, "realloc");
  130. return p;
  131. }
  132. static size_t
  133. xstrlcpy(char *dest, const char *src, size_t n)
  134. {
  135. size_t i;
  136. for (i = 0; i < n && *src; i++)
  137. *dest++ = *src++;
  138. if (n) {
  139. *dest = '\0';
  140. #ifdef CHECK_XSTRLCPY_RET
  141. /* Compiling this out as we are not checking
  142. the return value anywhere (controlled case).
  143. Just returning the number of bytes copied. */
  144. while(*src++)
  145. i++;
  146. #endif
  147. }
  148. return i;
  149. }
  150. /*
  151. * The poor man's implementation of memrchr(3).
  152. * We are only looking for '/' in this program.
  153. */
  154. static void *
  155. xmemrchr(const void *s, int c, size_t n)
  156. {
  157. unsigned char *p;
  158. unsigned char ch = (unsigned char)c;
  159. if (!s || !n)
  160. return NULL;
  161. p = (unsigned char *)s + n - 1;
  162. while(n--)
  163. if ((*p--) == ch)
  164. return ++p;
  165. return NULL;
  166. }
  167. #if 0
  168. /* Some implementations of dirname(3) may modify `path' and some
  169. * return a pointer inside `path'. */
  170. static char *
  171. xdirname(const char *path)
  172. {
  173. static char out[PATH_MAX];
  174. char tmp[PATH_MAX], *p;
  175. xstrlcpy(tmp, path, sizeof(tmp));
  176. p = dirname(tmp);
  177. if (p == NULL)
  178. printerr(1, "dirname");
  179. xstrlcpy(out, p, sizeof(out));
  180. return out;
  181. }
  182. #endif
  183. /*
  184. * The following dirname(3) implementation does not
  185. * change the input. We use a copy of the original.
  186. *
  187. * Modified from the glibc (GNU LGPL) version.
  188. */
  189. static char *
  190. xdirname(const char *path)
  191. {
  192. static char name[PATH_MAX];
  193. char *last_slash;
  194. xstrlcpy(name, path, PATH_MAX);
  195. /* Find last '/'. */
  196. last_slash = strrchr(name, '/');
  197. if (last_slash != NULL && last_slash != name && last_slash[1] == '\0') {
  198. /* Determine whether all remaining characters are slashes. */
  199. char *runp;
  200. for (runp = last_slash; runp != name; --runp)
  201. if (runp[-1] != '/')
  202. break;
  203. /* The '/' is the last character, we have to look further. */
  204. if (runp != name)
  205. last_slash = xmemrchr(name, '/', runp - name);
  206. }
  207. if (last_slash != NULL) {
  208. /* Determine whether all remaining characters are slashes. */
  209. char *runp;
  210. for (runp = last_slash; runp != name; --runp)
  211. if (runp[-1] != '/')
  212. break;
  213. /* Terminate the name. */
  214. if (runp == name) {
  215. /* The last slash is the first character in the string.
  216. We have to return "/". As a special case we have to
  217. return "//" if there are exactly two slashes at the
  218. beginning of the string. See XBD 4.10 Path Name
  219. Resolution for more information. */
  220. if (last_slash == name + 1)
  221. ++last_slash;
  222. else
  223. last_slash = name + 1;
  224. } else
  225. last_slash = runp;
  226. last_slash[0] = '\0';
  227. } else {
  228. /* This assignment is ill-designed but the XPG specs require to
  229. return a string containing "." in any case no directory part
  230. is found and so a static and constant string is required. */
  231. name[0] = '.';
  232. name[1] = '\0';
  233. }
  234. return name;
  235. }
  236. static void
  237. spawn(char *file, char *arg, char *dir)
  238. {
  239. pid_t pid;
  240. int status;
  241. pid = fork();
  242. if (pid == 0) {
  243. if (dir != NULL)
  244. status = chdir(dir);
  245. execlp(file, file, arg, NULL);
  246. _exit(1);
  247. } else {
  248. /* Ignore interruptions */
  249. while (waitpid(pid, &status, 0) == -1)
  250. DPRINTF_D(status);
  251. DPRINTF_D(pid);
  252. }
  253. }
  254. static char *
  255. xgetenv(char *name, char *fallback)
  256. {
  257. char *value;
  258. if (name == NULL)
  259. return fallback;
  260. value = getenv(name);
  261. return value && value[0] ? value : fallback;
  262. }
  263. int xisdigit(const char c) {
  264. if (c >= '0' && c <= '9') \
  265. return 1; \
  266. return 0;
  267. }
  268. /*
  269. * We assume none of the strings are NULL.
  270. *
  271. * Let's have the logic to sort numeric names in numeric order.
  272. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  273. *
  274. * If the absolute numeric values are same, we fallback to alphasort.
  275. */
  276. static int
  277. xstricmp(const char *s1, const char *s2)
  278. {
  279. static char *c1, *c2;
  280. static long long num1, num2;
  281. num1 = strtoll(s1, &c1, 10);
  282. num2 = strtoll(s2, &c2, 10);
  283. if (*c1 == '\0' && *c2 == '\0') {
  284. if (num1 != num2) {
  285. if (num1 > num2)
  286. return 1;
  287. else
  288. return -1;
  289. }
  290. } else if (*c1 == '\0' && *c2 != '\0')
  291. return -1;
  292. else if (*c1 != '\0' && *c2 == '\0')
  293. return 1;
  294. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  295. s1++, s2++;
  296. /* In case of alphabetically same names, make sure
  297. lower case one comes before upper case one */
  298. if (!*s1 && !*s2)
  299. return 1;
  300. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  301. }
  302. static char *
  303. openwith(char *file)
  304. {
  305. regex_t regex;
  306. char *bin = NULL;
  307. unsigned int i;
  308. for (i = 0; i < LEN(assocs); i++) {
  309. if (regcomp(&regex, assocs[i].regex,
  310. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  311. continue;
  312. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  313. bin = assocs[i].bin;
  314. break;
  315. }
  316. }
  317. DPRINTF_S(bin);
  318. return bin;
  319. }
  320. static int
  321. setfilter(regex_t *regex, char *filter)
  322. {
  323. char errbuf[LINE_MAX];
  324. size_t len;
  325. int r;
  326. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  327. if (r != 0) {
  328. len = COLS;
  329. if (len > sizeof(errbuf))
  330. len = sizeof(errbuf);
  331. regerror(r, regex, errbuf, len);
  332. printmsg(errbuf);
  333. }
  334. return r;
  335. }
  336. static void
  337. initfilter(int dot, char **ifilter)
  338. {
  339. *ifilter = dot ? "." : "^[^.]";
  340. }
  341. static int
  342. visible(regex_t *regex, char *file)
  343. {
  344. return regexec(regex, file, 0, NULL, 0) == 0;
  345. }
  346. static int
  347. entrycmp(const void *va, const void *vb)
  348. {
  349. static pEntry pa, pb;
  350. pa = (pEntry)va;
  351. pb = (pEntry)vb;
  352. /* Sort directories first */
  353. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  354. return 1;
  355. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  356. return -1;
  357. /* Do the actual sorting */
  358. if (mtimeorder)
  359. return pb->t - pa->t;
  360. if (sizeorder)
  361. if (pb->size != pa->size)
  362. return pb->size - pa->size;
  363. return xstricmp(pa->name, pb->name);
  364. }
  365. static void
  366. initcurses(void)
  367. {
  368. if (initscr() == NULL) {
  369. char *term = getenv("TERM");
  370. if (term != NULL)
  371. fprintf(stderr, "error opening terminal: %s\n", term);
  372. else
  373. fprintf(stderr, "failed to initialize curses\n");
  374. exit(1);
  375. }
  376. cbreak();
  377. noecho();
  378. nonl();
  379. intrflush(stdscr, FALSE);
  380. keypad(stdscr, TRUE);
  381. curs_set(FALSE); /* Hide cursor */
  382. timeout(1000); /* One second */
  383. }
  384. static void
  385. exitcurses(void)
  386. {
  387. endwin(); /* Restore terminal */
  388. }
  389. /* Messages show up at the bottom */
  390. static void
  391. printmsg(char *msg)
  392. {
  393. move(LINES - 1, 0);
  394. printw("%s\n", msg);
  395. }
  396. /* Display warning as a message */
  397. static void
  398. printwarn(void)
  399. {
  400. printmsg(strerror(errno));
  401. }
  402. /* Kill curses and display error before exiting */
  403. static void
  404. printerr(int ret, char *prefix)
  405. {
  406. exitcurses();
  407. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  408. exit(ret);
  409. }
  410. /* Clear the last line */
  411. static void
  412. clearprompt(void)
  413. {
  414. printmsg("");
  415. }
  416. /* Print prompt on the last line */
  417. static void
  418. printprompt(char *str)
  419. {
  420. clearprompt();
  421. printw(str);
  422. }
  423. /* Returns SEL_* if key is bound and 0 otherwise.
  424. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  425. static int
  426. nextsel(char **run, char **env)
  427. {
  428. int c;
  429. unsigned int i;
  430. c = getch();
  431. if (c == -1)
  432. idle++;
  433. else
  434. idle = 0;
  435. for (i = 0; i < LEN(bindings); i++)
  436. if (c == bindings[i].sym) {
  437. *run = bindings[i].run;
  438. *env = bindings[i].env;
  439. return bindings[i].act;
  440. }
  441. return 0;
  442. }
  443. static char *
  444. readln(void)
  445. {
  446. static char ln[LINE_MAX];
  447. timeout(-1);
  448. echo();
  449. curs_set(TRUE);
  450. memset(ln, 0, sizeof(ln));
  451. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  452. noecho();
  453. curs_set(FALSE);
  454. timeout(1000);
  455. return ln[0] ? ln : NULL;
  456. }
  457. static int
  458. canopendir(char *path)
  459. {
  460. DIR *dirp;
  461. dirp = opendir(path);
  462. if (dirp == NULL)
  463. return 0;
  464. closedir(dirp);
  465. return 1;
  466. }
  467. /*
  468. * Returns "dir/name or "/name"
  469. */
  470. static char *
  471. mkpath(char *dir, char *name, char *out, size_t n)
  472. {
  473. /* Handle absolute path */
  474. if (name[0] == '/')
  475. xstrlcpy(out, name, n);
  476. else {
  477. /* Handle root case */
  478. if (strcmp(dir, "/") == 0)
  479. snprintf(out, n, "/%s", name);
  480. else
  481. snprintf(out, n, "%s/%s", dir, name);
  482. }
  483. return out;
  484. }
  485. static void
  486. printent(struct entry *ent, int active)
  487. {
  488. if (S_ISDIR(ent->mode))
  489. printw("%s%s/\n", CURSYM(active), ent->name);
  490. else if (S_ISLNK(ent->mode))
  491. printw("%s%s@\n", CURSYM(active), ent->name);
  492. else if (S_ISSOCK(ent->mode))
  493. printw("%s%s=\n", CURSYM(active), ent->name);
  494. else if (S_ISFIFO(ent->mode))
  495. printw("%s%s|\n", CURSYM(active), ent->name);
  496. else if (ent->mode & S_IXUSR)
  497. printw("%s%s*\n", CURSYM(active), ent->name);
  498. else
  499. printw("%s%s\n", CURSYM(active), ent->name);
  500. }
  501. static void (*printptr)(struct entry *ent, int active) = &printent;
  502. static char*
  503. coolsize(off_t size)
  504. {
  505. static char size_buf[12]; /* Buffer to hold human readable size */
  506. int i = 0;
  507. long double fsize = (double)size;
  508. while (fsize > 1024) {
  509. fsize /= 1024;
  510. i++;
  511. }
  512. snprintf(size_buf, 12, "%.*Lf%s", i, fsize, size_units[i]);
  513. return size_buf;
  514. }
  515. static void
  516. printent_long(struct entry *ent, int active)
  517. {
  518. static char buf[18];
  519. strftime(buf, 18, "%b %d %H:%M %Y", localtime(&ent->t));
  520. if (active)
  521. attron(A_REVERSE);
  522. if (S_ISDIR(ent->mode))
  523. printw("%s%-17.17s / %s/\n",
  524. CURSYM(active), buf, ent->name);
  525. else if (S_ISLNK(ent->mode))
  526. printw("%s%-17.17s @ %s@\n",
  527. CURSYM(active), buf, ent->name);
  528. else if (S_ISSOCK(ent->mode))
  529. printw("%s%-17.17s = %s=\n",
  530. CURSYM(active), buf, ent->name);
  531. else if (S_ISFIFO(ent->mode))
  532. printw("%s%-17.17s | %s|\n",
  533. CURSYM(active), buf, ent->name);
  534. else if (S_ISBLK(ent->mode))
  535. printw("%s%-17.17s b %s\n",
  536. CURSYM(active), buf, ent->name);
  537. else if (S_ISCHR(ent->mode))
  538. printw("%s%-17.17s c %s\n",
  539. CURSYM(active), buf, ent->name);
  540. else if (ent->mode & S_IXUSR)
  541. printw("%s%-17.17s %8.8s* %s*\n", CURSYM(active),
  542. buf, coolsize(ent->size), ent->name);
  543. else
  544. printw("%s%-17.17s %8.8s %s\n", CURSYM(active),
  545. buf, coolsize(ent->size), ent->name);
  546. if (active)
  547. attroff(A_REVERSE);
  548. }
  549. static char
  550. get_fileind(mode_t mode, char *desc)
  551. {
  552. char c;
  553. if (S_ISREG(mode)) {
  554. c = '-';
  555. sprintf(desc, "%s", "regular file");
  556. if (mode & S_IXUSR)
  557. strcat(desc, ", executable");
  558. } else if (S_ISDIR(mode)) {
  559. c = 'd';
  560. sprintf(desc, "%s", "directory");
  561. } else if (S_ISBLK(mode)) {
  562. c = 'b';
  563. sprintf(desc, "%s", "block special device");
  564. } else if (S_ISCHR(mode)) {
  565. c = 'c';
  566. sprintf(desc, "%s", "character special device");
  567. #ifdef S_ISFIFO
  568. } else if (S_ISFIFO(mode)) {
  569. c = 'p';
  570. sprintf(desc, "%s", "FIFO");
  571. #endif /* S_ISFIFO */
  572. #ifdef S_ISLNK
  573. } else if (S_ISLNK(mode)) {
  574. c = 'l';
  575. sprintf(desc, "%s", "symbolic link");
  576. #endif /* S_ISLNK */
  577. #ifdef S_ISSOCK
  578. } else if (S_ISSOCK(mode)) {
  579. c = 's';
  580. sprintf(desc, "%s", "socket");
  581. #endif /* S_ISSOCK */
  582. #ifdef S_ISDOOR
  583. /* Solaris 2.6, etc. */
  584. } else if (S_ISDOOR(mode)) {
  585. c = 'D';
  586. desc[0] = '\0';
  587. #endif /* S_ISDOOR */
  588. } else {
  589. /* Unknown type -- possibly a regular file? */
  590. c = '?';
  591. desc[0] = '\0';
  592. }
  593. return(c);
  594. }
  595. /* Convert a mode field into "ls -l" type perms field. */
  596. static char *
  597. get_lsperms(mode_t mode, char *desc)
  598. {
  599. static const char *rwx[] = {"---", "--x", "-w-", "-wx",
  600. "r--", "r-x", "rw-", "rwx"};
  601. static char bits[11];
  602. bits[0] = get_fileind(mode, desc);
  603. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  604. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  605. strcpy(&bits[7], rwx[(mode & 7)]);
  606. if (mode & S_ISUID)
  607. bits[3] = (mode & S_IXUSR) ? 's' : 'S';
  608. if (mode & S_ISGID)
  609. bits[6] = (mode & S_IXGRP) ? 's' : 'l';
  610. if (mode & S_ISVTX)
  611. bits[9] = (mode & S_IXOTH) ? 't' : 'T';
  612. bits[10] = '\0';
  613. return(bits);
  614. }
  615. char *
  616. get_output(char *buf, size_t bytes)
  617. {
  618. char *ret;
  619. FILE *pf = popen(buf, "r");
  620. if (pf) {
  621. ret = fgets(buf, bytes, pf);
  622. pclose(pf);
  623. return ret;
  624. }
  625. return NULL;
  626. }
  627. /*
  628. * Follows the stat(1) output closely
  629. */
  630. void
  631. show_stats(char* fpath, char* fname, struct stat *sb)
  632. {
  633. char buf[PATH_MAX + 48];
  634. char *perms = get_lsperms(sb->st_mode, buf);
  635. FILE *pf;
  636. char *p, *begin = buf;
  637. clear();
  638. /* Show file name or 'symlink' -> 'target' */
  639. if (perms[0] == 'l') {
  640. char symtgt[PATH_MAX];
  641. ssize_t len = readlink(fpath, symtgt, PATH_MAX);
  642. if (len != -1) {
  643. symtgt[len] = '\0';
  644. printw("\n\n File: '%s' -> '%s'", fname, symtgt);
  645. }
  646. } else
  647. printw("\n File: '%s'", fname);
  648. /* Show size, blocks, file type */
  649. printw("\n Size: %-15llu Blocks: %-10llu IO Block: %-6llu %s",
  650. sb->st_size, sb->st_blocks, sb->st_blksize, buf);
  651. /* Show containing device, inode, hardlink count */
  652. sprintf(buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  653. printw("\n Device: %-15s Inode: %-11lu Links: %-9lu",
  654. buf, sb->st_ino, sb->st_nlink);
  655. /* Show major, minor number for block or char device */
  656. if (perms[0] == 'b' || perms[0] == 'c')
  657. printw(" Device type: %lx,%lx",
  658. major(sb->st_rdev), minor(sb->st_rdev));
  659. /* Show permissions, owner, group */
  660. printw("\n Access: 0%d%d%d/%s Uid: (%lu/%s) Gid: (%lu/%s)",
  661. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  662. perms,
  663. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  664. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  665. /* Show last access time */
  666. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  667. printw("\n\n Access: %s", buf);
  668. /* Show last modification time */
  669. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  670. printw("\n Modify: %s", buf);
  671. /* Show last status change time */
  672. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  673. printw("\n Change: %s", buf);
  674. if (S_ISREG(sb->st_mode)) {
  675. /* Show file(1) output */
  676. sprintf(buf, "file -b %s 2>&1", fpath);
  677. p = get_output(buf, PATH_MAX + 48);
  678. if (p) {
  679. printw("\n\n ");
  680. while (*p) {
  681. if (*p == ',') {
  682. *p = '\0';
  683. printw(" %s\n", begin);
  684. begin = p + 1;
  685. }
  686. p++;
  687. }
  688. printw(" %s", begin);
  689. }
  690. /* Show md5 */
  691. sprintf(buf, "openssl md5 %s 2>&1 | cut -d' ' -f2", fpath);
  692. p = get_output(buf, PATH_MAX + 48);
  693. if (p)
  694. printw("\n md5: %s", p);
  695. /* Show sha256 */
  696. sprintf(buf, "openssl sha256 %s 2>&1| cut -d' ' -f2", fpath);
  697. p = get_output(buf, PATH_MAX + 48);
  698. if (p)
  699. printw(" sha256: %s", p);
  700. }
  701. /* Show exit keys */
  702. printw("\n\n << (q/Esc)");
  703. while (*buf = getch())
  704. if (*buf == 'q' || *buf == 27)
  705. return;
  706. }
  707. void
  708. show_help(void)
  709. {
  710. char c;
  711. clear();
  712. printw("\n\
  713. << Key >> << Function >>\n\n\
  714. [Up], k, ^P Previous entry\n\
  715. [Down], j, ^N Next entry\n\
  716. [PgUp], ^U Scroll half page up\n\
  717. [PgDn], ^D Scroll half page down\n\
  718. [Home], ^, ^A Jump to first dir entry\n\
  719. [End], $, ^E Jump to last dir entry\n\
  720. [Right], [Enter], l, ^M Open file or enter dir\n\
  721. [Left], [Backspace], h, ^H Go to parent dir\n\
  722. ~ Jump to HOME dir\n\
  723. /, & Filter dir contents\n\
  724. c Show change dir prompt\n\
  725. d Toggle detail view\n\
  726. D Show details of selected file\n\
  727. . Toggle hide .dot files\n\
  728. s Toggle sort by file size\n\
  729. t Toggle sort by modified time\n\
  730. ! Spawn SHELL in PWD (fallback sh)\n\
  731. z Run top\n\
  732. e Edit entry in EDITOR (fallback vi)\n\
  733. p Open entry in PAGER (fallback less)\n\
  734. ^K Invoke file name copier\n\
  735. ^L Force a redraw\n\
  736. ? Show help\n\
  737. q Quit\n");
  738. /* Show exit keys */
  739. printw("\n\n << (q/Esc)");
  740. while (c = getch())
  741. if (c == 'q' || c == 27)
  742. return;
  743. }
  744. static int
  745. dentfill(char *path, struct entry **dents,
  746. int (*filter)(regex_t *, char *), regex_t *re)
  747. {
  748. char newpath[PATH_MAX];
  749. DIR *dirp;
  750. struct dirent *dp;
  751. struct stat sb;
  752. int r, n = 0;
  753. dirp = opendir(path);
  754. if (dirp == NULL)
  755. return 0;
  756. while ((dp = readdir(dirp)) != NULL) {
  757. /* Skip self and parent */
  758. if (strcmp(dp->d_name, ".") == 0 ||
  759. strcmp(dp->d_name, "..") == 0)
  760. continue;
  761. if (filter(re, dp->d_name) == 0)
  762. continue;
  763. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  764. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  765. /* Get mode flags */
  766. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  767. r = lstat(newpath, &sb);
  768. if (r == -1)
  769. printerr(1, "lstat");
  770. (*dents)[n].mode = sb.st_mode;
  771. (*dents)[n].t = sb.st_mtime;
  772. (*dents)[n].size = sb.st_size;
  773. n++;
  774. }
  775. /* Should never be null */
  776. r = closedir(dirp);
  777. if (r == -1)
  778. printerr(1, "closedir");
  779. return n;
  780. }
  781. static void
  782. dentfree(struct entry *dents)
  783. {
  784. free(dents);
  785. }
  786. /* Return the position of the matching entry or 0 otherwise */
  787. static int
  788. dentfind(struct entry *dents, int n, char *path)
  789. {
  790. if (!path)
  791. return 0;
  792. char *p = xmemrchr(path, '/', strlen(path));
  793. if (!p)
  794. p = path;
  795. else
  796. /* We are assuming an entry with actual
  797. name ending in '/' will not appear */
  798. p++;
  799. DPRINTF_S(p);
  800. for (int i = 0; i < n; i++)
  801. if (strcmp(p, dents[i].name) == 0)
  802. return i;
  803. return 0;
  804. }
  805. static int
  806. populate(char *path, char *oldpath, char *fltr)
  807. {
  808. regex_t re;
  809. int r;
  810. /* Can fail when permissions change while browsing */
  811. if (canopendir(path) == 0)
  812. return -1;
  813. /* Search filter */
  814. r = setfilter(&re, fltr);
  815. if (r != 0)
  816. return -1;
  817. dentfree(dents);
  818. ndents = 0;
  819. dents = NULL;
  820. ndents = dentfill(path, &dents, visible, &re);
  821. qsort(dents, ndents, sizeof(*dents), entrycmp);
  822. /* Find cur from history */
  823. cur = dentfind(dents, ndents, oldpath);
  824. return 0;
  825. }
  826. static void
  827. redraw(char *path)
  828. {
  829. static char cwd[PATH_MAX];
  830. static int nlines, odd;
  831. static int i;
  832. nlines = MIN(LINES - 4, ndents);
  833. /* Clean screen */
  834. erase();
  835. /* Strip trailing slashes */
  836. for (i = strlen(path) - 1; i > 0; i--)
  837. if (path[i] == '/')
  838. path[i] = '\0';
  839. else
  840. break;
  841. DPRINTF_D(cur);
  842. DPRINTF_S(path);
  843. /* No text wrapping in cwd line */
  844. if (!realpath(path, cwd)) {
  845. printmsg("Cannot resolve path");
  846. return;
  847. }
  848. printw(CWD "%s\n\n", cwd);
  849. /* Print listing */
  850. odd = ISODD(nlines);
  851. if (cur < (nlines >> 1)) {
  852. for (i = 0; i < nlines; i++)
  853. printptr(&dents[i], i == cur);
  854. } else if (cur >= ndents - (nlines >> 1)) {
  855. for (i = ndents - nlines; i < ndents; i++)
  856. printptr(&dents[i], i == cur);
  857. } else {
  858. nlines >>= 1;
  859. for (i = cur - nlines; i < cur + nlines + odd; i++)
  860. printptr(&dents[i], i == cur);
  861. }
  862. if (showdetail) {
  863. if (ndents) {
  864. static char ind[2] = "\0\0";
  865. static char sort[9];
  866. if (mtimeorder)
  867. sprintf(sort, "by time ");
  868. else if (sizeorder)
  869. sprintf(sort, "by size ");
  870. else
  871. sort[0] = '\0';
  872. if (S_ISDIR(dents[cur].mode))
  873. ind[0] = '/';
  874. else if (S_ISLNK(dents[cur].mode))
  875. ind[0] = '@';
  876. else if (S_ISSOCK(dents[cur].mode))
  877. ind[0] = '=';
  878. else if (S_ISFIFO(dents[cur].mode))
  879. ind[0] = '|';
  880. else if (dents[cur].mode & S_IXUSR)
  881. ind[0] = '*';
  882. else
  883. ind[0] = '\0';
  884. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  885. dents[cur].name, ind);
  886. printmsg(cwd);
  887. } else
  888. printmsg("0 items");
  889. }
  890. }
  891. static void
  892. browse(char *ipath, char *ifilter)
  893. {
  894. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  895. static char fltr[LINE_MAX];
  896. char *bin, *dir, *tmp, *run, *env;
  897. struct stat sb;
  898. regex_t re;
  899. int r, fd;
  900. xstrlcpy(path, ipath, sizeof(path));
  901. xstrlcpy(fltr, ifilter, sizeof(fltr));
  902. oldpath[0] = '\0';
  903. newpath[0] = '\0';
  904. begin:
  905. r = populate(path, oldpath, fltr);
  906. if (r == -1) {
  907. printwarn();
  908. goto nochange;
  909. }
  910. for (;;) {
  911. redraw(path);
  912. nochange:
  913. switch (nextsel(&run, &env)) {
  914. case SEL_QUIT:
  915. dentfree(dents);
  916. return;
  917. case SEL_BACK:
  918. /* There is no going back */
  919. if (strcmp(path, "/") == 0 ||
  920. strcmp(path, ".") == 0 ||
  921. strchr(path, '/') == NULL) {
  922. printmsg("You are at /");
  923. goto nochange;
  924. }
  925. dir = xdirname(path);
  926. if (canopendir(dir) == 0) {
  927. printwarn();
  928. goto nochange;
  929. }
  930. /* Save history */
  931. xstrlcpy(oldpath, path, sizeof(oldpath));
  932. xstrlcpy(path, dir, sizeof(path));
  933. /* Reset filter */
  934. xstrlcpy(fltr, ifilter, sizeof(fltr));
  935. goto begin;
  936. case SEL_GOIN:
  937. /* Cannot descend in empty directories */
  938. if (ndents == 0)
  939. goto nochange;
  940. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  941. DPRINTF_S(newpath);
  942. /* Get path info */
  943. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  944. if (fd == -1) {
  945. printwarn();
  946. goto nochange;
  947. }
  948. r = fstat(fd, &sb);
  949. if (r == -1) {
  950. printwarn();
  951. close(fd);
  952. goto nochange;
  953. }
  954. close(fd);
  955. DPRINTF_U(sb.st_mode);
  956. switch (sb.st_mode & S_IFMT) {
  957. case S_IFDIR:
  958. if (canopendir(newpath) == 0) {
  959. printwarn();
  960. goto nochange;
  961. }
  962. xstrlcpy(path, newpath, sizeof(path));
  963. /* Reset filter */
  964. xstrlcpy(fltr, ifilter, sizeof(fltr));
  965. goto begin;
  966. case S_IFREG:
  967. {
  968. static char cmd[MAX_CMD_LEN];
  969. static char *runvi = "vi";
  970. static int status;
  971. static FILE *fp;
  972. /* If default mime opener is set, use it */
  973. if (opener) {
  974. snprintf(cmd, MAX_CMD_LEN,
  975. "%s \"%s\" > /dev/null 2>&1",
  976. opener, newpath);
  977. status = system(cmd);
  978. continue;
  979. }
  980. /* Try custom applications */
  981. bin = openwith(newpath);
  982. if (bin == NULL) {
  983. /* If a custom handler application is
  984. not set, open plain text files with
  985. vi, then try fallback_opener */
  986. snprintf(cmd, MAX_CMD_LEN,
  987. "file \"%s\"", newpath);
  988. fp = popen(cmd, "r");
  989. if (fp == NULL)
  990. goto nochange;
  991. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  992. pclose(fp);
  993. goto nochange;
  994. }
  995. pclose(fp);
  996. if (strstr(cmd, "ASCII text") != NULL)
  997. bin = runvi;
  998. else if (fallback_opener) {
  999. snprintf(cmd, MAX_CMD_LEN,
  1000. "%s \"%s\" > \
  1001. /dev/null 2>&1",
  1002. fallback_opener,
  1003. newpath);
  1004. status = system(cmd);
  1005. continue;
  1006. } else {
  1007. printmsg("No association");
  1008. goto nochange;
  1009. }
  1010. }
  1011. exitcurses();
  1012. spawn(bin, newpath, NULL);
  1013. initcurses();
  1014. continue;
  1015. }
  1016. default:
  1017. printmsg("Unsupported file");
  1018. goto nochange;
  1019. }
  1020. case SEL_FLTR:
  1021. /* Read filter */
  1022. printprompt("filter: ");
  1023. tmp = readln();
  1024. if (tmp == NULL)
  1025. tmp = ifilter;
  1026. /* Check and report regex errors */
  1027. r = setfilter(&re, tmp);
  1028. if (r != 0)
  1029. goto nochange;
  1030. xstrlcpy(fltr, tmp, sizeof(fltr));
  1031. DPRINTF_S(fltr);
  1032. /* Save current */
  1033. if (ndents > 0)
  1034. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1035. goto begin;
  1036. case SEL_NEXT:
  1037. if (cur < ndents - 1)
  1038. cur++;
  1039. else if (ndents)
  1040. /* Roll over, set cursor to first entry */
  1041. cur = 0;
  1042. break;
  1043. case SEL_PREV:
  1044. if (cur > 0)
  1045. cur--;
  1046. else if (ndents)
  1047. /* Roll over, set cursor to last entry */
  1048. cur = ndents - 1;
  1049. break;
  1050. case SEL_PGDN:
  1051. if (cur < ndents - 1)
  1052. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1053. break;
  1054. case SEL_PGUP:
  1055. if (cur > 0)
  1056. cur -= MIN((LINES - 4) / 2, cur);
  1057. break;
  1058. case SEL_HOME:
  1059. cur = 0;
  1060. break;
  1061. case SEL_END:
  1062. cur = ndents - 1;
  1063. break;
  1064. case SEL_CD:
  1065. /* Read target dir */
  1066. printprompt("chdir: ");
  1067. tmp = readln();
  1068. if (tmp == NULL) {
  1069. clearprompt();
  1070. goto nochange;
  1071. }
  1072. mkpath(path, tmp, newpath, sizeof(newpath));
  1073. if (canopendir(newpath) == 0) {
  1074. printwarn();
  1075. goto nochange;
  1076. }
  1077. xstrlcpy(path, newpath, sizeof(path));
  1078. /* Reset filter */
  1079. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1080. DPRINTF_S(path);
  1081. goto begin;
  1082. case SEL_CDHOME:
  1083. tmp = getenv("HOME");
  1084. if (tmp == NULL) {
  1085. clearprompt();
  1086. goto nochange;
  1087. }
  1088. if (canopendir(tmp) == 0) {
  1089. printwarn();
  1090. goto nochange;
  1091. }
  1092. xstrlcpy(path, tmp, sizeof(path));
  1093. /* Reset filter */
  1094. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1095. DPRINTF_S(path);
  1096. goto begin;
  1097. case SEL_TOGGLEDOT:
  1098. showhidden ^= 1;
  1099. initfilter(showhidden, &ifilter);
  1100. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1101. goto begin;
  1102. case SEL_DETAIL:
  1103. showdetail = !showdetail;
  1104. showdetail ? (printptr = &printent_long)
  1105. : (printptr = &printent);
  1106. /* Save current */
  1107. if (ndents > 0)
  1108. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1109. goto begin;
  1110. case SEL_STATS:
  1111. {
  1112. struct stat sb;
  1113. if (ndents > 0)
  1114. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1115. r = lstat(oldpath, &sb);
  1116. if (r == -1)
  1117. printerr(1, "lstat");
  1118. else
  1119. show_stats(oldpath, dents[cur].name, &sb);
  1120. goto begin;
  1121. }
  1122. case SEL_FSIZE:
  1123. sizeorder = !sizeorder;
  1124. mtimeorder = 0;
  1125. /* Save current */
  1126. if (ndents > 0)
  1127. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1128. goto begin;
  1129. case SEL_MTIME:
  1130. mtimeorder = !mtimeorder;
  1131. sizeorder = 0;
  1132. /* Save current */
  1133. if (ndents > 0)
  1134. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1135. goto begin;
  1136. case SEL_REDRAW:
  1137. /* Save current */
  1138. if (ndents > 0)
  1139. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1140. goto begin;
  1141. case SEL_COPY:
  1142. if (copier && ndents) {
  1143. char abspath[PATH_MAX];
  1144. if (strcmp(path, "/") == 0)
  1145. snprintf(abspath, PATH_MAX, "/%s",
  1146. dents[cur].name);
  1147. else
  1148. snprintf(abspath, PATH_MAX, "%s/%s",
  1149. path, dents[cur].name);
  1150. spawn(copier, abspath, NULL);
  1151. printmsg(abspath);
  1152. } else if (!copier)
  1153. printmsg("NNN_COPIER is not set");
  1154. goto nochange;
  1155. case SEL_HELP:
  1156. show_help();
  1157. /* Save current */
  1158. if (ndents > 0)
  1159. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1160. goto begin;
  1161. case SEL_RUN:
  1162. run = xgetenv(env, run);
  1163. exitcurses();
  1164. spawn(run, NULL, path);
  1165. initcurses();
  1166. /* Re-populate as directory content may have changed */
  1167. goto begin;
  1168. case SEL_RUNARG:
  1169. run = xgetenv(env, run);
  1170. exitcurses();
  1171. spawn(run, dents[cur].name, path);
  1172. initcurses();
  1173. break;
  1174. }
  1175. /* Screensaver */
  1176. if (idletimeout != 0 && idle == idletimeout) {
  1177. idle = 0;
  1178. exitcurses();
  1179. spawn(idlecmd, NULL, NULL);
  1180. initcurses();
  1181. }
  1182. }
  1183. }
  1184. static void
  1185. usage(void)
  1186. {
  1187. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  1188. exit(1);
  1189. }
  1190. int
  1191. main(int argc, char *argv[])
  1192. {
  1193. char cwd[PATH_MAX], *ipath;
  1194. char *ifilter;
  1195. int opt = 0;
  1196. /* Confirm we are in a terminal */
  1197. if (!isatty(0) || !isatty(1)) {
  1198. fprintf(stderr, "stdin or stdout is not a tty\n");
  1199. exit(1);
  1200. }
  1201. if (argc > 3)
  1202. usage();
  1203. while ((opt = getopt(argc, argv, "d")) != -1) {
  1204. switch (opt) {
  1205. case 'd':
  1206. /* Open in detail mode, if set */
  1207. showdetail = 1;
  1208. printptr = &printent_long;
  1209. break;
  1210. default:
  1211. usage();
  1212. }
  1213. }
  1214. if (argc == optind) {
  1215. /* Start in the current directory */
  1216. ipath = getcwd(cwd, sizeof(cwd));
  1217. if (ipath == NULL)
  1218. ipath = "/";
  1219. } else {
  1220. ipath = realpath(argv[optind], cwd);
  1221. if (!ipath) {
  1222. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1223. exit(1);
  1224. }
  1225. }
  1226. if (getuid() == 0)
  1227. showhidden = 1;
  1228. initfilter(showhidden, &ifilter);
  1229. /* Get the default desktop mime opener, if set */
  1230. opener = getenv("NNN_OPENER");
  1231. /* Get the fallback desktop mime opener, if set */
  1232. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1233. /* Get the default copier, if set */
  1234. copier = getenv("NNN_COPIER");
  1235. signal(SIGINT, SIG_IGN);
  1236. /* Test initial path */
  1237. if (canopendir(ipath) == 0) {
  1238. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1239. exit(1);
  1240. }
  1241. /* Set locale before curses setup */
  1242. setlocale(LC_ALL, "");
  1243. initcurses();
  1244. browse(ipath, ifilter);
  1245. exitcurses();
  1246. exit(0);
  1247. }