Skip to content
pi-c Documentation
Login

Documentation

/* The host platform (see platform.h). */
#include <errno.h>
#include <limits.h>
#include <pwd.h>
#include <spawn.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <sys/random.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#include <sys/event.h>
#define PLAT_KQUEUE 1
#elif defined(__linux__)
#include <sys/inotify.h>
#define PLAT_INOTIFY 1
#endif

#include "platform.h"

static int64_t host_wall_ns(void) {
    struct timespec ts;
    if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
        return -1;
    }
    return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}

static uint64_t host_mono_ns(void) {
    struct timespec ts;
    (void)clock_gettime(CLOCK_MONOTONIC, &ts);
    return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec;
}

static int host_entropy(void *buf, size_t n) { return getentropy(buf, n); }

static int host_lock(const char *path, int shared) {
    int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
    if (fd < 0) {
        return -1;
    }
    if (flock(fd, (shared ? LOCK_SH : LOCK_EX) | LOCK_NB) != 0) {
        int e = errno;
        close(fd);
        errno = e;
        return -2;
    }
    return fd;
}

static void host_unlock(int handle) { close(handle); }

/* ---- host only: the terminal ---------------------------------------- */

/* While echo is off: the terminal's settings, so a signal can put them back.
 * SIGINT and SIGTERM restore and re-raise (the default then ends pic);
 * SIGTSTP restores and stops, and on the way back (or on a SIGCONT after an
 * outside stop) echo goes off again. */
static volatile sig_atomic_t tty_fd = -1;
static struct termios tty_old, tty_quiet;
static const int tty_signals[4] = {SIGINT, SIGTERM, SIGTSTP, SIGCONT};
static struct sigaction tty_saved[4];

static void tty_on_signal(int sig) {
    int e = errno;
    if (tty_fd >= 0) {
        if (sig == SIGCONT) {
            (void)tcsetattr(tty_fd, TCSANOW, &tty_quiet);
        } else {
            sigset_t one;
            struct sigaction dfl;
            (void)tcsetattr(tty_fd, TCSANOW, &tty_old);
            memset(&dfl, 0, sizeof dfl);
            dfl.sa_handler = SIG_DFL;
            sigemptyset(&dfl.sa_mask);
            (void)sigaction(sig, &dfl, NULL);
            sigemptyset(&one);
            sigaddset(&one, sig);
            (void)raise(sig);
            (void)sigprocmask(SIG_UNBLOCK, &one, NULL); /* delivered here: dies, or stops until SIGCONT */
            if (sig == SIGTSTP) { /* continued: back to the read, echo off again */
                struct sigaction mine;
                memset(&mine, 0, sizeof mine);
                mine.sa_handler = tty_on_signal;
                sigemptyset(&mine.sa_mask);
                (void)sigaction(SIGTSTP, &mine, NULL);
                (void)tcsetattr(tty_fd, TCSANOW, &tty_quiet);
            }
        }
    }
    errno = e;
}

static int tty_forbidden;

void pic_tty_forbid(void) { tty_forbidden = 1; }

long pic_tty_secret(const char *prompt, char *buf, size_t cap, char *err, size_t errcap) {
    int fd = tty_forbidden ? -1 : open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC);
    struct termios old, quiet;
    struct sigaction mine;
    size_t n = 0;
    long rc = -1;
    if (fd < 0) {
        (void)snprintf(err, errcap, PIC_NO_TERMINAL);
        return -1;
    }
    if (tcgetattr(fd, &old) != 0) {
        (void)snprintf(err, errcap, PIC_NO_TERMINAL);
        close(fd);
        return -1;
    }
    quiet = old;
    quiet.c_lflag &= ~(tcflag_t)(ECHO | ECHOE | ECHOK | ECHONL);
    quiet.c_lflag |= ICANON;
    tty_old = old;
    tty_quiet = quiet;
    tty_fd = fd;
    memset(&mine, 0, sizeof mine);
    mine.sa_handler = tty_on_signal; /* no SA_RESTART: the read sees EINTR and goes on */
    sigemptyset(&mine.sa_mask);
    for (int i = 0; i < 4; i++) {
        (void)sigaction(tty_signals[i], &mine, &tty_saved[i]);
    }
    /* Echo off before the prompt shows, so nothing typed after it can echo;
     * input typed before it is dropped. */
    if (tcsetattr(fd, TCSAFLUSH, &quiet) != 0) {
        (void)snprintf(err, errcap, "cannot turn the terminal's echo off");
        tty_fd = -1;
        for (int i = 0; i < 4; i++) {
            (void)sigaction(tty_signals[i], &tty_saved[i], NULL);
        }
        close(fd);
        return -1;
    }
    if (write(fd, prompt, strlen(prompt)) < 0) {
        /* the prompt is a courtesy: reading the secret goes on */
    }
    for (;;) {
        char c;
        ssize_t got = read(fd, &c, 1);
        if (got < 0 && errno == EINTR) {
            continue;
        }
        if (got <= 0) {
            (void)snprintf(err, errcap, "no answer was typed");
            break;
        }
        if (c == '\n' || c == '\r') {
            buf[n] = '\0';
            rc = (long)n;
            break;
        }
        if (n + 1 >= cap) {
            (void)snprintf(err, errcap, "the answer is longer than %zu bytes", cap - 1);
            break;
        }
        buf[n++] = c;
    }
    (void)tcsetattr(fd, TCSAFLUSH, &old);
    tty_fd = -1;
    for (int i = 0; i < 4; i++) {
        (void)sigaction(tty_signals[i], &tty_saved[i], NULL);
    }
    if (write(fd, "\n", 1) < 0) {
        /* the newline after the secret is a courtesy */
    }
    close(fd);
    if (rc < 0) {
        volatile char *v = buf;
        for (size_t i = 0; i < cap; i++) {
            v[i] = 0;
        }
    }
    return rc;
}

/* ---- host only: the credential store's key sources ----------------------
 * A raw key is kept in the login Keychain (macOS, /usr/bin/security) or the
 * Secret Service (secret-tool, when a session bus is there), else in a 0600
 * key file beside the store. Both keystores are run as child processes, the
 * key on their stdin and never in argv, so pic links no framework. The
 * keystore is used only for the store under the account's own home: a store
 * under another HOME (a test's) gets the key file. PIC_TEST_KEYCHAIN names a
 * program standing in for the keystore (it speaks security's dialect on
 * macOS, secret-tool's elsewhere), and lifts that rule. */

