Skip to content
suit Artifact [9a93da8cc8]
Login

Artifact [9a93da8cc8]

Artifact 9a93da8cc8602e7b3b2b7d3e6ab18bfb27ca8cfc7a1cc7b9f1af737d22794187:


#include "conf.h"

#include "platform.h"

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

constexpr int HEADER_WORDS_MAX = 4;

static const char *const kind_names[KIND_COUNT] = {
    "harness", "outfit", "wear", "need", "upstream",
};

static const uint32_t kind_limits[KIND_COUNT] = {
    CONF_HARNESS_MAX, CONF_OUTFIT_MAX, CONF_WEAR_MAX, CONF_NEED_MAX,
    CONF_UPSTREAM_MAX,
};

static_assert(CONF_SECTION_MAX == 64 + 512 + 256 + 256 + 128);

__attribute__((format(printf, 3, 4)))
static bool fail(ConfError *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;
}

// ---- text helpers ---------------------------------------------------------

static bool is_space(char c)
{
    return c == ' ' || c == '\t' || c == '\r';
}

static bool is_alnum(char c)
{
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
        (c >= '0' && c <= '9');
}

// Trim both ends in place; returns the new start.
static char *trim(char *s)
{
    while (is_space(*s)) s++;
    char *end = s + strlen(s);
    while (end > s && is_space(end[-1])) end--;
    *end = '\0';
    return s;
}

// '#' starts a comment at the start of the line or after whitespace.
static void strip_comment(char *s)
{
    for (size_t i = 0; s[i] != '\0'; i++) {
        if (s[i] == '#' && (i == 0 || is_space(s[i - 1]))) {
            s[i] = '\0';
            return;
        }
    }
}

// Replace each run of whitespace with one space. S must already be trimmed.
static void collapse_spaces(char *s)
{
    char *out = s;
    for (const char *in = s; *in != '\0'; in++) {
        if (is_space(*in)) {
            while (is_space(in[1])) in++;
            *out++ = ' ';
        } else {
            *out++ = *in;
        }
    }
    *out = '\0';
}

// True if every one of the LEN bytes is a letter, a digit or in EXTRA.
static bool all_in(const char *s, size_t len, const char *extra)
{
    for (size_t i = 0; i < len; i++)
        if (!is_alnum(s[i]) && strchr(extra, s[i]) == nullptr) return false;
    return true;
}

static bool name_ok(const char *s, size_t len, bool glob)
{
    return len > 0 && len <= CONF_NAME_MAX && all_in(s, len, glob ? "._-*" : "._-");
}

bool conf_list_next(const char **cursor, const char **word, size_t *len)
{
    const char *s = *cursor;
    if (*s == '\0') return false;
    const char *space = strchr(s, ' ');
    size_t n = space != nullptr ? (size_t)(space - s) : strlen(s);
    *word = s;
    *len = n;
    *cursor = space != nullptr ? space + 1 : s + n;
    return true;
}

// ---- keys and values ------------------------------------------------------

typedef enum {
    VT_PATH,   // anything non-empty
    VT_WORD,   // one word
    VT_NAME,   // one name
    VT_NAMES,  // list of names
    VT_GLOBS,  // list of names, '*' allowed
    VT_YESNO,
    VT_TRUST,
    VT_FREE,
} VType;

typedef struct {
    Kind kind;
    const char *name;
    VType vt;
    bool repeat;
    bool param;  // the key is "NAME PARAM"
} KeySpec;

static const KeySpec specs[] = {
    {KIND_HARNESS, "record", VT_PATH, true, false},
    {KIND_HARNESS, "event", VT_WORD, false, true},
    {KIND_OUTFIT, "include", VT_NAMES, false, false},
    {KIND_OUTFIT, "skills", VT_GLOBS, false, false},
    {KIND_OUTFIT, "agents", VT_GLOBS, false, false},
    {KIND_OUTFIT, "commands", VT_GLOBS, false, false},
    {KIND_OUTFIT, "instructions", VT_PATH, false, false},
    {KIND_OUTFIT, "only", VT_NAME, false, false},
    {KIND_OUTFIT, "slot", VT_PATH, false, true},
    {KIND_OUTFIT, "file", VT_PATH, false, true},
    {KIND_WEAR, "outfits", VT_NAMES, false, false},
    {KIND_WEAR, "publish", VT_YESNO, false, false},
    {KIND_NEED, "prompt", VT_PATH, false, false},
    {KIND_NEED, "done", VT_FREE, false, false},
    {KIND_UPSTREAM, "url", VT_WORD, false, false},
    {KIND_UPSTREAM, "pin", VT_WORD, false, false},
    {KIND_UPSTREAM, "path", VT_PATH, false, false},
    {KIND_UPSTREAM, "trust", VT_TRUST, false, false},
};

