gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2a4cfc552a4cfc55jukebox: library screens (songs, artists, albums, artist, album, search, favourites), compact player bar, /stream with Range, thumbnails, virtual list vendored, ui gate and real-library checkmre2a4cfc55/plugins/http1/http1.zig

155.6 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 GLOBAL engine per plugin (mirrors the SSE registry): a single reader
  310. // thread epolls all 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 `ws_mutex`.
  352. fn wsQueue(ev: WsEvent) !void {
  353. var e = ev;
  354. e.stamp = api.stamp();
  355. try ws_event_queue.append(allocator, e);
  356. }
  357. /// `head_stamp_fn` of the server's event source: when its next event was queued.
  358. fn wsEventsHeadStamp(_: ?*anyopaque) callconv(.c) u64 {
  359. mutexLock(&ws_mutex);
  360. defer mutexUnlock(&ws_mutex);
  361. return if (ws_event_queue.items.len == 0) api.STAMP_NONE else ws_event_queue.items[0].stamp;
  362. }
  363. const WsClient = struct {
  364. id: u32,
  365. fd: i32,
  366. decoder: ws.Decoder,
  367. closing: bool = false, // server sent close, awaiting peer echo
  368. // liveness (mission 091): when this socket last produced a frame, and when
  369. // the sweep's ping went out (0 = none outstanding). A TCP connection whose
  370. // peer vanished without a FIN stays writable indefinitely, so "still open"
  371. // is not evidence of a live peer — the pong is.
  372. last_seen_ms: i64 = 0,
  373. ping_at_ms: i64 = 0,
  374. };
  375. var ws_mutex: PthreadMutex = c.PTHREAD_MUTEX_INITIALIZER;
  376. var ws_clients: std.ArrayListUnmanaged(*WsClient) = .empty;
  377. var ws_event_queue: std.ArrayListUnmanaged(WsEvent) = .empty;
  378. var ws_epoll_fd: i32 = -1;
  379. var ws_wake_fd: i32 = -1;
  380. /// THE EVENT LOOP'S BELL for the WS event queue (mission 256), and a different fd
  381. /// from `ws_wake_fd` above — that one wakes the reader THREAD's own epoll, this
  382. /// one wakes the interpreter loop. Without it an app that turns sockets on has a
  383. /// source with no fd, and ONE such source puts the whole loop back on the 1ms
  384. /// poll (loop_wait.Waiter.observe) — so the server would busy-poll for as long as
  385. /// WebSockets were enabled.
  386. var ws_loop_wake_fd: i32 = -1;
  387. var ws_thread: ?std.Thread = null;
  388. var ws_running = std.atomic.Value(bool).init(false);
  389. var ws_enabled = std.atomic.Value(bool).init(false);
  390. var ws_next_id: u32 = 1;
  391. // --- liveness sweep (mission 091) ----------------------------------------
  392. // The reader thread already wakes every 500ms (the epoll timeout), so the sweep
  393. // costs no timer and no new thread: on every tick it pings sockets that have
  394. // gone quiet and drops the ones whose pong is overdue. The drop enqueues the
  395. // ordinary `close` event, so every consumer above (hl:web's subscription
  396. // registry included) prunes through the path it already had — nothing upstream
  397. // learns a new concept, and nothing at the hl level needs a timer.
  398. //
  399. // Operator knobs, read once at engine start; the defaults are production
  400. // values, the tests shrink them.
  401. const WS_PING_MS_DEFAULT: i64 = 15000; // quiet this long -> ask
  402. const WS_PONG_MS_DEFAULT: i64 = 10000; // no answer in this long -> gone
  403. var ws_ping_ms: i64 = WS_PING_MS_DEFAULT;
  404. var ws_pong_ms: i64 = WS_PONG_MS_DEFAULT;
  405. /// MONOTONIC milliseconds — a timeout measured against the wall clock would fire
  406. /// early or never after an NTP step.
  407. fn wsNowMs() i64 {
  408. var ts: linux.timespec = undefined;
  409. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  410. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  411. }
  412. fn wsEnvMs(name: [:0]const u8, fallback: i64) i64 {
  413. const raw = std.mem.span(std.c.getenv(name) orelse return fallback);
  414. const n = std.fmt.parseInt(i64, std.mem.trim(u8, raw, " \t"), 10) catch return fallback;
  415. if (n <= 0) return fallback;
  416. return n;
  417. }
  418. const EAGAIN_ERR: isize = 11;
  419. const EINTR_ERR: isize = 4;
  420. /// WriteFn callback over a raw fd (context = fd stuffed into the pointer).
  421. /// Non-blocking socket: bounded EAGAIN retries, then give up (caller drops).
  422. fn wsFdWrite(ctx: ?*anyopaque, data: []const u8) bool {
  423. const fd: i32 = @intCast(@intFromPtr(ctx));
  424. var written: usize = 0;
  425. var retries: u32 = 0;
  426. while (written < data.len) {
  427. const rc = linux.sendto(fd, data[written..].ptr, data.len - written, MSG_NOSIGNAL, null, 0);
  428. const n: isize = @bitCast(rc);
  429. if (n > 0) {
  430. written += @intCast(n);
  431. retries = 0;
  432. continue;
  433. }
  434. const e = -n;
  435. if (e == EAGAIN_ERR) {
  436. retries += 1;
  437. if (retries > 100) return false; // ~100ms of backpressure → drop
  438. const req = linux.timespec{ .sec = 0, .nsec = 1_000_000 }; // 1ms
  439. _ = linux.nanosleep(&req, null);
  440. continue;
  441. }
  442. if (e == EINTR_ERR) continue;
  443. return false;
  444. }
  445. return true;
  446. }
  447. fn wsFdCtx(fd: i32) ?*anyopaque {
  448. return @ptrFromInt(@as(usize, @intCast(fd)));
  449. }
  450. /// Start the reader thread + epoll instance. Idempotent. Called from the
  451. /// interpreter thread (hl_http1_ws_events); also flips ws_enabled so the I/O
  452. /// workers start honoring Upgrade requests.
  453. fn wsEnsureStarted() bool {
  454. mutexLock(&ws_mutex);
  455. defer mutexUnlock(&ws_mutex);
  456. if (ws_running.load(.acquire)) return true;
  457. ws_ping_ms = wsEnvMs("HL_WS_PING_MS", WS_PING_MS_DEFAULT);
  458. ws_pong_ms = wsEnvMs("HL_WS_PONG_TIMEOUT_MS", WS_PONG_MS_DEFAULT);
  459. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  460. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  461. if (ep < 0) return false;
  462. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  463. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  464. if (ef < 0) {
  465. _ = linux.close(ep);
  466. return false;
  467. }
  468. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  469. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  470. ws_epoll_fd = ep;
  471. ws_wake_fd = ef;
  472. if (ws_loop_wake_fd < 0) ws_loop_wake_fd = http.makeWakeFd(); // mission 256
  473. ws_running.store(true, .release);
  474. ws_thread = std.Thread.spawn(.{}, wsReaderLoop, .{}) catch {
  475. ws_running.store(false, .release);
  476. _ = linux.close(ep);
  477. _ = linux.close(ef);
  478. ws_epoll_fd = -1;
  479. ws_wake_fd = -1;
  480. return false;
  481. };
  482. ws_enabled.store(true, .release);
  483. return true;
  484. }
  485. fn wsWake() void {
  486. if (ws_wake_fd >= 0) {
  487. const one: u64 = 1;
  488. _ = linux.write(ws_wake_fd, @ptrCast(&one), @sizeOf(u64));
  489. }
  490. }
  491. /// The upgrade's headers as `name: value` lines joined by `\n` (ticket #105) — one
  492. /// allocation the connect event carries; a parsed header holds no `\n`. Null when
  493. /// there are none or the allocation fails (the connection still opens).
  494. fn joinHeaders(items: []const HeaderPair) ?[]u8 {
  495. var len: usize = 0;
  496. for (items) |hdr| len += hdr.key.len + 2 + hdr.value.len + 1;
  497. if (len == 0) return null;
  498. const out = allocator.alloc(u8, len - 1) catch return null;
  499. var at: usize = 0;
  500. for (items, 0..) |hdr, i| {
  501. if (i > 0) {
  502. out[at] = '\n';
  503. at += 1;
  504. }
  505. @memcpy(out[at .. at + hdr.key.len], hdr.key);
  506. at += hdr.key.len;
  507. @memcpy(out[at .. at + 2], ": ");
  508. at += 2;
  509. @memcpy(out[at .. at + hdr.value.len], hdr.value);
  510. at += hdr.value.len;
  511. }
  512. return out;
  513. }
  514. /// Hand an upgraded socket to the engine. Called from an I/O worker thread
  515. /// right after the 101 was written. `leftover` = bytes the client sent after
  516. /// the handshake that were already consumed into the header buffer. `cookie` is
  517. /// the handshake's `Cookie` header (mission 093) — copied here, because the
  518. /// parsed request is freed the moment this returns. `host` is its `Host` header
  519. /// (ticket #74), copied for the same reason. `headers` is all of them as
  520. /// `name: value` lines (ticket #105), already an allocated copy: owned from here.
  521. /// `handshake` is the 101 response. It is written HERE, under `ws_mutex` and after the
  522. /// `connect` event is queued (ticket: 039_http1_ws_client, 2026-10-02): written before
  523. /// registering, an in-process client could read it and queue its `open` ahead of the
  524. /// server's `connect`, and a `peer.send` from `on connect` could not overtake it either.
  525. /// The peer address of a connected socket as "a.b.c.d" (IPv4 listener), allocated; null
  526. /// when the kernel cannot say.
  527. fn peerIpText(fd: i32) ?[]u8 {
  528. var peer: linux.sockaddr.in = undefined;
  529. var peer_len: u32 = @sizeOf(linux.sockaddr.in);
  530. const rc = linux.getpeername(fd, @ptrCast(&peer), &peer_len);
  531. if (@as(isize, @bitCast(rc)) != 0 or peer.family != linux.AF.INET) return null;
  532. const a: [4]u8 = @bitCast(peer.addr);
  533. return std.fmt.allocPrint(allocator, "{d}.{d}.{d}.{d}", .{ a[0], a[1], a[2], a[3] }) catch null;
  534. }
  535. fn wsRegisterClient(fd: i32, handshake: []const u8, leftover: []const u8, cookie: []const u8, host: []const u8, headers: ?[]u8) void {
  536. // Non-blocking for the reader loop
  537. const flags_rc = linux.fcntl(fd, linux.F.GETFL, @as(usize, 0));
  538. const flags_i: isize = @bitCast(flags_rc);
  539. if (flags_i >= 0) {
  540. var oflags: linux.O = @bitCast(@as(u32, @truncate(flags_rc)));
  541. oflags.NONBLOCK = true;
  542. _ = linux.fcntl(fd, linux.F.SETFL, @as(usize, @as(u32, @bitCast(oflags))));
  543. }
  544. mutexLock(&ws_mutex);
  545. const client = allocator.create(WsClient) catch {
  546. mutexUnlock(&ws_mutex);
  547. if (headers) |hd| allocator.free(hd);
  548. _ = linux.close(fd);
  549. return;
  550. };
  551. client.* = .{
  552. .id = ws_next_id,
  553. .fd = fd,
  554. .decoder = ws.Decoder.init(allocator),
  555. .last_seen_ms = wsNowMs(),
  556. };
  557. ws_next_id += 1;
  558. ws_clients.append(allocator, client) catch {
  559. allocator.destroy(client);
  560. mutexUnlock(&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(.{ .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(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  578. wsRemoveLocked(ws_clients.items.len - 1);
  579. mutexUnlock(&ws_mutex);
  580. return;
  581. }
  582. mutexUnlock(&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(ws_epoll_fd, linux.EPOLL.CTL_ADD, fd, &ev);
  587. if (leftover.len > 0) wsWake(); // 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(ws_loop_wake_fd);
  591. }
  592. fn wsFindByFdLocked(fd: i32) ?usize {
  593. for (ws_clients.items, 0..) |cl, i| {
  594. if (cl.fd == fd) return i;
  595. }
  596. return null;
  597. }
  598. fn wsFindByIdLocked(id: u32) ?usize {
  599. for (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(idx: usize) void {
  606. const client = ws_clients.items[idx];
  607. _ = linux.epoll_ctl(ws_epoll_fd, linux.EPOLL.CTL_DEL, client.fd, null);
  608. _ = linux.close(client.fd);
  609. client.decoder.deinit();
  610. _ = 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(idx: usize) bool {
  616. const client = ws_clients.items[idx];
  617. while (true) {
  618. const maybe_ev = client.decoder.next() catch {
  619. // OOM mid-decode — drop the connection
  620. wsQueue(.{ .kind = .close, .id = client.id, .code = 1011 }) catch {};
  621. wsRemoveLocked(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(.{ .kind = .message, .id = client.id, .data = p }) catch allocator.free(p),
  631. .binary => |p| wsQueue(.{ .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(.{ .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(.{ .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(idx);
  651. return true;
  652. },
  653. .protocol_error => |code| {
  654. wsQueue(.{ .kind = .close, .id = client.id, .code = code }) catch {};
  655. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), code, "");
  656. wsRemoveLocked(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(idx: usize) bool {
  665. const client = 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(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  677. wsRemoveLocked(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(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  684. wsRemoveLocked(idx);
  685. return true;
  686. }
  687. return wsDrainDecoderLocked(idx);
  688. }
  689. /// One liveness pass over every upgraded socket. Quiet for longer than
  690. /// 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 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() void {
  697. const now = wsNowMs();
  698. mutexLock(&ws_mutex);
  699. defer mutexUnlock(&ws_mutex);
  700. var i: usize = 0;
  701. while (i < ws_clients.items.len) {
  702. const client = ws_clients.items[i];
  703. if (client.ping_at_ms != 0) {
  704. if (now - client.ping_at_ms > ws_pong_ms) {
  705. wsQueue(.{
  706. .kind = .close,
  707. .id = client.id,
  708. .code = ws.CLOSE_GOING_AWAY,
  709. }) catch {};
  710. wsRemoveLocked(i);
  711. continue;
  712. }
  713. } else if (now - client.last_seen_ms > 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(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  719. wsRemoveLocked(i);
  720. continue;
  721. }
  722. }
  723. i += 1;
  724. }
  725. }
  726. fn wsReaderLoop() void {
  727. var events: [64]linux.epoll_event = undefined;
  728. while (ws_running.load(.acquire)) {
  729. // RING THE EVENT LOOP'S BELL AT THE END OF EVERY ITERATION (mission 256),
  730. // unconditionally and without taking `ws_mutex`. Fifteen places in this
  731. // file push onto `ws_event_queue`; a bell is coalesced and a spurious one
  732. // is harmless (loop_wait.zig: "only a signal that is never sent at all
  733. // could ever be a bug"), so one ring per pass covers all of them and can
  734. // never deadlock against a path that still holds the lock. The idle cost
  735. // is two empty loop rounds a second — this epoll has a 500ms timeout.
  736. defer http.ringWake(ws_loop_wake_fd);
  737. const n_rc = linux.epoll_wait(ws_epoll_fd, &events, events.len, 500);
  738. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  739. // The 500ms epoll timeout IS the sweep's clock: an idle loop still ticks,
  740. // and a busy one sweeps just as often because the check is on wall time.
  741. if (n <= 0) {
  742. wsSweep();
  743. continue;
  744. }
  745. for (events[0..@intCast(n)]) |ev| {
  746. if (ev.data.fd == ws_wake_fd) {
  747. var drain: u64 = 0;
  748. _ = linux.read(ws_wake_fd, @ptrCast(&drain), @sizeOf(u64));
  749. if (!ws_running.load(.acquire)) return;
  750. // Drain decoder-buffered data (e.g. handshake leftover)
  751. mutexLock(&ws_mutex);
  752. var i: usize = 0;
  753. while (i < ws_clients.items.len) {
  754. if (!wsDrainDecoderLocked(i)) i += 1;
  755. }
  756. mutexUnlock(&ws_mutex);
  757. continue;
  758. }
  759. mutexLock(&ws_mutex);
  760. if (wsFindByFdLocked(ev.data.fd)) |idx| {
  761. _ = wsServiceClientLocked(idx);
  762. }
  763. mutexUnlock(&ws_mutex);
  764. }
  765. wsSweep();
  766. }
  767. }
  768. /// Stop the engine: join the reader thread, close all sockets, free queues.
  769. /// Runs at interpreter teardown via the events-iterator deinit — BEFORE the
  770. /// runtime dlcloses this .so, so the thread never outlives its code.
  771. fn wsShutdown() void {
  772. if (!ws_running.swap(false, .acq_rel)) return;
  773. wsWake();
  774. if (ws_thread) |t| {
  775. t.join();
  776. ws_thread = null;
  777. }
  778. mutexLock(&ws_mutex);
  779. for (ws_clients.items) |client| {
  780. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), ws.CLOSE_GOING_AWAY, "");
  781. _ = linux.close(client.fd);
  782. client.decoder.deinit();
  783. allocator.destroy(client);
  784. }
  785. ws_clients.deinit(allocator);
  786. ws_clients = .empty;
  787. for (ws_event_queue.items) |*ev| {
  788. if (ev.data) |d| allocator.free(d);
  789. if (ev.cookie) |ck| allocator.free(ck);
  790. if (ev.host) |hc| allocator.free(hc);
  791. if (ev.headers) |hd| allocator.free(hd);
  792. }
  793. ws_event_queue.deinit(allocator);
  794. ws_event_queue = .empty;
  795. mutexUnlock(&ws_mutex);
  796. if (ws_epoll_fd >= 0) _ = linux.close(ws_epoll_fd);
  797. if (ws_wake_fd >= 0) _ = linux.close(ws_wake_fd);
  798. ws_epoll_fd = -1;
  799. ws_wake_fd = -1;
  800. // `ws_loop_wake_fd` is deliberately NOT closed: the event loop may still hold
  801. // it in its epoll set, and a closed fd number gets REUSED — the loop would
  802. // then be watching whatever opened next. One eventfd per process, kept for
  803. // the process's life and reused if the engine restarts (mission 256).
  804. ws_enabled.store(false, .release);
  805. }
  806. // --- Interpreter-facing exports ------------------------------------------
  807. const ws_kind_names = [_][]const u8{ "connect", "message", "close", "pong" };
  808. fn wsEventObjDeinit(obj: *HlObject) callconv(.c) void {
  809. // fields[2] is "data", fields[5] "cookie", fields[6] "host" and fields[7]
  810. // "headers" — allocated iff non-empty (empty = the static "").
  811. const s = obj.fields[2].value.data.string;
  812. if (s.len > 0) allocator.free(s.ptr[0..s.len]);
  813. const ck = obj.fields[5].value.data.string;
  814. if (ck.len > 0) allocator.free(ck.ptr[0..ck.len]);
  815. const hs = obj.fields[6].value.data.string;
  816. if (hs.len > 0) allocator.free(hs.ptr[0..hs.len]);
  817. const hd = obj.fields[7].value.data.string;
  818. if (hd.len > 0) allocator.free(hd.ptr[0..hd.len]);
  819. const ipv = obj.fields[8].value.data.string; // "ip", allocated iff non-empty
  820. if (ipv.len > 0) allocator.free(ipv.ptr[0..ipv.len]);
  821. allocator.free(obj.fields[0..obj.field_count]);
  822. allocator.destroy(obj);
  823. }
  824. /// try_next over the WS event queue → { kind, id, data, binary, code, cookie, host, headers }
  825. /// or null. `cookie` is the handshake's Cookie header, `host` its Host header and
  826. /// `headers` all of its headers as `name: value` lines, each non-empty only on
  827. /// `connect` (mission 093, tickets #74 and #105).
  828. fn wsEventsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  829. _ = ctx;
  830. mutexLock(&ws_mutex);
  831. if (ws_event_queue.items.len == 0) {
  832. mutexUnlock(&ws_mutex);
  833. return api.makeNull();
  834. }
  835. const ev = ws_event_queue.orderedRemove(0);
  836. mutexUnlock(&ws_mutex);
  837. const fields = allocator.alloc(HlField, 10) catch {
  838. if (ev.ip) |ic| allocator.free(ic);
  839. if (ev.data) |d| allocator.free(d);
  840. if (ev.cookie) |ck| allocator.free(ck);
  841. if (ev.host) |hc| allocator.free(hc);
  842. if (ev.headers) |hd| allocator.free(hd);
  843. return api.makeNull();
  844. };
  845. const data_slice: []const u8 = if (ev.data) |d| d else "";
  846. const cookie_slice: []const u8 = if (ev.cookie) |ck| ck else "";
  847. const host_slice: []const u8 = if (ev.host) |hc| hc else "";
  848. const headers_slice: []const u8 = if (ev.headers) |hd| hd else "";
  849. fields[0] = .{ .key = http.hlStr("kind"), .value = api.makeString(ws_kind_names[@intFromEnum(ev.kind)]) };
  850. fields[1] = .{ .key = http.hlStr("id"), .value = api.makeNumber(@floatFromInt(ev.id)) };
  851. fields[2] = .{ .key = http.hlStr("data"), .value = api.makeString(data_slice) };
  852. fields[3] = .{ .key = http.hlStr("binary"), .value = api.makeBool(ev.is_binary) };
  853. fields[4] = .{ .key = http.hlStr("code"), .value = api.makeNumber(@floatFromInt(ev.code)) };
  854. fields[5] = .{ .key = http.hlStr("cookie"), .value = api.makeString(cookie_slice) };
  855. fields[6] = .{ .key = http.hlStr("host"), .value = api.makeString(host_slice) };
  856. fields[7] = .{ .key = http.hlStr("headers"), .value = api.makeString(headers_slice) };
  857. fields[8] = .{ .key = http.hlStr("ip"), .value = api.makeString(if (ev.ip) |ic| ic else "") };
  858. fields[9] = .{ .key = http.hlStr("secure"), .value = api.makeBool(ev.secure) };
  859. const obj = allocator.create(HlObject) catch {
  860. if (ev.data) |d| allocator.free(d);
  861. if (ev.cookie) |ck| allocator.free(ck);
  862. if (ev.host) |hc| allocator.free(hc);
  863. if (ev.headers) |hd| allocator.free(hd);
  864. if (ev.ip) |ic| allocator.free(ic);
  865. allocator.free(fields);
  866. return api.makeNull();
  867. };
  868. obj.* = .{ .fields = fields.ptr, .field_count = 10, .deinit_fn = &wsEventObjDeinit };
  869. return api.makeObject(obj);
  870. }
  871. fn wsEventsIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  872. _ = ctx;
  873. wsShutdown();
  874. }
  875. /// __native("http1.ws_events") → event iterator; starting it enables WS
  876. /// upgrades on all plain-HTTP hl:http1 servers in this process.
  877. export fn hl_http1_ws_events(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  878. _ = argc;
  879. _ = argv;
  880. if (!wsEnsureStarted()) return api.makeNull();
  881. const iter = allocator.create(HlIterator) catch return api.makeNull();
  882. iter.* = .{
  883. .context = null,
  884. .next_fn = &wsEventsTryNext, // non-blocking either way — event loop only
  885. .deinit_fn = &wsEventsIterDeinit,
  886. .try_next_fn = &wsEventsTryNext,
  887. .wake_fd = ws_loop_wake_fd, // mission 256 — set by wsEnsureStarted above
  888. .head_stamp_fn = &wsEventsHeadStamp,
  889. };
  890. return api.makeIterator(iter);
  891. }
  892. // --- cookie-grade random (mission 093) ------------------------------------
  893. // A session id is the ONLY thing standing between a stranger and someone else's
  894. // session, so it may not come from a seeded PRNG: `hl:math`'s random() is a
  895. // clock-seeded xoshiro, and a few of its outputs reveal its state, which would
  896. // make every other session's id derivable from one's own. This reads the
  897. // kernel's CSPRNG directly. It lives in hl:http1 because the session cookie is
  898. // an HTTP artifact and this plugin is the one that parses and sets it; there is
  899. // no other CSPRNG at the hl: level yet (named as a gap in mission 093's report).
  900. var token_buf: [128]u8 = undefined;
  901. /// __native("http1.random_token", n) → n lowercase hex chars (default 32, max 128)
  902. export fn hl_http1_random_token(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  903. var want: usize = 32;
  904. if (argc >= 1 and argv[0].type == .hl_number) {
  905. const n = argv[0].data.number;
  906. if (n >= 1 and n <= 128) want = @intFromFloat(n);
  907. }
  908. var raw: [64]u8 = undefined;
  909. const need = (want + 1) / 2;
  910. if (linux.getrandom(&raw, need, 0) != need) return api.makeNull();
  911. const hex = "0123456789abcdef";
  912. var i: usize = 0;
  913. while (i < want) : (i += 1) {
  914. const byte = raw[i / 2];
  915. const nib: u8 = if (i % 2 == 0) (byte >> 4) else (byte & 0x0f);
  916. token_buf[i] = hex[nib];
  917. }
  918. return api.makeString(token_buf[0..want]);
  919. }
  920. /// __native("http1.ws_send", id, text[, binaryFlag]) → 1 sent / 0 gone
  921. export fn hl_http1_ws_send(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  922. if (argc < 2 or argv[0].type != .hl_number or argv[1].type != .hl_string) return api.makeNumber(0);
  923. const id: u32 = @intFromFloat(argv[0].data.number);
  924. const text = argv[1].data.string.ptr[0..argv[1].data.string.len];
  925. const opcode: ws.Opcode = if (argc >= 3 and argv[2].type == .hl_bool and argv[2].data.boolean) .binary else .text;
  926. mutexLock(&ws_mutex);
  927. defer mutexUnlock(&ws_mutex);
  928. const idx = wsFindByIdLocked(id) orelse return api.makeNumber(0);
  929. const client = ws_clients.items[idx];
  930. if (!ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), opcode, text)) {
  931. wsQueue(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  932. wsRemoveLocked(idx);
  933. return api.makeNumber(0);
  934. }
  935. return api.makeNumber(1);
  936. }
  937. /// __native("http1.ws_broadcast", text) → number of clients written
  938. export fn hl_http1_ws_broadcast(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  939. if (argc < 1 or argv[0].type != .hl_string) return api.makeNumber(0);
  940. const text = argv[0].data.string.ptr[0..argv[0].data.string.len];
  941. mutexLock(&ws_mutex);
  942. defer mutexUnlock(&ws_mutex);
  943. var count: usize = 0;
  944. var i: usize = 0;
  945. while (i < ws_clients.items.len) {
  946. const client = ws_clients.items[i];
  947. if (ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .text, text)) {
  948. count += 1;
  949. i += 1;
  950. } else {
  951. wsQueue(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  952. wsRemoveLocked(i);
  953. }
  954. }
  955. return api.makeNumber(@floatFromInt(count));
  956. }
  957. /// __native("http1.ws_ping", id) → 1 sent / 0 gone
  958. export fn hl_http1_ws_ping(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  959. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  960. const id: u32 = @intFromFloat(argv[0].data.number);
  961. mutexLock(&ws_mutex);
  962. defer mutexUnlock(&ws_mutex);
  963. const idx = wsFindByIdLocked(id) orelse return api.makeNumber(0);
  964. const client = ws_clients.items[idx];
  965. if (!ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .ping, "")) {
  966. wsRemoveLocked(idx);
  967. return api.makeNumber(0);
  968. }
  969. return api.makeNumber(1);
  970. }
  971. /// __native("http1.ws_close", id[, code]) → 1 initiated / 0 gone.
  972. /// Sends the close frame and waits for the peer echo (reader completes it).
  973. export fn hl_http1_ws_close(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  974. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  975. const id: u32 = @intFromFloat(argv[0].data.number);
  976. const code: u16 = if (argc >= 2 and argv[1].type == .hl_number) @intFromFloat(argv[1].data.number) else ws.CLOSE_NORMAL;
  977. mutexLock(&ws_mutex);
  978. defer mutexUnlock(&ws_mutex);
  979. const idx = wsFindByIdLocked(id) orelse return api.makeNumber(0);
  980. const client = ws_clients.items[idx];
  981. if (!ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), code, "")) {
  982. wsQueue(.{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  983. wsRemoveLocked(idx);
  984. return api.makeNumber(0);
  985. }
  986. client.closing = true;
  987. return api.makeNumber(1);
  988. }
  989. // =========================================================================
  990. // TLS context — OpenSSL via dlopen (optional, no compile-time dep)
  991. // =========================================================================
  992. const c_dlfcn = @cImport({
  993. @cInclude("dlfcn.h");
  994. });
  995. const SSL_CTX = opaque {};
  996. const SSL = opaque {};
  997. const SSL_METHOD = opaque {};
  998. // OpenSSL function pointer types
  999. const SSL_library_init_fn = *const fn () callconv(.c) c_int;
  1000. const SSL_load_error_strings_fn = *const fn () callconv(.c) void;
  1001. const TLS_server_method_fn = *const fn () callconv(.c) ?*const SSL_METHOD;
  1002. const SSL_CTX_new_fn = *const fn (?*const SSL_METHOD) callconv(.c) ?*SSL_CTX;
  1003. const SSL_CTX_free_fn = *const fn (?*SSL_CTX) callconv(.c) void;
  1004. const SSL_CTX_use_certificate_chain_file_fn = *const fn (?*SSL_CTX, [*:0]const u8) callconv(.c) c_int;
  1005. const SSL_CTX_use_PrivateKey_file_fn = *const fn (?*SSL_CTX, [*:0]const u8, c_int) callconv(.c) c_int;
  1006. const SSL_new_fn = *const fn (?*SSL_CTX) callconv(.c) ?*SSL;
  1007. const SSL_free_fn = *const fn (?*SSL) callconv(.c) void;
  1008. const SSL_set_fd_fn = *const fn (?*SSL, c_int) callconv(.c) c_int;
  1009. const SSL_accept_fn = *const fn (?*SSL) callconv(.c) c_int;
  1010. const SSL_read_fn = *const fn (?*SSL, [*]u8, c_int) callconv(.c) c_int;
  1011. const SSL_write_fn = *const fn (?*SSL, [*]const u8, c_int) callconv(.c) c_int;
  1012. const SSL_shutdown_fn = *const fn (?*SSL) callconv(.c) c_int;
  1013. const SSL_get_error_fn = *const fn (?*SSL, c_int) callconv(.c) c_int;
  1014. const OPENSSL_init_ssl_fn = *const fn (u64, ?*anyopaque) callconv(.c) c_int;
  1015. const SSL_FILETYPE_PEM: c_int = 1;
  1016. const TlsContext = struct {
  1017. ssl_ctx: ?*SSL_CTX = null,
  1018. lib_ssl: ?*anyopaque = null,
  1019. lib_crypto: ?*anyopaque = null,
  1020. // Function pointers
  1021. fn_ssl_ctx_new: ?SSL_CTX_new_fn = null,
  1022. fn_ssl_ctx_free: ?SSL_CTX_free_fn = null,
  1023. fn_ssl_ctx_use_cert: ?SSL_CTX_use_certificate_chain_file_fn = null,
  1024. fn_ssl_ctx_use_key: ?SSL_CTX_use_PrivateKey_file_fn = null,
  1025. fn_ssl_new: ?SSL_new_fn = null,
  1026. fn_ssl_free: ?SSL_free_fn = null,
  1027. fn_ssl_set_fd: ?SSL_set_fd_fn = null,
  1028. fn_ssl_accept: ?SSL_accept_fn = null,
  1029. fn_ssl_read: ?SSL_read_fn = null,
  1030. fn_ssl_write: ?SSL_write_fn = null,
  1031. fn_ssl_shutdown: ?SSL_shutdown_fn = null,
  1032. fn_ssl_get_error: ?SSL_get_error_fn = null,
  1033. fn loadSym(lib: ?*anyopaque, comptime T: type, name: [*:0]const u8) ?T {
  1034. const sym = c_dlfcn.dlsym(lib, name) orelse return null;
  1035. return @ptrCast(sym);
  1036. }
  1037. fn init(cert_path: []const u8, key_path: []const u8) ?TlsContext {
  1038. var ctx = TlsContext{};
  1039. // Try loading libssl and libcrypto
  1040. const ssl_paths = [_][*:0]const u8{ "libssl.so.3", "libssl.so.1.1", "libssl.so" };
  1041. const crypto_paths = [_][*:0]const u8{ "libcrypto.so.3", "libcrypto.so.1.1", "libcrypto.so" };
  1042. for (ssl_paths) |path| {
  1043. ctx.lib_ssl = c_dlfcn.dlopen(path, c_dlfcn.RTLD_NOW | c_dlfcn.RTLD_LOCAL);
  1044. if (ctx.lib_ssl != null) break;
  1045. }
  1046. if (ctx.lib_ssl == null) {
  1047. logMsg("http1: TLS: failed to load libssl.so\n");
  1048. return null;
  1049. }
  1050. for (crypto_paths) |path| {
  1051. ctx.lib_crypto = c_dlfcn.dlopen(path, c_dlfcn.RTLD_NOW | c_dlfcn.RTLD_LOCAL);
  1052. if (ctx.lib_crypto != null) break;
  1053. }
  1054. if (ctx.lib_crypto == null) {
  1055. logMsg("http1: TLS: failed to load libcrypto.so\n");
  1056. _ = c_dlfcn.dlclose(ctx.lib_ssl);
  1057. return null;
  1058. }
  1059. // Load function pointers
  1060. // Try OPENSSL_init_ssl first (OpenSSL 1.1+), fall back to SSL_library_init
  1061. if (loadSym(ctx.lib_ssl, OPENSSL_init_ssl_fn, "OPENSSL_init_ssl")) |init_fn| {
  1062. _ = init_fn(0, null);
  1063. } else if (loadSym(ctx.lib_ssl, SSL_library_init_fn, "SSL_library_init")) |lib_init| {
  1064. _ = lib_init();
  1065. if (loadSym(ctx.lib_ssl, SSL_load_error_strings_fn, "SSL_load_error_strings")) |load_err| {
  1066. load_err();
  1067. }
  1068. }
  1069. const method_fn = loadSym(ctx.lib_ssl, TLS_server_method_fn, "TLS_server_method") orelse {
  1070. logMsg("http1: TLS: TLS_server_method not found\n");
  1071. ctx.deinit();
  1072. return null;
  1073. };
  1074. ctx.fn_ssl_ctx_new = loadSym(ctx.lib_ssl, SSL_CTX_new_fn, "SSL_CTX_new");
  1075. ctx.fn_ssl_ctx_free = loadSym(ctx.lib_ssl, SSL_CTX_free_fn, "SSL_CTX_free");
  1076. ctx.fn_ssl_ctx_use_cert = loadSym(ctx.lib_ssl, SSL_CTX_use_certificate_chain_file_fn, "SSL_CTX_use_certificate_chain_file");
  1077. ctx.fn_ssl_ctx_use_key = loadSym(ctx.lib_ssl, SSL_CTX_use_PrivateKey_file_fn, "SSL_CTX_use_PrivateKey_file");
  1078. ctx.fn_ssl_new = loadSym(ctx.lib_ssl, SSL_new_fn, "SSL_new");
  1079. ctx.fn_ssl_free = loadSym(ctx.lib_ssl, SSL_free_fn, "SSL_free");
  1080. ctx.fn_ssl_set_fd = loadSym(ctx.lib_ssl, SSL_set_fd_fn, "SSL_set_fd");
  1081. ctx.fn_ssl_accept = loadSym(ctx.lib_ssl, SSL_accept_fn, "SSL_accept");
  1082. ctx.fn_ssl_read = loadSym(ctx.lib_ssl, SSL_read_fn, "SSL_read");
  1083. ctx.fn_ssl_write = loadSym(ctx.lib_ssl, SSL_write_fn, "SSL_write");
  1084. ctx.fn_ssl_shutdown = loadSym(ctx.lib_ssl, SSL_shutdown_fn, "SSL_shutdown");
  1085. ctx.fn_ssl_get_error = loadSym(ctx.lib_ssl, SSL_get_error_fn, "SSL_get_error");
  1086. if (ctx.fn_ssl_ctx_new == null or ctx.fn_ssl_new == null or
  1087. ctx.fn_ssl_set_fd == null or ctx.fn_ssl_accept == null or
  1088. ctx.fn_ssl_read == null or ctx.fn_ssl_write == null)
  1089. {
  1090. logMsg("http1: TLS: missing required SSL symbols\n");
  1091. ctx.deinit();
  1092. return null;
  1093. }
  1094. // Create SSL_CTX
  1095. const method = method_fn();
  1096. ctx.ssl_ctx = ctx.fn_ssl_ctx_new.?(method);
  1097. if (ctx.ssl_ctx == null) {
  1098. logMsg("http1: TLS: SSL_CTX_new failed\n");
  1099. ctx.deinit();
  1100. return null;
  1101. }
  1102. // Load cert and key
  1103. const cert_z = allocator.dupeZ(u8, cert_path) catch {
  1104. ctx.deinit();
  1105. return null;
  1106. };
  1107. defer allocator.free(cert_z);
  1108. const key_z = allocator.dupeZ(u8, key_path) catch {
  1109. ctx.deinit();
  1110. return null;
  1111. };
  1112. defer allocator.free(key_z);
  1113. if (ctx.fn_ssl_ctx_use_cert) |use_cert| {
  1114. if (use_cert(ctx.ssl_ctx, cert_z.ptr) != 1) {
  1115. logFmt("http1: TLS: failed to load certificate: {s}\n", .{cert_path});
  1116. ctx.deinit();
  1117. return null;
  1118. }
  1119. }
  1120. if (ctx.fn_ssl_ctx_use_key) |use_key| {
  1121. if (use_key(ctx.ssl_ctx, key_z.ptr, SSL_FILETYPE_PEM) != 1) {
  1122. logFmt("http1: TLS: failed to load private key: {s}\n", .{key_path});
  1123. ctx.deinit();
  1124. return null;
  1125. }
  1126. }
  1127. logMsg("http1: TLS initialized\n");
  1128. return ctx;
  1129. }
  1130. fn wrapConnection(self: *const TlsContext, fd: i32) ?*SSL {
  1131. const ssl = self.fn_ssl_new.?(self.ssl_ctx);
  1132. if (ssl == null) return null;
  1133. _ = self.fn_ssl_set_fd.?(ssl, fd);
  1134. const ret = self.fn_ssl_accept.?(ssl);
  1135. if (ret != 1) {
  1136. self.fn_ssl_free.?(ssl);
  1137. return null;
  1138. }
  1139. return ssl;
  1140. }
  1141. fn sslRead(self: *const TlsContext, ssl: *SSL, buf: []u8) isize {
  1142. const ret = self.fn_ssl_read.?(ssl, buf.ptr, @intCast(@min(buf.len, std.math.maxInt(c_int))));
  1143. if (ret <= 0) return 0;
  1144. return @intCast(ret);
  1145. }
  1146. fn sslWrite(self: *const TlsContext, ssl: *SSL, data: []const u8) isize {
  1147. var written: usize = 0;
  1148. while (written < data.len) {
  1149. const chunk_len: c_int = @intCast(@min(data.len - written, std.math.maxInt(c_int)));
  1150. const ret = self.fn_ssl_write.?(ssl, data[written..].ptr, chunk_len);
  1151. if (ret <= 0) return @intCast(written);
  1152. written += @intCast(ret);
  1153. }
  1154. return @intCast(written);
  1155. }
  1156. fn sslShutdown(self: *const TlsContext, ssl: *SSL) void {
  1157. _ = self.fn_ssl_shutdown.?(ssl);
  1158. self.fn_ssl_free.?(ssl);
  1159. }
  1160. fn deinit(self: *TlsContext) void {
  1161. if (self.ssl_ctx != null) {
  1162. if (self.fn_ssl_ctx_free) |free_fn| {
  1163. free_fn(self.ssl_ctx);
  1164. }
  1165. self.ssl_ctx = null;
  1166. }
  1167. if (self.lib_ssl != null) {
  1168. _ = c_dlfcn.dlclose(self.lib_ssl);
  1169. self.lib_ssl = null;
  1170. }
  1171. if (self.lib_crypto != null) {
  1172. _ = c_dlfcn.dlclose(self.lib_crypto);
  1173. self.lib_crypto = null;
  1174. }
  1175. }
  1176. };
  1177. // =========================================================================
  1178. // MPSC Request Queue — thread-safe, blocks on dequeue
  1179. // =========================================================================
  1180. const ParsedRequest = struct {
  1181. method: []const u8,
  1182. path: []const u8, // URL-decoded
  1183. query_params: []http.QueryParam, // parsed key-value pairs
  1184. query_raw: []const u8, // raw query string
  1185. headers: std.ArrayListUnmanaged(HeaderPair),
  1186. body: []const u8,
  1187. client_fd: i32,
  1188. ssl: ?*SSL, // null if plain HTTP
  1189. keep_alive: bool,
  1190. };
  1191. const HeaderPair = struct {
  1192. key: []const u8,
  1193. value: []const u8,
  1194. };
  1195. const RequestQueue = struct {
  1196. queue: std.ArrayListUnmanaged(ParsedRequest),
  1197. mutex: PthreadMutex,
  1198. condvar: PthreadCond,
  1199. shutdown: bool,
  1200. /// THE EVENT LOOP'S BELL (mission 256). The condvar above wakes a `for (req of
  1201. /// server)` consumer blocked in `dequeue`; the interpreter's event loop is
  1202. /// NOT that consumer — it polls `tryDequeue` from a loop that also watches
  1203. /// every other source, so it cannot block on a condvar belonging to one of
  1204. /// them. An eventfd it can: `native/src/loop_wait.zig` epolls this fd, and an
  1205. /// idle server costs nothing instead of 1000 empty poll rounds a second.
  1206. loop_wake_fd: i32,
  1207. fn init() RequestQueue {
  1208. var self: RequestQueue = .{
  1209. .queue = .empty,
  1210. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1211. .condvar = c.PTHREAD_COND_INITIALIZER,
  1212. .shutdown = false,
  1213. .loop_wake_fd = http.makeWakeFd(),
  1214. };
  1215. mutexInit(&self.mutex);
  1216. condInit(&self.condvar);
  1217. return self;
  1218. }
  1219. fn enqueue(self: *RequestQueue, req: ParsedRequest) void {
  1220. mutexLock(&self.mutex);
  1221. defer mutexUnlock(&self.mutex);
  1222. self.queue.append(allocator, req) catch return;
  1223. condSignal(&self.condvar);
  1224. // Rung INSIDE the lock, so the fd's counter is already up by the time the
  1225. // request is visible to `tryDequeue`. A loop that is between its last poll
  1226. // and its next `epoll_wait` therefore finds the level raised and returns
  1227. // at once instead of sleeping on a queue that has work in it.
  1228. http.ringWake(self.loop_wake_fd);
  1229. }
  1230. fn dequeue(self: *RequestQueue) ?ParsedRequest {
  1231. mutexLock(&self.mutex);
  1232. defer mutexUnlock(&self.mutex);
  1233. while (self.queue.items.len == 0 and !self.shutdown) {
  1234. condWait(&self.condvar, &self.mutex);
  1235. }
  1236. if (self.shutdown and self.queue.items.len == 0) return null;
  1237. return self.queue.orderedRemove(0);
  1238. }
  1239. /// Non-blocking: returns null immediately if queue is empty
  1240. fn tryDequeue(self: *RequestQueue) ?ParsedRequest {
  1241. mutexLock(&self.mutex);
  1242. defer mutexUnlock(&self.mutex);
  1243. if (self.queue.items.len == 0) return null;
  1244. return self.queue.orderedRemove(0);
  1245. }
  1246. fn signalShutdown(self: *RequestQueue) void {
  1247. mutexLock(&self.mutex);
  1248. defer mutexUnlock(&self.mutex);
  1249. self.shutdown = true;
  1250. condBroadcast(&self.condvar);
  1251. // The event loop is told too — it is blocked on this fd and its `while`
  1252. // condition (has every source retired?) can only be re-read on the way out.
  1253. http.ringWake(self.loop_wake_fd);
  1254. }
  1255. fn deinit(self: *RequestQueue) void {
  1256. // Free any remaining queued requests
  1257. for (self.queue.items) |*req| {
  1258. freeRequest(req);
  1259. }
  1260. self.queue.deinit(allocator);
  1261. if (self.loop_wake_fd >= 0) {
  1262. _ = linux.close(self.loop_wake_fd);
  1263. self.loop_wake_fd = -1;
  1264. }
  1265. _ = c.pthread_cond_destroy(&self.condvar);
  1266. _ = c.pthread_mutex_destroy(&self.mutex);
  1267. }
  1268. };
  1269. fn freeRequest(req: *ParsedRequest) void {
  1270. allocator.free(req.method);
  1271. allocator.free(req.path);
  1272. allocator.free(req.query_raw);
  1273. for (req.query_params) |param| {
  1274. allocator.free(param.key);
  1275. allocator.free(param.value);
  1276. }
  1277. allocator.free(req.query_params);
  1278. for (req.headers.items) |hdr| {
  1279. allocator.free(hdr.key);
  1280. allocator.free(hdr.value);
  1281. }
  1282. req.headers.deinit(allocator);
  1283. if (req.body.len > 0) allocator.free(req.body);
  1284. }
  1285. // =========================================================================
  1286. // Connection — per-connection state tracked by I/O workers
  1287. // =========================================================================
  1288. const Connection = struct {
  1289. fd: i32,
  1290. ssl: ?*SSL,
  1291. keep_alive: bool,
  1292. request_count: u32,
  1293. max_requests: u32,
  1294. fn read(self: *const Connection, tls: ?*const TlsContext, buf: []u8) usize {
  1295. if (self.ssl) |ssl_ptr| {
  1296. if (tls) |t| {
  1297. const n = t.sslRead(ssl_ptr, buf);
  1298. if (n <= 0) return 0;
  1299. return @intCast(n);
  1300. }
  1301. return 0;
  1302. }
  1303. return sysRead(self.fd, buf);
  1304. }
  1305. fn write(self: *const Connection, tls: ?*const TlsContext, data: []const u8) void {
  1306. if (self.ssl) |ssl_ptr| {
  1307. if (tls) |t| {
  1308. _ = t.sslWrite(ssl_ptr, data);
  1309. return;
  1310. }
  1311. }
  1312. sysWriteAll(self.fd, data);
  1313. }
  1314. fn close(self: *Connection, tls: ?*const TlsContext) void {
  1315. if (self.ssl) |ssl_ptr| {
  1316. if (tls) |t| {
  1317. t.sslShutdown(ssl_ptr);
  1318. }
  1319. self.ssl = null;
  1320. }
  1321. _ = linux.close(self.fd);
  1322. }
  1323. };
  1324. // =========================================================================
  1325. // ServerCore — owns server socket, epoll, threads, queue, optional TLS
  1326. // =========================================================================
  1327. const MAX_KEEPALIVE_REQUESTS: u32 = 100;
  1328. const MAX_IO_THREADS: u32 = 16;
  1329. const ServerCore = struct {
  1330. port: u16 = 0,
  1331. server_fd: i32,
  1332. epoll_fd: i32,
  1333. shutdown_fd: i32, // eventfd for shutdown signal
  1334. tls: ?TlsContext,
  1335. request_queue: RequestQueue,
  1336. running: std.atomic.Value(bool),
  1337. acceptor_thread: ?std.Thread,
  1338. io_threads: []std.Thread,
  1339. num_threads: u32,
  1340. // Connection tracking for I/O threads
  1341. conn_queue: ConnectionQueue,
  1342. /// idle connections wait here instead of inside a blocking worker read (mission 084)
  1343. parked: ParkedConns,
  1344. /// Largest request body this server reads (ticket #445): a bigger Content-Length, or a
  1345. /// chunked body that grows past it, is refused `413` before the body is buffered.
  1346. max_body: usize = DEFAULT_MAX_BODY,
  1347. /// Refuse a WebSocket upgrade whose Origin is foreign with `403` before the 101 (#445).
  1348. ws_check_origin: bool = false,
  1349. /// Extra allowed origins (comma-separated, `scheme://host[:port]` or bare `host[:port]`);
  1350. /// owned copy, empty = none.
  1351. ws_origins: []const u8 = "",
  1352. fn create(port: u16, host_str: []const u8, cert_path: []const u8, key_path: []const u8, num_threads: u32) ?*ServerCore {
  1353. const core = allocator.create(ServerCore) catch return null;
  1354. core.* = .{
  1355. .server_fd = -1,
  1356. .epoll_fd = -1,
  1357. .shutdown_fd = -1,
  1358. .tls = null,
  1359. .request_queue = RequestQueue.init(),
  1360. .running = std.atomic.Value(bool).init(false),
  1361. .acceptor_thread = null,
  1362. .io_threads = &[_]std.Thread{},
  1363. .num_threads = @min(num_threads, MAX_IO_THREADS),
  1364. .conn_queue = ConnectionQueue.init(),
  1365. .parked = ParkedConns.init(),
  1366. };
  1367. // Create TCP socket. NONBLOCK IS NOT DECORATION (mission 260): the acceptor
  1368. // drains with `while (true) accept4(...)` until the call fails, and on a
  1369. // BLOCKING listener that last call does not fail — it sleeps in the kernel
  1370. // (`inet_csk_accept`) until the next client arrives. The thread then never
  1371. // re-reads `core.running`, so `shutdown()`'s `join(acceptor)` waits forever
  1372. // and `close()` never returns. Measured: after ONE connection the process was
  1373. // down to two threads, main in `__futex_wait` (the join) and the acceptor in
  1374. // `inet_csk_accept`; each extra TCP connect added exactly one fd and put the
  1375. // acceptor straight back into `inet_csk_accept`. hl:http2's listener
  1376. // (`http2.zig:926`) has always carried NONBLOCK — http1 was the outlier.
  1377. // The accept flags below apply to the ACCEPTED socket, never to this one.
  1378. const sock_rc = linux.socket(linux.AF.INET, linux.SOCK.STREAM | linux.SOCK.CLOEXEC | linux.SOCK.NONBLOCK, 0);
  1379. const server_fd: i32 = @bitCast(@as(u32, @truncate(sock_rc)));
  1380. if (server_fd < 0) {
  1381. logMsg("http1: socket() failed\n");
  1382. allocator.destroy(core);
  1383. return null;
  1384. }
  1385. core.server_fd = server_fd;
  1386. // SO_REUSEADDR
  1387. const one: i32 = 1;
  1388. _ = linux.setsockopt(server_fd, linux.SOL.SOCKET, linux.SO.REUSEADDR, @ptrCast(&one), @sizeOf(i32));
  1389. // Parse host address
  1390. var addr_val: u32 = 0; // INADDR_ANY
  1391. if (host_str.len > 0 and !std.mem.eql(u8, host_str, "0.0.0.0")) {
  1392. addr_val = parseIPv4(host_str) orelse 0;
  1393. }
  1394. // Bind
  1395. const addr = linux.sockaddr.in{
  1396. .port = std.mem.nativeToBig(u16, port),
  1397. .addr = addr_val,
  1398. };
  1399. const bind_rc = linux.bind(server_fd, @ptrCast(&addr), @sizeOf(linux.sockaddr.in));
  1400. const bind_err: i32 = @bitCast(@as(u32, @truncate(bind_rc)));
  1401. if (bind_err < 0) {
  1402. // The prefix is LOAD-BEARING: `tests/browser/fixtures.mjs` breaks its
  1403. // readiness wait on `bind() failed on port N` (mission 285). The errno
  1404. // and the holder are appended to it, never in front of it.
  1405. var why: [320]u8 = undefined;
  1406. logFmt("http1: bind() failed on port {d}: {s}\n", .{ port, http.bindFailureDetail(&why, bind_rc, port, false) });
  1407. core.destroy();
  1408. return null;
  1409. }
  1410. const listen_rc = linux.listen(server_fd, 128);
  1411. const listen_err: i32 = @bitCast(@as(u32, @truncate(listen_rc)));
  1412. if (listen_err < 0) {
  1413. logMsg("http1: listen() failed\n");
  1414. core.destroy();
  1415. return null;
  1416. }
  1417. // Create eventfd for shutdown signaling
  1418. const efd_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  1419. const shutdown_fd: i32 = @bitCast(@as(u32, @truncate(efd_rc)));
  1420. if (shutdown_fd < 0) {
  1421. logMsg("http1: eventfd() failed\n");
  1422. core.destroy();
  1423. return null;
  1424. }
  1425. core.shutdown_fd = shutdown_fd;
  1426. // Create epoll instance
  1427. const epoll_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  1428. const epoll_fd: i32 = @bitCast(@as(u32, @truncate(epoll_rc)));
  1429. if (epoll_fd < 0) {
  1430. logMsg("http1: epoll_create1() failed\n");
  1431. core.destroy();
  1432. return null;
  1433. }
  1434. core.epoll_fd = epoll_fd;
  1435. // Add server_fd to epoll
  1436. var ev = linux.epoll_event{
  1437. .events = linux.EPOLL.IN,
  1438. .data = .{ .fd = server_fd },
  1439. };
  1440. _ = linux.epoll_ctl(epoll_fd, linux.EPOLL.CTL_ADD, server_fd, &ev);
  1441. // Add shutdown_fd to epoll
  1442. var shutdown_ev = linux.epoll_event{
  1443. .events = linux.EPOLL.IN,
  1444. .data = .{ .fd = shutdown_fd },
  1445. };
  1446. _ = linux.epoll_ctl(epoll_fd, linux.EPOLL.CTL_ADD, shutdown_fd, &shutdown_ev);
  1447. // Initialize TLS if cert+key provided
  1448. if (cert_path.len > 0 and key_path.len > 0) {
  1449. core.tls = TlsContext.init(cert_path, key_path);
  1450. if (core.tls == null) {
  1451. logMsg("http1: TLS initialization failed, falling back to plain HTTP\n");
  1452. }
  1453. }
  1454. logFmt("http1: listening on :{d}{s}\n", .{ port, if (core.tls != null) " (TLS)" else "" });
  1455. // Start threads
  1456. core.running.store(true, .release);
  1457. // Parker thread first: the acceptor parks into it from its very first accept.
  1458. // If it cannot start we log and keep going — connections then go straight to the
  1459. // pool, which is the pre-084 (starvable) behaviour rather than an outage.
  1460. if (!core.parked.start(core)) {
  1461. logMsg("http1: parker thread unavailable — idle keep-alive connections will hold I/O workers\n");
  1462. }
  1463. // Allocate I/O threads
  1464. const threads = allocator.alloc(std.Thread, core.num_threads) catch {
  1465. core.destroy();
  1466. return null;
  1467. };
  1468. core.io_threads = threads;
  1469. for (0..core.num_threads) |i| {
  1470. core.io_threads[i] = std.Thread.spawn(.{}, ioWorker, .{core}) catch {
  1471. logFmt("http1: failed to spawn I/O thread {d}\n", .{i});
  1472. core.num_threads = @intCast(i);
  1473. core.io_threads = core.io_threads[0..i];
  1474. break;
  1475. };
  1476. }
  1477. // Start acceptor thread
  1478. core.acceptor_thread = std.Thread.spawn(.{}, acceptorLoop, .{core}) catch {
  1479. logMsg("http1: failed to spawn acceptor thread\n");
  1480. core.shutdown();
  1481. core.destroy();
  1482. return null;
  1483. };
  1484. core.port = port;
  1485. registerCore(core);
  1486. return core;
  1487. }
  1488. fn shutdown(self: *ServerCore) void {
  1489. unregisterCore(self);
  1490. if (!self.running.swap(false, .acq_rel)) return;
  1491. // Signal shutdown via eventfd
  1492. if (self.shutdown_fd >= 0) {
  1493. const val: u64 = 1;
  1494. _ = linux.write(self.shutdown_fd, @ptrCast(&val), @sizeOf(u64));
  1495. }
  1496. // Wake up the request queue so dequeue() unblocks
  1497. self.request_queue.signalShutdown();
  1498. // Stop parking before the workers: the parker must not push new work into a
  1499. // queue whose consumers are being torn down.
  1500. self.parked.stop();
  1501. // Signal connection queue to wake I/O workers
  1502. self.conn_queue.signalShutdown();
  1503. // Join acceptor thread
  1504. if (self.acceptor_thread) |t| {
  1505. t.join();
  1506. self.acceptor_thread = null;
  1507. }
  1508. // Join I/O threads
  1509. for (self.io_threads) |t| {
  1510. t.join();
  1511. }
  1512. }
  1513. fn destroy(self: *ServerCore) void {
  1514. self.shutdown();
  1515. if (self.epoll_fd >= 0) _ = linux.close(self.epoll_fd);
  1516. if (self.shutdown_fd >= 0) _ = linux.close(self.shutdown_fd);
  1517. if (self.server_fd >= 0) _ = linux.close(self.server_fd);
  1518. if (self.tls) |*tls| tls.deinit();
  1519. // Close every still-parked idle connection, then drain conn_queue
  1520. self.parked.deinit(if (self.tls) |*t| t else null);
  1521. self.conn_queue.deinit(if (self.tls) |*t| t else null);
  1522. self.request_queue.deinit();
  1523. if (self.io_threads.len > 0) allocator.free(self.io_threads);
  1524. allocator.destroy(self);
  1525. }
  1526. };
  1527. // =========================================================================
  1528. // Connection Queue — MPSC queue for acceptor → I/O workers
  1529. // =========================================================================
  1530. const ConnectionQueue = struct {
  1531. queue: std.ArrayListUnmanaged(Connection),
  1532. mutex: PthreadMutex,
  1533. condvar: PthreadCond,
  1534. shutdown: bool,
  1535. fn init() ConnectionQueue {
  1536. var self: ConnectionQueue = .{
  1537. .queue = .empty,
  1538. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1539. .condvar = c.PTHREAD_COND_INITIALIZER,
  1540. .shutdown = false,
  1541. };
  1542. mutexInit(&self.mutex);
  1543. condInit(&self.condvar);
  1544. return self;
  1545. }
  1546. fn enqueue(self: *ConnectionQueue, conn: Connection) void {
  1547. mutexLock(&self.mutex);
  1548. defer mutexUnlock(&self.mutex);
  1549. self.queue.append(allocator, conn) catch return;
  1550. condSignal(&self.condvar);
  1551. }
  1552. fn dequeue(self: *ConnectionQueue) ?Connection {
  1553. mutexLock(&self.mutex);
  1554. defer mutexUnlock(&self.mutex);
  1555. while (self.queue.items.len == 0 and !self.shutdown) {
  1556. condWait(&self.condvar, &self.mutex);
  1557. }
  1558. if (self.shutdown and self.queue.items.len == 0) return null;
  1559. return self.queue.orderedRemove(0);
  1560. }
  1561. fn signalShutdown(self: *ConnectionQueue) void {
  1562. mutexLock(&self.mutex);
  1563. defer mutexUnlock(&self.mutex);
  1564. self.shutdown = true;
  1565. condBroadcast(&self.condvar);
  1566. }
  1567. /// Close everything still queued and stay a VALID, EMPTY queue — `deinit`
  1568. /// leaves the list `undefined`, which is only safe on a core that is being
  1569. /// freed, and a closed core deliberately is not (see `hl_http1_close`).
  1570. fn closeAll(self: *ConnectionQueue, tls: ?*TlsContext) void {
  1571. mutexLock(&self.mutex);
  1572. defer mutexUnlock(&self.mutex);
  1573. for (self.queue.items) |*conn| conn.close(tls);
  1574. self.queue.clearRetainingCapacity();
  1575. }
  1576. fn deinit(self: *ConnectionQueue, tls: ?*TlsContext) void {
  1577. for (self.queue.items) |*conn| {
  1578. conn.close(tls);
  1579. }
  1580. self.queue.deinit(allocator);
  1581. }
  1582. };
  1583. // =========================================================================
  1584. // ParkedConns — idle connections wait HERE, not in an I/O worker (mission 084)
  1585. // =========================================================================
  1586. //
  1587. // The starvation this fixes, measured: a `threads = 4` server, four keep-alive
  1588. // connections that have gone quiet, and every subsequent request times out — each idle
  1589. // socket sat inside a worker's blocking read(). Parking inverts that: an idle connection
  1590. // costs one epoll registration and ZERO threads, and a worker only ever picks up a
  1591. // connection that already has bytes waiting (or has hung up, which it reads as EOF and
  1592. // closes). Connections are parked from the acceptor (a fresh socket may be silent — a
  1593. // pre-connected browser socket routinely is) and after every keep-alive response.
  1594. //
  1595. // TLS caveat: an ESTABLISHED TLS connection is never parked. OpenSSL may hold already-
  1596. // decrypted plaintext in its own buffer, which epoll on the raw fd cannot see, so parking
  1597. // it could hang a live request. `ssl == null` covers all plain HTTP plus the pre-handshake
  1598. // TLS socket (the ClientHello does arrive on the raw fd), which is what the park path takes.
  1599. /// How long a parked, silent connection is kept before it is closed. It costs no thread,
  1600. /// only an fd, so this is generous compared to the old in-worker 30s SO_RCVTIMEO.
  1601. const PARK_IDLE_TIMEOUT_MS: i64 = 60_000;
  1602. /// Milliseconds on CLOCK_MONOTONIC. This zig's `std.time` exposes no timestamp function,
  1603. /// and monotonic is the right clock anyway — a wall-clock step must not expire a live
  1604. /// connection early or keep a dead one parked.
  1605. fn monotonicMs() i64 {
  1606. var ts: linux.timespec = undefined;
  1607. if (linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts) != 0) return 0;
  1608. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  1609. }
  1610. const ParkedConn = struct {
  1611. conn: Connection,
  1612. /// monotonic ms after which this silent connection is closed
  1613. deadline_ms: i64,
  1614. };
  1615. const ParkedConns = struct {
  1616. epoll_fd: i32,
  1617. wake_fd: i32,
  1618. thread: ?std.Thread,
  1619. running: std.atomic.Value(bool),
  1620. mutex: PthreadMutex,
  1621. /// fd → parked connection. Guarded by `mutex`; the parker thread is the only
  1622. /// consumer, park() the only producer, so a plain map is enough.
  1623. map: std.AutoHashMapUnmanaged(i32, ParkedConn),
  1624. fn init() ParkedConns {
  1625. var self: ParkedConns = .{
  1626. .epoll_fd = -1,
  1627. .wake_fd = -1,
  1628. .thread = null,
  1629. .running = std.atomic.Value(bool).init(false),
  1630. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1631. .map = .empty,
  1632. };
  1633. mutexInit(&self.mutex);
  1634. return self;
  1635. }
  1636. /// Create the epoll instance + wake eventfd and spawn the parker thread.
  1637. /// Returns false if the kernel objects could not be made — the caller then falls
  1638. /// back to handing connections straight to the pool (old behaviour, still correct,
  1639. /// just starvable).
  1640. fn start(self: *ParkedConns, core: *ServerCore) bool {
  1641. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  1642. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  1643. if (ep < 0) return false;
  1644. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  1645. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  1646. if (ef < 0) {
  1647. _ = linux.close(ep);
  1648. return false;
  1649. }
  1650. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  1651. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  1652. self.epoll_fd = ep;
  1653. self.wake_fd = ef;
  1654. self.running.store(true, .release);
  1655. self.thread = std.Thread.spawn(.{}, parkerLoop, .{core}) catch {
  1656. self.running.store(false, .release);
  1657. _ = linux.close(ep);
  1658. _ = linux.close(ef);
  1659. self.epoll_fd = -1;
  1660. self.wake_fd = -1;
  1661. return false;
  1662. };
  1663. return true;
  1664. }
  1665. /// Hand a connection to the parker. The map insert happens BEFORE the epoll ADD so
  1666. /// the parker can never see a readable fd it has no entry for.
  1667. fn park(self: *ParkedConns, conn: Connection) bool {
  1668. if (self.epoll_fd < 0 or !self.running.load(.acquire)) return false;
  1669. mutexLock(&self.mutex);
  1670. self.map.put(allocator, conn.fd, .{
  1671. .conn = conn,
  1672. .deadline_ms = monotonicMs() + PARK_IDLE_TIMEOUT_MS,
  1673. }) catch {
  1674. mutexUnlock(&self.mutex);
  1675. return false;
  1676. };
  1677. var ev = linux.epoll_event{
  1678. .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
  1679. .data = .{ .fd = conn.fd },
  1680. };
  1681. const rc = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_ADD, conn.fd, &ev);
  1682. const err: i32 = @bitCast(@as(u32, @truncate(rc)));
  1683. if (err < 0) {
  1684. _ = self.map.remove(conn.fd);
  1685. mutexUnlock(&self.mutex);
  1686. return false;
  1687. }
  1688. mutexUnlock(&self.mutex);
  1689. return true;
  1690. }
  1691. /// Take a parked connection off the epoll set. Returns it if we still owned it.
  1692. fn take(self: *ParkedConns, fd: i32) ?Connection {
  1693. mutexLock(&self.mutex);
  1694. defer mutexUnlock(&self.mutex);
  1695. const entry = self.map.fetchRemove(fd) orelse return null;
  1696. _ = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  1697. return entry.value.conn;
  1698. }
  1699. /// Close every parked connection whose silence outlived PARK_IDLE_TIMEOUT_MS.
  1700. fn sweepExpired(self: *ParkedConns, tls: ?*TlsContext) void {
  1701. const now = monotonicMs();
  1702. mutexLock(&self.mutex);
  1703. defer mutexUnlock(&self.mutex);
  1704. var expired: [64]i32 = undefined;
  1705. var n: usize = 0;
  1706. var it = self.map.iterator();
  1707. while (it.next()) |kv| {
  1708. if (kv.value_ptr.deadline_ms <= now) {
  1709. if (n == expired.len) break;
  1710. expired[n] = kv.key_ptr.*;
  1711. n += 1;
  1712. }
  1713. }
  1714. for (expired[0..n]) |fd| {
  1715. if (self.map.fetchRemove(fd)) |e| {
  1716. _ = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  1717. var conn = e.value.conn;
  1718. conn.close(tls);
  1719. }
  1720. }
  1721. }
  1722. fn stop(self: *ParkedConns) void {
  1723. if (!self.running.swap(false, .acq_rel)) return;
  1724. if (self.wake_fd >= 0) {
  1725. const val: u64 = 1;
  1726. _ = linux.write(self.wake_fd, @ptrCast(&val), @sizeOf(u64));
  1727. }
  1728. if (self.thread) |t| {
  1729. t.join();
  1730. self.thread = null;
  1731. }
  1732. }
  1733. /// Close every parked connection and stay a VALID, EMPTY map. Unlike `deinit`
  1734. /// this keeps the epoll/wake fds and the struct usable — a CLOSED core is not
  1735. /// a freed one (`hl_http1_close`), and `park()` already refuses once `running`
  1736. /// is false, so the emptied map simply stays empty.
  1737. fn closeAll(self: *ParkedConns, tls: ?*TlsContext) void {
  1738. mutexLock(&self.mutex);
  1739. defer mutexUnlock(&self.mutex);
  1740. var it = self.map.iterator();
  1741. while (it.next()) |kv| {
  1742. var conn = kv.value_ptr.conn;
  1743. conn.close(tls);
  1744. }
  1745. self.map.clearRetainingCapacity();
  1746. }
  1747. fn deinit(self: *ParkedConns, tls: ?*TlsContext) void {
  1748. self.stop();
  1749. mutexLock(&self.mutex);
  1750. var it = self.map.iterator();
  1751. while (it.next()) |kv| {
  1752. var conn = kv.value_ptr.conn;
  1753. conn.close(tls);
  1754. }
  1755. self.map.deinit(allocator);
  1756. self.map = .empty;
  1757. mutexUnlock(&self.mutex);
  1758. if (self.epoll_fd >= 0) _ = linux.close(self.epoll_fd);
  1759. if (self.wake_fd >= 0) _ = linux.close(self.wake_fd);
  1760. self.epoll_fd = -1;
  1761. self.wake_fd = -1;
  1762. }
  1763. };
  1764. /// The parker thread: waits for a parked connection to become READABLE and only then
  1765. /// hands it to an I/O worker. The 1s epoll timeout doubles as the idle-sweep tick.
  1766. fn parkerLoop(core: *ServerCore) void {
  1767. var events: [64]linux.epoll_event = undefined;
  1768. while (core.parked.running.load(.acquire)) {
  1769. const n_rc = linux.epoll_wait(core.parked.epoll_fd, &events, events.len, 1000);
  1770. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  1771. if (n > 0) {
  1772. for (events[0..@intCast(n)]) |ev| {
  1773. if (ev.data.fd == core.parked.wake_fd) {
  1774. var drain: u64 = 0;
  1775. _ = linux.read(core.parked.wake_fd, @ptrCast(&drain), @sizeOf(u64));
  1776. continue;
  1777. }
  1778. // Readable, hung up or errored — all three are a worker's job: it either
  1779. // parses the request or reads EOF and closes.
  1780. if (core.parked.take(ev.data.fd)) |conn| {
  1781. if (core.running.load(.acquire)) {
  1782. core.conn_queue.enqueue(conn);
  1783. } else {
  1784. var dead = conn;
  1785. dead.close(if (core.tls) |*t| t else null);
  1786. }
  1787. }
  1788. }
  1789. }
  1790. core.parked.sweepExpired(if (core.tls) |*t| t else null);
  1791. }
  1792. }
  1793. /// Park `conn` if we can, otherwise hand it straight to the pool. Every enqueue site
  1794. /// that is NOT known to have bytes waiting goes through here.
  1795. fn parkOrEnqueue(core: *ServerCore, conn: Connection) void {
  1796. // An established TLS connection may hold decrypted bytes epoll cannot see — see the
  1797. // ParkedConns header comment. Those go straight to a worker, as before.
  1798. if (conn.ssl == null and core.parked.park(conn)) return;
  1799. core.conn_queue.enqueue(conn);
  1800. }
  1801. // =========================================================================
  1802. // Acceptor thread — epoll loop accepting new connections
  1803. // =========================================================================
  1804. fn acceptorLoop(core: *ServerCore) void {
  1805. var events: [64]linux.epoll_event = undefined;
  1806. while (core.running.load(.acquire)) {
  1807. const n_rc = linux.epoll_wait(core.epoll_fd, &events, events.len, 1000);
  1808. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  1809. if (n < 0) continue;
  1810. if (n == 0) continue;
  1811. for (events[0..@intCast(n)]) |ev| {
  1812. if (ev.data.fd == core.shutdown_fd) {
  1813. return; // shutdown signaled
  1814. }
  1815. if (ev.data.fd == core.server_fd) {
  1816. // Accept all pending connections — the listener is NONBLOCK, so the
  1817. // drain ends on EAGAIN instead of sleeping inside accept4().
  1818. while (true) {
  1819. var client_addr: linux.sockaddr.in = undefined;
  1820. var addr_len: u32 = @sizeOf(linux.sockaddr.in);
  1821. const accept_rc = linux.accept4(core.server_fd, @ptrCast(&client_addr), &addr_len, linux.SOCK.CLOEXEC | linux.SOCK.NONBLOCK);
  1822. const client_fd: i32 = @bitCast(@as(u32, @truncate(accept_rc)));
  1823. if (client_fd < 0) break;
  1824. // A shutdown that landed mid-drain: the parker is stopped and the
  1825. // conn_queue has no consumers left, so hand this socket to nobody —
  1826. // close it and leave, rather than leaking the fd into a dead queue.
  1827. if (!core.running.load(.acquire)) {

Only the first lines are shown.

Branches

Latest commits

  • 2a4cfc55jukebox: library screens (songs, artists, albums, artist, album, search, favourites), compact player bar, /stream with Range, thumbnails, virtual list vendored, ui gate and real-library checkmre
  • 93a44212jukebox: report, numbers of the full scan, notes on the index key rulemre
  • bf5167dajukebox: index keys without commas (mpackdb loses them after a reopen), comma fixture and gate checksmre
  • 28a82fa2jukebox: README, STATUS, LOG, DECISIONSmre
  • d13987dfjukebox: library scanner, ID3 reader, mpackdb database and JSON API, with fixtures and a gatemre