#define KEY_SERVICE "pic credential store"
#define RAW_KEY 32

extern char **environ;

static void plat_wipe(void *p, size_t n) {
    volatile unsigned char *v = p;
    while (n--) {
        *v++ = 0;
    }
}

/* Runs ARGV (argv[0] a path) with IN on its stdin (NULL: /dev/null) and its
 * stdout into OUT (at most cap - 1 bytes, NUL-terminated; NULL: /dev/null);
 * stderr goes to /dev/null unless KEEP_ERR. Its exit status, or -1. */
static int plat_run(const char *const argv[], const char *in, size_t inlen, char *out, size_t cap, int keep_err) {
    posix_spawn_file_actions_t fa;
    int inp[2] = {-1, -1}, outp[2] = {-1, -1}, status = -1, rc = -1;
    size_t got = 0;
    pid_t pid;
    struct sigaction ign, was;
    if ((in && pipe(inp) != 0) || (out && pipe(outp) != 0)) {
        goto done;
    }
    if (posix_spawn_file_actions_init(&fa) != 0) {
        goto done;
    }
    if (in) {
        (void)posix_spawn_file_actions_adddup2(&fa, inp[0], 0);
        (void)posix_spawn_file_actions_addclose(&fa, inp[1]);
    } else {
        (void)posix_spawn_file_actions_addopen(&fa, 0, "/dev/null", O_RDONLY, 0);
    }
    if (out) {
        (void)posix_spawn_file_actions_adddup2(&fa, outp[1], 1);
        (void)posix_spawn_file_actions_addclose(&fa, outp[0]);
    } else {
        (void)posix_spawn_file_actions_addopen(&fa, 1, "/dev/null", O_WRONLY, 0);
    }
    if (!keep_err) {
        (void)posix_spawn_file_actions_addopen(&fa, 2, "/dev/null", O_WRONLY, 0);
    }
    {
        char *args[16];
        size_t k = 0;
        for (; argv[k] && k + 1 < 16; k++) {
            memcpy(&args[k], &argv[k], sizeof args[k]); /* posix_spawn takes char *const[] */
        }
        args[k] = NULL;
        if (posix_spawn(&pid, args[0], &fa, NULL, args, environ) != 0) {
            posix_spawn_file_actions_destroy(&fa);
            goto done;
        }
    }
    posix_spawn_file_actions_destroy(&fa);
    if (in) {
        close(inp[0]);
        inp[0] = -1;
        memset(&ign, 0, sizeof ign);
        ign.sa_handler = SIG_IGN; /* a child that ends early must not end pic */
        (void)sigaction(SIGPIPE, &ign, &was);
        while (inlen > 0) {
            ssize_t w = write(inp[1], in, inlen);
            if (w < 0 && errno == EINTR) {
                continue;
            }
            if (w <= 0) {
                break;
            }
            in += w;
            inlen -= (size_t)w;
        }
        close(inp[1]);
        inp[1] = -1;
        (void)sigaction(SIGPIPE, &was, NULL);
    }
    if (out) {
        char sink[256];
        close(outp[1]);
        outp[1] = -1;
        for (;;) {
            char *to = got + 1 < cap ? out + got : sink;
            size_t room = got + 1 < cap ? cap - 1 - got : sizeof sink;
            ssize_t r = read(outp[0], to, room);
            if (r < 0 && errno == EINTR) {
                continue;
            }
            if (r <= 0) {
                break;
            }
            if (to != sink) {
                got += (size_t)r;
            }
        }
        out[got] = '\0';
        plat_wipe(sink, sizeof sink);
    }
    while (waitpid(pid, &status, 0) < 0) {
        if (errno != EINTR) {
            status = -1;
            break;
        }
    }
    rc = status >= 0 && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
done:
    for (int i = 0; i < 2; i++) {
        if (inp[i] >= 0) {
            close(inp[i]);
        }
        if (outp[i] >= 0) {
            close(outp[i]);
        }
    }
    return rc;
}

static void hex_of(const unsigned char *b, size_t n, char *out) {
    static const char digits[] = "0123456789abcdef";
    for (size_t i = 0; i < n; i++) {
        out[2 * i] = digits[b[i] >> 4];
        out[2 * i + 1] = digits[b[i] & 15];
    }
    out[2 * n] = '\0';
}

/* TEXT's leading 64 hex digits (then only white space) as a 32-byte key: 0 or -1. */
static int key_of_hex(const char *text, unsigned char *key) {
    for (size_t i = 0; i < 2 * RAW_KEY; i++) {
        char c = text[i];
        int v = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
        if (v < 0) {
            return -1;
        }
        key[i / 2] = (unsigned char)(i % 2 ? (key[i / 2] << 4) | v : v);
    }
    for (const char *t = text + 2 * RAW_KEY; *t; t++) {
        if (*t != '\n' && *t != '\r' && *t != ' ') {
            return -1;
        }
    }
    return 0;
}

int pic_host_own_home(void) {
    const char *home = getenv("HOME");
    struct passwd *pw = getpwuid(getuid());
    char a[PATH_MAX], b[PATH_MAX];
    return home && pw && pw->pw_dir && realpath(home, a) && realpath(pw->pw_dir, b) && strcmp(a, b) == 0;
}

#if !defined(__APPLE__)
/* The program on PATH named NAME, into out: 0 or -1. */
static int on_path(const char *name, char *out, size_t cap) {
    const char *path = getenv("PATH");
    while (path && *path) {
        const char *colon = strchr(path, ':');
        size_t n = colon ? (size_t)(colon - path) : strlen(path);
        if (n > 0 && snprintf(out, cap, "%.*s/%s", (int)n, path, name) < (int)cap && access(out, X_OK) == 0) {
            return 0;
        }
        path = colon ? colon + 1 : NULL;
    }
    return -1;
}
#endif

