/* * sx_http.c -- HTTP/1.1 over TCP or mbedTLS TLS, for plugin_ntfy. * * Two shapes of use, and the code is organised around them: * * sx_http_request() -- buffered: send a request, get status + body. * Used for publishing a notification and for the * bot API calls (/inbox, /conversation). * sx_http_open_stream() + * sx_http_readline() -- streaming: send a request, read status + * headers, then hand back one newline-delimited * record at a time. This is the /json * subscription, which sits idle for minutes * between keepalives and must never buffer the * whole stream nor block the process forever. * * Three details are the reason this file is written by hand instead of * shelling out to curl (a plugin that pops a shell to reach the network * cannot be audited, and curl is not present on a slim container or a * Windows node): * * 1. deadlines. Every phase -- connect, handshake, header read, ONE record * read -- has its own absolute monotonic deadline enforced with * select(). The only way to bound an mbedTLS handshake is to own the * socket under it, so after connecting the socket stays non-blocking * for its whole life and mbedTLS is fed through mbedtls_ssl_set_bio(): * WANT_READ -> select() -> retry, everywhere. * 2. chunked bodies. The live NDJSON stream is served as * Transfer-Encoding: chunked, so reading a body is a small state * machine (hex size line, chunk bytes, CRLF, trailers), not * "read Content-Length bytes". * 3. failing closed on TLS. The handshake runs with VERIFY_OPTIONAL and * the code then refuses on ANY bad-certificate flag, which behaves like * VERIFY_REQUIRED while still letting an operator's explicit SPKI pin * carry a self-hosted relay on a private CA. A hostname mismatch is * never pinnable away, and the only no-verification mode is the * environment variable NTFY_TLS_INSECURE=1 -- never a config value, * never an HTTP parameter. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0601 /* getaddrinfo, inet_ntop */ # endif # define WIN32_LEAN_AND_MEAN #else # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L # undef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # ifndef _DEFAULT_SOURCE # define _DEFAULT_SOURCE 1 # endif # if defined(__APPLE__) # undef _DARWIN_C_SOURCE # define _DARWIN_C_SOURCE 1 # endif #endif #include "sx_http.h" #include "ca_bundle_pem.h" #include #include #include #include #include #include #include #include "mbedtls/platform.h" #include "mbedtls/pk.h" #include "mbedtls/sha256.h" #include "mbedtls/error.h" #include "mbedtls/x509_crt.h" #if defined(_WIN32) # include # include # include # define sx_closesocket closesocket #else # include # include # include # include # include # include # include # include # include # define sx_closesocket close #endif /* ------------------------------------------------------------------ time */ long long sx_now_ms(void) { #if defined(_WIN32) FILETIME ft; ULARGE_INTEGER u; GetSystemTimeAsFileTime(&ft); u.LowPart = ft.dwLowDateTime; u.HighPart = ft.dwHighDateTime; /* FILETIME is 100ns since 1601; /10000 -> ms. Monotonic enough here: * every use is a difference between two readings. */ return (long long)(u.QuadPart / 10000ULL); #else struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); #endif } static void set_err(char *err, size_t errsz, const char *fmt, ...) { va_list ap; if (!err || !errsz) return; va_start(ap, fmt); vsnprintf(err, errsz, fmt, ap); va_end(ap); } /* ------------------------------------------------------------------ sha256 */ void sx_sha256_hex(const void *data, size_t len, char out[65]) { unsigned char d[32]; static const char *hex = "0123456789abcdef"; int i; mbedtls_sha256((const unsigned char *)data, len, d, 0); for (i = 0; i < 32; i++) { out[i * 2] = hex[(d[i] >> 4) & 0xF]; out[i * 2 + 1] = hex[d[i] & 0xF]; } out[64] = '\0'; } /* -------------------------------------------------------------- url encode */ void sx_url_encode(const char *in, char *out, size_t capsz) { static const char *hex = "0123456789ABCDEF"; size_t o = 0; const unsigned char *p; if (!capsz) return; for (p = (const unsigned char *)in; p && *p; p++) { unsigned char c = *p; int safe = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' || c == '~'; if (safe) { if (o + 1 >= capsz) break; out[o++] = (char)c; } else { if (o + 3 >= capsz) break; out[o++] = '%'; out[o++] = hex[c >> 4]; out[o++] = hex[c & 0xF]; } } out[o] = '\0'; } /* -------------------------------------------------------------------- url */ int sx_url_parse(const char *url, sx_url *out, char *err, size_t errsz) { const char *p, *h, *e; size_t n; memset(out, 0, sizeof *out); if (!url || !*url) { set_err(err, errsz, "empty url"); return -1; } if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; } else if (strncmp(url, "http://", 7) == 0) { p = url + 7; } else { set_err(err, errsz, "url must start with http:// or https://"); return -1; } if (*p == '[') { set_err(err, errsz, "IPv6 literals are not supported"); return -1; } h = p; e = p; while (*e && *e != '/' && *e != '?' && *e != '#' && *e != ' ' && (unsigned char)*e >= 0x20) e++; n = (size_t)(e - h); if (n == 0) { set_err(err, errsz, "url has no host"); return -1; } if (n >= sizeof out->host) { set_err(err, errsz, "host too long"); return -1; } if (memchr(h, '@', n)) { set_err(err, errsz, "userinfo in url is refused"); return -1; } out->port = out->tls ? 443 : 80; { const char *colon = memchr(h, ':', n); if (colon) { char ports[8]; size_t pl = (size_t)(e - colon - 1), i; if (pl == 0 || pl >= sizeof ports) { set_err(err, errsz, "bad port"); return -1; } for (i = 0; i < pl; i++) if (!isdigit((unsigned char)colon[1 + i])) { set_err(err, errsz, "bad port"); return -1; } memcpy(ports, colon + 1, pl); ports[pl] = '\0'; out->port = atoi(ports); if (out->port < 1 || out->port > 65535) { set_err(err, errsz, "port out of range"); return -1; } n = (size_t)(colon - h); } } memcpy(out->host, h, n); out->host[n] = '\0'; if (strspn(out->host, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-") != strlen(out->host)) { set_err(err, errsz, "host contains forbidden characters"); return -1; } if (*e == '/' || *e == '?') { size_t o = 0; while (*e && *e != ' ' && o + 1 < sizeof out->path) out->path[o++] = *e++; out->path[o] = '\0'; if (*e == ' ') { set_err(err, errsz, "path contains a space"); return -1; } } else { snprintf(out->path, sizeof out->path, "/"); } { const char *c; for (c = out->path; *c; c++) if ((unsigned char)*c < 0x20 || *c == '"' || *c == '\\') { set_err(err, errsz, "path contains forbidden characters"); return -1; } } snprintf(out->scheme, sizeof out->scheme, "%s", out->tls ? "https" : "http"); return 0; } /* ------------------------------------------------------------------ socket */ static void sock_set_nonblock(sx_sock_t fd) { #if defined(_WIN32) u_long nb = 1; ioctlsocket(fd, FIONBIO, &nb); #else int fl = fcntl(fd, F_GETFL, 0); if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); #endif } /* Wait until fd is readable, or the deadline passes. 1 = ready, 0 = timeout. */ static int sx_wait_readable(sx_sock_t fd, long long deadline_ms) { for (;;) { fd_set rf; struct timeval tv; long long left = deadline_ms - sx_now_ms(); int rc; if (left <= 0) return 0; tv.tv_sec = (long)(left / 1000); tv.tv_usec = (long)((left % 1000) * 1000); FD_ZERO(&rf); FD_SET(fd, &rf); #if defined(_WIN32) rc = select(0, &rf, NULL, NULL, &tv); #else rc = select((int)fd + 1, &rf, NULL, NULL, &tv); #endif if (rc > 0) return 1; if (rc == 0) return 0; #if defined(_WIN32) return 0; #else if (errno == EINTR) continue; return 0; #endif } } /* Wait until a non-blocking connect completes. A successful connect makes a * socket writable but NOT readable, so this must watch the write set. */ static int sx_wait_writable(sx_sock_t fd, long long deadline_ms) { for (;;) { fd_set wf; struct timeval tv; long long left = deadline_ms - sx_now_ms(); int rc; if (left <= 0) return 0; tv.tv_sec = (long)(left / 1000); tv.tv_usec = (long)((left % 1000) * 1000); FD_ZERO(&wf); FD_SET(fd, &wf); #if defined(_WIN32) rc = select(0, NULL, &wf, NULL, &tv); #else rc = select((int)fd + 1, NULL, &wf, NULL, &tv); #endif if (rc > 0) return 1; if (rc == 0) return 0; #if defined(_WIN32) return 0; #else if (errno == EINTR) continue; return 0; #endif } } static int sx_connect_timeout(const char *host, int port, long long timeout_ms, sx_sock_t *fd_out, char *err, size_t errsz) { struct addrinfo hints, *res = NULL, *ai; char ports[8], hostport[300]; long long deadline; sx_sock_t fd = SX_SOCK_INVALID; snprintf(hostport, sizeof hostport, "%s:%d", host, port); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf(ports, sizeof ports, "%d", port); if (getaddrinfo(host, ports, &hints, &res) != 0 || !res) { set_err(err, errsz, "cannot resolve %s", hostport); return -1; } deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 10000); for (ai = res; ai; ai = ai->ai_next) { int rc; /* getaddrinfo on a dual-stack host returns ::1 before 127.0.0.1, and a * server bound to IPv4 loopback only refuses the IPv6 attempt. Every * failure path here MUST reset fd: an old build left the previous * (closed) descriptor in it, the loop fell through, and the caller * got "cannot connect" with a stale fd -- or worse, used a closed * socket as if it were connected. */ fd = SX_SOCK_INVALID; rc = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (rc < 0) continue; fd = (sx_sock_t)rc; sock_set_nonblock(fd); #if !defined(_WIN32) { int one = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof one); } #endif rc = connect(fd, ai->ai_addr, (int)ai->ai_addrlen); if (rc == 0) break; #if defined(_WIN32) if (WSAGetLastError() != WSAEWOULDBLOCK) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } #else if (errno != EINPROGRESS) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } #endif /* A non-blocking connect completes on WRITABILITY, not readability: * a successful connect leaves the socket readable forever, so * waiting on the read set here hangs until the deadline and every * local server looks unreachable. */ if (!sx_wait_writable(fd, deadline)) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } { int soerr = 0; socklen_t slen = sizeof soerr; if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen) != 0 || soerr != 0) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } } break; } freeaddrinfo(res); if (fd == SX_SOCK_INVALID) { set_err(err, errsz, "cannot connect to %s", hostport); return -1; } *fd_out = fd; return 0; } /* ------------------------------------------------------------- mbedTLS bio */ static int bio_send(void *ctx, const unsigned char *buf, size_t n) { sx_sock_t fd = (sx_sock_t)(intptr_t)ctx; ssize_t r = send(fd, (const char *)buf, n, 0); if (r > 0) return (int)r; #if defined(_WIN32) { int e = WSAGetLastError(); if (e == WSAEWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_WRITE; return MBEDTLS_ERR_SSL_INTERNAL_ERROR; } #else if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_WRITE; return MBEDTLS_ERR_SSL_INTERNAL_ERROR; #endif } static int bio_recv(void *ctx, unsigned char *buf, size_t n) { sx_sock_t fd = (sx_sock_t)(intptr_t)ctx; ssize_t r = recv(fd, buf, n, 0); if (r > 0) return (int)r; if (r == 0) return 0; #if defined(_WIN32) { int e = WSAGetLastError(); if (e == WSAEWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_SSL_INTERNAL_ERROR; } #else if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_SSL_INTERNAL_ERROR; #endif } /* ------------------------------------------------------------------ connect */ void sx_conn_init(sx_conn *c) { memset(c, 0, sizeof *c); c->fd = SX_SOCK_INVALID; c->content_left = -1; } static int pin_allowed(const char *pins, const char *fp) { const char *p = pins; if (!pins || !*pins || !fp || !*fp) return 0; while (*p) { char tok[80]; size_t n = 0; while (*p && (isspace((unsigned char)*p) || *p == ',')) p++; if (!*p) break; while (*p && !isspace((unsigned char)*p) && *p != ',' && n + 1 < sizeof tok) tok[n++] = (char)tolower((unsigned char)*p++); tok[n] = '\0'; if (n == 64 && strcmp(tok, fp) == 0) return 1; } return 0; } int sx_conn_open(sx_conn *c, const sx_url *url, const char *bearer, const char *pins, const char *ca_file, int insecure, long long timeout_ms, char *err, size_t errsz) { (void)bearer; /* Authorization is a request header, applied per request */ sx_conn_init(c); if (sx_connect_timeout(url->host, url->port, timeout_ms, &c->fd, err, errsz) != 0) return -1; /* Remember the peer: every request on this connection rebuilds its own * Host header from these, so callers never have to pass the url twice. */ snprintf(c->host, sizeof c->host, "%s", url->host); c->port = url->port; c->tls = url->tls; if (!url->tls) { c->tls = 0; return 0; } c->tls = 1; c->ssl = calloc(1, sizeof *c->ssl); c->conf = calloc(1, sizeof *c->conf); c->ca = calloc(1, sizeof *c->ca); c->ent = calloc(1, sizeof *c->ent); c->drbg = calloc(1, sizeof *c->drbg); if (!c->ssl || !c->conf || !c->ca || !c->ent || !c->drbg) { set_err(err, errsz, "out of memory"); sx_conn_close(c); return -1; } mbedtls_ssl_init(c->ssl); mbedtls_ssl_config_init(c->conf); mbedtls_x509_crt_init(c->ca); mbedtls_entropy_init(c->ent); mbedtls_ctr_drbg_init(c->drbg); if (mbedtls_ctr_drbg_seed(c->drbg, mbedtls_entropy_func, c->ent, NULL, 0) != 0) { set_err(err, errsz, "entropy source unavailable"); sx_conn_close(c); return -1; } if (mbedtls_ssl_config_defaults(c->conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { set_err(err, errsz, "tls config failed"); sx_conn_close(c); return -1; } mbedtls_ssl_conf_rng(c->conf, mbedtls_ctr_drbg_random, c->drbg); /* * VERIFY_OPTIONAL + a hard refusal on every bad-certificate flag below. * Deliberate rather than VERIFY_REQUIRED: with REQUIRED the handshake * aborts before the code can inspect the leaf, which would make an * operator's SPKI pin useless for a self-hosted relay on a private CA. * Verification still fails closed -- the pin is an explicit alternative * anchor, never a bypass of hostname checking. */ mbedtls_ssl_conf_authmode(c->conf, insecure ? MBEDTLS_SSL_VERIFY_NONE : MBEDTLS_SSL_VERIFY_OPTIONAL); if (!insecure) { int r = mbedtls_x509_crt_parse(c->ca, (const unsigned char *)SX_NTFY_CA_BUNDLE_PEM, strlen(SX_NTFY_CA_BUNDLE_PEM) + 1); if (r != 0) { set_err(err, errsz, "bundled trust store unreadable (%d)", r); sx_conn_close(c); return -1; } if (ca_file && *ca_file) { FILE *f = fopen(ca_file, "rb"); char *pem; long sz; size_t rd; if (!f) { set_err(err, errsz, "cannot open ca_file %s", ca_file); sx_conn_close(c); return -1; } fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); if (sz <= 0 || sz > 4 * 1024 * 1024) { fclose(f); set_err(err, errsz, "ca_file %s has a bad size", ca_file); sx_conn_close(c); return -1; } pem = malloc((size_t)sz + 1); if (!pem) { fclose(f); set_err(err, errsz, "out of memory"); sx_conn_close(c); return -1; } rd = fread(pem, 1, (size_t)sz, f); pem[rd] = '\0'; fclose(f); r = mbedtls_x509_crt_parse(c->ca, (const unsigned char *)pem, rd + 1); free(pem); if (r != 0) { set_err(err, errsz, "ca_file %s has no usable certificate (%d)", ca_file, r); sx_conn_close(c); return -1; } } mbedtls_ssl_conf_ca_chain(c->conf, c->ca, NULL); } if (mbedtls_ssl_setup(c->ssl, c->conf) != 0) { set_err(err, errsz, "tls setup failed"); sx_conn_close(c); return -1; } if (mbedtls_ssl_set_hostname(c->ssl, url->host) != 0) { set_err(err, errsz, "tls hostname rejected"); sx_conn_close(c); return -1; } mbedtls_ssl_set_bio(c->ssl, (void *)(intptr_t)c->fd, bio_send, bio_recv, NULL); { long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 10000); int r = 0; int hs_want = 2; /* send the hello first: a fresh socket is writable */ for (;;) { /* mbedTLS is driven by WANT_READ/WANT_WRITE, not by a single * read-set. A handshake step that only has to *write* (the * ClientHello, the Finished) leaves the socket non-readable; if we * waited only on the read set, mbedtls_ssl_handshake() would return * WANT_WRITE and we would then block in select() forever on a * server that correctly says nothing until it has our hello. That * is the bug: the ClientHello never left the process (tcpdump on * the real peer sees SYN, then a FIN 15 s later) and every ntfy * call died as "tls handshake timed out". */ if (mbedtls_ssl_check_pending(c->ssl)) { /* nothing to wait for, mbedtls_ssl_read() has buffered data */ } else if (hs_want == 2) { if (!sx_wait_writable(c->fd, deadline)) { set_err(err, errsz, "tls handshake timed out (write)"); sx_conn_close(c); return -1; } } else if (hs_want == 1) { if (!sx_wait_readable(c->fd, deadline)) { set_err(err, errsz, "tls handshake timed out"); sx_conn_close(c); return -1; } } r = mbedtls_ssl_handshake(c->ssl); if (r == MBEDTLS_ERR_SSL_WANT_WRITE) hs_want = 2; else if (r == MBEDTLS_ERR_SSL_WANT_READ) hs_want = 1; else break; } if (r != 0) { char e[128]; mbedtls_strerror(r, e, sizeof e); set_err(err, errsz, "tls handshake failed: %s", e); sx_conn_close(c); return -1; } } { int flags = insecure ? 0 : (int)mbedtls_ssl_get_verify_result(c->ssl); const mbedtls_x509_crt *leaf = mbedtls_ssl_get_peer_cert(c->ssl); c->peer_fp_sha256[0] = '\0'; if (leaf) { /* SPKI pin = SHA-256 over the DER SubjectPublicKeyInfo. * mbedtls_pk_write_pubkey_der writes the DER from the END of the * buffer backwards and returns its length, so the blob starts at * buf + sizeof(buf) - n. Reading from buf[0] would hash garbage * and every pin would silently never match. */ unsigned char spki[1600]; int n = mbedtls_pk_write_pubkey_der( (mbedtls_pk_context *)&leaf->pk, spki, sizeof spki); if (n > 0 && n <= (int)sizeof spki) sx_sha256_hex(spki + sizeof spki - (size_t)n, (size_t)n, c->peer_fp_sha256); } if (insecure) { c->peer_verified = 0; c->pin_accepted = 0; return 0; } if (flags == 0) { c->peer_verified = 1; return 0; } if (flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) { set_err(err, errsz, "tls certificate is not valid for %s (a pin cannot override a hostname mismatch)", url->host); sx_conn_close(c); return -1; } if (pin_allowed(pins, c->peer_fp_sha256)) { c->peer_verified = 0; c->pin_accepted = 1; return 0; } set_err(err, errsz, "tls certificate rejected (verify flags 0x%x, no matching pin)", flags); sx_conn_close(c); return -1; } } void sx_conn_close(sx_conn *c) { if (!c) return; if (c->ssl) { mbedtls_ssl_free(c->ssl); free(c->ssl); c->ssl = NULL; } if (c->conf) { mbedtls_ssl_config_free(c->conf); free(c->conf); c->conf = NULL; } if (c->ca) { mbedtls_x509_crt_free(c->ca); free(c->ca); c->ca = NULL; } if (c->ent) { mbedtls_entropy_free(c->ent); free(c->ent); c->ent = NULL; } if (c->drbg) { mbedtls_ctr_drbg_free(c->drbg); free(c->drbg); c->drbg = NULL; } if (c->fd != SX_SOCK_INVALID) { sx_closesocket(c->fd); c->fd = SX_SOCK_INVALID; } free(c->body); c->body = NULL; c->body_len = c->body_cap = 0; } /* ------------------------------------------------------------------- raw io */ /* Pull more bytes from the transport into rbuf. * 1 = got bytes, 0 = clean EOF, -1 = timeout or transport error. */ static int sx_fill(sx_conn *c, long long deadline_ms) { if (c->rn > c->rp) return 1; c->rn = 0; c->rp = 0; if (c->eof) return 0; if (!c->tls) { ssize_t n; if (!sx_wait_readable(c->fd, deadline_ms)) return -1; n = recv(c->fd, c->rbuf, sizeof c->rbuf, 0); if (n == 0) { c->eof = 1; return 0; } if (n < 0) { #if defined(_WIN32) return -1; #else if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return -1; return -1; #endif } c->rn = (size_t)n; return 1; } for (;;) { ssize_t n; if (!mbedtls_ssl_check_pending(c->ssl) && !sx_wait_readable(c->fd, deadline_ms)) return -1; n = mbedtls_ssl_read(c->ssl, (unsigned char *)c->rbuf, sizeof c->rbuf); if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) continue; if (n == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY || n == 0) { c->eof = 1; return 0; } if (n < 0) return -1; c->rn = (size_t)n; return 1; } } /* Next body byte. 1 = byte in *out, 0 = end of body, -1 = error/timeout. */ static int sx_body_byte(sx_conn *c, long long deadline_ms, int *out) { for (;;) { int r, ch; if (!c->chunked) { if (c->content_left == 0) return 0; if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } *out = (unsigned char)c->rbuf[c->rp++]; if (c->content_left > 0) c->content_left--; return 1; } switch (c->chunk_state) { case CHUNK_SIZE: { char line[80]; size_t ln = 0; for (;;) { if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } ch = (unsigned char)c->rbuf[c->rp++]; if (ch == '\r') continue; if (ch == '\n') break; if (ln + 1 < sizeof line) line[ln++] = (char)ch; } line[ln] = '\0'; c->content_left = strtoll(line, NULL, 16); if (c->content_left < 0) return -1; if (c->content_left == 0) { c->chunk_state = CHUNK_TRAILER; continue; } c->chunk_state = CHUNK_DATA; continue; } case CHUNK_DATA: { if (c->content_left > 0) { if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } *out = (unsigned char)c->rbuf[c->rp++]; c->content_left--; if (c->content_left == 0) c->chunk_state = CHUNK_DATA_CRLF; return 1; } c->chunk_state = CHUNK_DATA_CRLF; continue; } case CHUNK_DATA_CRLF: { /* expect exactly one CRLF */ if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } ch = (unsigned char)c->rbuf[c->rp++]; if (ch == '\r') { if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } ch = (unsigned char)c->rbuf[c->rp++]; } if (ch != '\n') return -1; c->chunk_state = CHUNK_SIZE; continue; } case CHUNK_TRAILER: { /* read trailer lines until the blank line */ char line[128]; size_t ln = 0; for (;;) { if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } ch = (unsigned char)c->rbuf[c->rp++]; if (ch == '\r') continue; if (ch == '\n') break; if (ln + 1 < sizeof line) line[ln++] = (char)ch; } if (ln == 0) { c->eof = 1; return 0; } continue; /* trailer header line -- skip it */ } default: return 0; } } } /* Reads status line + headers. 0 = ok, -1 = error (err set). */ static int sx_read_headers(sx_conn *c, long long deadline_ms, char *err, size_t errsz) { char head[8192]; size_t n = 0; char *line; c->status = 0; c->status_text[0] = '\0'; c->chunked = 0; c->chunk_state = CHUNK_SIZE; c->content_left = -1; c->headers_done = 0; /* Accumulate until the blank header terminator. Bytes that arrive AFTER * the terminator are body bytes (headers + body frequently share one * packet); they are left in rbuf with rp pointing at the first of them, * so sx_body_byte can still read them. Without that, every small * response (headers + body in one segment, then Connection: close) * returned an empty body: the id of our own publish and the whole * /conversation poll silently vanished. */ for (;;) { int r = sx_fill(c, deadline_ms); size_t i, seg0, seglen, take; char *t; if (r < 0) { set_err(err, errsz, "timed out reading response headers"); return -1; } if (r == 0) { if (n == 0) { set_err(err, errsz, "server closed without a response"); return -1; } break; /* EOF right after headers is acceptable */ } seg0 = c->rp; seglen = c->rn; take = 0; for (i = seg0; i < c->rn && n + 1 < sizeof head; i++) { head[n++] = c->rbuf[i]; take++; } head[n] = '\0'; t = strstr(head, "\r\n\r\n"); if (t) { size_t tend = (size_t)(t - head) + 4; if (tend <= n) { c->rp = seg0 + take - (c->rn - tend > n ? 0 : 0); } /* place rp at absolute offset tend: current segment started at * absolute n-take, so the read cursor is seg0 + (tend-(n-take)) */ c->rp = seg0 + (tend - (n - take)); c->rn = seglen; n = tend; break; } t = strstr(head, "\n\n"); if (t) { size_t tend = (size_t)(t - head) + 2; if (tend <= n) { c->rp = seg0 + (tend - (n - take)); c->rn = seglen; n = tend; } break; } if (n + 1 >= sizeof head) { set_err(err, errsz, "response headers too large"); return -1; } } /* Trim at the terminator so header walking cannot run past it. */ { char *t = strstr(head, "\r\n\r\n"); if (t) *t = '\0'; else { t = strstr(head, "\n\n"); if (t) *t = '\0'; } } if (strncmp(head, "HTTP/1.1 ", 9) != 0 && strncmp(head, "HTTP/1.0 ", 9) != 0) { set_err(err, errsz, "not an HTTP/1.x response"); return -1; } c->status = atoi(head + 9); { char *sp = strchr(head + 9, ' '); char *nl = strchr(head + 9, '\n'); if (sp && (!nl || sp < nl)) { size_t l = strlen(sp + 1); if (nl && nl < sp + 1 + l) l = (size_t)(nl - (sp + 1)); while (l > 0 && (sp[1 + l - 1] == '\r')) l--; if (l >= sizeof c->status_text) l = sizeof c->status_text - 1; memcpy(c->status_text, sp + 1, l); c->status_text[l] = '\0'; } } line = strchr(head, '\n'); if (!line) { set_err(err, errsz, "malformed response"); return -1; } line++; while (line && *line) { char *next = strchr(line, '\n'); if (next) *next = '\0'; { size_t l = strlen(line); while (l > 0 && (line[l - 1] == '\r')) line[--l] = '\0'; } if (strncasecmp(line, "Transfer-Encoding:", 16) == 0 && strstr(line, "chunked")) { c->chunked = 1; c->chunk_state = CHUNK_SIZE; } else if (strncasecmp(line, "Content-Length:", 15) == 0) { long long v = strtoll(line + 15, NULL, 10); if (v < 0) v = 0; if (v > (long long)SX_HTTP_BODY_CAP) v = (long long)SX_HTTP_BODY_CAP; c->content_left = v; } if (!next) break; line = next + 1; } c->headers_done = 1; return 0; } /* ---------------------------------------------------------------- requests */ static int sx_send_all(sx_conn *c, const char *data, size_t len, long long deadline_ms, char *err, size_t errsz) { size_t off = 0; while (off < len) { ssize_t n; if (!c->tls) { /* A non-blocking socket that is ready to SEND is WRITABLE, not * readable: waiting on the read set here never fires, so every * plain-HTTP request timed out after the full deadline with * "timed out sending request". */ if (!sx_wait_writable(c->fd, deadline_ms)) { set_err(err, errsz, "timed out sending request"); return -1; } n = send(c->fd, data + off, len - off, 0); if (n > 0) { off += (size_t)n; continue; } #if defined(_WIN32) { set_err(err, errsz, "connection dropped while sending"); return -1; } #else if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue; set_err(err, errsz, "connection dropped while sending"); return -1; #endif } { int want_read = 0; for (;;) { if (want_read || mbedtls_ssl_check_pending(c->ssl)) { if (!sx_wait_readable(c->fd, deadline_ms)) { set_err(err, errsz, "timed out sending request"); return -1; } } else { if (!sx_wait_writable(c->fd, deadline_ms)) { set_err(err, errsz, "timed out sending request"); return -1; } } n = mbedtls_ssl_write(c->ssl, (const unsigned char *)data + off, len - off); if (n == MBEDTLS_ERR_SSL_WANT_READ) { want_read = 1; continue; } if (n == MBEDTLS_ERR_SSL_WANT_WRITE) { want_read = 0; continue; } break; } } if (n <= 0) { set_err(err, errsz, "tls write failed"); return -1; } off += (size_t)n; } return 0; } /* Builds the request into a freshly malloc'd buffer. Returns it via *req_out * (caller frees) and its length, or -1 when a header was rejected. */ static int build_request(const char *host, int port, int tls, const char *method, const char *path, const char *const *hdrs, const char *body, size_t body_len, int keep_alive, char **req_out, size_t *req_len_out) { static char line[2500]; char *buf; size_t cap = 4096 + body_len + 4096, o = 0; int i; if (strlen(method) > 10 || strlen(path) > 2000) return -1; for (i = 0; path[i]; i++) if ((unsigned char)path[i] < 0x20 || path[i] == '"' || path[i] == '\\') return -1; buf = malloc(cap); if (!buf) return -1; o += (size_t)snprintf(buf + o, cap - o, "%s %s HTTP/1.1\r\n", method, path); if (port != (tls ? 443 : 80)) o += (size_t)snprintf(buf + o, cap - o, "Host: %s:%d\r\n", host, port); else o += (size_t)snprintf(buf + o, cap - o, "Host: %s\r\n", host); o += (size_t)snprintf(buf + o, cap - o, "User-Agent: scorpiox-bot-plugin-ntfy/1.0.0\r\n"); o += (size_t)snprintf(buf + o, cap - o, "Accept: */*\r\n"); o += (size_t)snprintf(buf + o, cap - o, "Accept-Encoding: identity\r\n"); o += (size_t)snprintf(buf + o, cap - o, "Connection: %s\r\n", keep_alive ? "keep-alive" : "close"); (void)line; if (hdrs) { for (i = 0; hdrs[i]; i++) { const char *h = hdrs[i]; size_t l; /* Header injection guard: no control characters in a value, ever. * A value that fails is a programming error, not attacker input * (values are assembled by the caller from validated fields), so * the whole request is refused rather than sanitised. */ for (l = 0; h[l]; l++) if ((unsigned char)h[l] < 0x20 && h[l] != '\t') { free(buf); return -1; } if (strlen(h) > 1200) { free(buf); return -1; } o += (size_t)snprintf(buf + o, cap - o, "%s\r\n", h); if (o + 2 >= cap) { free(buf); return -1; } } } if (body_len > 0 || strcmp(method, "POST") == 0 || strcmp(method, "PUT") == 0) o += (size_t)snprintf(buf + o, cap - o, "Content-Length: %u\r\n", (unsigned)body_len); o += (size_t)snprintf(buf + o, cap - o, "\r\n"); if (o + body_len + 1 > cap) { free(buf); return -1; } if (body && body_len) { memcpy(buf + o, body, body_len); o += body_len; } buf[o] = '\0'; *req_out = buf; *req_len_out = o; return 0; } int sx_http_request(sx_conn *c, const char *method, const char *path, const char *const *hdrs, const char *body, size_t body_len, int *status, char **body_out, size_t *body_out_len, char *err, size_t errsz) { char *req = NULL; size_t reqlen = 0; long long deadline; if (body_out) *body_out = NULL; if (body_out_len) *body_out_len = 0; if (status) *status = 0; if (err && errsz) *err = '\0'; if (build_request(c->host, c->port, c->tls, method, path, hdrs, body, body_len, 0, &req, &reqlen) != 0) { set_err(err, errsz, "request refused (malformed header or path)"); return -1; } deadline = sx_now_ms() + 20000; if (sx_send_all(c, req, reqlen, deadline, err, errsz) != 0) { free(req); return -1; } free(req); if (sx_read_headers(c, deadline, err, errsz) != 0) return -1; if (status) *status = c->status; if (strcmp(method, "HEAD") == 0) return 0; { size_t bcap = 4096, len = 0; char *b = malloc(bcap); if (!b) { set_err(err, errsz, "out of memory"); return -1; } for (;;) { int ch, r = sx_body_byte(c, deadline, &ch); if (r == 0) break; if (r < 0) { free(b); set_err(err, errsz, "error reading response body"); return -1; } if (len + 1 >= bcap) { size_t nc = bcap * 2; char *nb; if (nc > SX_HTTP_BODY_CAP + 1) nc = SX_HTTP_BODY_CAP + 1; nb = realloc(b, nc); if (!nb) { free(b); set_err(err, errsz, "out of memory"); return -1; } b = nb; bcap = nc; if (len >= SX_HTTP_BODY_CAP) break; } b[len++] = (char)ch; if (len >= SX_HTTP_BODY_CAP) break; } b[len] = '\0'; if (body_out) *body_out = b; else free(b); if (body_out_len) *body_out_len = len; } return 0; } int sx_http_open_stream(sx_conn *c, const char *method, const char *path, const char *const *hdrs, int *status, char *err, size_t errsz) { char *req = NULL; size_t reqlen = 0; long long deadline; if (status) *status = 0; if (err && errsz) *err = '\0'; if (build_request(c->host, c->port, c->tls, method, path, hdrs, NULL, 0, 0, &req, &reqlen) != 0) { set_err(err, errsz, "request refused (malformed header or path)"); return -1; } deadline = sx_now_ms() + 20000; if (sx_send_all(c, req, reqlen, deadline, err, errsz) != 0) { free(req); return -1; } free(req); if (sx_read_headers(c, deadline, err, errsz) != 0) return -1; if (status) *status = c->status; return 0; } int sx_http_readline(sx_conn *c, char *line, size_t capsz, long long timeout_ms) { long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 30000); size_t o = 0; if (!capsz) return -1; for (;;) { int ch, r = sx_body_byte(c, deadline, &ch); if (r == 0) { line[o] = '\0'; return o ? 1 : 0; } /* EOF with a partial record: still deliver it */ if (r < 0) return -1; if (ch == '\n') { if (o > 0 && line[o - 1] == '\r') o--; line[o] = '\0'; return 1; } if (o + 1 < capsz && o + 1 < SX_HTTP_LINE_CAP) line[o++] = (char)ch; else if (o + 1 >= SX_HTTP_LINE_CAP) { /* Absurdly long single record: drop the rest of the line and * return what we have rather than growing without bound. */ int cc; while ((r = sx_body_byte(c, deadline, &cc)) == 1 && cc != '\n') ; line[o] = '\0'; return 1; } } }