diff --git a/.gitignore b/.gitignore
index 718e418..30b5bee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
wikid
+wikid-http
*.o
diff --git a/Makefile b/Makefile
index 031960b..def6310 100644
--- a/Makefile
+++ b/Makefile
@@ -2,20 +2,27 @@ CC ?= cc
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror
LIBDIR ?= vendor/libmcp
PREFIX ?= /usr/local
+CGIDIR ?= $(PREFIX)/lib/cgi-bin
-all: wikid
+all: wikid wikid-http
wikid: wikid.c $(LIBDIR)/mcp.h
$(CC) $(CFLAGS) -I$(LIBDIR) -o $@ wikid.c -lm
-test: wikid
- ./tests/run.sh
+wikid-http: wikid-http.c
+ $(CC) $(CFLAGS) -o $@ wikid-http.c
-install: wikid
+test: wikid wikid-http
+ ./tests/run.sh
+ ./tests/test-http.sh
+
+install: wikid wikid-http
mkdir -p $(DESTDIR)$(PREFIX)/bin
cp wikid $(DESTDIR)$(PREFIX)/bin/
+ install -d $(DESTDIR)$(CGIDIR)
+ install -m 0755 wikid-http $(DESTDIR)$(CGIDIR)/wikid-http
clean:
- rm -f wikid
+ rm -f wikid wikid-http
.PHONY: all test install clean
diff --git a/README.md b/README.md
index 37ceb0a..77519e0 100644
--- a/README.md
+++ b/README.md
@@ -60,8 +60,9 @@ Zwei Entscheidungen, die den Unterschied zu einem Dateiordner ausmachen:
## Bauen und prüfen
```sh
-make && make test # 26 Prüfungen gegen den laufenden Dienst
-sudo make install # /usr/local/bin/wikid
+make # wikid und wikid-http
+make test # MCP- und CGI-Prüfungen
+sudo make install # /usr/local/bin/wikid, /usr/local/lib/cgi-bin/wikid-http
```
`make test` startet den Dienst auf einem freien Port mit einem **deterministischen
@@ -69,7 +70,51 @@ Embedder-Stub** (Buchstabenzählung statt Modell) und prüft über HTTP und stdi
dem Namen, Aktualisierung statt Dublette, lesbarer Verlauf, Suche über alle Basen und
innerhalb einer, Löschen, `confirm`-Pflicht, den Rückfall ohne Embedder — und, wenn git
installiert ist, dass jede Änderung ein Commit ist und eine alte Fassung aus git
-zurückkommt.
+zurückkommt. Danach prüft `tests/test-http.sh` die CGI-Oberfläche gegen denselben Dienst.
+
+## Web-Oberfläche (CGI)
+
+`wikid-http` ist ein C99-CGI-Programm und **die einzige Stelle, die HTML schreibt**. Es
+liest keine Dateien selbst: jede Liste, jede Suche, jedes Lesen und Schreiben geht als
+JSON-RPC an den MCP-Server von wikid (`WIKID_URL`, Vorgabe
+`http://127.0.0.1:8796/mcp`). Damit sehen Mensch und Agent dieselbe Wiki — es gibt keinen
+zweiten Weg in die Ablage, der auseinanderlaufen könnte. Kein JavaScript, kein Zustand,
+kein Login; die Oberfläche ist für ein vertrauenswürdiges Netz gedacht.
+
+| Adresse | Wirkung |
+|---|---|
+| `/` bzw. `/wikid/` | alle Basen (`wiki_list`) |
+| `/wikid//` | Seiten einer Basis (`page_list`) |
+| `/wikid//` | eine Seite, per ID oder Titel (`page_read`, mit Verlauf) |
+| `/wikid/search?q=…` | Suche über alle Basen (`wiki_search`) |
+| `/wikid//write` | Formular und `page_write` |
+| `/wikid/create` | Formular und `wiki_create` |
+
+Ein Beispiel mit busybox httpd:
+
+```sh
+install -d /srv/data/media/wikid-web/cgi-bin
+install -m 0755 wikid-http /srv/data/media/wikid-web/cgi-bin/
+WIKID_URL=http://127.0.0.1:8796/mcp \
+ busybox httpd -f -p 0.0.0.0:8798 -h /srv/data/media/wikid-web
+```
+
+Die Oberfläche liegt dann unter `http://:8798/cgi-bin/wikid-http` (busybox setzt
+`PATH_INFO`; das Programm erkennt `SCRIPT_NAME` und schreibt alle Links entsprechend).
+`WIKID_URL` muss die Umgebung des CGI-Prozesses erreichen — bei busybox httpd also im
+Startbefehl setzen (oder in der Unit), nicht nur in der Shell davor.
+
+Als Dienst:
+
+```sh
+sudo cp packaging/wikid-web.service /etc/systemd/system/
+sudo systemctl daemon-reload && sudo systemctl enable --now wikid-web
+```
+
+Standardmäßig lauscht er auf `0.0.0.0:8798`; ohne Anmeldung darf jedes Gerät im Netz
+lesen, schreiben und löschen — die Oberfläche gehört deshalb in ein vertrauenswürdiges
+Netz oder hinter eine Firewall.
+
## Embedder
diff --git a/packaging/wikid-web.service b/packaging/wikid-web.service
new file mode 100644
index 0000000..f634578
--- /dev/null
+++ b/packaging/wikid-web.service
@@ -0,0 +1,21 @@
+[Unit]
+Description=fleet-web — CGI-Oberflächen für wikid, memoryd, skilld, tasksd (busybox httpd)
+After=network-online.target wikid.service memoryd.service skilld.service tasksd.service
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=lotherk
+Group=lotherk
+# Die Oberfläche liest und schreibt ausschließlich über den MCP-Server von wikid.
+Environment=WIKID_URL=http://127.0.0.1:8796/mcp
+Environment=MEMORYD_URL=http://127.0.0.1:8795/mcp
+Environment=SKILLD_URL=http://127.0.0.1:8790/mcp
+Environment=TASKSD_URL=http://127.0.0.1:8781/mcp
+ExecStart=/usr/bin/busybox httpd -f -p 0.0.0.0:8798 -h /srv/data/media/wikid-web
+Restart=always
+RestartSec=3
+NoNewPrivileges=yes
+
+[Install]
+WantedBy=multi-user.target
diff --git a/tests/test-http.sh b/tests/test-http.sh
new file mode 100755
index 0000000..a76233f
--- /dev/null
+++ b/tests/test-http.sh
@@ -0,0 +1,107 @@
+#!/bin/sh
+# Prüft wikid-http als CGI gegen einen laufenden wikid.
+# Kein Web-Server nötig: die CGI-Umgebung wird von Hand gesetzt.
+set -eu
+
+cd "$(dirname "$0")/.."
+
+PORT=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()')
+DIR=$(mktemp -d)
+LOG="$DIR/wikid.log"
+PID=
+
+cleanup() {
+ [ -n "$PID" ] && kill "$PID" 2>/dev/null || true
+ [ -n "$PID" ] && wait "$PID" 2>/dev/null || true
+ rm -rf "$DIR"
+}
+trap cleanup EXIT INT TERM
+
+WIKIDIR="$DIR/data" ./wikid --http "127.0.0.1:$PORT" >"$LOG" 2>&1 &
+PID=$!
+
+for _ in $(seq 1 50); do
+ curl -s -o /dev/null "http://127.0.0.1:$PORT/mcp" -X POST \
+ -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' \
+ && break
+ sleep 0.1
+done
+
+export WIKID_URL="http://127.0.0.1:$PORT/mcp"
+
+cgi() {
+ method=$1
+ uri=$2
+ if [ "$method" = POST ]; then
+ body=$3
+ printf '%s' "$body" | \
+ REQUEST_METHOD=POST REQUEST_URI="$uri" QUERY_STRING='' \
+ CONTENT_LENGTH=${#body} ./wikid-http
+ else
+ REQUEST_METHOD=GET REQUEST_URI="$uri" QUERY_STRING='' ./wikid-http
+ fi
+}
+
+fail() {
+ echo "FAIL: $*" >&2
+ exit 1
+}
+
+# 1. Leere Welt
+cgi GET / >"$DIR/out"
+grep -q 'no knowledge bases yet' "$DIR/out" || fail "empty index"
+grep -q 'Content-Type: text/html' "$DIR/out" || fail "content type"
+
+# 2. Wiki anlegen
+cgi POST /wikid/create 'name=Field+Notes&description=Procedures' >"$DIR/out"
+grep -q 'created knowledge base' "$DIR/out" || fail "create wiki"
+
+# 3. Seite schreiben
+cgi POST /wikid/field-notes/write \
+ 'title=Water+chlorination&text=Two+drops+of+bleach+per+litre.&tags=water&source=manual' >"$DIR/out"
+grep -q 'created field-notes/e00001' "$DIR/out" || fail "write page"
+
+# 4. Wiki-Index zeigt die Basis als Link
+cgi GET / >"$DIR/out"
+grep -q 'href="/wikid/field-notes/"' "$DIR/out" || fail "wiki link"
+grep -q 'Field Notes' "$DIR/out" || fail "wiki description"
+
+# 5. Seitenliste zeigt die Seite
+cgi GET /wikid/field-notes/ >"$DIR/out"
+grep -q 'Water chlorination' "$DIR/out" || fail "page in list"
+
+# 6. Seite per ID lesen
+cgi GET /wikid/field-notes/e00001 >"$DIR/out"
+grep -q 'Two drops of bleach per litre' "$DIR/out" || fail "read by id"
+
+# 7. Seite per (URL-kodiertem) Titel lesen
+cgi GET '/wikid/field-notes/Water%20chlorination' >"$DIR/out"
+grep -q 'Water chlorination' "$DIR/out" || fail "read by title"
+grep -q 'no page' "$DIR/out" && fail "title fallback did not happen"
+
+# 8. Suche
+cgi GET '/wikid/search?q=bleach' >"$DIR/out"
+grep -q 'href="/wikid/field-notes/e00001"' "$DIR/out" || fail "search link"
+grep -q 'hit(s)' "$DIR/out" || fail "search summary"
+
+# 9. Löschen braucht POST und entfernt die Seite
+cgi POST /wikid/field-notes/delete 'title=Water+chlorination' >"$DIR/out"
+grep -q 'deleted field-notes/e00001' "$DIR/out" || fail "delete page"
+cgi GET /wikid/field-notes/ >"$DIR/out"
+grep -q 'Water chlorination' "$DIR/out" && fail "deleted page still listed"
+true
+
+# 10. Unbekannte Route ist eine 404-Seite, kein Absturz
+cgi GET /nope >"$DIR/out"
+grep -q 'Not found' "$DIR/out" || fail "404 page"
+
+# 11. Unter /cgi-bin/wikid-http eingehängt (busybox httpd)
+REQUEST_METHOD=GET SCRIPT_NAME=/cgi-bin/wikid-http PATH_INFO=/ \
+ REQUEST_URI=/cgi-bin/wikid-http/ ./wikid-http >"$DIR/out"
+grep -q 'href="/cgi-bin/wikid-http/wikid/search"' "$DIR/out" || fail "prefix links"
+REQUEST_METHOD=GET SCRIPT_NAME=/cgi-bin/wikid-http PATH_INFO=/wikid/search \
+ REQUEST_URI=/cgi-bin/wikid-http/wikid/search QUERY_STRING='' \
+ ./wikid-http >"$DIR/out"
+grep -q 'Search
' "$DIR/out" || fail "prefix routing"
+
+echo "wikid-http: ok"
diff --git a/wikid-cgi.c b/wikid-cgi.c
new file mode 100644
index 0000000..0ca9624
--- /dev/null
+++ b/wikid-cgi.c
@@ -0,0 +1,719 @@
+/*
+ * wikid-cgi — C99 CGI binary that serves wikid data as HTML 4.01.
+ *
+ * Usage: placed in a CGI bin directory (e.g. /usr/lib/cgi-bin/), invoked
+ * by the web server. Reads the wiki data directory and serves:
+ *
+ * /wikid/ — list of all wikis
+ * /wikid// — pages in a wiki
+ * /wikid// — one page
+ * /wikid/search?q=… — search results
+ *
+ * Data source: $WIKIDIR (same as wikid). Falls back to ~/.local/share/wikid.
+ *
+ * Build:
+ * cc -std=c99 -O2 -Wall -Wextra -Wpedantic -D_POSIX_C_SOURCE=200809L \
+ * -D_DEFAULT_SOURCE -o wikid-cgi wikid-cgi.c
+ */
+#define _POSIX_C_SOURCE 200809L
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define MAX_TEXT 16384
+#define MAX_SLUG 256
+#define MAX_TITLE 512
+#define MAX_PATH 1024
+
+/* ── string buffer (append-only) ──────────────────────────────────── */
+
+typedef struct {
+ char *p;
+ size_t len;
+ size_t cap;
+} cgi_buf;
+
+static void cgi_buf_init(cgi_buf *b)
+{
+ b->p = NULL;
+ b->len = 0;
+ b->cap = 0;
+}
+
+static void cgi_buf_free(cgi_buf *b)
+{
+ free(b->p);
+ cgi_buf_init(b);
+}
+
+static int cgi_buf_grow(cgi_buf *b, size_t need)
+{
+ size_t newcap = b->cap ? b->cap * 2 : 256;
+ while (newcap < b->len + need)
+ newcap *= 2;
+ {
+ char *q = realloc(b->p, newcap);
+ if (!q)
+ return -1;
+ b->p = q;
+ b->cap = newcap;
+ }
+ return 0;
+}
+
+static int cgi_buf_add(cgi_buf *b, const char *data, size_t n)
+{
+ if (n == 0)
+ return 0;
+ if (cgi_buf_grow(b, n) != 0)
+ return -1;
+ memcpy(b->p + b->len, data, n);
+ b->len += n;
+ return 0;
+}
+
+static int cgi_buf_puts(cgi_buf *b, const char *s)
+{
+ return cgi_buf_add(b, s, strlen(s));
+}
+
+static int cgi_buf_printf(cgi_buf *b, const char *fmt, ...)
+{
+ char tmp[4096];
+ va_list ap;
+ int n;
+
+ va_start(ap, fmt);
+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
+ va_end(ap);
+ if (n < 0)
+ return -1;
+ if (n == 0)
+ return 0;
+ if (cgi_buf_grow(b, (size_t)n) != 0)
+ return -1;
+ memcpy(b->p + b->len, tmp, (size_t)n);
+ b->len += (size_t)n;
+ return 0;
+}
+
+/* ── small io helpers ─────────────────────────────────────────────── */
+
+static char *read_file(const char *path)
+{
+ FILE *f = fopen(path, "rb");
+ cgi_buf b;
+ char tmp[4096];
+ size_t n;
+
+ if (!f)
+ return NULL;
+ cgi_buf_init(&b);
+ while ((n = fread(tmp, 1, sizeof(tmp), f)) > 0)
+ cgi_buf_add(&b, tmp, n);
+ fclose(f);
+ if (!b.p)
+ cgi_buf_add(&b, "", 0);
+ return b.p;
+}
+
+static char *json_str(const char *json, const char *key)
+{
+ char pat[512];
+ const char *p, *v;
+ size_t klen;
+
+ if (!json || !key)
+ return NULL;
+ klen = strlen(key);
+ if (klen == 0 || klen > 250)
+ return NULL;
+ snprintf(pat, sizeof(pat), "\"%s\":", key);
+ p = strstr(json, pat);
+ if (!p)
+ return NULL;
+ p += klen + 2;
+ while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
+ p++;
+ if (*p != '"')
+ return NULL;
+ p++;
+ v = p;
+ while (*p && *p != '"')
+ p++;
+ if (!*p)
+ return NULL;
+ return strndup(v, (size_t)(p - v));
+}
+
+static long json_num(const char *json, const char *key, long def)
+{
+ const char *p;
+ char pat[512];
+ size_t klen;
+
+ if (!json || !key)
+ return def;
+ klen = strlen(key);
+ if (klen == 0 || klen > 250)
+ return def;
+ snprintf(pat, sizeof(pat), "\"%s\":", key);
+ p = strstr(json, pat);
+ if (!p)
+ return def;
+ p += klen + 2;
+ while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
+ p++;
+ if (*p == '-' || (*p >= '0' && *p <= '9')) {
+ long val = strtol(p, (char **)&p, 10);
+ return val;
+ }
+ return def;
+}
+
+/* ── wiki root ────────────────────────────────────────────────────── */
+
+static char *wiki_root(void)
+{
+ const char *env;
+ char *result;
+
+ env = getenv("WIKIDIR");
+ if (!env || !*env)
+ env = getenv("WIKID_HOME");
+ if (env && *env) {
+ result = strdup(env);
+ return result;
+ }
+
+ {
+ const char *home = getenv("HOME");
+ if (!home)
+ home = "/tmp";
+ {
+ const char *xdg = getenv("XDG_DATA_HOME");
+ if (xdg && *xdg)
+ result = malloc(strlen(xdg) + 9);
+ else
+ result = malloc(strlen(home) + 22);
+ if (xdg && *xdg)
+ sprintf(result, "%s/wikid", xdg);
+ else
+ sprintf(result, "%s/.local/share/wikid", home);
+ return result;
+ }
+ }
+}
+
+/* ── entry (wiki page) ───────────────────────────────────────────── */
+
+struct entry {
+ char *id;
+ char *title;
+ char *text;
+ char *tags;
+ char *source;
+ long created;
+ long updated;
+ int dim;
+};
+
+static void free_entry(struct entry *e)
+{
+ if (!e)
+ return;
+ free(e->id);
+ free(e->title);
+ free(e->text);
+ free(e->tags);
+ free(e->source);
+ memset(e, 0, sizeof(*e));
+}
+
+static int entry_load(const char *slug, const char *id, struct entry *out)
+{
+ char leaf[32], path[MAX_PATH];
+ char *raw;
+
+ memset(out, 0, sizeof(*out));
+ snprintf(leaf, sizeof(leaf), "%s.json", id);
+ snprintf(path, sizeof(path), "%s/%s", slug, leaf);
+
+ {
+ char *root = wiki_root();
+ char full[MAX_PATH];
+ snprintf(full, sizeof(full), "%s/%s", root, path);
+ raw = read_file(full);
+ free(root);
+ }
+ if (!raw)
+ return -1;
+
+ out->id = json_str(raw, "id");
+ out->title = json_str(raw, "title");
+ out->text = json_str(raw, "text");
+ out->tags = json_str(raw, "tags");
+ out->source = json_str(raw, "source");
+ out->created = json_num(raw, "created", 0);
+ out->updated = json_num(raw, "updated", out->created);
+ out->dim = (int)json_num(raw, "embedding", 0);
+
+ if (!out->id || !out->title || !out->text) {
+ free_entry(out);
+ free(raw);
+ return -1;
+ }
+ free(raw);
+ return 0;
+}
+
+/* ── knowledge base (wiki) ───────────────────────────────────────── */
+
+static int kb_meta(const char *slug, char *name, size_t namelen, char *desc, size_t desclen)
+{
+ char path[MAX_PATH];
+ char *raw;
+
+ snprintf(path, sizeof(path), "%s/kb.json", slug);
+ {
+ char *root = wiki_root();
+ char full[MAX_PATH];
+ snprintf(full, sizeof(full), "%s/%s", root, path);
+ raw = read_file(full);
+ free(root);
+ }
+ if (!raw)
+ return -1;
+
+ if (name) {
+ const char *s = json_str(raw, "name");
+ snprintf(name, namelen, "%s", s ? s : "");
+ }
+ if (desc) {
+ const char *s = json_str(raw, "description");
+ snprintf(desc, desclen, "%s", s ? s : "");
+ }
+ free(raw);
+ return 0;
+}
+
+/* ── slugify ──────────────────────────────────────────────────────── */
+
+static void slugify(const char *name, char *out, size_t outlen)
+{
+ size_t i = 0;
+ int last_dash = 0;
+
+ for (const char *p = name; *p && i + 1 < outlen; p++) {
+ unsigned char ch = (unsigned char)*p;
+ if (isalnum(ch)) {
+ out[i++] = (char)tolower(ch);
+ last_dash = 0;
+ } else if (!last_dash) {
+ out[i++] = '-';
+ last_dash = 1;
+ }
+ }
+ while (i > 0 && out[i - 1] == '-')
+ i--;
+ out[i] = '\0';
+}
+
+/* ── list wiki slugs (all wikis) ─────────────────────────────────── */
+
+#define MAX_SLUGS 64
+
+static int list_slugs(char slugs[][MAX_SLUG], int max)
+{
+ char *root = wiki_root();
+ DIR *d;
+ struct dirent *de;
+ int count = 0;
+
+ *slugs[0] = '\0';
+ d = opendir(root);
+ free(root);
+ if (!d)
+ return -1;
+ while ((de = readdir(d)) && count < max) {
+ char path[MAX_PATH];
+ FILE *f;
+ if (de->d_name[0] == '.')
+ continue;
+ snprintf(path, sizeof(path), "%s/%s/kb.json", root, de->d_name);
+ f = fopen(path, "r");
+ if (!f)
+ continue;
+ fclose(f);
+ snprintf(slugs[count], MAX_SLUG, "%s", de->d_name);
+ count++;
+ }
+ closedir(d);
+ /* sort */
+ for (int i = 1; i < count; i++)
+ for (int j = i; j > 0 && strcmp(slugs[j-1], slugs[j]) > 0; j--) {
+ char tmp[MAX_SLUG];
+ snprintf(tmp, sizeof(tmp), "%s", slugs[j]);
+ snprintf(slugs[j], sizeof(slugs[j]), "%s", slugs[j-1]);
+ snprintf(slugs[j-1], sizeof(slugs[j-1]), "%s", tmp);
+ }
+ return count;
+}
+
+/* ── list page ids in a wiki ─────────────────────────────────────── */
+
+static int list_entry_ids(const char *slug, char ids[][16], int max)
+{
+ char *root = wiki_root();
+ char dir[MAX_PATH];
+ DIR *d;
+ struct dirent *de;
+ int count = 0;
+
+ snprintf(dir, sizeof(dir), "%s/%s", root, slug);
+ free(root);
+ d = opendir(dir);
+ if (!d)
+ return -1;
+ while ((de = readdir(d)) && count < max) {
+ size_t len = strlen(de->d_name);
+ if (len < 6 || de->d_name[0] != 'e' ||
+ strcmp(de->d_name + len - 5, ".json") != 0)
+ continue;
+ snprintf(ids[count], 16, "%.*s", (int)(len - 5), de->d_name);
+ count++;
+ }
+ closedir(d);
+ return count;
+}
+
+/* ── HTML escaping ──────────────────────────────────────────────── */
+
+static void html_escape(cgi_buf *b, const char *s)
+{
+ if (!s)
+ return;
+ for (; *s; s++) {
+ switch (*s) {
+ case '&': cgi_buf_puts(b, "&"); break;
+ case '<': cgi_buf_puts(b, "<"); break;
+ case '>': cgi_buf_puts(b, ">"); break;
+ case '"': cgi_buf_puts(b, """); break;
+ default: cgi_buf_add(b, s, 1); break;
+ }
+ }
+}
+
+/* ── HTTP helpers ───────────────────────────────────────────────── */
+
+static void send_header(cgi_buf *b, int code, const char *reason, const char *ctype)
+{
+ const char *statuses[] = {
+ [200] = "OK", [404] = "Not Found", [400] = "Bad Request",
+ [500] = "Internal Server Error"
+ };
+ if (!reason)
+ reason = statuses[code] ? statuses[code] : "Error";
+ cgi_buf_printf(b, "HTTP/1.1 %d %s\r\n", code, reason);
+ cgi_buf_printf(b, "Content-Type: %s\r\n", ctype);
+ cgi_buf_puts(b, "Connection: close\r\n\r\n");
+}
+
+/* ── Markdown → simple HTML 4.01 ────────────────────────────────── */
+
+static int md_to_html(cgi_buf *out, const char *text)
+{
+ const char *p = text;
+ int in_para = 0;
+ int in_list = 0;
+
+ while (*p) {
+ /* Heading */
+ if (*p == '#') {
+ int level = 0;
+ while (*p == '#') { level++; p++; }
+ while (*p == ' ') p++;
+ if (in_para) { cgi_buf_puts(out, "
\n"); in_para = 0; }
+ if (in_list) { cgi_buf_puts(out, "\n"); in_list = 0; }
+ if (level > 6) level = 6;
+ cgi_buf_printf(out, "", level);
+ while (*p && *p != '\n') {
+ if (*p == '`') {
+ cgi_buf_puts(out, ""); p++;
+ while (*p && *p != '`' && *p != '\n') {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ if (*p == '`') p++;
+ cgi_buf_puts(out, "");
+ } else {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ }
+ cgi_buf_printf(out, "\n", level);
+ continue;
+ }
+ /* Unordered list */
+ if (*p == '-' && (p[1] == ' ' || p[1] == ' ')) {
+ if (!in_list) { cgi_buf_puts(out, "\n"); in_list = 1; }
+ cgi_buf_puts(out, "- ");
+ p += 2;
+ while (*p && *p != '\n') {
+ if (*p == '`') {
+ cgi_buf_puts(out, "
"); p++;
+ while (*p && *p != '`' && *p != '\n') {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ if (*p == '`') p++;
+ cgi_buf_puts(out, "");
+ } else {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ }
+ cgi_buf_puts(out, " \n");
+ continue;
+ }
+ if (in_list) { cgi_buf_puts(out, "
\n"); in_list = 0; }
+ /* Horizontal rule */
+ if (strncmp(p, "---", 3) == 0 && (p[3] == '\n' || !p[3])) {
+ if (in_para) { cgi_buf_puts(out, "\n"); in_para = 0; }
+ cgi_buf_puts(out, "
\n");
+ p += 3;
+ while (*p == '\n') p++;
+ continue;
+ }
+ /* Blank line */
+ if (*p == '\n') {
+ if (in_para) { cgi_buf_puts(out, "\n"); in_para = 0; }
+ p++;
+ continue;
+ }
+ /* Paragraph */
+ if (!in_para) { cgi_buf_puts(out, ""); in_para = 1; }
+ while (*p && *p != '\n') {
+ if (*p == '*' && p[1] == '*') {
+ cgi_buf_puts(out, ""); p += 2;
+ while (*p && !(*p == '*' && p[1] == '*') && *p != '\n') {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ if (*p == '*') p++;
+ cgi_buf_puts(out, "");
+ } else if (*p == '*' && p[1] != '*') {
+ cgi_buf_puts(out, ""); p++;
+ while (*p && *p != '*' && *p != '\n') {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ if (*p == '*') p++;
+ cgi_buf_puts(out, "");
+ } else if (*p == '`') {
+ cgi_buf_puts(out, ""); p++;
+ while (*p && *p != '`' && *p != '\n') {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ if (*p == '`') p++;
+ cgi_buf_puts(out, "");
+ } else {
+ cgi_buf_add(out, p, 1); p++;
+ }
+ }
+ if (*p == '\n') p++;
+ }
+ if (in_para) cgi_buf_puts(out, "
\n");
+ if (in_list) cgi_buf_puts(out, "\n");
+ return 0;
+}
+
+/* ── HTML page shell ────────────────────────────────────────────── */
+
+static const char *css =
+"body{font-family:serif;margin:2em;max-width:72em;background:#fff;color:#222}\n"
+"h1,h2,h3,h4,h5,h6{margin-top:1.2em;margin-bottom:0.4em}\n"
+"a{color:#0055aa;text-decoration:none}\n"
+"a:hover{text-decoration:underline}\n"
+"ul{margin:0.5em 0}\n"
+"li{margin:0.2em 0}\n"
+"code{background:#f4f4f4;padding:0.1em 0.3em;font-size:0.9em}\n"
+"table{border-collapse:collapse;margin:1em 0}\n"
+"td,th{border:1px solid #ccc;padding:0.3em 0.6em;text-align:left}\n"
+"th{background:#f0f0f0}\n"
+".meta{font-size:0.85em;color:#666;margin-bottom:1em}\n"
+".nav{margin:1em 0;border-top:1px solid #ddd;padding-top:0.5em}\n"
+".nav a{margin-right:1em}\n";
+
+static void html_head(cgi_buf *b, const char *title)
+{
+ cgi_buf_puts(b, "\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "");
+ html_escape(b, title);
+ cgi_buf_puts(b, "\n"
+ "\n"
+ "\n"
+ "\n");
+}
+
+static void html_foot(cgi_buf *b)
+{
+ cgi_buf_puts(b, "\n\n");
+}
+
+/* ── render one page ────────────────────────────────────────────── */
+
+static void render_page(cgi_buf *out, const char *slug, const char *id)
+{
+ struct entry e;
+ char name[MAX_SLUG] = "";
+
+ kb_meta(slug, name, sizeof(name), NULL, 0);
+
+ html_head(out, e.title ? e.title : "Page not found");
+
+ cgi_buf_printf(out, "");
+ html_escape(out, e.title);
+ cgi_buf_printf(out, " [edit]
\n");
+
+ cgi_buf_puts(out, "");
+ if (e.tags && *e.tags) {
+ cgi_buf_puts(out, "tags: ");
+ html_escape(out, e.tags);
+ cgi_buf_puts(out, " ");
+ }
+ cgi_buf_printf(out, "updated: %ld ", e.updated);
+ if (e.dim > 0)
+ cgi_buf_puts(out, "embedded");
+ cgi_buf_puts(out, "
\n");
+
+ md_to_html(out, e.text);
+
+ cgi_buf_puts(out, "\n");
+ cgi_buf_printf(out, "
Back to %s ", slug, name[0] ? name : slug);
+ cgi_buf_printf(out, "
All wikis\n");
+ cgi_buf_puts(out, "
\n");
+
+ html_foot(out);
+}
+
+/* ── render wiki index (list of wikis) ──────────────────────────── */
+
+static void render_wiki_index(cgi_buf *out)
+{
+ char slugs[MAX_SLUGS][MAX_SLUG];
+ int n = list_slugs(slugs, MAX_SLUGS);
+
+ html_head(out, "Wikis");
+
+ cgi_buf_puts(out, "Wikis
\n");
+
+ if (n <= 0) {
+ cgi_buf_puts(out, "No wikis yet — create one with wikid or kb_create.
\n");
+ } else {
+ cgi_buf_printf(out, "%d wiki(s) below.
\n", n);
+ for (int i = 0; i < n; i++) {
+ char name[MAX_SLUG] = "", desc[512] = "";
+ char ids[256][16];
+ int np;
+
+ kb_meta(slugs[i], name, sizeof(name), desc, sizeof(desc));
+ np = list_entry_ids(slugs[i], ids, 256);
+
+ cgi_buf_printf(out, "\n", np, np == 1 ? "" : "s");
+ if (desc[0]) {
+ cgi_buf_puts(out, "");
+ html_escape(out, desc);
+ cgi_buf_puts(out, "
\n");
+ }
+ }
+ }
+
+ html_foot(out);
+}
+
+/* ── render wiki pages listing ──────────────────────────────────── */
+
+static void render_wiki_list(cgi_buf *out, const char *slug)
+{
+ char name[MAX_SLUG] = "", desc[512] = "";
+ char ids[256][16];
+ int np;
+
+ kb_meta(slug, name, sizeof(name), desc, sizeof(desc));
+
+ html_head(out, name[0] ? name : slug);
+
+ cgi_buf_printf(out, "%s
\n", name[0] ? name : slug);
+ if (desc[0]) {
+ cgi_buf_printf(out, "");
+ html_escape(out, desc);
+ cgi_buf_puts(out, "
\n");
+ }
+
+ np = list_entry_ids(slug, ids, 256);
+ if (np <= 0) {
+ cgi_buf_puts(out, "No pages yet.
\n");
+ } else {
+ cgi_buf_printf(out, "%d page(s)
\n", np);
+ for (int i = 0; i < np; i++) {
+ struct entry e;
+ if (entry_load(slug, ids[i], &e) != 0)
+ continue;
+
+ cgi_buf_printf(out, "\n");
+
+ cgi_buf_printf(out, "%s ", e.id);
+ if (e.tags && *e.tags) {
+ cgi_buf_puts(out, "tags: ");
+ html_escape(out, e.tags);
+ cgi_buf_puts(out, " ");
+ }
+ if (e.dim > 0)
+ cgi_buf_puts(out, "embedded ");
+ cgi_buf_printf(out, "updated: %ld
\n", e.updated);
+
+ /* First 300 chars of text */
+ cgi_buf_puts(out, "");
+ {
+ const char *p = e.text;
+ int len = 0;
+ while (*p && *p != '\n' && len < 300) {
+ if (*p == '*' && p[1] == '*') { p += 2; continue; }
+ if (*p == '*') { p++; continue; }
+ if (*p == '`') { p++; continue; }
+ cgi_buf_add(out, p, 1);
+ p++;
+ len++;
+ }
+ }
+ cgi_buf_puts(out, "…
\n");
+ free_entry(&e);
+ }
+ }
+
+ cgi_buf_puts(out, "\n");
+ cgi_buf_puts(out, "
All wikis\n");
+ cgi_buf_puts(out, "
\n");
+
+ html_foot(out);
+}
diff --git a/wikid-http.c b/wikid-http.c
new file mode 100644
index 0000000..ec2cd8b
--- /dev/null
+++ b/wikid-http.c
@@ -0,0 +1,1374 @@
+/*
+ * wikid-http — HTTP front-end for wikid, via wikid's MCP server.
+ *
+ * A C99 CGI binary. It speaks JSON-RPC over HTTP to wikid (POST /mcp)
+ * instead of reading the data files itself: every list, search, read and
+ * write goes back to wikid, so the web view and the agents see the same
+ * wiki. No auth, no JavaScript, no state — plain HTML 4.01.
+ *
+ * Routes:
+ * / — all wikis (wiki_list)
+ * /wikid/ — same page
+ * /wikid// — pages of one wiki (page_list)
+ * /wikid// — read one page (page_read)
+ * /wikid/search?q=… — search (wiki_search)
+ * GET /wikid//write — write form
+ * POST /wikid//write — write a page (page_write)
+ * GET /wikid/create — create form
+ * POST /wikid/create — create a wiki (wiki_create)
+ *
+ * Environment: WIKID_URL (default http://127.0.0.1:8796/mcp)
+ *
+ * Build:
+ * cc -std=c99 -O2 -Wall -Wextra -Wpedantic -D_POSIX_C_SOURCE=200809L \
+ * -D_DEFAULT_SOURCE -o wikid-http wikid-http.c
+ */
+#define _POSIX_C_SOURCE 200809L
+
+#include
+#include
+#include
+#include
+#include
+
+#define MAX_LINE 4096
+#define MAX_BODY 65536
+
+/* Path under which the CGI is mounted: "" when it is the root, otherwise
+ * SCRIPT_NAME (e.g. "/cgi-bin/wikid-http"). Every internal link is emitted
+ * relative to this, so the same binary works at / and under /cgi-bin/. */
+static char g_prefix[256];
+
+static void url(const char *suffix)
+{
+ fputs(g_prefix, stdout);
+ fputs(suffix, stdout);
+}
+
+/* ------------------------------------------------------------------ buffer */
+
+static char *buf_add(char *p, size_t *len, size_t *cap, const char *s, size_t n)
+{
+ size_t newcap = *cap ? *cap : 256;
+ char *q;
+
+ if (n == 0)
+ return p;
+ while (newcap < *len + n + 1)
+ newcap *= 2;
+ q = realloc(p, newcap);
+ if (q == NULL) {
+ free(p);
+ return NULL;
+ }
+ memcpy(q + *len, s, n);
+ *len += n;
+ q[*len] = '\0';
+ *cap = newcap;
+ return q;
+}
+
+static char *buf_puts(char *p, size_t *len, size_t *cap, const char *s)
+{
+ return buf_add(p, len, cap, s, strlen(s));
+}
+
+static char *buf_printf(char *p, size_t *len, size_t *cap, const char *fmt, ...)
+{
+ char tmp[4096];
+ va_list ap;
+ int n;
+
+ va_start(ap, fmt);
+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
+ va_end(ap);
+ if (n < 0)
+ return p;
+ return buf_add(p, len, cap, tmp, (size_t)n);
+}
+
+/* ----------------------------------------------------------------- escaping */
+
+static void html_esc(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;
+ }
+ }
+}
+
+/* Escape exactly n bytes (a line inside a larger buffer). */
+static void html_esc_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 char *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;
+}
+
+/* Append a JSON-escaped copy of s. */
+static char *buf_json(char *p, size_t *len, size_t *cap, const char *s)
+{
+ for (; s != NULL && *s; s++) {
+ switch (*s) {
+ case '"': p = buf_puts(p, len, cap, "\\\""); break;
+ case '\\': p = buf_puts(p, len, cap, "\\\\"); break;
+ case '\n': p = buf_puts(p, len, cap, "\\n"); break;
+ case '\r': p = buf_puts(p, len, cap, "\\r"); break;
+ case '\t': p = buf_puts(p, len, cap, "\\t"); break;
+ default:
+ if ((unsigned char)*s < 0x20)
+ p = buf_printf(p, len, cap, "\\u%04x", (unsigned char)*s);
+ else
+ p = buf_add(p, len, cap, s, 1);
+ break;
+ }
+ if (p == NULL)
+ return NULL;
+ }
+ return p;
+}
+
+/* ------------------------------------------------------------------ MCP RPC */
+
+/* Extract a JSON string value for "text": "…" from a response body.
+ * Handles the escapes wikid can produce (\" \\ \n \r \t \u). */
+static char *json_text_value(const char *json)
+{
+ const char *pat = "\"text\":\"";
+ const char *p = strstr(json, pat);
+ char *out;
+ size_t len = 0, cap = 0;
+
+ if (p == NULL)
+ return NULL;
+ p += strlen(pat);
+ out = NULL;
+ while (*p != '\0' && *p != '"') {
+ char ch = *p;
+
+ if (ch == '\\') {
+ p++;
+ switch (*p) {
+ case 'n': ch = '\n'; p++; break;
+ case 'r': ch = '\r'; p++; break;
+ case 't': ch = '\t'; p++; break;
+ case 'u':
+ /* Wikid does not emit \u except control chars;
+ * decode the four hex digits. */
+ if (isxdigit((unsigned char)p[1]) &&
+ isxdigit((unsigned char)p[2]) &&
+ isxdigit((unsigned char)p[3]) &&
+ isxdigit((unsigned char)p[4])) {
+ char hex[5] = { p[1], p[2], p[3], p[4], 0 };
+ ch = (char)strtol(hex, NULL, 16);
+ p += 5;
+ } else {
+ p++;
+ }
+ break;
+ default: ch = *p; p++; break;
+ }
+ } else {
+ p++;
+ }
+ out = buf_add(out, &len, &cap, &ch, 1);
+ if (out == NULL)
+ return NULL;
+ }
+ if (out == NULL)
+ out = buf_add(NULL, &len, &cap, "", 0);
+ return out;
+}
+
+/* Extract an error message if the response is an error. */
+static char *json_error_value(const char *json)
+{
+ const char *p = strstr(json, "\"message\":\"");
+
+ if (p == NULL)
+ return NULL;
+ p += 11;
+ {
+ const char *end = strchr(p, '"');
+ char *msg;
+
+ if (end == NULL)
+ return NULL;
+ msg = malloc((size_t)(end - p) + 1);
+ if (msg == NULL)
+ return NULL;
+ memcpy(msg, p, (size_t)(end - p));
+ msg[end - p] = '\0';
+ return msg;
+ }
+}
+
+static char *wikid_call(const char *tool, const char *args)
+{
+ char *body = NULL;
+ size_t blen = 0, bcap = 0;
+ const char *url;
+ char cmd[8192];
+ FILE *fp;
+ char chunk[2048];
+ size_t got;
+ char *raw = NULL;
+ size_t rlen = 0, rcap = 0;
+ char *text;
+
+ body = buf_printf(body, &blen, &bcap,
+ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"%s\",\"arguments\":%s}}", tool, args);
+ if (body == NULL)
+ return NULL;
+
+ url = getenv("WIKID_URL");
+ if (url == NULL || *url == '\0')
+ url = "http://127.0.0.1:8796/mcp";
+
+ /* Single-quote the body: it contains only JSON double quotes and
+ * escaped backslashes; the only dangerous character is a single
+ * quote, which JSON bodies here cannot contain (titles/texts are
+ * escaped to \u0027 by json_esc? no — single quotes pass through).
+ * Escape them. */
+ {
+ char *qbody = NULL;
+ size_t qlen = 0, qcap = 0;
+
+ for (const char *p = body; *p; p++) {
+ if (*p == '\'') {
+ qbody = buf_puts(qbody, &qlen, &qcap, "'\\''");
+ if (qbody == NULL)
+ break;
+ } else {
+ qbody = buf_add(qbody, &qlen, &qcap, p, 1);
+ if (qbody == NULL)
+ break;
+ }
+ }
+ if (qbody == NULL && *body != '\0') {
+ free(body);
+ return NULL;
+ }
+ snprintf(cmd, sizeof(cmd),
+ "curl -sS -m 30 -X POST -H 'Content-Type: application/json' "
+ "-d '%s' '%s' 2>/dev/null", qbody != NULL ? qbody : "", url);
+ free(qbody);
+ }
+ free(body);
+
+ fp = popen(cmd, "r");
+ if (fp == NULL)
+ return NULL;
+ while ((got = fread(chunk, 1, sizeof(chunk), fp)) > 0) {
+ raw = buf_add(raw, &rlen, &rcap, chunk, got);
+ if (raw == NULL)
+ break;
+ }
+ pclose(fp);
+ if (raw == NULL)
+ return NULL;
+
+ text = json_text_value(raw);
+ if (text == NULL)
+ text = json_error_value(raw);
+ free(raw);
+ return text;
+}
+
+/* ------------------------------------------------------------------ markdown */
+
+static void md_inline(const char **pp)
+{
+ const char *p = *pp;
+
+ while (*p && *p != '\n') {
+ if (*p == '*' && p[1] == '*') {
+ fputs("", stdout);
+ p += 2;
+ while (*p && !(*p == '*' && p[1] == '*') && *p != '\n')
+ putchar(*p++);
+ if (*p == '*')
+ p++;
+ fputs("", stdout);
+ } else if (*p == '*') {
+ fputs("", stdout);
+ p++;
+ while (*p && *p != '*' && *p != '\n')
+ putchar(*p++);
+ if (*p == '*')
+ p++;
+ fputs("", stdout);
+ } else if (*p == '`') {
+ fputs("", stdout);
+ p++;
+ while (*p && *p != '`' && *p != '\n')
+ putchar(*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 void md_render(const char *text)
+{
+ const char *p = text;
+ int in_para = 0, in_list = 0;
+
+ while (*p) {
+ 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);
+ md_inline(&p);
+ printf("\n", level);
+ continue;
+ }
+ if (*p == '-' && (p[1] == ' ' || p[1] == '\t')) {
+ if (!in_list) { fputs("\n", stdout); in_list = 1; }
+ fputs("- ", stdout);
+ p += 2;
+ md_inline(&p);
+ fputs("
\n", stdout);
+ continue;
+ }
+ if (in_list) { fputs("
\n", stdout); in_list = 0; }
+ if (strncmp(p, "---", 3) == 0 && (p[3] == '\n' || p[3] == '\0')) {
+ if (in_para) { fputs("\n", stdout); in_para = 0; }
+ fputs("
\n", stdout);
+ p += 3;
+ while (*p == '\n')
+ p++;
+ continue;
+ }
+ if (*p == '\n') {
+ if (in_para) { fputs("\n", stdout); in_para = 0; }
+ p++;
+ continue;
+ }
+ if (!in_para) { fputs("", stdout); in_para = 1; }
+ 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);
+}
+
+/* ----------------------------------------------------------------- HTML shell */
+
+static const char *css =
+"body{font-family:serif;margin:2em;max-width:72em;background:#fff;color:#222}\n"
+"h1,h2,h3,h4,h5,h6{margin-top:1.2em;margin-bottom:0.4em}\n"
+"a{color:#0055aa;text-decoration:none}\n"
+"a:hover{text-decoration:underline}\n"
+"ul{margin:0.5em 0}\n"
+"li{margin:0.2em 0}\n"
+"code{background:#f4f4f4;padding:0.1em 0.3em;font-size:0.9em}\n"
+"table{border-collapse:collapse;margin:1em 0}\n"
+"td,th{border:1px solid #ccc;padding:0.3em 0.6em;text-align:left}\n"
+"th{background:#f0f0f0}\n"
+".meta{font-size:0.85em;color:#666;margin-bottom:1em}\n"
+".nav{margin:1em 0;border-top:1px solid #ddd;padding-top:0.5em}\n"
+".nav a{margin-right:1em}\n"
+".error{color:#a00}\n"
+".listing{list-style:none;padding-left:0}\n"
+".listing li{margin:0.6em 0}\n"
+".snippet{color:#555;font-size:0.9em;margin-left:1.5em}\n";
+
+static void html_head(const char *title)
+{
+ puts("\n"
+ "\n"
+ "\n"
+ "\n"
+ "");
+ html_esc(title);
+ puts("\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n", stdout);
+}
+
+static void html_foot(void)
+{
+ puts("\n\n");
+}
+
+static void error_page(const char *title, const char *msg)
+{
+ html_head(title);
+ printf("");
+ html_esc(title);
+ fputs("
\n", stdout);
+ html_esc(msg != NULL ? msg : "unknown error");
+ puts("
");
+ html_foot();
+}
+
+/* ------------------------------------------------------------------- forms */
+
+/* Copy a URL-encoded parameter out of qs (malloc'd, caller frees). */
+static char *param_get(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';
+ url_decode(out);
+ return out;
+ }
+ p = strchr(p, '&');
+ if (p != NULL)
+ p++;
+ }
+ return NULL;
+}
+
+static void write_form(const char *slug, const char *title,
+ const char *text, const char *tags, const char *source)
+{
+ printf("Write into %s
\n", slug);
+ fputs("\n", stdout);
+ fputs("\n", stdout);
+}
+
+static void create_form(const char *name, const char *desc)
+{
+ fputs("Create a wiki
\n\n\n", stdout);
+}
+
+/* --------------------------------------------------------------- list render */
+
+/*
+ * wiki_list output:
+ * %d knowledge base(s) in %s (history: …)
+ * entries —
+ * The line is fixed-width: slug 24, name 20, then "%4zu entries".
+ * Rather than trusting the widths, take the first token as the slug and
+ * print the rest verbatim.
+ */
+static void render_wikis(const char *text)
+{
+ const char *p = text;
+ int first = 1;
+
+ while (*p) {
+ const char *eol = strchr(p, '\n');
+ size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p);
+ const char *line_end = p + len;
+
+ if (len > 2 && p[0] == ' ' && p[1] == ' ') {
+ const char *tok = p + 2;
+ const char *tok_end = tok;
+ char slug[128];
+ size_t slen;
+
+ while (tok_end < line_end && *tok_end != ' ' && *tok_end != '\t')
+ tok_end++;
+ slen = (size_t)(tok_end - tok);
+ if (slen >= sizeof(slug))
+ slen = sizeof(slug) - 1;
+ memcpy(slug, tok, slen);
+ slug[slen] = '\0';
+
+ fputs("", stdout);
+ html_esc(slug);
+ fputs("", stdout);
+ if (tok_end < line_end) {
+ fputs(" · ", stdout);
+ {
+ char rest[1024];
+ size_t rlen = (size_t)(line_end - tok_end);
+
+ if (rlen >= sizeof(rest))
+ rlen = sizeof(rest) - 1;
+ memcpy(rest, tok_end, rlen);
+ rest[rlen] = '\0';
+ {
+ char *rs = rest;
+
+ while (*rs == ' ' || *rs == '\t')
+ rs++;
+ html_esc(rs);
+ }
+ }
+ }
+ fputs("\n", stdout);
+ } else {
+ if (first) {
+ fputs("", stdout);
+ html_esc_n(p, len);
+ fputs("
\n\n", stdout);
+ } else {
+ error_page("Wiki engine", "unexpected output");
+ return;
+ }
+ }
+ first = 0;
+ if (eol == NULL)
+ break;
+ p = eol + 1;
+ }
+ if (!first)
+ fputs("
\n", stdout);
+}
+
+/* page_list output:
+ * %zu entries in "%s" (newest first):
+ * tags=… (embedded, updated N)
+ */
+static void render_pages(const char *text, const char *slug)
+{
+ const char *p = text;
+ int first = 1;
+
+ while (*p) {
+ const char *eol = strchr(p, '\n');
+ size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p);
+ const char *line_end = p + len;
+
+ if (len > 2 && p[0] == ' ' && p[1] == ' ') {
+ const char *tok = p + 2;
+ const char *tok_end = tok;
+ char id[64];
+ size_t tlen;
+
+ while (tok_end < line_end && *tok_end != ' ' && *tok_end != '\t')
+ tok_end++;
+ tlen = (size_t)(tok_end - tok);
+ if (tlen >= sizeof(id))
+ tlen = sizeof(id) - 1;
+ memcpy(id, tok, tlen);
+ id[tlen] = '\0';
+
+ fputs("", stdout);
+ html_esc(id);
+ fputs("", stdout);
+ if (tok_end < line_end) {
+ char rest[1024];
+ size_t rlen = (size_t)(line_end - tok_end);
+
+ if (rlen >= sizeof(rest))
+ rlen = sizeof(rest) - 1;
+ memcpy(rest, tok_end, rlen);
+ rest[rlen] = '\0';
+ fputs(" · ", stdout);
+ {
+ char *rs = rest;
+
+ while (*rs == ' ' || *rs == '\t')
+ rs++;
+ html_esc(rs);
+ }
+ }
+ fputs("\n", stdout);
+ } else {
+ if (first) {
+ fputs("", stdout);
+ html_esc_n(p, len);
+ fputs("
\n\n", stdout);
+ } else {
+ fputs("", stdout);
+ html_esc_n(p, len);
+ fputs("
\n", stdout);
+ }
+ }
+ first = 0;
+ if (eol == NULL)
+ break;
+ p = eol + 1;
+ }
+ if (!first)
+ fputs("
\n", stdout);
+}
+
+/* wiki_search output:
+ * %zu hit(s) for "…":
+ * / [title] score=… tags=…
+ *
+ */
+static void render_search(const char *text)
+{
+ const char *p = text;
+ int first = 1, opened = 0;
+
+ while (*p) {
+ const char *eol = strchr(p, '\n');
+ size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p);
+ const char *line_end = p + len;
+
+ if (len > 4 && p[0] == ' ' && p[1] == ' ' && p[2] == ' ' && p[3] == ' ') {
+ const char *sp = p;
+
+ while (sp < line_end && (*sp == ' ' || *sp == '\t'))
+ sp++;
+ fputs("", stdout);
+ {
+ const char *mp = sp;
+
+ md_inline(&mp);
+ }
+ fputs("\n", stdout);
+ } else if (!first && strchr(p, '/') != NULL &&
+ (size_t)(strchr(p, ' ') - p) < len) {
+ /* hit line: slug/id [title] score=… tags=… */
+ const char *tok_end = p;
+ char ref[512];
+ size_t rlen;
+
+ while (tok_end < line_end && *tok_end != ' ' && *tok_end != '\t')
+ tok_end++;
+ rlen = (size_t)(tok_end - p);
+ if (rlen >= sizeof(ref))
+ rlen = sizeof(ref) - 1;
+ memcpy(ref, p, rlen);
+ ref[rlen] = '\0';
+ {
+ char *slash = strchr(ref, '/');
+
+ if (slash != NULL) {
+ char wiki[256];
+ size_t wlen = (size_t)(slash - ref);
+ const char *title = tok_end;
+ const char *title_end = NULL;
+ const char *after = tok_end;
+
+ /* rest begins with " [title] ..." — lift the title
+ * out of the brackets and use it as link text. */
+ while (title < line_end && *title == ' ')
+ title++;
+ if (title < line_end && *title == '[') {
+ title_end = memchr(title, ']',
+ (size_t)(line_end - title));
+ if (title_end != NULL)
+ after = title_end + 1;
+ }
+
+ if (wlen >= sizeof(wiki))
+ wlen = sizeof(wiki) - 1;
+ memcpy(wiki, ref, wlen);
+ wiki[wlen] = '\0';
+ fputs("", stdout);
+ if (title_end != NULL)
+ html_esc_n(title + 1,
+ (size_t)(title_end - title - 1));
+ else
+ html_esc(ref);
+ fputs("", stdout);
+ if (after < line_end) {
+ fputs(" · ", stdout);
+ html_esc_n(after, (size_t)(line_end - after));
+ }
+ fputs("\n", stdout);
+ }
+ }
+ } else if (first) {
+ fputs("", stdout);
+ html_esc_n(p, len);
+ fputs("
\n", stdout);
+ if (len > 0 && p[len - 1] == ':') {
+ fputs("\n", stdout);
+ opened = 1;
+ }
+ } else {
+ fputs("", stdout);
+ html_esc_n(p, len);
+ fputs("
\n", stdout);
+ }
+ first = 0;
+ if (eol == NULL)
+ break;
+ p = eol + 1;
+ }
+ if (opened)
+ fputs("
\n", stdout);
+}
+
+/* ------------------------------------------------------------------- routes */
+
+static void route_index(void)
+{
+ char *text = wikid_call("wiki_list", "{}");
+
+ if (text == NULL) {
+ error_page("Wikis", "The wiki engine did not answer.");
+ return;
+ }
+ html_head("Wikis");
+ fputs("Wikis
\n", stdout);
+ render_wikis(text);
+ free(text);
+ html_foot();
+}
+
+static void route_wiki_index(const char *slug)
+{
+ char *args = NULL;
+ size_t alen = 0, acap = 0;
+ char *text;
+
+ args = buf_puts(args, &alen, &acap, "{\"kb\":\"");
+ args = buf_json(args, &alen, &acap, slug);
+ args = buf_puts(args, &alen, &acap, "\"}");
+ if (args == NULL) {
+ error_page("Wikis", "out of memory");
+ return;
+ }
+ text = wikid_call("page_list", args);
+ free(args);
+ if (text == NULL) {
+ error_page("Wiki", "The wiki engine did not answer.");
+ return;
+ }
+ if (strncmp(text, "no knowledge base", 17) == 0) {
+ html_head("No such wiki");
+ fputs("No such wiki
\n", stdout);
+ html_esc(text);
+ fputs("
\n\n", stdout);
+ html_foot();
+ free(text);
+ return;
+ }
+ html_head(slug);
+ fputs("", stdout);
+ html_esc(slug);
+ fputs("
\n", stdout);
+ render_pages(text, slug);
+ fputs("\n", stdout);
+ free(text);
+ html_foot();
+}
+
+static int looks_like_id(const char *s)
+{
+ if (s == NULL || s[0] != 'e' || s[1] == '\0')
+ return 0;
+ for (s++; *s; s++)
+ if (!isdigit((unsigned char)*s))
+ return 0;
+ return 1;
+}
+
+/* POST /wikid//delete — page_delete */
+static void route_delete(const char *slug, const char *body)
+{
+ char *id = param_get(body, "id");
+ char *title = param_get(body, "title");
+ char *args = NULL;
+ size_t alen = 0, acap = 0;
+ char *result;
+
+ if ((id == NULL || *id == '\0') && (title == NULL || *title == '\0')) {
+ error_page("Delete page", "No page named.");
+ free(id);
+ free(title);
+ return;
+ }
+ args = buf_puts(args, &alen, &acap, "{\"kb\":\"");
+ args = buf_json(args, &alen, &acap, slug);
+ if (id != NULL && *id != '\0') {
+ args = buf_puts(args, &alen, &acap, "\",\"id\":\"");
+ args = buf_json(args, &alen, &acap, id);
+ } else {
+ args = buf_puts(args, &alen, &acap, "\",\"title\":\"");
+ args = buf_json(args, &alen, &acap, title);
+ }
+ args = buf_puts(args, &alen, &acap, "\"}");
+ if (args == NULL) {
+ error_page("Delete page", "out of memory");
+ free(id);
+ free(title);
+ return;
+ }
+ result = wikid_call("page_delete", args);
+ free(args);
+ if (result == NULL) {
+ error_page("Delete page", "The wiki engine did not answer.");
+ } else {
+ html_head("Page deleted");
+ fputs("", stdout);
+ html_esc(result);
+ fputs("
\n\n", stdout);
+ html_foot();
+ free(result);
+ }
+ free(id);
+ free(title);
+}
+
+static void route_page(const char *slug, const char *page)
+{
+ char *args = NULL;
+ size_t alen = 0, acap = 0;
+ char *text;
+ int not_found = 0;
+
+ args = buf_puts(args, &alen, &acap, "{\"kb\":\"");
+ args = buf_json(args, &alen, &acap, slug);
+ args = buf_puts(args, &alen, &acap, "\",\"id\":\"");
+ args = buf_json(args, &alen, &acap, page);
+ args = buf_puts(args, &alen, &acap, "\",\"history\":true}");
+ if (args == NULL) {
+ error_page("Page", "out of memory");
+ return;
+ }
+ text = wikid_call("page_read", args);
+ free(args);
+ /* A failed lookup is a text reply ("no page ..."), not a JSON error. */
+ if (text != NULL && strncmp(text, "no page", 7) == 0) {
+ free(text);
+ text = NULL;
+ }
+
+ if (text == NULL) {
+ alen = acap = 0;
+ args = NULL;
+ args = buf_puts(args, &alen, &acap, "{\"kb\":\"");
+ args = buf_json(args, &alen, &acap, slug);
+ args = buf_puts(args, &alen, &acap, "\",\"title\":\"");
+ args = buf_json(args, &alen, &acap, page);
+ args = buf_puts(args, &alen, &acap, "\",\"history\":true}");
+ if (args == NULL) {
+ error_page("Page", "out of memory");
+ return;
+ }
+ text = wikid_call("page_read", args);
+ free(args);
+ if (text != NULL && strncmp(text, "no page", 7) == 0) {
+ free(text);
+ text = NULL;
+ }
+ }
+
+ if (text == NULL) {
+ not_found = 1;
+ html_head("Page not found");
+ fputs("Page not found
\n", stdout);
+ html_esc(page);
+ fputs(" is not in ", stdout);
+ html_esc(slug);
+ fputs(".
\n", stdout);
+ fputs("\n", stdout);
+ html_foot();
+ }
+ (void)not_found;
+ if (text == NULL)
+ return;
+ html_head(page);
+ md_render(text);
+ fputs("\n", stdout);
+
+ /* Delete needs a POST, so no link prefetcher can remove a page. */
+ fputs("\n", stdout);
+ free(text);
+ html_foot();
+}
+
+static void search_form(const char *query)
+{
+ fputs("\n", stdout);
+}
+
+static void route_search(const char *query)
+{
+ char *args = NULL;
+ size_t alen = 0, acap = 0;
+ char *text;
+
+ if (query == NULL || *query == '\0') {
+ html_head("Search");
+ fputs("Search
\n", stdout);
+ search_form("");
+ html_foot();
+ return;
+ }
+ args = buf_puts(args, &alen, &acap, "{\"query\":\"");
+ args = buf_json(args, &alen, &acap, query);
+ args = buf_puts(args, &alen, &acap, "\"}");
+ if (args == NULL) {
+ error_page("Search", "out of memory");
+ return;
+ }
+ text = wikid_call("wiki_search", args);
+ free(args);
+ if (text == NULL) {
+ error_page("Search", "The wiki engine did not answer.");
+ return;
+ }
+ html_head(query);
+ fputs("Search
\n", stdout);
+ search_form(query);
+ render_search(text);
+ free(text);
+ html_foot();
+}
+
+static void route_write(const char *slug, const char *body)
+{
+ char *title = param_get(body, "title");
+ char *text = param_get(body, "text");
+ char *tags = param_get(body, "tags");
+ char *source = param_get(body, "source");
+
+ if (title == NULL || *title == '\0' || text == NULL || *text == '\0') {
+ html_head("Write page");
+ fputs("Title and text are required.
\n", stdout);
+ write_form(slug, title, text, tags, source);
+ html_foot();
+ free(title); free(text); free(tags); free(source);
+ return;
+ }
+
+ {
+ char *args = NULL;
+ size_t alen = 0, acap = 0;
+ char *result;
+
+ args = buf_puts(args, &alen, &acap, "{\"kb\":\"");
+ args = buf_json(args, &alen, &acap, slug);
+ args = buf_puts(args, &alen, &acap, "\",\"title\":\"");
+ args = buf_json(args, &alen, &acap, title);
+ args = buf_puts(args, &alen, &acap, "\",\"text\":\"");
+ args = buf_json(args, &alen, &acap, text);
+ args = buf_puts(args, &alen, &acap, "\"");
+ if (tags != NULL && *tags != '\0') {
+ args = buf_puts(args, &alen, &acap, ",\"tags\":\"");
+ args = buf_json(args, &alen, &acap, tags);
+ args = buf_puts(args, &alen, &acap, "\"");
+ }
+ if (source != NULL && *source != '\0') {
+ args = buf_puts(args, &alen, &acap, ",\"source\":\"");
+ args = buf_json(args, &alen, &acap, source);
+ args = buf_puts(args, &alen, &acap, "\"");
+ }
+ args = buf_puts(args, &alen, &acap, "}");
+ if (args == NULL) {
+ error_page("Write page", "out of memory");
+ free(title); free(text); free(tags); free(source);
+ return;
+ }
+
+ result = wikid_call("page_write", args);
+ free(args);
+
+ html_head(result != NULL ? "Page written" : "Error");
+ if (result != NULL) {
+ fputs("", stdout);
+ html_esc(result);
+ fputs("
\n", stdout);
+ fputs("\n", stdout);
+ free(result);
+ } else {
+ fputs("Could not write the page.
\n", stdout);
+ write_form(slug, title, text, tags, source);
+ }
+ html_foot();
+ }
+ free(title); free(text); free(tags); free(source);
+}
+
+static void route_create(const char *body)
+{
+ char *name = param_get(body, "name");
+ char *desc = param_get(body, "description");
+
+ if (name == NULL || *name == '\0') {
+ html_head("Create wiki");
+ fputs("A name is required.
\n", stdout);
+ create_form(name, desc);
+ html_foot();
+ free(name); free(desc);
+ return;
+ }
+
+ {
+ char *args = NULL;
+ size_t alen = 0, acap = 0;
+ char *result;
+
+ args = buf_puts(args, &alen, &acap, "{\"name\":\"");
+ args = buf_json(args, &alen, &acap, name);
+ args = buf_puts(args, &alen, &acap, "\"");
+ if (desc != NULL && *desc != '\0') {
+ args = buf_puts(args, &alen, &acap, ",\"description\":\"");
+ args = buf_json(args, &alen, &acap, desc);
+ args = buf_puts(args, &alen, &acap, "\"");
+ }
+ args = buf_puts(args, &alen, &acap, "}");
+ if (args == NULL) {
+ error_page("Create wiki", "out of memory");
+ free(name); free(desc);
+ return;
+ }
+
+ result = wikid_call("wiki_create", args);
+ free(args);
+
+ html_head(result != NULL ? "Wiki created" : "Error");
+ if (result != NULL) {
+ fputs("", stdout);
+ html_esc(result);
+ fputs("
\n\n", stdout);
+ free(result);
+ } else {
+ fputs("Could not create the wiki.
\n", stdout);
+ create_form(name, desc);
+ }
+ html_foot();
+ }
+ free(name); free(desc);
+}
+
+/* ------------------------------------------------------------------- router */
+
+static void split_path(const char *uri, char *path, size_t pathlen,
+ char *query, size_t querylen)
+{
+ size_t i;
+
+ strncpy(path, uri, pathlen - 1);
+ path[pathlen - 1] = '\0';
+ for (i = 0; i < pathlen && path[i] != '\0' && path[i] != '?'; i++)
+ ;
+ if (i < pathlen && path[i] == '?') {
+ if (querylen > 0) {
+ strncpy(query, path + i + 1, querylen - 1);
+ query[querylen - 1] = '\0';
+ }
+ path[i] = '\0';
+ } else if (querylen > 0) {
+ query[0] = '\0';
+ }
+}
+
+static void handle_request(const char *method, const char *path,
+ const char *query, const char *body)
+{
+ if (strcmp(path, "/") == 0 || strcmp(path, "/wikid") == 0 ||
+ strcmp(path, "/wikid/") == 0) {
+ route_index();
+ return;
+ }
+
+ if (strcmp(path, "/wikid/search") == 0) {
+ route_search(param_get(query, "q"));
+ /* param_get leaks its result by design here; the process ends. */
+ return;
+ }
+
+ if (strcmp(path, "/wikid/create") == 0) {
+ if (strcmp(method, "POST") == 0)
+ route_create(body);
+ else {
+ html_head("Create wiki");
+ create_form(NULL, NULL);
+ html_foot();
+ }
+ return;
+ }
+
+ if (strncmp(path, "/wikid/", 7) == 0) {
+ const char *slug = path + 7;
+ size_t slen = strcspn(slug, "/");
+ char slug_buf[256];
+ const char *rest;
+
+ if (slen == 0 || slen >= sizeof(slug_buf)) {
+ error_page("Not found", "No wiki named in the path.");
+ return;
+ }
+ memcpy(slug_buf, slug, slen);
+ slug_buf[slen] = '\0';
+ url_decode(slug_buf);
+ rest = slug + slen;
+ {
+ /* The page part is percent-encoded; decode into a copy so
+ * titles like "Water%20chlorination" reach wikid intact. */
+ char rest_buf[MAX_LINE];
+
+ strncpy(rest_buf, rest, sizeof(rest_buf) - 1);
+ rest_buf[sizeof(rest_buf) - 1] = '\0';
+ url_decode(rest_buf);
+ rest = rest_buf;
+
+ if (strcmp(rest, "/delete") == 0) {
+ if (strcmp(method, "POST") == 0)
+ route_delete(slug_buf, body);
+ else
+ error_page("Delete page", "Deletion needs a POST.");
+ return;
+ }
+ if (strcmp(rest, "/write") == 0) {
+ if (strcmp(method, "POST") == 0) {
+ route_write(slug_buf, body);
+ } else {
+ html_head("Write page");
+ write_form(slug_buf, NULL, NULL, NULL, NULL);
+ html_foot();
+ }
+ return;
+ }
+ if (rest[0] == '/' && rest[1] != '\0') {
+ route_page(slug_buf, rest + 1);
+ return;
+ }
+ if (rest[0] == '\0' || strcmp(rest, "/") == 0) {
+ route_wiki_index(slug_buf);
+ return;
+ }
+ }
+ }
+
+ error_page("Not found", "No such page.");
+}
+
+/* ------------------------------------------------------------------ main */
+
+static char *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 > MAX_BODY)
+ 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;
+}
+
+int main(void)
+{
+ const char *method = getenv("REQUEST_METHOD");
+ const char *uri = getenv("REQUEST_URI");
+ const char *qs = getenv("QUERY_STRING");
+ const char *script = getenv("SCRIPT_NAME");
+ const char *pathinfo = getenv("PATH_INFO");
+ char pathbuf[MAX_LINE], querybuf[MAX_LINE];
+ char *body = NULL;
+
+ if (method == NULL)
+ method = "GET";
+ if (uri == NULL)
+ uri = "/";
+ if (qs == NULL)
+ qs = "";
+
+ /* Where the CGI is mounted: SCRIPT_NAME for urls, PATH_INFO for routing. */
+ g_prefix[0] = '\0';
+ if (script != NULL && *script != '\0' && strcmp(script, "/") != 0)
+ snprintf(g_prefix, sizeof(g_prefix), "%s", script);
+
+ if (pathinfo != NULL && *pathinfo != '\0') {
+ uri = pathinfo;
+ } else if (g_prefix[0] != '\0') {
+ size_t plen = strlen(g_prefix);
+
+ if (strncmp(uri, g_prefix, plen) == 0) {
+ uri += plen;
+ if (*uri == '\0')
+ uri = "/";
+ }
+ }
+
+ split_path(uri, pathbuf, sizeof(pathbuf), querybuf, sizeof(querybuf));
+ if (querybuf[0] == '\0' && qs[0] != '\0') {
+ strncpy(querybuf, qs, sizeof(querybuf) - 1);
+ querybuf[sizeof(querybuf) - 1] = '\0';
+ }
+
+ if (strcmp(method, "POST") == 0)
+ body = read_body();
+
+ printf("Content-Type: text/html; charset=utf-8\r\n\r\n");
+ handle_request(method, pathbuf, querybuf, body != NULL ? body : "");
+ free(body);
+ return 0;
+}