diff --git a/src/junction.c b/src/junction.c index 318960d..b80c1c6 100644 --- a/src/junction.c +++ b/src/junction.c @@ -677,6 +677,86 @@ static int relay_stream(j_conn *client, j_conn *up, const char *pre, size_t pre_ } } +/* Relay a chunked upstream body to the client WITHOUT the chunk framing. + * + * Why this exists: the client's response head is written before the upstream is even + * chosen on a streaming request, so Transfer-Encoding cannot be added afterwards. The + * old code forwarded the raw framing, and the client read the hex size lines as + * content — Hermes saw `f\r\ndata: …` and reported a truncated JSON body while + * junction logged relay_failed. De-chunking here keeps the bytes identical to what + * the upstream meant to send; the body ends when the connection closes. */ +static int relay_dechunk(j_conn *client, j_conn *up, const char *pre, size_t pre_len, + double idle_s, double deadline) +{ + char err[192]; + static char in[RELAY_CHUNK * 2]; + size_t have = 0; + if (pre && pre_len) { + if (pre_len > sizeof in) return -1; + memcpy(in, pre, pre_len); + have = pre_len; + } + long chunk_left = -1; /* bytes still to copy of the current chunk, -1 = need size */ + int at_line = 1; /* expecting a chunk-size line */ + for (;;) { + if (at_line) { + /* look for CRLF in the buffer */ + size_t i = 0; + while (i + 1 < have && !(in[i] == '\r' && in[i + 1] == '\n')) i++; + if (i + 1 >= have) { + if (have == sizeof in) return -1; /* size line never ends */ + if (wait_readable(up, idle_s, deadline) != 1) return -1; + ssize_t n = j_conn_read(up, in + have, sizeof in - have, err, sizeof err); + if (n <= 0) return -1; + have += (size_t)n; + continue; + } + char num[32]; + size_t nl = i < sizeof num - 1 ? i : sizeof num - 1; + memcpy(num, in, nl); + num[nl] = '\0'; + long sz = strtol(num, NULL, 16); + /* drop the line (plus an optional chunk extension) */ + size_t consumed = i + 2; + memmove(in, in + consumed, have - consumed); + have -= consumed; + if (sz <= 0) { + /* last chunk: swallow the trailer and stop */ + return 0; + } + chunk_left = sz; + at_line = 0; + } + if (chunk_left > 0) { + if (have == 0) { + if (wait_readable(up, idle_s, deadline) != 1) return -1; + ssize_t n = j_conn_read(up, in, sizeof in, err, sizeof err); + if (n <= 0) return -1; + have = (size_t)n; + } + size_t copy = have < (size_t)chunk_left ? have : (size_t)chunk_left; + if (j_conn_write(client, in, copy, err, sizeof err) < 0) return -1; + memmove(in, in + copy, have - copy); + have -= copy; + chunk_left -= (long)copy; + continue; + } + /* end of chunk data: expect CRLF, then the next size line */ + if (have < 2) { + if (wait_readable(up, idle_s, deadline) != 1) return -1; + ssize_t n = j_conn_read(up, in + have, sizeof in - have, err, sizeof err); + if (n <= 0) return -1; + have += (size_t)n; + continue; + } + if (in[0] == '\r' && in[1] == '\n') { + memmove(in, in + 2, have - 2); + have -= 2; + } + at_line = 1; + } +} + /* Read a complete body (chunked or Content-Length) into memory. */ static int read_full_body(j_conn *up, j_buf *buf, size_t off, int chunked, long content_length, double idle_s, double deadline, char **body, size_t *body_len, @@ -710,6 +790,24 @@ 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. */ + 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"); @@ -717,7 +815,7 @@ static int send_head(j_conn *client, int status, const char *reason, j_hdrs *h, if (!out) { snprintf(err, errlen, "oom"); return -1; } size_t used = (size_t)snprintf(out, HDR_BLOCK_MAX, "HTTP/1.1 %d %s\r\n", status, reason[0] ? reason : "OK"); - used += j_hdrs_serialize(h, out + used, HDR_BLOCK_MAX - used, 1, 1); + used += j_hdrs_serialize(h, out + used, HDR_BLOCK_MAX - used, body_len >= 0 ? 1 : 0, 1); int rc = j_conn_write(client, out, used, err, errlen) < 0 ? -1 : 0; free(out); return rc; @@ -818,11 +916,19 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, /* Forward the client's headers, but not the ones we own. Forwarding the client's * Host gave the upstream TWO Host headers, and its Content-Length plus ours gave - * it two lengths — Ollama answered 400 for a request that was valid. */ + * it two lengths — Ollama answered 400 for a request that was valid. + * + * Authorization is the same class of bug: when this endpoint injects its own key, + * the client's header must be dropped, or the upstream receives two Authorization + * headers. Ollama shrugged; Cloudflare answers 400 Bad Request for it, which looks + * like a broken endpoint and is really a duplicated header. */ + const char *inj_key = ep->api_key_env[0] ? getenv(ep->api_key_env) : NULL; + int inject_auth = (inj_key && inj_key[0]); for (int i = 0; i < rq->hdrs.n; i++) { const char *name = rq->hdrs.it[i].name; if (j_is_hop_by_hop(&rq->hdrs, name)) continue; if (!strcasecmp(name, "Host") || !strcasecmp(name, "Content-Length") || + (inject_auth && !strcasecmp(name, "Authorization")) || !strcasecmp(name, "Transfer-Encoding") || !strcasecmp(name, "X-Forwarded-For") || !strcasecmp(name, "X-Forwarded-Proto") || !strncasecmp(name, "X-Junction-", 11)) @@ -841,12 +947,9 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, snprintf(hosthdr, sizeof hosthdr, "%s:%s", host, port); used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "Host: %s\r\n", hosthdr); - if (ep->api_key_env[0]) { - const char *key = getenv(ep->api_key_env); - if (key && key[0]) - used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, - "Authorization: Bearer %s\r\n", key); - } + if (inject_auth) + used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, + "Authorization: Bearer %s\r\n", inj_key); for (int i = 0; i < ep->header_count; i++) { if (strchr(ep->headers[i], '\r') || strchr(ep->headers[i], '\n')) continue; used += (size_t)snprintf(req + used, HDR_BLOCK_MAX - used, "%s\r\n", ep->headers[i]); @@ -871,6 +974,36 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, free(rewritten); return -1; } + + /* J_DUMP_REQ=: write exactly what goes upstream, with the credentials + * masked. Exists because a strict frontend (Cloudflare) rejects what a lenient + * one (Ollama) accepts, and guessing from the outside wastes hours. */ + const char *dump_path = getenv("J_DUMP_REQ"); + if (dump_path && dump_path[0]) { + FILE *df = fopen(dump_path, "a"); + if (df) { + fprintf(df, "--- %s %s -> %s (%s) ---\n", rq->method, target, ep->name, + tls ? "tls" : "plain"); + const char *p = req; + while (*p) { + const char *nl = strchr(p, '\n'); + size_t len = nl ? (size_t)(nl - p + 1) : strlen(p); + if (!strncasecmp(p, "Authorization:", 14)) + fprintf(df, "Authorization: \n"); + else + fwrite(p, 1, len, df); + if (!nl) break; + p = nl + 1; + } + if (out_body && out_len) { + fputs("=== BODY ===\n", df); + fwrite(out_body, 1, out_len, df); + fputc('\n', df); + } + fclose(df); + } + } + if (j_conn_write(&up, req, used, err, errlen) < 0 || (out_body && out_len && j_conn_write(&up, out_body, out_len, err, errlen) < 0)) { free(req); @@ -983,7 +1116,7 @@ static int forward_step(j_conn *client, j_endpoint *ep, const j_req *rq, } if (!head_sent && - send_head(client, r.status, r.reason, &r.hdrs, r.chunked ? -1 : r.content_length, + send_head(client, r.status, r.reason, &r.hdrs, r.chunked ? -2 : r.content_length, err, errlen)) { t_heartbeat = NULL; resp_free(&r); @@ -993,8 +1126,10 @@ 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 = relay_stream(client, &up, r.buf.data + pre_off, pre_len, - r.chunked ? -1 : r.content_length, ep->idle_timeout_s, deadline); + int rc = r.chunked + ? 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); t_heartbeat = NULL; resp_free(&r); j_conn_close(&up);