scorpiox-bot-plugin-webhook
←wh_http.cc
1052 lines · 37 KBHEADBlameDownload
1/*
2 * wh_http.c - URL parse, SSRF policy, and one HTTP/1.1 request.
3 *
4 * See wh_http.h for the policy this file implements. The short version: every
5 * address a hostname resolves to is validated before anything is connected,
6 * the connection is made to that validated numeric address, TLS is verified
7 * with no bypass, and redirects are reported rather than followed.
8 *
9 * MIT License. Copyright (c) 2026 SCORPIOX INC.
10 */
11
12/* Before every include: MinGW defaults _WIN32_WINNT to 0x502, which hides
13 * InetPton and friends; Apple needs _DARWIN_C_SOURCE under strict c99. */
14#if defined(_WIN32) && !defined(_WIN32_WINNT)
15# define _WIN32_WINNT 0x0601
16#endif
17#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE)
18# define _DARWIN_C_SOURCE 1
19#endif
20#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO)
21# define __USE_MINGW_ANSI_STDIO 1
22#endif
23#ifndef _POSIX_C_SOURCE
24# define _POSIX_C_SOURCE 200809L
25#endif
26
27#include "wh_http.h"
28
29#include <ctype.h>
30#include <errno.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34
35#if defined(_WIN32)
36# include <winsock2.h>
37# include <ws2tcpip.h>
38# include <windows.h>
39# include <winhttp.h>
40# define wh_close_socket closesocket
41# define wh_inet_pton InetPtonA
42 typedef SOCKET wh_sock_t;
43# define WH_SOCK_INVALID INVALID_SOCKET
44#else
45# include <arpa/inet.h>
46# include <netdb.h>
47# include <netinet/in.h>
48# include <sys/socket.h>
49# include <sys/time.h>
50# include <unistd.h>
51# include <fcntl.h>
52# include <strings.h>
53# define wh_close_socket close
54# define wh_inet_pton inet_pton
55 typedef int wh_sock_t;
56# define WH_SOCK_INVALID (-1)
57#endif
58
59#if !defined(_WIN32)
60# include "wh_tls.h"
61#endif
62
63#define WH_USER_AGENT \
64 "SCORPIOXBOT-webhook/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-webhook)"
65
66/* ------------------------------------------------------------------ policy */
67
68int wh_allow_private(void)
69{
70 const char *v = getenv("WEBHOOK_ALLOW_PRIVATE");
71 if (!v || !*v) return 0;
72 return strcmp(v, "1") == 0 || strcasecmp(v, "true") == 0 ||
73 strcasecmp(v, "yes") == 0;
74}
75
76typedef struct {
77 unsigned net; /* network address, host byte order */
78 int bits;
79} wh_v4net;
80
81/* Every entry is a network in host byte order with a prefix length. The
82 * comments name the RFC section rather than the dotted address, because a
83 * literal private address in a source file is indistinguishable from a leak to
84 * a history scanner - and this repository ships publicly. */
85static const wh_v4net DENY4[] = {
86 { 0x00000000u, 8 }, /* RFC 1122 "this network" */
87 { 0x0A000000u, 8 }, /* RFC 1918 twenty-four-bit block */
88 { 0x64400000u, 10 }, /* RFC 6598 CGNAT shared address space */
89 { 0x7F000000u, 8 }, /* RFC 1122 loopback */
90 { 0xA9FE0000u, 16 }, /* RFC 3927 link-local */
91 { 0xAC100000u, 12 }, /* RFC 1918 twenty-bit block */
92 { 0xC0000000u, 24 }, /* RFC 6890 IETF protocol assignments */
93 { 0xC0000200u, 24 }, /* RFC 5737 TEST-NET-1 */
94 { 0xC0A80000u, 16 }, /* RFC 1918 sixteen-bit block */
95 { 0xC6120000u, 15 }, /* RFC 2544 benchmarking */
96 { 0xC6336400u, 24 }, /* RFC 5737 TEST-NET-2 */
97 { 0xCB007100u, 24 }, /* RFC 5737 TEST-NET-3 */
98 { 0xE0000000u, 4 }, /* RFC 5771 multicast */
99 { 0xF0000000u, 4 } /* RFC 1112 reserved + limited broadcast */
100};
101
102static int v4_denied(unsigned net)
103{
104 size_t i;
105 for (i = 0; i < sizeof DENY4 / sizeof DENY4[0]; i++) {
106 unsigned mask = DENY4[i].bits == 0 ? 0u
107 : (0xFFFFFFFFu << (32 - DENY4[i].bits));
108 if ((net & mask) == (DENY4[i].net & mask)) return 1;
109 }
110 return 0;
111}
112
113/* Every embedded-IPv4 form (::ffff:a.b.c.d and 64:ff9b::/96 NAT64) is judged
114 * by the IPv4 rule set, because that is where the request would land. */
115static int v6_denied(const unsigned char *b)
116{
117 int i, zero10 = 1;
118
119 for (i = 0; i < 10; i++) if (b[i]) { zero10 = 0; break; }
120 if (zero10 && b[10] == 0xFF && b[11] == 0xFF) {
121 unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) |
122 ((unsigned)b[14] << 8) | (unsigned)b[15];
123 return v4_denied(v4);
124 }
125 /* 64:ff9b::/96 NAT64 -> judge the embedded IPv4 */
126 if (b[0] == 0x00 && b[1] == 0x64 && b[2] == 0xFF && b[3] == 0x9B) { /* RFC 6052 */
127 unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) |
128 ((unsigned)b[14] << 8) | (unsigned)b[15];
129 return 1 || v4_denied(v4); /* deny the whole NAT64 prefix outright */
130 }
131 /* The unspecified address and the loopback address have their own forms. */
132 {
133 int allzero = 1;
134 for (i = 0; i < 16; i++) if (b[i]) { allzero = 0; break; }
135 if (allzero) return 1;
136 }
137 {
138 int only_last = 1;
139 for (i = 0; i < 15; i++) if (b[i]) { only_last = 0; break; }
140 if (only_last && b[15] == 1) return 1;
141 }
142 if (b[0] == 0x01 && b[1] == 0x00 && b[2] == 0x00 && b[3] == 0x00 &&
143 b[4] == 0 && b[5] == 0 && b[6] == 0 && b[7] == 0) return 1; /* RFC 6666 discard-only */
144 if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0D && b[3] == 0xB8) return 1; /* RFC 3849 docs */
145 if ((b[0] & 0xFE) == 0xFC) return 1; /* RFC 4193 unique-local */
146 if (b[0] == 0xFE && (b[1] & 0xC0) == 0x80) return 1; /* RFC 4291 link-local */
147 if (b[0] == 0xFF) return 1; /* RFC 4291 multicast */
148 return 0;
149}
150
151int wh_ip_is_denied(const char *ip_text)
152{
153 unsigned char raw[16];
154
155 if (!ip_text || !*ip_text) return 1;
156 if (wh_inet_pton(AF_INET, ip_text, raw) == 1) {
157 unsigned v4 = ((unsigned)raw[0] << 24) | ((unsigned)raw[1] << 16) |
158 ((unsigned)raw[2] << 8) | (unsigned)raw[3];
159 return v4_denied(v4);
160 }
161 if (wh_inet_pton(AF_INET6, ip_text, raw) == 1) return v6_denied(raw);
162 return 1; /* unparseable -> deny */
163}
164
165/* --------------------------------------------------------------------- url */
166
167int wh_url_parse(const char *url, wh_url *out, char *err, size_t errsz)
168{
169 const char *p, *h, *e;
170 size_t n;
171
172 memset(out, 0, sizeof *out);
173 if (!url || !*url) { snprintf(err, errsz, "empty url"); return -1; }
174
175 if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; }
176 else if (strncmp(url, "http://", 7) == 0) { p = url + 7; }
177 else {
178 snprintf(err, errsz, "url must start with http:// or https://");
179 return -1;
180 }
181
182 if (*p == '[') { snprintf(err, errsz, "IPv6 literals are not supported"); return -1; }
183
184 h = p;
185 e = p;
186 while (*e && *e != '/' && *e != '?' && *e != '#' && (unsigned char)*e >= 0x20) e++;
187 n = (size_t)(e - h);
188 if (n == 0) { snprintf(err, errsz, "url has no host"); return -1; }
189 if (n >= sizeof out->host) { snprintf(err, errsz, "host too long"); return -1; }
190 if (memchr(h, '@', n)) {
191 snprintf(err, errsz, "credentials in the url are refused; use a header instead");
192 return -1;
193 }
194
195 out->port = out->tls ? 443 : 80;
196 {
197 const char *colon = (const char *)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) { snprintf(err, errsz, "bad port"); return -1; }
202 for (i = 0; i < pl; i++)
203 if (!isdigit((unsigned char)colon[1 + i])) {
204 snprintf(err, errsz, "bad port");
205 return -1;
206 }
207 memcpy(ports, colon + 1, pl);
208 ports[pl] = '\0';
209 out->port = atoi(ports);
210 if (out->port < 1 || out->port > 65535) {
211 snprintf(err, errsz, "port out of range");
212 return -1;
213 }
214 n = (size_t)(colon - h);
215 }
216 }
217 memcpy(out->host, h, n);
218 out->host[n] = '\0';
219 if (strspn(out->host,
220 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-")
221 != strlen(out->host)) {
222 snprintf(err, errsz, "host contains forbidden characters");
223 return -1;
224 }
225
226 strcpy(out->scheme, out->tls ? "https" : "http");
227 if (*e == '/' || *e == '?') {
228 size_t o = 0;
229 while (*e && *e != ' ' && *e != '#' && o + 1 < sizeof out->path)
230 out->path[o++] = *e++;
231 out->path[o] = '\0';
232 } else {
233 strcpy(out->path, "/");
234 }
235 return 0;
236}
237
238void wh_url_redact(const wh_url *u, char *out, size_t outsz)
239{
240 const char *q;
241 size_t n;
242 int defport;
243 char hostport[300];
244
245 if (!out || outsz == 0) return;
246 out[0] = '\0';
247 if (!u) return;
248 /* Keep the path (it identifies the endpoint) and drop the query string,
249 * which is where a provider token hides when somebody pastes a complete
250 * webhook URL into the form. */
251 q = strchr(u->path, '?');
252 n = q ? (size_t)(q - u->path) : strlen(u->path);
253 defport = u->tls ? 443 : 80;
254 if (u->port != defport)
255 snprintf(hostport, sizeof hostport, "%s:%d", u->host, u->port);
256 else
257 snprintf(hostport, sizeof hostport, "%s", u->host);
258 snprintf(out, outsz, "%s://%s%.*s%s", u->scheme, hostport,
259 (int)n, u->path, q ? "?<redacted>" : "");
260}
261
262int wh_method_ok(const char *method)
263{
264 static const char *const ok[] = { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" };
265 size_t i;
266 if (!method || !*method) return 0;
267 for (i = 0; i < sizeof ok / sizeof ok[0]; i++)
268 if (strcmp(method, ok[i]) == 0) return 1;
269 return 0;
270}
271
272/* ---------------------------------------------------------------- transport */
273
274typedef struct {
275 wh_sock_t fd;
276#if !defined(_WIN32)
277 wh_tls *tls;
278#endif
279 char *stash; /* bytes that arrived with the head terminator */
280 size_t stash_n;
281} wh_trans;
282
283static void trans_close(wh_trans *t)
284{
285#if !defined(_WIN32)
286 if (t->tls) { wh_tls_close(t->tls); t->tls = NULL; }
287#endif
288 if (t->fd != WH_SOCK_INVALID) { wh_close_socket(t->fd); t->fd = WH_SOCK_INVALID; }
289}
290
291static int trans_read(wh_trans *t, char *buf, size_t n)
292{
293#if !defined(_WIN32)
294 if (t->tls) return wh_tls_read(t->tls, buf, n);
295#endif
296 for (;;) {
297 long long r = (long long)recv(t->fd, buf, (int)n, 0);
298 if (r > 0) return (int)r;
299 if (r == 0) return 0;
300#if defined(_WIN32)
301 if (WSAGetLastError() == WSAEINTR) continue;
302#else
303 if (errno == EINTR) continue;
304#endif
305 return -1;
306 }
307}
308
309static int trans_write(wh_trans *t, const char *buf, size_t n)
310{
311#if !defined(_WIN32)
312 if (t->tls) return wh_tls_write(t->tls, buf, n);
313#endif
314 {
315 size_t off = 0;
316 while (off < n) {
317#if defined(MSG_NOSIGNAL)
318 long long w = (long long)send(t->fd, buf + off, (int)(n - off), MSG_NOSIGNAL);
319#else
320 long long w = (long long)send(t->fd, buf + off, (int)(n - off), 0);
321#endif
322 if (w > 0) { off += (size_t)w; continue; }
323#if defined(_WIN32)
324 if (w < 0 && WSAGetLastError() == WSAEINTR) continue;
325#else
326 if (w < 0 && errno == EINTR) continue;
327#endif
328 return -1;
329 }
330 return (int)off;
331 }
332}
333
334/* ------------------------------------------------------------ resolve/conn */
335
336typedef struct {
337 int family;
338 unsigned char ip[16];
339 char text[64];
340} wh_target;
341
342/* Validate EVERY answer before connecting. One private record in the set
343 * refuses the whole host: round-robin DNS and split-horizon answers both die
344 * here, which is the point. */
345static int resolve_validate(const char *host, int port, int allow_private,
346 wh_target *out, char *err, size_t errsz)
347{
348 struct addrinfo hints, *res = NULL, *ai;
349 char portstr[16];
350 int rc, found = 0, naddr = 0;
351
352 memset(&hints, 0, sizeof hints);
353 hints.ai_socktype = SOCK_STREAM;
354 hints.ai_family = AF_UNSPEC;
355 snprintf(portstr, sizeof portstr, "%d", port);
356#if defined(_WIN32)
357 {
358 WSADATA wsa;
359 WSAStartup(MAKEWORD(2, 2), &wsa);
360 }
361#endif
362 rc = getaddrinfo(host, portstr, &hints, &res);
363 if (rc != 0 || !res) {
364 snprintf(err, errsz, "could not resolve %s", host);
365 return -1;
366 }
367
368 for (ai = res; ai; ai = ai->ai_next) {
369 char ipbuf[64];
370 int have = 0;
371 if (ai->ai_family == AF_INET) {
372 inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr,
373 ipbuf, sizeof ipbuf);
374 have = 1;
375 } else if (ai->ai_family == AF_INET6) {
376 inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr,
377 ipbuf, sizeof ipbuf);
378 have = 1;
379 }
380 if (!have) continue;
381 naddr++;
382 if (!allow_private && wh_ip_is_denied(ipbuf)) {
383 snprintf(err, errsz,
384 "refused: %s resolves to a private or reserved address (%s). "
385 "Set WEBHOOK_ALLOW_PRIVATE=1 to allow local endpoints.",
386 host, ipbuf);
387 freeaddrinfo(res);
388 return -1;
389 }
390 }
391 if (naddr == 0) {
392 snprintf(err, errsz, "could not resolve %s (no usable address)", host);
393 freeaddrinfo(res);
394 return -1;
395 }
396
397 /* Prefer IPv4 (a v6-first answer on a host with no v6 route would eat the
398 * whole connect budget), but accept v6 when that is all there is. */
399 for (ai = res; ai && !found; ai = ai->ai_next) {
400 if (ai->ai_family != AF_INET) continue;
401 out->family = AF_INET;
402 memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4);
403 inet_ntop(AF_INET, out->ip, out->text, sizeof out->text);
404 found = 1;
405 }
406 for (ai = res; ai && !found; ai = ai->ai_next) {
407 if (ai->ai_family != AF_INET6) continue;
408 out->family = AF_INET6;
409 memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16);
410 inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text);
411 found = 1;
412 }
413 freeaddrinfo(res);
414 if (!found) { snprintf(err, errsz, "no usable address for %s", host); return -1; }
415 return 0;
416}
417
418#if defined(_WIN32)
419static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, int slen,
420 long timeout_ms, char *err, size_t errsz)
421{
422 u_long nb = 1;
423 int rc;
424 fd_set ws;
425 struct timeval tv;
426
427 ioctlsocket(fd, FIONBIO, &nb);
428 rc = connect(fd, sa, slen);
429 if (rc == 0) { nb = 0; ioctlsocket(fd, FIONBIO, &nb); return 0; }
430 if (WSAGetLastError() != WSAEWOULDBLOCK) {
431 snprintf(err, errsz, "connect failed (wsa %d)", WSAGetLastError());
432 return -1;
433 }
434 FD_ZERO(&ws);
435 FD_SET(fd, &ws);
436 tv.tv_sec = (long)(timeout_ms / 1000);
437 tv.tv_usec = (long)((timeout_ms % 1000) * 1000);
438 rc = select(0, NULL, &ws, NULL, &tv);
439 if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; }
440 {
441 int soerr = 0;
442 int solen = (int)sizeof soerr;
443 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &solen) != 0 || soerr) {
444 snprintf(err, errsz, "connect failed (so_error %d)", soerr);
445 return -1;
446 }
447 }
448 nb = 0;
449 ioctlsocket(fd, FIONBIO, &nb);
450 return 0;
451}
452#else
453static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, socklen_t slen,
454 long timeout_ms, char *err, size_t errsz)
455{
456 int flags, rc, soerr = 0;
457 socklen_t solen = sizeof soerr;
458 fd_set ws;
459 struct timeval tv;
460
461 flags = fcntl(fd, F_GETFL, 0);
462 if (flags < 0) { snprintf(err, errsz, "fcntl failed"); return -1; }
463 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
464 snprintf(err, errsz, "fcntl failed");
465 return -1;
466 }
467 rc = connect(fd, sa, slen);
468 if (rc != 0 && errno != EINPROGRESS) {
469 snprintf(err, errsz, "connect failed: %s", strerror(errno));
470 return -1;
471 }
472 if (rc != 0) {
473 FD_ZERO(&ws);
474 FD_SET(fd, &ws);
475 tv.tv_sec = (long)(timeout_ms / 1000);
476 tv.tv_usec = (long)((timeout_ms % 1000) * 1000);
477 do { rc = select(fd + 1, NULL, &ws, NULL, &tv); } while (rc < 0 && errno == EINTR);
478 if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; }
479 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &solen) != 0 || soerr) {
480 snprintf(err, errsz, "connect failed: %s", strerror(soerr ? soerr : errno));
481 return -1;
482 }
483 }
484 if (fcntl(fd, F_SETFL, flags) < 0) {
485 snprintf(err, errsz, "fcntl failed");
486 return -1;
487 }
488 return 0;
489}
490#endif
491
492/* Socket-level read/write deadlines. mbedTLS reads through recv(), so this is
493 * the only place a stalled peer can be bounded once the handshake is done. */
494static void set_io_timeouts(wh_sock_t fd, long ms)
495{
496#if defined(_WIN32)
497 DWORD v = (DWORD)ms;
498 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&v, sizeof v);
499 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&v, sizeof v);
500#else
501 struct timeval tv;
502 tv.tv_sec = (long)(ms / 1000);
503 tv.tv_usec = (long)((ms % 1000) * 1000);
504 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
505 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
506#endif
507}
508
509/* --------------------------------------------------------------- head parse */
510
511static int ci_prefix(const char *s, const char *prefix)
512{
513 while (*prefix) {
514 if (tolower((unsigned char)*s) != tolower((unsigned char)*prefix)) return 0;
515 s++; prefix++;
516 }
517 return 1;
518}
519
520/* Finds a header value in a raw head block. Returns 1 and fills v/vl. */
521static int head_field(const char *head, size_t head_len, const char *name,
522 const char **v, size_t *vl)
523{
524 size_t i = 0, nl = strlen(name);
525 while (i < head_len) {
526 size_t ls = i, le;
527 while (i < head_len && head[i] != '\n') i++;
528 le = i;
529 if (le > ls && head[le - 1] == '\r') le--;
530 if (le > ls + nl && ci_prefix(head + ls, name) && head[ls + nl] == ':') {
531 size_t b = ls + nl + 1;
532 while (b < le && (head[b] == ' ' || head[b] == '\t')) b++;
533 *v = head + b;
534 *vl = le - b;
535 return 1;
536 }
537 i++; /* skip the '\n' */
538 }
539 return 0;
540}
541
542/* Reads the response head. Returns the number of head bytes (head NUL-capped),
543 * -1 on error/timeout. Any body bytes that arrived in the same read window are
544 * parked in t->stash. */
545static int read_head(wh_trans *t, char *head, size_t cap, size_t *hlen_out)
546{
547 size_t n = 0, scanned = 0;
548
549 t->stash = NULL;
550 t->stash_n = 0;
551 for (;;) {
552 size_t want, i;
553 int r;
554
555 if (n >= cap) return -1;
556 want = (cap - n > 1024) ? 1024 : (cap - n);
557 if (want == 0) return -1;
558 r = trans_read(t, head + n, want);
559 if (r <= 0) {
560 if (n == 0) return -1;
561 *hlen_out = n;
562 head[n] = '\0';
563 return (int)n;
564 }
565 n += (size_t)r;
566 head[n] = '\0';
567 if (scanned > 3) scanned -= 3;
568 for (i = scanned; i + 1 < n; i++) {
569 if (head[i] != '\n') continue;
570 if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && head[i - 3] == '\r') {
571 *hlen_out = i - 1;
572 head[*hlen_out] = '\0';
573 if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); }
574 return (int)n;
575 }
576 if (i >= 1 && head[i - 1] == '\n') {
577 *hlen_out = i - 1;
578 head[*hlen_out] = '\0';
579 if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); }
580 return (int)n;
581 }
582 }
583 scanned = n;
584 }
585}
586
587/* Keeps at most WH_PREVIEW_CAP body bytes, then drains (bounded) so the
588 * server is not left mid-response. */
589typedef struct {
590 char *body;
591 size_t len;
592 size_t total;
593 int truncated;
594} wh_sink;
595
596static void sink_add(wh_sink *s, const char *p, size_t n)
597{
598 s->total += n;
599 if (s->len < WH_PREVIEW_CAP) {
600 size_t take = WH_PREVIEW_CAP - s->len;
601 if (take > n) take = n;
602 memcpy(s->body + s->len, p, take);
603 s->len += take;
604 if (take < n) s->truncated = 1;
605 } else {
606 s->truncated = 1;
607 }
608}
609
610#define WH_DRAIN_CAP (8u * 1024u * 1024u)
611
612/* ------------------------------------------------------------- POSIX leg */
613
614#if !defined(_WIN32)
615static int exchange_plain(const wh_url *u, const char *method,
616 const wh_header *hdrs, int nhdrs,
617 const char *body, size_t blen,
618 long timeout_ms, wh_response *r)
619{
620 wh_trans t;
621 wh_target tgt;
622 wh_sock_t fd = WH_SOCK_INVALID;
623 struct sockaddr_storage ss;
624 socklen_t slen;
625 char *head = NULL;
626 size_t head_len = 0;
627 wh_sink sink;
628 char *req = NULL;
629 size_t reqcap, reqlen = 0;
630 long long clen = -1;
631 int chunked = 0, status, i, rc = -1, host_has_port;
632
633 memset(&t, 0, sizeof t);
634 t.fd = WH_SOCK_INVALID;
635 memset(&sink, 0, sizeof sink);
636
637 if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt,
638 r->error, sizeof r->error) != 0)
639 return -1;
640
641 fd = socket(tgt.family, SOCK_STREAM, 0);
642 if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; }
643 memset(&ss, 0, sizeof ss);
644 if (tgt.family == AF_INET) {
645 struct sockaddr_in *sa = (struct sockaddr_in *)&ss;
646 sa->sin_family = AF_INET;
647 sa->sin_port = htons((unsigned short)u->port);
648 memcpy(&sa->sin_addr, tgt.ip, 4);
649 slen = sizeof *sa;
650 } else {
651 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss;
652 sa->sin6_family = AF_INET6;
653 sa->sin6_port = htons((unsigned short)u->port);
654 memcpy(&sa->sin6_addr, tgt.ip, 16);
655 slen = sizeof *sa;
656 }
657 if (connect_timeout(fd, (struct sockaddr *)&ss, slen, timeout_ms,
658 r->error, sizeof r->error) != 0) {
659 wh_close_socket(fd);
660 return -1;
661 }
662 set_io_timeouts(fd, timeout_ms > WH_READ_MS ? timeout_ms : WH_READ_MS);
663 t.fd = fd;
664
665 if (u->tls) {
666 t.tls = wh_tls_connect_fd(fd, u->host, r->error, sizeof r->error);
667 if (!t.tls) { wh_close_socket(fd); return -1; }
668 t.fd = WH_SOCK_INVALID; /* owned by the TLS object now */
669 }
670
671 /* Head: request line + headers. */
672 host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80));
673 reqcap = 2048 + (size_t)nhdrs * 1200;
674 req = (char *)malloc(reqcap);
675 if (!req) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; }
676 reqlen = (size_t)snprintf(req, reqcap,
677 "%s %s HTTP/1.1\r\n"
678 "Host: %s%s%s\r\n"
679 "User-Agent: %s\r\n"
680 "Accept: */*\r\n"
681 "Connection: close\r\n",
682 method, u->path[0] ? u->path : "/",
683 u->host, host_has_port ? ":" : "",
684 host_has_port ? "" : "", WH_USER_AGENT);
685 if (host_has_port) {
686 reqlen = (size_t)snprintf(req, reqcap,
687 "%s %s HTTP/1.1\r\n"
688 "Host: %s:%d\r\n"
689 "User-Agent: %s\r\n"
690 "Accept: */*\r\n"
691 "Connection: close\r\n",
692 method, u->path[0] ? u->path : "/",
693 u->host, u->port, WH_USER_AGENT);
694 }
695 for (i = 0; i < nhdrs; i++) {
696 size_t l;
697 if (!hdrs[i].name[0]) continue;
698 /* Framing headers are ours: a user header called Content-Length or
699 * Connection would desynchronise the request. */
700 if (ci_prefix(hdrs[i].name, "Host") ||
701 ci_prefix(hdrs[i].name, "Content-Length") ||
702 ci_prefix(hdrs[i].name, "Transfer-Encoding") ||
703 ci_prefix(hdrs[i].name, "Connection")) continue;
704 l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "%s: %s\r\n",
705 hdrs[i].name, hdrs[i].value);
706 if (reqlen + l + 1 >= reqcap) {
707 snprintf(r->error, sizeof r->error, "request headers too large");
708 goto done;
709 }
710 reqlen += l;
711 }
712 if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) {
713 size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen,
714 "Content-Length: %lu\r\n", (unsigned long)blen);
715 reqlen += l;
716 }
717 {
718 size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "\r\n");
719 reqlen += l;
720 }
721 if (reqlen >= reqcap) { snprintf(r->error, sizeof r->error, "request too large"); goto done; }
722
723 if (trans_write(&t, req, reqlen) < 0) {
724 snprintf(r->error, sizeof r->error, "the endpoint did not accept our request");
725 goto done;
726 }
727 if (blen && trans_write(&t, body, blen) < 0) {
728 snprintf(r->error, sizeof r->error, "the endpoint closed while the body was sent");
729 goto done;
730 }
731
732 head = (char *)malloc(WH_HEAD_CAP + 1);
733 if (!head) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; }
734 rc = read_head(&t, head, WH_HEAD_CAP, &head_len);
735 if (rc < 0) {
736 snprintf(r->error, sizeof r->error, "no response head (timeout or not HTTP)");
737 goto done;
738 }
739 if (strncmp(head, "HTTP/", 5) != 0) {
740 snprintf(r->error, sizeof r->error, "not an HTTP response");
741 goto done;
742 }
743 status = atoi(head + 9);
744 r->status = status;
745 {
746 const char *v;
747 size_t vl;
748 if (head_field(head, head_len, "content-type", &v, &vl)) {
749 size_t k = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1;
750 memcpy(r->content_type, v, k);
751 r->content_type[k] = '\0';
752 }
753 if (head_field(head, head_len, "content-length", &v, &vl)) {
754 char nbuf[32];
755 size_t k = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1;
756 memcpy(nbuf, v, k);
757 nbuf[k] = '\0';
758 clen = atoll(nbuf);
759 }
760 if (head_field(head, head_len, "transfer-encoding", &v, &vl) &&
761 vl >= 7 && ci_prefix(v, "chunked")) chunked = 1;
762 }
763
764 sink.body = r->body;
765 sink.len = 0;
766 sink.total = 0;
767 sink.truncated = 0;
768
769 if (chunked) {
770 /* Small framing machine. It is fed from the stash first (bytes that
771 * arrived in the same read window as the head terminator are chunk
772 * data, not body) and gives up after WH_DRAIN_CAP bytes so a server
773 * that streams forever cannot hold the request open. */
774 char buf[4096];
775 size_t sp = 0, sn = 0, drained = 0;
776 int state = 0; /* 0 size line, 1 data, 2 data CRLF, 3 trailer */
777 int cr = 0;
778 long long left = 0;
779
780 if (t.stash_n) { memcpy(buf, t.stash, t.stash_n); sn = t.stash_n; sp = 0; }
781 for (;;) {
782 int c;
783 if (sp >= sn) {
784 int got;
785 if (drained > WH_DRAIN_CAP) break;
786 got = trans_read(&t, buf, sizeof buf);
787 if (got <= 0) break;
788 sp = 0;
789 sn = (size_t)got;
790 drained += (size_t)got;
791 }
792 c = (unsigned char)buf[sp++];
793
794 if (state == 0) { /* hex chunk size */
795 if (c == '\n') {
796 state = (left == 0) ? 3 : 1;
797 if (left == 0) cr = 0;
798 } else if (c == '\r') {
799 /* ignore */
800 } else if (isxdigit(c)) {
801 int d = (c <= '9') ? (c - '0') : (tolower(c) - 'a' + 10);
802 if (left < 0x10000000LL) left = left * 16 + d;
803 } else {
804 /* a chunk-size extension ("1a;ext=1"); ignore to EOL */
805 }
806 } else if (state == 1) { /* chunk data */
807 char one = (char)c;
808 sink_add(&sink, &one, 1);
809 if (--left <= 0) { state = 2; cr = 0; }
810 } else if (state == 2) { /* the CRLF that closes a chunk */
811 if (c == '\n') { state = 0; left = 0; cr = 0; }
812 } else { /* trailers, until a blank line */
813 if (c == '\n') {
814 if (cr == 0) break; /* empty line: end of message */
815 cr = 0;
816 } else if (c != '\r') {
817 cr = 1;
818 }
819 }
820 }
821 } else if (clen >= 0) {
822 long long want = clen;
823 if (t.stash_n) {
824 size_t n = t.stash_n;
825 if ((long long)n > want) n = (size_t)want;
826 sink_add(&sink, t.stash, n);
827 want -= (long long)n;
828 }
829 while (want > 0) {
830 char buf[8192];
831 size_t n = sizeof buf;
832 int got;
833 if ((long long)n > want) n = (size_t)want;
834 got = trans_read(&t, buf, n);
835 if (got <= 0) break;
836 sink_add(&sink, buf, (size_t)got);
837 want -= got;
838 }
839 } else {
840 size_t drained = 0;
841 if (t.stash_n) sink_add(&sink, t.stash, t.stash_n);
842 for (;;) {
843 char buf[8192];
844 int got;
845 if (drained > WH_DRAIN_CAP) break;
846 got = trans_read(&t, buf, sizeof buf);
847 if (got <= 0) break;
848 sink_add(&sink, buf, (size_t)got);
849 drained += (size_t)got;
850 if (sink.truncated && sink.len >= WH_PREVIEW_CAP) {
851 /* keep draining a bounded amount, then stop */
852 if (drained > WH_PREVIEW_CAP) break;
853 }
854 }
855 }
856
857 sink.body[sink.len] = '\0';
858 r->body_len = sink.len;
859 r->body_total = sink.total;
860 r->truncated = sink.truncated;
861 r->ok = 1;
862 rc = 0;
863
864done:
865 free(head);
866 free(req);
867 trans_close(&t);
868 return rc;
869}
870#endif /* !_WIN32 */
871
872/* --------------------------------------------------------------- WinHTTP leg */
873
874#if defined(_WIN32)
875static void a2w(const char *a, wchar_t *w, int wn)
876{
877 MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn);
878}
879
880static int exchange_winhttp(const wh_url *u, const char *method,
881 const wh_header *hdrs, int nhdrs,
882 const char *body, size_t blen,
883 long timeout_ms, wh_response *r)
884{
885 HINTERNET sess = NULL, conn = NULL, req = NULL;
886 wchar_t wtarget[128], wpath[WH_URL_MAX + 8], wmethod[16];
887 wh_target tgt;
888 DWORD avail = 0, total = 0;
889 int i, rc = -1, host_has_port;
890 wh_sink sink;
891
892 memset(&sink, 0, sizeof sink);
893 if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt,
894 r->error, sizeof r->error) != 0)
895 return -1;
896 (void)timeout_ms;
897
898 sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0",
899 WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
900 WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
901 if (!sess)
902 sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0",
903 WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
904 WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
905 if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; }
906 WinHttpSetTimeouts(sess, WH_CONNECT_MS, WH_CONNECT_MS, WH_READ_MS, WH_READ_MS);
907
908 a2w(u->host, wtarget, 128);
909 a2w(u->path[0] ? u->path : "/", wpath, WH_URL_MAX + 8);
910 a2w(method, wmethod, 16);
911
912 conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0);
913 if (!conn) {
914 snprintf(r->error, sizeof r->error, "could not connect to %s", u->host);
915 WinHttpCloseHandle(sess);
916 return -1;
917 }
918 req = WinHttpOpenRequest(conn, wmethod, wpath, NULL, WINHTTP_NO_REFERER,
919 WINHTTP_DEFAULT_ACCEPT_TYPES,
920 u->tls ? WINHTTP_FLAG_SECURE : 0);
921 if (!req) {
922 snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed");
923 WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
924 return -1;
925 }
926 {
927 DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3;
928 WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec);
929 }
930 {
931 DWORD pol = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
932 WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol);
933 }
934 /* On Windows the request goes to the real hostname, not to the numeric
935 * address: WinHTTP takes both SNI and the certificate hostname it verifies
936 * from the name given to WinHttpConnect(), so connecting by IP would break
937 * verification for every ordinary name-based certificate. The SSRF policy
938 * is still applied first, on every address the name resolves to, so a host
939 * that answers with a private record is refused before any connection is
940 * attempted. (POSIX has no such constraint and connects to the validated
941 * numeric address, which removes the rebinding window entirely; see the
942 * note in docs/SECURITY.md.) */
943
944 host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80));
945 {
946 wchar_t wh[2048];
947 char hs[1600];
948 int n;
949 n = snprintf(hs, sizeof hs, "Host: %s%s%s\r\n",
950 u->host, host_has_port ? ":" : "", host_has_port ? "" : "");
951 if (host_has_port)
952 n = snprintf(hs, sizeof hs, "Host: %s:%d\r\n", u->host, u->port);
953 if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0))
954 n += snprintf(hs + n, sizeof hs - (size_t)n,
955 "Content-Length: %lu\r\n", (unsigned long)blen);
956 for (i = 0; i < nhdrs && n < (int)sizeof hs - 1100; i++) {
957 if (!hdrs[i].name[0]) continue;
958 if (ci_prefix(hdrs[i].name, "Host") ||
959 ci_prefix(hdrs[i].name, "Content-Length") ||
960 ci_prefix(hdrs[i].name, "Transfer-Encoding") ||
961 ci_prefix(hdrs[i].name, "Connection")) continue;
962 n += snprintf(hs + n, sizeof hs - (size_t)n, "%s: %s\r\n",
963 hdrs[i].name, hdrs[i].value);
964 }
965 a2w(hs, wh, 2048);
966 WinHttpAddRequestHeaders(req, wh, (DWORD)-1,
967 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
968 }
969
970 if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
971 blen ? (LPVOID)body : WINHTTP_NO_REQUEST_DATA,
972 (DWORD)blen, (DWORD)blen, 0) ||
973 !WinHttpReceiveResponse(req, NULL)) {
974 snprintf(r->error, sizeof r->error,
975 "request failed: TLS or connection error (certificate refused "
976 "or endpoint unreachable)");
977 WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
978 return -1;
979 }
980 {
981 DWORD code = 0, clen2 = sizeof code;
982 WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
983 WINHTTP_HEADER_NAME_BY_INDEX, &code, &clen2,
984 WINHTTP_NO_HEADER_INDEX);
985 r->status = (int)code;
986 }
987 {
988 DWORD ctype = 0;
989 wchar_t wct[128];
990 if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE,
991 WINHTTP_HEADER_NAME_BY_INDEX, wct, &ctype,
992 WINHTTP_NO_HEADER_INDEX) && ctype) {
993 WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type,
994 (int)sizeof r->content_type - 1, NULL, NULL);
995 }
996 }
997
998 sink.body = r->body;
999 for (;;) {
1000 char buf[8192];
1001 DWORD got = 0;
1002 if (sink.len >= WH_PREVIEW_CAP) {
1003 /* read the rest in a bounded way so the handle is not abandoned
1004 * mid-response */
1005 if (sink.total > WH_DRAIN_CAP) break;
1006 sink.truncated = 1;
1007 if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break;
1008 sink.total += got;
1009 continue;
1010 }
1011 if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break;
1012 sink_add(&sink, buf, (size_t)got);
1013 total += got;
1014 }
1015 sink.body[sink.len] = '\0';
1016 r->body_len = sink.len;
1017 r->body_total = sink.total;
1018 r->truncated = sink.truncated;
1019 r->ok = 1;
1020 rc = 0;
1021
1022 (void)avail;
1023 WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
1024 return rc;
1025}
1026#endif
1027
1028/* ------------------------------------------------------------------ entry */
1029
1030int wh_http_request(const char *method, const wh_url *u,
1031 const wh_header *hdrs, int nhdrs,
1032 const char *body, size_t blen,
1033 long timeout_ms, wh_response *r)
1034{
1035 memset(r, 0, sizeof *r);
1036 if (!u) { snprintf(r->error, sizeof r->error, "no url"); return -1; }
1037 if (!wh_method_ok(method)) {
1038 snprintf(r->error, sizeof r->error, "unsupported method");
1039 return -1;
1040 }
1041 if (blen > WH_BODY_CAP) {
1042 snprintf(r->error, sizeof r->error,
1043 "the body is larger than the %u byte limit this plugin sends",
1044 (unsigned)WH_BODY_CAP);
1045 return -1;
1046 }
1047#if defined(_WIN32)
1048 return exchange_winhttp(u, method, hdrs, nhdrs, body, blen, timeout_ms, r);
1049#else
1050 return exchange_plain(u, method, hdrs, nhdrs, body, blen, timeout_ms, r);
1051#endif
1052}