Skip to content
pi-c Artifact [54c118a3c8]
Login

Artifact [54c118a3c8]

Artifact 54c118a3c84acde112eed5623d6bb6a4375ef68b1022694de30fc5deaed4a524:


/* The MCP stdio transport on a host (mcp_wire.h's pipe seam): the server is a program pic starts
 * in a process group of its own, one JSON-RPC message per line on its stdin and stdout. Its stderr
 * is kept, the last part of it, for the error when it fails. Stopping it closes its stdin, then
 * sends SIGTERM and SIGKILL to its group, as Pi does, so a server started through npx or uvx
 * goes too. The composition root registers it; a build without processes does not. */
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "mcp_stdio.h"
#include "net.h"
#include "pic.h"

#define MS_LINE_CAP (32u << 20)
#define MS_STDERR_KEEP 1024

struct pic_mcp_pipe {
    pid_t pid;
    int in, out, err; /* our ends: its stdin, stdout, stderr */
    char *buf;        /* stdout bytes not yet a whole line */
    size_t len, cap;
    char tail[MS_STDERR_KEEP + 1]; /* the end of its stderr */
    size_t tail_len;
    long long proc; /* pic ps's record, or -1 */
    char name[80];
};

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

/* "~/" at the start of S as the home directory (malloc'd). */
static char *ms_home(const char *s) {
    const char *home = getenv("HOME");
    char *out;
    if (strncmp(s, "~/", 2) != 0 || !home) {
        return strdup(s);
    }
    if ((out = malloc(strlen(home) + strlen(s)))) {
        (void)snprintf(out, strlen(home) + strlen(s), "%s%s", home, s + 1);
    }
    return out;
}

static void ms_keep_stderr(pic_mcp_pipe *p) {
    char b[512];
    ssize_t n;
    while ((n = read(p->err, b, sizeof b)) > 0) {
        for (ssize_t i = 0; i < n; i++) {
            if (p->tail_len == MS_STDERR_KEEP) {
                memmove(p->tail, p->tail + 1, MS_STDERR_KEEP - 1);
                p->tail_len--;
            }
            p->tail[p->tail_len++] = b[i] == '\n' || b[i] == '\r' ? ' ' : b[i];
        }
    }
    p->tail[p->tail_len] = '\0';
}

static void ms_stop(pic_mcp_pipe *p) {
    int status = 0, done = 0;
    if (!p) {
        return;
    }
    if (p->in >= 0) {
        close(p->in);
    }
    if (p->pid > 0) {
        /* closed stdin is the polite end; then TERM, then KILL, to the whole group */
        for (int step = 0; step < 3 && !done; step++) {
            long long until = ms_now() + (step == 2 ? 1000 : 2000);
            if (step == 1) {
                (void)kill(-p->pid, SIGTERM);
            } else if (step == 2) {
                (void)kill(-p->pid, SIGKILL);
            }
            while (!done && ms_now() < until) {
                pid_t w = waitpid(p->pid, &status, WNOHANG);
                if (w == p->pid || (w < 0 && errno != EINTR)) {
                    done = 1;
                } else {
                    struct timespec nap = {0, 20000000};
                    (void)nanosleep(&nap, NULL);
                }
            }
        }
        (void)kill(-p->pid, SIGKILL); /* what it left behind in its group */
        if (p->proc >= 0 && pic_proc_sink_get()) {
            pic_proc_sink_get()->end(p->proc, done && WIFEXITED(status) ? WEXITSTATUS(status) : -1,
                                     done && WIFSIGNALED(status) ? WTERMSIG(status) : 0);
        }
    }
    if (p->out >= 0) {
        close(p->out);
    }
    if (p->err >= 0) {
        close(p->err);
    }
    free(p->buf);
    free(p);
}

