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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A listener over TCP, which is what almost every HTTP server is actually//! sitting on.//!//! There is nothing HTTP about this file. It accepts sockets and dresses each//! one as a `transport.Connection`; a TLS listener would be the same fifty//! lines with a handshake in the middle and `secure` set, and it would plug//! into the same `server.Server` without either of them knowing about the//! other.
const std = @import("std");const Io = std.Io;const net = Io.net;const Allocator = std.mem.Allocator;
// Through the module rather than by path: a relative import would pull the// protocol module's files into this one, and a file belongs to exactly one// module.const http = @import("http");const transport = http.transport;
pub const Listener = struct { server: net.Server, /// What `listen` was asked for, reported as each connection's local /// address. After a bind to port zero this has the port the kernel chose /// filled in. address: net.IpAddress,
pub const Options = struct { /// How many connections the kernel holds for us between accepts. kernel_backlog: u31 = net.default_kernel_backlog, /// Whether to set `SO_REUSEADDR`, so that a restarted server does not /// have to wait out the previous one's sockets in `TIME_WAIT`. On by /// default, because the alternative is a server that cannot be /// restarted for two minutes. reuse_address: bool = true, };
pub const ListenError = net.IpAddress.ListenError;
/// Starts listening. /// /// The port may be zero, in which case the kernel picks one and /// `localAddress` reports which — how a test gets a server without /// choosing a port something else may already have. pub fn listen(io: Io, address: net.IpAddress, options: Options) ListenError!Listener { const server = try net.IpAddress.listen(&address, io, .{ .kernel_backlog = options.kernel_backlog, .reuse_address = options.reuse_address, }); return .{ .server = server, // After `listen` the socket's address is this end, filled in by // the kernel, which is where the chosen port comes from. .address = server.socket.address, }; }
test listen { const io = testing.io; var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); defer l.deinit(io); // Port zero asked the kernel to choose, and it has. try testing.expect(l.localAddress().getPort() != 0); }
/// Closes the listening socket. Connections already accepted are their /// own, and are not closed by this. pub fn deinit(l: *Listener, io: Io) void { l.server.deinit(io); l.* = undefined; }
test deinit { var l: Listener = try .listen(testing.io, .{ .ip4 = .loopback(0) }, .{}); l.deinit(testing.io); }
/// Where this listener is: the address `listen` was given, with the port /// the kernel chose when that was zero. pub fn localAddress(l: *const Listener) net.IpAddress { return l.address; }
test localAddress { const io = testing.io; var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); defer l.deinit(io);
// Which is the address a client dials to reach it. var conn = try connect(io, testing.allocator, l.localAddress(), .{}); defer conn.close(io, testing.allocator); try testing.expectEqual(l.localAddress().getPort(), conn.info.peer.?.port()); }
/// Makes an accept in progress return `error.ListenerClosed`, and every /// accept after it. /// /// Shutting the listening socket down is what an operating system has /// instead of a cancel: `accept` comes back with /// `error.SocketNotListening` and the loop above it stops. The socket is /// still open, so `deinit` is still wanted afterwards. pub fn shutdown(l: *Listener, io: Io) void { const as_stream: net.Stream = .{ .socket = l.server.socket }; as_stream.shutdown(io, .both) catch {}; }
test shutdown { const io = testing.io; var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); defer l.deinit(io);
l.shutdown(io); try testing.expectError(error.ListenerClosed, l.listener().accept(io, testing.allocator, .{})); }
/// The transport-level view of this listener, which is what /// `server.Server` takes. It borrows `l`, which must not move while it /// is in use. pub fn listener(l: *Listener) transport.Listener { return .{ .context = l, .vtable = &vtable }; }
test listener { const io = testing.io; const gpa = testing.allocator; var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); defer l.deinit(io);
// The kernel completes the handshake from its backlog, so a client // can connect before anything accepts. var client = try connect(io, gpa, l.localAddress(), .{}); defer client.close(io, gpa); var accepted = try l.listener().accept(io, gpa, .{}); defer accepted.close(io, gpa);
try client.output.writeAll("ping"); try client.output.flush(); try testing.expectEqualStrings("ping", try accepted.input.take(4)); try testing.expect(!accepted.info.secure); }
const vtable: transport.Listener.VTable = .{ .accept = acceptImpl, .shutdown = shutdownImpl, .localAddress = localAddressImpl, };
fn acceptImpl( context: ?*anyopaque, io: Io, gpa: Allocator, options: transport.Listener.Options, ) transport.Listener.AcceptError!transport.Connection { const l: *Listener = @ptrCast(@alignCast(context.?)); const stream = l.server.accept(io) catch |err| switch (err) { error.SocketNotListening => return error.ListenerClosed, error.Canceled => return error.Canceled, error.ConnectionAborted, error.BlockedByFirewall, error.ProtocolFailure, error.WouldBlock, => return error.ConnectionAborted, else => return error.AcceptFailed, }; errdefer stream.close(io); return Connection.open(gpa, io, stream, l.address, options, null); }
fn shutdownImpl(context: ?*anyopaque, io: Io) void { const l: *Listener = @ptrCast(@alignCast(context.?)); l.shutdown(io); }
fn localAddressImpl(context: ?*anyopaque) ?transport.Endpoint { const l: *Listener = @ptrCast(@alignCast(context.?)); // The edge: sockets speak `std.Io.net`, everything above this speaks // values, and this is the one line that knows both. return .fromStdAddress(l.address); }};
/// Dials a server and hands back the same `transport.Connection` an accepted/// socket becomes.////// The client's half of accepting through `Listener.listener`, and/// deliberately the same return type: what a driver is handed does not depend/// on which end opened it, so `http1.client` works over this, over a TLS/// session, and over a slice of memory in a test without knowing the/// difference. Closing the connection returned closes the socket and frees/// its buffers, which are sized by `options`.pub fn connect( io: Io, gpa: Allocator, address: net.IpAddress, options: transport.Listener.Options,) (net.IpAddress.ConnectError || Allocator.Error)!transport.Connection { const stream = try net.IpAddress.connect(&address, io, .{ .mode = .stream }); errdefer stream.close(io); // After `connect` a socket's address is this end, so the peer is the // address that was dialled -- the reverse of `accept`, where the socket // carries the peer and the listener knows the local end. return Connection.open(gpa, io, stream, stream.socket.address, options, .fromStdAddress(address));}
test connect { const io = testing.io; const gpa = testing.allocator; var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); defer l.deinit(io);
var conn = try connect(io, gpa, l.localAddress(), .{}); defer conn.close(io, gpa); // The peer is the address that was dialled, and nothing was negotiated. try testing.expectEqual(l.localAddress().getPort(), conn.info.peer.?.port()); try testing.expect(!conn.info.secure); try testing.expectEqual(@as(?[]const u8, null), conn.info.alpn);
var accepted = try l.listener().accept(io, gpa, .{}); defer accepted.close(io, gpa); try conn.output.writeAll("hello"); try conn.output.flush(); try testing.expectEqualStrings("hello", try accepted.input.take(5));}
/// Dials each address in turn and hands back the first that answers.////// What a name resolves to is a list, and the first entry is often the one/// that does not work: a resolver that returns `::1` ahead of `127.0.0.1` for/// a server listening on IPv4 alone is the ordinary case, not an exotic one./// The resolver hands the list over in the order it would rather be tried,/// and this tries it in that order and does nothing cleverer -- the attempts/// are sequential rather than raced, so an address that drops/// packets rather than refusing them costs its whole timeout before the next/// is tried.////// The error is the last attempt's, which is the one a caller reading it will/// assume it is. Asserts there is at least one address.pub fn connectAny( io: Io, gpa: Allocator, addresses: []const net.IpAddress, options: transport.Listener.Options,) (net.IpAddress.ConnectError || Allocator.Error)!transport.Connection { std.debug.assert(addresses.len > 0); var last: (net.IpAddress.ConnectError || Allocator.Error) = undefined; for (addresses) |address| { return connect(io, gpa, address, options) catch |err| switch (err) { // Not a property of the address, so the next one would fail the // same way. error.OutOfMemory, error.Canceled => |e| return e, else => |e| { last = e; continue; }, }; } return last;}
test connectAny { const io = testing.io; const gpa = testing.allocator;
// A port nothing is listening on: one a listener had, and gave back. var gone: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); const refused = gone.localAddress(); gone.deinit(io);
var l: Listener = try .listen(io, .{ .ip4 = .loopback(0) }, .{}); defer l.deinit(io);
// The first address refuses, and the second is the one that answers. var conn = try connectAny(io, gpa, &.{ refused, l.localAddress() }, .{}); defer conn.close(io, gpa); try testing.expectEqual(l.localAddress().getPort(), conn.info.peer.?.port());
// When none answers, the error is the last one's. try testing.expectError(error.ConnectionRefused, connectAny(io, gpa, &.{refused}, .{}));}
/// One socket, accepted or dialled, and the buffers it is read and written/// through.////// Boxed rather than returned by value because `net.Stream.Reader` holds an/// `Io.Reader` whose address is handed out: the moment the struct moves,/// every pointer into it is wrong. Putting it on the heap and handing back/// pointers is the cheapest way to make that impossible.pub const Connection = struct { stream: net.Stream, reader: net.Stream.Reader, writer: net.Stream.Writer, read_buffer: []u8, write_buffer: []u8,
fn open( gpa: Allocator, io: Io, stream: net.Stream, local: net.IpAddress, options: transport.Listener.Options, /// Null for an accepted socket, whose own address is the peer's. dialled: ?transport.Endpoint, ) Allocator.Error!transport.Connection { const c = try gpa.create(Connection); errdefer gpa.destroy(c);
const read_buffer = try gpa.alloc(u8, options.read_buffer_len); errdefer gpa.free(read_buffer); const write_buffer = try gpa.alloc(u8, options.write_buffer_len); errdefer gpa.free(write_buffer);
c.* = .{ .stream = stream, .reader = stream.reader(io, read_buffer), .writer = stream.writer(io, write_buffer), .read_buffer = read_buffer, .write_buffer = write_buffer, };
return .{ .input = &c.reader.interface, .output = &c.writer.interface, .info = .{ // After `accept` a socket's address is the peer's, which is // the opposite of what it means after `listen`. .peer = dialled orelse .fromStdAddress(stream.socket.address), .local = .fromStdAddress(local), .secure = false, .alpn = null, }, .context = c, .vtable = &vtable, }; }
const vtable: transport.Connection.VTable = .{ .close = closeImpl, .shutdownWrite = shutdownWriteImpl, .canceled = canceledImpl, };
fn canceledImpl(context: ?*anyopaque) bool { const c: *Connection = @ptrCast(@alignCast(context.?)); if (c.reader.err) |err| if (err == error.Canceled) return true; if (c.writer.err) |err| if (err == error.Canceled) return true; return false; }
fn closeImpl(context: ?*anyopaque, io: Io, gpa: Allocator) void { const c: *Connection = @ptrCast(@alignCast(context.?)); c.stream.close(io); gpa.free(c.read_buffer); gpa.free(c.write_buffer); gpa.destroy(c); }
fn shutdownWriteImpl(context: ?*anyopaque, io: Io) void { const c: *Connection = @ptrCast(@alignCast(context.?)); c.stream.shutdown(io, .send) catch {}; }};
const testing = std.testing;
test { std.testing.refAllDecls(@This());}