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.
 
 
 
 
 
 

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