/* The keystore program into prog: 0, or -1 with err (none here, or not for this HOME). */
static int keystore(char *prog, size_t cap, char *err, size_t errcap) {
    const char *seam = getenv("PIC_TEST_KEYCHAIN");
    if (seam && *seam) {
        (void)snprintf(prog, cap, "%s", seam);
        return 0;
    }
    if (!pic_host_own_home()) {
        (void)snprintf(err, errcap, "the keychain keeps only the key of the store in your own home directory");
        return -1;
    }
#if defined(__APPLE__)
    (void)snprintf(prog, cap, "/usr/bin/security");
    if (access(prog, X_OK) == 0) {
        return 0;
    }
    (void)snprintf(err, errcap, "/usr/bin/security is missing");
#else
    {
        const char *bus = getenv("DBUS_SESSION_BUS_ADDRESS");
        if (bus && *bus && on_path("secret-tool", prog, cap) == 0) {
            return 0;
        }
        (void)snprintf(err, errcap, "no keyring: secret-tool and a session bus are needed");
    }
#endif
    return -1;
}

/* The store's id as a keystore account: no quote, backslash or line break. */
static int account_ok(const char *id, char *err, size_t errcap) {
    if (!id || !*id || strpbrk(id, "\"\\\n\r")) {
        (void)snprintf(err, errcap, "the store's path has a character the keychain cannot name");
        return -1;
    }
    return 0;
}

static int keychain_get(const char *id, unsigned char *key, char *err, size_t errcap) {
    char prog[PATH_MAX], out[256];
    int st, rc = -1;
    if (keystore(prog, sizeof prog, err, errcap) != 0 || account_ok(id, err, errcap) != 0) {
        return -1;
    }
#if defined(__APPLE__)
    {
        const char *argv[] = {prog, "find-generic-password", "-s", KEY_SERVICE, "-a", id, "-w", NULL};
        st = plat_run(argv, NULL, 0, out, sizeof out, 0);
    }
#else
    {
        const char *argv[] = {prog, "lookup", "service", KEY_SERVICE, "account", id, NULL};
        st = plat_run(argv, NULL, 0, out, sizeof out, 0);
    }
#endif
    if (st != 0) {
        (void)snprintf(err, errcap, "the keychain has no key for this store, or would not give it (locked, or over ssh)");
    } else if (key_of_hex(out, key) != 0) {
        (void)snprintf(err, errcap, "the keychain's item for this store is not a key");
    } else {
        rc = 0;
    }
    plat_wipe(out, sizeof out);
    return rc;
}

static void keychain_drop(const char *id) {
    char prog[PATH_MAX], err[200];
    if (keystore(prog, sizeof prog, err, sizeof err) != 0 || account_ok(id, err, sizeof err) != 0) {
        return;
    }
#if defined(__APPLE__)
    {
        const char *argv[] = {prog, "delete-generic-password", "-s", KEY_SERVICE, "-a", id, NULL};
        (void)plat_run(argv, NULL, 0, NULL, 0, 0);
    }
#else
    {
        const char *argv[] = {prog, "clear", "service", KEY_SERVICE, "account", id, NULL};
        (void)plat_run(argv, NULL, 0, NULL, 0, 0);
    }
#endif
}

/* Keeps KEY in the keychain, then reads it back: a locked keychain that
 * seemed to take it is a refusal. 0, or -1 with err. */
static int keychain_keep(const char *id, const unsigned char *key, char *err, size_t errcap) {
    char prog[PATH_MAX], hex[2 * RAW_KEY + 1], line[PATH_MAX + 256];
    unsigned char back[RAW_KEY];
    int same;
    if (keystore(prog, sizeof prog, err, errcap) != 0 || account_ok(id, err, errcap) != 0) {
        return -1;
    }
    hex_of(key, RAW_KEY, hex);
#if defined(__APPLE__)
    {   /* security -i reads the command on stdin, so the key is never in argv */
        const char *argv[] = {prog, "-i", NULL};
        int n = snprintf(line, sizeof line, "add-generic-password -U -s \"" KEY_SERVICE "\" -l \"" KEY_SERVICE "\" -a \"%s\" -w %s\n",
                     id, hex);
        if (n > 0 && (size_t)n < sizeof line) {
            (void)plat_run(argv, line, (size_t)n, NULL, 0, 0);
        }
    }
#else
    {
        const char *argv[] = {prog, "store", "--label=" KEY_SERVICE, "service", KEY_SERVICE, "account", id, NULL};
        (void)plat_run(argv, hex, 2 * RAW_KEY, NULL, 0, 0);
    }
#endif
    plat_wipe(line, sizeof line);
    plat_wipe(hex, sizeof hex);
    if (keychain_get(id, back, err, errcap) != 0) {
        (void)snprintf(err, errcap, "the keychain did not keep the key (locked, or over ssh)");
        return -1;
    }
    same = memcmp(back, key, RAW_KEY) == 0;
    plat_wipe(back, sizeof back);
    if (!same) {
        (void)snprintf(err, errcap, "the keychain gave back another key");
        return -1;
    }
    return 0;
}

/* The key file beside the store ID (its database's path). */
static int key_file(const char *id, char *out, size_t cap) {
    const char *slash = id ? strrchr(id, '/') : NULL;
    return slash && snprintf(out, cap, "%.*s/master.key", (int)(slash - id), id) < (int)cap ? 0 : -1;
}

static int file_get(const char *id, unsigned char *key, char *err, size_t errcap) {
    char path[PATH_MAX], text[160];
    struct stat st;
    ssize_t n;
    int fd, rc = -1;
    if (key_file(id, path, sizeof path) != 0) {
        (void)snprintf(err, errcap, "no path for the key file");
        return -1;
    }
    if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW)) < 0) {
        (void)snprintf(err, errcap, "cannot read %s: %s", path, strerror(errno));
        return -1;
    }
    if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_uid != getuid()) {
        (void)snprintf(err, errcap, "%s is not a file you own", path);
    } else if (st.st_mode & 077) {
        (void)snprintf(err, errcap, "%s can be read by others: chmod 600 it", path);
    } else if ((n = read(fd, text, sizeof text - 1)) < 0) {
        (void)snprintf(err, errcap, "cannot read %s: %s", path, strerror(errno));
    } else {
        text[n] = '\0';
        if (key_of_hex(text, key) != 0) {
            (void)snprintf(err, errcap, "%s does not hold a key", path);
        } else {
            rc = 0;
        }
    }
    plat_wipe(text, sizeof text);
    close(fd);
    return rc;
}

