/* * sx_http_tls.c -- HTTP/1.1 + WebSocket over TCP/TLS for the SCORPIOX BOT * Connector SDK. See sx_http_tls.h for the contract. * * The plugin owns the socket; vendored BearSSL 0.6 rides on top through the * br_sslio_* API, whose low_read/low_write callbacks are the single place * that enforces absolute monotonic deadlines (select() on the raw socket). * That puts a hard ceiling on every phase: DNS, connect, handshake, every * header byte, and every read of a stream that may sit idle for minutes. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #define _DEFAULT_SOURCE #define _POSIX_C_SOURCE 200809L #define _GNU_SOURCE #include "sx_http_tls.h" #include #include #include #include #include #include #include "bearssl/bearssl_ssl.h" #include "bearssl/bearssl_x509.h" #include "bearssl/bearssl_hash.h" #include "bearssl/bearssl_pem.h" #include "ca_roots_pem.h" #if defined(_WIN32) # include # include # include # include typedef SSIZE_T sx_ssize_t; # define SX_CLOSESOCKET(s) closesocket(s) #else # include # include # include # include # include # include # include # include typedef ssize_t sx_ssize_t; # define SX_CLOSESOCKET(s) close(s) #endif /* Every wait helper refuses an unusable descriptor up front: a negative one * makes glibc's FD_SET trip __fdset_chk ("*** buffer overflow detected ***") * and abort the process. * * The bound is deliberately platform-conditional. On POSIX a descriptor is a * small array index, so FD_SETSIZE is the right ceiling. On Windows a SOCKET * is a kernel handle -- typically a large number -- so the same test is true * for almost every *working* socket, and using it as a guard silently refuses * every connection: select() is never called and connect() reports "timed out" * against a server that answers in three milliseconds. */ #if defined(_WIN32) # define sx_fd_usable(fd) ((fd) != SX_SOCK_INVALID) #else # define sx_fd_usable(fd) ((fd) >= 0 && (fd) < FD_SETSIZE) #endif static int sx_strcasecmp(const char *a, const char *b) { while (*a && *b) { int ca = tolower((unsigned char)*a), cb = tolower((unsigned char)*b); if (ca != cb) return ca - cb; a++; b++; } return (int)(unsigned char)*a - (int)(unsigned char)*b; } /* ------------------------------------------------------------- winsock 2 */ #if defined(_WIN32) static int g_wsa_started = 0; static void sx_wsa_init(void) { if (!g_wsa_started) { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); g_wsa_started = 1; } } #else static void sx_wsa_init(void) {} #endif /* ------------------------------------------------------------ monotonic */ 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"; br_sha256_context hc; int i; br_sha256_init(&hc); br_sha256_update(&hc, data, len); br_sha256_out(&hc, d); 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 if (strncmp(url, "wss://", 6) == 0) { out->tls = 1; p = url + 6; } else if (strncmp(url, "ws://", 5) == 0) { p = url + 5; } else { set_err(err, errsz, "url must start with http(s):// or ws(s)://"); 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; } strcpy(out->scheme, out->tls ? "https" : "http"); /* ws/wss map to http/https */ if (*e == '/' || *e == '?') { size_t o = 0; while (*e && *e != ' ' && *e != '#' && o + 1 < sizeof out->path) out->path[o++] = *e++; out->path[o] = '\0'; } else { strcpy(out->path, "/"); } return 0; } /* ------------------------------------------------------------------ trust */ #define SX_MAX_ANCHORS 640 typedef struct { br_x509_trust_anchor ta; unsigned char *dn; unsigned char *key; unsigned char *key_e; } sx_anchor; static sx_anchor g_anchors[SX_MAX_ANCHORS]; static size_t g_anchor_count = 0; static int g_env_ca_loaded = 0; /* ---- PEM -> DER collector (br_pem_decoder feeds dest callbacks) -------- */ typedef struct { unsigned char *buf; size_t len, cap; } sx_blob; typedef struct { sx_blob cert; sx_blob dn; } sx_sink; static void sx_blob_append(sx_blob *b, const void *src, size_t len) { unsigned char *nb; if (b->len + len > 256 * 1024) return; /* absurd cert: drop */ nb = (unsigned char *)realloc(b->buf, b->len + len + 1); if (!nb) return; memcpy(nb + b->len, src, len); b->len += len; nb[b->len] = 0; b->buf = nb; } static sx_sink g_pem_sink; /* dest ctx must outlive br_pem_decoder_push */ static void sx_dest_cert(void *ctx, const void *src, size_t len) { sx_sink *s = (sx_sink *)ctx; sx_blob_append(&s->cert, src, len); } static void sx_collect_dn(void *ctx, const void *buf, size_t len) { sx_sink *s = (sx_sink *)ctx; sx_blob_append(&s->dn, buf, len); } /* Decode one DER certificate into an owned CA trust anchor. 1 accepted. */ static int sx_anchor_from_der(const unsigned char *der, size_t derlen) { br_x509_decoder_context dc; br_x509_pkey *pk; sx_sink sink; sx_anchor *a; if (g_anchor_count >= SX_MAX_ANCHORS) return 0; memset(&sink, 0, sizeof sink); br_x509_decoder_init(&dc, sx_collect_dn, &sink); br_x509_decoder_push(&dc, der, derlen); if (br_x509_decoder_last_error(&dc) != 0) { free(sink.cert.buf); free(sink.dn.buf); return 0; } pk = br_x509_decoder_get_pkey(&dc); if (!pk || !sink.dn.buf || !sink.dn.len) { free(sink.cert.buf); free(sink.dn.buf); return 0; } a = &g_anchors[g_anchor_count]; memset(a, 0, sizeof *a); a->dn = sink.dn.buf; /* ownership moves into the anchor */ a->ta.dn.data = a->dn; a->ta.dn.len = sink.dn.len; a->ta.flags = BR_X509_TA_CA; if (pk->key_type == BR_KEYTYPE_RSA) { a->key = (unsigned char *)malloc(pk->key.rsa.nlen ? pk->key.rsa.nlen : 1); a->key_e = (unsigned char *)malloc(pk->key.rsa.elen ? pk->key.rsa.elen : 1); if (!a->key || !a->key_e) { free(a->dn); free(a->key); free(a->key_e); memset(a, 0, sizeof *a); return 0; } memcpy(a->key, pk->key.rsa.n, pk->key.rsa.nlen); memcpy(a->key_e, pk->key.rsa.e, pk->key.rsa.elen); a->ta.pkey.key_type = BR_KEYTYPE_RSA; a->ta.pkey.key.rsa.n = a->key; a->ta.pkey.key.rsa.nlen = pk->key.rsa.nlen; a->ta.pkey.key.rsa.e = a->key_e; a->ta.pkey.key.rsa.elen = pk->key.rsa.elen; } else if (pk->key_type == BR_KEYTYPE_EC) { a->key = (unsigned char *)malloc(pk->key.ec.qlen ? pk->key.ec.qlen : 1); if (!a->key) { free(a->dn); memset(a, 0, sizeof *a); return 0; } memcpy(a->key, pk->key.ec.q, pk->key.ec.qlen); a->ta.pkey.key_type = BR_KEYTYPE_EC; a->ta.pkey.key.ec.curve = pk->key.ec.curve; a->ta.pkey.key.ec.q = a->key; a->ta.pkey.key.ec.qlen = pk->key.ec.qlen; } else { free(a->dn); memset(a, 0, sizeof *a); return 0; } g_anchor_count++; return 1; } /* Feed a PEM bundle; every "CERTIFICATE" object found becomes an anchor. */ static int sx_add_pem_mem(const char *pem, size_t len) { br_pem_decoder_context pd; const unsigned char *p = (const unsigned char *)pem; size_t left = len; int accepted = 0; br_pem_decoder_init(&pd); for (;;) { size_t used = br_pem_decoder_push(&pd, p, left); int made = 0; p += used; left -= used; for (;;) { int ev = br_pem_decoder_event(&pd); if (ev == 0) break; made = 1; if (ev == BR_PEM_ERROR) return accepted ? accepted : -1; if (ev == BR_PEM_BEGIN_OBJ) { free(g_pem_sink.cert.buf); g_pem_sink.cert.buf = NULL; g_pem_sink.cert.len = 0; g_pem_sink.cert.cap = 0; g_pem_sink.dn.buf = NULL; g_pem_sink.dn.len = 0; g_pem_sink.dn.cap = 0; br_pem_decoder_setdest(&pd, sx_dest_cert, &g_pem_sink); } else if (ev == BR_PEM_END_OBJ) { unsigned char *buf = g_pem_sink.cert.buf; size_t blen = g_pem_sink.cert.len; g_pem_sink.cert.buf = NULL; g_pem_sink.cert.len = 0; if (buf && blen && blen <= 8192 && sx_anchor_from_der(buf, blen)) accepted++; free(buf); } } if (left == 0 && !made) break; } return accepted > 0 ? accepted : -1; } int sx_http_add_ca_pem(const char *pem, size_t len) { if (!pem || !len) return -1; return sx_add_pem_mem(pem, len); } /* Load anchors once: compiled-in bundle, then SX_CA_BUNDLE or the first * system bundle that exists. Silent on failure -- the compiled bundle * already covers the public web. */ static void sx_load_env_ca(void) { static const char *paths[] = { "/etc/ssl/certs/ca-certificates.crt", /* Debian/Ubuntu/Alpine */ "/etc/pki/tls/certs/ca-bundle.crt", /* RHEL/Fedora */ "/etc/ssl/ca-bundle.pem", /* openSUSE */ "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", /* Fedora */ "/etc/ssl/cert.pem" /* macOS/BSD */ }; size_t i; const char *env; if (g_env_ca_loaded) return; g_env_ca_loaded = 1; sx_add_pem_mem(SX_CA_BUNDLE_PEM, strlen(SX_CA_BUNDLE_PEM)); env = getenv("SX_CA_BUNDLE"); if (env && *env) { FILE *f = fopen(env, "rb"); if (f) { char *buf; long sz; size_t rd; fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); buf = (sz > 0 && sz < 4 * 1024 * 1024) ? (char *)malloc((size_t)sz + 1) : NULL; if (buf) { rd = fread(buf, 1, (size_t)sz, f); buf[rd] = '\0'; sx_add_pem_mem(buf, rd); free(buf); } fclose(f); } return; /* an explicit SX_CA_BUNDLE replaces the system probe */ } for (i = 0; i < sizeof paths / sizeof paths[0]; i++) { FILE *f = fopen(paths[i], "rb"); char *buf; long sz; size_t rd; if (!f) continue; fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); buf = (sz > 0 && sz < 4 * 1024 * 1024) ? (char *)malloc((size_t)sz + 1) : NULL; if (buf) { rd = fread(buf, 1, (size_t)sz, f); buf[rd] = '\0'; sx_add_pem_mem(buf, rd); free(buf); } fclose(f); break; } } /* A non-CA anchor with an impossible key so br_ssl_client_init_full() has * a usable (non-empty) anchor table in SX_TLS_INSECURE debug mode. It can * never match a real server key, and non-CA anchors are direct-trust only, * so this cannot weaken a verification that passed. */ static const unsigned char g_insecure_dn[] = { 0x30, 0x0F, 0x31, 0x0D, 0x30, 0x0B, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x04, 's', 'x', 'd', 'e' }; static int g_insecure_anchor_idx = -1; static void sx_ensure_insecure_anchor(void) { if (g_insecure_anchor_idx >= 0) return; sx_load_env_ca(); if (g_anchor_count >= SX_MAX_ANCHORS) return; { static const unsigned char e3[] = { 0x01, 0x00, 0x01 }; sx_anchor *a = &g_anchors[g_anchor_count]; memset(a, 0, sizeof *a); a->dn = (unsigned char *)malloc(sizeof g_insecure_dn); a->key = (unsigned char *)malloc(3); a->key_e = (unsigned char *)malloc(3); if (!a->dn || !a->key || !a->key_e) { free(a->dn); free(a->key); free(a->key_e); memset(a, 0, sizeof *a); return; } memcpy(a->dn, g_insecure_dn, sizeof g_insecure_dn); a->key[0] = 0xC0; a->key[1] = 0xDE; a->key[2] = 0x01; /* impossible modulus */ memcpy(a->key_e, e3, 3); a->ta.dn.data = a->dn; a->ta.dn.len = sizeof g_insecure_dn; a->ta.flags = 0; /* non-CA: direct trust only */ a->ta.pkey.key_type = BR_KEYTYPE_RSA; a->ta.pkey.key.rsa.n = a->key; a->ta.pkey.key.rsa.nlen = 3; a->ta.pkey.key.rsa.e = a->key_e; a->ta.pkey.key.rsa.elen = 3; g_insecure_anchor_idx = (int)g_anchor_count; g_anchor_count++; } } static const char **g_pins = NULL; static size_t g_pin_count = 0; void sx_http_set_pins(const char **pins, size_t n) { g_pins = pins; g_pin_count = n; } /* Pins may also arrive from the environment (SX_TLS_PIN="hex[,hex...]"). * Used by deployments and the test suite without recompiling the plugin. */ static const char *g_env_pins[8]; static size_t g_env_pin_count = 0; static int g_env_pins_parsed = 0; static void sx_parse_env_pins(void) { const char *v; char buf[8 * 80]; size_t n = 0, start, i; if (g_env_pins_parsed) return; g_env_pins_parsed = 1; v = getenv("SX_TLS_PIN"); if (!v || !*v) return; snprintf(buf, sizeof buf, "%s", v); start = 0; for (i = 0; buf[i] != '\0'; i++) { if (buf[i] == ',' || buf[i] == ' ' || buf[i] == ';') { buf[i] = '\0'; if (i > start && n < sizeof g_env_pins / sizeof g_env_pins[0]) g_env_pins[n++] = strdup(buf + start); start = i + 1; } } if (i > start && n < sizeof g_env_pins / sizeof g_env_pins[0]) g_env_pins[n++] = strdup(buf + start); g_env_pin_count = n; } int sx_tls_insecure(void) { const char *v = getenv("SX_TLS_INSECURE"); return v && strcmp(v, "1") == 0; } /* ---------------------------------------------------------------- sockets */ static int sx_set_nonblocking(sx_sock_t fd, int nb) { #if defined(_WIN32) u_long mode = nb ? 1 : 0; return ioctlsocket(fd, FIONBIO, &mode) == 0 ? 0 : -1; #else int fl = fcntl(fd, F_GETFL, 0); int want = nb ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK); if (fl < 0) return -1; return fcntl(fd, F_SETFL, want) < 0 ? -1 : 0; #endif } static int sx_wait_readable(sx_sock_t fd, long long deadline_ms) { if (!sx_fd_usable(fd)) return 0; /* see sx_fd_usable */ for (;;) { long long left = deadline_ms - sx_now_ms(); struct timeval tv, *ptv = NULL; fd_set rs; int r; if (left <= 0) return 0; if (left > 30000) left = 30000; tv.tv_sec = (long)(left / 1000); tv.tv_usec = (long)((left % 1000) * 1000); ptv = &tv; FD_ZERO(&rs); FD_SET(fd, &rs); #if defined(_WIN32) r = select((int)fd + 1, &rs, NULL, NULL, ptv); if (r > 0) return 1; if (r == 0) return 0; if (WSAGetLastError() == WSAEINTR) continue; #else r = select(fd + 1, &rs, NULL, NULL, ptv); if (r > 0) return 1; if (r == 0) return 0; if (errno == EINTR) continue; #endif return 0; } } static int sx_wait_writable(sx_sock_t fd, long long deadline_ms) { if (!sx_fd_usable(fd)) return 0; /* see sx_fd_usable */ for (;;) { long long left = deadline_ms - sx_now_ms(); struct timeval tv, *ptv = NULL; fd_set ws; int r; if (left <= 0) return 0; if (left > 30000) left = 30000; tv.tv_sec = (long)(left / 1000); tv.tv_usec = (long)((left % 1000) * 1000); ptv = &tv; FD_ZERO(&ws); FD_SET(fd, &ws); #if defined(_WIN32) r = select((int)fd + 1, NULL, &ws, NULL, ptv); if (r > 0) return 1; if (r == 0) return 0; if (WSAGetLastError() == WSAEINTR) continue; #else r = select(fd + 1, NULL, &ws, NULL, ptv); if (r > 0) return 1; if (r == 0) return 0; if (errno == EINTR) continue; #endif return 0; } } /* One budget per DNS candidate; see sx_connect_timeout for why a single * shared deadline makes every dual-stack host with an unreachable IPv6 * route fail. */ #define SX_CONNECT_PER_ATTEMPT_MS 3000 static sx_sock_t sx_connect_timeout(const char *host, int port, long long timeout_ms, char *err, size_t errsz) { struct addrinfo hints, *res = NULL, *ai; char ports[8]; sx_sock_t fd = SX_SOCK_INVALID; long long total_deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 10000); int rc, naddr = 0; /* Budget per address candidate, in milliseconds. * * One absolute deadline shared across every candidate is a bug hiding in * plain sight: a host whose DNS returns AAAA records first (which most * public names do) spends the entire budget on an IPv6 attempt that a * host without an IPv6 route never answers, and by the time the loop * reaches the working IPv4 address the deadline has passed, every later * attempt fails instantly, and the user sees "connect failed" for a * server that is perfectly reachable. Each candidate therefore gets its * own budget, bounded both by what is left and by PER_ATTEMPT_MS, with a * floor so the last candidates are never starved. */ long long left, d, per_attempt; sx_wsa_init(); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf(ports, sizeof ports, "%d", port); rc = getaddrinfo(host, ports, &hints, &res); if (rc != 0 || !res) { set_err(err, errsz, "dns failure for %s", host); return SX_SOCK_INVALID; } for (ai = res; ai; ai = ai->ai_next) naddr++; for (ai = res; ai; ai = ai->ai_next) { int soerr = 0; socklen_t solen = (socklen_t)sizeof soerr; #if defined(_WIN32) int wsa_err = 0; #endif left = total_deadline - sx_now_ms(); if (left < 1500) left = 1500; /* never starve a candidate */ per_attempt = (left < SX_CONNECT_PER_ATTEMPT_MS) ? left : SX_CONNECT_PER_ATTEMPT_MS; d = sx_now_ms() + per_attempt; fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (fd == SX_SOCK_INVALID) continue; sx_set_nonblocking(fd, 1); #if defined(_WIN32) if (connect(fd, ai->ai_addr, (int)ai->ai_addrlen) == SOCKET_ERROR) { wsa_err = WSAGetLastError(); if (wsa_err != WSAEWOULDBLOCK) { if (getenv("SX_VERBOSE")) fprintf(stderr, "sx_http_tls: connect %s:%d family %d " "failed up front (wsa %d), %d candidate(s) " "left\n", host, port, ai->ai_family, wsa_err, naddr); SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; } } #else if (connect(fd, ai->ai_addr, ai->ai_addrlen) != 0) { if (errno != EINPROGRESS) { if (getenv("SX_VERBOSE")) fprintf(stderr, "sx_http_tls: connect %s:%d family %d " "failed up front (errno %d), %d candidate(s) " "left\n", host, port, ai->ai_family, errno, naddr); SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; } } #endif if (!sx_wait_writable(fd, d)) { if (getenv("SX_VERBOSE")) fprintf(stderr, "sx_http_tls: connect %s:%d family %d timed out " "after %lld ms (%d candidate(s) tried)\n", host, port, ai->ai_family, per_attempt, naddr); SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; } if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &solen) != 0 || soerr != 0) { if (getenv("SX_VERBOSE")) fprintf(stderr, "sx_http_tls: connect %s:%d family %d refused " "(so_error %d), %d candidate(s) left\n", host, port, ai->ai_family, soerr, naddr); SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; } break; } freeaddrinfo(res); if (fd == SX_SOCK_INVALID) set_err(err, errsz, "connect to %s:%d failed", host, port); return fd; } static int sx_low_read(void *ctx, unsigned char *data, size_t len) { sx_conn *c = (sx_conn *)ctx; sx_ssize_t n; if (c->fd == SX_SOCK_INVALID) return -1; if (!sx_wait_readable(c->fd, c->deadline_ms)) return -1; n = recv(c->fd, (char *)data, len, 0); return n > 0 ? (int)n : -1; } static int sx_low_write(void *ctx, const unsigned char *data, size_t len) { sx_conn *c = (sx_conn *)ctx; sx_ssize_t n; if (!sx_wait_writable(c->fd, c->deadline_ms)) return -1; #if defined(MSG_NOSIGNAL) n = send(c->fd, (const char *)data, len, MSG_NOSIGNAL); #else n = send(c->fd, (const char *)data, len, 0); #endif return n > 0 ? (int)n : -1; } /* align a char buffer to a pointer-aligned context */ #define SX_SSLIO(c) ((br_sslio_context *)(void *)(c)->sslio_buf) /* SDK-canonical public key encoding: key_type || (n||e | curve||q). */ static size_t sx_key_spki(const br_x509_pkey *pk, unsigned char *spki, size_t capsz) { size_t off = 0; if (!pk) return 0; spki[off++] = (unsigned char)(pk->key_type & 0x0F); if (pk->key_type == BR_KEYTYPE_RSA) { if (pk->key.rsa.nlen + pk->key.rsa.elen + off > capsz) return 0; memcpy(spki + off, pk->key.rsa.n, pk->key.rsa.nlen); off += pk->key.rsa.nlen; memcpy(spki + off, pk->key.rsa.e, pk->key.rsa.elen); off += pk->key.rsa.elen; } else if (pk->key_type == BR_KEYTYPE_EC) { if (pk->key.ec.qlen + 2 + off > capsz) return 0; spki[off++] = (unsigned char)pk->key.ec.curve; memcpy(spki + off, pk->key.ec.q, pk->key.ec.qlen); off += pk->key.ec.qlen; } else return 0; return off; } static int sx_pin_matches_hex(const char *hex) { size_t i; const char **pins = g_pins; size_t n = g_pin_count; if (!hex || !*hex) return 0; if (!pins || !n) { pins = g_env_pins; n = g_env_pin_count; } for (i = 0; i < n; i++) if (pins[i] && sx_strcasecmp(pins[i], hex) == 0) return 1; return 0; } /* ---- SX_TLS_INSECURE lenient engine (debug escape hatch) --------------- * * Wraps br_x509_minimal: certificates are still parsed and the public key * still extracted, but end_chain() never fails, so the handshake completes * over TLS against an unverified chain (curl --insecure semantics). It is * only ever installed when SX_TLS_INSECURE=1 comes from the environment -- * never from a connector config file or an HTTP request -- and every use is * logged. Verification code itself is untouched by this. */ typedef struct { const br_x509_class *vtable; br_x509_minimal_context inner; int last_err; } sx_x509_lenient_context; static void sx_len_start_chain(const br_x509_class **ctx, const char *name) { sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; if (getenv("SX_DEBUG")) fprintf(stderr, "sx_http_tls: [lenient] start_chain\n"); cc->inner.err = 0; cc->inner.vtable->start_chain(&cc->inner.vtable, name); } static void sx_len_start_cert(const br_x509_class **ctx, uint32_t len) { sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; cc->inner.vtable->start_cert(&cc->inner.vtable, len); } static void sx_len_append(const br_x509_class **ctx, const unsigned char *buf, size_t len) { sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; cc->inner.vtable->append(&cc->inner.vtable, buf, len); } static void sx_len_end_cert(const br_x509_class **ctx) { sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; cc->inner.vtable->end_cert(&cc->inner.vtable); } static unsigned sx_len_end_chain(const br_x509_class **ctx) { sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; unsigned r = cc->inner.vtable->end_chain(&cc->inner.vtable); cc->last_err = (int)r; /* Clear an X.509-class error so the inner get_pkey() still yields the * leaf key (xm_get_pkey refuses anything but OK/NOT_TRUSTED) and the * engine continues to CertificateVerify -- whose signature check we do * NOT bypass, so the peer still proves key possession. */ if (r >= BR_ERR_X509_OK && r <= BR_ERR_X509_NOT_TRUSTED) cc->inner.err = BR_ERR_X509_OK; if (getenv("SX_VERBOSE") || getenv("SX_DEBUG")) fprintf(stderr, "sx_http_tls: SX_TLS_INSECURE=1 ignoring certificate " "error (%d) -- debugging only\n", (int)r); return 0; /* lenient: the handshake proceeds */ } static const br_x509_pkey *sx_len_get_pkey(const br_x509_class *const *ctx, unsigned *usages) { sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; return cc->inner.vtable->get_pkey(&cc->inner.vtable, usages); } static const br_x509_class sx_x509_lenient_vtable = { sizeof(sx_x509_lenient_context), sx_len_start_chain, sx_len_start_cert, sx_len_append, sx_len_end_cert, sx_len_end_chain, sx_len_get_pkey }; /* --------------------------------------------------------------- handshake */ static int sx_tls_handshake(sx_conn *c, long timeout_ms, char *err, size_t errsz) { br_ssl_client_context *cc; br_x509_minimal_context *xc; br_x509_trust_anchor *tas; const br_x509_pkey *pk; unsigned usages = 0; size_t i; int insecure = sx_tls_insecure(); c->deadline_ms = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); cc = (br_ssl_client_context *)calloc(1, sizeof *cc); xc = (br_x509_minimal_context *)calloc(1, sizeof *xc); c->iobuf = (unsigned char *)malloc(BR_SSL_BUFSIZE_BIDI); if (!cc || !xc || !c->iobuf) { set_err(err, errsz, "out of memory"); free(cc); free(xc); free(c->iobuf); c->ssl = NULL; c->x509 = NULL; c->iobuf = NULL; return -1; } sx_parse_env_pins(); sx_load_env_ca(); if (insecure) sx_ensure_insecure_anchor(); if (g_anchor_count == 0) { set_err(err, errsz, "no trust anchors available"); free(cc); free(xc); free(c->iobuf); c->ssl = NULL; c->x509 = NULL; c->iobuf = NULL; return -1; } tas = (br_x509_trust_anchor *)calloc(g_anchor_count, sizeof *tas); if (!tas) { set_err(err, errsz, "out of memory"); free(cc); free(xc); free(c->iobuf); c->ssl = NULL; c->x509 = NULL; c->iobuf = NULL; return -1; } for (i = 0; i < g_anchor_count; i++) tas[i] = g_anchors[i].ta; c->ta = tas; c->ta_n = g_anchor_count; /* keep alive: engine links it */ br_ssl_client_init_full(cc, xc, tas, g_anchor_count); if (insecure) { /* debug escape hatch: environment-only, logged, TLS stays on. * The engine is pointed at the lenient wrapper whose embedded * minimal engine is initialised fresh; the original xc simply * goes unused (both live until sx_conn_close). */ sx_x509_lenient_context *ln = (sx_x509_lenient_context *)calloc(1, sizeof *ln); if (!ln) { set_err(err, errsz, "out of memory"); sx_conn_close(c); return -1; } ln->vtable = &sx_x509_lenient_vtable; br_x509_minimal_init_full(&ln->inner, tas, g_anchor_count); br_ssl_engine_set_x509(&cc->eng, (const br_x509_class **)&ln->vtable); c->x509 = ln; /* freed by sx_conn_close as plain memory */ c->ssl = cc; } br_ssl_engine_set_buffer(&cc->eng, c->iobuf, BR_SSL_BUFSIZE_BIDI, 1); if (!br_ssl_client_reset(cc, c->host, 0)) { set_err(err, errsz, "bad SNI hostname"); sx_conn_close(c); return -1; } br_sslio_init(SX_SSLIO(c), &cc->eng, sx_low_read, c, sx_low_write, c); /* Drive the handshake: an empty flush runs the engine to OPEN or fail. */ if (br_sslio_flush(SX_SSLIO(c)) != 0) { int le = br_ssl_engine_last_error(&cc->eng); int cert_err = (le >= BR_ERR_X509_OK && le <= BR_ERR_X509_NOT_TRUSTED); if (insecure && cert_err) { /* SX_TLS_INSECURE=1 (debugging only, environment-set, never * config-set): the wrapper engine returned an X.509 error that * its lenient end_chain swallowed, so the engine closed. That * cannot happen with the wrapper -- if we are here with the * wrapper installed, the failure is NOT a certificate problem * (it is a transport/protocol error). Fall through to the error * path below. */ } /* Pin trust: the chain ended untrusted (self-signed / private CA) but * the operator pinned this exact server key. Reconnect and complete a * full handshake against a known-key X.509 engine: without the * server's private key the finished/sig verify still cannot be * forged, so this is real authentication, not a bypass. */ if (le == BR_ERR_X509_NOT_TRUSTED && (g_pin_count || g_env_pin_count)) { const br_x509_pkey *pk0; unsigned us0 = 0; unsigned char spki[1200]; char hex[65]; pk0 = xc->vtable->get_pkey((const br_x509_class *const *)xc, &us0); if (pk0 && sx_key_spki(pk0, spki, sizeof spki)) { sx_sha256_hex(spki, sx_key_spki(pk0, spki, sizeof spki), hex); if (sx_pin_matches_hex(hex)) { br_x509_pkey saved = *pk0; static unsigned char saved_key[2 * BR_X509_BUFSIZE_KEY + 16]; unsigned char *kp = saved_key; if (saved.key_type == BR_KEYTYPE_RSA) { memcpy(kp, saved.key.rsa.n, saved.key.rsa.nlen); saved.key.rsa.n = kp; kp += saved.key.rsa.nlen; memcpy(kp, saved.key.rsa.e, saved.key.rsa.elen); saved.key.rsa.e = kp; } else { memcpy(kp, saved.key.ec.q, saved.key.ec.qlen); saved.key.ec.q = kp; } /* tear down the failed attempt (through the one * owner, sx_conn_close) and redo with known-key */ sx_conn_close(c); cc = NULL; xc = NULL; c->fd = sx_connect_timeout(c->host, c->port, timeout_ms > 0 ? timeout_ms : 15000, err, errsz); if (c->fd == SX_SOCK_INVALID) return -1; cc = (br_ssl_client_context *)calloc(1, sizeof *cc); xc = (br_x509_minimal_context *)calloc(1, sizeof *xc); c->iobuf = (unsigned char *)malloc(BR_SSL_BUFSIZE_BIDI); { br_x509_knownkey_context *kk = (br_x509_knownkey_context *)calloc(1, sizeof *kk); if (!cc || !xc || !kk || !c->iobuf) { set_err(err, errsz, "out of memory"); free(cc); free(xc); free(kk); free(c->iobuf); c->ssl = c->x509 = NULL; c->iobuf = NULL; return -1; } if (saved.key_type == BR_KEYTYPE_RSA) br_x509_knownkey_init_rsa(kk, &saved.key.rsa, BR_KEYTYPE_SIGN | BR_KEYTYPE_KEYX); else br_x509_knownkey_init_ec(kk, &saved.key.ec, BR_KEYTYPE_SIGN | BR_KEYTYPE_KEYX); br_ssl_client_init_full(cc, xc, tas, g_anchor_count); br_ssl_engine_set_x509(&cc->eng, (const br_x509_class **)&kk->vtable); br_ssl_engine_set_buffer(&cc->eng, c->iobuf, BR_SSL_BUFSIZE_BIDI, 1); if (!br_ssl_client_reset(cc, c->host, 0)) { set_err(err, errsz, "bad SNI hostname"); free(cc); free(xc); free(kk); free(c->iobuf); c->ssl = c->x509 = NULL; c->iobuf = NULL; return -1; } br_sslio_init(SX_SSLIO(c), &cc->eng, sx_low_read, c, sx_low_write, c); if (br_sslio_flush(SX_SSLIO(c)) != 0) { set_err(err, errsz, "pinned TLS handshake failed (code %d)", br_ssl_engine_last_error(&cc->eng)); free(cc); free(xc); free(kk); free(c->iobuf); c->ssl = c->x509 = NULL; c->iobuf = NULL; return -1; } c->ssl = cc; c->x509 = xc; /* kk stays alive via the engine */ c->knownkey = kk; /* freed by sx_conn_close */ c->tls_open = 1; sx_sha256_hex(spki, sx_key_spki(&saved, spki, sizeof spki), c->peer_fp_sha256); c->chain_verified = 0; c->pin_accepted = 1; return 0; } } } } set_err(err, errsz, "TLS handshake failed (code %d%s)", le, insecure ? "" : "; SX_TLS_INSECURE=1 exists for debugging self-hosted relays only"); sx_conn_close(c); return -1; } c->ssl = cc; if (!insecure) c->x509 = xc; c->tls_open = 1; /* leaf public key -> SDK-canonical SPKI pin */ if (insecure) { sx_x509_lenient_context *ln = (sx_x509_lenient_context *)c->x509; pk = ln->inner.vtable->get_pkey((const br_x509_class *const *)&ln->inner, &usages); } else { pk = xc->vtable->get_pkey((const br_x509_class *const *)xc, &usages); } if (pk) { static unsigned char spki[1200]; size_t n = sx_key_spki(pk, spki, sizeof spki); if (n) { sx_sha256_hex(spki, n, c->peer_fp_sha256); if (getenv("SX_VERBOSE")) fprintf(stderr, "sx_http_tls: peer pin %s for %s\n", c->peer_fp_sha256, c->host); } } if (insecure) { sx_x509_lenient_context *ln = (sx_x509_lenient_context *)c->x509; c->chain_verified = (ln->last_err == 0); } else { c->chain_verified = (br_ssl_engine_last_error(&cc->eng) == 0) && ((br_ssl_engine_current_state(&cc->eng) & BR_SSL_CLOSED) == 0); } c->pin_accepted = sx_pin_matches_hex(c->peer_fp_sha256); if (!insecure && !c->chain_verified && !c->pin_accepted) { set_err(err, errsz, "TLS certificate not trusted and no SPKI pin matched"); sx_conn_close(c); return -1; } return 0; } /* ------------------------------------------------------------------ open */ int sx_conn_open(sx_conn *c, const sx_url *url, long timeout_ms, char *err, size_t errsz) { memset(c, 0, sizeof *c); c->fd = SX_SOCK_INVALID; snprintf(c->host, sizeof c->host, "%s", url->host); c->port = url->port; c->tls = url->tls; c->fd = sx_connect_timeout(url->host, url->port, timeout_ms, err, errsz); if (c->fd == SX_SOCK_INVALID) return -1; if (c->tls) { if (sx_tls_handshake(c, timeout_ms, err, errsz) != 0) { if (c->fd != SX_SOCK_INVALID) { SX_CLOSESOCKET(c->fd); c->fd = SX_SOCK_INVALID; } return -1; } } else { c->deadline_ms = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); } return 0; } /* ------------------------------------------------------------ transport */ static int sx_send_all(sx_conn *c, const void *buf, size_t len, long timeout_ms, char *err, size_t errsz) { c->deadline_ms = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); if (c->tls && c->tls_open) { if (len && br_sslio_write_all(SX_SSLIO(c), buf, len) != 0) { set_err(err, errsz, "TLS send failed (code %d)", br_ssl_engine_last_error(&((br_ssl_client_context *)c->ssl)->eng)); return -1; } if (br_sslio_flush(SX_SSLIO(c)) != 0) { set_err(err, errsz, "TLS flush failed (code %d)", br_ssl_engine_last_error(&((br_ssl_client_context *)c->ssl)->eng)); return -1; } return 0; } { const unsigned char *p = (const unsigned char *)buf; while (len > 0) { sx_ssize_t n; if (!sx_wait_writable(c->fd, c->deadline_ms)) { set_err(err, errsz, "send timeout"); return -1; } /* MSG_NOSIGNAL: a server that has already half-closed the * connection (every `Connection: close` reply, and the node API * right after it answers) makes write() raise SIGPIPE. Without * the flag the signal escapes into the connector's own process * and its disposition decides what the caller sees -- usually a * nonsense status taken from errno instead of a clean send * failure. */ #if defined(MSG_NOSIGNAL) n = send(c->fd, (const char *)p, len, MSG_NOSIGNAL); #else n = send(c->fd, (const char *)p, len, 0); #endif if (n <= 0) { if (!sx_wait_writable(c->fd, c->deadline_ms)) { set_err(err, errsz, "send timeout"); return -1; } continue; } p += n; len -= (size_t)n; } } return 0; } /* Refill c->rbuf with fresh bytes from the transport. * 1 = data, 0 = clean EOF, -1 = error/timeout. */ static int sx_fill(sx_conn *c, long long deadline_ms) { if (c->tls && c->tls_open) { br_ssl_client_context *cc = (br_ssl_client_context *)c->ssl; int n; unsigned st; c->deadline_ms = deadline_ms; n = br_sslio_read(SX_SSLIO(c), c->rbuf, sizeof c->rbuf); if (n > 0) { c->rp = 0; c->rn = (size_t)n; return 1; } st = br_ssl_engine_current_state(&cc->eng); if (st & BR_SSL_CLOSED) { int le = br_ssl_engine_last_error(&cc->eng); if (le == 0) return 0; /* orderly close_notify */ return -1; } return -1; } { sx_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->rp = 0; c->rn = (size_t)n; return 1; } if (n == 0) return 0; return -1; } } /* raw byte from transport (headers phase) */ static int sx_next_raw_byte(sx_conn *c, long long deadline_ms, int *out) { for (;;) { if (c->rp < c->rn) { *out = (unsigned char)c->rbuf[c->rp++]; return 1; } { int r = sx_fill(c, deadline_ms); if (r < 0) return -1; if (r == 0) return 0; } } } /* body byte with framing 0 (until-EOF) or 1 (content-length) */ static int sx_raw_body_byte(sx_conn *c, long long deadline_ms, int *out) { if (c->framing == 1 && c->content_left == 0) return 0; for (;;) { if (c->rp < c->rn) { *out = (unsigned char)c->rbuf[c->rp++]; if (c->framing == 1) c->content_left--; c->body_total++; if (c->body_total > SX_HTTP_BODY_CAP) return -1; return 1; } { int r = sx_fill(c, deadline_ms); if (r < 0) return -1; if (r == 0) return 0; if (c->framing == 1 && c->rn > c->content_left) c->rn = c->content_left; } } } /* one decoded body byte with the chunked state machine on top */ static int sx_next_body_byte(sx_conn *c, long long deadline_ms, int *out) { if (c->eof_seen) return 0; if (c->framing != 2) { int r = sx_raw_body_byte(c, deadline_ms, out); if (r == 0) c->eof_seen = 1; return r; } for (;;) { int ch, r; switch (c->chunk_state) { case SX_CHUNK_SIZE: { char line[32]; size_t ln = 0; for (;;) { r = sx_raw_body_byte(c, deadline_ms, &ch); if (r < 0) return -1; if (r == 0) { c->eof_seen = 1; return 0; } if (ch == '\n') break; if (ch == '\r') continue; if (ln + 1 < sizeof line) line[ln++] = (char)ch; else return -1; } line[ln] = '\0'; c->content_left = (size_t)strtoul(line, NULL, 16); if (c->content_left == 0) { c->chunk_state = SX_CHUNK_TRAILER; continue; } if (c->content_left > SX_HTTP_BODY_CAP) return -1; c->chunk_state = SX_CHUNK_DATA; continue; } case SX_CHUNK_DATA: { r = sx_raw_body_byte(c, deadline_ms, out); if (r <= 0) return -1; /* truncated mid-chunk */ c->content_left--; if (c->content_left == 0) c->chunk_state = SX_CHUNK_DATA_CRLF; return 1; } case SX_CHUNK_DATA_CRLF: r = sx_raw_body_byte(c, deadline_ms, &ch); if (r <= 0) return -1; if (ch == '\n') { c->chunk_state = SX_CHUNK_SIZE; continue; } continue; case SX_CHUNK_TRAILER: r = sx_raw_body_byte(c, deadline_ms, &ch); if (r <= 0) { c->eof_seen = 1; return 0; } if (ch == '\n') { c->eof_seen = 1; return 0; } continue; } } } /* --------------------------------------------------------------- headers */ static int hdr_eq(const char *a, const char *b) { return sx_strcasecmp(a, b) == 0; } static int sx_read_response(sx_conn *c, long timeout_ms, char *err, size_t errsz) { char line[8192]; size_t ln; int ch; long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); int first_line = 1; c->status = 0; c->framing = 0; c->content_left = 0; c->eof_seen = 0; c->rp = c->rn = 0; c->body_total = 0; c->close_after = 0; c->chunk_state = SX_CHUNK_SIZE; for (;;) { ln = 0; for (;;) { int r = sx_next_raw_byte(c, deadline, &ch); if (r <= 0) { set_err(err, errsz, "timeout reading response headers"); return -1; } if (ch == '\n') break; if (ch != '\r' && ln + 1 < sizeof line) line[ln++] = (char)ch; } line[ln] = '\0'; if (first_line) { if (strncmp(line, "HTTP/1.1 ", 9) == 0 || strncmp(line, "HTTP/1.0 ", 9) == 0) c->status = atol(line + 9); else { set_err(err, errsz, "bad status line"); return -1; } first_line = 0; continue; } if (ln == 0) break; { char *colon = strchr(line, ':'); char *val; if (!colon) continue; *colon = '\0'; val = colon + 1; while (*val == ' ' || *val == '\t') val++; if (hdr_eq(line, "Content-Length")) { c->content_left = (size_t)strtoul(val, NULL, 10); c->framing = 1; } else if (hdr_eq(line, "Transfer-Encoding")) { if (strstr(val, "chunked") || strstr(val, "Chunked")) c->framing = 2; } else if (hdr_eq(line, "Connection")) { if (strstr(val, "close") || strstr(val, "Close")) c->close_after = 1; } } } if (c->status == 204 || c->status == 304) { c->framing = 1; c->content_left = 0; } return 0; } /* -------------------------------------------------------------- request */ int sx_http_request(sx_conn *c, const char *method, const char *path, const char *extra_headers, const char *bearer, const void *body, size_t blen, long timeout_ms, char *err, size_t errsz) { char req[8192]; int n; size_t off = 0; int default_port = (c->port == (c->tls ? 443 : 80)); n = snprintf(req + off, sizeof req - off, "%s %s HTTP/1.1\r\nHost: %s", method, path, c->host); if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } off += (size_t)n; if (!default_port) { n = snprintf(req + off, sizeof req - off, ":%d", c->port); if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } off += (size_t)n; } n = snprintf(req + off, sizeof req - off, "\r\nUser-Agent: sx-connector-sdk/1.0\r\n" "Accept: */*\r\nConnection: close\r\n"); if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } off += (size_t)n; if (bearer && *bearer) { n = snprintf(req + off, sizeof req - off, "Authorization: Bearer %s\r\n", bearer); if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } off += (size_t)n; } if (extra_headers && *extra_headers) { n = snprintf(req + off, sizeof req - off, "%s", extra_headers); if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } off += (size_t)n; } if (body && blen > 0) { n = snprintf(req + off, sizeof req - off, "Content-Length: %lu\r\n\r\n", (unsigned long)blen); } else { n = snprintf(req + off, sizeof req - off, "\r\n"); } if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } off += (size_t)n; if (sx_send_all(c, req, off, timeout_ms, err, errsz) != 0) return -1; if (body && blen > 0) { if (sx_send_all(c, body, blen, timeout_ms, err, errsz) != 0) return -1; } return sx_read_response(c, timeout_ms, err, errsz); } /* -------------------------------------------------------------- body IO */ int sx_read_line(sx_conn *c, char *out, size_t capsz, long timeout_ms) { size_t n = 0; long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); if (capsz == 0) return -1; for (;;) { int ch; int r = sx_next_body_byte(c, deadline, &ch); if (r < 0) return -1; if (r == 0) { if (n == 0) return 0; /* clean EOF, no partial line */ out[n] = '\0'; return 1; /* final partial line */ } if (ch == '\n') { if (n > 0 && out[n - 1] == '\r') n--; out[n] = '\0'; return 1; } if (n + 1 < capsz && n + 1 < SX_HTTP_LINE_CAP) out[n++] = (char)ch; else { while (ch != '\n') { r = sx_next_body_byte(c, deadline, &ch); if (r <= 0) break; } out[n] = '\0'; return 1; } } } int sx_read_all(sx_conn *c, char **buf, size_t *len, long timeout_ms) { size_t cap = 4096, n = 0; long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); char *b = (char *)malloc(cap); if (!b) return -1; for (;;) { int ch; int r = sx_next_body_byte(c, deadline, &ch); if (r < 0) { free(b); return -1; } if (r == 0) break; if (n + 1 >= cap) { char *nb; cap *= 2; if (cap > SX_HTTP_BODY_CAP) cap = SX_HTTP_BODY_CAP; nb = (char *)realloc(b, cap); if (!nb) { free(b); return -1; } b = nb; } b[n++] = (char)ch; } b[n] = '\0'; *buf = b; if (len) *len = n; return 1; } /* -------------------------------------------------------------- close */ void sx_conn_close(sx_conn *c) { if (c->tls && c->tls_open && c->ssl) { br_ssl_client_context *cc = (br_ssl_client_context *)c->ssl; long long dl; br_ssl_engine_close(&cc->eng); dl = sx_now_ms() + 500; while ((br_ssl_engine_current_state(&cc->eng) & BR_SSL_SENDREC) && sx_now_ms() < dl) { if (br_sslio_flush(SX_SSLIO(c)) != 0) break; } } if (c->fd != SX_SOCK_INVALID) { SX_CLOSESOCKET(c->fd); c->fd = SX_SOCK_INVALID; } free(c->ssl); c->ssl = NULL; free(c->x509); c->x509 = NULL; free(c->knownkey); c->knownkey = NULL; free(c->iobuf); c->iobuf = NULL; free(c->ta); c->ta = NULL; c->ta_n = 0; c->tls_open = 0; } /* ------------------------------------------------------------ websocket */ static void sx_base64(const unsigned char *in, size_t len, char *out) { static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; size_t i, o = 0; for (i = 0; i + 3 <= len; i += 3) { unsigned v = ((unsigned)in[i] << 16) | ((unsigned)in[i + 1] << 8) | in[i + 2]; out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = tbl[(v >> 6) & 63]; out[o++] = tbl[v & 63]; } if (i < len) { unsigned v = (unsigned)in[i] << 16; if (i + 1 < len) v |= (unsigned)in[i + 1] << 8; out[o++] = tbl[(v >> 18) & 63]; out[o++] = tbl[(v >> 12) & 63]; out[o++] = (i + 1 < len) ? tbl[(v >> 6) & 63] : '='; out[o++] = '='; } out[o] = '\0'; } static void sx_rand_bytes(unsigned char *p, size_t n) { static int seeded = 0; size_t i; if (!seeded) { unsigned long long seed = (unsigned long long)sx_now_ms() ^ ((unsigned long long)(size_t)p << 8) ^ (unsigned long long)(size_t)&seeded; #if !defined(_WIN32) seed ^= (unsigned long long)(size_t)getpid(); #endif srand((unsigned)(seed ^ (seed >> 32))); seeded = 1; } for (i = 0; i < n; i++) p[i] = (unsigned char)((rand() >> (i % 7)) & 0xFF); } int sx_ws_connect(sx_ws *w, const sx_url *url, const char *extra_headers, long timeout_ms, char *err, size_t errsz) { unsigned char keyb[16]; char key[25]; char hdrs[4096]; int n; memset(w, 0, sizeof *w); if (sx_conn_open(&w->c, url, timeout_ms, err, errsz) != 0) return -1; sx_rand_bytes(keyb, sizeof keyb); sx_base64(keyb, sizeof keyb, key); n = snprintf(hdrs, sizeof hdrs, "Upgrade: websocket\r\nConnection: Upgrade\r\n" "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: %s\r\n%s%s", key, extra_headers ? extra_headers : "", (extra_headers && *extra_headers) ? "\r\n" : ""); if (n < 0 || (size_t)n >= sizeof hdrs) { set_err(err, errsz, "headers too large"); sx_conn_close(&w->c); return -1; } if (sx_http_request(&w->c, "GET", url->path, hdrs, NULL, NULL, 0, timeout_ms, err, errsz) != 0) { sx_conn_close(&w->c); return -1; } if (w->c.status != 101) { set_err(err, errsz, "websocket handshake returned %ld, expected 101", w->c.status); sx_conn_close(&w->c); return -1; } /* after the upgrade the stream is raw frames, not HTTP body framing */ w->c.framing = 0; w->c.eof_seen = 0; w->closed = 0; return 0; } int sx_ws_send(sx_ws *w, int opcode, const void *payload, size_t len, long timeout_ms, char *err, size_t errsz) { unsigned char hdr[14]; unsigned char mask[4]; size_t hl = 0, i; unsigned char *frame; if (w->closed) { set_err(err, errsz, "websocket closed"); return -1; } hdr[hl++] = (unsigned char)(0x80 | (opcode & 0x0F)); sx_rand_bytes(mask, 4); if (len < 126) { hdr[hl++] = (unsigned char)(0x80 | len); } else if (len < 65536) { hdr[hl++] = (unsigned char)(0x80 | 126); hdr[hl++] = (unsigned char)(len >> 8); hdr[hl++] = (unsigned char)(len & 0xFF); } else { int k; hdr[hl++] = (unsigned char)(0x80 | 127); for (k = 7; k >= 0; k--) hdr[hl++] = (unsigned char)(((unsigned long long)len >> (8 * k)) & 0xFF); } memcpy(hdr + hl, mask, 4); hl += 4; frame = (unsigned char *)malloc(hl + (len ? len : 1)); if (!frame) { set_err(err, errsz, "out of memory"); return -1; } memcpy(frame, hdr, hl); for (i = 0; i < len; i++) frame[hl + i] = ((unsigned char *)payload)[i] ^ mask[i & 3]; if (sx_send_all(&w->c, frame, hl + len, timeout_ms, err, errsz) != 0) { free(frame); return -1; } free(frame); return 0; } static int sx_ws_read_n(sx_ws *w, unsigned char *p, size_t n, long long deadline, char *err, size_t errsz) { size_t got = 0; while (got < n) { int ch; int r = sx_raw_body_byte(&w->c, deadline, &ch); if (r < 0) { set_err(err, errsz, "websocket read error"); return -1; } if (r == 0) { set_err(err, errsz, "websocket closed by peer"); return -1; } p[got++] = (unsigned char)ch; } return 0; } int sx_ws_recv(sx_ws *w, void *buf, size_t capsz, size_t *len, long timeout_ms, char *err, size_t errsz) { long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 60000); if (len) *len = 0; for (;;) { unsigned char h[2], ext[8], mask[4]; unsigned char *acc = NULL; size_t plen, i, got; int fin, opcode; if (w->closed) return 0; if (sx_ws_read_n(w, h, 2, deadline, err, errsz) != 0) return -1; fin = (h[0] & 0x80) != 0; if (h[1] & 0x80) { if (sx_ws_read_n(w, mask, 4, deadline, err, errsz) != 0) return -1; } else { memset(mask, 0, 4); } plen = (size_t)(h[1] & 0x7F); if (plen == 126) { if (sx_ws_read_n(w, ext, 2, deadline, err, errsz) != 0) return -1; plen = ((size_t)ext[0] << 8) | ext[1]; } else if (plen == 127) { unsigned long long v = 0; if (sx_ws_read_n(w, ext, 8, deadline, err, errsz) != 0) return -1; for (i = 0; i < 8; i++) v = (v << 8) | ext[i]; if (v > SX_WS_FRAME_CAP) { set_err(err, errsz, "frame too large"); return -1; } plen = (size_t)v; } if (plen > SX_WS_FRAME_CAP) { set_err(err, errsz, "frame too large"); return -1; } acc = (unsigned char *)malloc(plen ? plen : 1); if (!acc) { set_err(err, errsz, "out of memory"); return -1; } got = 0; while (got < plen) { int ch; int r = sx_raw_body_byte(&w->c, deadline, &ch); if (r <= 0) { free(acc); set_err(err, errsz, "websocket frame truncated"); return -1; } acc[got++] = (unsigned char)ch; } for (i = 0; i < plen; i++) acc[i] ^= mask[i & 3]; opcode = h[0] & 0x0F; if (opcode == 0x8) { /* close */ sx_ws_send(w, 0x8, NULL, 0, 200, NULL, 0); w->closed = 1; free(acc); return 0; } if (opcode == 0x9) { /* ping -> pong */ sx_ws_send(w, 0xA, acc, plen, 200, NULL, 0); free(acc); continue; } if (opcode == 0xA) { free(acc); continue; } /* pong */ if (!fin || opcode == 0x0) { free(acc); continue; } /* fragments dropped */ if (opcode == 0x1 || opcode == 0x2) { size_t ncopy = plen < capsz - 1 ? plen : capsz - 1; memcpy(buf, acc, ncopy); ((char *)buf)[ncopy] = '\0'; if (len) *len = ncopy; free(acc); return 1; } free(acc); /* unknown opcode */ } } void sx_ws_close(sx_ws *w) { if (!w->closed) sx_ws_send(w, 0x8, NULL, 0, 200, NULL, 0); w->closed = 1; sx_conn_close(&w->c); }