My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

1435 linhas
30 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", fpath);
  692. p = get_output(buf, PATH_MAX + 48);
  693. if (p) {
  694. p = xmemrchr(buf, ' ', strlen(buf));
  695. if (!p)
  696. p = buf;
  697. else
  698. p++;
  699. printw("\n md5: %s", p);
  700. }
  701. /* Show sha256 */
  702. sprintf(buf, "openssl sha256 \"%s\" 2>&1", fpath);
  703. p = get_output(buf, PATH_MAX + 48);
  704. if (p) {
  705. p = xmemrchr(buf, ' ', strlen(buf));
  706. if (!p)
  707. p = buf;
  708. else
  709. p++;
  710. printw(" sha256: %s", p);
  711. }
  712. }
  713. /* Show exit keys */
  714. printw("\n\n << (q/Esc)");
  715. while (*buf = getch())
  716. if (*buf == 'q' || *buf == 27)
  717. return;
  718. }
  719. void
  720. show_help(void)
  721. {
  722. char c;
  723. clear();
  724. printw("\n\
  725. << Key >> << Function >>\n\n\
  726. [Up], k, ^P Previous entry\n\
  727. [Down], j, ^N Next entry\n\
  728. [PgUp], ^U Scroll half page up\n\
  729. [PgDn], ^D Scroll half page down\n\
  730. [Home], ^, ^A Jump to first dir entry\n\
  731. [End], $, ^E Jump to last dir entry\n\
  732. [Right], [Enter], l, ^M Open file or enter dir\n\
  733. [Left], [Backspace], h, ^H Go to parent dir\n\
  734. ~ Jump to HOME dir\n\
  735. /, & Filter dir contents\n\
  736. c Show change dir prompt\n\
  737. d Toggle detail view\n\
  738. D Show details of selected file\n\
  739. . Toggle hide .dot files\n\
  740. s Toggle sort by file size\n\
  741. t Toggle sort by modified time\n\
  742. ! Spawn SHELL in PWD (fallback sh)\n\
  743. z Run top\n\
  744. e Edit entry in EDITOR (fallback vi)\n\
  745. p Open entry in PAGER (fallback less)\n\
  746. ^K Invoke file name copier\n\
  747. ^L Force a redraw\n\
  748. ? Show help\n\
  749. q Quit\n");
  750. /* Show exit keys */
  751. printw("\n\n << (q/Esc)");
  752. while (c = getch())
  753. if (c == 'q' || c == 27)
  754. return;
  755. }
  756. static int
  757. dentfill(char *path, struct entry **dents,
  758. int (*filter)(regex_t *, char *), regex_t *re)
  759. {
  760. char newpath[PATH_MAX];
  761. DIR *dirp;
  762. struct dirent *dp;
  763. struct stat sb;
  764. int r, n = 0;
  765. dirp = opendir(path);
  766. if (dirp == NULL)
  767. return 0;
  768. while ((dp = readdir(dirp)) != NULL) {
  769. /* Skip self and parent */
  770. if (strcmp(dp->d_name, ".") == 0 ||
  771. strcmp(dp->d_name, "..") == 0)
  772. continue;
  773. if (filter(re, dp->d_name) == 0)
  774. continue;
  775. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  776. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  777. /* Get mode flags */
  778. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  779. r = lstat(newpath, &sb);
  780. if (r == -1)
  781. printerr(1, "lstat");
  782. (*dents)[n].mode = sb.st_mode;
  783. (*dents)[n].t = sb.st_mtime;
  784. (*dents)[n].size = sb.st_size;
  785. n++;
  786. }
  787. /* Should never be null */
  788. r = closedir(dirp);
  789. if (r == -1)
  790. printerr(1, "closedir");
  791. return n;
  792. }
  793. static void
  794. dentfree(struct entry *dents)
  795. {
  796. free(dents);
  797. }
  798. /* Return the position of the matching entry or 0 otherwise */
  799. static int
  800. dentfind(struct entry *dents, int n, char *path)
  801. {
  802. if (!path)
  803. return 0;
  804. char *p = xmemrchr(path, '/', strlen(path));
  805. if (!p)
  806. p = path;
  807. else
  808. /* We are assuming an entry with actual
  809. name ending in '/' will not appear */
  810. p++;
  811. DPRINTF_S(p);
  812. for (int i = 0; i < n; i++)
  813. if (strcmp(p, dents[i].name) == 0)
  814. return i;
  815. return 0;
  816. }
  817. static int
  818. populate(char *path, char *oldpath, char *fltr)
  819. {
  820. regex_t re;
  821. int r;
  822. /* Can fail when permissions change while browsing */
  823. if (canopendir(path) == 0)
  824. return -1;
  825. /* Search filter */
  826. r = setfilter(&re, fltr);
  827. if (r != 0)
  828. return -1;
  829. dentfree(dents);
  830. ndents = 0;
  831. dents = NULL;
  832. ndents = dentfill(path, &dents, visible, &re);
  833. qsort(dents, ndents, sizeof(*dents), entrycmp);
  834. /* Find cur from history */
  835. cur = dentfind(dents, ndents, oldpath);
  836. return 0;
  837. }
  838. static void
  839. redraw(char *path)
  840. {
  841. static char cwd[PATH_MAX];
  842. static int nlines, odd;
  843. static int i;
  844. nlines = MIN(LINES - 4, ndents);
  845. /* Clean screen */
  846. erase();
  847. /* Strip trailing slashes */
  848. for (i = strlen(path) - 1; i > 0; i--)
  849. if (path[i] == '/')
  850. path[i] = '\0';
  851. else
  852. break;
  853. DPRINTF_D(cur);
  854. DPRINTF_S(path);
  855. /* No text wrapping in cwd line */
  856. if (!realpath(path, cwd)) {
  857. printmsg("Cannot resolve path");
  858. return;
  859. }
  860. printw(CWD "%s\n\n", cwd);
  861. /* Print listing */
  862. odd = ISODD(nlines);
  863. if (cur < (nlines >> 1)) {
  864. for (i = 0; i < nlines; i++)
  865. printptr(&dents[i], i == cur);
  866. } else if (cur >= ndents - (nlines >> 1)) {
  867. for (i = ndents - nlines; i < ndents; i++)
  868. printptr(&dents[i], i == cur);
  869. } else {
  870. nlines >>= 1;
  871. for (i = cur - nlines; i < cur + nlines + odd; i++)
  872. printptr(&dents[i], i == cur);
  873. }
  874. if (showdetail) {
  875. if (ndents) {
  876. static char ind[2] = "\0\0";
  877. static char sort[9];
  878. if (mtimeorder)
  879. sprintf(sort, "by time ");
  880. else if (sizeorder)
  881. sprintf(sort, "by size ");
  882. else
  883. sort[0] = '\0';
  884. if (S_ISDIR(dents[cur].mode))
  885. ind[0] = '/';
  886. else if (S_ISLNK(dents[cur].mode))
  887. ind[0] = '@';
  888. else if (S_ISSOCK(dents[cur].mode))
  889. ind[0] = '=';
  890. else if (S_ISFIFO(dents[cur].mode))
  891. ind[0] = '|';
  892. else if (dents[cur].mode & S_IXUSR)
  893. ind[0] = '*';
  894. else
  895. ind[0] = '\0';
  896. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  897. dents[cur].name, ind);
  898. printmsg(cwd);
  899. } else
  900. printmsg("0 items");
  901. }
  902. }
  903. static void
  904. browse(char *ipath, char *ifilter)
  905. {
  906. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  907. static char fltr[LINE_MAX];
  908. char *bin, *dir, *tmp, *run, *env;
  909. struct stat sb;
  910. regex_t re;
  911. int r, fd;
  912. xstrlcpy(path, ipath, sizeof(path));
  913. xstrlcpy(fltr, ifilter, sizeof(fltr));
  914. oldpath[0] = '\0';
  915. newpath[0] = '\0';
  916. begin:
  917. r = populate(path, oldpath, fltr);
  918. if (r == -1) {
  919. printwarn();
  920. goto nochange;
  921. }
  922. for (;;) {
  923. redraw(path);
  924. nochange:
  925. switch (nextsel(&run, &env)) {
  926. case SEL_QUIT:
  927. dentfree(dents);
  928. return;
  929. case SEL_BACK:
  930. /* There is no going back */
  931. if (strcmp(path, "/") == 0 ||
  932. strcmp(path, ".") == 0 ||
  933. strchr(path, '/') == NULL) {
  934. printmsg("You are at /");
  935. goto nochange;
  936. }
  937. dir = xdirname(path);
  938. if (canopendir(dir) == 0) {
  939. printwarn();
  940. goto nochange;
  941. }
  942. /* Save history */
  943. xstrlcpy(oldpath, path, sizeof(oldpath));
  944. xstrlcpy(path, dir, sizeof(path));
  945. /* Reset filter */
  946. xstrlcpy(fltr, ifilter, sizeof(fltr));
  947. goto begin;
  948. case SEL_GOIN:
  949. /* Cannot descend in empty directories */
  950. if (ndents == 0)
  951. goto nochange;
  952. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  953. DPRINTF_S(newpath);
  954. /* Get path info */
  955. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  956. if (fd == -1) {
  957. printwarn();
  958. goto nochange;
  959. }
  960. r = fstat(fd, &sb);
  961. if (r == -1) {
  962. printwarn();
  963. close(fd);
  964. goto nochange;
  965. }
  966. close(fd);
  967. DPRINTF_U(sb.st_mode);
  968. switch (sb.st_mode & S_IFMT) {
  969. case S_IFDIR:
  970. if (canopendir(newpath) == 0) {
  971. printwarn();
  972. goto nochange;
  973. }
  974. xstrlcpy(path, newpath, sizeof(path));
  975. /* Reset filter */
  976. xstrlcpy(fltr, ifilter, sizeof(fltr));
  977. goto begin;
  978. case S_IFREG:
  979. {
  980. static char cmd[MAX_CMD_LEN];
  981. static char *runvi = "vi";
  982. static int status;
  983. static FILE *fp;
  984. /* If default mime opener is set, use it */
  985. if (opener) {
  986. snprintf(cmd, MAX_CMD_LEN,
  987. "%s \"%s\" > /dev/null 2>&1",
  988. opener, newpath);
  989. status = system(cmd);
  990. continue;
  991. }
  992. /* Try custom applications */
  993. bin = openwith(newpath);
  994. if (bin == NULL) {
  995. /* If a custom handler application is
  996. not set, open plain text files with
  997. vi, then try fallback_opener */
  998. snprintf(cmd, MAX_CMD_LEN,
  999. "file \"%s\"", newpath);
  1000. fp = popen(cmd, "r");
  1001. if (fp == NULL)
  1002. goto nochange;
  1003. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  1004. pclose(fp);
  1005. goto nochange;
  1006. }
  1007. pclose(fp);
  1008. if (strstr(cmd, "ASCII text") != NULL)
  1009. bin = runvi;
  1010. else if (fallback_opener) {
  1011. snprintf(cmd, MAX_CMD_LEN,
  1012. "%s \"%s\" > \
  1013. /dev/null 2>&1",
  1014. fallback_opener,
  1015. newpath);
  1016. status = system(cmd);
  1017. continue;
  1018. } else {
  1019. printmsg("No association");
  1020. goto nochange;
  1021. }
  1022. }
  1023. exitcurses();
  1024. spawn(bin, newpath, NULL);
  1025. initcurses();
  1026. continue;
  1027. }
  1028. default:
  1029. printmsg("Unsupported file");
  1030. goto nochange;
  1031. }
  1032. case SEL_FLTR:
  1033. /* Read filter */
  1034. printprompt("filter: ");
  1035. tmp = readln();
  1036. if (tmp == NULL)
  1037. tmp = ifilter;
  1038. /* Check and report regex errors */
  1039. r = setfilter(&re, tmp);
  1040. if (r != 0)
  1041. goto nochange;
  1042. xstrlcpy(fltr, tmp, sizeof(fltr));
  1043. DPRINTF_S(fltr);
  1044. /* Save current */
  1045. if (ndents > 0)
  1046. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1047. goto begin;
  1048. case SEL_NEXT:
  1049. if (cur < ndents - 1)
  1050. cur++;
  1051. else if (ndents)
  1052. /* Roll over, set cursor to first entry */
  1053. cur = 0;
  1054. break;
  1055. case SEL_PREV:
  1056. if (cur > 0)
  1057. cur--;
  1058. else if (ndents)
  1059. /* Roll over, set cursor to last entry */
  1060. cur = ndents - 1;
  1061. break;
  1062. case SEL_PGDN:
  1063. if (cur < ndents - 1)
  1064. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1065. break;
  1066. case SEL_PGUP:
  1067. if (cur > 0)
  1068. cur -= MIN((LINES - 4) / 2, cur);
  1069. break;
  1070. case SEL_HOME:
  1071. cur = 0;
  1072. break;
  1073. case SEL_END:
  1074. cur = ndents - 1;
  1075. break;
  1076. case SEL_CD:
  1077. /* Read target dir */
  1078. printprompt("chdir: ");
  1079. tmp = readln();
  1080. if (tmp == NULL) {
  1081. clearprompt();
  1082. goto nochange;
  1083. }
  1084. mkpath(path, tmp, newpath, sizeof(newpath));
  1085. if (canopendir(newpath) == 0) {
  1086. printwarn();
  1087. goto nochange;
  1088. }
  1089. xstrlcpy(path, newpath, sizeof(path));
  1090. /* Reset filter */
  1091. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1092. DPRINTF_S(path);
  1093. goto begin;
  1094. case SEL_CDHOME:
  1095. tmp = getenv("HOME");
  1096. if (tmp == NULL) {
  1097. clearprompt();
  1098. goto nochange;
  1099. }
  1100. if (canopendir(tmp) == 0) {
  1101. printwarn();
  1102. goto nochange;
  1103. }
  1104. xstrlcpy(path, tmp, sizeof(path));
  1105. /* Reset filter */
  1106. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1107. DPRINTF_S(path);
  1108. goto begin;
  1109. case SEL_TOGGLEDOT:
  1110. showhidden ^= 1;
  1111. initfilter(showhidden, &ifilter);
  1112. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1113. goto begin;
  1114. case SEL_DETAIL:
  1115. showdetail = !showdetail;
  1116. showdetail ? (printptr = &printent_long)
  1117. : (printptr = &printent);
  1118. /* Save current */
  1119. if (ndents > 0)
  1120. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1121. goto begin;
  1122. case SEL_STATS:
  1123. {
  1124. struct stat sb;
  1125. if (ndents > 0)
  1126. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1127. r = lstat(oldpath, &sb);
  1128. if (r == -1)
  1129. printerr(1, "lstat");
  1130. else
  1131. show_stats(oldpath, dents[cur].name, &sb);
  1132. goto begin;
  1133. }
  1134. case SEL_FSIZE:
  1135. sizeorder = !sizeorder;
  1136. mtimeorder = 0;
  1137. /* Save current */
  1138. if (ndents > 0)
  1139. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1140. goto begin;
  1141. case SEL_MTIME:
  1142. mtimeorder = !mtimeorder;
  1143. sizeorder = 0;
  1144. /* Save current */
  1145. if (ndents > 0)
  1146. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1147. goto begin;
  1148. case SEL_REDRAW:
  1149. /* Save current */
  1150. if (ndents > 0)
  1151. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1152. goto begin;
  1153. case SEL_COPY:
  1154. if (copier && ndents) {
  1155. char abspath[PATH_MAX];
  1156. if (strcmp(path, "/") == 0)
  1157. snprintf(abspath, PATH_MAX, "/%s",
  1158. dents[cur].name);
  1159. else
  1160. snprintf(abspath, PATH_MAX, "%s/%s",
  1161. path, dents[cur].name);
  1162. spawn(copier, abspath, NULL);
  1163. printmsg(abspath);
  1164. } else if (!copier)
  1165. printmsg("NNN_COPIER is not set");
  1166. goto nochange;
  1167. case SEL_HELP:
  1168. show_help();
  1169. /* Save current */
  1170. if (ndents > 0)
  1171. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1172. goto begin;
  1173. case SEL_RUN:
  1174. run = xgetenv(env, run);
  1175. exitcurses();
  1176. spawn(run, NULL, path);
  1177. initcurses();
  1178. /* Re-populate as directory content may have changed */
  1179. goto begin;
  1180. case SEL_RUNARG:
  1181. run = xgetenv(env, run);
  1182. exitcurses();
  1183. spawn(run, dents[cur].name, path);
  1184. initcurses();
  1185. break;
  1186. }
  1187. /* Screensaver */
  1188. if (idletimeout != 0 && idle == idletimeout) {
  1189. idle = 0;
  1190. exitcurses();
  1191. spawn(idlecmd, NULL, NULL);
  1192. initcurses();
  1193. }
  1194. }
  1195. }
  1196. static void
  1197. usage(void)
  1198. {
  1199. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  1200. exit(1);
  1201. }
  1202. int
  1203. main(int argc, char *argv[])
  1204. {
  1205. char cwd[PATH_MAX], *ipath;
  1206. char *ifilter;
  1207. int opt = 0;
  1208. /* Confirm we are in a terminal */
  1209. if (!isatty(0) || !isatty(1)) {
  1210. fprintf(stderr, "stdin or stdout is not a tty\n");
  1211. exit(1);
  1212. }
  1213. if (argc > 3)
  1214. usage();
  1215. while ((opt = getopt(argc, argv, "d")) != -1) {
  1216. switch (opt) {
  1217. case 'd':
  1218. /* Open in detail mode, if set */
  1219. showdetail = 1;
  1220. printptr = &printent_long;
  1221. break;
  1222. default:
  1223. usage();
  1224. }
  1225. }
  1226. if (argc == optind) {
  1227. /* Start in the current directory */
  1228. ipath = getcwd(cwd, sizeof(cwd));
  1229. if (ipath == NULL)
  1230. ipath = "/";
  1231. } else {
  1232. ipath = realpath(argv[optind], cwd);
  1233. if (!ipath) {
  1234. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1235. exit(1);
  1236. }
  1237. }
  1238. if (getuid() == 0)
  1239. showhidden = 1;
  1240. initfilter(showhidden, &ifilter);
  1241. /* Get the default desktop mime opener, if set */
  1242. opener = getenv("NNN_OPENER");
  1243. /* Get the fallback desktop mime opener, if set */
  1244. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1245. /* Get the default copier, if set */
  1246. copier = getenv("NNN_COPIER");
  1247. signal(SIGINT, SIG_IGN);
  1248. /* Test initial path */
  1249. if (canopendir(ipath) == 0) {
  1250. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1251. exit(1);
  1252. }
  1253. /* Set locale before curses setup */
  1254. setlocale(LC_ALL, "");
  1255. initcurses();
  1256. browse(ipath, ifilter);
  1257. exitcurses();
  1258. exit(0);
  1259. }