scroll.c 10 KB

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