// Harness path keys "KIND.SCOPE": every scope for each of four kinds.
static const char *const harness_kinds[] = {
    "skills", "agents", "commands", "instructions",
};

typedef struct {
    const char *name;
    bool needs_target;
    bool allows_machine;
} Scope;

static const Scope scopes[] = {
    {"enterprise", false, false},
    {"user", false, true},
    {"shared", true, false},
    {"personal", true, true},
};

#define COUNT(a) (sizeof(a) / sizeof((a)[0]))

static const Scope *find_scope(const char *name, size_t len)
{
    for (size_t i = 0; i < COUNT(scopes); i++)
        if (strlen(scopes[i].name) == len && memcmp(scopes[i].name, name, len) == 0)
            return &scopes[i];
    return nullptr;
}

static bool harness_path_key(const char *key)
{
    const char *dot = strchr(key, '.');
    if (dot == nullptr) return false;
    bool kind_ok = false;
    for (size_t i = 0; i < COUNT(harness_kinds); i++)
        kind_ok |= strlen(harness_kinds[i]) == (size_t)(dot - key) &&
            memcmp(harness_kinds[i], key, (size_t)(dot - key)) == 0;
    return kind_ok && find_scope(dot + 1, strlen(dot + 1)) != nullptr;
}

static const KeySpec path_spec = {KIND_HARNESS, "KIND.SCOPE", VT_PATH, false, false};

static const KeySpec *find_spec(Kind kind, const char *key)
{
    if (kind == KIND_HARNESS && harness_path_key(key)) return &path_spec;
    for (size_t i = 0; i < COUNT(specs); i++) {
        const KeySpec *sp = &specs[i];
        size_t n = strlen(sp->name);
        bool match = sp->param ? strncmp(key, sp->name, n) == 0 && key[n] == ' '
                               : strcmp(key, sp->name) == 0;
        if (sp->kind == kind && match) return sp;
    }
    return nullptr;
}

// The PARAM of "event PARAM", "slot PARAM" and "file PARAM": one word.
static bool param_ok(const KeySpec *sp, const char *key)
{
    const char *p = key + strlen(sp->name) + 1;
    if (strchr(p, ' ') != nullptr) return false;
    return strcmp(sp->name, "file") == 0 || all_in(p, strlen(p), "._-/");
}

static bool list_ok(char *val, bool glob, const char **bad, size_t *bad_len)
{
    collapse_spaces(val);
    const char *cur = val;
    const char *w;
    size_t n;
    while (conf_list_next(&cur, &w, &n)) {
        if (!name_ok(w, n, glob)) {
            *bad = w;
            *bad_len = n > 40 ? 40 : n;
            return false;
        }
    }
    return true;
}

static bool check_value(ConfError *e, int line, const KeySpec *sp, const char *key,
    char *val)
{
    if (val[0] == '\0') return fail(e, line, "empty value for '%s'", key);
    const char *bad = nullptr;
    size_t bad_len = 0;
    if (sp->vt == VT_PATH || sp->vt == VT_FREE) return true;
    if (sp->vt == VT_WORD) {
        if (strchr(val, ' ') != nullptr)
            return fail(e, line, "'%s' takes one word, not '%.40s'", key, val);
        return true;
    }
    if (sp->vt == VT_NAME) {
        if (!name_ok(val, strlen(val), false))
            return fail(e, line, "'%s' takes one name, not '%.40s'", key, val);
        return true;
    }
    if (sp->vt == VT_NAMES || sp->vt == VT_GLOBS) {
        if (!list_ok(val, sp->vt == VT_GLOBS, &bad, &bad_len))
            return fail(e, line, "'%s' has an invalid name '%.*s'", key, (int)bad_len, bad);
        return true;
    }
    if (sp->vt == VT_YESNO) {
        if (strcmp(val, "yes") != 0 && strcmp(val, "no") != 0)
            return fail(e, line, "'%s' must be yes or no, not '%.40s'", key, val);
        return true;
    }
    ensure(sp->vt == VT_TRUST);
    if (strcmp(val, "review") != 0 && strcmp(val, "auto") != 0)
        return fail(e, line, "'%s' must be review or auto, not '%.40s'", key, val);
    return true;
}

