diff --git a/README.md b/README.md index f720a50..55ec4e0 100644 --- a/README.md +++ b/README.md @@ -717,7 +717,7 @@ Endpoint: | `kind anthropic` | native Messages API; the effort selector becomes `output_config.effort` | | `auth_basic ` | HTTP Basic instead of a bearer token (opencode wants this) | | `pass_cmd ` | stdout is the password — opencode makes a new one on every start | - | `base_cmd ` | stdout is the base URL — the background server binds a random port | + | `base_cmd ` | stdout is the base URL — the background server binds a random port. The health check and the request path both use this value, not the static `base`, so a service that restarts on a new port is picked up without restarting junction | With `kind opencode`, the bridge carries the client's reasoning effort into the session: `reasoning_effort` (Chat Completions), `reasoning.effort` (Responses), an diff --git a/src/conn.c b/src/conn.c index 972e2db..b401153 100644 --- a/src/conn.c +++ b/src/conn.c @@ -219,12 +219,21 @@ ssize_t j_conn_write(j_conn *c, const void *buf, size_t len, char *err, size_t e if (c->tls) { SSL *ssl = c->tls; size_t off = 0; + int stalls = 0; while (off < len) { int rc = SSL_write(ssl, (const char *)buf + off, (int)(len - off)); - if (rc > 0) { off += (size_t)rc; continue; } + if (rc > 0) { off += (size_t)rc; stalls = 0; 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; } + /* SO_SNDTIMEO turns a full socket into WANT_WRITE; a peer that never + * drains it must end the request instead of pinning this thread. */ + if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) { + if (++stalls > 30) { + snprintf(err, errlen, "tls write: client did not read"); + return -1; + } + wait_fd(c->fd, e == SSL_ERROR_WANT_READ ? POLLIN : POLLOUT, 1000); + continue; + } ssl_error(err, errlen, "tls write"); return -1; } @@ -236,6 +245,10 @@ ssize_t j_conn_write(j_conn *c, const void *buf, size_t len, char *err, size_t e ssize_t n = write(c->fd, (const char *)buf + off, len - off); if (n < 0) { if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) { + snprintf(err, errlen, "write: client did not read"); + return -1; + } snprintf(err, errlen, "write: %s", strerror(errno)); return -1; } diff --git a/src/junction.c b/src/junction.c index 8af02e0..65792d6 100644 --- a/src/junction.c +++ b/src/junction.c @@ -42,6 +42,7 @@ void j_control_ops_install(void); #include #include #include +#include #include #include #include @@ -49,6 +50,29 @@ void j_control_ops_install(void); #define HDR_BLOCK_MAX 32768 #define RELAY_CHUNK 8192 +/* Transfer-Encoding is a case-insensitive token list and gateways do send + * "Chunked". A plain strstr missed that, the body was relayed as if it were + * close-delimited, and the client read the hex size lines as content. */ +static int te_has_chunked(const char *v) +{ + if (!v) return 0; + for (const char *p = v; *p; p++) + if (!strncasecmp(p, "chunked", 7)) return 1; + return 0; +} + +/* A body that starts with "\r\n" carries chunk framing whether or not a + * (possibly stripped) header says so. Relaying it raw into a close-delimited + * response is what put "d9\r\n" in front of a client's SSE stream. */ +static int body_looks_chunked(const char *p, size_t n) +{ + size_t i = 0; + if (!p || n < 3) return 0; + while (i < n && i < 16 && isxdigit((unsigned char)p[i])) i++; + if (i == 0) return 0; + return i + 1 < n && p[i] == '\r' && p[i + 1] == '\n'; +} + j_config CFG; /* nicht static: der Steuerkanal liest dieselbe Konfiguration */ /* One lock for stderr (so log lines never interleave) and one for the runtime state @@ -517,7 +541,7 @@ static int read_request(j_conn *c, j_buf *buf, j_req *rq, char *err, size_t errl 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; + te_has_chunked(te); long content_length = -1; if (!j_hdrs_find(&rq->hdrs, "Content-Length", cl, sizeof cl)) content_length = strtol(cl, NULL, 10); @@ -1858,10 +1882,12 @@ static void admin(j_conn *c, const char *path) * * Gebraucht für base_cmd und pass_cmd: opencode serve bindet einen freien Port und * erzeugt bei jedem Start ein neues Passwort, beides ist nur über ein Kommando zu - * erfahren. Ein Cache von 60 Sekunden verhindert, dass jede Anfrage einen Prozess - * startet — häufiger als einmal pro Minute ändert sich daran nichts. + * erfahren. Ein Cache verhindert, dass jede Anfrage einen Prozess startet — häufiger + * als einmal pro Minute ändert sich daran nichts. Die Hintergrundprüfung darf einen + * kürzeren Cache benutzen: nach einem Neustart von opencode serve gilt die alte + * Adresse nur noch Sekunden, nicht eine Minute. */ -static int cmd_value(int ep_index, int which, char *out, size_t outlen) +static int cmd_value(int ep_index, int which, char *out, size_t outlen, double ttl_s) { static char cache_base[J_MAX_ENDPOINTS][J_URL_MAX]; static char cache_pass[J_MAX_ENDPOINTS][J_NAME_MAX]; @@ -1870,7 +1896,7 @@ static int cmd_value(int ep_index, int which, char *out, size_t outlen) char *dst = which ? cache_pass[ep_index] : cache_base[ep_index]; size_t dstlen = which ? J_NAME_MAX : J_URL_MAX; - if (cache_at[ep_index][which] > 0 && now - cache_at[ep_index][which] < 60.0 && dst[0]) { + if (cache_at[ep_index][which] > 0 && now - cache_at[ep_index][which] < ttl_s && dst[0]) { snprintf(out, outlen, "%s", dst); return 0; } @@ -1901,7 +1927,7 @@ static int opencode_serve(j_conn *client, j_endpoint *ep_index_owner, const j_re { (void)ep_index_owner; char base[J_URL_MAX], pass[J_NAME_MAX]; - if (cmd_value((int)(ep_index_owner - CFG.endpoints), 0, base, sizeof base) != 0) { + if (cmd_value((int)(ep_index_owner - CFG.endpoints), 0, base, sizeof base, 60.0) != 0) { if (CFG.endpoints[ep_index_owner - CFG.endpoints].base_cmd[0]) { snprintf(err, errlen, "opencode: base_cmd failed"); return -1; @@ -1910,7 +1936,7 @@ static int opencode_serve(j_conn *client, j_endpoint *ep_index_owner, const j_re } pass[0] = '\0'; if (ep_index_owner->pass_cmd[0] && - cmd_value((int)(ep_index_owner - CFG.endpoints), 1, pass, sizeof pass) != 0) { + cmd_value((int)(ep_index_owner - CFG.endpoints), 1, pass, sizeof pass, 60.0) != 0) { snprintf(err, errlen, "opencode: pass_cmd failed"); return -1; } @@ -1952,11 +1978,21 @@ static int opencode_serve(j_conn *client, j_endpoint *ep_index_owner, const j_re } /* --------------------------------------------------------------------- rules */ +/* Most rules name a literal model ("chat", "worker", "claude-opus-5-5"). fnmatch + * still walks the pattern machinery for every one of them on every request; with a + * long rule list that is wasted work. A pattern without wildcards is a strcmp. */ +static int glob_match(const char *pattern, const char *value) +{ + if (!strpbrk(pattern, "*?[")) + return strcmp(pattern, value) == 0; + return fnmatch(pattern, value, 0) == 0; +} + static int rule_matches(const j_rule *r, const char *path, const char *model, long need, long ctx, int has_image) { - 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->model_glob[0] && !glob_match(r->model_glob, model ? model : "")) return 0; + if (r->path_glob[0] && !glob_match(r->path_glob, path)) return 0; if (r->need_min >= 0 && need < r->need_min) return 0; if (r->need_max >= 0 && need > r->need_max) return 0; /* ctx: ohne Schätzung (-1) erfüllt keine ctx-Bedingung — was man nicht messen @@ -2526,10 +2562,15 @@ static int relay_stream(j_conn *client, j_conn *up, const char *pre, size_t pre_ 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 -2; + size_t n = pre_len; + + /* Never relay past the declared length: an upstream that over-sends + * would otherwise have the extra bytes appended to this body. */ + if (remaining > 0 && (long)n > remaining) n = (size_t)remaining; + if (j_conn_write(client, pre, n, err, sizeof err) < 0) return -2; /* these bytes are part of the body too — forgetting this made every * Content-Length response end in a bogus relay failure */ - if (remaining > 0) remaining -= (long)pre_len; + if (remaining > 0) remaining -= (long)n; } for (;;) { if (remaining == 0) return 0; @@ -2556,10 +2597,15 @@ static int relay_dechunk(j_conn *client, j_conn *up, const char *pre, size_t pre double idle_s, double deadline) { char err[192]; - static char in[RELAY_CHUNK * 2]; + static char in[RELAY_CHUNK * 8]; size_t have = 0; if (pre && pre_len) { - if (pre_len > sizeof in) return -1; + if (pre_len > sizeof in) { + /* Already more than we can re-frame: hand it over unchanged rather + * than killing a stream we cannot buffer. */ + if (j_conn_write(client, pre, pre_len, err, sizeof err) < 0) return -2; + return relay_stream(client, up, NULL, 0, -1, idle_s, deadline); + } memcpy(in, pre, pre_len); have = pre_len; } @@ -2580,8 +2626,19 @@ static int relay_dechunk(j_conn *client, j_conn *up, const char *pre, size_t pre } char num[32]; size_t nl = i < sizeof num - 1 ? i : sizeof num - 1; + size_t hx = 0; memcpy(num, in, nl); num[nl] = '\0'; + while (hx < nl && isxdigit((unsigned char)num[hx])) hx++; + if (hx == 0 || (hx < nl && num[hx] != ';')) { + /* Not a chunk-size line after all (a proxy that lied, or a + * plain close-delimited body). Pass everything we have through + * unchanged; treating it as the end chunk truncated the + * answer to nothing. */ + if (have && j_conn_write(client, in, have, err, sizeof err) < 0) + return -2; + return relay_stream(client, up, NULL, 0, -1, idle_s, deadline); + } long sz = strtol(num, NULL, 16); /* drop the line (plus an optional chunk extension) */ size_t consumed = i + 2; @@ -2657,24 +2714,21 @@ static int send_head(j_conn *client, int status, const char *reason, j_hdrs *h, snprintf(cl, sizeof cl, "%ld", body_len); j_hdrs_set(h, "Content-Length", cl); j_hdrs_del(h, "Transfer-Encoding"); - } else if (body_len == -1) { - /* Chunked relay: the BODY keeps the upstream's chunk framing, so the client - * must be told that — otherwise it reads the hex size lines as content. The - * hop-by-hop filter drops Transfer-Encoding by definition, so it is set here - * and serialized without that filter; the other hop headers are removed. */ + } else { + /* Negative: the body ends when the connection closes, and the client is + * never sent chunk framing. A chunked upstream body is de-chunked by the + * relay, a plain one goes out unchanged. Announcing + * Transfer-Encoding: chunked here wrote framing nobody produced: the + * client waited for hex sizes and saw a truncated stream. The hop-by-hop + * headers are dropped by name because the serializer would not. */ + j_hdrs_del(h, "Transfer-Encoding"); + j_hdrs_del(h, "Content-Length"); j_hdrs_del(h, "Keep-Alive"); j_hdrs_del(h, "Proxy-Authenticate"); j_hdrs_del(h, "Proxy-Authorization"); j_hdrs_del(h, "TE"); j_hdrs_del(h, "Trailer"); j_hdrs_del(h, "Upgrade"); - j_hdrs_set(h, "Transfer-Encoding", "chunked"); - } else { - /* -2: the de-chunked body is forwarded as-is and ends when the connection - * closes, so neither Content-Length nor Transfer-Encoding is announced. */ - j_hdrs_del(h, "Transfer-Encoding"); - j_hdrs_del(h, "Content-Length"); - j_hdrs_del(h, "Keep-Alive"); } j_hdrs_set(h, "Connection", "close"); @@ -2735,7 +2789,7 @@ static int read_response(j_conn *up, j_upstream_resp *r, double idle_s, double d 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; + te_has_chunked(te); r->content_length = -1; if (!j_hdrs_find(&r->hdrs, "Content-Length", cl, sizeof cl)) r->content_length = strtol(cl, NULL, 10); @@ -2746,15 +2800,54 @@ static int read_response(j_conn *up, j_upstream_resp *r, double idle_s, double d * "context exhausted", ...). Ohne ihn bleibt im Log nur der Status, und die Ursache * muss von Hand nachgestellt werden. Best effort: kurze Frist, gekappte Länge, * Steuerzeichen werden zu Leerzeichen. */ -static void log_upstream_error_body(j_conn *up, j_upstream_resp *r, const char *endpoint) +/* Case-blind substring; the error body is not guaranteed to be JSON. */ +static int +ci_has(const char *hay, const char *needle) +{ + size_t n; + if (!hay || !needle || !*needle) return 0; + n = strlen(needle); + for (; *hay; hay++) + if (!strncasecmp(hay, needle, n)) return 1; + return 0; +} + +/* + * A 500 can be the endpoint's fault or the request's. These bodies say the + * caller sent a conversation the engine cannot parse (a malformed tool call); + * cooling every endpoint for that turns one bad client turn into a fleet-wide + * outage and the next retry repeats it. + */ +static int +body_is_request_error(const char *body, size_t len) +{ + char snip[512]; + size_t n; + + if (!body || !len) return 0; + n = len < sizeof snip - 1 ? len : sizeof snip - 1; + memcpy(snip, body, n); + snip[n] = '\0'; + return ci_has(snip, "Failed to parse tool call arguments") || + ci_has(snip, "failed to parse tool call arguments") || + ci_has(snip, "invalid_request_error") || + ci_has(snip, "Bad Request") || + ci_has(snip, "expected end of input"); +} + +/* Log the upstream's error body and hand it back to the caller; caller frees. */ +static char *log_upstream_error_body(j_conn *up, j_upstream_resp *r, + const char *endpoint, size_t *lenp) { char body_err[96]; char *body = NULL; size_t len = 0; + if (lenp) *lenp = 0; if (read_full_body(up, &r->buf, r->body_off, r->chunked, r->content_length, 0.5, now_s() + 1.0, &body, &len, body_err, sizeof body_err) != 0) - return; + return NULL; + if (lenp) *lenp = len; if (body != NULL && len > 0) { char snip[241]; size_t n = len > 200 ? 200 : len, o = 0, spaces = 0; @@ -2773,11 +2866,33 @@ static void log_upstream_error_body(j_conn *up, j_upstream_resp *r, const char * snip[o] = '\0'; jlog("upstream_error", "endpoint=%s status=%d body=%s", endpoint, r->status, snip); } - free(body); + return body; } /* Returns 0 = served, -1 = endpoint failed (fail over), -2 = bytes already sent to the * client, so failing over is impossible. */ +/* The peer's address, for X-Forwarded-For and the logs. The old code wrote a + * literal 127.0.0.1, which told every upstream a lie about the last hop. */ +static void peer_ip(const j_conn *c, char *buf, size_t cap) +{ + struct sockaddr_storage ss; + socklen_t len = sizeof ss; + + if (buf == NULL || cap == 0) return; + buf[0] = '\0'; + if (c == NULL || c->fd < 0) return; + if (getpeername(c->fd, (struct sockaddr *)&ss, &len) != 0) return; + if (ss.ss_family == AF_INET) { + const struct sockaddr_in *a = (const struct sockaddr_in *)&ss; + + (void)inet_ntop(AF_INET, &a->sin_addr, buf, (socklen_t)cap); + } else if (ss.ss_family == AF_INET6) { + const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)&ss; + + (void)inet_ntop(AF_INET6, &a6->sin6_addr, buf, (socklen_t)cap); + } +} + static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, const char *out_body, size_t out_len, const char *as_model, const char *rq_model, const char *cache_state, double req_started, @@ -2786,7 +2901,21 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, { 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)) { + /* base_cmd, not base, is the truth for a service that binds its port at + * startup. The opencode bridge has always resolved it; every other endpoint + * kind went to the static address and failed after a restart. */ + char base_cmd_url[J_URL_MAX]; + const char *base_url = ep->base; + if (ep->base_cmd[0]) { + ptrdiff_t ep_index = ep - CFG.endpoints; + if (ep_index < 0 || ep_index >= CFG.endpoint_count || + cmd_value((int)ep_index, 0, base_cmd_url, sizeof base_cmd_url, 60.0) != 0) { + snprintf(err, errlen, "base_cmd_failed"); + return -1; + } + base_url = base_cmd_url; + } + if (split_url(base_url, host, sizeof host, port, sizeof port, prefix, sizeof prefix, &tls)) { snprintf(err, errlen, "bad_base_url"); return -1; } @@ -2867,10 +2996,24 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, const char *inj_key = NULL; if (ep->key_env_count > 0) { STATE_LOCK(); - int ki = (int)(ep->key_rr++ % (unsigned long)ep->key_env_count); + int base = (int)(ep->key_rr++ % (unsigned long)ep->key_env_count); STATE_UNLOCK(); - const char *v = getenv(ep->api_key_env[ki]); - if (v && v[0]) inj_key = v; + /* The rotation may land on an env that is empty; another key of the same + * endpoint can still be set. Only when none of them is do we stop. */ + for (int k = 0; k < ep->key_env_count; k++) { + const char *v = getenv(ep->api_key_env[(base + k) % ep->key_env_count]); + if (v && v[0]) { inj_key = v; break; } + } + if (inj_key == NULL) { + /* The endpoint declares keys but none is set. Forwarding the client's + * Authorization here sent a junction virtual key to a provider; fail + * this endpoint instead, and let routing try the next one. */ + snprintf(err, errlen, "no_key_for_endpoint_%s", ep->name); + jlog("no_key", "endpoint=%s", ep->name); + free(body_alloc); + j_conn_close(&up); + return -1; + } } int inject_auth = (inj_key != NULL); int anthropic_kind = !strcmp(ep->kind, "anthropic"); @@ -2927,8 +3070,11 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, char xff[J_HDR_VALUE]; int have_xff = (j_hdrs_find(&rq->hdrs, "X-Forwarded-For", xff, sizeof xff) == 0 && xff[0] != '\0'); - used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "X-Forwarded-For: %s%s127.0.0.1\r\n", - have_xff ? xff : "", have_xff ? ", " : ""); + char peerbuf[64]; + peer_ip(client, peerbuf, sizeof peerbuf); + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "X-Forwarded-For: %s%s%s\r\n", + have_xff ? xff : "", have_xff ? ", " : "", + peerbuf[0] ? peerbuf : "unknown"); if (out_body && out_len) used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "Content-Length: %zu\r\n", out_len); @@ -2995,8 +3141,37 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, return -1; } if (r.status >= 500 || r.status == 429) { + size_t errbody_len = 0; + char *errbody; + t_heartbeat = NULL; - log_upstream_error_body(&up, &r, ep->name); + errbody = log_upstream_error_body(&up, &r, ep->name, &errbody_len); + /* + * The request itself was bad (malformed tool_call in the + * conversation). Do not bench an endpoint for that, and do not + * fail over to the next one with the same poison. + */ + if ((capture == NULL || capture_client_error) && + body_is_request_error(errbody, errbody_len)) { + char msg[700]; + + snprintf(msg, sizeof msg, "upstream rejected the request: %.*s", + (int)(errbody_len > 500 ? 500 : errbody_len), + errbody ? errbody : ""); + if (head_sent) + sse_error(client, 422, msg); + else + send_simple(client, 422, "Unprocessable Content", msg); + jlog("client_error", "endpoint=%s status=%d body=%.300s", + ep->name, r.status, errbody ? errbody : ""); + snprintf(err, errlen, "client_request_error_%d", r.status); + free(errbody); + resp_free(&r); + j_conn_close(&up); + free(body_alloc); + return -2; + } + free(errbody); snprintf(err, errlen, "upstream_status_%d", r.status); /* Was der Anbieter selbst sagt, ist besser als jede eigene Wartezeit: bei 429 * und 503 steht dort oft, wann es wieder geht. Nur Sekunden werden gelesen — @@ -3021,7 +3196,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, * provider error must be delivered, not hidden behind no_endpoint. */ if (capture && (r.status < 200 || r.status >= 300)) { if (!capture_client_error) { - log_upstream_error_body(&up, &r, ep->name); + free(log_upstream_error_body(&up, &r, ep->name, NULL)); snprintf(err, errlen, "upstream_status_%d", r.status); resp_free(&r); j_conn_close(&up); @@ -3286,7 +3461,30 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, } size_t pre_off = r.body_off; size_t pre_len = r.buf.len > pre_off ? r.buf.len - pre_off : 0; - int rc = r.chunked + /* + * The head (if any) is already out and promises a close-delimited body, so + * the framing has to be decided from the bytes, not only from a header a + * proxy may have dropped. A chunk-framed body relayed raw put "d9\r\n" in + * front of a client's SSE events; splinter read the hex sizes as content + * and reported a truncated stream. + */ + int chunked_body = r.chunked; + if (!chunked_body && r.content_length < 0 && + r.status != 204 && r.status != 304 && + (rq == NULL || strcmp(rq->method, "HEAD") != 0)) { + if (pre_len < 20 && wait_readable(&up, ep->idle_timeout_s < 5.0 ? ep->idle_timeout_s : 5.0, + deadline) == 1) { + char sniff[64]; + ssize_t n = j_conn_read(&up, sniff, sizeof sniff, err, sizeof err); + if (n > 0 && j_buf_append(&r.buf, sniff, (size_t)n) == 0) + pre_len = r.buf.len - pre_off; + } + chunked_body = body_looks_chunked(r.buf.data + pre_off, pre_len); + if (chunked_body) + jlog("chunked_without_header", "endpoint=%s: body has chunk framing, " + "Transfer-Encoding did not say so", ep->name); + } + int rc = chunked_body ? relay_dechunk(client, &up, r.buf.data + pre_off, pre_len, ep->idle_timeout_s, deadline) : relay_stream(client, &up, r.buf.data + pre_off, pre_len, r.content_length, ep->idle_timeout_s, deadline); @@ -3866,6 +4064,22 @@ static void handle_client_inner(j_conn *client) !strcmp(rq.path, "/v1/queue") || !strcmp(rq.path, "/queue")) { status_page(client); goto done; } + /* + * The management surface is for the machine's own operator. The listener is + * 0.0.0.0 so clients on the LAN can use /v1 and /status; a pause, a cache + * flush or the spend report must not work from there. It must not work with + * a plain GET either: any web page the operator visits could fire it with + * an tag. /metrics has its own listener (metrics tcp ...); this copy + * only stays for the loopback. + */ + if (!peer_is_local(client) && + (!strncmp(rq.path, "/admin/", 7) || !strncmp(rq.path, "/spend", 6) || + !strcmp(rq.path, "/metrics"))) { + send_simple(client, 403, "Forbidden", + "{\"error\":\"management endpoint is loopback-only\"}"); + jlog("mgmt_denied", "path=%.64s", rq.path); + goto done; + } if (!strcmp(rq.path, "/metrics")) { metrics_page(client); goto done; } if (!strncmp(rq.path, "/spend", 6)) { spend_page(client, rq.path); goto done; } if (!strncmp(rq.path, "/admin/", 7)) { admin(client, rq.path); goto done; } @@ -4651,6 +4865,14 @@ static void *connection_thread(void *arg) free(arg); j_conn client = J_CONN_INIT; char err[256]; + /* + * A client that stops reading must not hold this thread (and the inflight + * slot it carries) forever: write() is blocking and has no deadline of its + * own. A stalled write means the client is gone, not that we should wait. + */ + struct timeval snd = { .tv_sec = 15, .tv_usec = 0 }; + + (void)setsockopt(cfd, SOL_SOCKET, SO_SNDTIMEO, &snd, sizeof snd); if (CFG.listen_tls) { if (j_tls_server_accept(&client, cfd, err, sizeof err)) { jlog("tls_accept_failed", "%s", err); @@ -4718,12 +4940,22 @@ static int make_listener(const j_config *cfg, char *err, size_t errlen) * 4xx zählt als erreichbar: ein 401 heißt "falscher Schlüssel", nicht "Maschine aus". * Für den Router ist das ein anderer Fehler und gehört nicht hierher. */ -static int probe_endpoint(const j_endpoint *ep) +static int probe_endpoint(int index, char *resolved, size_t resolved_len) { + const j_endpoint *ep = &CFG.endpoints[index]; char base[J_URL_MAX]; - snprintf(base, sizeof base, "%s", ep->base); + /* base_cmd ist die Wahrheit, nicht base: opencode serve bindet bei jedem Start + * einen freien Port. Wer hier die statische Adresse prüft, nimmt einen gesunden + * Dienst für offline — und die Anfrage bekommt 503, obwohl er erreichbar ist. */ + if (resolved && resolved_len) snprintf(resolved, resolved_len, "%s", ep->base); + if (ep->base_cmd[0]) { + if (cmd_value(index, 0, base, sizeof base, 5.0) != 0) return -1; + } else { + snprintf(base, sizeof base, "%s", ep->base); + } size_t bl = strlen(base); while (bl > 0 && base[bl - 1] == '/') base[--bl] = '\0'; + if (resolved && resolved_len) snprintf(resolved, resolved_len, "%s", base); if (!bl) return -1; char cmd[2048]; @@ -4772,15 +5004,16 @@ static void *probe_thread(void *unused) double t = now_s(); for (int i = 0; i < CFG.endpoint_count; i++) { j_endpoint *ep = &CFG.endpoints[i]; - if (!ep->probe_on || ep->paused || !ep->base[0]) continue; - int alive = probe_endpoint(ep) == 0; + if (!ep->probe_on || ep->paused || (!ep->base[0] && !ep->base_cmd[0])) continue; + char probed_base[J_URL_MAX] = ""; + int alive = probe_endpoint(i, probed_base, sizeof probed_base) == 0; if (!alive) { /* A single failed probe under load must not take an endpoint out * of service for offline_hold_s: the request path is the better * witness. Give the probe one immediate second chance. */ struct timespec again = { 0, 200 * 1000 * 1000 }; nanosleep(&again, NULL); - alive = probe_endpoint(ep) == 0; + alive = probe_endpoint(i, probed_base, sizeof probed_base) == 0; } int was_off = ep->offline_until > now_s(); STATE_LOCK(); @@ -4795,7 +5028,8 @@ static void *probe_thread(void *unused) STATE_UNLOCK(); if (!alive && !was_off) jlog("probe_offline", "endpoint=%s base=%s hold_s=%.0f", - ep->name, ep->base, CFG.offline_hold_s); + ep->name, probed_base[0] ? probed_base : ep->base, + CFG.offline_hold_s); else if (alive && was_off) jlog("probe_recovered", "endpoint=%s", ep->name); } diff --git a/src/models.c b/src/models.c index 8ddef25..1bed487 100644 --- a/src/models.c +++ b/src/models.c @@ -183,11 +183,19 @@ done: /* Ein Muster gegen die volle ID und, falls vorhanden, gegen die ID ohne * "#variante" prüfen. So bleibt eine Freigabe für das Modell auch dann gültig, - * wenn der Client einen opencode-Variantenselektor anhängt. */ + * wenn der Client einen opencode-Variantenselektor anhängt. Ein Muster ohne + * Platzhalter ist ein strcmp; nur echte Globs gehen durch fnmatch. */ +static int pattern_match(const char *pattern, const char *value) +{ + if (!strpbrk(pattern, "*?[")) + return strcmp(pattern, value) == 0; + return fnmatch(pattern, value, 0) == 0; +} + static int model_match(const char *pattern, const char *model, const char *base) { - return fnmatch(pattern, model, 0) == 0 || - (base && base[0] && fnmatch(pattern, base, 0) == 0); + return pattern_match(pattern, model) || + (base && base[0] && pattern_match(pattern, base)); } int j_model_allowed(const char *model) diff --git a/tests/probe.sh b/tests/probe.sh index fae2ea8..a404951 100755 --- a/tests/probe.sh +++ b/tests/probe.sh @@ -93,3 +93,47 @@ if grep -q "probe_offline endpoint=quiet" "$TMP/probe_off.log" 2>/dev/null; then else ok "probe off keeps an endpoint out of the check" fi + +# base_cmd ist die Adresse, nicht base. opencode serve bindet bei jedem Start einen +# neuen Port; eine Prüfung gegen die alte Adresse nimmt den gesunden Dienst offline +# und jede Anfrage bekommt 503, obwohl er läuft. +echo +echo "== 39. Hintergrundprüfung folgt base_cmd ==" +PP2=$((PORT+300)) +P_DYN=$((PORT+301)) +P_STALE=$((PORT+302)) +tests/stub $P_DYN "DYNAMIC" > "$TMP/probe_dynamic_stub.log" 2>&1 & +PIDS+=($!) +sleep 0.4 +cat > "$TMP/probe_base_cmd.conf" < "$TMP/probe_base_cmd.log" 2>&1 & +PIDS+=($!) +wait_port "$PP2" 10 || bad "the base_cmd probe instance did not come up" +sleep 2.5 +dyn_state=$(curl -s -m 5 "http://127.0.0.1:$PP2/status" | python3 -c " +import sys,json +d=json.load(sys.stdin) +for e in d['endpoints']: + if e['name']=='dynamic': print(e['probe_ok'], int(e['offline_s']))") +set -- $dyn_state +if [ "${1:-0}" = "1" ] && [ "${2:-1}" = "0" ]; then + ok "the probe checks the address reported by base_cmd" +else + bad "the probe used the stale base address (probe_ok=$1 offline_s=$2)" +fi +R=$(curl -s -m 15 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"m","messages":[{"role":"user","content":"x"}],"max_tokens":3}' \ + "http://127.0.0.1:$PP2/v1/chat/completions") +contains "$R" "served by DYNAMIC" "a base_cmd endpoint is not skipped as offline" diff --git a/tests/run.sh b/tests/run.sh index ead9698..994d17e 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -11,7 +11,7 @@ done TMP=$(mktemp -d) PORT=8135 -P_FAIL=9990; P_GATED=9991; P_DEAD=9992; P_SLOW=9993; P_PONDER=9994 +P_FAIL=9990; P_GATED=9991; P_DEAD=9992; P_SLOW=9993; P_PONDER=9994; P_SSE_NOT=9997; P_SSE_CAP=9998 PIDS=() FAILED=0 @@ -71,7 +71,7 @@ log_has() { # answer requests with somebody else's config), so fail loudly and early. # 8157 gehört auf dieser Maschine dem Hermes-Gateway — der Port wird von keinem # Test benutzt, also darf er die Suite nicht aufhalten. -for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8204 8205 8206 8207 8208 8209 8210 9443 9990 9991 9992 9993 9994 9995 9996; do +for port in 8361 8362 8363 8364 8357 8358 8359 8360 8355 8356 8347 8348 8349 8350 8351 8352 8353 8354 8345 8346 8335 8336 8337 8338 8339 8340 8341 8342 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8395 8396 8397 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8150 8151 8152 8153 8154 8155 8156 8158 8159 8160 8161 8162 8163 8164 8165 8166 8365 8366 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8167 8168 8170 8171 8172 8173 8175 8180 8181 8194 8176 8177 8185 8186 8187 8188 8189 8190 8204 8205 8206 8207 8208 8209 8210 9443 9990 9991 9992 9993 9994 9995 9996 9997 9998 8215 8216; 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/^/ /' @@ -96,6 +96,8 @@ tests/stub $P_FAIL "FAILING" --fail & PIDS+=($!) tests/stub $P_GATED "GATED" & PIDS+=($!) tests/stub $P_SLOW "SLOW" --delay 6 & PIDS+=($!) tests/stub $P_PONDER "PONDER" --delay 13 & PIDS+=($!) +tests/stub $P_SSE_NOT "SSENOTE" --sse-no-te & PIDS+=($!) +tests/stub $P_SSE_CAP "SSECAP" --sse-cap & PIDS+=($!) sleep 0.5 # a hook that refuses until a marker file exists (created after 3 s) @@ -320,6 +322,22 @@ endpoint gated { header "X-Static: yes" } +endpoint ssenote { + base http://127.0.0.1:$P_SSE_NOT/v1 + context 64000 + timeout 10 + idle_timeout 5 +} + +endpoint ssecap { + base http://127.0.0.1:$P_SSE_CAP/v1 + context 64000 + timeout 10 + idle_timeout 5 +} + +req for "streamnote" check none pass ssenote +req for "streamcap" check none pass ssecap req for "*" check none pass gated CFG ./junction --config "$TMP/features.conf" > "$TMP/features.log" 2>&1 & @@ -336,6 +354,83 @@ RESP=$( { printf 'POST /v1/chat/completions HTTP/1.1\r\nHost: t\r\nContent-Type: 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" +# A gateway in front of the provider may strip Transfer-Encoding and leave the +# chunk framing in the body. Relayed raw, the client reads the hex sizes as SSE +# content and reports a truncated stream. +SSE1=$(curl -sN --raw -m 15 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"streamnote","stream":true,"messages":[{"role":"user","content":"go"}]}' \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +case "$SSE1" in + data:*) ok "chunk framing without a TE header is removed" ;; + *) bad "framing leaked: $(printf '%s' "$SSE1" | head -c 30 | tr -d '\r\n')" ;; +esac +contains "$SSE1" '"stub":"two"' "both events arrive" +SSE2=$(curl -sN --raw -m 15 -X POST -H 'Content-Type: application/json' \ + -d '{"model":"streamcap","stream":true,"messages":[{"role":"user","content":"go"}]}' \ + "http://127.0.0.1:$FEAT/v1/chat/completions") +case "$SSE2" in + data:*) ok "Transfer-Encoding is matched case-blind" ;; + *) bad "capital-Chunked missed: $(printf '%s' "$SSE2" | head -c 30 | tr -d '\r\n')" ;; +esac + +echo "== 10c. management endpoints are loopback-only ==" +MG=$((PORT+80)) +cat > "$TMP/mgmt.conf" < "$TMP/mgmt.log" 2>&1 & +PIDS+=($!) +sleep 0.7 +IP=$(ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -1) +if [ -n "$IP" ]; then + R=$(curl -s -o /dev/null -w '%{http_code}' "http://$IP:$MG/admin/pause/gated") + [ "$R" = "403" ] && ok "pause from $IP is refused (403)" || bad "pause from $IP answered $R" + R=$(curl -s -o /dev/null -w '%{http_code}' "http://$IP:$MG/metrics") + [ "$R" = "403" ] && ok "/metrics from $IP is refused (403)" || bad "/metrics from $IP answered $R" + R=$(curl -s -o /dev/null -w '%{http_code}' "http://$IP:$MG/spend") + [ "$R" = "403" ] && ok "/spend from $IP is refused (403)" || bad "/spend from $IP answered $R" +else + echo " SKIP management-from-LAN (no non-loopback address)" +fi +R=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$MG/admin/pause/gated") +[ "$R" = "200" ] && ok "pause from loopback still works" || bad "local pause answered $R" +curl -s -o /dev/null "http://127.0.0.1:$MG/admin/resume/gated" + +echo "== 10d. an endpoint with no key never forwards the caller's Authorization ==" +NK=$((PORT+81)) +cat > "$TMP/nokey.conf" </dev/null || true +./junction --config "$TMP/nokey.conf" > "$TMP/nokey.log" 2>&1 & +PIDS+=($!) +sleep 0.7 +NK_RESP=$(curl -s -m 10 -H 'Authorization: Bearer SUPER-SECRET-TOKEN' \ + -H 'Content-Type: application/json' \ + -d '{"model":"nokeytest","messages":[{"role":"user","content":"hi"}]}' \ + "http://127.0.0.1:$NK/v1/chat/completions") +case "$NK_RESP" in + *"served by GATED"*) bad "client Authorization reached the endpoint" ;; + *) ok "request failed instead of forwarding the client token" ;; +esac +grep -q "no_key endpoint=nokey" "$TMP/nokey.log" && ok "the missing key is logged" \ + || bad "missing key not logged" + # 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) # Temperatur 0, weil der Cache sonst bewusst nicht greift (siehe Abschnitt 22). diff --git a/tests/stub.c b/tests/stub.c index a6c679e..9a843c5 100644 --- a/tests/stub.c +++ b/tests/stub.c @@ -136,10 +136,14 @@ int main(int argc, char **argv) int retry_after = 0; int retry_after_date = 0; int has_retry_date = 0; + int sse_mode = 0; const char *deny_auth = ""; 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], "--sse")) sse_mode = 1; + else if (!strcmp(argv[i], "--sse-cap")) sse_mode = 2; + else if (!strcmp(argv[i], "--sse-no-te")) sse_mode = 3; else if (!strcmp(argv[i], "--delay") && i + 1 < argc) delay = atof(argv[++i]); else if (!strcmp(argv[i], "--fail-n") && i + 1 < argc) fail_n = atoi(argv[++i]); else if (!strcmp(argv[i], "--status") && i + 1 < argc) forced_status = atoi(argv[++i]); @@ -508,6 +512,22 @@ int main(int argc, char **argv) if (bo < sizeof b - 2) snprintf(b + bo, sizeof b - bo, "]%s}", usage); } + if (sse_mode) { + const char *e1 = "data: {\"stub\":\"one\"}\n\n"; + const char *e2 = "data: {\"stub\":\"two\"}\n\n"; + int off = snprintf(body, sizeof body, + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n" + "Cache-Control: no-cache\r\n%sConnection: close\r\n\r\n", + sse_mode == 1 ? "Transfer-Encoding: chunked\r\n" : + sse_mode == 2 ? "Transfer-Encoding: Chunked\r\n" : ""); + if (off > 0 && (size_t)off < sizeof body) { + off += snprintf(body + off, sizeof body - (size_t)off, + "%zx\r\n%s\r\n", strlen(e1), e1); + off += snprintf(body + off, sizeof body - (size_t)off, + "%zx\r\n%s\r\n", strlen(e2), e2); + snprintf(body + off, sizeof body - (size_t)off, "0\r\n\r\n"); + } + } else snprintf(body, sizeof body, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" "Content-Length: %zu\r\n"