/*
* cgi.h — shared CGI helpers for the fleet's MCP daemons.
*
* Header-only. Include libmcp's mcp.h first (with MCP_IMPLEMENTATION in
* exactly one translation unit); this file uses mcp_buf and the JSON parser.
*
* What it gives a CGI program:
* - CGI environment: base URL, PATH_INFO/REQUEST_URI routing, POST body
* - HTML 4.01 shell with a common navigation across the fleet UIs
* - escaping, URL decoding, form parameters
* - a minimal Markdown renderer
* - cg_rpc(): one MCP tools/call over HTTP via curl
*
* Every daemon answers with result.content[0].text. Text replies stay text;
* JSON replies are parsed by the caller with cg_rpc_json().
*/
#ifndef FLEET_CGI_H
#define FLEET_CGI_H
#include
#include
#include
#include
#include
#if defined(__GNUC__)
#define CG_UNUSED __attribute__((unused))
#else
#define CG_UNUSED
#endif
/* ------------------------------------------------------------------ escaping */
static CG_UNUSED void cg_html(const char *s)
{
for (; s != NULL && *s; s++) {
switch (*s) {
case '&': fputs("&", stdout); break;
case '<': fputs("<", stdout); break;
case '>': fputs(">", stdout); break;
case '"': fputs(""", stdout); break;
default: putchar(*s); break;
}
}
}
static CG_UNUSED void cg_html_n(const char *s, size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
switch (s[i]) {
case '&': fputs("&", stdout); break;
case '<': fputs("<", stdout); break;
case '>': fputs(">", stdout); break;
case '"': fputs(""", stdout); break;
default: putchar(s[i]); break;
}
}
}
static CG_UNUSED char *cg_url_decode(char *s)
{
char *r = s, *w = s;
for (; *r; r++, w++) {
if (*r == '+') {
*w = ' ';
} else if (*r == '%' && isxdigit((unsigned char)r[1]) &&
isxdigit((unsigned char)r[2])) {
char hex[3] = { r[1], r[2], 0 };
*w = (char)strtol(hex, NULL, 16);
r += 2;
} else {
*w = *r;
}
}
*w = '\0';
return s;
}
/* Copy one URL-encoded parameter out of qs. malloc'd; caller frees. */
static CG_UNUSED char *cg_param(const char *qs, const char *name)
{
size_t nlen = strlen(name);
for (const char *p = qs; p != NULL && *p; ) {
if (strncmp(p, name, nlen) == 0 && p[nlen] == '=') {
const char *val = p + nlen + 1;
const char *end = strchr(val, '&');
size_t vlen = end != NULL ? (size_t)(end - val) : strlen(val);
char *out = malloc(vlen + 1);
if (out == NULL)
return NULL;
memcpy(out, val, vlen);
out[vlen] = '\0';
cg_url_decode(out);
return out;
}
p = strchr(p, '&');
if (p != NULL)
p++;
}
return NULL;
}
/* ------------------------------------------------------------------- env */
static CG_UNUSED const char *cg_method(void)
{
const char *m = getenv("REQUEST_METHOD");
return (m != NULL && *m != '\0') ? m : "GET";
}
/* "" at the root, otherwise SCRIPT_NAME ("/cgi-bin/memoryd-http"). */
static CG_UNUSED const char *cg_base(void)
{
static char base[256];
static int done;
if (!done) {
const char *s = getenv("SCRIPT_NAME");
base[0] = '\0';
if (s != NULL && *s != '\0' && strcmp(s, "/") != 0)
snprintf(base, sizeof(base), "%s", s);
done = 1;
}
return base;
}
/* Percent-encode a query-string value (letters, digits and -_.~/ stay). */
static CG_UNUSED void cg_urlenc(const char *s)
{
for (; s != NULL && *s; s++) {
unsigned char c = (unsigned char)*s;
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~' ||
c == '/')
putchar(c);
else
printf("%%%02X", c);
}
}
/* Print an internal link target (base + suffix). */
static CG_UNUSED void cg_link(const char *suffix)
{
fputs(cg_base(), stdout);
fputs(suffix, stdout);
}
/* PATH_INFO when the server provides it, else REQUEST_URI minus base. */
static CG_UNUSED void cg_route(char *path, size_t pathlen, char *query, size_t querylen)
{
const char *uri = getenv("REQUEST_URI");
const char *pi = getenv("PATH_INFO");
const char *qs = getenv("QUERY_STRING");
const char *base = cg_base();
size_t i;
if (uri == NULL)
uri = "/";
if (pi != NULL && *pi != '\0') {
uri = pi;
} else if (*base != '\0' && strncmp(uri, base, strlen(base)) == 0) {
uri += strlen(base);
if (*uri == '\0')
uri = "/";
}
snprintf(path, pathlen, "%s", uri);
for (i = 0; path[i] != '\0' && path[i] != '?'; i++)
;
if (path[i] == '?') {
if (querylen > 0)
snprintf(query, querylen, "%s", path + i + 1);
path[i] = '\0';
} else if (querylen > 0) {
query[0] = '\0';
}
if (querylen > 0 && query[0] == '\0' && qs != NULL && *qs != '\0')
snprintf(query, querylen, "%s", qs);
}
static CG_UNUSED char *cg_read_body(void)
{
const char *cl = getenv("CONTENT_LENGTH");
long len;
char *body;
size_t got = 0;
if (cl == NULL)
return NULL;
len = strtol(cl, NULL, 10);
if (len <= 0 || len > 1024 * 1024)
return NULL;
body = malloc((size_t)len + 1);
if (body == NULL)
return NULL;
while (got < (size_t)len) {
size_t r = fread(body + got, 1, (size_t)len - got, stdin);
if (r == 0)
break;
got += r;
}
body[got] = '\0';
return body;
}
static CG_UNUSED void cg_header(void)
{
printf("Content-Type: text/html; charset=utf-8\r\n\r\n");
}
/* --------------------------------------------------------------- chrome */
struct cg_app {
const char *file;
const char *label;
};
static CG_UNUSED const struct cg_app cg_apps[] = {
{ "wikid-http", "Wiki" },
{ "memoryd-http", "Memories" },
{ "skilld-http", "Skills" },
{ "tasksd-http", "Tasks" },
};
static CG_UNUSED void cg_nav(const char *active)
{
char dir[256] = "";
const char *base = cg_base();
const char *slash = strrchr(base, '/');
const char *here = slash != NULL ? slash + 1 : base;
if (slash != NULL) {
size_t n = (size_t)(slash - base) + 1;
if (n >= sizeof(dir))
n = sizeof(dir) - 1;
memcpy(dir, base, n);
dir[n] = '\0';
}
fputs("\n", stdout);
}
static CG_UNUSED const char *cg_css =
"body{font-family:serif;margin:1.5em;max-width:76em;background:#fff;color:#222}\n"
"h1,h2,h3,h4{margin-top:1.1em;margin-bottom:0.35em}\n"
"a{color:#0055aa;text-decoration:none}\n"
"a:hover{text-decoration:underline}\n"
"code{background:#f4f4f4;padding:0.08em 0.25em;font-size:0.92em}\n"
"pre{background:#f7f7f7;border:1px solid #ddd;padding:0.7em;overflow:auto;font-size:0.9em}\n"
"textarea{width:100%;max-width:72em;font-family:monospace;font-size:0.95em}\n"
"input[type=text]{max-width:62em;width:100%;font-family:monospace}\n"
".topnav{border-bottom:2px solid #ccc;padding-bottom:0.45em;margin-bottom:1.2em}\n"
".topnav a{margin-right:1.2em;font-size:1.05em}\n"
".meta{color:#666;font-size:0.86em}\n"
".item{border-bottom:1px solid #e6e6e6;padding:0.65em 0}\n"
".head{font-size:0.95em}\n"
".scope{color:#0055aa}\n"
".actions{margin-top:0.35em;font-size:0.9em}\n"
".actions a,.actions form{display:inline-block;margin-right:0.9em}\n"
".actions input[type=submit]{font-size:0.85em}\n"
"form.inline{display:inline}\n"
"table.list{border-collapse:collapse;width:100%;margin:0.7em 0}\n"
"table.list td,table.list th{border-bottom:1px solid #ddd;padding:0.3em 0.55em;text-align:left;vertical-align:top}\n"
"table.list th{background:#f2f2f2}\n"
".state{display:inline-block;padding:0.02em 0.45em;border:1px solid #999;font-size:0.78em;text-transform:uppercase;letter-spacing:0.03em}\n"
".s-pending{background:#fff;color:#333}\n"
".s-running{background:#e6f2ff;color:#004c99}\n"
".s-paused{background:#fff6d8;color:#7a5c00}\n"
".s-done{background:#e8f8e8;color:#1a661a}\n"
".s-dropped{background:#f0f0f0;color:#777}\n"
".msg{border-left:4px solid #9c9;background:#f4faf4;padding:0.5em 0.8em;margin:0.8em 0}\n"
".err{border-left:4px solid #c66;background:#fdf4f4;padding:0.5em 0.8em;margin:0.8em 0;color:#800}\n";
static CG_UNUSED void cg_head(const char *active, const char *title)
{
fputs("\n"
"\n\n"
"\n"
"", stdout);
cg_html(title);
fputs("\n\n\n\n", stdout);
cg_nav(active);
}
static CG_UNUSED void cg_foot(void)
{
fputs("\n\n", stdout);
}
static CG_UNUSED void cg_error_page(const char *active, const char *title, const char *msg)
{
cg_head(active, title);
fputs("", stdout);
cg_html(title);
fputs("
\n", stdout);
cg_html(msg != NULL ? msg : "unknown error");
fputs("
\n", stdout);
cg_foot();
}
static CG_UNUSED void cg_pre(const char *s)
{
fputs("", stdout);
cg_html(s != NULL ? s : "");
fputs("\n", stdout);
}
static CG_UNUSED void cg_time(long t)
{
time_t tt = (time_t)t;
struct tm tm;
char buf[32];
if (t <= 0) {
fputs("-", stdout);
return;
}
if (localtime_r(&tt, &tm) == NULL) {
printf("%ld", t);
return;
}
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", &tm);
fputs(buf, stdout);
}
/* --------------------------------------------------------------- markdown */
static CG_UNUSED void cg_put_esc(char c)
{
switch (c) {
case '&': fputs("&", stdout); break;
case '<': fputs("<", stdout); break;
case '>': fputs(">", stdout); break;
case '"': fputs(""", stdout); break;
default: putchar(c); break;
}
}
static CG_UNUSED void cg_md_inline(const char **pp)
{
const char *p = *pp;
while (*p != '\0' && *p != '\n') {
if (*p == '*' && p[1] == '*') {
fputs("", stdout);
p += 2;
while (*p != '\0' && !(*p == '*' && p[1] == '*') && *p != '\n')
cg_put_esc(*p++);
if (*p == '*')
p++;
fputs("", stdout);
} else if (*p == '*') {
fputs("", stdout);
p++;
while (*p != '\0' && *p != '*' && *p != '\n')
cg_put_esc(*p++);
if (*p == '*')
p++;
fputs("", stdout);
} else if (*p == '`') {
if (p[1] == '`') {
p += 2; /* empty span, emit nothing */
continue;
}
fputs("", stdout);
p++;
while (*p != '\0' && *p != '`' && *p != '\n')
cg_put_esc(*p++);
if (*p == '`')
p++;
fputs("", stdout);
} else if (*p == '&') {
fputs("&", stdout);
p++;
} else if (*p == '<') {
fputs("<", stdout);
p++;
} else if (*p == '>') {
fputs(">", stdout);
p++;
} else {
putchar(*p++);
}
}
*pp = p;
}
static CG_UNUSED void cg_md(const char *text)
{
const char *p = text;
int in_para = 0, in_list = 0;
if (text == NULL)
return;
while (*p != '\0') {
if (strncmp(p, "```", 3) == 0) {
const char *eol = strchr(p, '\n');
const char *code, *end, *stop;
if (eol == NULL) {
p += 3;
continue;
}
code = eol + 1;
stop = strstr(code, "\n```");
end = stop != NULL ? stop : code + strlen(code);
if (in_para) { fputs("
\n", stdout); in_para = 0; }
if (in_list) { fputs("\n", stdout); in_list = 0; }
fputs("", stdout);
cg_html_n(code, (size_t)(end - code));
fputs("\n", stdout);
if (stop != NULL) {
p = stop + 4;
while (*p == '\n')
p++;
} else {
p = end;
}
continue;
}
if (*p == '#') {
int level = 0;
while (*p == '#') {
level++;
p++;
}
while (*p == ' ')
p++;
if (in_para) { fputs("\n", stdout); in_para = 0; }
if (in_list) { fputs("\n", stdout); in_list = 0; }
if (level > 6)
level = 6;
printf("", level);
cg_md_inline(&p);
printf("\n", level);
continue;
}
if (*p == '-' && (p[1] == ' ' || p[1] == '\t')) {
if (in_para) { fputs("\n", stdout); in_para = 0; }
if (!in_list) { fputs("\n", stdout); in_list = 1; }
fputs("- ", stdout);
p += 2;
cg_md_inline(&p);
fputs("
\n", stdout);
continue;
}
if (strncmp(p, "---", 3) == 0 && (p[3] == '\n' || p[3] == '\0')) {
if (in_para) { fputs("\n", stdout); in_para = 0; }
if (in_list) { fputs("
\n", stdout); in_list = 0; }
fputs("
\n", stdout);
p += 3;
while (*p == '\n')
p++;
continue;
}
if (*p == '\n') {
if (in_para) {
fputs("\n", stdout);
in_para = 0;
} else if (in_list && (p[1] == '\n' || p[1] == '\0')) {
fputs("\n", stdout);
in_list = 0;
}
p++;
continue;
}
if (!in_para) {
if (in_list) { fputs("\n", stdout); in_list = 0; }
fputs("", stdout);
in_para = 1;
}
cg_md_inline(&p);
if (*p == '\n') {
if (p[1] != '\n' && p[1] != '\0')
fputs("
\n", stdout);
p++;
}
}
if (in_para)
fputs("
\n", stdout);
if (in_list)
fputs("\n", stdout);
}
/* ------------------------------------------------------------------ JSON args */
static CG_UNUSED void cg_args_add_str(mcp_buf *b, int *first, const char *key,
const char *val)
{
if (val == NULL)
return;
if (!*first)
mcp_buf_puts(b, ",");
*first = 0;
mcp_buf_printf(b, "\"%s\":\"", key);
mcp_json_escape(b, val);
mcp_buf_puts(b, "\"");
}
static CG_UNUSED void cg_args_add_int(mcp_buf *b, int *first, const char *key, int val)
{
if (!*first)
mcp_buf_puts(b, ",");
*first = 0;
mcp_buf_printf(b, "\"%s\":%d", key, val);
}
static CG_UNUSED void cg_args_add_bool(mcp_buf *b, int *first, const char *key, int val)
{
if (!*first)
mcp_buf_puts(b, ",");
*first = 0;
mcp_buf_printf(b, "\"%s\":%s", key, val ? "true" : "false");
}
/* -------------------------------------------------------------------- RPC */
static CG_UNUSED void cg_shell_quote(mcp_buf *b, const char *s)
{
mcp_buf_puts(b, "'");
for (; s != NULL && *s; s++) {
if (*s == '\'')
mcp_buf_puts(b, "'\\''");
else
mcp_buf_add(b, s, 1);
}
mcp_buf_puts(b, "'");
}
/* One tools/call. Returns the text reply (malloc'd) or NULL. */
static CG_UNUSED char *cg_rpc(const char *env, const char *dflt, const char *tool,
const char *args)
{
mcp_buf body, cmd, raw;
const char *url;
FILE *fp;
char chunk[4096];
size_t got;
mcp_json *v;
const mcp_json *result, *content, *first;
const char *text;
char *out = NULL;
url = (env != NULL) ? getenv(env) : NULL;
if (url == NULL || *url == '\0')
url = dflt;
mcp_buf_init(&body);
mcp_buf_puts(&body, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","
"\"params\":{\"name\":\"");
mcp_json_escape(&body, tool);
mcp_buf_puts(&body, "\",\"arguments\":");
mcp_buf_puts(&body, (args != NULL && *args != '\0') ? args : "{}");
mcp_buf_puts(&body, "}}");
mcp_buf_init(&cmd);
mcp_buf_puts(&cmd, "curl -sS -m 120 -X POST "
"-H 'Content-Type: application/json' -d ");
cg_shell_quote(&cmd, body.p != NULL ? body.p : "{}");
mcp_buf_puts(&cmd, " ");
cg_shell_quote(&cmd, url);
mcp_buf_puts(&cmd, " 2>/dev/null");
mcp_buf_free(&body);
fp = popen(cmd.p != NULL ? cmd.p : "true", "r");
mcp_buf_free(&cmd);
if (fp == NULL)
return NULL;
mcp_buf_init(&raw);
while ((got = fread(chunk, 1, sizeof(chunk), fp)) > 0) {
mcp_buf_add(&raw, chunk, got);
if (raw.p == NULL)
break;
}
pclose(fp);
if (raw.p == NULL) {
mcp_buf_free(&raw);
return NULL;
}
v = mcp_parse(raw.p);
mcp_buf_free(&raw);
if (v == NULL)
return NULL;
result = mcp_arg(v, "result");
content = mcp_arg(result, "content");
first = mcp_array_at(content, 0);
text = mcp_arg_string(first, "text");
if (text == NULL) {
const mcp_json *err = mcp_arg(v, "error");
text = mcp_arg_string(err, "message");
}
if (text != NULL)
out = strdup(text);
mcp_json_free(v);
return out;
}
/* tools/call whose text reply is JSON. Caller frees with mcp_json_free(). */
static CG_UNUSED mcp_json *cg_rpc_json(const char *env, const char *dflt,
const char *tool, const char *args)
{
char *text = cg_rpc(env, dflt, tool, args);
mcp_json *v;
if (text == NULL)
return NULL;
v = mcp_parse(text);
free(text);
return v;
}
#endif /* FLEET_CGI_H */