scroll.c 9.5 KB

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