#include "conf.h"
#include "platform.h"
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdint.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;
e->ward = 0;
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;
}
bool conf_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_INTO, // a relative path of names: no empty, . or .. part
VT_FREE,
VT_GLOB, // a glob of session files: absolute, or starting with ~/
VT_FIELD, // a path of field names in a session record
VT_RULE, // a rule `use KIND` takes
VT_HEADER, // one front matter line, NAME: VALUE
} 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_HARNESS, "sessions", VT_GLOB, true, false},
{KIND_HARNESS, "session time", VT_FIELD, false, false},
{KIND_HARNESS, "session project", VT_FIELD, false, false},
{KIND_HARNESS, "use", VT_RULE, true, true},
{KIND_HARNESS, "skills.call", VT_HEADER, false, false},
{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},
{KIND_UPSTREAM, "into", VT_INTO, 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;
}
static const char *const use_kinds[USE_KIND_COUNT] = {"skill", "agent", "command"};
const char *use_kind_name(UseKind kind)
{
ensure((unsigned)kind < USE_KIND_COUNT);
return use_kinds[kind];
}
static UseKind use_kind_of(const char *word)
{
UseKind k = USE_SKILL;
while (k < USE_KIND_COUNT && strcmp(use_kinds[k], word) != 0) k++;
return k;
}
// The PARAM of "event PARAM", "slot PARAM", "file PARAM" and "use 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;
if (strcmp(sp->name, "use") == 0) return use_kind_of(p) != USE_KIND_COUNT;
return strcmp(sp->name, "file") == 0 || all_in(p, strlen(p), "._-/");
}
// How many times a key may appear in one section; 0 for no limit.
static uint32_t key_limit(const KeySpec *sp)
{
if (strcmp(sp->name, "sessions") == 0) return CONF_SESSIONS_MAX;
return strcmp(sp->name, "use") == 0 ? CONF_USE_MAX : 0;
}
// ---- session records: paths and rules ---------------------------------------
static void path_push(UsagePath *p, bool each, const char *key, size_t len)
{
ensure(p->n < USAGE_STEPS_MAX + 2);
p->each[p->n] = each;
p->len[p->n] = (uint8_t)len;
memcpy(p->key[p->n], key, len);
p->key[p->n][len] = '\0';
p->n++;
}
bool conf_path_parse(UsagePath *p, const char *text, bool each, bool dot)
{
p->n = 0;
if (strcmp(text, ".") == 0) return dot;
for (const char *s = text;;) {
size_t len = strcspn(s, ".");
bool arr = len >= 2 && s[len - 2] == '[' && s[len - 1] == ']';
size_t klen = arr ? len - 2 : len;
if (klen == 0 || klen > USAGE_KEY_MAX) return false;
if (memchr(s, '[', klen) != nullptr || memchr(s, ']', klen) != nullptr) return false;
if (arr && !each) return false;
if (p->n + (arr ? 2u : 1u) > USAGE_STEPS_MAX) return false;
path_push(p, false, s, klen);
if (arr) path_push(p, true, "", 0);
if (s[len] == '\0') return true;
s += len + 1;
}
}
// The next word of *CUR, ended in place, or null at the end.
static char *take_word(char **cur)
{
char *s = *cur;
while (*s == ' ' || *s == '\t') s++;
if (*s == '\0') return nullptr;
char *w = s;
while (*s != '\0' && *s != ' ' && *s != '\t') s++;
if (*s != '\0') *s++ = '\0';
*cur = s;
return w;
}
__attribute__((format(printf, 4, 5)))
static bool rule_fail(char *msg, size_t cap, UseKind kind, const char *fmt, ...)
{
int n = snprintf(msg, cap, "use %s: ", use_kind_name(kind));
ensure(n > 0 && (size_t)n < cap);
va_list ap;
va_start(ap, fmt);
vsnprintf(msg + n, cap - (size_t)n, fmt, ap);
va_end(ap);
return false;
}
// FIELD=VALUE of a where.
static bool rule_where(UsageRule *r, char *w, char *msg, size_t cap)
{
char *eq = strchr(w, '=');
if (eq == nullptr) return rule_fail(msg, cap, r->kind, "'%.40s' is not FIELD=VALUE", w);
*eq = '\0';
size_t vlen = strlen(eq + 1);
UsagePath *path = &r->where_path[r->nwhere];
if (!conf_path_parse(path, w, false, false))
return rule_fail(msg, cap, r->kind, "'%.40s' is not a path of field names in a where", w);
if (vlen == 0 || vlen > USAGE_VALUE_MAX)
return rule_fail(msg, cap, r->kind, "the VALUE of where %.40s must be 1 to %zu bytes", w, USAGE_VALUE_MAX);
memcpy(r->where_value[r->nwhere], eq + 1, vlen + 1);
r->nwhere++;
return true;
}
bool conf_rule_parse(UsageRule *r, UseKind kind, const char *text, char *msg, size_t cap)
{
ensure(strlen(text) <= CONF_LINE_MAX);
char buf[CONF_LINE_MAX + 1];
memcpy(buf, text, strlen(text) + 1);
*r = (UsageRule){.kind = kind};
char *cur = buf;
char *w = take_word(&cur);
ensure(w != nullptr); // a value is never empty
if (!conf_path_parse(&r->in, w, true, true))
return rule_fail(msg, cap, kind, "'%.40s' is not a path from the record's top", w);
w = take_word(&cur);
if (w != nullptr && strcmp(w, "where") == 0) {
for (w = take_word(&cur); w != nullptr && strcmp(w, "name") != 0; w = take_word(&cur)) {
if (r->nwhere == USAGE_WHERE_MAX)
return rule_fail(msg, cap, kind, "at most %u where tests", USAGE_WHERE_MAX);
if (!rule_where(r, w, msg, cap)) return false;
}
if (r->nwhere == 0) return rule_fail(msg, cap, kind, "where needs at least one FIELD=VALUE");
}
if (w == nullptr || strcmp(w, "name") != 0) return rule_fail(msg, cap, kind, "'name PATH' is missing");
w = take_word(&cur);
if (w == nullptr || !conf_path_parse(&r->name, w, false, false))
return rule_fail(msg, cap, kind, "name needs a path of field names");
r->name_list = r->name;
path_push(&r->name_list, true, "", 0);
path_push(&r->name_list, false, "text", 4);
w = take_word(&cur);
if (w != nullptr && strcmp(w, "between") == 0) {
char *a = take_word(&cur);
char *b = a != nullptr ? take_word(&cur) : nullptr;
if (b == nullptr) return rule_fail(msg, cap, kind, "between needs A and B");
if (strlen(a) > USAGE_VALUE_MAX || strlen(b) > USAGE_VALUE_MAX)
return rule_fail(msg, cap, kind, "A and B of between are at most %zu bytes", USAGE_VALUE_MAX);
r->between = true;
memcpy(r->a, a, strlen(a) + 1);
memcpy(r->b, b, strlen(b) + 1);
w = take_word(&cur);
}
if (w != nullptr && strcmp(w, "id") == 0) {
w = take_word(&cur);
if (w == nullptr || !conf_path_parse(&r->id, w, false, false))
return rule_fail(msg, cap, kind, "id needs a path of field names");
r->has_id = true;
w = take_word(&cur);
}
if (w != nullptr) return rule_fail(msg, cap, kind, "unexpected '%.40s'", w);
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 (!conf_name_ok(w, n, glob)) {
*bad = w;
*bad_len = n > 40 ? 40 : n;
return false;
}
}
return true;
}
// PATH is at most CONF_INTO_MAX bytes and each part of it, between slashes, is a name that does not
// start with a dot.
static bool into_ok(const char *path)
{
if (strlen(path) > CONF_INTO_MAX) return false;
for (const char *s = path;;) {
size_t len = strcspn(s, "/");
if (s[0] == '.' || !conf_name_ok(s, len, false)) return false;
if (s[len] == '\0') return true;
s += len + 1;
}
}
bool conf_header_line_ok(const char *s, size_t len)
{
size_t name = 0;
while (name < len && all_in(s + name, 1, "-_.")) name++;
if (len > CONF_HEADER_MAX || name == 0 || len < name + 3 || s[name] != ':' || s[name + 1] != ' ' || s[name + 2] == ' ' || s[len - 1] == ' ')
return false;
for (size_t i = name + 2; i < len; i++)
if ((unsigned char)s[i] < 0x20 || s[i] == 0x7f) 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_GLOB) {
if (val[0] != '/' && strncmp(val, "~/", 2) != 0)
return fail(e, line, "'%s' takes an absolute path or one starting with ~/, not '%.40s'", key, val);
return true;
}
if (sp->vt == VT_FIELD) {
UsagePath path;
if (!conf_path_parse(&path, val, false, false))
return fail(e, line, "'%s' takes a path of field names joined by dots, not '%.40s'", key, val);
return true;
}
if (sp->vt == VT_RULE) {
static UsageRule rule;
char msg[sizeof e->msg];
if (!conf_rule_parse(&rule, use_kind_of(key + 4), val, msg, sizeof msg)) return fail(e, line, "%s", msg);
return true;
}
if (sp->vt == VT_HEADER) {
if (!conf_header_line_ok(val, strlen(val)))
return fail(e, line, "'%s' takes one front matter line, NAME: VALUE, of at most %zu bytes, not '%.40s'", key, CONF_HEADER_MAX,
val);
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 (!conf_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;
}
if (sp->vt == VT_INTO) {
if (!into_ok(val))
return fail(e, line, "'%s' must be a relative path of names, at most %zu bytes, with no empty, . or .. part, not '%.40s'",
key, CONF_INTO_MAX, 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 (!conf_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 (!conf_name_ok(w[1], strlen(w[1]), false) || !conf_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 (!conf_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;
sec->ward = 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);
}
}
uint32_t limit = key_limit(sp);
if (limit != 0) {
uint32_t have = 0;
for (uint32_t i = 0; i < sec->count; i++)
if (find_spec(sec->kind, c->entries[sec->first + i].key) == sp) have++;
if (have == limit) return fail(e, line, "too many '%s' keys in a harness (limit %u)", sp->name, limit);
}
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) {
(void)fail(e, s->line, "need names unknown harness '%.40s'", s->arg[0]);
e->ward = s->ward;
return false;
}
for (uint32_t j = 0; j < s->count; j++) {
if (check_entry_refs(c, e, &c->entries[s->first + j])) continue;
e->ward = s->ward;
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;
e->ward = c->sections[f->sec].ward;
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 ----------------------------------------------------------------
bool conf_check(const Conf *c, ConfError *e)
{
return check_refs(c, e) && check_cycles(c, e);
}
static bool parse_in_place(Conf *c, size_t len, ConfError *e, bool check)
{
c->nsections = 0;
c->nentries = 0;
c->len = len;
c->used = len + 1;
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 || conf_check(c, e);
}
static bool parse_text(Conf *c, const char *data, size_t len, ConfError *e, bool check)
{
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, check);
}
bool conf_parse(Conf *c, const char *data, size_t len, ConfError *e)
{
return parse_text(c, data, len, e, true);
}
bool conf_parse_part(Conf *c, const char *data, size_t len, ConfError *e)
{
return parse_text(c, data, len, e, false);
}
static bool load(Conf *c, const char *path, ConfError *e, bool check)
{
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, check);
}
bool conf_load(Conf *c, const char *path, ConfError *e)
{
return load(c, path, e, true);
}
bool conf_load_part(Conf *c, const char *path, ConfError *e)
{
return load(c, path, e, false);
}
// ---- merge ----------------------------------------------------------------
void conf_merge_init(Conf *c)
{
c->nsections = 0;
c->nentries = 0;
c->len = 0;
c->used = 0;
memset(c->kind_count, 0, sizeof c->kind_count);
}
// The header as the file wrote it: [harness claude], [wear user machine=studio].
static void header_text(const Section *s, char *out, size_t cap)
{
const char *a = s->arg[0];
if (s->kind == KIND_WEAR)
snprintf(out, cap, "[wear %s%s%s%s%s]", a, s->arg[1][0] != '\0' ? " " : "", s->arg[1],
s->arg[2][0] != '\0' ? " machine=" : "", s->arg[2]);
else if (s->kind == KIND_NEED)
snprintf(out, cap, "[need %s %s]", a, s->arg[1]);
else
snprintf(out, cap, "[%s %s]", kind_names[s->kind], a);
}
// P as it will be in DST, whose copy of SRC's buffer starts AT bytes in. A
// string that is not in SRC's buffer (a scope's name, "") stays where it is.
static const char *rebase(const Conf *src, const Conf *dst, size_t at, const char *p)
{
uintptr_t off = (uintptr_t)p - (uintptr_t)src->buf; // wraps for an address below the buffer
return off < src->used ? dst->buf + at + off : p;
}
static bool merge_fail(ConfError *e, uint32_t ward, int line)
{
e->line = line;
e->ward = ward;
return false;
}
static bool merge_in(Conf *dst, const Conf *src, uint32_t ward, const Wards *w, ConfError *e)
{
ensure(ward < w->n && ward < WARDROBE_MAX);
if (dst->len + src->len > CONF_FILE_MAX) {
(void)fail(e, 0, "the config files together are over the limit of %zu bytes", CONF_FILE_MAX);
return merge_fail(e, ward, 0);
}
size_t at = dst->used;
// The strings first, so the sections compared and added point at real bytes.
memcpy(dst->buf + at, src->buf, src->used);
for (uint32_t i = 0; i < src->nsections; i++) {
const Section *s = &src->sections[i];
for (uint32_t k = 0; k < dst->nsections; k++) {
const Section *first = &dst->sections[k];
if (!section_same(first, s)) continue;
char hdr[2 * CONF_NAME_MAX + 2 * 128];
header_text(s, hdr, sizeof hdr);
(void)fail(e, s->line, "duplicate section %s; first at %s:%d", hdr, w->w[first->ward].conf,
first->line);
return merge_fail(e, ward, s->line);
}
if (dst->kind_count[s->kind] == kind_limits[s->kind]) {
(void)fail(e, s->line, "too many %s sections (limit %u)", kind_names[s->kind],
kind_limits[s->kind]);
return merge_fail(e, ward, s->line);
}
if (dst->nentries + s->count > CONF_ENTRY_MAX) {
(void)fail(e, s->line, "too many entries (limit %u)", CONF_ENTRY_MAX);
return merge_fail(e, ward, s->line);
}
// The per-kind limits add up to the section limit.
ensure(dst->nsections < CONF_SECTION_MAX);
Section *out = &dst->sections[dst->nsections++];
*out = *s;
for (int a = 0; a < 3; a++) out->arg[a] = rebase(src, dst, at, s->arg[a]);
out->first = dst->nentries;
out->ward = (uint8_t)ward;
for (uint32_t j = 0; j < s->count; j++) {
const Entry *en = &src->entries[s->first + j];
dst->entries[dst->nentries++] = (Entry){.key = rebase(src, dst, at, en->key),
.val = rebase(src, dst, at, en->val), .line = en->line};
}
dst->kind_count[s->kind]++;
}
dst->len += src->len;
dst->used += src->used;
return true;
}
bool conf_merge(Conf *dst, const Conf *src, uint32_t ward, const Wards *w, ConfError *e)
{
uint32_t nsections = dst->nsections;
uint32_t nentries = dst->nentries;
uint32_t kind_count[KIND_COUNT];
memcpy(kind_count, dst->kind_count, sizeof kind_count);
bool ok = merge_in(dst, src, ward, w, e);
if (!ok) { // a refused merge leaves DST as it was
dst->nsections = nsections;
dst->nentries = nentries;
memcpy(dst->kind_count, kind_count, sizeof kind_count);
}
return ok;
}
// ---- 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);
}