static pic_mcp_pipe *ms_start(const pic_mcp_target *t, char *err, size_t errcap) {
    int in[2] = {-1, -1}, out[2] = {-1, -1}, er[2] = {-1, -1}, ready[2] = {-1, -1};
    pic_mcp_pipe *p = calloc(1, sizeof *p);
    char *cwd = NULL, **argv = NULL, why[256];
    size_t argc = 0;
    ssize_t got;
    if (!p) {
        (void)snprintf(err, errcap, "out of memory");
        return NULL;
    }
    p->in = p->out = p->err = -1;
    p->proc = -1;
    (void)snprintf(p->name, sizeof p->name, "%s", t->name);
    while (t->argv[argc]) {
        argc++;
    }
    if (!(argv = calloc(argc + 1, sizeof *argv)) || (t->cwd && !(cwd = ms_home(t->cwd)))) {
        goto oom;
    }
    for (size_t i = 0; i < argc; i++) {
        if (!(argv[i] = ms_home(t->argv[i]))) {
            goto oom;
        }
    }
    if (pipe(in) != 0 || pipe(out) != 0 || pipe(er) != 0 || pipe(ready) != 0) {
        (void)snprintf(err, errcap, "cannot make pipes for %s: %s", t->name, strerror(errno));
        goto fail;
    }
    (void)fcntl(ready[1], F_SETFD, FD_CLOEXEC);
    p->pid = fork();
    if (p->pid < 0) {
        (void)snprintf(err, errcap, "cannot start %s: %s", t->name, strerror(errno));
        goto fail;
    }
    if (p->pid == 0) {
        int n;
        (void)setpgid(0, 0);
        (void)signal(SIGPIPE, SIG_DFL);
        (void)signal(SIGINT, SIG_DFL);
        (void)signal(SIGTERM, SIG_DFL);
        (void)dup2(in[0], 0);
        (void)dup2(out[1], 1);
        (void)dup2(er[1], 2);
        for (int fd = 3; fd < 256; fd++) {
            if (fd != ready[1]) {
                (void)close(fd);
            }
        }
        for (size_t i = 0; t->env && t->env[i]; i++) {
            const char *eq = strchr(t->env[i], '=');
            char name[256];
            if (eq && (size_t)(eq - t->env[i]) < sizeof name) {
                (void)snprintf(name, sizeof name, "%.*s", (int)(eq - t->env[i]), t->env[i]);
                (void)setenv(name, eq + 1, 1);
            }
        }
        if (cwd && chdir(cwd) != 0) {
            n = snprintf(why, sizeof why, "cannot enter %s: %s", cwd, strerror(errno));
            (void)!write(ready[1], why, (size_t)n);
            _exit(127);
        }
        execvp(argv[0], argv);
        n = snprintf(why, sizeof why, "cannot run %s: %s", argv[0], strerror(errno));
        (void)!write(ready[1], why, (size_t)n);
        _exit(127);
    }
    (void)setpgid(p->pid, p->pid);
    close(in[0]);
    close(out[1]);
    close(er[1]);
    close(ready[1]);
    in[0] = out[1] = er[1] = ready[1] = -1;
    p->in = in[1];
    p->out = out[0];
    p->err = er[0];
    (void)fcntl(p->in, F_SETFD, FD_CLOEXEC);
    (void)fcntl(p->out, F_SETFD, FD_CLOEXEC);
    (void)fcntl(p->err, F_SETFD, FD_CLOEXEC);
    (void)fcntl(p->err, F_SETFL, O_NONBLOCK);
    /* exec closes the ready pipe: nothing on it means the program is running */
    while ((got = read(ready[0], why, sizeof why - 1)) < 0 && errno == EINTR) {
    }
    close(ready[0]);
    ready[0] = -1;
    if (got > 0) {
        why[got] = '\0';
        (void)snprintf(err, errcap, "%s: %s", t->name, why);
        goto fail;
    }
    if (pic_proc_sink_get()) {
        char command[512] = "";
        for (size_t i = 0; i < argc; i++) {
            size_t have = strlen(command);
            (void)snprintf(command + have, sizeof command - have, "%s%s", i ? " " : "", argv[i]);
        }
        p->proc = pic_proc_sink_get()->start("mcp", command, (long)p->pid, (long)p->pid);
    }
    for (size_t i = 0; i < argc; i++) {
        free(argv[i]);
    }
    free(argv);
    free(cwd);
    return p;
oom:
    (void)snprintf(err, errcap, "out of memory");
fail:
    for (int i = 0; i < 2; i++) {
        if (in[i] >= 0) {
            close(in[i]);
        }
        if (out[i] >= 0) {
            close(out[i]);
        }
        if (er[i] >= 0) {
            close(er[i]);
        }
        if (ready[i] >= 0) {
            close(ready[i]);
        }
    }
    p->in = p->out = p->err = -1;
    for (size_t i = 0; argv && i < argc; i++) {
        free(argv[i]);
    }
    free(argv);
    free(cwd);
    if (p->pid > 0) {
        (void)kill(-p->pid, SIGKILL);
        (void)waitpid(p->pid, NULL, 0);
        p->pid = 0;
    }
    ms_stop(p);
    return NULL;
}

