scorpiox-bot-plugin-websearch
←sx_http_tls.hc
193 lines · 7 KBHEADBlameDownload
1/*
2 * sx_http_tls.h -- the network stack of the SCORPIOX BOT Connector SDK.
3 *
4 * One tiny HTTP/1.1 + WebSocket client over plain TCP or TLS, pure C99,
5 * zero external runtime dependencies on all six dist targets
6 * (linux-x86_64, linux-x86_64-musl, linux-arm64-musl, macos-arm64,
7 * macos-x86_64, windows-x86_64). TLS is vendored BearSSL 0.6 (MIT) on every
8 * platform, so there is no libcurl, no OpenSSL, no WinHTTP import library,
9 * and no system .so/.dll to be missing on a slim container or a stock
10 * Windows laptop.
11 *
12 * Design rules:
13 * 1. Deadlines everywhere. DNS, connect, handshake, every header byte and
14 * every read of a stream that may sit idle for minutes has its own
15 * absolute monotonic deadline (select() on the raw socket).
16 * 2. Chunked bodies are a small state machine, so an infinite NDJSON /
17 * SSE stream is read record-at-a-time and never buffered whole.
18 * Hard caps: 4 MiB body, 1 MiB line, 1 MiB websocket frame.
19 * 3. Verification is on by default against the compiled-in root bundle
20 * (src/ca_roots_pem.h) plus SX_CA_BUNDLE / system bundles as extra
21 * anchors, with hostname verification. There is no "accept anything"
22 * default; the single escape hatch is the environment variable
23 * SX_TLS_INSECURE=1, which is never settable from a config file or an
24 * HTTP request and is meant for debugging a self-hosted relay.
25 * 4. Optional SPKI pinning: sx_http_set_pins() takes hex SHA-256 pins
26 * computed over the SDK's canonical public-key encoding
27 * (key_type || n || e for RSA, key_type || curve || q for EC).
28 * A connection passes when the chain verifies OR the leaf key is
29 * pinned (pinning is an operator override, not a downgrade).
30 *
31 * MIT License. Copyright (c) 2026 SCORPIOX INC.
32 */
33#ifndef SX_HTTP_TLS_H
34#define SX_HTTP_TLS_H
35
36#include <stddef.h>
37#include <stdint.h>
38
39#ifdef __cplusplus
40extern "C" {
41#endif
42
43#if defined(_WIN32)
44# include <winsock2.h>
45 typedef SOCKET sx_sock_t;
46# define SX_SOCK_INVALID INVALID_SOCKET
47#else
48 typedef int sx_sock_t;
49# define SX_SOCK_INVALID (-1)
50#endif
51
52#define SX_HTTP_BODY_CAP (4u * 1024u * 1024u) /* hard cap on a response body */
53#define SX_HTTP_LINE_CAP (1u * 1024u * 1024u) /* cap on one streamed line */
54#define SX_HTTP_RBUF 16384
55#define SX_WS_FRAME_CAP (1u * 1024u * 1024u) /* cap on one websocket frame */
56
57/* ------------------------------------------------------------------ types */
58
59typedef struct {
60 char scheme[8]; /* "http" | "https" */
61 char host[256];
62 int port;
63 char path[1024]; /* keeps the query string; empty becomes "/" */
64 int tls; /* 1 when scheme is https */
65} sx_url;
66
67typedef enum {
68 SX_CHUNK_SIZE = 0,
69 SX_CHUNK_DATA,
70 SX_CHUNK_DATA_CRLF,
71 SX_CHUNK_TRAILER
72} sx_chunk_state;
73
74/* opaque BearSSL contexts live in c->ssl / c->x509 / c->ta (heap) */
75#define SX_SSLIO_SPACE 256
76
77typedef struct sx_conn {
78 sx_sock_t fd;
79 int tls;
80 char host[256];
81 int port;
82
83 /* BearSSL state (only used when tls) */
84 void *ssl; /* br_ssl_client_context* */
85 void *x509; /* br_x509_minimal_context* */
86 void *ta; /* br_x509_trust_anchor[] kept alive for the engine */
87 void *knownkey; /* br_x509_knownkey_context* when pin-trusted */
88 size_t ta_n;
89 unsigned char *iobuf; /* BR_SSL_BUFSIZE_BIDI */
90 char sslio_buf[SX_SSLIO_SPACE]; /* br_sslio_context, aligned */
91 int tls_open; /* handshake done, not yet closed */
92
93 long long deadline_ms; /* absolute monotonic deadline */
94 char peer_fp_sha256[80]; /* hex SPKI pin of the leaf, empty when plain */
95 int chain_verified;
96 int pin_accepted;
97
98 /* response framing */
99 char rbuf[SX_HTTP_RBUF];
100 size_t rp, rn;
101 int framing; /* 0 until-EOF, 1 content-length, 2 chunked */
102 sx_chunk_state chunk_state;
103 size_t content_left;
104 long status;
105 size_t body_total;
106 int eof_seen;
107 int close_after;
108} sx_conn;
109
110/* ------------------------------------------------------------------ utils */
111
112/* Monotonic milliseconds (differences only). */
113long long sx_now_ms(void);
114
115/* SHA-256 of data into a 64-char lowercase hex string + NUL. */
116void sx_sha256_hex(const void *data, size_t len, char out[65]);
117
118/* Percent-encode for URLs (RFC 3986 unreserved pass-through). */
119void sx_url_encode(const char *in, char *out, size_t capsz);
120
121/* Parse http(s)://host[:port][/path][?query]. Refuses userinfo, IPv6
122 * literals and control characters. Returns 0 on success, -1 with err. */
123int sx_url_parse(const char *url, sx_url *out, char *err, size_t errsz);
124
125/* ------------------------------------------------------------------ trust */
126
127/* Register extra PEM anchors (operator ca_file / SX_CA_BUNDLE). May be
128 * called any number of times before sx_conn_open(); copies are kept.
129 * Returns the number of anchors accepted, -1 on parse failure. */
130int sx_http_add_ca_pem(const char *pem, size_t len);
131
132/* Set the SPKI pin allowlist (array of lowercase hex sha256 strings,
133 * SDK canonical key encoding, see file header). */
134void sx_http_set_pins(const char **pins, size_t n);
135
136/* 1 when the environment allows unverified TLS (SX_TLS_INSECURE=1).
137 * Logged loudly at connect. Never settable via config/HTTP. */
138int sx_tls_insecure(void);
139
140/* ------------------------------------------------------------- connection */
141
142/* Open + (for https) handshake. timeout_ms covers DNS/connect/handshake.
143 * Returns 0 on success, -1 with err. */
144int sx_conn_open(sx_conn *c, const sx_url *url, long timeout_ms,
145 char *err, size_t errsz);
146
147/* Send method path HTTP/1.1. extra_headers is a possibly-empty string of
148 * "Key: Value\r\n" lines (already terminated); bearer may be NULL.
149 * Returns 0 when status line + headers parsed, -1 with err. */
150int sx_http_request(sx_conn *c, const char *method, const char *path,
151 const char *extra_headers, const char *bearer,
152 const void *body, size_t blen,
153 long timeout_ms, char *err, size_t errsz);
154
155/* Read one line (up to \n, \r stripped) from the response body stream.
156 * Used for NDJSON/SSE. Returns 1 line read, 0 EOF, -1 error/timeout. */
157int sx_read_line(sx_conn *c, char *out, size_t capsz, long timeout_ms);
158
159/* Read the whole remaining body into a malloc'd buffer (capped).
160 * Returns 1 on success (buf/len set, caller frees), -1 error. */
161int sx_read_all(sx_conn *c, char **buf, size_t *len, long timeout_ms);
162
163/* Close transport, free TLS state. Safe to call twice. */
164void sx_conn_close(sx_conn *c);
165
166/* --------------------------------------------------------------- websocket */
167
168typedef struct sx_ws {
169 sx_conn c; /* the upgraded connection (framing reset to raw) */
170 int closed;
171} sx_ws;
172
173/* GET path with Upgrade: websocket against url, then frame I/O.
174 * sec_websocket_key is generated internally. 0 on the 101, -1 with err. */
175int sx_ws_connect(sx_ws *w, const sx_url *url, const char *extra_headers,
176 long timeout_ms, char *err, size_t errsz);
177
178/* Send a text (opcode 1) or binary (opcode 2) frame, masked per RFC 6455. */
179int sx_ws_send(sx_ws *w, int opcode, const void *payload, size_t len,
180 long timeout_ms, char *err, size_t errsz);
181
182/* Receive one data frame (auto-answers ping, ignores pong, follows close).
183 * Returns 1 payload read (NUL-terminated, *len set), 0 closed, -1 error. */
184int sx_ws_recv(sx_ws *w, void *buf, size_t capsz, size_t *len,
185 long timeout_ms, char *err, size_t errsz);
186
187void sx_ws_close(sx_ws *w);
188
189#ifdef __cplusplus
190}
191#endif
192
193#endif /* SX_HTTP_TLS_H */