Files
junction/src/http.c
T
Hermes 3ad38869ae http: a client that goes away is not an upstream failure
When a streaming client closed the connection, the heartbeat write in
wait_readable() failed and the read path reported it as a poll/read error. The
router then counted it against the endpoint and put the whole pool into
cooldown: one cancelled stream (a splinter session stopped after a malformed
tool call) cooled four endpoints, and the next request answered "no endpoint
available ... tried: cooling cooling cooling cooling".

wait_readable() now returns -2 for "the progress hook could not write to the
client", the two buffer readers report it as client_gone, and the request
handler maps that to the existing abort path (rc=-2) instead of the failure
path. The endpoint stays available: the operator closed the stream, the model
did nothing wrong.

Reproduced with a stub that answers after 25 s while the client leaves after
1 s: before, the endpoint was cooled and the follow-up request had no endpoint;
now the log says aborted ... error=client_gone, offline_s=0 and the follow-up
request is served. tests/run.sh: PASS.
2026-11-19 08:43:46 +00:00

444 lines
15 KiB
C

/* 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 int (*g_progress)(const char *role, double idle_s);
void j_set_progress(int (*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;
/* a connection that carries a live stream is allowed to be woken earlier:
* the caller wants to emit a heartbeat, not to give up */
if (c->heartbeat_s > 0 && (double)c->heartbeat_s < t) t = (double)c->heartbeat_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) {
/* The progress hook writes a heartbeat to the client. If that write
* fails, the client is gone -- that is not an upstream fault and
* must not cool the endpoint. -2 says so; -1 stays "poll failed". */
if (g_progress && g_progress(c->role ? c->role : "upstream", t) != 0)
return -2;
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 == -2) { snprintf(err, errlen, "client_gone"); return -1; }
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 == -2) { snprintf(err, errlen, "client_gone"); return -1; }
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;
}
static void (*g_hdr_note)(const char *event, const char *name);
void j_hdrs_set_note_hook(void (*fn)(const char *event, const char *name))
{
g_hdr_note = fn;
}
static void hdr_note(const char *event, const char *name)
{
if (g_hdr_note) g_hdr_note(event, name);
}
/* A header name is a token: no whitespace, no colon, no control bytes. Rejecting
* the whole header is safer than rewriting its name into a different one. */
static int hdr_name_ok(const char *name)
{
if (!name || !name[0]) return 0;
for (const unsigned char *p = (const unsigned char *)name; *p; p++) {
if (*p <= 0x20 || *p >= 0x7f || *p == ':') return 0;
}
return 1;
}
/* CR/LF in a value would end the header and start an injected one. Other control
* bytes are invalid in a field value too; replace them with a space. Tabs stay. */
static int hdr_value_clean(char *dst, size_t cap, const char *src)
{
size_t o = 0;
int dirty = 0;
for (const unsigned char *p = (const unsigned char *)(src ? src : "");
*p && o + 1 < cap; p++) {
unsigned char c = *p;
if (c == '\r' || c == '\n' || (c < 0x20 && c != '\t') || c == 0x7f) {
c = ' ';
dirty = 1;
}
dst[o++] = (char)c;
}
dst[o] = '\0';
return dirty;
}
void j_hdrs_add(j_hdrs *h, const char *name, const char *value)
{
if (!hdr_name_ok(name)) { hdr_note("header_name_rejected", name); return; }
if (h->n >= J_MAX_HDRS) { /* dropping beats corrupting */
hdr_note("headers_dropped", name);
return;
}
char clean[J_HDR_VALUE];
if (hdr_value_clean(clean, sizeof clean, value))
hdr_note("header_control_chars", name);
snprintf(h->it[h->n].name, J_HDR_NAME, "%s", name);
snprintf(h->it[h->n].value, J_HDR_VALUE, "%s", clean);
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;
}