diff --git a/Makefile b/Makefile index 65d0307..8e9cb6c 100644 --- a/Makefile +++ b/Makefile @@ -1,19 +1,32 @@ -# junction — C99 + POSIX, no third-party libraries -CC ?= cc -CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Wpedantic -Wshadow -Wconversion +# junction — C99 + POSIX. TLS is optional: an OpenSSL build adds https:// upstreams +# and a TLS listener; J_WITH_TLS=0 gives a dependency-free binary. +CC ?= cc +CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Wpedantic -Wshadow -Wconversion CPPFLAGS += -D_POSIX_C_SOURCE=200809L -LDFLAGS ?= -PREFIX ?= /usr/local +LDFLAGS ?= +PREFIX ?= /usr/local +J_WITH_TLS ?= auto -SRC = src/config.c src/junction.c +SRC = src/config.c src/conn.c src/http.c src/cache.c src/junction.c OBJ = $(SRC:.c=.o) +ifeq ($(J_WITH_TLS),0) +TLS_LIBS = +else +ifeq ($(wildcard /usr/include/openssl/ssl.h),) +TLS_LIBS = +else +CPPFLAGS += -DJ_HAVE_TLS +TLS_LIBS = -lssl -lcrypto +endif +endif + all: junction junction: $(OBJ) - $(CC) $(CFLAGS) $(OBJ) -o $@ $(LDFLAGS) + $(CC) $(CFLAGS) $(OBJ) -o $@ $(LDFLAGS) $(TLS_LIBS) -src/%.o: src/%.c src/config.h +src/%.o: src/%.c src/config.h src/conn.h src/http.h src/cache.h $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ test: junction diff --git a/README.md b/README.md index 71fc357..1021f77 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,63 @@ # junction -A policy router for OpenAI-compatible model endpoints. **C99 + POSIX, no -dependencies beyond libc.** +A policy router for OpenAI-compatible model endpoints. **C99 + POSIX**, plus +OpenSSL when built with TLS. No branding in the code: the only name in the sources +is `junction` (even the log prefix is a config keyword), so a product name can be +layered on later without touching logic. `junction` sits in front of N model servers and decides **per request** which one -serves it — and what to do when none of them wants to. No product name, no vendor -strings, no branding anywhere in the code: the only name in the sources is -`junction` itself, so branding can be layered on later without touching logic. +serves it — and what to do when none of them wants to. -## What it does that a static proxy does not +## What it does - **Ordered rules, like a firewall.** `req ... pass ...` / `block`, first match wins. Match on model glob, path glob and required context. - **Shell pre-hooks per endpoint.** A hook that exits non-zero means "not available - yet" — the endpoint is retried with backoff for a bounded time, optionally after - running a wake command. Hooks get the request in their environment. -- **Unreachable means offline, immediately.** A failed TCP connect is not a retry - case: the endpoint is marked offline and skipped in milliseconds. -- **Honest timeouts.** Two of them per endpoint: *idle* ("nothing arrived for N - seconds") and *total*. Silence is logged as `still_working` and the wait - continues; it never looks like a hang and it never abandons a model that is - legitimately thinking. -- **Context-aware.** A request needing more context than an endpoint offers is - refused for that endpoint instead of being silently truncated. + yet" — retried with backoff for a bounded time, optionally after a wake command. +- **Unreachable means offline, immediately.** A connect failure is not a retry case. +- **Honest timeouts.** Two per endpoint: *idle* ("nothing for N seconds", logged as + `still_working`) and *total*. A thinking model never looks like a hang. +- **Context-aware.** A request needing more context than an endpoint offers skips it + instead of being silently truncated. - **Failover with cooldown**, and a `503` that names why each endpoint was skipped. +- **TLS both ways.** `https://` upstreams (SNI, optional chain + hostname + verification, custom CA) and an optional TLS listener — no stunnel needed. +- **Chunked transfer coding.** Chunked request bodies are decoded; chunked responses + are relayed byte for byte, so streaming (`text/event-stream`) survives untouched. +- **Response cache.** Memory-only LRU keyed on method + path + model + body, honouring + `Cache-Control: no-store/private`, bypassed by the client's `no-cache`, flushed + with one call. Streams are never cached. +- **Header passthrough.** Client headers are forwarded (hop-by-hop removed), static + headers can be added per endpoint, and `X-Forwarded-For`/`Proto` are appended. + Every response carries `X-Junction-Endpoint`, `X-Junction-Ms`, `X-Junction-Cache`. ## Build / run ```bash -make # -> ./junction -make test # stub endpoints, no network, no models (~30 s) -sudo make install # /usr/local/bin + /usr/local/share/junction +make # -> ./junction (TLS auto-detected via openssl headers) +make J_WITH_TLS=0 # dependency-free build: http:// upstreams only +make test # stub endpoints, no network, no models (~40 s) +sudo make install # /usr/local/bin + /usr/local/share/junction ./junction --config junction.conf [--port 8090] -curl -s localhost:8090/status | python3 -m json.tool # (only for pretty-printing) +curl -s localhost:8090/status ``` ## Configuration — pf.conf style -Keyword, arguments, braces. `#` starts a comment, double quotes group words, unknown +Keyword, arguments, braces. `#` comments, double quotes group words, unknown keywords are a **hard error with a line number**. Full example: `config.example`. ``` +# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem listen 0.0.0.0:8090 chars_per_token 4 default_max_tokens 4096 connect_timeout_ms 1500 offline_hold_s 20 +cache_ttl 300 +cache_entries 128 +cache_bytes 33554432 endpoint peer1 { base http://192.0.2.10:8081/v1 @@ -62,19 +73,22 @@ endpoint peer1 { endpoint workstation { base http://192.0.2.20:8080/v1 context 128000 - priority 10 timeout 1800 idle_timeout 30 - hook_retry 180 # wait up to 3 min for the hooks to pass + hook_retry 180 hook_backoff 5 wake /usr/local/share/junction/hooks/wake-wol.sh hook /usr/local/share/junction/hooks/check-http.sh + header "X-Box: workstation" } endpoint cloud { base https://api.example.com/v1 context 200000 - priority 90 + timeout 900 + idle_timeout 120 + cache off + tls_verify on api_key_env EXAMPLE_API_KEY } @@ -94,25 +108,29 @@ req [for ] [path ] [need >N | [,...] [as ] | block ) ``` -- `for` — model name glob (`fnmatch`), matches the model in the request body. +- `for` — model glob (`fnmatch`) against the model in the request body. - `need` — estimated tokens (`chars/4 + max_tokens`); `>64000` means "needs more - than 64k", so small endpoints are not even considered. + than 64k". - `check hooks|none` — override the endpoint's hook list for this rule. -- `retry ` — override `hook_retry` for this rule ("wait up to N s until the box - is ready"). +- `retry ` — override `hook_retry` ("wait up to N s for the box"). - `pass a, b` — try `a`, then `b` on failure. -- `as ` — rewrite the `model` field before forwarding (the local box may - serve a different name than the client asked for). +- `as ` — rewrite the `model` field before forwarding. - `block` — refuse with `403`. -No matching rule at all → `503 no_matching_rule`. That is deliberate: an unmatched -request is a configuration gap, not something to quietly send to a cloud. +No matching rule → `503 no_matching_rule`: an unmatched request is a config gap, not +something to quietly send to a cloud. -## Endpoint keys +## Keys + +Global: `listen`, `chars_per_token`, `default_max_tokens`, `connect_timeout_ms`, +`offline_hold_s`, `max_body_bytes`, `log_prefix`, `cache_ttl`, `cache_entries`, +`cache_bytes`. + +Endpoint: | key | meaning | |---|---| -| `base` | OpenAI-compatible base URL including `/v1` (http:// only in this version) | +| `base` | OpenAI-compatible base URL including `/v1` (`http://` or `https://`) | | `context` | usable context window in tokens | | `kind` | free-form label (`local`, `remote`, `cloud`) | | `priority` | lower wins when a rule lists several | @@ -123,11 +141,15 @@ request is a configuration gap, not something to quietly send to a cloud. | `hook_retry` | how long to keep retrying hooks | | `hook_backoff` | sleep between hook attempts | | `wake` | command run once before the hook retries begin | -| `api_key_env` | env var whose value is sent as `Authorization: Bearer ...` | +| `api_key_env` | env var sent as `Authorization: Bearer ...` | +| `tls_verify` | `on` (default) / `off` | +| `tls_ca` | CA bundle for a private CA (default: system store) | +| `cache` | `on` / `off` for this endpoint | +| `header` | static request header, `"Name: value"` (repeatable) | ## Hooks -Plain POSIX shell. Environment: +Plain POSIX shell, with the request in the environment: ``` JUNCTION_BACKEND JUNCTION_BASE JUNCTION_PATH JUNCTION_MODEL @@ -135,30 +157,30 @@ JUNCTION_NEED_TOKENS JUNCTION_ATTEMPT ``` Exit non-zero and print the reason on stdout — it lands in `/status` and in the -`503` body. Examples in `hooks/`: `check-http.sh`, `check-budget.sh` -(refuse below a threshold read from any JSON URL), `wake-wol.sh` (magic packet). +`503` body. Examples in `hooks/`: `check-http.sh`, `check-budget.sh`, +`wake-wol.sh`. ## Control plane | Method | Path | Effect | |---|---|---| -| GET | `/status` | endpoints (state, counters, last error), rules | +| GET | `/status` | endpoints, counters, cache stats, rules | | POST | `/admin/pause/` | stop routing there | -| POST | `/admin/resume/` | clear pause + cooldown + offline window | +| POST | `/admin/resume/` | clear pause + cooldown + offline | +| POST | `/admin/flush/cache` | drop every cached response | -Everything else is proxied to the endpoint the rules choose, including streaming -responses (the upstream's framing is relayed byte for byte). +Everything else is proxied to the endpoint the rules choose. ## Known limits (v0.1, deliberately named) - **One request at a time.** The accept loop handles a request to completion before - taking the next one. A slow model therefore queues everything behind it. This - keeps the counters and the state machine honest; a thread pool is the next step. -- **http:// upstreams only.** No TLS client yet — a cloud endpoint needs a local - terminator (stunnel, nginx) in front. -- **Chunked request bodies are not supported** (Content-Length only). Chunked - *responses* are relayed fine. -- **Token estimate is `chars/4`**, good enough to pick an endpoint, not to bill. + the next. A slow model queues everything behind it. Threads are the next step. +- **HTTP/1.1 only** — no HTTP/2, no h2c. +- **The cache is memory-only** and lost on restart; it is not shared between + processes and does not survive `SIGHUP`. +- **TLS client is verified** against the system store or `tls_ca`; there is no + certificate pinning and no client-certificate auth. +- **Token estimate is `chars/4`** — good enough to choose an endpoint, not to bill. ## Tests @@ -166,7 +188,14 @@ responses (the upstream's framing is relayed byte for byte). tests/run.sh ``` -Builds stubs (C) for: a failing endpoint, a gated one (hook refuses until a file -appears), a slow one (6 s silence), and a dead port. Checks offline detection, -cooldown/failover, hook retry, `still_working` logging, block rules, catch-all, -model rewrite, `no_matching_rule`, and two config-error cases. Pass = `PASS`. +C stubs for a failing endpoint, a hook-gated one, a slow one (6 s silence), a dead +port, and a TLS peer with a self-signed cert. Checks: offline detection, cooldown and +failover, hook retry, `still_working`, block rules, catch-all, model rewrite, +`no_matching_rule`, config errors, chunked request decoding (byte-exact body), +cache miss/hit/flush/bypass, header passthrough and injection, TLS listener, https +upstream, and that certificate verification actually refuses a self-signed peer. +Pass = `PASS`. + +The suite refuses to run if a test port is already taken — a stale `junction` on +`:8105` once answered requests with someone else's config and made a good test look +broken. diff --git a/config.example b/config.example index 9e125d1..0fedbc3 100644 --- a/config.example +++ b/config.example @@ -1,13 +1,23 @@ # junction.conf — pf.conf-style. keyword, arguments, braces. '#' starts a comment. # Double quotes group words. Unknown keywords are a hard error with a line number. +# Plain listener: listen 0.0.0.0:8090 +# ... or TLS (https clients without a proxy in front): +# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem + chars_per_token 4 default_max_tokens 4096 connect_timeout_ms 1500 offline_hold_s 20 max_body_bytes 67108864 +# Response cache (memory only). ttl 0 disables it. Only complete, non-streamed 200 +# answers are stored, keyed on method + path + model + body. +cache_ttl 300 +cache_entries 128 +cache_bytes 33554432 + # --------------------------------------------------------------------- endpoints endpoint peer1 { base http://192.0.2.10:8081/v1 @@ -53,7 +63,11 @@ endpoint cloud { priority 90 timeout 900 idle_timeout 120 + cache off # never store cloud answers api_key_env EXAMPLE_API_KEY + tls_verify on # off only for a self-signed internal endpoint + # tls_ca /etc/junction/tls/internal-ca.pem + header "X-Title: olivia" # static header sent with every request here } # ------------------------------------------------------------------------- rules diff --git a/src/cache.c b/src/cache.c new file mode 100644 index 0000000..8725e63 --- /dev/null +++ b/src/cache.c @@ -0,0 +1,180 @@ +/* junction/cache.c — LRU cache of complete (non-streamed) responses. + * + * Only fully received, non-streaming responses are cached: a streamed answer has no + * end we could store, and replaying one would turn a live stream into a fake one. + */ +#define _POSIX_C_SOURCE 200809L + +#include "cache.h" + +#include +#include +#include + +typedef struct entry { + uint64_t key; + char *head; + size_t head_len; + char *body; + size_t body_len; + double stored; + double ttl; + struct entry *prev; /* more recent */ + struct entry *next; /* less recent */ +} entry; + +static entry *g_head, *g_tail; +static size_t g_entries, g_bytes; +static size_t g_max_entries = 0, g_max_bytes = 0; +static double g_ttl = 0; +static unsigned long g_hits, g_misses; + +static double now_s(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} + +void j_cache_config(size_t max_entries, size_t max_bytes, double ttl) +{ + g_max_entries = max_entries; + g_max_bytes = max_bytes; + g_ttl = ttl; +} + +void j_cache_stats(size_t *entries, size_t *bytes, unsigned long *hits, unsigned long *misses) +{ + if (entries) *entries = g_entries; + if (bytes) *bytes = g_bytes; + if (hits) *hits = g_hits; + if (misses) *misses = g_misses; +} + +/* FNV-1a, 64 bit — enough to key a local cache; this is not a security boundary. */ +static void fnv(uint64_t *h, const void *p, size_t n) +{ + const unsigned char *b = p; + for (size_t i = 0; i < n; i++) { + *h ^= b[i]; + *h *= 1099511628211ULL; + } +} + +uint64_t j_cache_key(const char *method, const char *path, const char *model, + const char *body, size_t body_len) +{ + uint64_t h = 1469598103934665603ULL; + fnv(&h, method, strlen(method)); + fnv(&h, "\x1f", 1); + fnv(&h, path, strlen(path)); + fnv(&h, "\x1f", 1); + fnv(&h, model, strlen(model)); + fnv(&h, "\x1f", 1); + if (body) fnv(&h, body, body_len); + return h; +} + +static void unlink_entry(entry *e) +{ + if (e->prev) e->prev->next = e->next; else g_head = e->next; + if (e->next) e->next->prev = e->prev; else g_tail = e->prev; + e->prev = e->next = NULL; +} + +static void free_entry(entry *e) +{ + unlink_entry(e); + g_entries--; + g_bytes -= e->head_len + e->body_len; + free(e->head); + free(e->body); + free(e); +} + +static void touch(entry *e) +{ + if (e == g_head) return; + unlink_entry(e); + e->prev = NULL; + e->next = g_head; + if (g_head) g_head->prev = e; + g_head = e; + if (!g_tail) g_tail = e; +} + +static void expire_old(void) +{ + double t = now_s(); + entry *e = g_tail; + while (e) { + entry *prev = e->prev; + if (e->ttl > 0 && t - e->stored >= e->ttl) free_entry(e); + e = prev; + } +} + +int j_cache_get(uint64_t key, const char **head, size_t *head_len, + const char **body, size_t *body_len, double *age) +{ + expire_old(); + for (entry *e = g_head; e; e = e->next) { + if (e->key != key) continue; + if (e->ttl > 0 && now_s() - e->stored >= e->ttl) { free_entry(e); break; } + touch(e); + g_hits++; + if (head) *head = e->head; + if (head_len) *head_len = e->head_len; + if (body) *body = e->body; + if (body_len) *body_len = e->body_len; + if (age) *age = now_s() - e->stored; + return 0; + } + g_misses++; + return -1; +} + +int j_cache_put(uint64_t key, const char *head, size_t head_len, + const char *body, size_t body_len, double ttl) +{ + if (g_max_entries == 0 || g_max_bytes == 0) return -1; + if (ttl <= 0) ttl = g_ttl; + if (ttl <= 0) return -1; + if (head_len + body_len > g_max_bytes) return -1; + + for (entry *e = g_head; e; e = e->next) { + if (e->key == key) { free_entry(e); break; } + } + while ((g_entries + 1 > g_max_entries) || (g_bytes + head_len + body_len > g_max_bytes)) { + if (!g_tail) break; + free_entry(g_tail); + } + + entry *e = calloc(1, sizeof *e); + if (!e) return -1; + e->head = malloc(head_len ? head_len : 1); + e->body = malloc(body_len ? body_len : 1); + if (!e->head || !e->body) { free(e->head); free(e->body); free(e); return -1; } + memcpy(e->head, head, head_len); + memcpy(e->body, body, body_len); + e->head_len = head_len; + e->body_len = body_len; + e->key = key; + e->stored = now_s(); + e->ttl = ttl; + + e->next = g_head; + if (g_head) g_head->prev = e; + g_head = e; + if (!g_tail) g_tail = e; + g_entries++; + g_bytes += head_len + body_len; + return 0; +} + +void j_cache_clear(void) +{ + while (g_head) free_entry(g_head); + g_head = g_tail = NULL; + g_entries = g_bytes = 0; +} diff --git a/src/cache.h b/src/cache.h new file mode 100644 index 0000000..244d98f --- /dev/null +++ b/src/cache.h @@ -0,0 +1,21 @@ +/* junction/cache.h — small in-memory response cache with LRU eviction. */ +#ifndef J_CACHE_H +#define J_CACHE_H + +#include +#include + +void j_cache_config(size_t max_entries, size_t max_bytes, double ttl); +void j_cache_stats(size_t *entries, size_t *bytes, unsigned long *hits, unsigned long *misses); +void j_cache_clear(void); + +uint64_t j_cache_key(const char *method, const char *path, const char *model, + const char *body, size_t body_len); + +/* Returned pointers stay valid until the next put/clear — copy before storing. */ +int j_cache_get(uint64_t key, const char **head, size_t *head_len, + const char **body, size_t *body_len, double *age); +int j_cache_put(uint64_t key, const char *head, size_t head_len, + const char *body, size_t body_len, double ttl); + +#endif diff --git a/src/config.c b/src/config.c index 9963645..e64465b 100644 --- a/src/config.c +++ b/src/config.c @@ -78,6 +78,9 @@ void j_config_defaults(j_config *cfg) cfg->connect_timeout_ms = 1500; cfg->offline_hold_s = 20; cfg->max_body_bytes = 64 * 1024 * 1024; + cfg->cache_ttl_s = 0; + cfg->cache_entries = 128; + cfg->cache_bytes = 32L * 1024 * 1024; snprintf(cfg->log_prefix, sizeof cfg->log_prefix, "junction"); } @@ -92,6 +95,8 @@ static void endpoint_defaults(j_endpoint *ep) ep->hook_retry_s = 0; ep->hook_backoff_s = 5; ep->last_ms = -1; + ep->tls_verify = 1; + ep->cache_on = -1; } static int as_double(const char *s, double *dst) @@ -141,7 +146,17 @@ static int parse_listen(j_config *cfg, const char *v) 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, "cache_ttl")) { if (n != 2 || as_double(w[1], &cfg->cache_ttl_s)) goto bad; return 0; } + if (!strcmp(k, "cache_entries")) { if (n != 2 || as_long(w[1], &cfg->cache_entries)) goto bad; return 0; } + if (!strcmp(k, "cache_bytes")) { if (n != 2 || as_long(w[1], &cfg->cache_bytes)) goto bad; return 0; } if (!strcmp(k, "listen")) { + if (n == 5 && !strcmp(w[2], "tls")) { + if (parse_listen(cfg, w[1])) goto bad; + cfg->listen_tls = 1; + snprintf(cfg->tls_cert, sizeof cfg->tls_cert, "%s", w[3]); + snprintf(cfg->tls_key, sizeof cfg->tls_key, "%s", w[4]); + return 0; + } if (n != 2 || parse_listen(cfg, w[1])) goto bad; return 0; } @@ -176,6 +191,44 @@ static int endpoint_kw(j_endpoint *ep, char **w, int n, int lineno, char *err, s 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, "tls_verify")) { + if (n != 2) goto bad; + if (!strcmp(w[1], "on")) ep->tls_verify = 1; + else if (!strcmp(w[1], "off")) ep->tls_verify = 0; + else goto bad; + return 0; + } + if (!strcmp(k, "tls_ca")) { if (n != 2) goto bad; snprintf(ep->tls_ca, sizeof ep->tls_ca, "%s", w[1]); return 0; } + if (!strcmp(k, "cache")) { + if (n != 2) goto bad; + if (!strcmp(w[1], "on")) ep->cache_on = 1; + else if (!strcmp(w[1], "off")) ep->cache_on = 0; + else goto bad; + return 0; + } + if (!strcmp(k, "header")) { + /* header "X-Name: value" — repeatable; forwarded on every request to this endpoint */ + if (n < 2) goto bad; + if (ep->header_count >= J_MAX_EP_HEADERS) { + snprintf(err, errlen, "line %d: endpoint %s has more than %d headers", lineno, + ep->name, J_MAX_EP_HEADERS); + return -1; + } + char joined[J_HDR_LINE_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; + } + if (!strchr(joined, ':')) { + snprintf(err, errlen, "line %d: header needs 'Name: value', got '%s'", lineno, joined); + return -1; + } + snprintf(ep->headers[ep->header_count++], J_HDR_LINE_MAX, "%s", joined); + return 0; + } if (!strcmp(k, "hook")) { if (n < 2) goto bad; if (ep->hook_count >= J_MAX_HOOKS) { diff --git a/src/config.h b/src/config.h index e32a1b8..583e289 100644 --- a/src/config.h +++ b/src/config.h @@ -45,6 +45,8 @@ #define J_URL_MAX 512 #define J_CMD_MAX 512 #define J_GLOB_MAX 128 +#define J_MAX_EP_HEADERS 8 +#define J_HDR_LINE_MAX 256 typedef struct { char name[J_NAME_MAX]; @@ -64,6 +66,12 @@ typedef struct { char wake[J_CMD_MAX]; char api_key_env[J_NAME_MAX]; + int tls_verify; /* default 1 */ + char tls_ca[J_URL_MAX]; /* "" = system CA store */ + int cache_on; /* -1 inherit, 0 off, 1 on */ + char headers[J_MAX_EP_HEADERS][J_HDR_LINE_MAX]; /* static request headers */ + int header_count; + /* runtime state — not from the file */ double offline_until; double cooldown_until; @@ -103,6 +111,14 @@ typedef struct { int max_body_bytes; char log_prefix[J_NAME_MAX]; + int listen_tls; + char tls_cert[J_URL_MAX]; + char tls_key[J_URL_MAX]; + + double cache_ttl_s; /* 0 = cache disabled */ + long cache_entries; + long cache_bytes; + j_endpoint endpoints[J_MAX_ENDPOINTS]; int endpoint_count; diff --git a/src/conn.c b/src/conn.c new file mode 100644 index 0000000..972e2db --- /dev/null +++ b/src/conn.c @@ -0,0 +1,326 @@ +/* junction/conn.c — plain TCP and TLS connections behind one handle. + * + * TLS is optional at build time (J_HAVE_TLS). Without OpenSSL the binary still + * builds and runs for http:// upstreams; a config that needs TLS is refused at + * startup with a clear message instead of failing at request time. + */ +#define _POSIX_C_SOURCE 200809L + +#include "conn.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef J_HAVE_TLS +#include +#include +#include + +static SSL_CTX *g_client_ctx; +static SSL_CTX *g_server_ctx; + +static void ssl_error(char *err, size_t errlen, const char *what) +{ + unsigned long e = ERR_get_error(); + char buf[256] = ""; + if (e) ERR_error_string_n(e, buf, sizeof buf); + snprintf(err, errlen, "%s: %s", what, buf[0] ? buf : "unknown TLS error"); +} + +int j_tls_available(void) { return 1; } + +#else + +int j_tls_available(void) { return 0; } + +#endif + +/* ------------------------------------------------------------------- helpers */ + +static double now_s(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} + +static int wait_fd(int fd, short events, double timeout_ms) +{ + struct pollfd p = { .fd = fd, .events = events, .revents = 0 }; + for (;;) { + int rc = poll(&p, 1, (int)timeout_ms + 1); + if (rc < 0 && errno == EINTR) continue; + return rc; + } +} + +static int tcp_connect(const char *host, const char *port, double timeout_ms, + char *err, size_t errlen) +{ + struct addrinfo hints, *res = NULL; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + int gai = getaddrinfo(host, port, &hints, &res); + if (gai != 0) { + snprintf(err, errlen, "resolve %s: %s", host, gai_strerror(gai)); + return -1; + } + int fd = -1; + for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { + int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); + if (s < 0) continue; + int flags = fcntl(s, F_GETFL, 0); + fcntl(s, F_SETFL, flags | O_NONBLOCK); + int rc = connect(s, ai->ai_addr, ai->ai_addrlen); + if (rc == 0) { fcntl(s, F_SETFL, flags); fd = s; break; } + if (errno == EINPROGRESS && wait_fd(s, POLLOUT, timeout_ms) == 1) { + int so_err = 0; + socklen_t sl = sizeof so_err; + getsockopt(s, SOL_SOCKET, SO_ERROR, &so_err, &sl); + if (!so_err) { fcntl(s, F_SETFL, flags); fd = s; break; } + errno = so_err; + } + snprintf(err, errlen, "connect %s:%s: %s", host, port, strerror(errno)); + close(s); + } + freeaddrinfo(res); + if (fd < 0 && !err[0]) snprintf(err, errlen, "connect %s:%s failed", host, port); + return fd; +} + +/* --------------------------------------------------------------------- open */ + +int j_conn_open(j_conn *c, const char *host, const char *port, int use_tls, int verify, + const char *ca_file, double timeout_ms, char *err, size_t errlen) +{ + c->fd = -1; + c->tls = NULL; + if (errlen) err[0] = '\0'; + + int fd = tcp_connect(host, port, timeout_ms, err, errlen); + if (fd < 0) return -1; + c->fd = fd; + + if (!use_tls) return 0; + +#ifdef J_HAVE_TLS + if (!g_client_ctx) { + g_client_ctx = SSL_CTX_new(TLS_client_method()); + if (!g_client_ctx) { ssl_error(err, errlen, "SSL_CTX_new"); close(fd); c->fd = -1; return -1; } + SSL_CTX_set_min_proto_version(g_client_ctx, TLS1_2_VERSION); + /* HTTP/1.0-style responses end at close. OpenSSL 3 treats a close without + * close_notify as an error ("unexpected eof"), which would turn a perfectly + * valid answer into a failure — for HTTP that close IS the terminator. */ +#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF + SSL_CTX_set_options(g_client_ctx, SSL_OP_IGNORE_UNEXPECTED_EOF); +#endif + } + SSL *ssl = SSL_new(g_client_ctx); + if (!ssl) { ssl_error(err, errlen, "SSL_new"); close(fd); c->fd = -1; return -1; } + SSL_set_tlsext_host_name(ssl, host); /* SNI: virtual hosts need it */ + if (verify) { + SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL); + if (ca_file && ca_file[0]) { + if (!SSL_CTX_load_verify_locations(g_client_ctx, ca_file, NULL)) { + ssl_error(err, errlen, "load CA file"); + SSL_free(ssl); close(fd); c->fd = -1; return -1; + } + } else { + SSL_CTX_set_default_verify_paths(g_client_ctx); + } + SSL_set1_host(ssl, host); /* hostname, not just any valid chain */ + } else { + SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL); + } + if (!SSL_set_fd(ssl, fd)) { ssl_error(err, errlen, "SSL_set_fd"); SSL_free(ssl); close(fd); c->fd = -1; return -1; } + + /* A handshake without an overall deadline can spin forever on a peer that + * accepted the TCP connection but never answers. */ + double hs_deadline = now_s() + (timeout_ms > 5000 ? timeout_ms : 5000) / 1000.0; + for (;;) { + if (now_s() >= hs_deadline) { + snprintf(err, errlen, "tls handshake timed out"); + SSL_free(ssl); close(fd); c->fd = -1; + return -1; + } + int rc = SSL_connect(ssl); + if (rc == 1) break; + int e = SSL_get_error(ssl, rc); + if (e == SSL_ERROR_WANT_READ) { wait_fd(fd, POLLIN, timeout_ms); continue; } + if (e == SSL_ERROR_WANT_WRITE) { wait_fd(fd, POLLOUT, timeout_ms); continue; } + if (verify) { + long vr = SSL_get_verify_result(ssl); + if (vr != X509_V_OK) + snprintf(err, errlen, "tls_verify_failed: %s", + X509_verify_cert_error_string(vr)); + else + ssl_error(err, errlen, "tls handshake"); + } else { + ssl_error(err, errlen, "tls handshake"); + } + SSL_free(ssl); close(fd); c->fd = -1; + return -1; + } + c->tls = ssl; + return 0; +#else + snprintf(err, errlen, "https upstream but this build has no TLS (J_HAVE_TLS)"); + close(fd); + c->fd = -1; + return -1; +#endif +} + +/* --------------------------------------------------------------------- I/O */ + +ssize_t j_conn_read(j_conn *c, void *buf, size_t len, char *err, size_t errlen) +{ + if (c->fd < 0) return -1; +#ifdef J_HAVE_TLS + if (c->tls) { + SSL *ssl = c->tls; + for (;;) { + int rc = SSL_read(ssl, buf, (int)len); + if (rc > 0) return rc; + int e = SSL_get_error(ssl, rc); + if (e == SSL_ERROR_WANT_READ) { wait_fd(c->fd, POLLIN, 1000); continue; } + if (e == SSL_ERROR_WANT_WRITE) { wait_fd(c->fd, POLLOUT, 1000); continue; } + if (e == SSL_ERROR_ZERO_RETURN) return 0; + if (e == SSL_ERROR_SYSCALL && ERR_peek_error() == 0) return 0; /* plain EOF */ + if (e == SSL_ERROR_SSL) { + unsigned long u = ERR_peek_error(); + if (u == 0) return 0; + } + ssl_error(err, errlen, "tls read"); + return -1; + } + } +#endif + for (;;) { + ssize_t n = read(c->fd, buf, len); + if (n < 0 && errno == EINTR) continue; + if (n < 0) snprintf(err, errlen, "read: %s", strerror(errno)); + return n; + } +} + +ssize_t j_conn_write(j_conn *c, const void *buf, size_t len, char *err, size_t errlen) +{ + if (c->fd < 0) return -1; +#ifdef J_HAVE_TLS + if (c->tls) { + SSL *ssl = c->tls; + size_t off = 0; + while (off < len) { + int rc = SSL_write(ssl, (const char *)buf + off, (int)(len - off)); + if (rc > 0) { off += (size_t)rc; continue; } + int e = SSL_get_error(ssl, rc); + if (e == SSL_ERROR_WANT_READ) { wait_fd(c->fd, POLLIN, 1000); continue; } + if (e == SSL_ERROR_WANT_WRITE) { wait_fd(c->fd, POLLOUT, 1000); continue; } + ssl_error(err, errlen, "tls write"); + return -1; + } + return (ssize_t)off; + } +#endif + size_t off = 0; + while (off < len) { + ssize_t n = write(c->fd, (const char *)buf + off, len - off); + if (n < 0) { + if (errno == EINTR) continue; + snprintf(err, errlen, "write: %s", strerror(errno)); + return -1; + } + off += (size_t)n; + } + return (ssize_t)off; +} + +int j_conn_pending(const j_conn *c) +{ +#ifdef J_HAVE_TLS + if (c->tls) return SSL_pending((SSL *)c->tls); +#endif + (void)c; + return 0; +} + +void j_conn_close(j_conn *c) +{ +#ifdef J_HAVE_TLS + if (c->tls) { + SSL_shutdown((SSL *)c->tls); + SSL_free((SSL *)c->tls); + c->tls = NULL; + } +#endif + if (c->fd >= 0) close(c->fd); + c->fd = -1; +} + +/* ------------------------------------------------------------------ server */ + +#ifdef J_HAVE_TLS +int j_tls_server_start(const char *cert, const char *key, char *err, size_t errlen) +{ + g_server_ctx = SSL_CTX_new(TLS_server_method()); + if (!g_server_ctx) { ssl_error(err, errlen, "SSL_CTX_new(server)"); return -1; } + SSL_CTX_set_min_proto_version(g_server_ctx, TLS1_2_VERSION); + if (SSL_CTX_use_certificate_chain_file(g_server_ctx, cert) != 1) { + ssl_error(err, errlen, "load certificate"); + return -1; + } + if (SSL_CTX_use_PrivateKey_file(g_server_ctx, key, SSL_FILETYPE_PEM) != 1) { + ssl_error(err, errlen, "load private key"); + return -1; + } + if (SSL_CTX_check_private_key(g_server_ctx) != 1) { + ssl_error(err, errlen, "certificate and key do not match"); + return -1; + } + return 0; +} + +int j_tls_server_accept(j_conn *c, int fd, char *err, size_t errlen) +{ + if (!g_server_ctx) { snprintf(err, errlen, "no TLS context"); return -1; } + SSL *ssl = SSL_new(g_server_ctx); + if (!ssl) { ssl_error(err, errlen, "SSL_new(server)"); return -1; } + if (!SSL_set_fd(ssl, fd)) { ssl_error(err, errlen, "SSL_set_fd"); SSL_free(ssl); return -1; } + for (;;) { + int rc = SSL_accept(ssl); + if (rc == 1) break; + int e = SSL_get_error(ssl, rc); + if (e == SSL_ERROR_WANT_READ) { wait_fd(fd, POLLIN, 5000); continue; } + if (e == SSL_ERROR_WANT_WRITE) { wait_fd(fd, POLLOUT, 5000); continue; } + ssl_error(err, errlen, "tls accept"); + SSL_free(ssl); + return -1; + } + c->fd = fd; + c->tls = ssl; + return 0; +} +#else +int j_tls_server_start(const char *cert, const char *key, char *err, size_t errlen) +{ + (void)cert; (void)key; + snprintf(err, errlen, "this build has no TLS support (J_HAVE_TLS)"); + return -1; +} + +int j_tls_server_accept(j_conn *c, int fd, char *err, size_t errlen) +{ + (void)c; (void)fd; + snprintf(err, errlen, "this build has no TLS support"); + return -1; +} +#endif diff --git a/src/conn.h b/src/conn.h new file mode 100644 index 0000000..ccac557 --- /dev/null +++ b/src/conn.h @@ -0,0 +1,35 @@ +/* junction/conn.h — one connection handle that may or may not be TLS. + * + * Everything above this layer (HTTP parsing, relaying) talks to j_conn and never + * touches a raw fd, so TLS is a property of the connection rather than a special + * case in the request path. + */ +#ifndef J_CONN_H +#define J_CONN_H + +#include +#include + +typedef struct { + int fd; + void *tls; /* SSL * when TLS, NULL otherwise */ + const char *role; /* "client" or "upstream" — used for progress logging */ +} j_conn; + +#define J_CONN_INIT { -1, NULL, NULL } + +/* Client side. use_tls selects TLS; verify 1 = check chain + hostname. */ +int j_conn_open(j_conn *c, const char *host, const char *port, int use_tls, int verify, + const char *ca_file, double timeout_ms, char *err, size_t errlen); + +ssize_t j_conn_read(j_conn *c, void *buf, size_t len, char *err, size_t errlen); +ssize_t j_conn_write(j_conn *c, const void *buf, size_t len, char *err, size_t errlen); +int j_conn_pending(const j_conn *c); /* decrypted bytes already buffered by TLS */ +void j_conn_close(j_conn *c); + +/* Server side: one context for the listener. */ +int j_tls_server_start(const char *cert, const char *key, char *err, size_t errlen); +int j_tls_server_accept(j_conn *c, int fd, char *err, size_t errlen); +int j_tls_available(void); + +#endif diff --git a/src/http.c b/src/http.c new file mode 100644 index 0000000..3c4e32a --- /dev/null +++ b/src/http.c @@ -0,0 +1,385 @@ +/* junction/http.c — buffers, header arrays, chunked coding. + * + * The buffer type exists because of a bug that cost a debugging session: a single + * read() from a socket normally returns the header block AND the first body bytes. + * Any code that parses the headers and then reads the body "again" must replay the + * bytes it already consumed, or it waits forever for data it discarded. + */ +#define _POSIX_C_SOURCE 200809L + +#include "http.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#define J_READ_CHUNK 8192 + +static double now_s(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} + +/* ------------------------------------------------------------------- buffer */ + +void j_buf_init(j_buf *b) +{ + b->data = NULL; + b->len = 0; + b->cap = 0; +} + +void j_buf_free(j_buf *b) +{ + free(b->data); + j_buf_init(b); +} + +void j_buf_reset(j_buf *b) { b->len = 0; } + +int j_buf_reserve(j_buf *b, size_t need) +{ + if (b->cap >= need) return 0; + size_t cap = b->cap ? b->cap : 4096; + while (cap < need) cap *= 2; + char *p = realloc(b->data, cap); + if (!p) return -1; + b->data = p; + b->cap = cap; + return 0; +} + +int j_buf_append(j_buf *b, const void *p, size_t n) +{ + if (j_buf_reserve(b, b->len + n + 1)) return -1; + memcpy(b->data + b->len, p, n); + b->len += n; + b->data[b->len] = '\0'; /* always NUL-terminated for string helpers */ + return 0; +} + +static void (*g_progress)(const char *role, double idle_s); + +void j_set_progress(void (*fn)(const char *role, double idle_s)) { g_progress = fn; } + +/* Wait for readability. A silent window is not an error: the request stays alive until + * the deadline, and the wait is reported so a slow model looks like progress. */ +static int wait_readable(j_conn *c, double idle_s, double deadline) +{ + for (;;) { + if (j_conn_pending(c) > 0) return 1; + if (now_s() >= deadline) return 0; + double left = deadline - now_s(); + double t = left < idle_s ? left : idle_s; + struct pollfd p = { .fd = c->fd, .events = POLLIN, .revents = 0 }; + int rc = poll(&p, 1, (int)(t * 1000.0) + 1); + if (rc < 0) { if (errno == EINTR) continue; return -1; } + if (rc == 0) { + if (g_progress) g_progress(c->role ? c->role : "upstream", idle_s); + continue; /* keep waiting until the deadline */ + } + return 1; + } +} + +ssize_t j_buf_read_until(j_conn *c, j_buf *b, const char *needle, size_t max, + double idle_s, double deadline, char *err, size_t errlen) +{ + size_t nlen = strlen(needle); + for (;;) { + if (b->len >= nlen) { + char *hit = NULL; + /* search from the start; header blocks are small */ + for (size_t i = 0; i + nlen <= b->len; i++) { + if (!memcmp(b->data + i, needle, nlen)) { hit = b->data + i; break; } + } + if (hit) { + /* pointer difference + length is a positive offset; the cast is the + * only place where unsigned -> signed happens, so keep it local */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-conversion" + return (ssize_t)((hit - b->data) + nlen); +#pragma GCC diagnostic pop + } + } + if (b->len > max) { snprintf(err, errlen, "header_block_too_large"); return -1; } + int w = wait_readable(c, idle_s, deadline); + if (w < 0) { snprintf(err, errlen, "poll: %s", strerror(errno)); return -1; } + if (w == 0) { snprintf(err, errlen, "timeout_waiting_headers"); return -2; } + if (j_buf_reserve(b, b->len + J_READ_CHUNK + 1)) { snprintf(err, errlen, "oom"); return -1; } + ssize_t n = j_conn_read(c, b->data + b->len, J_READ_CHUNK, err, errlen); + if (n < 0) return -1; + if (n == 0) { snprintf(err, errlen, "eof_in_headers"); return -1; } + b->len += (size_t)n; + b->data[b->len] = '\0'; + } +} + +int j_buf_ensure(j_conn *c, j_buf *b, size_t from, size_t n, double idle_s, + double deadline, char *err, size_t errlen) +{ + while (b->len - from < n) { + int w = wait_readable(c, idle_s, deadline); + if (w < 0) { snprintf(err, errlen, "poll: %s", strerror(errno)); return -1; } + if (w == 0) { snprintf(err, errlen, "timeout_waiting_body"); return -2; } + if (j_buf_reserve(b, b->len + J_READ_CHUNK + 1)) { snprintf(err, errlen, "oom"); return -1; } + ssize_t got = j_conn_read(c, b->data + b->len, J_READ_CHUNK, err, errlen); + if (got < 0) return -1; + if (got == 0) { snprintf(err, errlen, "eof_in_body"); return -1; } + b->len += (size_t)got; + b->data[b->len] = '\0'; + } + return 0; +} + +/* ------------------------------------------------------------------ headers */ + +void j_hdrs_init(j_hdrs *h) { h->n = 0; } + +int j_hdrs_find(const j_hdrs *h, const char *name, char *out, size_t outlen) +{ + for (int i = 0; i < h->n; i++) { + if (!strcasecmp(h->it[i].name, name)) { + snprintf(out, outlen, "%s", h->it[i].value); + return 0; + } + } + return -1; +} + +int j_hdrs_count(const j_hdrs *h, const char *name) +{ + int n = 0; + for (int i = 0; i < h->n; i++) if (!strcasecmp(h->it[i].name, name)) n++; + return n; +} + +void j_hdrs_add(j_hdrs *h, const char *name, const char *value) +{ + if (h->n >= J_MAX_HDRS) return; /* dropping beats corrupting */ + snprintf(h->it[h->n].name, J_HDR_NAME, "%s", name); + snprintf(h->it[h->n].value, J_HDR_VALUE, "%s", value); + h->n++; +} + +void j_hdrs_del(j_hdrs *h, const char *name) +{ + int o = 0; + for (int i = 0; i < h->n; i++) { + if (!strcasecmp(h->it[i].name, name)) continue; + if (o != i) h->it[o] = h->it[i]; + o++; + } + h->n = o; +} + +void j_hdrs_set(j_hdrs *h, const char *name, const char *value) +{ + j_hdrs_del(h, name); + j_hdrs_add(h, name, value); +} + +int j_hdrs_has_token(const j_hdrs *h, const char *name, const char *token) +{ + char v[J_HDR_VALUE]; + if (j_hdrs_find(h, name, v, sizeof v)) return 0; + for (char *p = v; *p; p++) *p = (char)tolower((unsigned char)*p); + return strstr(v, token) != NULL; +} + +int j_hdrs_parse(j_hdrs *h, const char *block, size_t len) +{ + /* block = header lines, one per CRLF, no request/status line */ + size_t i = 0; + while (i < len) { + size_t eol = i; + while (eol + 1 < len && !(block[eol] == '\r' && block[eol + 1] == '\n')) eol++; + if (eol + 1 >= len) eol = len; + size_t linelen = eol - i; + if (linelen == 0) break; + const char *line = block + i; + const char *colon = memchr(line, ':', linelen); + if (colon && colon > line) { + char name[J_HDR_NAME]; + size_t nl = (size_t)(colon - line); + if (nl >= sizeof name) nl = sizeof name - 1; + memcpy(name, line, nl); + name[nl] = '\0'; + const char *v = colon + 1; + const char *vend = line + linelen; + while (v < vend && (*v == ' ' || *v == '\t')) v++; + char value[J_HDR_VALUE]; + size_t vl = (size_t)(vend - v); + if (vl >= sizeof value) vl = sizeof value - 1; + memcpy(value, v, vl); + value[vl] = '\0'; + j_hdrs_add(h, name, value); + } + i = (eol + 2 <= len) ? eol + 2 : len; + } + return h->n; +} + +int j_is_hop_by_hop(const j_hdrs *h, const char *name) +{ + static const char *hop[] = { + "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", + "TE", "Trailer", "Transfer-Encoding", "Upgrade", NULL + }; + for (int i = 0; hop[i]; i++) if (!strcasecmp(name, hop[i])) return 1; + /* anything named in the Connection header is hop-by-hop for this message */ + char conn[J_HDR_VALUE]; + if (!j_hdrs_find(h, "Connection", conn, sizeof conn)) { + char lower[J_HDR_VALUE]; + snprintf(lower, sizeof lower, "%s", conn); + for (char *p = lower; *p; p++) *p = (char)tolower((unsigned char)*p); + char nlower[J_HDR_NAME]; + snprintf(nlower, sizeof nlower, "%s", name); + for (char *p = nlower; *p; p++) *p = (char)tolower((unsigned char)*p); + if (strstr(lower, nlower)) return 1; + } + return 0; +} + +size_t j_hdrs_serialize(const j_hdrs *h, char *out, size_t cap, int skip_hop, int terminate) +{ + size_t used = 0; + for (int i = 0; i < h->n; i++) { + if (skip_hop && j_is_hop_by_hop(h, h->it[i].name)) continue; + int n = snprintf(out + used, cap > used ? cap - used : 0, "%s: %s\r\n", + h->it[i].name, h->it[i].value); + if (n < 0) break; + used += (size_t)n; + if (used >= cap) { used = cap - 1; break; } + } + if (terminate) { + if (used + 2 < cap) { memcpy(out + used, "\r\n", 3); used += 2; } + else if (cap >= 2) { memcpy(out + cap - 2, "\r\n", 2); used = cap - 2; } + } + return used; +} + +/* ------------------------------------------------------------------ chunked */ + +static int hexval(int ch) +{ + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; + if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; + return -1; +} + +/* Parse "[;ext]CRLF" at *pos; returns chunk size or -1. */ +static long chunk_size(const char *buf, size_t len, size_t *pos, size_t *next) +{ + size_t i = *pos; + long size = 0; + int digits = 0; + while (i < len) { + int v = hexval((unsigned char)buf[i]); + if (v < 0) break; + size = size * 16 + v; + if (size > 0x7fffffffL) return -1; + digits++; + i++; + } + if (!digits) return -1; + while (i + 1 < len && !(buf[i] == '\r' && buf[i + 1] == '\n')) i++; /* skip extensions */ + if (i + 1 >= len) return -1; + *next = i + 2; + return size; +} + +int j_chunked_decode(const char *in, size_t inlen, char **out, size_t *outlen) +{ + size_t pos = 0, cap = 0, used = 0; + char *buf = NULL; + while (pos < inlen) { + size_t next = 0; + long size = chunk_size(in, inlen, &pos, &next); + if (size < 0) { free(buf); return -1; } + pos = next; + if (size == 0) break; /* last chunk */ + if (pos + (size_t)size > inlen) { free(buf); return -1; } + if (used + (size_t)size + 1 > cap) { + size_t nc = cap ? cap : 4096; + while (nc < used + (size_t)size + 1) nc *= 2; + char *nb = realloc(buf, nc); + if (!nb) { free(buf); return -1; } + buf = nb; + cap = nc; + } + memcpy(buf + used, in + pos, (size_t)size); + used += (size_t)size; + pos += (size_t)size; + if (pos + 1 < inlen && in[pos] == '\r' && in[pos + 1] == '\n') pos += 2; + } + if (!buf) buf = calloc(1, 1); + if (!buf) return -1; + buf[used] = '\0'; + *out = buf; + *outlen = used; + return 0; +} + +int j_chunked_read(j_conn *c, j_buf *b, size_t from, size_t max, double idle_s, + double deadline, char **out, size_t *outlen, char *err, size_t errlen) +{ + size_t pos = from, cap = 0, used = 0; + char *buf = NULL; + for (;;) { + /* need a full chunk header line */ + size_t line_end; + for (;;) { + if (j_buf_ensure(c, b, pos, 1, idle_s, deadline, err, errlen)) { free(buf); return -1; } + line_end = pos; + while (line_end + 1 < b->len && !(b->data[line_end] == '\r' && b->data[line_end + 1] == '\n')) line_end++; + if (line_end + 1 < b->len) break; + if (b->len > max) { snprintf(err, errlen, "chunk_header_too_large"); free(buf); return -1; } + } + size_t next = 0; + long size = chunk_size(b->data, b->len, &pos, &next); + if (size < 0) { snprintf(err, errlen, "bad_chunk_size"); free(buf); return -1; } + pos = next; + if (size == 0) break; + if (used + (size_t)size > max) { snprintf(err, errlen, "body_too_large"); free(buf); return -1; } + if (j_buf_ensure(c, b, pos, (size_t)size + 2, idle_s, deadline, err, errlen)) { free(buf); return -1; } + if (used + (size_t)size + 1 > cap) { + size_t nc = cap ? cap : 4096; + while (nc < used + (size_t)size + 1) nc *= 2; + char *nb = realloc(buf, nc); + if (!nb) { free(buf); snprintf(err, errlen, "oom"); return -1; } + buf = nb; + cap = nc; + } + memcpy(buf + used, b->data + pos, (size_t)size); + used += (size_t)size; + pos += (size_t)size; + if (pos + 1 < b->len && b->data[pos] == '\r' && b->data[pos + 1] == '\n') pos += 2; + } + /* swallow trailers up to the final blank line */ + for (;;) { + size_t e; + for (;;) { + if (j_buf_ensure(c, b, pos, 2, idle_s, deadline, err, errlen)) { free(buf); return -1; } + e = pos; + while (e + 1 < b->len && !(b->data[e] == '\r' && b->data[e + 1] == '\n')) e++; + if (e + 1 < b->len) break; + } + int blank = (e == pos); + pos = e + 2; + if (blank) break; + } + if (!buf) { buf = calloc(1, 1); if (!buf) { snprintf(err, errlen, "oom"); return -1; } } + buf[used] = '\0'; + *out = buf; + *outlen = used; + return 0; +} diff --git a/src/http.h b/src/http.h new file mode 100644 index 0000000..d3d817d --- /dev/null +++ b/src/http.h @@ -0,0 +1,67 @@ +/* junction/http.h — header handling, buffered reading, chunked transfer coding. */ +#ifndef J_HTTP_H +#define J_HTTP_H + +#include + +#include "conn.h" + +#define J_MAX_HDRS 96 +#define J_HDR_NAME 64 +#define J_HDR_VALUE 2048 + +typedef struct { + char name[J_HDR_NAME]; + char value[J_HDR_VALUE]; +} j_hdr; + +typedef struct { + j_hdr it[J_MAX_HDRS]; + int n; +} j_hdrs; + +/* growable byte buffer that keeps what it has already read (the leftover-body + * problem: one read() usually returns headers *and* body) */ +typedef struct { + char *data; + size_t len; + size_t cap; +} j_buf; + +/* Called when a read waits longer than the idle window, so a thinking model shows up + * as progress in the log instead of as a hang. */ +void j_set_progress(void (*fn)(const char *role, double idle_s)); + +void j_buf_init(j_buf *b); +void j_buf_free(j_buf *b); +void j_buf_reset(j_buf *b); +int j_buf_reserve(j_buf *b, size_t need); +int j_buf_append(j_buf *b, const void *p, size_t n); +/* Append from `c` until `needle` occurs in the buffer. Returns the offset just past + * the needle, or -1 on error/timeout/eof. */ +ssize_t j_buf_read_until(j_conn *c, j_buf *b, const char *needle, size_t max, + double idle_s, double deadline, char *err, size_t errlen); +/* Make sure at least `n` bytes are buffered (from offset `from`). */ +int j_buf_ensure(j_conn *c, j_buf *b, size_t from, size_t n, double idle_s, + double deadline, char *err, size_t errlen); + +void j_hdrs_init(j_hdrs *h); +int j_hdrs_find(const j_hdrs *h, const char *name, char *out, size_t outlen); +int j_hdrs_count(const j_hdrs *h, const char *name); +void j_hdrs_add(j_hdrs *h, const char *name, const char *value); +void j_hdrs_set(j_hdrs *h, const char *name, const char *value); +void j_hdrs_del(j_hdrs *h, const char *name); +int j_hdrs_has_token(const j_hdrs *h, const char *name, const char *token); +int j_hdrs_parse(j_hdrs *h, const char *block, size_t len); +int j_is_hop_by_hop(const j_hdrs *h, const char *name); +/* Serialize as "Name: value\r\n" lines (no terminating blank line unless asked). */ +size_t j_hdrs_serialize(const j_hdrs *h, char *out, size_t cap, int skip_hop, int terminate); + +/* Decode a complete chunked body already in memory. */ +int j_chunked_decode(const char *in, size_t inlen, char **out, size_t *outlen); + +/* Read a chunked body from `c`, decoding it into a fresh buffer (bounded by `max`). */ +int j_chunked_read(j_conn *c, j_buf *b, size_t from, size_t max, double idle_s, + double deadline, char **out, size_t *outlen, char *err, size_t errlen); + +#endif diff --git a/src/junction.c b/src/junction.c index e042ab9..bd4805a 100644 --- a/src/junction.c +++ b/src/junction.c @@ -1,11 +1,17 @@ -/* junction/junction.c — HTTP surface, rule routing, hooks, forwarding. +/* junction/junction.c — HTTP surface, rule routing, hooks, forwarding, caching. * - * C99 + POSIX, no third-party libraries. One request at a time on purpose (README, - * "Known limits"). + * C99 + POSIX (+ OpenSSL when built with TLS). One request at a time on purpose. + * + * All socket I/O goes through j_conn, so TLS is a property of the connection, not a + * branch in the request path. Bodies are parsed out of a j_buf so bytes that arrive + * together with the headers are never lost again. */ #define _POSIX_C_SOURCE 200809L +#include "cache.h" #include "config.h" +#include "conn.h" +#include "http.h" #include #include @@ -25,12 +31,11 @@ #include #include -#define HDR_MAX 32768 +#define HDR_BLOCK_MAX 32768 #define RELAY_CHUNK 8192 static j_config CFG; -/* ------------------------------------------------------------------ utility */ static double now_s(void) { struct timespec ts; @@ -45,7 +50,8 @@ static void jlog(const char *event, const char *fmt, ...) va_start(ap, fmt); int n = vsnprintf(line, sizeof line, fmt, ap); va_end(ap); - fprintf(stderr, "[%s] %s%s%s\n", CFG.log_prefix, event, n > 0 ? " " : "", n > 0 ? line : ""); + fprintf(stderr, "[%s] %s%s%s\n", CFG.log_prefix, event, n > 0 ? " " : "", + n > 0 ? line : ""); fflush(stderr); } @@ -95,12 +101,24 @@ static long json_int_value(const char *body, const char *key) return strtol(p, NULL, 10); } +static int json_bool_value(const char *body, const char *key) +{ + if (!body) return 0; + char pat[64]; + snprintf(pat, sizeof pat, "\"%s\"", key); + const char *p = strstr(body, pat); + if (!p) return 0; + p += strlen(pat); + while (*p && (*p == ':' || isspace((unsigned char)*p))) p++; + return !strncmp(p, "true", 4); +} + static void json_str_value(const char *body, const char *key, char *out, size_t outlen) { char pat[64]; out[0] = '\0'; snprintf(pat, sizeof pat, "\"%s\"", key); - const char *p = strstr(body, pat); + const char *p = body ? strstr(body, pat) : NULL; if (!p) return; p += strlen(pat); while (*p && (*p == ':' || isspace((unsigned char)*p))) p++; @@ -132,95 +150,227 @@ static long need_tokens(const char *body) typedef struct { char method[16]; char path[2048]; - char *headers; + j_hdrs hdrs; char *body; size_t body_len; -} j_request; +} j_req; -/* Returns the length of the header block (including its terminating CRLFCRLF), or -1/-2. - * `extra` receives the number of bytes read PAST that block — a single read() almost - * always returns body bytes too, and losing that count makes the caller wait forever - * for a body that already arrived. */ -static ssize_t read_header_block(int fd, char *buf, size_t cap, double idle_s, double deadline, - const char *who, size_t *extra) +static int wait_readable(j_conn *c, double idle_s, double deadline) { - if (extra) *extra = 0; - size_t used = 0; for (;;) { - if (now_s() >= deadline) return -2; - struct pollfd p = { .fd = fd, .events = POLLIN, .revents = 0 }; + if (j_conn_pending(c) > 0) return 1; + if (now_s() >= deadline) return 0; double left = deadline - now_s(); double t = left < idle_s ? left : idle_s; - int pr = poll(&p, 1, (int)(t * 1000.0) + 1); - if (pr == 0) { jlog("still_working", "side=%s silent_s=%.1f", who, idle_s); continue; } - if (pr < 0) { if (errno == EINTR) continue; return -1; } - if (used >= cap - 1) return -1; - ssize_t n = read(fd, buf + used, cap - 1 - used); - if (n < 0) { if (errno == EINTR) continue; return -1; } - if (n == 0) return -1; - used += (size_t)n; - buf[used] = '\0'; - char *end = strstr(buf, "\r\n\r\n"); - if (end) { - size_t hlen = (size_t)(end + 4 - buf); - if (extra) *extra = used - hlen; - return (ssize_t)hlen; - } + struct pollfd p = { .fd = c->fd, .events = POLLIN, .revents = 0 }; + int rc = poll(&p, 1, (int)(t * 1000.0) + 1); + if (rc < 0) { if (errno == EINTR) continue; return -1; } + if (rc == 0) { jlog("still_working", "side=wait silent_s=%.1f", idle_s); continue; } + return 1; } } -static int read_exact(int fd, char *buf, size_t len, double idle_s, double deadline, const char *who) +/* Read a request head + body. Returns 0, or -1 with `err` filled. */ +static int read_request(j_conn *c, j_buf *buf, j_req *rq, char *err, size_t errlen) { - size_t got = 0; - while (got < len) { - if (now_s() >= deadline) return -1; - struct pollfd p = { .fd = fd, .events = POLLIN, .revents = 0 }; - double left = deadline - now_s(); - double t = left < idle_s ? left : idle_s; - int pr = poll(&p, 1, (int)(t * 1000.0) + 1); - if (pr == 0) { jlog("still_working", "side=%s silent_s=%.1f", who, idle_s); continue; } - if (pr < 0) { if (errno == EINTR) continue; return -1; } - ssize_t n = read(fd, buf + got, len - got); - if (n <= 0) { if (n < 0 && errno == EINTR) continue; return -1; } - got += (size_t)n; + memset(rq, 0, sizeof *rq); + j_hdrs_init(&rq->hdrs); + j_buf_reset(buf); + + double deadline = now_s() + 120.0; + ssize_t head_len = j_buf_read_until(c, buf, "\r\n\r\n", HDR_BLOCK_MAX, 60.0, deadline, + err, errlen); + if (head_len <= 0) return -1; + size_t body_off = (size_t)head_len; + + char *line_end = strstr(buf->data, "\r\n"); + if (!line_end) { snprintf(err, errlen, "bad_request_line"); return -1; } + size_t line_len = (size_t)(line_end - buf->data); + char line[2200]; + if (line_len >= sizeof line) { snprintf(err, errlen, "request_line_too_long"); return -1; } + memcpy(line, buf->data, line_len); + line[line_len] = '\0'; + if (sscanf(line, "%15s %2047s", rq->method, rq->path) != 2) { + snprintf(err, errlen, "bad_request_line"); + return -1; } + + const char *hdr_start = line_end + 2; + size_t hdr_len = (size_t)((buf->data + head_len - 4) - hdr_start); + j_hdrs_parse(&rq->hdrs, hdr_start, hdr_len); + + char te[J_HDR_VALUE], cl[J_HDR_VALUE]; + int chunked = !j_hdrs_find(&rq->hdrs, "Transfer-Encoding", te, sizeof te) && + strstr(te, "chunked") != NULL; + long content_length = -1; + if (!j_hdrs_find(&rq->hdrs, "Content-Length", cl, sizeof cl)) + content_length = strtol(cl, NULL, 10); + + if (chunked) { + if (j_chunked_read(c, buf, body_off, (size_t)CFG.max_body_bytes, 30.0, + now_s() + 120.0, &rq->body, &rq->body_len, err, errlen)) + return -1; + return 0; + } + if (content_length <= 0) { rq->body = NULL; rq->body_len = 0; return 0; } + if (content_length > CFG.max_body_bytes) { snprintf(err, errlen, "body_too_large"); return -1; } + if (j_buf_ensure(c, buf, body_off, (size_t)content_length, 30.0, now_s() + 120.0, + err, errlen)) + return -1; + rq->body = malloc((size_t)content_length + 1); + if (!rq->body) { snprintf(err, errlen, "oom"); return -1; } + memcpy(rq->body, buf->data + body_off, (size_t)content_length); + rq->body[(size_t)content_length] = '\0'; + rq->body_len = (size_t)content_length; return 0; } -static int header_value(const char *headers, const char *name, char *out, size_t outlen) +/* ------------------------------------------------------------------ respond */ +static void send_simple(j_conn *c, int code, const char *reason, const char *body) { - size_t nlen = strlen(name); - for (const char *p = headers; *p; ) { - const char *eol = strstr(p, "\r\n"); - if (!eol) break; - if ((size_t)(eol - p) > nlen && !strncasecmp(p, name, nlen) && p[nlen] == ':') { - const char *v = p + nlen + 1; - while (v < eol && (*v == ' ' || *v == '\t')) v++; - size_t vl = (size_t)(eol - v); - if (vl >= outlen) vl = outlen - 1; - memcpy(out, v, vl); - out[vl] = '\0'; - return 0; - } - p = eol + 2; - } - return -1; + char hdr[512]; + int n = snprintf(hdr, sizeof hdr, + "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\n" + "Content-Length: %zu\r\nConnection: close\r\n\r\n", + code, reason, strlen(body)); + char err[128]; + if (j_conn_write(c, hdr, (size_t)n, err, sizeof err) < 0) return; + (void)j_conn_write(c, body, strlen(body), err, sizeof err); } -static int has_header_token(const char *headers, const char *name, const char *token) +static void status_page(j_conn *c) { - char v[512]; - if (header_value(headers, name, v, sizeof v)) return 0; - for (char *p = v; *p; p++) *p = (char)tolower((unsigned char)*p); - return strstr(v, token) != NULL; + size_t cap = 8192 + (size_t)CFG.endpoint_count * 1400 + (size_t)CFG.rule_count * 220; + char *out = calloc(1, cap); + if (!out) { send_simple(c, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } + double t = now_s(); + size_t used = (size_t)snprintf(out, cap, "{\"endpoints\":["); + for (int i = 0; i < CFG.endpoint_count; i++) { + j_endpoint *ep = &CFG.endpoints[i]; + char errs[512], hook[512]; + json_escape(ep->last_error, errs, sizeof errs); + json_escape(ep->last_hook_reason, hook, sizeof hook); + used += (size_t)snprintf(out + used, cap - used, + "%s{\"name\":\"%s\",\"base\":\"%s\",\"kind\":\"%s\",\"context\":%ld," + "\"priority\":%d,\"paused\":%s,\"inflight\":%d,\"ok\":%lu,\"fail\":%lu," + "\"last_ms\":%ld,\"offline_s\":%d,\"cooldown_s\":%d,\"hooks\":%d," + "\"wakeable\":%s,\"tls\":%s,\"cache\":%d," + "\"last_error\":\"%s\",\"last_hook_reason\":\"%s\"}", + i ? "," : "", ep->name, ep->base, ep->kind, ep->context, ep->priority, + ep->paused ? "true" : "false", ep->inflight, ep->ok_count, ep->fail_count, + ep->last_ms, + (int)(ep->offline_until > t ? ep->offline_until - t : 0), + (int)(ep->cooldown_until > t ? ep->cooldown_until - t : 0), + ep->hook_count, ep->wake[0] ? "true" : "false", + !strncmp(ep->base, "https://", 8) ? "true" : "false", + ep->cache_on, errs, hook); + } + size_t entries = 0, bytes = 0; + unsigned long hits = 0, misses = 0; + j_cache_stats(&entries, &bytes, &hits, &misses); + used += (size_t)snprintf(out + used, cap - used, + "],\"cache\":{\"ttl_s\":%.0f,\"entries\":%zu,\"bytes\":%zu,\"hits\":%lu,\"misses\":%lu}," + "\"listener\":{\"tls\":%s},\"rules\":[", + CFG.cache_ttl_s, entries, bytes, hits, misses, CFG.listen_tls ? "true" : "false"); + for (int i = 0; i < CFG.rule_count; i++) { + j_rule *r = &CFG.rules[i]; + used += (size_t)snprintf(out + used, cap - used, + "%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"targets\":\"%s\"}", + i ? "," : "", r->line, r->model_glob, r->path_glob, + r->block ? "true" : "false", r->targets[0]); + } + snprintf(out + used, cap - used, "]}"); + send_simple(c, 200, "OK", out); + free(out); +} + +static void admin(j_conn *c, const char *path) +{ + const char *p = path + strlen("/admin/"); + const char *slash = strchr(p, '/'); + char action[16], name[J_NAME_MAX]; + if (!slash) { + send_simple(c, 400, "Bad Request", "{\"error\":\"use /admin/pause|resume/\"}"); + return; + } + snprintf(action, sizeof action, "%.*s", (int)(slash - p), p); + snprintf(name, sizeof name, "%s", slash + 1); + + if (!strcmp(action, "flush") && !strcmp(name, "cache")) { + j_cache_clear(); + send_simple(c, 200, "OK", "{\"cache\":\"flushed\"}"); + return; + } + for (int i = 0; i < CFG.endpoint_count; i++) { + j_endpoint *ep = &CFG.endpoints[i]; + if (strcmp(ep->name, name)) continue; + if (!strcmp(action, "pause")) ep->paused = 1; + else if (!strcmp(action, "resume")) { + ep->paused = 0; + ep->offline_until = 0; + ep->cooldown_until = 0; + } else { + send_simple(c, 400, "Bad Request", "{\"error\":\"use pause or resume\"}"); + return; + } + jlog("admin", "endpoint=%s action=%s paused=%d", name, action, ep->paused); + char body[160]; + snprintf(body, sizeof body, "{\"name\":\"%s\",\"paused\":%s}", name, + ep->paused ? "true" : "false"); + send_simple(c, 200, "OK", body); + return; + } + send_simple(c, 404, "Not Found", "{\"error\":\"unknown endpoint\"}"); +} + +/* --------------------------------------------------------------------- rules */ +static int rule_matches(const j_rule *r, const char *path, const char *model, long need) +{ + if (r->model_glob[0] && fnmatch(r->model_glob, model ? model : "", 0) != 0) return 0; + if (r->path_glob[0] && fnmatch(r->path_glob, path, 0) != 0) return 0; + if (r->need_min >= 0 && need < r->need_min) return 0; + if (r->need_max >= 0 && need > r->need_max) return 0; + return 1; +} + +static j_rule *first_matching_rule(const char *path, const char *model, long need) +{ + for (int i = 0; i < CFG.rule_count; i++) + if (rule_matches(&CFG.rules[i], path, model, need)) return &CFG.rules[i]; + return NULL; +} + +static char *rewrite_model(const char *body, const char *new_model) +{ + if (!body) return NULL; + const char *key = strstr(body, "\"model\""); + if (!key) return NULL; + const char *v = key + 7; + while (*v && (*v == ':' || isspace((unsigned char)*v))) v++; + if (*v != '"') return NULL; + const char *start = v + 1; + const char *end = start; + while (*end && *end != '"') { if (*end == '\\' && end[1]) end++; end++; } + if (*end != '"') return NULL; + + size_t pre = (size_t)(start - body); + size_t post = strlen(end + 1); + size_t nl = strlen(new_model); + char *out = malloc(pre + nl + post + 1); + if (!out) return NULL; + memcpy(out, body, pre); + memcpy(out + pre, new_model, nl); + memcpy(out + pre + nl, end + 1, post + 1); + return out; } /* ------------------------------------------------------------------- network */ -static int split_url(const char *base, char *host, size_t hostlen, char *port, size_t portlen, - char *prefix, size_t prefixlen) +static int split_url(const char *base, char *host, size_t hostlen, char *port, + size_t portlen, char *prefix, size_t prefixlen, int *is_tls) { const char *p = base; - if (!strncmp(p, "https://", 8)) p += 8; + *is_tls = 0; + if (!strncmp(p, "https://", 8)) { *is_tls = 1; p += 8; } else if (!strncmp(p, "http://", 7)) p += 7; else return -1; const char *slash = strchr(p, '/'); @@ -236,7 +386,7 @@ static int split_url(const char *base, char *host, size_t hostlen, char *port, s memcpy(port, colon + 1, pl); port[pl] = '\0'; } else { - snprintf(port, portlen, "%s", base[4] == 's' ? "443" : "80"); + snprintf(port, portlen, "%s", *is_tls ? "443" : "80"); } snprintf(prefix, prefixlen, "%s", slash ? slash : ""); size_t pl2 = strlen(prefix); @@ -244,49 +394,17 @@ static int split_url(const char *base, char *host, size_t hostlen, char *port, s return 0; } -static int tcp_connect(const char *host, const char *port, double timeout_ms) +/* Connectivity is decided by the request itself: a second "probe" connection per + * request doubles the cost and wedges servers that serve one connection at a time + * (the probe takes the slot, closes without a request, and the real one waits). A + * connect/handshake failure is classified as "offline" below. */ +static int error_is_offline(const char *err) { - struct addrinfo hints, *res = NULL; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - if (getaddrinfo(host, port, &hints, &res) != 0) return -1; - - int fd = -1; - for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { - int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); - if (s < 0) continue; - int flags = fcntl(s, F_GETFL, 0); - fcntl(s, F_SETFL, flags | O_NONBLOCK); - int rc = connect(s, ai->ai_addr, ai->ai_addrlen); - if (rc == 0) { fcntl(s, F_SETFL, flags); fd = s; break; } - if (errno == EINPROGRESS) { - struct pollfd p = { .fd = s, .events = POLLOUT, .revents = 0 }; - if (poll(&p, 1, (int)timeout_ms) == 1) { - int err = 0; - socklen_t el = sizeof err; - getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &el); - if (!err) { fcntl(s, F_SETFL, flags); fd = s; break; } - } - } - close(s); - } - freeaddrinfo(res); - return fd; + return !strncmp(err, "connect", 7) || !strncmp(err, "resolve", 7) || + !strncmp(err, "tls handshake", 13) || !strncmp(err, "tls_verify", 10); } -static int endpoint_reachable(const j_endpoint *ep) -{ - char host[J_NAME_MAX], port[16], prefix[J_URL_MAX]; - if (split_url(ep->base, host, sizeof host, port, sizeof port, prefix, sizeof prefix)) - return 0; - int fd = tcp_connect(host, port, CFG.connect_timeout_ms); - if (fd < 0) return 0; - close(fd); - return 1; -} - -/* --------------------------------------------------------------------- hooks */ +/* ---------------------------------------------------------------------- hooks */ static int run_cmd(const char *cmd, const j_endpoint *ep, const char *path, const char *model, long need, int attempt, char *reason, size_t rlen) { @@ -297,7 +415,8 @@ static int run_cmd(const char *cmd, const j_endpoint *ep, const char *path, if (pid == 0) { dup2(out[1], STDOUT_FILENO); dup2(out[1], STDERR_FILENO); - close(out[0]); close(out[1]); + close(out[0]); + close(out[1]); char buf[64]; setenv("JUNCTION_BACKEND", ep->name, 1); setenv("JUNCTION_BASE", ep->base, 1); @@ -329,11 +448,14 @@ static int run_cmd(const char *cmd, const j_endpoint *ep, const char *path, reason[used] = '\0'; } } - pid_t w = waitpid(pid, &status, WNOHANG); - if (w == pid) break; + if (waitpid(pid, &status, WNOHANG) == pid) break; } close(out[0]); - if (timed_out) { waitpid(pid, &status, 0); if (rlen) snprintf(reason, rlen, "hook_timeout"); return 1; } + if (timed_out) { + waitpid(pid, &status, 0); + if (rlen) snprintf(reason, rlen, "hook_timeout"); + return 1; + } if (rlen) { reason[strcspn(reason, "\r\n")] = '\0'; if (!reason[0] && WIFEXITED(status)) @@ -348,7 +470,6 @@ static int wait_until_ready(j_endpoint *ep, const char *path, const char *model, double deadline = now_s() + (retry_s > 0 ? retry_s : 0); int attempt = 1, woke = 0; for (;;) { - if (!endpoint_reachable(ep)) return -2; int failing = 0; if (use_hooks) { for (int i = 0; i < ep->hook_count; i++) { @@ -376,311 +497,351 @@ static int wait_until_ready(j_endpoint *ep, const char *path, const char *model, } } -/* ------------------------------------------------------------------ respond */ -static void send_simple(int fd, int code, const char *reason, const char *body) -{ - char hdr[256]; - int n = snprintf(hdr, sizeof hdr, - "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\n" - "Content-Length: %zu\r\nConnection: close\r\n\r\n", - code, reason, strlen(body)); - if (write(fd, hdr, (size_t)n) < 0) return; - if (write(fd, body, strlen(body)) < 0) return; -} - -static void status_page(int fd) -{ - size_t cap = 4096 + (size_t)CFG.endpoint_count * 1200 + (size_t)CFG.rule_count * 200; - char *out = calloc(1, cap); - if (!out) { send_simple(fd, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } - double t = now_s(); - size_t used = (size_t)snprintf(out, cap, "{\"endpoints\":["); - for (int i = 0; i < CFG.endpoint_count; i++) { - j_endpoint *ep = &CFG.endpoints[i]; - char err[512], hook[512]; - json_escape(ep->last_error, err, sizeof err); - json_escape(ep->last_hook_reason, hook, sizeof hook); - used += (size_t)snprintf(out + used, cap - used, - "%s{\"name\":\"%s\",\"base\":\"%s\",\"kind\":\"%s\",\"context\":%ld," - "\"priority\":%d,\"paused\":%s,\"inflight\":%d,\"ok\":%lu,\"fail\":%lu," - "\"last_ms\":%ld,\"offline_s\":%d,\"cooldown_s\":%d,\"hooks\":%d," - "\"wakeable\":%s,\"last_error\":\"%s\",\"last_hook_reason\":\"%s\"}", - i ? "," : "", ep->name, ep->base, ep->kind, ep->context, ep->priority, - ep->paused ? "true" : "false", ep->inflight, ep->ok_count, ep->fail_count, - ep->last_ms, - (int)(ep->offline_until > t ? ep->offline_until - t : 0), - (int)(ep->cooldown_until > t ? ep->cooldown_until - t : 0), - ep->hook_count, ep->wake[0] ? "true" : "false", err, hook); - } - used += (size_t)snprintf(out + used, cap - used, "],\"rules\":["); - for (int i = 0; i < CFG.rule_count; i++) { - j_rule *r = &CFG.rules[i]; - used += (size_t)snprintf(out + used, cap - used, - "%s{\"line\":%d,\"model\":\"%s\",\"path\":\"%s\",\"block\":%s,\"targets\":\"%s\"}", - i ? "," : "", r->line, r->model_glob, r->path_glob, - r->block ? "true" : "false", r->targets[0]); - } - snprintf(out + used, cap - used, "]}"); - send_simple(fd, 200, "OK", out); - free(out); -} - -/* --------------------------------------------------------------------- rules */ -static int rule_matches(const j_rule *r, const char *path, const char *model, long need) -{ - if (r->model_glob[0] && fnmatch(r->model_glob, model ? model : "", 0) != 0) return 0; - if (r->path_glob[0] && fnmatch(r->path_glob, path, 0) != 0) return 0; - if (r->need_min >= 0 && need < r->need_min) return 0; - if (r->need_max >= 0 && need > r->need_max) return 0; - return 1; -} - -static j_rule *first_matching_rule(const char *path, const char *model, long need) -{ - for (int i = 0; i < CFG.rule_count; i++) - if (rule_matches(&CFG.rules[i], path, model, need)) return &CFG.rules[i]; - return NULL; -} - -/* Rewrite the "model" value inside the JSON body. Returns a new buffer or NULL. */ -static char *rewrite_model(const char *body, const char *new_model) -{ - if (!body) return NULL; - const char *key = strstr(body, "\"model\""); - if (!key) return NULL; - const char *v = key + 7; - while (*v && (*v == ':' || isspace((unsigned char)*v))) v++; - if (*v != '"') return NULL; - const char *start = v + 1; - const char *end = start; - while (*end && *end != '"') { if (*end == '\\' && end[1]) end++; end++; } - if (*end != '"') return NULL; - - size_t pre = (size_t)(start - body); - size_t post = strlen(end + 1); - size_t nl = strlen(new_model); - char *out = malloc(pre + nl + post + 1); - if (!out) return NULL; - memcpy(out, body, pre); - memcpy(out + pre, new_model, nl); - memcpy(out + pre + nl, end + 1, post + 1); - return out; -} - -/* ----------------------------------------------------------------- forwarding */ -/* Raw relay of (already framed) upstream bytes: chunked framing and streaming pass - * through untouched, so we cannot corrupt a stream by re-chunking it. */ -static int relay_body(int out_fd, int in_fd, long content_length, double idle_s, - double deadline, int *progress_at) +/* ------------------------------------------------------------------ relaying */ +/* Copy what the upstream sends, preserving its framing (chunked stays chunked). + * Used for streamed responses, which must not be buffered. */ +static int relay_stream(j_conn *client, j_conn *up, const char *pre, size_t pre_len, + long content_length, double idle_s, double deadline) { + char err[192]; static char buf[RELAY_CHUNK]; long remaining = content_length; + if (pre && pre_len) { + if (j_conn_write(client, pre, pre_len, err, sizeof err) < 0) return -1; + /* these bytes are part of the body too — forgetting this made every + * Content-Length response end in a bogus "relay_failed" */ + if (remaining > 0) remaining -= (long)pre_len; + } for (;;) { - if (now_s() >= deadline) return -1; - struct pollfd p = { .fd = in_fd, .events = POLLIN, .revents = 0 }; - double left = deadline - now_s(); - double t = left < idle_s ? left : idle_s; - int pr = poll(&p, 1, (int)(t * 1000.0) + 1); - if (pr == 0) { *progress_at = 1; jlog("still_working", "side=upstream silent_s=%.1f", idle_s); continue; } - if (pr < 0) { if (errno == EINTR) continue; return -1; } + if (remaining == 0) return 0; + if (wait_readable(up, idle_s, deadline) != 1) return -1; size_t want = sizeof buf; - if (remaining >= 0 && (long)want > remaining) want = (size_t)remaining; - ssize_t n = read(in_fd, buf, want); - if (n < 0) { if (errno == EINTR) continue; return -1; } - if (n == 0) return (remaining > 0) ? -1 : 0; - if (write(out_fd, buf, (size_t)n) != n) return -1; - if (remaining > 0) { - remaining -= n; - if (remaining == 0) return 0; - } - *progress_at = 1; + if (remaining > 0 && (long)want > remaining) want = (size_t)remaining; + ssize_t n = j_conn_read(up, buf, want, err, sizeof err); + if (n < 0) return -1; + if (n == 0) return remaining > 0 ? -1 : 0; + if (j_conn_write(client, buf, (size_t)n, err, sizeof err) < 0) return -1; + if (remaining > 0) remaining -= n; } } -static int forward(int client_fd, j_endpoint *ep, const char *method, const char *path, - const char *client_headers, const char *body, size_t body_len, long need) +/* Read a complete body (chunked or Content-Length) into memory. */ +static int read_full_body(j_conn *up, j_buf *buf, size_t off, int chunked, long content_length, + double idle_s, double deadline, char **body, size_t *body_len, + char *err, size_t errlen) { - (void)need; - char host[J_NAME_MAX], port[16], prefix[J_URL_MAX]; - if (split_url(ep->base, host, sizeof host, port, sizeof port, prefix, sizeof prefix)) - return -1; - - int fd = tcp_connect(host, port, CFG.connect_timeout_ms); - if (fd < 0) return -1; - - /* build the upstream request: client headers minus hop-by-hop, plus Host */ - char target[4096]; - if (!strncmp(path, "/v1", 3)) snprintf(target, sizeof target, "%s%s", prefix, path + 3); - else snprintf(target, sizeof target, "%s%s", prefix, path); - - char req[HDR_MAX]; - size_t used = (size_t)snprintf(req, sizeof req, "%s %s HTTP/1.1\r\n", method, target); - for (const char *p = client_headers; *p && used < sizeof req - 64; ) { - const char *eol = strstr(p, "\r\n"); - if (!eol) break; - size_t len = (size_t)(eol - p); - if (len > 0 && strncasecmp(p, "Host:", 5) && strncasecmp(p, "Connection:", 11) && - strncasecmp(p, "Content-Length:", 15) && strncasecmp(p, "Transfer-Encoding:", 18)) { - memcpy(req + used, p, len); - used += len; - memcpy(req + used, "\r\n", 2); - used += 2; - } - p = eol + 2; + if (chunked) + return j_chunked_read(up, buf, off, (size_t)CFG.max_body_bytes, idle_s, deadline, + body, body_len, err, errlen); + if (content_length <= 0) { + *body = calloc(1, 1); + *body_len = 0; + return *body ? 0 : -1; } - used += (size_t)snprintf(req + used, sizeof req - used, "Host: %s\r\n", host); + if (content_length > CFG.max_body_bytes) { snprintf(err, errlen, "response_too_large"); return -1; } + if (j_buf_ensure(up, buf, off, (size_t)content_length, idle_s, deadline, err, errlen)) return -1; + char *b = malloc((size_t)content_length + 1); + if (!b) { snprintf(err, errlen, "oom"); return -1; } + memcpy(b, buf->data + off, (size_t)content_length); + b[content_length] = '\0'; + *body = b; + *body_len = (size_t)content_length; + return 0; +} + +/* Send a status line + headers; body_len >= 0 sets Content-Length. */ +static int send_head(j_conn *client, int status, const char *reason, j_hdrs *h, + long body_len, char *err, size_t errlen) +{ + if (body_len >= 0) { + char cl[J_HDR_VALUE]; + snprintf(cl, sizeof cl, "%ld", body_len); + j_hdrs_set(h, "Content-Length", cl); + j_hdrs_del(h, "Transfer-Encoding"); + } + j_hdrs_set(h, "Connection", "close"); + + char *out = malloc(HDR_BLOCK_MAX); + if (!out) { snprintf(err, errlen, "oom"); return -1; } + size_t used = (size_t)snprintf(out, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n", status, + reason[0] ? reason : "OK"); + used += j_hdrs_serialize(h, out + used, HDR_BLOCK_MAX - used, 1, 1); + int rc = j_conn_write(client, out, used, err, errlen) < 0 ? -1 : 0; + free(out); + return rc; +} + +/* --------------------------------------------------------------- forwarding */ +typedef struct { + int status; + char reason[64]; + j_hdrs hdrs; + j_buf buf; + size_t body_off; + int chunked; + long content_length; +} j_upstream_resp; + +static void resp_free(j_upstream_resp *r) +{ + j_buf_free(&r->buf); +} + +static int read_response(j_conn *up, j_upstream_resp *r, double idle_s, double deadline, + char *err, size_t errlen) +{ + memset(r, 0, sizeof *r); + j_hdrs_init(&r->hdrs); + j_buf_init(&r->buf); + ssize_t head_len = j_buf_read_until(up, &r->buf, "\r\n\r\n", HDR_BLOCK_MAX, idle_s, + deadline, err, errlen); + if (head_len <= 0) { + if (head_len == -2) snprintf(err, errlen, "no_response_headers"); + return -1; + } + r->body_off = (size_t)head_len; + + char *line_end = strstr(r->buf.data, "\r\n"); + if (!line_end) { snprintf(err, errlen, "unparsable_status_line"); return -1; } + size_t line_len = (size_t)(line_end - r->buf.data); + char line[512]; + if (line_len >= sizeof line) { snprintf(err, errlen, "status_line_too_long"); return -1; } + memcpy(line, r->buf.data, line_len); + line[line_len] = '\0'; + if (sscanf(line, "HTTP/%*d.%*d %d %63[^\r\n]", &r->status, r->reason) < 1) { + snprintf(err, errlen, "unparsable_status_line"); + return -1; + } + const char *hdr_start = line_end + 2; + size_t hdr_len = (size_t)((r->buf.data + head_len - 4) - hdr_start); + j_hdrs_parse(&r->hdrs, hdr_start, hdr_len); + + char te[J_HDR_VALUE], cl[J_HDR_VALUE]; + r->chunked = !j_hdrs_find(&r->hdrs, "Transfer-Encoding", te, sizeof te) && + strstr(te, "chunked") != NULL; + r->content_length = -1; + if (!j_hdrs_find(&r->hdrs, "Content-Length", cl, sizeof cl)) + r->content_length = strtol(cl, NULL, 10); + return 0; +} + +/* Returns 0 = served, -1 = endpoint failed (fail over), -2 = bytes already sent to the + * client, so failing over is impossible. */ +static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, + const char *out_body, size_t out_len, const char *out_model, + const char *cache_state, double req_started, char *err, size_t errlen) +{ + char host[J_NAME_MAX], port[16], prefix[J_URL_MAX]; + int tls = 0; + if (split_url(ep->base, host, sizeof host, port, sizeof port, prefix, sizeof prefix, &tls)) { + snprintf(err, errlen, "bad_base_url"); + return -1; + } + + j_conn up = J_CONN_INIT; + if (j_conn_open(&up, host, port, tls, tls ? ep->tls_verify : 0, ep->tls_ca, + CFG.connect_timeout_ms, err, errlen)) + return -1; + up.role = "upstream"; + + char target[4096]; + if (!strncmp(rq->path, "/v1", 3)) + snprintf(target, sizeof target, "%s%s", prefix, rq->path + 3); + else + snprintf(target, sizeof target, "%s%s", prefix, rq->path); + + char *req = malloc(HDR_BLOCK_MAX); + if (!req) { snprintf(err, errlen, "oom"); j_conn_close(&up); return -1; } + size_t used = (size_t)snprintf(req, HDR_BLOCK_MAX, "%s %s HTTP/1.1\r\n", rq->method, target); + used += j_hdrs_serialize(&rq->hdrs, req + used, HDR_BLOCK_MAX - used, 1, 0); + + char hosthdr[300]; + if ((!tls && !strcmp(port, "80")) || (tls && !strcmp(port, "443"))) + snprintf(hosthdr, sizeof hosthdr, "%s", host); + else + snprintf(hosthdr, sizeof hosthdr, "%s:%s", host, port); + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "Host: %s\r\n", hosthdr); + if (ep->api_key_env[0]) { const char *key = getenv(ep->api_key_env); - if (key) used += (size_t)snprintf(req + used, sizeof req - used, - "Authorization: Bearer %s\r\n", key); + if (key && key[0]) + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, + "Authorization: Bearer %s\r\n", key); } - if (body) used += (size_t)snprintf(req + used, sizeof req - used, - "Content-Length: %zu\r\n", body_len); - used += (size_t)snprintf(req + used, sizeof req - used, "Connection: close\r\n\r\n"); + for (int i = 0; i < ep->header_count; i++) { + if (strchr(ep->headers[i], '\r') || strchr(ep->headers[i], '\n')) continue; + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "%s\r\n", ep->headers[i]); + } + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, + "X-Forwarded-Proto: %s\r\nX-Junction-Endpoint: %s\r\n", + tls ? "https" : "http", ep->name); + char xff[J_HDR_VALUE]; + if (!j_hdrs_find(&rq->hdrs, "X-Forwarded-For", xff, sizeof xff)) + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, + "X-Forwarded-For: 127.0.0.1\r\n"); + else + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, + "X-Forwarded-For: %s, 127.0.0.1\r\n", xff); + if (out_body && out_len) + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, + "Content-Length: %zu\r\n", out_len); + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "Connection: close\r\n\r\n"); - double deadline = now_s() + ep->timeout_s; - if (write(fd, req, used) != (ssize_t)used) { close(fd); return -1; } - if (body && body_len && write(fd, body, body_len) != (ssize_t)body_len) { close(fd); return -1; } - - char *hdr = malloc(HDR_MAX); - if (!hdr) { close(fd); return -1; } - size_t up_extra = 0; - ssize_t hlen = read_header_block(fd, hdr, HDR_MAX, ep->idle_timeout_s, deadline, "upstream", - &up_extra); - if (hlen <= 0) { free(hdr); close(fd); ep->last_error[0] ? 0 : snprintf(ep->last_error, sizeof ep->last_error, "no_response_headers"); return -1; } - - int status = 0; - if (sscanf(hdr, "HTTP/%*d.%*d %d", &status) != 1) { - free(hdr); close(fd); - snprintf(ep->last_error, sizeof ep->last_error, "unparsable_status_line"); + if (used >= HDR_BLOCK_MAX - 2) { + snprintf(err, errlen, "request_headers_too_large"); + free(req); + j_conn_close(&up); return -1; } - /* A 5xx or 429 is the endpoint failing, not an answer: fail over instead of - * passing a broken reply to the caller. */ - if (status >= 500 || status == 429) { - snprintf(ep->last_error, sizeof ep->last_error, "upstream_status_%d", status); - free(hdr); close(fd); + if (j_conn_write(&up, req, used, err, errlen) < 0 || + (out_body && out_len && j_conn_write(&up, out_body, out_len, err, errlen) < 0)) { + free(req); + j_conn_close(&up); + return -1; + } + free(req); + + double deadline = now_s() + ep->timeout_s; + j_upstream_resp r; + if (read_response(&up, &r, ep->idle_timeout_s, deadline, err, errlen)) { + j_conn_close(&up); + return -1; + } + if (r.status >= 500 || r.status == 429) { + snprintf(err, errlen, "upstream_status_%d", r.status); + snprintf(ep->last_error, sizeof ep->last_error, "upstream_status_%d", r.status); + resp_free(&r); + j_conn_close(&up); + return -1; + } + + char cc[J_HDR_VALUE]; + int resp_no_store = !j_hdrs_find(&r.hdrs, "Cache-Control", cc, sizeof cc) && + (strstr(cc, "no-store") || strstr(cc, "private")); + int store = (CFG.cache_ttl_s > 0) && (ep->cache_on != 0) && (r.status == 200) && + !resp_no_store && out_len > 0 && !json_bool_value(out_body, "stream"); + + char msbuf[32]; + snprintf(msbuf, sizeof msbuf, "%ld", (long)((now_s() - req_started) * 1000.0)); + j_hdrs_set(&r.hdrs, "X-Junction-Endpoint", ep->name); + j_hdrs_set(&r.hdrs, "X-Junction-Ms", msbuf); + j_hdrs_set(&r.hdrs, "X-Junction-Cache", cache_state); + + if (store) { + char *body = NULL; + size_t body_len = 0; + if (read_full_body(&up, &r.buf, r.body_off, r.chunked, r.content_length, + ep->idle_timeout_s, deadline, &body, &body_len, err, errlen)) { + resp_free(&r); + j_conn_close(&up); + return -1; /* nothing sent yet, failover is safe */ + } + /* cache the serialized head *with* its final headers, then send the same bytes */ + char *headcopy = malloc(HDR_BLOCK_MAX); + size_t headused = 0; + if (headcopy) { + headused = (size_t)snprintf(headcopy, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n", + r.status, r.reason[0] ? r.reason : "OK"); + j_hdrs tmp = r.hdrs; + headused += j_hdrs_serialize(&tmp, headcopy + headused, HDR_BLOCK_MAX - headused, + 1, 1); + j_cache_put(j_cache_key(rq->method, rq->path, out_model, out_body, out_len), + headcopy, headused, body, body_len, CFG.cache_ttl_s); + free(headcopy); + } + int rc = send_head(client, r.status, r.reason, &r.hdrs, (long)body_len, err, errlen); + if (rc == 0 && body_len && j_conn_write(client, body, body_len, err, errlen) < 0) + rc = -1; + free(body); + resp_free(&r); + j_conn_close(&up); + return rc == 0 ? 0 : -2; + } + + if (send_head(client, r.status, r.reason, &r.hdrs, + r.chunked ? -1 : r.content_length, err, errlen)) { + resp_free(&r); + j_conn_close(&up); return -2; } - - char cl[64]; - long content_length = -1; - if (!header_value(hdr, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10); - int is_chunked = has_header_token(hdr, "Transfer-Encoding", "chunked"); - - /* relay the header block minus its terminator, so the client sees the upstream's - * framing (chunked stays chunked, content-length stays content-length) */ - char *hdr_end = strstr(hdr, "\r\n\r\n"); - if (hdr_end) { - if (write(client_fd, hdr, (size_t)(hdr_end - hdr)) < 0) { free(hdr); close(fd); return -1; } - if (write(client_fd, "\r\n\r\n", 4) < 0) { free(hdr); close(fd); return -1; } + size_t pre_off = r.body_off; + size_t pre_len = r.buf.len > pre_off ? r.buf.len - pre_off : 0; + int rc = relay_stream(client, &up, r.buf.data + pre_off, pre_len, + r.chunked ? -1 : r.content_length, ep->idle_timeout_s, deadline); + resp_free(&r); + j_conn_close(&up); + if (rc) { + snprintf(err, errlen, "relay_failed"); + return -2; } - /* Body bytes that arrived together with the headers are already in hand: - * write them first or the client waits for bytes we have already consumed. */ - size_t buffered = up_extra; - if (content_length >= 0 && buffered > (size_t)content_length) buffered = (size_t)content_length; - if (buffered && write(client_fd, hdr + hlen, buffered) != (ssize_t)buffered) { - free(hdr); close(fd); return -1; - } - free(hdr); - - int progress = 0; - int rc; - if (is_chunked || content_length < 0) { - /* chunked or connection-close framing: the upstream's own framing is relayed - * byte for byte, so EOF (or the chunk terminator) ends it. */ - (void)relay_body(client_fd, fd, -1, ep->idle_timeout_s, deadline, &progress); - rc = 0; - } else { - long remaining = content_length - (long)buffered; - rc = remaining > 0 ? relay_body(client_fd, fd, remaining, ep->idle_timeout_s, - deadline, &progress) : 0; - } - close(fd); - return rc == 0 ? 0 : -1; + return 0; } /* --------------------------------------------------------------- connection */ -static void admin(int fd, const char *path) +static int request_is_cacheable(const j_req *rq, char *why, size_t whylen) { - const char *p = path + strlen("/admin/"); - char action[16], name[J_NAME_MAX]; - const char *slash = strchr(p, '/'); - if (!slash) { send_simple(fd, 400, "Bad Request", "{\"error\":\"use /admin/pause|resume/\"}"); return; } - snprintf(action, sizeof action, "%.*s", (int)(slash - p), p); - snprintf(name, sizeof name, "%s", slash + 1); - - for (int i = 0; i < CFG.endpoint_count; i++) { - j_endpoint *ep = &CFG.endpoints[i]; - if (strcmp(ep->name, name)) continue; - if (!strcmp(action, "pause")) ep->paused = 1; - else if (!strcmp(action, "resume")) { ep->paused = 0; ep->offline_until = 0; ep->cooldown_until = 0; } - else { send_simple(fd, 400, "Bad Request", "{\"error\":\"use pause or resume\"}"); return; } - jlog("admin", "endpoint=%s action=%s paused=%d", name, action, ep->paused); - char body[128]; - snprintf(body, sizeof body, "{\"name\":\"%s\",\"paused\":%s}", name, ep->paused ? "true" : "false"); - send_simple(fd, 200, "OK", body); - return; + if (CFG.cache_ttl_s <= 0) { snprintf(why, whylen, "disabled"); return 0; } + if (!rq->body) { snprintf(why, whylen, "no_body"); return 0; } + if (json_bool_value(rq->body, "stream")) { snprintf(why, whylen, "stream"); return 0; } + char cc[J_HDR_VALUE]; + if (!j_hdrs_find(&rq->hdrs, "Cache-Control", cc, sizeof cc) && + (strstr(cc, "no-cache") || strstr(cc, "no-store"))) { + snprintf(why, whylen, "client_no_cache"); + return 0; } - send_simple(fd, 404, "Not Found", "{\"error\":\"unknown endpoint\"}"); + return 1; } -static void handle_client(int fd) +static void serve_from_cache(j_conn *client, const char *head, size_t head_len, + const char *body, size_t body_len, const char *path, + const char *model, double age) { - char *hdr = malloc(HDR_MAX); - if (!hdr) { send_simple(fd, 500, "Internal Server Error", "{\"error\":\"oom\"}"); return; } - double deadline = now_s() + 120.0; - size_t extra = 0; - ssize_t hlen = read_header_block(fd, hdr, HDR_MAX, 60.0, deadline, "client", &extra); - if (hlen <= 0) { free(hdr); return; } - /* NOTE: do NOT write hdr[hlen] = '\0'. read_header_block already terminated the - * buffer at the END of everything it read, and the body bytes that came with the - * headers live right after the header block — terminating at hlen overwrote the - * first body byte with NUL, so the body looked empty while body_len said 84. */ - - j_request rq; - memset(&rq, 0, sizeof rq); - if (sscanf(hdr, "%15s %2047s", rq.method, rq.path) != 2) { - send_simple(fd, 400, "Bad Request", "{\"error\":\"bad request line\"}"); - free(hdr); - return; - } - rq.headers = strstr(hdr, "\r\n") + 2; - - char cl[64]; - long content_length = 0; - if (!header_value(rq.headers, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10); - if (content_length < 0) content_length = 0; - if (content_length > CFG.max_body_bytes) { - send_simple(fd, 413, "Payload Too Large", "{\"error\":\"body_too_large\"}"); - free(hdr); - return; - } - - char *head_end = strstr(hdr, "\r\n\r\n") + 4; - if (content_length) { - rq.body = calloc((size_t)content_length + 1, 1); - if (!rq.body) { send_simple(fd, 500, "Internal Server Error", "{\"error\":\"oom\"}"); free(hdr); return; } - size_t copied = extra < (size_t)content_length ? extra : (size_t)content_length; - memcpy(rq.body, head_end, copied); - if (copied < (size_t)content_length) { - if (read_exact(fd, rq.body + copied, (size_t)content_length - copied, 30.0, - now_s() + 120.0, "client")) { - send_simple(fd, 400, "Bad Request", "{\"error\":\"body_incomplete\"}"); - free(rq.body); free(hdr); - return; - } + char err[192]; + char *out = malloc(head_len + 64); + if (!out) return; + size_t used = 0; + memcpy(out, head, head_len); + used = head_len; + /* rewrite the cache marker: stored heads say "miss", a hit must say "hit" */ + char *marker = strstr(out, "X-Junction-Cache:"); + if (marker) { + char *eol = strstr(marker, "\r\n"); + if (eol) { + static const char hit[] = "X-Junction-Cache: hit\r\n"; + size_t tail = used - (size_t)(eol + 2 - out); + memmove(marker + sizeof hit - 1, eol + 2, tail); + memcpy(marker, hit, sizeof hit - 1); + used = (size_t)(marker - out) + (sizeof hit - 1) + tail; } - rq.body_len = (size_t)content_length; + } + if (j_conn_write(client, out, used, err, sizeof err) >= 0 && body_len) + (void)j_conn_write(client, body, body_len, err, sizeof err); + free(out); + jlog("cache_hit", "path=%s model=%s age_s=%.0f bytes=%zu", path, model, age, body_len); +} + +static void handle_client(j_conn *client) +{ + j_buf buf; + j_buf_init(&buf); + j_req rq; + char err[512] = ""; + if (read_request(client, &buf, &rq, err, sizeof err)) { + if (!strcmp(err, "body_too_large")) + send_simple(client, 413, "Payload Too Large", "{\"error\":\"body_too_large\"}"); + else if (strcmp(err, "eof_in_headers") && strcmp(err, "timeout_waiting_headers") && + !strstr(err, "eof_in")) + send_simple(client, 400, "Bad Request", "{\"error\":\"bad_request\"}"); + j_buf_free(&buf); + return; } - /* control plane */ - if (!strcmp(rq.path, "/status")) { status_page(fd); free(rq.body); free(hdr); return; } - if (!strncmp(rq.path, "/admin/", 7)) { admin(fd, rq.path); free(rq.body); free(hdr); return; } + if (!strcmp(rq.path, "/status")) { status_page(client); goto done; } + if (!strncmp(rq.path, "/admin/", 7)) { admin(client, rq.path); goto done; } long need = need_tokens(rq.body); char model[J_GLOB_MAX]; - json_str_value(rq.body ? rq.body : "", "model", model, sizeof model); + json_str_value(rq.body, "model", model, sizeof model); j_rule *rule = first_matching_rule(rq.path, model, need); if (!rule) { @@ -690,9 +851,8 @@ static void handle_client(int fd) snprintf(body, sizeof body, "{\"error\":\"no_matching_rule\",\"path\":\"%s\",\"model\":\"%s\",\"need_tokens\":%ld}", epath, emodel, need); - send_simple(fd, 503, "Service Unavailable", body); - free(rq.body); free(hdr); - return; + send_simple(client, 503, "Service Unavailable", body); + goto done; } if (rule->block) { char body[1024], emodel[256]; @@ -700,9 +860,8 @@ static void handle_client(int fd) snprintf(body, sizeof body, "{\"error\":\"blocked_by_rule\",\"line\":%d,\"model\":\"%s\"}", rule->line, emodel); jlog("blocked", "line=%d model=%s", rule->line, model); - send_simple(fd, 403, "Forbidden", body); - free(rq.body); free(hdr); - return; + send_simple(client, 403, "Forbidden", body); + goto done; } const char *out_body = rq.body; @@ -713,6 +872,22 @@ static void handle_client(int fd) if (rewritten) { out_body = rewritten; out_model = rule->rewrite_model; } } size_t out_len = out_body ? strlen(out_body) : 0; + double started = now_s(); + + /* a rewritten body must be cached under the model it is actually sent as */ + uint64_t ckey = 0; + int may_cache = request_is_cacheable(&rq, err, sizeof err); + if (may_cache) { + ckey = j_cache_key(rq.method, rq.path, out_model, out_body, out_len); + const char *head = NULL, *cbody = NULL; + size_t head_len = 0, cbody_len = 0; + double age = 0; + if (j_cache_get(ckey, &head, &head_len, &cbody, &cbody_len, &age) == 0) { + serve_from_cache(client, head, head_len, cbody, cbody_len, rq.path, out_model, age); + free(rewritten); + goto done; + } + } char attempts[768] = ""; for (int t = 0; t < rule->target_count; t++) { @@ -726,23 +901,10 @@ static void handle_client(int fd) if (ep->context < need) { strncat(attempts, " context", sizeof attempts - strlen(attempts) - 1); continue; } if (ep->offline_until > now_s()) { strncat(attempts, " offline", sizeof attempts - strlen(attempts) - 1); continue; } - if (!endpoint_reachable(ep)) { - ep->offline_until = now_s() + CFG.offline_hold_s; - jlog("offline", "endpoint=%s reason=connect_failed hold_s=%.0f", ep->name, CFG.offline_hold_s); - strncat(attempts, " offline", sizeof attempts - strlen(attempts) - 1); - continue; - } - int use_hooks = (rule->check == J_CHECK_HOOKS) || (rule->check == J_CHECK_INHERIT && ep->hook_count > 0); double retry = rule->retry_s >= 0 ? rule->retry_s : ep->hook_retry_s; int ready = wait_until_ready(ep, rq.path, out_model, need, retry, use_hooks); - if (ready == -2) { - ep->offline_until = now_s() + CFG.offline_hold_s; - jlog("offline", "endpoint=%s reason=vanished", ep->name); - strncat(attempts, " vanished", sizeof attempts - strlen(attempts) - 1); - continue; - } if (ready != 0) { jlog("hooks_failed", "endpoint=%s reason=%s", ep->name, ep->last_hook_reason); strncat(attempts, " hooks", sizeof attempts - strlen(attempts) - 1); @@ -750,33 +912,85 @@ static void handle_client(int fd) } ep->inflight++; - double started = now_s(); - int rc = forward(fd, ep, rq.method, rq.path, rq.headers, out_body, out_len, need); + int rc = forward_step(client, ep, &rq, out_body, out_len, out_model, + may_cache ? "miss" : "off", started, err, sizeof err); ep->inflight--; if (rc == 0) { ep->ok_count++; ep->last_ms = (long)((now_s() - started) * 1000.0); - jlog("served_by", "endpoint=%s ms=%ld need_tokens=%ld rule_line=%d", - ep->name, ep->last_ms, need, rule->line); - free(rewritten); free(rq.body); free(hdr); - return; + jlog("served_by", "endpoint=%s ms=%ld need_tokens=%ld rule_line=%d tls=%d cache=%s", + ep->name, ep->last_ms, need, rule->line, + !strncmp(ep->base, "https://", 8), may_cache ? "miss" : "off"); + free(rewritten); + goto done; + } + if (rc == -2) { + ep->fail_count++; + snprintf(ep->last_error, sizeof ep->last_error, "%s", err); + jlog("aborted", "endpoint=%s error=%s", ep->name, err); + free(rewritten); + goto done; } ep->fail_count++; - ep->cooldown_until = now_s() + ep->cooldown_s; - jlog("failed", "endpoint=%s error=%s", ep->name, - ep->last_error[0] ? ep->last_error : "forward_error"); - strncat(attempts, " failed", sizeof attempts - strlen(attempts) - 1); + if (error_is_offline(err)) { + ep->offline_until = now_s() + CFG.offline_hold_s; + jlog("offline", "endpoint=%s reason=connect_failed hold_s=%.0f error=%s", + ep->name, CFG.offline_hold_s, err); + strncat(attempts, " offline", sizeof attempts - strlen(attempts) - 1); + } else { + ep->cooldown_until = now_s() + ep->cooldown_s; + jlog("failed", "endpoint=%s error=%s", ep->name, err); + strncat(attempts, " failed", sizeof attempts - strlen(attempts) - 1); + } } char body[1024]; snprintf(body, sizeof body, "{\"error\":\"no_endpoint_available\",\"need_tokens\":%ld,\"rule_line\":%d,\"attempts\":\"%s\"}", need, rule->line, attempts[0] ? attempts + 1 : "none"); - send_simple(fd, 503, "Service Unavailable", body); - free(rewritten); free(rq.body); free(hdr); + send_simple(client, 503, "Service Unavailable", body); + free(rewritten); + +done: + free(rq.body); + j_buf_free(&buf); +} + +static void progress_log(const char *role, double idle_s) +{ + jlog("still_working", "side=%s silent_s=%.1f", role, idle_s); } /* ---------------------------------------------------------------------- main */ +static int make_listener(const j_config *cfg, char *err, size_t errlen) +{ + struct addrinfo hints, *res = NULL; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + char portstr[16]; + snprintf(portstr, sizeof portstr, "%d", cfg->listen_port); + if (getaddrinfo(cfg->listen_host, portstr, &hints, &res) != 0) { + snprintf(err, errlen, "cannot resolve %s:%d", cfg->listen_host, cfg->listen_port); + return -1; + } + int lfd = -1; + for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { + lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); + if (lfd < 0) continue; + int one = 1; + setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); + if (!bind(lfd, ai->ai_addr, ai->ai_addrlen) && !listen(lfd, 32)) break; + close(lfd); + lfd = -1; + } + freeaddrinfo(res); + if (lfd < 0) snprintf(err, errlen, "cannot listen on %s:%d: %s", cfg->listen_host, + cfg->listen_port, strerror(errno)); + return lfd; +} + int main(int argc, char **argv) { const char *config_path = NULL; @@ -800,43 +1014,53 @@ int main(int argc, char **argv) } if (port_override) CFG.listen_port = port_override; - signal(SIGPIPE, SIG_IGN); + if (CFG.listen_tls) { + if (!j_tls_available()) { + fprintf(stderr, "config error: 'listen ... tls' needs a build with TLS support\n"); + return 1; + } + if (j_tls_server_start(CFG.tls_cert, CFG.tls_key, err, sizeof err)) { + fprintf(stderr, "tls error: %s\n", err); + return 1; + } + } + for (int i = 0; i < CFG.endpoint_count; i++) { + if (!strncmp(CFG.endpoints[i].base, "https://", 8) && !j_tls_available()) { + fprintf(stderr, "config error: endpoint %s uses https but this build has no TLS\n", + CFG.endpoints[i].name); + return 1; + } + } + j_cache_config((size_t)CFG.cache_entries, (size_t)CFG.cache_bytes, CFG.cache_ttl_s); - struct addrinfo hints, *res = NULL; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_PASSIVE; - char portstr[16]; - snprintf(portstr, sizeof portstr, "%d", CFG.listen_port); - if (getaddrinfo(CFG.listen_host, portstr, &hints, &res) != 0) { - fprintf(stderr, "cannot resolve %s:%d\n", CFG.listen_host, CFG.listen_port); - return 1; - } - int lfd = -1; - for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { - lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); - if (lfd < 0) continue; - int one = 1; - setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); - if (!bind(lfd, ai->ai_addr, ai->ai_addrlen) && !listen(lfd, 32)) break; - close(lfd); - lfd = -1; - } - freeaddrinfo(res); + signal(SIGPIPE, SIG_IGN); + j_set_progress(progress_log); + + int lfd = make_listener(&CFG, err, sizeof err); if (lfd < 0) { - fprintf(stderr, "cannot listen on %s:%d: %s\n", CFG.listen_host, CFG.listen_port, - strerror(errno)); + fprintf(stderr, "%s\n", err); return 1; } - jlog("listening", "addr=%s:%d endpoints=%d rules=%d", CFG.listen_host, CFG.listen_port, - CFG.endpoint_count, CFG.rule_count); + jlog("listening", "addr=%s:%d endpoints=%d rules=%d tls=%d cache_ttl=%.0f", + CFG.listen_host, CFG.listen_port, CFG.endpoint_count, CFG.rule_count, + CFG.listen_tls, CFG.cache_ttl_s); for (;;) { int cfd = accept(lfd, NULL, NULL); if (cfd < 0) { if (errno == EINTR) continue; break; } - handle_client(cfd); - close(cfd); + j_conn client = J_CONN_INIT; + if (CFG.listen_tls) { + if (j_tls_server_accept(&client, cfd, err, sizeof err)) { + jlog("tls_accept_failed", "%s", err); + close(cfd); + continue; + } + } else { + client.fd = cfd; + } + client.role = "client"; + handle_client(&client); + j_conn_close(&client); } close(lfd); return 0; diff --git a/tests/run.sh b/tests/run.sh index da9568e..9ac842a 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -18,8 +18,20 @@ ok() { printf ' OK %s\n' "$1"; } bad() { printf ' FAIL %s\n' "$1"; FAILED=1; } contains() { case "$1" in *"$2"*) ok "$3";; *) bad "$3 (missing '$2')";; esac; } +# A leftover process on a test port produces confusing failures (a stale junction can +# answer requests with somebody else's config), so fail loudly and early. +for port in 8099 8100 8101 8102 8103 8104 8105 8106 9443 9990 9991 9992 9993; do + if ss -tln 2>/dev/null | grep -q ":$port "; then + echo "port $port is busy — a leftover junction/stub is still running:" + ss -tlnp 2>/dev/null | grep ":$port " | sed 's/^/ /' + exit 1 + fi +done + make -s >/dev/null || { echo "build failed"; exit 1; } -[ -x tests/stub ] || cc -std=c99 -O2 -o tests/stub tests/stub.c || exit 1 +TLSCC="-DJ_HAVE_TLS -lssl -lcrypto" +[ -f /usr/include/openssl/ssl.h ] || TLSCC="" +[ -x tests/stub ] || cc -std=c99 -O2 -Isrc $TLSCC -o tests/stub tests/stub.c src/conn.c || exit 1 tests/stub $P_FAIL "FAILING" --fail & PIDS+=($!) tests/stub $P_GATED "GATED" & PIDS+=($!) @@ -204,6 +216,141 @@ printf 'listen 127.0.0.1:8090\nendpoint x {\n base http://a/v1\n}\nreq for "* OUT2=$(./junction --config "$TMP/bad2.conf" 2>&1) contains "$OUT2" "unknown endpoint 'nope'" "a rule may not pass to an unknown endpoint" +echo "== 8-10. features: chunked bodies, caching, header passthrough ==" +FEAT=$((PORT+4)) +cat > "$TMP/features.conf" < "$TMP/features.log" 2>&1 & +PIDS+=($!) +sleep 0.7 + +BODY='{"model":"x","messages":[{"role":"user","content":"chunked body arrives intact"}],"max_tokens":8}' +C1=${BODY:0:16} +C2=${BODY:16} +RESP=$( { printf 'POST /v1/chat/completions HTTP/1.1\r\nHost: t\r\nContent-Type: application/json\r\n' + printf 'Transfer-Encoding: chunked\r\n\r\n' + printf '%x\r\n%s\r\n%x\r\n%s\r\n0\r\n\r\n' ${#C1} "$C1" ${#C2} "$C2" + } | nc -w 5 127.0.0.1 "$FEAT" ) +contains "$RESP" "served by GATED" "chunked request is decoded and forwarded" +contains "$RESP" "X-Stub-Body-Len: ${#BODY}" "decoded body reached the endpoint byte-exact" + +# same request twice: the second must come out of the cache (own body — the chunked +# request above already filled the cache for its own body) +CBODY='{"model":"cachemodel","messages":[{"role":"user","content":"cache me once"}],"max_tokens":8}' +R1=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +contains "$R1" "X-Junction-Cache: miss" "first request is a cache miss" +R2=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +contains "$R2" "X-Junction-Cache: hit" "identical second request is a cache hit" +R3=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +contains "$R3" "X-Junction-Cache: hit" "third request still a hit" +curl -s -m 5 -X POST "http://127.0.0.1:$FEAT/admin/flush/cache" >/dev/null +R4=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' -d "$CBODY" \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +contains "$R4" "X-Junction-Cache: miss" "flush clears the cache" +R5=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' \ + -H 'Cache-Control: no-cache' -d "$CBODY" "http://127.0.0.1:$FEAT/v1/chat/completions") +contains "$R5" "X-Junction-Cache: off" "client no-cache bypasses the cache" + +R6=$(curl -s -m 10 -D- -X POST -H 'Content-Type: application/json' -H 'X-Custom: abc123' \ + -d '{"model":"y","messages":[{"role":"user","content":"header check"}],"max_tokens":8}' \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +contains "$R6" "X-Stub-Custom: abc123" "client header reaches the endpoint" +contains "$R6" "X-Stub-Static: yes" "endpoint 'header' line is injected" +contains "$R6" "X-Junction-Endpoint: gated" "response names the serving endpoint" +contains "$R6" "X-Stub-Xff: " "X-Forwarded-For reaches the endpoint" + +echo "== 11. TLS listener ==" +if command -v openssl >/dev/null 2>&1 && [ -f /usr/include/openssl/ssl.h ]; then + openssl req -x509 -newkey rsa:2048 -nodes -keyout "$TMP/key.pem" -out "$TMP/cert.pem" \ + -days 1 -subj "/CN=localhost" >/dev/null 2>&1 + TLSP=$((PORT+5)) + cat > "$TMP/tls.conf" < "$TMP/tls.log" 2>&1 & + PIDS+=($!) + sleep 0.8 + TS=$(curl -sk -m 10 "https://127.0.0.1:$TLSP/status") + contains "$TS" '"listener":{"tls":true}' "TLS listener answers https" + TR=$(curl -sk -m 10 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"z","messages":[{"role":"user","content":"tls"}],"max_tokens":8}' \ + "https://127.0.0.1:$TLSP/v1/chat/completions") + contains "$TR" "served by GATED" "request over TLS reaches the endpoint" + + echo "== 12. TLS upstream (https endpoint) ==" + ./tests/stub 9443 SECURE --tls "$TMP/cert.pem" "$TMP/key.pem" > "$TMP/stubtls.log" 2>&1 & + PIDS+=($!) + sleep 0.8 + cat > "$TMP/tlsup.conf" < "$TMP/tlsup.log" 2>&1 & + PIDS+=($!) + sleep 0.8 + US=$(curl -s -m 15 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"s","messages":[{"role":"user","content":"over tls"}],"max_tokens":8}' \ + "http://127.0.0.1:$((PORT+6))/v1/chat/completions") + contains "$US" "served by SECURE" "request served by an https endpoint" + grep -q "tls=1" "$TMP/tlsup.log" && ok "log marks the TLS connection" || bad "log marks the TLS connection" + + # verification must actually be enforced: the same self-signed peer, tls_verify on + cat > "$TMP/tlsverify.conf" < "$TMP/tlsverify.log" 2>&1 & + PIDS+=($!) + sleep 0.8 + VS=$(curl -s -m 15 -o /dev/null -w '%{http_code}' -X POST \ + -H 'Content-Type: application/json' -d '{"model":"s","max_tokens":8}' \ + "http://127.0.0.1:$((PORT+7))/v1/chat/completions") + if [ "$VS" = "503" ]; then ok "self-signed cert refused when verification is on"; else bad "unverified TLS accepted (got $VS)"; fi + grep -q "tls_verify_failed" "$TMP/tlsverify.log" && ok "failure names the certificate problem" || bad "failure names the certificate problem" +else + echo " SKIP (no OpenSSL headers)" +fi + echo if [ "$FAILED" -eq 0 ]; then echo "PASS"; else echo "FAILURES"; fi exit "$FAILED" diff --git a/tests/stub.c b/tests/stub.c index 349651d..849b51a 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -1,29 +1,46 @@ -/* tests/stub.c — a stub OpenAI-compatible endpoint for the test suite. +/* tests/stub.c — OpenAI-compatible stub endpoint for the test suite. * - * stub [--fail] [--delay SECONDS] + * stub [--fail] [--delay SECONDS] [--tls CERT KEY] * * --fail always answers 503 (an endpoint that is up but will not serve) * --delay waits that long before answering (to exercise "still_working") + * + * The stub echoes what it received in response headers (X-Stub-*) so the tests can + * prove header passthrough and body integrity, including after chunked decoding. */ #define _POSIX_C_SOURCE 200809L +#include "../src/conn.h" + #include #include #include #include #include +#include #include #include #include -static void send_all(int fd, const char *buf, size_t len) +/* header value of `name` in a request head, or NULL */ +static const char *find_header(const char *head, const char *name, char *out, size_t outlen) { - size_t off = 0; - while (off < len) { - ssize_t n = write(fd, buf + off, len - off); - if (n <= 0) return; - off += (size_t)n; + size_t nlen = strlen(name); + for (const char *p = head; *p; ) { + const char *eol = strstr(p, "\r\n"); + if (!eol) break; + if ((size_t)(eol - p) > nlen && !strncasecmp(p, name, nlen) && p[nlen] == ':') { + const char *v = p + nlen + 1; + while (v < eol && (*v == ' ' || *v == '\t')) v++; + size_t vl = (size_t)(eol - v); + if (vl >= outlen) vl = outlen - 1; + memcpy(out, v, vl); + out[vl] = '\0'; + return out; + } + p = eol + 2; } + return NULL; } int main(int argc, char **argv) @@ -36,9 +53,16 @@ int main(int argc, char **argv) const char *name = argv[2]; int fail = 0; double delay = 0; + const char *cert = NULL, *key = NULL; for (int i = 3; i < argc; i++) { if (!strcmp(argv[i], "--fail")) fail = 1; else if (!strcmp(argv[i], "--delay") && i + 1 < argc) delay = atof(argv[++i]); + else if (!strcmp(argv[i], "--tls") && i + 2 < argc) { cert = argv[++i]; key = argv[++i]; } + } + char tlserr[256]; + if (cert && j_tls_server_start(cert, key, tlserr, sizeof tlserr)) { + fprintf(stderr, "stub tls: %s\n", tlserr); + return 1; } int lfd = socket(AF_INET, SOCK_STREAM, 0); @@ -58,18 +82,59 @@ int main(int argc, char **argv) for (;;) { int cfd = accept(lfd, NULL, NULL); if (cfd < 0) continue; + j_conn client = J_CONN_INIT; + char aerr[256]; + if (cert) { + if (j_tls_server_accept(&client, cfd, aerr, sizeof aerr)) { + fprintf(stderr, "stub tls accept: %s\n", aerr); + close(cfd); + continue; + } + } else { + client.fd = cfd; + } + client.role = "stub"; - char req[8192]; - ssize_t n = read(cfd, req, sizeof req - 1); - if (n <= 0) { close(cfd); continue; } - req[n] = '\0'; + char req[131072]; + size_t used = 0; + ssize_t n; + char ioerr[192]; + while (used < sizeof req - 1 && (n = j_conn_read(&client, req + used, + sizeof req - 1 - used, + ioerr, sizeof ioerr)) > 0) { + used += (size_t)n; + req[used] = '\0'; + if (strstr(req, "\r\n\r\n")) break; + } + if (used == 0) { j_conn_close(&client); continue; } + req[used] = '\0'; + + char *head_end = strstr(req, "\r\n\r\n"); + size_t head_len = head_end ? (size_t)(head_end + 4 - req) : used; + char cl[32]; + long content_length = 0; + if (find_header(req, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10); + + while ((long)(used - head_len) < content_length && used < sizeof req - 1) { + n = j_conn_read(&client, req + used, sizeof req - 1 - used, ioerr, sizeof ioerr); + if (n <= 0) break; + used += (size_t)n; + } + req[used] = '\0'; + long body_len = (long)used - (long)head_len; + if (body_len < 0) body_len = 0; if (delay > 0) { struct timespec ts = { (time_t)delay, (time_t)((delay - (time_t)delay) * 1e9) }; nanosleep(&ts, NULL); } - char body[512]; + char custom[256] = "", static_hdr[256] = "", fwd[256] = ""; + find_header(req, "X-Custom", custom, sizeof custom); + find_header(req, "X-Static", static_hdr, sizeof static_hdr); + find_header(req, "X-Forwarded-For", fwd, sizeof fwd); + + char body[1024]; if (fail) { const char *b = "{\"error\":\"not serving\"}"; snprintf(body, sizeof body, @@ -80,18 +145,24 @@ int main(int argc, char **argv) snprintf(b, sizeof b, "{\"object\":\"list\",\"data\":[{\"id\":\"%s\"}]}", name); snprintf(body, sizeof body, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" - "Content-Length: %zu\r\nConnection: close\r\n\r\n%s", strlen(b), b); + "Content-Length: %zu\r\nX-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n" + "Connection: close\r\n\r\n%s", strlen(b), name, body_len, b); } else { - char b[320]; + char b[512]; snprintf(b, sizeof b, "{\"id\":\"stub\",\"model\":\"%s\",\"choices\":[{\"index\":0," "\"message\":{\"role\":\"assistant\",\"content\":\"served by %s\"}}]}", name, name); snprintf(body, sizeof body, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" - "Content-Length: %zu\r\nConnection: close\r\n\r\n%s", strlen(b), b); + "Content-Length: %zu\r\n" + "X-Stub-Name: %s\r\nX-Stub-Body-Len: %ld\r\n" + "X-Stub-Custom: %s\r\nX-Stub-Static: %s\r\nX-Stub-Xff: %s\r\n" + "Connection: close\r\n\r\n%s", + strlen(b), name, body_len, custom, static_hdr, fwd, b); } - send_all(cfd, body, strlen(body)); - close(cfd); + if (j_conn_write(&client, body, strlen(body), ioerr, sizeof ioerr) < 0) + fprintf(stderr, "stub write failed: %s\n", ioerr); + j_conn_close(&client); } }