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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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 0.16 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, };
pub fn close(c: *Connection, io: Io, gpa: Allocator) void { c.vtable.close(c.context, io, gpa); c.* = undefined; }
pub fn shutdownWrite(c: *Connection, io: Io) void { const f = c.vtable.shutdownWrite orelse return; f(c.context, io); }
/// 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"; }
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, }; }};
/// 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, };
pub fn accept(l: Listener, io: Io, gpa: Allocator, options: Options) AcceptError!Connection { return l.vtable.accept(l.context, io, gpa, options); }
pub fn shutdown(l: Listener, io: Io) void { l.vtable.shutdown(l.context, io); }
pub fn localAddress(l: Listener) ?Endpoint { return l.vtable.localAddress(l.context); }};
test { std.testing.refAllDecls(@This());}