// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Where the bytes come from, which this library otherwise has no opinion //! about. //! //! A `Connection` is a reader, a writer, and the handful of facts about the //! channel that HTTP needs and cannot learn by reading it: who is at the //! other end, whether the channel is confidential, and what — if anything — //! was negotiated about which version of HTTP to speak. Everything above this //! is written against those three things, so a server serves a TCP socket, a //! TLS session, a Unix socket, a pair of pipes handed over by `inetd`, or a //! slice of bytes in a test, without any of it being a special case. //! //! The implementations that own a file descriptor are not here. `http_io` //! has the TCP listener and the QUIC-backed session, and this module has the //! seams they fit and the in-memory one the tests use -- which is the whole //! of what keeps a parser bug from needing a port to reproduce. //! //! That is not only tidiness. It is what makes the test suite possible: the //! whole of an HTTP exchange can be driven over `transport.memory` with no //! socket, no port, and no scheduling, which is why the parser can be fuzzed //! at half a million inputs a second and why an end-to-end test of a keep- //! alive sequence is a string literal rather than a client. //! //! ## Where HTTP/2 and HTTP/3 fit //! //! HTTP/1.1 and HTTP/2 are both a single ordered byte stream, so both are //! served over exactly this. HTTP/3 is not: it runs on QUIC, where a //! connection is many independent streams and the loss of one does not stall //! the others, and a `Connection` as defined here cannot express that. The //! seam for it is `Connection.Info.alpn` and `server.Protocol`: a QUIC //! transport would offer its own listener, report `h3`, and be dispatched to //! a driver that takes the QUIC connection rather than this one. Nothing in //! `protocol` would change, which is the point of `protocol` being where it //! is. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const z46 = @import("z46"); /// An address and a port, which is what a transport knows about the far end /// of a connection when it knows anything at all. /// /// `std.Io.net.IpAddress` would carry the same octets and was what this used /// to be. What it cost was the claim the module is built on: one that says /// every byte reaches it through a seam it cannot see behind should not be /// naming the networking namespace. z46's are values rather than socket /// plumbing -- they parse, format canonically, compare and classify, and /// convert to and from the socket types at the edge where `http_io` needs /// them. pub const Endpoint = z46.Endpoint; pub const memory = @import("transport/memory.zig"); const session_mod = @import("transport/session.zig"); /// A connection carrying many independent streams, which is what HTTP/3 needs /// and a single byte stream cannot express. See `transport/session.zig`. pub const Session = session_mod.Session; pub const Stream = session_mod.Stream; /// A `Session` made of slices, which is to HTTP/3 what `memory` is to /// HTTP/1.1. pub const memory_session = @import("transport/memory_session.zig"); /// An established connection: somewhere to read a request from and somewhere /// to write a response to. pub const Connection = struct { /// The request side. Buffered by the transport, and the buffer bounds how /// long a single header line may be. input: *Io.Reader, /// The response side. Nothing above this flushes it except at the end of /// a response, so a small write is a small write and not a packet. output: *Io.Writer, info: Info, context: ?*anyopaque, vtable: *const VTable, /// What the transport knows that the byte stream does not say. pub const Info = struct { /// The address the client connected from, when there is one. Null for /// a Unix socket, a pipe or a test. /// /// Worth remembering what this is not: behind a reverse proxy it is /// the proxy. A handler that wants the client's address there has to /// read `Forwarded` or `X-Forwarded-For` and decide for itself /// whether to believe them, which is a policy question this library /// declines to answer for it. peer: ?Endpoint = null, /// The address the client connected to. /// /// A server bound to the unspecified address has nothing true to say /// here, and Zig 0.17 has no `getsockname` for an accepted socket in /// any case, so this is what the listener was given rather than what /// the kernel chose. local: ?Endpoint = null, /// Whether the channel is confidential and its far end authenticated /// — which is to say, whether this is TLS. /// /// It decides the scheme a request is understood to have arrived /// over, and so what an absolute URI built from it looks like and /// whether a `Secure` cookie may be set. secure: bool = false, /// What ALPN settled on, when the transport negotiates it: `http/1.1`, /// `h2`, `h3`. Null when nothing was negotiated, which is every /// cleartext connection. /// /// This is the one place a transport gets to say which version of /// HTTP is about to be spoken, and it is how an HTTP/2 driver would /// come to be chosen without anything guessing. alpn: ?[]const u8 = null, }; pub const VTable = struct { /// Closes the channel and releases whatever the transport allocated /// for it. `gpa` is the allocator the connection was accepted with. close: *const fn (context: ?*anyopaque, io: Io, gpa: Allocator) void, /// Tells the peer that nothing more will be sent, leaving the read /// side open. /// /// This is what an HTTP/1.0 response of unknown length ends with, and /// what lets a client tell a complete response from a truncated one. /// A transport with no such notion leaves it null and the connection /// is simply closed instead. shutdownWrite: ?*const fn (context: ?*anyopaque, io: Io) void = null, /// Whether the last read or write that failed did so because the /// task was canceled. /// /// An `Io.Reader` or `Io.Writer` can only say `ReadFailed` or /// `WriteFailed`, and a cancel is used up by the operation that /// observed it, so a layer above -- a TLS handshake, say -- that turned /// every failure into its own error would lose the cancel, and with it /// any deadline the caller had set. This is how it asks. Null answers /// false. canceled: ?*const fn (context: ?*anyopaque) bool = null, }; /// Closes the channel through the transport's `VTable.close` and leaves /// `c` undefined, so nothing may be read or written through it /// afterwards. `gpa` must be the allocator the connection was accepted /// or dialled with. pub fn close(c: *Connection, io: Io, gpa: Allocator) void { c.vtable.close(c.context, io, gpa); c.* = undefined; } test close { var input: Io.Reader = .fixed(""); var buffer: [16]u8 = undefined; var output: Io.Writer = .fixed(&buffer); // A borrowed connection's close releases nothing, because its reader // and writer belong to whoever lent them. var c: Connection = .borrowed(&input, &output, .{}); c.close(std.testing.io, std.testing.allocator); } /// Tells the peer that nothing more will be sent, leaving the read side /// open. On a transport whose `VTable.shutdownWrite` is null this does /// nothing, and the caller closes the connection instead. pub fn shutdownWrite(c: *Connection, io: Io) void { const f = c.vtable.shutdownWrite orelse return; f(c.context, io); } test shutdownWrite { var m: memory.Connection = try .init(std.testing.allocator, "", .{}); defer m.deinit(); var c = m.connection(); c.shutdownWrite(std.testing.io); try std.testing.expect(m.write_shutdown); } /// Whether the last read or write that failed did so because the task /// was canceled. See `VTable.canceled`; a transport that leaves it null /// answers false. pub fn canceled(c: Connection) bool { const f = c.vtable.canceled orelse return false; return f(c.context); } test canceled { var input: Io.Reader = .fixed(""); var buffer: [16]u8 = undefined; var output: Io.Writer = .fixed(&buffer); // Memory cannot be canceled out from under a reader. const c: Connection = .borrowed(&input, &output, .{}); try std.testing.expect(!c.canceled()); } /// The URI scheme a request arriving here is understood to have used. pub fn scheme(c: Connection) []const u8 { return if (c.info.secure) "https" else "http"; } test scheme { var input: Io.Reader = .fixed(""); var buffer: [16]u8 = undefined; var output: Io.Writer = .fixed(&buffer); const plain: Connection = .borrowed(&input, &output, .{}); try std.testing.expectEqualStrings("http", plain.scheme()); const tls: Connection = .borrowed(&input, &output, .{ .secure = true }); try std.testing.expectEqualStrings("https", tls.scheme()); } const borrowed_vtable: VTable = .{ .close = closeBorrowed }; fn closeBorrowed(context: ?*anyopaque, io: Io, gpa: Allocator) void { _ = .{ context, io, gpa }; } /// Wraps a reader and a writer that somebody else owns and will close. /// /// This is the whole of what it takes to serve HTTP over something this /// library has never heard of: get the bytes into an `Io.Reader` and out /// of an `Io.Writer` by whatever means, and hand the pair over. pub fn borrowed(input: *Io.Reader, output: *Io.Writer, info: Info) Connection { return .{ .input = input, .output = output, .info = info, .context = null, .vtable = &borrowed_vtable, }; } test borrowed { var input: Io.Reader = .fixed("GET / HTTP/1.1\r\n"); var buffer: [32]u8 = undefined; var output: Io.Writer = .fixed(&buffer); var c: Connection = .borrowed(&input, &output, .{ .alpn = "http/1.1" }); defer c.close(std.testing.io, std.testing.allocator); try std.testing.expectEqualStrings("GET / HTTP/1.1\r\n", try c.input.takeDelimiterInclusive('\n')); try c.output.writeAll("HTTP/1.1 200 OK\r\n"); // The bytes went straight to the writer that was lent. try std.testing.expectEqualStrings("HTTP/1.1 200 OK\r\n", output.buffered()); try std.testing.expectEqualStrings("http/1.1", c.info.alpn.?); } }; /// A source of connections: an accept loop with the socket taken out of it. pub const Listener = struct { context: ?*anyopaque, vtable: *const VTable, pub const Options = struct { /// The per-connection read buffer. It bounds the length of a single /// header line, and below `http1.min_read_buffer_len` a request line /// of any use will not fit. read_buffer_len: usize = 8192, /// The per-connection write buffer. Since a response is flushed once /// at its end, this is mostly how much of a small response leaves in /// one write. write_buffer_len: usize = 8192, }; pub const AcceptError = error{ /// The listener was shut down, by `shutdown` or by never having /// listened. An accept loop treats this as "we are done" rather than /// as a failure. ListenerClosed, /// This connection is gone — it died between the handshake and the /// accept, or a firewall rule refused it. Says nothing about the /// next one, so an accept loop tries again. ConnectionAborted, /// Accepting failed for a reason that is not going to go away: out of /// file descriptors, or the network stack has gone. AcceptFailed, } || Allocator.Error || Io.Cancelable; pub const VTable = struct { /// Waits for a connection and returns it. Whatever it allocates with /// `gpa`, `Connection.close` gives back. accept: *const fn ( context: ?*anyopaque, io: Io, gpa: Allocator, options: Options, ) AcceptError!Connection, /// Makes `accept` return `error.ListenerClosed`, from another task. /// This is how a running server is stopped. shutdown: *const fn (context: ?*anyopaque, io: Io) void, /// Where this listener is listening, when that is an address. A /// listener bound to port zero reports the port the kernel chose, /// which is how a test gets a server without picking a port /// something else may already have. localAddress: *const fn (context: ?*anyopaque) ?Endpoint, /// The part of accepting that belongs to one connection rather than /// to the listener: a TLS handshake. It takes as long as the peer /// chooses, so it must not be done in `accept`, where one client /// that connects and says nothing would stop every other client /// being accepted. An accept loop runs this in the connection's own /// task; see `acceptPending` and `establish`. /// /// Takes `conn`, as `accept` returned it, and returns the connection /// to serve; on an error it has closed `conn`. Null when what /// `accept` returns is ready as it is. establish: ?*const fn ( context: ?*anyopaque, io: Io, gpa: Allocator, conn: Connection, ) AcceptError!Connection = null, }; /// Waits for the next connection and makes it ready to serve. Whatever it /// allocates with `gpa` the connection's `close` gives back, so the same /// allocator goes to both. /// /// Both stages in the calling task, which is what a caller serving one /// connection wants. An accept loop serving many wants `acceptPending` /// and `establish` instead. pub fn accept(l: Listener, io: Io, gpa: Allocator, options: Options) AcceptError!Connection { return l.establish(io, gpa, try l.acceptPending(io, gpa, options)); } /// Waits for the next connection and returns it before any per-connection /// setup, such as a TLS handshake, which `establish` does. This returns as /// soon as the peer has connected, whatever it then does or does not say. pub fn acceptPending(l: Listener, io: Io, gpa: Allocator, options: Options) AcceptError!Connection { return l.vtable.accept(l.context, io, gpa, options); } test acceptPending { var one: OneConnection = try .init("GET / HTTP/1.1\r\n\r\n"); defer one.deinit(); const l = one.listener(); const pending = try l.acceptPending(std.testing.io, std.testing.allocator, .{}); var c = try l.establish(std.testing.io, std.testing.allocator, pending); defer c.close(std.testing.io, std.testing.allocator); try std.testing.expectEqualStrings("GET / HTTP/1.1\r\n", try c.input.takeDelimiterInclusive('\n')); } /// Finishes what `acceptPending` began: the per-connection setup, run in /// whichever task is to serve the connection. Takes ownership of `conn`, /// and on an error has already closed it. A listener with nothing to do /// here hands `conn` back as it is. pub fn establish(l: Listener, io: Io, gpa: Allocator, conn: Connection) AcceptError!Connection { const f = l.vtable.establish orelse return conn; return f(l.context, io, gpa, conn); } test establish { var one: OneConnection = try .init(""); defer one.deinit(); const l = one.listener(); // Nothing to set up on this listener, so the connection is the same. const pending = try l.acceptPending(std.testing.io, std.testing.allocator, .{}); var c = try l.establish(std.testing.io, std.testing.allocator, pending); defer c.close(std.testing.io, std.testing.allocator); try std.testing.expectEqual(pending.context, c.context); } test accept { var one: OneConnection = try .init("GET / HTTP/1.1\r\n\r\n"); defer one.deinit(); const l = one.listener(); var c = try l.accept(std.testing.io, std.testing.allocator, .{}); defer c.close(std.testing.io, std.testing.allocator); try std.testing.expectEqualStrings("GET / HTTP/1.1\r\n", try c.input.takeDelimiterInclusive('\n')); } /// Stops the listener: an `accept` waiting now, and every one after it, /// returns `error.ListenerClosed`. Meant to be called from a task other /// than the one accepting, which is how a running server is stopped. pub fn shutdown(l: Listener, io: Io) void { l.vtable.shutdown(l.context, io); } test shutdown { var one: OneConnection = try .init(""); defer one.deinit(); const l = one.listener(); l.shutdown(std.testing.io); try std.testing.expectError( error.ListenerClosed, l.accept(std.testing.io, std.testing.allocator, .{}), ); } /// Where this listener is listening, or null when that is not an /// address. A listener bound to port zero reports the port the kernel /// chose. pub fn localAddress(l: Listener) ?Endpoint { return l.vtable.localAddress(l.context); } test localAddress { var one: OneConnection = try .init(""); defer one.deinit(); const l = one.listener(); const bound = l.localAddress().?; try std.testing.expectEqual(@as(u16, 8080), bound.port()); } }; /// A listener with one in-memory connection behind it, for the examples /// above: everything a `Listener.VTable` has to do, and nothing more. const OneConnection = struct { memory: memory.Connection, taken: bool = false, closed: bool = false, fn init(request: []const u8) Allocator.Error!OneConnection { return .{ .memory = try .init(std.testing.allocator, request, .{}) }; } fn deinit(o: *OneConnection) void { o.memory.deinit(); } fn listener(o: *OneConnection) Listener { return .{ .context = o, .vtable = &vtable }; } const vtable: Listener.VTable = .{ .accept = acceptImpl, .shutdown = shutdownImpl, .localAddress = localAddressImpl, }; fn acceptImpl( context: ?*anyopaque, io: Io, gpa: Allocator, options: Listener.Options, ) Listener.AcceptError!Connection { _ = .{ io, gpa, options }; const o: *OneConnection = @ptrCast(@alignCast(context.?)); if (o.closed or o.taken) return error.ListenerClosed; o.taken = true; return o.memory.connection(); } fn shutdownImpl(context: ?*anyopaque, io: Io) void { _ = io; const o: *OneConnection = @ptrCast(@alignCast(context.?)); o.closed = true; } fn localAddressImpl(context: ?*anyopaque) ?Endpoint { _ = context; return Endpoint.parse("127.0.0.1:8080") catch unreachable; } }; test { std.testing.refAllDecls(@This()); }