scroll.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 == '\r')
  156. return true;
  157. if (c == '\033')
  158. state = BREK;
  159. break;
  160. case BREK:
  161. if (c == '[')
  162. state = ESC;
  163. else
  164. state = CHAR;
  165. break;
  166. case ESC:
  167. buf[i++] = c;
  168. if (i == sizeof buf) {
  169. /* TODO: find a better way to handle this situation */
  170. state = CHAR;
  171. i = 0;
  172. } else if (c >= 64 && c <= 126) {
  173. state = CHAR;
  174. buf[i] = '\0';
  175. i = 0;
  176. /* esc seq. enable alternative screen */
  177. if (strcmp(buf, "?1049h") == 0 ||
  178. strcmp(buf, "?1047h") == 0 ||
  179. strcmp(buf, "?47h" ) == 0)
  180. altscreen = true;
  181. /* esc seq. disable alternative screen */
  182. if (strcmp(buf, "?1049l") == 0 ||
  183. strcmp(buf, "?1047l") == 0 ||
  184. strcmp(buf, "?47l" ) == 0)
  185. altscreen = false;
  186. /* don't save cursor move or clear screen */
  187. /* esc sequences to log */
  188. switch (c) {
  189. case 'A':
  190. case 'B':
  191. case 'C':
  192. case 'D':
  193. case 'H':
  194. case 'J':
  195. case 'K':
  196. case 'f':
  197. return true;
  198. }
  199. }
  200. break;
  201. }
  202. return altscreen;
  203. }
  204. void
  205. getcursorposition(int *x, int *y)
  206. {
  207. char input[BUFSIZ];
  208. ssize_t n;
  209. if (write(STDOUT_FILENO, "\033[6n", 4) == -1)
  210. die("requesting cursor position");
  211. do {
  212. if ((n = read(STDIN_FILENO, input, sizeof(input)-1)) == -1)
  213. die("reading cursor position");
  214. input[n] = '\0';
  215. } while (sscanf(input, "\033[%d;%dR", y, x) != 2);
  216. if (*x <= 0 || *y <= 0)
  217. die("invalid cursor position: x=%d y=%d", *x, *y);
  218. }
  219. void
  220. addline(char *buf, size_t size)
  221. {
  222. struct line *line = earealloc(NULL, sizeof *line);
  223. line->size = size;
  224. line->len = strelen(buf, size);
  225. line->buf = earealloc(NULL, size);
  226. memcpy(line->buf, buf, size);
  227. TAILQ_INSERT_HEAD(&head, line, entries);
  228. }
  229. void
  230. redraw()
  231. {
  232. int rows = 0, x, y;
  233. if (bottom == NULL)
  234. return;
  235. getcursorposition(&x, &y);
  236. if (y < ws.ws_row-1)
  237. y--;
  238. /* wind back bottom pointer by shown history */
  239. for (; bottom != NULL && TAILQ_NEXT(bottom, entries) != NULL &&
  240. rows < y - 1; rows++)
  241. bottom = TAILQ_NEXT(bottom, entries);
  242. /* clear screen */
  243. dprintf(STDOUT_FILENO, "\033[2J");
  244. /* set cursor position to upper left corner */
  245. write(STDOUT_FILENO, "\033[0;0H", 6);
  246. /* remove newline of first line as we are at 0,0 already */
  247. if (bottom->size > 0 && bottom->buf[0] == '\n')
  248. write(STDOUT_FILENO, bottom->buf + 1, bottom->size - 1);
  249. else
  250. write(STDOUT_FILENO, bottom->buf, bottom->size);
  251. for (rows = ws.ws_row; rows > 0 &&
  252. TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  253. bottom = TAILQ_PREV(bottom, tailhead, entries);
  254. write(STDOUT_FILENO, bottom->buf, bottom->size);
  255. }
  256. if (bottom == TAILQ_FIRST(&head)) {
  257. /* add new line in front of the shell prompt */
  258. write(STDOUT_FILENO, "\n", 1);
  259. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  260. } else
  261. bottom = TAILQ_NEXT(bottom, entries);
  262. }
  263. void
  264. scrollup(int n)
  265. {
  266. int rows = 2, x, y, extra = 0;
  267. struct line *scrollend = bottom;
  268. if (bottom == NULL)
  269. return;
  270. getcursorposition(&x, &y);
  271. if (n < 0) /* scroll by fraction of ws.ws_row, but at least one line */
  272. n = ws.ws_row > (-n) ? ws.ws_row / (-n) : 1;
  273. /* wind back scrollend pointer by the current screen */
  274. while (rows < y && TAILQ_NEXT(scrollend, entries) != NULL) {
  275. scrollend = TAILQ_NEXT(scrollend, entries);
  276. rows += (scrollend->len - 1) / ws.ws_col + 1;
  277. }
  278. if (rows <= 0)
  279. return;
  280. /* wind back scrollend pointer n lines */
  281. for (rows = 0; rows + extra < n &&
  282. TAILQ_NEXT(scrollend, entries) != NULL; rows++) {
  283. scrollend = TAILQ_NEXT(scrollend, entries);
  284. extra += (scrollend->len - 1) / ws.ws_col;
  285. }
  286. /* move the text in terminal rows lines down */
  287. dprintf(STDOUT_FILENO, "\033[%dT", n);
  288. /* set cursor position to upper left corner */
  289. write(STDOUT_FILENO, "\033[0;0H", 6);
  290. /* hide cursor */
  291. write(STDOUT_FILENO, "\033[?25l", 6);
  292. /* remove newline of first line as we are at 0,0 already */
  293. if (scrollend->size > 0 && scrollend->buf[0] == '\n')
  294. write(STDOUT_FILENO, scrollend->buf + 1, scrollend->size - 1);
  295. else
  296. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  297. if (y + n >= ws.ws_row)
  298. bottom = TAILQ_NEXT(bottom, entries);
  299. /* print rows lines and move bottom forward to the new screen bottom */
  300. for (; rows > 1; rows--) {
  301. scrollend = TAILQ_PREV(scrollend, tailhead, entries);
  302. if (y + n >= ws.ws_row)
  303. bottom = TAILQ_NEXT(bottom, entries);
  304. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  305. }
  306. /* move cursor from line n to the old bottom position */
  307. if (y + n < ws.ws_row) {
  308. dprintf(STDOUT_FILENO, "\033[%d;%dH", y + n, x);
  309. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  310. } else
  311. dprintf(STDOUT_FILENO, "\033[%d;0H", ws.ws_row);
  312. }
  313. void
  314. scrolldown(char *buf, size_t size, int n)
  315. {
  316. if (bottom == NULL || bottom == TAILQ_FIRST(&head))
  317. return;
  318. if (n < 0) /* scroll by fraction of ws.ws_row, but at least one line */
  319. n = ws.ws_row > (-n) ? ws.ws_row / (-n) : 1;
  320. bottom = TAILQ_PREV(bottom, tailhead, entries);
  321. /* print n lines */
  322. while (n > 0 && bottom != NULL && bottom != TAILQ_FIRST(&head)) {
  323. bottom = TAILQ_PREV(bottom, tailhead, entries);
  324. write(STDOUT_FILENO, bottom->buf, bottom->size);
  325. n -= (bottom->len - 1) / ws.ws_col + 1;
  326. }
  327. if (n > 0 && bottom == TAILQ_FIRST(&head)) {
  328. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  329. write(STDOUT_FILENO, buf, size);
  330. } else if (bottom != NULL)
  331. bottom = TAILQ_NEXT(bottom, entries);
  332. }
  333. void
  334. jumpdown(char *buf, size_t size)
  335. {
  336. int rows = ws.ws_row;
  337. /* wind back by one page starting from the latest line */
  338. bottom = TAILQ_FIRST(&head);
  339. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  340. bottom = TAILQ_NEXT(bottom, entries);
  341. scrolldown(buf, size, ws.ws_row);
  342. }
  343. void
  344. usage(void) {
  345. die("usage: %s [-Mvh] [-m mem] [program]", argv0);
  346. }
  347. int
  348. main(int argc, char *argv[])
  349. {
  350. int ch;
  351. struct rlimit rlimit;
  352. argv0 = argv[0];
  353. if (getrlimit(RLIMIT_DATA, &rlimit) == -1)
  354. die("getrlimit");
  355. const char *optstring = "Mm:vh";
  356. while ((ch = getopt(argc, argv, optstring)) != -1) {
  357. switch (ch) {
  358. case 'M':
  359. rlimit.rlim_cur = rlimit.rlim_max;
  360. break;
  361. case 'm':
  362. rlimit.rlim_cur = strtoull(optarg, NULL, 0);
  363. if (errno != 0)
  364. die("strtoull: %s", optarg);
  365. break;
  366. case 'v':
  367. die("%s " VERSION, argv0);
  368. break;
  369. case 'h':
  370. default:
  371. usage();
  372. }
  373. }
  374. argc -= optind;
  375. argv += optind;
  376. TAILQ_INIT(&head);
  377. if (isatty(STDIN_FILENO) == 0 || isatty(STDOUT_FILENO) == 0)
  378. die("parent it not a tty");
  379. /* save terminal settings for resetting after exit */
  380. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  381. die("tcgetattr:");
  382. if (atexit(reset))
  383. die("atexit:");
  384. /* get window size of the terminal */
  385. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  386. die("ioctl:");
  387. child = forkpty(&mfd, NULL, &dfl, &ws);
  388. if (child == -1)
  389. die("forkpty:");
  390. if (child == 0) { /* child */
  391. if (argc >= 1) {
  392. execvp(argv[0], argv);
  393. } else {
  394. struct passwd *passwd = getpwuid(getuid());
  395. if (passwd == NULL)
  396. die("getpwid:");
  397. execlp(passwd->pw_shell, passwd->pw_shell, NULL);
  398. }
  399. perror("execvp");
  400. _exit(127);
  401. }
  402. /* set maximum memory size for scrollback buffer */
  403. if (setrlimit(RLIMIT_DATA, &rlimit) == -1)
  404. die("setrlimit:");
  405. #ifdef __OpenBSD__
  406. if (pledge("stdio tty proc", NULL) == -1)
  407. die("pledge:");
  408. #endif
  409. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  410. die("signal:");
  411. struct termios new = dfl;
  412. cfmakeraw(&new);
  413. new.c_cc[VMIN ] = 1; /* return read if at least one byte in buffer */
  414. new.c_cc[VTIME] = 0; /* no polling time for read from terminal */
  415. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  416. die("tcsetattr:");
  417. size_t size = BUFSIZ, pos = 0;
  418. char *buf = calloc(size, sizeof *buf);
  419. if (buf == NULL)
  420. die("calloc:");
  421. struct pollfd pfd[2] = {
  422. {STDIN_FILENO, POLLIN, 0},
  423. {mfd, POLLIN, 0}
  424. };
  425. for (;;) {
  426. char input[BUFSIZ];
  427. if (poll(pfd, LENGTH(pfd), -1) == -1 && errno != EINTR)
  428. die("poll:");
  429. if (doredraw) {
  430. redraw();
  431. doredraw = false;
  432. }
  433. if (pfd[0].revents & POLLHUP || pfd[1].revents & POLLHUP)
  434. break;
  435. if (pfd[0].revents & POLLIN) {
  436. ssize_t n = read(STDIN_FILENO, input, sizeof(input)-1);
  437. if (n == -1 && errno != EINTR)
  438. die("read:");
  439. if (n == 0)
  440. break;
  441. input[n] = '\0';
  442. if (altscreen)
  443. goto noevent;
  444. for (size_t i = 0; i < LENGTH(rules); i++) {
  445. if (strncmp(rules[i].seq, input,
  446. strlen(rules[i].seq)) == 0) {
  447. if (rules[i].event == SCROLL_UP)
  448. scrollup(rules[i].lines);
  449. if (rules[i].event == SCROLL_DOWN)
  450. scrolldown(buf, pos,
  451. rules[i].lines);
  452. goto out;
  453. }
  454. }
  455. noevent:
  456. if (write(mfd, input, n) == -1)
  457. die("write:");
  458. if (bottom != TAILQ_FIRST(&head))
  459. jumpdown(buf, pos);
  460. }
  461. out:
  462. if (pfd[1].revents & POLLIN) {
  463. ssize_t n = read(mfd, input, sizeof(input)-1);
  464. if (n == -1 && errno != EINTR)
  465. die("read:");
  466. if (n == 0) /* on exit of child we continue here */
  467. continue; /* let signal handler catch SIGCHLD */
  468. input[n] = '\0';
  469. /* don't print child output while scrolling */
  470. if (bottom == TAILQ_FIRST(&head))
  471. if (write(STDOUT_FILENO, input, n) == -1)
  472. die("write:");
  473. /* iterate over the input buffer */
  474. for (char *c = input; n-- > 0; c++) {
  475. /* don't save alternative screen and */
  476. /* clear screen esc sequences to scrollback */
  477. if (skipesc(*c))
  478. continue;
  479. if (*c == '\n') {
  480. addline(buf, pos);
  481. /* only advance bottom if scroll is */
  482. /* at the end of the scroll back */
  483. if (bottom == NULL ||
  484. TAILQ_PREV(bottom, tailhead,
  485. entries) == TAILQ_FIRST(&head))
  486. bottom = TAILQ_FIRST(&head);
  487. memset(buf, 0, size);
  488. pos = 0;
  489. buf[pos++] = '\r';
  490. }
  491. buf[pos++] = *c;
  492. if (pos == size) {
  493. size *= 2;
  494. buf = earealloc(buf, size);
  495. }
  496. }
  497. }
  498. }
  499. if (close(mfd) == -1)
  500. die("close:");
  501. int status;
  502. if (waitpid(child, &status, 0) == -1)
  503. die("waitpid:");
  504. return WEXITSTATUS(status);
  505. }