junction: TLS, chunked coding, response cache, header passthrough
- TLS both directions behind one j_conn handle: https upstreams with SNI, chain and
hostname verification (system store or tls_ca) and a 'listen ... tls cert key'
listener. Handshake has a hard deadline; a peer that closes without close_notify
is EOF, not an error (HTTP/1.0 bodies end at close).
- Chunked request bodies decoded into the body buffer; chunked responses relayed
byte for byte so streaming is untouched.
- Memory-only LRU response cache (method+path+model+body), honouring no-store/
private, client no-cache, never caching streams, flushable at runtime.
- Header passthrough with hop-by-hop removal, per-endpoint static headers,
X-Forwarded-For/Proto, and X-Junction-{Endpoint,Ms,Cache} on every response.
- No separate reachability probe: the request itself is the test (the probe wedged
servers that serve one connection at a time).
- tests/run.sh: 34 checks incl. a TLS peer; refuses to start on a busy test port.
This commit is contained in:
1 parent
137113b0a2
commit
dc31481914
14 files changed
+2111
-530
No files matched your search
@@ -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
|
||||
|
||||
@@ -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 <model-glob>] [path <glob>] [need >N | <N | N]
|
||||
( pass <endpoint>[,<endpoint>...] [as <model>] | 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 <s>` — override `hook_retry` for this rule ("wait up to N s until the box
|
||||
is ready").
|
||||
- `retry <s>` — override `hook_retry` ("wait up to N s for the box").
|
||||
- `pass a, b` — try `a`, then `b` on failure.
|
||||
- `as <model>` — rewrite the `model` field before forwarding (the local box may
|
||||
serve a different name than the client asked for).
|
||||
- `as <model>` — 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/<name>` | stop routing there |
|
||||
| POST | `/admin/resume/<name>` | clear pause + cooldown + offline window |
|
||||
| POST | `/admin/resume/<name>` | 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.
|
||||
@@ -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
|
||||
|
||||
+180
@@ -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 <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
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;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/* junction/cache.h — small in-memory response cache with LRU eviction. */
|
||||
#ifndef J_CACHE_H
|
||||
#define J_CACHE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
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
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+326
@@ -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 <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef J_HAVE_TLS
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509v3.h>
|
||||
|
||||
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
|
||||
+35
@@ -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 <stddef.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
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
|
||||
+385
@@ -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 <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <time.h>
|
||||
|
||||
#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 "<hex>[;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;
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/* junction/http.h — header handling, buffered reading, chunked transfer coding. */
|
||||
#ifndef J_HTTP_H
|
||||
#define J_HTTP_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#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
|
||||
+674
-450
File diff suppressed because it is too large.
Load diff
+148
-1
@@ -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" <<CFG
|
||||
listen 127.0.0.1:$FEAT
|
||||
default_max_tokens 8
|
||||
cache_ttl 60
|
||||
cache_entries 32
|
||||
cache_bytes 1048576
|
||||
|
||||
endpoint gated {
|
||||
base http://127.0.0.1:$P_GATED/v1
|
||||
context 64000
|
||||
timeout 10
|
||||
idle_timeout 5
|
||||
header "X-Static: yes"
|
||||
}
|
||||
|
||||
req for "*" check none pass gated
|
||||
CFG
|
||||
./junction --config "$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" <<CFG
|
||||
listen 127.0.0.1:$TLSP tls $TMP/cert.pem $TMP/key.pem
|
||||
default_max_tokens 8
|
||||
endpoint gated {
|
||||
base http://127.0.0.1:$P_GATED/v1
|
||||
context 64000
|
||||
timeout 10
|
||||
}
|
||||
req for "*" check none pass gated
|
||||
CFG
|
||||
./junction --config "$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" <<CFG
|
||||
listen 127.0.0.1:$((PORT+6))
|
||||
default_max_tokens 8
|
||||
endpoint secure {
|
||||
base https://127.0.0.1:9443/v1
|
||||
tls_verify off
|
||||
context 64000
|
||||
timeout 10
|
||||
idle_timeout 5
|
||||
}
|
||||
req for "*" check none pass secure
|
||||
CFG
|
||||
./junction --config "$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" <<CFG
|
||||
listen 127.0.0.1:$((PORT+7))
|
||||
default_max_tokens 8
|
||||
endpoint secure {
|
||||
base https://127.0.0.1:9443/v1
|
||||
context 64000
|
||||
timeout 10
|
||||
idle_timeout 5
|
||||
}
|
||||
req for "*" check none pass secure
|
||||
CFG
|
||||
./junction --config "$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"
|
||||
+89
-18
@@ -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 <port> <name> [--fail] [--delay SECONDS]
|
||||
* stub <port> <name> [--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 <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user