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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! One response, as a handler writes it.//!//! A status, a set of fields, and a body — and nothing about framing. The//! handler says how long the body is going to be, in `Length`, and the driver//! for whichever version is in use turns that into a `Content-Length`, a//! chunked transfer coding, a closed connection or a sequence of DATA frames.//! That is the whole reason this type exists rather than the handler writing//! to the socket: it is the seam that lets one handler serve HTTP/1.0,//! HTTP/1.1 and, when there is a driver for them, HTTP/2 and HTTP/3.//!//! Which is also why `Content-Length`, `Transfer-Encoding` and `Connection`//! set by hand are ignored. The first two are framing and belong to the//! driver; the third is an HTTP/1.1 connection-management field that HTTP/2//! makes a connection error to send at all.//!//! ## Order of operations//!//! Set the status and the fields, then call `beginBody` once, write to the//! writer it returns, then `end`. `send` and the other conveniences do all//! three. Setting a field after `beginBody` is a programmer error and//! asserts: by then the head is on the wire and there is nowhere for it to//! go.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const assert = std.debug.assert;
const protocol = @import("../protocol.zig");const coding = protocol.coding;const compression = @import("compression.zig");const Headers = protocol.Headers;const Length = protocol.Length;const Status = protocol.Status;const Version = protocol.Version;
const Response = @This();
/// The status to send. `.ok` unless the handler says otherwise.status: Status = .ok,/// The fields to send. Neither the names nor the values are copied, so both/// must outlive `end`; `printHeader` is the way to add one that has to be/// computed.headers: Headers,/// RFC 9110 §6.5: fields sent *after* the content, for things that are not/// known until it has been produced — a checksum, a signature, how long the/// work took, why a stream stopped early.////// Filled in any time before the response ends; the driver writes them when/// it finishes the body. Which driver is running decides whether they can be/// sent at all, and §6.6.2 is explicit that "a trailer section is only/// possible when the message framing allows it": over HTTP/1.1 that means a/// chunked coding, so a response whose length was declared has nowhere to put/// them and they are dropped. Over HTTP/2 and HTTP/3 they are a second field/// section and always possible.////// Dropping rather than failing is the specified behaviour rather than a/// shortcut — a trailer field is by construction something the recipient may/// not receive, which is also why §6.5.1 forbids putting anything the/// recipient *needs* in one. `isForbiddenTrailer` is that list, and the/// drivers refuse those names on the way out rather than trusting a handler/// to have read the section.trailers: Headers = .empty,/// Scratch for the length of this exchange. The same arena as/// `Request.arena`.arena: Allocator,/// The version this response will be framed in, which is the version of the/// request unless the server had to fall back.version: Version,state: State = .head,context: ?*anyopaque,vtable: *const VTable,/// What the client said it would take, borrowed from the request that asked.////// The driver fills it in, because the driver is what has both halves: this/// struct is written against a response and never sees the request that/// caused it.accept_encoding: ?[]const u8 = null,/// Whether to code the body, and how. Null is a server that does not.compress: ?compression.Config = null,/// The compressor, once `beginBody` has decided to use one. `end` finishes/// it — §2.2 of RFC 1952's footer is not written by a flush — before letting/// the driver end the body.compressor: ?*coding.Compressor = null,
pub const State = enum { /// Nothing has been written. The status and the fields can still change. head, /// The head is on the wire and the body is being written. body, /// The response is complete. ended, /// The connection is no longer speaking HTTP. `upgrade` handed the byte /// stream to the handler, and nothing here may touch it again. upgraded,};
pub const Error = error{ /// The connection failed. Nothing more will go out on it. WriteFailed, OutOfMemory, /// A field name that is not a token, or a value carrying an octet that /// would change the framing of the message around it. InvalidField, /// The body was longer than the length that was declared for it, or /// `end` was reached before it was as long as declared. Either way the /// message on the wire is not the one that was described, so the /// connection cannot be reused. LengthMismatch,};
pub const VTable = struct { /// Commits the status and the fields, and returns the writer the body /// goes to. Called at most once. beginBody: *const fn (res: *Response, length: Length) Error!*Io.Writer, /// Finishes the body — the terminating chunk, the end of the stream, /// whatever the version needs — and flushes. end: *const fn (res: *Response) Error!void, /// Sends an interim response: a `1xx` with fields and no body, which is /// followed by the real response later. sendInterim: *const fn (res: *Response, status: Status, headers: *const Headers) Error!void, /// Stops speaking HTTP and hands the byte stream over. Null for a driver /// that has no way to do it. upgrade: ?*const fn (res: *Response, protocol_name: []const u8) UpgradeError!Upgrade = null,};
/// The byte stream, once it is no longer carrying HTTP.////// Both halves are exactly where HTTP left off: anything the client sent/// after its request head, and before the `101` went out, is still buffered/// in `input` and will be read first. That is the property a protocol switch/// lives or dies by — a client that pipelines its first frames behind the/// handshake must not lose them — and it is why `upgrade` hands back the/// reader the server was already using rather than a fresh one.pub const Upgrade = struct { input: *Io.Reader, output: *Io.Writer,};
pub const UpgradeError = Error || error{ /// The client did not offer this protocol. RFC 9110 §7.8 forbids /// switching to one it did not list, and this is that rule. NotOffered, /// Nothing here can switch protocols: an HTTP/1.0 client, or a driver /// for a version where `Upgrade` does not exist. UpgradeUnavailable, /// The request has a body that the handler did not read. Its remaining /// octets are still in front of the new protocol's first octet, and /// handing the stream over with them there would corrupt it. BodyNotConsumed,};
/// Stops speaking HTTP on this connection and hands the byte stream to the/// handler.////// This is the `Upgrade` mechanism of RFC 9110 §7.8: the handler sees a/// request offering to switch, decides, and gets back a reader and a writer/// that are no longer anybody else's business. `101 Switching Protocols` goes/// out first, carrying whatever fields have been set — which for a WebSocket/// is where `Sec-WebSocket-Accept` belongs.////// ## It is not a callback, on purpose////// The obvious shape for this is a callback registered with the server: "when/// somebody upgrades to `websocket`, call me with the socket". This is a/// method that returns the stream instead, and the reason is lifetime. A/// callback invoked after the handler returns would be handed a connection/// whose owner had already moved on, which means the server has to keep it/// alive on the callback's behalf and the two have to agree about when it is/// finished. Returning the stream to the handler that is already running/// keeps the whole thing in one stack frame: the handler speaks the new/// protocol for as long as it likes, returns when it is done, and the/// connection closes where every other connection closes.////// So a WebSocket handler is an ordinary handler that, at the top, checks/// whether it was offered the upgrade, computes the accept token, calls this,/// and then never returns to HTTP.////// ## After it returns////// The response is over — the status and the fields cannot change, no body/// may be written, and this connection will not serve another request. The/// server closes the connection once the handler returns.////// If it returns an error instead, nothing has been written and nothing has/// changed: the handler can go on to send an ordinary response, which for a/// refused upgrade is usually `426 Upgrade Required`.pub fn upgrade(res: *Response, protocol_name: []const u8) UpgradeError!Upgrade { assert(res.state == .head); const switchProtocols = res.vtable.upgrade orelse return error.UpgradeUnavailable; // Nothing is touched until the driver has agreed. A refused upgrade has // to leave the response exactly as it found it, because the handler's // next move is to send an ordinary one instead — `426 Upgrade Required`, // usually — and it would go out as a `101` if the status had already // been changed on the way in. const stream = try switchProtocols(res, protocol_name); res.status = .switching_protocols; res.state = .upgraded; return stream;}
/// Adds a field, keeping any other field of the same name. Which is what/// `Set-Cookie` and `Via` want, and not what `Content-Type` wants.pub fn addHeader(res: *Response, name: []const u8, value: []const u8) Error!void { assert(res.state == .head); return res.headers.append(res.arena, name, value) catch |err| switch (err) { error.InvalidField => error.InvalidField, error.OutOfMemory => error.OutOfMemory, };}
/// Replaces every field of this name with one holding `value`.pub fn setHeader(res: *Response, name: []const u8, value: []const u8) Error!void { assert(res.state == .head); return res.headers.set(res.arena, name, value) catch |err| switch (err) { error.InvalidField => error.InvalidField, error.OutOfMemory => error.OutOfMemory, };}
/// `setHeader` with the value formatted into the exchange's arena, for the/// common case of a value that has to be computed and has nowhere else to/// live.pub fn printHeader( res: *Response, name: []const u8, comptime fmt: []const u8, args: anytype,) Error!void { const value = std.fmt.allocPrint(res.arena, fmt, args) catch return error.OutOfMemory; return res.setHeader(name, value);}
/// Commits the status and the fields and returns the writer for the body.////// `length` is a promise. `.exact` says how many octets are coming and the/// driver will hold the body to it; `.unknown` says the handler does not know/// yet, which costs a chunked transfer coding in HTTP/1.1 and a closed/// connection in HTTP/1.0; `.none` says there is no body, which is not the/// same as an empty one.pub fn beginBody(res: *Response, length: Length) Error!*Io.Writer { assert(res.state == .head);
// §8.4: a content coding is applied to the representation, so this // happens above the framing and before it -- which is also why it is here // and not in a driver. All three call this, and none of them has a line // about codings in it. var effective = length; var chosen: ?coding.Coding = null; if (res.compress) |config| chosen = res.negotiateCoding(config, &effective);
const w = try res.vtable.beginBody(res, effective); res.state = .body;
const want = chosen orelse return w; // The window and the compressor both outlive this call and are pointed at // by what it returns, so neither may be on this stack. The arena is the // exchange's and goes away with it. const window = res.arena.alloc(u8, coding.window_len) catch return error.OutOfMemory; const c = res.arena.create(coding.Compressor) catch return error.OutOfMemory; // gzip is the only coding `Coding.supported` admits, and `wants` only // ever returns one from `config.codings`. An assertion rather than a // silent fallthrough, so that adding a second coding to that list without // teaching this line about it stops here rather than labelling one // coding's octets with another's name. assert(want == .gzip); c.* = coding.gzipCompressor(w, window, res.compress.?.level) catch return error.WriteFailed; res.compressor = c; return &c.writer;}
/// Decides the coding and says so in the fields, before the head is committed.////// `length` is rewritten because a coded body has a length nobody knows until/// it has been produced: §8.6's `Content-Length` counts the coded octets, and/// there is no way to count them in advance. `.unknown` is what every driver/// already does for a body of undeclared length -- a chunked coding over/// HTTP/1.1, DATA frames over the other two -- so a compressed response costs/// the framing it would have had, and nothing else changes.fn negotiateCoding(res: *Response, config: compression.Config, length: *Length) ?coding.Coding { if (!statusAllowsBody(res.status)) return null; // A handler that coded it already has said so, and coding it twice would // be this library disagreeing with the handler about the representation. if (res.headers.get("content-encoding") != null) return null;
const content_type = res.headers.get("content-type"); if (!compression.negotiable(config, content_type)) return null;
// §12.5.4: the representation this server sends for this resource depends // on `Accept-Encoding`, and it says so whether or not it happens to have // compressed *this* one. A cache told only about the compressed times // would keep an identity body under a key that a gzip-accepting client // matches, and serve the wrong one ever after. res.addHeader("Vary", "Accept-Encoding") catch return null;
const want = compression.wants(config, res.accept_encoding, content_type, length.*) orelse return null; res.setHeader("Content-Encoding", want.name()) catch return null; length.* = .unknown; return want;}
/// RFC 9110 §6.5.1: whether a field may not be sent in a trailer section.////// The list is not arbitrary. A trailer arrives after the recipient has/// already acted on the head and, for a proxy, after it has already forwarded/// it — so anything that would change how the message is *framed*, *routed*,/// *cached* or *authenticated* arrives too late to be obeyed and is a way to/// say one thing to a cache and another to whatever is behind it. §6.5.1/// names the classes; these are the fields in them that this library can/// meet.pub fn isForbiddenTrailer(name: []const u8) bool { const forbidden = [_][]const u8{ // Framing: the recipient has already decided where the body ends. "transfer-encoding", "content-length", "host", // Routing and request modifiers. "te", "expect", "max-forwards", "cache-control", "expires", "pragma", "age", "vary", "warning", // Authentication, which a recipient acted on before the body. "authorization", "proxy-authorization", "www-authenticate", "proxy-authenticate", "set-cookie", "cookie", // How to interpret the content, which is needed to read it at all. "content-encoding", "content-type", "content-range", "trailer", }; for (forbidden) |f| { if (std.ascii.eqlIgnoreCase(name, f)) return true; } return false;}
/// Finishes the response.pub fn end(res: *Response) Error!void { assert(res.state == .body); // §2.2 of RFC 1952: the final block and the footer, which `flush` does not // write. Without this the body stops mid-member and a recipient that // checks says so while one that does not is quietly given less than was // sent. if (res.compressor) |c| c.finish() catch return error.WriteFailed; try res.vtable.end(res); res.state = .ended;}
/// Sends `bytes` as the whole body, with its length declared up front.pub fn send(res: *Response, bytes: []const u8) Error!void { const w = try res.beginBody(.{ .exact = bytes.len }); try w.writeAll(bytes); return res.end();}
/// `send` with the body formatted into the exchange's arena.pub fn sendPrint(res: *Response, comptime fmt: []const u8, args: anytype) Error!void { const body = std.fmt.allocPrint(res.arena, fmt, args) catch return error.OutOfMemory; return res.send(body);}
/// Sends a status with a one-line body naming it, which is what an error/// response looks like when nobody has written a nicer one.////// The statuses that may not carry a body get none: a `204` with a body in it/// is a framing error, not a friendlier `204`.pub fn sendStatus(res: *Response, status: Status) Error!void { res.status = status; if (!statusAllowsBody(status)) { _ = try res.beginBody(.none); return res.end(); } try res.setHeader("Content-Type", "text/plain; charset=utf-8"); const phrase = status.phrase() orelse "Unknown"; return res.sendPrint("{d} {s}\n", .{ @intFromEnum(status), phrase });}
/// Sends a redirect. `status` must be one of the `3xx` that carry a/// `Location`.pub fn redirect(res: *Response, status: Status, location: []const u8) Error!void { res.status = status; try res.setHeader("Location", location); return res.sendStatus(status);}
/// Sends an interim `1xx` response, which is followed by the real one.////// `103 Early Hints` is the one worth sending: it lets a client start/// fetching the stylesheet while the server is still working out what the/// page says. Interim responses are silently dropped for an HTTP/1.0 client,/// which has no idea what to do with one.pub fn sendInterim(res: *Response, status: Status, headers: *const Headers) Error!void { assert(res.state == .head); assert(status.class() == .informational); return res.vtable.sendInterim(res, status, headers);}
/// Whether a response with this status may carry a body at all (RFC 9110/// §6.4.1). Nothing to do with whether one is wanted — a `204` with a body is/// malformed however much the handler would like to explain itself.pub fn statusAllowsBody(status: Status) bool { return switch (status.class()) { .informational => false, else => switch (@intFromEnum(status)) { 204, 304 => false, else => true, }, };}
test statusAllowsBody { try std.testing.expect(statusAllowsBody(.ok)); try std.testing.expect(statusAllowsBody(.not_found)); try std.testing.expect(!statusAllowsBody(.no_content)); try std.testing.expect(!statusAllowsBody(.not_modified)); try std.testing.expect(!statusAllowsBody(.@"continue"));}
test { std.testing.refAllDecls(@This());}