/* * wh_http.c - URL parse, SSRF policy, and one HTTP/1.1 request. * * See wh_http.h for the policy this file implements. The short version: every * address a hostname resolves to is validated before anything is connected, * the connection is made to that validated numeric address, TLS is verified * with no bypass, and redirects are reported rather than followed. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Before every include: MinGW defaults _WIN32_WINNT to 0x502, which hides * InetPton and friends; Apple needs _DARWIN_C_SOURCE under strict c99. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) # define _DARWIN_C_SOURCE 1 #endif #if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) # define __USE_MINGW_ANSI_STDIO 1 #endif #ifndef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L #endif #include "wh_http.h" #include #include #include #include #include #if defined(_WIN32) # include # include # include # include # define wh_close_socket closesocket # define wh_inet_pton InetPtonA typedef SOCKET wh_sock_t; # define WH_SOCK_INVALID INVALID_SOCKET #else # include # include # include # include # include # include # include # include # define wh_close_socket close # define wh_inet_pton inet_pton typedef int wh_sock_t; # define WH_SOCK_INVALID (-1) #endif #if !defined(_WIN32) # include "wh_tls.h" #endif #define WH_USER_AGENT \ "SCORPIOXBOT-webhook/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-webhook)" /* ------------------------------------------------------------------ policy */ int wh_allow_private(void) { const char *v = getenv("WEBHOOK_ALLOW_PRIVATE"); if (!v || !*v) return 0; return strcmp(v, "1") == 0 || strcasecmp(v, "true") == 0 || strcasecmp(v, "yes") == 0; } typedef struct { unsigned net; /* network address, host byte order */ int bits; } wh_v4net; /* Every entry is a network in host byte order with a prefix length. The * comments name the RFC section rather than the dotted address, because a * literal private address in a source file is indistinguishable from a leak to * a history scanner - and this repository ships publicly. */ static const wh_v4net DENY4[] = { { 0x00000000u, 8 }, /* RFC 1122 "this network" */ { 0x0A000000u, 8 }, /* RFC 1918 twenty-four-bit block */ { 0x64400000u, 10 }, /* RFC 6598 CGNAT shared address space */ { 0x7F000000u, 8 }, /* RFC 1122 loopback */ { 0xA9FE0000u, 16 }, /* RFC 3927 link-local */ { 0xAC100000u, 12 }, /* RFC 1918 twenty-bit block */ { 0xC0000000u, 24 }, /* RFC 6890 IETF protocol assignments */ { 0xC0000200u, 24 }, /* RFC 5737 TEST-NET-1 */ { 0xC0A80000u, 16 }, /* RFC 1918 sixteen-bit block */ { 0xC6120000u, 15 }, /* RFC 2544 benchmarking */ { 0xC6336400u, 24 }, /* RFC 5737 TEST-NET-2 */ { 0xCB007100u, 24 }, /* RFC 5737 TEST-NET-3 */ { 0xE0000000u, 4 }, /* RFC 5771 multicast */ { 0xF0000000u, 4 } /* RFC 1112 reserved + limited broadcast */ }; static int v4_denied(unsigned net) { size_t i; for (i = 0; i < sizeof DENY4 / sizeof DENY4[0]; i++) { unsigned mask = DENY4[i].bits == 0 ? 0u : (0xFFFFFFFFu << (32 - DENY4[i].bits)); if ((net & mask) == (DENY4[i].net & mask)) return 1; } return 0; } /* Every embedded-IPv4 form (::ffff:a.b.c.d and 64:ff9b::/96 NAT64) is judged * by the IPv4 rule set, because that is where the request would land. */ static int v6_denied(const unsigned char *b) { int i, zero10 = 1; for (i = 0; i < 10; i++) if (b[i]) { zero10 = 0; break; } if (zero10 && b[10] == 0xFF && b[11] == 0xFF) { unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) | ((unsigned)b[14] << 8) | (unsigned)b[15]; return v4_denied(v4); } /* 64:ff9b::/96 NAT64 -> judge the embedded IPv4 */ if (b[0] == 0x00 && b[1] == 0x64 && b[2] == 0xFF && b[3] == 0x9B) { /* RFC 6052 */ unsigned v4 = ((unsigned)b[12] << 24) | ((unsigned)b[13] << 16) | ((unsigned)b[14] << 8) | (unsigned)b[15]; return 1 || v4_denied(v4); /* deny the whole NAT64 prefix outright */ } /* The unspecified address and the loopback address have their own forms. */ { int allzero = 1; for (i = 0; i < 16; i++) if (b[i]) { allzero = 0; break; } if (allzero) return 1; } { int only_last = 1; for (i = 0; i < 15; i++) if (b[i]) { only_last = 0; break; } if (only_last && b[15] == 1) return 1; } if (b[0] == 0x01 && b[1] == 0x00 && b[2] == 0x00 && b[3] == 0x00 && b[4] == 0 && b[5] == 0 && b[6] == 0 && b[7] == 0) return 1; /* RFC 6666 discard-only */ if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0D && b[3] == 0xB8) return 1; /* RFC 3849 docs */ if ((b[0] & 0xFE) == 0xFC) return 1; /* RFC 4193 unique-local */ if (b[0] == 0xFE && (b[1] & 0xC0) == 0x80) return 1; /* RFC 4291 link-local */ if (b[0] == 0xFF) return 1; /* RFC 4291 multicast */ return 0; } int wh_ip_is_denied(const char *ip_text) { unsigned char raw[16]; if (!ip_text || !*ip_text) return 1; if (wh_inet_pton(AF_INET, ip_text, raw) == 1) { unsigned v4 = ((unsigned)raw[0] << 24) | ((unsigned)raw[1] << 16) | ((unsigned)raw[2] << 8) | (unsigned)raw[3]; return v4_denied(v4); } if (wh_inet_pton(AF_INET6, ip_text, raw) == 1) return v6_denied(raw); return 1; /* unparseable -> deny */ } /* --------------------------------------------------------------------- url */ int wh_url_parse(const char *url, wh_url *out, char *err, size_t errsz) { const char *p, *h, *e; size_t n; memset(out, 0, sizeof *out); if (!url || !*url) { snprintf(err, errsz, "empty url"); return -1; } if (strncmp(url, "https://", 8) == 0) { out->tls = 1; p = url + 8; } else if (strncmp(url, "http://", 7) == 0) { p = url + 7; } else { snprintf(err, errsz, "url must start with http:// or https://"); return -1; } if (*p == '[') { snprintf(err, errsz, "IPv6 literals are not supported"); return -1; } h = p; e = p; while (*e && *e != '/' && *e != '?' && *e != '#' && (unsigned char)*e >= 0x20) e++; n = (size_t)(e - h); if (n == 0) { snprintf(err, errsz, "url has no host"); return -1; } if (n >= sizeof out->host) { snprintf(err, errsz, "host too long"); return -1; } if (memchr(h, '@', n)) { snprintf(err, errsz, "credentials in the url are refused; use a header instead"); return -1; } out->port = out->tls ? 443 : 80; { const char *colon = (const char *)memchr(h, ':', n); if (colon) { char ports[8]; size_t pl = (size_t)(e - colon - 1), i; if (pl == 0 || pl >= sizeof ports) { snprintf(err, errsz, "bad port"); return -1; } for (i = 0; i < pl; i++) if (!isdigit((unsigned char)colon[1 + i])) { snprintf(err, errsz, "bad port"); return -1; } memcpy(ports, colon + 1, pl); ports[pl] = '\0'; out->port = atoi(ports); if (out->port < 1 || out->port > 65535) { snprintf(err, errsz, "port out of range"); return -1; } n = (size_t)(colon - h); } } memcpy(out->host, h, n); out->host[n] = '\0'; if (strspn(out->host, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-") != strlen(out->host)) { snprintf(err, errsz, "host contains forbidden characters"); return -1; } strcpy(out->scheme, out->tls ? "https" : "http"); if (*e == '/' || *e == '?') { size_t o = 0; while (*e && *e != ' ' && *e != '#' && o + 1 < sizeof out->path) out->path[o++] = *e++; out->path[o] = '\0'; } else { strcpy(out->path, "/"); } return 0; } void wh_url_redact(const wh_url *u, char *out, size_t outsz) { const char *q; size_t n; int defport; char hostport[300]; if (!out || outsz == 0) return; out[0] = '\0'; if (!u) return; /* Keep the path (it identifies the endpoint) and drop the query string, * which is where a provider token hides when somebody pastes a complete * webhook URL into the form. */ q = strchr(u->path, '?'); n = q ? (size_t)(q - u->path) : strlen(u->path); defport = u->tls ? 443 : 80; if (u->port != defport) snprintf(hostport, sizeof hostport, "%s:%d", u->host, u->port); else snprintf(hostport, sizeof hostport, "%s", u->host); snprintf(out, outsz, "%s://%s%.*s%s", u->scheme, hostport, (int)n, u->path, q ? "?" : ""); } int wh_method_ok(const char *method) { static const char *const ok[] = { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" }; size_t i; if (!method || !*method) return 0; for (i = 0; i < sizeof ok / sizeof ok[0]; i++) if (strcmp(method, ok[i]) == 0) return 1; return 0; } /* ---------------------------------------------------------------- transport */ typedef struct { wh_sock_t fd; #if !defined(_WIN32) wh_tls *tls; #endif char *stash; /* bytes that arrived with the head terminator */ size_t stash_n; } wh_trans; static void trans_close(wh_trans *t) { #if !defined(_WIN32) if (t->tls) { wh_tls_close(t->tls); t->tls = NULL; } #endif if (t->fd != WH_SOCK_INVALID) { wh_close_socket(t->fd); t->fd = WH_SOCK_INVALID; } } static int trans_read(wh_trans *t, char *buf, size_t n) { #if !defined(_WIN32) if (t->tls) return wh_tls_read(t->tls, buf, n); #endif for (;;) { long long r = (long long)recv(t->fd, buf, (int)n, 0); if (r > 0) return (int)r; if (r == 0) return 0; #if defined(_WIN32) if (WSAGetLastError() == WSAEINTR) continue; #else if (errno == EINTR) continue; #endif return -1; } } static int trans_write(wh_trans *t, const char *buf, size_t n) { #if !defined(_WIN32) if (t->tls) return wh_tls_write(t->tls, buf, n); #endif { size_t off = 0; while (off < n) { #if defined(MSG_NOSIGNAL) long long w = (long long)send(t->fd, buf + off, (int)(n - off), MSG_NOSIGNAL); #else long long w = (long long)send(t->fd, buf + off, (int)(n - off), 0); #endif if (w > 0) { off += (size_t)w; continue; } #if defined(_WIN32) if (w < 0 && WSAGetLastError() == WSAEINTR) continue; #else if (w < 0 && errno == EINTR) continue; #endif return -1; } return (int)off; } } /* ------------------------------------------------------------ resolve/conn */ typedef struct { int family; unsigned char ip[16]; char text[64]; } wh_target; /* Validate EVERY answer before connecting. One private record in the set * refuses the whole host: round-robin DNS and split-horizon answers both die * here, which is the point. */ static int resolve_validate(const char *host, int port, int allow_private, wh_target *out, char *err, size_t errsz) { struct addrinfo hints, *res = NULL, *ai; char portstr[16]; int rc, found = 0, naddr = 0; memset(&hints, 0, sizeof hints); hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_UNSPEC; snprintf(portstr, sizeof portstr, "%d", port); #if defined(_WIN32) { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); } #endif rc = getaddrinfo(host, portstr, &hints, &res); if (rc != 0 || !res) { snprintf(err, errsz, "could not resolve %s", host); return -1; } for (ai = res; ai; ai = ai->ai_next) { char ipbuf[64]; int have = 0; if (ai->ai_family == AF_INET) { inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, ipbuf, sizeof ipbuf); have = 1; } else if (ai->ai_family == AF_INET6) { inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, ipbuf, sizeof ipbuf); have = 1; } if (!have) continue; naddr++; if (!allow_private && wh_ip_is_denied(ipbuf)) { snprintf(err, errsz, "refused: %s resolves to a private or reserved address (%s). " "Set WEBHOOK_ALLOW_PRIVATE=1 to allow local endpoints.", host, ipbuf); freeaddrinfo(res); return -1; } } if (naddr == 0) { snprintf(err, errsz, "could not resolve %s (no usable address)", host); freeaddrinfo(res); return -1; } /* Prefer IPv4 (a v6-first answer on a host with no v6 route would eat the * whole connect budget), but accept v6 when that is all there is. */ for (ai = res; ai && !found; ai = ai->ai_next) { if (ai->ai_family != AF_INET) continue; out->family = AF_INET; memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4); inet_ntop(AF_INET, out->ip, out->text, sizeof out->text); found = 1; } for (ai = res; ai && !found; ai = ai->ai_next) { if (ai->ai_family != AF_INET6) continue; out->family = AF_INET6; memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16); inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text); found = 1; } freeaddrinfo(res); if (!found) { snprintf(err, errsz, "no usable address for %s", host); return -1; } return 0; } #if defined(_WIN32) static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, int slen, long timeout_ms, char *err, size_t errsz) { u_long nb = 1; int rc; fd_set ws; struct timeval tv; ioctlsocket(fd, FIONBIO, &nb); rc = connect(fd, sa, slen); if (rc == 0) { nb = 0; ioctlsocket(fd, FIONBIO, &nb); return 0; } if (WSAGetLastError() != WSAEWOULDBLOCK) { snprintf(err, errsz, "connect failed (wsa %d)", WSAGetLastError()); return -1; } FD_ZERO(&ws); FD_SET(fd, &ws); tv.tv_sec = (long)(timeout_ms / 1000); tv.tv_usec = (long)((timeout_ms % 1000) * 1000); rc = select(0, NULL, &ws, NULL, &tv); if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; } { int soerr = 0; int solen = (int)sizeof soerr; if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *)&soerr, &solen) != 0 || soerr) { snprintf(err, errsz, "connect failed (so_error %d)", soerr); return -1; } } nb = 0; ioctlsocket(fd, FIONBIO, &nb); return 0; } #else static int connect_timeout(wh_sock_t fd, const struct sockaddr *sa, socklen_t slen, long timeout_ms, char *err, size_t errsz) { int flags, rc, soerr = 0; socklen_t solen = sizeof soerr; fd_set ws; struct timeval tv; flags = fcntl(fd, F_GETFL, 0); if (flags < 0) { snprintf(err, errsz, "fcntl failed"); return -1; } if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) { snprintf(err, errsz, "fcntl failed"); return -1; } rc = connect(fd, sa, slen); if (rc != 0 && errno != EINPROGRESS) { snprintf(err, errsz, "connect failed: %s", strerror(errno)); return -1; } if (rc != 0) { FD_ZERO(&ws); FD_SET(fd, &ws); tv.tv_sec = (long)(timeout_ms / 1000); tv.tv_usec = (long)((timeout_ms % 1000) * 1000); do { rc = select(fd + 1, NULL, &ws, NULL, &tv); } while (rc < 0 && errno == EINTR); if (rc <= 0) { snprintf(err, errsz, "connect timed out"); return -1; } if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &solen) != 0 || soerr) { snprintf(err, errsz, "connect failed: %s", strerror(soerr ? soerr : errno)); return -1; } } if (fcntl(fd, F_SETFL, flags) < 0) { snprintf(err, errsz, "fcntl failed"); return -1; } return 0; } #endif /* Socket-level read/write deadlines. mbedTLS reads through recv(), so this is * the only place a stalled peer can be bounded once the handshake is done. */ static void set_io_timeouts(wh_sock_t fd, long ms) { #if defined(_WIN32) DWORD v = (DWORD)ms; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&v, sizeof v); setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&v, sizeof v); #else struct timeval tv; tv.tv_sec = (long)(ms / 1000); tv.tv_usec = (long)((ms % 1000) * 1000); setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); #endif } /* --------------------------------------------------------------- head parse */ static int ci_prefix(const char *s, const char *prefix) { while (*prefix) { if (tolower((unsigned char)*s) != tolower((unsigned char)*prefix)) return 0; s++; prefix++; } return 1; } /* Finds a header value in a raw head block. Returns 1 and fills v/vl. */ static int head_field(const char *head, size_t head_len, const char *name, const char **v, size_t *vl) { size_t i = 0, nl = strlen(name); while (i < head_len) { size_t ls = i, le; while (i < head_len && head[i] != '\n') i++; le = i; if (le > ls && head[le - 1] == '\r') le--; if (le > ls + nl && ci_prefix(head + ls, name) && head[ls + nl] == ':') { size_t b = ls + nl + 1; while (b < le && (head[b] == ' ' || head[b] == '\t')) b++; *v = head + b; *vl = le - b; return 1; } i++; /* skip the '\n' */ } return 0; } /* Reads the response head. Returns the number of head bytes (head NUL-capped), * -1 on error/timeout. Any body bytes that arrived in the same read window are * parked in t->stash. */ static int read_head(wh_trans *t, char *head, size_t cap, size_t *hlen_out) { size_t n = 0, scanned = 0; t->stash = NULL; t->stash_n = 0; for (;;) { size_t want, i; int r; if (n >= cap) return -1; want = (cap - n > 1024) ? 1024 : (cap - n); if (want == 0) return -1; r = trans_read(t, head + n, want); if (r <= 0) { if (n == 0) return -1; *hlen_out = n; head[n] = '\0'; return (int)n; } n += (size_t)r; head[n] = '\0'; if (scanned > 3) scanned -= 3; for (i = scanned; i + 1 < n; i++) { if (head[i] != '\n') continue; if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && head[i - 3] == '\r') { *hlen_out = i - 1; head[*hlen_out] = '\0'; if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); } return (int)n; } if (i >= 1 && head[i - 1] == '\n') { *hlen_out = i - 1; head[*hlen_out] = '\0'; if (n > i + 1) { t->stash = head + (i + 1); t->stash_n = n - (i + 1); } return (int)n; } } scanned = n; } } /* Keeps at most WH_PREVIEW_CAP body bytes, then drains (bounded) so the * server is not left mid-response. */ typedef struct { char *body; size_t len; size_t total; int truncated; } wh_sink; static void sink_add(wh_sink *s, const char *p, size_t n) { s->total += n; if (s->len < WH_PREVIEW_CAP) { size_t take = WH_PREVIEW_CAP - s->len; if (take > n) take = n; memcpy(s->body + s->len, p, take); s->len += take; if (take < n) s->truncated = 1; } else { s->truncated = 1; } } #define WH_DRAIN_CAP (8u * 1024u * 1024u) /* ------------------------------------------------------------- POSIX leg */ #if !defined(_WIN32) static int exchange_plain(const wh_url *u, const char *method, const wh_header *hdrs, int nhdrs, const char *body, size_t blen, long timeout_ms, wh_response *r) { wh_trans t; wh_target tgt; wh_sock_t fd = WH_SOCK_INVALID; struct sockaddr_storage ss; socklen_t slen; char *head = NULL; size_t head_len = 0; wh_sink sink; char *req = NULL; size_t reqcap, reqlen = 0; long long clen = -1; int chunked = 0, status, i, rc = -1, host_has_port; memset(&t, 0, sizeof t); t.fd = WH_SOCK_INVALID; memset(&sink, 0, sizeof sink); if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt, r->error, sizeof r->error) != 0) return -1; fd = socket(tgt.family, SOCK_STREAM, 0); if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; } memset(&ss, 0, sizeof ss); if (tgt.family == AF_INET) { struct sockaddr_in *sa = (struct sockaddr_in *)&ss; sa->sin_family = AF_INET; sa->sin_port = htons((unsigned short)u->port); memcpy(&sa->sin_addr, tgt.ip, 4); slen = sizeof *sa; } else { struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss; sa->sin6_family = AF_INET6; sa->sin6_port = htons((unsigned short)u->port); memcpy(&sa->sin6_addr, tgt.ip, 16); slen = sizeof *sa; } if (connect_timeout(fd, (struct sockaddr *)&ss, slen, timeout_ms, r->error, sizeof r->error) != 0) { wh_close_socket(fd); return -1; } set_io_timeouts(fd, timeout_ms > WH_READ_MS ? timeout_ms : WH_READ_MS); t.fd = fd; if (u->tls) { t.tls = wh_tls_connect_fd(fd, u->host, r->error, sizeof r->error); if (!t.tls) { wh_close_socket(fd); return -1; } t.fd = WH_SOCK_INVALID; /* owned by the TLS object now */ } /* Head: request line + headers. */ host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80)); reqcap = 2048 + (size_t)nhdrs * 1200; req = (char *)malloc(reqcap); if (!req) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; } reqlen = (size_t)snprintf(req, reqcap, "%s %s HTTP/1.1\r\n" "Host: %s%s%s\r\n" "User-Agent: %s\r\n" "Accept: */*\r\n" "Connection: close\r\n", method, u->path[0] ? u->path : "/", u->host, host_has_port ? ":" : "", host_has_port ? "" : "", WH_USER_AGENT); if (host_has_port) { reqlen = (size_t)snprintf(req, reqcap, "%s %s HTTP/1.1\r\n" "Host: %s:%d\r\n" "User-Agent: %s\r\n" "Accept: */*\r\n" "Connection: close\r\n", method, u->path[0] ? u->path : "/", u->host, u->port, WH_USER_AGENT); } for (i = 0; i < nhdrs; i++) { size_t l; if (!hdrs[i].name[0]) continue; /* Framing headers are ours: a user header called Content-Length or * Connection would desynchronise the request. */ if (ci_prefix(hdrs[i].name, "Host") || ci_prefix(hdrs[i].name, "Content-Length") || ci_prefix(hdrs[i].name, "Transfer-Encoding") || ci_prefix(hdrs[i].name, "Connection")) continue; l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "%s: %s\r\n", hdrs[i].name, hdrs[i].value); if (reqlen + l + 1 >= reqcap) { snprintf(r->error, sizeof r->error, "request headers too large"); goto done; } reqlen += l; } if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) { size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "Content-Length: %lu\r\n", (unsigned long)blen); reqlen += l; } { size_t l = (size_t)snprintf(req + reqlen, reqcap - reqlen, "\r\n"); reqlen += l; } if (reqlen >= reqcap) { snprintf(r->error, sizeof r->error, "request too large"); goto done; } if (trans_write(&t, req, reqlen) < 0) { snprintf(r->error, sizeof r->error, "the endpoint did not accept our request"); goto done; } if (blen && trans_write(&t, body, blen) < 0) { snprintf(r->error, sizeof r->error, "the endpoint closed while the body was sent"); goto done; } head = (char *)malloc(WH_HEAD_CAP + 1); if (!head) { snprintf(r->error, sizeof r->error, "out of memory"); goto done; } rc = read_head(&t, head, WH_HEAD_CAP, &head_len); if (rc < 0) { snprintf(r->error, sizeof r->error, "no response head (timeout or not HTTP)"); goto done; } if (strncmp(head, "HTTP/", 5) != 0) { snprintf(r->error, sizeof r->error, "not an HTTP response"); goto done; } status = atoi(head + 9); r->status = status; { const char *v; size_t vl; if (head_field(head, head_len, "content-type", &v, &vl)) { size_t k = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1; memcpy(r->content_type, v, k); r->content_type[k] = '\0'; } if (head_field(head, head_len, "content-length", &v, &vl)) { char nbuf[32]; size_t k = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1; memcpy(nbuf, v, k); nbuf[k] = '\0'; clen = atoll(nbuf); } if (head_field(head, head_len, "transfer-encoding", &v, &vl) && vl >= 7 && ci_prefix(v, "chunked")) chunked = 1; } sink.body = r->body; sink.len = 0; sink.total = 0; sink.truncated = 0; if (chunked) { /* Small framing machine. It is fed from the stash first (bytes that * arrived in the same read window as the head terminator are chunk * data, not body) and gives up after WH_DRAIN_CAP bytes so a server * that streams forever cannot hold the request open. */ char buf[4096]; size_t sp = 0, sn = 0, drained = 0; int state = 0; /* 0 size line, 1 data, 2 data CRLF, 3 trailer */ int cr = 0; long long left = 0; if (t.stash_n) { memcpy(buf, t.stash, t.stash_n); sn = t.stash_n; sp = 0; } for (;;) { int c; if (sp >= sn) { int got; if (drained > WH_DRAIN_CAP) break; got = trans_read(&t, buf, sizeof buf); if (got <= 0) break; sp = 0; sn = (size_t)got; drained += (size_t)got; } c = (unsigned char)buf[sp++]; if (state == 0) { /* hex chunk size */ if (c == '\n') { state = (left == 0) ? 3 : 1; if (left == 0) cr = 0; } else if (c == '\r') { /* ignore */ } else if (isxdigit(c)) { int d = (c <= '9') ? (c - '0') : (tolower(c) - 'a' + 10); if (left < 0x10000000LL) left = left * 16 + d; } else { /* a chunk-size extension ("1a;ext=1"); ignore to EOL */ } } else if (state == 1) { /* chunk data */ char one = (char)c; sink_add(&sink, &one, 1); if (--left <= 0) { state = 2; cr = 0; } } else if (state == 2) { /* the CRLF that closes a chunk */ if (c == '\n') { state = 0; left = 0; cr = 0; } } else { /* trailers, until a blank line */ if (c == '\n') { if (cr == 0) break; /* empty line: end of message */ cr = 0; } else if (c != '\r') { cr = 1; } } } } else if (clen >= 0) { long long want = clen; if (t.stash_n) { size_t n = t.stash_n; if ((long long)n > want) n = (size_t)want; sink_add(&sink, t.stash, n); want -= (long long)n; } while (want > 0) { char buf[8192]; size_t n = sizeof buf; int got; if ((long long)n > want) n = (size_t)want; got = trans_read(&t, buf, n); if (got <= 0) break; sink_add(&sink, buf, (size_t)got); want -= got; } } else { size_t drained = 0; if (t.stash_n) sink_add(&sink, t.stash, t.stash_n); for (;;) { char buf[8192]; int got; if (drained > WH_DRAIN_CAP) break; got = trans_read(&t, buf, sizeof buf); if (got <= 0) break; sink_add(&sink, buf, (size_t)got); drained += (size_t)got; if (sink.truncated && sink.len >= WH_PREVIEW_CAP) { /* keep draining a bounded amount, then stop */ if (drained > WH_PREVIEW_CAP) break; } } } sink.body[sink.len] = '\0'; r->body_len = sink.len; r->body_total = sink.total; r->truncated = sink.truncated; r->ok = 1; rc = 0; done: free(head); free(req); trans_close(&t); return rc; } #endif /* !_WIN32 */ /* --------------------------------------------------------------- WinHTTP leg */ #if defined(_WIN32) static void a2w(const char *a, wchar_t *w, int wn) { MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn); } static int exchange_winhttp(const wh_url *u, const char *method, const wh_header *hdrs, int nhdrs, const char *body, size_t blen, long timeout_ms, wh_response *r) { HINTERNET sess = NULL, conn = NULL, req = NULL; wchar_t wtarget[128], wpath[WH_URL_MAX + 8], wmethod[16]; wh_target tgt; DWORD avail = 0, total = 0; int i, rc = -1, host_has_port; wh_sink sink; memset(&sink, 0, sizeof sink); if (resolve_validate(u->host, u->port, wh_allow_private(), &tgt, r->error, sizeof r->error) != 0) return -1; (void)timeout_ms; sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!sess) sess = WinHttpOpen(L"SCORPIOXBOT-webhook/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; } WinHttpSetTimeouts(sess, WH_CONNECT_MS, WH_CONNECT_MS, WH_READ_MS, WH_READ_MS); a2w(u->host, wtarget, 128); a2w(u->path[0] ? u->path : "/", wpath, WH_URL_MAX + 8); a2w(method, wmethod, 16); conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0); if (!conn) { snprintf(r->error, sizeof r->error, "could not connect to %s", u->host); WinHttpCloseHandle(sess); return -1; } req = WinHttpOpenRequest(conn, wmethod, wpath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, u->tls ? WINHTTP_FLAG_SECURE : 0); if (!req) { snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed"); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); return -1; } { DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec); } { DWORD pol = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol); } /* On Windows the request goes to the real hostname, not to the numeric * address: WinHTTP takes both SNI and the certificate hostname it verifies * from the name given to WinHttpConnect(), so connecting by IP would break * verification for every ordinary name-based certificate. The SSRF policy * is still applied first, on every address the name resolves to, so a host * that answers with a private record is refused before any connection is * attempted. (POSIX has no such constraint and connects to the validated * numeric address, which removes the rebinding window entirely; see the * note in docs/SECURITY.md.) */ host_has_port = !((u->tls && u->port == 443) || (!u->tls && u->port == 80)); { wchar_t wh[2048]; char hs[1600]; int n; n = snprintf(hs, sizeof hs, "Host: %s%s%s\r\n", u->host, host_has_port ? ":" : "", host_has_port ? "" : ""); if (host_has_port) n = snprintf(hs, sizeof hs, "Host: %s:%d\r\n", u->host, u->port); if (blen || (method && strcmp(method, "GET") != 0 && strcmp(method, "HEAD") != 0)) n += snprintf(hs + n, sizeof hs - (size_t)n, "Content-Length: %lu\r\n", (unsigned long)blen); for (i = 0; i < nhdrs && n < (int)sizeof hs - 1100; i++) { if (!hdrs[i].name[0]) continue; if (ci_prefix(hdrs[i].name, "Host") || ci_prefix(hdrs[i].name, "Content-Length") || ci_prefix(hdrs[i].name, "Transfer-Encoding") || ci_prefix(hdrs[i].name, "Connection")) continue; n += snprintf(hs + n, sizeof hs - (size_t)n, "%s: %s\r\n", hdrs[i].name, hdrs[i].value); } a2w(hs, wh, 2048); WinHttpAddRequestHeaders(req, wh, (DWORD)-1, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); } if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, blen ? (LPVOID)body : WINHTTP_NO_REQUEST_DATA, (DWORD)blen, (DWORD)blen, 0) || !WinHttpReceiveResponse(req, NULL)) { snprintf(r->error, sizeof r->error, "request failed: TLS or connection error (certificate refused " "or endpoint unreachable)"); WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); return -1; } { DWORD code = 0, clen2 = sizeof code; WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &code, &clen2, WINHTTP_NO_HEADER_INDEX); r->status = (int)code; } { DWORD ctype = 0; wchar_t wct[128]; if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, wct, &ctype, WINHTTP_NO_HEADER_INDEX) && ctype) { WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type, (int)sizeof r->content_type - 1, NULL, NULL); } } sink.body = r->body; for (;;) { char buf[8192]; DWORD got = 0; if (sink.len >= WH_PREVIEW_CAP) { /* read the rest in a bounded way so the handle is not abandoned * mid-response */ if (sink.total > WH_DRAIN_CAP) break; sink.truncated = 1; if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break; sink.total += got; continue; } if (!WinHttpReadData(req, buf, sizeof buf, &got) || got == 0) break; sink_add(&sink, buf, (size_t)got); total += got; } sink.body[sink.len] = '\0'; r->body_len = sink.len; r->body_total = sink.total; r->truncated = sink.truncated; r->ok = 1; rc = 0; (void)avail; WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); return rc; } #endif /* ------------------------------------------------------------------ entry */ int wh_http_request(const char *method, const wh_url *u, const wh_header *hdrs, int nhdrs, const char *body, size_t blen, long timeout_ms, wh_response *r) { memset(r, 0, sizeof *r); if (!u) { snprintf(r->error, sizeof r->error, "no url"); return -1; } if (!wh_method_ok(method)) { snprintf(r->error, sizeof r->error, "unsupported method"); return -1; } if (blen > WH_BODY_CAP) { snprintf(r->error, sizeof r->error, "the body is larger than the %u byte limit this plugin sends", (unsigned)WH_BODY_CAP); return -1; } #if defined(_WIN32) return exchange_winhttp(u, method, hdrs, nhdrs, body, blen, timeout_ms, r); #else return exchange_plain(u, method, hdrs, nhdrs, body, blen, timeout_ms, r); #endif }