Skip to content
pi-c Artifact [c196efb0ed]
Login

Artifact [c196efb0ed]

Artifact c196efb0edd3266ac1e39fd9894cf1344e77993c230aad5176dd9707d9d4fef3:


/* Test-only: runs a program on a pseudo-terminal and drives it from a
 * script on stdin, one step per line:
 *   send TEXT       write TEXT (\r \n \t \e \xHH escapes) to the terminal
 *   expect TEXT     wait (up to 30 s) until TEXT appears in the output
 *                   received since the last expect; fail otherwise
 *   expectraw TEXT  expect, on the bytes as written, escapes included (\e \xHH as for send):
 *                   "expectraw \e[2J" waits for the next full repaint
 *   seen TEXT       wait (up to 30 s) until TEXT has appeared anywhere in the output, before
 *                   the last expect too; what the next expect looks at is unchanged (two
 *                   things that both happen, in either order)
 *   wait MS         pause
 *   waitfile PATH   wait (up to 30 s) until PATH exists; a leading $NAME/
 *                   is that environment variable (a condition, not a pause)
 *   touch PATH      create PATH, for a helper waiting on it (a gate: fake_server)
 *   size COLS ROWS  resize the terminal (SIGWINCH reaches the program)
 *   signal NUM      send the program signal NUM; it is then expected to die of it
 *   answer off      stop answering queries: a terminal that answers nothing
 *   bg SPEC         answer the background colour query (OSC 11) with SPEC
 *                   ("rgb:ffff/ffff/ffff"); unanswered by default
 * Like every terminal, it answers DA1 (ESC [ c) with ESC [ ?62;22c, in order
 * with the queries before it, and the alternate scroll mode's DECRQM
 * (ESC [ ? 1007 $ p) with "set", as Ghostty does.
 * Every byte the program writes is copied to TRANSCRIPT. Exits 0 when the
 * script finished and the program exited 0 (or died of the signal sent)
 * within 30 s afterwards (generous: CI machines run loaded). PIC_TEST_SLOW makes each 30 s two
 * minutes.
 * Usage: pty_drive TRANSCRIPT COLS ROWS PROGRAM [ARGS...] < script */
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

static int master = -1;
static FILE *transcript;
static char *seen;
static size_t seen_len, seen_cap, mark;
static size_t scanned;  /* the output searched for queries so far */
static int answering = 1;
static char bg_spec[128]; /* "": OSC 11 goes unanswered */

static void reply(const char *s) {
    size_t n = strlen(s);
    if (write(master, s, n) != (ssize_t)n) {
        fprintf(stderr, "pty_drive: answer failed\n");
    }
}

/* Answers the queries that arrived in the output, in order. */
static void answer(void) {
    static const char da1[] = "\x1b[c", osc11[] = "\x1b]11;?", decrqm[] = "\x1b[?1007$p";
    while (scanned < seen_len) {
        size_t left = seen_len - scanned;
        const char *at = seen + scanned;
        if (left >= sizeof da1 - 1 && memcmp(at, da1, sizeof da1 - 1) == 0) {
            if (answering) {
                reply("\x1b[?62;22c");
            }
            scanned += sizeof da1 - 1;
        } else if (left >= sizeof osc11 - 1 && memcmp(at, osc11, sizeof osc11 - 1) == 0) {
            if (answering && bg_spec[0]) {
                char r[160];
                (void)snprintf(r, sizeof r, "\x1b]11;%s\x1b\\", bg_spec);
                reply(r);
            }
            scanned += sizeof osc11 - 1;
        } else if (left >= sizeof decrqm - 1 && memcmp(at, decrqm, sizeof decrqm - 1) == 0) {
            if (answering) {
                reply("\x1b[?1007;1$y"); /* alternate scroll on, as Ghostty and others start */
            }
            scanned += sizeof decrqm - 1;
        } else if (*at == '\x1b' && left < sizeof decrqm - 1) {
            break; /* perhaps the start of a query; wait for the rest */
        } else {
            scanned++;
        }
    }
}

static long now_ms(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}

/* MS, or four times it under PIC_TEST_SLOW (a loaded machine): how long to wait before failing. */
static long patience(long ms) {
    const char *s = getenv("PIC_TEST_SLOW");
    return s && *s && strcmp(s, "0") != 0 ? ms * 4 : ms;
}

/* Reads what the program wrote, waiting up to ms. 0 at EOF. */
static int pump(int ms) {
    struct pollfd p = {master, POLLIN, 0};
    char buf[4096];
    ssize_t n;
    if (poll(&p, 1, ms) <= 0) {
        return 1;
    }
    n = read(master, buf, sizeof buf);
    if (n <= 0) {
        return 0;
    }
    fwrite(buf, 1, (size_t)n, transcript);
    fflush(transcript);
    if (seen_len + (size_t)n + 1 > seen_cap) {
        seen_cap = (seen_len + (size_t)n + 1) * 2;
        seen = realloc(seen, seen_cap);
        if (!seen) {
            exit(3);
        }
    }
    memcpy(seen + seen_len, buf, (size_t)n);
    seen_len += (size_t)n;
    seen[seen_len] = '\0';
    answer();
    return 1;
}

