Skip to content
pi-c Artifact [b453fe4ec9]
Login

Artifact [b453fe4ec9]

Artifact b453fe4ec94c3eac3f0cf7d70955595b2cd051a5e8004c927153da675ea7950b:


/* The host platform (see platform.h). */
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.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;
}

/* The passphrase, asked on the controlling terminal (twice for a new
 * store). A dev build (PIC_FAULTS) also takes it from PIC_TEST_PASSPHRASE so
 * the suite can run without a terminal; a release build never reads it. */
static int host_secret_key(int fresh, unsigned char *buf, size_t cap, size_t *len, int *stretch, char *err,
                           size_t errcap) {
    char again[512];
    long n;
    *stretch = 1;
#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
    n = pic_tty_secret(fresh ? "New passphrase for pic's credential store: " : "Passphrase for pic's credential store: ",
                       (char *)buf, cap, err, errcap);
    if (n < 0) {
        return -1;
    }
    if (n == 0) {
        (void)snprintf(err, errcap, "the passphrase is empty");
        return -1;
    }
    if (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;
        volatile char *v = again;
        for (size_t i = 0; i < sizeof again; i++) {
            v[i] = 0;
        }
        if (m < 0) {
            return -1;
        }
        if (!same) {
            (void)snprintf(err, errcap, "the two passphrases differ");
            return -1;
        }
    }
    *len = (size_t)n;
    return 0;
}

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