/* Writes the key file whole or not at all: a 0600 temporary, synced, renamed over. */
static int file_keep(const char *id, const unsigned char *key, char *err, size_t errcap) {
    char path[PATH_MAX], tmp[PATH_MAX + 32], hex[2 * RAW_KEY + 2];
    int fd, ok;
    if (key_file(id, path, sizeof path) != 0 ||
        snprintf(tmp, sizeof tmp, "%s.%ld.tmp", path, (long)getpid()) >= (int)sizeof tmp) {
        (void)snprintf(err, errcap, "no path for the key file");
        return -1;
    }
    (void)unlink(tmp);
    if ((fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600)) < 0) {
        (void)snprintf(err, errcap, "cannot write %s: %s", tmp, strerror(errno));
        return -1;
    }
    hex_of(key, RAW_KEY, hex);
    hex[2 * RAW_KEY] = '\n';
    hex[2 * RAW_KEY + 1] = '\0';
    ok = fchmod(fd, 0600) == 0 && write(fd, hex, 2 * RAW_KEY + 1) == 2 * RAW_KEY + 1 && fsync(fd) == 0;
    plat_wipe(hex, sizeof hex);
    if (close(fd) != 0 || !ok || rename(tmp, path) != 0) {
        (void)snprintf(err, errcap, "cannot write %s: %s", path, strerror(errno));
        (void)unlink(tmp);
        return -1;
    }
#if defined(__APPLE__)
    if (pic_host_own_home() && !getenv("PIC_TEST_KEYCHAIN")) { /* best effort: keep it out of Time Machine */
        const char *argv[] = {"/usr/bin/tmutil", "addexclusion", path, NULL};
        (void)plat_run(argv, NULL, 0, NULL, 0, 0);
    }
#endif
    return 0;
}

/* A line from FD, read a byte at a time so a second line stays for the next ask. */
static long fd_line(int fd, char *buf, size_t cap, char *err, size_t errcap) {
    size_t n = 0;
    for (;;) {
        char c;
        ssize_t r = read(fd, &c, 1);
        if (r < 0 && errno == EINTR) {
            continue;
        }
        if (r <= 0 || c == '\n') {
            if (r <= 0 && n == 0) {
                (void)snprintf(err, errcap, "nothing to read on descriptor %d", fd);
                return -1;
            }
            break;
        }
        if (n + 1 >= cap) {
            (void)snprintf(err, errcap, "the passphrase is longer than %zu bytes", cap - 1);
            plat_wipe(buf, cap);
            return -1;
        }
        buf[n++] = c;
    }
    if (n > 0 && buf[n - 1] == '\r') {
        n--;
    }
    buf[n] = '\0';
    return (long)n;
}

/* The passphrase: from --passphrase-fd, a command, the dev build's
 * PIC_TEST_PASSPHRASE (a release build never reads it), else typed on the
 * controlling terminal (twice for a new store). */
static int host_passphrase(const pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                           size_t errcap) {
    char again[512];
    long n;
    *how = PIC_SECRET_PASSPHRASE;
    if (ask->fd >= 0) {
        n = fd_line(ask->fd, (char *)buf, cap, err, errcap);
    } else if (ask->command && *ask->command) {
        const char *argv[] = {"/bin/sh", "-c", ask->command, NULL};
        char *nl;
        int st = plat_run(argv, NULL, 0, (char *)buf, cap, 1);
        if (st != 0) {
            plat_wipe(buf, cap);
            (void)snprintf(err, errcap, "the passphrase command failed (exit %d)", st);
            return -1;
        }
        if ((nl = strchr((char *)buf, '\n'))) {
            plat_wipe(nl, strlen(nl));
        }
        n = (long)strlen((char *)buf);
    } else {
#ifdef PIC_FAULTS
        const char *t = getenv("PIC_TEST_PASSPHRASE");
        if (t) {
            size_t k = strlen(t);
            if (k == 0 || k > cap) {
                (void)snprintf(err, errcap, "PIC_TEST_PASSPHRASE is empty or too long");
                return -1;
            }
            memcpy(buf, t, k);
            *len = k;
            return 0;
        }
#endif
        *how = PIC_SECRET_TYPED;
        n = pic_tty_secret(ask->fresh ? "New passphrase for pic's credential store: " : "Passphrase for pic's credential store: ",
                           (char *)buf, cap, err, errcap);
        if (n > 0 && ask->fresh) {
            long m = pic_tty_secret("Same passphrase again: ", again, sizeof again, err, errcap);
            int same = m == n && memcmp(again, buf, (size_t)n) == 0;
            plat_wipe(again, sizeof again);
            if (m < 0) {
                return -1;
            }
            if (!same) {
                (void)snprintf(err, errcap, "the two passphrases differ");
                return -1;
            }
        }
    }
    if (n < 0) {
        return -1;
    }
    if (n == 0) {
        (void)snprintf(err, errcap, "the passphrase is empty");
        return -1;
    }
    *len = (size_t)n;
    return 0;
}

int pic_host_open(const char *target) {
#ifdef __APPLE__
    static const char *const at[] = {"/usr/bin/open"};
#else
    static const char *const at[] = {"/usr/bin/xdg-open", "/bin/xdg-open", "/usr/local/bin/xdg-open"};
#endif
    static const char *const schemes[] = {"https://", "http://", "file://", "mailto:"};
    const char *opener = NULL;
    int known = 0;
    pid_t pid;
    for (size_t i = 0; i < sizeof schemes / sizeof schemes[0]; i++) {
        known |= strncmp(target, schemes[i], strlen(schemes[i])) == 0;
    }
    for (const char *c = target; known && *c; c++) {
        known = (unsigned char)*c > 0x20 && *c != 0x7f;
    }
    if (!known) {
        return -1;
    }
#ifdef PIC_FAULTS
    opener = getenv("PIC_TEST_BROWSER");
    if (opener && !*opener) {
        opener = NULL;
    }
#endif
    for (size_t i = 0; !opener && i < sizeof at / sizeof at[0]; i++) {
        if (access(at[i], X_OK) == 0) {
            opener = at[i];
        }
    }
    if (!opener || (pid = fork()) < 0) {
        return -1;
    }
    if (pid == 0) { /* a grandchild runs it, so no zombie is left */
        int null = open("/dev/null", O_RDWR);
        (void)setsid();
        if (null >= 0) {
            (void)dup2(null, STDIN_FILENO);
            (void)dup2(null, STDOUT_FILENO);
            (void)dup2(null, STDERR_FILENO);
        }
        if (fork() == 0) {
            execl(opener, opener, target, (char *)NULL);
        }
        _exit(0);
    }
    while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) {
    }
    return 0;
}

