Skip to content
pi-c Artifact [d8ddafa1b7]
Login

Artifact [d8ddafa1b7]

Artifact d8ddafa1b7d2441cdf81b9c599f687fd943351ff75299a186fde26f4375e148c:


/* 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>
#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;
}

long pic_tty_secret(const char *prompt, char *buf, size_t cap, char *err, size_t errcap) {
    int fd = 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, "no terminal to ask on");
        return -1;
    }
    if (tcgetattr(fd, &old) != 0) {
        (void)snprintf(err, errcap, "no terminal to ask on");
        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;
}

/* Whether HOME is the account's own home directory. */
static int 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 (!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 (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;
}

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 = 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);
}

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,
};

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; }