| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560 |
- /*
- * Based on an example code from Roberto E. Vargas Caballero.
- *
- * Copyright (c) 2020 Jan Klemkow <j.klemkow@wemelug.de>
- * Copyright (c) 2020 Jochen Sprickerhof <git@jochen.sprickerhof.de>
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
- #include <sys/types.h>
- #include <sys/ioctl.h>
- #include <sys/wait.h>
- #include <sys/queue.h>
- #include <sys/resource.h>
- #include <assert.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <poll.h>
- #include <pwd.h>
- #include <signal.h>
- #include <stdarg.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <termios.h>
- #include <unistd.h>
- #if defined(__linux)
- #include <pty.h>
- #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
- #include <util.h>
- #elif defined(__FreeBSD__) || defined(__DragonFly__)
- #include <libutil.h>
- #endif
- #define LENGTH(X) (sizeof (X) / sizeof ((X)[0]))
- TAILQ_HEAD(tailhead, line) head;
- struct line {
- TAILQ_ENTRY(line) entries;
- size_t size;
- size_t len;
- char *buf;
- } *bottom;
- pid_t child;
- int mfd;
- struct termios dfl;
- struct winsize ws;
- static bool altscreen = false; /* is alternative screen active */
- static bool doredraw = false; /* redraw upon sigwinch */
- struct rule {
- const char *seq;
- enum {SCROLL_UP, SCROLL_DOWN} event;
- short lines;
- };
- #include "config.h"
- void
- die(const char *fmt, ...)
- {
- va_list ap;
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
- if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
- fputc(' ', stderr);
- perror(NULL);
- } else {
- fputc('\n', stderr);
- }
- exit(EXIT_FAILURE);
- }
- void
- sigchld(int sig)
- {
- pid_t pid;
- int status;
- assert(sig == SIGCHLD);
- while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
- if (pid == child)
- exit(WEXITSTATUS(status));
- }
- void
- sigwinch(int sig)
- {
- assert(sig == SIGWINCH);
- if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
- die("ioctl:");
- if (ioctl(mfd, TIOCSWINSZ, &ws) == -1)
- die("ioctl:");
- kill(-child, SIGWINCH);
- doredraw = true;
- }
- void
- reset(void)
- {
- if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
- die("tcsetattr:");
- }
- /* error avoiding remalloc */
- void *
- earealloc(void *ptr, size_t size)
- {
- void *mem;
- while ((mem = realloc(ptr, size)) == NULL) {
- struct line *line = TAILQ_LAST(&head, tailhead);
- if (line == NULL)
- die("realloc:");
- TAILQ_REMOVE(&head, line, entries);
- free(line->buf);
- free(line);
- }
- return mem;
- }
- /* Count string length w/o ansi esc sequences. */
- size_t
- strelen(const char *buf, size_t size)
- {
- enum {CHAR, BREK, ESC} state = CHAR;
- size_t len = 0;
- for (size_t i = 0; i < size; i++) {
- char c = buf[i];
- switch (state) {
- case CHAR:
- if (c == '\033')
- state = BREK;
- else
- len++;
- break;
- case BREK:
- if (c == '[') {
- state = ESC;
- } else {
- state = CHAR;
- len++;
- }
- break;
- case ESC:
- if (c >= 64 && c <= 126)
- state = CHAR;
- break;
- }
- }
- return len;
- }
- /* detect alternative screen switching and clear screen */
- bool
- skipesc(char c)
- {
- static enum {CHAR, BREK, ESC} state = CHAR;
- static char buf[BUFSIZ];
- static size_t i = 0;
- switch (state) {
- case CHAR:
- if (c == '\033')
- state = BREK;
- break;
- case BREK:
- if (c == '[')
- state = ESC;
- else
- state = CHAR;
- break;
- case ESC:
- buf[i++] = c;
- if (i == sizeof buf) {
- /* TODO: find a better way to handle this situation */
- state = CHAR;
- i = 0;
- } else if (c >= 64 && c <= 126) {
- state = CHAR;
- buf[i] = '\0';
- i = 0;
- /* esc seq. enable alternative screen */
- if (strcmp(buf, "?1049h") == 0 ||
- strcmp(buf, "?1047h") == 0 ||
- strcmp(buf, "?47h" ) == 0)
- altscreen = true;
- /* esc seq. disable alternative screen */
- if (strcmp(buf, "?1049l") == 0 ||
- strcmp(buf, "?1047l") == 0 ||
- strcmp(buf, "?47l" ) == 0)
- altscreen = false;
- /* don't save cursor move or clear screen */
- /* esc sequences to log */
- if (c == 'H' || strcmp(buf, "2J") == 0)
- return true;
- }
- break;
- }
- return altscreen;
- }
- void
- getcursorposition(int *x, int *y)
- {
- char input[BUFSIZ];
- ssize_t n;
- if (write(STDOUT_FILENO, "\033[6n", 4) < 0)
- die("requesting cursor position");
- if ((n = read(STDIN_FILENO, input, sizeof(input)-1)) < 0)
- die("reading cursor position");
- input[n] = '\0';
- if (sscanf(input, "\033[%d;%dR", x, y) != 2)
- die("parsing cursor position");
- }
- void
- addline(char *buf, size_t size)
- {
- struct line *line = earealloc(NULL, sizeof *line);
- line->size = size;
- line->len = strelen(buf, size);
- line->buf = earealloc(NULL, size);
- memcpy(line->buf, buf, size);
- bottom = line;
- TAILQ_INSERT_HEAD(&head, line, entries);
- }
- void
- redraw()
- {
- int rows = 0, x, y;
- getcursorposition(&x, &y);
- /* wind back bottom pointer by one page */
- for (; bottom != NULL && TAILQ_NEXT(bottom, entries) != NULL &&
- rows < x - 1; rows++)
- bottom = TAILQ_NEXT(bottom, entries);
- if (rows == 0)
- return;
- /* clear screen */
- dprintf(STDOUT_FILENO, "\033[2J");
- /* set cursor position to upper left corner */
- write(STDOUT_FILENO, "\033[0;0H", 6);
- /* remove newline of first line as we are at 0,0 already */
- if (bottom->size > 0 && bottom->buf[0] == '\n')
- write(STDOUT_FILENO, bottom->buf + 1, bottom->size - 1);
- else
- write(STDOUT_FILENO, bottom->buf, bottom->size);
- for (; rows > 0; rows--) {
- bottom = TAILQ_PREV(bottom, tailhead, entries);
- write(STDOUT_FILENO, bottom->buf, bottom->size);
- }
- }
- void
- scrollup(int n)
- {
- int rows = 2, x, y;
- struct line *scrollend = bottom;
- getcursorposition(&x, &y);
- if (n < 0) /* scroll by fraction of ws.ws_row, but at least one line */
- n = ws.ws_row > (-n) ? ws.ws_row / (-n) : 1;
- /* wind back scrollend pointer by one page plus n */
- for (; scrollend != NULL && TAILQ_NEXT(scrollend, entries) != NULL &&
- rows < x + n; rows++)
- scrollend = TAILQ_NEXT(scrollend, entries);
- rows -= x;
- if (rows <= 0)
- return;
- /* move the text in terminal rows lines down */
- dprintf(STDOUT_FILENO, "\033[%dT", rows);
- /* set cursor position to upper left corner */
- write(STDOUT_FILENO, "\033[0;0H", 6);
- /* hide cursor */
- write(STDOUT_FILENO, "\033[?25l", 6);
- /* remove newline of first line as we are at 0,0 already */
- if (scrollend->size > 0 && scrollend->buf[0] == '\n')
- write(STDOUT_FILENO, scrollend->buf + 1, scrollend->size - 1);
- else
- write(STDOUT_FILENO, scrollend->buf, scrollend->size);
- bottom = TAILQ_NEXT(bottom, entries);
- /* print rows lines and move bottom forward to the new screen bottom */
- for (; rows > 1; rows--) {
- scrollend = TAILQ_PREV(scrollend, tailhead, entries);
- bottom = TAILQ_NEXT(bottom, entries);
- write(STDOUT_FILENO, scrollend->buf, scrollend->size);
- }
- /* move cursor from line n to the old bottom position */
- dprintf(STDOUT_FILENO, "\033[%d;0H", x);
- }
- void
- scrolldown(char *buf, size_t size, int n)
- {
- if (bottom == NULL || bottom == TAILQ_FIRST(&head))
- return;
- if (n < 0) /* scroll by fraction of ws.ws_row, but at least one line */
- n = ws.ws_row > (-n) ? ws.ws_row / (-n) : 1;
- bottom = TAILQ_PREV(bottom, tailhead, entries);
- /* print n lines */
- for (; n > 0 && bottom != NULL && bottom != TAILQ_FIRST(&head); n--) {
- bottom = TAILQ_PREV(bottom, tailhead, entries);
- write(STDOUT_FILENO, bottom->buf, bottom->size);
- }
- if (n > 0 && bottom == TAILQ_FIRST(&head)) {
- write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
- write(STDOUT_FILENO, buf, size);
- } else if (bottom != NULL)
- bottom = TAILQ_NEXT(bottom, entries);
- }
- void
- jumpdown(char *buf, size_t size)
- {
- int rows = ws.ws_row;
- /* wind back by one page starting from the latest line */
- bottom = TAILQ_FIRST(&head);
- for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
- bottom = TAILQ_NEXT(bottom, entries);
- scrolldown(buf, size, ws.ws_row);
- }
- void
- usage(void) {
- die("usage: scroll [-Mh] [-m mem] [program]");
- }
- int
- main(int argc, char *argv[])
- {
- int ch;
- struct rlimit rlimit;
- if (getrlimit(RLIMIT_DATA, &rlimit) == -1)
- die("getrlimit");
- while ((ch = getopt(argc, argv, "Mm:h")) != -1) {
- switch (ch) {
- case 'M':
- rlimit.rlim_cur = rlimit.rlim_max;
- break;
- case 'm':
- rlimit.rlim_cur = strtoull(optarg, NULL, 0);
- if (errno != 0)
- die("strtoull: %s", optarg);
- break;
- case 'h':
- default:
- usage();
- }
- }
- argc -= optind;
- argv += optind;
- TAILQ_INIT(&head);
- if (isatty(STDIN_FILENO) == 0 || isatty(STDOUT_FILENO) == 0)
- die("parent it not a tty");
- /* save terminal settings for resetting after exit */
- if (tcgetattr(STDIN_FILENO, &dfl) == -1)
- die("tcgetattr:");
- if (atexit(reset))
- die("atexit:");
- /* get window size of the terminal */
- if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
- die("ioctl:");
- if (signal(SIGCHLD, sigchld) == SIG_ERR)
- die("signal:");
- if (signal(SIGWINCH, sigwinch) == SIG_ERR)
- die("signal:");
- child = forkpty(&mfd, NULL, &dfl, &ws);
- if (child == -1)
- die("forkpty:");
- if (child == 0) { /* child */
- if (argc >= 1) {
- execvp(argv[0], argv);
- } else {
- struct passwd *passwd = getpwuid(getuid());
- if (passwd == NULL)
- die("getpwid:");
- execlp(passwd->pw_shell, passwd->pw_shell, NULL);
- }
- perror("execvp");
- _exit(127);
- }
- /* set maximum memory size for scrollback buffer */
- if (setrlimit(RLIMIT_DATA, &rlimit) == -1)
- die("setrlimit:");
- #ifdef __OpenBSD__
- if (pledge("stdio tty proc", NULL) == -1)
- die("pledge:");
- #endif
- struct termios new = dfl;
- cfmakeraw(&new);
- new.c_cc[VMIN ] = 1; /* return read if at least one byte in buffer */
- new.c_cc[VTIME] = 0; /* no polling time for read from terminal */
- if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
- die("tcsetattr:");
- size_t size = BUFSIZ, pos = 0;
- char *buf = calloc(size, sizeof *buf);
- if (buf == NULL)
- die("calloc:");
- struct pollfd pfd[2] = {
- {STDIN_FILENO, POLLIN, 0},
- {mfd, POLLIN, 0}
- };
- for (;;) {
- char input[BUFSIZ];
- if (poll(pfd, LENGTH(pfd), -1) == -1 && errno != EINTR)
- die("poll:");
- if (doredraw) {
- redraw();
- doredraw = false;
- }
- if (pfd[0].revents & POLLIN) {
- ssize_t n = read(STDIN_FILENO, input, sizeof(input)-1);
- if (n == -1 && errno != EINTR)
- die("read:");
- if (n == 0)
- break;
- input[n] = '\0';
- if (altscreen)
- goto noevent;
- for (size_t i = 0; i < LENGTH(rules); i++) {
- if (strcmp(rules[i].seq, input) == 0) {
- if (rules[i].event == SCROLL_UP)
- scrollup(rules[i].lines);
- if (rules[i].event == SCROLL_DOWN)
- scrolldown(buf, pos,
- rules[i].lines);
- goto out;
- }
- }
- noevent:
- if (write(mfd, input, n) == -1)
- die("write:");
- if (bottom != TAILQ_FIRST(&head))
- jumpdown(buf, pos);
- }
- out:
- if (pfd[1].revents & POLLIN) {
- ssize_t n = read(mfd, input, sizeof(input)-1);
- if (n == -1 && errno != EINTR)
- die("read:");
- if (n == 0) /* on exit of child we continue here */
- continue; /* let signal handler catch SIGCHLD */
- input[n] = '\0';
- /* don't print child output while scrolling */
- if (bottom == TAILQ_FIRST(&head))
- if (write(STDOUT_FILENO, input, n) == -1)
- die("write:");
- /* iterate over the input buffer */
- for (char *c = input; n-- > 0; c++) {
- /* don't save alternative screen and */
- /* clear screen esc sequences to scrollback */
- if (skipesc(*c))
- continue;
- if (*c == '\n') {
- addline(buf, pos);
- memset(buf, 0, size);
- pos = 0;
- }
- buf[pos++] = *c;
- if (pos == size) {
- size *= 2;
- buf = earealloc(buf, size);
- }
- }
- }
- }
- if (close(mfd) == -1)
- die("close:");
- pid_t pid;
- int status;
- while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
- if (pid != child)
- continue;
- return WEXITSTATUS(status);
- }
|