Docker Compose Validator — C source
Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.
This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.
// compose-validator — structural checks for a Docker Compose file. C port
// (canonical TS: src/lib/compose-validator.ts; Go twin: cli/compose-validator).
// Checks: root/services mappings, per-service image or build, port syntax
// ("8080", "80:8080", "127.0.0.1:80:8080", "6053:53/udp"), environment shape
// (mapping or KEY=value list), volumes lists, depends_on references and
// acyclicity — same rules, paths and message texts as the TS contract. No
// YAML library ships with C, so, like every port in this set, a minimal
// hand-rolled parser covers the compose subset: block mappings/sequences,
// single-line flow collections, quoted and plain scalars, comments.
// Anchors/aliases/merge keys, block scalars (| >), multi-line plain scalars
// and multi-document streams are outside the subset. Never crashes on
// malformed input; parse errors travel in Result.error (NULL mirrors TS
// null). Nodes are malloc'd and deliberately never freed — a one-shot
// display snippet whose result lives as long as the paste.
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct YNode YNode;
typedef struct { char *key; YNode *val; } YKV;
typedef enum { N_NULL, N_BOOL, N_INT, N_FLOAT, N_STR, N_SEQ, N_MAP } YType;
struct YNode { YType type; long long i; double f; char *s; YNode **seq; YKV *kv; size_t n; };
typedef struct { char *path; char *msg; } Issue;
typedef struct { int valid; Issue *issues; size_t n; const char *error; } Result;
static char errbuf[80];
static void fail(const char *m) { if (!errbuf[0]) snprintf(errbuf, sizeof errbuf, "%s", m); }
static char *xstrndup(const char *s, size_t n) { char *p = malloc(n + 1); memcpy(p, s, n); p[n] = 0; return p; }
static char *xstrdup(const char *s) { return xstrndup(s, strlen(s)); }
static char *xsprintf(const char *fmt, ...) {
va_list ap, ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
int n = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
char *p = malloc((size_t)n + 1);
vsnprintf(p, (size_t)n + 1, fmt, ap2);
va_end(ap2);
return p;
}
static YNode *node(YType t) { YNode *v = calloc(1, sizeof *v); v->type = t; return v; }
static void seq_add(YNode *a, YNode *v) { a->seq = realloc(a->seq, (a->n + 1) * sizeof *a->seq); a->seq[a->n++] = v; }
static void map_add(YNode *m, char *k, YNode *v) {
m->kv = realloc(m->kv, (m->n + 1) * sizeof *m->kv);
m->kv[m->n].key = k; m->kv[m->n].val = v; m->n++;
}
/* NULL = key absent; a present null value comes back as an N_NULL node. */
static YNode *map_get(YNode *m, const char *k) {
if (!m || m->type != N_MAP) return NULL;
for (size_t j = 0; j < m->n; j++) if (!strcmp(m->kv[j].key, k)) return m->kv[j].val;
return NULL;
}
/* /^[-+]?[0-9]+$/ and the FLOAT_RE shape, by hand (no std regex). */
static size_t take_digits(const char *t, size_t i) {
size_t s = i;
while (isdigit((unsigned char)t[i])) i++;
return i > s ? i : 0;
}
static int is_int(const char *t) {
size_t i = t[0] == '-' || t[0] == '+' ? 1 : 0, p;
if (!(p = take_digits(t, i))) return 0;
return t[p] == 0;
}
static int is_float(const char *t) {
size_t i = t[0] == '-' || t[0] == '+' ? 1 : 0, p;
if ((p = take_digits(t, i))) {
i = p;
if (t[i] == '.') { size_t q = take_digits(t, i + 1); i = q ? q : i + 1; }
} else if (t[i] == '.' && (p = take_digits(t, i + 1))) i = p;
else return 0;
if (t[i] == 'e' || t[i] == 'E') {
size_t j = t[i + 1] == '-' || t[i + 1] == '+' ? i + 2 : i + 1;
if (!(p = take_digits(t, j))) return 0;
i = p;
}
return t[i] == 0;
}
/* Core-schema resolution of a plain scalar; takes ownership of t. */
static YNode *plain_node(char *t) {
size_t a = 0, b = strlen(t);
while (a < b && isspace((unsigned char)t[a])) a++;
while (b > a && isspace((unsigned char)t[b - 1])) b--;
memmove(t, t + a, b - a);
t[b - a] = 0;
YNode *v = node(N_STR);
if (!t[0] || !strcmp(t, "~") || !strcmp(t, "null") || !strcmp(t, "Null") || !strcmp(t, "NULL")) v->type = N_NULL;
else if (!strcmp(t, "true") || !strcmp(t, "True") || !strcmp(t, "TRUE")) { v->type = N_BOOL; v->i = 1; }
else if (!strcmp(t, "false") || !strcmp(t, "False") || !strcmp(t, "FALSE")) v->type = N_BOOL;
else if (is_int(t)) { v->type = N_INT; v->i = strtoll(t, NULL, 10); }
else if (is_float(t)) { v->type = N_FLOAT; v->f = strtod(t, NULL); }
else v->s = t;
return v;
}
static char *quoted_at(const char *s, size_t i, size_t *ni) {
char q = s[i++];
char *out = malloc(strlen(s + i) + 2);
size_t l = 0;
while (s[i]) {
char ch = s[i];
if (q == '"' && ch == '\\') {
char nxt = s[i + 1];
if (!nxt) { fail("Invalid YAML: unterminated quoted scalar"); return NULL; }
out[l++] = nxt == 'n' ? '\n' : nxt == 't' ? '\t' : nxt == 'r' ? '\r' : nxt;
i += 2;
} else if (ch == q) {
if (q == '\'' && s[i + 1] == '\'') { out[l++] = '\''; i += 2; }
else { out[l] = 0; *ni = i + 1; return out; }
} else { out[l++] = ch; i++; }
}
fail("Invalid YAML: unterminated quoted scalar");
return NULL;
}
static YNode *flow_at(const char *s, size_t i, size_t *ni) {
while (s[i] == ' ') i++;
if (s[i] == '[') {
YNode *out = node(N_SEQ);
i++;
for (;;) {
while (s[i] == ' ') i++;
if (!s[i]) { fail("Invalid YAML: unterminated flow sequence"); return NULL; }
if (s[i] == ']') { *ni = i + 1; return out; }
YNode *v = flow_at(s, i, &i);
if (!v) return NULL;
seq_add(out, v);
while (s[i] == ' ' || s[i] == ',') i++;
}
}
if (s[i] == '{') {
YNode *out = node(N_MAP);
i++;
for (;;) {
while (s[i] == ' ') i++;
if (!s[i]) { fail("Invalid YAML: unterminated flow mapping"); return NULL; }
if (s[i] == '}') { *ni = i + 1; return out; }
char *k;
if (s[i] == '"' || s[i] == '\'') { if (!(k = quoted_at(s, i, &i))) return NULL; }
else {
size_t j = i;
while (s[j] && s[j] != ':' && s[j] != ',' && s[j] != '}') j++;
if (s[j] != ':') { fail("Invalid YAML: flow mapping entry without a colon"); return NULL; }
size_t a = i, b = j;
while (a < b && s[a] == ' ') a++;
while (b > a && s[b - 1] == ' ') b--;
k = xstrndup(s + a, b - a);
i = j + 1;
}
while (s[i] == ' ') i++;
YNode *v = node(N_NULL);
if (s[i] && s[i] != ',' && s[i] != '}') { if (!(v = flow_at(s, i, &i))) return NULL; }
map_add(out, k, v);
while (s[i] == ' ' || s[i] == ',') i++;
}
}
if (s[i] == '"' || s[i] == '\'') {
char *t;
if (!(t = quoted_at(s, i, &i))) return NULL;
*ni = i;
YNode *v = node(N_STR);
v->s = t;
return v;
}
size_t j = i;
while (s[j] && s[j] != ',' && s[j] != ']' && s[j] != '}') j++;
*ni = j;
return plain_node(xstrndup(s + i, j - i));
}
/* `key: rest` split; 0 when the line is not a mapping entry. */
static int key_split(const char *s, char **key, const char **rest) {
if (s[0] == '"' || s[0] == '\'') {
size_t j;
char *k = quoted_at(s, 0, &j);
if (!k) return 0;
while (s[j] == ' ') j++;
if (s[j] != ':') return 0;
*key = k;
*rest = s + j + 1;
return 1;
}
for (size_t j = 0; s[j]; j++)
if (s[j] == ':' && (!s[j + 1] || s[j + 1] == ' ')) {
size_t b = j;
while (b && s[b - 1] == ' ') b--;
*key = xstrndup(s, b);
*rest = s + j + 1;
return 1;
}
return 0;
}
static int flow_trailing(const char *s) { for (; *s; s++) if (*s != ' ' && *s != '#') return 1; return 0; }
static YNode *inline_value(const char *rest) {
size_t j;
if (rest[0] == '[' || rest[0] == '{') {
YNode *v = flow_at(rest, 0, &j);
if (!v) return NULL;
if (flow_trailing(rest + j)) { fail("Invalid YAML: trailing content after flow value"); return NULL; }
return v;
}
if (rest[0] == '"' || rest[0] == '\'') {
char *t = quoted_at(rest, 0, &j);
if (!t) return NULL;
if (flow_trailing(rest + j)) { fail("Invalid YAML: trailing content after quoted value"); return NULL; }
YNode *v = node(N_STR);
v->s = t;
return v;
}
const char *cut = strstr(rest, " #");
return plain_node(cut ? xstrndup(rest, (size_t)(cut - rest)) : xstrdup(rest));
}
typedef struct { size_t ind; char *b; } Line;
/* Content lines as (indent, body): blanks, comments, %directives and a
* --- marker dropped. */
static Line *content_lines(const char *t, size_t *out_n) {
size_t cap = 1, n = 0;
for (const char *p = t; *p; p++) if (*p == '\n') cap++;
Line *ls = malloc(cap * sizeof *ls);
for (const char *p = t;;) {
const char *nl = strchr(p, '\n');
const char *e = nl ? nl : p + strlen(p);
size_t len = (size_t)(e - p);
if (len && p[len - 1] == '\r') len--;
size_t ind = 0;
while (ind < len && p[ind] == ' ') ind++;
size_t bl = len - ind;
while (bl && isspace((unsigned char)p[ind + bl - 1])) bl--;
if (bl && p[ind] != '#' && p[ind] != '%' && !(bl == 3 && !memcmp(p + ind, "---", 3))) {
if (memchr(p, '\t', ind)) fail("Invalid YAML: tab in indentation");
ls[n].ind = ind;
ls[n].b = xstrndup(p + ind, bl);
n++;
}
if (!nl) break;
p = nl + 1;
}
*out_n = n;
return ls;
}
static int is_item(const char *s) { return s[0] == '-' && (s[1] == 0 || s[1] == ' '); }
/* The node whose first line is ls[i] at the given indent; NULL on parse error. */
static YNode *block(Line *ls, size_t *i, size_t n, size_t indent) {
if (is_item(ls[*i].b)) {
YNode *out = node(N_SEQ);
while (*i < n && ls[*i].ind == indent && is_item(ls[*i].b)) {
const char *content = ls[*i].b[1] ? ls[*i].b + 2 : "";
YNode *v;
size_t a = 0;
while (content[a] && isspace((unsigned char)content[a])) a++;
if (!content[a] || content[a] == '#') {
(*i)++;
if (*i < n && ls[*i].ind > indent) v = block(ls, i, n, ls[*i].ind);
else v = node(N_NULL);
} else {
ls[*i].ind = indent + 2;
ls[*i].b += 2;
v = block(ls, i, n, indent + 2);
}
seq_add(out, v);
}
return out;
}
char *k;
const char *r;
if (!key_split(ls[*i].b, &k, &r)) {
YNode *v = inline_value(ls[*i].b);
if (!v) return NULL;
(*i)++;
return v;
}
YNode *out = node(N_MAP);
while (*i < n && ls[*i].ind == indent && !is_item(ls[*i].b) && key_split(ls[*i].b, &k, &r)) {
const char *rs = r;
size_t re = strlen(r);
while (*rs && isspace((unsigned char)*rs)) rs++;
while (re > (size_t)(rs - r) && isspace((unsigned char)r[re - 1])) re--;
char *rest = xstrndup(rs, re - (size_t)(rs - r));
(*i)++;
YNode *v;
if (rest[0]) { if (!(v = inline_value(rest))) return NULL; }
else if (*i < n && ls[*i].ind > indent) { if (!(v = block(ls, i, n, ls[*i].ind))) return NULL; }
else if (*i < n && ls[*i].ind == indent && is_item(ls[*i].b)) { if (!(v = block(ls, i, n, indent))) return NULL; }
else v = node(N_NULL);
map_add(out, k, v);
}
return out;
}
static YNode *parse_yaml(const char *t) {
size_t n, i = 0;
Line *ls = content_lines(t, &n);
if (!n) return NULL;
YNode *v = block(ls, &i, n, ls[0].ind);
if (v && i != n) { fail("Invalid YAML: inconsistent indentation"); return NULL; }
return v;
}
/* Port entries: "8080", "80:8080", "127.0.0.1:80:8080", "::1:8080:80",
* "6053:53/udp" all pass; an issue string or NULL otherwise. */
static char *port_issue(YNode *e) {
if (e->type == N_INT || e->type == N_FLOAT) {
double f = e->type == N_INT ? (double)e->i : e->f;
if (e->type == N_FLOAT && (!isfinite(f) || f != trunc(f)))
return xstrdup("port must be a string or integer");
if (f < 0 || f > 65535) {
if (e->type == N_INT) return xsprintf("port %lld out of range 0-65535", e->i);
return xsprintf("port %.0f out of range 0-65535", f);
}
return NULL;
}
if (e->type != N_STR) return xstrdup("port must be a string or integer");
const char *slash = strchr(e->s, '/');
const char *proto = slash ? slash + 1 : "";
if (proto[0] && strcmp(proto, "tcp") && strcmp(proto, "udp"))
return xsprintf("unknown protocol \"%s\" (use tcp or udp)", proto);
char *body = xstrndup(e->s, slash ? (size_t)(slash - e->s) : strlen(e->s));
size_t np = 0, cap = 4;
char **parts = malloc(cap * sizeof *parts);
for (char *b = body;;) {
if (np == cap) parts = realloc(parts, (cap *= 2) * sizeof *parts);
char *c = strchr(b, ':');
if (c) { parts[np++] = xstrndup(b, (size_t)(c - b)); b = c + 1; }
else { parts[np++] = xstrdup(b); break; }
}
/* Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere. */
for (size_t k = 0; k < np; k++)
if (!parts[k][0] || strspn(parts[k], "0123456789") != strlen(parts[k])) return NULL;
if (np > 3) return xstrdup("port must have 1-3 colon-separated parts");
for (size_t k = 0; k < np; k++) {
long long v = strtoll(parts[k], NULL, 10);
if (v < 0 || v > 65535) return xsprintf("port %s out of range 0-65535", parts[k]);
}
return NULL;
}
/* TS String(value) form for depends_on coercion. */
static char *ts_str(YNode *v) {
switch (v->type) {
case N_NULL: return xstrdup("null");
case N_BOOL: return xstrdup(v->i ? "true" : "false");
case N_INT: return xsprintf("%lld", v->i);
case N_FLOAT:
if (!isfinite(v->f)) return xstrdup("null");
if (v->f == trunc(v->f) && fabs(v->f) < 1e21) return xsprintf("%.0f", v->f);
return xsprintf("%g", v->f);
case N_STR: return xstrdup(v->s);
case N_SEQ: {
char *out = xstrdup("");
size_t l = 0;
for (size_t k = 0; k < v->n; k++) {
char *e = ts_str(v->seq[k]);
size_t el = strlen(e);
out = realloc(out, l + el + 2);
memcpy(out + l, e, el);
l += el;
if (k + 1 < v->n) out[l++] = ',';
out[l] = 0;
}
return out;
}
case N_MAP: return xstrdup("[object Object]");
}
return xstrdup("");
}
typedef struct { Issue *v; size_t n, cap; } Issues;
static void push(Issues *o, const char *path, const char *msg) {
if (o->n == o->cap) o->v = realloc(o->v, (o->cap = o->cap ? o->cap * 2 : 8) * sizeof *o->v);
o->v[o->n].path = xstrdup(path);
o->v[o->n].msg = xstrdup(msg);
o->n++;
}
/* depends_on cycle detection: color 1 open / 2 done; map-form conditions do
* not affect the graph. */
static void visit(YNode *services, long *color, char **stack, size_t depth, char *id, Issues *out) {
size_t idx = 0;
while (strcmp(services->kv[idx].key, id)) idx++;
if (color[idx] == 2) return;
if (color[idx] == 1) {
size_t from = 0;
while (strcmp(stack[from], id)) from++;
size_t len = strlen(id) + 1;
for (size_t k = from; k < depth; k++) len += strlen(stack[k]) + 4;
char *m = malloc(len);
m[0] = 0;
for (size_t k = from; k < depth; k++) { strcat(m, stack[k]); strcat(m, " -> "); }
strcat(m, id);
push(out, "$.services", xsprintf("depends_on cycle: %s", m));
return;
}
color[idx] = 1;
stack[depth] = id;
YNode *svc = services->kv[idx].val;
YNode *dep = svc && svc->type == N_MAP ? map_get(svc, "depends_on") : NULL;
if (dep) {
if (dep->type == N_STR) {
if (map_get(services, dep->s)) visit(services, color, stack, depth + 1, dep->s, out);
} else if (dep->type == N_MAP) {
for (size_t k = 0; k < dep->n; k++)
if (map_get(services, dep->kv[k].key)) visit(services, color, stack, depth + 1, dep->kv[k].key, out);
} else if (dep->type == N_SEQ) {
for (size_t k = 0; k < dep->n; k++)
if (dep->seq[k]->type == N_STR && map_get(services, dep->seq[k]->s))
visit(services, color, stack, depth + 1, dep->seq[k]->s, out);
}
}
color[idx] = 2;
}
/* Walk the document; append issues in TS order (root, services, per-service
* in document order, then cycle detection). */
static void check(YNode *root, Issues *out) {
if (!root || root->type != N_MAP) { push(out, "$", "compose root must be a mapping"); return; }
YNode *services = map_get(root, "services");
if (!services || services->type != N_MAP) { push(out, "$.services", "missing or invalid \"services\" mapping"); return; }
if (!services->n) push(out, "$.services", "services must not be empty");
for (size_t si = 0; si < services->n; si++) {
char *id = services->kv[si].key;
YNode *svc = services->kv[si].val;
char *at = xsprintf("$.services.%s", id);
if (!svc || svc->type != N_MAP) { push(out, at, "service must be a mapping"); continue; }
if (!map_get(svc, "image") && !map_get(svc, "build")) push(out, at, "service needs image or build");
YNode *ports = map_get(svc, "ports");
if (ports) {
if (ports->type != N_SEQ) push(out, xsprintf("%s.ports", at), "ports must be a list");
else for (size_t k = 0; k < ports->n; k++) {
char *m = port_issue(ports->seq[k]);
if (m) push(out, xsprintf("%s.ports[%zu]", at, k), m);
}
}
YNode *env = map_get(svc, "environment");
if (env) {
if (env->type == N_MAP) {
for (size_t k = 0; k < env->n; k++) {
YNode *v = env->kv[k].val;
if (v && v->type != N_NULL && v->type != N_STR && v->type != N_INT && v->type != N_FLOAT && v->type != N_BOOL)
push(out, xsprintf("%s.environment.%s", at, env->kv[k].key), "environment values must be scalars");
}
} else if (env->type == N_SEQ) {
for (size_t k = 0; k < env->n; k++) {
YNode *e = env->seq[k];
const char *eq = e->type == N_STR ? strchr(e->s, '=') : NULL;
if (e->type != N_STR || !eq || eq == e->s)
push(out, xsprintf("%s.environment[%zu]", at, k), "list environment entries must look like KEY=value");
}
} else push(out, xsprintf("%s.environment", at), "environment must be a mapping or a list");
}
YNode *vol = map_get(svc, "volumes");
if (vol && vol->type != N_SEQ) push(out, xsprintf("%s.volumes", at), "volumes must be a list");
YNode *dep = map_get(svc, "depends_on");
if (dep) {
if (dep->type != N_SEQ && dep->type != N_STR && dep->type != N_MAP)
push(out, xsprintf("%s.depends_on", at), "depends_on must be a string, list or mapping");
else {
char **names = malloc((dep->n ? dep->n : 1) * sizeof *names);
size_t nn = 0;
if (dep->type == N_STR) { names = realloc(names, sizeof *names); names[nn++] = dep->s; }
else if (dep->type == N_MAP) for (size_t k = 0; k < dep->n; k++) names[nn++] = dep->kv[k].key;
else for (size_t k = 0; k < dep->n; k++) names[nn++] = ts_str(dep->seq[k]);
for (size_t k = 0; k < nn; k++)
if (!map_get(services, names[k]))
push(out, xsprintf("%s.depends_on[%zu]", at, k), xsprintf("unknown service \"%s\"", names[k]));
}
}
}
long *color = calloc(services->n ? services->n : 1, sizeof *color);
char **stack = malloc((services->n + 1) * sizeof *stack);
for (size_t si = 0; si < services->n; si++)
visit(services, color, stack, 0, services->kv[si].key, out);
}
/* Validate a Docker Compose file. */
Result validate_compose(const char *raw) {
Result r = {0, NULL, 0, NULL};
int blank = 1;
for (const char *p = raw; *p; p++) if (!isspace((unsigned char)*p)) { blank = 0; break; }
if (blank) { r.error = "A compose document is required"; return r; }
errbuf[0] = 0;
YNode *root = parse_yaml(raw);
if (errbuf[0]) { r.error = errbuf; return r; }
Issues out = {NULL, 0, 0};
check(root, &out);
r.valid = out.n == 0;
r.issues = out.v;
r.n = out.n;
return r;
}
int main(void) {
Result ok = validate_compose("services:\n web:\n image: nginx:1.25\n ports:\n - \"8080:80\"\n db:\n image: postgres:16\n depends_on: web");
printf("valid=%d error=%s\n", ok.valid, ok.error ? ok.error : "(none)");
Result bad = validate_compose("services:\n web:\n image: nginx\n ports: [\"99999\"]");
for (size_t i = 0; i < bad.n; i++) printf("%s: %s\n", bad.issues[i].path, bad.issues[i].msg);
Result cyc = validate_compose("services:\n a:\n image: x\n depends_on: b\n b:\n image: y\n depends_on: a");
for (size_t i = 0; i < cyc.n; i++) printf("%s: %s\n", cyc.issues[i].path, cyc.issues[i].msg);
return 0;
}
// Example:
// validate_compose("services:\n web:\n image: nginx:1.25\n ports:\n - \"8080:80\"\n db:\n image: postgres:16\n depends_on: web").valid
// → 1
// validate_compose("services:\n web:\n image: nginx\n ports: [\"99999\"]").issues[0]
// → { path "$.services.web.ports[0]", msg "port 99999 out of range 0-65535" }
// validate_compose("services:\n a:\n image: x\n depends_on: b\n b:\n image: y\n depends_on: a").issues[0]
// → { path "$.services", msg "depends_on cycle: a -> b -> a" }
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →