scroll.c 12 KB

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