static int host_secret_key(const pic_secret_ask *ask, unsigned char *buf, size_t cap, size_t *len, int *how, char *err,
                           size_t errcap) {
    *how = PIC_SECRET_KEY;
    if (strcmp(ask->source, "passphrase") == 0) {
        return host_passphrase(ask, buf, cap, len, how, err, errcap);
    }
    if (cap < RAW_KEY) {
        (void)snprintf(err, errcap, "no room for the key");
        return -1;
    }
    *len = RAW_KEY;
    if (strcmp(ask->source, "keychain") == 0) {
        return keychain_get(ask->id, buf, err, errcap);
    }
    if (strcmp(ask->source, "file") == 0) {
        return file_get(ask->id, buf, err, errcap);
    }
    (void)snprintf(err, errcap, "this pic does not know the key source \"%.40s\"", ask->source);
    return -1;
}

static int host_secret_keep(const char *want, const char *id, const unsigned char *key, size_t n, char *source, size_t scap,
                            char *err, size_t errcap) {
    char why[200] = "";
    if (n != RAW_KEY) {
        (void)snprintf(err, errcap, "a raw key is %d bytes", RAW_KEY);
        return -1;
    }
    if (want && strcmp(want, "passphrase") == 0) {
        (void)snprintf(source, scap, "passphrase");
        return 1;
    }
#ifdef PIC_FAULTS
    if (!want && getenv("PIC_TEST_PASSPHRASE")) { /* the suite's stores keep their passphrase */
        (void)snprintf(source, scap, "passphrase");
        return 1;
    }
#endif
    if (want && !*want) {
        want = NULL; /* "": a kept key, the keychain else the file */
    }
    if (!want || strcmp(want, "keychain") == 0) {
        if (keychain_keep(id, key, why, sizeof why) == 0) {
            (void)snprintf(source, scap, "keychain");
            return 0;
        }
        if (want) {
            (void)snprintf(err, errcap, "%s", why);
            return -1;
        }
    }
    if (!want || strcmp(want, "file") == 0) {
        if (file_keep(id, key, err, errcap) == 0) {
            (void)snprintf(source, scap, "file");
            return 0;
        }
        return -1;
    }
    (void)snprintf(err, errcap, "no key source named \"%.40s\": keychain, file or passphrase", want);
    return -1;
}

static void host_secret_drop(const char *source, const char *id) {
    char path[PATH_MAX];
    if (strcmp(source, "keychain") == 0) {
        keychain_drop(id);
    } else if (strcmp(source, "file") == 0 && key_file(id, path, sizeof path) == 0) {
        (void)unlink(path);
    }
}

const char *pic_host_where(const char *source) {
    char prog[PATH_MAX], err[200];
    if (!source) {
        source = keystore(prog, sizeof prog, err, sizeof err) == 0 ? "keychain" : "file";
    }
    if (strcmp(source, "passphrase") == 0) {
        return "a passphrase";
    }
    if (strcmp(source, "file") == 0) {
        return "~/.pic/master.key";
    }
#if defined(__APPLE__)
    return "your Keychain";
#else
    return "your keyring";
#endif
}

long pic_tty_answer(const char *prompt, char *buf, size_t cap) {
    int fd = tty_forbidden ? -1 : open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC);
    char err[64];
    long n;
    if (fd < 0) {
        return -1;
    }
    if (write(fd, prompt, strlen(prompt)) < 0) {
        /* the prompt is a courtesy */
    }
    n = fd_line(fd, buf, cap, err, sizeof err);
    close(fd);
    return n;
}

/* ---- file watches ------------------------------------------------------ */

#if defined(PLAT_KQUEUE)
/* Each kqueue's watched file, closed with it. */
static struct {
    int kq, fd;
} plat_watches[8] = {{-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}};
#endif

/* PIC_NO_WATCH=1 (tests) stands in for a platform with none. */
static int host_watch(const char *path) {
    const char *off = getenv("PIC_NO_WATCH");
    if (off && strcmp(off, "1") == 0) {
        return -1;
    }
#if defined(PLAT_KQUEUE)
    int kq = kqueue(), fd = open(path, O_RDONLY | O_CLOEXEC), slot = -1;
    struct kevent ev;
    for (int i = 0; i < 8 && slot < 0; i++) {
        slot = plat_watches[i].kq < 0 ? i : -1;
    }
    if (kq < 0 || fd < 0 || slot < 0) {
        if (kq >= 0) {
            close(kq);
        }
        if (fd >= 0) {
            close(fd);
        }
        return -1;
    }
    (void)fcntl(kq, F_SETFD, FD_CLOEXEC);
    EV_SET(&ev, (uintptr_t)fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB, 0, NULL);
    if (kevent(kq, &ev, 1, NULL, 0, NULL) != 0) {
        close(kq);
        close(fd);
        return -1;
    }
    plat_watches[slot].kq = kq;
    plat_watches[slot].fd = fd;
    return kq;
#elif defined(PLAT_INOTIFY)
    int fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
    if (fd < 0) {
        return -1;
    }
    if (inotify_add_watch(fd, path, IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE) < 0) {
        close(fd);
        return -1;
    }
    return fd;
#else
    (void)path;
    return -1;
#endif
}

static void host_watch_clear(int fd) {
#if defined(PLAT_KQUEUE)
    struct kevent ev[8];
    struct timespec zero = {0, 0};
    (void)kevent(fd, NULL, 0, ev, 8, &zero);
#elif defined(PLAT_INOTIFY)
    char buf[4096];
    while (read(fd, buf, sizeof buf) > 0) {
    }
#else
    (void)fd;
#endif
}

static void host_watch_end(int fd) {
#if defined(PLAT_KQUEUE)
    for (int i = 0; i < 8; i++) {
        if (plat_watches[i].kq == fd) {
            close(plat_watches[i].fd);
            plat_watches[i].kq = plat_watches[i].fd = -1;
        }
    }
#endif
    close(fd);
}

