/* 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
* wait MS pause
* 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
* 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).
* 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 long now_ms(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
/* 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';
return 1;
}
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);
execvp(argv[4], argv + 4);
_exit(127);
}
(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 (write(master, out, n) != (ssize_t)n) {
fprintf(stderr, "pty_drive: write failed\n");
return 1;
}
} else if (strncmp(line, "expect ", 7) == 0) {
long until = now_ms() + 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, "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 (strncmp(line, "signal ", 7) == 0) {
sig = atoi(line + 7);
(void)kill(pid, sig);
}
}
{
long until = now_ms() + 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;
}