gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit56e70dcb56e70dcbrecords: review time limit 1800 s (routger 132)mre56e70dcb/plugins/fetch/fetch.zig

68.0 KB

  1. // hl:fetch — the HTTP(S) CLIENT, as a server-realm plugin (mission 135).
  2. //
  3. // Shaped on the web `fetch` the creator already knows: a method, a url, headers and
  4. // a body go out; a status, headers and a body come back. What is NOT web-shaped is
  5. // where the wait happens, and that is the one design decision in this file:
  6. //
  7. // `fetch.start` NEVER WAITS. It hands the request to a thread of its own and
  8. // returns a TICKET (an HlHandle) immediately. `ticket.result()` is the wait.
  9. //
  10. // `fetch()` in server.hl is `fetchStart(…).response()` — start plus wait.
  11. // PendingFetch.response() yields the calling delivery fiber while the worker
  12. // runs; concurrent arms and other event-loop deliveries can keep progressing.
  13. // At the process root there is no delivery fiber, so reading a result can block.
  14. //
  15. // THE EVENT LOOP is never blocked by a fetch in flight: no loop thread is inside a
  16. // socket call, and a completed request rings the mission-125 BELL — `fetch.completions`
  17. // is an ordinary loop source with a `wake_fd`, so an `on fetched(ev)` handler is woken
  18. // by the same `epoll_wait` that wakes an http1 request. (The wait in `result()` is a
  19. // wait like any other plugin call's: it blocks the FIBER that asked. Starting the
  20. // fetches early and reading them later is what keeps a server serving, and the
  21. // completions source is how a server never has to wait at all.)
  22. //
  23. // TLS is `plugins/http/tls_common.zig` — the same module hl:http1 and hl:http2 use,
  24. // extended with a client half in this mission. Verification is ON: system trust
  25. // store plus hostname checking, with `caFile` naming an EXTRA anchor for a test
  26. // fixture's self-signed certificate. There is no verify-off switch at all.
  27. //
  28. // HTTP/1.1 only. An h2 client is a later slice: it needs ALPN on the client side and
  29. // a multiplexed connection pool, neither of which this file has. `connection: close`
  30. // on every request, so there is no pool to keep coherent either.
  31. const std = @import("std");
  32. const api = @import("plugin_api");
  33. const http = @import("http_common");
  34. const tls = @import("tls_common");
  35. const HlValue = api.HlValue;
  36. const HlField = api.HlField;
  37. const HlObject = api.HlObject;
  38. const HlIterator = api.HlIterator;
  39. const HlHandle = api.HlHandle;
  40. const c = @cImport({
  41. @cInclude("netdb.h");
  42. @cInclude("sys/socket.h");
  43. @cInclude("sys/time.h");
  44. @cInclude("unistd.h");
  45. @cInclude("netinet/in.h");
  46. @cInclude("netinet/tcp.h");
  47. });
  48. // requests run on their own threads: the plugins' allocator (plugin_api.zig)
  49. const allocator = api.allocator;
  50. const linux = std.os.linux;
  51. const libc = std.c;
  52. // pthread rather than std.Thread.Mutex, exactly as hl:http1 does: this is a `.so`
  53. // loaded into a binary built by a possibly different Zig, and the C primitives are
  54. // the ones whose ABI is fixed by the platform rather than by the standard library.
  55. const PthreadMutex = libc.pthread_mutex_t;
  56. const PthreadCond = libc.pthread_cond_t;
  57. fn mutexLock(m: *PthreadMutex) void {
  58. _ = libc.pthread_mutex_lock(m);
  59. }
  60. fn mutexUnlock(m: *PthreadMutex) void {
  61. _ = libc.pthread_mutex_unlock(m);
  62. }
  63. fn condBroadcast(cnd: *PthreadCond) void {
  64. _ = libc.pthread_cond_broadcast(cnd);
  65. }
  66. fn condWait(cnd: *PthreadCond, m: *PthreadMutex) void {
  67. _ = libc.pthread_cond_wait(cnd, m);
  68. }
  69. fn logMsg(msg: []const u8) void {
  70. _ = linux.write(2, msg.ptr, msg.len);
  71. }
  72. fn logFmt(comptime fmt: []const u8, args: anytype) void {
  73. var buf: [512]u8 = undefined;
  74. const s = std.fmt.bufPrint(&buf, fmt, args) catch return;
  75. logMsg(s);
  76. }
  77. // ── Limits, all of them documented defaults rather than hard walls ───────────
  78. /// No answer at all within this many milliseconds is a failed fetch. Overridable
  79. /// per call with `timeoutMs`; it covers the WHOLE exchange (DNS, connect,
  80. /// handshake, request, response, and every redirect hop), not one syscall.
  81. const DEFAULT_TIMEOUT_MS: i64 = 30_000;
  82. /// How many 3xx hops are followed before the fetch fails with "too many redirects".
  83. /// Overridable with `maxRedirects`; 0 means the 3xx is RETURNED as the response.
  84. const DEFAULT_MAX_REDIRECTS: u32 = 5;
  85. /// A response body larger than this fails rather than growing the process without
  86. /// bound — a client that pulls other people's APIs must not be a memory bomb.
  87. const MAX_BODY: usize = 32 * 1024 * 1024;
  88. /// O_NONBLOCK on x86-64 Linux. Spelled here because <fcntl.h> cannot be imported
  89. /// (see tcpConnect); it is an ABI constant, not a libc detail.
  90. const O_NONBLOCK: usize = 0o4000;
  91. const Header = struct {
  92. name: []u8,
  93. value: []u8,
  94. };
  95. fn sameOrigin(a: Url, b: Url) bool {
  96. return a.https == b.https and a.port == b.port and std.ascii.eqlIgnoreCase(a.host, b.host);
  97. }
  98. fn sensitiveHeader(name: []const u8) bool {
  99. return std.ascii.eqlIgnoreCase(name, "authorization") or
  100. std.ascii.eqlIgnoreCase(name, "proxy-authorization") or
  101. std.ascii.eqlIgnoreCase(name, "cookie");
  102. }
  103. fn freeHeaders(list: []Header) void {
  104. for (list) |h| {
  105. allocator.free(h.name);
  106. allocator.free(h.value);
  107. }
  108. allocator.free(list);
  109. }
  110. // ── The request, as the ticket carries it ────────────────────────────────────
  111. const Request = struct {
  112. method: []u8,
  113. url: []u8,
  114. headers: []Header,
  115. body: []u8,
  116. has_body: bool,
  117. json_body: bool,
  118. timeout_ms: i64,
  119. max_redirects: u32,
  120. ca_file: ?[]u8,
  121. tag: []u8,
  122. strip_credentials: bool = false,
  123. drop_body_headers: bool = false,
  124. /// STREAMING (the LLM-token mode): deliver the body INCREMENTALLY as chunk
  125. /// events on the completions source instead of accumulating it. The final
  126. /// completion then carries status/headers and an EMPTY body — the chunks
  127. /// were the body. Requires an armed completions source; `result()` still
  128. /// works and yields the empty-body summary when the stream ends.
  129. stream: bool = false,
  130. fn deinit(self: *Request) void {
  131. allocator.free(self.method);
  132. allocator.free(self.url);
  133. freeHeaders(self.headers);
  134. allocator.free(self.body);
  135. if (self.ca_file) |ca| allocator.free(ca);
  136. allocator.free(self.tag);
  137. }
  138. };
  139. // ── The ticket: one in-flight (or finished) request ──────────────────────────
  140. const Ticket = struct {
  141. mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER,
  142. cond: PthreadCond = libc.PTHREAD_COND_INITIALIZER,
  143. done: bool = false,
  144. thread: ?std.Thread = null,
  145. req: Request,
  146. status: u16 = 0,
  147. final_url: []u8 = &.{},
  148. headers: []Header = &.{},
  149. body: []u8 = &.{},
  150. /// Non-null = the fetch failed and this is the located message the handle
  151. /// hands back as an `hl_error`.
  152. err: ?[]u8 = null,
  153. /// ABORT (the LLM-interrupt primitive): the socket currently carrying this
  154. /// request, visible under the ticket mutex so `fetchAbort(tag)` can
  155. /// shutdown() it from the interpreter thread — the read unblocks, the peer
  156. /// sees the disconnect and stops generating. -1 = none in flight.
  157. live_fd: i32 = -1,
  158. aborted: bool = false,
  159. /// INSTANCE EVENTS (stream mode): a streaming ticket carries its OWN frame
  160. /// queue and bell, created at start — before the worker exists — so no chunk
  161. /// can outrun the arming. `handle.events()` wraps them into a loop source;
  162. /// pending_fetch.hl registers it and re-emits `chunk`/`done` at itself.
  163. /// -1 = not a streaming ticket (completions go the global route, if armed).
  164. ev_queue: std.ArrayListUnmanaged(Completion) = .empty,
  165. ev_wake_fd: i32 = -1,
  166. /// THE PARKED FIBER'S BELL (lazy, under the mutex): `doneFd()` makes an eventfd
  167. /// that finish() rings, so a `concurrent` group whose arms all wait on fetches
  168. /// sleeps in poll() on these instead of spinning. -1 = nobody asked.
  169. done_fd: i32 = -1,
  170. fn doneFd(self: *Ticket) i32 {
  171. mutexLock(&self.mutex);
  172. defer mutexUnlock(&self.mutex);
  173. if (self.done_fd < 0) {
  174. self.done_fd = http.makeWakeFd();
  175. if (self.done and self.done_fd >= 0) http.ringWake(self.done_fd);
  176. }
  177. return self.done_fd;
  178. }
  179. fn wait(self: *Ticket) void {
  180. mutexLock(&self.mutex);
  181. while (!self.done) condWait(&self.cond, &self.mutex);
  182. mutexUnlock(&self.mutex);
  183. }
  184. fn isDone(self: *Ticket) bool {
  185. mutexLock(&self.mutex);
  186. defer mutexUnlock(&self.mutex);
  187. return self.done;
  188. }
  189. fn setLiveFd(self: *Ticket, fd: i32) bool {
  190. mutexLock(&self.mutex);
  191. defer mutexUnlock(&self.mutex);
  192. if (self.aborted) return false; // aborted before the connect landed
  193. self.live_fd = fd;
  194. return true;
  195. }
  196. fn clearLiveFd(self: *Ticket) void {
  197. mutexLock(&self.mutex);
  198. self.live_fd = -1;
  199. mutexUnlock(&self.mutex);
  200. }
  201. /// The abort itself: mark, and shutdown() any in-flight socket so the
  202. /// worker's blocking read returns NOW. Closing is still the worker's job
  203. /// (its defer owns the fd); shutdown only cuts the conversation.
  204. fn abort(self: *Ticket) void {
  205. mutexLock(&self.mutex);
  206. self.aborted = true;
  207. if (self.live_fd >= 0) _ = c.shutdown(self.live_fd, 2); // SHUT_RDWR
  208. mutexUnlock(&self.mutex);
  209. }
  210. fn finish(self: *Ticket) void {
  211. mutexLock(&self.mutex);
  212. self.done = true;
  213. http.ringWake(self.done_fd);
  214. condBroadcast(&self.cond);
  215. mutexUnlock(&self.mutex);
  216. }
  217. fn fail(self: *Ticket, comptime fmt: []const u8, args: anytype) void {
  218. self.err = std.fmt.allocPrint(allocator, fmt, args) catch null;
  219. }
  220. };
  221. // ── URL ──────────────────────────────────────────────────────────────────────
  222. const Url = struct {
  223. https: bool,
  224. host: []const u8,
  225. port: u16,
  226. /// path + query, always starting with '/'
  227. target: []const u8,
  228. };
  229. /// `scheme://host[:port][/path][?query]`. Only http and https; a URL with
  230. /// credentials or an IPv6 literal is refused rather than half-understood.
  231. fn parseUrl(url: []const u8) ?Url {
  232. var rest: []const u8 = undefined;
  233. var https = false;
  234. if (std.mem.startsWith(u8, url, "http://")) {
  235. rest = url["http://".len..];
  236. } else if (std.mem.startsWith(u8, url, "https://")) {
  237. rest = url["https://".len..];
  238. https = true;
  239. } else return null;
  240. const slash = std.mem.indexOfScalar(u8, rest, '/');
  241. const authority = if (slash) |s| rest[0..s] else rest;
  242. const target = if (slash) |s| rest[s..] else "/";
  243. if (authority.len == 0) return null;
  244. if (std.mem.indexOfScalar(u8, authority, '@') != null) return null;
  245. if (std.mem.indexOfScalar(u8, authority, '[') != null) return null;
  246. var host = authority;
  247. var port: u16 = if (https) 443 else 80;
  248. if (std.mem.lastIndexOfScalar(u8, authority, ':')) |colon| {
  249. host = authority[0..colon];
  250. port = std.fmt.parseInt(u16, authority[colon + 1 ..], 10) catch return null;
  251. }
  252. if (host.len == 0) return null;
  253. return .{ .https = https, .host = host, .port = port, .target = target };
  254. }
  255. /// Resolve a `Location` against the URL it came from: absolute stays, `/x` replaces
  256. /// the path, anything else is relative to the current directory of the path.
  257. fn resolveLocation(base: []const u8, loc: []const u8) ?[]u8 {
  258. if (loc.len == 0) return null;
  259. if (std.mem.startsWith(u8, loc, "http://") or std.mem.startsWith(u8, loc, "https://")) {
  260. return allocator.dupe(u8, loc) catch null;
  261. }
  262. const b = parseUrl(base) orelse return null;
  263. const scheme = if (b.https) "https" else "http";
  264. const default_port: u16 = if (b.https) 443 else 80;
  265. var authority_buf: [300]u8 = undefined;
  266. const authority = if (b.port == default_port)
  267. std.fmt.bufPrint(&authority_buf, "{s}", .{b.host}) catch return null
  268. else
  269. std.fmt.bufPrint(&authority_buf, "{s}:{d}", .{ b.host, b.port }) catch return null;
  270. if (loc[0] == '/') {
  271. return std.fmt.allocPrint(allocator, "{s}://{s}{s}", .{ scheme, authority, loc }) catch null;
  272. }
  273. // Relative: cut the base target back to its last '/'.
  274. const path_only = if (std.mem.indexOfScalar(u8, b.target, '?')) |q| b.target[0..q] else b.target;
  275. const cut = std.mem.lastIndexOfScalar(u8, path_only, '/') orelse 0;
  276. return std.fmt.allocPrint(allocator, "{s}://{s}{s}/{s}", .{ scheme, authority, path_only[0..cut], loc }) catch null;
  277. }
  278. // ── Socket plumbing ──────────────────────────────────────────────────────────
  279. fn nowMs() i64 {
  280. var ts: linux.timespec = undefined;
  281. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  282. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  283. }
  284. /// Connect to host:port using the worker's whole-exchange `deadline`. The connect is non-blocking
  285. /// plus a poll so the DEADLINE is honoured even when the peer never answers SYN;
  286. /// the socket is put back into blocking mode with SO_RCVTIMEO/SO_SNDTIMEO after,
  287. /// which is what bounds the read side.
  288. fn tcpConnect(host: []const u8, port: u16, deadline: i64, err_out: *[]const u8) ?i32 {
  289. if (deadline <= nowMs()) {
  290. err_out.* = "timed out";
  291. return null;
  292. }
  293. var host_buf: [256]u8 = undefined;
  294. if (host.len >= host_buf.len) {
  295. err_out.* = "host name too long";
  296. return null;
  297. }
  298. @memcpy(host_buf[0..host.len], host);
  299. host_buf[host.len] = 0;
  300. var port_buf: [8]u8 = undefined;
  301. const port_str = std.fmt.bufPrintZ(&port_buf, "{d}", .{port}) catch {
  302. err_out.* = "bad port";
  303. return null;
  304. };
  305. var hints: c.struct_addrinfo = std.mem.zeroes(c.struct_addrinfo);
  306. hints.ai_family = c.AF_UNSPEC;
  307. hints.ai_socktype = c.SOCK_STREAM;
  308. hints.ai_protocol = c.IPPROTO_TCP;
  309. var res: ?*c.struct_addrinfo = null;
  310. if (c.getaddrinfo(@ptrCast(&host_buf), port_str.ptr, &hints, &res) != 0 or res == null) {
  311. err_out.* = "could not resolve host";
  312. return null;
  313. }
  314. defer c.freeaddrinfo(res);
  315. return tcpConnectAddresses(res, deadline, err_out);
  316. }
  317. // Internal address-list seam: DNS owns the list; this loop owns each socket.
  318. fn tcpConnectAddresses(res: ?*c.struct_addrinfo, deadline: i64, err_out: *[]const u8) ?i32 {
  319. var last: []const u8 = "connection failed";
  320. var it: ?*c.struct_addrinfo = res;
  321. while (it) |ai| : (it = ai.ai_next) {
  322. const remaining = deadline - nowMs();
  323. if (remaining <= 0) {
  324. err_out.* = "timed out";
  325. return null;
  326. }
  327. const fd_c = c.socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol);
  328. if (fd_c < 0) {
  329. last = "could not create a socket";
  330. continue;
  331. }
  332. const fd: i32 = @intCast(fd_c);
  333. // fcntl straight from the kernel: glibc's <fcntl.h> does not survive
  334. // translate-c under _FORTIFY_SOURCE (its open() overloads are declared
  335. // with attribute error), and the flags are ABI constants either way.
  336. const flags = linux.fcntl(fd, linux.F.GETFL, 0);
  337. _ = linux.fcntl(fd, linux.F.SETFL, flags | @as(usize, O_NONBLOCK));
  338. var connected = false;
  339. if (c.connect(fd, ai.ai_addr, ai.ai_addrlen) == 0) {
  340. connected = true;
  341. } else {
  342. // linux.poll, not glibc's: <poll.h> is fortified too (see above).
  343. var pfd = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.OUT, .revents = 0 }};
  344. // Leave time for later DNS candidates; the final one gets the rest.
  345. const wait_ms = if (ai.ai_next != null) @min(remaining, 300) else remaining;
  346. const pr: isize = @bitCast(linux.poll(&pfd, 1, @intCast(@min(wait_ms, std.math.maxInt(i32)))));
  347. if (pr > 0) {
  348. var so_err: c_int = 0;
  349. var len: c.socklen_t = @sizeOf(c_int);
  350. _ = c.getsockopt(fd, c.SOL_SOCKET, c.SO_ERROR, &so_err, &len);
  351. if (so_err == 0) {
  352. connected = true;
  353. } else if (so_err == 111) {
  354. last = "connection refused";
  355. } else {
  356. last = "connection failed";
  357. }
  358. } else if (pr == 0) {
  359. last = "timed out";
  360. } else {
  361. last = "connection failed";
  362. }
  363. }
  364. if (!connected) {
  365. _ = c.close(fd);
  366. continue;
  367. }
  368. _ = linux.fcntl(fd, linux.F.SETFL, flags);
  369. const left = @max(deadline - nowMs(), 1);
  370. var tv = c.struct_timeval{
  371. .tv_sec = @intCast(@divTrunc(left, 1000)),
  372. .tv_usec = @intCast(@rem(left, 1000) * 1000),
  373. };
  374. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_RCVTIMEO, &tv, @sizeOf(c.struct_timeval));
  375. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_SNDTIMEO, &tv, @sizeOf(c.struct_timeval));
  376. const one: c_int = 1;
  377. _ = c.setsockopt(fd, c.IPPROTO_TCP, c.TCP_NODELAY, &one, @sizeOf(c_int));
  378. return fd;
  379. }
  380. err_out.* = last;
  381. return null;
  382. }
  383. /// The one place either transport is read or written, so the HTTP exchange below
  384. /// is written once for http:// and https://.
  385. const Conn = struct {
  386. fd: i32,
  387. ssl: ?*tls.SSL = null,
  388. tls_ctx: ?*const tls.TlsContext = null,
  389. fn writeAll(self: *Conn, data: []const u8) bool {
  390. if (self.ssl) |ssl| {
  391. return self.tls_ctx.?.writeAll(ssl, data) == data.len;
  392. }
  393. var sent: usize = 0;
  394. while (sent < data.len) {
  395. const n = c.write(self.fd, data.ptr + sent, data.len - sent);
  396. if (n <= 0) return false;
  397. sent += @intCast(n);
  398. }
  399. return true;
  400. }
  401. /// >0 bytes, 0 = clean end of body, <0 = error (or a socket timeout, which the
  402. /// caller separates from an error by looking at the clock).
  403. fn read(self: *Conn, buf: []u8) isize {
  404. if (self.ssl) |ssl| {
  405. const n = self.tls_ctx.?.read(ssl, buf);
  406. if (n > 0) return n;
  407. const e = self.tls_ctx.?.getError(ssl, n);
  408. if (e == tls.SSL_ERROR_ZERO_RETURN) return 0;
  409. return -1;
  410. }
  411. return c.read(self.fd, buf.ptr, buf.len);
  412. }
  413. fn close(self: *Conn) void {
  414. if (self.ssl) |ssl| {
  415. self.tls_ctx.?.shutdownAndFree(ssl);
  416. self.ssl = null;
  417. }
  418. _ = c.close(self.fd);
  419. }
  420. };
  421. // ── The client TLS context, one per CA file ──────────────────────────────────
  422. //
  423. // An SSL_CTX is expensive (it reads the system trust store) and thread-safe, so it
  424. // is built once per distinct `caFile` and shared. The map is tiny by construction:
  425. // a program has a system-trust context and at most a handful of pinned fixtures.
  426. const CtxEntry = struct {
  427. key: []u8,
  428. ctx: tls.TlsContext,
  429. };
  430. var ctx_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  431. var ctx_list: std.ArrayListUnmanaged(CtxEntry) = .empty;
  432. fn clientCtx(ca_file: ?[]const u8, err_out: *[]const u8) ?*const tls.TlsContext {
  433. const key = ca_file orelse "";
  434. mutexLock(&ctx_mutex);
  435. defer mutexUnlock(&ctx_mutex);
  436. for (ctx_list.items) |*e| {
  437. if (std.mem.eql(u8, e.key, key)) return &e.ctx;
  438. }
  439. const ctx = tls.TlsContext.initClient(.{ .ca_file = ca_file, .tag = "fetch" }) orelse {
  440. err_out.* = "https is not available (no usable OpenSSL, or the caFile could not be loaded)";
  441. return null;
  442. };
  443. const key_copy = allocator.dupe(u8, key) catch {
  444. err_out.* = "out of memory";
  445. return null;
  446. };
  447. ctx_list.append(allocator, .{ .key = key_copy, .ctx = ctx }) catch {
  448. allocator.free(key_copy);
  449. err_out.* = "out of memory";
  450. return null;
  451. };
  452. return &ctx_list.items[ctx_list.items.len - 1].ctx;
  453. }
  454. // ── One HTTP exchange ────────────────────────────────────────────────────────
  455. const Exchange = struct {
  456. status: u16 = 0,
  457. headers: []Header = &.{},
  458. body: []u8 = &.{},
  459. fn deinit(self: *Exchange) void {
  460. freeHeaders(self.headers);
  461. allocator.free(self.body);
  462. }
  463. };
  464. fn headerValue(headers: []const Header, name: []const u8) ?[]const u8 {
  465. for (headers) |h| {
  466. if (std.ascii.eqlIgnoreCase(h.name, name)) return h.value;
  467. }
  468. return null;
  469. }
  470. fn hasHeader(headers: []const Header, name: []const u8) bool {
  471. return headerValue(headers, name) != null;
  472. }
  473. /// Send one request over one connection and read the whole response.
  474. /// `err_out` gets a short static reason; the caller adds the URL.
  475. /// The status code off a raw head, or null while unparseable.
  476. fn parseStatus(head: []const u8) ?u16 {
  477. var lines = std.mem.splitSequence(u8, head, "\r\n");
  478. const status_line = lines.next() orelse return null;
  479. var parts = std.mem.splitScalar(u8, status_line, ' ');
  480. _ = parts.next(); // HTTP/1.1
  481. const code = parts.next() orelse return null;
  482. return std.fmt.parseInt(u16, code, 10) catch null;
  483. }
  484. /// Head only → an Exchange with an EMPTY body (the chunks were the body).
  485. fn parseHeadOnly(head_raw: []const u8, err_out: *[]const u8) ?Exchange {
  486. // reuse the full parser on a synthetic complete response: the head as-is
  487. // (its transfer-encoding stripped so no body is expected) + no body.
  488. var synth: std.ArrayListUnmanaged(u8) = .empty;
  489. defer synth.deinit(allocator);
  490. var lines = std.mem.splitSequence(u8, head_raw[0 .. head_raw.len - 4], "\r\n");
  491. while (lines.next()) |line| {
  492. if (line.len > 18 and std.ascii.eqlIgnoreCase(line[0..18], "transfer-encoding:")) continue;
  493. if (line.len > 15 and std.ascii.eqlIgnoreCase(line[0..15], "content-length:")) continue;
  494. if (!add(&synth, line)) return oom(err_out);
  495. if (!add(&synth, "\r\n")) return oom(err_out);
  496. }
  497. if (!add(&synth, "\r\n")) return oom(err_out);
  498. return parseResponse(synth.items, err_out);
  499. }
  500. /// STREAM the body: post every decoded piece as a chunk frame until the peer
  501. /// closes (`connection: close` is on every request, so close IS the end).
  502. /// Chunked transfer is decoded incrementally; anything else streams as-is.
  503. fn streamBody(t: *Ticket, conn: *Conn, raw: *std.ArrayListUnmanaged(u8), he: usize, deadline: i64, err_out: *[]const u8) ?Exchange {
  504. defer raw.deinit(allocator);
  505. const chunked = blk: {
  506. if (findHeaderIn(raw.items[0..he], "transfer-encoding")) |v| {
  507. break :blk std.ascii.indexOfIgnoreCase(v, "chunked") != null;
  508. }
  509. break :blk false;
  510. };
  511. // chunked-decoder state, carried across reads
  512. var pending: std.ArrayListUnmanaged(u8) = .empty;
  513. defer pending.deinit(allocator);
  514. var remaining: usize = 0; // bytes left of the current chunk's data
  515. var done = false;
  516. // seed with whatever body bytes arrived along with the head
  517. if (raw.items.len > he) {
  518. pending.appendSlice(allocator, raw.items[he..]) catch return oom(err_out);
  519. }
  520. var buf: [16 * 1024]u8 = undefined;
  521. while (true) {
  522. // decode + post what we hold
  523. if (!chunked) {
  524. if (pending.items.len > 0) {
  525. postChunk(t, pending.items);
  526. pending.clearRetainingCapacity();
  527. }
  528. } else while (!done) {
  529. if (remaining > 0) {
  530. const take = @min(remaining, pending.items.len);
  531. if (take == 0) break;
  532. postChunk(t, pending.items[0..take]);
  533. std.mem.copyForwards(u8, pending.items, pending.items[take..]);
  534. pending.shrinkRetainingCapacity(pending.items.len - take);
  535. remaining -= take;
  536. if (remaining == 0) {
  537. // the CRLF after the chunk data
  538. if (pending.items.len < 2) break;
  539. std.mem.copyForwards(u8, pending.items, pending.items[2..]);
  540. pending.shrinkRetainingCapacity(pending.items.len - 2);
  541. }
  542. continue;
  543. }
  544. const nl = std.mem.indexOf(u8, pending.items, "\r\n") orelse break;
  545. const size_line = pending.items[0..nl];
  546. const semi = std.mem.indexOfScalar(u8, size_line, ';') orelse size_line.len;
  547. const n = std.fmt.parseInt(usize, std.mem.trim(u8, size_line[0..semi], " \t"), 16) catch {
  548. err_out.* = "the peer sent a malformed chunked body";
  549. return null;
  550. };
  551. std.mem.copyForwards(u8, pending.items, pending.items[nl + 2 ..]);
  552. pending.shrinkRetainingCapacity(pending.items.len - nl - 2);
  553. if (n == 0) {
  554. done = true;
  555. break;
  556. }
  557. remaining = n;
  558. }
  559. if (done) break;
  560. const n = conn.read(&buf);
  561. if (n == 0) break; // close IS the end (identity), or a truncated chunked stream
  562. if (n < 0) {
  563. if (nowMs() >= deadline) {
  564. err_out.* = "timed out";
  565. return null;
  566. }
  567. break;
  568. }
  569. pending.appendSlice(allocator, buf[0..@intCast(n)]) catch return oom(err_out);
  570. }
  571. return parseHeadOnly(raw.items[0..he], err_out);
  572. }
  573. fn exchange(t: *Ticket, url: Url, method: []const u8, body: []const u8, send_body: bool, deadline: i64, err_out: *[]const u8) ?Exchange {
  574. const fd = tcpConnect(url.host, url.port, deadline, err_out) orelse return null;
  575. if (!t.setLiveFd(fd)) {
  576. _ = c.close(fd);
  577. err_out.* = "aborted";
  578. return null;
  579. }
  580. var conn = Conn{ .fd = fd };
  581. if (url.https) {
  582. const ctx = clientCtx(t.req.ca_file, err_out) orelse {
  583. _ = c.close(fd);
  584. return null;
  585. };
  586. // 137's shared client half logs the specific failure itself; the caller
  587. // gets the located summary (certificate not trusted, or not a TLS server)
  588. const ssl = ctx.connect(fd, url.host, "fetch") orelse {
  589. _ = c.close(fd);
  590. err_out.* = "TLS handshake failed (certificate not trusted, or not a TLS server)";
  591. return null;
  592. };
  593. conn.ssl = ssl;
  594. conn.tls_ctx = ctx;
  595. }
  596. defer conn.close();
  597. defer t.clearLiveFd();
  598. // --- request ---
  599. var req_buf: std.ArrayListUnmanaged(u8) = .empty;
  600. defer req_buf.deinit(allocator);
  601. const default_port: u16 = if (url.https) 443 else 80;
  602. var ok = true;
  603. ok = ok and addFmt(&req_buf, "{s} {s} HTTP/1.1\r\n", .{ method, url.target });
  604. if (url.port == default_port) {
  605. ok = ok and addFmt(&req_buf, "host: {s}\r\n", .{url.host});
  606. } else {
  607. ok = ok and addFmt(&req_buf, "host: {s}:{d}\r\n", .{ url.host, url.port });
  608. }
  609. // `connection: close` on every request: there is no connection pool, and a
  610. // closed connection is also the unambiguous end of a body with no length.
  611. ok = ok and add(&req_buf, "connection: close\r\n");
  612. if (!hasHeader(t.req.headers, "user-agent")) {
  613. ok = ok and add(&req_buf, "user-agent: hybriel-fetch/1\r\n");
  614. }
  615. if (!hasHeader(t.req.headers, "accept")) {
  616. ok = ok and add(&req_buf, "accept: */*\r\n");
  617. }
  618. if (send_body) {
  619. ok = ok and addFmt(&req_buf, "content-length: {d}\r\n", .{body.len});
  620. if (t.req.json_body and !hasHeader(t.req.headers, "content-type")) {
  621. ok = ok and add(&req_buf, "content-type: application/json\r\n");
  622. }
  623. }
  624. for (t.req.headers) |h| {
  625. if (t.req.strip_credentials and sensitiveHeader(h.name)) continue;
  626. if (t.req.drop_body_headers and (std.ascii.eqlIgnoreCase(h.name, "content-type") or
  627. std.ascii.eqlIgnoreCase(h.name, "content-length"))) continue;
  628. // A caller header may not smuggle a second request in (CRLF injection).
  629. if (std.mem.indexOfAny(u8, h.name, "\r\n") != null or std.mem.indexOfAny(u8, h.value, "\r\n") != null) {
  630. err_out.* = "a header name or value contains a line break";
  631. return null;
  632. }
  633. ok = ok and addFmt(&req_buf, "{s}: {s}\r\n", .{ h.name, h.value });
  634. }
  635. ok = ok and add(&req_buf, "\r\n");
  636. if (send_body and body.len > 0) {
  637. ok = ok and add(&req_buf, body);
  638. }
  639. if (!ok) return oom(err_out);
  640. if (!conn.writeAll(req_buf.items)) {
  641. err_out.* = if (nowMs() >= deadline) "timed out" else "could not send the request";
  642. return null;
  643. }
  644. // --- response ---
  645. var raw: std.ArrayListUnmanaged(u8) = .empty;
  646. errdefer raw.deinit(allocator);
  647. var head_end: ?usize = null;
  648. var buf: [16 * 1024]u8 = undefined;
  649. while (true) {
  650. if (head_end == null) {
  651. if (std.mem.indexOf(u8, raw.items, "\r\n\r\n")) |idx| head_end = idx + 4;
  652. }
  653. if (head_end) |he| {
  654. // STREAMING (LLM tokens): the head is in — if this is the final
  655. // answer (not a redirect the caller follows), hand the rest of the
  656. // body over CHUNK BY CHUNK as it arrives instead of accumulating.
  657. if (t.req.stream) {
  658. const status_ok = parseStatus(raw.items[0..he]);
  659. if (status_ok != null and !isRedirect(status_ok.?)) {
  660. return streamBody(t, &conn, &raw, he, deadline, err_out);
  661. }
  662. }
  663. // Once the head is in, stop as soon as the body is provably complete.
  664. if (bodyComplete(raw.items, he)) break;
  665. }
  666. if (raw.items.len > MAX_BODY) {
  667. raw.deinit(allocator);
  668. err_out.* = "the response is larger than the 32 MiB limit";
  669. return null;
  670. }
  671. const n = conn.read(&buf);
  672. if (n == 0) break;
  673. if (n < 0) {
  674. if (nowMs() >= deadline) {
  675. raw.deinit(allocator);
  676. err_out.* = "timed out";
  677. return null;
  678. }
  679. // A TLS peer that just closes without close_notify, or a plain socket
  680. // reset after a complete answer: the parse below decides whether what
  681. // arrived is a whole response.
  682. break;
  683. }
  684. raw.appendSlice(allocator, buf[0..@intCast(n)]) catch {
  685. raw.deinit(allocator);
  686. return oom(err_out);
  687. };
  688. }
  689. const out = parseResponse(raw.items, err_out) orelse {
  690. raw.deinit(allocator);
  691. return null;
  692. };
  693. raw.deinit(allocator);
  694. return out;
  695. }
  696. fn add(buf: *std.ArrayListUnmanaged(u8), data: []const u8) bool {
  697. buf.appendSlice(allocator, data) catch return false;
  698. return true;
  699. }
  700. /// One request line or header, formatted. A header that does not fit 2 KiB is not
  701. /// a header anyone meant to send.
  702. fn addFmt(buf: *std.ArrayListUnmanaged(u8), comptime fmt: []const u8, args: anytype) bool {
  703. var tmp: [2048]u8 = undefined;
  704. const s = std.fmt.bufPrint(&tmp, fmt, args) catch return false;
  705. return add(buf, s);
  706. }
  707. fn oom(err_out: *[]const u8) ?Exchange {
  708. err_out.* = "out of memory";
  709. return null;
  710. }
  711. /// Is everything the response promised already in `raw`? Content-Length is exact,
  712. /// chunked ends at the zero chunk, and anything else ends when the peer closes.
  713. fn bodyComplete(raw: []const u8, head_end: usize) bool {
  714. const head = raw[0..head_end];
  715. if (findHeaderIn(head, "content-length")) |v| {
  716. const want = std.fmt.parseInt(usize, std.mem.trim(u8, v, " \t"), 10) catch return false;
  717. return raw.len - head_end >= want;
  718. }
  719. if (findHeaderIn(head, "transfer-encoding")) |v| {
  720. if (std.ascii.indexOfIgnoreCase(v, "chunked") != null) {
  721. return std.mem.indexOf(u8, raw[head_end..], "\r\n0\r\n") != null or
  722. std.mem.startsWith(u8, raw[head_end..], "0\r\n");
  723. }
  724. }
  725. return false;
  726. }
  727. fn findHeaderIn(head: []const u8, name: []const u8) ?[]const u8 {
  728. var lines = std.mem.splitSequence(u8, head, "\r\n");
  729. _ = lines.next(); // status line
  730. while (lines.next()) |line| {
  731. if (line.len == 0) break;
  732. const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
  733. if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " \t"), name)) {
  734. return std.mem.trim(u8, line[colon + 1 ..], " \t");
  735. }
  736. }
  737. return null;
  738. }
  739. fn parseResponse(raw: []const u8, err_out: *[]const u8) ?Exchange {
  740. const he = std.mem.indexOf(u8, raw, "\r\n\r\n") orelse {
  741. err_out.* = "the peer sent no complete HTTP response";
  742. return null;
  743. };
  744. const head = raw[0..he];
  745. const body_raw = raw[he + 4 ..];
  746. var lines = std.mem.splitSequence(u8, head, "\r\n");
  747. const status_line = lines.next() orelse {
  748. err_out.* = "the peer sent no status line";
  749. return null;
  750. };
  751. // "HTTP/1.1 200 OK"
  752. const sp = std.mem.indexOfScalar(u8, status_line, ' ') orelse {
  753. err_out.* = "the peer sent a malformed status line";
  754. return null;
  755. };
  756. const after = status_line[sp + 1 ..];
  757. const code_end = std.mem.indexOfScalar(u8, after, ' ') orelse after.len;
  758. const status = std.fmt.parseInt(u16, std.mem.trim(u8, after[0..code_end], " \t"), 10) catch {
  759. err_out.* = "the peer sent a malformed status line";
  760. return null;
  761. };
  762. var headers: std.ArrayListUnmanaged(Header) = .empty;
  763. errdefer {
  764. for (headers.items) |h| {
  765. allocator.free(h.name);
  766. allocator.free(h.value);
  767. }
  768. headers.deinit(allocator);
  769. }
  770. var chunked = false;
  771. while (lines.next()) |line| {
  772. if (line.len == 0) continue;
  773. const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
  774. const name = std.mem.trim(u8, line[0..colon], " \t");
  775. const value = std.mem.trim(u8, line[colon + 1 ..], " \t");
  776. if (name.len == 0) continue;
  777. const name_copy = allocator.dupe(u8, name) catch return oom(err_out);
  778. http.toLowercase(name_copy);
  779. const value_copy = allocator.dupe(u8, value) catch {
  780. allocator.free(name_copy);
  781. return oom(err_out);
  782. };
  783. if (std.mem.eql(u8, name_copy, "transfer-encoding") and
  784. std.ascii.indexOfIgnoreCase(value_copy, "chunked") != null) chunked = true;
  785. headers.append(allocator, .{ .name = name_copy, .value = value_copy }) catch {
  786. allocator.free(name_copy);
  787. allocator.free(value_copy);
  788. return oom(err_out);
  789. };
  790. }
  791. var body: []u8 = undefined;
  792. if (chunked) {
  793. body = dechunk(body_raw) orelse {
  794. for (headers.items) |h| {
  795. allocator.free(h.name);
  796. allocator.free(h.value);
  797. }
  798. headers.deinit(allocator);
  799. err_out.* = "the peer sent a malformed chunked body";
  800. return null;
  801. };
  802. } else if (findHeaderIn(head, "content-length")) |v| {
  803. const want = std.fmt.parseInt(usize, v, 10) catch body_raw.len;
  804. const take = @min(want, body_raw.len);
  805. body = allocator.dupe(u8, body_raw[0..take]) catch return oom(err_out);
  806. } else {
  807. body = allocator.dupe(u8, body_raw) catch return oom(err_out);
  808. }
  809. const headers_slice = headers.toOwnedSlice(allocator) catch return oom(err_out);
  810. return .{ .status = status, .headers = headers_slice, .body = body };
  811. }
  812. fn dechunk(input: []const u8) ?[]u8 {
  813. var out: std.ArrayListUnmanaged(u8) = .empty;
  814. var i: usize = 0;
  815. while (true) {
  816. const line_end = std.mem.indexOfPos(u8, input, i, "\r\n") orelse {
  817. out.deinit(allocator);
  818. return null;
  819. };
  820. var size_txt = input[i..line_end];
  821. if (std.mem.indexOfScalar(u8, size_txt, ';')) |semi| size_txt = size_txt[0..semi];
  822. const size = std.fmt.parseInt(usize, std.mem.trim(u8, size_txt, " \t"), 16) catch {
  823. out.deinit(allocator);
  824. return null;
  825. };
  826. i = line_end + 2;
  827. if (size == 0) return out.toOwnedSlice(allocator) catch null;
  828. if (i + size > input.len) {
  829. out.deinit(allocator);
  830. return null;
  831. }
  832. out.appendSlice(allocator, input[i .. i + size]) catch {
  833. out.deinit(allocator);
  834. return null;
  835. };
  836. i += size + 2; // skip the chunk's trailing CRLF
  837. if (i > input.len) return out.toOwnedSlice(allocator) catch null;
  838. }
  839. }
  840. // ── The worker: one thread per fetch, redirects and all ───────────────────────
  841. fn isRedirect(status: u16) bool {
  842. return status == 301 or status == 302 or status == 303 or status == 307 or status == 308;
  843. }
  844. // ── The ACTIVE registry: every in-flight ticket, so `fetchAbort(tag)` can find
  845. // its socket. Added at spawn, removed at finish — a finished ticket is owned by
  846. // its handle alone and an abort of it is a no-op.
  847. var active_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  848. var active_tickets: std.ArrayListUnmanaged(*Ticket) = .empty;
  849. fn activeAdd(t: *Ticket) void {
  850. mutexLock(&active_mutex);
  851. active_tickets.append(allocator, t) catch {};
  852. mutexUnlock(&active_mutex);
  853. }
  854. fn activeRemove(t: *Ticket) void {
  855. mutexLock(&active_mutex);
  856. for (active_tickets.items, 0..) |a, i| {
  857. if (a == t) {
  858. _ = active_tickets.swapRemove(i);
  859. break;
  860. }
  861. }
  862. mutexUnlock(&active_mutex);
  863. }
  864. fn workerMain(t: *Ticket) void {
  865. runFetch(t);
  866. activeRemove(t);
  867. // an aborted request reports ABORTED whatever the read error looked like —
  868. // the app asked for the interrupt, the message says the interrupt happened
  869. if (t.aborted) {
  870. if (t.err) |e| allocator.free(e);
  871. t.err = std.fmt.allocPrint(allocator, "hl:fetch: aborted", .{}) catch null;
  872. }
  873. t.finish();
  874. postCompletion(t);
  875. }
  876. fn runFetch(t: *Ticket) void {
  877. const deadline = nowMs() + t.req.timeout_ms;
  878. var current = allocator.dupe(u8, t.req.url) catch {
  879. t.fail("hl:fetch: out of memory", .{});
  880. return;
  881. };
  882. var method = allocator.dupe(u8, t.req.method) catch {
  883. allocator.free(current);
  884. t.fail("hl:fetch: out of memory", .{});
  885. return;
  886. };
  887. var send_body = t.req.has_body;
  888. var hops: u32 = 0;
  889. while (true) {
  890. const url = parseUrl(current) orelse {
  891. t.fail("hl:fetch: '{s}' is not an http:// or https:// URL", .{current});
  892. allocator.free(current);
  893. allocator.free(method);
  894. return;
  895. };
  896. var reason: []const u8 = "connection failed";
  897. var ex = exchange(t, url, method, t.req.body, send_body, deadline, &reason) orelse {
  898. t.fail("hl:fetch {s} {s}: {s}", .{ method, current, reason });
  899. allocator.free(current);
  900. allocator.free(method);
  901. return;
  902. };
  903. if (isRedirect(ex.status) and hops < t.req.max_redirects) {
  904. if (headerValue(ex.headers, "location")) |loc| {
  905. const next = resolveLocation(current, loc) orelse {
  906. t.fail("hl:fetch {s}: redirect to an unusable Location '{s}'", .{ current, loc });
  907. ex.deinit();
  908. allocator.free(current);
  909. allocator.free(method);
  910. return;
  911. };
  912. const next_url = parseUrl(next) orelse {
  913. t.fail("hl:fetch: unusable redirect URL", .{});
  914. allocator.free(next);
  915. ex.deinit();
  916. allocator.free(current);
  917. allocator.free(method);
  918. return;
  919. };
  920. // Once stripped, credentials stay stripped even if a later hop returns.
  921. if (!sameOrigin(url, next_url)) t.req.strip_credentials = true;
  922. // 303 always becomes a GET; 301/302 become one for anything that
  923. // is not already GET/HEAD — what every browser does, and what a
  924. // server that answers a POST with "see the result over there"
  925. // means. 307/308 keep the method AND the body by definition.
  926. if (ex.status == 303 or
  927. ((ex.status == 301 or ex.status == 302) and
  928. !std.mem.eql(u8, method, "GET") and !std.mem.eql(u8, method, "HEAD")))
  929. {
  930. allocator.free(method);
  931. method = allocator.dupe(u8, "GET") catch {
  932. allocator.free(next);
  933. ex.deinit();
  934. allocator.free(current);
  935. t.fail("hl:fetch: out of memory", .{});
  936. return;
  937. };
  938. send_body = false;
  939. t.req.drop_body_headers = true;
  940. }
  941. ex.deinit();
  942. allocator.free(current);
  943. current = next;
  944. hops += 1;
  945. continue;
  946. }
  947. }
  948. if (isRedirect(ex.status) and t.req.max_redirects > 0 and hops >= t.req.max_redirects) {
  949. t.fail("hl:fetch {s}: more than {d} redirects", .{ t.req.url, t.req.max_redirects });
  950. ex.deinit();
  951. allocator.free(current);
  952. allocator.free(method);
  953. return;
  954. }
  955. t.status = ex.status;
  956. t.headers = ex.headers;
  957. t.body = ex.body;
  958. t.final_url = current;
  959. allocator.free(method);
  960. return;
  961. }
  962. }
  963. // ── The value shapes handed back to Hybriel ──────────────────────────────────
  964. fn hlStr(s: []const u8) api.HlString {
  965. return .{ .ptr = s.ptr, .len = s.len };
  966. }
  967. /// Only the SHELLS are freed: every string in a `result()` object points into the
  968. /// ticket, which outlives the call (the loader copies what it keeps before this
  969. /// runs — the plugin ABI's ownership rule).
  970. fn respShellDeinit(obj: *HlObject) callconv(.c) void {
  971. const hdrs = if (obj.field_count > 3) obj.fields[3].value else api.makeNull();
  972. if (hdrs.type == .hl_object) {
  973. const inner = hdrs.data.object;
  974. allocator.free(inner.fields[0..inner.field_count]);
  975. allocator.destroy(inner);
  976. }
  977. allocator.free(obj.fields[0..obj.field_count]);
  978. allocator.destroy(obj);
  979. }
  980. fn buildHeadersObject(headers: []const Header) ?*HlObject {
  981. const fields = allocator.alloc(HlField, headers.len) catch return null;
  982. for (headers, 0..) |h, i| {
  983. fields[i] = .{ .key = hlStr(h.name), .value = api.makeString(h.value) };
  984. }
  985. const obj = allocator.create(HlObject) catch {
  986. allocator.free(fields);
  987. return null;
  988. };
  989. obj.* = .{ .fields = fields.ptr, .field_count = headers.len, .deinit_fn = null };
  990. return obj;
  991. }
  992. /// `{ status, ok, url, headers, body, tag }` — the response as the .hl side sees
  993. /// it, hydrated into a FetchResponse by server.hl.
  994. fn buildResponse(t: *Ticket) HlValue {
  995. const headers_obj = buildHeadersObject(t.headers) orelse return api.makeError("hl:fetch: out of memory");
  996. const fields = allocator.alloc(HlField, 6) catch {
  997. allocator.free(headers_obj.fields[0..headers_obj.field_count]);
  998. allocator.destroy(headers_obj);
  999. return api.makeError("hl:fetch: out of memory");
  1000. };
  1001. fields[0] = .{ .key = hlStr("status"), .value = api.makeNumber(@floatFromInt(t.status)) };
  1002. fields[1] = .{ .key = hlStr("ok"), .value = api.makeBool(t.status >= 200 and t.status < 300) };
  1003. fields[2] = .{ .key = hlStr("url"), .value = api.makeString(t.final_url) };
  1004. fields[3] = .{ .key = hlStr("headers"), .value = api.makeObject(headers_obj) };
  1005. fields[4] = .{ .key = hlStr("body"), .value = api.makeString(t.body) };
  1006. fields[5] = .{ .key = hlStr("tag"), .value = api.makeString(t.req.tag) };
  1007. const obj = allocator.create(HlObject) catch {
  1008. allocator.free(fields);
  1009. allocator.free(headers_obj.fields[0..headers_obj.field_count]);
  1010. allocator.destroy(headers_obj);
  1011. return api.makeError("hl:fetch: out of memory");
  1012. };
  1013. obj.* = .{ .fields = fields.ptr, .field_count = 6, .deinit_fn = &respShellDeinit };
  1014. return api.makeObject(obj);
  1015. }
  1016. // ── The ticket handle ────────────────────────────────────────────────────────
  1017. fn ticketCall(ctx: ?*anyopaque, op: api.HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1018. _ = argc;
  1019. _ = argv;
  1020. const t: *Ticket = @ptrCast(@alignCast(ctx orelse return api.makeError("hl:fetch: dead ticket")));
  1021. const name = op.ptr[0..op.len];
  1022. if (std.mem.eql(u8, name, "done")) {
  1023. return api.makeBool(t.isDone());
  1024. }
  1025. if (std.mem.eql(u8, name, "doneFd")) {
  1026. return api.makeNumber(@floatFromInt(t.doneFd()));
  1027. }
  1028. if (std.mem.eql(u8, name, "tryResult")) {
  1029. t.wait();
  1030. if (t.err) |msg| {
  1031. const fields = allocator.alloc(HlField, 3) catch return api.makeError("hl:fetch: out of memory");
  1032. const obj = allocator.create(HlObject) catch {
  1033. allocator.free(fields);
  1034. return api.makeError("hl:fetch: out of memory");
  1035. };
  1036. fields[0] = .{ .key = hlStr("ok"), .value = api.makeBool(false) };
  1037. fields[1] = .{ .key = hlStr("status"), .value = api.makeNumber(0) };
  1038. fields[2] = .{ .key = hlStr("error"), .value = api.makeString(msg) };
  1039. obj.* = .{ .fields = fields.ptr, .field_count = 3, .deinit_fn = &respShellDeinit };
  1040. return api.makeObject(obj);
  1041. }
  1042. return buildResponse(t);
  1043. }
  1044. if (std.mem.eql(u8, name, "result")) {
  1045. t.wait();
  1046. if (t.err) |msg| return api.makeError(msg);
  1047. return buildResponse(t);
  1048. }
  1049. if (std.mem.eql(u8, name, "events")) {
  1050. if (t.ev_wake_fd < 0) return api.makeError("hl:fetch: events() is stream mode — start the fetch with stream = true");
  1051. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fetch: out of memory");
  1052. iter.* = .{
  1053. .context = @ptrCast(t),
  1054. .next_fn = &eventsTryNext, // non-blocking either way — event loop only
  1055. .deinit_fn = null,
  1056. .try_next_fn = &eventsTryNext,
  1057. .wake_fd = t.ev_wake_fd,
  1058. };
  1059. return api.makeIterator(iter);
  1060. }
  1061. if (std.mem.eql(u8, name, "abort")) {
  1062. t.abort();
  1063. return api.makeBool(true);
  1064. }
  1065. return api.makeError("hl:fetch: a pending fetch has no method by that name");
  1066. }
  1067. fn ticketClose(ctx: ?*anyopaque) callconv(.c) void {
  1068. const t: *Ticket = @ptrCast(@alignCast(ctx orelse return));
  1069. // The worker writes into this ticket, so it is JOINED before anything is
  1070. // freed — a detached thread finishing after the free is a use-after-free the
  1071. // collector would surface as random corruption. A dropped, never-read fetch
  1072. // therefore costs at most its own timeout at collection time.
  1073. if (t.thread) |th| {
  1074. th.join();
  1075. t.thread = null;
  1076. }
  1077. t.req.deinit();
  1078. if (t.done_fd >= 0) _ = std.os.linux.close(t.done_fd);
  1079. // The stream bell (stream = true) is the ticket's own too: without this every streamed fetch leaked one eventfd (#efd439, hycon EMFILE).
  1080. if (t.ev_wake_fd >= 0) {
  1081. _ = std.os.linux.close(t.ev_wake_fd);
  1082. t.ev_wake_fd = -1;
  1083. }
  1084. for (t.ev_queue.items) |comp| {
  1085. allocator.free(comp.tag);
  1086. allocator.free(comp.url);
  1087. allocator.free(comp.body);
  1088. allocator.free(comp.err);
  1089. if (comp.chunk) |ch| allocator.free(ch);
  1090. for (comp.headers) |h| {
  1091. allocator.free(h.name);
  1092. allocator.free(h.value);
  1093. }
  1094. if (comp.headers.len > 0) allocator.free(comp.headers);
  1095. }
  1096. t.ev_queue.deinit(allocator);
  1097. freeHeaders(t.headers);
  1098. allocator.free(t.body);
  1099. allocator.free(t.final_url);
  1100. if (t.err) |e| allocator.free(e);
  1101. allocator.destroy(t);
  1102. }
  1103. // ── Argument reading ─────────────────────────────────────────────────────────
  1104. fn fieldOf(v: HlValue, name: []const u8) ?HlValue {
  1105. if (v.type != .hl_object) return null;
  1106. const obj = v.data.object;
  1107. for (obj.fields[0..obj.field_count]) |f| {
  1108. if (std.mem.eql(u8, f.key.ptr[0..f.key.len], name)) return f.value;
  1109. }
  1110. return null;
  1111. }
  1112. fn dupString(v: ?HlValue, fallback: []const u8) []u8 {
  1113. if (v) |val| {
  1114. if (val.type == .hl_string) {
  1115. return allocator.dupe(u8, val.data.string.ptr[0..val.data.string.len]) catch
  1116. allocator.dupe(u8, fallback) catch unreachable;
  1117. }
  1118. }
  1119. return allocator.dupe(u8, fallback) catch unreachable;
  1120. }
  1121. fn numberOr(v: ?HlValue, fallback: i64) i64 {
  1122. if (v) |val| {
  1123. if (val.type == .hl_number) return @intFromFloat(val.data.number);
  1124. }
  1125. return fallback;
  1126. }
  1127. fn boolOr(v: ?HlValue, fallback: bool) bool {
  1128. if (v) |val| {
  1129. if (val.type == .hl_bool) return val.data.boolean;
  1130. }
  1131. return fallback;
  1132. }
  1133. fn readHeaders(v: ?HlValue) []Header {
  1134. const val = v orelse return &.{};
  1135. if (val.type != .hl_object) return &.{};
  1136. const obj = val.data.object;
  1137. var list: std.ArrayListUnmanaged(Header) = .empty;
  1138. for (obj.fields[0..obj.field_count]) |f| {
  1139. if (f.value.type != .hl_string) continue;
  1140. const name = allocator.dupe(u8, f.key.ptr[0..f.key.len]) catch continue;
  1141. const value = allocator.dupe(u8, f.value.data.string.ptr[0..f.value.data.string.len]) catch {
  1142. allocator.free(name);
  1143. continue;
  1144. };
  1145. list.append(allocator, .{ .name = name, .value = value }) catch {
  1146. allocator.free(name);
  1147. allocator.free(value);
  1148. };
  1149. }
  1150. return list.toOwnedSlice(allocator) catch &.{};
  1151. }
  1152. /// __native("fetch.start", url, options) → a ticket HANDLE, immediately.
  1153. /// Options: method, headers, body, jsonBody, timeoutMs, maxRedirects, caFile, tag.
  1154. export fn hl_fetch_start(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1155. if (argc < 1 or argv[0].type != .hl_string) {
  1156. return api.makeError("hl:fetch: fetch() needs a URL string");
  1157. }
  1158. const url = argv[0].data.string.ptr[0..argv[0].data.string.len];
  1159. const opts: ?HlValue = if (argc > 1 and argv[1].type == .hl_object) argv[1] else null;
  1160. const method_raw = dupString(if (opts) |o| fieldOf(o, "method") else null, "GET");
  1161. for (method_raw) |*ch| {
  1162. if (ch.* >= 'a' and ch.* <= 'z') ch.* -= 32;
  1163. }
  1164. const body = dupString(if (opts) |o| fieldOf(o, "body") else null, "");
  1165. const has_body = blk: {
  1166. const bv = if (opts) |o| fieldOf(o, "body") else null;
  1167. if (bv) |v| break :blk v.type == .hl_string;
  1168. break :blk false;
  1169. };
  1170. const ca_val = if (opts) |o| fieldOf(o, "caFile") else null;
  1171. const ca_file: ?[]u8 = if (ca_val != null and ca_val.?.type == .hl_string)
  1172. allocator.dupe(u8, ca_val.?.data.string.ptr[0..ca_val.?.data.string.len]) catch null
  1173. else
  1174. null;
  1175. const t = allocator.create(Ticket) catch return api.makeError("hl:fetch: out of memory");
  1176. t.* = .{
  1177. .req = .{
  1178. .method = method_raw,
  1179. .url = allocator.dupe(u8, url) catch return api.makeError("hl:fetch: out of memory"),
  1180. .headers = readHeaders(if (opts) |o| fieldOf(o, "headers") else null),
  1181. .body = body,
  1182. .has_body = has_body,
  1183. .json_body = boolOr(if (opts) |o| fieldOf(o, "jsonBody") else null, false),
  1184. .timeout_ms = @max(numberOr(if (opts) |o| fieldOf(o, "timeoutMs") else null, DEFAULT_TIMEOUT_MS), 1),
  1185. .max_redirects = @intCast(@max(numberOr(if (opts) |o| fieldOf(o, "maxRedirects") else null, DEFAULT_MAX_REDIRECTS), 0)),
  1186. .ca_file = ca_file,
  1187. .tag = dupString(if (opts) |o| fieldOf(o, "tag") else null, ""),
  1188. .stream = boolOr(if (opts) |o| fieldOf(o, "stream") else null, false),
  1189. },
  1190. };
  1191. if (t.req.stream) t.ev_wake_fd = http.makeWakeFd();
  1192. activeAdd(t);
  1193. t.thread = std.Thread.spawn(.{}, workerMain, .{t}) catch {
  1194. // No thread: run it here rather than lying about having started. The call
  1195. // then blocks, which is slower and still correct.
  1196. workerMain(t);
  1197. t.thread = null;
  1198. return makeTicketHandle(t);
  1199. };
  1200. return makeTicketHandle(t);
  1201. }
  1202. fn makeTicketHandle(t: *Ticket) HlValue {
  1203. const h = allocator.create(HlHandle) catch return api.makeError("hl:fetch: out of memory");
  1204. h.* = .{
  1205. .context = @ptrCast(t),
  1206. .call_fn = &ticketCall,
  1207. .close_fn = &ticketClose,
  1208. .type_name = hlStr("pending fetch"),
  1209. };
  1210. return api.makeHandle(h);
  1211. }
  1212. // ── The completions source: a loop source with the mission-125 bell ──────────
  1213. //
  1214. // `for (ev of completions())` / `eventloop.register` — the SAME shape hl:http1's
  1215. // request and ws-event sources have, so a finished fetch reaches an `on fetched(ev)`
  1216. // handler through the loop's own `epoll_wait` instead of anyone polling. The queue
  1217. // is filled by the worker threads and drained by the loop thread.
  1218. const Completion = struct {
  1219. aborted: bool = false,
  1220. tag: []u8,
  1221. url: []u8,
  1222. status: u16,
  1223. headers: []Header,
  1224. body: []u8,
  1225. err: []u8,
  1226. /// non-null = a STREAM CHUNK frame ({tag, url, chunk}), not a completion
  1227. chunk: ?[]u8 = null,
  1228. };
  1229. var comp_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  1230. var comp_queue: std.ArrayListUnmanaged(Completion) = .empty;
  1231. var comp_wake_fd: i32 = -1;
  1232. var comp_enabled = std.atomic.Value(bool).init(false);
  1233. /// Called by every worker as its last act. Nothing is copied — and no wake is
  1234. /// rung — unless a completions source actually exists, so a program that only
  1235. /// uses `result()` pays nothing for this.
  1236. /// One decoded piece of a STREAMING body → a `{ tag, url, chunk }` frame on the
  1237. /// completions source, bell rung. Dropped (with one log line) when no source is
  1238. /// armed — a stream nobody listens to is a programming error worth seeing.
  1239. fn postChunk(t: *Ticket, bytes: []const u8) void {
  1240. if (t.ev_wake_fd < 0 and !comp_enabled.load(.acquire)) {
  1241. logMsg("hl:fetch: stream chunk dropped — nobody is listening");
  1242. return;
  1243. }
  1244. const comp = Completion{
  1245. .tag = allocator.dupe(u8, t.req.tag) catch return,
  1246. .url = allocator.dupe(u8, t.req.url) catch return,
  1247. .status = 0,
  1248. .headers = &.{},
  1249. .body = allocator.dupe(u8, "") catch return,
  1250. .err = allocator.dupe(u8, "") catch return,
  1251. .chunk = allocator.dupe(u8, bytes) catch return,
  1252. };
  1253. postFrame(t, comp);
  1254. }
  1255. /// One frame to wherever this ticket's listener lives: the ticket's own source
  1256. /// (stream mode) or the global completions source.
  1257. fn postFrame(t: *Ticket, comp: Completion) void {
  1258. if (t.ev_wake_fd >= 0) {
  1259. mutexLock(&t.mutex);
  1260. t.ev_queue.append(allocator, comp) catch {};
  1261. mutexUnlock(&t.mutex);
  1262. http.ringWake(t.ev_wake_fd);
  1263. return;
  1264. }
  1265. mutexLock(&comp_mutex);
  1266. comp_queue.append(allocator, comp) catch {};
  1267. mutexUnlock(&comp_mutex);
  1268. http.ringWake(comp_wake_fd);
  1269. }
  1270. fn postCompletion(t: *Ticket) void {
  1271. if (t.ev_wake_fd < 0 and !comp_enabled.load(.acquire)) return;
  1272. var headers = allocator.alloc(Header, t.headers.len) catch return;
  1273. var built: usize = 0;
  1274. for (t.headers, 0..) |h, i| {
  1275. const n = allocator.dupe(u8, h.name) catch break;
  1276. const v = allocator.dupe(u8, h.value) catch {
  1277. allocator.free(n);
  1278. break;
  1279. };
  1280. headers[i] = .{ .name = n, .value = v };
  1281. built = i + 1;
  1282. }
  1283. headers = headers[0..built];
  1284. const comp = Completion{
  1285. .aborted = t.aborted,
  1286. .tag = allocator.dupe(u8, t.req.tag) catch "",
  1287. .url = allocator.dupe(u8, if (t.final_url.len > 0) t.final_url else t.req.url) catch "",
  1288. .status = t.status,
  1289. .headers = headers,
  1290. .body = allocator.dupe(u8, t.body) catch "",
  1291. .err = allocator.dupe(u8, if (t.err) |e| e else "") catch "",
  1292. };
  1293. // Ring generously (D-125): the loop treats the fd as a bell, so a wake for a
  1294. // queue somebody already drained costs one empty round and nothing else.
  1295. postFrame(t, comp);
  1296. }
  1297. /// Frees the SHELLS and the payload: a completion is a snapshot nobody else owns.
  1298. fn compObjDeinit(obj: *HlObject) callconv(.c) void {
  1299. const fields = obj.fields[0..obj.field_count];
  1300. for (fields) |f| {
  1301. if (f.value.type == .hl_string) {
  1302. const s = f.value.data.string;
  1303. if (s.len > 0) allocator.free(@constCast(s.ptr[0..s.len]));
  1304. } else if (f.value.type == .hl_object) {
  1305. const inner = f.value.data.object;
  1306. for (inner.fields[0..inner.field_count]) |hf| {
  1307. allocator.free(@constCast(hf.key.ptr[0..hf.key.len]));
  1308. const hv = hf.value.data.string;
  1309. allocator.free(@constCast(hv.ptr[0..hv.len]));
  1310. }
  1311. allocator.free(inner.fields[0..inner.field_count]);
  1312. allocator.destroy(inner);
  1313. }
  1314. }
  1315. allocator.free(fields);
  1316. allocator.destroy(obj);
  1317. }
  1318. fn completionsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  1319. _ = ctx;
  1320. mutexLock(&comp_mutex);
  1321. if (comp_queue.items.len == 0) {
  1322. mutexUnlock(&comp_mutex);
  1323. return api.makeNull();
  1324. }
  1325. const comp = comp_queue.orderedRemove(0);
  1326. if (comp_queue.items.len > 0) http.ringWake(comp_wake_fd);
  1327. mutexUnlock(&comp_mutex);
  1328. return frameToValue(comp);
  1329. }
  1330. /// A streaming ticket's own source: drains that ticket's queue and nothing else.
  1331. fn eventsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  1332. const t: *Ticket = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  1333. mutexLock(&t.mutex);
  1334. if (t.ev_queue.items.len == 0) {
  1335. mutexUnlock(&t.mutex);
  1336. return api.makeNull();
  1337. }
  1338. const comp = t.ev_queue.orderedRemove(0);
  1339. if (t.ev_queue.items.len > 0) http.ringWake(t.ev_wake_fd);
  1340. mutexUnlock(&t.mutex);
  1341. return frameToValue(comp);
  1342. }
  1343. fn frameToValue(comp: Completion) HlValue {
  1344. // a STREAM CHUNK frame: { tag, url, chunk } and nothing else
  1345. if (comp.chunk) |chunk| {
  1346. allocator.free(comp.body);
  1347. allocator.free(comp.err);
  1348. const cfields = allocator.alloc(HlField, 3) catch return api.makeNull();
  1349. cfields[0] = .{ .key = hlStr("tag"), .value = api.makeString(comp.tag) };
  1350. cfields[1] = .{ .key = hlStr("url"), .value = api.makeString(comp.url) };
  1351. cfields[2] = .{ .key = hlStr("chunk"), .value = api.makeString(chunk) };
  1352. const cobj = allocator.create(HlObject) catch {
  1353. allocator.free(cfields);
  1354. return api.makeNull();
  1355. };
  1356. cobj.* = .{ .fields = cfields.ptr, .field_count = 3, .deinit_fn = &compObjDeinit };
  1357. return api.makeObject(cobj);
  1358. }
  1359. const hdr_fields = allocator.alloc(HlField, comp.headers.len) catch return api.makeNull();
  1360. for (comp.headers, 0..) |h, i| {
  1361. hdr_fields[i] = .{ .key = hlStr(h.name), .value = api.makeString(h.value) };
  1362. }
  1363. const hdr_obj = allocator.create(HlObject) catch {
  1364. allocator.free(hdr_fields);
  1365. return api.makeNull();
  1366. };
  1367. hdr_obj.* = .{ .fields = hdr_fields.ptr, .field_count = comp.headers.len, .deinit_fn = null };
  1368. allocator.free(comp.headers);
  1369. const fields = allocator.alloc(HlField, 8) catch return api.makeNull();
  1370. fields[0] = .{ .key = hlStr("tag"), .value = api.makeString(comp.tag) };
  1371. fields[1] = .{ .key = hlStr("url"), .value = api.makeString(comp.url) };
  1372. fields[2] = .{ .key = hlStr("status"), .value = api.makeNumber(@floatFromInt(comp.status)) };
  1373. fields[3] = .{ .key = hlStr("ok"), .value = api.makeBool(comp.status >= 200 and comp.status < 300) };
  1374. fields[4] = .{ .key = hlStr("body"), .value = api.makeString(comp.body) };
  1375. fields[5] = .{ .key = hlStr("error"), .value = api.makeString(comp.err) };
  1376. fields[6] = .{ .key = hlStr("headers"), .value = api.makeObject(hdr_obj) };
  1377. fields[7] = .{ .key = hlStr("aborted"), .value = api.makeBool(comp.aborted) };
  1378. const obj = allocator.create(HlObject) catch {
  1379. allocator.free(fields);
  1380. return api.makeNull();
  1381. };
  1382. obj.* = .{ .fields = fields.ptr, .field_count = 8, .deinit_fn = &compObjDeinit };
  1383. return api.makeObject(obj);
  1384. }
  1385. /// __native("fetch.abort", tag) — THE INTERRUPT (the LLM stop button): every
  1386. /// in-flight fetch whose `tag` matches is aborted by shutting its socket down.
  1387. /// The peer sees the disconnect (llama-server / OpenRouter stop generating and
  1388. /// billing), the worker's read unblocks, and the FINAL completion frame arrives
  1389. /// with `aborted = true` and error "hl:fetch: aborted". Returns how many were
  1390. /// aborted (0 = nothing in flight under that tag — already finished, or a typo).
  1391. export fn hl_fetch_abort(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1392. if (argc < 1 or argv[0].type != .hl_string) {
  1393. return api.makeError("hl:fetch abort: pass the tag the fetch was started with");
  1394. }
  1395. const tag = argv[0].data.string.ptr[0..argv[0].data.string.len];
  1396. var n: u32 = 0;
  1397. mutexLock(&active_mutex);
  1398. for (active_tickets.items) |t| {
  1399. if (std.mem.eql(u8, t.req.tag, tag)) {
  1400. t.abort();
  1401. n += 1;
  1402. }
  1403. }
  1404. mutexUnlock(&active_mutex);
  1405. return api.makeNumber(@floatFromInt(n));
  1406. }
  1407. /// __native("fetch.completions") → the loop source. Calling it ARMS completion
  1408. /// delivery for every fetch started from here on.
  1409. export fn hl_fetch_completions(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1410. _ = argc;
  1411. _ = argv;
  1412. mutexLock(&comp_mutex);
  1413. if (comp_wake_fd < 0) comp_wake_fd = http.makeWakeFd();
  1414. mutexUnlock(&comp_mutex);
  1415. comp_enabled.store(true, .release);
  1416. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fetch: out of memory");
  1417. iter.* = .{
  1418. .context = null,
  1419. .next_fn = &completionsTryNext, // non-blocking either way — event loop only
  1420. .deinit_fn = null,
  1421. .try_next_fn = &completionsTryNext,
  1422. .wake_fd = comp_wake_fd,
  1423. };
  1424. return api.makeIterator(iter);
  1425. }
  1426. test "wake burst fetch stream and global completions" {
  1427. const w = @import("wake_test");
  1428. var stream_passed: usize = 0;
  1429. var global_passed: usize = 0;
  1430. for (0..10) |_| {
  1431. comp_wake_fd = w.bell();
  1432. defer _ = linux.close(comp_wake_fd);
  1433. defer comp_queue.deinit(allocator);
  1434. comp_queue = .empty;
  1435. var t: Ticket = undefined;
  1436. t.mutex = libc.PTHREAD_MUTEX_INITIALIZER;
  1437. t.ev_queue = .empty;
  1438. const stream_fd = w.bell();
  1439. t.ev_wake_fd = stream_fd;
  1440. defer _ = linux.close(stream_fd);
  1441. defer t.ev_queue.deinit(allocator);
  1442. for (0..2) |mode| {
  1443. if (mode == 1) t.ev_wake_fd = -1;
  1444. for (0..221) |i| postFrame(&t, .{
  1445. .tag = @constCast(""), .url = @constCast(""), .status = 200,
  1446. .headers = &.{}, .body = @constCast(""), .err = @constCast(""),
  1447. .chunk = if (i < 220) try allocator.dupe(u8, "chunk") else null,
  1448. });
  1449. if (mode == 0) {
  1450. if (w.burst(t.ev_wake_fd, &t, &eventsTryNext, 221)) stream_passed += 1;
  1451. } else if (w.burst(comp_wake_fd, null, &completionsTryNext, 221)) global_passed += 1;
  1452. }
  1453. }
  1454. try w.result("fetch stream chunk/done", stream_passed);
  1455. try w.result("fetch global chunk/done", global_passed);
  1456. try w.require(&.{stream_passed, global_passed});
  1457. }
  1458. // A full local accept queue drops subsequent SYNs without relying on routing.
  1459. // Every descriptor is owned by the fixture or the test, including failure paths.
  1460. const ConnectFixture = struct {
  1461. blackhole: i32,
  1462. queued: i32,
  1463. good: i32,
  1464. refused: i32,
  1465. addresses: [3]c.struct_sockaddr_in,
  1466. fn init() !ConnectFixture {
  1467. const blackhole = try listener(27570, true);
  1468. errdefer _ = c.close(blackhole);
  1469. const queued = c.socket(c.AF_INET, c.SOCK_STREAM, c.IPPROTO_TCP);
  1470. if (queued < 0) return error.Socket;
  1471. errdefer _ = c.close(queued);
  1472. var black_addr = address(27570);
  1473. if (c.connect(queued, @ptrCast(&black_addr), @sizeOf(c.struct_sockaddr_in)) != 0) return error.Connect;
  1474. const good = try listener(27571, true);
  1475. errdefer _ = c.close(good);
  1476. // Bound but not listening reserves a reliably refused destination.
  1477. const refused = try listener(27572, false);
  1478. return .{ .blackhole = blackhole, .queued = queued, .good = good, .refused = refused, .addresses = .{ address(27570), address(27571), address(27572) } };
  1479. }
  1480. fn address(port: u16) c.struct_sockaddr_in {
  1481. var addr = std.mem.zeroes(c.struct_sockaddr_in);
  1482. addr.sin_family = c.AF_INET;
  1483. addr.sin_port = std.mem.nativeToBig(u16, port);
  1484. addr.sin_addr.s_addr = std.mem.nativeToBig(u32, 0x7f000001);
  1485. return addr;
  1486. }
  1487. fn listener(port: u16, listen: bool) !i32 {
  1488. const fd = c.socket(c.AF_INET, c.SOCK_STREAM, c.IPPROTO_TCP);
  1489. if (fd < 0) return error.Socket;
  1490. errdefer _ = c.close(fd);
  1491. const one: c_int = 1;
  1492. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_REUSEADDR, &one, @sizeOf(c_int));
  1493. var addr = address(port);
  1494. if (c.bind(fd, @ptrCast(&addr), @sizeOf(c.struct_sockaddr_in)) != 0) return error.Bind;
  1495. if (listen and c.listen(fd, 0) != 0) return error.Listen;
  1496. return fd;
  1497. }
  1498. fn info(self: *ConnectFixture, index: usize, next: ?*c.struct_addrinfo) c.struct_addrinfo {
  1499. var ai = std.mem.zeroes(c.struct_addrinfo);
  1500. ai.ai_family = c.AF_INET;
  1501. ai.ai_socktype = c.SOCK_STREAM;
  1502. ai.ai_protocol = c.IPPROTO_TCP;
  1503. ai.ai_addr = @ptrCast(&self.addresses[index]);
  1504. ai.ai_addrlen = @sizeOf(c.struct_sockaddr_in);
  1505. ai.ai_next = next;
  1506. return ai;
  1507. }
  1508. fn deinit(self: ConnectFixture) void {
  1509. _ = c.close(self.queued);
  1510. _ = c.close(self.blackhole);
  1511. _ = c.close(self.good);
  1512. _ = c.close(self.refused);
  1513. }
  1514. };
  1515. test "connect falls back after a blackholed first address" {
  1516. var fixture = try ConnectFixture.init();
  1517. defer fixture.deinit();
  1518. var good = fixture.info(1, null);
  1519. var first = fixture.info(0, &good);
  1520. var err: []const u8 = "";
  1521. const start = nowMs();
  1522. const fd = tcpConnectAddresses(&first, start + 1200, &err);
  1523. defer if (fd) |f| {
  1524. _ = c.close(f);
  1525. };
  1526. const elapsed = nowMs() - start;
  1527. std.debug.print("blackhole + good: {d} ms, {s}\n", .{ elapsed, err });
  1528. try std.testing.expect(fd != null);
  1529. try std.testing.expect(elapsed >= 250 and elapsed < 550);
  1530. }
  1531. test "single blackholed address keeps the remaining whole-exchange budget" {
  1532. var fixture = try ConnectFixture.init();
  1533. defer fixture.deinit();
  1534. var first = fixture.info(0, null);
  1535. var err: []const u8 = "";
  1536. const start = nowMs();
  1537. // Model 200 ms already spent in DNS: only 650 ms of 850 ms remains.
  1538. const fd = tcpConnectAddresses(&first, start + 850 - 200, &err);
  1539. defer if (fd) |f| {
  1540. _ = c.close(f);
  1541. };
  1542. const elapsed = nowMs() - start;
  1543. std.debug.print("single blackhole: {d} ms, {s}\n", .{ elapsed, err });
  1544. try std.testing.expect(fd == null);
  1545. try std.testing.expectEqualStrings("timed out", err);
  1546. try std.testing.expect(elapsed >= 600 and elapsed < 900);
  1547. }
  1548. test "refused first address falls back immediately" {
  1549. var fixture = try ConnectFixture.init();
  1550. defer fixture.deinit();
  1551. var good = fixture.info(1, null);
  1552. var first = fixture.info(2, &good);
  1553. var err: []const u8 = "";
  1554. const start = nowMs();
  1555. const fd = tcpConnectAddresses(&first, start + 1200, &err);
  1556. defer if (fd) |f| {
  1557. _ = c.close(f);
  1558. };
  1559. const elapsed = nowMs() - start;
  1560. std.debug.print("refused + good: {d} ms, {s}\n", .{ elapsed, err });
  1561. try std.testing.expect(fd != null);
  1562. try std.testing.expect(elapsed < 250);
  1563. }
  1564. test "expired whole-exchange deadline does not connect" {
  1565. var fixture = try ConnectFixture.init();
  1566. defer fixture.deinit();
  1567. var good = fixture.info(1, null);
  1568. var err: []const u8 = "";
  1569. const fd = tcpConnectAddresses(&good, nowMs() - 1, &err);
  1570. defer if (fd) |f| {
  1571. _ = c.close(f);
  1572. };
  1573. try std.testing.expect(fd == null);
  1574. try std.testing.expectEqualStrings("timed out", err);
  1575. }
  1576. test "redirect origin includes scheme host and effective port" {
  1577. const base = parseUrl("https://example.com/start").?;
  1578. try std.testing.expect(sameOrigin(base, parseUrl("https://EXAMPLE.COM:443/next").?));
  1579. try std.testing.expect(!sameOrigin(base, parseUrl("http://example.com/next").?));
  1580. try std.testing.expect(!sameOrigin(base, parseUrl("https://example.com:444/next").?));
  1581. try std.testing.expect(!sameOrigin(base, parseUrl("https://other.example/next").?));
  1582. }
  1583. test "redirect credentials use case insensitive header names" {
  1584. for ([_][]const u8{ "Authorization", "PROXY-AUTHORIZATION", "cOoKiE" }) |name| {
  1585. try std.testing.expect(sensitiveHeader(name));
  1586. }
  1587. try std.testing.expect(!sensitiveHeader("X-Test"));
  1588. }