/* ---- host only: the login agent (pic remote install) ---------------------
 * launchd on macOS (a LaunchAgent), systemd --user where systemd runs, else
 * an @reboot line in the user's crontab, each driven through its own program
 * (launchctl, systemctl, crontab) so pic links nothing. Like the keystore it
 * is only for the account's own home: a test's HOME is refused before any
 * program runs. PIC_TEST_AGENT=KIND:DIR stands in for that: KIND picks the
 * mechanism and DIR holds the programs it runs, and the rule is lifted. */

#define AGENT_LABEL "app.zeitforge.pic.remote"
#define AGENT_UNIT "pic-remote.service"
#define AGENT_MARK "# pic remote install"

/* The mechanism into a->kind and its program into prog: 0, or -1 with err. */
static int agent_pick(pic_login_agent *a, char *prog, size_t cap, char *err, size_t errcap) {
    const char *seam = getenv("PIC_TEST_AGENT"), *colon = seam ? strchr(seam, ':') : NULL;
    const char *name;
    if (colon) {
        (void)snprintf(a->kind, sizeof a->kind, "%.*s", (int)(colon - seam), seam);
        name = strcmp(a->kind, "launchd") == 0 ? "launchctl" : strcmp(a->kind, "systemd") == 0 ? "systemctl" : "crontab";
        if (snprintf(prog, cap, "%s/%s", colon + 1, name) >= (int)cap) {
            (void)snprintf(err, errcap, "PIC_TEST_AGENT is too long");
            return -1;
        }
        return 0;
    }
    if (!pic_host_own_home()) {
        (void)snprintf(err, errcap, "a login agent is kept only for your own home directory, and HOME is another");
        return -1;
    }
#if defined(__APPLE__)
    (void)snprintf(a->kind, sizeof a->kind, "launchd");
    (void)snprintf(prog, cap, "/bin/launchctl");
    if (access(prog, X_OK) == 0) {
        return 0;
    }
#else
    {
        struct stat sb;
        if (stat("/run/systemd/system", &sb) == 0 && S_ISDIR(sb.st_mode) && on_path("systemctl", prog, cap) == 0) {
            (void)snprintf(a->kind, sizeof a->kind, "systemd");
            return 0;
        }
        if (on_path("crontab", prog, cap) == 0) {
            (void)snprintf(a->kind, sizeof a->kind, "cron");
            return 0;
        }
    }
#endif
    a->kind[0] = '\0';
    (void)snprintf(err, errcap, "this system has none of launchd, systemd or cron to start pic remote at login");
    return -1;
}

/* Whether S has a byte of BAD (or a control character). */
static int agent_has(const char *s, const char *bad) {
    for (; *s; s++) {
        if ((unsigned char)*s < 0x20 || strchr(bad, *s)) {
            return 1;
        }
    }
    return 0;
}

/* Writes TEXT to PATH whole (a temporary file, then a rename), making its directory: 0 or -1. */
static int agent_write(const char *path, const char *text, char *err, size_t errcap) {
    char dir[PATH_MAX], tmp[PATH_MAX + 8];
    FILE *f;
    int ok;
    (void)snprintf(dir, sizeof dir, "%s", path);
    for (char *p = dir + 1; *p; p++) {
        if (*p == '/') {
            *p = '\0';
            (void)mkdir(dir, 0755);
            *p = '/';
        }
    }
    (void)snprintf(tmp, sizeof tmp, "%s.tmp", path);
    if (!(f = fopen(tmp, "w"))) {
        (void)snprintf(err, errcap, "cannot write %s: %s", tmp, strerror(errno));
        return -1;
    }
    ok = fputs(text, f) >= 0;
    ok = fclose(f) == 0 && ok;
    if (!ok || rename(tmp, path) != 0) {
        (void)snprintf(err, errcap, "cannot write %s: %s", path, strerror(errno));
        (void)unlink(tmp);
        return -1;
    }
    return 0;
}

/* Appends S to the text at *T (length *N, capacity CAP), XML-escaped when XML: 0, or -1 when full. */
static int agent_put(char *t, size_t cap, size_t *n, const char *s, int xml) {
    for (; *s; s++) {
        const char *r = !xml ? NULL : *s == '&' ? "&amp;" : *s == '<' ? "&lt;" : *s == '>' ? "&gt;" : NULL;
        size_t k = r ? strlen(r) : 1;
        if (*n + k >= cap) {
            return -1;
        }
        memcpy(t + *n, r ? r : s, k);
        *n += k;
    }
    t[*n] = '\0';
    return 0;
}

static int agent_launchd(int op, pic_login_agent *a, const char *prog, char *err, size_t errcap) {
    const char *home = getenv("HOME");
    char domain[48], target[96], text[8192];
    size_t n = 0;
    int had, ok = 0;
    (void)snprintf(domain, sizeof domain, "gui/%ld", (long)getuid());
    (void)snprintf(target, sizeof target, "%s/%s", domain, AGENT_LABEL);
    (void)snprintf(a->where, sizeof a->where, "%s/Library/LaunchAgents/%s.plist", home, AGENT_LABEL);
    had = access(a->where, F_OK) == 0;
    if (op == PIC_AGENT_STATE) {
        return had;
    }
    if (op == PIC_AGENT_REMOVE || had) { /* stops what launchd started; a new plist is read afresh */
        const char *argv[] = {prog, "bootout", target, NULL};
        (void)plat_run(argv, NULL, 0, NULL, 0, 0);
    }
    if (op == PIC_AGENT_REMOVE) {
        return had && unlink(a->where) == 0;
    }
    ok = agent_put(text, sizeof text, &n,
                   "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                   "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
                   "<plist version=\"1.0\">\n<dict>\n\t<key>Label</key>\n\t<string>" AGENT_LABEL "</string>\n"
                   "\t<key>ProgramArguments</key>\n\t<array>\n",
                   0) == 0;
    for (int i = 0; ok && a->argv[i]; i++) {
        ok = agent_put(text, sizeof text, &n, "\t\t<string>", 0) == 0 && agent_put(text, sizeof text, &n, a->argv[i], 1) == 0 &&
             agent_put(text, sizeof text, &n, "</string>\n", 0) == 0;
    }
    /* Started at login and again after a failure, not after it stopped on its own (pic remote stop). */
    ok = ok && agent_put(text, sizeof text, &n,
                         "\t</array>\n\t<key>RunAtLoad</key>\n\t<true/>\n\t<key>KeepAlive</key>\n\t<dict>\n"
                         "\t\t<key>SuccessfulExit</key>\n\t\t<false/>\n\t</dict>\n\t<key>ThrottleInterval</key>\n"
                         "\t<integer>30</integer>\n\t<key>StandardOutPath</key>\n\t<string>",
                         0) == 0;
    ok = ok && agent_put(text, sizeof text, &n, a->log, 1) == 0 &&
         agent_put(text, sizeof text, &n, "</string>\n\t<key>StandardErrorPath</key>\n\t<string>", 0) == 0 &&
         agent_put(text, sizeof text, &n, a->log, 1) == 0 && agent_put(text, sizeof text, &n, "</string>\n</dict>\n</plist>\n", 0) == 0;
    if (!ok) {
        (void)snprintf(err, errcap, "the LaunchAgent is too long");
        return -1;
    }
    if (agent_write(a->where, text, err, errcap) != 0) {
        return -1;
    }
    { /* over ssh there may be no login session to start it in: then the next login does */
        const char *argv[] = {prog, "bootstrap", domain, a->where, NULL};
        a->started = plat_run(argv, NULL, 0, NULL, 0, 0) == 0;
    }
    return 1;
}

