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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! HTTPS, both ways round: a TCP listener with a TLS handshake in front of//! every connection it accepts, and a dialler with one in front of every//! connection it opens.//!//! The two halves are the same file because they are the same job seen from//! either end, and they meet in `Connection.wrap`: everything after the//! handshake is identical, and what differs is only whether this end was//! proving who it is or deciding whom to believe.//!//! Nothing above this knows. `transport.Connection` already says whether a//! channel is confidential and what was negotiated over it, so a driver reads//! and writes exactly as it does over a plain socket, and `server.Server`//! chooses HTTP/2 or HTTP/1.1 from `Info.alpn` without a line of it being//! about TLS. That is why this file is short: the seam it fits was designed//! for it long before it existed, and `Info.secure` and `Info.alpn` have been//! sitting there with nothing to fill them in.//!//! ## ALPN is the whole of how HTTP/2 gets selected//!//! §3.1 of RFC 9113 gives HTTP/2 over TLS the identifier `h2`, and there is//! no other way in: the `PRI ` preface only works on a cleartext port, and//! §3.2's `Upgrade` was removed. So a server that does not offer `h2` in its//! ALPN list is a server no browser will speak HTTP/2 to, whatever else it//! supports.
const std = @import("std");const Io = std.Io;const net = Io.net;const Allocator = std.mem.Allocator;
const tls = @import("tls");const http = @import("http");const transport = http.transport;const tcp = @import("tcp.zig");
/// The certificate and key a listener answers with. Re-exported so that a/// caller does not have to name the TLS library to configure one.pub const CertKeyPair = tls.config.CertKeyPair;
/// The trust a client checks a server's chain against, re-exported for the/// same reason. It is `std.crypto.Certificate.Bundle`, which has `rescan` for/// the system store; `certBundleFromFilePath` is the one-file case.pub const CertBundle = tls.config.cert.Bundle;
/// Reads a bundle of trusted certificates out of one PEM file.pub const certBundleFromFilePath = tls.config.cert.fromFilePath;
pub const Options = struct { /// The certificate chain and its private key. auth: *CertKeyPair, /// What to offer in ALPN, in preference order. /// /// The default offers HTTP/2 ahead of HTTP/1.1, which is what a browser /// expects and what this library can serve. A caller that does not want /// HTTP/2 removes it here rather than turning the driver off, because /// what is advertised and what is served disagreeing is a client that /// selects `h2` and is answered in HTTP/1.1. alpn_protocols: []const []const u8 = &.{ "h2", "http/1.1" }, /// Where randomness for the handshake comes from. rng: std.Random, /// Options for the socket underneath. tcp: tcp.Listener.Options = .{},};
pub const Listener = struct { inner: tcp.Listener, options: Options,
pub const ListenError = tcp.Listener.ListenError;
pub fn listen(io: Io, address: net.IpAddress, options: Options) ListenError!Listener { return .{ .inner = try tcp.Listener.listen(io, address, options.tcp), .options = options, }; }
pub fn deinit(l: *Listener, io: Io) void { l.inner.deinit(io); l.* = undefined; }
pub fn localAddress(l: *const Listener) net.IpAddress { return l.inner.localAddress(); }
pub fn shutdown(l: *Listener, io: Io) void { l.inner.shutdown(io); }
pub fn listener(l: *Listener) transport.Listener { return .{ .context = l, .vtable = &vtable }; }
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.?)); // Through the seam rather than around it: the plain listener's own // accept is what knows how to turn a socket into a connection, and // this only has to put a handshake in front of what it returns. var plain = try l.inner.listener().accept(io, gpa, options); errdefer plain.close(io, gpa); return Connection.open(gpa, io, plain, l.options) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // A handshake that does not complete is this connection's // problem and nobody else's: a client offering nothing this // server accepts, a scan, or a plaintext request to a TLS port. // §6.2 of RFC 8446 has the alert already sent by the time this // returns, so what is left is to forget the connection. error.HandshakeFailed => return error.ConnectionAborted, }; }
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.?)); return .fromStdAddress(l.inner.localAddress()); }};
/// What a client has to settle before it will believe an answer.////// The mirror of `Options` and deliberately not the same struct: a server/// proves who it is and a client decides whom to believe, so beyond the socket/// underneath the two have almost nothing in common.pub const ClientOptions = struct { /// The name to ask for, which is also the name the certificate has to /// carry. It travels as SNI, and it is not simply the address because one /// address serves many names — which is the whole reason SNI exists, and /// the reason a caller that dialled an address still has to say what it /// expects to find there. /// /// A bare address here almost certainly fails the check, and that is /// worth knowing before it costs an afternoon: verification goes through /// `std.crypto.Certificate.Parsed.verifyHostName`, which compares this /// against the certificate's dNSName entries and its common name. It does /// not read iPAddress entries at all, so a certificate issued for /// `IP:127.0.0.1` — which is what `openssl req -addext` writes, and what /// curl accepts — is not matched by `127.0.0.1` here. Give the name the /// certificate was issued for, and dial whatever address you like. host: []const u8, /// Where the trust for that check comes from. /// /// Empty by default, which fails every connection closed until a caller /// says what it trusts: `std.crypto.Certificate.Bundle` has `rescan` for /// the system store and `addCertsFromFilePath` for one file. Empty and /// trusting nothing is the right default for a library — a client that /// silently trusted whatever the machine happened to hold would be making /// that decision on the caller's behalf. The type is the one zig-quic's /// client takes, so a bundle loaded once serves an HTTP/3 connection and /// this one both. root_ca: tls.config.cert.Bundle = .{ .bytes = .empty, .map = .empty }, /// For a test, and named so that it cannot be set by accident. insecure_skip_verify: bool = false, /// What to offer in ALPN, in preference order. /// /// HTTP/1.1 alone, because that is the driver this dials for. Offering /// `h2` would be asking for a protocol the caller may have no driver /// ready to speak, and what is advertised disagreeing with what is spoken /// is the same fault at this end as at the server's. An empty list sends /// no ALPN extension at all, which is what to pass when talking to /// something that does not expect one. alpn_protocols: []const []const u8 = &.{"http/1.1"}, /// Where randomness for the handshake comes from. rng: std.Random, /// Options for the socket underneath. Its buffers are raised to what a /// handshake needs — see `connect`. tcp: transport.Listener.Options = .{},};
pub const ConnectError = net.IpAddress.ConnectError || Allocator.Error || error{HandshakeFailed};
/// The smallest read buffer a connection may have for a TLS handshake to be/// run over it: one whole record, which `tls.client` asserts rather than/// checks.pub const min_read_buffer_len = tls.input_buffer_len;/// And the smallest write buffer, which is the ClientHello: 1572 octets plus/// the host name, rounded up to what the library asserts.pub const min_write_buffer_len = 2048;
pub const ConnectOverError = error{ OutOfMemory, HandshakeFailed, /// The connection's buffers are smaller than `min_read_buffer_len` and /// `min_write_buffer_len`. Checked here because the TLS library asserts /// it, and an assertion is a crash rather than an answer. BufferTooSmall,};
/// Puts a TLS handshake on a connection that is already open -- a tunnel/// through a proxy, which is the case this is for, or anything else a/// `transport.Connection` can be.////// Takes ownership of `plain`: it is closed on failure, and closing the/// connection returned closes it as well. `options.tcp` is not used, since/// there is no socket to make.pub fn connectOver( io: Io, gpa: Allocator, plain: transport.Connection, options: ClientOptions,) ConnectOverError!transport.Connection { var owned = plain; errdefer owned.close(io, gpa); if (plain.input.buffer.len < min_read_buffer_len or plain.output.buffer.len < @max(min_write_buffer_len, 1600 + options.host.len)) { return error.BufferTooSmall; } return Connection.dial(gpa, io, plain, options);}
/// Dials a server and puts a TLS handshake in front of the connection.////// The client half of `Listener.accept`, and deliberately the same return/// type: what a driver is handed does not depend on which end opened it, or on/// whether there is TLS underneath at all. `http1.client` reads and writes/// this exactly as it reads and writes a plain socket, and can learn that the/// channel is confidential only by asking `Info.secure` — which is the same/// division that lets one driver serve a terminated connection and a direct/// one without knowing the difference.pub fn connect( io: Io, gpa: Allocator, address: net.IpAddress, options: ClientOptions,) ConnectError!transport.Connection { // The handshake runs through the socket's own buffers, and `tls.client` // *asserts* their sizes rather than reporting an error: a record is up to // `tls.input_buffer_len` octets, and a ClientHello is 1572 plus the host // name. The socket's default read buffer here is 8 KB, so a caller who // changed nothing would panic inside the TLS library rather than be told // anything. Raised rather than refused, because the number belongs to the // protocol and there is nothing useful a caller could say about it. return connectAny(io, gpa, &.{address}, options);}
/// `connect` for a name that resolved to several addresses: the first that/// accepts a TCP connection gets the handshake, as `tcp.connectAny` explains.////// A failed *handshake* is not retried against the next address. Every/// address a name resolves to is meant to be the same server, so a/// certificate that did not verify at one is an answer about the name rather/// than about that address -- and trying the others until one says something/// different is the shape of an attack, not of a fallback.pub fn connectAny( io: Io, gpa: Allocator, addresses: []const net.IpAddress, options: ClientOptions,) ConnectError!transport.Connection { var plain_options = options.tcp; plain_options.read_buffer_len = @max(plain_options.read_buffer_len, min_read_buffer_len); plain_options.write_buffer_len = @max(plain_options.write_buffer_len, min_write_buffer_len, 1600 + options.host.len);
var plain = try tcp.connectAny(io, gpa, addresses, plain_options); errdefer plain.close(io, gpa); return Connection.dial(gpa, io, plain, options);}
/// One TLS session over one accepted socket.////// Boxed for the same reason the plain one is: the reader and writer hand out/// the addresses of interfaces inside this struct, so it must not move.pub const Connection = struct { /// The socket underneath, still owning its own buffers. plain: transport.Connection, session: tls.Connection, reader: tls.Connection.Reader, writer: tls.Connection.Writer, read_buffer: []u8, write_buffer: []u8, /// The negotiated protocol, copied because the handshake's own copy does /// not outlive it. alpn_buf: [32]u8 = undefined, alpn_len: usize = 0,
const OpenError = error{ OutOfMemory, HandshakeFailed };
/// A server's end: a handshake that proves who this is. fn open( gpa: Allocator, io: Io, plain: transport.Connection, options: Options, ) OpenError!transport.Connection { // The handshake reads and writes the socket directly; the TLS // connection it produces is what everything after it goes through. const session = tls.server(plain.input, plain.output, .{ .auth = options.auth, .alpn_protocols = options.alpn_protocols, .rng = options.rng, .now = Io.Timestamp.now(io, .real), }) catch return error.HandshakeFailed; return wrap(gpa, plain, session); }
/// A client's end: a handshake that decides whether to believe the peer. fn dial( gpa: Allocator, io: Io, plain: transport.Connection, options: ClientOptions, ) OpenError!transport.Connection { const session = tls.client(plain.input, plain.output, .{ .host = options.host, .root_ca = options.root_ca, .insecure_skip_verify = options.insecure_skip_verify, .alpn_protocols = options.alpn_protocols, .rng = options.rng, .now = Io.Timestamp.now(io, .real), }) catch return error.HandshakeFailed; return wrap(gpa, plain, session); }
/// Everything after the handshake, which is the same whichever end did /// it: the session gets buffers of its own, and what comes back is a /// `transport.Connection` that says it is confidential and says what was /// negotiated over it. fn wrap( gpa: Allocator, plain: transport.Connection, session: tls.Connection, ) error{OutOfMemory}!transport.Connection { const c = gpa.create(Connection) catch return error.OutOfMemory; errdefer gpa.destroy(c);
// A whole record rather than a round 16 KiB, so that a second TLS // session can be run over this one -- an `https` URL through an // `https://` proxy -- without `connectOver` refusing the buffers. const read_buffer = gpa.alloc(u8, min_read_buffer_len) catch return error.OutOfMemory; errdefer gpa.free(read_buffer); const write_buffer = gpa.alloc(u8, 16 * 1024) catch return error.OutOfMemory; errdefer gpa.free(write_buffer);
c.* = .{ .plain = plain, .session = session, .reader = undefined, .writer = undefined, .read_buffer = read_buffer, .write_buffer = write_buffer, }; c.reader = c.session.reader(read_buffer); c.writer = c.session.writer(write_buffer);
if (session.alpn_protocol) |selected| { const n = @min(selected.len, c.alpn_buf.len); @memcpy(c.alpn_buf[0..n], selected[0..n]); c.alpn_len = n; }
return .{ .input = &c.reader.interface, .output = &c.writer.interface, .info = .{ .peer = plain.info.peer, .local = plain.info.local, .secure = true, .alpn = if (c.alpn_len > 0) c.alpn_buf[0..c.alpn_len] else null, }, .context = c, .vtable = &vtable, }; }
const vtable: transport.Connection.VTable = .{ .close = closeImpl, .shutdownWrite = shutdownWriteImpl, };
fn closeImpl(context: ?*anyopaque, io: Io, gpa: Allocator) void { const c: *Connection = @ptrCast(@alignCast(context.?)); // §6.1 of RFC 8446: `close_notify` says the end of the data was // meant, which is what stops a truncation from looking like one. c.session.close() catch {}; c.plain.close(io, gpa); 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.session.close() catch {}; c.plain.shutdownWrite(io); }};
test { std.testing.refAllDecls(@This());}
test "every vtable entry is compiled" { // Not a tautology, and here because it caught a real one. Zig analyzes a // function when something reaches it, and nothing reaches a vtable entry // until the vtable itself is reached -- so this file compiled, and the // whole suite passed, while `acceptImpl` called a function that did not // exist. `refAllDecls` above does not go deep enough to find it. // // Naming the tables is enough: their initializers hold the function // pointers, so analyzing them analyzes everything they point at. _ = Listener.vtable; _ = Connection.vtable;}