// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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, /// Told of each interim response to this request as it arrives, or null to /// have them skipped unseen. /// /// §15.2 of RFC 9110: a server may send any number of 1xx responses ahead of /// the final one, and "a client MUST be able to parse one or more 1xx /// responses received prior to a final response, even if the client does not /// expect one". Every driver does that whether or not this is set, and /// returns only the final response. This is for the caller that wants to see /// them on the way -- a `103 Early Hints` naming what to preload, say. /// /// Not told of a `101 Switching Protocols`, which is informational by number /// but final in meaning: it ends HTTP on the connection, and is what `send` /// returns. /// /// Called on whatever is reading the connection, which over HTTP/2 may be an /// `await` for a *different* request on it: frames are filed as they arrive, /// whichever stream they are for. So `context` has to stay valid until this /// request's own response has been returned. interim: ?InterimHook = null, /// Whether to hold the body back until the server asks for it. /// /// §10.1.1 of RFC 9110: the request goes out with `Expect: 100-continue` and /// no content, and the content follows only once a `100 Continue` arrives. /// A server that would refuse the request anyway -- a `401`, a `413` -- says /// so with a final response instead, and the content is never sent, which /// is the whole point: an upload a server was always going to refuse costs /// one head rather than all of it. `Response.content_sent` says which /// happened. /// /// There is no timer: the driver waits for a `100` or a final response for /// as long as the server takes. §10.1.1 has an origin server answer such a /// request "immediately", so a conforming one never leaves it waiting, but /// one that ignores the field -- an old intermediary, say -- leaves it /// waiting for ever. Zig's standard library times a read only on one `Io` /// and not over TLS, so a timeout belongs to whatever is above the driver; /// `fetch` has one. /// /// Dropped, quietly, where it cannot apply: a request with no content has /// nothing to hold back, and an HTTP/1.0 request has no 1xx responses to be /// answered with. /// /// Over HTTP/2, `begin` sends the head alone and the content goes out from /// that request's own `await`, so `content` or `source` has to stay valid /// until then. expect_continue: bool = false, /// One interim response, as `InterimHook` is shown it. /// /// Borrowed: `headers` points into the connection and is gone once the hook /// returns, so a caller that wants a field afterwards copies it. pub const InterimHead = struct { /// Between 100 and 199, and never 101. status: u16, version: protocol.Version, headers: *const Headers, }; /// What `interim` is: somewhere to tell, and what to tell it with. /// /// It returns nothing, because an interim response is advice. A caller that /// wants to give up on the request on the strength of one has the same ways /// to do it that it always had. pub const InterimHook = struct { context: ?*anyopaque, call: *const fn (context: ?*anyopaque, head: InterimHead) void, /// Tells the hook of one interim response. What a driver calls; a caller /// supplies `context` and `call` and is the one told. pub fn notify(hook: InterimHook, head: InterimHead) void { hook.call(hook.context, head); } test notify { const Seen = struct { status: u16 = 0, fn record(context: ?*anyopaque, h: InterimHead) void { const seen: *@This() = @ptrCast(@alignCast(context.?)); seen.status = h.status; } }; var seen: Seen = .{}; const hook: InterimHook = .{ .context = &seen, .call = Seen.record }; const headers: Headers = .empty; hook.notify(.{ .status = 103, .version = .http_1_1, .headers = &headers }); try std.testing.expectEqual(@as(u16, 103), seen.status); } }; /// 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", // `expect_continue`'s, because the driver has to know to wait, and a // field set by hand would say one thing while the driver did another. "expect", }; /// Whether the request carries content, which is what decides whether /// `expect_continue` has anything to hold back. pub fn hasContent(r: Request) bool { return switch (r.body) { .none => false, .exact => |n| n > 0, .unknown => if (r.content) |content| content.len > 0 else false, }; } test hasContent { const get: Request = .{ .host = "example.com" }; try std.testing.expect(!get.hasContent()); const post: Request = .{ .host = "example.com", .method = .post, .body = .{ .exact = 5 }, .content = "hello" }; try std.testing.expect(post.hasContent()); // A body of zero octets is a body, but there is nothing in it to hold back. const empty: Request = .{ .host = "example.com", .body = .{ .exact = 0 }, .content = "" }; try std.testing.expect(!empty.hasContent()); } /// Whether `name` is one of `reserved`, compared without regard to case as /// field names are. pub fn isReserved(name: []const u8) bool { for (reserved) |one| { if (protocol.token.eqlIgnoreCase(name, one)) return true; } return false; } test isReserved { try std.testing.expect(isReserved("Content-Length")); try std.testing.expect(isReserved("host")); try std.testing.expect(!isReserved("accept")); } /// 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, }; } test declaredContentLength { const post: Request = .{ .host = "example.com", .method = .post, .body = .{ .exact = 5 }, .content = "hello" }; try std.testing.expectEqual(@as(?u64, 5), try post.declaredContentLength()); // No body, so no field -- not a `Content-Length: 0`. const get: Request = .{ .host = "example.com" }; try std.testing.expectEqual(@as(?u64, null), try get.declaredContentLength()); // A length the content in hand does not fill. const short: Request = .{ .host = "example.com", .body = .{ .exact = 9 }, .content = "hello" }; try std.testing.expectError(error.InvalidRequest, short.declaredContentLength()); } /// 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; } test validate { const ordinary: Request = .{ .host = "example.com", .target = "/a/b?c=d" }; try ordinary.validate(); const splitting: Request = .{ .host = "example.com", .target = "/a\r\nX-Injected: yes" }; try std.testing.expectError(error.InvalidRequest, splitting.validate()); } /// Frees the list of fields `setHeader` added to. That list is the only thing /// a request owns: the names and values in it, `target`, `host`, `content` /// and `source` are all borrowed from the caller. pub fn deinit(r: *Request, gpa: std.mem.Allocator) void { r.headers.deinit(gpa); } test deinit { var r: Request = .{ .host = "example.com" }; try r.setHeader(std.testing.allocator, "accept", "text/plain"); r.deinit(std.testing.allocator); } /// Adds a field, refusing the ones the driver owns. /// /// `ReservedField` for a name in `reserved`, and `InvalidField` for a name /// that is not a token or a value that would reframe the message, as /// `Headers.append` decides it. Neither `name` nor `value` is copied, so both /// have to outlive the request. 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); } test setHeader { var r: Request = .{ .host = "example.com" }; defer r.deinit(std.testing.allocator); try r.setHeader(std.testing.allocator, "accept", "text/plain"); try std.testing.expectEqualStrings("text/plain", r.headers.get("accept").?); // The driver writes `Content-Length` from `body`, so a caller may not. try std.testing.expectError( error.ReservedField, r.setHeader(std.testing.allocator, "content-length", "5"), ); } 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")); // `expect_continue` is how a 100-continue expectation is asked for, so // that the driver knows to wait for the answer to it. try testing.expectError(error.ReservedField, r.setHeader(testing.allocator, "Expect", "100-continue")); 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()); }