/* Writes S[0..n) to the program, reading what it writes meanwhile: a long send
 * fills the terminal's input while the program, busy drawing, fills its output,
 * and neither may wait on the other (a terminal always reads). 0 or -1. */
static int send_all(const char *s, size_t n) {
    size_t off = 0;
    while (off < n) {
        struct pollfd p = {master, POLLIN | POLLOUT, 0};
        if (poll(&p, 1, 1000) < 0 && errno != EINTR) {
            return -1;
        }
        if (p.revents & POLLIN) {
            (void)pump(0);
        }
        if (p.revents & POLLOUT) {
            ssize_t w = write(master, s + off, n - off < 256 ? n - off : 256);
            if (w < 0 && errno != EAGAIN && errno != EINTR) {
                return -1;
            }
            off += w > 0 ? (size_t)w : 0;
        }
    }
    return 0;
}

static size_t unescape(const char *s, char *out) {
    size_t n = 0;
    for (; *s; s++) {
        if (*s != '\\' || !s[1]) {
            out[n++] = *s;
            continue;
        }
        s++;
        switch (*s) {
        case 'r': out[n++] = '\r'; break;
        case 'n': out[n++] = '\n'; break;
        case 't': out[n++] = '\t'; break;
        case 'e': out[n++] = '\x1b'; break;
        case 'x': {
            char hex[3] = {s[1], s[1] ? s[2] : 0, 0};
            out[n++] = (char)strtol(hex, NULL, 16);
            s += 2;
            break;
        }
        default: out[n++] = *s;
        }
    }
    return n;
}

/* Looks for WANT in the output since the last match, escape sequences
 * removed; on a match, the next search starts just after it (not at the end
 * of what was read, which may hold what the next expect wants). */
static int contains(const char *want) {
    char *plain = malloc(seen_len - mark + 1);
    size_t *raw = malloc((seen_len - mark + 1) * sizeof *raw); /* plain index -> seen index */
    size_t j = 0;
    char *hit;
    if (!plain || !raw) {
        exit(3);
    }
    for (size_t i = mark; i < seen_len; i++) {
        if (seen[i] == '\x1b' && i + 1 < seen_len && seen[i + 1] == '[') {
            for (i += 2; i < seen_len && !(seen[i] >= '@' && seen[i] <= '~'); i++) {
            }
            continue;
        }
        raw[j] = i;
        plain[j++] = seen[i];
    }
    plain[j] = '\0';
    hit = strstr(plain, want);
    if (hit) {
        size_t end = (size_t)(hit - plain) + strlen(want);
        mark = end < j ? raw[end] : seen_len;
    }
    free(plain);
    free(raw);
    return hit != NULL;
}

