scroll.c 12 KB

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