scroll.c 13 KB

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