static int agent_systemd(int op, pic_login_agent *a, const char *prog, char *err, size_t errcap) {
    const char *home = getenv("HOME"), *xdg = getenv("XDG_CONFIG_HOME");
    const char *reload[] = {prog, "--user", "daemon-reload", NULL};
    char text[8192];
    size_t n = 0;
    int had, ok;
    if (xdg && *xdg == '/') {
        (void)snprintf(a->where, sizeof a->where, "%s/systemd/user/%s", xdg, AGENT_UNIT);
    } else {
        (void)snprintf(a->where, sizeof a->where, "%s/.config/systemd/user/%s", home, AGENT_UNIT);
    }
    had = access(a->where, F_OK) == 0;
    if (op == PIC_AGENT_STATE) {
        return had;
    }
    if (op == PIC_AGENT_REMOVE) {
        const char *argv[] = {prog, "--user", "disable", "--now", AGENT_UNIT, NULL};
        if (!had) {
            return 0;
        }
        (void)plat_run(argv, NULL, 0, NULL, 0, 0);
        ok = unlink(a->where) == 0;
        (void)plat_run(reload, NULL, 0, NULL, 0, 0);
        return ok;
    }
    /* Quoted for ExecStart; a byte systemd would read as a specifier or an escape is refused. */
    ok = !agent_has(a->log, "%\\\" ");
    ok = ok && agent_put(text, sizeof text, &n, "[Unit]\nDescription=pic remote: remote control through the relay\n\n[Service]\nExecStart=", 0) == 0;
    for (int i = 0; ok && a->argv[i]; i++) {
        ok = !agent_has(a->argv[i], "%\\\"$") && agent_put(text, sizeof text, &n, i ? " \"" : "\"", 0) == 0 &&
             agent_put(text, sizeof text, &n, a->argv[i], 0) == 0 && agent_put(text, sizeof text, &n, "\"", 0) == 0;
    }
    ok = ok && agent_put(text, sizeof text, &n, "\nRestart=on-failure\nRestartSec=30\nStandardOutput=append:", 0) == 0 &&
         agent_put(text, sizeof text, &n, a->log, 0) == 0 && agent_put(text, sizeof text, &n, "\nStandardError=append:", 0) == 0 &&
         agent_put(text, sizeof text, &n, a->log, 0) == 0 &&
         agent_put(text, sizeof text, &n, "\n\n[Install]\nWantedBy=default.target\n", 0) == 0;
    if (!ok) {
        (void)snprintf(err, errcap, "pic's path or HOME has a character a systemd unit cannot hold");
        return -1;
    }
    if (agent_write(a->where, text, err, errcap) != 0) {
        return -1;
    }
    {
        const char *argv[] = {prog, "--user", "enable", "--now", AGENT_UNIT, NULL};
        if (plat_run(reload, NULL, 0, NULL, 0, 0) != 0 || plat_run(argv, NULL, 0, NULL, 0, 0) != 0) {
            (void)unlink(a->where);
            (void)plat_run(reload, NULL, 0, NULL, 0, 0);
            (void)snprintf(err, errcap, "systemctl --user could not enable %s (is there a user session?)", AGENT_UNIT);
            return -1;
        }
    }
    a->started = 1;
    return 1;
}

static int agent_cron(int op, pic_login_agent *a, const char *prog, char *err, size_t errcap) {
    const char *list[] = {prog, "-l", NULL}, *home = getenv("HOME");
    char *table = malloc(65536), *kept = malloc(65536 + 4096), tmp[PATH_MAX];
    size_t n = 0;
    int had = 0, rc = -1, ok = 1;
    (void)snprintf(a->where, sizeof a->where, "crontab");
    if (!table || !kept) {
        (void)snprintf(err, errcap, "out of memory");
        goto done;
    }
    if (plat_run(list, NULL, 0, table, 65536, 0) != 0) {
        table[0] = '\0'; /* no crontab yet */
    }
    kept[0] = '\0';
    for (char *line = table, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        if (strstr(line, AGENT_MARK)) {
            had = 1;
        } else {
            ok = ok && agent_put(kept, 65536, &n, line, 0) == 0 && agent_put(kept, 65536, &n, "\n", 0) == 0;
        }
        if (!nl) {
            break;
        }
    }
    if (op == PIC_AGENT_STATE || (op == PIC_AGENT_REMOVE && !had)) {
        rc = had;
        goto done;
    }
    if (op == PIC_AGENT_INSTALL) { /* cron has no login: the machine's start is what it offers */
        ok = ok && !agent_has(a->log, "'%") && agent_put(kept, 65536 + 4096, &n, "@reboot", 0) == 0;
        for (int i = 0; ok && a->argv[i]; i++) {
            ok = !agent_has(a->argv[i], "'%") && agent_put(kept, 65536 + 4096, &n, " '", 0) == 0 &&
                 agent_put(kept, 65536 + 4096, &n, a->argv[i], 0) == 0 && agent_put(kept, 65536 + 4096, &n, "'", 0) == 0;
        }
        ok = ok && agent_put(kept, 65536 + 4096, &n, " >> '", 0) == 0 && agent_put(kept, 65536 + 4096, &n, a->log, 0) == 0 &&
             agent_put(kept, 65536 + 4096, &n, "' 2>&1 " AGENT_MARK "\n", 0) == 0;
    }
    if (!ok) {
        (void)snprintf(err, errcap, "the crontab is too long, or pic's path has a character cron cannot hold");
        goto done;
    }
    (void)snprintf(tmp, sizeof tmp, "%s/.pic/crontab.tmp", home);
    if (agent_write(tmp, kept, err, errcap) == 0) {
        const char *put[] = {prog, tmp, NULL};
        if (plat_run(put, NULL, 0, NULL, 0, 0) == 0) {
            rc = 1;
        } else {
            (void)snprintf(err, errcap, "crontab refused the new table");
        }
        (void)unlink(tmp);
    }
done:
    free(table);
    free(kept);
    return rc;
}

