gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9ba258d39ba258d3|||PR records: HM55b resultTracker9ba258d3/plugins/http1/http1.zig

160.8 KB

  1. // hl:http1 plugin — HTTP/1.1 server with epoll + I/O thread pool
  2. // Compiled to libhttp1.so, loaded by runtime via dlopen
  3. //
  4. // Architecture:
  5. // Acceptor thread (epoll on server fd) → PARK (epoll) → I/O thread pool (TLS + parse)
  6. // → request queue → Hybriel main thread
  7. //
  8. // An IDLE connection never occupies an I/O worker (mission 084). A worker's read() is
  9. // blocking, so a connection handed straight to the pool pins a thread until bytes arrive;
  10. // with the default `threads = 4`, four idle keep-alive sockets (one open browser tab is
  11. // already several) starved every later request. Instead every connection that is not
  12. // known to have readable bytes is PARKED in the parker thread's epoll, and only enters
  13. // conn_queue when it is actually readable (or hung up). See ParkedConns below.
  14. //
  15. // Exports:
  16. // hl_http1_create_server(port, host, cert_path, key_path, threads) → iterator of request objects
  17. // hl_http1_listen(port) → same with defaults (backward compat)
  18. //
  19. // Each request object: method, path, query (object), headers (object), body, respond (handle),
  20. // remoteAddress, bytes (the body as a Bytes, ticket #88), secure (TLS terminated here, #214)
  21. // Respond handle: call("send", status_code, body [, content_type]) → writes response
  22. const std = @import("std");
  23. const api = @import("plugin_api");
  24. const http = @import("http_common");
  25. const ws = @import("ws_common");
  26. // The outgoing WebSocket client's TLS (wss://, ticket #109) — the SAME client
  27. // half hl:fetch uses (system trust store, hostname verification on, an
  28. // optional extra `caFile` for a test fixture). Aliased away from `TlsContext`:
  29. // the name is taken below by http1's own pre-existing SERVER-only TLS type,
  30. // which this does not touch.
  31. const tls_client = @import("tls_common");
  32. const HlValue = api.HlValue;
  33. const HlObject = api.HlObject;
  34. const HlField = api.HlField;
  35. const HlIterator = api.HlIterator;
  36. const HlHandle = api.HlHandle;
  37. const HlString = api.HlString;
  38. const linux = std.os.linux;
  39. const posix = std.posix;
  40. const c = std.c;
  41. const PthreadMutex = c.pthread_mutex_t;
  42. const PthreadCond = c.pthread_cond_t;
  43. fn mutexInit(m: *PthreadMutex) void {
  44. // Static initializer is sufficient; explicit init not exposed in this std.c.
  45. _ = m;
  46. }
  47. fn mutexLock(m: *PthreadMutex) void {
  48. _ = c.pthread_mutex_lock(m);
  49. }
  50. fn mutexUnlock(m: *PthreadMutex) void {
  51. _ = c.pthread_mutex_unlock(m);
  52. }
  53. fn condInit(cnd: *PthreadCond) void {
  54. _ = cnd;
  55. }
  56. fn condSignal(cnd: *PthreadCond) void {
  57. _ = c.pthread_cond_signal(cnd);
  58. }
  59. fn condBroadcast(cnd: *PthreadCond) void {
  60. _ = c.pthread_cond_broadcast(cnd);
  61. }
  62. fn condWait(cnd: *PthreadCond, m: *PthreadMutex) void {
  63. _ = c.pthread_cond_wait(cnd, m);
  64. }
  65. // allocations cross the acceptor, I/O-worker and interpreter threads: the plugins'
  66. // allocator (plugin_api.zig), never the debug one, whose bookkeeping segfaulted in its
  67. // own free() under request churn (mission 027)
  68. const allocator = api.allocator;
  69. // Use direct syscall for stderr writes — std.debug.print uses std.Progress
  70. // which has ABI-incompatible global state when loaded as a plugin into a
  71. // binary compiled with a different Zig version.
  72. fn logMsg(msg: []const u8) void {
  73. _ = linux.write(2, msg.ptr, msg.len);
  74. }
  75. fn logFmt(comptime fmt: []const u8, args: anytype) void {
  76. var buf: [512]u8 = undefined;
  77. const s = std.fmt.bufPrint(&buf, fmt, args) catch return;
  78. logMsg(s);
  79. }
  80. // =========================================================================
  81. // SSE (Server-Sent Events) push channel — mission 031, ADDRESSED in 080
  82. // A registry of connected event-stream clients. `sse_start` (on the respond
  83. // handle) upgrades a GET request into a long-lived text/event-stream, assigns
  84. // the connection a stable id and registers it; `hl_http1_sse_broadcast` writes
  85. // a `data:` frame to every registered client and `hl_http1_sse_send` to ONE of
  86. // them, dropping any that error (peer closed). Touched only from the
  87. // interpreter (main) thread, but guarded by a mutex for safety.
  88. //
  89. // Mission 080 (D26): the id is a MONOTONIC counter, never the fd — a closed
  90. // connection's fd is recycled by the kernel within milliseconds, so an fd-keyed
  91. // push would eventually land on a stranger's socket. `sse_start` returns the id
  92. // (it used to return the raw fd, which no caller used), and the framework sends
  93. // it to the browser as the `__hlHello` event so the client can name itself.
  94. // =========================================================================
  95. // Mission 084: a subscription is reaped PROACTIVELY, not on the first failed push.
  96. // A closed tab used to stay in this registry until something happened to be pushed to
  97. // it — and because a scoped push (§9.5) sends nothing to a client whose needs did not
  98. // change, "something" could be never. Two mechanisms, both in the reaper thread:
  99. //
  100. // • EPOLLRDHUP on every registered fd — a closed tab sends FIN, which fires
  101. // immediately and costs no traffic at all. This is the primary detector.
  102. // • a periodic SSE COMMENT heartbeat (`:\n\n`, which EventSource ignores) — catches
  103. // a peer that vanished WITHOUT a FIN (killed machine, dropped NAT entry), which no
  104. // amount of epolling can see, and keeps intermediaries from timing the stream out.
  105. //
  106. // A heartbeat is also why one failed write is enough to declare death here: the probe
  107. // runs repeatedly, so the "first write after FIN succeeds, second gets EPIPE" TCP
  108. // behaviour just means the peer is reaped one tick later.
  109. const MSG_NOSIGNAL: u32 = 0x4000;
  110. const SseConn = struct { id: u32, fd: i32 };
  111. var sse_mutex: PthreadMutex = c.PTHREAD_MUTEX_INITIALIZER;
  112. var sse_subs: std.ArrayListUnmanaged(SseConn) = .empty;
  113. var sse_next_id: u32 = 1;
  114. /// how often the reaper writes its comment heartbeat / probes for silent death
  115. const SSE_HEARTBEAT_MS: i64 = 5_000;
  116. var sse_epoll_fd: i32 = -1;
  117. var sse_wake_fd: i32 = -1;
  118. var sse_reaper_thread: ?std.Thread = null;
  119. var sse_reaper_running = std.atomic.Value(bool).init(false);
  120. /// Start the reaper thread + its epoll. Idempotent; called under sse_mutex from the
  121. /// first sseRegister(), so a server that never opens a stream never spawns it.
  122. fn sseReaperEnsureLocked() void {
  123. if (sse_reaper_running.load(.acquire)) return;
  124. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  125. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  126. if (ep < 0) return;
  127. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  128. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  129. if (ef < 0) {
  130. _ = linux.close(ep);
  131. return;
  132. }
  133. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  134. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  135. sse_epoll_fd = ep;
  136. sse_wake_fd = ef;
  137. sse_reaper_running.store(true, .release);
  138. sse_reaper_thread = std.Thread.spawn(.{}, sseReaperLoop, .{}) catch {
  139. sse_reaper_running.store(false, .release);
  140. _ = linux.close(ep);
  141. _ = linux.close(ef);
  142. sse_epoll_fd = -1;
  143. sse_wake_fd = -1;
  144. return;
  145. };
  146. }
  147. /// Drop subscription at index `i`: epoll DEL, close, remove. Caller holds sse_mutex.
  148. fn sseDropLocked(i: usize) void {
  149. const fd = sse_subs.items[i].fd;
  150. if (sse_epoll_fd >= 0) _ = linux.epoll_ctl(sse_epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  151. _ = linux.close(fd);
  152. _ = sse_subs.swapRemove(i);
  153. }
  154. /// The reaper: EPOLLRDHUP wakes it the instant a tab closes; the 1s timeout paces the
  155. /// heartbeat. Nothing here pushes application data, so a reap needs no traffic from the
  156. /// app at all — which is the whole point (mission 080's gap).
  157. fn sseReaperLoop() void {
  158. var events: [64]linux.epoll_event = undefined;
  159. var last_beat: i64 = monotonicMs();
  160. while (sse_reaper_running.load(.acquire)) {
  161. const n_rc = linux.epoll_wait(sse_epoll_fd, &events, events.len, 1000);
  162. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  163. if (n > 0) {
  164. for (events[0..@intCast(n)]) |ev| {
  165. if (ev.data.fd == sse_wake_fd) {
  166. var drain: u64 = 0;
  167. _ = linux.read(sse_wake_fd, @ptrCast(&drain), @sizeOf(u64));
  168. continue;
  169. }
  170. // A subscriber never SENDS on its stream, so any readable/hangup event
  171. // means the peer went away (or is misbehaving) — either way it is dead.
  172. mutexLock(&sse_mutex);
  173. for (sse_subs.items, 0..) |conn, i| {
  174. if (conn.fd == ev.data.fd) {
  175. sseDropLocked(i);
  176. break;
  177. }
  178. }
  179. mutexUnlock(&sse_mutex);
  180. }
  181. }
  182. const now = monotonicMs();
  183. if (now - last_beat >= SSE_HEARTBEAT_MS) {
  184. last_beat = now;
  185. mutexLock(&sse_mutex);
  186. var i: usize = 0;
  187. while (i < sse_subs.items.len) {
  188. // ":\n\n" is an SSE comment — EventSource ignores it, so this is a pure
  189. // liveness probe that never reaches an `onmessage` handler.
  190. if (!sseRawWrite(sse_subs.items[i].fd, ":\n\n")) {
  191. sseDropLocked(i);
  192. continue;
  193. }
  194. i += 1;
  195. }
  196. mutexUnlock(&sse_mutex);
  197. }
  198. }
  199. }
  200. // Write via sendto with MSG_NOSIGNAL so a dead peer yields EPIPE instead of
  201. // killing the process with SIGPIPE. Returns false on any short/failed write.
  202. fn sseRawWrite(fd: i32, data: []const u8) bool {
  203. var written: usize = 0;
  204. while (written < data.len) {
  205. const rc = linux.sendto(fd, data[written..].ptr, data.len - written, MSG_NOSIGNAL, null, 0);
  206. const n: isize = @bitCast(rc);
  207. if (n <= 0) return false;
  208. written += @intCast(n);
  209. }
  210. return true;
  211. }
  212. fn sseRegister(fd: i32) u32 {
  213. mutexLock(&sse_mutex);
  214. defer mutexUnlock(&sse_mutex);
  215. const id = sse_next_id;
  216. sse_next_id += 1;
  217. sse_subs.append(allocator, .{ .id = id, .fd = fd }) catch return 0;
  218. // Watch it for hangup from now on — see the reaper comment above.
  219. sseReaperEnsureLocked();
  220. if (sse_epoll_fd >= 0) {
  221. var ev = linux.epoll_event{
  222. .events = linux.EPOLL.RDHUP | linux.EPOLL.IN,
  223. .data = .{ .fd = fd },
  224. };
  225. _ = linux.epoll_ctl(sse_epoll_fd, linux.EPOLL.CTL_ADD, fd, &ev);
  226. }
  227. return id;
  228. }
  229. // One `data:` frame on one socket. Caller holds sse_mutex.
  230. fn sseWriteFrameLocked(fd: i32, msg: []const u8) bool {
  231. var ok = sseRawWrite(fd, "data: ");
  232. if (ok) ok = sseRawWrite(fd, msg);
  233. if (ok) ok = sseRawWrite(fd, "\n\n");
  234. return ok;
  235. }
  236. // Broadcast one SSE message to all subscribers. `msg` should be a single line
  237. // (callers send single-line JSON). Dead sockets are closed and removed.
  238. // Returns the number of clients successfully written to.
  239. fn sseBroadcast(msg: []const u8) usize {
  240. mutexLock(&sse_mutex);
  241. defer mutexUnlock(&sse_mutex);
  242. var count: usize = 0;
  243. var i: usize = 0;
  244. while (i < sse_subs.items.len) {
  245. if (!sseWriteFrameLocked(sse_subs.items[i].fd, msg)) {
  246. sseDropLocked(i);
  247. continue;
  248. }
  249. count += 1;
  250. i += 1;
  251. }
  252. return count;
  253. }
  254. // __native("http1.sse_count") → how many SSE subscriptions are currently LIVE.
  255. // The observable the proactive reaper exists to keep honest (mission 084): it must fall
  256. // when a client goes away, with nothing being pushed.
  257. export fn hl_http1_sse_count(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  258. _ = argc;
  259. _ = argv;
  260. mutexLock(&sse_mutex);
  261. defer mutexUnlock(&sse_mutex);
  262. return api.makeNumber(@floatFromInt(sse_subs.items.len));
  263. }
  264. // __native("http1.sse_alive", connId) → 1 if that subscription is still registered.
  265. // Lets the framework prune its own per-connection bookkeeping without pushing anything.
  266. export fn hl_http1_sse_alive(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  267. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  268. const id: u32 = @intFromFloat(argv[0].data.number);
  269. mutexLock(&sse_mutex);
  270. defer mutexUnlock(&sse_mutex);
  271. for (sse_subs.items) |conn| {
  272. if (conn.id == id) return api.makeNumber(1);
  273. }
  274. return api.makeNumber(0);
  275. }
  276. // __native("http1.sse_broadcast", jsonString) → number of clients pushed to.
  277. export fn hl_http1_sse_broadcast(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  278. if (argc < 1 or argv[0].type != .hl_string) return api.makeNumber(0);
  279. const msg = argv[0].data.string.ptr[0..argv[0].data.string.len];
  280. const n = sseBroadcast(msg);
  281. return api.makeNumber(@floatFromInt(n));
  282. }
  283. // __native("http1.sse_send", connId, jsonString) → 1 pushed / 0 gone.
  284. // Mission 080 (D26): the ADDRESSED half of the channel — the dependency-scoped
  285. // push sends a different payload to each client, so it cannot use broadcast.
  286. export fn hl_http1_sse_send(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  287. if (argc < 2 or argv[0].type != .hl_number or argv[1].type != .hl_string) return api.makeNumber(0);
  288. const id: u32 = @intFromFloat(argv[0].data.number);
  289. const msg = argv[1].data.string.ptr[0..argv[1].data.string.len];
  290. mutexLock(&sse_mutex);
  291. defer mutexUnlock(&sse_mutex);
  292. for (sse_subs.items, 0..) |conn, i| {
  293. if (conn.id != id) continue;
  294. if (!sseWriteFrameLocked(conn.fd, msg)) {
  295. sseDropLocked(i);
  296. return api.makeNumber(0);
  297. }
  298. return api.makeNumber(1);
  299. }
  300. return api.makeNumber(0);
  301. }
  302. // =========================================================================
  303. // WebSocket engine (mission 064, decisions D8/D9)
  304. //
  305. // Framing lives in the shared core (plugins/http/ws_common.zig); this engine
  306. // owns the h1-specific parts: the Upgrade/101 handshake (done inline in the
  307. // I/O worker, see readAndParseRequest) and the socket lifecycle after it.
  308. //
  309. // One engine per listening server: each owns a queue, peers and a reader
  310. // thread that epolls its upgraded sockets with level-triggered EPOLLIN only —
  311. // EPOLLOUT is never armed, so an idle connection never wakes the loop (the
  312. // busy-spin trap found in the http2 TLS path). Complete messages become
  313. // WsEvent entries that the interpreter drains via the hl_http1_ws_events
  314. // iterator (registered on the event loop like the request iterator).
  315. //
  316. // Outbound writes (send/broadcast/ping/close + pong replies) happen under
  317. // ws_mutex from either the interpreter thread or the reader thread. Sockets
  318. // are non-blocking; a slow consumer gets bounded EAGAIN retries (~100ms)
  319. // and is dropped rather than buffered (no outbound queue, no EPOLLOUT).
  320. // WS upgrades are plain-HTTP only for now (TLS WS = future work, like SSE).
  321. // =========================================================================
  322. const WsEventKind = enum(u8) { connect, message, close, pong };
  323. const WsEvent = struct {
  324. kind: WsEventKind,
  325. id: u32,
  326. data: ?[]u8 = null, // allocated payload (message data / close reason)
  327. is_binary: bool = false,
  328. code: u16 = 0, // close code
  329. // Mission 093: the UPGRADE REQUEST's `Cookie` header, verbatim, carried on the
  330. // `connect` event only. A WebSocket handshake is an ordinary HTTP request, so
  331. // the browser sends the session cookie with it automatically — this is the one
  332. // moment the socket can be attributed to whoever loaded the page, and after the
  333. // 101 the request (and its headers) is freed. Allocated; freed with the event.
  334. cookie: ?[]u8 = null,
  335. // Ticket #74: the upgrade request's `Host` header, verbatim, on `connect` only —
  336. // the address the browser dialled, which a page served per subdomain is rendered
  337. // for. Allocated; freed with the event.
  338. host: ?[]u8 = null,
  339. // Ticket #105: EVERY header of the upgrade request, `name: value` lines joined by
  340. // `\n` (names already lowercase), on `connect` only — what a page constructed for
  341. // a navigation over this socket reads as `headers`. Allocated; freed with the event.
  342. headers: ?[]u8 = null,
  343. // Ticket #214: the peer's address ("a.b.c.d", the request's `remoteAddress` form) on
  344. // `connect` only — null when the kernel cannot say. Allocated; freed with the event.
  345. ip: ?[]u8 = null,
  346. // Ticket #214: whether the upgrade arrived over TLS this server terminated. Upgrades
  347. // are plain-HTTP only today (a TLS connection is never upgraded), so always false.
  348. secure: bool = false,
  349. stamp: u64 = 0, // api.stamp() when queued (wsQueue)
  350. };
  351. /// Queue one server-side event, stamped (plugin_api.zig `head_stamp_fn`). Caller holds `engine.ws_mutex`.
  352. fn wsQueue(engine: *WsEngine, ev: WsEvent) !void {
  353. var e = ev;
  354. e.stamp = api.stamp();
  355. try engine.ws_event_queue.append(allocator, e);
  356. // Also covers close events queued by failed sends outside the reader.
  357. http.ringWake(engine.ws_loop_wake_fd);
  358. }
  359. /// `head_stamp_fn` of the server's event source: when its next event was queued.
  360. fn wsEventsHeadStamp(ctx: ?*anyopaque) callconv(.c) u64 {
  361. const engine: *WsEngine = @ptrCast(@alignCast(ctx orelse return api.STAMP_NONE));
  362. mutexLock(&engine.ws_mutex);
  363. defer mutexUnlock(&engine.ws_mutex);
  364. return if (engine.ws_event_queue.items.len == 0) api.STAMP_NONE else engine.ws_event_queue.items[0].stamp;
  365. }
  366. const WsClient = struct {
  367. id: u32,
  368. fd: i32,
  369. decoder: ws.Decoder,
  370. closing: bool = false, // server sent close, awaiting peer echo
  371. // liveness (mission 091): when this socket last produced a frame, and when
  372. // the sweep's ping went out (0 = none outstanding). A TCP connection whose
  373. // peer vanished without a FIN stays writable indefinitely, so "still open"
  374. // is not evidence of a live peer — the pong is.
  375. last_seen_ms: i64 = 0,
  376. ping_at_ms: i64 = 0,
  377. };
  378. const WsEngine = struct {
  379. ws_mutex: PthreadMutex = c.PTHREAD_MUTEX_INITIALIZER,
  380. ws_clients: std.ArrayListUnmanaged(*WsClient) = .empty,
  381. ws_event_queue: std.ArrayListUnmanaged(WsEvent) = .empty,
  382. ws_epoll_fd: i32 = -1,
  383. ws_wake_fd: i32 = -1,
  384. // Kept alive with the core: an event loop may still hold this fd.
  385. ws_loop_wake_fd: i32 = -1,
  386. ws_thread: ?std.Thread = null,
  387. ws_running: std.atomic.Value(bool) = .init(false),
  388. ws_enabled: std.atomic.Value(bool) = .init(false),
  389. ws_ping_ms: i64 = WS_PING_MS_DEFAULT,
  390. ws_pong_ms: i64 = WS_PONG_MS_DEFAULT,
  391. };
  392. // Connection IDs stay process-unique so the existing WsClient API is unchanged.
  393. var ws_next_id = std.atomic.Value(u32).init(1);
  394. // --- liveness sweep (mission 091) ----------------------------------------
  395. // The reader thread already wakes every 500ms (the epoll timeout), so the sweep
  396. // costs no timer and no new thread: on every tick it pings sockets that have
  397. // gone quiet and drops the ones whose pong is overdue. The drop enqueues the
  398. // ordinary `close` event, so every consumer above (hl:web's subscription
  399. // registry included) prunes through the path it already had — nothing upstream
  400. // learns a new concept, and nothing at the hl level needs a timer.
  401. //
  402. // Operator knobs, read once at engine start; the defaults are production
  403. // values, the tests shrink them.
  404. const WS_PING_MS_DEFAULT: i64 = 15000; // quiet this long -> ask
  405. const WS_PONG_MS_DEFAULT: i64 = 10000; // no answer in this long -> gone
  406. /// MONOTONIC milliseconds — a timeout measured against the wall clock would fire
  407. /// early or never after an NTP step.
  408. fn wsNowMs() i64 {
  409. var ts: linux.timespec = undefined;
  410. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  411. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  412. }
  413. fn wsEnvMs(name: [:0]const u8, fallback: i64) i64 {
  414. const raw = std.mem.span(std.c.getenv(name) orelse return fallback);
  415. const n = std.fmt.parseInt(i64, std.mem.trim(u8, raw, " \t"), 10) catch return fallback;
  416. if (n <= 0) return fallback;
  417. return n;
  418. }
  419. const EAGAIN_ERR: isize = 11;
  420. const EINTR_ERR: isize = 4;
  421. /// WriteFn callback over a raw fd (context = fd stuffed into the pointer).
  422. /// Non-blocking socket: bounded EAGAIN retries, then give up (caller drops).
  423. fn wsFdWrite(ctx: ?*anyopaque, data: []const u8) bool {
  424. const fd: i32 = @intCast(@intFromPtr(ctx));
  425. var written: usize = 0;
  426. var retries: u32 = 0;
  427. while (written < data.len) {
  428. const rc = linux.sendto(fd, data[written..].ptr, data.len - written, MSG_NOSIGNAL, null, 0);
  429. const n: isize = @bitCast(rc);
  430. if (n > 0) {
  431. written += @intCast(n);
  432. retries = 0;
  433. continue;
  434. }
  435. const e = -n;
  436. if (e == EAGAIN_ERR) {
  437. retries += 1;
  438. if (retries > 100) return false; // ~100ms of backpressure → drop
  439. const req = linux.timespec{ .sec = 0, .nsec = 1_000_000 }; // 1ms
  440. _ = linux.nanosleep(&req, null);
  441. continue;
  442. }
  443. if (e == EINTR_ERR) continue;
  444. return false;
  445. }
  446. return true;
  447. }
  448. fn wsFdCtx(fd: i32) ?*anyopaque {
  449. return @ptrFromInt(@as(usize, @intCast(fd)));
  450. }
  451. /// Start the reader thread + epoll instance. Idempotent. Called from the
  452. /// interpreter thread (hl_http1_ws_events); also flips engine.ws_enabled so the I/O
  453. /// workers start honoring Upgrade requests.
  454. fn wsEnsureStarted(engine: *WsEngine) bool {
  455. mutexLock(&engine.ws_mutex);
  456. defer mutexUnlock(&engine.ws_mutex);
  457. if (engine.ws_running.load(.acquire)) return true;
  458. engine.ws_ping_ms = wsEnvMs("HL_WS_PING_MS", WS_PING_MS_DEFAULT);
  459. engine.ws_pong_ms = wsEnvMs("HL_WS_PONG_TIMEOUT_MS", WS_PONG_MS_DEFAULT);
  460. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  461. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  462. if (ep < 0) return false;
  463. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  464. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  465. if (ef < 0) {
  466. _ = linux.close(ep);
  467. return false;
  468. }
  469. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  470. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  471. engine.ws_epoll_fd = ep;
  472. engine.ws_wake_fd = ef;
  473. if (engine.ws_loop_wake_fd < 0) engine.ws_loop_wake_fd = http.makeWakeFd(); // mission 256
  474. engine.ws_running.store(true, .release);
  475. engine.ws_thread = std.Thread.spawn(.{}, wsReaderLoop, .{engine}) catch {
  476. engine.ws_running.store(false, .release);
  477. _ = linux.close(ep);
  478. _ = linux.close(ef);
  479. engine.ws_epoll_fd = -1;
  480. engine.ws_wake_fd = -1;
  481. return false;
  482. };
  483. engine.ws_enabled.store(true, .release);
  484. return true;
  485. }
  486. fn wsWake(engine: *WsEngine) void {
  487. if (engine.ws_wake_fd >= 0) {
  488. const one: u64 = 1;
  489. _ = linux.write(engine.ws_wake_fd, @ptrCast(&one), @sizeOf(u64));
  490. }
  491. }
  492. /// The upgrade's headers as `name: value` lines joined by `\n` (ticket #105) — one
  493. /// allocation the connect event carries; a parsed header holds no `\n`. Null when
  494. /// there are none or the allocation fails (the connection still opens).
  495. fn joinHeaders(items: []const HeaderPair) ?[]u8 {
  496. var len: usize = 0;
  497. for (items) |hdr| len += hdr.key.len + 2 + hdr.value.len + 1;
  498. if (len == 0) return null;
  499. const out = allocator.alloc(u8, len - 1) catch return null;
  500. var at: usize = 0;
  501. for (items, 0..) |hdr, i| {
  502. if (i > 0) {
  503. out[at] = '\n';
  504. at += 1;
  505. }
  506. @memcpy(out[at .. at + hdr.key.len], hdr.key);
  507. at += hdr.key.len;
  508. @memcpy(out[at .. at + 2], ": ");
  509. at += 2;
  510. @memcpy(out[at .. at + hdr.value.len], hdr.value);
  511. at += hdr.value.len;
  512. }
  513. return out;
  514. }
  515. /// Hand an upgraded socket to the engine. Called from an I/O worker thread
  516. /// right after the 101 was written. `leftover` = bytes the client sent after
  517. /// the handshake that were already consumed into the header buffer. `cookie` is
  518. /// the handshake's `Cookie` header (mission 093) — copied here, because the
  519. /// parsed request is freed the moment this returns. `host` is its `Host` header
  520. /// (ticket #74), copied for the same reason. `headers` is all of them as
  521. /// `name: value` lines (ticket #105), already an allocated copy: owned from here.
  522. /// `handshake` is the 101 response. It is written HERE, under `engine.ws_mutex` and after the
  523. /// `connect` event is queued (ticket: 039_http1_ws_client, 2026-10-02): written before
  524. /// registering, an in-process client could read it and queue its `open` ahead of the
  525. /// server's `connect`, and a `peer.send` from `on connect` could not overtake it either.
  526. /// The peer address of a connected socket as "a.b.c.d" (IPv4 listener), allocated; null
  527. /// when the kernel cannot say.
  528. fn peerIpText(fd: i32) ?[]u8 {
  529. var peer: linux.sockaddr.in = undefined;
  530. var peer_len: u32 = @sizeOf(linux.sockaddr.in);
  531. const rc = linux.getpeername(fd, @ptrCast(&peer), &peer_len);
  532. if (@as(isize, @bitCast(rc)) != 0 or peer.family != linux.AF.INET) return null;
  533. const a: [4]u8 = @bitCast(peer.addr);
  534. return std.fmt.allocPrint(allocator, "{d}.{d}.{d}.{d}", .{ a[0], a[1], a[2], a[3] }) catch null;
  535. }
  536. fn wsRegisterClient(engine: *WsEngine, fd: i32, handshake: []const u8, leftover: []const u8, cookie: []const u8, host: []const u8, headers: ?[]u8) void {
  537. // Non-blocking for the reader loop
  538. const flags_rc = linux.fcntl(fd, linux.F.GETFL, @as(usize, 0));
  539. const flags_i: isize = @bitCast(flags_rc);
  540. if (flags_i >= 0) {
  541. var oflags: linux.O = @bitCast(@as(u32, @truncate(flags_rc)));
  542. oflags.NONBLOCK = true;
  543. _ = linux.fcntl(fd, linux.F.SETFL, @as(usize, @as(u32, @bitCast(oflags))));
  544. }
  545. mutexLock(&engine.ws_mutex);
  546. const client = allocator.create(WsClient) catch {
  547. mutexUnlock(&engine.ws_mutex);
  548. if (headers) |hd| allocator.free(hd);
  549. _ = linux.close(fd);
  550. return;
  551. };
  552. client.* = .{
  553. .id = ws_next_id.fetchAdd(1, .monotonic),
  554. .fd = fd,
  555. .decoder = ws.Decoder.init(allocator),
  556. .last_seen_ms = wsNowMs(),
  557. };
  558. engine.ws_clients.append(allocator, client) catch {
  559. allocator.destroy(client);
  560. mutexUnlock(&engine.ws_mutex);
  561. if (headers) |hd| allocator.free(hd);
  562. _ = linux.close(fd);
  563. return;
  564. };
  565. const cookie_copy: ?[]u8 = if (cookie.len > 0) (allocator.dupe(u8, cookie) catch null) else null;
  566. const host_copy: ?[]u8 = if (host.len > 0) (allocator.dupe(u8, host) catch null) else null;
  567. const ip_copy = peerIpText(fd);
  568. wsQueue(engine, .{ .kind = .connect, .id = client.id, .cookie = cookie_copy, .host = host_copy, .headers = headers, .ip = ip_copy, .secure = false }) catch {
  569. if (ip_copy) |ic| allocator.free(ic);
  570. if (cookie_copy) |cc| allocator.free(cc);
  571. if (host_copy) |hc| allocator.free(hc);
  572. if (headers) |hd| allocator.free(hd);
  573. };
  574. if (leftover.len > 0) client.decoder.feed(leftover) catch {};
  575. if (!wsFdWrite(wsFdCtx(fd), handshake)) {
  576. // the same answer a failed send gets: `close` 1006 after the `connect`
  577. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  578. wsRemoveLocked(engine, engine.ws_clients.items.len - 1);
  579. mutexUnlock(&engine.ws_mutex);
  580. return;
  581. }
  582. mutexUnlock(&engine.ws_mutex);
  583. // Level-triggered EPOLLIN only (never EPOLLOUT): pending socket data fires
  584. // immediately, idle connections cost nothing.
  585. var ev = linux.epoll_event{ .events = linux.EPOLL.IN | linux.EPOLL.RDHUP, .data = .{ .fd = fd } };
  586. _ = linux.epoll_ctl(engine.ws_epoll_fd, linux.EPOLL.CTL_ADD, fd, &ev);
  587. if (leftover.len > 0) wsWake(engine); // decoder-buffered bytes won't fire EPOLLIN
  588. // This runs on an I/O WORKER thread, not the reader thread, and it queued a
  589. // `connect` — so it rings the event loop itself (mission 256).
  590. http.ringWake(engine.ws_loop_wake_fd);
  591. }
  592. fn wsFindByFdLocked(engine: *WsEngine, fd: i32) ?usize {
  593. for (engine.ws_clients.items, 0..) |cl, i| {
  594. if (cl.fd == fd) return i;
  595. }
  596. return null;
  597. }
  598. fn wsFindByIdLocked(engine: *WsEngine, id: u32) ?usize {
  599. for (engine.ws_clients.items, 0..) |cl, i| {
  600. if (cl.id == id) return i;
  601. }
  602. return null;
  603. }
  604. /// Remove client at index: epoll DEL, close fd, free state. Mutex held.
  605. fn wsRemoveLocked(engine: *WsEngine, idx: usize) void {
  606. const client = engine.ws_clients.items[idx];
  607. _ = linux.epoll_ctl(engine.ws_epoll_fd, linux.EPOLL.CTL_DEL, client.fd, null);
  608. _ = linux.close(client.fd);
  609. client.decoder.deinit();
  610. _ = engine.ws_clients.swapRemove(idx);
  611. allocator.destroy(client);
  612. }
  613. /// Drain the client's decoder; enqueue events, auto-reply pings, run the
  614. /// close handshake. Returns true if the client was removed. Mutex held.
  615. fn wsDrainDecoderLocked(engine: *WsEngine, idx: usize) bool {
  616. const client = engine.ws_clients.items[idx];
  617. while (true) {
  618. const maybe_ev = client.decoder.next() catch {
  619. // OOM mid-decode — drop the connection
  620. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1011 }) catch {};
  621. wsRemoveLocked(engine, idx);
  622. return true;
  623. };
  624. const ev = maybe_ev orelse return false;
  625. // Any complete frame is proof of life, and it answers an outstanding
  626. // sweep ping whatever its opcode — a peer that is talking is not dead.
  627. client.last_seen_ms = wsNowMs();
  628. client.ping_at_ms = 0;
  629. switch (ev) {
  630. .text => |p| wsQueue(engine, .{ .kind = .message, .id = client.id, .data = p }) catch allocator.free(p),
  631. .binary => |p| wsQueue(engine, .{ .kind = .message, .id = client.id, .data = p, .is_binary = true }) catch allocator.free(p),
  632. .ping => |p| {
  633. _ = ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .pong, p);
  634. allocator.free(p);
  635. },
  636. .pong => |p| {
  637. allocator.free(p);
  638. wsQueue(engine, .{ .kind = .pong, .id = client.id }) catch {};
  639. },
  640. // QUEUED BEFORE THE ANSWER IS WRITTEN, as the 101 is: the peer may be a
  641. // client in this process, whose `close` the echo causes, and the loop
  642. // delivers in stamp order (plugin_api.zig `head_stamp_fn`)
  643. .close => |cl| {
  644. const code = cl.code;
  645. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = code, .data = cl.reason }) catch allocator.free(cl.reason);
  646. if (!client.closing) {
  647. const echo_code = if (code == ws.CLOSE_NO_STATUS) ws.CLOSE_NORMAL else code;
  648. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), echo_code, "");
  649. }
  650. wsRemoveLocked(engine, idx);
  651. return true;
  652. },
  653. .protocol_error => |code| {
  654. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = code }) catch {};
  655. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), code, "");
  656. wsRemoveLocked(engine, idx);
  657. return true;
  658. },
  659. }
  660. }
  661. }
  662. /// Read all available bytes from the client socket into its decoder, then
  663. /// drain. Returns true if the client was removed. Mutex held.
  664. fn wsServiceClientLocked(engine: *WsEngine, idx: usize) bool {
  665. const client = engine.ws_clients.items[idx];
  666. var buf: [16384]u8 = undefined;
  667. while (true) {
  668. const rc = linux.read(client.fd, &buf, buf.len);
  669. const n: isize = @bitCast(rc);
  670. if (n > 0) {
  671. client.decoder.feed(buf[0..@intCast(n)]) catch {};
  672. continue;
  673. }
  674. if (n == 0) {
  675. // Peer closed without a close frame → 1006 abnormal closure
  676. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  677. wsRemoveLocked(engine, idx);
  678. return true;
  679. }
  680. const e = -n;
  681. if (e == EINTR_ERR) continue;
  682. if (e == EAGAIN_ERR) break; // all available data consumed
  683. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  684. wsRemoveLocked(engine, idx);
  685. return true;
  686. }
  687. return wsDrainDecoderLocked(engine, idx);
  688. }
  689. /// One liveness pass over every upgraded socket. Quiet for longer than
  690. /// engine.ws_ping_ms → send a protocol ping (RFC 6455 §5.5.2; every browser answers it
  691. /// at the protocol layer, so nothing application-side is involved). A ping that
  692. /// stands unanswered for engine.ws_pong_ms → the peer is gone however open the socket
  693. /// looks: enqueue the SAME `close` event a real FIN would have produced and drop
  694. /// the connection. That is the whole mechanism — no separate timer, no new
  695. /// thread, no concept added above this file.
  696. fn wsSweep(engine: *WsEngine) void {
  697. const now = wsNowMs();
  698. mutexLock(&engine.ws_mutex);
  699. defer mutexUnlock(&engine.ws_mutex);
  700. var i: usize = 0;
  701. while (i < engine.ws_clients.items.len) {
  702. const client = engine.ws_clients.items[i];
  703. if (client.ping_at_ms != 0) {
  704. if (now - client.ping_at_ms > engine.ws_pong_ms) {
  705. wsQueue(engine, .{
  706. .kind = .close,
  707. .id = client.id,
  708. .code = ws.CLOSE_GOING_AWAY,
  709. }) catch {};
  710. wsRemoveLocked(engine, i);
  711. continue;
  712. }
  713. } else if (now - client.last_seen_ms > engine.ws_ping_ms) {
  714. if (ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .ping, "")) {
  715. client.ping_at_ms = now;
  716. } else {
  717. // the write itself failed — this one needs no grace period
  718. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  719. wsRemoveLocked(engine, i);
  720. continue;
  721. }
  722. }
  723. i += 1;
  724. }
  725. }
  726. fn wsReaderLoop(engine: *WsEngine) void {
  727. var events: [64]linux.epoll_event = undefined;
  728. while (engine.ws_running.load(.acquire)) {
  729. const n_rc = linux.epoll_wait(engine.ws_epoll_fd, &events, events.len, 500);
  730. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  731. // The 500ms epoll timeout IS the sweep's clock: an idle loop still ticks,
  732. // and a busy one sweeps just as often because the check is on wall time.
  733. if (n <= 0) {
  734. wsSweep(engine);
  735. continue;
  736. }
  737. for (events[0..@intCast(n)]) |ev| {
  738. if (ev.data.fd == engine.ws_wake_fd) {
  739. var drain: u64 = 0;
  740. _ = linux.read(engine.ws_wake_fd, @ptrCast(&drain), @sizeOf(u64));
  741. if (!engine.ws_running.load(.acquire)) return;
  742. // Drain decoder-buffered data (e.g. handshake leftover)
  743. mutexLock(&engine.ws_mutex);
  744. var i: usize = 0;
  745. while (i < engine.ws_clients.items.len) {
  746. if (!wsDrainDecoderLocked(engine, i)) i += 1;
  747. }
  748. mutexUnlock(&engine.ws_mutex);
  749. continue;
  750. }
  751. mutexLock(&engine.ws_mutex);
  752. if (wsFindByFdLocked(engine, ev.data.fd)) |idx| {
  753. _ = wsServiceClientLocked(engine, idx);
  754. }
  755. mutexUnlock(&engine.ws_mutex);
  756. }
  757. wsSweep(engine);
  758. }
  759. }
  760. /// Stop the engine: join the reader thread, close all sockets, free queues.
  761. /// Runs after this server's I/O workers have joined, before the runtime
  762. /// dlcloses this .so, so neither upgrades nor readers outlive the engine.
  763. fn wsShutdown(engine: *WsEngine) void {
  764. if (!engine.ws_running.swap(false, .acq_rel)) return;
  765. wsWake(engine);
  766. if (engine.ws_thread) |t| {
  767. t.join();
  768. engine.ws_thread = null;
  769. }
  770. mutexLock(&engine.ws_mutex);
  771. for (engine.ws_clients.items) |client| {
  772. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), ws.CLOSE_GOING_AWAY, "");
  773. _ = linux.close(client.fd);
  774. client.decoder.deinit();
  775. allocator.destroy(client);
  776. }
  777. engine.ws_clients.deinit(allocator);
  778. engine.ws_clients = .empty;
  779. for (engine.ws_event_queue.items) |*ev| {
  780. if (ev.data) |d| allocator.free(d);
  781. if (ev.cookie) |ck| allocator.free(ck);
  782. if (ev.host) |hc| allocator.free(hc);
  783. if (ev.headers) |hd| allocator.free(hd);
  784. if (ev.ip) |ip| allocator.free(ip);
  785. }
  786. engine.ws_event_queue.deinit(allocator);
  787. engine.ws_event_queue = .empty;
  788. mutexUnlock(&engine.ws_mutex);
  789. if (engine.ws_epoll_fd >= 0) _ = linux.close(engine.ws_epoll_fd);
  790. if (engine.ws_wake_fd >= 0) _ = linux.close(engine.ws_wake_fd);
  791. engine.ws_epoll_fd = -1;
  792. engine.ws_wake_fd = -1;
  793. // `engine.ws_loop_wake_fd` is deliberately NOT closed: the event loop may still hold
  794. // it in its epoll set, and a closed fd number gets REUSED — the loop would
  795. // then be watching whatever opened next. One eventfd per engine, kept for
  796. // the process's life (mission 256).
  797. engine.ws_enabled.store(false, .release);
  798. }
  799. // --- Interpreter-facing exports ------------------------------------------
  800. const ws_kind_names = [_][]const u8{ "connect", "message", "close", "pong" };
  801. fn wsEventObjDeinit(obj: *HlObject) callconv(.c) void {
  802. // fields[2] is "data", fields[5] "cookie", fields[6] "host" and fields[7]
  803. // "headers" — allocated iff non-empty (empty = the static "").
  804. const s = obj.fields[2].value.data.string;
  805. if (s.len > 0) allocator.free(s.ptr[0..s.len]);
  806. const ck = obj.fields[5].value.data.string;
  807. if (ck.len > 0) allocator.free(ck.ptr[0..ck.len]);
  808. const hs = obj.fields[6].value.data.string;
  809. if (hs.len > 0) allocator.free(hs.ptr[0..hs.len]);
  810. const hd = obj.fields[7].value.data.string;
  811. if (hd.len > 0) allocator.free(hd.ptr[0..hd.len]);
  812. const ipv = obj.fields[8].value.data.string; // "ip", allocated iff non-empty
  813. if (ipv.len > 0) allocator.free(ipv.ptr[0..ipv.len]);
  814. allocator.free(obj.fields[0..obj.field_count]);
  815. allocator.destroy(obj);
  816. }
  817. /// try_next over the WS event queue → { kind, id, data, binary, code, cookie, host, headers }
  818. /// or null. `cookie` is the handshake's Cookie header, `host` its Host header and
  819. /// `headers` all of its headers as `name: value` lines, each non-empty only on
  820. /// `connect` (mission 093, tickets #74 and #105).
  821. fn wsEventsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  822. const engine: *WsEngine = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  823. mutexLock(&engine.ws_mutex);
  824. if (engine.ws_event_queue.items.len == 0) {
  825. mutexUnlock(&engine.ws_mutex);
  826. return api.makeNull();
  827. }
  828. const ev = engine.ws_event_queue.orderedRemove(0);
  829. if (engine.ws_event_queue.items.len > 0) http.ringWake(engine.ws_loop_wake_fd);
  830. mutexUnlock(&engine.ws_mutex);
  831. const fields = allocator.alloc(HlField, 10) catch {
  832. if (ev.ip) |ic| allocator.free(ic);
  833. if (ev.data) |d| allocator.free(d);
  834. if (ev.cookie) |ck| allocator.free(ck);
  835. if (ev.host) |hc| allocator.free(hc);
  836. if (ev.headers) |hd| allocator.free(hd);
  837. return api.makeNull();
  838. };
  839. const data_slice: []const u8 = if (ev.data) |d| d else "";
  840. const cookie_slice: []const u8 = if (ev.cookie) |ck| ck else "";
  841. const host_slice: []const u8 = if (ev.host) |hc| hc else "";
  842. const headers_slice: []const u8 = if (ev.headers) |hd| hd else "";
  843. fields[0] = .{ .key = http.hlStr("kind"), .value = api.makeString(ws_kind_names[@intFromEnum(ev.kind)]) };
  844. fields[1] = .{ .key = http.hlStr("id"), .value = api.makeNumber(@floatFromInt(ev.id)) };
  845. fields[2] = .{ .key = http.hlStr("data"), .value = api.makeString(data_slice) };
  846. fields[3] = .{ .key = http.hlStr("binary"), .value = api.makeBool(ev.is_binary) };
  847. fields[4] = .{ .key = http.hlStr("code"), .value = api.makeNumber(@floatFromInt(ev.code)) };
  848. fields[5] = .{ .key = http.hlStr("cookie"), .value = api.makeString(cookie_slice) };
  849. fields[6] = .{ .key = http.hlStr("host"), .value = api.makeString(host_slice) };
  850. fields[7] = .{ .key = http.hlStr("headers"), .value = api.makeString(headers_slice) };
  851. fields[8] = .{ .key = http.hlStr("ip"), .value = api.makeString(if (ev.ip) |ic| ic else "") };
  852. fields[9] = .{ .key = http.hlStr("secure"), .value = api.makeBool(ev.secure) };
  853. const obj = allocator.create(HlObject) catch {
  854. if (ev.data) |d| allocator.free(d);
  855. if (ev.cookie) |ck| allocator.free(ck);
  856. if (ev.host) |hc| allocator.free(hc);
  857. if (ev.headers) |hd| allocator.free(hd);
  858. if (ev.ip) |ic| allocator.free(ic);
  859. allocator.free(fields);
  860. return api.makeNull();
  861. };
  862. obj.* = .{ .fields = fields.ptr, .field_count = 10, .deinit_fn = &wsEventObjDeinit };
  863. return api.makeObject(obj);
  864. }
  865. fn wsEventsIterDeinit(_: ?*anyopaque) callconv(.c) void {
  866. // The request iterator owns shutdown: join I/O workers before the WS reader.
  867. // The small engine allocation and its loop wake fd outlive either iterator,
  868. // whose retirement order is unspecified (as for an explicitly closed core).
  869. }
  870. /// __native("http1.ws_events", port) → this listener's event iterator.
  871. export fn hl_http1_ws_events(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  872. const engine = wsEngineForPort(argc, argv, 0) orelse return api.makeNull();
  873. if (!wsEnsureStarted(engine)) return api.makeNull();
  874. const iter = allocator.create(HlIterator) catch return api.makeNull();
  875. iter.* = .{
  876. .context = engine,
  877. .next_fn = &wsEventsTryNext, // non-blocking either way — event loop only
  878. .deinit_fn = &wsEventsIterDeinit,
  879. .try_next_fn = &wsEventsTryNext,
  880. .wake_fd = engine.ws_loop_wake_fd, // mission 256 — set by wsEnsureStarted above
  881. .head_stamp_fn = &wsEventsHeadStamp,
  882. };
  883. return api.makeIterator(iter);
  884. }
  885. // --- cookie-grade random (mission 093) ------------------------------------
  886. // A session id is the ONLY thing standing between a stranger and someone else's
  887. // session, so it may not come from a seeded PRNG: `hl:math`'s random() is a
  888. // clock-seeded xoshiro, and a few of its outputs reveal its state, which would
  889. // make every other session's id derivable from one's own. This reads the
  890. // kernel's CSPRNG directly. It lives in hl:http1 because the session cookie is
  891. // an HTTP artifact and this plugin is the one that parses and sets it; there is
  892. // no other CSPRNG at the hl: level yet (named as a gap in mission 093's report).
  893. var token_buf: [128]u8 = undefined;
  894. /// __native("http1.random_token", n) → n lowercase hex chars (default 32, max 128)
  895. export fn hl_http1_random_token(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  896. var want: usize = 32;
  897. if (argc >= 1 and argv[0].type == .hl_number) {
  898. const n = argv[0].data.number;
  899. if (n >= 1 and n <= 128) want = @intFromFloat(n);
  900. }
  901. var raw: [64]u8 = undefined;
  902. const need = (want + 1) / 2;
  903. if (linux.getrandom(&raw, need, 0) != need) return api.makeNull();
  904. const hex = "0123456789abcdef";
  905. var i: usize = 0;
  906. while (i < want) : (i += 1) {
  907. const byte = raw[i / 2];
  908. const nib: u8 = if (i % 2 == 0) (byte >> 4) else (byte & 0x0f);
  909. token_buf[i] = hex[nib];
  910. }
  911. return api.makeString(token_buf[0..want]);
  912. }
  913. /// __native("http1.ws_send", id, text[, binaryFlag]) → 1 sent / 0 gone
  914. export fn hl_http1_ws_send(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  915. if (argc < 2 or argv[0].type != .hl_number or argv[1].type != .hl_string) return api.makeNumber(0);
  916. const id: u32 = @intFromFloat(argv[0].data.number);
  917. const engine = wsEngineForClient(id) orelse return api.makeNumber(0);
  918. const text = argv[1].data.string.ptr[0..argv[1].data.string.len];
  919. const opcode: ws.Opcode = if (argc >= 3 and argv[2].type == .hl_bool and argv[2].data.boolean) .binary else .text;
  920. mutexLock(&engine.ws_mutex);
  921. defer mutexUnlock(&engine.ws_mutex);
  922. const idx = wsFindByIdLocked(engine, id) orelse return api.makeNumber(0);
  923. const client = engine.ws_clients.items[idx];
  924. if (!ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), opcode, text)) {
  925. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  926. wsRemoveLocked(engine, idx);
  927. return api.makeNumber(0);
  928. }
  929. return api.makeNumber(1);
  930. }
  931. /// __native("http1.ws_broadcast", text) → number of clients written
  932. export fn hl_http1_ws_broadcast(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  933. if (argc < 1 or argv[0].type != .hl_string) return api.makeNumber(0);
  934. const engine = wsEngineForPort(argc, argv, 1) orelse return api.makeNumber(0);
  935. const text = argv[0].data.string.ptr[0..argv[0].data.string.len];
  936. mutexLock(&engine.ws_mutex);
  937. defer mutexUnlock(&engine.ws_mutex);
  938. var count: usize = 0;
  939. var i: usize = 0;
  940. while (i < engine.ws_clients.items.len) {
  941. const client = engine.ws_clients.items[i];
  942. if (ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .text, text)) {
  943. count += 1;
  944. i += 1;
  945. } else {
  946. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  947. wsRemoveLocked(engine, i);
  948. }
  949. }
  950. return api.makeNumber(@floatFromInt(count));
  951. }
  952. /// __native("http1.ws_ping", id) → 1 sent / 0 gone
  953. export fn hl_http1_ws_ping(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  954. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  955. const id: u32 = @intFromFloat(argv[0].data.number);
  956. const engine = wsEngineForClient(id) orelse return api.makeNumber(0);
  957. mutexLock(&engine.ws_mutex);
  958. defer mutexUnlock(&engine.ws_mutex);
  959. const idx = wsFindByIdLocked(engine, id) orelse return api.makeNumber(0);
  960. const client = engine.ws_clients.items[idx];
  961. if (!ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .ping, "")) {
  962. wsRemoveLocked(engine, idx);
  963. return api.makeNumber(0);
  964. }
  965. return api.makeNumber(1);
  966. }
  967. /// __native("http1.ws_close", id[, code]) → 1 initiated / 0 gone.
  968. /// Sends the close frame and waits for the peer echo (reader completes it).
  969. export fn hl_http1_ws_close(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  970. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  971. const id: u32 = @intFromFloat(argv[0].data.number);
  972. const engine = wsEngineForClient(id) orelse return api.makeNumber(0);
  973. const code: u16 = if (argc >= 2 and argv[1].type == .hl_number) @intFromFloat(argv[1].data.number) else ws.CLOSE_NORMAL;
  974. mutexLock(&engine.ws_mutex);
  975. defer mutexUnlock(&engine.ws_mutex);
  976. const idx = wsFindByIdLocked(engine, id) orelse return api.makeNumber(0);
  977. const client = engine.ws_clients.items[idx];
  978. if (!ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), code, "")) {
  979. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  980. wsRemoveLocked(engine, idx);
  981. return api.makeNumber(0);
  982. }
  983. client.closing = true;
  984. return api.makeNumber(1);
  985. }
  986. // =========================================================================
  987. // TLS context — OpenSSL via dlopen (optional, no compile-time dep)
  988. // =========================================================================
  989. const c_dlfcn = @cImport({
  990. @cInclude("dlfcn.h");
  991. });
  992. const SSL_CTX = opaque {};
  993. const SSL = opaque {};
  994. const SSL_METHOD = opaque {};
  995. // OpenSSL function pointer types
  996. const SSL_library_init_fn = *const fn () callconv(.c) c_int;
  997. const SSL_load_error_strings_fn = *const fn () callconv(.c) void;
  998. const TLS_server_method_fn = *const fn () callconv(.c) ?*const SSL_METHOD;
  999. const SSL_CTX_new_fn = *const fn (?*const SSL_METHOD) callconv(.c) ?*SSL_CTX;
  1000. const SSL_CTX_free_fn = *const fn (?*SSL_CTX) callconv(.c) void;
  1001. const SSL_CTX_use_certificate_chain_file_fn = *const fn (?*SSL_CTX, [*:0]const u8) callconv(.c) c_int;
  1002. const SSL_CTX_use_PrivateKey_file_fn = *const fn (?*SSL_CTX, [*:0]const u8, c_int) callconv(.c) c_int;
  1003. const SSL_new_fn = *const fn (?*SSL_CTX) callconv(.c) ?*SSL;
  1004. const SSL_free_fn = *const fn (?*SSL) callconv(.c) void;
  1005. const SSL_set_fd_fn = *const fn (?*SSL, c_int) callconv(.c) c_int;
  1006. const SSL_accept_fn = *const fn (?*SSL) callconv(.c) c_int;
  1007. const SSL_read_fn = *const fn (?*SSL, [*]u8, c_int) callconv(.c) c_int;
  1008. const SSL_write_fn = *const fn (?*SSL, [*]const u8, c_int) callconv(.c) c_int;
  1009. const SSL_shutdown_fn = *const fn (?*SSL) callconv(.c) c_int;
  1010. const SSL_get_error_fn = *const fn (?*SSL, c_int) callconv(.c) c_int;
  1011. const OPENSSL_init_ssl_fn = *const fn (u64, ?*anyopaque) callconv(.c) c_int;
  1012. const SSL_FILETYPE_PEM: c_int = 1;
  1013. const TlsContext = struct {
  1014. ssl_ctx: ?*SSL_CTX = null,
  1015. lib_ssl: ?*anyopaque = null,
  1016. lib_crypto: ?*anyopaque = null,
  1017. // Function pointers
  1018. fn_ssl_ctx_new: ?SSL_CTX_new_fn = null,
  1019. fn_ssl_ctx_free: ?SSL_CTX_free_fn = null,
  1020. fn_ssl_ctx_use_cert: ?SSL_CTX_use_certificate_chain_file_fn = null,
  1021. fn_ssl_ctx_use_key: ?SSL_CTX_use_PrivateKey_file_fn = null,
  1022. fn_ssl_new: ?SSL_new_fn = null,
  1023. fn_ssl_free: ?SSL_free_fn = null,
  1024. fn_ssl_set_fd: ?SSL_set_fd_fn = null,
  1025. fn_ssl_accept: ?SSL_accept_fn = null,
  1026. fn_ssl_read: ?SSL_read_fn = null,
  1027. fn_ssl_write: ?SSL_write_fn = null,
  1028. fn_ssl_shutdown: ?SSL_shutdown_fn = null,
  1029. fn_ssl_get_error: ?SSL_get_error_fn = null,
  1030. fn loadSym(lib: ?*anyopaque, comptime T: type, name: [*:0]const u8) ?T {
  1031. const sym = c_dlfcn.dlsym(lib, name) orelse return null;
  1032. return @ptrCast(sym);
  1033. }
  1034. fn init(cert_path: []const u8, key_path: []const u8) ?TlsContext {
  1035. var ctx = TlsContext{};
  1036. // Try loading libssl and libcrypto
  1037. const ssl_paths = [_][*:0]const u8{ "libssl.so.3", "libssl.so.1.1", "libssl.so" };
  1038. const crypto_paths = [_][*:0]const u8{ "libcrypto.so.3", "libcrypto.so.1.1", "libcrypto.so" };
  1039. for (ssl_paths) |path| {
  1040. ctx.lib_ssl = c_dlfcn.dlopen(path, c_dlfcn.RTLD_NOW | c_dlfcn.RTLD_LOCAL);
  1041. if (ctx.lib_ssl != null) break;
  1042. }
  1043. if (ctx.lib_ssl == null) {
  1044. logMsg("http1: TLS: failed to load libssl.so\n");
  1045. return null;
  1046. }
  1047. for (crypto_paths) |path| {
  1048. ctx.lib_crypto = c_dlfcn.dlopen(path, c_dlfcn.RTLD_NOW | c_dlfcn.RTLD_LOCAL);
  1049. if (ctx.lib_crypto != null) break;
  1050. }
  1051. if (ctx.lib_crypto == null) {
  1052. logMsg("http1: TLS: failed to load libcrypto.so\n");
  1053. _ = c_dlfcn.dlclose(ctx.lib_ssl);
  1054. return null;
  1055. }
  1056. // Load function pointers
  1057. // Try OPENSSL_init_ssl first (OpenSSL 1.1+), fall back to SSL_library_init
  1058. if (loadSym(ctx.lib_ssl, OPENSSL_init_ssl_fn, "OPENSSL_init_ssl")) |init_fn| {
  1059. _ = init_fn(0, null);
  1060. } else if (loadSym(ctx.lib_ssl, SSL_library_init_fn, "SSL_library_init")) |lib_init| {
  1061. _ = lib_init();
  1062. if (loadSym(ctx.lib_ssl, SSL_load_error_strings_fn, "SSL_load_error_strings")) |load_err| {
  1063. load_err();
  1064. }
  1065. }
  1066. const method_fn = loadSym(ctx.lib_ssl, TLS_server_method_fn, "TLS_server_method") orelse {
  1067. logMsg("http1: TLS: TLS_server_method not found\n");
  1068. ctx.deinit();
  1069. return null;
  1070. };
  1071. ctx.fn_ssl_ctx_new = loadSym(ctx.lib_ssl, SSL_CTX_new_fn, "SSL_CTX_new");
  1072. ctx.fn_ssl_ctx_free = loadSym(ctx.lib_ssl, SSL_CTX_free_fn, "SSL_CTX_free");
  1073. ctx.fn_ssl_ctx_use_cert = loadSym(ctx.lib_ssl, SSL_CTX_use_certificate_chain_file_fn, "SSL_CTX_use_certificate_chain_file");
  1074. ctx.fn_ssl_ctx_use_key = loadSym(ctx.lib_ssl, SSL_CTX_use_PrivateKey_file_fn, "SSL_CTX_use_PrivateKey_file");
  1075. ctx.fn_ssl_new = loadSym(ctx.lib_ssl, SSL_new_fn, "SSL_new");
  1076. ctx.fn_ssl_free = loadSym(ctx.lib_ssl, SSL_free_fn, "SSL_free");
  1077. ctx.fn_ssl_set_fd = loadSym(ctx.lib_ssl, SSL_set_fd_fn, "SSL_set_fd");
  1078. ctx.fn_ssl_accept = loadSym(ctx.lib_ssl, SSL_accept_fn, "SSL_accept");
  1079. ctx.fn_ssl_read = loadSym(ctx.lib_ssl, SSL_read_fn, "SSL_read");
  1080. ctx.fn_ssl_write = loadSym(ctx.lib_ssl, SSL_write_fn, "SSL_write");
  1081. ctx.fn_ssl_shutdown = loadSym(ctx.lib_ssl, SSL_shutdown_fn, "SSL_shutdown");
  1082. ctx.fn_ssl_get_error = loadSym(ctx.lib_ssl, SSL_get_error_fn, "SSL_get_error");
  1083. if (ctx.fn_ssl_ctx_new == null or ctx.fn_ssl_new == null or
  1084. ctx.fn_ssl_set_fd == null or ctx.fn_ssl_accept == null or
  1085. ctx.fn_ssl_read == null or ctx.fn_ssl_write == null)
  1086. {
  1087. logMsg("http1: TLS: missing required SSL symbols\n");
  1088. ctx.deinit();
  1089. return null;
  1090. }
  1091. // Create SSL_CTX
  1092. const method = method_fn();
  1093. ctx.ssl_ctx = ctx.fn_ssl_ctx_new.?(method);
  1094. if (ctx.ssl_ctx == null) {
  1095. logMsg("http1: TLS: SSL_CTX_new failed\n");
  1096. ctx.deinit();
  1097. return null;
  1098. }
  1099. // Load cert and key
  1100. const cert_z = allocator.dupeZ(u8, cert_path) catch {
  1101. ctx.deinit();
  1102. return null;
  1103. };
  1104. defer allocator.free(cert_z);
  1105. const key_z = allocator.dupeZ(u8, key_path) catch {
  1106. ctx.deinit();
  1107. return null;
  1108. };
  1109. defer allocator.free(key_z);
  1110. if (ctx.fn_ssl_ctx_use_cert) |use_cert| {
  1111. if (use_cert(ctx.ssl_ctx, cert_z.ptr) != 1) {
  1112. logFmt("http1: TLS: failed to load certificate: {s}\n", .{cert_path});
  1113. ctx.deinit();
  1114. return null;
  1115. }
  1116. }
  1117. if (ctx.fn_ssl_ctx_use_key) |use_key| {
  1118. if (use_key(ctx.ssl_ctx, key_z.ptr, SSL_FILETYPE_PEM) != 1) {
  1119. logFmt("http1: TLS: failed to load private key: {s}\n", .{key_path});
  1120. ctx.deinit();
  1121. return null;
  1122. }
  1123. }
  1124. logMsg("http1: TLS initialized\n");
  1125. return ctx;
  1126. }
  1127. fn wrapConnection(self: *const TlsContext, fd: i32) ?*SSL {
  1128. const ssl = self.fn_ssl_new.?(self.ssl_ctx);
  1129. if (ssl == null) return null;
  1130. _ = self.fn_ssl_set_fd.?(ssl, fd);
  1131. const ret = self.fn_ssl_accept.?(ssl);
  1132. if (ret != 1) {
  1133. self.fn_ssl_free.?(ssl);
  1134. return null;
  1135. }
  1136. return ssl;
  1137. }
  1138. fn sslRead(self: *const TlsContext, ssl: *SSL, buf: []u8) isize {
  1139. const ret = self.fn_ssl_read.?(ssl, buf.ptr, @intCast(@min(buf.len, std.math.maxInt(c_int))));
  1140. if (ret <= 0) return 0;
  1141. return @intCast(ret);
  1142. }
  1143. fn sslWrite(self: *const TlsContext, ssl: *SSL, data: []const u8) isize {
  1144. var written: usize = 0;
  1145. while (written < data.len) {
  1146. const chunk_len: c_int = @intCast(@min(data.len - written, std.math.maxInt(c_int)));
  1147. const ret = self.fn_ssl_write.?(ssl, data[written..].ptr, chunk_len);
  1148. if (ret <= 0) return @intCast(written);
  1149. written += @intCast(ret);
  1150. }
  1151. return @intCast(written);
  1152. }
  1153. fn sslShutdown(self: *const TlsContext, ssl: *SSL) void {
  1154. _ = self.fn_ssl_shutdown.?(ssl);
  1155. self.fn_ssl_free.?(ssl);
  1156. }
  1157. fn deinit(self: *TlsContext) void {
  1158. if (self.ssl_ctx != null) {
  1159. if (self.fn_ssl_ctx_free) |free_fn| {
  1160. free_fn(self.ssl_ctx);
  1161. }
  1162. self.ssl_ctx = null;
  1163. }
  1164. if (self.lib_ssl != null) {
  1165. _ = c_dlfcn.dlclose(self.lib_ssl);
  1166. self.lib_ssl = null;
  1167. }
  1168. if (self.lib_crypto != null) {
  1169. _ = c_dlfcn.dlclose(self.lib_crypto);
  1170. self.lib_crypto = null;
  1171. }
  1172. }
  1173. };
  1174. // =========================================================================
  1175. // MPSC Request Queue — thread-safe, blocks on dequeue
  1176. // =========================================================================
  1177. const ParsedRequest = struct {
  1178. method: []const u8,
  1179. path: []const u8, // URL-decoded
  1180. query_params: []http.QueryParam, // parsed key-value pairs
  1181. query_raw: []const u8, // raw query string
  1182. headers: std.ArrayListUnmanaged(HeaderPair),
  1183. body: []const u8,
  1184. client_fd: i32,
  1185. ssl: ?*SSL, // null if plain HTTP
  1186. keep_alive: bool,
  1187. };
  1188. const HeaderPair = struct {
  1189. key: []const u8,
  1190. value: []const u8,
  1191. };
  1192. const RequestQueue = struct {
  1193. queue: std.ArrayListUnmanaged(ParsedRequest),
  1194. mutex: PthreadMutex,
  1195. condvar: PthreadCond,
  1196. shutdown: bool,
  1197. /// THE EVENT LOOP'S BELL (mission 256). The condvar above wakes a `for (req of
  1198. /// server)` consumer blocked in `dequeue`; the interpreter's event loop is
  1199. /// NOT that consumer — it polls `tryDequeue` from a loop that also watches
  1200. /// every other source, so it cannot block on a condvar belonging to one of
  1201. /// them. An eventfd it can: `native/src/loop_wait.zig` epolls this fd, and an
  1202. /// idle server costs nothing instead of 1000 empty poll rounds a second.
  1203. loop_wake_fd: i32,
  1204. fn init() RequestQueue {
  1205. var self: RequestQueue = .{
  1206. .queue = .empty,
  1207. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1208. .condvar = c.PTHREAD_COND_INITIALIZER,
  1209. .shutdown = false,
  1210. .loop_wake_fd = http.makeWakeFd(),
  1211. };
  1212. mutexInit(&self.mutex);
  1213. condInit(&self.condvar);
  1214. return self;
  1215. }
  1216. fn enqueue(self: *RequestQueue, req: ParsedRequest) void {
  1217. mutexLock(&self.mutex);
  1218. defer mutexUnlock(&self.mutex);
  1219. self.queue.append(allocator, req) catch return;
  1220. condSignal(&self.condvar);
  1221. // Rung INSIDE the lock, so the fd's counter is already up by the time the
  1222. // request is visible to `tryDequeue`. A loop that is between its last poll
  1223. // and its next `epoll_wait` therefore finds the level raised and returns
  1224. // at once instead of sleeping on a queue that has work in it.
  1225. http.ringWake(self.loop_wake_fd);
  1226. }
  1227. fn dequeue(self: *RequestQueue) ?ParsedRequest {
  1228. mutexLock(&self.mutex);
  1229. defer mutexUnlock(&self.mutex);
  1230. while (self.queue.items.len == 0 and !self.shutdown) {
  1231. condWait(&self.condvar, &self.mutex);
  1232. }
  1233. if (self.shutdown and self.queue.items.len == 0) return null;
  1234. const req = self.queue.orderedRemove(0);
  1235. if (self.queue.items.len > 0) http.ringWake(self.loop_wake_fd);
  1236. return req;
  1237. }
  1238. /// Non-blocking: returns null immediately if queue is empty
  1239. fn tryDequeue(self: *RequestQueue) ?ParsedRequest {
  1240. mutexLock(&self.mutex);
  1241. defer mutexUnlock(&self.mutex);
  1242. if (self.queue.items.len == 0) return null;
  1243. const req = self.queue.orderedRemove(0);
  1244. if (self.queue.items.len > 0) http.ringWake(self.loop_wake_fd);
  1245. return req;
  1246. }
  1247. fn signalShutdown(self: *RequestQueue) void {
  1248. mutexLock(&self.mutex);
  1249. defer mutexUnlock(&self.mutex);
  1250. self.shutdown = true;
  1251. condBroadcast(&self.condvar);
  1252. // The event loop is told too — it is blocked on this fd and its `while`
  1253. // condition (has every source retired?) can only be re-read on the way out.
  1254. http.ringWake(self.loop_wake_fd);
  1255. }
  1256. fn deinit(self: *RequestQueue) void {
  1257. // Free any remaining queued requests
  1258. for (self.queue.items) |*req| {
  1259. freeRequest(req);
  1260. }
  1261. self.queue.deinit(allocator);
  1262. if (self.loop_wake_fd >= 0) {
  1263. _ = linux.close(self.loop_wake_fd);
  1264. self.loop_wake_fd = -1;
  1265. }
  1266. _ = c.pthread_cond_destroy(&self.condvar);
  1267. _ = c.pthread_mutex_destroy(&self.mutex);
  1268. }
  1269. };
  1270. fn freeRequest(req: *ParsedRequest) void {
  1271. allocator.free(req.method);
  1272. allocator.free(req.path);
  1273. allocator.free(req.query_raw);
  1274. for (req.query_params) |param| {
  1275. allocator.free(param.key);
  1276. allocator.free(param.value);
  1277. }
  1278. allocator.free(req.query_params);
  1279. for (req.headers.items) |hdr| {
  1280. allocator.free(hdr.key);
  1281. allocator.free(hdr.value);
  1282. }
  1283. req.headers.deinit(allocator);
  1284. if (req.body.len > 0) allocator.free(req.body);
  1285. }
  1286. // =========================================================================
  1287. // Connection — per-connection state tracked by I/O workers
  1288. // =========================================================================
  1289. const Connection = struct {
  1290. fd: i32,
  1291. ssl: ?*SSL,
  1292. keep_alive: bool,
  1293. request_count: u32,
  1294. max_requests: u32,
  1295. fn read(self: *const Connection, tls: ?*const TlsContext, buf: []u8) usize {
  1296. if (self.ssl) |ssl_ptr| {
  1297. if (tls) |t| {
  1298. const n = t.sslRead(ssl_ptr, buf);
  1299. if (n <= 0) return 0;
  1300. return @intCast(n);
  1301. }
  1302. return 0;
  1303. }
  1304. return sysRead(self.fd, buf);
  1305. }
  1306. fn write(self: *const Connection, tls: ?*const TlsContext, data: []const u8) void {
  1307. if (self.ssl) |ssl_ptr| {
  1308. if (tls) |t| {
  1309. _ = t.sslWrite(ssl_ptr, data);
  1310. return;
  1311. }
  1312. }
  1313. sysWriteAll(self.fd, data);
  1314. }
  1315. fn close(self: *Connection, tls: ?*const TlsContext) void {
  1316. if (self.ssl) |ssl_ptr| {
  1317. if (tls) |t| {
  1318. t.sslShutdown(ssl_ptr);
  1319. }
  1320. self.ssl = null;
  1321. }
  1322. _ = linux.close(self.fd);
  1323. }
  1324. };
  1325. // =========================================================================
  1326. // ServerCore — owns server socket, epoll, threads, queue, optional TLS
  1327. // =========================================================================
  1328. const MAX_KEEPALIVE_REQUESTS: u32 = 100;
  1329. const MAX_IO_THREADS: u32 = 16;
  1330. const ServerCore = struct {
  1331. port: u16 = 0,
  1332. websocket: *WsEngine,
  1333. server_fd: i32,
  1334. epoll_fd: i32,
  1335. shutdown_fd: i32, // eventfd for shutdown signal
  1336. tls: ?TlsContext,
  1337. request_queue: RequestQueue,
  1338. running: std.atomic.Value(bool),
  1339. acceptor_thread: ?std.Thread,
  1340. io_threads: []std.Thread,
  1341. num_threads: u32,
  1342. // Connection tracking for I/O threads
  1343. conn_queue: ConnectionQueue,
  1344. /// idle connections wait here instead of inside a blocking worker read (mission 084)
  1345. parked: ParkedConns,
  1346. /// Largest request body this server reads (ticket #445): a bigger Content-Length, or a
  1347. /// chunked body that grows past it, is refused `413` before the body is buffered.
  1348. max_body: usize = DEFAULT_MAX_BODY,
  1349. /// Refuse a WebSocket upgrade whose Origin is foreign with `403` before the 101 (#445).
  1350. ws_check_origin: bool = false,
  1351. /// Extra allowed origins (comma-separated, `scheme://host[:port]` or bare `host[:port]`);
  1352. /// owned copy, empty = none.
  1353. ws_origins: []const u8 = "",
  1354. fn create(port: u16, host_str: []const u8, cert_path: []const u8, key_path: []const u8, num_threads: u32) ?*ServerCore {
  1355. const core = allocator.create(ServerCore) catch return null;
  1356. const engine = allocator.create(WsEngine) catch {
  1357. allocator.destroy(core);
  1358. return null;
  1359. };
  1360. engine.* = .{};
  1361. core.* = .{
  1362. .websocket = engine,
  1363. .server_fd = -1,
  1364. .epoll_fd = -1,
  1365. .shutdown_fd = -1,
  1366. .tls = null,
  1367. .request_queue = RequestQueue.init(),
  1368. .running = std.atomic.Value(bool).init(false),
  1369. .acceptor_thread = null,
  1370. .io_threads = &[_]std.Thread{},
  1371. .num_threads = @min(num_threads, MAX_IO_THREADS),
  1372. .conn_queue = ConnectionQueue.init(),
  1373. .parked = ParkedConns.init(),
  1374. };
  1375. // Create TCP socket. NONBLOCK IS NOT DECORATION (mission 260): the acceptor
  1376. // drains with `while (true) accept4(...)` until the call fails, and on a
  1377. // BLOCKING listener that last call does not fail — it sleeps in the kernel
  1378. // (`inet_csk_accept`) until the next client arrives. The thread then never
  1379. // re-reads `core.running`, so `shutdown()`'s `join(acceptor)` waits forever
  1380. // and `close()` never returns. Measured: after ONE connection the process was
  1381. // down to two threads, main in `__futex_wait` (the join) and the acceptor in
  1382. // `inet_csk_accept`; each extra TCP connect added exactly one fd and put the
  1383. // acceptor straight back into `inet_csk_accept`. hl:http2's listener
  1384. // (`http2.zig:926`) has always carried NONBLOCK — http1 was the outlier.
  1385. // The accept flags below apply to the ACCEPTED socket, never to this one.
  1386. const sock_rc = linux.socket(linux.AF.INET, linux.SOCK.STREAM | linux.SOCK.CLOEXEC | linux.SOCK.NONBLOCK, 0);
  1387. const server_fd: i32 = @bitCast(@as(u32, @truncate(sock_rc)));
  1388. if (server_fd < 0) {
  1389. logMsg("http1: socket() failed\n");
  1390. allocator.destroy(core);
  1391. return null;
  1392. }
  1393. core.server_fd = server_fd;
  1394. // SO_REUSEADDR
  1395. const one: i32 = 1;
  1396. _ = linux.setsockopt(server_fd, linux.SOL.SOCKET, linux.SO.REUSEADDR, @ptrCast(&one), @sizeOf(i32));
  1397. // Parse host address
  1398. var addr_val: u32 = 0; // INADDR_ANY
  1399. if (host_str.len > 0 and !std.mem.eql(u8, host_str, "0.0.0.0")) {
  1400. addr_val = parseIPv4(host_str) orelse 0;
  1401. }
  1402. // Bind
  1403. const addr = linux.sockaddr.in{
  1404. .port = std.mem.nativeToBig(u16, port),
  1405. .addr = addr_val,
  1406. };
  1407. const bind_rc = linux.bind(server_fd, @ptrCast(&addr), @sizeOf(linux.sockaddr.in));
  1408. const bind_err: i32 = @bitCast(@as(u32, @truncate(bind_rc)));
  1409. if (bind_err < 0) {
  1410. // The prefix is LOAD-BEARING: `tests/browser/fixtures.mjs` breaks its
  1411. // readiness wait on `bind() failed on port N` (mission 285). The errno
  1412. // and the holder are appended to it, never in front of it.
  1413. var why: [320]u8 = undefined;
  1414. logFmt("http1: bind() failed on port {d}: {s}\n", .{ port, http.bindFailureDetail(&why, bind_rc, port, false) });
  1415. core.destroy();
  1416. return null;
  1417. }
  1418. const listen_rc = linux.listen(server_fd, 128);
  1419. const listen_err: i32 = @bitCast(@as(u32, @truncate(listen_rc)));
  1420. if (listen_err < 0) {
  1421. logMsg("http1: listen() failed\n");
  1422. core.destroy();
  1423. return null;
  1424. }
  1425. // Create eventfd for shutdown signaling
  1426. const efd_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  1427. const shutdown_fd: i32 = @bitCast(@as(u32, @truncate(efd_rc)));
  1428. if (shutdown_fd < 0) {
  1429. logMsg("http1: eventfd() failed\n");
  1430. core.destroy();
  1431. return null;
  1432. }
  1433. core.shutdown_fd = shutdown_fd;
  1434. // Create epoll instance
  1435. const epoll_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  1436. const epoll_fd: i32 = @bitCast(@as(u32, @truncate(epoll_rc)));
  1437. if (epoll_fd < 0) {
  1438. logMsg("http1: epoll_create1() failed\n");
  1439. core.destroy();
  1440. return null;
  1441. }
  1442. core.epoll_fd = epoll_fd;
  1443. // Add server_fd to epoll
  1444. var ev = linux.epoll_event{
  1445. .events = linux.EPOLL.IN,
  1446. .data = .{ .fd = server_fd },
  1447. };
  1448. _ = linux.epoll_ctl(epoll_fd, linux.EPOLL.CTL_ADD, server_fd, &ev);
  1449. // Add shutdown_fd to epoll
  1450. var shutdown_ev = linux.epoll_event{
  1451. .events = linux.EPOLL.IN,
  1452. .data = .{ .fd = shutdown_fd },
  1453. };
  1454. _ = linux.epoll_ctl(epoll_fd, linux.EPOLL.CTL_ADD, shutdown_fd, &shutdown_ev);
  1455. // Initialize TLS if cert+key provided
  1456. if (cert_path.len > 0 and key_path.len > 0) {
  1457. core.tls = TlsContext.init(cert_path, key_path);
  1458. if (core.tls == null) {
  1459. logMsg("http1: TLS initialization failed, falling back to plain HTTP\n");
  1460. }
  1461. }
  1462. logFmt("http1: listening on :{d}{s}\n", .{ port, if (core.tls != null) " (TLS)" else "" });
  1463. // Start threads
  1464. core.running.store(true, .release);
  1465. // Parker thread first: the acceptor parks into it from its very first accept.
  1466. // If it cannot start we log and keep going — connections then go straight to the
  1467. // pool, which is the pre-084 (starvable) behaviour rather than an outage.
  1468. if (!core.parked.start(core)) {
  1469. logMsg("http1: parker thread unavailable — idle keep-alive connections will hold I/O workers\n");
  1470. }
  1471. // Allocate I/O threads
  1472. const threads = allocator.alloc(std.Thread, core.num_threads) catch {
  1473. core.destroy();
  1474. return null;
  1475. };
  1476. core.io_threads = threads;
  1477. for (0..core.num_threads) |i| {
  1478. core.io_threads[i] = std.Thread.spawn(.{}, ioWorker, .{core}) catch {
  1479. logFmt("http1: failed to spawn I/O thread {d}\n", .{i});
  1480. core.num_threads = @intCast(i);
  1481. core.io_threads = core.io_threads[0..i];
  1482. break;
  1483. };
  1484. }
  1485. // Start acceptor thread
  1486. core.acceptor_thread = std.Thread.spawn(.{}, acceptorLoop, .{core}) catch {
  1487. logMsg("http1: failed to spawn acceptor thread\n");
  1488. core.shutdown();
  1489. core.destroy();
  1490. return null;
  1491. };
  1492. core.port = port;
  1493. registerCore(core);
  1494. return core;
  1495. }
  1496. fn shutdown(self: *ServerCore) void {
  1497. unregisterCore(self);
  1498. if (!self.running.swap(false, .acq_rel)) return;
  1499. // Signal shutdown via eventfd
  1500. if (self.shutdown_fd >= 0) {
  1501. const val: u64 = 1;
  1502. _ = linux.write(self.shutdown_fd, @ptrCast(&val), @sizeOf(u64));
  1503. }
  1504. // Wake up the request queue so dequeue() unblocks
  1505. self.request_queue.signalShutdown();
  1506. // Stop parking before the workers: the parker must not push new work into a
  1507. // queue whose consumers are being torn down.
  1508. self.parked.stop();
  1509. // Signal connection queue to wake I/O workers
  1510. self.conn_queue.signalShutdown();
  1511. // Join acceptor thread
  1512. if (self.acceptor_thread) |t| {
  1513. t.join();
  1514. self.acceptor_thread = null;
  1515. }
  1516. // Join I/O threads
  1517. for (self.io_threads) |t| {
  1518. t.join();
  1519. }
  1520. wsShutdown(self.websocket);
  1521. }
  1522. fn destroy(self: *ServerCore) void {
  1523. self.shutdown();
  1524. if (self.epoll_fd >= 0) _ = linux.close(self.epoll_fd);
  1525. if (self.shutdown_fd >= 0) _ = linux.close(self.shutdown_fd);
  1526. if (self.server_fd >= 0) _ = linux.close(self.server_fd);
  1527. if (self.tls) |*tls| tls.deinit();
  1528. // Close every still-parked idle connection, then drain conn_queue
  1529. self.parked.deinit(if (self.tls) |*t| t else null);
  1530. self.conn_queue.deinit(if (self.tls) |*t| t else null);
  1531. self.request_queue.deinit();
  1532. if (self.io_threads.len > 0) allocator.free(self.io_threads);
  1533. allocator.destroy(self);
  1534. }
  1535. };
  1536. // =========================================================================
  1537. // Connection Queue — MPSC queue for acceptor → I/O workers
  1538. // =========================================================================
  1539. const ConnectionQueue = struct {
  1540. queue: std.ArrayListUnmanaged(Connection),
  1541. mutex: PthreadMutex,
  1542. condvar: PthreadCond,
  1543. shutdown: bool,
  1544. fn init() ConnectionQueue {
  1545. var self: ConnectionQueue = .{
  1546. .queue = .empty,
  1547. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1548. .condvar = c.PTHREAD_COND_INITIALIZER,
  1549. .shutdown = false,
  1550. };
  1551. mutexInit(&self.mutex);
  1552. condInit(&self.condvar);
  1553. return self;
  1554. }
  1555. fn enqueue(self: *ConnectionQueue, conn: Connection) void {
  1556. mutexLock(&self.mutex);
  1557. defer mutexUnlock(&self.mutex);
  1558. self.queue.append(allocator, conn) catch return;
  1559. condSignal(&self.condvar);
  1560. }
  1561. fn dequeue(self: *ConnectionQueue) ?Connection {
  1562. mutexLock(&self.mutex);
  1563. defer mutexUnlock(&self.mutex);
  1564. while (self.queue.items.len == 0 and !self.shutdown) {
  1565. condWait(&self.condvar, &self.mutex);
  1566. }
  1567. if (self.shutdown and self.queue.items.len == 0) return null;
  1568. return self.queue.orderedRemove(0);
  1569. }
  1570. fn signalShutdown(self: *ConnectionQueue) void {
  1571. mutexLock(&self.mutex);
  1572. defer mutexUnlock(&self.mutex);
  1573. self.shutdown = true;
  1574. condBroadcast(&self.condvar);
  1575. }
  1576. /// Close everything still queued and stay a VALID, EMPTY queue — `deinit`
  1577. /// leaves the list `undefined`, which is only safe on a core that is being
  1578. /// freed, and a closed core deliberately is not (see `hl_http1_close`).
  1579. fn closeAll(self: *ConnectionQueue, tls: ?*TlsContext) void {
  1580. mutexLock(&self.mutex);
  1581. defer mutexUnlock(&self.mutex);
  1582. for (self.queue.items) |*conn| conn.close(tls);
  1583. self.queue.clearRetainingCapacity();
  1584. }
  1585. fn deinit(self: *ConnectionQueue, tls: ?*TlsContext) void {
  1586. for (self.queue.items) |*conn| {
  1587. conn.close(tls);
  1588. }
  1589. self.queue.deinit(allocator);
  1590. }
  1591. };
  1592. // =========================================================================
  1593. // ParkedConns — idle connections wait HERE, not in an I/O worker (mission 084)
  1594. // =========================================================================
  1595. //
  1596. // The starvation this fixes, measured: a `threads = 4` server, four keep-alive
  1597. // connections that have gone quiet, and every subsequent request times out — each idle
  1598. // socket sat inside a worker's blocking read(). Parking inverts that: an idle connection
  1599. // costs one epoll registration and ZERO threads, and a worker only ever picks up a
  1600. // connection that already has bytes waiting (or has hung up, which it reads as EOF and
  1601. // closes). Connections are parked from the acceptor (a fresh socket may be silent — a
  1602. // pre-connected browser socket routinely is) and after every keep-alive response.
  1603. //
  1604. // TLS caveat: an ESTABLISHED TLS connection is never parked. OpenSSL may hold already-
  1605. // decrypted plaintext in its own buffer, which epoll on the raw fd cannot see, so parking
  1606. // it could hang a live request. `ssl == null` covers all plain HTTP plus the pre-handshake
  1607. // TLS socket (the ClientHello does arrive on the raw fd), which is what the park path takes.
  1608. /// How long a parked, silent connection is kept before it is closed. It costs no thread,
  1609. /// only an fd, so this is generous compared to the old in-worker 30s SO_RCVTIMEO.
  1610. const PARK_IDLE_TIMEOUT_MS: i64 = 60_000;
  1611. /// Milliseconds on CLOCK_MONOTONIC. This zig's `std.time` exposes no timestamp function,
  1612. /// and monotonic is the right clock anyway — a wall-clock step must not expire a live
  1613. /// connection early or keep a dead one parked.
  1614. fn monotonicMs() i64 {
  1615. var ts: linux.timespec = undefined;
  1616. if (linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts) != 0) return 0;
  1617. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  1618. }
  1619. const ParkedConn = struct {
  1620. conn: Connection,
  1621. /// monotonic ms after which this silent connection is closed
  1622. deadline_ms: i64,
  1623. };
  1624. const ParkedConns = struct {
  1625. epoll_fd: i32,
  1626. wake_fd: i32,
  1627. thread: ?std.Thread,
  1628. running: std.atomic.Value(bool),
  1629. mutex: PthreadMutex,
  1630. /// fd → parked connection. Guarded by `mutex`; the parker thread is the only
  1631. /// consumer, park() the only producer, so a plain map is enough.
  1632. map: std.AutoHashMapUnmanaged(i32, ParkedConn),
  1633. fn init() ParkedConns {
  1634. var self: ParkedConns = .{
  1635. .epoll_fd = -1,
  1636. .wake_fd = -1,
  1637. .thread = null,
  1638. .running = std.atomic.Value(bool).init(false),
  1639. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1640. .map = .empty,
  1641. };
  1642. mutexInit(&self.mutex);
  1643. return self;
  1644. }
  1645. /// Create the epoll instance + wake eventfd and spawn the parker thread.
  1646. /// Returns false if the kernel objects could not be made — the caller then falls
  1647. /// back to handing connections straight to the pool (old behaviour, still correct,
  1648. /// just starvable).
  1649. fn start(self: *ParkedConns, core: *ServerCore) bool {
  1650. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  1651. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  1652. if (ep < 0) return false;
  1653. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  1654. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  1655. if (ef < 0) {
  1656. _ = linux.close(ep);
  1657. return false;
  1658. }
  1659. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  1660. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  1661. self.epoll_fd = ep;
  1662. self.wake_fd = ef;
  1663. self.running.store(true, .release);
  1664. self.thread = std.Thread.spawn(.{}, parkerLoop, .{core}) catch {
  1665. self.running.store(false, .release);
  1666. _ = linux.close(ep);
  1667. _ = linux.close(ef);
  1668. self.epoll_fd = -1;
  1669. self.wake_fd = -1;
  1670. return false;
  1671. };
  1672. return true;
  1673. }
  1674. /// Hand a connection to the parker. The map insert happens BEFORE the epoll ADD so
  1675. /// the parker can never see a readable fd it has no entry for.
  1676. fn park(self: *ParkedConns, conn: Connection) bool {
  1677. if (self.epoll_fd < 0 or !self.running.load(.acquire)) return false;
  1678. mutexLock(&self.mutex);
  1679. self.map.put(allocator, conn.fd, .{
  1680. .conn = conn,
  1681. .deadline_ms = monotonicMs() + PARK_IDLE_TIMEOUT_MS,
  1682. }) catch {
  1683. mutexUnlock(&self.mutex);
  1684. return false;
  1685. };
  1686. var ev = linux.epoll_event{
  1687. .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
  1688. .data = .{ .fd = conn.fd },
  1689. };
  1690. const rc = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_ADD, conn.fd, &ev);
  1691. const err: i32 = @bitCast(@as(u32, @truncate(rc)));
  1692. if (err < 0) {
  1693. _ = self.map.remove(conn.fd);
  1694. mutexUnlock(&self.mutex);
  1695. return false;
  1696. }
  1697. mutexUnlock(&self.mutex);
  1698. return true;
  1699. }
  1700. /// Take a parked connection off the epoll set. Returns it if we still owned it.
  1701. fn take(self: *ParkedConns, fd: i32) ?Connection {
  1702. mutexLock(&self.mutex);
  1703. defer mutexUnlock(&self.mutex);
  1704. const entry = self.map.fetchRemove(fd) orelse return null;
  1705. _ = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  1706. return entry.value.conn;
  1707. }
  1708. /// Close every parked connection whose silence outlived PARK_IDLE_TIMEOUT_MS.
  1709. fn sweepExpired(self: *ParkedConns, tls: ?*TlsContext) void {
  1710. const now = monotonicMs();
  1711. mutexLock(&self.mutex);
  1712. defer mutexUnlock(&self.mutex);
  1713. var expired: [64]i32 = undefined;
  1714. var n: usize = 0;
  1715. var it = self.map.iterator();
  1716. while (it.next()) |kv| {
  1717. if (kv.value_ptr.deadline_ms <= now) {
  1718. if (n == expired.len) break;
  1719. expired[n] = kv.key_ptr.*;
  1720. n += 1;
  1721. }
  1722. }
  1723. for (expired[0..n]) |fd| {
  1724. if (self.map.fetchRemove(fd)) |e| {
  1725. _ = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  1726. var conn = e.value.conn;
  1727. conn.close(tls);
  1728. }
  1729. }
  1730. }
  1731. fn stop(self: *ParkedConns) void {
  1732. if (!self.running.swap(false, .acq_rel)) return;
  1733. if (self.wake_fd >= 0) {
  1734. const val: u64 = 1;
  1735. _ = linux.write(self.wake_fd, @ptrCast(&val), @sizeOf(u64));
  1736. }
  1737. if (self.thread) |t| {
  1738. t.join();
  1739. self.thread = null;
  1740. }
  1741. }
  1742. /// Close every parked connection and stay a VALID, EMPTY map. Unlike `deinit`
  1743. /// this keeps the epoll/wake fds and the struct usable — a CLOSED core is not
  1744. /// a freed one (`hl_http1_close`), and `park()` already refuses once `running`
  1745. /// is false, so the emptied map simply stays empty.
  1746. fn closeAll(self: *ParkedConns, tls: ?*TlsContext) void {
  1747. mutexLock(&self.mutex);
  1748. defer mutexUnlock(&self.mutex);
  1749. var it = self.map.iterator();
  1750. while (it.next()) |kv| {
  1751. var conn = kv.value_ptr.conn;
  1752. conn.close(tls);
  1753. }
  1754. self.map.clearRetainingCapacity();
  1755. }
  1756. fn deinit(self: *ParkedConns, tls: ?*TlsContext) void {
  1757. self.stop();
  1758. mutexLock(&self.mutex);
  1759. var it = self.map.iterator();
  1760. while (it.next()) |kv| {
  1761. var conn = kv.value_ptr.conn;
  1762. conn.close(tls);
  1763. }
  1764. self.map.deinit(allocator);
  1765. self.map = .empty;
  1766. mutexUnlock(&self.mutex);
  1767. if (self.epoll_fd >= 0) _ = linux.close(self.epoll_fd);
  1768. if (self.wake_fd >= 0) _ = linux.close(self.wake_fd);
  1769. self.epoll_fd = -1;
  1770. self.wake_fd = -1;
  1771. }
  1772. };
  1773. /// The parker thread: waits for a parked connection to become READABLE and only then
  1774. /// hands it to an I/O worker. The 1s epoll timeout doubles as the idle-sweep tick.
  1775. fn parkerLoop(core: *ServerCore) void {
  1776. var events: [64]linux.epoll_event = undefined;
  1777. while (core.parked.running.load(.acquire)) {
  1778. const n_rc = linux.epoll_wait(core.parked.epoll_fd, &events, events.len, 1000);
  1779. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  1780. if (n > 0) {
  1781. for (events[0..@intCast(n)]) |ev| {
  1782. if (ev.data.fd == core.parked.wake_fd) {
  1783. var drain: u64 = 0;
  1784. _ = linux.read(core.parked.wake_fd, @ptrCast(&drain), @sizeOf(u64));
  1785. continue;
  1786. }
  1787. // Readable, hung up or errored — all three are a worker's job: it either
  1788. // parses the request or reads EOF and closes.
  1789. if (core.parked.take(ev.data.fd)) |conn| {
  1790. if (core.running.load(.acquire)) {
  1791. core.conn_queue.enqueue(conn);
  1792. } else {
  1793. var dead = conn;
  1794. dead.close(if (core.tls) |*t| t else null);
  1795. }
  1796. }
  1797. }
  1798. }
  1799. core.parked.sweepExpired(if (core.tls) |*t| t else null);
  1800. }
  1801. }
  1802. /// Park `conn` if we can, otherwise hand it straight to the pool. Every enqueue site
  1803. /// that is NOT known to have bytes waiting goes through here.
  1804. fn parkOrEnqueue(core: *ServerCore, conn: Connection) void {
  1805. // An established TLS connection may hold decrypted bytes epoll cannot see — see the
  1806. // ParkedConns header comment. Those go straight to a worker, as before.
  1807. if (conn.ssl == null and core.parked.park(conn)) return;
  1808. core.conn_queue.enqueue(conn);
  1809. }
  1810. // =========================================================================
  1811. // Acceptor thread — epoll loop accepting new connections
  1812. // =========================================================================
  1813. fn acceptorLoop(core: *ServerCore) void {
  1814. var events: [64]linux.epoll_event = undefined;
  1815. while (core.running.load(.acquire)) {
  1816. const n_rc = linux.epoll_wait(core.epoll_fd, &events, events.len, 1000);
  1817. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  1818. if (n < 0) continue;
  1819. if (n == 0) continue;
  1820. for (events[0..@intCast(n)]) |ev| {
  1821. if (ev.data.fd == core.shutdown_fd) {
  1822. return; // shutdown signaled
  1823. }
  1824. if (ev.data.fd == core.server_fd) {
  1825. // Accept all pending connections — the listener is NONBLOCK, so the
  1826. // drain ends on EAGAIN instead of sleeping inside accept4().
  1827. while (true) {

Only the first lines are shown.

Branches

Latest commits

  • 9ba258d3|||PR records: HM55b resultTracker
  • 64f2d300Merge branch 'records-hm55b2' into mainTracker
  • ae3b80dc|||PR records: HM55b briefTracker
  • 7ef3cb3bMerge branch 'records-st55' into mainTracker
  • fec2e080|||PR records: STATUS HM55Tracker
  • 8e174918Merge branch 'records-hm55b' into mainTracker
  • b1ecee57|||PR records: HM55 stateTracker
  • 28eab08cMerge branch 'records-hm55' into mainTracker
  • d3edaa05|||PR records: HM55 start, PROCEDURES.mdTracker
  • 3059f86cMerge branch 'records-design-rule' into mainTracker
  • 421a4809|||PR records: his-design rule (Apollo 2026-11-13)Tracker
  • d1390692Merge branch 'records-dp75b' into mainTracker
  • a4d1a7d2|||PR records: later steps checked, branch auditTracker
  • e070e16fMerge branch 'records-dp75' into mainTracker
  • 642b4fa8|||PR records: DP75 day62 live, AP62 briefTracker
  • bfc4ea4dMerge branch 'ap62' into mainTracker
  • 2c95ac46|||PR AP62: re-vendor Hybriel set day62 (source 70341ad2, bin a54f5f08)Tracker
  • b9c7c3c8Merge branch 'records-dp74' into mainTracker
  • 85cfb4ae|||PR records: AP61 day61, DP74 liveTracker
  • b1496147Merge branch 'ap61' into mainTracker