Skip to content
suit Artifact [31c3763dc6]
Login

Artifact [31c3763dc6]

Artifact 31c3763dc688b4113f9034741e503bd4962a89899d739338960483831e64f45f:


#include "remote.h"

#include "anchors.h"
#include "conf.h"
#include "platform.h"
#include "stamp.h"

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

static char work[REMOTE_FILE_MAX + 1];
static char out_buf[REMOTE_FILE_MAX + 1];
static Remotes remotes;
static Creds creds;
static CredCmds cmds;
static CaFiles cafiles;
static Anchors check_anchors;

__attribute__((format(printf, 3, 4)))
static bool fail(RemoteError *e, int line, const char *fmt, ...)
{
    va_list ap;
    e->line = line;
    va_start(ap, fmt);
    vsnprintf(e->msg, sizeof e->msg, fmt, ap);
    va_end(ap);
    return false;
}

bool no_core_dumps(void)
{
    if (sys_no_core_dumps() == 0) return true;
    say(STDERR_FILENO, "suit: cannot turn off core files, which could hold a secret: %s\n", strerror(errno));
    return false;
}

void secret_wipe(void *p, size_t n)
{
    volatile unsigned char *v = p;
    for (size_t i = 0; i < n; i++) v[i] = 0;
}

static bool name_ok(const char *s, size_t max)
{
    size_t len = strlen(s);
    return len <= max && conf_name_ok(s, len, false);
}

// ---- the address -----------------------------------------------------------

static bool port_ok(const char *s, size_t len)
{
    if (len == 0 || len > 5) return false;
    unsigned v = 0;
    for (size_t i = 0; i < len; i++) {
        if (s[i] < '0' || s[i] > '9') return false;
        v = v * 10 + (unsigned)(s[i] - '0');
    }
    return v >= 1 && v <= 65535;
}

