// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! An HTTP/3 server: a UDP socket, and a handler. //! //! A listener of its own rather than a driver registered with `server.Server` //! because a QUIC connection is many streams where a `transport.Connection` //! is one, so there is nothing for the byte-stream listener to hand it. What //! it hands the driver instead is a `transport.Session`, which is the seam //! the driver is written against -- so everything QUIC about this file stops //! here. const std = @import("std"); const Io = std.Io; const net = Io.net; const Allocator = std.mem.Allocator; const quic = @import("quic"); const quic_io = @import("quic_io"); const http = @import("http"); const Handler = http.server.Handler; const Config = http.http3.Config; const Connection = http.http3.Connection; const session_mod = @import("session.zig"); /// How many connections a listener will track for shutdown. The endpoint's /// own bound is what actually limits concurrency; this only has to be at /// least as large. const max_live = 64; pub const Listener = struct { io: Io, gpa: Allocator, handler: Handler, config: Config, endpoint: quic_io.Endpoint, /// The connections being served, so that `shutdown` can reach them. A /// fixed table like everything else, and the same size as the endpoint's. live: [max_live]?*Connection = @splat(null), going_away: bool = false, mutex: Io.Mutex = .init, /// The transport parameters this listener advertises: what the caller /// asked for, with the flow control limits replaced by what the memory it /// asked for can actually hold. fn advertised(config: Config) quic.parameters.Parameters { var p = config.transport; const window = config.sizes.recv_window; p.initial_max_stream_data_bidi_local = window; p.initial_max_stream_data_bidi_remote = window; p.initial_max_stream_data_uni = window; // Every stream's worth at once, which is what the buffers hold and so // what may honestly be promised. p.initial_max_data = quic.Connection.max_streams * window; return p; } /// Makes a listener on a UDP socket the caller has already bound. Nothing /// is read from the socket until `run`. /// /// Initialises in place, because the endpoint holds a pointer back to /// this struct -- a listener returned by value would hand back one whose /// endpoint pointed at the local it was built in. The socket and whatever /// `handler` and `config` point at are borrowed, and have to outlive the /// listener. The ALPN offered is always `h3`. pub fn init( l: *Listener, io: Io, gpa: Allocator, socket: *net.Socket, handler: Handler, config: Config, ) !void { l.* = .{ .io = io, .gpa = gpa, .handler = handler, .config = config, .endpoint = undefined, .live = @splat(null), }; l.endpoint = try .init(io, gpa, socket, .{ .auth = config.auth, // §3.1 of RFC 9114: "HTTP/3 uses the ALPN token 'h3'". Not an // option, because a server offering anything else would not be // offering HTTP/3 -- which is why this is set here rather than // left where a caller could get it wrong. .alpn = &.{"h3"}, .local = advertised(config), .sizes = config.sizes, .max_send_window = config.max_send_window, .rng = config.rng, .reset_key = config.reset_key, .token_key = config.token_key, .ticket_key = config.ticket_key, .early_data = config.early_data, .require_retry = config.require_retry, .max_connections = config.max_connections, }, .{ .context = l, .serveFn = serveSession, }); } test init { const io = testing.io; const gpa = testing.allocator; var prng: std.Random.DefaultPrng = .init(1); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var listener: Listener = undefined; try listener.init(io, gpa, &socket, .initStateless(hello), .{ // No `auth`: a handshake that authenticates nobody, which is // what a test wants and nothing else does. .rng = prng.random(), .reset_key = @splat(0x11), .token_key = @splat(0x22), }); defer listener.deinit(); var tasks: Io.Group = .init; defer tasks.cancel(io); tasks.concurrent(io, serve, .{&listener}) catch return error.SkipZigTest; defer listener.stop(); var buffer: [16]u8 = undefined; try testing.expectEqualStrings("hello", try ask(socket.address, &buffer)); } /// Lets go of every connection and what the endpoint allocated. `run` /// must have returned first. The socket is the caller's, and is not /// closed. pub fn deinit(l: *Listener) void { l.endpoint.deinit(); } test deinit { const io = testing.io; var prng: std.Random.DefaultPrng = .init(1); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var listener: Listener = undefined; try listener.init(io, testing.allocator, &socket, .initStateless(hello), .{ .rng = prng.random(), .reset_key = @splat(0x11), .token_key = @splat(0x22), }); listener.deinit(); } /// Reads datagrams, runs timers and serves connections until `stop`, or /// until the socket fails. Wants a task of its own: it is the only thing /// that reads the socket, and each connection is served on a task of the /// endpoint's. pub fn run(l: *Listener) !void { return l.endpoint.pump(); } test run { const io = testing.io; var prng: std.Random.DefaultPrng = .init(1); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var listener: Listener = undefined; try listener.init(io, testing.allocator, &socket, .initStateless(hello), .{ .rng = prng.random(), .reset_key = @splat(0x11), .token_key = @splat(0x22), }); defer listener.deinit(); // On a task of its own, which `serve` wraps; the request below is // answered by it. var tasks: Io.Group = .init; defer tasks.cancel(io); tasks.concurrent(io, serve, .{&listener}) catch return error.SkipZigTest; defer listener.stop(); var buffer: [16]u8 = undefined; try testing.expectEqualStrings("hello", try ask(socket.address, &buffer)); } /// Asks `run` to return, which it does after its current turn -- at /// most a second, since zig-quic caps how long a turn waits for a /// datagram whatever timers its connections have due. Cancelling the task /// running `run` ends it at once. Connections are not told; `shutdown` is /// the way to finish them first. pub fn stop(l: *Listener) void { l.endpoint.stop(); } test stop { const io = testing.io; var prng: std.Random.DefaultPrng = .init(1); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var listener: Listener = undefined; try listener.init(io, testing.allocator, &socket, .initStateless(hello), .{ .rng = prng.random(), .reset_key = @splat(0x11), .token_key = @splat(0x22), }); defer listener.deinit(); var tasks: Io.Group = .init; defer tasks.cancel(io); tasks.concurrent(io, serve, .{&listener}) catch return error.SkipZigTest; listener.stop(); // `run` returns by itself, with no cancellation to make it. try tasks.await(io); } test "stop takes effect within a second or so while a connection idles" { // Before zig-quic 0f78ec5 a turn waited for a datagram until the next // timer a connection had due, so with one open and quiet, `stop` took // as long as the idle timeout -- thirty seconds, here. var served: Served = undefined; try served.start(); defer served.stop(); const io = testing.io; var prng: std.Random.DefaultPrng = .init(3); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: Dialer = undefined; try dialer.connect(io, testing.allocator, &socket, served.socket.address, .{ .host = "localhost", .insecure_skip_verify = true, .rng = prng.random(), }); defer dialer.deinit(); var pumping: Io.Group = .init; defer pumping.cancel(io); pumping.concurrent(io, pump, .{&dialer}) catch return error.SkipZigTest; defer dialer.stop(); // One exchange, and then long enough for its acknowledgements and // loss timers to settle, so that the idle timer is the only one due. var c: http.http3.client.Connection = .init(testing.allocator, dialer.session(), .{}); try c.start(); var exchange = try c.send(.{ .host = "localhost", .target = "/" }); exchange.deinit(testing.allocator); try io.sleep(.fromSeconds(2), .awake); const began = Io.Timestamp.now(io, .awake); served.listener.stop(); try served.tasks.await(io); const took = Io.Timestamp.now(io, .awake).nanoseconds - began.nanoseconds; try testing.expect(took < 5 * std.time.ns_per_s); } fn serveSession(context: ?*anyopaque, session: *quic_io.Session) void { const l: *Listener = @ptrCast(@alignCast(context.?)); var connection: Connection = .init(l.io, l.gpa, session_mod.session(session), l.handler, l.config.connection); // Registered while it is being served, so that `shutdown` can reach // it. A connection that arrived after the shutdown began is not // registered and is refused at once, which is the same answer by a // shorter route. if (!l.register(&connection)) { session.closeApplication( @backingInt(http.http3.frame.Error.no_error), "shutting down", ); return; } defer l.unregister(&connection); connection.run(); } /// §5.2: asks every live connection to finish what it is doing and take /// nothing new. /// /// Graceful rather than immediate, which is the whole point: a GOAWAY /// names the request this endpoint has not started, so everything already /// in flight is answered and everything after it is refused with a code /// the client can retry on. A listener that simply closed its socket /// would leave every client that had a request outstanding unable to tell /// whether it happened. /// /// A connection that completes its handshake afterwards is closed at /// once. `run` carries on, so that what is in flight can finish; `stop` /// ends it. pub fn shutdown(l: *Listener) void { l.mutex.lockUncancelable(l.io); l.going_away = true; for (l.live) |maybe| { const connection = maybe orelse continue; connection.shutdown(); } l.mutex.unlock(l.io); } test shutdown { const io = testing.io; var prng: std.Random.DefaultPrng = .init(1); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var listener: Listener = undefined; try listener.init(io, testing.allocator, &socket, .initStateless(hello), .{ .rng = prng.random(), .reset_key = @splat(0x11), .token_key = @splat(0x22), }); defer listener.deinit(); var tasks: Io.Group = .init; defer tasks.cancel(io); tasks.concurrent(io, serve, .{&listener}) catch return error.SkipZigTest; defer listener.stop(); listener.shutdown(); // A new connection is closed rather than served. Which error the // client sees depends on how far it got before the close arrived. var buffer: [16]u8 = undefined; if (ask(socket.address, &buffer)) |_| return error.TestUnexpectedResult else |_| {} } fn register(l: *Listener, connection: *Connection) bool { l.mutex.lockUncancelable(l.io); defer l.mutex.unlock(l.io); if (l.going_away) return false; for (&l.live) |*slot| { if (slot.* != null) continue; slot.* = connection; return true; } return false; } fn unregister(l: *Listener, connection: *Connection) void { l.mutex.lockUncancelable(l.io); defer l.mutex.unlock(l.io); for (&l.live) |*slot| { if (slot.* == connection) slot.* = null; } } }; /// Dials an HTTP/3 server and hands back a session for the driver. /// /// The client half of `Listener`, and the same division: this owns the QUIC /// connection over a socket the caller has bound, and everything above it is /// written against `transport.Session` and cannot tell a real one from a /// scripted one. /// /// `run` wants a task of its own once `connect` has returned -- see the note /// on `quic_io.Client`. A stream read blocks until a datagram arrives, and /// the only thing that makes one arrive is that pump, so a caller doing both /// on one task waits for itself. pub const Dialer = struct { client: quic_io.Client, pub const Options = struct { /// The name to ask for, checked against the certificate. host: []const u8, /// Where the trust for that check comes from. root_ca: @FieldType(quic.tls_handshake.Client.Options, "root_ca") = .{ .bytes = .empty, .map = .empty }, /// For a test, and named so that it cannot be set by accident. insecure_skip_verify: bool = false, rng: std.Random, sizes: quic.Connection.Sizes = .{}, max_send_window: ?usize = 64 << 10, /// How long the handshake may take before `connect` gives up with /// `error.HandshakeTimeout`, which is what a server that is not there /// -- or UDP that is blocked on the way -- looks like. handshake_timeout_ns: u64 = 10 * std.time.ns_per_s, }; /// Dials `server` from `socket` and completes the QUIC handshake, /// offering `h3` and nothing else, before returning. /// /// In place, because the connection holds pointers into itself. The /// socket is borrowed and has to outlive the dialer. A handshake that /// does not finish within `options.handshake_timeout_ns` is /// `error.HandshakeTimeout`. pub fn connect( d: *Dialer, io: Io, gpa: Allocator, socket: *net.Socket, server: net.IpAddress, options: Options, ) !void { const window = options.sizes.recv_window; try d.client.connect(io, gpa, socket, server, .{ // §3.1 of RFC 9114: "HTTP/3 uses the ALPN token `h3`". Not an // option, because a client offering anything else would not be // asking for HTTP/3. .alpn = &.{"h3"}, .host = options.host, .root_ca = options.root_ca, .insecure_skip_verify = options.insecure_skip_verify, .rng = options.rng, .sizes = options.sizes, .max_send_window = options.max_send_window, .handshake_timeout_ns = options.handshake_timeout_ns, .local = .{ // What this end can hold is what it may promise, the same // arithmetic `Listener.advertised` does for the server. .initial_max_stream_data_bidi_local = window, .initial_max_stream_data_bidi_remote = window, .initial_max_stream_data_uni = window, .initial_max_data = quic.Connection.max_streams * window, // §6.2 needs three unidirectional streams before anything // else: the control stream and the two QPACK streams. Each // one promised is a slot of the shared table kept free for // the server, so three and a spare leaves this end its own // three and nine requests. .initial_max_streams_uni = 4, .initial_max_streams_bidi = 0, .max_idle_timeout = 30_000, .active_connection_id_limit = 4, }, }); } test connect { var served: Served = undefined; try served.start(); defer served.stop(); const io = testing.io; var prng: std.Random.DefaultPrng = .init(2); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: Dialer = undefined; try dialer.connect(io, testing.allocator, &socket, served.socket.address, .{ .host = "localhost", // The server in these examples has no certificate to check. .insecure_skip_verify = true, .rng = prng.random(), }); defer dialer.deinit(); // The handshake is done by the time `connect` returns. try testing.expect(dialer.session().waitEstablished()); } /// Ends the connection and frees what it allocated. `run` must have /// returned first. The socket is the caller's, and is not closed. pub fn deinit(d: *Dialer) void { d.client.deinit(); } test deinit { var served: Served = undefined; try served.start(); defer served.stop(); const io = testing.io; var prng: std.Random.DefaultPrng = .init(2); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: Dialer = undefined; try dialer.connect(io, testing.allocator, &socket, served.socket.address, .{ .host = "localhost", .insecure_skip_verify = true, .rng = prng.random(), }); dialer.deinit(); } /// Asks `run` to return, which it does after its current turn -- at /// most a second, as long as it waits for a datagram. pub fn stop(d: *Dialer) void { d.client.stop(); } test stop { var served: Served = undefined; try served.start(); defer served.stop(); const io = testing.io; var prng: std.Random.DefaultPrng = .init(2); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: Dialer = undefined; try dialer.connect(io, testing.allocator, &socket, served.socket.address, .{ .host = "localhost", .insecure_skip_verify = true, .rng = prng.random(), }); defer dialer.deinit(); var tasks: Io.Group = .init; defer tasks.cancel(io); tasks.concurrent(io, pump, .{&dialer}) catch return error.SkipZigTest; dialer.stop(); // `run` returns by itself, with no cancellation to make it. try tasks.await(io); } /// Reads datagrams and runs timers until `stop`, or until the connection /// has closed. Wants a task of its own, for the reason the note on /// `Dialer` gives. pub fn run(d: *Dialer) !void { return d.client.run(); } test run { var served: Served = undefined; try served.start(); defer served.stop(); var buffer: [16]u8 = undefined; // `ask` is a `Dialer`, a task running `run`, and the HTTP/3 driver // over `session`: the whole of a client. try testing.expectEqualStrings("hello", try ask(served.socket.address, &buffer)); } /// The seam the driver is written against, which is what /// `http3.client.Connection.init` takes. It borrows the dialer, which /// must not move while it is in use. pub fn session(d: *Dialer) http.transport.Session { return session_mod.session(d.client.session); } test session { var served: Served = undefined; try served.start(); defer served.stop(); const io = testing.io; var prng: std.Random.DefaultPrng = .init(2); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: Dialer = undefined; try dialer.connect(io, testing.allocator, &socket, served.socket.address, .{ .host = "localhost", .insecure_skip_verify = true, .rng = prng.random(), }); defer dialer.deinit(); const s = dialer.session(); // §2.1 of RFC 9000: the client's first bidirectional stream is 0, // which is where its first request goes. const stream = try s.openBidirectional(); try testing.expectEqual(@as(u64, 0), stream.id.value); } }; const testing = std.testing; test { // So that the examples on `Listener` and `Dialer` are compiled: a nested // type's tests are reached only when something refers to the type // itself. testing.refAllDecls(@This()); } fn hello(_: *http.server.Request, res: *http.server.Response) anyerror!void { try res.send("hello"); } fn serve(l: *Listener) void { l.run() catch {}; } fn pump(d: *Dialer) void { d.run() catch {}; } /// An HTTP/3 server on a loopback port for the examples, answering every /// request with `hello`. Must not move once started. const Served = struct { socket: net.Socket, listener: Listener, prng: std.Random.DefaultPrng, tasks: Io.Group, fn start(s: *Served) !void { const io = testing.io; const any: net.IpAddress = .{ .ip4 = .loopback(0) }; s.socket = try any.bind(io, .{ .mode = .dgram }); errdefer s.socket.close(io); s.prng = .init(1); try s.listener.init(io, testing.allocator, &s.socket, .initStateless(hello), .{ .rng = s.prng.random(), .reset_key = @splat(0x11), .token_key = @splat(0x22), }); errdefer s.listener.deinit(); s.tasks = .init; s.tasks.concurrent(io, serve, .{&s.listener}) catch return error.SkipZigTest; } fn stop(s: *Served) void { s.listener.stop(); s.tasks.cancel(testing.io); s.listener.deinit(); s.socket.close(testing.io); } }; /// Asks the HTTP/3 server at `address` for `/` and returns the body of the /// answer, copied into `buffer`. fn ask(address: net.IpAddress, buffer: []u8) ![]const u8 { const io = testing.io; const gpa = testing.allocator; var prng: std.Random.DefaultPrng = .init(2); const any: net.IpAddress = .{ .ip4 = .loopback(0) }; var socket = try any.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: Dialer = undefined; try dialer.connect(io, gpa, &socket, address, .{ .host = "localhost", .insecure_skip_verify = true, .rng = prng.random(), }); defer dialer.deinit(); var tasks: Io.Group = .init; defer tasks.cancel(io); tasks.concurrent(io, pump, .{&dialer}) catch return error.SkipZigTest; defer dialer.stop(); var c: http.http3.client.Connection = .init(gpa, dialer.session(), .{}); try c.start(); var exchange = try c.send(.{ .host = "localhost", .target = "/" }); defer exchange.deinit(gpa); const body = exchange.body(); @memcpy(buffer[0..body.len], body); return buffer[0..body.len]; }