Skip to content
suit Artifact [4340f4760e]
Login

Artifact [4340f4760e]

Artifact 4340f4760e706812eacf1eeaebeef73f7db3475c9ca444abef9c7561dbc52c25:


#include "conf.h"

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.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);

const char *conf_kind_name(Kind kind)
{
    assert(kind < KIND_COUNT);
    return kind_names[kind];
}

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

static bool name_ok(const char *s, size_t len, bool glob)
{
    if (len == 0 || len > CONF_NAME_MAX) return false;
    for (size_t i = 0; i < len; i++) {
        char c = s[i];
        if (!(is_alnum(c) || c == '.' || c == '_' || c == '-' ||
                (glob && c == '*')))
            return false;
    }
    return true;
}

static bool target_ok(const char *s)
{
    if (s[0] == '\0') return false;
    for (; *s != '\0'; s++) {
        char c = *s;
        if (!(is_alnum(c) || c == '.' || c == '_' || c == '-' || c == '/' ||
                c == ':' || c == '@' || c == '~'))
            return false;
    }
    return true;
}

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

static const char *const harness_kinds[] = {
    "skills", "agents", "commands", "instructions",
};
static const char *const scopes[] = {"enterprise", "user", "shared", "personal"};

static bool in_list(const char *s, size_t len, const char *const *list, size_t n)
{
    for (size_t i = 0; i < n; i++)
        if (strlen(list[i]) == len && memcmp(list[i], s, len) == 0) return true;
    return false;
}

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

// harness key "KIND.SCOPE".
static bool harness_path_key(const char *key)
{
    const char *dot = strchr(key, '.');
    if (dot == nullptr) return false;
    return in_list(key, (size_t)(dot - key), harness_kinds, COUNT(harness_kinds)) &&
        in_list(dot + 1, strlen(dot + 1), scopes, COUNT(scopes));
}

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];
        if (sp->kind != kind) continue;
        size_t n = strlen(sp->name);
        if (!sp->param) {
            if (strcmp(key, sp->name) == 0) return sp;
        } else if (strncmp(key, sp->name, n) == 0 && key[n] == ' ' &&
            key[n + 1] != '\0') {
            return sp;
        }
    }
    return nullptr;
}

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

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;
    switch (sp->vt) {
    case VT_PATH:
    case VT_FREE:
        return true;
    case VT_WORD:
        if (strchr(val, ' ') != nullptr)
            return fail(e, line, "'%s' takes one word, not '%.40s'", key, val);
        return true;
    case VT_NAME:
        if (!name_ok(val, strlen(val), false))
            return fail(e, line, "'%s' takes one name, not '%.40s'", key, val);
        return true;
    case VT_NAMES:
    case 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;
    case 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;
    case 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;
    }
    assert(false);
    return false;
}

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

static bool section_same(const Section *a, const Section *b)
{
    return a->kind == b->kind && strcmp(a->arg[0], b->arg[0]) == 0 &&
        strcmp(a->arg[1], b->arg[1]) == 0 && strcmp(a->arg[2], b->arg[2]) == 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");
    if (!in_list(w[1], strlen(w[1]), scopes, COUNT(scopes)))
        return fail(e, line,
            "unknown scope '%.40s' (enterprise, user, shared or personal)", w[1]);
    const char *scope = 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];

    bool needs_target = strcmp(scope, "shared") == 0 || strcmp(scope, "personal") == 0;
    bool allows_machine = strcmp(scope, "user") == 0 || strcmp(scope, "personal") == 0;
    if (needs_target && target[0] == '\0')
        return fail(e, line, "wear %s needs a TARGET (a project's remote address)",
            scope);
    if (!needs_target && target[0] != '\0')
        return fail(e, line, "wear %s takes no TARGET", scope);
    if (target[0] != '\0' && !target_ok(target))
        return fail(e, line, "invalid target '%.60s'", target);
    if (machine[0] != '\0' && !allows_machine)
        return fail(e, line, "machine= is allowed only on user and personal, not %s",
            scope);
    s->arg[0] = scope;
    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] = "";
    const char *k = kind_names[kind];
    switch (kind) {
    case KIND_HARNESS:
    case KIND_OUTFIT:
    case KIND_UPSTREAM:
        if (nw != 2) return fail(e, line, "%s takes exactly one NAME", k);
        if (!name_ok(w[1], strlen(w[1]), false))
            return fail(e, line, "invalid %s name '%.40s'", k, w[1]);
        s->arg[0] = w[1];
        return true;
    case 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;
    case KIND_WEAR:
        return header_wear(e, line, w, nw, s);
    case KIND_COUNT:
        break;
    }
    assert(false);
    return false;
}