int main(int argc, char **argv) {
    struct winsize ws;
    char line[4096], out[4096];
    pid_t pid;
    int status = 0, sig = 0;
    if (argc < 5) {
        fprintf(stderr, "usage: pty_drive TRANSCRIPT COLS ROWS PROGRAM [ARGS...] < script\n");
        return 2;
    }
    transcript = fopen(argv[1], "w");
    memset(&ws, 0, sizeof ws);
    ws.ws_col = (unsigned short)atoi(argv[2]);
    ws.ws_row = (unsigned short)atoi(argv[3]);
    master = posix_openpt(O_RDWR | O_NOCTTY);
    if (!transcript || master < 0 || grantpt(master) != 0 || unlockpt(master) != 0) {
        perror("pty");
        return 2;
    }
    (void)ioctl(master, TIOCSWINSZ, &ws);
    pid = fork();
    if (pid == 0) {
        int slave;
        (void)setsid();
        slave = open(ptsname(master), O_RDWR);
        if (slave < 0) {
            _exit(126);
        }
        (void)ioctl(slave, TIOCSCTTY, 0);
        (void)ioctl(slave, TIOCSWINSZ, &ws); /* macOS: the size set on the master before the open is not kept */
        (void)dup2(slave, 0);
        (void)dup2(slave, 1);
        (void)dup2(slave, 2);
        close(slave);
        close(master);
        /* A free key check of the interface's own would take a scripted server's connection:
         * off unless a test sets the variable (to nothing, to turn them on). */
        (void)setenv("PIC_NO_KEY_CHECKS", "1", 0);
        (void)setenv("PIC_NO_NATIVE_CLIPBOARD", "1", 0); /* a driven pic never writes the real clipboard */
        execvp(argv[4], argv + 4);
        _exit(127);
    }
    (void)fcntl(master, F_SETFL, fcntl(master, F_GETFL) | O_NONBLOCK); /* send_all never blocks on a full input */
    (void)alarm(120); /* the whole run, however it goes */
    while (fgets(line, sizeof line, stdin)) {
        line[strcspn(line, "\n")] = '\0';
        if (strncmp(line, "send ", 5) == 0) {
            size_t n = unescape(line + 5, out);
            if (send_all(out, n) != 0) {
                fprintf(stderr, "pty_drive: write failed\n");
                return 1;
            }
        } else if (strncmp(line, "expect ", 7) == 0) {
            long until = now_ms() + patience(30000);
            while (!contains(line + 7)) {
                if (now_ms() > until || !pump(100)) {
                    fprintf(stderr, "pty_drive: never saw \"%s\"\n", line + 7);
                    kill(pid, SIGKILL);
                    return 1;
                }
            }
        } else if (strncmp(line, "expectraw ", 10) == 0) {
            long until = now_ms() + patience(30000);
            size_t wn = unescape(line + 10, out);
            for (;;) {
                size_t at = mark;
                while (wn && at + wn <= seen_len && memcmp(seen + at, out, wn) != 0) {
                    at++;
                }
                if (wn && at + wn <= seen_len) {
                    mark = at + wn;
                    break;
                }
                if (now_ms() > until || !pump(100)) {
                    fprintf(stderr, "pty_drive: never saw \"%s\"\n", line + 10);
                    kill(pid, SIGKILL);
                    return 1;
                }
            }
        } else if (strncmp(line, "seen ", 5) == 0) {
            long until = now_ms() + patience(30000);
            size_t was = mark;
            for (;;) {
                int hit;
                mark = 0;
                hit = contains(line + 5);
                mark = was;
                if (hit) {
                    break;
                }
                if (now_ms() > until || !pump(100)) {
                    fprintf(stderr, "pty_drive: never saw \"%s\"\n", line + 5);
                    kill(pid, SIGKILL);
                    return 1;
                }
            }
        } else if (strncmp(line, "waitfile ", 9) == 0) {
            char path[4096];
            const char *want = line + 9, *slash = strchr(want, '/');
            const char *val = want[0] == '$' && slash ? getenv(strndup(want + 1, (size_t)(slash - want - 1))) : NULL;
            long until = now_ms() + patience(30000);
            if (val) {
                (void)snprintf(path, sizeof path, "%s%s", val, slash);
            } else {
                (void)snprintf(path, sizeof path, "%s", want);
            }
            while (access(path, F_OK) != 0) {
                if (now_ms() > until || !pump(50)) {
                    fprintf(stderr, "pty_drive: never saw file \"%s\"\n", path);
                    kill(pid, SIGKILL);
                    return 1;
                }
            }
        } else if (strncmp(line, "touch ", 6) == 0) {
            int fd = open(line + 6, O_WRONLY | O_CREAT, 0600);
            if (fd < 0) {
                fprintf(stderr, "pty_drive: cannot create \"%s\"\n", line + 6);
                kill(pid, SIGKILL);
                return 1;
            }
            close(fd);
        } else if (strncmp(line, "wait ", 5) == 0) {
            long until = now_ms() + atol(line + 5);
            while (now_ms() < until) {
                (void)pump((int)(until - now_ms()));
            }
        } else if (strncmp(line, "size ", 5) == 0) {
            ws.ws_col = (unsigned short)atoi(line + 5);
            ws.ws_row = (unsigned short)atoi(strchr(line + 5, ' ') ? strchr(line + 5, ' ') + 1 : "24");
            (void)ioctl(master, TIOCSWINSZ, &ws);
        } else if (strcmp(line, "answer off") == 0) {
            answering = 0;
        } else if (strncmp(line, "bg ", 3) == 0) {
            (void)snprintf(bg_spec, sizeof bg_spec, "%s", line + 3);
        } else if (strncmp(line, "signal ", 7) == 0) {
            sig = atoi(line + 7);
            (void)kill(pid, sig);
        }
    }
    {
        long until = now_ms() + patience(30000);
        while (now_ms() < until && waitpid(pid, &status, WNOHANG) == 0) {
            (void)pump(50);
        }
        while (pump(10)) {
            if (errno == EIO) {
                break;
            }
            if (now_ms() > until + 1000) {
                break;
            }
        }
        if (waitpid(pid, &status, WNOHANG) == 0) {
            fprintf(stderr, "pty_drive: the program did not exit\n");
            kill(pid, SIGKILL);
            return 1;
        }
    }
    if (sig) {
        return WIFSIGNALED(status) && WTERMSIG(status) == sig ? 0 : 1;
    }
    return WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : 1;
}