static int ms_send(pic_mcp_pipe *p, const char *line, size_t n, char *err, size_t errcap) {
    const char *parts[2] = {line, "\n"};
    size_t lens[2] = {n, 1};
    for (int k = 0; k < 2; k++) {
        const char *b = parts[k];
        size_t left = lens[k];
        while (left > 0) {
            ssize_t w = write(p->in, b, left);
            if (w < 0 && errno == EINTR) {
                continue;
            }
            if (w <= 0) {
                ms_keep_stderr(p);
                (void)snprintf(err, errcap, "%s is not running%s%.300s", p->name, p->tail_len ? "; it said: " : "",
                               p->tail);
                return -1;
            }
            b += w;
            left -= (size_t)w;
        }
    }
    return 0;
}

static char *ms_recv(pic_mcp_pipe *p, int timeout, char *err, size_t errcap) {
    long long idle_end = ms_now() + (long long)timeout * 1000;
    for (;;) {
        char *nl = p->buf ? memchr(p->buf, '\n', p->len) : NULL;
        struct pollfd fds[2];
        int r;
        if (nl) {
            size_t n = (size_t)(nl - p->buf);
            char *line = malloc(n + 1);
            if (!line) {
                (void)snprintf(err, errcap, "out of memory");
                return NULL;
            }
            memcpy(line, p->buf, n);
            line[n] = '\0';
            if (n && line[n - 1] == '\r') {
                line[n - 1] = '\0';
            }
            memmove(p->buf, nl + 1, p->len - n - 1);
            p->len -= n + 1;
            return line;
        }
        if (pic_interrupted) {
            (void)snprintf(err, errcap, "interrupted");
            return NULL;
        }
        if (ms_now() >= idle_end) {
            (void)snprintf(err, errcap, "timed out (no answer within %d seconds)", timeout);
            return NULL;
        }
        fds[0].fd = p->out;
        fds[0].events = POLLIN;
        fds[1].fd = p->err;
        fds[1].events = POLLIN;
        fds[0].revents = fds[1].revents = 0;
        r = poll(fds, 2, 200);
        if (r < 0 && errno != EINTR) {
            (void)snprintf(err, errcap, "%s", strerror(errno));
            return NULL;
        }
        if (r > 0 && fds[1].revents) {
            ms_keep_stderr(p);
        }
        if (r > 0 && fds[0].revents) {
            ssize_t got;
            if (p->len + 65536 + 1 > p->cap) {
                size_t cap = p->cap ? p->cap * 2 : 131072;
                char *grown;
                if (cap > MS_LINE_CAP + 65536 + 1 || !(grown = realloc(p->buf, cap))) {
                    (void)snprintf(err, errcap, "%s wrote a line longer than %u MB", p->name, MS_LINE_CAP >> 20);
                    return NULL;
                }
                p->buf = grown;
                p->cap = cap;
            }
            got = read(p->out, p->buf + p->len, 65536);
            if (got > 0) {
                p->len += (size_t)got;
                idle_end = ms_now() + (long long)timeout * 1000;
            } else if (got == 0 || errno != EINTR) {
                ms_keep_stderr(p);
                (void)snprintf(err, errcap, "%s exited%s%.300s", p->name, p->tail_len ? "; it said: " : "", p->tail);
                return NULL;
            }
        }
    }
}

const pic_mcp_pipe_ops pic_mcp_host_pipes = {ms_start, ms_send, ms_recv, ms_stop};