static int host_login_agent(int op, pic_login_agent *a, char *err, size_t errcap) {
    char prog[PATH_MAX];
    a->kind[0] = a->where[0] = '\0';
    a->started = 0;
    if (!getenv("HOME") || agent_pick(a, prog, sizeof prog, err, errcap) != 0) {
        if (!getenv("HOME")) {
            (void)snprintf(err, errcap, "HOME is not set");
        }
        return op == PIC_AGENT_STATE && a->kind[0] == '\0' && getenv("HOME") ? 0 : -1;
    }
    if (strcmp(a->kind, "launchd") == 0) {
        return agent_launchd(op, a, prog, err, errcap);
    }
    if (strcmp(a->kind, "systemd") == 0) {
        return agent_systemd(op, a, prog, err, errcap);
    }
    return agent_cron(op, a, prog, err, errcap);
}

/* ---- host only: this program's file ---------------------------------------------------- */

static int host_self_path(char *out, size_t cap) {
#ifdef __APPLE__
    uint32_t size = (uint32_t)cap;
    char raw[PATH_MAX];
    if (cap > PATH_MAX) {
        size = PATH_MAX;
    }
    if (_NSGetExecutablePath(raw, &size) == 0 && realpath(raw, out)) {
        return 0;
    }
#else
    ssize_t n = readlink("/proc/self/exe", out, cap - 1);
    if (n > 0 && (size_t)n < cap - 1) {
        out[n] = '\0';
        return out[0] == '/' ? 0 : -1;
    }
#endif
    return -1;
}

static int host_file_stamp(const char *path, char *out, size_t cap) {
    struct stat sb;
    long long nsec;
    if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) {
        return -1;
    }
#ifdef __APPLE__
    nsec = (long long)sb.st_mtimespec.tv_sec * 1000000000LL + sb.st_mtimespec.tv_nsec;
#else
    nsec = (long long)sb.st_mtim.tv_sec * 1000000000LL + sb.st_mtim.tv_nsec;
#endif
    return snprintf(out, cap, "%llx:%llx:%llx:%llx", (unsigned long long)sb.st_dev, (unsigned long long)sb.st_ino,
                    (unsigned long long)sb.st_size, (unsigned long long)nsec) < (int)cap
               ? 0
               : -1;
}

/* lsof -F pc: a "p" line per process and a "c" line with its command. */
static int host_file_users(const char *path, long *pids, char (*names)[32], int cap) {
    const char *lsof = access("/usr/sbin/lsof", X_OK) == 0 ? "/usr/sbin/lsof" : access("/usr/bin/lsof", X_OK) == 0 ? "/usr/bin/lsof" : NULL;
    char file[4096], a0[] = "lsof", a1[] = "-n", a2[] = "-w", a3[] = "-F", a4[] = "pc", a5[] = "--";
    char *argv[] = {a0, a1, a2, a3, a4, a5, file, NULL};
    char buf[8192];
    size_t len = 0;
    int fds[2], st = 0, n = 0;
    posix_spawn_file_actions_t fa;
    pid_t pid;
    ssize_t r;
    if (!lsof || snprintf(file, sizeof file, "%s", path) >= (int)sizeof file || pipe(fds) != 0) {
        return -1;
    }
    (void)posix_spawn_file_actions_init(&fa);
    (void)posix_spawn_file_actions_adddup2(&fa, fds[1], STDOUT_FILENO);
    (void)posix_spawn_file_actions_addopen(&fa, STDERR_FILENO, "/dev/null", O_WRONLY, 0);
    (void)posix_spawn_file_actions_addopen(&fa, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
    (void)posix_spawn_file_actions_addclose(&fa, fds[0]);
    if (posix_spawn(&pid, lsof, &fa, NULL, argv, NULL) != 0) {
        (void)posix_spawn_file_actions_destroy(&fa);
        close(fds[0]);
        close(fds[1]);
        return -1;
    }
    (void)posix_spawn_file_actions_destroy(&fa);
    close(fds[1]);
    for (;;) { /* to the end, past what fits, so lsof never waits on a full pipe */
        char spill[512];
        r = len < sizeof buf - 1 ? read(fds[0], buf + len, sizeof buf - 1 - len) : read(fds[0], spill, sizeof spill);
        if (r < 0 && errno == EINTR) {
            continue;
        }
        if (r <= 0) {
            break;
        }
        len += len < sizeof buf - 1 ? (size_t)r : 0;
    }
    close(fds[0]);
    while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {
    }
    buf[len] = '\0';
    for (char *line = buf, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
        nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        if (line[0] == 'p') {
            if (n < cap) {
                pids[n] = strtol(line + 1, NULL, 10);
                names[n][0] = '\0';
            }
            n++;
        } else if (line[0] == 'c' && n > 0 && n <= cap) {
            (void)snprintf(names[n - 1], sizeof names[n - 1], "%s", line + 1);
        }
    }
    return n < cap ? n : cap;
}

static const pic_platform plat_host = {
    host_wall_ns, host_mono_ns, host_entropy, host_lock, host_unlock, pic_input_read_host, pic_input_list_host, NULL,
    host_secret_key, host_secret_keep, host_secret_drop, host_watch, host_watch_clear, host_watch_end, host_login_agent,
    host_self_path, host_file_stamp, host_file_users,
};

static const pic_platform *plat_current = &plat_host;

const pic_platform *pic_platform_host(void) { return &plat_host; }
const pic_platform *pic_platform_get(void) { return plat_current; }
void pic_platform_set(const pic_platform *p) { plat_current = p ? p : &plat_host; }