Something went wrong. Try again.
An HTTP library for Zig 0.17, server and client, HTTP/1.0 through HTTP/3, with the protocol in a module that owns no socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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 in whatever is one day written beside it,//! 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 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 HTTP/2 and HTTP/3 is here and in `Config.drivers`: this/// library implements `http1` and dispatches the other two to whatever has/// been registered for them, 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 (RFC 9110 §14.6). pub fn alpn(p: Protocol) []const u8 { return switch (p) { .http1 => "http/1.1", .h2 => "h2", .h3 => "h3", }; }
/// Which version an ALPN identifier names, or null for one nobody here /// knows. 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; }};
/// A driver for a version this library does not implement.////// Registering one is the whole of adding HTTP/2: 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. 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 = &.{},};
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, };}
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.////// Waits for the connections in flight before returning, so that a caller/// which frees the handler's state afterwards is not freeing it underneath/// one.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) { const conn = s.listener.accept(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, serveConnection, .{ 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 => serveConnection(s, conn), }; }}
/// Accepts exactly one connection and serves it in this task, returning when/// the connection ends.////// What a test wants, and what a program driven by `inetd` wants.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);}
/// 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), }}
/// 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./// 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) }); };}
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);}
/// Where the server is listening, when that is an address.pub fn localAddress(s: *const Server) ?transport.Endpoint { return s.listener.localAddress();}
test { std.testing.refAllDecls(@This());}