Another copy of my dotfiles. Because I don't completely trust GitHub.
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.

594 lines
12 KiB

  1. /*
  2. * Based on an example code from Roberto E. Vargas Caballero.
  3. *
  4. * See LICENSE file for copyright and license details.
  5. */
  6. #include <sys/types.h>
  7. #include <sys/ioctl.h>
  8. #include <sys/wait.h>
  9. #include <sys/queue.h>
  10. #include <sys/resource.h>
  11. #include <assert.h>
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <poll.h>
  15. #include <pwd.h>
  16. #include <signal.h>
  17. #include <stdarg.h>
  18. #include <stdbool.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <termios.h>
  23. #include <unistd.h>
  24. #if defined(__linux)
  25. #include <pty.h>
  26. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  27. #include <util.h>
  28. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  29. #include <libutil.h>
  30. #endif
  31. #define LENGTH(X) (sizeof (X) / sizeof ((X)[0]))
  32. const char *argv0;
  33. TAILQ_HEAD(tailhead, line) head;
  34. struct line {
  35. TAILQ_ENTRY(line) entries;
  36. size_t size;
  37. size_t len;
  38. char *buf;
  39. } *bottom;
  40. pid_t child;
  41. int mfd;
  42. struct termios dfl;
  43. struct winsize ws;
  44. static bool altscreen = false; /* is alternative screen active */
  45. static bool doredraw = false; /* redraw upon sigwinch */
  46. struct rule {
  47. const char *seq;
  48. enum {SCROLL_UP, SCROLL_DOWN} event;
  49. short lines;
  50. };
  51. #include "config.h"
  52. void
  53. die(const char *fmt, ...)
  54. {
  55. va_list ap;
  56. va_start(ap, fmt);
  57. vfprintf(stderr, fmt, ap);
  58. va_end(ap);
  59. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  60. fputc(' ', stderr);
  61. perror(NULL);
  62. } else {
  63. fputc('\n', stderr);
  64. }
  65. exit(EXIT_FAILURE);
  66. }
  67. void
  68. sigwinch(int sig)
  69. {
  70. assert(sig == SIGWINCH);
  71. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  72. die("ioctl:");
  73. if (ioctl(mfd, TIOCSWINSZ, &ws) == -1) {
  74. if (errno == EBADF) /* child already exited */
  75. return;
  76. die("ioctl:");
  77. }
  78. kill(-child, SIGWINCH);
  79. doredraw = true;
  80. }
  81. void
  82. reset(void)
  83. {
  84. if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
  85. die("tcsetattr:");
  86. }
  87. /* error avoiding remalloc */
  88. void *
  89. earealloc(void *ptr, size_t size)
  90. {
  91. void *mem;
  92. while ((mem = realloc(ptr, size)) == NULL) {
  93. struct line *line = TAILQ_LAST(&head, tailhead);
  94. if (line == NULL)
  95. die("realloc:");
  96. TAILQ_REMOVE(&head, line, entries);
  97. free(line->buf);
  98. free(line);
  99. }
  100. return mem;
  101. }
  102. /* Count string length w/o ansi esc sequences. */
  103. size_t
  104. strelen(const char *buf, size_t size)
  105. {
  106. enum {CHAR, BREK, ESC} state = CHAR;
  107. size_t len = 0;
  108. for (size_t i = 0; i < size; i++) {
  109. char c = buf[i];
  110. switch (state) {
  111. case CHAR:
  112. if (c == '\033')
  113. state = BREK;
  114. else
  115. len++;
  116. break;
  117. case BREK:
  118. if (c == '[') {
  119. state = ESC;
  120. } else {
  121. state = CHAR;
  122. len++;
  123. }
  124. break;
  125. case ESC:
  126. if (c >= 64 && c <= 126)
  127. state = CHAR;
  128. break;
  129. }
  130. }
  131. return len;
  132. }
  133. /* detect alternative screen switching and clear screen */
  134. bool
  135. skipesc(char c)
  136. {
  137. static enum {CHAR, BREK, ESC} state = CHAR;
  138. static char buf[BUFSIZ];
  139. static size_t i = 0;
  140. switch (state) {
  141. case CHAR:
  142. if (c == '\033')
  143. state = BREK;
  144. break;
  145. case BREK:
  146. if (c == '[')
  147. state = ESC;
  148. else
  149. state = CHAR;
  150. break;
  151. case ESC:
  152. buf[i++] = c;
  153. if (i == sizeof buf) {
  154. /* TODO: find a better way to handle this situation */
  155. state = CHAR;
  156. i = 0;
  157. } else if (c >= 64 && c <= 126) {
  158. state = CHAR;
  159. buf[i] = '\0';
  160. i = 0;
  161. /* esc seq. enable alternative screen */
  162. if (strcmp(buf, "?1049h") == 0 ||
  163. strcmp(buf, "?1047h") == 0 ||
  164. strcmp(buf, "?47h" ) == 0)
  165. altscreen = true;
  166. /* esc seq. disable alternative screen */
  167. if (strcmp(buf, "?1049l") == 0 ||
  168. strcmp(buf, "?1047l") == 0 ||
  169. strcmp(buf, "?47l" ) == 0)
  170. altscreen = false;
  171. /* don't save cursor move or clear screen */
  172. /* esc sequences to log */
  173. switch (c) {
  174. case 'A':
  175. case 'B':
  176. case 'C':
  177. case 'D':
  178. case 'H':
  179. case 'J':
  180. case 'K':
  181. case 'f':
  182. return true;
  183. }
  184. }
  185. break;
  186. }
  187. return altscreen;
  188. }
  189. void
  190. getcursorposition(int *x, int *y)
  191. {
  192. char input[BUFSIZ];
  193. ssize_t n;
  194. if (write(STDOUT_FILENO, "\033[6n", 4) == -1)
  195. die("requesting cursor position");
  196. do {
  197. if ((n = read(STDIN_FILENO, input, sizeof(input)-1)) == -1)
  198. die("reading cursor position");
  199. input[n] = '\0';
  200. } while (sscanf(input, "\033[%d;%dR", y, x) != 2);
  201. if (*x <= 0 || *y <= 0)
  202. die("invalid cursor position: x=%d y=%d", *x, *y);
  203. }
  204. void
  205. addline(char *buf, size_t size)
  206. {
  207. struct line *line = earealloc(NULL, sizeof *line);
  208. line->size = size;
  209. line->len = strelen(buf, size);
  210. line->buf = earealloc(NULL, size);
  211. memcpy(line->buf, buf, size);
  212. TAILQ_INSERT_HEAD(&head, line, entries);
  213. }
  214. void
  215. redraw()
  216. {
  217. int rows = 0, x, y;
  218. if (bottom == NULL)
  219. return;
  220. getcursorposition(&x, &y);
  221. if (y < ws.ws_row-1)
  222. y--;
  223. /* wind back bottom pointer by shown history */
  224. for (; bottom != NULL && TAILQ_NEXT(bottom, entries) != NULL &&
  225. rows < y - 1; rows++)
  226. bottom = TAILQ_NEXT(bottom, entries);
  227. /* clear screen */
  228. dprintf(STDOUT_FILENO, "\033[2J");
  229. /* set cursor position to upper left corner */
  230. write(STDOUT_FILENO, "\033[0;0H", 6);
  231. /* remove newline of first line as we are at 0,0 already */
  232. if (bottom->size > 0 && bottom->buf[0] == '\n')
  233. write(STDOUT_FILENO, bottom->buf + 1, bottom->size - 1);
  234. else
  235. write(STDOUT_FILENO, bottom->buf, bottom->size);
  236. for (rows = ws.ws_row; rows > 0 &&
  237. TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  238. bottom = TAILQ_PREV(bottom, tailhead, entries);
  239. write(STDOUT_FILENO, bottom->buf, bottom->size);
  240. }
  241. if (bottom == TAILQ_FIRST(&head)) {
  242. /* add new line in front of the shell prompt */
  243. write(STDOUT_FILENO, "\n", 1);
  244. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  245. } else
  246. bottom = TAILQ_NEXT(bottom, entries);
  247. }
  248. void
  249. scrollup(int n)
  250. {
  251. int rows = 2, x, y, extra = 0;
  252. struct line *scrollend = bottom;
  253. if (bottom == NULL)
  254. return;
  255. getcursorposition(&x, &y);
  256. if (n < 0) /* scroll by fraction of ws.ws_row, but at least one line */
  257. n = ws.ws_row > (-n) ? ws.ws_row / (-n) : 1;
  258. /* wind back scrollend pointer by the current screen */
  259. while (rows < y && TAILQ_NEXT(scrollend, entries) != NULL) {
  260. scrollend = TAILQ_NEXT(scrollend, entries);
  261. rows += (scrollend->len - 1) / ws.ws_col + 1;
  262. }
  263. if (rows <= 0)
  264. return;
  265. /* wind back scrollend pointer n lines */
  266. for (rows = 0; rows + extra < n &&
  267. TAILQ_NEXT(scrollend, entries) != NULL; rows++) {
  268. scrollend = TAILQ_NEXT(scrollend, entries);
  269. extra += (scrollend->len - 1) / ws.ws_col;
  270. }
  271. /* move the text in terminal rows lines down */
  272. dprintf(STDOUT_FILENO, "\033[%dT", n);
  273. /* set cursor position to upper left corner */
  274. write(STDOUT_FILENO, "\033[0;0H", 6);
  275. /* hide cursor */
  276. write(STDOUT_FILENO, "\033[?25l", 6);
  277. /* remove newline of first line as we are at 0,0 already */
  278. if (scrollend->size > 0 && scrollend->buf[0] == '\n')
  279. write(STDOUT_FILENO, scrollend->buf + 1, scrollend->size - 1);
  280. else
  281. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  282. if (y + n >= ws.ws_row)
  283. bottom = TAILQ_NEXT(bottom, entries);
  284. /* print rows lines and move bottom forward to the new screen bottom */
  285. for (; rows > 1; rows--) {
  286. scrollend = TAILQ_PREV(scrollend, tailhead, entries);
  287. if (y + n >= ws.ws_row)
  288. bottom = TAILQ_NEXT(bottom, entries);
  289. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  290. }
  291. /* move cursor from line n to the old bottom position */
  292. if (y + n < ws.ws_row) {
  293. dprintf(STDOUT_FILENO, "\033[%d;%dH", y + n, x);
  294. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  295. } else
  296. dprintf(STDOUT_FILENO, "\033[%d;0H", ws.ws_row);
  297. }
  298. void
  299. scrolldown(char *buf, size_t size, int n)
  300. {
  301. if (bottom == NULL || bottom == TAILQ_FIRST(&head))
  302. return;
  303. if (n < 0) /* scroll by fraction of ws.ws_row, but at least one line */
  304. n = ws.ws_row > (-n) ? ws.ws_row / (-n) : 1;
  305. bottom = TAILQ_PREV(bottom, tailhead, entries);
  306. /* print n lines */
  307. while (n > 0 && bottom != NULL && bottom != TAILQ_FIRST(&head)) {
  308. bottom = TAILQ_PREV(bottom, tailhead, entries);
  309. write(STDOUT_FILENO, bottom->buf, bottom->size);
  310. n -= (bottom->len - 1) / ws.ws_col + 1;
  311. }
  312. if (n > 0 && bottom == TAILQ_FIRST(&head)) {
  313. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  314. write(STDOUT_FILENO, buf, size);
  315. } else if (bottom != NULL)
  316. bottom = TAILQ_NEXT(bottom, entries);
  317. }
  318. void
  319. jumpdown(char *buf, size_t size)
  320. {
  321. int rows = ws.ws_row;
  322. /* wind back by one page starting from the latest line */
  323. bottom = TAILQ_FIRST(&head);
  324. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  325. bottom = TAILQ_NEXT(bottom, entries);
  326. scrolldown(buf, size, ws.ws_row);
  327. }
  328. void
  329. usage(void) {
  330. die("usage: %s [-Mvh] [-m mem] [program]", argv0);
  331. }
  332. int
  333. main(int argc, char *argv[])
  334. {
  335. int ch;
  336. struct rlimit rlimit;
  337. argv0 = argv[0];
  338. if (getrlimit(RLIMIT_DATA, &rlimit) == -1)
  339. die("getrlimit");
  340. const char *optstring = "Mm:vh";
  341. while ((ch = getopt(argc, argv, optstring)) != -1) {
  342. switch (ch) {
  343. case 'M':
  344. rlimit.rlim_cur = rlimit.rlim_max;
  345. break;
  346. case 'm':
  347. rlimit.rlim_cur = strtoull(optarg, NULL, 0);
  348. if (errno != 0)
  349. die("strtoull: %s", optarg);
  350. break;
  351. case 'v':
  352. die("%s " VERSION, argv0);
  353. break;
  354. case 'h':
  355. default:
  356. usage();
  357. }
  358. }
  359. argc -= optind;
  360. argv += optind;
  361. TAILQ_INIT(&head);
  362. if (isatty(STDIN_FILENO) == 0 || isatty(STDOUT_FILENO) == 0)
  363. die("parent it not a tty");
  364. /* save terminal settings for resetting after exit */
  365. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  366. die("tcgetattr:");
  367. if (atexit(reset))
  368. die("atexit:");
  369. /* get window size of the terminal */
  370. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  371. die("ioctl:");
  372. child = forkpty(&mfd, NULL, &dfl, &ws);
  373. if (child == -1)
  374. die("forkpty:");
  375. if (child == 0) { /* child */
  376. if (argc >= 1) {
  377. execvp(argv[0], argv);
  378. } else {
  379. struct passwd *passwd = getpwuid(getuid());
  380. if (passwd == NULL)
  381. die("getpwid:");
  382. execlp(passwd->pw_shell, passwd->pw_shell, NULL);
  383. }
  384. perror("execvp");
  385. _exit(127);
  386. }
  387. /* set maximum memory size for scrollback buffer */
  388. if (setrlimit(RLIMIT_DATA, &rlimit) == -1)
  389. die("setrlimit:");
  390. #ifdef __OpenBSD__
  391. if (pledge("stdio tty proc", NULL) == -1)
  392. die("pledge:");
  393. #endif
  394. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  395. die("signal:");
  396. struct termios new = dfl;
  397. cfmakeraw(&new);
  398. new.c_cc[VMIN ] = 1; /* return read if at least one byte in buffer */
  399. new.c_cc[VTIME] = 0; /* no polling time for read from terminal */
  400. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  401. die("tcsetattr:");
  402. size_t size = BUFSIZ, len = 0, pos = 0;
  403. char *buf = calloc(size, sizeof *buf);
  404. if (buf == NULL)
  405. die("calloc:");
  406. struct pollfd pfd[2] = {
  407. {STDIN_FILENO, POLLIN, 0},
  408. {mfd, POLLIN, 0}
  409. };
  410. for (;;) {
  411. char input[BUFSIZ];
  412. if (poll(pfd, LENGTH(pfd), -1) == -1 && errno != EINTR)
  413. die("poll:");
  414. if (doredraw) {
  415. redraw();
  416. doredraw = false;
  417. }
  418. if (pfd[0].revents & POLLHUP || pfd[1].revents & POLLHUP)
  419. break;
  420. if (pfd[0].revents & POLLIN) {
  421. ssize_t n = read(STDIN_FILENO, input, sizeof(input)-1);
  422. if (n == -1 && errno != EINTR)
  423. die("read:");
  424. if (n == 0)
  425. break;
  426. input[n] = '\0';
  427. if (altscreen)
  428. goto noevent;
  429. for (size_t i = 0; i < LENGTH(rules); i++) {
  430. if (strncmp(rules[i].seq, input,
  431. strlen(rules[i].seq)) == 0) {
  432. if (rules[i].event == SCROLL_UP)
  433. scrollup(rules[i].lines);
  434. if (rules[i].event == SCROLL_DOWN)
  435. scrolldown(buf, len,
  436. rules[i].lines);
  437. goto out;
  438. }
  439. }
  440. noevent:
  441. if (write(mfd, input, n) == -1)
  442. die("write:");
  443. if (bottom != TAILQ_FIRST(&head))
  444. jumpdown(buf, len);
  445. }
  446. out:
  447. if (pfd[1].revents & POLLIN) {
  448. ssize_t n = read(mfd, input, sizeof(input)-1);
  449. if (n == -1 && errno != EINTR)
  450. die("read:");
  451. if (n == 0) /* on exit of child we continue here */
  452. continue; /* let signal handler catch SIGCHLD */
  453. input[n] = '\0';
  454. /* don't print child output while scrolling */
  455. if (bottom == TAILQ_FIRST(&head))
  456. if (write(STDOUT_FILENO, input, n) == -1)
  457. die("write:");
  458. /* iterate over the input buffer */
  459. for (char *c = input; n-- > 0; c++) {
  460. /* don't save alternative screen and */
  461. /* clear screen esc sequences to scrollback */
  462. if (skipesc(*c))
  463. continue;
  464. if (*c == '\n') {
  465. addline(buf, len);
  466. /* only advance bottom if scroll is */
  467. /* at the end of the scroll back */
  468. if (bottom == NULL ||
  469. TAILQ_PREV(bottom, tailhead,
  470. entries) == TAILQ_FIRST(&head))
  471. bottom = TAILQ_FIRST(&head);
  472. memset(buf, 0, size);
  473. len = pos = 0;
  474. buf[pos++] = '\r';
  475. } else if (*c == '\r') {
  476. pos = 0;
  477. continue;
  478. }
  479. buf[pos++] = *c;
  480. if (pos > len)
  481. len = pos;
  482. if (len == size) {
  483. size *= 2;
  484. buf = earealloc(buf, size);
  485. }
  486. }
  487. }
  488. }
  489. if (close(mfd) == -1)
  490. die("close:");
  491. int status;
  492. if (waitpid(child, &status, 0) == -1)
  493. die("waitpid:");
  494. return WEXITSTATUS(status);
  495. }