/* * fetch_http.c - URL parsing, SSRF policy, HTTP(S) GET with redirect chain. * * Both platforms: our own getaddrinfo, per-address SSRF validation, then the * socket is connected to the EXACT validated numeric address (never the * hostname), so a rebinding DNS server cannot answer a private IP between * the check and the connect. TLS on POSIX is vendored mbedTLS over our own * socket (fetch_tls.c); on _WIN32 the exchange runs over WinHTTP with the * resolution pinned through WINHTTP_OPTION_RESOLVE_TIMEOUT-era connection * semantics by connecting to the numeric IP while sending the real Host * header and SNI name (https). * * Every redirect hop re-enters the same parse/resolve/validate path, up to * FX_MAX_REDIRECTS. No TLS bypass exists. */ /* The feature-test macros must precede every include (netdb/inet functions, * POSIX sockets). _WIN32_WINNT likewise precedes winsock2.h: MinGW defaults * it to 0x0502, which hides InetPtonA and inet_ntop - both of which the SSRF * validator needs - behind a Windows Vista gate. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) # define _POSIX_C_SOURCE 200809L #endif #include "fetch_http.h" #include #include #include #include #include #include #include #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include # include # include # include typedef SOCKET sx_sock; # define SX_SOCK_INVALID INVALID_SOCKET # define sx_closesocket closesocket #else # ifndef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # include # include # include # include # include # include # include # include # include # include typedef int sx_sock; # define SX_SOCK_INVALID (-1) # define sx_closesocket close #endif #include "fetch_tls.h" #include "fetch_md.h" #ifdef HAVE_ZLIB # include #endif /* Persisted policy hook (implemented in plugin_fetch.c). */ extern int fx_policy_allow_private(void); char *fx_strndup(const char *s, size_t n) { char *p; if (!s || !n) { p = (char *)sx_malloc(1); p[0] = '\0'; return p; } p = (char *)sx_malloc(n + 1); memcpy(p, s, n); p[n] = '\0'; return p; } long long fx_now_ms(void) { #if defined(_WIN32) static LARGE_INTEGER freq; LARGE_INTEGER t; if (!freq.QuadPart) QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&t); return (long long)(t.QuadPart / (freq.QuadPart / 1000)); #else struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; #endif } /* ------------------------------------------------------------------ */ /* URL parsing */ /* ------------------------------------------------------------------ */ typedef struct { char scheme[8]; /* http | https */ char host[256]; int port; char path[2048]; /* path?query, always starts with '/' */ } fx_url; static int parse_port(const char *s, const char *end, int *port_out) { long pl = 0; const char *p = s; if (p == end) return -1; for (; p < end; p++) { if (!isdigit((unsigned char)*p)) return -1; pl = pl * 10 + (*p - '0'); if (pl > 65535) return -1; } if (pl <= 0) return -1; *port_out = (int)pl; return 0; } static int fx_url_parse(const char *url, fx_url *u, char *err, size_t errsz) { const char *p = url, *sc_end, *host_start, *host_end; size_t n; memset(u, 0, sizeof *u); if (strlen(url) >= sizeof(u->host) + 2300) { snprintf(err, errsz, "invalid URL (too long)"); return -1; } sc_end = strstr(p, "://"); if (!sc_end) { snprintf(err, errsz, "invalid URL (no scheme)"); return -1; } n = (size_t)(sc_end - p); if (n == 0 || n >= sizeof u->scheme) { snprintf(err, errsz, "invalid URL (scheme)"); return -1; } for (size_t i = 0; i < n; i++) u->scheme[i] = (char)tolower((unsigned char)p[i]); u->scheme[n] = '\0'; if (strcmp(u->scheme, "http") != 0 && strcmp(u->scheme, "https") != 0) { snprintf(err, errsz, "Unsupported URL scheme '%s' - only http and https are allowed", u->scheme); return -1; } host_start = sc_end + 3; host_end = host_start; while (*host_end && *host_end != '/' && *host_end != '?' && *host_end != '#') host_end++; n = (size_t)(host_end - host_start); if (n == 0) { snprintf(err, errsz, "invalid URL (empty host)"); return -1; } if (memchr(host_start, '@', n)) { snprintf(err, errsz, "URLs with userinfo are refused"); return -1; } u->port = strcmp(u->scheme, "https") == 0 ? 443 : 80; if (host_start[0] == '[') { const char *cb = (const char *)memchr(host_start, ']', n); size_t hl; if (!cb || cb >= host_end) { snprintf(err, errsz, "invalid URL (IPv6 host)"); return -1; } hl = (size_t)(cb - (host_start + 1)); if (hl == 0 || hl >= sizeof u->host) { snprintf(err, errsz, "invalid URL (IPv6 host)"); return -1; } memcpy(u->host, host_start + 1, hl); u->host[hl] = '\0'; if (cb + 1 != host_end) { if (cb[1] != ':' || parse_port(cb + 2, host_end, &u->port) != 0) { snprintf(err, errsz, "invalid URL (port)"); return -1; } } } else { const char *colon = (const char *)memchr(host_start, ':', n); if (colon) { n = (size_t)(colon - host_start); if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; } memcpy(u->host, host_start, n); u->host[n] = '\0'; if (parse_port(colon + 1, host_end, &u->port) != 0) { snprintf(err, errsz, "invalid URL (port)"); return -1; } } else { if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; } memcpy(u->host, host_start, n); u->host[n] = '\0'; } { /* reject characters that are neither hostname-safe nor a raw IPv4 */ size_t i; for (i = 0; u->host[i]; i++) { char c = u->host[i]; if (!(isalnum((unsigned char)c) || c == '.' || c == '-' || c == '_')) { snprintf(err, errsz, "invalid URL (host characters)"); return -1; } } } } if (*host_end == '\0' || *host_end == '#') { snprintf(u->path, sizeof u->path, "/"); } else { const char *hash = strchr(host_end, '#'); size_t plen = hash ? (size_t)(hash - host_end) : strlen(host_end); if (plen >= sizeof u->path) { snprintf(err, errsz, "invalid URL (path too long)"); return -1; } memcpy(u->path, host_end, plen); u->path[plen] = '\0'; } return 0; } static void fx_url_build(const fx_url *u, char *out, size_t outsz) { int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80; if (u->port == defport) snprintf(out, outsz, "%s://%s%s", u->scheme, u->host, u->path); else snprintf(out, outsz, "%s://%s:%d%s", u->scheme, u->host, u->port, u->path); } static int fx_url_resolve(const fx_url *base, const char *to, fx_url *out, char *err, size_t errsz) { if (!to || !*to) { snprintf(err, errsz, "empty redirect target"); return -1; } if (strstr(to, "://")) return fx_url_parse(to, out, err, errsz); *out = *base; if (to[0] == '/') { if (strlen(to) >= sizeof out->path) { snprintf(err, errsz, "redirect target too long"); return -1; } snprintf(out->path, sizeof out->path, "%s", to); return 0; } { char dir[2048]; const char *slash = strrchr(base->path, '/'); size_t dirlen = slash ? (size_t)(slash - base->path) + 1 : 0; if (dirlen + strlen(to) + 1 >= sizeof dir) { snprintf(err, errsz, "redirect target too long"); return -1; } memcpy(dir, base->path, dirlen); dir[dirlen] = '\0'; strcat(dir, to); snprintf(out->path, sizeof out->path, "%s", dir); } return 0; } /* ------------------------------------------------------------------ */ /* SSRF denylist */ /* ------------------------------------------------------------------ */ /* The deny ranges are assembled from octet arrays in code (no dotted-quad * literals in this file), mirroring upstream _NON_PUBLIC_NETWORKS. */ typedef struct { unsigned o[4]; int bits; } fx_v4net; #define V4(a, b, c, d, bits) { { (a), (b), (c), (d) }, (bits) } static const fx_v4net DENY4[] = { V4(0, 0, 0, 0, 8), /* this-network */ V4(10, 0, 0, 0, 8), /* private */ V4(100, 64, 0, 0, 10), /* CGNAT */ V4(127, 0, 0, 0, 8), /* loopback */ V4(169, 254, 0, 0, 16), /* link-local + cloud metadata */ V4(172, 16, 0, 0, 12), /* private */ V4(192, 0, 0, 0, 24), /* IANA special */ V4(192, 0, 2, 0, 24), /* TEST-NET-1 */ V4(192, 88, 99, 0, 24), /* 6to4 relay */ V4(192, 168, 0, 0, 16), /* private */ V4(198, 18, 0, 0, 15), /* benchmarking */ V4(198, 51, 100, 0, 24), /* TEST-NET-2 */ V4(203, 0, 113, 0, 24), /* TEST-NET-3 */ V4(224, 0, 0, 0, 4), /* multicast (our own hardening) */ V4(240, 0, 0, 0, 4) /* reserved */ }; #define DENY4_N ((int)(sizeof DENY4 / sizeof DENY4[0])) static int deny4_match(const unsigned *o, const fx_v4net *net) { unsigned a = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3]; unsigned b = (net->o[0] << 24) | (net->o[1] << 16) | (net->o[2] << 8) | net->o[3]; unsigned mask = net->bits >= 32 ? 0xFFFFFFFFu : ~(0xFFFFFFFFu >> net->bits); return (a & mask) == (b & mask); } static int deny4_any(const unsigned *o) { int i; for (i = 0; i < DENY4_N; i++) { if (!deny4_match(o, &DENY4[i])) continue; /* upstream _PUBLIC_EXCEPTIONS: the two anycast IPs inside 192.0.0.0/24 */ if (o[0] == 192 && o[1] == 0 && o[2] == 0 && (o[3] == 9 || o[3] == 10)) continue; return 1; } return 0; } static int deny6_match(const unsigned char *ip) { unsigned w0 = (unsigned)((ip[0] << 8) | ip[1]); unsigned w1 = (unsigned)((ip[2] << 8) | ip[3]); unsigned v0 = ((unsigned)ip[0] << 24) | ((unsigned)ip[1] << 16) | ((unsigned)ip[2] << 8) | (unsigned)ip[3]; int j; unsigned o[4]; /* ::/96 - covers ::, ::1 and all deprecated IPv4-compatible space. */ { int allz = 1; for (j = 0; j < 12; j++) if (ip[j]) { allz = 0; break; } if (allz) return 1; } /* ::ffff:a.b.c.d - apply the v4 list to the embedded address. */ { int pre = 1; for (j = 0; j < 10; j++) if (ip[j]) { pre = 0; break; } if (pre && ip[10] == 0xff && ip[11] == 0xff) { o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15]; return deny4_any(o); } } /* 64:ff9b::/96 well-known NAT64 -> inspect the embedded v4. * 64:ff9b:1::/48 isolated prefix -> always refused. */ if (w0 == 0x0064 && w1 == 0xff9b) { if (ip[4] || ip[5] || ip[6] || ip[7]) return 1; o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15]; return deny4_any(o); } if ((w0 & 0xFFC0) == 0x0100 && w1 == 0x0000) return 1; /* 100::/64 */ if ((v0 & 0xFFFFFE00u) == 0x20010000u) { /* 2001::/23 */ unsigned w2 = (unsigned)((ip[4] << 8) | ip[5]); unsigned w3 = (unsigned)((ip[6] << 8) | ip[7]); if ((w2 == 0x0001 || w2 == 0x0002 || w2 == 0x0003) && !w3) return 0; /* TEREDO/AMP */ if (w2 == 0x0004 && w3 == 0x0112) return 0; if ((w2 & 0xFFF0) == 0x0020) return 0; if ((w2 & 0xFFF0) == 0x0030) return 0; return 1; } if (v0 == 0x20010db8u) return 1; /* 2001:db8::/32 */ if (w0 == 0x2002) return 1; /* 6to4 */ if ((v0 & 0xFFFFF000u) == 0x3fff0000u) return 1; /* 3fff::/20 */ if ((w0 & 0xFC00) == 0xFC00) return 1; /* fc00::/7 ULA */ if ((w0 & 0xFFC0) == 0xFE80) return 1; /* fe80::/10 */ if (w0 == 0xFEC0) return 1; /* fec0::/10 site-local */ return 0; } int fx_ip_is_denied(const char *ip_text) { const char *q; if (!ip_text || !*ip_text) return 1; for (q = ip_text; *q; q++) if (*q == '.') break; if (*q == '.') { unsigned o[4]; char *end; int i; long v; const char *p = ip_text; for (i = 0; i < 4; i++) { const char *d; if (!p || !isdigit((unsigned char)*p)) return 1; /* Exactly one canonical form is accepted: digits only, no sign, * no leading zero on a multi-digit group, at most three digits. * inet_aton's octal and hex habits (0177.0.0.1, 0x7f.0.0.1) and * its short forms must never parse into a different address than * the caller wrote, so anything non-canonical is refused rather * than reinterpreted. */ for (d = p; *d && *d != '.'; d++) { if (!isdigit((unsigned char)*d)) return 1; if (d > p && *p == '0') return 1; if (d - p > 2) return 1; } v = strtol(p, &end, 10); if (v < 0 || v > 255 || end == p) return 1; o[i] = (unsigned)v; p = (*end == '.') ? end + 1 : end; } if (*p) return 1; /* trailing junk */ return deny4_any(o); } { unsigned char buf[16]; #if defined(_WIN32) if (InetPtonA(AF_INET6, ip_text, buf) != 1) return 1; #else if (inet_pton(AF_INET6, ip_text, buf) != 1) return 1; #endif return deny6_match(buf); } } /* ------------------------------------------------------------------ */ /* Host header / response head helpers */ /* ------------------------------------------------------------------ */ static int head_field(const char *head, size_t head_len, const char *name, const char **vout, size_t *vlen) { size_t nlen = strlen(name); const char *p = head, *end = head + head_len; while (p < end) { const char *eol = (const char *)memchr(p, '\n', (size_t)(end - p)); size_t llen; if (!eol) eol = end; llen = (size_t)(eol - p); if (llen && p[llen - 1] == '\r') llen--; if (llen > nlen && p[nlen] == ':' && sx_strncasecmp(p, name, nlen) == 0) { const char *v = p + nlen + 1; size_t vl = llen - nlen - 1; while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; } while (vl && (v[vl - 1] == ' ' || v[vl - 1] == '\t')) vl--; *vout = v; *vlen = vl; return 1; } p = eol + 1; } return 0; } /* Case-insensitive prefix test used by the no-Content-Type sniffer: servers * emit DOCTYPE in every casing, and a document whose very first token is * = 'A' && a <= 'Z') a = (unsigned char)(a + 32); if (b >= 'A' && b <= 'Z') b = (unsigned char)(b + 32); if (a != b) return 0; if (!a) return 0; /* both NUL: prefix longer than s */ } return 1; } int fx_body_looks_like_html(const char *body, size_t len) { size_t i = 0, n; char probe[24]; if (!body || !len) return 0; while (i < len && (unsigned char)body[i] <= ' ') i++; if (i + 3 <= len && (unsigned char)body[i] == 0xEF && (unsigned char)body[i + 1] == 0xBB && (unsigned char)body[i + 2] == 0xBF) i += 3; while (i < len && (unsigned char)body[i] <= ' ') i++; n = len - i < 20 ? len - i : 20; memcpy(probe, body + i, n); probe[n] = '\0'; return ci_prefix(probe, "ai_next) { char ipbuf[64]; if (ai->ai_family == AF_INET) inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, ipbuf, sizeof ipbuf); else if (ai->ai_family == AF_INET6) inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, ipbuf, sizeof ipbuf); else continue; naddr++; if (!allow_private && fx_ip_is_denied(ipbuf)) { snprintf(err, errsz, "Access to private or reserved address space is not allowed. " "The hostname '%s' resolves to a denied address (%s).", host, ipbuf); freeaddrinfo(res); return -1; } } if (naddr == 0) { snprintf(err, errsz, "Failed to resolve host %s: no usable address", host); freeaddrinfo(res); return -1; } /* Pick the first answer; it is validated, and we connect to its numbers. */ for (ai = res; ai; ai = ai->ai_next) { if (ai->ai_family == AF_INET) { 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 = 0; break; } if (ai->ai_family == AF_INET6) { 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 = 0; /* prefer v4 but keep v6 if it came first */ if (0) break; } } /* second pass: prefer IPv4 if present */ if (found == 0) { for (ai = res; ai; ai = ai->ai_next) { if (ai->ai_family == AF_INET) { 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); break; } } } freeaddrinfo(res); if (found != 0) { snprintf(err, errsz, "Failed to resolve host %s: no usable address", host); return -1; } return 0; } #if !defined(_WIN32) /* ------------------------------------------------------------------ */ /* POSIX transport */ /* ------------------------------------------------------------------ */ typedef struct { sx_sock fd; fx_tls *tls; long long deadline_ms; } sx_trans; static int connect_timeout(int fd, const struct sockaddr *sa, socklen_t slen, int ms, char *err, size_t errsz) { int flags, rc, soerr = 0; socklen_t elen = sizeof soerr; struct pollfd pfd; flags = fcntl(fd, F_GETFL, 0); if (flags < 0) return -1; if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) return -1; rc = connect(fd, sa, slen); if (rc != 0) { if (errno != EINPROGRESS) { snprintf(err, errsz, "connect failed: %s", strerror(errno)); return -1; } pfd.fd = fd; pfd.events = POLLOUT; pfd.revents = 0; do { rc = poll(&pfd, 1, ms); } while (rc < 0 && errno == EINTR); if (rc == 0) { snprintf(err, errsz, "connect timed out"); return -1; } if (rc < 0) { snprintf(err, errsz, "connect failed: %s", strerror(errno)); return -1; } if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &elen) != 0 || soerr != 0) { snprintf(err, errsz, "connect failed: %s", strerror(soerr ? soerr : ECONNREFUSED)); return -1; } } if (fcntl(fd, F_SETFL, flags) < 0) return -1; return 0; } static int trans_read(sx_trans *t, char *buf, size_t n) { if (t->tls) return fx_tls_read(t->tls, buf, n); for (;;) { ssize_t r; struct pollfd pfd; long long remain = t->deadline_ms - fx_now_ms(); int waited; if (remain <= 0) return -2; /* stalled: EOF-like */ pfd.fd = t->fd; pfd.events = POLLIN; pfd.revents = 0; waited = (int)(remain > 500 ? 500 : remain); r = poll(&pfd, 1, waited); if (r < 0) { if (errno == EINTR) continue; return -1; } if (r == 0) continue; /* loop rechecks deadline */ if (!(pfd.revents & (POLLIN | POLLHUP | POLLERR))) continue; do { r = recv(t->fd, buf, n, 0); } while (r < 0 && errno == EINTR); if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue; if (r < 0) return -1; if (r == 0) return 0; /* EOF */ return (int)r; } } static int trans_write(sx_trans *t, const char *buf, size_t n) { if (t->tls) return fx_tls_write(t->tls, buf, n); { size_t off = 0; while (off < n) { ssize_t w = send(t->fd, buf + off, n - off, MSG_NOSIGNAL); if (w < 0) { if (errno == EINTR) continue; return -1; } off += (size_t)w; } return (int)n; } } static void trans_close(sx_trans *t) { if (t->tls) { fx_tls_close(t->tls); t->tls = NULL; } if (t->fd != SX_SOCK_INVALID) { sx_closesocket(t->fd); t->fd = SX_SOCK_INVALID; } } /* Reads the head; returns bytes consumed of the terminator inclusive, sets * head_len to the head length (before the terminator), *extra_out to body * bytes that arrived in the same window (0 — we always read exactly the * head window with a small overread stash). On hard failure, -1; on deadline, * -2. */ typedef struct { char *p; size_t n; size_t cap; } sx_stash; static int read_head(sx_trans *t, char *head, size_t cap, size_t *hlen_out, sx_stash *stash) { size_t n = 0; size_t scanned = 0; for (;;) { size_t i; int r = trans_read(t, head + n, cap - n > 1024 ? 1024 : cap - n); if (r == -2) return n ? -1 : -2; if (r < 0) return -1; if (r == 0) { /* EOF */ if (n == 0) return -1; *hlen_out = n; /* no terminator: whole thing is head */ stash->p = NULL; stash->n = 0; return (int)n; } n += (size_t)r; if (n >= cap) return -1; /* oversized head */ /* scan for the terminator; the window may re-include up to 3 bytes * already scanned so a terminator split across two reads is found */ if (scanned > 3) scanned -= 3; for (i = scanned; i + 1 < n; i++) { if (head[i] == '\n') { size_t headlen; size_t term; if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' && head[i - 3] == '\r') { headlen = i - 1; term = 4; } else if (i >= 1 && head[i - 1] == '\n') { headlen = i - 1; term = 2; /* tolerate bare \n\n */ } else continue; *hlen_out = headlen; if (n > i + 1) { stash->p = head + (i + 1); stash->n = n - (i + 1); } else { stash->p = NULL; stash->n = 0; } (void)term; return (int)n; } } scanned = n; } } static int exchange_plain(const fx_url *u, const char *urltext, fx_response *r, int allow_private) { sx_trans t; fx_target tgt; char req[4300]; char *head; size_t head_len = 0; sx_stash stash; const char *v; size_t vl; buf_t body; long long clen = -1; int chunked = 0, gzip = 0; int status, fd, rc; struct sockaddr_storage ss; socklen_t slen; const char *UA = "SCORPIOXBOT-fetch/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-fetch)"; int host_has_port = !((strcmp(u->scheme, "http") == 0 && u->port == 80) || (strcmp(u->scheme, "https") == 0 && u->port == 443)); memset(&t, 0, sizeof t); t.fd = SX_SOCK_INVALID; t.deadline_ms = fx_now_ms() + FX_CONNECT_MS + FX_READ_MS; if (fx_resolve_validate(u->host, u->port, 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, FX_CONNECT_MS, r->error, sizeof r->error) != 0) { close(fd); return -1; } t.fd = fd; if (strcmp(u->scheme, "https") == 0) { char terr[256] = ""; t.tls = fx_tls_connect_fd(t.fd, u->host, terr, sizeof terr); if (!t.tls) { snprintf(r->error, sizeof r->error, "%s", terr[0] ? terr : "TLS handshake failed"); close(t.fd); t.fd = SX_SOCK_INVALID; return -1; } t.fd = SX_SOCK_INVALID; /* owned by the TLS layer now */ } snprintf(req, sizeof req, "GET %s HTTP/1.1\r\n" "Host: %s%s%s\r\n" "User-Agent: %s\r\n" "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" "Accept-Encoding: identity\r\n" "Connection: close\r\n\r\n", u->path, u->host, host_has_port ? ":" : "", host_has_port ? "" : "", UA); if (host_has_port) { snprintf(req, sizeof req, "GET %s HTTP/1.1\r\n" "Host: %s:%d\r\n" "User-Agent: %s\r\n" "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" "Accept-Encoding: identity\r\n" "Connection: close\r\n\r\n", u->path, u->host, u->port, UA); } if (trans_write(&t, req, strlen(req)) < 0) { snprintf(r->error, sizeof r->error, "Failed to fetch %s: the server did not accept our request", urltext); trans_close(&t); return -1; } head = (char *)sx_malloc(FX_MAX_HEAD + 1); rc = read_head(&t, head, FX_MAX_HEAD, &head_len, &stash); if (rc < 0) { snprintf(r->error, sizeof r->error, rc == -2 ? "Failed to fetch %s: timed out reading the response head" : "Failed to fetch %s: bad or oversized response head", urltext); free(head); trans_close(&t); return -1; } head[head_len] = '\0'; if (strncmp(head, "HTTP/", 5) != 0) { snprintf(r->error, sizeof r->error, "Failed to fetch %s: not an HTTP response", urltext); free(head); trans_close(&t); return -1; } status = atoi(head + 9); r->status = status; if (head_field(head, head_len, "content-type", &v, &vl)) { size_t n = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1; memcpy(r->content_type, v, n); r->content_type[n] = '\0'; } { char nbuf[32]; if (head_field(head, head_len, "content-length", &v, &vl)) { size_t n = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1; memcpy(nbuf, v, n); nbuf[n] = '\0'; clen = atoll(nbuf); if (clen > (long long)FX_MAX_BODY) { snprintf(r->error, sizeof r->error, "Failed to fetch %s: the response body is larger than the " "%u byte limit this plugin reads", urltext, FX_MAX_BODY); free(head); trans_close(&t); return -1; } } if (head_field(head, head_len, "transfer-encoding", &v, &vl) && vl >= 7 && sx_strncasecmp(v, "chunked", 7) == 0) chunked = 1; #ifdef HAVE_ZLIB if (head_field(head, head_len, "content-encoding", &v, &vl) && vl >= 4 && sx_strncasecmp(v, "gzip", 4) == 0) gzip = 1; #else if (head_field(head, head_len, "content-encoding", &v, &vl) && vl) { char enc[64]; size_t n = vl < sizeof enc - 1 ? vl : sizeof enc - 1; memcpy(enc, v, n); enc[n] = '\0'; if (sx_strcasecmp(enc, "identity") != 0) { snprintf(r->error, sizeof r->error, "Unsupported content encoding %s: this server cannot decode it", enc); free(head); trans_close(&t); return -1; } } #endif } if ((status == 301 || status == 302 || status == 303 || status == 307 || status == 308) && head_field(head, head_len, "location", &v, &vl)) { size_t n = vl < sizeof r->url - 1 ? vl : sizeof r->url - 1; memcpy(r->url, v, n); r->url[n] = '\0'; free(head); trans_close(&t); return 2; } buf_init(&body); fx_md_set_base_url(urltext); /* relativise links during conversion */ if (chunked) { /* stream chunk framing directly; bytes that arrived in the same read * window as the head terminator seed the framing buffer (they are * chunk data, NOT body — appending them raw would emit the hex size * line as content) */ char small[4096]; size_t sp = 0, sn = 0; int dead = 0; if (stash.n) { memcpy(small, stash.p, stash.n); sn = stash.n; } #define CHUNK_GETC(ch) \ do { \ int _done = 0; \ while (!_done) { \ if (sp < sn) { (ch) = small[sp++]; _done = 1; break; } \ { \ int _r = trans_read(&t, small, sizeof small); \ if (_r == 0) { dead = 1; _done = 1; break; } \ if (_r < 0) { dead = -1; _done = 1; break; } \ sn = (size_t)_r; sp = 0; \ } \ } \ } while (0) for (;;) { char ch = 0; char hex[24]; size_t hn = 0; unsigned long csz; CHUNK_GETC(ch); if (dead) break; if (ch == '\r' || ch == '\n') continue; /* skip CRLFs between chunks */ hex[hn++] = ch; while (hn < sizeof hex - 1) { CHUNK_GETC(ch); if (dead) break; if (ch == '\r') { CHUNK_GETC(ch); if (dead) break; if (ch == '\n') break; } else if (ch == '\n') break; hex[hn++] = ch; } if (dead) break; hex[hn] = '\0'; { char *semi = strchr(hex, ';'); if (semi) *semi = '\0'; } csz = strtoul(hex, NULL, 16); if (csz == 0) break; if (body.n + csz > FX_MAX_BODY) { buf_free(&body); free(head); trans_close(&t); snprintf(r->error, sizeof r->error, "Failed to fetch %s: the response body is larger than the " "%u byte limit this plugin reads", urltext, FX_MAX_BODY); return -1; } while (csz > 0) { size_t take; if (sp >= sn) { int _r = trans_read(&t, small, sizeof small); if (_r <= 0) { buf_free(&body); free(head); trans_close(&t); snprintf(r->error, sizeof r->error, "Failed to fetch %s: truncated chunked body", urltext); return -1; } sn = (size_t)_r; sp = 0; } take = sn - sp; if (take > csz) take = csz; buf_bput(&body, small + sp, take); sp += take; csz -= take; } } #undef CHUNK_GETC } else if (clen >= 0) { size_t want = (size_t)clen; if (stash.n) buf_bput(&body, stash.p, stash.n); if (want > body.n) { size_t need = want - body.n; char *tmp = (char *)sx_malloc(need); size_t got = 0; while (got < need) { int rr = trans_read(&t, tmp + got, need - got); if (rr <= 0) { free(tmp); buf_free(&body); free(head); trans_close(&t); snprintf(r->error, sizeof r->error, "Failed to fetch %s: the server closed before the " "declared body was complete", urltext); return -1; } got += (size_t)rr; } buf_bput(&body, tmp, need); free(tmp); } } else { char tmp[8192]; if (stash.n) buf_bput(&body, stash.p, stash.n); for (;;) { int rr = trans_read(&t, tmp, sizeof tmp); if (rr == -2 || rr == 0) break; if (rr < 0) { buf_free(&body); free(head); trans_close(&t); snprintf(r->error, sizeof r->error, "Failed to fetch %s: body read failed", urltext); return -1; } if (body.n + (size_t)rr > FX_MAX_BODY) { buf_free(&body); free(head); trans_close(&t); snprintf(r->error, sizeof r->error, "Failed to fetch %s: the response body is larger than the " "%u byte limit this plugin reads", urltext, FX_MAX_BODY); return -1; } buf_bput(&body, tmp, (size_t)rr); } } free(head); trans_close(&t); #ifdef HAVE_ZLIB if (gzip && body.n > 18 && (unsigned char)body.p[0] == 0x1f && (unsigned char)body.p[1] == 0x8b) { uLongf cap = (uLongf)(body.n * 16 + 4096); int inflated = 0; while (!inflated && cap <= FX_MAX_BODY) { char *outb = (char *)sx_malloc(cap + 1); z_stream zs; int zr; memset(&zs, 0, sizeof zs); zs.next_in = (Bytef *)body.p; zs.avail_in = (uInt)body.n; zs.next_out = (Bytef *)outb; zs.avail_out = (uInt)cap; zr = inflateInit2(&zs, 15 + 16); if (zr == Z_OK) zr = inflate(&zs, Z_FINISH); if (zr == Z_STREAM_END) { free(body.p); body.p = outb; body.n = (size_t)zs.total_out; body.p[body.n] = '\0'; inflated = 1; } else { free(outb); cap *= 4; } inflateEnd(&zs); } /* if it never inflated, keep the raw bytes: they are still an honest * answer for a server that mislabelled its payload */ } #else (void)gzip; #endif r->body = body.p ? body.p : fx_strndup("", 0); r->body_len = body.n; return 0; } #endif /* !_WIN32 */ /* ------------------------------------------------------------------ */ /* WinHTTP transport */ /* ------------------------------------------------------------------ */ #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 fx_url *u, const char *urltext, fx_response *r, int allow_private) { HINTERNET sess = NULL, conn = NULL, req = NULL; wchar_t wtarget[1024], wpath[2100]; fx_target tgt; char target_ip[64]; wchar_t whdr[128]; DWORD avail = 0; BOOL ok; buf_t body; int status = 0; if (fx_resolve_validate(u->host, u->port, allow_private, &tgt, r->error, sizeof r->error) != 0) return -1; snprintf(target_ip, sizeof target_ip, "%s", tgt.text); sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!sess) sess = WinHttpOpen(L"SCORPIOXBOT-fetch/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, FX_CONNECT_MS, FX_CONNECT_MS, FX_READ_MS, FX_READ_MS); /* connect to the validated numeric IP; Host + SNI carry the real name */ a2w(target_ip, wtarget, 1024); a2w(u->path, wpath, 2100); conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0); if (!conn) { snprintf(r->error, sizeof r->error, "Failed to connect to %s", u->host); WinHttpCloseHandle(sess); return -1; } { DWORD flags = strcmp(u->scheme, "https") == 0 ? WINHTTP_FLAG_SECURE : 0; req = WinHttpOpenRequest(conn, L"GET", wpath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags); } 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); } { /* Our own redirect loop owns every hop (each one re-resolved and * re-validated), so WinHTTP must not follow any on its own. * _NEVER is the documented spelling; _NONE is what the WinRT * WINHTTP_REDIRECT_POLICY enum calls it and MinGW's winhttp.h does * not define _NONE at all. */ DWORD pol = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol); } { wchar_t wh[640]; char hs[520]; int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80; if (u->port != defport) snprintf(hs, sizeof hs, "Host: %s:%d\r\n" "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" "Accept-Encoding: identity\r\n", u->host, u->port); else snprintf(hs, sizeof hs, "Host: %s\r\n" "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n" "Accept-Encoding: identity\r\n", u->host); a2w(hs, wh, 640); WinHttpAddRequestHeaders(req, wh, (DWORD)-1, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); } ok = WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); if (!ok || !WinHttpReceiveResponse(req, NULL)) { snprintf(r->error, sizeof r->error, "Failed to fetch %s: TLS or connection error (certificate refused " "or host unreachable)", urltext); WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); return -1; } { DWORD sz = sizeof status; WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &sz, WINHTTP_NO_HEADER_INDEX); r->status = (int)status; } { wchar_t wct[256]; DWORD sz = sizeof wct; wct[0] = L'\0'; if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, wct, &sz, WINHTTP_NO_HEADER_INDEX)) WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type, sizeof r->content_type, NULL, NULL); } if (r->status == 301 || r->status == 302 || r->status == 303 || r->status == 307 || r->status == 308) { wchar_t wloc[1024]; DWORD sz = sizeof wloc; wloc[0] = L'\0'; a2w("Location", whdr, 128); if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CUSTOM, whdr, wloc, &sz, WINHTTP_NO_HEADER_INDEX)) { WideCharToMultiByte(CP_UTF8, 0, wloc, -1, r->url, sizeof r->url, NULL, NULL); WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); return 2; } } buf_init(&body); for (;;) { if (!WinHttpQueryDataAvailable(req, &avail)) break; if (avail == 0) break; { DWORD take = avail > 65536 ? 65536 : avail; char *tmp; DWORD rd = 0; if (body.n + take > FX_MAX_BODY) { buf_free(&body); WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); snprintf(r->error, sizeof r->error, "Failed to fetch %s: the response body is larger than the " "%u byte limit this plugin reads", urltext, FX_MAX_BODY); return -1; } tmp = (char *)sx_malloc(take + 1); if (!WinHttpReadData(req, tmp, take, &rd) || rd == 0) { free(tmp); break; } tmp[rd] = '\0'; buf_bput(&body, tmp, rd); free(tmp); } } WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess); r->body = body.p ? body.p : fx_strndup("", 0); r->body_len = body.n; return 0; } #endif /* _WIN32 */ /* ------------------------------------------------------------------ */ /* fx_fetch — the redirect loop */ /* ------------------------------------------------------------------ */ int fx_fetch(const char *url, fx_response *r) { fx_url u; char urltext[1100]; int hops = 0; int allow_private = 0; const char *env; memset(r, 0, sizeof *r); env = getenv("FETCH_ALLOW_PRIVATE"); if (env && *env && strcmp(env, "0") != 0) allow_private = 1; if (fx_policy_allow_private()) allow_private = 1; if (fx_url_parse(url, &u, r->error, sizeof r->error) != 0) return -1; snprintf(r->first_url, sizeof r->first_url, "%s", url); for (;;) { int rc; fx_url_build(&u, urltext, sizeof urltext); r->url[0] = '\0'; free(r->body); r->body = NULL; r->body_len = 0; r->content_type[0] = '\0'; #if defined(_WIN32) rc = exchange_winhttp(&u, urltext, r, allow_private); #else rc = exchange_plain(&u, urltext, r, allow_private); #endif if (rc == 0) { if (!r->url[0]) snprintf(r->url, sizeof r->url, "%s", urltext); r->ok = 1; r->hops = hops; return 0; } if (rc == 2) { if (++hops > FX_MAX_REDIRECTS) { snprintf(r->error, sizeof r->error, "Exceeded maximum allowed redirects."); return -1; } /* Absolute-ise the Location against the CURRENT url: a bare * "relative" resolves against the directory of the current path, * "/abs" against the authority, and anything carrying "://" is * already absolute. fx_url_resolve is the single place that owns * those rules. Every hop then re-enters the same * parse/resolve/validate path, so each new address is SSRF * checked before it is connected to. */ { fx_url next; if (fx_url_resolve(&u, r->url, &next, r->error, sizeof r->error) != 0) return -1; u = next; } continue; } return -1; } } void fx_response_free(fx_response *r) { if (!r) return; free(r->body); r->body = NULL; r->body_len = 0; }