static bool parse_header(Conf *c, ConfError *e, int line, char *s)
{
    size_t n = strlen(s);
    assert(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]);

    if (c->nsections == CONF_SECTION_MAX) return fail(e, line, "too many sections");
    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);
    if (key[0] == '\0') return fail(e, line, "expected KEY = VALUE: key is empty");

    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;
    if (sec->kind == KIND_WEAR && 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;
}

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++) {
            const Entry *en = &c->entries[s->first + j];
            bool ok = true;
            if (s->kind == KIND_OUTFIT && strcmp(en->key, "include") == 0)
                ok = check_names(c, e, en, KIND_OUTFIT, "include of unknown outfit");
            else if (s->kind == KIND_OUTFIT && strcmp(en->key, "only") == 0)
                ok = check_names(c, e, en, KIND_HARNESS,
                    "only names unknown harness");
            else if (s->kind == KIND_WEAR && strcmp(en->key, "outfits") == 0)
                ok = check_names(c, e, en, KIND_OUTFIT, "wear names unknown outfit");
            if (!ok) return false;
        }
    }
    return true;
}

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

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

// 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;
        const Entry *inc = find_entry(c, &c->sections[root], "include");
        stack[0] = (Frame){root, inc != nullptr ? inc->val : "", inc};
        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 next = find_section(c, KIND_OUTFIT, w, n);
            assert(next >= 0);
            if (color[next] == 1) {
                uint32_t from = 0;
                while (stack[from].sec != (uint32_t)next) from++;
                cycle_message(c, e, stack, from, top, (uint32_t)next);
                e->line = f->inc->line;
                return false;
            }
            if (color[next] == 2) continue;
            assert(top + 1 < CONF_OUTFIT_MAX);
            inc = find_entry(c, &c->sections[next], "include");
            color[next] = 1;
            stack[++top] = (Frame){(uint32_t)next, inc != nullptr ? inc->val : "", inc};
        }
    }
    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)
{
    assert(c != nullptr && e != nullptr);
    if (len > CONF_FILE_MAX)
        return fail(e, 0, "file is %zu bytes, limit is %zu", len, CONF_FILE_MAX);
    if (len > 0) memcpy(c->buf, data, len);
    return parse_in_place(c, len, e);
}

bool conf_load(Conf *c, const char *path, ConfError *e)
{
    assert(c != nullptr && path != nullptr && e != nullptr);
    int fd = open(path, O_RDONLY);
    if (fd < 0) return fail(e, 0, "cannot open: %s", strerror(errno));
    size_t len = 0;
    while (len <= CONF_FILE_MAX) {
        ssize_t got = read(fd, c->buf + len, CONF_FILE_MAX + 1 - len);
        if (got < 0 && errno == EINTR) continue;
        if (got < 0) {
            int err = errno;
            close(fd);
            return fail(e, 0, "cannot read: %s", strerror(err));
        }
        if (got == 0) break;
        len += (size_t)got;
    }
    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;
    for (int i = 0; i < 3; i++) {
        int r = strcmp(a->arg[i], b->arg[i]);
        if (r != 0) return r;
    }
    return 0;
}

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);
    if (r != 0) return r;
    r = strcmp(a->val, b->val);
    if (r != 0) return r;
    return (a->line > b->line) - (a->line < b->line);
}

static void dump_prefix(FILE *out, const Section *s)
{
    fputs(kind_names[s->kind], out);
    if (s->kind == KIND_WEAR) {
        fprintf(out, " %s", s->arg[0]);
        if (s->arg[1][0] != '\0') fprintf(out, " %s", s->arg[1]);
        if (s->arg[2][0] != '\0') fprintf(out, " machine=%s", s->arg[2]);
    } else {
        for (int i = 0; i < 2 && s->arg[i][0] != '\0'; i++)
            fprintf(out, " %s", s->arg[i]);
    }
}

void conf_dump(Conf *c, FILE *out)
{
    assert(c->nsections <= CONF_SECTION_MAX && c->nentries <= CONF_ENTRY_MAX);
    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];
        if (s->count > 0)
            qsort(&c->entries[s->first], s->count, sizeof c->entries[0], cmp_entry);
        dump_prefix(out, s);
        fputc('\n', out);
        for (uint32_t j = 0; j < s->count; j++) {
            const Entry *en = &c->entries[s->first + j];
            dump_prefix(out, s);
            fprintf(out, " %s = %s\n", en->key, en->val);
        }
    }
}