scroll.c 13 KB

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