scroll.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 <signal.h>
  29. #include <stdarg.h>
  30. #include <stdbool.h>
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <termios.h>
  35. #include <unistd.h>
  36. #if defined(__linux)
  37. #include <pty.h>
  38. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  39. #include <util.h>
  40. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  41. #include <libutil.h>
  42. #endif
  43. #define LENGTH(X) (sizeof (X) / sizeof ((X)[0]))
  44. TAILQ_HEAD(tailhead, line) head;
  45. struct line {
  46. TAILQ_ENTRY(line) entries;
  47. size_t size;
  48. size_t len;
  49. char *buf;
  50. } *bottom;
  51. pid_t child;
  52. int mfd;
  53. struct termios dfl;
  54. struct winsize ws;
  55. static bool altscreen = false; /* is alternative screen active */
  56. static bool doredraw = false; /* redraw upon sigwinch */
  57. struct rule {
  58. const char *seq;
  59. enum {SCROLL_UP, SCROLL_DOWN} event;
  60. short lines;
  61. };
  62. #include "config.h"
  63. void
  64. die(const char *fmt, ...)
  65. {
  66. va_list ap;
  67. va_start(ap, fmt);
  68. vfprintf(stderr, fmt, ap);
  69. va_end(ap);
  70. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  71. fputc(' ', stderr);
  72. perror(NULL);
  73. } else {
  74. fputc('\n', stderr);
  75. }
  76. exit(EXIT_FAILURE);
  77. }
  78. void
  79. sigchld(int sig)
  80. {
  81. pid_t pid;
  82. int status;
  83. assert(sig == SIGCHLD);
  84. while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
  85. if (pid == child)
  86. exit(WEXITSTATUS(status));
  87. }
  88. void
  89. sigwinch(int sig)
  90. {
  91. assert(sig == SIGWINCH);
  92. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  93. die("ioctl:");
  94. if (ioctl(mfd, TIOCSWINSZ, &ws) == -1)
  95. die("ioctl:");
  96. kill(-child, SIGWINCH);
  97. doredraw = true;
  98. }
  99. void
  100. reset(void)
  101. {
  102. if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
  103. die("tcsetattr:");
  104. }
  105. /* error avoiding malloc */
  106. void *
  107. eamalloc(size_t size)
  108. {
  109. void *mem;
  110. while ((mem = malloc(size)) == NULL) {
  111. struct line *line = TAILQ_LAST(&head, tailhead);
  112. if (line == NULL)
  113. die("malloc:");
  114. TAILQ_REMOVE(&head, line, entries);
  115. free(line->buf);
  116. free(line);
  117. }
  118. return mem;
  119. }
  120. /* error avoiding remalloc */
  121. void *
  122. earealloc(void *ptr, size_t size)
  123. {
  124. void *mem;
  125. while ((mem = realloc(ptr, size)) == NULL) {
  126. struct line *line = TAILQ_LAST(&head, tailhead);
  127. if (line == NULL)
  128. die("realloc:");
  129. TAILQ_REMOVE(&head, line, entries);
  130. free(line->buf);
  131. free(line);
  132. }
  133. return mem;
  134. }
  135. /* Count string length w/o ansi esc sequences. */
  136. size_t
  137. strelen(const char *buf, size_t size)
  138. {
  139. enum {CHAR, BREK, ESC} state = CHAR;
  140. size_t len = 0;
  141. for (size_t i = 0; i < size; i++) {
  142. char c = buf[i];
  143. switch (state) {
  144. case CHAR:
  145. if (c == '\033')
  146. state = BREK;
  147. else
  148. len++;
  149. break;
  150. case BREK:
  151. if (c == '[') {
  152. state = ESC;
  153. } else {
  154. state = CHAR;
  155. len++;
  156. }
  157. break;
  158. case ESC:
  159. if (c >= 64 && c <= 126)
  160. state = CHAR;
  161. break;
  162. }
  163. }
  164. return len;
  165. }
  166. /* detect alternative screen switching */
  167. bool
  168. isaltscreen(char c)
  169. {
  170. static enum {CHAR, BREK, ESC} state = CHAR;
  171. static char buf[BUFSIZ];
  172. static size_t i = 0;
  173. switch (state) {
  174. case CHAR:
  175. if (c == '\033')
  176. state = BREK;
  177. break;
  178. case BREK:
  179. if (c == '[')
  180. state = ESC;
  181. else
  182. state = CHAR;
  183. break;
  184. case ESC:
  185. buf[i++] = c;
  186. if (i == sizeof buf) {
  187. /* TODO: find a better way to handle this situation */
  188. state = CHAR;
  189. i = 0;
  190. } else if (c >= 64 && c <= 126) {
  191. state = CHAR;
  192. buf[i] = '\0';
  193. i = 0;
  194. /* esc seq. enable alternative screen */
  195. if (strcmp(buf, "?1049h") == 0 ||
  196. strcmp(buf, "?1047h") == 0 ||
  197. strcmp(buf, "?47h" ) == 0)
  198. altscreen = true;
  199. /* esc seq. disable alternative screen */
  200. if (strcmp(buf, "?1049l") == 0 ||
  201. strcmp(buf, "?1047l") == 0 ||
  202. strcmp(buf, "?47l" ) == 0)
  203. altscreen = false;
  204. }
  205. break;
  206. }
  207. return altscreen;
  208. }
  209. void
  210. addline(char *buf, size_t size)
  211. {
  212. struct line *line = eamalloc(sizeof *line);
  213. line->size = size;
  214. line->len = strelen(buf, size);
  215. line->buf = eamalloc(size);
  216. memcpy(line->buf, buf, size);
  217. bottom = line;
  218. TAILQ_INSERT_HEAD(&head, line, entries);
  219. }
  220. void
  221. redraw()
  222. {
  223. int rows = 0;
  224. /* wind back bottom pointer by one page */
  225. for (; bottom != NULL && TAILQ_NEXT(bottom, entries) != NULL &&
  226. rows < ws.ws_row; rows++)
  227. bottom = TAILQ_NEXT(bottom, entries);
  228. if (rows <= 0) {
  229. return;
  230. }
  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)
  251. n = ws.ws_row / (-n) > 0 ? 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. }
  260. /* move the text in terminal rows lines down */
  261. dprintf(STDOUT_FILENO, "\033[%dT", rows);
  262. /* set cursor position to upper left corner */
  263. write(STDOUT_FILENO, "\033[0;0H", 6);
  264. /* hide cursor */
  265. write(STDOUT_FILENO, "\033[?25l", 6);
  266. /* remove newline of first line as we are at 0,0 already */
  267. if (scrollend->size > 0 && scrollend->buf[0] == '\n')
  268. write(STDOUT_FILENO, scrollend->buf + 1, scrollend->size - 1);
  269. else
  270. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  271. bottom = TAILQ_NEXT(bottom, entries);
  272. /* print rows lines and move bottom forward to the new screen bottom */
  273. for (; rows > 1; rows--) {
  274. scrollend = TAILQ_PREV(scrollend, tailhead, entries);
  275. bottom = TAILQ_NEXT(bottom, entries);
  276. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  277. }
  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)
  286. n = ws.ws_row / (-n) > 0 ? 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. bottom = TAILQ_FIRST(&head);
  304. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  305. bottom = TAILQ_NEXT(bottom, entries);
  306. scrolldown(buf, size, ws.ws_row);
  307. }
  308. void
  309. usage(void) {
  310. die("usage: scroll [-M] [-m mem] <program>");
  311. }
  312. int
  313. main(int argc, char *argv[])
  314. {
  315. int ch;
  316. struct rlimit rlimit;
  317. if (getrlimit(RLIMIT_DATA, &rlimit) == -1)
  318. die("getrlimit");
  319. while ((ch = getopt(argc, argv, "Mm:")) != -1) {
  320. switch (ch) {
  321. case 'M':
  322. rlimit.rlim_cur = rlimit.rlim_max;
  323. break;
  324. case 'm':
  325. rlimit.rlim_cur = strtoull(optarg, NULL, 0);
  326. if (errno != 0)
  327. die("strtoull: %s", optarg);
  328. break;
  329. default:
  330. usage();
  331. }
  332. }
  333. argc -= optind;
  334. argv += optind;
  335. TAILQ_INIT(&head);
  336. if (isatty(STDIN_FILENO) == 0)
  337. die("stdin it not a tty");
  338. if (isatty(STDOUT_FILENO) == 0)
  339. die("stdout it not a tty");
  340. if (argc < 1)
  341. usage();
  342. /* save terminal settings for resetting after exit */
  343. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  344. die("tcgetattr:");
  345. if (atexit(reset))
  346. die("atexit:");
  347. /* get window size of the terminal */
  348. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  349. die("ioctl:");
  350. child = forkpty(&mfd, NULL, &dfl, &ws);
  351. if (child == -1)
  352. die("forkpty:");
  353. if (child == 0) { /* child */
  354. execvp(argv[0], argv);
  355. perror("execvp");
  356. _exit(127);
  357. }
  358. /* set maximum memory size for scrollback buffer */
  359. if (setrlimit(RLIMIT_DATA, &rlimit) == -1)
  360. die("setrlimit:");
  361. #ifdef __OpenBSD__
  362. if (pledge("stdio tty proc", NULL) == -1)
  363. die("pledge:");
  364. #endif
  365. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  366. die("signal:");
  367. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  368. die("signal:");
  369. int f;
  370. if ((f = fcntl(mfd, F_GETFL)) == -1)
  371. die("fcntl:");
  372. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  373. die("fcntl:");
  374. struct termios new = dfl;
  375. cfmakeraw(&new);
  376. new.c_cc[VMIN ] = 1;
  377. new.c_cc[VTIME] = 0;
  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, 2, -1) == -1 && errno != EINTR)
  391. die("poll:");
  392. if (doredraw) {
  393. redraw();
  394. doredraw = false;
  395. continue;
  396. }
  397. if (pfd[0].revents & POLLIN) {
  398. ssize_t n = read(STDIN_FILENO, input, sizeof(input)-1);
  399. if (n <= 0 && errno != EINTR)
  400. die("read:");
  401. input[n] = '\0';
  402. if (altscreen)
  403. goto noevent;
  404. for (size_t i = 0; i < LENGTH(rules); i++) {
  405. if (strcmp(rules[i].seq, input) == 0) {
  406. if (rules[i].event == SCROLL_UP)
  407. scrollup(rules[i].lines);
  408. if (rules[i].event == SCROLL_DOWN)
  409. scrolldown(buf, pos, rules[i].lines);
  410. goto out;
  411. }
  412. }
  413. noevent:
  414. if (write(mfd, input, n) == -1)
  415. die("write:");
  416. if (bottom != TAILQ_FIRST(&head))
  417. jumpdown(buf, pos);
  418. }
  419. out:
  420. if (pfd[1].revents & POLLIN) {
  421. ssize_t n = read(mfd, input, sizeof input);
  422. if (n == -1 && errno != EINTR)
  423. die("read:");
  424. if (write(STDOUT_FILENO, input, n) == -1)
  425. die("write:");
  426. /* don't save clear screen esc sequences in log */
  427. if (strncmp("\033[H\033[2J", input, n) == 0)
  428. continue;
  429. /* iterate over the input buffer */
  430. for (char *c = input; n-- > 0; c++) {
  431. /* don't save lines from alternative screen */
  432. if (isaltscreen(*c))
  433. continue;
  434. if (*c == '\n') {
  435. addline(buf, pos);
  436. memset(buf, 0, size);
  437. pos = 0;
  438. }
  439. buf[pos++] = *c;
  440. if (pos == size) {
  441. size *= 2;
  442. buf = earealloc(buf, size);
  443. }
  444. }
  445. }
  446. }
  447. return EXIT_SUCCESS;
  448. }