// ---- section headers ------------------------------------------------------

static bool section_same(const Section *a, const Section *b)
{
    int r = a->kind != b->kind;
    for (int i = 0; i < 3; i++) r |= strcmp(a->arg[i], b->arg[i]) != 0;
    return r == 0;
}

static bool header_wear(ConfError *e, int line, char **w, int nw, Section *s)
{
    // w[0] is "wear".
    if (nw < 2) return fail(e, line, "wear needs a SCOPE");
    const Scope *scope = find_scope(w[1], strlen(w[1]));
    if (scope == nullptr)
        return fail(e, line, "unknown scope '%.40s' (enterprise, user, shared or personal)", w[1]);
    const char *machine = "";
    const char *target = "";
    int last = nw - 1;
    if (last >= 2 && strncmp(w[last], "machine=", 8) == 0) {
        machine = w[last] + 8;
        last--;
        if (!name_ok(machine, strlen(machine), false))
            return fail(e, line, "invalid machine name '%.40s'", machine);
    }
    if (last > 2) return fail(e, line, "too many arguments for wear");
    if (last == 2) target = w[2];

    if (scope->needs_target && target[0] == '\0')
        return fail(e, line, "wear %s needs a TARGET (a project's remote address)", scope->name);
    if (!scope->needs_target && target[0] != '\0')
        return fail(e, line, "wear %s takes no TARGET", scope->name);
    if (target[0] != '\0' && !all_in(target, strlen(target), "._-/:@~"))
        return fail(e, line, "invalid target '%.60s'", target);
    if (machine[0] != '\0' && !scope->allows_machine)
        return fail(e, line, "machine= is allowed only on user and personal, not %s",
            scope->name);
    s->arg[0] = scope->name;
    s->arg[1] = target;
    s->arg[2] = machine;
    return true;
}

static bool header_args(ConfError *e, int line, Kind kind, char **w, int nw, Section *s)
{
    s->arg[0] = s->arg[1] = s->arg[2] = "";
    if (kind == KIND_WEAR) return header_wear(e, line, w, nw, s);
    if (kind == KIND_NEED) {
        if (nw != 3) return fail(e, line, "need takes a HARNESS and a NAME");
        if (!name_ok(w[1], strlen(w[1]), false) || !name_ok(w[2], strlen(w[2]), false))
            return fail(e, line, "invalid need '%.40s %.40s'", w[1], w[2]);
        s->arg[0] = w[1];
        s->arg[1] = w[2];
        return true;
    }
    if (nw != 2) return fail(e, line, "%s takes exactly one NAME", kind_names[kind]);
    if (!name_ok(w[1], strlen(w[1]), false))
        return fail(e, line, "invalid %s name '%.40s'", kind_names[kind], w[1]);
    s->arg[0] = w[1];
    return true;
}

