Files
junction/src/config.c
T
Hermes Agent 137113b0a2 junction: pf.conf-style policy router for model endpoints (C99/POSIX)
Rules are ordered and first-match-wins: model glob, path glob, required context,
hook/retry overrides, pass <endpoint>[,<endpoint>] [as <model>] or block.
Endpoints carry shell pre-hooks (exit != 0 = not yet, retried with backoff after an
optional wake command), an offline window after a failed connect, and two timeouts
(idle + total) so a thinking model logs still_working instead of looking hung.

tests/run.sh: 14 checks against C stubs (failing, gated, slow, dead endpoints).
2026-10-29 13:24:31 +00:00

449 lines
16 KiB
C

/* junction/config.c — parser for the pf.conf-style configuration.
*
* The format is deliberately dumb: keyword, arguments, braces. No '=', no nesting
* beyond one level, no quoting rules beyond "double quotes group words".
*
* # global options
* listen 0.0.0.0:8090
* chars_per_token 4
*
* endpoint peer1 {
* base http://192.0.2.10:8081/v1
* context 64000
* timeout 600
* hook /opt/junction/hooks/check-http.sh
* }
*
* Unknown keywords are a hard error with a line number. A config typo that silently
* keeps a default is worse than a router that refuses to start.
*/
#define _POSIX_C_SOURCE 200809L
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 16
static void strip_comment(char *s)
{
int quoted = 0;
for (char *p = s; *p; p++) {
if (*p == '"') quoted = !quoted;
else if (*p == '#' && !quoted) { *p = '\0'; return; }
}
}
/* Split into words; double quotes group. Returns word count, -1 on unbalanced quote.
* The words point into `buf`, which is modified in place. */
static int tokenize(char *buf, char **words, int maxw)
{
int n = 0;
char *p = buf;
while (*p) {
while (*p && isspace((unsigned char)*p)) p++;
if (!*p) break;
if (n >= maxw) return -2;
if (*p == '"') {
p++;
words[n++] = p;
char *out = p;
int closed = 0;
while (*p) {
if (*p == '"') { closed = 1; p++; break; }
*out++ = *p++;
}
*out = '\0';
if (!closed) return -1;
} else {
words[n++] = p;
while (*p && !isspace((unsigned char)*p)) p++;
if (*p) *p++ = '\0';
}
}
return n;
}
void j_config_defaults(j_config *cfg)
{
memset(cfg, 0, sizeof *cfg);
snprintf(cfg->listen_host, sizeof cfg->listen_host, "0.0.0.0");
cfg->listen_port = 8090;
cfg->chars_per_token = 4;
cfg->default_max_tokens = 4096;
cfg->connect_timeout_ms = 1500;
cfg->offline_hold_s = 20;
cfg->max_body_bytes = 64 * 1024 * 1024;
snprintf(cfg->log_prefix, sizeof cfg->log_prefix, "junction");
}
static void endpoint_defaults(j_endpoint *ep)
{
memset(ep, 0, sizeof *ep);
ep->context = 8192;
ep->priority = 50;
ep->timeout_s = 600;
ep->idle_timeout_s = 60;
ep->cooldown_s = 60;
ep->hook_retry_s = 0;
ep->hook_backoff_s = 5;
ep->last_ms = -1;
}
static int as_double(const char *s, double *dst)
{
char *end = NULL;
errno = 0;
double d = strtod(s, &end);
if (errno || end == s || (end && *end) || d < 0) return -1;
*dst = d;
return 0;
}
static int as_long(const char *s, long *dst)
{
char *end = NULL;
errno = 0;
long n = strtol(s, &end, 10);
if (errno || end == s || (end && *end)) return -1;
*dst = n;
return 0;
}
static int as_int(const char *s, int *dst)
{
long n = 0;
if (as_long(s, &n)) return -1;
*dst = (int)n;
return 0;
}
/* "8090" or "127.0.0.1:8090" or "[::1]:8090" */
static int parse_listen(j_config *cfg, const char *v)
{
const char *colon = strrchr(v, ':');
if (!colon) return as_int(v, &cfg->listen_port);
size_t hlen = (size_t)(colon - v);
if (hlen >= sizeof cfg->listen_host) return -1;
memcpy(cfg->listen_host, v, hlen);
cfg->listen_host[hlen] = '\0';
if (cfg->listen_host[0] == '[') { /* strip brackets for IPv6 */
memmove(cfg->listen_host, cfg->listen_host + 1, hlen - 1);
cfg->listen_host[hlen - 2] = '\0';
}
return as_int(colon + 1, &cfg->listen_port);
}
static int global_kw(j_config *cfg, char **w, int n, int lineno, char *err, size_t errlen)
{
const char *k = w[0];
if (!strcmp(k, "listen")) {
if (n != 2 || parse_listen(cfg, w[1])) goto bad;
return 0;
}
if (!strcmp(k, "chars_per_token")) { if (n != 2 || as_int(w[1], &cfg->chars_per_token)) goto bad; return 0; }
if (!strcmp(k, "default_max_tokens")) { if (n != 2 || as_long(w[1], &cfg->default_max_tokens)) goto bad; return 0; }
if (!strcmp(k, "connect_timeout_ms")) { if (n != 2 || as_double(w[1], &cfg->connect_timeout_ms)) goto bad; return 0; }
if (!strcmp(k, "offline_hold_s")) { if (n != 2 || as_double(w[1], &cfg->offline_hold_s)) goto bad; return 0; }
if (!strcmp(k, "max_body_bytes")) { if (n != 2 || as_int(w[1], &cfg->max_body_bytes)) goto bad; return 0; }
if (!strcmp(k, "log_prefix")) {
if (n != 2) goto bad;
snprintf(cfg->log_prefix, sizeof cfg->log_prefix, "%s", w[1]);
return 0;
}
snprintf(err, errlen, "line %d: unknown keyword '%s'", lineno, k);
return -1;
bad:
snprintf(err, errlen, "line %d: bad arguments for '%s'", lineno, k);
return -1;
}
static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, size_t errlen)
{
const char *k = w[0];
if (!strcmp(k, "base")) { if (n != 2) goto bad; snprintf(ep->base, sizeof ep->base, "%s", w[1]); return 0; }
if (!strcmp(k, "kind")) { if (n != 2) goto bad; snprintf(ep->kind, sizeof ep->kind, "%s", w[1]); return 0; }
if (!strcmp(k, "context")) { if (n != 2 || as_long(w[1], &ep->context)) goto bad; return 0; }
if (!strcmp(k, "priority")) { if (n != 2 || as_int(w[1], &ep->priority)) goto bad; return 0; }
if (!strcmp(k, "timeout")) { if (n != 2 || as_double(w[1], &ep->timeout_s)) goto bad; return 0; }
if (!strcmp(k, "idle_timeout")) { if (n != 2 || as_double(w[1], &ep->idle_timeout_s)) goto bad; return 0; }
if (!strcmp(k, "cooldown")) { if (n != 2 || as_double(w[1], &ep->cooldown_s)) goto bad; return 0; }
if (!strcmp(k, "hook_retry")) { if (n != 2 || as_double(w[1], &ep->hook_retry_s)) goto bad; return 0; }
if (!strcmp(k, "hook_backoff")) { if (n != 2 || as_double(w[1], &ep->hook_backoff_s)) goto bad; return 0; }
if (!strcmp(k, "wake")) { if (n != 2) goto bad; snprintf(ep->wake, sizeof ep->wake, "%s", w[1]); return 0; }
if (!strcmp(k, "api_key_env")) { if (n != 2) goto bad; snprintf(ep->api_key_env, sizeof ep->api_key_env, "%s", w[1]); return 0; }
if (!strcmp(k, "hook")) {
if (n < 2) goto bad;
if (ep->hook_count >= J_MAX_HOOKS) {
snprintf(err, errlen, "line %d: endpoint %s has more than %d hooks", lineno, ep->name, J_MAX_HOOKS);
return -1;
}
/* join remaining words so an unquoted command with arguments works */
char joined[J_CMD_MAX] = "";
size_t used = 0;
for (int i = 1; i < n && used < sizeof joined - 1; i++) {
int wrote = snprintf(joined + used, sizeof joined - used, "%s%s",
i > 1 ? " " : "", w[i]);
if (wrote < 0) break;
used += (size_t)wrote;
}
snprintf(ep->hooks[ep->hook_count++], J_CMD_MAX, "%s", joined);
return 0;
}
snprintf(err, errlen, "line %d: unknown endpoint keyword '%s'", lineno, k);
return -1;
bad:
snprintf(err, errlen, "line %d: bad arguments for '%s'", lineno, k);
return -1;
}
/* --- rules: req [for GLOB] [path GLOB] [need OP N] [check hooks|none]
* [retry SECONDS] (pass EP[,EP...] [as MODEL] | block) */
static int parse_rule(char **w, int n, int lineno, j_rule *r, char *err, size_t errlen)
{
memset(r, 0, sizeof *r);
r->need_min = -1;
r->need_max = -1;
r->check = J_CHECK_INHERIT;
r->retry_s = -1;
r->line = lineno;
int i = 1; /* w[0] == "req" */
while (i < n) {
const char *k = w[i];
if (!strcmp(k, "for")) {
if (i + 1 >= n) goto bad;
snprintf(r->model_glob, sizeof r->model_glob, "%s", w[i + 1]);
i += 2;
} else if (!strcmp(k, "path")) {
if (i + 1 >= n) goto bad;
snprintf(r->path_glob, sizeof r->path_glob, "%s", w[i + 1]);
i += 2;
} else if (!strcmp(k, "need")) {
if (i + 1 >= n) goto bad;
const char *v = w[i + 1];
long num = 0;
if (v[0] == '>') { if (as_long(v + (v[1] == '=' ? 2 : 1), &num)) goto bad;
r->need_min = v[1] == '=' ? num : num + 1; }
else if (v[0] == '<') { if (as_long(v + (v[1] == '=' ? 2 : 1), &num)) goto bad;
r->need_max = v[1] == '=' ? num : num - 1; }
else { if (as_long(v, &num)) goto bad; r->need_min = r->need_max = num; }
i += 2;
} else if (!strcmp(k, "check")) {
if (i + 1 >= n) goto bad;
if (!strcmp(w[i + 1], "hooks")) r->check = J_CHECK_HOOKS;
else if (!strcmp(w[i + 1], "none")) r->check = J_CHECK_NONE;
else goto bad;
i += 2;
} else if (!strcmp(k, "retry")) {
if (i + 1 >= n || as_double(w[i + 1], &r->retry_s)) goto bad;
i += 2;
} else if (!strcmp(k, "block")) {
r->block = 1;
i++;
return 0;
} else if (!strcmp(k, "pass")) {
if (i + 1 >= n) goto bad;
/* targets run until "as" or the end of the line; they may be written as
* one comma list, as separate words, or both. */
int j = i + 1;
char joined[J_CMD_MAX] = "";
size_t ju = 0;
for (; j < n && strcmp(w[j], "as"); j++) {
int wrote = snprintf(joined + ju, sizeof joined - ju, "%s%s",
ju ? "," : "", w[j]);
if (wrote < 0) break;
ju += (size_t)wrote;
}
char *save = NULL;
for (char *tok = strtok_r(joined, ",", &save); tok;
tok = strtok_r(NULL, ",", &save)) {
while (*tok == ' ') tok++;
if (!*tok) continue;
if (r->target_count >= J_MAX_TARGETS) {
snprintf(err, errlen, "line %d: more than %d pass targets", lineno, J_MAX_TARGETS);
return -1;
}
snprintf(r->targets[r->target_count++], J_NAME_MAX, "%s", tok);
}
if (!r->target_count) goto bad;
i = j;
/* optional: as MODEL */
if (i < n && !strcmp(w[i], "as")) {
if (i + 1 >= n) goto bad;
snprintf(r->rewrite_model, sizeof r->rewrite_model, "%s", w[i + 1]);
i += 2;
}
if (i != n) goto bad;
return 0;
} else {
snprintf(err, errlen, "line %d: unknown rule keyword '%s'", lineno, k);
return -1;
}
}
snprintf(err, errlen, "line %d: rule without 'pass' or 'block'", lineno);
return -1;
bad:
snprintf(err, errlen, "line %d: bad arguments in rule", lineno);
return -1;
}
int j_config_load(const char *path, j_config *cfg, char *err, size_t errlen)
{
FILE *fh = fopen(path, "r");
if (!fh) {
snprintf(err, errlen, "cannot open %s: %s", path, strerror(errno));
return -1;
}
j_config_defaults(cfg);
char line[4096];
int lineno = 0;
j_endpoint *cur = NULL;
while (fgets(line, sizeof line, fh)) {
lineno++;
strip_comment(line);
char *w[MAX_WORDS];
int n = tokenize(line, w, MAX_WORDS);
if (n == 0) continue;
if (n < 0) {
snprintf(err, errlen, "line %d: unbalanced quote", lineno);
fclose(fh);
return -1;
}
if (!strcmp(w[0], "}")) {
if (!cur) {
snprintf(err, errlen, "line %d: '}' without an open block", lineno);
fclose(fh);
return -1;
}
cur = NULL;
continue;
}
if (!strcmp(w[0], "req")) {
if (cur) {
snprintf(err, errlen, "line %d: rules are not allowed inside an endpoint block", lineno);
fclose(fh);
return -1;
}
if (cfg->rule_count >= J_MAX_RULES) {
snprintf(err, errlen, "more than %d rules", J_MAX_RULES);
fclose(fh);
return -1;
}
if (parse_rule(w, n, lineno, &cfg->rules[cfg->rule_count], err, errlen)) {
fclose(fh);
return -1;
}
cfg->rule_count++;
continue;
}
if (!strcmp(w[0], "pass") || !strcmp(w[0], "block")) {
/* bare catch-all rule: pass a, b / block */
char **shifted = w;
(void)shifted;
if (cur) {
snprintf(err, errlen, "line %d: rules are not allowed inside an endpoint block", lineno);
fclose(fh);
return -1;
}
if (cfg->rule_count >= J_MAX_RULES) {
snprintf(err, errlen, "more than %d rules", J_MAX_RULES);
fclose(fh);
return -1;
}
/* synthesise "req <rest>" */
char synth[4096] = "req";
for (int i = 0; i < n; i++) {
size_t used = strlen(synth);
snprintf(synth + used, sizeof synth - used, " %s", w[i]);
}
char *w2[MAX_WORDS];
int n2 = tokenize(synth, w2, MAX_WORDS);
if (n2 < 2 || parse_rule(w2, n2, lineno, &cfg->rules[cfg->rule_count], err, errlen)) {
if (!err[0])
snprintf(err, errlen, "line %d: rule without 'req' malformed", lineno);
fclose(fh);
return -1;
}
cfg->rule_count++;
continue;
}
if (!strcmp(w[0], "endpoint") || !strcmp(w[0], "backend")) {
/* endpoint NAME { — the brace must be the last word */
if (n != 3 || strcmp(w[2], "{")) {
snprintf(err, errlen, "line %d: expected 'endpoint NAME {'", lineno);
fclose(fh);
return -1;
}
if (cur) {
snprintf(err, errlen, "line %d: nested endpoint block", lineno);
fclose(fh);
return -1;
}
if (cfg->endpoint_count >= J_MAX_ENDPOINTS) {
snprintf(err, errlen, "more than %d endpoints", J_MAX_ENDPOINTS);
fclose(fh);
return -1;
}
cur = &cfg->endpoints[cfg->endpoint_count++];
endpoint_defaults(cur);
snprintf(cur->name, sizeof cur->name, "%s", w[1]);
continue;
}
int rc = cur ? endpoint_kw(cur, w, n, lineno, err, errlen)
: global_kw(cfg, w, n, lineno, err, errlen);
if (rc) {
fclose(fh);
return -1;
}
}
fclose(fh);
if (cur) {
snprintf(err, errlen, "endpoint %s: block not closed with '}'", cur->name);
return -1;
}
if (!cfg->endpoint_count) {
snprintf(err, errlen, "no 'endpoint NAME {' blocks in %s", path);
return -1;
}
for (int i = 0; i < cfg->endpoint_count; i++) {
j_endpoint *ep = &cfg->endpoints[i];
if (!ep->base[0]) {
snprintf(err, errlen, "endpoint %s: 'base' is required", ep->name);
return -1;
}
if (strncmp(ep->base, "http://", 7) && strncmp(ep->base, "https://", 8)) {
snprintf(err, errlen, "endpoint %s: base must start with http:// or https://", ep->name);
return -1;
}
if (!ep->kind[0]) snprintf(ep->kind, sizeof ep->kind, "remote");
}
for (int i = 0; i < cfg->rule_count; i++) {
j_rule *r = &cfg->rules[i];
for (int t = 0; t < r->target_count; t++) {
int found = 0;
for (int e = 0; e < cfg->endpoint_count; e++)
if (!strcmp(cfg->endpoints[e].name, r->targets[t])) { found = 1; break; }
if (!found) {
snprintf(err, errlen, "line %d: rule passes to unknown endpoint '%s'",
r->line, r->targets[t]);
return -1;
}
}
}
return 0;
}