scorpiox-bot-plugin-fetch
←fetch_http.cc
1270 lines · 46 KBHEADBlameDownload
1/*
2 * fetch_http.c - URL parsing, SSRF policy, HTTP(S) GET with redirect chain.
3 *
4 * Both platforms: our own getaddrinfo, per-address SSRF validation, then the
5 * socket is connected to the EXACT validated numeric address (never the
6 * hostname), so a rebinding DNS server cannot answer a private IP between
7 * the check and the connect. TLS on POSIX is vendored mbedTLS over our own
8 * socket (fetch_tls.c); on _WIN32 the exchange runs over WinHTTP with the
9 * resolution pinned through WINHTTP_OPTION_RESOLVE_TIMEOUT-era connection
10 * semantics by connecting to the numeric IP while sending the real Host
11 * header and SNI name (https).
12 *
13 * Every redirect hop re-enters the same parse/resolve/validate path, up to
14 * FX_MAX_REDIRECTS. No TLS bypass exists.
15 */
16/* The feature-test macros must precede every include (netdb/inet functions,
17 * POSIX sockets). _WIN32_WINNT likewise precedes winsock2.h: MinGW defaults
18 * it to 0x0502, which hides InetPtonA and inet_ntop - both of which the SSRF
19 * validator needs - behind a Windows Vista gate. */
20#if defined(_WIN32) && !defined(_WIN32_WINNT)
21# define _WIN32_WINNT 0x0601
22#endif
23#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE)
24# define _POSIX_C_SOURCE 200809L
25#endif
26
27#include "fetch_http.h"
28
29#include <ctype.h>
30#include <errno.h>
31#include <limits.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#include <time.h>
36
37#if defined(_WIN32)
38# ifndef WIN32_LEAN_AND_MEAN
39# define WIN32_LEAN_AND_MEAN
40# endif
41# include <winsock2.h>
42# include <windows.h>
43# include <ws2tcpip.h>
44# include <winhttp.h>
45 typedef SOCKET sx_sock;
46# define SX_SOCK_INVALID INVALID_SOCKET
47# define sx_closesocket closesocket
48#else
49# ifndef _POSIX_C_SOURCE
50# define _POSIX_C_SOURCE 200809L
51# endif
52# include <netdb.h>
53# include <arpa/inet.h>
54# include <netinet/in.h>
55# include <netinet/tcp.h>
56# include <poll.h>
57# include <fcntl.h>
58# include <sys/socket.h>
59# include <sys/time.h>
60# include <sys/types.h>
61# include <unistd.h>
62 typedef int sx_sock;
63# define SX_SOCK_INVALID (-1)
64# define sx_closesocket close
65#endif
66
67#include "fetch_tls.h"
68#include "fetch_md.h"
69
70#ifdef HAVE_ZLIB
71# include <zlib.h>
72#endif
73/* Persisted policy hook (implemented in plugin_fetch.c). */
74extern int fx_policy_allow_private(void);
75
76char *fx_strndup(const char *s, size_t n)
77{
78 char *p;
79 if (!s || !n) { p = (char *)sx_malloc(1); p[0] = '\0'; return p; }
80 p = (char *)sx_malloc(n + 1);
81 memcpy(p, s, n);
82 p[n] = '\0';
83 return p;
84}
85
86long long fx_now_ms(void)
87{
88#if defined(_WIN32)
89 static LARGE_INTEGER freq;
90 LARGE_INTEGER t;
91 if (!freq.QuadPart) QueryPerformanceFrequency(&freq);
92 QueryPerformanceCounter(&t);
93 return (long long)(t.QuadPart / (freq.QuadPart / 1000));
94#else
95 struct timespec ts;
96 clock_gettime(CLOCK_MONOTONIC, &ts);
97 return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
98#endif
99}
100
101/* ------------------------------------------------------------------ */
102/* URL parsing */
103/* ------------------------------------------------------------------ */
104
105typedef struct {
106 char scheme[8]; /* http | https */
107 char host[256];
108 int port;
109 char path[2048]; /* path?query, always starts with '/' */
110} fx_url;
111
112static int parse_port(const char *s, const char *end, int *port_out)
113{
114 long pl = 0;
115 const char *p = s;
116 if (p == end) return -1;
117 for (; p < end; p++) {
118 if (!isdigit((unsigned char)*p)) return -1;
119 pl = pl * 10 + (*p - '0');
120 if (pl > 65535) return -1;
121 }
122 if (pl <= 0) return -1;
123 *port_out = (int)pl;
124 return 0;
125}
126
127static int fx_url_parse(const char *url, fx_url *u, char *err, size_t errsz)
128{
129 const char *p = url, *sc_end, *host_start, *host_end;
130 size_t n;
131
132 memset(u, 0, sizeof *u);
133 if (strlen(url) >= sizeof(u->host) + 2300) {
134 snprintf(err, errsz, "invalid URL (too long)");
135 return -1;
136 }
137 sc_end = strstr(p, "://");
138 if (!sc_end) { snprintf(err, errsz, "invalid URL (no scheme)"); return -1; }
139 n = (size_t)(sc_end - p);
140 if (n == 0 || n >= sizeof u->scheme) {
141 snprintf(err, errsz, "invalid URL (scheme)");
142 return -1;
143 }
144 for (size_t i = 0; i < n; i++) u->scheme[i] = (char)tolower((unsigned char)p[i]);
145 u->scheme[n] = '\0';
146 if (strcmp(u->scheme, "http") != 0 && strcmp(u->scheme, "https") != 0) {
147 snprintf(err, errsz,
148 "Unsupported URL scheme '%s' - only http and https are allowed",
149 u->scheme);
150 return -1;
151 }
152 host_start = sc_end + 3;
153 host_end = host_start;
154 while (*host_end && *host_end != '/' && *host_end != '?' && *host_end != '#')
155 host_end++;
156 n = (size_t)(host_end - host_start);
157 if (n == 0) { snprintf(err, errsz, "invalid URL (empty host)"); return -1; }
158 if (memchr(host_start, '@', n)) {
159 snprintf(err, errsz, "URLs with userinfo are refused");
160 return -1;
161 }
162
163 u->port = strcmp(u->scheme, "https") == 0 ? 443 : 80;
164 if (host_start[0] == '[') {
165 const char *cb = (const char *)memchr(host_start, ']', n);
166 size_t hl;
167 if (!cb || cb >= host_end) { snprintf(err, errsz, "invalid URL (IPv6 host)"); return -1; }
168 hl = (size_t)(cb - (host_start + 1));
169 if (hl == 0 || hl >= sizeof u->host) {
170 snprintf(err, errsz, "invalid URL (IPv6 host)");
171 return -1;
172 }
173 memcpy(u->host, host_start + 1, hl);
174 u->host[hl] = '\0';
175 if (cb + 1 != host_end) {
176 if (cb[1] != ':' || parse_port(cb + 2, host_end, &u->port) != 0) {
177 snprintf(err, errsz, "invalid URL (port)");
178 return -1;
179 }
180 }
181 } else {
182 const char *colon = (const char *)memchr(host_start, ':', n);
183 if (colon) {
184 n = (size_t)(colon - host_start);
185 if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; }
186 memcpy(u->host, host_start, n);
187 u->host[n] = '\0';
188 if (parse_port(colon + 1, host_end, &u->port) != 0) {
189 snprintf(err, errsz, "invalid URL (port)");
190 return -1;
191 }
192 } else {
193 if (n >= sizeof u->host) { snprintf(err, errsz, "invalid URL (host)"); return -1; }
194 memcpy(u->host, host_start, n);
195 u->host[n] = '\0';
196 }
197 { /* reject characters that are neither hostname-safe nor a raw IPv4 */
198 size_t i;
199 for (i = 0; u->host[i]; i++) {
200 char c = u->host[i];
201 if (!(isalnum((unsigned char)c) || c == '.' || c == '-' || c == '_')) {
202 snprintf(err, errsz, "invalid URL (host characters)");
203 return -1;
204 }
205 }
206 }
207 }
208
209 if (*host_end == '\0' || *host_end == '#') {
210 snprintf(u->path, sizeof u->path, "/");
211 } else {
212 const char *hash = strchr(host_end, '#');
213 size_t plen = hash ? (size_t)(hash - host_end) : strlen(host_end);
214 if (plen >= sizeof u->path) {
215 snprintf(err, errsz, "invalid URL (path too long)");
216 return -1;
217 }
218 memcpy(u->path, host_end, plen);
219 u->path[plen] = '\0';
220 }
221 return 0;
222}
223
224static void fx_url_build(const fx_url *u, char *out, size_t outsz)
225{
226 int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80;
227 if (u->port == defport)
228 snprintf(out, outsz, "%s://%s%s", u->scheme, u->host, u->path);
229 else
230 snprintf(out, outsz, "%s://%s:%d%s", u->scheme, u->host, u->port, u->path);
231}
232
233static int fx_url_resolve(const fx_url *base, const char *to, fx_url *out,
234 char *err, size_t errsz)
235{
236 if (!to || !*to) { snprintf(err, errsz, "empty redirect target"); return -1; }
237 if (strstr(to, "://")) return fx_url_parse(to, out, err, errsz);
238 *out = *base;
239 if (to[0] == '/') {
240 if (strlen(to) >= sizeof out->path) {
241 snprintf(err, errsz, "redirect target too long");
242 return -1;
243 }
244 snprintf(out->path, sizeof out->path, "%s", to);
245 return 0;
246 }
247 {
248 char dir[2048];
249 const char *slash = strrchr(base->path, '/');
250 size_t dirlen = slash ? (size_t)(slash - base->path) + 1 : 0;
251 if (dirlen + strlen(to) + 1 >= sizeof dir) {
252 snprintf(err, errsz, "redirect target too long");
253 return -1;
254 }
255 memcpy(dir, base->path, dirlen);
256 dir[dirlen] = '\0';
257 strcat(dir, to);
258 snprintf(out->path, sizeof out->path, "%s", dir);
259 }
260 return 0;
261}
262
263/* ------------------------------------------------------------------ */
264/* SSRF denylist */
265/* ------------------------------------------------------------------ */
266
267/* The deny ranges are assembled from octet arrays in code (no dotted-quad
268 * literals in this file), mirroring upstream _NON_PUBLIC_NETWORKS. */
269typedef struct { unsigned o[4]; int bits; } fx_v4net;
270
271#define V4(a, b, c, d, bits) { { (a), (b), (c), (d) }, (bits) }
272static const fx_v4net DENY4[] = {
273 V4(0, 0, 0, 0, 8), /* this-network */
274 V4(10, 0, 0, 0, 8), /* private */
275 V4(100, 64, 0, 0, 10), /* CGNAT */
276 V4(127, 0, 0, 0, 8), /* loopback */
277 V4(169, 254, 0, 0, 16), /* link-local + cloud metadata */
278 V4(172, 16, 0, 0, 12), /* private */
279 V4(192, 0, 0, 0, 24), /* IANA special */
280 V4(192, 0, 2, 0, 24), /* TEST-NET-1 */
281 V4(192, 88, 99, 0, 24), /* 6to4 relay */
282 V4(192, 168, 0, 0, 16), /* private */
283 V4(198, 18, 0, 0, 15), /* benchmarking */
284 V4(198, 51, 100, 0, 24), /* TEST-NET-2 */
285 V4(203, 0, 113, 0, 24), /* TEST-NET-3 */
286 V4(224, 0, 0, 0, 4), /* multicast (our own hardening) */
287 V4(240, 0, 0, 0, 4) /* reserved */
288};
289#define DENY4_N ((int)(sizeof DENY4 / sizeof DENY4[0]))
290
291static int deny4_match(const unsigned *o, const fx_v4net *net)
292{
293 unsigned a = (o[0] << 24) | (o[1] << 16) | (o[2] << 8) | o[3];
294 unsigned b = (net->o[0] << 24) | (net->o[1] << 16) | (net->o[2] << 8) | net->o[3];
295 unsigned mask = net->bits >= 32 ? 0xFFFFFFFFu : ~(0xFFFFFFFFu >> net->bits);
296 return (a & mask) == (b & mask);
297}
298
299static int deny4_any(const unsigned *o)
300{
301 int i;
302 for (i = 0; i < DENY4_N; i++) {
303 if (!deny4_match(o, &DENY4[i])) continue;
304 /* upstream _PUBLIC_EXCEPTIONS: the two anycast IPs inside 192.0.0.0/24 */
305 if (o[0] == 192 && o[1] == 0 && o[2] == 0 && (o[3] == 9 || o[3] == 10))
306 continue;
307 return 1;
308 }
309 return 0;
310}
311
312static int deny6_match(const unsigned char *ip)
313{
314 unsigned w0 = (unsigned)((ip[0] << 8) | ip[1]);
315 unsigned w1 = (unsigned)((ip[2] << 8) | ip[3]);
316 unsigned v0 = ((unsigned)ip[0] << 24) | ((unsigned)ip[1] << 16) |
317 ((unsigned)ip[2] << 8) | (unsigned)ip[3];
318 int j;
319 unsigned o[4];
320
321 /* ::/96 - covers ::, ::1 and all deprecated IPv4-compatible space. */
322 {
323 int allz = 1;
324 for (j = 0; j < 12; j++) if (ip[j]) { allz = 0; break; }
325 if (allz) return 1;
326 }
327 /* ::ffff:a.b.c.d - apply the v4 list to the embedded address. */
328 {
329 int pre = 1;
330 for (j = 0; j < 10; j++) if (ip[j]) { pre = 0; break; }
331 if (pre && ip[10] == 0xff && ip[11] == 0xff) {
332 o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15];
333 return deny4_any(o);
334 }
335 }
336 /* 64:ff9b::/96 well-known NAT64 -> inspect the embedded v4.
337 * 64:ff9b:1::/48 isolated prefix -> always refused. */
338 if (w0 == 0x0064 && w1 == 0xff9b) {
339 if (ip[4] || ip[5] || ip[6] || ip[7]) return 1;
340 o[0] = ip[12]; o[1] = ip[13]; o[2] = ip[14]; o[3] = ip[15];
341 return deny4_any(o);
342 }
343 if ((w0 & 0xFFC0) == 0x0100 && w1 == 0x0000) return 1; /* 100::/64 */
344 if ((v0 & 0xFFFFFE00u) == 0x20010000u) { /* 2001::/23 */
345 unsigned w2 = (unsigned)((ip[4] << 8) | ip[5]);
346 unsigned w3 = (unsigned)((ip[6] << 8) | ip[7]);
347 if ((w2 == 0x0001 || w2 == 0x0002 || w2 == 0x0003) && !w3) return 0; /* TEREDO/AMP */
348 if (w2 == 0x0004 && w3 == 0x0112) return 0;
349 if ((w2 & 0xFFF0) == 0x0020) return 0;
350 if ((w2 & 0xFFF0) == 0x0030) return 0;
351 return 1;
352 }
353 if (v0 == 0x20010db8u) return 1; /* 2001:db8::/32 */
354 if (w0 == 0x2002) return 1; /* 6to4 */
355 if ((v0 & 0xFFFFF000u) == 0x3fff0000u) return 1; /* 3fff::/20 */
356 if ((w0 & 0xFC00) == 0xFC00) return 1; /* fc00::/7 ULA */
357 if ((w0 & 0xFFC0) == 0xFE80) return 1; /* fe80::/10 */
358 if (w0 == 0xFEC0) return 1; /* fec0::/10 site-local */
359 return 0;
360}
361
362int fx_ip_is_denied(const char *ip_text)
363{
364 const char *q;
365 if (!ip_text || !*ip_text) return 1;
366 for (q = ip_text; *q; q++) if (*q == '.') break;
367 if (*q == '.') {
368 unsigned o[4];
369 char *end;
370 int i;
371 long v;
372 const char *p = ip_text;
373 for (i = 0; i < 4; i++) {
374 const char *d;
375 if (!p || !isdigit((unsigned char)*p)) return 1;
376 /* Exactly one canonical form is accepted: digits only, no sign,
377 * no leading zero on a multi-digit group, at most three digits.
378 * inet_aton's octal and hex habits (0177.0.0.1, 0x7f.0.0.1) and
379 * its short forms must never parse into a different address than
380 * the caller wrote, so anything non-canonical is refused rather
381 * than reinterpreted. */
382 for (d = p; *d && *d != '.'; d++) {
383 if (!isdigit((unsigned char)*d)) return 1;
384 if (d > p && *p == '0') return 1;
385 if (d - p > 2) return 1;
386 }
387 v = strtol(p, &end, 10);
388 if (v < 0 || v > 255 || end == p) return 1;
389 o[i] = (unsigned)v;
390 p = (*end == '.') ? end + 1 : end;
391 }
392 if (*p) return 1; /* trailing junk */
393 return deny4_any(o);
394 }
395 {
396 unsigned char buf[16];
397#if defined(_WIN32)
398 if (InetPtonA(AF_INET6, ip_text, buf) != 1) return 1;
399#else
400 if (inet_pton(AF_INET6, ip_text, buf) != 1) return 1;
401#endif
402 return deny6_match(buf);
403 }
404}
405
406/* ------------------------------------------------------------------ */
407/* Host header / response head helpers */
408/* ------------------------------------------------------------------ */
409
410static int head_field(const char *head, size_t head_len, const char *name,
411 const char **vout, size_t *vlen)
412{
413 size_t nlen = strlen(name);
414 const char *p = head, *end = head + head_len;
415 while (p < end) {
416 const char *eol = (const char *)memchr(p, '\n', (size_t)(end - p));
417 size_t llen;
418 if (!eol) eol = end;
419 llen = (size_t)(eol - p);
420 if (llen && p[llen - 1] == '\r') llen--;
421 if (llen > nlen && p[nlen] == ':' && sx_strncasecmp(p, name, nlen) == 0) {
422 const char *v = p + nlen + 1;
423 size_t vl = llen - nlen - 1;
424 while (vl && (*v == ' ' || *v == '\t')) { v++; vl--; }
425 while (vl && (v[vl - 1] == ' ' || v[vl - 1] == '\t')) vl--;
426 *vout = v;
427 *vlen = vl;
428 return 1;
429 }
430 p = eol + 1;
431 }
432 return 0;
433}
434
435/* Case-insensitive prefix test used by the no-Content-Type sniffer: servers
436 * emit DOCTYPE in every casing, and a document whose very first token is
437 * <!doctype html or <html is HTML whatever the server forgot to declare. */
438static int ci_prefix(const char *s, const char *prefix)
439{
440 for (; *prefix; s++, prefix++) {
441 unsigned char a = (unsigned char)*s;
442 unsigned char b = (unsigned char)*prefix;
443 if (a >= 'A' && a <= 'Z') a = (unsigned char)(a + 32);
444 if (b >= 'A' && b <= 'Z') b = (unsigned char)(b + 32);
445 if (a != b) return 0;
446 if (!a) return 0; /* both NUL: prefix longer than s */
447 }
448 return 1;
449}
450
451int fx_body_looks_like_html(const char *body, size_t len)
452{
453 size_t i = 0, n;
454 char probe[24];
455 if (!body || !len) return 0;
456 while (i < len && (unsigned char)body[i] <= ' ') i++;
457 if (i + 3 <= len && (unsigned char)body[i] == 0xEF &&
458 (unsigned char)body[i + 1] == 0xBB && (unsigned char)body[i + 2] == 0xBF)
459 i += 3;
460 while (i < len && (unsigned char)body[i] <= ' ') i++;
461 n = len - i < 20 ? len - i : 20;
462 memcpy(probe, body + i, n);
463 probe[n] = '\0';
464 return ci_prefix(probe, "<!doctype html") || ci_prefix(probe, "<html");
465}
466
467/* ------------------------------------------------------------------ */
468/* Resolution + validation (shared by both transports) */
469/* ------------------------------------------------------------------ */
470
471typedef struct {
472 int family; /* AF_INET | AF_INET6 */
473 unsigned char ip[16]; /* numeric address */
474 char text[64];
475} fx_target;
476
477static int fx_resolve_validate(const char *host, int port, int allow_private,
478 fx_target *out, char *err, size_t errsz)
479{
480 struct addrinfo hints, *res = NULL, *ai;
481 char portstr[16];
482 int rc, found = -1;
483 int naddr = 0;
484
485 memset(&hints, 0, sizeof hints);
486 hints.ai_socktype = SOCK_STREAM;
487 snprintf(portstr, sizeof portstr, "%d", port);
488 rc = getaddrinfo(host, portstr, &hints, &res);
489 if (rc != 0 || !res) {
490 snprintf(err, errsz, "Failed to resolve host %s: %s", host, gai_strerror(rc));
491 return -1;
492 }
493 /* Validate EVERY answer first: one private record in the set (even if we
494 * would connect to a public one) refuses the whole host — split-horizon
495 * and round-robin rebinding both die here. */
496 for (ai = res; ai; ai = ai->ai_next) {
497 char ipbuf[64];
498 if (ai->ai_family == AF_INET)
499 inet_ntop(AF_INET, &((struct sockaddr_in *)ai->ai_addr)->sin_addr,
500 ipbuf, sizeof ipbuf);
501 else if (ai->ai_family == AF_INET6)
502 inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr,
503 ipbuf, sizeof ipbuf);
504 else continue;
505 naddr++;
506 if (!allow_private && fx_ip_is_denied(ipbuf)) {
507 snprintf(err, errsz,
508 "Access to private or reserved address space is not allowed. "
509 "The hostname '%s' resolves to a denied address (%s).",
510 host, ipbuf);
511 freeaddrinfo(res);
512 return -1;
513 }
514 }
515 if (naddr == 0) {
516 snprintf(err, errsz, "Failed to resolve host %s: no usable address", host);
517 freeaddrinfo(res);
518 return -1;
519 }
520 /* Pick the first answer; it is validated, and we connect to its numbers. */
521 for (ai = res; ai; ai = ai->ai_next) {
522 if (ai->ai_family == AF_INET) {
523 out->family = AF_INET;
524 memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4);
525 inet_ntop(AF_INET, out->ip, out->text, sizeof out->text);
526 found = 0;
527 break;
528 }
529 if (ai->ai_family == AF_INET6) {
530 out->family = AF_INET6;
531 memcpy(out->ip, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, 16);
532 inet_ntop(AF_INET6, out->ip, out->text, sizeof out->text);
533 found = 0;
534 /* prefer v4 but keep v6 if it came first */
535 if (0) break;
536 }
537 }
538 /* second pass: prefer IPv4 if present */
539 if (found == 0) {
540 for (ai = res; ai; ai = ai->ai_next) {
541 if (ai->ai_family == AF_INET) {
542 out->family = AF_INET;
543 memcpy(out->ip, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, 4);
544 inet_ntop(AF_INET, out->ip, out->text, sizeof out->text);
545 break;
546 }
547 }
548 }
549 freeaddrinfo(res);
550 if (found != 0) {
551 snprintf(err, errsz, "Failed to resolve host %s: no usable address", host);
552 return -1;
553 }
554 return 0;
555}
556
557#if !defined(_WIN32)
558
559/* ------------------------------------------------------------------ */
560/* POSIX transport */
561/* ------------------------------------------------------------------ */
562
563typedef struct {
564 sx_sock fd;
565 fx_tls *tls;
566 long long deadline_ms;
567} sx_trans;
568
569
570static int connect_timeout(int fd, const struct sockaddr *sa, socklen_t slen,
571 int ms, char *err, size_t errsz)
572{
573 int flags, rc, soerr = 0;
574 socklen_t elen = sizeof soerr;
575 struct pollfd pfd;
576
577 flags = fcntl(fd, F_GETFL, 0);
578 if (flags < 0) return -1;
579 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) return -1;
580 rc = connect(fd, sa, slen);
581 if (rc != 0) {
582 if (errno != EINPROGRESS) {
583 snprintf(err, errsz, "connect failed: %s", strerror(errno));
584 return -1;
585 }
586 pfd.fd = fd;
587 pfd.events = POLLOUT;
588 pfd.revents = 0;
589 do { rc = poll(&pfd, 1, ms); } while (rc < 0 && errno == EINTR);
590 if (rc == 0) { snprintf(err, errsz, "connect timed out"); return -1; }
591 if (rc < 0) { snprintf(err, errsz, "connect failed: %s", strerror(errno)); return -1; }
592 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &elen) != 0 || soerr != 0) {
593 snprintf(err, errsz, "connect failed: %s",
594 strerror(soerr ? soerr : ECONNREFUSED));
595 return -1;
596 }
597 }
598 if (fcntl(fd, F_SETFL, flags) < 0) return -1;
599 return 0;
600}
601
602static int trans_read(sx_trans *t, char *buf, size_t n)
603{
604 if (t->tls) return fx_tls_read(t->tls, buf, n);
605 for (;;) {
606 ssize_t r;
607 struct pollfd pfd;
608 long long remain = t->deadline_ms - fx_now_ms();
609 int waited;
610 if (remain <= 0) return -2; /* stalled: EOF-like */
611 pfd.fd = t->fd;
612 pfd.events = POLLIN;
613 pfd.revents = 0;
614 waited = (int)(remain > 500 ? 500 : remain);
615 r = poll(&pfd, 1, waited);
616 if (r < 0) { if (errno == EINTR) continue; return -1; }
617 if (r == 0) continue; /* loop rechecks deadline */
618 if (!(pfd.revents & (POLLIN | POLLHUP | POLLERR))) continue;
619 do { r = recv(t->fd, buf, n, 0); } while (r < 0 && errno == EINTR);
620 if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue;
621 if (r < 0) return -1;
622 if (r == 0) return 0; /* EOF */
623 return (int)r;
624 }
625}
626
627static int trans_write(sx_trans *t, const char *buf, size_t n)
628{
629 if (t->tls) return fx_tls_write(t->tls, buf, n);
630 {
631 size_t off = 0;
632 while (off < n) {
633 ssize_t w = send(t->fd, buf + off, n - off, MSG_NOSIGNAL);
634 if (w < 0) {
635 if (errno == EINTR) continue;
636 return -1;
637 }
638 off += (size_t)w;
639 }
640 return (int)n;
641 }
642}
643
644static void trans_close(sx_trans *t)
645{
646 if (t->tls) { fx_tls_close(t->tls); t->tls = NULL; }
647 if (t->fd != SX_SOCK_INVALID) { sx_closesocket(t->fd); t->fd = SX_SOCK_INVALID; }
648}
649
650/* Reads the head; returns bytes consumed of the terminator inclusive, sets
651 * head_len to the head length (before the terminator), *extra_out to body
652 * bytes that arrived in the same window (0 — we always read exactly the
653 * head window with a small overread stash). On hard failure, -1; on deadline,
654 * -2. */
655typedef struct { char *p; size_t n; size_t cap; } sx_stash;
656
657static int read_head(sx_trans *t, char *head, size_t cap, size_t *hlen_out,
658 sx_stash *stash)
659{
660 size_t n = 0;
661 size_t scanned = 0;
662 for (;;) {
663 size_t i;
664 int r = trans_read(t, head + n, cap - n > 1024 ? 1024 : cap - n);
665 if (r == -2) return n ? -1 : -2;
666 if (r < 0) return -1;
667 if (r == 0) { /* EOF */
668 if (n == 0) return -1;
669 *hlen_out = n; /* no terminator: whole thing is head */
670 stash->p = NULL; stash->n = 0;
671 return (int)n;
672 }
673 n += (size_t)r;
674 if (n >= cap) return -1; /* oversized head */
675 /* scan for the terminator; the window may re-include up to 3 bytes
676 * already scanned so a terminator split across two reads is found */
677 if (scanned > 3) scanned -= 3;
678 for (i = scanned; i + 1 < n; i++) {
679 if (head[i] == '\n') {
680 size_t headlen;
681 size_t term;
682 if (i >= 3 && head[i - 1] == '\r' && head[i - 2] == '\n' &&
683 head[i - 3] == '\r') {
684 headlen = i - 1; term = 4;
685 } else if (i >= 1 && head[i - 1] == '\n') {
686 headlen = i - 1; term = 2; /* tolerate bare \n\n */
687 } else continue;
688 *hlen_out = headlen;
689 if (n > i + 1) {
690 stash->p = head + (i + 1);
691 stash->n = n - (i + 1);
692 } else { stash->p = NULL; stash->n = 0; }
693 (void)term;
694 return (int)n;
695 }
696 }
697 scanned = n;
698 }
699}
700
701static int exchange_plain(const fx_url *u, const char *urltext, fx_response *r,
702 int allow_private)
703{
704 sx_trans t;
705 fx_target tgt;
706 char req[4300];
707 char *head;
708 size_t head_len = 0;
709 sx_stash stash;
710 const char *v; size_t vl;
711 buf_t body;
712 long long clen = -1;
713 int chunked = 0, gzip = 0;
714 int status, fd, rc;
715 struct sockaddr_storage ss;
716 socklen_t slen;
717 const char *UA =
718 "SCORPIOXBOT-fetch/1.0 (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-fetch)";
719 int host_has_port = !((strcmp(u->scheme, "http") == 0 && u->port == 80) ||
720 (strcmp(u->scheme, "https") == 0 && u->port == 443));
721
722 memset(&t, 0, sizeof t);
723 t.fd = SX_SOCK_INVALID;
724 t.deadline_ms = fx_now_ms() + FX_CONNECT_MS + FX_READ_MS;
725
726 if (fx_resolve_validate(u->host, u->port, allow_private, &tgt,
727 r->error, sizeof r->error) != 0)
728 return -1;
729
730 fd = socket(tgt.family, SOCK_STREAM, 0);
731 if (fd < 0) { snprintf(r->error, sizeof r->error, "socket() failed"); return -1; }
732 memset(&ss, 0, sizeof ss);
733 if (tgt.family == AF_INET) {
734 struct sockaddr_in *sa = (struct sockaddr_in *)&ss;
735 sa->sin_family = AF_INET;
736 sa->sin_port = htons((unsigned short)u->port);
737 memcpy(&sa->sin_addr, tgt.ip, 4);
738 slen = sizeof *sa;
739 } else {
740 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&ss;
741 sa->sin6_family = AF_INET6;
742 sa->sin6_port = htons((unsigned short)u->port);
743 memcpy(&sa->sin6_addr, tgt.ip, 16);
744 slen = sizeof *sa;
745 }
746 if (connect_timeout(fd, (struct sockaddr *)&ss, slen, FX_CONNECT_MS,
747 r->error, sizeof r->error) != 0) {
748 close(fd);
749 return -1;
750 }
751 t.fd = fd;
752
753 if (strcmp(u->scheme, "https") == 0) {
754 char terr[256] = "";
755 t.tls = fx_tls_connect_fd(t.fd, u->host, terr, sizeof terr);
756 if (!t.tls) {
757 snprintf(r->error, sizeof r->error, "%s",
758 terr[0] ? terr : "TLS handshake failed");
759 close(t.fd);
760 t.fd = SX_SOCK_INVALID;
761 return -1;
762 }
763 t.fd = SX_SOCK_INVALID; /* owned by the TLS layer now */
764 }
765
766 snprintf(req, sizeof req,
767 "GET %s HTTP/1.1\r\n"
768 "Host: %s%s%s\r\n"
769 "User-Agent: %s\r\n"
770 "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n"
771 "Accept-Encoding: identity\r\n"
772 "Connection: close\r\n\r\n",
773 u->path, u->host, host_has_port ? ":" : "",
774 host_has_port ? "" : "", UA);
775 if (host_has_port) {
776 snprintf(req, sizeof req,
777 "GET %s HTTP/1.1\r\n"
778 "Host: %s:%d\r\n"
779 "User-Agent: %s\r\n"
780 "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n"
781 "Accept-Encoding: identity\r\n"
782 "Connection: close\r\n\r\n",
783 u->path, u->host, u->port, UA);
784 }
785 if (trans_write(&t, req, strlen(req)) < 0) {
786 snprintf(r->error, sizeof r->error,
787 "Failed to fetch %s: the server did not accept our request", urltext);
788 trans_close(&t);
789 return -1;
790 }
791
792 head = (char *)sx_malloc(FX_MAX_HEAD + 1);
793 rc = read_head(&t, head, FX_MAX_HEAD, &head_len, &stash);
794 if (rc < 0) {
795 snprintf(r->error, sizeof r->error, rc == -2
796 ? "Failed to fetch %s: timed out reading the response head"
797 : "Failed to fetch %s: bad or oversized response head", urltext);
798 free(head);
799 trans_close(&t);
800 return -1;
801 }
802 head[head_len] = '\0';
803
804 if (strncmp(head, "HTTP/", 5) != 0) {
805 snprintf(r->error, sizeof r->error,
806 "Failed to fetch %s: not an HTTP response", urltext);
807 free(head);
808 trans_close(&t);
809 return -1;
810 }
811 status = atoi(head + 9);
812 r->status = status;
813
814 if (head_field(head, head_len, "content-type", &v, &vl)) {
815 size_t n = vl < sizeof r->content_type - 1 ? vl : sizeof r->content_type - 1;
816 memcpy(r->content_type, v, n);
817 r->content_type[n] = '\0';
818 }
819 {
820 char nbuf[32];
821 if (head_field(head, head_len, "content-length", &v, &vl)) {
822 size_t n = vl < sizeof nbuf - 1 ? vl : sizeof nbuf - 1;
823 memcpy(nbuf, v, n); nbuf[n] = '\0';
824 clen = atoll(nbuf);
825 if (clen > (long long)FX_MAX_BODY) {
826 snprintf(r->error, sizeof r->error,
827 "Failed to fetch %s: the response body is larger than the "
828 "%u byte limit this plugin reads", urltext, FX_MAX_BODY);
829 free(head);
830 trans_close(&t);
831 return -1;
832 }
833 }
834 if (head_field(head, head_len, "transfer-encoding", &v, &vl) &&
835 vl >= 7 && sx_strncasecmp(v, "chunked", 7) == 0)
836 chunked = 1;
837#ifdef HAVE_ZLIB
838 if (head_field(head, head_len, "content-encoding", &v, &vl) &&
839 vl >= 4 && sx_strncasecmp(v, "gzip", 4) == 0)
840 gzip = 1;
841#else
842 if (head_field(head, head_len, "content-encoding", &v, &vl) && vl) {
843 char enc[64];
844 size_t n = vl < sizeof enc - 1 ? vl : sizeof enc - 1;
845 memcpy(enc, v, n); enc[n] = '\0';
846 if (sx_strcasecmp(enc, "identity") != 0) {
847 snprintf(r->error, sizeof r->error,
848 "Unsupported content encoding %s: this server cannot decode it",
849 enc);
850 free(head);
851 trans_close(&t);
852 return -1;
853 }
854 }
855#endif
856 }
857
858 if ((status == 301 || status == 302 || status == 303 ||
859 status == 307 || status == 308) &&
860 head_field(head, head_len, "location", &v, &vl)) {
861 size_t n = vl < sizeof r->url - 1 ? vl : sizeof r->url - 1;
862 memcpy(r->url, v, n);
863 r->url[n] = '\0';
864 free(head);
865 trans_close(&t);
866 return 2;
867 }
868
869 buf_init(&body);
870 fx_md_set_base_url(urltext); /* relativise links during conversion */
871
872 if (chunked) {
873 /* stream chunk framing directly; bytes that arrived in the same read
874 * window as the head terminator seed the framing buffer (they are
875 * chunk data, NOT body — appending them raw would emit the hex size
876 * line as content) */
877 char small[4096];
878 size_t sp = 0, sn = 0;
879 int dead = 0;
880 if (stash.n) { memcpy(small, stash.p, stash.n); sn = stash.n; }
881#define CHUNK_GETC(ch) \
882 do { \
883 int _done = 0; \
884 while (!_done) { \
885 if (sp < sn) { (ch) = small[sp++]; _done = 1; break; } \
886 { \
887 int _r = trans_read(&t, small, sizeof small); \
888 if (_r == 0) { dead = 1; _done = 1; break; } \
889 if (_r < 0) { dead = -1; _done = 1; break; } \
890 sn = (size_t)_r; sp = 0; \
891 } \
892 } \
893 } while (0)
894 for (;;) {
895 char ch = 0;
896 char hex[24];
897 size_t hn = 0;
898 unsigned long csz;
899 CHUNK_GETC(ch);
900 if (dead) break;
901 if (ch == '\r' || ch == '\n') continue; /* skip CRLFs between chunks */
902 hex[hn++] = ch;
903 while (hn < sizeof hex - 1) {
904 CHUNK_GETC(ch);
905 if (dead) break;
906 if (ch == '\r') { CHUNK_GETC(ch); if (dead) break; if (ch == '\n') break; }
907 else if (ch == '\n') break;
908 hex[hn++] = ch;
909 }
910 if (dead) break;
911 hex[hn] = '\0';
912 { char *semi = strchr(hex, ';'); if (semi) *semi = '\0'; }
913 csz = strtoul(hex, NULL, 16);
914 if (csz == 0) break;
915 if (body.n + csz > FX_MAX_BODY) {
916 buf_free(&body); free(head); trans_close(&t);
917 snprintf(r->error, sizeof r->error,
918 "Failed to fetch %s: the response body is larger than the "
919 "%u byte limit this plugin reads", urltext, FX_MAX_BODY);
920 return -1;
921 }
922 while (csz > 0) {
923 size_t take;
924 if (sp >= sn) {
925 int _r = trans_read(&t, small, sizeof small);
926 if (_r <= 0) {
927 buf_free(&body); free(head); trans_close(&t);
928 snprintf(r->error, sizeof r->error,
929 "Failed to fetch %s: truncated chunked body", urltext);
930 return -1;
931 }
932 sn = (size_t)_r; sp = 0;
933 }
934 take = sn - sp;
935 if (take > csz) take = csz;
936 buf_bput(&body, small + sp, take);
937 sp += take; csz -= take;
938 }
939 }
940#undef CHUNK_GETC
941 } else if (clen >= 0) {
942 size_t want = (size_t)clen;
943 if (stash.n) buf_bput(&body, stash.p, stash.n);
944 if (want > body.n) {
945 size_t need = want - body.n;
946 char *tmp = (char *)sx_malloc(need);
947 size_t got = 0;
948 while (got < need) {
949 int rr = trans_read(&t, tmp + got, need - got);
950 if (rr <= 0) {
951 free(tmp); buf_free(&body); free(head); trans_close(&t);
952 snprintf(r->error, sizeof r->error,
953 "Failed to fetch %s: the server closed before the "
954 "declared body was complete", urltext);
955 return -1;
956 }
957 got += (size_t)rr;
958 }
959 buf_bput(&body, tmp, need);
960 free(tmp);
961 }
962 } else {
963 char tmp[8192];
964 if (stash.n) buf_bput(&body, stash.p, stash.n);
965 for (;;) {
966 int rr = trans_read(&t, tmp, sizeof tmp);
967 if (rr == -2 || rr == 0) break;
968 if (rr < 0) {
969 buf_free(&body); free(head); trans_close(&t);
970 snprintf(r->error, sizeof r->error,
971 "Failed to fetch %s: body read failed", urltext);
972 return -1;
973 }
974 if (body.n + (size_t)rr > FX_MAX_BODY) {
975 buf_free(&body); free(head); trans_close(&t);
976 snprintf(r->error, sizeof r->error,
977 "Failed to fetch %s: the response body is larger than the "
978 "%u byte limit this plugin reads", urltext, FX_MAX_BODY);
979 return -1;
980 }
981 buf_bput(&body, tmp, (size_t)rr);
982 }
983 }
984
985 free(head);
986 trans_close(&t);
987
988#ifdef HAVE_ZLIB
989 if (gzip && body.n > 18 && (unsigned char)body.p[0] == 0x1f &&
990 (unsigned char)body.p[1] == 0x8b) {
991 uLongf cap = (uLongf)(body.n * 16 + 4096);
992 int inflated = 0;
993 while (!inflated && cap <= FX_MAX_BODY) {
994 char *outb = (char *)sx_malloc(cap + 1);
995 z_stream zs;
996 int zr;
997 memset(&zs, 0, sizeof zs);
998 zs.next_in = (Bytef *)body.p;
999 zs.avail_in = (uInt)body.n;
1000 zs.next_out = (Bytef *)outb;
1001 zs.avail_out = (uInt)cap;
1002 zr = inflateInit2(&zs, 15 + 16);
1003 if (zr == Z_OK) zr = inflate(&zs, Z_FINISH);
1004 if (zr == Z_STREAM_END) {
1005 free(body.p);
1006 body.p = outb;
1007 body.n = (size_t)zs.total_out;
1008 body.p[body.n] = '\0';
1009 inflated = 1;
1010 } else {
1011 free(outb);
1012 cap *= 4;
1013 }
1014 inflateEnd(&zs);
1015 }
1016 /* if it never inflated, keep the raw bytes: they are still an honest
1017 * answer for a server that mislabelled its payload */
1018 }
1019#else
1020 (void)gzip;
1021#endif
1022
1023 r->body = body.p ? body.p : fx_strndup("", 0);
1024 r->body_len = body.n;
1025 return 0;
1026}
1027
1028#endif /* !_WIN32 */
1029
1030/* ------------------------------------------------------------------ */
1031/* WinHTTP transport */
1032/* ------------------------------------------------------------------ */
1033
1034#if defined(_WIN32)
1035
1036static void a2w(const char *a, wchar_t *w, int wn)
1037{
1038 MultiByteToWideChar(CP_UTF8, 0, a, -1, w, wn);
1039}
1040
1041static int exchange_winhttp(const fx_url *u, const char *urltext, fx_response *r,
1042 int allow_private)
1043{
1044 HINTERNET sess = NULL, conn = NULL, req = NULL;
1045 wchar_t wtarget[1024], wpath[2100];
1046 fx_target tgt;
1047 char target_ip[64];
1048 wchar_t whdr[128];
1049 DWORD avail = 0;
1050 BOOL ok;
1051 buf_t body;
1052 int status = 0;
1053
1054 if (fx_resolve_validate(u->host, u->port, allow_private, &tgt,
1055 r->error, sizeof r->error) != 0)
1056 return -1;
1057 snprintf(target_ip, sizeof target_ip, "%s", tgt.text);
1058
1059 sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0",
1060 WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
1061 WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
1062 if (!sess)
1063 sess = WinHttpOpen(L"SCORPIOXBOT-fetch/1.0",
1064 WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
1065 WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
1066 if (!sess) { snprintf(r->error, sizeof r->error, "WinHttpOpen failed"); return -1; }
1067 WinHttpSetTimeouts(sess, FX_CONNECT_MS, FX_CONNECT_MS, FX_READ_MS, FX_READ_MS);
1068
1069 /* connect to the validated numeric IP; Host + SNI carry the real name */
1070 a2w(target_ip, wtarget, 1024);
1071 a2w(u->path, wpath, 2100);
1072
1073 conn = WinHttpConnect(sess, wtarget, (INTERNET_PORT)u->port, 0);
1074 if (!conn) {
1075 snprintf(r->error, sizeof r->error, "Failed to connect to %s", u->host);
1076 WinHttpCloseHandle(sess);
1077 return -1;
1078 }
1079 {
1080 DWORD flags = strcmp(u->scheme, "https") == 0 ? WINHTTP_FLAG_SECURE : 0;
1081 req = WinHttpOpenRequest(conn, L"GET", wpath, NULL, WINHTTP_NO_REFERER,
1082 WINHTTP_DEFAULT_ACCEPT_TYPES, flags);
1083 }
1084 if (!req) {
1085 snprintf(r->error, sizeof r->error, "WinHttpOpenRequest failed");
1086 WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
1087 return -1;
1088 }
1089 {
1090 DWORD sec = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 |
1091 WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3;
1092 WinHttpSetOption(req, WINHTTP_OPTION_SECURE_PROTOCOLS, &sec, sizeof sec);
1093 }
1094 {
1095 /* Our own redirect loop owns every hop (each one re-resolved and
1096 * re-validated), so WinHTTP must not follow any on its own.
1097 * _NEVER is the documented spelling; _NONE is what the WinRT
1098 * WINHTTP_REDIRECT_POLICY enum calls it and MinGW's winhttp.h does
1099 * not define _NONE at all. */
1100 DWORD pol = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
1101 WinHttpSetOption(req, WINHTTP_OPTION_REDIRECT_POLICY, &pol, sizeof pol);
1102 }
1103 {
1104 wchar_t wh[640];
1105 char hs[520];
1106 int defport = (strcmp(u->scheme, "https") == 0) ? 443 : 80;
1107 if (u->port != defport)
1108 snprintf(hs, sizeof hs,
1109 "Host: %s:%d\r\n"
1110 "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n"
1111 "Accept-Encoding: identity\r\n",
1112 u->host, u->port);
1113 else
1114 snprintf(hs, sizeof hs,
1115 "Host: %s\r\n"
1116 "Accept: text/markdown, text/html;q=0.9, */*;q=0.8\r\n"
1117 "Accept-Encoding: identity\r\n",
1118 u->host);
1119 a2w(hs, wh, 640);
1120 WinHttpAddRequestHeaders(req, wh, (DWORD)-1,
1121 WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
1122 }
1123
1124 ok = WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
1125 WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
1126 if (!ok || !WinHttpReceiveResponse(req, NULL)) {
1127 snprintf(r->error, sizeof r->error,
1128 "Failed to fetch %s: TLS or connection error (certificate refused "
1129 "or host unreachable)", urltext);
1130 WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
1131 return -1;
1132 }
1133
1134 {
1135 DWORD sz = sizeof status;
1136 WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
1137 WINHTTP_HEADER_NAME_BY_INDEX, &status, &sz,
1138 WINHTTP_NO_HEADER_INDEX);
1139 r->status = (int)status;
1140 }
1141 {
1142 wchar_t wct[256];
1143 DWORD sz = sizeof wct;
1144 wct[0] = L'\0';
1145 if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_TYPE,
1146 WINHTTP_HEADER_NAME_BY_INDEX, wct, &sz,
1147 WINHTTP_NO_HEADER_INDEX))
1148 WideCharToMultiByte(CP_UTF8, 0, wct, -1, r->content_type,
1149 sizeof r->content_type, NULL, NULL);
1150 }
1151 if (r->status == 301 || r->status == 302 || r->status == 303 ||
1152 r->status == 307 || r->status == 308) {
1153 wchar_t wloc[1024];
1154 DWORD sz = sizeof wloc;
1155 wloc[0] = L'\0';
1156 a2w("Location", whdr, 128);
1157 if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CUSTOM, whdr, wloc, &sz,
1158 WINHTTP_NO_HEADER_INDEX)) {
1159 WideCharToMultiByte(CP_UTF8, 0, wloc, -1, r->url, sizeof r->url,
1160 NULL, NULL);
1161 WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
1162 return 2;
1163 }
1164 }
1165
1166 buf_init(&body);
1167 for (;;) {
1168 if (!WinHttpQueryDataAvailable(req, &avail)) break;
1169 if (avail == 0) break;
1170 {
1171 DWORD take = avail > 65536 ? 65536 : avail;
1172 char *tmp;
1173 DWORD rd = 0;
1174 if (body.n + take > FX_MAX_BODY) {
1175 buf_free(&body);
1176 WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
1177 snprintf(r->error, sizeof r->error,
1178 "Failed to fetch %s: the response body is larger than the "
1179 "%u byte limit this plugin reads", urltext, FX_MAX_BODY);
1180 return -1;
1181 }
1182 tmp = (char *)sx_malloc(take + 1);
1183 if (!WinHttpReadData(req, tmp, take, &rd) || rd == 0) { free(tmp); break; }
1184 tmp[rd] = '\0';
1185 buf_bput(&body, tmp, rd);
1186 free(tmp);
1187 }
1188 }
1189
1190 WinHttpCloseHandle(req); WinHttpCloseHandle(conn); WinHttpCloseHandle(sess);
1191 r->body = body.p ? body.p : fx_strndup("", 0);
1192 r->body_len = body.n;
1193 return 0;
1194}
1195
1196#endif /* _WIN32 */
1197
1198/* ------------------------------------------------------------------ */
1199/* fx_fetch — the redirect loop */
1200/* ------------------------------------------------------------------ */
1201
1202int fx_fetch(const char *url, fx_response *r)
1203{
1204 fx_url u;
1205 char urltext[1100];
1206 int hops = 0;
1207 int allow_private = 0;
1208 const char *env;
1209
1210 memset(r, 0, sizeof *r);
1211 env = getenv("FETCH_ALLOW_PRIVATE");
1212 if (env && *env && strcmp(env, "0") != 0) allow_private = 1;
1213 if (fx_policy_allow_private()) allow_private = 1;
1214
1215 if (fx_url_parse(url, &u, r->error, sizeof r->error) != 0) return -1;
1216 snprintf(r->first_url, sizeof r->first_url, "%s", url);
1217
1218 for (;;) {
1219 int rc;
1220 fx_url_build(&u, urltext, sizeof urltext);
1221 r->url[0] = '\0';
1222 free(r->body);
1223 r->body = NULL;
1224 r->body_len = 0;
1225 r->content_type[0] = '\0';
1226
1227#if defined(_WIN32)
1228 rc = exchange_winhttp(&u, urltext, r, allow_private);
1229#else
1230 rc = exchange_plain(&u, urltext, r, allow_private);
1231#endif
1232 if (rc == 0) {
1233 if (!r->url[0]) snprintf(r->url, sizeof r->url, "%s", urltext);
1234 r->ok = 1;
1235 r->hops = hops;
1236 return 0;
1237 }
1238 if (rc == 2) {
1239 if (++hops > FX_MAX_REDIRECTS) {
1240 snprintf(r->error, sizeof r->error,
1241 "Exceeded maximum allowed redirects.");
1242 return -1;
1243 }
1244 /* Absolute-ise the Location against the CURRENT url: a bare
1245 * "relative" resolves against the directory of the current path,
1246 * "/abs" against the authority, and anything carrying "://" is
1247 * already absolute. fx_url_resolve is the single place that owns
1248 * those rules. Every hop then re-enters the same
1249 * parse/resolve/validate path, so each new address is SSRF
1250 * checked before it is connected to. */
1251 {
1252 fx_url next;
1253 if (fx_url_resolve(&u, r->url, &next, r->error,
1254 sizeof r->error) != 0)
1255 return -1;
1256 u = next;
1257 }
1258 continue;
1259 }
1260 return -1;
1261 }
1262}
1263
1264void fx_response_free(fx_response *r)
1265{
1266 if (!r) return;
1267 free(r->body);
1268 r->body = NULL;
1269 r->body_len = 0;
1270}