static bool parse_header(Conf *c, ConfError *e, int line, char *s)
{
    size_t n = strlen(s);
    ensure(n > 0 && s[0] == '[');
    if (s[n - 1] != ']')
        return fail(e, line, "malformed section header: no closing ']'");
    s[n - 1] = '\0';
    s++;

    char *w[HEADER_WORDS_MAX];
    int nw = 0;
    while (true) {
        while (is_space(*s)) s++;
        if (*s == '\0') break;
        if (nw == HEADER_WORDS_MAX)
            return fail(e, line, "malformed section header: too many words");
        w[nw++] = s;
        while (*s != '\0' && !is_space(*s)) s++;
        if (*s != '\0') *s++ = '\0';
    }
    if (nw == 0) return fail(e, line, "malformed section header: empty");

    Kind kind = KIND_COUNT;
    for (int k = 0; k < KIND_COUNT; k++)
        if (strcmp(w[0], kind_names[k]) == 0) kind = (Kind)k;
    if (kind == KIND_COUNT) return fail(e, line, "unknown section kind '%.40s'", w[0]);

    // The per-kind limits add up to the section limit.
    ensure(c->nsections < CONF_SECTION_MAX);
    Section *sec = &c->sections[c->nsections];
    sec->kind = kind;
    sec->line = line;
    sec->first = c->nentries;
    sec->count = 0;
    if (!header_args(e, line, kind, w, nw, sec)) return false;

    for (uint32_t i = 0; i < c->nsections; i++)
        if (section_same(&c->sections[i], sec))
            return fail(e, line, "duplicate section (first at line %d)", c->sections[i].line);
    if (c->kind_count[kind] == kind_limits[kind])
        return fail(e, line, "too many %s sections (limit %u)", kind_names[kind],
            kind_limits[kind]);
    c->kind_count[kind]++;
    c->nsections++;
    return true;
}

// ---- entries --------------------------------------------------------------

static bool parse_entry(Conf *c, ConfError *e, int line, char *s)
{
    if (c->nsections == 0) return fail(e, line, "entry before any section header");
    Section *sec = &c->sections[c->nsections - 1];

    char *sep = strstr(s, " = ");
    char *val;
    if (sep != nullptr) {
        *sep = '\0';
        val = trim(sep + 3);
    } else {
        size_t n = strlen(s);
        if (n < 2 || strcmp(s + n - 2, " =") != 0)
            return fail(e, line, "expected KEY = VALUE");
        s[n - 2] = '\0';
        val = s + n;  // empty
    }
    char *key = trim(s);
    collapse_spaces(key);
    // S starts with a non-space, so the key cannot be empty.
    ensure(key[0] != '\0');

    const KeySpec *sp = find_spec(sec->kind, key);
    if (sp == nullptr)
        return fail(e, line, "unknown key '%.60s' in %s section", key, kind_names[sec->kind]);
    if (sp->param && !param_ok(sp, key)) return fail(e, line, "invalid key '%.60s'", key);
    if (!check_value(e, line, sp, key, val)) return false;
    // Only wear sections have a publish key.
    if (strcmp(key, "publish") == 0 && strcmp(sec->arg[0], "shared") != 0)
        return fail(e, line, "publish is allowed only on wear shared");

    if (!sp->repeat) {
        for (uint32_t i = 0; i < sec->count; i++) {
            const Entry *prev = &c->entries[sec->first + i];
            if (strcmp(prev->key, key) == 0)
                return fail(e, line, "duplicate key '%.60s' (first at line %d)", key,
                    prev->line);
        }
    }
    if (c->nentries == CONF_ENTRY_MAX)
        return fail(e, line, "too many entries (limit %u)", CONF_ENTRY_MAX);
    c->entries[c->nentries++] = (Entry){.key = key, .val = val, .line = line};
    sec->count++;
    return true;
}

// ---- references and cycles ------------------------------------------------

static int find_section(const Conf *c, Kind kind, const char *name, size_t len)
{
    for (uint32_t i = 0; i < c->nsections; i++) {
        const Section *s = &c->sections[i];
        if (s->kind == kind && strncmp(s->arg[0], name, len) == 0 && s->arg[0][len] == '\0')
            return (int)i;
    }
    return -1;
}

static const Entry *find_entry(const Conf *c, const Section *s, const char *key)
{
    for (uint32_t i = 0; i < s->count; i++) {
        const Entry *en = &c->entries[s->first + i];
        if (strcmp(en->key, key) == 0) return en;
    }
    return nullptr;
}

static bool check_names(const Conf *c, ConfError *e, const Entry *en, Kind kind,
    const char *what)
{
    const char *cur = en->val;
    const char *w;
    size_t n;
    while (conf_list_next(&cur, &w, &n))
        if (find_section(c, kind, w, n) < 0)
            return fail(e, en->line, "%s '%.*s'", what, (int)n, w);
    return true;
}

