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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A request to send, described the way a caller thinks about one.//!//! The mirror of `server.Request`, and deliberately the same shape: a method,//! a target, fields and a body. What differs is the direction, so the fields//! here are what the caller sets rather than what arrived, and the body is//! something to write rather than something to read.//!//! Nothing about framing is here. Whether a body leaves as a//! `Content-Length` or as chunks is the driver's decision and depends on the//! version it is speaking, which is the same division that lets one handler//! serve HTTP/1.0, 1.1, 2 and 3 on the server side.
const std = @import("std");
const protocol = @import("../protocol.zig");
const Headers = protocol.Headers;const Length = protocol.Length;const Target = protocol.Target;const Method = protocol.Method;
const Request = @This();
method: Method = .get,/// The request target, in origin form: a path and an optional query.////// §3.2.1 of RFC 9112, which is the form a client uses for an ordinary/// request. The authority goes in `host` and not here -- absolute form is/// for a request to a proxy, and mixing the two is how a request is routed/// to one origin by a proxy and another by the server behind it.target: []const u8 = "/",/// The authority this request is addressed to, which becomes the `Host`/// field.////// §3.2 of RFC 9112 requires exactly one on an HTTP/1.1 request, so the/// driver refuses to send one without it rather than emitting a message a/// server must reject.host: []const u8,/// Fields to send. `Host`, `Content-Length` and `Transfer-Encoding` are the/// driver's and are refused here -- see `reserved`.headers: Headers = .empty,/// What the body is, which decides the framing.body: Length = .none,/// The body itself, for `.exact` and for a `.unknown` body small enough to/// have in hand.content: ?[]const u8 = null,/// Or the body read from here as it is sent, for one too large to hold: a/// container layer, a disk image. Only with `body = .exact`, because the/// length has to be declared before the first octet goes, and only when/// `content` is null, since a request has one body and not two.////// Exactly the declared length is read, and no more: whatever the reader/// holds after that is left where it is. A reader that ends sooner is/// `error.RequestBodyShort` and one that fails is/// `error.RequestBodyReadFailed`, from every driver -- never a body silently/// cut short, which the other end would read as the whole of it or wait on/// for ever.////// Nothing is buffered beyond the connection's own buffers, so a request of/// any size costs what a small one does. All three drivers take one.source: ?*std.Io.Reader = null,
/// Fields a caller may not set, because the driver sets them from what it/// was told and two sources disagreeing is how a message gets framed one way/// by the sender and another by the recipient.pub const reserved = [_][]const u8{ "host", "content-length", "transfer-encoding",};
pub fn isReserved(name: []const u8) bool { for (reserved) |one| { if (protocol.token.eqlIgnoreCase(name, one)) return true; } return false;}
/// What a `Content-Length` should say on a version that does not need one, or/// null when the message must not carry one.////// HTTP/2 and HTTP/3 delimit content with the stream rather than with a field/// -- §8.1 of RFC 9113 and §4.1 of RFC 9114 -- so the field is optional there/// in a way it is not over HTTP/1.1, and for a long time these drivers left it/// out on that ground. §8.6 of RFC 9110 is the other half of the story: "A/// user agent SHOULD send Content-Length in a request when the method defines/// a meaning for enclosed content and it is not sending Transfer-Encoding."/// It is what lets a recipient check that what arrived is what was sent, and a/// server is within its rights to insist -- Cloudflare's DNS-over-HTTP/3/// endpoint answers `400` to a `POST` without one.////// So both drivers send it when the length is known, and this is the one place/// that decides what "known" means, so that the two cannot drift.////// It is also where the length is checked against the content in hand, because/// a `Content-Length` that disagrees with the DATA frames makes the message/// malformed -- §8.1.1 of RFC 9113 and §4.1.2 of RFC 9114 both say so -- and a/// sender that framed a message two ways is a sender doing to itself what/// `reserved` exists to stop a caller doing.pub fn declaredContentLength(r: Request) error{InvalidRequest}!?u64 { return switch (r.body) { // Not a body of zero octets: no body at all, which is why it carries // no `Content-Length` of `0`. .none => { if (r.content) |content| if (content.len != 0) return error.InvalidRequest; if (r.source != null) return error.InvalidRequest; return null; }, .exact => |n| { if (r.content) |content| { if (r.source != null) return error.InvalidRequest; if (content.len != n) return error.InvalidRequest; } else if (n != 0 and r.source == null) { // A length promised with nothing to fill it, which would be a // promise the stream breaks by ending. return error.InvalidRequest; } return n; }, // The caller declined to say, and the stream's end is what delimits // it. A field filled in from whatever happens to be in hand would be // this driver deciding a question the caller left open. // // Not with a `source`, which needs a length to know when to stop. .unknown => if (r.source != null) error.InvalidRequest else null, };}
/// Whether an authority can be written into a `Host` line without ending it/// early.////// §2.2 of RFC 9112 builds a request out of lines ended by CRLF, and §3.2/// builds the first of those lines out of three fields separated by spaces. A/// target or an authority carrying either delimiter does not travel as one/// value: it becomes a short request line and then whatever the rest of it/// happens to parse as. With a CRLF in it that is a field the caller never/// meant to send and the recipient has no way to tell from one it did --/// request splitting, performed by the client rather than against it, and/// reachable by any caller that builds a path out of something it was given.////// So the rule is every octet above the control range and below DEL, which/// refuses SP, HTAB, CR, LF and NUL together without naming any of them./// HTTP/2 and HTTP/3 do not frame a message out of lines and could carry/// these octets safely, but §8.2.1 of RFC 9113 forbids them in a field value/// for the same reason one step further on -- a gateway converting the/// message back to HTTP/1.1 would do the splitting -- so all three drivers/// ask the same question and get the same answer.////// A target is held to `Target.parse`'s stricter rule instead, which starts/// here and goes on to refuse the octets a URI has no place for. Being the/// sender is what makes that affordable: the argument for letting a merely/// malformed target through is about not turning somebody else's `404` into/// a `400`, and there is nobody else here.fn isSafeToSend(s: []const u8) bool { for (s) |ch| { if (ch <= ' ' or ch == 0x7f) return false; } return true;}
/// Checks what the caller supplied, before any of it reaches the wire.////// Fields have been validated since there were fields to validate: they can/// only arrive through `Headers.append`, which refuses a name that is not a/// token and a value that would reframe the message. `target` and `host` are/// plain slices on this struct that nothing looked at, and went out exactly/// as they came in. That is the hole this closes, and it lives here rather/// than in a driver so that the three cannot disagree about what a request/// they are willing to send is.////// Found by fuzzing what the client emits rather than what it reads: a/// target of `/a\r\nX-Injected: yes\r\nJunk: ` produced a request carrying/// a field nobody asked for, and `send` reported success.pub fn validate(r: Request) error{InvalidRequest}!void { // The library's own rule for what a request target may contain, asked of // what this library is about to send: it refuses the empty target §3.2 of // RFC 9112 has no room for and §8.3.1 of RFC 9113 forbids as a `:path`, // and every octet that would rewrite the request line around it. _ = Target.parse(r.target) catch return error.InvalidRequest; // An empty authority is a caller declining to send one, which HTTP/1.0 // permits and each driver decides about for itself; a non-empty one has // to survive being written into a `Host` line. if (!isSafeToSend(r.host)) return error.InvalidRequest;}
pub fn deinit(r: *Request, gpa: std.mem.Allocator) void { r.headers.deinit(gpa);}
/// Adds a field, refusing the ones the driver owns.pub fn setHeader( r: *Request, gpa: std.mem.Allocator, name: []const u8, value: []const u8,) error{ OutOfMemory, ReservedField, InvalidField }!void { if (isReserved(name)) return error.ReservedField; try r.headers.append(gpa, name, value);}
const testing = std.testing;
test "a target that would rewrite the request line is refused" { // §2.2 of RFC 9112: a message is lines ended by CRLF. A target carrying // one does not travel as a target -- it ends the request line and what // follows is read as fields, which is a field the caller never sent and // the server cannot tell from one it did. // // Found by fuzzing what the client emits. Before this, the request below // went out as three lines and `send` reported success: // // GET /a // X-Injected: yes // Junk: HTTP/1.1 // Host: example.com const splitting: Request = .{ .host = "example.com", .target = "/a\r\nX-Injected: yes\r\nJunk: ", }; try testing.expectError(error.InvalidRequest, splitting.validate());
// §3.2: the request line separates its three fields with spaces, so a // target containing one arrives as a target and a version that is not. const spaced: Request = .{ .host = "example.com", .target = "/a b" }; try testing.expectError(error.InvalidRequest, spaced.validate());
// And the same reasoning one hop further on for the authority, which is // written into a `Host` line the same way. const split_host: Request = .{ .host = "example.com\r\nX-Injected: yes", .target = "/" }; try testing.expectError(error.InvalidRequest, split_host.validate());
// §8.3.1 of RFC 9113 has no empty `:path`, and §3.2 of RFC 9112 no empty // request-target. const empty: Request = .{ .host = "example.com", .target = "" }; try testing.expectError(error.InvalidRequest, empty.validate());
// What a caller actually sends, which must still go. const ordinary: Request = .{ .host = "example.com:8443", .target = "/a/b?c=d&e=%20" }; try ordinary.validate(); const asterisk: Request = .{ .host = "example.com", .target = "*" }; try asterisk.validate(); // An HTTP/1.0 request may decline to send an authority at all; which // versions accept that is each driver's business, not this check's. const no_host: Request = .{ .host = "", .target = "/" }; try no_host.validate();}
test "the fields the driver owns cannot be set by hand" { // Two sources for one framing decision is how a message is read one way // by its sender and another by its recipient, which is request smuggling // written as a convenience. var r: Request = .{ .host = "example.com" }; defer r.deinit(testing.allocator);
try testing.expectError(error.ReservedField, r.setHeader(testing.allocator, "Content-Length", "5")); try testing.expectError(error.ReservedField, r.setHeader(testing.allocator, "transfer-encoding", "chunked")); try testing.expectError(error.ReservedField, r.setHeader(testing.allocator, "HOST", "elsewhere"));
try r.setHeader(testing.allocator, "accept", "text/plain"); try testing.expectEqualStrings("text/plain", r.headers.get("accept").?);}
test "what a multiplexed version declares about its content" { // The rule both the HTTP/2 and the HTTP/3 driver ask for, in one place so // that the two cannot answer it differently. const none: Request = .{ .host = "example.com" }; try testing.expectEqual(@as(?u64, null), try none.declaredContentLength());
// A body of zero octets is a body, and says so -- which is not the same // message as one with no body at all. const empty: Request = .{ .host = "example.com", .body = .{ .exact = 0 }, .content = "" }; try testing.expectEqual(@as(?u64, 0), try empty.declaredContentLength());
const post: Request = .{ .host = "example.com", .method = protocol.Method.post, .body = .{ .exact = 5 }, .content = "hello", }; try testing.expectEqual(@as(?u64, 5), try post.declaredContentLength());
// Nothing declared, so nothing said: the stream's end delimits it. const streamed: Request = .{ .host = "example.com", .body = .unknown, .content = "hello" }; try testing.expectEqual(@as(?u64, null), try streamed.declaredContentLength());}
test "a streamed body declares its length, and only an exact one" { var reader: std.Io.Reader = .fixed("hello"); const streamed: Request = .{ .host = "example.com", .method = protocol.Method.put, .body = .{ .exact = 5 }, .source = &reader, }; try testing.expectEqual(@as(?u64, 5), try streamed.declaredContentLength());
// No length, nothing to say when to stop. const unbounded: Request = .{ .host = "example.com", .body = .unknown, .source = &reader }; try testing.expectError(error.InvalidRequest, unbounded.declaredContentLength()); // No body, and a body. const contradiction: Request = .{ .host = "example.com", .body = .none, .source = &reader }; try testing.expectError(error.InvalidRequest, contradiction.declaredContentLength()); // Two bodies. const both: Request = .{ .host = "example.com", .body = .{ .exact = 5 }, .content = "hello", .source = &reader }; try testing.expectError(error.InvalidRequest, both.declaredContentLength());}
test "a length that disagrees with the content is refused before it is sent" { // §8.1.1 of RFC 9113 and §4.1.2 of RFC 9114: a `Content-Length` that does // not match what the DATA frames carry makes the message malformed. A // sender that let it through would be framing a message two ways at once, // which is exactly what `reserved` stops a caller doing by hand. const short: Request = .{ .host = "example.com", .body = .{ .exact = 9 }, .content = "hello", }; try testing.expectError(error.InvalidRequest, short.declaredContentLength());
// A length promised with nothing to fill it: these drivers write what // `content` holds, so the stream would end nine octets early. const promised: Request = .{ .host = "example.com", .body = .{ .exact = 9 } }; try testing.expectError(error.InvalidRequest, promised.declaredContentLength());
// And content where the message says there is no body. const contradiction: Request = .{ .host = "example.com", .body = .none, .content = "hello" }; try testing.expectError(error.InvalidRequest, contradiction.declaredContentLength());}