Branches

Latest commits

  • 56e70dcbrecords: review time limit 1800 s (routger 132)mre
  • c3a304c5Merge branch 'job-timeout' into mainKunibert
  • 402bfeb0|||PR runner: the model run uses the job's time limit (jobTimeoutSeconds), not a fixed 900 smre
  • 8d34ca33records: repo rename (gitoria#53)mre
  • 1e05cb3fMerge branch 'repo-rename' into mainKunibert
  • 6ee0d2e9|||PR intake: match a delivery by repo.id and signature, not URLs (gitoria#53 rename)mre
  • 900ffcd4status: routgermre
  • 59b0b793log: routger merge waitmre
  • e52f094alog: routger intake check (hycon#122)mre
  • f979027frecords: design rule livemre
  • 71efaf84Merge branch 'design-guard' into mainKunibert
  • c0656581|||PR Flag removal of a documented design as major unless his recorded yes is linked; rules version 5mre
  • 901cdd75records: L10 update 2 livemre
  • 4a68016bMerge branch 'hl-standard-l10b' into mainKunibert
  • 246d0f30|||PR HL-STANDARD L10 update (hybriel ab293e5a), rules version 4mre
  • 1aa4d64crecords: HL-STANDARD L10 update livemre
  • 2b04c240Merge branch 'hl-standard-l10' into mainKunibert
  • 88c7b09d|||PR HL-STANDARD L10 update (hybriel 5885d688), rules version 3mre
  • 00869ecbrecords: gitoria#50 step 3 livemre
  • f97a0e5fMerge branch 'hl-standard' into mainKunibert