// Entry keys are unique to one kind, so the key alone says what it names.
static bool check_entry_refs(const Conf *c, ConfError *e, const Entry *en)
{
    if (strcmp(en->key, "include") == 0)
        return check_names(c, e, en, KIND_OUTFIT, "include of unknown outfit");
    if (strcmp(en->key, "only") == 0)
        return check_names(c, e, en, KIND_HARNESS, "only names unknown harness");
    if (strcmp(en->key, "outfits") == 0)
        return check_names(c, e, en, KIND_OUTFIT, "wear names unknown outfit");
    return true;
}

static bool check_refs(const Conf *c, ConfError *e)
{
    for (uint32_t i = 0; i < c->nsections; i++) {
        const Section *s = &c->sections[i];
        if (s->kind == KIND_NEED &&
            find_section(c, KIND_HARNESS, s->arg[0], strlen(s->arg[0])) < 0)
            return fail(e, s->line, "need names unknown harness '%.40s'", s->arg[0]);
        for (uint32_t j = 0; j < s->count; j++)
            if (!check_entry_refs(c, e, &c->entries[s->first + j])) return false;
    }
    return true;
}

typedef struct {
    uint32_t sec;
    const char *cursor;
    const Entry *inc;
} Frame;

static void append_text(ConfError *e, size_t *off, const char *text)
{
    size_t room = sizeof e->msg - 1 - *off;
    size_t n = strlen(text);
    size_t k = n < room ? n : room;
    memcpy(e->msg + *off, text, k);
    *off += k;
    e->msg[*off] = '\0';
}

static void cycle_message(const Conf *c, ConfError *e, const Frame *stack, uint32_t from,
    uint32_t top, uint32_t again)
{
    size_t off = 0;
    e->msg[0] = '\0';
    append_text(e, &off, "include cycle: ");
    for (uint32_t k = from; k <= top; k++) {
        append_text(e, &off, c->sections[stack[k].sec].arg[0]);
        append_text(e, &off, " -> ");
    }
    append_text(e, &off, c->sections[again].arg[0]);
}

static Frame frame_for(const Conf *c, uint32_t sec)
{
    const Entry *inc = find_entry(c, &c->sections[sec], "include");
    return (Frame){sec, inc != nullptr ? inc->val : "", inc};
}

// Iterative depth-first walk of the include graph. color: 0 new, 1 on the
// stack, 2 done. References were already checked, so every lookup succeeds.
static bool check_cycles(const Conf *c, ConfError *e)
{
    static uint8_t color[CONF_SECTION_MAX];
    static Frame stack[CONF_OUTFIT_MAX];
    memset(color, 0, sizeof color);

    for (uint32_t root = 0; root < c->nsections; root++) {
        if (c->sections[root].kind != KIND_OUTFIT || color[root] != 0) continue;
        uint32_t top = 0;
        stack[0] = frame_for(c, root);
        color[root] = 1;
        while (true) {
            Frame *f = &stack[top];
            const char *w;
            size_t n;
            if (!conf_list_next(&f->cursor, &w, &n)) {
                color[f->sec] = 2;
                if (top == 0) break;
                top--;
                continue;
            }
            int found = find_section(c, KIND_OUTFIT, w, n);
            ensure(found >= 0);
            uint32_t next = (uint32_t)found;
            if (color[next] == 1) {
                uint32_t from = 0;
                while (stack[from].sec != next) from++;
                cycle_message(c, e, stack, from, top, next);
                e->line = f->inc->line;
                return false;
            }
            if (color[next] == 2) continue;
            // Each outfit is pushed once, so the stack cannot outgrow them.
            ensure(top + 1 < CONF_OUTFIT_MAX);
            color[next] = 1;
            stack[++top] = frame_for(c, next);
        }
    }
    return true;
}

// ---- parse ----------------------------------------------------------------

