| 1 | /* |
| 2 | * sx_http.c -- HTTP/1.1 over TCP or mbedTLS TLS, for plugin_ntfy. |
| 3 | * |
| 4 | * Two shapes of use, and the code is organised around them: |
| 5 | * |
| 6 | * sx_http_request() -- buffered: send a request, get status + body. |
| 7 | * Used for publishing a notification and for the |
| 8 | * bot API calls (/inbox, /conversation). |
| 9 | * sx_http_open_stream() + |
| 10 | * sx_http_readline() -- streaming: send a request, read status + |
| 11 | * headers, then hand back one newline-delimited |
| 12 | * record at a time. This is the <topic>/json |
| 13 | * subscription, which sits idle for minutes |
| 14 | * between keepalives and must never buffer the |
| 15 | * whole stream nor block the process forever. |
| 16 | * |
| 17 | * Three details are the reason this file is written by hand instead of |
| 18 | * shelling out to curl (a plugin that pops a shell to reach the network |
| 19 | * cannot be audited, and curl is not present on a slim container or a |
| 20 | * Windows node): |
| 21 | * |
| 22 | * 1. deadlines. Every phase -- connect, handshake, header read, ONE record |
| 23 | * read -- has its own absolute monotonic deadline enforced with |
| 24 | * select(). The only way to bound an mbedTLS handshake is to own the |
| 25 | * socket under it, so after connecting the socket stays non-blocking |
| 26 | * for its whole life and mbedTLS is fed through mbedtls_ssl_set_bio(): |
| 27 | * WANT_READ -> select() -> retry, everywhere. |
| 28 | * 2. chunked bodies. The live NDJSON stream is served as |
| 29 | * Transfer-Encoding: chunked, so reading a body is a small state |
| 30 | * machine (hex size line, chunk bytes, CRLF, trailers), not |
| 31 | * "read Content-Length bytes". |
| 32 | * 3. failing closed on TLS. The handshake runs with VERIFY_OPTIONAL and |
| 33 | * the code then refuses on ANY bad-certificate flag, which behaves like |
| 34 | * VERIFY_REQUIRED while still letting an operator's explicit SPKI pin |
| 35 | * carry a self-hosted relay on a private CA. A hostname mismatch is |
| 36 | * never pinnable away, and the only no-verification mode is the |
| 37 | * environment variable NTFY_TLS_INSECURE=1 -- never a config value, |
| 38 | * never an HTTP parameter. |
| 39 | * |
| 40 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 41 | */ |
| 42 | |
| 43 | #if defined(_WIN32) |
| 44 | # ifndef _WIN32_WINNT |
| 45 | # define _WIN32_WINNT 0x0601 /* getaddrinfo, inet_ntop */ |
| 46 | # endif |
| 47 | # define WIN32_LEAN_AND_MEAN |
| 48 | #else |
| 49 | # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L |
| 50 | # undef _POSIX_C_SOURCE |
| 51 | # define _POSIX_C_SOURCE 200809L |
| 52 | # endif |
| 53 | # ifndef _DEFAULT_SOURCE |
| 54 | # define _DEFAULT_SOURCE 1 |
| 55 | # endif |
| 56 | # if defined(__APPLE__) |
| 57 | # undef _DARWIN_C_SOURCE |
| 58 | # define _DARWIN_C_SOURCE 1 |
| 59 | # endif |
| 60 | #endif |
| 61 | |
| 62 | #include "sx_http.h" |
| 63 | #include "ca_bundle_pem.h" |
| 64 | |
| 65 | #include <stdio.h> |
| 66 | #include <stdlib.h> |
| 67 | #include <stdarg.h> |
| 68 | #include <string.h> |
| 69 | #include <ctype.h> |
| 70 | #include <errno.h> |
| 71 | #include <time.h> |
| 72 | |
| 73 | #include "mbedtls/platform.h" |
| 74 | #include "mbedtls/pk.h" |
| 75 | #include "mbedtls/sha256.h" |
| 76 | #include "mbedtls/error.h" |
| 77 | #include "mbedtls/x509_crt.h" |
| 78 | |
| 79 | #if defined(_WIN32) |
| 80 | # include <winsock2.h> |
| 81 | # include <ws2tcpip.h> |
| 82 | # include <windows.h> |
| 83 | # define sx_closesocket closesocket |
| 84 | #else |
| 85 | # include <unistd.h> |
| 86 | # include <sys/socket.h> |
| 87 | # include <sys/select.h> |
| 88 | # include <sys/time.h> |
| 89 | # include <sys/types.h> |
| 90 | # include <netinet/in.h> |
| 91 | # include <netinet/tcp.h> |
| 92 | # include <netdb.h> |
| 93 | # include <fcntl.h> |
| 94 | # define sx_closesocket close |
| 95 | #endif |
| 96 | |
| 97 | /* ------------------------------------------------------------------ time */ |
| 98 | |
| 99 | long long sx_now_ms(void) |
| 100 | { |
| 101 | #if defined(_WIN32) |
| 102 | FILETIME ft; |
| 103 | ULARGE_INTEGER u; |
| 104 | GetSystemTimeAsFileTime(&ft); |
| 105 | u.LowPart = ft.dwLowDateTime; |
| 106 | u.HighPart = ft.dwHighDateTime; |
| 107 | /* FILETIME is 100ns since 1601; /10000 -> ms. Monotonic enough here: |
| 108 | * every use is a difference between two readings. */ |
| 109 | return (long long)(u.QuadPart / 10000ULL); |
| 110 | #else |
| 111 | struct timespec ts; |
| 112 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 113 | return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L); |
| 114 | #endif |
| 115 | } |
| 116 | |
| 117 | static void set_err(char *err, size_t errsz, const char *fmt, ...) |
| 118 | { |
| 119 | va_list ap; |
| 120 | if (!err || !errsz) return; |
| 121 | va_start(ap, fmt); |
| 122 | vsnprintf(err, errsz, fmt, ap); |
| 123 | va_end(ap); |
| 124 | } |
| 125 | |
| 126 | /* ------------------------------------------------------------------ sha256 */ |
| 127 | |
| 128 | void sx_sha256_hex(const void *data, size_t len, char out[65]) |
| 129 | { |
| 130 | unsigned char d[32]; |
| 131 | static const char *hex = "0123456789abcdef"; |
| 132 | int i; |
| 133 | mbedtls_sha256((const unsigned char *)data, len, d, 0); |
| 134 | for (i = 0; i < 32; i++) { |
| 135 | out[i * 2] = hex[(d[i] >> 4) & 0xF]; |
| 136 | out[i * 2 + 1] = hex[d[i] & 0xF]; |
| 137 | } |
| 138 | out[64] = '\0'; |
| 139 | } |
| 140 | |
| 141 | /* -------------------------------------------------------------- url encode */ |
| 142 | |
| 143 | void sx_url_encode(const char *in, char *out, size_t capsz) |
| 144 | { |
| 145 | static const char *hex = "0123456789ABCDEF"; |
| 146 | size_t o = 0; |
| 147 | const unsigned char *p; |
| 148 | if (!capsz) return; |
| 149 | for (p = (const unsigned char *)in; p && *p; p++) { |
| 150 | unsigned char c = *p; |
| 151 | int safe = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || |
| 152 | (c >= '0' && c <= '9') || c == '.' || c == '_' || |
| 153 | c == '-' || c == '~'; |
| 154 | if (safe) { |
| 155 | if (o + 1 >= capsz) break; |
| 156 | out[o++] = (char)c; |
| 157 | } else { |
| 158 | if (o + 3 >= capsz) break; |
| 159 | out[o++] = '%'; |
| 160 | out[o++] = hex[c >> 4]; |
| 161 | out[o++] = hex[c & 0xF]; |
| 162 | } |
| 163 | } |
| 164 | out[o] = '\0'; |
| 165 | } |
| 166 | |
| 167 | /* -------------------------------------------------------------------- url */ |
| 168 | |
| 169 | int sx_url_parse(const char *url, sx_url *out, char *err, size_t errsz) |
| 170 | { |
| 171 | const char *p, *h, *e; |
| 172 | size_t n; |
| 173 | |
| 174 | memset(out, 0, sizeof *out); |
| 175 | if (!url || !*url) { set_err(err, errsz, "empty url"); return -1; } |
| 176 | |
| 177 | if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; } |
| 178 | else if (strncmp(url, "http://", 7) == 0) { p = url + 7; } |
| 179 | else { set_err(err, errsz, "url must start with http:// or https://"); return -1; } |
| 180 | |
| 181 | if (*p == '[') { set_err(err, errsz, "IPv6 literals are not supported"); return -1; } |
| 182 | |
| 183 | h = p; |
| 184 | e = p; |
| 185 | while (*e && *e != '/' && *e != '?' && *e != '#' && *e != ' ' && |
| 186 | (unsigned char)*e >= 0x20) e++; |
| 187 | n = (size_t)(e - h); |
| 188 | if (n == 0) { set_err(err, errsz, "url has no host"); return -1; } |
| 189 | if (n >= sizeof out->host) { set_err(err, errsz, "host too long"); return -1; } |
| 190 | if (memchr(h, '@', n)) { set_err(err, errsz, "userinfo in url is refused"); return -1; } |
| 191 | |
| 192 | out->port = out->tls ? 443 : 80; |
| 193 | { |
| 194 | const char *colon = memchr(h, ':', n); |
| 195 | if (colon) { |
| 196 | char ports[8]; |
| 197 | size_t pl = (size_t)(e - colon - 1), i; |
| 198 | if (pl == 0 || pl >= sizeof ports) { set_err(err, errsz, "bad port"); return -1; } |
| 199 | for (i = 0; i < pl; i++) |
| 200 | if (!isdigit((unsigned char)colon[1 + i])) { set_err(err, errsz, "bad port"); return -1; } |
| 201 | memcpy(ports, colon + 1, pl); |
| 202 | ports[pl] = '\0'; |
| 203 | out->port = atoi(ports); |
| 204 | if (out->port < 1 || out->port > 65535) { set_err(err, errsz, "port out of range"); return -1; } |
| 205 | n = (size_t)(colon - h); |
| 206 | } |
| 207 | } |
| 208 | memcpy(out->host, h, n); |
| 209 | out->host[n] = '\0'; |
| 210 | if (strspn(out->host, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-") != strlen(out->host)) { |
| 211 | set_err(err, errsz, "host contains forbidden characters"); |
| 212 | return -1; |
| 213 | } |
| 214 | |
| 215 | if (*e == '/' || *e == '?') { |
| 216 | size_t o = 0; |
| 217 | while (*e && *e != ' ' && o + 1 < sizeof out->path) out->path[o++] = *e++; |
| 218 | out->path[o] = '\0'; |
| 219 | if (*e == ' ') { set_err(err, errsz, "path contains a space"); return -1; } |
| 220 | } else { |
| 221 | snprintf(out->path, sizeof out->path, "/"); |
| 222 | } |
| 223 | { |
| 224 | const char *c; |
| 225 | for (c = out->path; *c; c++) |
| 226 | if ((unsigned char)*c < 0x20 || *c == '"' || *c == '\\') { |
| 227 | set_err(err, errsz, "path contains forbidden characters"); |
| 228 | return -1; |
| 229 | } |
| 230 | } |
| 231 | snprintf(out->scheme, sizeof out->scheme, "%s", out->tls ? "https" : "http"); |
| 232 | return 0; |
| 233 | } |
| 234 | |
| 235 | /* ------------------------------------------------------------------ socket */ |
| 236 | |
| 237 | static void sock_set_nonblock(sx_sock_t fd) |
| 238 | { |
| 239 | #if defined(_WIN32) |
| 240 | u_long nb = 1; |
| 241 | ioctlsocket(fd, FIONBIO, &nb); |
| 242 | #else |
| 243 | int fl = fcntl(fd, F_GETFL, 0); |
| 244 | if (fl >= 0) fcntl(fd, F_SETFL, fl | O_NONBLOCK); |
| 245 | #endif |
| 246 | } |
| 247 | |
| 248 | /* Wait until fd is readable, or the deadline passes. 1 = ready, 0 = timeout. */ |
| 249 | static int sx_wait_readable(sx_sock_t fd, long long deadline_ms) |
| 250 | { |
| 251 | for (;;) { |
| 252 | fd_set rf; |
| 253 | struct timeval tv; |
| 254 | long long left = deadline_ms - sx_now_ms(); |
| 255 | int rc; |
| 256 | if (left <= 0) return 0; |
| 257 | tv.tv_sec = (long)(left / 1000); |
| 258 | tv.tv_usec = (long)((left % 1000) * 1000); |
| 259 | FD_ZERO(&rf); |
| 260 | FD_SET(fd, &rf); |
| 261 | #if defined(_WIN32) |
| 262 | rc = select(0, &rf, NULL, NULL, &tv); |
| 263 | #else |
| 264 | rc = select((int)fd + 1, &rf, NULL, NULL, &tv); |
| 265 | #endif |
| 266 | if (rc > 0) return 1; |
| 267 | if (rc == 0) return 0; |
| 268 | #if defined(_WIN32) |
| 269 | return 0; |
| 270 | #else |
| 271 | if (errno == EINTR) continue; |
| 272 | return 0; |
| 273 | #endif |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /* Wait until a non-blocking connect completes. A successful connect makes a |
| 278 | * socket writable but NOT readable, so this must watch the write set. */ |
| 279 | static int sx_wait_writable(sx_sock_t fd, long long deadline_ms) |
| 280 | { |
| 281 | for (;;) { |
| 282 | fd_set wf; |
| 283 | struct timeval tv; |
| 284 | long long left = deadline_ms - sx_now_ms(); |
| 285 | int rc; |
| 286 | if (left <= 0) return 0; |
| 287 | tv.tv_sec = (long)(left / 1000); |
| 288 | tv.tv_usec = (long)((left % 1000) * 1000); |
| 289 | FD_ZERO(&wf); |
| 290 | FD_SET(fd, &wf); |
| 291 | #if defined(_WIN32) |
| 292 | rc = select(0, NULL, &wf, NULL, &tv); |
| 293 | #else |
| 294 | rc = select((int)fd + 1, NULL, &wf, NULL, &tv); |
| 295 | #endif |
| 296 | if (rc > 0) return 1; |
| 297 | if (rc == 0) return 0; |
| 298 | #if defined(_WIN32) |
| 299 | return 0; |
| 300 | #else |
| 301 | if (errno == EINTR) continue; |
| 302 | return 0; |
| 303 | #endif |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | static int sx_connect_timeout(const char *host, int port, long long timeout_ms, |
| 308 | sx_sock_t *fd_out, char *err, size_t errsz) |
| 309 | { |
| 310 | struct addrinfo hints, *res = NULL, *ai; |
| 311 | char ports[8], hostport[300]; |
| 312 | long long deadline; |
| 313 | sx_sock_t fd = SX_SOCK_INVALID; |
| 314 | |
| 315 | snprintf(hostport, sizeof hostport, "%s:%d", host, port); |
| 316 | memset(&hints, 0, sizeof hints); |
| 317 | hints.ai_family = AF_UNSPEC; |
| 318 | hints.ai_socktype = SOCK_STREAM; |
| 319 | snprintf(ports, sizeof ports, "%d", port); |
| 320 | |
| 321 | if (getaddrinfo(host, ports, &hints, &res) != 0 || !res) { |
| 322 | set_err(err, errsz, "cannot resolve %s", hostport); |
| 323 | return -1; |
| 324 | } |
| 325 | deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 10000); |
| 326 | |
| 327 | for (ai = res; ai; ai = ai->ai_next) { |
| 328 | int rc; |
| 329 | /* getaddrinfo on a dual-stack host returns ::1 before 127.0.0.1, and a |
| 330 | * server bound to IPv4 loopback only refuses the IPv6 attempt. Every |
| 331 | * failure path here MUST reset fd: an old build left the previous |
| 332 | * (closed) descriptor in it, the loop fell through, and the caller |
| 333 | * got "cannot connect" with a stale fd -- or worse, used a closed |
| 334 | * socket as if it were connected. */ |
| 335 | fd = SX_SOCK_INVALID; |
| 336 | rc = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); |
| 337 | if (rc < 0) continue; |
| 338 | fd = (sx_sock_t)rc; |
| 339 | sock_set_nonblock(fd); |
| 340 | #if !defined(_WIN32) |
| 341 | { int one = 1; setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof one); } |
| 342 | #endif |
| 343 | rc = connect(fd, ai->ai_addr, (int)ai->ai_addrlen); |
| 344 | if (rc == 0) break; |
| 345 | #if defined(_WIN32) |
| 346 | if (WSAGetLastError() != WSAEWOULDBLOCK) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } |
| 347 | #else |
| 348 | if (errno != EINPROGRESS) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } |
| 349 | #endif |
| 350 | /* A non-blocking connect completes on WRITABILITY, not readability: |
| 351 | * a successful connect leaves the socket readable forever, so |
| 352 | * waiting on the read set here hangs until the deadline and every |
| 353 | * local server looks unreachable. */ |
| 354 | if (!sx_wait_writable(fd, deadline)) { sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; } |
| 355 | { |
| 356 | int soerr = 0; |
| 357 | socklen_t slen = sizeof soerr; |
| 358 | if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &slen) != 0 || soerr != 0) { |
| 359 | sx_closesocket(fd); fd = SX_SOCK_INVALID; continue; |
| 360 | } |
| 361 | } |
| 362 | break; |
| 363 | } |
| 364 | freeaddrinfo(res); |
| 365 | if (fd == SX_SOCK_INVALID) { set_err(err, errsz, "cannot connect to %s", hostport); return -1; } |
| 366 | *fd_out = fd; |
| 367 | return 0; |
| 368 | } |
| 369 | |
| 370 | /* ------------------------------------------------------------- mbedTLS bio */ |
| 371 | |
| 372 | static int bio_send(void *ctx, const unsigned char *buf, size_t n) |
| 373 | { |
| 374 | sx_sock_t fd = (sx_sock_t)(intptr_t)ctx; |
| 375 | ssize_t r = send(fd, (const char *)buf, n, 0); |
| 376 | if (r > 0) return (int)r; |
| 377 | #if defined(_WIN32) |
| 378 | { int e = WSAGetLastError(); |
| 379 | if (e == WSAEWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_WRITE; |
| 380 | return MBEDTLS_ERR_SSL_INTERNAL_ERROR; } |
| 381 | #else |
| 382 | if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) |
| 383 | return MBEDTLS_ERR_SSL_WANT_WRITE; |
| 384 | return MBEDTLS_ERR_SSL_INTERNAL_ERROR; |
| 385 | #endif |
| 386 | } |
| 387 | |
| 388 | static int bio_recv(void *ctx, unsigned char *buf, size_t n) |
| 389 | { |
| 390 | sx_sock_t fd = (sx_sock_t)(intptr_t)ctx; |
| 391 | ssize_t r = recv(fd, buf, n, 0); |
| 392 | if (r > 0) return (int)r; |
| 393 | if (r == 0) return 0; |
| 394 | #if defined(_WIN32) |
| 395 | { int e = WSAGetLastError(); |
| 396 | if (e == WSAEWOULDBLOCK) return MBEDTLS_ERR_SSL_WANT_READ; |
| 397 | return MBEDTLS_ERR_SSL_INTERNAL_ERROR; } |
| 398 | #else |
| 399 | if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) |
| 400 | return MBEDTLS_ERR_SSL_WANT_READ; |
| 401 | return MBEDTLS_ERR_SSL_INTERNAL_ERROR; |
| 402 | #endif |
| 403 | } |
| 404 | |
| 405 | /* ------------------------------------------------------------------ connect */ |
| 406 | |
| 407 | void sx_conn_init(sx_conn *c) |
| 408 | { |
| 409 | memset(c, 0, sizeof *c); |
| 410 | c->fd = SX_SOCK_INVALID; |
| 411 | c->content_left = -1; |
| 412 | } |
| 413 | |
| 414 | static int pin_allowed(const char *pins, const char *fp) |
| 415 | { |
| 416 | const char *p = pins; |
| 417 | if (!pins || !*pins || !fp || !*fp) return 0; |
| 418 | while (*p) { |
| 419 | char tok[80]; |
| 420 | size_t n = 0; |
| 421 | while (*p && (isspace((unsigned char)*p) || *p == ',')) p++; |
| 422 | if (!*p) break; |
| 423 | while (*p && !isspace((unsigned char)*p) && *p != ',' && n + 1 < sizeof tok) |
| 424 | tok[n++] = (char)tolower((unsigned char)*p++); |
| 425 | tok[n] = '\0'; |
| 426 | if (n == 64 && strcmp(tok, fp) == 0) return 1; |
| 427 | } |
| 428 | return 0; |
| 429 | } |
| 430 | |
| 431 | int sx_conn_open(sx_conn *c, const sx_url *url, const char *bearer, |
| 432 | const char *pins, const char *ca_file, int insecure, |
| 433 | long long timeout_ms, char *err, size_t errsz) |
| 434 | { |
| 435 | (void)bearer; /* Authorization is a request header, applied per request */ |
| 436 | sx_conn_init(c); |
| 437 | if (sx_connect_timeout(url->host, url->port, timeout_ms, &c->fd, err, errsz) != 0) |
| 438 | return -1; |
| 439 | /* Remember the peer: every request on this connection rebuilds its own |
| 440 | * Host header from these, so callers never have to pass the url twice. */ |
| 441 | snprintf(c->host, sizeof c->host, "%s", url->host); |
| 442 | c->port = url->port; |
| 443 | c->tls = url->tls; |
| 444 | if (!url->tls) { c->tls = 0; return 0; } |
| 445 | |
| 446 | c->tls = 1; |
| 447 | c->ssl = calloc(1, sizeof *c->ssl); |
| 448 | c->conf = calloc(1, sizeof *c->conf); |
| 449 | c->ca = calloc(1, sizeof *c->ca); |
| 450 | c->ent = calloc(1, sizeof *c->ent); |
| 451 | c->drbg = calloc(1, sizeof *c->drbg); |
| 452 | if (!c->ssl || !c->conf || !c->ca || !c->ent || !c->drbg) { |
| 453 | set_err(err, errsz, "out of memory"); |
| 454 | sx_conn_close(c); |
| 455 | return -1; |
| 456 | } |
| 457 | mbedtls_ssl_init(c->ssl); |
| 458 | mbedtls_ssl_config_init(c->conf); |
| 459 | mbedtls_x509_crt_init(c->ca); |
| 460 | mbedtls_entropy_init(c->ent); |
| 461 | mbedtls_ctr_drbg_init(c->drbg); |
| 462 | |
| 463 | if (mbedtls_ctr_drbg_seed(c->drbg, mbedtls_entropy_func, c->ent, NULL, 0) != 0) { |
| 464 | set_err(err, errsz, "entropy source unavailable"); |
| 465 | sx_conn_close(c); |
| 466 | return -1; |
| 467 | } |
| 468 | if (mbedtls_ssl_config_defaults(c->conf, MBEDTLS_SSL_IS_CLIENT, |
| 469 | MBEDTLS_SSL_TRANSPORT_STREAM, |
| 470 | MBEDTLS_SSL_PRESET_DEFAULT) != 0) { |
| 471 | set_err(err, errsz, "tls config failed"); |
| 472 | sx_conn_close(c); |
| 473 | return -1; |
| 474 | } |
| 475 | mbedtls_ssl_conf_rng(c->conf, mbedtls_ctr_drbg_random, c->drbg); |
| 476 | /* |
| 477 | * VERIFY_OPTIONAL + a hard refusal on every bad-certificate flag below. |
| 478 | * Deliberate rather than VERIFY_REQUIRED: with REQUIRED the handshake |
| 479 | * aborts before the code can inspect the leaf, which would make an |
| 480 | * operator's SPKI pin useless for a self-hosted relay on a private CA. |
| 481 | * Verification still fails closed -- the pin is an explicit alternative |
| 482 | * anchor, never a bypass of hostname checking. |
| 483 | */ |
| 484 | mbedtls_ssl_conf_authmode(c->conf, insecure ? MBEDTLS_SSL_VERIFY_NONE |
| 485 | : MBEDTLS_SSL_VERIFY_OPTIONAL); |
| 486 | if (!insecure) { |
| 487 | int r = mbedtls_x509_crt_parse(c->ca, |
| 488 | (const unsigned char *)SX_NTFY_CA_BUNDLE_PEM, |
| 489 | strlen(SX_NTFY_CA_BUNDLE_PEM) + 1); |
| 490 | if (r != 0) { set_err(err, errsz, "bundled trust store unreadable (%d)", r); sx_conn_close(c); return -1; } |
| 491 | if (ca_file && *ca_file) { |
| 492 | FILE *f = fopen(ca_file, "rb"); |
| 493 | char *pem; |
| 494 | long sz; |
| 495 | size_t rd; |
| 496 | if (!f) { set_err(err, errsz, "cannot open ca_file %s", ca_file); sx_conn_close(c); return -1; } |
| 497 | fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); |
| 498 | if (sz <= 0 || sz > 4 * 1024 * 1024) { |
| 499 | fclose(f); |
| 500 | set_err(err, errsz, "ca_file %s has a bad size", ca_file); |
| 501 | sx_conn_close(c); |
| 502 | return -1; |
| 503 | } |
| 504 | pem = malloc((size_t)sz + 1); |
| 505 | if (!pem) { fclose(f); set_err(err, errsz, "out of memory"); sx_conn_close(c); return -1; } |
| 506 | rd = fread(pem, 1, (size_t)sz, f); |
| 507 | pem[rd] = '\0'; |
| 508 | fclose(f); |
| 509 | r = mbedtls_x509_crt_parse(c->ca, (const unsigned char *)pem, rd + 1); |
| 510 | free(pem); |
| 511 | if (r != 0) { |
| 512 | set_err(err, errsz, "ca_file %s has no usable certificate (%d)", ca_file, r); |
| 513 | sx_conn_close(c); |
| 514 | return -1; |
| 515 | } |
| 516 | } |
| 517 | mbedtls_ssl_conf_ca_chain(c->conf, c->ca, NULL); |
| 518 | } |
| 519 | |
| 520 | if (mbedtls_ssl_setup(c->ssl, c->conf) != 0) { |
| 521 | set_err(err, errsz, "tls setup failed"); |
| 522 | sx_conn_close(c); |
| 523 | return -1; |
| 524 | } |
| 525 | if (mbedtls_ssl_set_hostname(c->ssl, url->host) != 0) { |
| 526 | set_err(err, errsz, "tls hostname rejected"); |
| 527 | sx_conn_close(c); |
| 528 | return -1; |
| 529 | } |
| 530 | mbedtls_ssl_set_bio(c->ssl, (void *)(intptr_t)c->fd, bio_send, bio_recv, NULL); |
| 531 | |
| 532 | { |
| 533 | long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 10000); |
| 534 | int r = 0; |
| 535 | int hs_want = 2; /* send the hello first: a fresh socket is writable */ |
| 536 | for (;;) { |
| 537 | /* mbedTLS is driven by WANT_READ/WANT_WRITE, not by a single |
| 538 | * read-set. A handshake step that only has to *write* (the |
| 539 | * ClientHello, the Finished) leaves the socket non-readable; if we |
| 540 | * waited only on the read set, mbedtls_ssl_handshake() would return |
| 541 | * WANT_WRITE and we would then block in select() forever on a |
| 542 | * server that correctly says nothing until it has our hello. That |
| 543 | * is the bug: the ClientHello never left the process (tcpdump on |
| 544 | * the real peer sees SYN, then a FIN 15 s later) and every ntfy |
| 545 | * call died as "tls handshake timed out". */ |
| 546 | if (mbedtls_ssl_check_pending(c->ssl)) { |
| 547 | /* nothing to wait for, mbedtls_ssl_read() has buffered data */ |
| 548 | } else if (hs_want == 2) { |
| 549 | if (!sx_wait_writable(c->fd, deadline)) { |
| 550 | set_err(err, errsz, "tls handshake timed out (write)"); |
| 551 | sx_conn_close(c); |
| 552 | return -1; |
| 553 | } |
| 554 | } else if (hs_want == 1) { |
| 555 | if (!sx_wait_readable(c->fd, deadline)) { |
| 556 | set_err(err, errsz, "tls handshake timed out"); |
| 557 | sx_conn_close(c); |
| 558 | return -1; |
| 559 | } |
| 560 | } |
| 561 | r = mbedtls_ssl_handshake(c->ssl); |
| 562 | if (r == MBEDTLS_ERR_SSL_WANT_WRITE) hs_want = 2; |
| 563 | else if (r == MBEDTLS_ERR_SSL_WANT_READ) hs_want = 1; |
| 564 | else break; |
| 565 | } |
| 566 | if (r != 0) { |
| 567 | char e[128]; |
| 568 | mbedtls_strerror(r, e, sizeof e); |
| 569 | set_err(err, errsz, "tls handshake failed: %s", e); |
| 570 | sx_conn_close(c); |
| 571 | return -1; |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | { |
| 576 | int flags = insecure ? 0 : (int)mbedtls_ssl_get_verify_result(c->ssl); |
| 577 | const mbedtls_x509_crt *leaf = mbedtls_ssl_get_peer_cert(c->ssl); |
| 578 | c->peer_fp_sha256[0] = '\0'; |
| 579 | if (leaf) { |
| 580 | /* SPKI pin = SHA-256 over the DER SubjectPublicKeyInfo. |
| 581 | * mbedtls_pk_write_pubkey_der writes the DER from the END of the |
| 582 | * buffer backwards and returns its length, so the blob starts at |
| 583 | * buf + sizeof(buf) - n. Reading from buf[0] would hash garbage |
| 584 | * and every pin would silently never match. */ |
| 585 | unsigned char spki[1600]; |
| 586 | int n = mbedtls_pk_write_pubkey_der( |
| 587 | (mbedtls_pk_context *)&leaf->pk, spki, sizeof spki); |
| 588 | if (n > 0 && n <= (int)sizeof spki) |
| 589 | sx_sha256_hex(spki + sizeof spki - (size_t)n, (size_t)n, |
| 590 | c->peer_fp_sha256); |
| 591 | } |
| 592 | if (insecure) { c->peer_verified = 0; c->pin_accepted = 0; return 0; } |
| 593 | if (flags == 0) { c->peer_verified = 1; return 0; } |
| 594 | if (flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) { |
| 595 | set_err(err, errsz, "tls certificate is not valid for %s (a pin cannot override a hostname mismatch)", url->host); |
| 596 | sx_conn_close(c); |
| 597 | return -1; |
| 598 | } |
| 599 | if (pin_allowed(pins, c->peer_fp_sha256)) { |
| 600 | c->peer_verified = 0; |
| 601 | c->pin_accepted = 1; |
| 602 | return 0; |
| 603 | } |
| 604 | set_err(err, errsz, "tls certificate rejected (verify flags 0x%x, no matching pin)", flags); |
| 605 | sx_conn_close(c); |
| 606 | return -1; |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | void sx_conn_close(sx_conn *c) |
| 611 | { |
| 612 | if (!c) return; |
| 613 | if (c->ssl) { mbedtls_ssl_free(c->ssl); free(c->ssl); c->ssl = NULL; } |
| 614 | if (c->conf) { mbedtls_ssl_config_free(c->conf); free(c->conf); c->conf = NULL; } |
| 615 | if (c->ca) { mbedtls_x509_crt_free(c->ca); free(c->ca); c->ca = NULL; } |
| 616 | if (c->ent) { mbedtls_entropy_free(c->ent); free(c->ent); c->ent = NULL; } |
| 617 | if (c->drbg) { mbedtls_ctr_drbg_free(c->drbg); free(c->drbg); c->drbg = NULL; } |
| 618 | if (c->fd != SX_SOCK_INVALID) { sx_closesocket(c->fd); c->fd = SX_SOCK_INVALID; } |
| 619 | free(c->body); |
| 620 | c->body = NULL; |
| 621 | c->body_len = c->body_cap = 0; |
| 622 | } |
| 623 | |
| 624 | /* ------------------------------------------------------------------- raw io */ |
| 625 | |
| 626 | /* Pull more bytes from the transport into rbuf. |
| 627 | * 1 = got bytes, 0 = clean EOF, -1 = timeout or transport error. */ |
| 628 | static int sx_fill(sx_conn *c, long long deadline_ms) |
| 629 | { |
| 630 | if (c->rn > c->rp) return 1; |
| 631 | c->rn = 0; |
| 632 | c->rp = 0; |
| 633 | if (c->eof) return 0; |
| 634 | |
| 635 | if (!c->tls) { |
| 636 | ssize_t n; |
| 637 | if (!sx_wait_readable(c->fd, deadline_ms)) return -1; |
| 638 | n = recv(c->fd, c->rbuf, sizeof c->rbuf, 0); |
| 639 | if (n == 0) { c->eof = 1; return 0; } |
| 640 | if (n < 0) { |
| 641 | #if defined(_WIN32) |
| 642 | return -1; |
| 643 | #else |
| 644 | if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return -1; |
| 645 | return -1; |
| 646 | #endif |
| 647 | } |
| 648 | c->rn = (size_t)n; |
| 649 | return 1; |
| 650 | } |
| 651 | |
| 652 | for (;;) { |
| 653 | ssize_t n; |
| 654 | if (!mbedtls_ssl_check_pending(c->ssl) && |
| 655 | !sx_wait_readable(c->fd, deadline_ms)) return -1; |
| 656 | n = mbedtls_ssl_read(c->ssl, (unsigned char *)c->rbuf, sizeof c->rbuf); |
| 657 | if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) |
| 658 | continue; |
| 659 | if (n == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY || n == 0) { c->eof = 1; return 0; } |
| 660 | if (n < 0) return -1; |
| 661 | c->rn = (size_t)n; |
| 662 | return 1; |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | /* Next body byte. 1 = byte in *out, 0 = end of body, -1 = error/timeout. */ |
| 667 | static int sx_body_byte(sx_conn *c, long long deadline_ms, int *out) |
| 668 | { |
| 669 | for (;;) { |
| 670 | int r, ch; |
| 671 | |
| 672 | if (!c->chunked) { |
| 673 | if (c->content_left == 0) return 0; |
| 674 | if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } |
| 675 | *out = (unsigned char)c->rbuf[c->rp++]; |
| 676 | if (c->content_left > 0) c->content_left--; |
| 677 | return 1; |
| 678 | } |
| 679 | |
| 680 | switch (c->chunk_state) { |
| 681 | case CHUNK_SIZE: { |
| 682 | char line[80]; |
| 683 | size_t ln = 0; |
| 684 | for (;;) { |
| 685 | if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } |
| 686 | ch = (unsigned char)c->rbuf[c->rp++]; |
| 687 | if (ch == '\r') continue; |
| 688 | if (ch == '\n') break; |
| 689 | if (ln + 1 < sizeof line) line[ln++] = (char)ch; |
| 690 | } |
| 691 | line[ln] = '\0'; |
| 692 | c->content_left = strtoll(line, NULL, 16); |
| 693 | if (c->content_left < 0) return -1; |
| 694 | if (c->content_left == 0) { c->chunk_state = CHUNK_TRAILER; continue; } |
| 695 | c->chunk_state = CHUNK_DATA; |
| 696 | continue; |
| 697 | } |
| 698 | case CHUNK_DATA: { |
| 699 | if (c->content_left > 0) { |
| 700 | if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } |
| 701 | *out = (unsigned char)c->rbuf[c->rp++]; |
| 702 | c->content_left--; |
| 703 | if (c->content_left == 0) c->chunk_state = CHUNK_DATA_CRLF; |
| 704 | return 1; |
| 705 | } |
| 706 | c->chunk_state = CHUNK_DATA_CRLF; |
| 707 | continue; |
| 708 | } |
| 709 | case CHUNK_DATA_CRLF: { |
| 710 | /* expect exactly one CRLF */ |
| 711 | if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } |
| 712 | ch = (unsigned char)c->rbuf[c->rp++]; |
| 713 | if (ch == '\r') { |
| 714 | if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } |
| 715 | ch = (unsigned char)c->rbuf[c->rp++]; |
| 716 | } |
| 717 | if (ch != '\n') return -1; |
| 718 | c->chunk_state = CHUNK_SIZE; |
| 719 | continue; |
| 720 | } |
| 721 | case CHUNK_TRAILER: { |
| 722 | /* read trailer lines until the blank line */ |
| 723 | char line[128]; |
| 724 | size_t ln = 0; |
| 725 | for (;;) { |
| 726 | if (c->rn <= c->rp) { r = sx_fill(c, deadline_ms); if (r <= 0) return r; } |
| 727 | ch = (unsigned char)c->rbuf[c->rp++]; |
| 728 | if (ch == '\r') continue; |
| 729 | if (ch == '\n') break; |
| 730 | if (ln + 1 < sizeof line) line[ln++] = (char)ch; |
| 731 | } |
| 732 | if (ln == 0) { c->eof = 1; return 0; } |
| 733 | continue; /* trailer header line -- skip it */ |
| 734 | } |
| 735 | default: |
| 736 | return 0; |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | /* Reads status line + headers. 0 = ok, -1 = error (err set). */ |
| 742 | static int sx_read_headers(sx_conn *c, long long deadline_ms, char *err, size_t errsz) |
| 743 | { |
| 744 | char head[8192]; |
| 745 | size_t n = 0; |
| 746 | char *line; |
| 747 | |
| 748 | c->status = 0; |
| 749 | c->status_text[0] = '\0'; |
| 750 | c->chunked = 0; |
| 751 | c->chunk_state = CHUNK_SIZE; |
| 752 | c->content_left = -1; |
| 753 | c->headers_done = 0; |
| 754 | |
| 755 | /* Accumulate until the blank header terminator. Bytes that arrive AFTER |
| 756 | * the terminator are body bytes (headers + body frequently share one |
| 757 | * packet); they are left in rbuf with rp pointing at the first of them, |
| 758 | * so sx_body_byte can still read them. Without that, every small |
| 759 | * response (headers + body in one segment, then Connection: close) |
| 760 | * returned an empty body: the id of our own publish and the whole |
| 761 | * /conversation poll silently vanished. */ |
| 762 | for (;;) { |
| 763 | int r = sx_fill(c, deadline_ms); |
| 764 | size_t i, seg0, seglen, take; |
| 765 | char *t; |
| 766 | if (r < 0) { set_err(err, errsz, "timed out reading response headers"); return -1; } |
| 767 | if (r == 0) { |
| 768 | if (n == 0) { set_err(err, errsz, "server closed without a response"); return -1; } |
| 769 | break; /* EOF right after headers is acceptable */ |
| 770 | } |
| 771 | seg0 = c->rp; seglen = c->rn; |
| 772 | take = 0; |
| 773 | for (i = seg0; i < c->rn && n + 1 < sizeof head; i++) { head[n++] = c->rbuf[i]; take++; } |
| 774 | head[n] = '\0'; |
| 775 | t = strstr(head, "\r\n\r\n"); |
| 776 | if (t) { |
| 777 | size_t tend = (size_t)(t - head) + 4; |
| 778 | if (tend <= n) { c->rp = seg0 + take - (c->rn - tend > n ? 0 : 0); } |
| 779 | /* place rp at absolute offset tend: current segment started at |
| 780 | * absolute n-take, so the read cursor is seg0 + (tend-(n-take)) */ |
| 781 | c->rp = seg0 + (tend - (n - take)); |
| 782 | c->rn = seglen; |
| 783 | n = tend; |
| 784 | break; |
| 785 | } |
| 786 | t = strstr(head, "\n\n"); |
| 787 | if (t) { |
| 788 | size_t tend = (size_t)(t - head) + 2; |
| 789 | if (tend <= n) { |
| 790 | c->rp = seg0 + (tend - (n - take)); |
| 791 | c->rn = seglen; |
| 792 | n = tend; |
| 793 | } |
| 794 | break; |
| 795 | } |
| 796 | if (n + 1 >= sizeof head) { set_err(err, errsz, "response headers too large"); return -1; } |
| 797 | } |
| 798 | /* Trim at the terminator so header walking cannot run past it. */ |
| 799 | { |
| 800 | char *t = strstr(head, "\r\n\r\n"); |
| 801 | if (t) *t = '\0'; |
| 802 | else { |
| 803 | t = strstr(head, "\n\n"); |
| 804 | if (t) *t = '\0'; |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | if (strncmp(head, "HTTP/1.1 ", 9) != 0 && strncmp(head, "HTTP/1.0 ", 9) != 0) { |
| 809 | set_err(err, errsz, "not an HTTP/1.x response"); |
| 810 | return -1; |
| 811 | } |
| 812 | c->status = atoi(head + 9); |
| 813 | { |
| 814 | char *sp = strchr(head + 9, ' '); |
| 815 | char *nl = strchr(head + 9, '\n'); |
| 816 | if (sp && (!nl || sp < nl)) { |
| 817 | size_t l = strlen(sp + 1); |
| 818 | if (nl && nl < sp + 1 + l) l = (size_t)(nl - (sp + 1)); |
| 819 | while (l > 0 && (sp[1 + l - 1] == '\r')) l--; |
| 820 | if (l >= sizeof c->status_text) l = sizeof c->status_text - 1; |
| 821 | memcpy(c->status_text, sp + 1, l); |
| 822 | c->status_text[l] = '\0'; |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | line = strchr(head, '\n'); |
| 827 | if (!line) { set_err(err, errsz, "malformed response"); return -1; } |
| 828 | line++; |
| 829 | while (line && *line) { |
| 830 | char *next = strchr(line, '\n'); |
| 831 | if (next) *next = '\0'; |
| 832 | { |
| 833 | size_t l = strlen(line); |
| 834 | while (l > 0 && (line[l - 1] == '\r')) line[--l] = '\0'; |
| 835 | } |
| 836 | if (strncasecmp(line, "Transfer-Encoding:", 16) == 0 && |
| 837 | strstr(line, "chunked")) { |
| 838 | c->chunked = 1; |
| 839 | c->chunk_state = CHUNK_SIZE; |
| 840 | } else if (strncasecmp(line, "Content-Length:", 15) == 0) { |
| 841 | long long v = strtoll(line + 15, NULL, 10); |
| 842 | if (v < 0) v = 0; |
| 843 | if (v > (long long)SX_HTTP_BODY_CAP) v = (long long)SX_HTTP_BODY_CAP; |
| 844 | c->content_left = v; |
| 845 | } |
| 846 | if (!next) break; |
| 847 | line = next + 1; |
| 848 | } |
| 849 | c->headers_done = 1; |
| 850 | return 0; |
| 851 | } |
| 852 | |
| 853 | /* ---------------------------------------------------------------- requests */ |
| 854 | |
| 855 | static int sx_send_all(sx_conn *c, const char *data, size_t len, |
| 856 | long long deadline_ms, char *err, size_t errsz) |
| 857 | { |
| 858 | size_t off = 0; |
| 859 | while (off < len) { |
| 860 | ssize_t n; |
| 861 | if (!c->tls) { |
| 862 | /* A non-blocking socket that is ready to SEND is WRITABLE, not |
| 863 | * readable: waiting on the read set here never fires, so every |
| 864 | * plain-HTTP request timed out after the full deadline with |
| 865 | * "timed out sending request". */ |
| 866 | if (!sx_wait_writable(c->fd, deadline_ms)) { set_err(err, errsz, "timed out sending request"); return -1; } |
| 867 | n = send(c->fd, data + off, len - off, 0); |
| 868 | if (n > 0) { off += (size_t)n; continue; } |
| 869 | #if defined(_WIN32) |
| 870 | { set_err(err, errsz, "connection dropped while sending"); return -1; } |
| 871 | #else |
| 872 | if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue; |
| 873 | set_err(err, errsz, "connection dropped while sending"); |
| 874 | return -1; |
| 875 | #endif |
| 876 | } |
| 877 | { |
| 878 | int want_read = 0; |
| 879 | for (;;) { |
| 880 | if (want_read || mbedtls_ssl_check_pending(c->ssl)) { |
| 881 | if (!sx_wait_readable(c->fd, deadline_ms)) { set_err(err, errsz, "timed out sending request"); return -1; } |
| 882 | } else { |
| 883 | if (!sx_wait_writable(c->fd, deadline_ms)) { set_err(err, errsz, "timed out sending request"); return -1; } |
| 884 | } |
| 885 | n = mbedtls_ssl_write(c->ssl, (const unsigned char *)data + off, len - off); |
| 886 | if (n == MBEDTLS_ERR_SSL_WANT_READ) { want_read = 1; continue; } |
| 887 | if (n == MBEDTLS_ERR_SSL_WANT_WRITE) { want_read = 0; continue; } |
| 888 | break; |
| 889 | } |
| 890 | } |
| 891 | if (n <= 0) { set_err(err, errsz, "tls write failed"); return -1; } |
| 892 | off += (size_t)n; |
| 893 | } |
| 894 | return 0; |
| 895 | } |
| 896 | /* Builds the request into a freshly malloc'd buffer. Returns it via *req_out |
| 897 | * (caller frees) and its length, or -1 when a header was rejected. */ |
| 898 | static int build_request(const char *host, int port, int tls, |
| 899 | const char *method, const char *path, |
| 900 | const char *const *hdrs, |
| 901 | const char *body, size_t body_len, |
| 902 | int keep_alive, char **req_out, size_t *req_len_out) |
| 903 | { |
| 904 | static char line[2500]; |
| 905 | char *buf; |
| 906 | size_t cap = 4096 + body_len + 4096, o = 0; |
| 907 | int i; |
| 908 | |
| 909 | if (strlen(method) > 10 || strlen(path) > 2000) return -1; |
| 910 | for (i = 0; path[i]; i++) |
| 911 | if ((unsigned char)path[i] < 0x20 || path[i] == '"' || path[i] == '\\') |
| 912 | return -1; |
| 913 | |
| 914 | buf = malloc(cap); |
| 915 | if (!buf) return -1; |
| 916 | |
| 917 | o += (size_t)snprintf(buf + o, cap - o, "%s %s HTTP/1.1\r\n", method, path); |
| 918 | if (port != (tls ? 443 : 80)) |
| 919 | o += (size_t)snprintf(buf + o, cap - o, "Host: %s:%d\r\n", host, port); |
| 920 | else |
| 921 | o += (size_t)snprintf(buf + o, cap - o, "Host: %s\r\n", host); |
| 922 | o += (size_t)snprintf(buf + o, cap - o, |
| 923 | "User-Agent: scorpiox-bot-plugin-ntfy/1.0.0\r\n"); |
| 924 | o += (size_t)snprintf(buf + o, cap - o, "Accept: */*\r\n"); |
| 925 | o += (size_t)snprintf(buf + o, cap - o, "Accept-Encoding: identity\r\n"); |
| 926 | o += (size_t)snprintf(buf + o, cap - o, "Connection: %s\r\n", |
| 927 | keep_alive ? "keep-alive" : "close"); |
| 928 | (void)line; |
| 929 | |
| 930 | if (hdrs) { |
| 931 | for (i = 0; hdrs[i]; i++) { |
| 932 | const char *h = hdrs[i]; |
| 933 | size_t l; |
| 934 | /* Header injection guard: no control characters in a value, ever. |
| 935 | * A value that fails is a programming error, not attacker input |
| 936 | * (values are assembled by the caller from validated fields), so |
| 937 | * the whole request is refused rather than sanitised. */ |
| 938 | for (l = 0; h[l]; l++) |
| 939 | if ((unsigned char)h[l] < 0x20 && h[l] != '\t') { free(buf); return -1; } |
| 940 | if (strlen(h) > 1200) { free(buf); return -1; } |
| 941 | o += (size_t)snprintf(buf + o, cap - o, "%s\r\n", h); |
| 942 | if (o + 2 >= cap) { free(buf); return -1; } |
| 943 | } |
| 944 | } |
| 945 | if (body_len > 0 || strcmp(method, "POST") == 0 || strcmp(method, "PUT") == 0) |
| 946 | o += (size_t)snprintf(buf + o, cap - o, "Content-Length: %u\r\n", |
| 947 | (unsigned)body_len); |
| 948 | o += (size_t)snprintf(buf + o, cap - o, "\r\n"); |
| 949 | if (o + body_len + 1 > cap) { free(buf); return -1; } |
| 950 | if (body && body_len) { memcpy(buf + o, body, body_len); o += body_len; } |
| 951 | buf[o] = '\0'; |
| 952 | *req_out = buf; |
| 953 | *req_len_out = o; |
| 954 | return 0; |
| 955 | } |
| 956 | |
| 957 | int sx_http_request(sx_conn *c, const char *method, const char *path, |
| 958 | const char *const *hdrs, const char *body, size_t body_len, |
| 959 | int *status, char **body_out, size_t *body_out_len, |
| 960 | char *err, size_t errsz) |
| 961 | { |
| 962 | char *req = NULL; |
| 963 | size_t reqlen = 0; |
| 964 | long long deadline; |
| 965 | |
| 966 | if (body_out) *body_out = NULL; |
| 967 | if (body_out_len) *body_out_len = 0; |
| 968 | if (status) *status = 0; |
| 969 | if (err && errsz) *err = '\0'; |
| 970 | |
| 971 | if (build_request(c->host, c->port, c->tls, method, path, hdrs, |
| 972 | body, body_len, 0, &req, &reqlen) != 0) { |
| 973 | set_err(err, errsz, "request refused (malformed header or path)"); |
| 974 | return -1; |
| 975 | } |
| 976 | deadline = sx_now_ms() + 20000; |
| 977 | if (sx_send_all(c, req, reqlen, deadline, err, errsz) != 0) { |
| 978 | free(req); |
| 979 | return -1; |
| 980 | } |
| 981 | free(req); |
| 982 | |
| 983 | if (sx_read_headers(c, deadline, err, errsz) != 0) return -1; |
| 984 | if (status) *status = c->status; |
| 985 | if (strcmp(method, "HEAD") == 0) return 0; |
| 986 | |
| 987 | { |
| 988 | size_t bcap = 4096, len = 0; |
| 989 | char *b = malloc(bcap); |
| 990 | if (!b) { set_err(err, errsz, "out of memory"); return -1; } |
| 991 | for (;;) { |
| 992 | int ch, r = sx_body_byte(c, deadline, &ch); |
| 993 | if (r == 0) break; |
| 994 | if (r < 0) { free(b); set_err(err, errsz, "error reading response body"); return -1; } |
| 995 | if (len + 1 >= bcap) { |
| 996 | size_t nc = bcap * 2; |
| 997 | char *nb; |
| 998 | if (nc > SX_HTTP_BODY_CAP + 1) nc = SX_HTTP_BODY_CAP + 1; |
| 999 | nb = realloc(b, nc); |
| 1000 | if (!nb) { free(b); set_err(err, errsz, "out of memory"); return -1; } |
| 1001 | b = nb; |
| 1002 | bcap = nc; |
| 1003 | if (len >= SX_HTTP_BODY_CAP) break; |
| 1004 | } |
| 1005 | b[len++] = (char)ch; |
| 1006 | if (len >= SX_HTTP_BODY_CAP) break; |
| 1007 | } |
| 1008 | b[len] = '\0'; |
| 1009 | if (body_out) *body_out = b; else free(b); |
| 1010 | if (body_out_len) *body_out_len = len; |
| 1011 | } |
| 1012 | return 0; |
| 1013 | } |
| 1014 | |
| 1015 | int sx_http_open_stream(sx_conn *c, const char *method, const char *path, |
| 1016 | const char *const *hdrs, int *status, |
| 1017 | char *err, size_t errsz) |
| 1018 | { |
| 1019 | char *req = NULL; |
| 1020 | size_t reqlen = 0; |
| 1021 | long long deadline; |
| 1022 | |
| 1023 | if (status) *status = 0; |
| 1024 | if (err && errsz) *err = '\0'; |
| 1025 | |
| 1026 | if (build_request(c->host, c->port, c->tls, method, path, hdrs, |
| 1027 | NULL, 0, 0, &req, &reqlen) != 0) { |
| 1028 | set_err(err, errsz, "request refused (malformed header or path)"); |
| 1029 | return -1; |
| 1030 | } |
| 1031 | deadline = sx_now_ms() + 20000; |
| 1032 | if (sx_send_all(c, req, reqlen, deadline, err, errsz) != 0) { |
| 1033 | free(req); |
| 1034 | return -1; |
| 1035 | } |
| 1036 | free(req); |
| 1037 | if (sx_read_headers(c, deadline, err, errsz) != 0) return -1; |
| 1038 | if (status) *status = c->status; |
| 1039 | return 0; |
| 1040 | } |
| 1041 | |
| 1042 | int sx_http_readline(sx_conn *c, char *line, size_t capsz, long long timeout_ms) |
| 1043 | { |
| 1044 | long long deadline = sx_now_ms() + (timeout_ms > 0 ? timeout_ms : 30000); |
| 1045 | size_t o = 0; |
| 1046 | |
| 1047 | if (!capsz) return -1; |
| 1048 | for (;;) { |
| 1049 | int ch, r = sx_body_byte(c, deadline, &ch); |
| 1050 | if (r == 0) { line[o] = '\0'; return o ? 1 : 0; } /* EOF with a partial record: still deliver it */ |
| 1051 | if (r < 0) return -1; |
| 1052 | if (ch == '\n') { |
| 1053 | if (o > 0 && line[o - 1] == '\r') o--; |
| 1054 | line[o] = '\0'; |
| 1055 | return 1; |
| 1056 | } |
| 1057 | if (o + 1 < capsz && o + 1 < SX_HTTP_LINE_CAP) line[o++] = (char)ch; |
| 1058 | else if (o + 1 >= SX_HTTP_LINE_CAP) { |
| 1059 | /* Absurdly long single record: drop the rest of the line and |
| 1060 | * return what we have rather than growing without bound. */ |
| 1061 | int cc; |
| 1062 | while ((r = sx_body_byte(c, deadline, &cc)) == 1 && cc != '\n') |
| 1063 | ; |
| 1064 | line[o] = '\0'; |
| 1065 | return 1; |
| 1066 | } |
| 1067 | } |
| 1068 | } |