// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The accept loop, and the one decision it makes: which version of HTTP this //! connection is about to speak. //! //! There is deliberately not much to it. Everything that makes a server an //! HTTP server is in `http1` and `http2` and whatever is written beside them, //! and everything that makes it serve anything in particular is in the //! handler. A program that gets its connections some other way — from //! `systemd`, from an `inetd`-style parent, from a TLS terminator in the same //! process — can skip this entirely and call `serveConnection`. //! //! Sessions run concurrently, one task each, because a session spends nearly //! all of its time blocked on a socket. Where the `Io` implementation cannot //! provide concurrency the connection is served inline instead, which is //! correct but serves one client at a time. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const http1 = @import("../http1.zig"); const http2 = @import("../http2.zig"); const transport = @import("../transport.zig"); const Handler = @import("Handler.zig"); const Request = @import("Request.zig"); const Response = @import("Response.zig"); const Server = @This(); const log = std.log.scoped(.server); io: Io, gpa: Allocator, listener: transport.Listener, handler: Handler, config: Config, /// Which version of HTTP a connection is speaking. /// /// The seam for other versions is here and in `Config.drivers`: this library /// serves `http1` itself, and `h2` too unless `Config.http2` is null, and /// dispatches anything else to whatever has been registered for it, so a /// driver can be written, tested and shipped without any of this changing. pub const Protocol = enum { /// RFC 9112, over a byte stream. http1, /// RFC 9113, over a byte stream. h2, /// RFC 9114, over QUIC — which this transport cannot carry, since a QUIC /// connection is many streams and a `transport.Connection` is one. An /// HTTP/3 implementation brings its own listener; this is here so that /// the enumeration is the real set and not the convenient one. h3, /// The ALPN protocol identifier for this version: `http/1.1` from RFC /// 7301's own registry, `h2` from RFC 9113 §3.1, and `h3` from RFC 9114 /// §3.1. pub fn alpn(p: Protocol) []const u8 { return switch (p) { .http1 => "http/1.1", .h2 => "h2", .h3 => "h3", }; } test alpn { try std.testing.expectEqualStrings("http/1.1", Protocol.http1.alpn()); try std.testing.expectEqualStrings("h2", Protocol.h2.alpn()); } /// Which version an ALPN identifier names, or null for one nobody here /// knows. /// /// Accepts a little more than `alpn` produces: `http/1.0`, and `h2c`, /// which RFC 9113 §3.1 deprecated but which names the same protocol. pub fn fromAlpn(name: []const u8) ?Protocol { if (std.mem.eql(u8, name, "http/1.1")) return .http1; if (std.mem.eql(u8, name, "http/1.0")) return .http1; if (std.mem.eql(u8, name, "h2")) return .h2; if (std.mem.eql(u8, name, "h2c")) return .h2; if (std.mem.eql(u8, name, "h3")) return .h3; return null; } test fromAlpn { try std.testing.expectEqual(Protocol.h2, Protocol.fromAlpn("h2").?); try std.testing.expectEqual(Protocol.http1, Protocol.fromAlpn("http/1.0").?); // Identifiers are compared exactly: RFC 7301 §3.1 makes them octets, // not case-insensitive tokens. try std.testing.expect(Protocol.fromAlpn("H2") == null); try std.testing.expect(Protocol.fromAlpn("spdy/3") == null); } }; /// A driver for a version this library does not serve itself. /// /// Registering one is the whole of adding a version: write something that /// reads frames off `conn` and fills in a `Request` and a `Response` the way /// `http1.Connection` does, and hand it over here. An `h2` driver is consulted /// only when `Config.http2` is null. Nothing else changes — /// not the handler, not the transport, not this file. pub const Driver = struct { protocol: Protocol, context: ?*anyopaque, serveFn: *const fn ( context: ?*anyopaque, io: Io, gpa: Allocator, conn: *transport.Connection, handler: Handler, ) anyerror!void, }; pub const Config = struct { /// How each connection is read and written. listener: transport.Listener.Options = .{}, /// What the HTTP/1.x driver does. http1: http1.Config = .{}, /// What the HTTP/2 driver does, or null to not speak it at all. /// /// On by default costs nothing: HTTP/2 is only ever selected by an ALPN /// of `h2` or a literal `PRI ` preface, and no HTTP/1.1 client sends /// either. The one caveat is that HTTP/2 needs an `Io` that can give a /// task per stream — see `http2.Config.max_concurrent_streams` — and on /// one that cannot, every stream is refused. Set this to null there. /// /// A named field rather than an entry in `drivers` because `Driver` /// holds its configuration behind a `?*anyopaque` whose lifetime is the /// caller's problem, and the natural way to write that — a temporary — /// compiles and is wrong. http2: ?http2.Config = .{}, /// Drivers for versions this library does not implement, searched by /// protocol. HTTP/3 would arrive here. drivers: []const Driver = &.{}, }; /// A server that will accept from `listener` and hand every request to /// `handler`. Nothing is accepted until `serve` or `serveOne` is called. /// /// `io` is what every connection is served on, and whether it can run tasks /// concurrently decides whether this serves more than one client at a time. /// `gpa` is what the transport and the drivers allocate each connection's /// buffers from. A read buffer in `config.listener` too small for the drivers /// that are switched on is a programmer error and asserts. pub fn init( io: Io, gpa: Allocator, listener: transport.Listener, handler: Handler, config: Config, ) Server { std.debug.assert(config.listener.read_buffer_len >= http1.min_read_buffer_len); if (config.http2 != null) { std.debug.assert(config.listener.read_buffer_len >= http2.min_read_buffer_len); } return .{ .io = io, .gpa = gpa, .listener = listener, .handler = handler, .config = config, }; } test init { var listener: OneShot = .{ .pending = null }; const server: Server = .init(std.testing.io, std.testing.allocator, listener.listener(), .initStateless(hello), .{ .http1 = .{ .server_name = "example" }, }); // HTTP/2 is on unless it is switched off. try std.testing.expect(server.config.http2 != null); try std.testing.expectEqualStrings("example", server.config.http1.server_name.?); } pub const ServeError = error{ /// Accepting failed for a reason that is not going to go away: the /// process is out of file descriptors, or the network stack has gone. AcceptFailed, OutOfMemory, } || Io.Cancelable; /// Accepts connections until `shutdown` is called or the task is cancelled, /// serving each one concurrently. /// /// Cancels the connections still in flight and waits for them before /// returning, so that a caller which frees the handler's state afterwards is /// not freeing it underneath one. A connection mid-response when `shutdown` /// is called is therefore cut short rather than allowed to finish. pub fn serve(s: *Server) ServeError!void { var group: Io.Group = .init; // On the way out -- including out of a cancellation -- the sessions are // asked to stop and then waited for. defer group.cancel(s.io); while (true) { // Only the accepting here. Anything the connection needs before it // can be served -- a TLS handshake -- happens in its own task, or // one client that connected and said nothing would keep every other // from being accepted. const conn = s.listener.acceptPending(s.io, s.gpa, s.config.listener) catch |err| switch (err) { error.ListenerClosed => return, error.Canceled => return error.Canceled, // One client's connection died between the handshake and the // accept. It says nothing about the next one. error.ConnectionAborted => continue, error.OutOfMemory => return error.OutOfMemory, error.AcceptFailed => return error.AcceptFailed, }; group.concurrent(s.io, establishAndServe, .{ s, conn }) catch |err| switch (err) { // No concurrency to be had from this `Io`, or no room left for // another task. Serving inline is still serving; it just means // the next client waits. error.ConcurrencyUnavailable => establishAndServe(s, conn), }; } } /// One accepted connection's task: whatever the listener still has to do to /// it, then serving it. A connection that cannot be established is this /// client's problem alone, and is already closed. fn establishAndServe(s: *Server, pending: transport.Connection) void { const conn = s.listener.establish(s.io, s.gpa, pending) catch return; serveConnection(s, conn); } test serve { var c: transport.memory.Connection = try .init(std.testing.allocator, "GET / HTTP/1.1\r\nHost: a\r\n\r\n", .{}); defer c.deinit(); var listener: OneShot = .{ .pending = &c }; // `Io.failing` cannot run a task, so the one connection is served inline // and is finished by the time `serve` finds the listener closed. var server: Server = .init(Io.failing, std.testing.allocator, listener.listener(), .initStateless(hello), .{ .http1 = .{ .send_date = false, .server_name = null }, }); try server.serve(); try std.testing.expectEqualStrings("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", c.written()); } /// Accepts exactly one connection and serves it in this task, returning when /// the connection ends — or at once, if the listener is closed or the /// connection died before it could be accepted. /// /// What a test wants. A program handed its connection by `inetd` has no /// listener to accept from, and wants `serveConnection`. pub fn serveOne(s: *Server) ServeError!void { const conn = s.listener.accept(s.io, s.gpa, s.config.listener) catch |err| switch (err) { error.ListenerClosed, error.ConnectionAborted => return, error.Canceled => return error.Canceled, error.OutOfMemory => return error.OutOfMemory, error.AcceptFailed => return error.AcceptFailed, }; serveConnection(s, conn); } test serveOne { var c: transport.memory.Connection = try .init(std.testing.allocator, "GET / HTTP/1.1\r\nHost: a\r\n\r\n", .{}); defer c.deinit(); var listener: OneShot = .{ .pending = &c }; var server: Server = .init(std.testing.io, std.testing.allocator, listener.listener(), .initStateless(hello), .{ .http1 = .{ .send_date = false, .server_name = null }, }); try server.serveOne(); try std.testing.expectEqualStrings("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", c.written()); } /// Serves one connection to its end and then closes it. /// /// Takes ownership: whatever the transport allocated for the connection is /// given back here. This is the entry point for a program that accepted the /// connection itself. pub fn serveConnection(s: *Server, connection: transport.Connection) void { var conn = connection; defer conn.close(s.io, s.gpa); switch (selectProtocol(&conn)) { .http1 => http1.serve(s.io, s.gpa, &conn, s.handler, s.config.http1) catch |err| switch (err) { // Nothing can be said to the client about this, and nothing is // gained by saying it to the log for every connection in a // machine that is out of memory. error.OutOfMemory => {}, }, .h2 => { if (s.config.http2) |config| { http2.serve(s.io, s.gpa, &conn, s.handler, config) catch |err| switch (err) { error.OutOfMemory => {}, }; return; } s.runDriver(.h2, &conn); }, .h3 => s.runDriver(.h3, &conn), } } test serveConnection { // A connection that came from somewhere other than the listener: here, a // string, with the facts a TLS terminator would have supplied. var c: transport.memory.Connection = try .init(std.testing.allocator, "GET / HTTP/1.1\r\nHost: a\r\n\r\n", .{ .info = .{ .secure = true, .alpn = "http/1.1" }, }); defer c.deinit(); var listener: OneShot = .{ .pending = null }; var server: Server = .init(std.testing.io, std.testing.allocator, listener.listener(), .initStateless(hello), .{ .http1 = .{ .send_date = false, .server_name = null }, }); server.serveConnection(c.connection()); try std.testing.expectEqualStrings("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", c.written()); } /// Hands a connection to a driver this library does not provide. fn runDriver(s: *Server, protocol: Protocol, conn: *transport.Connection) void { const driver = s.driverFor(protocol) orelse { // Nothing useful can be said here: a client that opened with an // HTTP/2 preface will not read an HTTP/1.1 response, and one that // negotiated `h3` is not on this transport at all. return; }; driver.serveFn(driver.context, s.io, s.gpa, conn, s.handler) catch |err| { // Logged rather than dropped: without this, `OutOfMemory` and a // broken socket are indistinguishable from a clean close, which makes // the first bug in a new driver undiagnosable. log.debug("{s} driver failed: {s}", .{ @tagName(protocol), @errorName(err) }); }; } /// Works out which version this connection is about to speak. /// /// ALPN settles it when there is one, which is every TLS connection and no /// cleartext one. Failing that the only thing to go on is what the client /// sends first, and the one case worth telling apart is a client using HTTP/2 /// with prior knowledge: its connection preface begins `PRI `, which is a /// method no HTTP/1.x request uses and which RFC 9113 §3.4 chose precisely so /// that this test would work. /// /// Four octets, and not the whole twenty-four the preface occupies, because /// peeking twenty-four would block until a client that had sent a complete /// eighteen-octet `GET / HTTP/1.1` request sent something else, which it /// never will. fn selectProtocol(conn: *transport.Connection) Protocol { if (conn.info.alpn) |name| return Protocol.fromAlpn(name) orelse .http1; const prefix = conn.input.peek(http2.preface_prefix.len) catch return .http1; if (std.mem.eql(u8, prefix, http2.preface_prefix)) return .h2; return .http1; } fn driverFor(s: *Server, protocol: Protocol) ?Driver { for (s.config.drivers) |driver| { if (driver.protocol == protocol) return driver; } return null; } /// Makes `serve` return, from another task. pub fn shutdown(s: *Server) void { s.listener.shutdown(s.io); } test shutdown { var c: transport.memory.Connection = try .init(std.testing.allocator, "GET / HTTP/1.1\r\nHost: a\r\n\r\n", .{}); defer c.deinit(); var listener: OneShot = .{ .pending = &c }; var server: Server = .init(std.testing.io, std.testing.allocator, listener.listener(), .initStateless(hello), .{}); // Ordinarily from another task while `serve` is blocked in `accept`. server.shutdown(); try server.serve(); // Nothing was accepted, so nothing was answered. try std.testing.expectEqualStrings("", c.written()); } /// Where the server is listening, when that is an address. pub fn localAddress(s: *const Server) ?transport.Endpoint { return s.listener.localAddress(); } test localAddress { var listener: OneShot = .{ .pending = null, .local = try .parse("127.0.0.1:8080") }; const server: Server = .init(std.testing.io, std.testing.allocator, listener.listener(), .initStateless(hello), .{}); try std.testing.expect(server.localAddress().?.eql(try .parse("127.0.0.1:8080"))); } /// The handler the doctests serve. fn hello(req: *Request, res: *Response) anyerror!void { _ = req; try res.send("hello"); } /// A listener with at most one connection in it, for the doctests: `accept` /// hands over `pending` once and then reports the listener closed, which is /// what a real one does after `shutdown`. const OneShot = struct { pending: ?*transport.memory.Connection, local: ?transport.Endpoint = null, const vtable: transport.Listener.VTable = .{ .accept = accept, .shutdown = shutdownImpl, .localAddress = localAddressImpl, }; fn listener(o: *OneShot) transport.Listener { return .{ .context = o, .vtable = &vtable }; } fn accept( context: ?*anyopaque, io: Io, gpa: Allocator, options: transport.Listener.Options, ) transport.Listener.AcceptError!transport.Connection { _ = .{ io, gpa, options }; const o: *OneShot = @ptrCast(@alignCast(context.?)); const c = o.pending orelse return error.ListenerClosed; o.pending = null; return c.connection(); } fn shutdownImpl(context: ?*anyopaque, io: Io) void { _ = io; const o: *OneShot = @ptrCast(@alignCast(context.?)); o.pending = null; } fn localAddressImpl(context: ?*anyopaque) ?transport.Endpoint { const o: *OneShot = @ptrCast(@alignCast(context.?)); return o.local; } }; test { std.testing.refAllDecls(@This()); }