static bool parse_in_place(Conf *c, size_t len, ConfError *e)
{
    c->nsections = 0;
    c->nentries = 0;
    memset(c->kind_count, 0, sizeof c->kind_count);
    c->buf[len] = '\0';

    char *p = c->buf;
    char *end = c->buf + len;
    int line = 0;
    while (p < end) {
        char *nl = memchr(p, '\n', (size_t)(end - p));
        char *stop = nl != nullptr ? nl : end;
        size_t n = (size_t)(stop - p);
        line++;
        if (n > CONF_LINE_MAX)
            return fail(e, line, "line is %zu bytes, limit is %zu", n, CONF_LINE_MAX);
        if (memchr(p, '\0', n) != nullptr) return fail(e, line, "NUL byte in line");
        *stop = '\0';
        char *s = p;
        p = stop + 1;

        strip_comment(s);
        s = trim(s);
        if (s[0] == '\0') continue;
        bool ok = s[0] == '[' ? parse_header(c, e, line, s) : parse_entry(c, e, line, s);
        if (!ok) return false;
    }
    return check_refs(c, e) && check_cycles(c, e);
}

bool conf_parse(Conf *c, const char *data, size_t len, ConfError *e)
{
    if (len > CONF_FILE_MAX)
        return fail(e, 0, "file is %zu bytes, limit is %zu", len, CONF_FILE_MAX);
    memcpy(c->buf, data, len);
    return parse_in_place(c, len, e);
}

bool conf_load(Conf *c, const char *path, ConfError *e)
{
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) return fail(e, 0, "cannot open: %s", strerror(errno));
    size_t len = 0;
    while (len <= CONF_FILE_MAX) {
        ssize_t got = sys_read(fd, c->buf + len, CONF_FILE_MAX + 1 - len);
        if (got < 0 && errno == EINTR) continue;
        if (got < 0) {
            int err = errno;
            (void)sys_close(fd);
            return fail(e, 0, "cannot read: %s", strerror(err));
        }
        if (got == 0) break;
        len += (size_t)got;
    }
    (void)sys_close(fd);
    if (len > CONF_FILE_MAX)
        return fail(e, 0, "file is over the limit of %zu bytes", CONF_FILE_MAX);
    return parse_in_place(c, len, e);
}

// ---- dump -----------------------------------------------------------------

static int cmp_section(const void *pa, const void *pb)
{
    const Section *a = pa;
    const Section *b = pb;
    if (a->kind != b->kind) return a->kind < b->kind ? -1 : 1;
    int r = 0;
    for (int i = 0; i < 3; i++) r = r != 0 ? r : strcmp(a->arg[i], b->arg[i]);
    return r;
}

static int cmp_entry(const void *pa, const void *pb)
{
    const Entry *a = pa;
    const Entry *b = pb;
    int r = strcmp(a->key, b->key);
    r = r != 0 ? r : strcmp(a->val, b->val);
    return r != 0 ? r : (a->line > b->line) - (a->line < b->line);
}

static void dump_prefix(Out *o, const Section *s)
{
    out_str(o, kind_names[s->kind]);
    if (s->kind == KIND_WEAR) {
        out_str(o, " ");
        out_str(o, s->arg[0]);
        if (s->arg[1][0] != '\0') {
            out_str(o, " ");
            out_str(o, s->arg[1]);
        }
        if (s->arg[2][0] != '\0') {
            out_str(o, " machine=");
            out_str(o, s->arg[2]);
        }
        return;
    }
    for (int i = 0; i < 2 && s->arg[i][0] != '\0'; i++) {
        out_str(o, " ");
        out_str(o, s->arg[i]);
    }
}

bool conf_dump(Conf *c, int fd)
{
    Out out;
    out_init(&out, fd);
    qsort(c->sections, c->nsections, sizeof c->sections[0], cmp_section);
    for (uint32_t i = 0; i < c->nsections; i++) {
        const Section *s = &c->sections[i];
        qsort(&c->entries[s->first], s->count, sizeof c->entries[0], cmp_entry);
        dump_prefix(&out, s);
        out_str(&out, "\n");
        for (uint32_t j = 0; j < s->count; j++) {
            const Entry *en = &c->entries[s->first + j];
            dump_prefix(&out, s);
            out_str(&out, " ");
            out_str(&out, en->key);
            out_str(&out, " = ");
            out_str(&out, en->val);
            out_str(&out, "\n");
        }
    }
    return out_finish(&out);
}