scorpiox-bot-plugin-github
←sx_http_tls.hc
203 lines · 8 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_HTTP_HDR_CAP 8192
56#define SX_WS_FRAME_CAP (1u * 1024u * 1024u) /* cap on one websocket frame */
57
58/* ------------------------------------------------------------------ types */
59
60typedef struct {
61 char scheme[8]; /* "http" | "https" */
62 char host[256];
63 int port;
64 char path[1024]; /* keeps the query string; empty becomes "/" */
65 int tls; /* 1 when scheme is https */
66} sx_url;
67
68typedef enum {
69 SX_CHUNK_SIZE = 0,
70 SX_CHUNK_DATA,
71 SX_CHUNK_DATA_CRLF,
72 SX_CHUNK_TRAILER
73} sx_chunk_state;
74
75/* opaque BearSSL contexts live in c->ssl / c->x509 / c->ta (heap) */
76#define SX_SSLIO_SPACE 256
77
78typedef struct sx_conn {
79 sx_sock_t fd;
80 int tls;
81 char host[256];
82 int port;
83
84 /* BearSSL state (only used when tls) */
85 void *ssl; /* br_ssl_client_context* */
86 void *x509; /* br_x509_minimal_context* */
87 void *ta; /* br_x509_trust_anchor[] kept alive for the engine */
88 void *knownkey; /* br_x509_knownkey_context* when pin-trusted */
89 size_t ta_n;
90 unsigned char *iobuf; /* BR_SSL_BUFSIZE_BIDI */
91 char sslio_buf[SX_SSLIO_SPACE]; /* br_sslio_context, aligned */
92 int tls_open; /* handshake done, not yet closed */
93
94 long long deadline_ms; /* absolute monotonic deadline */
95 char peer_fp_sha256[80]; /* hex SPKI pin of the leaf, empty when plain */
96 int chain_verified;
97 int pin_accepted;
98
99 /* response framing */
100 char rbuf[SX_HTTP_RBUF];
101 size_t rp, rn;
102 int framing; /* 0 until-EOF, 1 content-length, 2 chunked */
103 sx_chunk_state chunk_state;
104 size_t content_left;
105 long status;
106 size_t body_total;
107 int eof_seen;
108 int close_after;
109
110 /* every response header line from the last sx_http_request(), joined
111 * "Name: Value\n", bounded at SX_HTTP_HDR_CAP; lets a caller read a
112 * header the framing state machine does not own (e.g. Retry-After) */
113 char last_headers[SX_HTTP_HDR_CAP];
114} sx_conn;
115
116/* ------------------------------------------------------------------ utils */
117
118/* Monotonic milliseconds (differences only). */
119long long sx_now_ms(void);
120
121/* SHA-256 of data into a 64-char lowercase hex string + NUL. */
122void sx_sha256_hex(const void *data, size_t len, char out[65]);
123
124/* Percent-encode for URLs (RFC 3986 unreserved pass-through). */
125void sx_url_encode(const char *in, char *out, size_t capsz);
126
127/* Parse http(s)://host[:port][/path][?query]. Refuses userinfo, IPv6
128 * literals and control characters. Returns 0 on success, -1 with err. */
129int sx_url_parse(const char *url, sx_url *out, char *err, size_t errsz);
130
131/* ------------------------------------------------------------------ trust */
132
133/* Register extra PEM anchors (operator ca_file / SX_CA_BUNDLE). May be
134 * called any number of times before sx_conn_open(); copies are kept.
135 * Returns the number of anchors accepted, -1 on parse failure. */
136int sx_http_add_ca_pem(const char *pem, size_t len);
137
138/* Set the SPKI pin allowlist (array of lowercase hex sha256 strings,
139 * SDK canonical key encoding, see file header). */
140void sx_http_set_pins(const char **pins, size_t n);
141
142/* 1 when the environment allows unverified TLS (SX_TLS_INSECURE=1).
143 * Logged loudly at connect. Never settable via config/HTTP. */
144int sx_tls_insecure(void);
145
146/* ------------------------------------------------------------- connection */
147
148/* Open + (for https) handshake. timeout_ms covers DNS/connect/handshake.
149 * Returns 0 on success, -1 with err. */
150int sx_conn_open(sx_conn *c, const sx_url *url, long timeout_ms,
151 char *err, size_t errsz);
152
153/* Send method path HTTP/1.1. extra_headers is a possibly-empty string of
154 * "Key: Value\r\n" lines (already terminated); bearer may be NULL.
155 * Returns 0 when status line + headers parsed, -1 with err. */
156int sx_http_request(sx_conn *c, const char *method, const char *path,
157 const char *extra_headers, const char *bearer,
158 const void *body, size_t blen,
159 long timeout_ms, char *err, size_t errsz);
160
161/* Read one line (up to \n, \r stripped) from the response body stream.
162 * Used for NDJSON/SSE. Returns 1 line read, 0 EOF, -1 error/timeout. */
163int sx_read_line(sx_conn *c, char *out, size_t capsz, long timeout_ms);
164
165/* Read the whole remaining body into a malloc'd buffer (capped).
166 * Returns 1 on success (buf/len set, caller frees), -1 error. */
167int sx_read_all(sx_conn *c, char **buf, size_t *len, long timeout_ms);
168
169/* Case-insensitive lookup of one header from the last response, into out.
170 * Returns 1 found. */
171int sx_http_header(const sx_conn *c, const char *name, char *out, size_t capsz);
172
173/* Close transport, free TLS state. Safe to call twice. */
174void sx_conn_close(sx_conn *c);
175
176/* --------------------------------------------------------------- websocket */
177
178typedef struct sx_ws {
179 sx_conn c; /* the upgraded connection (framing reset to raw) */
180 int closed;
181} sx_ws;
182
183/* GET path with Upgrade: websocket against url, then frame I/O.
184 * sec_websocket_key is generated internally. 0 on the 101, -1 with err. */
185int sx_ws_connect(sx_ws *w, const sx_url *url, const char *extra_headers,
186 long timeout_ms, char *err, size_t errsz);
187
188/* Send a text (opcode 1) or binary (opcode 2) frame, masked per RFC 6455. */
189int sx_ws_send(sx_ws *w, int opcode, const void *payload, size_t len,
190 long timeout_ms, char *err, size_t errsz);
191
192/* Receive one data frame (auto-answers ping, ignores pong, follows close).
193 * Returns 1 payload read (NUL-terminated, *len set), 0 closed, -1 error. */
194int sx_ws_recv(sx_ws *w, void *buf, size_t capsz, size_t *len,
195 long timeout_ms, char *err, size_t errsz);
196
197void sx_ws_close(sx_ws *w);
198
199#ifdef __cplusplus
200}
201#endif
202
203#endif /* SX_HTTP_TLS_H */