| 1 | /* |
| 2 | * sx_http_tls.c -- HTTP/1.1 + WebSocket over TCP/TLS for the SCORPIOX BOT |
| 3 | * Connector SDK. See sx_http_tls.h for the contract. |
| 4 | * |
| 5 | * The plugin owns the socket; vendored BearSSL 0.6 rides on top through the |
| 6 | * br_sslio_* API, whose low_read/low_write callbacks are the single place |
| 7 | * that enforces absolute monotonic deadlines (select() on the raw socket). |
| 8 | * That puts a hard ceiling on every phase: DNS, connect, handshake, every |
| 9 | * header byte, and every read of a stream that may sit idle for minutes. |
| 10 | * |
| 11 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 12 | */ |
| 13 | #define _DEFAULT_SOURCE |
| 14 | #define _POSIX_C_SOURCE 200809L |
| 15 | #define _GNU_SOURCE |
| 16 | |
| 17 | #include "sx_http_tls.h" |
| 18 | |
| 19 | #include <ctype.h> |
| 20 | #include <stdarg.h> |
| 21 | #include <stdio.h> |
| 22 | #include <stdlib.h> |
| 23 | #include <string.h> |
| 24 | #include <time.h> |
| 25 | |
| 26 | #include "bearssl/bearssl_ssl.h" |
| 27 | #include "bearssl/bearssl_x509.h" |
| 28 | #include "bearssl/bearssl_hash.h" |
| 29 | #include "bearssl/bearssl_pem.h" |
| 30 | |
| 31 | #include "ca_roots_pem.h" |
| 32 | |
| 33 | #if defined(_WIN32) |
| 34 | # include <winsock2.h> |
| 35 | # include <ws2tcpip.h> |
| 36 | # include <io.h> |
| 37 | # include <process.h> |
| 38 | typedef SSIZE_T sx_ssize_t; |
| 39 | # define SX_CLOSESOCKET(s) closesocket(s) |
| 40 | #else |
| 41 | # include <netdb.h> |
| 42 | # include <unistd.h> |
| 43 | # include <fcntl.h> |
| 44 | # include <errno.h> |
| 45 | # include <poll.h> |
| 46 | # include <sys/socket.h> |
| 47 | # include <sys/select.h> |
| 48 | # include <sys/time.h> |
| 49 | typedef ssize_t sx_ssize_t; |
| 50 | # define SX_CLOSESOCKET(s) close(s) |
| 51 | #endif |
| 52 | |
| 53 | /* Every wait helper refuses an unusable descriptor up front: a negative one |
| 54 | * makes glibc's FD_SET trip __fdset_chk ("*** buffer overflow detected ***") |
| 55 | * and abort the process. |
| 56 | * |
| 57 | * The bound is deliberately platform-conditional. On POSIX a descriptor is a |
| 58 | * small array index, so FD_SETSIZE is the right ceiling. On Windows a SOCKET |
| 59 | * is a kernel handle -- typically a large number -- so the same test is true |
| 60 | * for almost every *working* socket, and using it as a guard silently refuses |
| 61 | * every connection: select() is never called and connect() reports "timed out" |
| 62 | * against a server that answers in three milliseconds. */ |
| 63 | #if defined(_WIN32) |
| 64 | # define sx_fd_usable(fd) ((fd) != SX_SOCK_INVALID) |
| 65 | #else |
| 66 | # define sx_fd_usable(fd) ((fd) >= 0 && (fd) < FD_SETSIZE) |
| 67 | #endif |
| 68 | |
| 69 | static int sx_strcasecmp(const char *a, const char *b) |
| 70 | { |
| 71 | while (*a && *b) { |
| 72 | int ca = tolower((unsigned char)*a), cb = tolower((unsigned char)*b); |
| 73 | if (ca != cb) return ca - cb; |
| 74 | a++; b++; |
| 75 | } |
| 76 | return (int)(unsigned char)*a - (int)(unsigned char)*b; |
| 77 | } |
| 78 | |
| 79 | /* ------------------------------------------------------------- winsock 2 */ |
| 80 | |
| 81 | #if defined(_WIN32) |
| 82 | static int g_wsa_started = 0; |
| 83 | static void sx_wsa_init(void) |
| 84 | { |
| 85 | if (!g_wsa_started) { |
| 86 | WSADATA wsa; |
| 87 | WSAStartup(MAKEWORD(2, 2), &wsa); |
| 88 | g_wsa_started = 1; |
| 89 | } |
| 90 | } |
| 91 | #else |
| 92 | static void sx_wsa_init(void) {} |
| 93 | #endif |
| 94 | |
| 95 | /* ------------------------------------------------------------ monotonic */ |
| 96 | |
| 97 | long long sx_now_ms(void) |
| 98 | { |
| 99 | #if defined(_WIN32) |
| 100 | FILETIME ft; |
| 101 | ULARGE_INTEGER u; |
| 102 | GetSystemTimeAsFileTime(&ft); |
| 103 | u.LowPart = ft.dwLowDateTime; |
| 104 | u.HighPart = ft.dwHighDateTime; |
| 105 | /* FILETIME is 100ns since 1601; /10000 -> ms. Monotonic enough here: |
| 106 | * every use is a difference between two readings. */ |
| 107 | return (long long)(u.QuadPart / 10000ULL); |
| 108 | #else |
| 109 | struct timespec ts; |
| 110 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 111 | return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); |
| 112 | #endif |
| 113 | } |
| 114 | |
| 115 | static void set_err(char *err, size_t errsz, const char *fmt, ...) |
| 116 | { |
| 117 | va_list ap; |
| 118 | if (!err || !errsz) return; |
| 119 | va_start(ap, fmt); |
| 120 | vsnprintf(err, errsz, fmt, ap); |
| 121 | va_end(ap); |
| 122 | } |
| 123 | |
| 124 | /* ---------------------------------------------------------------- sha256 */ |
| 125 | |
| 126 | void sx_sha256_hex(const void *data, size_t len, char out[65]) |
| 127 | { |
| 128 | unsigned char d[32]; |
| 129 | static const char *hex = "0123456789abcdef"; |
| 130 | br_sha256_context hc; |
| 131 | int i; |
| 132 | br_sha256_init(&hc); |
| 133 | br_sha256_update(&hc, data, len); |
| 134 | br_sha256_out(&hc, d); |
| 135 | for (i = 0; i < 32; i++) { |
| 136 | out[i * 2] = hex[(d[i] >> 4) & 0xF]; |
| 137 | out[i * 2 + 1] = hex[d[i] & 0xF]; |
| 138 | } |
| 139 | out[64] = '\0'; |
| 140 | } |
| 141 | |
| 142 | /* ------------------------------------------------------------ url encode */ |
| 143 | |
| 144 | void sx_url_encode(const char *in, char *out, size_t capsz) |
| 145 | { |
| 146 | static const char *hex = "0123456789ABCDEF"; |
| 147 | size_t o = 0; |
| 148 | const unsigned char *p; |
| 149 | if (!capsz) return; |
| 150 | for (p = (const unsigned char *)in; p && *p; p++) { |
| 151 | unsigned char c = *p; |
| 152 | int safe = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || |
| 153 | (c >= '0' && c <= '9') || c == '.' || c == '_' || |
| 154 | c == '-' || c == '~'; |
| 155 | if (safe) { |
| 156 | if (o + 1 >= capsz) break; |
| 157 | out[o++] = (char)c; |
| 158 | } else { |
| 159 | if (o + 3 >= capsz) break; |
| 160 | out[o++] = '%'; |
| 161 | out[o++] = hex[c >> 4]; |
| 162 | out[o++] = hex[c & 0xF]; |
| 163 | } |
| 164 | } |
| 165 | out[o] = '\0'; |
| 166 | } |
| 167 | |
| 168 | /* ------------------------------------------------------------------- url */ |
| 169 | |
| 170 | int sx_url_parse(const char *url, sx_url *out, char *err, size_t errsz) |
| 171 | { |
| 172 | const char *p, *h, *e; |
| 173 | size_t n; |
| 174 | |
| 175 | memset(out, 0, sizeof *out); |
| 176 | if (!url || !*url) { set_err(err, errsz, "empty url"); return -1; } |
| 177 | |
| 178 | if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; } |
| 179 | else if (strncmp(url, "http://", 7) == 0) { p = url + 7; } |
| 180 | else if (strncmp(url, "wss://", 6) == 0) { out->tls = 1; p = url + 6; } |
| 181 | else if (strncmp(url, "ws://", 5) == 0) { p = url + 5; } |
| 182 | else { set_err(err, errsz, "url must start with http(s):// or ws(s)://"); return -1; } |
| 183 | |
| 184 | if (*p == '[') { set_err(err, errsz, "IPv6 literals are not supported"); return -1; } |
| 185 | |
| 186 | h = p; |
| 187 | e = p; |
| 188 | while (*e && *e != '/' && *e != '?' && *e != '#' && *e != ' ' && |
| 189 | (unsigned char)*e >= 0x20) e++; |
| 190 | n = (size_t)(e - h); |
| 191 | if (n == 0) { set_err(err, errsz, "url has no host"); return -1; } |
| 192 | if (n >= sizeof out->host) { set_err(err, errsz, "host too long"); return -1; } |
| 193 | if (memchr(h, '@', n)) { set_err(err, errsz, "userinfo in url is refused"); return -1; } |
| 194 | |
| 195 | out->port = out->tls ? 443 : 80; |
| 196 | { |
| 197 | const char *colon = memchr(h, ':', n); |
| 198 | if (colon) { |
| 199 | char ports[8]; |
| 200 | size_t pl = (size_t)(e - colon - 1), i; |
| 201 | if (pl == 0 || pl >= sizeof ports) { set_err(err, errsz, "bad port"); return -1; } |
| 202 | for (i = 0; i < pl; i++) |
| 203 | if (!isdigit((unsigned char)colon[1 + i])) { set_err(err, errsz, "bad port"); return -1; } |
| 204 | memcpy(ports, colon + 1, pl); |
| 205 | ports[pl] = '\0'; |
| 206 | out->port = atoi(ports); |
| 207 | if (out->port < 1 || out->port > 65535) { set_err(err, errsz, "port out of range"); return -1; } |
| 208 | n = (size_t)(colon - h); |
| 209 | } |
| 210 | } |
| 211 | memcpy(out->host, h, n); |
| 212 | out->host[n] = '\0'; |
| 213 | if (strspn(out->host, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-") |
| 214 | != strlen(out->host)) { |
| 215 | set_err(err, errsz, "host contains forbidden characters"); |
| 216 | return -1; |
| 217 | } |
| 218 | |
| 219 | strcpy(out->scheme, out->tls ? "https" : "http"); /* ws/wss map to http/https */ |
| 220 | if (*e == '/' || *e == '?') { |
| 221 | size_t o = 0; |
| 222 | while (*e && *e != ' ' && *e != '#' && o + 1 < sizeof out->path) out->path[o++] = *e++; |
| 223 | out->path[o] = '\0'; |
| 224 | } else { |
| 225 | strcpy(out->path, "/"); |
| 226 | } |
| 227 | return 0; |
| 228 | } |
| 229 | |
| 230 | /* ------------------------------------------------------------------ trust */ |
| 231 | |
| 232 | #define SX_MAX_ANCHORS 640 |
| 233 | |
| 234 | typedef struct { |
| 235 | br_x509_trust_anchor ta; |
| 236 | unsigned char *dn; |
| 237 | unsigned char *key; |
| 238 | unsigned char *key_e; |
| 239 | } sx_anchor; |
| 240 | |
| 241 | static sx_anchor g_anchors[SX_MAX_ANCHORS]; |
| 242 | static size_t g_anchor_count = 0; |
| 243 | static int g_env_ca_loaded = 0; |
| 244 | |
| 245 | /* ---- PEM -> DER collector (br_pem_decoder feeds dest callbacks) -------- */ |
| 246 | |
| 247 | typedef struct { unsigned char *buf; size_t len, cap; } sx_blob; |
| 248 | typedef struct { sx_blob cert; sx_blob dn; } sx_sink; |
| 249 | |
| 250 | static void sx_blob_append(sx_blob *b, const void *src, size_t len) |
| 251 | { |
| 252 | unsigned char *nb; |
| 253 | if (b->len + len > 256 * 1024) return; /* absurd cert: drop */ |
| 254 | nb = (unsigned char *)realloc(b->buf, b->len + len + 1); |
| 255 | if (!nb) return; |
| 256 | memcpy(nb + b->len, src, len); |
| 257 | b->len += len; |
| 258 | nb[b->len] = 0; |
| 259 | b->buf = nb; |
| 260 | } |
| 261 | |
| 262 | static sx_sink g_pem_sink; /* dest ctx must outlive br_pem_decoder_push */ |
| 263 | |
| 264 | static void sx_dest_cert(void *ctx, const void *src, size_t len) |
| 265 | { |
| 266 | sx_sink *s = (sx_sink *)ctx; |
| 267 | sx_blob_append(&s->cert, src, len); |
| 268 | } |
| 269 | |
| 270 | static void sx_collect_dn(void *ctx, const void *buf, size_t len) |
| 271 | { |
| 272 | sx_sink *s = (sx_sink *)ctx; |
| 273 | sx_blob_append(&s->dn, buf, len); |
| 274 | } |
| 275 | |
| 276 | /* Decode one DER certificate into an owned CA trust anchor. 1 accepted. */ |
| 277 | static int sx_anchor_from_der(const unsigned char *der, size_t derlen) |
| 278 | { |
| 279 | br_x509_decoder_context dc; |
| 280 | br_x509_pkey *pk; |
| 281 | sx_sink sink; |
| 282 | sx_anchor *a; |
| 283 | |
| 284 | if (g_anchor_count >= SX_MAX_ANCHORS) return 0; |
| 285 | memset(&sink, 0, sizeof sink); |
| 286 | br_x509_decoder_init(&dc, sx_collect_dn, &sink); |
| 287 | br_x509_decoder_push(&dc, der, derlen); |
| 288 | if (br_x509_decoder_last_error(&dc) != 0) { free(sink.cert.buf); free(sink.dn.buf); return 0; } |
| 289 | pk = br_x509_decoder_get_pkey(&dc); |
| 290 | if (!pk || !sink.dn.buf || !sink.dn.len) { free(sink.cert.buf); free(sink.dn.buf); return 0; } |
| 291 | |
| 292 | a = &g_anchors[g_anchor_count]; |
| 293 | memset(a, 0, sizeof *a); |
| 294 | a->dn = sink.dn.buf; /* ownership moves into the anchor */ |
| 295 | a->ta.dn.data = a->dn; |
| 296 | a->ta.dn.len = sink.dn.len; |
| 297 | a->ta.flags = BR_X509_TA_CA; |
| 298 | |
| 299 | if (pk->key_type == BR_KEYTYPE_RSA) { |
| 300 | a->key = (unsigned char *)malloc(pk->key.rsa.nlen ? pk->key.rsa.nlen : 1); |
| 301 | a->key_e = (unsigned char *)malloc(pk->key.rsa.elen ? pk->key.rsa.elen : 1); |
| 302 | if (!a->key || !a->key_e) { |
| 303 | free(a->dn); free(a->key); free(a->key_e); |
| 304 | memset(a, 0, sizeof *a); |
| 305 | return 0; |
| 306 | } |
| 307 | memcpy(a->key, pk->key.rsa.n, pk->key.rsa.nlen); |
| 308 | memcpy(a->key_e, pk->key.rsa.e, pk->key.rsa.elen); |
| 309 | a->ta.pkey.key_type = BR_KEYTYPE_RSA; |
| 310 | a->ta.pkey.key.rsa.n = a->key; a->ta.pkey.key.rsa.nlen = pk->key.rsa.nlen; |
| 311 | a->ta.pkey.key.rsa.e = a->key_e; a->ta.pkey.key.rsa.elen = pk->key.rsa.elen; |
| 312 | } else if (pk->key_type == BR_KEYTYPE_EC) { |
| 313 | a->key = (unsigned char *)malloc(pk->key.ec.qlen ? pk->key.ec.qlen : 1); |
| 314 | if (!a->key) { free(a->dn); memset(a, 0, sizeof *a); return 0; } |
| 315 | memcpy(a->key, pk->key.ec.q, pk->key.ec.qlen); |
| 316 | a->ta.pkey.key_type = BR_KEYTYPE_EC; |
| 317 | a->ta.pkey.key.ec.curve = pk->key.ec.curve; |
| 318 | a->ta.pkey.key.ec.q = a->key; a->ta.pkey.key.ec.qlen = pk->key.ec.qlen; |
| 319 | } else { |
| 320 | free(a->dn); |
| 321 | memset(a, 0, sizeof *a); |
| 322 | return 0; |
| 323 | } |
| 324 | g_anchor_count++; |
| 325 | return 1; |
| 326 | } |
| 327 | |
| 328 | /* Feed a PEM bundle; every "CERTIFICATE" object found becomes an anchor. */ |
| 329 | static int sx_add_pem_mem(const char *pem, size_t len) |
| 330 | { |
| 331 | br_pem_decoder_context pd; |
| 332 | const unsigned char *p = (const unsigned char *)pem; |
| 333 | size_t left = len; |
| 334 | int accepted = 0; |
| 335 | |
| 336 | br_pem_decoder_init(&pd); |
| 337 | for (;;) { |
| 338 | size_t used = br_pem_decoder_push(&pd, p, left); |
| 339 | int made = 0; |
| 340 | p += used; left -= used; |
| 341 | for (;;) { |
| 342 | int ev = br_pem_decoder_event(&pd); |
| 343 | if (ev == 0) break; |
| 344 | made = 1; |
| 345 | if (ev == BR_PEM_ERROR) return accepted ? accepted : -1; |
| 346 | if (ev == BR_PEM_BEGIN_OBJ) { |
| 347 | free(g_pem_sink.cert.buf); |
| 348 | g_pem_sink.cert.buf = NULL; g_pem_sink.cert.len = 0; g_pem_sink.cert.cap = 0; |
| 349 | g_pem_sink.dn.buf = NULL; g_pem_sink.dn.len = 0; g_pem_sink.dn.cap = 0; |
| 350 | br_pem_decoder_setdest(&pd, sx_dest_cert, &g_pem_sink); |
| 351 | } else if (ev == BR_PEM_END_OBJ) { |
| 352 | unsigned char *buf = g_pem_sink.cert.buf; |
| 353 | size_t blen = g_pem_sink.cert.len; |
| 354 | g_pem_sink.cert.buf = NULL; g_pem_sink.cert.len = 0; |
| 355 | if (buf && blen && blen <= 8192 && sx_anchor_from_der(buf, blen)) accepted++; |
| 356 | free(buf); |
| 357 | } |
| 358 | } |
| 359 | if (left == 0 && !made) break; |
| 360 | } |
| 361 | return accepted > 0 ? accepted : -1; |
| 362 | } |
| 363 | |
| 364 | int sx_http_add_ca_pem(const char *pem, size_t len) |
| 365 | { |
| 366 | if (!pem || !len) return -1; |
| 367 | return sx_add_pem_mem(pem, len); |
| 368 | } |
| 369 | |
| 370 | /* Load anchors once: compiled-in bundle, then SX_CA_BUNDLE or the first |
| 371 | * system bundle that exists. Silent on failure -- the compiled bundle |
| 372 | * already covers the public web. */ |
| 373 | static void sx_load_env_ca(void) |
| 374 | { |
| 375 | static const char *paths[] = { |
| 376 | "/etc/ssl/certs/ca-certificates.crt", /* Debian/Ubuntu/Alpine */ |
| 377 | "/etc/pki/tls/certs/ca-bundle.crt", /* RHEL/Fedora */ |
| 378 | "/etc/ssl/ca-bundle.pem", /* openSUSE */ |
| 379 | "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", /* Fedora */ |
| 380 | "/etc/ssl/cert.pem" /* macOS/BSD */ |
| 381 | }; |
| 382 | size_t i; |
| 383 | const char *env; |
| 384 | |
| 385 | if (g_env_ca_loaded) return; |
| 386 | g_env_ca_loaded = 1; |
| 387 | |
| 388 | sx_add_pem_mem(SX_CA_BUNDLE_PEM, strlen(SX_CA_BUNDLE_PEM)); |
| 389 | |
| 390 | env = getenv("SX_CA_BUNDLE"); |
| 391 | if (env && *env) { |
| 392 | FILE *f = fopen(env, "rb"); |
| 393 | if (f) { |
| 394 | char *buf; long sz; size_t rd; |
| 395 | fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); |
| 396 | buf = (sz > 0 && sz < 4 * 1024 * 1024) ? (char *)malloc((size_t)sz + 1) : NULL; |
| 397 | if (buf) { |
| 398 | rd = fread(buf, 1, (size_t)sz, f); |
| 399 | buf[rd] = '\0'; |
| 400 | sx_add_pem_mem(buf, rd); |
| 401 | free(buf); |
| 402 | } |
| 403 | fclose(f); |
| 404 | } |
| 405 | return; /* an explicit SX_CA_BUNDLE replaces the system probe */ |
| 406 | } |
| 407 | for (i = 0; i < sizeof paths / sizeof paths[0]; i++) { |
| 408 | FILE *f = fopen(paths[i], "rb"); |
| 409 | char *buf; long sz; size_t rd; |
| 410 | if (!f) continue; |
| 411 | fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); |
| 412 | buf = (sz > 0 && sz < 4 * 1024 * 1024) ? (char *)malloc((size_t)sz + 1) : NULL; |
| 413 | if (buf) { |
| 414 | rd = fread(buf, 1, (size_t)sz, f); |
| 415 | buf[rd] = '\0'; |
| 416 | sx_add_pem_mem(buf, rd); |
| 417 | free(buf); |
| 418 | } |
| 419 | fclose(f); |
| 420 | break; |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | /* A non-CA anchor with an impossible key so br_ssl_client_init_full() has |
| 425 | * a usable (non-empty) anchor table in SX_TLS_INSECURE debug mode. It can |
| 426 | * never match a real server key, and non-CA anchors are direct-trust only, |
| 427 | * so this cannot weaken a verification that passed. */ |
| 428 | static const unsigned char g_insecure_dn[] = { 0x30, 0x0F, 0x31, 0x0D, 0x30, 0x0B, |
| 429 | 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x04, 's', 'x', 'd', 'e' }; |
| 430 | static int g_insecure_anchor_idx = -1; |
| 431 | |
| 432 | static void sx_ensure_insecure_anchor(void) |
| 433 | { |
| 434 | if (g_insecure_anchor_idx >= 0) return; |
| 435 | sx_load_env_ca(); |
| 436 | if (g_anchor_count >= SX_MAX_ANCHORS) return; |
| 437 | { |
| 438 | static const unsigned char e3[] = { 0x01, 0x00, 0x01 }; |
| 439 | sx_anchor *a = &g_anchors[g_anchor_count]; |
| 440 | memset(a, 0, sizeof *a); |
| 441 | a->dn = (unsigned char *)malloc(sizeof g_insecure_dn); |
| 442 | a->key = (unsigned char *)malloc(3); |
| 443 | a->key_e = (unsigned char *)malloc(3); |
| 444 | if (!a->dn || !a->key || !a->key_e) { free(a->dn); free(a->key); free(a->key_e); memset(a, 0, sizeof *a); return; } |
| 445 | memcpy(a->dn, g_insecure_dn, sizeof g_insecure_dn); |
| 446 | a->key[0] = 0xC0; a->key[1] = 0xDE; a->key[2] = 0x01; /* impossible modulus */ |
| 447 | memcpy(a->key_e, e3, 3); |
| 448 | a->ta.dn.data = a->dn; a->ta.dn.len = sizeof g_insecure_dn; |
| 449 | a->ta.flags = 0; /* non-CA: direct trust only */ |
| 450 | a->ta.pkey.key_type = BR_KEYTYPE_RSA; |
| 451 | a->ta.pkey.key.rsa.n = a->key; a->ta.pkey.key.rsa.nlen = 3; |
| 452 | a->ta.pkey.key.rsa.e = a->key_e; a->ta.pkey.key.rsa.elen = 3; |
| 453 | g_insecure_anchor_idx = (int)g_anchor_count; |
| 454 | g_anchor_count++; |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | static const char **g_pins = NULL; |
| 459 | static size_t g_pin_count = 0; |
| 460 | |
| 461 | void sx_http_set_pins(const char **pins, size_t n) |
| 462 | { |
| 463 | g_pins = pins; |
| 464 | g_pin_count = n; |
| 465 | } |
| 466 | |
| 467 | /* Pins may also arrive from the environment (SX_TLS_PIN="hex[,hex...]"). |
| 468 | * Used by deployments and the test suite without recompiling the plugin. */ |
| 469 | static const char *g_env_pins[8]; |
| 470 | static size_t g_env_pin_count = 0; |
| 471 | static int g_env_pins_parsed = 0; |
| 472 | |
| 473 | static void sx_parse_env_pins(void) |
| 474 | { |
| 475 | const char *v; |
| 476 | char buf[8 * 80]; |
| 477 | size_t n = 0, start, i; |
| 478 | |
| 479 | if (g_env_pins_parsed) return; |
| 480 | g_env_pins_parsed = 1; |
| 481 | v = getenv("SX_TLS_PIN"); |
| 482 | if (!v || !*v) return; |
| 483 | snprintf(buf, sizeof buf, "%s", v); |
| 484 | start = 0; |
| 485 | for (i = 0; buf[i] != '\0'; i++) { |
| 486 | if (buf[i] == ',' || buf[i] == ' ' || buf[i] == ';') { |
| 487 | buf[i] = '\0'; |
| 488 | if (i > start && n < sizeof g_env_pins / sizeof g_env_pins[0]) |
| 489 | g_env_pins[n++] = strdup(buf + start); |
| 490 | start = i + 1; |
| 491 | } |
| 492 | } |
| 493 | if (i > start && n < sizeof g_env_pins / sizeof g_env_pins[0]) |
| 494 | g_env_pins[n++] = strdup(buf + start); |
| 495 | g_env_pin_count = n; |
| 496 | } |
| 497 | |
| 498 | int sx_tls_insecure(void) |
| 499 | { |
| 500 | const char *v = getenv("SX_TLS_INSECURE"); |
| 501 | return v && strcmp(v, "1") == 0; |
| 502 | } |
| 503 | |
| 504 | /* ---------------------------------------------------------------- sockets */ |
| 505 | |
| 506 | static int sx_set_nonblocking(sx_sock_t fd, int nb) |
| 507 | { |
| 508 | #if defined(_WIN32) |
| 509 | u_long mode = nb ? 1 : 0; |
| 510 | return ioctlsocket(fd, FIONBIO, &mode) == 0 ? 0 : -1; |
| 511 | #else |
| 512 | int fl = fcntl(fd, F_GETFL, 0); |
| 513 | int want = nb ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK); |
| 514 | if (fl < 0) return -1; |
| 515 | return fcntl(fd, F_SETFL, want) < 0 ? -1 : 0; |
| 516 | #endif |
| 517 | } |
| 518 | |
| 519 | static int sx_wait_readable(sx_sock_t fd, long long deadline_ms) |
| 520 | { |
| 521 | if (!sx_fd_usable(fd)) return 0; /* see sx_fd_usable */ |
| 522 | for (;;) { |
| 523 | long long left = deadline_ms - sx_now_ms(); |
| 524 | struct timeval tv, *ptv = NULL; |
| 525 | fd_set rs; |
| 526 | int r; |
| 527 | if (left <= 0) return 0; |
| 528 | if (left > 30000) left = 30000; |
| 529 | tv.tv_sec = (long)(left / 1000); |
| 530 | tv.tv_usec = (long)((left % 1000) * 1000); |
| 531 | ptv = &tv; |
| 532 | FD_ZERO(&rs); |
| 533 | FD_SET(fd, &rs); |
| 534 | #if defined(_WIN32) |
| 535 | r = select((int)fd + 1, &rs, NULL, NULL, ptv); |
| 536 | if (r > 0) return 1; |
| 537 | if (r == 0) return 0; |
| 538 | if (WSAGetLastError() == WSAEINTR) continue; |
| 539 | #else |
| 540 | r = select(fd + 1, &rs, NULL, NULL, ptv); |
| 541 | if (r > 0) return 1; |
| 542 | if (r == 0) return 0; |
| 543 | if (errno == EINTR) continue; |
| 544 | #endif |
| 545 | return 0; |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | static int sx_wait_writable(sx_sock_t fd, long long deadline_ms) |
| 550 | { |
| 551 | if (!sx_fd_usable(fd)) return 0; /* see sx_fd_usable */ |
| 552 | for (;;) { |
| 553 | long long left = deadline_ms - sx_now_ms(); |
| 554 | struct timeval tv, *ptv = NULL; |
| 555 | fd_set ws; |
| 556 | int r; |
| 557 | if (left <= 0) return 0; |
| 558 | if (left > 30000) left = 30000; |
| 559 | tv.tv_sec = (long)(left / 1000); |
| 560 | tv.tv_usec = (long)((left % 1000) * 1000); |
| 561 | ptv = &tv; |
| 562 | FD_ZERO(&ws); |
| 563 | FD_SET(fd, &ws); |
| 564 | #if defined(_WIN32) |
| 565 | r = select((int)fd + 1, NULL, &ws, NULL, ptv); |
| 566 | if (r > 0) return 1; |
| 567 | if (r == 0) return 0; |
| 568 | if (WSAGetLastError() == WSAEINTR) continue; |
| 569 | #else |
| 570 | r = select(fd + 1, NULL, &ws, NULL, ptv); |
| 571 | if (r > 0) return 1; |
| 572 | if (r == 0) return 0; |
| 573 | if (errno == EINTR) continue; |
| 574 | #endif |
| 575 | return 0; |
| 576 | } |
| 577 | } |
| 578 | /* One budget per DNS candidate; see sx_connect_timeout for why a single |
| 579 | * shared deadline makes every dual-stack host with an unreachable IPv6 |
| 580 | * route fail. */ |
| 581 | #define SX_CONNECT_PER_ATTEMPT_MS 3000 |
| 582 | |
| 583 | |
| 584 | static sx_sock_t sx_connect_timeout(const char *host, int port, |
| 585 | long long timeout_ms, char *err, size_t errsz) |
| 586 | { |
| 587 | struct addrinfo hints, *res = NULL, *ai; |
| 588 | char ports[8]; |
| 589 | sx_sock_t fd = SX_SOCK_INVALID; |
| 590 | long long total_deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 10000); |
| 591 | int rc, naddr = 0; |
| 592 | |
| 593 | /* Budget per address candidate, in milliseconds. |
| 594 | * |
| 595 | * One absolute deadline shared across every candidate is a bug hiding in |
| 596 | * plain sight: a host whose DNS returns AAAA records first (which most |
| 597 | * public names do) spends the entire budget on an IPv6 attempt that a |
| 598 | * host without an IPv6 route never answers, and by the time the loop |
| 599 | * reaches the working IPv4 address the deadline has passed, every later |
| 600 | * attempt fails instantly, and the user sees "connect failed" for a |
| 601 | * server that is perfectly reachable. Each candidate therefore gets its |
| 602 | * own budget, bounded both by what is left and by PER_ATTEMPT_MS, with a |
| 603 | * floor so the last candidates are never starved. */ |
| 604 | long long left, d, per_attempt; |
| 605 | |
| 606 | sx_wsa_init(); |
| 607 | memset(&hints, 0, sizeof hints); |
| 608 | hints.ai_family = AF_UNSPEC; |
| 609 | hints.ai_socktype = SOCK_STREAM; |
| 610 | snprintf(ports, sizeof ports, "%d", port); |
| 611 | rc = getaddrinfo(host, ports, &hints, &res); |
| 612 | if (rc != 0 || !res) { |
| 613 | set_err(err, errsz, "dns failure for %s", host); |
| 614 | return SX_SOCK_INVALID; |
| 615 | } |
| 616 | for (ai = res; ai; ai = ai->ai_next) naddr++; |
| 617 | |
| 618 | for (ai = res; ai; ai = ai->ai_next) { |
| 619 | int soerr = 0; |
| 620 | socklen_t solen = (socklen_t)sizeof soerr; |
| 621 | #if defined(_WIN32) |
| 622 | int wsa_err = 0; |
| 623 | #endif |
| 624 | |
| 625 | left = total_deadline - sx_now_ms(); |
| 626 | if (left < 1500) left = 1500; /* never starve a candidate */ |
| 627 | per_attempt = (left < SX_CONNECT_PER_ATTEMPT_MS) |
| 628 | ? left : SX_CONNECT_PER_ATTEMPT_MS; |
| 629 | d = sx_now_ms() + per_attempt; |
| 630 | |
| 631 | fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); |
| 632 | if (fd == SX_SOCK_INVALID) continue; |
| 633 | sx_set_nonblocking(fd, 1); |
| 634 | #if defined(_WIN32) |
| 635 | if (connect(fd, ai->ai_addr, (int)ai->ai_addrlen) == SOCKET_ERROR) { |
| 636 | wsa_err = WSAGetLastError(); |
| 637 | if (wsa_err != WSAEWOULDBLOCK) { |
| 638 | if (getenv("SX_VERBOSE")) |
| 639 | fprintf(stderr, "sx_http_tls: connect %s:%d family %d " |
| 640 | "failed up front (wsa %d), %d candidate(s) " |
| 641 | "left\n", host, port, ai->ai_family, |
| 642 | wsa_err, naddr); |
| 643 | SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; |
| 644 | } |
| 645 | } |
| 646 | #else |
| 647 | if (connect(fd, ai->ai_addr, ai->ai_addrlen) != 0) { |
| 648 | if (errno != EINPROGRESS) { |
| 649 | if (getenv("SX_VERBOSE")) |
| 650 | fprintf(stderr, "sx_http_tls: connect %s:%d family %d " |
| 651 | "failed up front (errno %d), %d candidate(s) " |
| 652 | "left\n", host, port, ai->ai_family, |
| 653 | errno, naddr); |
| 654 | SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; |
| 655 | } |
| 656 | } |
| 657 | #endif |
| 658 | if (!sx_wait_writable(fd, d)) { |
| 659 | if (getenv("SX_VERBOSE")) |
| 660 | fprintf(stderr, "sx_http_tls: connect %s:%d family %d timed out " |
| 661 | "after %lld ms (%d candidate(s) tried)\n", |
| 662 | host, port, ai->ai_family, per_attempt, naddr); |
| 663 | SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; |
| 664 | } |
| 665 | if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &solen) != 0 || soerr != 0) { |
| 666 | if (getenv("SX_VERBOSE")) |
| 667 | fprintf(stderr, "sx_http_tls: connect %s:%d family %d refused " |
| 668 | "(so_error %d), %d candidate(s) left\n", |
| 669 | host, port, ai->ai_family, soerr, naddr); |
| 670 | SX_CLOSESOCKET(fd); fd = SX_SOCK_INVALID; continue; |
| 671 | } |
| 672 | break; |
| 673 | } |
| 674 | freeaddrinfo(res); |
| 675 | if (fd == SX_SOCK_INVALID) set_err(err, errsz, "connect to %s:%d failed", host, port); |
| 676 | return fd; |
| 677 | } |
| 678 | |
| 679 | static int sx_low_read(void *ctx, unsigned char *data, size_t len) |
| 680 | { |
| 681 | sx_conn *c = (sx_conn *)ctx; |
| 682 | sx_ssize_t n; |
| 683 | if (c->fd == SX_SOCK_INVALID) return -1; |
| 684 | if (!sx_wait_readable(c->fd, c->deadline_ms)) return -1; |
| 685 | n = recv(c->fd, (char *)data, len, 0); |
| 686 | return n > 0 ? (int)n : -1; |
| 687 | } |
| 688 | |
| 689 | static int sx_low_write(void *ctx, const unsigned char *data, size_t len) |
| 690 | { |
| 691 | sx_conn *c = (sx_conn *)ctx; |
| 692 | sx_ssize_t n; |
| 693 | if (!sx_wait_writable(c->fd, c->deadline_ms)) return -1; |
| 694 | #if defined(MSG_NOSIGNAL) |
| 695 | n = send(c->fd, (const char *)data, len, MSG_NOSIGNAL); |
| 696 | #else |
| 697 | n = send(c->fd, (const char *)data, len, 0); |
| 698 | #endif |
| 699 | return n > 0 ? (int)n : -1; |
| 700 | } |
| 701 | |
| 702 | /* align a char buffer to a pointer-aligned context */ |
| 703 | #define SX_SSLIO(c) ((br_sslio_context *)(void *)(c)->sslio_buf) |
| 704 | |
| 705 | /* SDK-canonical public key encoding: key_type || (n||e | curve||q). */ |
| 706 | static size_t sx_key_spki(const br_x509_pkey *pk, unsigned char *spki, size_t capsz) |
| 707 | { |
| 708 | size_t off = 0; |
| 709 | if (!pk) return 0; |
| 710 | spki[off++] = (unsigned char)(pk->key_type & 0x0F); |
| 711 | if (pk->key_type == BR_KEYTYPE_RSA) { |
| 712 | if (pk->key.rsa.nlen + pk->key.rsa.elen + off > capsz) return 0; |
| 713 | memcpy(spki + off, pk->key.rsa.n, pk->key.rsa.nlen); off += pk->key.rsa.nlen; |
| 714 | memcpy(spki + off, pk->key.rsa.e, pk->key.rsa.elen); off += pk->key.rsa.elen; |
| 715 | } else if (pk->key_type == BR_KEYTYPE_EC) { |
| 716 | if (pk->key.ec.qlen + 2 + off > capsz) return 0; |
| 717 | spki[off++] = (unsigned char)pk->key.ec.curve; |
| 718 | memcpy(spki + off, pk->key.ec.q, pk->key.ec.qlen); off += pk->key.ec.qlen; |
| 719 | } else return 0; |
| 720 | return off; |
| 721 | } |
| 722 | |
| 723 | static int sx_pin_matches_hex(const char *hex) |
| 724 | { |
| 725 | size_t i; |
| 726 | const char **pins = g_pins; |
| 727 | size_t n = g_pin_count; |
| 728 | if (!hex || !*hex) return 0; |
| 729 | if (!pins || !n) { pins = g_env_pins; n = g_env_pin_count; } |
| 730 | for (i = 0; i < n; i++) |
| 731 | if (pins[i] && sx_strcasecmp(pins[i], hex) == 0) return 1; |
| 732 | return 0; |
| 733 | } |
| 734 | |
| 735 | /* ---- SX_TLS_INSECURE lenient engine (debug escape hatch) --------------- |
| 736 | * |
| 737 | * Wraps br_x509_minimal: certificates are still parsed and the public key |
| 738 | * still extracted, but end_chain() never fails, so the handshake completes |
| 739 | * over TLS against an unverified chain (curl --insecure semantics). It is |
| 740 | * only ever installed when SX_TLS_INSECURE=1 comes from the environment -- |
| 741 | * never from a connector config file or an HTTP request -- and every use is |
| 742 | * logged. Verification code itself is untouched by this. |
| 743 | */ |
| 744 | |
| 745 | typedef struct { |
| 746 | const br_x509_class *vtable; |
| 747 | br_x509_minimal_context inner; |
| 748 | int last_err; |
| 749 | } sx_x509_lenient_context; |
| 750 | |
| 751 | static void sx_len_start_chain(const br_x509_class **ctx, const char *name) |
| 752 | { |
| 753 | sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; |
| 754 | if (getenv("SX_DEBUG")) fprintf(stderr, "sx_http_tls: [lenient] start_chain\n"); |
| 755 | cc->inner.err = 0; |
| 756 | cc->inner.vtable->start_chain(&cc->inner.vtable, name); |
| 757 | } |
| 758 | |
| 759 | static void sx_len_start_cert(const br_x509_class **ctx, uint32_t len) |
| 760 | { |
| 761 | sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; |
| 762 | cc->inner.vtable->start_cert(&cc->inner.vtable, len); |
| 763 | } |
| 764 | |
| 765 | static void sx_len_append(const br_x509_class **ctx, |
| 766 | const unsigned char *buf, size_t len) |
| 767 | { |
| 768 | sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; |
| 769 | cc->inner.vtable->append(&cc->inner.vtable, buf, len); |
| 770 | } |
| 771 | |
| 772 | static void sx_len_end_cert(const br_x509_class **ctx) |
| 773 | { |
| 774 | sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; |
| 775 | cc->inner.vtable->end_cert(&cc->inner.vtable); |
| 776 | } |
| 777 | |
| 778 | static unsigned sx_len_end_chain(const br_x509_class **ctx) |
| 779 | { |
| 780 | sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; |
| 781 | unsigned r = cc->inner.vtable->end_chain(&cc->inner.vtable); |
| 782 | cc->last_err = (int)r; |
| 783 | /* Clear an X.509-class error so the inner get_pkey() still yields the |
| 784 | * leaf key (xm_get_pkey refuses anything but OK/NOT_TRUSTED) and the |
| 785 | * engine continues to CertificateVerify -- whose signature check we do |
| 786 | * NOT bypass, so the peer still proves key possession. */ |
| 787 | if (r >= BR_ERR_X509_OK && r <= BR_ERR_X509_NOT_TRUSTED) |
| 788 | cc->inner.err = BR_ERR_X509_OK; |
| 789 | if (getenv("SX_VERBOSE") || getenv("SX_DEBUG")) |
| 790 | fprintf(stderr, "sx_http_tls: SX_TLS_INSECURE=1 ignoring certificate " |
| 791 | "error (%d) -- debugging only\n", (int)r); |
| 792 | return 0; /* lenient: the handshake proceeds */ |
| 793 | } |
| 794 | |
| 795 | static const br_x509_pkey *sx_len_get_pkey(const br_x509_class *const *ctx, |
| 796 | unsigned *usages) |
| 797 | { |
| 798 | sx_x509_lenient_context *cc = (sx_x509_lenient_context *)ctx; |
| 799 | return cc->inner.vtable->get_pkey(&cc->inner.vtable, usages); |
| 800 | } |
| 801 | |
| 802 | static const br_x509_class sx_x509_lenient_vtable = { |
| 803 | sizeof(sx_x509_lenient_context), |
| 804 | sx_len_start_chain, |
| 805 | sx_len_start_cert, |
| 806 | sx_len_append, |
| 807 | sx_len_end_cert, |
| 808 | sx_len_end_chain, |
| 809 | sx_len_get_pkey |
| 810 | }; |
| 811 | |
| 812 | /* --------------------------------------------------------------- handshake */ |
| 813 | |
| 814 | static int sx_tls_handshake(sx_conn *c, long timeout_ms, char *err, size_t errsz) |
| 815 | { |
| 816 | br_ssl_client_context *cc; |
| 817 | br_x509_minimal_context *xc; |
| 818 | br_x509_trust_anchor *tas; |
| 819 | const br_x509_pkey *pk; |
| 820 | unsigned usages = 0; |
| 821 | size_t i; |
| 822 | int insecure = sx_tls_insecure(); |
| 823 | |
| 824 | c->deadline_ms = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); |
| 825 | |
| 826 | cc = (br_ssl_client_context *)calloc(1, sizeof *cc); |
| 827 | xc = (br_x509_minimal_context *)calloc(1, sizeof *xc); |
| 828 | c->iobuf = (unsigned char *)malloc(BR_SSL_BUFSIZE_BIDI); |
| 829 | if (!cc || !xc || !c->iobuf) { |
| 830 | set_err(err, errsz, "out of memory"); |
| 831 | free(cc); free(xc); free(c->iobuf); |
| 832 | c->ssl = NULL; c->x509 = NULL; c->iobuf = NULL; |
| 833 | return -1; |
| 834 | } |
| 835 | |
| 836 | sx_parse_env_pins(); |
| 837 | sx_load_env_ca(); |
| 838 | if (insecure) sx_ensure_insecure_anchor(); |
| 839 | if (g_anchor_count == 0) { |
| 840 | set_err(err, errsz, "no trust anchors available"); |
| 841 | free(cc); free(xc); free(c->iobuf); |
| 842 | c->ssl = NULL; c->x509 = NULL; c->iobuf = NULL; |
| 843 | return -1; |
| 844 | } |
| 845 | |
| 846 | tas = (br_x509_trust_anchor *)calloc(g_anchor_count, sizeof *tas); |
| 847 | if (!tas) { |
| 848 | set_err(err, errsz, "out of memory"); |
| 849 | free(cc); free(xc); free(c->iobuf); |
| 850 | c->ssl = NULL; c->x509 = NULL; c->iobuf = NULL; |
| 851 | return -1; |
| 852 | } |
| 853 | for (i = 0; i < g_anchor_count; i++) tas[i] = g_anchors[i].ta; |
| 854 | c->ta = tas; c->ta_n = g_anchor_count; /* keep alive: engine links it */ |
| 855 | |
| 856 | br_ssl_client_init_full(cc, xc, tas, g_anchor_count); |
| 857 | if (insecure) { |
| 858 | /* debug escape hatch: environment-only, logged, TLS stays on. |
| 859 | * The engine is pointed at the lenient wrapper whose embedded |
| 860 | * minimal engine is initialised fresh; the original xc simply |
| 861 | * goes unused (both live until sx_conn_close). */ |
| 862 | sx_x509_lenient_context *ln = |
| 863 | (sx_x509_lenient_context *)calloc(1, sizeof *ln); |
| 864 | if (!ln) { |
| 865 | set_err(err, errsz, "out of memory"); |
| 866 | sx_conn_close(c); |
| 867 | return -1; |
| 868 | } |
| 869 | ln->vtable = &sx_x509_lenient_vtable; |
| 870 | br_x509_minimal_init_full(&ln->inner, tas, g_anchor_count); |
| 871 | br_ssl_engine_set_x509(&cc->eng, (const br_x509_class **)&ln->vtable); |
| 872 | c->x509 = ln; /* freed by sx_conn_close as plain memory */ |
| 873 | c->ssl = cc; |
| 874 | } |
| 875 | br_ssl_engine_set_buffer(&cc->eng, c->iobuf, BR_SSL_BUFSIZE_BIDI, 1); |
| 876 | if (!br_ssl_client_reset(cc, c->host, 0)) { |
| 877 | set_err(err, errsz, "bad SNI hostname"); |
| 878 | sx_conn_close(c); |
| 879 | return -1; |
| 880 | } |
| 881 | |
| 882 | br_sslio_init(SX_SSLIO(c), &cc->eng, sx_low_read, c, sx_low_write, c); |
| 883 | |
| 884 | /* Drive the handshake: an empty flush runs the engine to OPEN or fail. */ |
| 885 | if (br_sslio_flush(SX_SSLIO(c)) != 0) { |
| 886 | int le = br_ssl_engine_last_error(&cc->eng); |
| 887 | int cert_err = (le >= BR_ERR_X509_OK && le <= BR_ERR_X509_NOT_TRUSTED); |
| 888 | |
| 889 | if (insecure && cert_err) { |
| 890 | /* SX_TLS_INSECURE=1 (debugging only, environment-set, never |
| 891 | * config-set): the wrapper engine returned an X.509 error that |
| 892 | * its lenient end_chain swallowed, so the engine closed. That |
| 893 | * cannot happen with the wrapper -- if we are here with the |
| 894 | * wrapper installed, the failure is NOT a certificate problem |
| 895 | * (it is a transport/protocol error). Fall through to the error |
| 896 | * path below. */ |
| 897 | } |
| 898 | |
| 899 | /* Pin trust: the chain ended untrusted (self-signed / private CA) but |
| 900 | * the operator pinned this exact server key. Reconnect and complete a |
| 901 | * full handshake against a known-key X.509 engine: without the |
| 902 | * server's private key the finished/sig verify still cannot be |
| 903 | * forged, so this is real authentication, not a bypass. */ |
| 904 | if (le == BR_ERR_X509_NOT_TRUSTED && (g_pin_count || g_env_pin_count)) { |
| 905 | const br_x509_pkey *pk0; |
| 906 | unsigned us0 = 0; |
| 907 | unsigned char spki[1200]; |
| 908 | char hex[65]; |
| 909 | pk0 = xc->vtable->get_pkey((const br_x509_class *const *)xc, &us0); |
| 910 | if (pk0 && sx_key_spki(pk0, spki, sizeof spki)) { |
| 911 | sx_sha256_hex(spki, sx_key_spki(pk0, spki, sizeof spki), hex); |
| 912 | if (sx_pin_matches_hex(hex)) { |
| 913 | br_x509_pkey saved = *pk0; |
| 914 | static unsigned char saved_key[2 * BR_X509_BUFSIZE_KEY + 16]; |
| 915 | unsigned char *kp = saved_key; |
| 916 | if (saved.key_type == BR_KEYTYPE_RSA) { |
| 917 | memcpy(kp, saved.key.rsa.n, saved.key.rsa.nlen); |
| 918 | saved.key.rsa.n = kp; |
| 919 | kp += saved.key.rsa.nlen; |
| 920 | memcpy(kp, saved.key.rsa.e, saved.key.rsa.elen); |
| 921 | saved.key.rsa.e = kp; |
| 922 | } else { |
| 923 | memcpy(kp, saved.key.ec.q, saved.key.ec.qlen); |
| 924 | saved.key.ec.q = kp; |
| 925 | } |
| 926 | /* tear down the failed attempt (through the one |
| 927 | * owner, sx_conn_close) and redo with known-key */ |
| 928 | sx_conn_close(c); |
| 929 | cc = NULL; xc = NULL; |
| 930 | c->fd = sx_connect_timeout(c->host, c->port, |
| 931 | timeout_ms > 0 ? timeout_ms : 15000, |
| 932 | err, errsz); |
| 933 | if (c->fd == SX_SOCK_INVALID) return -1; |
| 934 | cc = (br_ssl_client_context *)calloc(1, sizeof *cc); |
| 935 | xc = (br_x509_minimal_context *)calloc(1, sizeof *xc); |
| 936 | c->iobuf = (unsigned char *)malloc(BR_SSL_BUFSIZE_BIDI); |
| 937 | { |
| 938 | br_x509_knownkey_context *kk = |
| 939 | (br_x509_knownkey_context *)calloc(1, sizeof *kk); |
| 940 | if (!cc || !xc || !kk || !c->iobuf) { |
| 941 | set_err(err, errsz, "out of memory"); |
| 942 | free(cc); free(xc); free(kk); free(c->iobuf); |
| 943 | c->ssl = c->x509 = NULL; c->iobuf = NULL; |
| 944 | return -1; |
| 945 | } |
| 946 | if (saved.key_type == BR_KEYTYPE_RSA) |
| 947 | br_x509_knownkey_init_rsa(kk, &saved.key.rsa, |
| 948 | BR_KEYTYPE_SIGN | BR_KEYTYPE_KEYX); |
| 949 | else |
| 950 | br_x509_knownkey_init_ec(kk, &saved.key.ec, |
| 951 | BR_KEYTYPE_SIGN | BR_KEYTYPE_KEYX); |
| 952 | br_ssl_client_init_full(cc, xc, tas, g_anchor_count); |
| 953 | br_ssl_engine_set_x509(&cc->eng, (const br_x509_class **)&kk->vtable); |
| 954 | br_ssl_engine_set_buffer(&cc->eng, c->iobuf, BR_SSL_BUFSIZE_BIDI, 1); |
| 955 | if (!br_ssl_client_reset(cc, c->host, 0)) { |
| 956 | set_err(err, errsz, "bad SNI hostname"); |
| 957 | free(cc); free(xc); free(kk); free(c->iobuf); |
| 958 | c->ssl = c->x509 = NULL; c->iobuf = NULL; |
| 959 | return -1; |
| 960 | } |
| 961 | br_sslio_init(SX_SSLIO(c), &cc->eng, sx_low_read, c, sx_low_write, c); |
| 962 | if (br_sslio_flush(SX_SSLIO(c)) != 0) { |
| 963 | set_err(err, errsz, "pinned TLS handshake failed (code %d)", |
| 964 | br_ssl_engine_last_error(&cc->eng)); |
| 965 | free(cc); free(xc); free(kk); free(c->iobuf); |
| 966 | c->ssl = c->x509 = NULL; c->iobuf = NULL; |
| 967 | return -1; |
| 968 | } |
| 969 | c->ssl = cc; |
| 970 | c->x509 = xc; /* kk stays alive via the engine */ |
| 971 | c->knownkey = kk; /* freed by sx_conn_close */ |
| 972 | c->tls_open = 1; |
| 973 | sx_sha256_hex(spki, sx_key_spki(&saved, spki, sizeof spki), |
| 974 | c->peer_fp_sha256); |
| 975 | c->chain_verified = 0; |
| 976 | c->pin_accepted = 1; |
| 977 | return 0; |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | set_err(err, errsz, "TLS handshake failed (code %d%s)", le, |
| 984 | insecure ? "" : "; SX_TLS_INSECURE=1 exists for debugging self-hosted relays only"); |
| 985 | sx_conn_close(c); |
| 986 | return -1; |
| 987 | } |
| 988 | |
| 989 | c->ssl = cc; |
| 990 | if (!insecure) c->x509 = xc; |
| 991 | c->tls_open = 1; |
| 992 | |
| 993 | /* leaf public key -> SDK-canonical SPKI pin */ |
| 994 | if (insecure) { |
| 995 | sx_x509_lenient_context *ln = (sx_x509_lenient_context *)c->x509; |
| 996 | pk = ln->inner.vtable->get_pkey((const br_x509_class *const *)&ln->inner, |
| 997 | &usages); |
| 998 | } else { |
| 999 | pk = xc->vtable->get_pkey((const br_x509_class *const *)xc, &usages); |
| 1000 | } |
| 1001 | if (pk) { |
| 1002 | static unsigned char spki[1200]; |
| 1003 | size_t n = sx_key_spki(pk, spki, sizeof spki); |
| 1004 | if (n) { |
| 1005 | sx_sha256_hex(spki, n, c->peer_fp_sha256); |
| 1006 | if (getenv("SX_VERBOSE")) |
| 1007 | fprintf(stderr, "sx_http_tls: peer pin %s for %s\n", |
| 1008 | c->peer_fp_sha256, c->host); |
| 1009 | } |
| 1010 | } |
| 1011 | |
| 1012 | if (insecure) { |
| 1013 | sx_x509_lenient_context *ln = (sx_x509_lenient_context *)c->x509; |
| 1014 | c->chain_verified = (ln->last_err == 0); |
| 1015 | } else { |
| 1016 | c->chain_verified = (br_ssl_engine_last_error(&cc->eng) == 0) && |
| 1017 | ((br_ssl_engine_current_state(&cc->eng) & BR_SSL_CLOSED) == 0); |
| 1018 | } |
| 1019 | c->pin_accepted = sx_pin_matches_hex(c->peer_fp_sha256); |
| 1020 | |
| 1021 | if (!insecure && !c->chain_verified && !c->pin_accepted) { |
| 1022 | set_err(err, errsz, "TLS certificate not trusted and no SPKI pin matched"); |
| 1023 | sx_conn_close(c); |
| 1024 | return -1; |
| 1025 | } |
| 1026 | return 0; |
| 1027 | } |
| 1028 | |
| 1029 | /* ------------------------------------------------------------------ open */ |
| 1030 | |
| 1031 | int sx_conn_open(sx_conn *c, const sx_url *url, long timeout_ms, |
| 1032 | char *err, size_t errsz) |
| 1033 | { |
| 1034 | memset(c, 0, sizeof *c); |
| 1035 | c->fd = SX_SOCK_INVALID; |
| 1036 | snprintf(c->host, sizeof c->host, "%s", url->host); |
| 1037 | c->port = url->port; |
| 1038 | c->tls = url->tls; |
| 1039 | |
| 1040 | c->fd = sx_connect_timeout(url->host, url->port, timeout_ms, err, errsz); |
| 1041 | if (c->fd == SX_SOCK_INVALID) return -1; |
| 1042 | |
| 1043 | if (c->tls) { |
| 1044 | if (sx_tls_handshake(c, timeout_ms, err, errsz) != 0) { |
| 1045 | if (c->fd != SX_SOCK_INVALID) { SX_CLOSESOCKET(c->fd); c->fd = SX_SOCK_INVALID; } |
| 1046 | return -1; |
| 1047 | } |
| 1048 | } else { |
| 1049 | c->deadline_ms = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); |
| 1050 | } |
| 1051 | return 0; |
| 1052 | } |
| 1053 | |
| 1054 | /* ------------------------------------------------------------ transport */ |
| 1055 | |
| 1056 | static int sx_send_all(sx_conn *c, const void *buf, size_t len, |
| 1057 | long timeout_ms, char *err, size_t errsz) |
| 1058 | { |
| 1059 | c->deadline_ms = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); |
| 1060 | if (c->tls && c->tls_open) { |
| 1061 | if (len && br_sslio_write_all(SX_SSLIO(c), buf, len) != 0) { |
| 1062 | set_err(err, errsz, "TLS send failed (code %d)", |
| 1063 | br_ssl_engine_last_error(&((br_ssl_client_context *)c->ssl)->eng)); |
| 1064 | return -1; |
| 1065 | } |
| 1066 | if (br_sslio_flush(SX_SSLIO(c)) != 0) { |
| 1067 | set_err(err, errsz, "TLS flush failed (code %d)", |
| 1068 | br_ssl_engine_last_error(&((br_ssl_client_context *)c->ssl)->eng)); |
| 1069 | return -1; |
| 1070 | } |
| 1071 | return 0; |
| 1072 | } |
| 1073 | { |
| 1074 | const unsigned char *p = (const unsigned char *)buf; |
| 1075 | while (len > 0) { |
| 1076 | sx_ssize_t n; |
| 1077 | if (!sx_wait_writable(c->fd, c->deadline_ms)) { |
| 1078 | set_err(err, errsz, "send timeout"); |
| 1079 | return -1; |
| 1080 | } |
| 1081 | /* MSG_NOSIGNAL: a server that has already half-closed the |
| 1082 | * connection (every `Connection: close` reply, and the node API |
| 1083 | * right after it answers) makes write() raise SIGPIPE. Without |
| 1084 | * the flag the signal escapes into the connector's own process |
| 1085 | * and its disposition decides what the caller sees -- usually a |
| 1086 | * nonsense status taken from errno instead of a clean send |
| 1087 | * failure. */ |
| 1088 | #if defined(MSG_NOSIGNAL) |
| 1089 | n = send(c->fd, (const char *)p, len, MSG_NOSIGNAL); |
| 1090 | #else |
| 1091 | n = send(c->fd, (const char *)p, len, 0); |
| 1092 | #endif |
| 1093 | if (n <= 0) { |
| 1094 | if (!sx_wait_writable(c->fd, c->deadline_ms)) { set_err(err, errsz, "send timeout"); return -1; } |
| 1095 | continue; |
| 1096 | } |
| 1097 | p += n; len -= (size_t)n; |
| 1098 | } |
| 1099 | } |
| 1100 | return 0; |
| 1101 | } |
| 1102 | |
| 1103 | /* Refill c->rbuf with fresh bytes from the transport. |
| 1104 | * 1 = data, 0 = clean EOF, -1 = error/timeout. */ |
| 1105 | static int sx_fill(sx_conn *c, long long deadline_ms) |
| 1106 | { |
| 1107 | if (c->tls && c->tls_open) { |
| 1108 | br_ssl_client_context *cc = (br_ssl_client_context *)c->ssl; |
| 1109 | int n; |
| 1110 | unsigned st; |
| 1111 | c->deadline_ms = deadline_ms; |
| 1112 | n = br_sslio_read(SX_SSLIO(c), c->rbuf, sizeof c->rbuf); |
| 1113 | if (n > 0) { c->rp = 0; c->rn = (size_t)n; return 1; } |
| 1114 | st = br_ssl_engine_current_state(&cc->eng); |
| 1115 | if (st & BR_SSL_CLOSED) { |
| 1116 | int le = br_ssl_engine_last_error(&cc->eng); |
| 1117 | if (le == 0) return 0; /* orderly close_notify */ |
| 1118 | return -1; |
| 1119 | } |
| 1120 | return -1; |
| 1121 | } |
| 1122 | { |
| 1123 | sx_ssize_t n; |
| 1124 | if (!sx_wait_readable(c->fd, deadline_ms)) return -1; |
| 1125 | n = recv(c->fd, c->rbuf, sizeof c->rbuf, 0); |
| 1126 | if (n > 0) { c->rp = 0; c->rn = (size_t)n; return 1; } |
| 1127 | if (n == 0) return 0; |
| 1128 | return -1; |
| 1129 | } |
| 1130 | } |
| 1131 | |
| 1132 | /* raw byte from transport (headers phase) */ |
| 1133 | static int sx_next_raw_byte(sx_conn *c, long long deadline_ms, int *out) |
| 1134 | { |
| 1135 | for (;;) { |
| 1136 | if (c->rp < c->rn) { *out = (unsigned char)c->rbuf[c->rp++]; return 1; } |
| 1137 | { |
| 1138 | int r = sx_fill(c, deadline_ms); |
| 1139 | if (r < 0) return -1; |
| 1140 | if (r == 0) return 0; |
| 1141 | } |
| 1142 | } |
| 1143 | } |
| 1144 | |
| 1145 | /* body byte with framing 0 (until-EOF) or 1 (content-length) */ |
| 1146 | static int sx_raw_body_byte(sx_conn *c, long long deadline_ms, int *out) |
| 1147 | { |
| 1148 | if (c->framing == 1 && c->content_left == 0) return 0; |
| 1149 | for (;;) { |
| 1150 | if (c->rp < c->rn) { |
| 1151 | *out = (unsigned char)c->rbuf[c->rp++]; |
| 1152 | if (c->framing == 1) c->content_left--; |
| 1153 | c->body_total++; |
| 1154 | if (c->body_total > SX_HTTP_BODY_CAP) return -1; |
| 1155 | return 1; |
| 1156 | } |
| 1157 | { |
| 1158 | int r = sx_fill(c, deadline_ms); |
| 1159 | if (r < 0) return -1; |
| 1160 | if (r == 0) return 0; |
| 1161 | if (c->framing == 1 && c->rn > c->content_left) c->rn = c->content_left; |
| 1162 | } |
| 1163 | } |
| 1164 | } |
| 1165 | |
| 1166 | /* one decoded body byte with the chunked state machine on top */ |
| 1167 | static int sx_next_body_byte(sx_conn *c, long long deadline_ms, int *out) |
| 1168 | { |
| 1169 | if (c->eof_seen) return 0; |
| 1170 | |
| 1171 | if (c->framing != 2) { |
| 1172 | int r = sx_raw_body_byte(c, deadline_ms, out); |
| 1173 | if (r == 0) c->eof_seen = 1; |
| 1174 | return r; |
| 1175 | } |
| 1176 | |
| 1177 | for (;;) { |
| 1178 | int ch, r; |
| 1179 | switch (c->chunk_state) { |
| 1180 | case SX_CHUNK_SIZE: { |
| 1181 | char line[32]; |
| 1182 | size_t ln = 0; |
| 1183 | for (;;) { |
| 1184 | r = sx_raw_body_byte(c, deadline_ms, &ch); |
| 1185 | if (r < 0) return -1; |
| 1186 | if (r == 0) { c->eof_seen = 1; return 0; } |
| 1187 | if (ch == '\n') break; |
| 1188 | if (ch == '\r') continue; |
| 1189 | if (ln + 1 < sizeof line) line[ln++] = (char)ch; |
| 1190 | else return -1; |
| 1191 | } |
| 1192 | line[ln] = '\0'; |
| 1193 | c->content_left = (size_t)strtoul(line, NULL, 16); |
| 1194 | if (c->content_left == 0) { c->chunk_state = SX_CHUNK_TRAILER; continue; } |
| 1195 | if (c->content_left > SX_HTTP_BODY_CAP) return -1; |
| 1196 | c->chunk_state = SX_CHUNK_DATA; |
| 1197 | continue; |
| 1198 | } |
| 1199 | case SX_CHUNK_DATA: { |
| 1200 | r = sx_raw_body_byte(c, deadline_ms, out); |
| 1201 | if (r <= 0) return -1; /* truncated mid-chunk */ |
| 1202 | c->content_left--; |
| 1203 | if (c->content_left == 0) c->chunk_state = SX_CHUNK_DATA_CRLF; |
| 1204 | return 1; |
| 1205 | } |
| 1206 | case SX_CHUNK_DATA_CRLF: |
| 1207 | r = sx_raw_body_byte(c, deadline_ms, &ch); |
| 1208 | if (r <= 0) return -1; |
| 1209 | if (ch == '\n') { c->chunk_state = SX_CHUNK_SIZE; continue; } |
| 1210 | continue; |
| 1211 | case SX_CHUNK_TRAILER: |
| 1212 | r = sx_raw_body_byte(c, deadline_ms, &ch); |
| 1213 | if (r <= 0) { c->eof_seen = 1; return 0; } |
| 1214 | if (ch == '\n') { c->eof_seen = 1; return 0; } |
| 1215 | continue; |
| 1216 | } |
| 1217 | } |
| 1218 | } |
| 1219 | |
| 1220 | /* --------------------------------------------------------------- headers */ |
| 1221 | |
| 1222 | static int hdr_eq(const char *a, const char *b) |
| 1223 | { |
| 1224 | return sx_strcasecmp(a, b) == 0; |
| 1225 | } |
| 1226 | |
| 1227 | static int sx_read_response(sx_conn *c, long timeout_ms, char *err, size_t errsz) |
| 1228 | { |
| 1229 | char line[8192]; |
| 1230 | size_t ln; |
| 1231 | int ch; |
| 1232 | long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); |
| 1233 | int first_line = 1; |
| 1234 | |
| 1235 | c->status = 0; |
| 1236 | c->framing = 0; |
| 1237 | c->content_left = 0; |
| 1238 | c->eof_seen = 0; |
| 1239 | c->rp = c->rn = 0; |
| 1240 | c->body_total = 0; |
| 1241 | c->close_after = 0; |
| 1242 | c->chunk_state = SX_CHUNK_SIZE; |
| 1243 | |
| 1244 | for (;;) { |
| 1245 | ln = 0; |
| 1246 | for (;;) { |
| 1247 | int r = sx_next_raw_byte(c, deadline, &ch); |
| 1248 | if (r <= 0) { set_err(err, errsz, "timeout reading response headers"); return -1; } |
| 1249 | if (ch == '\n') break; |
| 1250 | if (ch != '\r' && ln + 1 < sizeof line) line[ln++] = (char)ch; |
| 1251 | } |
| 1252 | line[ln] = '\0'; |
| 1253 | if (first_line) { |
| 1254 | if (strncmp(line, "HTTP/1.1 ", 9) == 0 || strncmp(line, "HTTP/1.0 ", 9) == 0) |
| 1255 | c->status = atol(line + 9); |
| 1256 | else { set_err(err, errsz, "bad status line"); return -1; } |
| 1257 | first_line = 0; |
| 1258 | continue; |
| 1259 | } |
| 1260 | if (ln == 0) break; |
| 1261 | { |
| 1262 | char *colon = strchr(line, ':'); |
| 1263 | char *val; |
| 1264 | if (!colon) continue; |
| 1265 | *colon = '\0'; |
| 1266 | val = colon + 1; |
| 1267 | while (*val == ' ' || *val == '\t') val++; |
| 1268 | if (hdr_eq(line, "Content-Length")) { |
| 1269 | c->content_left = (size_t)strtoul(val, NULL, 10); |
| 1270 | c->framing = 1; |
| 1271 | } else if (hdr_eq(line, "Transfer-Encoding")) { |
| 1272 | if (strstr(val, "chunked") || strstr(val, "Chunked")) |
| 1273 | c->framing = 2; |
| 1274 | } else if (hdr_eq(line, "Connection")) { |
| 1275 | if (strstr(val, "close") || strstr(val, "Close")) c->close_after = 1; |
| 1276 | } |
| 1277 | } |
| 1278 | } |
| 1279 | if (c->status == 204 || c->status == 304) { c->framing = 1; c->content_left = 0; } |
| 1280 | return 0; |
| 1281 | } |
| 1282 | |
| 1283 | /* -------------------------------------------------------------- request */ |
| 1284 | |
| 1285 | int sx_http_request(sx_conn *c, const char *method, const char *path, |
| 1286 | const char *extra_headers, const char *bearer, |
| 1287 | const void *body, size_t blen, |
| 1288 | long timeout_ms, char *err, size_t errsz) |
| 1289 | { |
| 1290 | char req[8192]; |
| 1291 | int n; |
| 1292 | size_t off = 0; |
| 1293 | int default_port = (c->port == (c->tls ? 443 : 80)); |
| 1294 | |
| 1295 | n = snprintf(req + off, sizeof req - off, |
| 1296 | "%s %s HTTP/1.1\r\nHost: %s", |
| 1297 | method, path, c->host); |
| 1298 | if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } |
| 1299 | off += (size_t)n; |
| 1300 | if (!default_port) { |
| 1301 | n = snprintf(req + off, sizeof req - off, ":%d", c->port); |
| 1302 | if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } |
| 1303 | off += (size_t)n; |
| 1304 | } |
| 1305 | n = snprintf(req + off, sizeof req - off, |
| 1306 | "\r\nUser-Agent: sx-connector-sdk/1.0\r\n" |
| 1307 | "Accept: */*\r\nConnection: close\r\n"); |
| 1308 | if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } |
| 1309 | off += (size_t)n; |
| 1310 | if (bearer && *bearer) { |
| 1311 | n = snprintf(req + off, sizeof req - off, "Authorization: Bearer %s\r\n", bearer); |
| 1312 | if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } |
| 1313 | off += (size_t)n; |
| 1314 | } |
| 1315 | if (extra_headers && *extra_headers) { |
| 1316 | n = snprintf(req + off, sizeof req - off, "%s", extra_headers); |
| 1317 | if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } |
| 1318 | off += (size_t)n; |
| 1319 | } |
| 1320 | if (body && blen > 0) { |
| 1321 | n = snprintf(req + off, sizeof req - off, "Content-Length: %lu\r\n\r\n", |
| 1322 | (unsigned long)blen); |
| 1323 | } else { |
| 1324 | n = snprintf(req + off, sizeof req - off, "\r\n"); |
| 1325 | } |
| 1326 | if (n < 0 || (size_t)n >= sizeof req - off) { set_err(err, errsz, "request too large"); return -1; } |
| 1327 | off += (size_t)n; |
| 1328 | |
| 1329 | if (sx_send_all(c, req, off, timeout_ms, err, errsz) != 0) return -1; |
| 1330 | if (body && blen > 0) { |
| 1331 | if (sx_send_all(c, body, blen, timeout_ms, err, errsz) != 0) return -1; |
| 1332 | } |
| 1333 | return sx_read_response(c, timeout_ms, err, errsz); |
| 1334 | } |
| 1335 | |
| 1336 | /* -------------------------------------------------------------- body IO */ |
| 1337 | |
| 1338 | int sx_read_line(sx_conn *c, char *out, size_t capsz, long timeout_ms) |
| 1339 | { |
| 1340 | size_t n = 0; |
| 1341 | long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); |
| 1342 | if (capsz == 0) return -1; |
| 1343 | for (;;) { |
| 1344 | int ch; |
| 1345 | int r = sx_next_body_byte(c, deadline, &ch); |
| 1346 | if (r < 0) return -1; |
| 1347 | if (r == 0) { |
| 1348 | if (n == 0) return 0; /* clean EOF, no partial line */ |
| 1349 | out[n] = '\0'; |
| 1350 | return 1; /* final partial line */ |
| 1351 | } |
| 1352 | if (ch == '\n') { |
| 1353 | if (n > 0 && out[n - 1] == '\r') n--; |
| 1354 | out[n] = '\0'; |
| 1355 | return 1; |
| 1356 | } |
| 1357 | if (n + 1 < capsz && n + 1 < SX_HTTP_LINE_CAP) out[n++] = (char)ch; |
| 1358 | else { |
| 1359 | while (ch != '\n') { |
| 1360 | r = sx_next_body_byte(c, deadline, &ch); |
| 1361 | if (r <= 0) break; |
| 1362 | } |
| 1363 | out[n] = '\0'; |
| 1364 | return 1; |
| 1365 | } |
| 1366 | } |
| 1367 | } |
| 1368 | |
| 1369 | int sx_read_all(sx_conn *c, char **buf, size_t *len, long timeout_ms) |
| 1370 | { |
| 1371 | size_t cap = 4096, n = 0; |
| 1372 | long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 15000); |
| 1373 | char *b = (char *)malloc(cap); |
| 1374 | if (!b) return -1; |
| 1375 | for (;;) { |
| 1376 | int ch; |
| 1377 | int r = sx_next_body_byte(c, deadline, &ch); |
| 1378 | if (r < 0) { free(b); return -1; } |
| 1379 | if (r == 0) break; |
| 1380 | if (n + 1 >= cap) { |
| 1381 | char *nb; |
| 1382 | cap *= 2; |
| 1383 | if (cap > SX_HTTP_BODY_CAP) cap = SX_HTTP_BODY_CAP; |
| 1384 | nb = (char *)realloc(b, cap); |
| 1385 | if (!nb) { free(b); return -1; } |
| 1386 | b = nb; |
| 1387 | } |
| 1388 | b[n++] = (char)ch; |
| 1389 | } |
| 1390 | b[n] = '\0'; |
| 1391 | *buf = b; |
| 1392 | if (len) *len = n; |
| 1393 | return 1; |
| 1394 | } |
| 1395 | |
| 1396 | /* -------------------------------------------------------------- close */ |
| 1397 | |
| 1398 | void sx_conn_close(sx_conn *c) |
| 1399 | { |
| 1400 | if (c->tls && c->tls_open && c->ssl) { |
| 1401 | br_ssl_client_context *cc = (br_ssl_client_context *)c->ssl; |
| 1402 | long long dl; |
| 1403 | br_ssl_engine_close(&cc->eng); |
| 1404 | dl = sx_now_ms() + 500; |
| 1405 | while ((br_ssl_engine_current_state(&cc->eng) & BR_SSL_SENDREC) && |
| 1406 | sx_now_ms() < dl) { |
| 1407 | if (br_sslio_flush(SX_SSLIO(c)) != 0) break; |
| 1408 | } |
| 1409 | } |
| 1410 | if (c->fd != SX_SOCK_INVALID) { SX_CLOSESOCKET(c->fd); c->fd = SX_SOCK_INVALID; } |
| 1411 | free(c->ssl); c->ssl = NULL; |
| 1412 | free(c->x509); c->x509 = NULL; |
| 1413 | free(c->knownkey); c->knownkey = NULL; |
| 1414 | free(c->iobuf); c->iobuf = NULL; |
| 1415 | free(c->ta); c->ta = NULL; c->ta_n = 0; |
| 1416 | c->tls_open = 0; |
| 1417 | } |
| 1418 | |
| 1419 | /* ------------------------------------------------------------ websocket */ |
| 1420 | |
| 1421 | static void sx_base64(const unsigned char *in, size_t len, char *out) |
| 1422 | { |
| 1423 | static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 1424 | size_t i, o = 0; |
| 1425 | for (i = 0; i + 3 <= len; i += 3) { |
| 1426 | unsigned v = ((unsigned)in[i] << 16) | ((unsigned)in[i + 1] << 8) | in[i + 2]; |
| 1427 | out[o++] = tbl[(v >> 18) & 63]; |
| 1428 | out[o++] = tbl[(v >> 12) & 63]; |
| 1429 | out[o++] = tbl[(v >> 6) & 63]; |
| 1430 | out[o++] = tbl[v & 63]; |
| 1431 | } |
| 1432 | if (i < len) { |
| 1433 | unsigned v = (unsigned)in[i] << 16; |
| 1434 | if (i + 1 < len) v |= (unsigned)in[i + 1] << 8; |
| 1435 | out[o++] = tbl[(v >> 18) & 63]; |
| 1436 | out[o++] = tbl[(v >> 12) & 63]; |
| 1437 | out[o++] = (i + 1 < len) ? tbl[(v >> 6) & 63] : '='; |
| 1438 | out[o++] = '='; |
| 1439 | } |
| 1440 | out[o] = '\0'; |
| 1441 | } |
| 1442 | |
| 1443 | static void sx_rand_bytes(unsigned char *p, size_t n) |
| 1444 | { |
| 1445 | static int seeded = 0; |
| 1446 | size_t i; |
| 1447 | if (!seeded) { |
| 1448 | unsigned long long seed = (unsigned long long)sx_now_ms() |
| 1449 | ^ ((unsigned long long)(size_t)p << 8) |
| 1450 | ^ (unsigned long long)(size_t)&seeded; |
| 1451 | #if !defined(_WIN32) |
| 1452 | seed ^= (unsigned long long)(size_t)getpid(); |
| 1453 | #endif |
| 1454 | srand((unsigned)(seed ^ (seed >> 32))); |
| 1455 | seeded = 1; |
| 1456 | } |
| 1457 | for (i = 0; i < n; i++) p[i] = (unsigned char)((rand() >> (i % 7)) & 0xFF); |
| 1458 | } |
| 1459 | |
| 1460 | int sx_ws_connect(sx_ws *w, const sx_url *url, const char *extra_headers, |
| 1461 | long timeout_ms, char *err, size_t errsz) |
| 1462 | { |
| 1463 | unsigned char keyb[16]; |
| 1464 | char key[25]; |
| 1465 | char hdrs[4096]; |
| 1466 | int n; |
| 1467 | |
| 1468 | memset(w, 0, sizeof *w); |
| 1469 | if (sx_conn_open(&w->c, url, timeout_ms, err, errsz) != 0) return -1; |
| 1470 | |
| 1471 | sx_rand_bytes(keyb, sizeof keyb); |
| 1472 | sx_base64(keyb, sizeof keyb, key); |
| 1473 | |
| 1474 | n = snprintf(hdrs, sizeof hdrs, |
| 1475 | "Upgrade: websocket\r\nConnection: Upgrade\r\n" |
| 1476 | "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: %s\r\n%s%s", |
| 1477 | key, extra_headers ? extra_headers : "", |
| 1478 | (extra_headers && *extra_headers) ? "\r\n" : ""); |
| 1479 | if (n < 0 || (size_t)n >= sizeof hdrs) { |
| 1480 | set_err(err, errsz, "headers too large"); |
| 1481 | sx_conn_close(&w->c); |
| 1482 | return -1; |
| 1483 | } |
| 1484 | |
| 1485 | if (sx_http_request(&w->c, "GET", url->path, hdrs, NULL, NULL, 0, |
| 1486 | timeout_ms, err, errsz) != 0) { |
| 1487 | sx_conn_close(&w->c); |
| 1488 | return -1; |
| 1489 | } |
| 1490 | if (w->c.status != 101) { |
| 1491 | set_err(err, errsz, "websocket handshake returned %ld, expected 101", w->c.status); |
| 1492 | sx_conn_close(&w->c); |
| 1493 | return -1; |
| 1494 | } |
| 1495 | /* after the upgrade the stream is raw frames, not HTTP body framing */ |
| 1496 | w->c.framing = 0; |
| 1497 | w->c.eof_seen = 0; |
| 1498 | w->closed = 0; |
| 1499 | return 0; |
| 1500 | } |
| 1501 | |
| 1502 | int sx_ws_send(sx_ws *w, int opcode, const void *payload, size_t len, |
| 1503 | long timeout_ms, char *err, size_t errsz) |
| 1504 | { |
| 1505 | unsigned char hdr[14]; |
| 1506 | unsigned char mask[4]; |
| 1507 | size_t hl = 0, i; |
| 1508 | unsigned char *frame; |
| 1509 | |
| 1510 | if (w->closed) { set_err(err, errsz, "websocket closed"); return -1; } |
| 1511 | |
| 1512 | hdr[hl++] = (unsigned char)(0x80 | (opcode & 0x0F)); |
| 1513 | sx_rand_bytes(mask, 4); |
| 1514 | if (len < 126) { |
| 1515 | hdr[hl++] = (unsigned char)(0x80 | len); |
| 1516 | } else if (len < 65536) { |
| 1517 | hdr[hl++] = (unsigned char)(0x80 | 126); |
| 1518 | hdr[hl++] = (unsigned char)(len >> 8); |
| 1519 | hdr[hl++] = (unsigned char)(len & 0xFF); |
| 1520 | } else { |
| 1521 | int k; |
| 1522 | hdr[hl++] = (unsigned char)(0x80 | 127); |
| 1523 | for (k = 7; k >= 0; k--) hdr[hl++] = (unsigned char)(((unsigned long long)len >> (8 * k)) & 0xFF); |
| 1524 | } |
| 1525 | memcpy(hdr + hl, mask, 4); |
| 1526 | hl += 4; |
| 1527 | |
| 1528 | frame = (unsigned char *)malloc(hl + (len ? len : 1)); |
| 1529 | if (!frame) { set_err(err, errsz, "out of memory"); return -1; } |
| 1530 | memcpy(frame, hdr, hl); |
| 1531 | for (i = 0; i < len; i++) frame[hl + i] = ((unsigned char *)payload)[i] ^ mask[i & 3]; |
| 1532 | |
| 1533 | if (sx_send_all(&w->c, frame, hl + len, timeout_ms, err, errsz) != 0) { |
| 1534 | free(frame); |
| 1535 | return -1; |
| 1536 | } |
| 1537 | free(frame); |
| 1538 | return 0; |
| 1539 | } |
| 1540 | |
| 1541 | static int sx_ws_read_n(sx_ws *w, unsigned char *p, size_t n, |
| 1542 | long long deadline, char *err, size_t errsz) |
| 1543 | { |
| 1544 | size_t got = 0; |
| 1545 | while (got < n) { |
| 1546 | int ch; |
| 1547 | int r = sx_raw_body_byte(&w->c, deadline, &ch); |
| 1548 | if (r < 0) { set_err(err, errsz, "websocket read error"); return -1; } |
| 1549 | if (r == 0) { set_err(err, errsz, "websocket closed by peer"); return -1; } |
| 1550 | p[got++] = (unsigned char)ch; |
| 1551 | } |
| 1552 | return 0; |
| 1553 | } |
| 1554 | |
| 1555 | int sx_ws_recv(sx_ws *w, void *buf, size_t capsz, size_t *len, |
| 1556 | long timeout_ms, char *err, size_t errsz) |
| 1557 | { |
| 1558 | long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 60000); |
| 1559 | if (len) *len = 0; |
| 1560 | for (;;) { |
| 1561 | unsigned char h[2], ext[8], mask[4]; |
| 1562 | unsigned char *acc = NULL; |
| 1563 | size_t plen, i, got; |
| 1564 | int fin, opcode; |
| 1565 | |
| 1566 | if (w->closed) return 0; |
| 1567 | if (sx_ws_read_n(w, h, 2, deadline, err, errsz) != 0) return -1; |
| 1568 | fin = (h[0] & 0x80) != 0; |
| 1569 | if (h[1] & 0x80) { |
| 1570 | if (sx_ws_read_n(w, mask, 4, deadline, err, errsz) != 0) return -1; |
| 1571 | } else { |
| 1572 | memset(mask, 0, 4); |
| 1573 | } |
| 1574 | plen = (size_t)(h[1] & 0x7F); |
| 1575 | if (plen == 126) { |
| 1576 | if (sx_ws_read_n(w, ext, 2, deadline, err, errsz) != 0) return -1; |
| 1577 | plen = ((size_t)ext[0] << 8) | ext[1]; |
| 1578 | } else if (plen == 127) { |
| 1579 | unsigned long long v = 0; |
| 1580 | if (sx_ws_read_n(w, ext, 8, deadline, err, errsz) != 0) return -1; |
| 1581 | for (i = 0; i < 8; i++) v = (v << 8) | ext[i]; |
| 1582 | if (v > SX_WS_FRAME_CAP) { set_err(err, errsz, "frame too large"); return -1; } |
| 1583 | plen = (size_t)v; |
| 1584 | } |
| 1585 | if (plen > SX_WS_FRAME_CAP) { set_err(err, errsz, "frame too large"); return -1; } |
| 1586 | |
| 1587 | acc = (unsigned char *)malloc(plen ? plen : 1); |
| 1588 | if (!acc) { set_err(err, errsz, "out of memory"); return -1; } |
| 1589 | got = 0; |
| 1590 | while (got < plen) { |
| 1591 | int ch; |
| 1592 | int r = sx_raw_body_byte(&w->c, deadline, &ch); |
| 1593 | if (r <= 0) { free(acc); set_err(err, errsz, "websocket frame truncated"); return -1; } |
| 1594 | acc[got++] = (unsigned char)ch; |
| 1595 | } |
| 1596 | for (i = 0; i < plen; i++) acc[i] ^= mask[i & 3]; |
| 1597 | |
| 1598 | opcode = h[0] & 0x0F; |
| 1599 | if (opcode == 0x8) { /* close */ |
| 1600 | sx_ws_send(w, 0x8, NULL, 0, 200, NULL, 0); |
| 1601 | w->closed = 1; |
| 1602 | free(acc); |
| 1603 | return 0; |
| 1604 | } |
| 1605 | if (opcode == 0x9) { /* ping -> pong */ |
| 1606 | sx_ws_send(w, 0xA, acc, plen, 200, NULL, 0); |
| 1607 | free(acc); |
| 1608 | continue; |
| 1609 | } |
| 1610 | if (opcode == 0xA) { free(acc); continue; } /* pong */ |
| 1611 | if (!fin || opcode == 0x0) { free(acc); continue; } /* fragments dropped */ |
| 1612 | if (opcode == 0x1 || opcode == 0x2) { |
| 1613 | size_t ncopy = plen < capsz - 1 ? plen : capsz - 1; |
| 1614 | memcpy(buf, acc, ncopy); |
| 1615 | ((char *)buf)[ncopy] = '\0'; |
| 1616 | if (len) *len = ncopy; |
| 1617 | free(acc); |
| 1618 | return 1; |
| 1619 | } |
| 1620 | free(acc); /* unknown opcode */ |
| 1621 | } |
| 1622 | } |
| 1623 | |
| 1624 | void sx_ws_close(sx_ws *w) |
| 1625 | { |
| 1626 | if (!w->closed) sx_ws_send(w, 0x8, NULL, 0, 200, NULL, 0); |
| 1627 | w->closed = 1; |
| 1628 | sx_conn_close(&w->c); |
| 1629 | } |