/* * sx_http_tls.h -- the network stack of the SCORPIOX BOT Connector SDK. * * One tiny HTTP/1.1 + WebSocket client over plain TCP or TLS, pure C99, * zero external runtime dependencies on all six dist targets * (linux-x86_64, linux-x86_64-musl, linux-arm64-musl, macos-arm64, * macos-x86_64, windows-x86_64). TLS is vendored BearSSL 0.6 (MIT) on every * platform, so there is no libcurl, no OpenSSL, no WinHTTP import library, * and no system .so/.dll to be missing on a slim container or a stock * Windows laptop. * * Design rules: * 1. Deadlines everywhere. DNS, connect, handshake, every header byte and * every read of a stream that may sit idle for minutes has its own * absolute monotonic deadline (select() on the raw socket). * 2. Chunked bodies are a small state machine, so an infinite NDJSON / * SSE stream is read record-at-a-time and never buffered whole. * Hard caps: 4 MiB body, 1 MiB line, 1 MiB websocket frame. * 3. Verification is on by default against the compiled-in root bundle * (src/ca_roots_pem.h) plus SX_CA_BUNDLE / system bundles as extra * anchors, with hostname verification. There is no "accept anything" * default; the single escape hatch is the environment variable * SX_TLS_INSECURE=1, which is never settable from a config file or an * HTTP request and is meant for debugging a self-hosted relay. * 4. Optional SPKI pinning: sx_http_set_pins() takes hex SHA-256 pins * computed over the SDK's canonical public-key encoding * (key_type || n || e for RSA, key_type || curve || q for EC). * A connection passes when the chain verifies OR the leaf key is * pinned (pinning is an operator override, not a downgrade). * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #ifndef SX_HTTP_TLS_H #define SX_HTTP_TLS_H #include #include #ifdef __cplusplus extern "C" { #endif #if defined(_WIN32) # include typedef SOCKET sx_sock_t; # define SX_SOCK_INVALID INVALID_SOCKET #else typedef int sx_sock_t; # define SX_SOCK_INVALID (-1) #endif #define SX_HTTP_BODY_CAP (4u * 1024u * 1024u) /* hard cap on a response body */ #define SX_HTTP_LINE_CAP (1u * 1024u * 1024u) /* cap on one streamed line */ #define SX_HTTP_RBUF 16384 #define SX_WS_FRAME_CAP (1u * 1024u * 1024u) /* cap on one websocket frame */ /* ------------------------------------------------------------------ types */ typedef struct { char scheme[8]; /* "http" | "https" */ char host[256]; int port; char path[1024]; /* keeps the query string; empty becomes "/" */ int tls; /* 1 when scheme is https */ } sx_url; typedef enum { SX_CHUNK_SIZE = 0, SX_CHUNK_DATA, SX_CHUNK_DATA_CRLF, SX_CHUNK_TRAILER } sx_chunk_state; /* opaque BearSSL contexts live in c->ssl / c->x509 / c->ta (heap) */ #define SX_SSLIO_SPACE 256 typedef struct sx_conn { sx_sock_t fd; int tls; char host[256]; int port; /* BearSSL state (only used when tls) */ void *ssl; /* br_ssl_client_context* */ void *x509; /* br_x509_minimal_context* */ void *ta; /* br_x509_trust_anchor[] kept alive for the engine */ void *knownkey; /* br_x509_knownkey_context* when pin-trusted */ size_t ta_n; unsigned char *iobuf; /* BR_SSL_BUFSIZE_BIDI */ char sslio_buf[SX_SSLIO_SPACE]; /* br_sslio_context, aligned */ int tls_open; /* handshake done, not yet closed */ long long deadline_ms; /* absolute monotonic deadline */ char peer_fp_sha256[80]; /* hex SPKI pin of the leaf, empty when plain */ int chain_verified; int pin_accepted; /* response framing */ char rbuf[SX_HTTP_RBUF]; size_t rp, rn; int framing; /* 0 until-EOF, 1 content-length, 2 chunked */ sx_chunk_state chunk_state; size_t content_left; long status; size_t body_total; int eof_seen; int close_after; } sx_conn; /* ------------------------------------------------------------------ utils */ /* Monotonic milliseconds (differences only). */ long long sx_now_ms(void); /* SHA-256 of data into a 64-char lowercase hex string + NUL. */ void sx_sha256_hex(const void *data, size_t len, char out[65]); /* Percent-encode for URLs (RFC 3986 unreserved pass-through). */ void sx_url_encode(const char *in, char *out, size_t capsz); /* Parse http(s)://host[:port][/path][?query]. Refuses userinfo, IPv6 * literals and control characters. Returns 0 on success, -1 with err. */ int sx_url_parse(const char *url, sx_url *out, char *err, size_t errsz); /* ------------------------------------------------------------------ trust */ /* Register extra PEM anchors (operator ca_file / SX_CA_BUNDLE). May be * called any number of times before sx_conn_open(); copies are kept. * Returns the number of anchors accepted, -1 on parse failure. */ int sx_http_add_ca_pem(const char *pem, size_t len); /* Set the SPKI pin allowlist (array of lowercase hex sha256 strings, * SDK canonical key encoding, see file header). */ void sx_http_set_pins(const char **pins, size_t n); /* 1 when the environment allows unverified TLS (SX_TLS_INSECURE=1). * Logged loudly at connect. Never settable via config/HTTP. */ int sx_tls_insecure(void); /* ------------------------------------------------------------- connection */ /* Open + (for https) handshake. timeout_ms covers DNS/connect/handshake. * Returns 0 on success, -1 with err. */ int sx_conn_open(sx_conn *c, const sx_url *url, long timeout_ms, char *err, size_t errsz); /* Send method path HTTP/1.1. extra_headers is a possibly-empty string of * "Key: Value\r\n" lines (already terminated); bearer may be NULL. * Returns 0 when status line + headers parsed, -1 with err. */ 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); /* Read one line (up to \n, \r stripped) from the response body stream. * Used for NDJSON/SSE. Returns 1 line read, 0 EOF, -1 error/timeout. */ int sx_read_line(sx_conn *c, char *out, size_t capsz, long timeout_ms); /* Read the whole remaining body into a malloc'd buffer (capped). * Returns 1 on success (buf/len set, caller frees), -1 error. */ int sx_read_all(sx_conn *c, char **buf, size_t *len, long timeout_ms); /* Close transport, free TLS state. Safe to call twice. */ void sx_conn_close(sx_conn *c); /* --------------------------------------------------------------- websocket */ typedef struct sx_ws { sx_conn c; /* the upgraded connection (framing reset to raw) */ int closed; } sx_ws; /* GET path with Upgrade: websocket against url, then frame I/O. * sec_websocket_key is generated internally. 0 on the 101, -1 with err. */ int sx_ws_connect(sx_ws *w, const sx_url *url, const char *extra_headers, long timeout_ms, char *err, size_t errsz); /* Send a text (opcode 1) or binary (opcode 2) frame, masked per RFC 6455. */ int sx_ws_send(sx_ws *w, int opcode, const void *payload, size_t len, long timeout_ms, char *err, size_t errsz); /* Receive one data frame (auto-answers ping, ignores pong, follows close). * Returns 1 payload read (NUL-terminated, *len set), 0 closed, -1 error. */ int sx_ws_recv(sx_ws *w, void *buf, size_t capsz, size_t *len, long timeout_ms, char *err, size_t errsz); void sx_ws_close(sx_ws *w); #ifdef __cplusplus } #endif #endif /* SX_HTTP_TLS_H */