const char *remote_url_check(const char *url, size_t len)
{
    if (len == 0 || len > REMOTE_URL_MAX) return "an address is 1 to 1024 characters";
    for (size_t i = 0; i < len; i++)
        if ((unsigned char)url[i] < 0x21 || (unsigned char)url[i] > 0x7e)
            return "an address has printable characters only, and no space";
    bool file = strncmp(url, "file://", 7) == 0;
    bool https = strncmp(url, "https://", 8) == 0;
    if (!file && !https && strncmp(url, "http://", 7) != 0)
        return "an address starts with file://, http:// or https://";
    const char *rest = url + (https ? 8 : 7);
    if (file) {
        if (rest[0] != '/') return "a file:// address needs an absolute path after file://";
        if (strpbrk(rest, "?#%") != nullptr) return "an address has no query, fragment or % escape";
        return nullptr;
    }
    size_t auth = strcspn(rest, "/");
    if (memchr(rest, '@', auth) != nullptr)
        return "credentials do not go in the address; use suit login";
    if (rest[auth] != '/') return "an http address is http://HOST[:PORT]/PATH";
    if (strpbrk(rest, "?#%") != nullptr) return "an address has no query, fragment or % escape";
    const char *colon = memchr(rest, ':', auth);
    size_t host = colon != nullptr ? (size_t)(colon - rest) : auth;
    if (host == 0 || strspn(rest, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-") != host)
        return "the host is letters, digits, . and - only";
    if (colon != nullptr && !port_ok(colon + 1, auth - host - 1)) return "the port is 1 to 65535";
    return nullptr;
}

void remote_host(const char *url, char *out, size_t cap)
{
    const char *rest = strstr(url, "://") + 3;
    size_t n = strncmp(url, "file", 4) == 0 ? strlen(rest) : strcspn(rest, "/");
    snprintf(out, cap, "%.*s", (int)n, rest);
}

// ---- parsing ---------------------------------------------------------------

// F holds the fields of the line, then a null pointer.
typedef bool (*AddFn)(void *state, char *const *f, int line, RemoteError *e);

// Split each line of DATA on single spaces into NMIN to NMAX fields and give
// them to ADD. WORK holds secrets for a while: it is wiped before returning.
static bool parse_lines(const char *data, size_t len, size_t nmin, size_t nmax, const char *shape,
    AddFn add, void *state, RemoteError *e)
{
    if (len > REMOTE_FILE_MAX) return fail(e, 0, "file is %zu bytes, limit is %zu", len, REMOTE_FILE_MAX);
    memcpy(work, data, len);
    work[len] = '\0';
    char *p = work;
    char *end = work + len;
    int line = 0;
    bool ok = true;
    while (ok && p < end) {
        char *nl = memchr(p, '\n', (size_t)(end - p));
        line++;
        if (nl == nullptr) {
            ok = fail(e, line, "line has no newline");
        } else if ((size_t)(nl - p) > REMOTE_LINE_MAX) {
            ok = fail(e, line, "line is over the limit of %zu bytes", REMOTE_LINE_MAX);
        } else if (memchr(p, '\0', (size_t)(nl - p)) != nullptr) {
            ok = fail(e, line, "NUL byte in line");
        } else {
            *nl = '\0';
            char *f[CRED_CMD_WORDS_MAX + 4];  // the most fields, one more to see too many, and the end
            size_t k = 0;
            char *s = p;
            p = nl + 1;
            while (k <= nmax) {
                f[k++] = s;
                char *sp = strchr(s, ' ');
                if (sp == nullptr) break;
                *sp = '\0';
                s = sp + 1;
            }
            f[k] = nullptr;
            if (k < nmin || k > nmax) ok = fail(e, line, "expected %s", shape);
            else ok = add(state, f, line, e);
        }
    }
    secret_wipe(work, len);
    return ok;
}

static bool add_remote(void *state, char *const *f, int line, RemoteError *e)
{
    Remotes *r = state;
    if (!name_ok(f[0], CONF_NAME_MAX)) return fail(e, line, "not a wardrobe name (letters, digits, . _ -)");
    const char *why = remote_url_check(f[1], strlen(f[1]));
    if (why != nullptr) return fail(e, line, "%s", why);
    if (remotes_find(r, f[0]) != nullptr) return fail(e, line, "duplicate remote for %.80s", f[0]);
    if (r->n == REMOTE_ENTRY_MAX) return fail(e, line, "too many remotes (limit %u)", REMOTE_ENTRY_MAX);
    snprintf(r->e[r->n].name, sizeof r->e[0].name, "%s", f[0]);
    snprintf(r->e[r->n].url, sizeof r->e[0].url, "%s", f[1]);
    r->n++;
    return true;
}

// Whether the LEN bytes at S are printable ASCII with no space.
static bool printable(const char *s, size_t len)
{
    for (size_t i = 0; i < len; i++)
        if ((unsigned char)s[i] < 0x21 || (unsigned char)s[i] > 0x7e) return false;
    return true;
}

static bool secret_ok(const char *s, size_t len)
{
    return len >= 1 && len <= CRED_SECRET_MAX && printable(s, len);
}

// Nothing here repeats a field: one of them is a secret.
static bool add_cred(void *state, char *const *f, int line, RemoteError *e)
{
    Creds *c = state;
    if (!name_ok(f[0], CONF_NAME_MAX)) return fail(e, line, "not a wardrobe name (letters, digits, . _ -)");
    if (!name_ok(f[1], CRED_USER_MAX)) return fail(e, line, "not a user name (1 to %zu letters, digits, . _ -)", CRED_USER_MAX);
    if (!secret_ok(f[2], strlen(f[2]))) return fail(e, line, "the secret is 1 to %zu printable characters, no space", CRED_SECRET_MAX);
    if (creds_find(c, f[0]) != nullptr) return fail(e, line, "duplicate login for %.80s", f[0]);
    if (c->n == REMOTE_ENTRY_MAX) return fail(e, line, "too many logins (limit %u)", REMOTE_ENTRY_MAX);
    snprintf(c->e[c->n].name, sizeof c->e[0].name, "%s", f[0]);
    snprintf(c->e[c->n].user, sizeof c->e[0].user, "%s", f[1]);
    snprintf(c->e[c->n].secret, sizeof c->e[0].secret, "%s", f[2]);
    c->n++;
    return true;
}

static bool add_cafile(void *state, char *const *f, int line, RemoteError *e)
{
    CaFiles *c = state;
    if (!name_ok(f[0], CONF_NAME_MAX)) return fail(e, line, "not a wardrobe name (letters, digits, . _ -)");
    const char *why = anchors_path_check(f[1]);
    if (why != nullptr) return fail(e, line, "%s", why);
    if (cafiles_find(c, f[0]) != nullptr) return fail(e, line, "duplicate CA file for %.80s", f[0]);
    if (c->n == REMOTE_ENTRY_MAX) return fail(e, line, "too many CA files (limit %u)", REMOTE_ENTRY_MAX);
    snprintf(c->e[c->n].name, sizeof c->e[0].name, "%s", f[0]);
    snprintf(c->e[c->n].path, sizeof c->e[0].path, "%s", f[1]);
    c->n++;
    return true;
}

// Nullptr if the N words W (a program and its arguments) can be kept as a command, else why not.
static const char *words_check(size_t n, char *const *w)
{
    if (n > CRED_CMD_WORDS_MAX) return "a command is a program and at most 15 arguments";
    if (w[0][0] != '/') return "the program must be an absolute path: a timer has no PATH to search";
    size_t total = 0;
    for (size_t i = 0; i < n; i++) {
        if (w[i][0] == '\0' || !printable(w[i], strlen(w[i])))
            return "a command is words of printable characters with no space or newline, and no quoting";
        total += strlen(w[i]) + 1;
    }
    return total > CRED_CMD_MAX + 1 ? "a command is at most 1024 characters" : nullptr;
}

// The N words W as one line, a space between them. CAP is enough: words_check passed them.
static void words_join(char *out, size_t cap, size_t n, char *const *w)
{
    size_t len = 0;
    for (size_t i = 0; i < n; i++) len += (size_t)snprintf(out + len, cap - len, "%s%s", i > 0 ? " " : "", w[i]);
}

// Nothing here repeats a word: an argument might be a secret.
static bool add_credcmd(void *state, char *const *f, int line, RemoteError *e)
{
    CredCmds *c = state;
    size_t n = 0;
    while (f[n] != nullptr) n++;
    ensure(n >= 3);  // parse_lines gave at least NMIN fields
    if (!name_ok(f[0], CONF_NAME_MAX)) return fail(e, line, "not a wardrobe name (letters, digits, . _ -)");
    if (!name_ok(f[1], CRED_USER_MAX)) return fail(e, line, "not a user name (1 to %zu letters, digits, . _ -)", CRED_USER_MAX);
    const char *why = words_check(n - 2, f + 2);
    if (why != nullptr) return fail(e, line, "%s", why);
    if (credcmds_find(c, f[0]) != nullptr) return fail(e, line, "duplicate command for %.80s", f[0]);
    if (c->n == REMOTE_ENTRY_MAX) return fail(e, line, "too many commands (limit %u)", REMOTE_ENTRY_MAX);
    snprintf(c->e[c->n].name, sizeof c->e[0].name, "%s", f[0]);
    snprintf(c->e[c->n].user, sizeof c->e[0].user, "%s", f[1]);
    words_join(c->e[c->n].cmd, sizeof c->e[0].cmd, n - 2, f + 2);
    c->n++;
    return true;
}

bool credcmds_parse(CredCmds *c, const char *data, size_t len, RemoteError *e)
{
    c->n = 0;
    bool ok = parse_lines(data, len, 3, CRED_CMD_WORDS_MAX + 2, "NAME USER PROG ARG... (PROG and at most 15 arguments)",
        add_credcmd, c, e);
    c->n = ok ? c->n : 0;
    return ok;
}

bool cafiles_parse(CaFiles *c, const char *data, size_t len, RemoteError *e)
{
    c->n = 0;
    bool ok = parse_lines(data, len, 2, 2, "NAME PATH", add_cafile, c, e);
    c->n = ok ? c->n : 0;
    return ok;
}

bool remotes_parse(Remotes *r, const char *data, size_t len, RemoteError *e)
{
    r->n = 0;
    bool ok = parse_lines(data, len, 2, 2, "NAME URL", add_remote, r, e);
    r->n = ok ? r->n : 0;
    return ok;
}

bool creds_parse(Creds *c, const char *data, size_t len, RemoteError *e)
{
    c->n = 0;
    bool ok = parse_lines(data, len, 3, 3, "NAME USER SECRET", add_cred, c, e);
    if (!ok) secret_wipe(c, sizeof *c);
    c->n = ok ? c->n : 0;
    return ok;
}

RemoteEntry *remotes_find(Remotes *r, const char *name)
{
    for (uint32_t i = 0; i < r->n; i++)
        if (strcmp(r->e[i].name, name) == 0) return &r->e[i];
    return nullptr;
}

CaEntry *cafiles_find(CaFiles *c, const char *name)
{
    for (uint32_t i = 0; i < c->n; i++)
        if (strcmp(c->e[i].name, name) == 0) return &c->e[i];
    return nullptr;
}

CredEntry *creds_find(Creds *c, const char *name)
{
    for (uint32_t i = 0; i < c->n; i++)
        if (strcmp(c->e[i].name, name) == 0) return &c->e[i];
    return nullptr;
}

CredCmdEntry *credcmds_find(CredCmds *c, const char *name)
{
    for (uint32_t i = 0; i < c->n; i++)
        if (strcmp(c->e[i].name, name) == 0) return &c->e[i];
    return nullptr;
}

// ---- reading and writing ---------------------------------------------------

// Read PATH into BUF. 0, or an errno value; ENOENT is for the caller.
static int read_file(const char *path, char *buf, size_t *len)
{
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) return errno;
    *len = 0;
    ssize_t n = 1;
    while (*len <= REMOTE_FILE_MAX && n > 0) {
        n = sys_read(fd, buf + *len, REMOTE_FILE_MAX + 1 - *len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        *len += n > 0 ? (size_t)n : 0;
    }
    int err = n < 0 ? errno : 0;
    (void)sys_close(fd);
    return err;
}

static char read_buf[REMOTE_FILE_MAX + 1];

bool remotes_load(Remotes *r, const char *path, RemoteError *e)
{
    r->n = 0;
    size_t len = 0;
    int err = read_file(path, read_buf, &len);
    if (err == ENOENT) return true;
    if (err != 0) return fail(e, 0, "cannot read: %s", strerror(err));
    return remotes_parse(r, read_buf, len, e);
}

bool cafiles_load(CaFiles *c, const char *path, RemoteError *e)
{
    c->n = 0;
    size_t len = 0;
    int err = read_file(path, read_buf, &len);
    if (err == ENOENT) return true;
    if (err != 0) return fail(e, 0, "cannot read: %s", strerror(err));
    return cafiles_parse(c, read_buf, len, e);
}

typedef enum { FILE_OK, FILE_ABSENT, FILE_BAD } FileState;

// Whether PATH is a regular file that only its owner can use. FILE_BAD says why in E.
static FileState private_file(const char *path, RemoteError *e)
{
    struct stat st;
    int found = sys_stat(path, &st);
    if (found != 0 && errno == ENOENT) return FILE_ABSENT;
    if (found != 0) {
        fail(e, 0, "cannot look at it: %s", strerror(errno));
        return FILE_BAD;
    }
    if (!S_ISREG(st.st_mode)) {
        fail(e, 0, "not a regular file");
        return FILE_BAD;
    }
    if ((st.st_mode & 077) != 0) {
        fail(e, 0, "group or other can use it (mode %04o); run chmod 600 on it", (unsigned)(st.st_mode & 07777));
        return FILE_BAD;
    }
    return FILE_OK;
}

bool credcmds_load(CredCmds *c, const char *path, RemoteError *e)
{
    c->n = 0;
    FileState state = private_file(path, e);
    if (state != FILE_OK) return state == FILE_ABSENT;
    size_t len = 0;
    int err = read_file(path, read_buf, &len);
    return err == 0 ? credcmds_parse(c, read_buf, len, e) : fail(e, 0, "cannot read: %s", strerror(err));
}

bool creds_load(Creds *c, const char *path, RemoteError *e)
{
    c->n = 0;
    FileState state = private_file(path, e);
    if (state != FILE_OK) return state == FILE_ABSENT;
    size_t len = 0;
    int err = read_file(path, read_buf, &len);
    bool ok = err == 0 ? creds_parse(c, read_buf, len, e) : fail(e, 0, "cannot read: %s", strerror(err));
    secret_wipe(read_buf, sizeof read_buf);
    return ok;
}

bool syncfail_parse(const char *data, size_t len, unsigned *n)
{
    bool ok = len >= 2 && len <= 7 && data[len - 1] == '\n' && data[0] >= '1';
    unsigned v = 0;
    for (size_t i = 0; ok && i + 1 < len; i++) {
        ok = data[i] >= '0' && data[i] <= '9';
        v = v * 10 + (ok ? (unsigned)(data[i] - '0') : 0);
    }
    *n = ok ? v : 0;
    return ok;
}

bool syncfail_load(const char *path, unsigned *n, RemoteError *e)
{
    *n = 0;
    size_t len = 0;
    int err = read_file(path, read_buf, &len);
    if (err == ENOENT) return true;
    if (err != 0) return fail(e, 0, "cannot read: %s", strerror(err));
    if (!syncfail_parse(read_buf, len, n)) return fail(e, 0, "not a count of failed syncs (1 to %u and a newline)", SYNC_FAILS_MAX);
    return true;
}

int syncfail_write(const char *path, unsigned n)
{
    char text[16];
    int len = snprintf(text, sizeof text, "%u\n", n);
    ensure(n >= 1 && n <= SYNC_FAILS_MAX && len > 0);
    return sys_write_atomic(path, text, (size_t)len);
}

void login_fingerprint(const char *url, const char *user, const char *secret, char *out)
{
    static const char hex[] = "0123456789abcdef";
    br_sha256_context h;
    unsigned char sum[br_sha256_SIZE];
    br_sha256_init(&h);
    // Each part and its end, so that no two logins make the same input.
    br_sha256_update(&h, url, strlen(url) + 1);
    br_sha256_update(&h, user, strlen(user) + 1);
    br_sha256_update(&h, secret, strlen(secret) + 1);
    br_sha256_out(&h, sum);
    for (size_t i = 0; i < sizeof sum; i++) {
        out[2 * i] = hex[sum[i] >> 4];
        out[2 * i + 1] = hex[sum[i] & 15];
    }
    out[FINGERPRINT_SIZE - 1] = '\0';
    secret_wipe(&h, sizeof h);
    secret_wipe(sum, sizeof sum);
}

bool refused_parse(const char *data, size_t len, char *fingerprint)
{
    bool ok = len == FINGERPRINT_SIZE && data[len - 1] == '\n';
    for (size_t i = 0; ok && i + 1 < len; i++) ok = memchr("0123456789abcdef", data[i], 16) != nullptr;
    if (ok) memcpy(fingerprint, data, len - 1);
    fingerprint[ok ? len - 1 : 0] = '\0';
    return ok;
}

bool refused_load(const char *path, char *fingerprint, bool *have, RemoteError *e)
{
    *have = false;
    fingerprint[0] = '\0';
    size_t len = 0;
    int err = read_file(path, read_buf, &len);
    if (err == ENOENT) return true;
    if (err != 0) return fail(e, 0, "cannot read: %s", strerror(err));
    *have = refused_parse(read_buf, len, fingerprint);
    return *have ? true : fail(e, 0, "not a fingerprint (64 hex digits and a newline)");
}

int refused_write(const char *path, const char *fingerprint)
{
    char text[FINGERPRINT_SIZE + 1];
    int len = snprintf(text, sizeof text, "%s\n", fingerprint);
    ensure(len == (int)FINGERPRINT_SIZE);
    return sys_write_atomic_mode(path, text, (size_t)len, 0600);
}

void refused_path(const char *name, char *out, size_t cap)
{
    char rel[CONF_NAME_MAX + 16];
    [[maybe_unused]] int n = snprintf(rel, sizeof rel, "%s.refused", name);
    ensure(n > 0 && (size_t)n < sizeof rel);
    [[maybe_unused]] size_t home = suit_home_path(out, cap, rel);
    ensure(home != 0);
}

int refused_remove(const char *name)
{
    char path[STAMP_PATH_MAX];
    refused_path(name, path, sizeof path);
    if (sys_unlink(path) == 0 || errno == ENOENT) return 0;
    say(STDERR_FILENO, "suit: cannot remove %s: %s\n", path, strerror(errno));
    return 1;
}

static int cmp_name(const void *a, const void *b)
{
    return strcmp(a, b);
}

// Entries sorted by name: indexes into the array of STRIDE-byte records.
static void sort_entries(void *base, size_t n, size_t stride)
{
    qsort(base, n, stride, cmp_name);
}

int remotes_write(const Remotes *r, const char *path)
{
    static Remotes sorted;
    sorted = *r;
    sort_entries(sorted.e, sorted.n, sizeof sorted.e[0]);
    size_t len = 0;
    for (uint32_t i = 0; i < sorted.n; i++) {
        int n = snprintf(out_buf + len, sizeof out_buf - len, "%s %s\n", sorted.e[i].name, sorted.e[i].url);
        if ((size_t)n >= sizeof out_buf - len) return EFBIG;
        len += (size_t)n;
    }
    return sys_write_atomic(path, out_buf, len);
}

int cafiles_write(const CaFiles *c, const char *path)
{
    static CaFiles sorted;
    sorted = *c;
    sort_entries(sorted.e, sorted.n, sizeof sorted.e[0]);
    size_t len = 0;
    for (uint32_t i = 0; i < sorted.n; i++) {
        int n = snprintf(out_buf + len, sizeof out_buf - len, "%s %s\n", sorted.e[i].name, sorted.e[i].path);
        if ((size_t)n >= sizeof out_buf - len) return EFBIG;
        len += (size_t)n;
    }
    return sys_write_atomic(path, out_buf, len);
}

int credcmds_write(const CredCmds *c, const char *path)
{
    static CredCmds sorted;
    sorted = *c;
    sort_entries(sorted.e, sorted.n, sizeof sorted.e[0]);
    size_t len = 0;
    for (uint32_t i = 0; i < sorted.n; i++) {
        int n = snprintf(out_buf + len, sizeof out_buf - len, "%s %s %s\n", sorted.e[i].name,
            sorted.e[i].user, sorted.e[i].cmd);
        if ((size_t)n >= sizeof out_buf - len) return EFBIG;
        len += (size_t)n;
    }
    return sys_write_atomic_mode(path, out_buf, len, 0600);
}

int creds_write(const Creds *c, const char *path)
{
    static Creds sorted;
    sorted = *c;
    sort_entries(sorted.e, sorted.n, sizeof sorted.e[0]);
    size_t len = 0;
    int err = 0;
    for (uint32_t i = 0; i < sorted.n && err == 0; i++) {
        int n = snprintf(out_buf + len, sizeof out_buf - len, "%s %s %s\n", sorted.e[i].name,
            sorted.e[i].user, sorted.e[i].secret);
        err = (size_t)n >= sizeof out_buf - len ? EFBIG : 0;
        len += err == 0 ? (size_t)n : 0;
    }
    err = err != 0 ? err : sys_write_atomic_mode(path, out_buf, len, 0600);
    secret_wipe(out_buf, sizeof out_buf);
    secret_wipe(&sorted, sizeof sorted);
    return err;
}

// ---- credential commands ---------------------------------------------------

static unsigned cred_seconds(void)
{
#ifdef SUIT_TEST
    const char *forced = getenv("SUIT_CRED_TIMEOUT");
    if (forced != nullptr) return (unsigned)atoi(forced);
#endif
    return CRED_CMD_SECONDS;
}

__attribute__((format(printf, 4, 5)))
static bool cred_fail(const char *verb, const char *name, const char *prog, const char *fmt, ...)
{
    char why[200];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(why, sizeof why, fmt, ap);
    va_end(ap);
    say(STDERR_FILENO, "suit: %s %s: credential command %.200s: %s\n", verb, name, prog, why);
    return false;
}

// Milliseconds until DEADLINE (nanoseconds on the monotonic clock): 0 when it has passed, or
// when the clock cannot be read, which is the safe way to be wrong.
static int left_ms(uint64_t deadline)
{
    uint64_t now;
    if (!sys_now_ns(&now) || now >= deadline) return 0;
    return (int)((deadline - now) / 1000000u + 1);
}

// In the child: its own process group, standard input from /dev/null, standard output the pipe,
// then the program. 127 is what a shell says of a program it cannot run.
[[noreturn]] static void cred_child(int null, const int fds[2], char *const argv[])
{
    [[maybe_unused]] int group = sys_setpgid(0, 0);
    [[maybe_unused]] int in = sys_dup2(null, STDIN_FILENO);
    [[maybe_unused]] int out = sys_dup2(fds[1], STDOUT_FILENO);
    ensure(group == 0 && in >= 0 && out >= 0);
    (void)sys_close(null);
    (void)sys_close(fds[0]);
    (void)sys_close(fds[1]);
    (void)sys_execv(argv[0], argv);
    sys_child_exit(127);
}

// Start ARGV with its output on a pipe: the child in PID and the read end in RFD. 0, or an
// errno value and WHAT it was doing. A fork without exec before the program: suit is single-threaded.
// The parent puts the child in its group too, so the group is there to be signalled whatever
// the child has got to (after the exec the call fails, and the child has done it).
static int cred_start(char *const argv[], pid_t *pid, int *rfd, const char **what)
{
    int null = sys_open("/dev/null", O_RDONLY, 0);
    if (null < 0) {
        *what = "open /dev/null";
        return errno;
    }
    int fds[2];
    if (sys_pipe(fds) != 0) {
        int err = errno;
        (void)sys_close(null);
        *what = "pipe";
        return err;
    }
    *pid = sys_fork();
    if (*pid < 0) {
        int err = errno;
        (void)sys_close(null);
        (void)sys_close(fds[0]);
        (void)sys_close(fds[1]);
        *what = "fork";
        return err;
    }
    if (*pid == 0) cred_child(null, fds, argv);
    (void)sys_setpgid(*pid, *pid);
    (void)sys_close(null);
    (void)sys_close(fds[1]);
    *rfd = fds[0];
    return 0;
}

typedef enum { OUT_END, OUT_FULL, OUT_LATE, OUT_ERROR, OUT_WAIT_ERROR } Output;

// How long, in milliseconds, to wait for output before looking again whether the command has ended.
constexpr int CRED_LOOK_MS = 10;

// What the command writes to FD, into BUF (CAP bytes, LEN of them used). It returns when the command
// PID has ended and nothing more is waiting to be read, so a child that the command left running
// with the pipe open does not hold it back. Also when BUF is full or DEADLINE comes before the
// command ends. The command is not reaped: its number stays its own until the caller does.
static Output cred_collect(int fd, pid_t pid, uint64_t deadline, char *buf, size_t cap, size_t *len)
{
    bool ended = false;
    bool eof = false;
    *len = 0;
    for (;;) {
        if (!ended) {
            int w = sys_wait_ended(pid);
            if (w < 0) return OUT_WAIT_ERROR;
            ended = w == 1;
        }
        if (eof && ended) return OUT_END;
        if (!ended && left_ms(deadline) == 0) return OUT_LATE;
        if (eof) {
            platform_pause_ms(5);
            continue;
        }
        int r = sys_poll(fd, POLLIN, ended ? 0 : CRED_LOOK_MS);
        if (r < 0 && errno != EINTR) return OUT_ERROR;
        if (r < 0) continue;
        if (r == 0) {
            if (ended) return OUT_END;
            continue;
        }
        ssize_t n = sys_read(fd, buf + *len, cap - *len);
        if (n < 0 && errno == EINTR) continue;
        if (n < 0) return OUT_ERROR;
        eof = n == 0;
        *len += (size_t)n;
        if (*len == cap) return OUT_FULL;
    }
}

// What the command printed, in OUT (LEN bytes), into SECRET. False after saying why not.
static bool cred_secret(const char *verb, const char *name, const char *prog, const char *out, size_t len, char *secret)
{
    size_t n = len > 0 && out[len - 1] == '\n' ? len - 1 : len;
    if (n == 0) return cred_fail(verb, name, prog, "printed nothing");
    if (!secret_ok(out, n))
        return cred_fail(verb, name, prog, "printed something that is not a secret: 1 to %zu printable characters, no space", CRED_SECRET_MAX);
    memcpy(secret, out, n);
    secret[n] = '\0';
    return true;
}

// Why the command's end (STATUS) was not a success, or true.
static bool cred_ended(const char *verb, const char *name, const char *prog, int status)
{
    if (WIFSIGNALED(status)) return cred_fail(verb, name, prog, "was ended by signal %d", WTERMSIG(status));
    int code = WEXITSTATUS(status);
    if (code == 0) return true;
    return cred_fail(verb, name, prog, "exited with status %d%s", code,
        code == 127 ? " (it may not be there, or may not be executable)" : "");
}

bool credential_run(const char *verb, const char *name, const char *cmd, char *secret)
{
    char text[CRED_CMD_MAX + 1];
    char *argv[CRED_CMD_WORDS_MAX + 1];
    size_t argc = 0;
    snprintf(text, sizeof text, "%s", cmd);
    for (char *w = text; w != nullptr;) {
        ensure(argc < CRED_CMD_WORDS_MAX);  // the file was parsed, and a login was checked
        argv[argc++] = w;
        w = strchr(w, ' ');
        if (w != nullptr) *w++ = '\0';
    }
    argv[argc] = nullptr;
    const char *prog = argv[0];
    secret[0] = '\0';
    uint64_t start;
    if (!sys_now_ns(&start)) return cred_fail(verb, name, prog, "cannot read the clock: %s", strerror(errno));
    uint64_t deadline = start + (uint64_t)cred_seconds() * 1000000000u;
    pid_t pid = -1;
    int rfd = -1;
    const char *what;
    int err = cred_start(argv, &pid, &rfd, &what);
    if (err != 0) return cred_fail(verb, name, prog, "cannot start it: %s: %s", what, strerror(err));
    // Two bytes more than a secret: its newline, and one to tell a secret too long from one that fits.
    char out[CRED_SECRET_MAX + 2];
    size_t len;
    Output o = cred_collect(rfd, pid, deadline, out, sizeof out, &len);
    int err_no = errno;
    (void)sys_close(rfd);
    // Whatever the command left running goes with it, and a command still running is stopped. It is
    // signalled before it is reaped: until then its number is its group's, and no one else's. A
    // command that has ended keeps its status, which the signal does not change.
    (void)sys_signal(-pid, SIGKILL);
    int status = 0;
    pid_t reaped = sys_wait4(pid, &status, nullptr);
    int reap_err = errno;
    bool ok = false;
    if (o == OUT_ERROR) cred_fail(verb, name, prog, "cannot read its output: %s", strerror(err_no));
    else if (o == OUT_WAIT_ERROR) cred_fail(verb, name, prog, "cannot wait for it: %s", strerror(err_no));
    else if (o == OUT_FULL) cred_fail(verb, name, prog, "printed more than %zu characters", CRED_SECRET_MAX);
    else if (o == OUT_LATE) cred_fail(verb, name, prog, "did not end in %u seconds and was stopped", cred_seconds());
    else if (reaped != pid) cred_fail(verb, name, prog, "cannot wait for it: %s", strerror(reap_err));
    else ok = cred_ended(verb, name, prog, status) && cred_secret(verb, name, prog, out, len, secret);
    secret_wipe(out, sizeof out);
    return ok;
}

// ---- the commands ----------------------------------------------------------

int remote_paths(char *remotes_path, char *creds_path, size_t cap)
{
    if (suit_home_path(remotes_path, cap, "remotes") == 0) return 1;
    // The same folder, so a longer name fits if that did.
    [[maybe_unused]] size_t home = suit_home_path(creds_path, cap, "credentials");
    ensure(home != 0);
    return 0;
}

static bool check_name(const char *name)
{
    if (name_ok(name, CONF_NAME_MAX)) return true;
    say(STDERR_FILENO, "suit: '%.40s' is not a wardrobe name (letters, digits, . _ -)\n", name);
    return false;
}

static void remove_remote(Remotes *r, const char *name)
{
    for (uint32_t i = 0; i < r->n; i++) {
        if (strcmp(r->e[i].name, name) == 0) {
            r->e[i] = r->e[--r->n];
            return;
        }
    }
}

// Nullptr if CA may be the CA file of the remote URL, else why not.
static const char *ca_check(const char *url, const char *ca, char *why, size_t cap)
{
    char path[STAMP_PATH_MAX];
    if (strncmp(url, "https://", 8) != 0) return "--ca is for an https:// address";
    const char *bad = anchors_path_check(ca);
    if (bad != nullptr) return bad;
    if (!anchors_load(&check_anchors, ca, path, sizeof path, why, cap)) return why;
    return nullptr;
}

// Record CA as NAME's CA file, or forget NAME's when CA is null.
static int apply_ca(const char *name, const char *ca)
{
    char path[STAMP_PATH_MAX];
    // The same folder as the remotes file, which was found.
    [[maybe_unused]] size_t home = suit_home_path(path, sizeof path, "cafiles");
    ensure(home != 0);
    RemoteError e;
    if (!cafiles_load(&cafiles, path, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", path, e.line, e.msg);
        return 1;
    }
    CaEntry *old = cafiles_find(&cafiles, name);
    if (old == nullptr && ca == nullptr) return 0;
    if (old != nullptr) *old = cafiles.e[--cafiles.n];
    if (ca != nullptr && cafiles.n == REMOTE_ENTRY_MAX) {
        say(STDERR_FILENO, "suit: cafiles: too many CA files (limit %u)\n", REMOTE_ENTRY_MAX);
        return 1;
    }
    if (ca != nullptr) {
        snprintf(cafiles.e[cafiles.n].name, sizeof cafiles.e[0].name, "%s", name);
        snprintf(cafiles.e[cafiles.n].path, sizeof cafiles.e[0].path, "%s", ca);
        cafiles.n++;
    }
    int err = cafiles_write(&cafiles, path);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
    return err == 0 ? 0 : 1;
}

int remote_ca(const char *name, char *out, size_t cap)
{
    char path[STAMP_PATH_MAX];
    out[0] = '\0';
    // The same folder as the remotes file, which was found.
    [[maybe_unused]] size_t home = suit_home_path(path, sizeof path, "cafiles");
    ensure(home != 0);
    RemoteError e;
    if (!cafiles_load(&cafiles, path, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", path, e.line, e.msg);
        return 1;
    }
    const CaEntry *c = cafiles_find(&cafiles, name);
    if (c != nullptr) snprintf(out, cap, "%s", c->path);
    return 0;
}

static int apply_remote(Remotes *r, const char *name, const char *url, const char *ca, const char *path)
{
    char detail[300];
    bool none = strcmp(url, "--none") == 0;
    const char *why = none ? nullptr : remote_url_check(url, strlen(url));
    why = why != nullptr || ca == nullptr ? why : ca_check(url, ca, detail, sizeof detail);
    if (why != nullptr) {
        say(STDERR_FILENO, "suit: remote %s: %s\n", name, why);
        return 2;
    }
    remove_remote(r, name);
    if (!none && r->n == REMOTE_ENTRY_MAX) {
        say(STDERR_FILENO, "suit: remotes: too many remotes (limit %u)\n", REMOTE_ENTRY_MAX);
        return 1;
    }
    if (!none) {
        snprintf(r->e[r->n].name, sizeof r->e[0].name, "%s", name);
        snprintf(r->e[r->n].url, sizeof r->e[0].url, "%s", url);
        r->n++;
    }
    // A new address has not refused the login yet. The record goes before the files change: if it
    // cannot, the remote stays as it was.
    if (refused_remove(name) != 0 || apply_ca(name, ca) != 0) return 1;
    int err = remotes_write(r, path);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
    return err == 0 ? 0 : 1;
}

int cmd_remote(const char *name, const char *url, const char *ca)
{
    char path[STAMP_PATH_MAX];
    char cpath[STAMP_PATH_MAX];
    if (!check_name(name)) return 2;
    if (remote_paths(path, cpath, sizeof path) != 0) return 1;
    RemoteError e;
    if (!remotes_load(&remotes, path, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", path, e.line, e.msg);
        return 1;
    }
    if (url != nullptr) {
        return apply_remote(&remotes, name, url, ca, path);
    }
    const RemoteEntry *r = remotes_find(&remotes, name);
    if (r == nullptr) {
        say(STDERR_FILENO, "suit: no remote is set for %s\n", name);
        return 1;
    }
    char ca_path[REMOTE_URL_MAX + 1];
    if (remote_ca(name, ca_path, sizeof ca_path) != 0) return 1;
    say(STDOUT_FILENO, "%s\n", r->url);
    if (ca_path[0] != '\0') say(STDOUT_FILENO, "ca %s\n", ca_path);
    return 0;
}

// One line from standard input into BUF (CAP bytes): its length without the
// newline, or SIZE_MAX if it did not fit or could not be read.
static size_t read_secret_line(char *buf, size_t cap)
{
    size_t len = 0;
    ssize_t n = 1;
    while (len < cap && n > 0 && memchr(buf, '\n', len) == nullptr) {
        n = sys_read(STDIN_FILENO, buf + len, cap - len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        len += n > 0 ? (size_t)n : 0;
    }
    const char *nl = memchr(buf, '\n', len);
    size_t line = nl != nullptr ? (size_t)(nl - buf) : len;
    return n < 0 || (nl == nullptr && len == cap) ? SIZE_MAX : line;
}

static int login_with(const char *name, const char *user, const char *path, RemoteError *e)
{
    static char line[CRED_SECRET_MAX + 3];
    if (!no_core_dumps()) return 1;
    size_t len = read_secret_line(line, sizeof line);
    int result = 1;
    if (len == SIZE_MAX) {
        say(STDERR_FILENO, "suit: login %s: cannot read the secret: one line of 1 to %zu characters on standard input\n",
            name, CRED_SECRET_MAX);
    } else if (!secret_ok(line, len)) {
        say(STDERR_FILENO, "suit: login %s: the secret is 1 to %zu printable characters, no space\n",
            name, CRED_SECRET_MAX);
        result = 2;
    } else if (!creds_load(&creds, path, e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", path, e->line, e->msg);
    } else if (creds_find(&creds, name) == nullptr && creds.n == REMOTE_ENTRY_MAX) {
        say(STDERR_FILENO, "suit: credentials: too many logins (limit %u)\n", REMOTE_ENTRY_MAX);
    } else {
        CredEntry *c = creds_find(&creds, name);
        c = c != nullptr ? c : &creds.e[creds.n++];
        snprintf(c->name, sizeof c->name, "%s", name);
        snprintf(c->user, sizeof c->user, "%s", user);
        memcpy(c->secret, line, len);
        c->secret[len] = '\0';
        int err = creds_write(&creds, path);
        if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
        result = err == 0 ? 0 : 1;
    }
    secret_wipe(line, sizeof line);
    secret_wipe(&creds, sizeof creds);
    return result;
}

// Take NAME's secret out of the credentials file at PATH. 0, or 1 after saying why not.
static int drop_secret(const char *name, const char *path)
{
    RemoteError e;
    int result = 0;
    if (!creds_load(&creds, path, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", path, e.line, e.msg);
        result = 1;
    } else if (creds_find(&creds, name) != nullptr) {
        CredEntry *gone = creds_find(&creds, name);
        *gone = creds.e[--creds.n];
        int err = creds_write(&creds, path);
        if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
        result = err == 0 ? 0 : 1;
    }
    secret_wipe(&creds, sizeof creds);
    return result;
}

// Take NAME's command out of the file at PATH. 0, or 1 after saying why not.
static int drop_command(const char *name, const char *path)
{
    RemoteError e;
    if (!credcmds_load(&cmds, path, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", path, e.line, e.msg);
        return 1;
    }
    CredCmdEntry *gone = credcmds_find(&cmds, name);
    if (gone == nullptr) return 0;
    *gone = cmds.e[--cmds.n];
    int err = credcmds_write(&cmds, path);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
    return err == 0 ? 0 : 1;
}

// The path of the credential-commands file; the home was found already.
static void commands_path(char *out, size_t cap)
{
    [[maybe_unused]] size_t home = suit_home_path(out, cap, "credential-commands");
    ensure(home != 0);
}

int cmd_login(const char *name, const char *user)
{
    char path[STAMP_PATH_MAX];
    char rpath[STAMP_PATH_MAX];
    char mpath[STAMP_PATH_MAX];
    if (!check_name(name)) return 2;
    if (!name_ok(user, CRED_USER_MAX)) {
        say(STDERR_FILENO, "suit: login %s: not a user name (1 to %zu letters, digits, . _ -)\n", name, CRED_USER_MAX);
        return 2;
    }
    if (remote_paths(rpath, path, sizeof path) != 0) return 1;
    commands_path(mpath, sizeof mpath);
    RemoteError e;
    int rc = login_with(name, user, path, &e);
    return rc != 0 ? rc : drop_command(name, mpath) | refused_remove(name);
}

int cmd_login_command(const char *name, const char *user, int argc, char *const *argv)
{
    char path[STAMP_PATH_MAX];
    char rpath[STAMP_PATH_MAX];
    char mpath[STAMP_PATH_MAX];
    if (!check_name(name)) return 2;
    if (!name_ok(user, CRED_USER_MAX)) {
        say(STDERR_FILENO, "suit: login %s: not a user name (1 to %zu letters, digits, . _ -)\n", name, CRED_USER_MAX);
        return 2;
    }
    const char *why = words_check((size_t)argc, argv);
    if (why != nullptr) {
        say(STDERR_FILENO, "suit: login %s: %s\n", name, why);
        return 2;
    }
    if (remote_paths(rpath, path, sizeof path) != 0) return 1;
    commands_path(mpath, sizeof mpath);
    // The secret it replaces is read to be taken out.
    if (!no_core_dumps()) return 1;
    RemoteError e;
    if (!credcmds_load(&cmds, mpath, &e)) {
        say(STDERR_FILENO, "suit: %s:%d: %s\n", mpath, e.line, e.msg);
        return 1;
    }
    CredCmdEntry *c = credcmds_find(&cmds, name);
    if (c == nullptr && cmds.n == REMOTE_ENTRY_MAX) {
        say(STDERR_FILENO, "suit: credential-commands: too many commands (limit %u)\n", REMOTE_ENTRY_MAX);
        return 1;
    }
    c = c != nullptr ? c : &cmds.e[cmds.n++];
    snprintf(c->name, sizeof c->name, "%s", name);
    snprintf(c->user, sizeof c->user, "%s", user);
    words_join(c->cmd, sizeof c->cmd, (size_t)argc, argv);
    int err = credcmds_write(&cmds, mpath);
    if (err != 0) {
        say(STDERR_FILENO, "suit: cannot write %s: %s\n", mpath, strerror(err));
        return 1;
    }
    return drop_secret(name, path) | refused_remove(name);
}

int cmd_logout(const char *name)
{
    char path[STAMP_PATH_MAX];
    char rpath[STAMP_PATH_MAX];
    char mpath[STAMP_PATH_MAX];
    if (!check_name(name)) return 2;
    if (remote_paths(rpath, path, sizeof path) != 0) return 1;
    commands_path(mpath, sizeof mpath);
    if (!no_core_dumps()) return 1;
    return drop_secret(name, path) | drop_command(name, mpath) | refused_remove(name);
}