scroll.c 12 KB

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