// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One request, as a handler sees it. //! //! Everything here is HTTP semantics and none of it is HTTP/1.1: the method, //! the target, the fields and the body are the same four things an HTTP/2 //! HEADERS frame and its DATA frames carry, and a driver for that version //! would fill in exactly this struct. What is deliberately *not* here is the //! framing — there is no way to ask whether the body arrived chunked, because //! a handler that cared could not be run over HTTP/2, where the question has //! no answer. //! //! Nothing in here outlives the call to the handler. The names and values //! point into the buffer the head was read into, which the next request on a //! kept-alive connection will overwrite, and `arena` is reset at the same //! moment. A handler that wants to keep something must copy it somewhere of //! its own. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const protocol = @import("../protocol.zig"); const transport = @import("../transport.zig"); const Headers = protocol.Headers; const Length = protocol.Length; const Method = protocol.Method; const Target = protocol.Target; const Version = protocol.Version; const Request = @This(); /// The `Io` the connection is being served on. A handler that needs to do I/O /// of its own — open a file, make a request onward — takes it from here /// rather than reaching for an implementation, so that a test can serve the /// whole thing on `Io.failing` and a fuzzer can drive it with no I/O at all. io: Io, /// Scratch for the length of this exchange, and no longer. Reset between /// requests on the same connection. arena: Allocator, version: Version, method: Method, target: Target, headers: Headers, /// What the transport knows about the channel this arrived on. connection: transport.Connection.Info, body: Body, /// The `:protocol` of RFC 8441's extended CONNECT, when the request carried /// one. /// /// This is HTTP/2's replacement for `Upgrade`, and it is deliberately not /// surfaced as one: a handler asks `offersUpgrade`, which answers from /// whichever mechanism the version in front of it actually has. Null for /// every HTTP/1.x request and for every HTTP/2 request that is not an /// extended CONNECT. connect_protocol: ?[]const u8 = null, /// The request body, already decoded: whatever transfer coding it arrived /// under has been taken off, so this is the content and not the framing. pub const Body = struct { reader: *Io.Reader, /// How long the body is, if the message said. `.unknown` is an HTTP/1.1 /// chunked body, whose length is not known until it ends. length: Length, pub const empty_reader: *Io.Reader = Io.Reader.ending; /// Whether there is a body at all. pub fn isPresent(b: Body) bool { return b.length != .none; } test isPresent { const none: Body = .{ .reader = empty_reader, .length = .none }; try std.testing.expect(!none.isPresent()); // An empty body is still a body: `Content-Length: 0` said so. const zero: Body = .{ .reader = empty_reader, .length = .{ .exact = 0 } }; try std.testing.expect(zero.isPresent()); } pub const ReadError = Io.Reader.LimitedAllocError; /// Reads the whole body into memory, refusing to read more than `limit`. /// /// The limit is not optional and there is no overload without one. A body /// of unknown length is whatever the client decides to send, and a server /// that reads it into memory until it stops is a server that can be /// stopped by one client. pub fn readAlloc(b: Body, gpa: Allocator, limit: usize) ReadError![]u8 { return b.reader.allocRemaining(gpa, .limited(limit)); } test readAlloc { const gpa = std.testing.allocator; var reader: Io.Reader = .fixed("name=value"); const body: Body = .{ .reader = &reader, .length = .{ .exact = 10 } }; const got = try body.readAlloc(gpa, 1024); defer gpa.free(got); try std.testing.expectEqualStrings("name=value", got); // One octet more than the limit is refused rather than truncated. var long: Io.Reader = .fixed("name=value"); const too_long: Body = .{ .reader = &long, .length = .unknown }; try std.testing.expectError(error.StreamTooLong, too_long.readAlloc(gpa, 9)); } }; /// The value of the first field with this name, or null. pub fn header(r: *const Request, name: []const u8) ?[]const u8 { return r.headers.get(name); } test header { var fields = [_]Headers.Field{ .{ .name = "Host", .value = "example.com" }, .{ .name = "Accept", .value = "text/html" }, .{ .name = "Accept", .value = "text/plain" }, }; const req = try example("/", &fields); // Names are compared without regard to case, and the first one wins. try std.testing.expectEqualStrings("text/html", req.header("ACCEPT").?); try std.testing.expect(req.header("cookie") == null); } /// The authority the request is for: the host and optional port it was /// addressed to. /// /// An absolute-form target carries it, and when it does it wins over the /// `Host` field — RFC 9112 §3.2.2 is explicit, and the reason is that a /// client and a proxy that disagree about which to believe is the whole shape /// of a cache poisoning attack. Everything else falls back to `Host`, which /// an HTTP/1.1 request must carry and an HTTP/1.0 request need not. pub fn authority(r: *const Request) ?[]const u8 { if (r.target.authority) |a| return a; return r.headers.get("host"); } test authority { var fields = [_]Headers.Field{.{ .name = "Host", .value = "example.com" }}; const origin_form = try example("/index.html", &fields); try std.testing.expectEqualStrings("example.com", origin_form.authority().?); // An absolute-form target overrules `Host`, as RFC 9112 §3.2.2 requires. const absolute_form = try example("http://example.net:8080/index.html", &fields); try std.testing.expectEqualStrings("example.net:8080", absolute_form.authority().?); // An HTTP/1.0 request may carry neither. const neither = try example("/", &.{}); try std.testing.expect(neither.authority() == null); } /// The scheme the request arrived over: `https` when the transport is /// confidential, `http` otherwise, unless an absolute-form target said /// something else. pub fn scheme(r: *const Request) []const u8 { if (r.target.scheme) |s| return s; return if (r.connection.secure) "https" else "http"; } test scheme { var req = try example("/", &.{}); try std.testing.expectEqualStrings("http", req.scheme()); req.connection.secure = true; try std.testing.expectEqualStrings("https", req.scheme()); // An absolute-form target names its own, whatever the channel is. var absolute = try example("http://example.com/", &.{}); absolute.connection.secure = true; try std.testing.expectEqualStrings("http", absolute.scheme()); } /// Whether the client said it would take a particular content coding — /// `gzip`, `br`, `zstd` — by RFC 9110 §12.5.3's reading of `Accept-Encoding`. /// /// A coding is accepted when its weight is above zero, whether the client /// named it or left it to `*`, and refused at `q=0`. `identity` is accepted /// unless it is refused one of those two ways. Names are compared without /// regard to case, and several `Accept-Encoding` fields read as one list. /// /// A request with no `Accept-Encoding` at all is answered as though it had /// accepted only `identity`. §12.5.3 calls every coding acceptable then, but /// a client that never mentioned a coding is the last one to send one to, /// which is the same choice `protocol.coding.selectEncoding` makes. /// /// It answers "may I send this" and not "which would this client like best": /// a caller choosing among several codings wants `selectEncoding`, which is /// what the server's own compression uses. pub fn acceptsEncoding(r: *const Request, coding_name: []const u8) bool { const identity = protocol.token.eqlIgnoreCase(coding_name, "identity"); var fields = r.headers.values("accept-encoding"); var any = false; var stated: ?protocol.coding.Quality = null; var star: ?protocol.coding.Quality = null; while (fields.next()) |value| { any = true; if (protocol.coding.statedWeight(value, coding_name)) |q| stated = q; if (protocol.coding.statedWeight(value, "*")) |q| star = q; } if (!any) return identity; const weight = stated orelse star orelse return identity; return weight > 0; } test acceptsEncoding { var fields = [_]Headers.Field{ .{ .name = "Accept-Encoding", .value = "gzip;q=1.0, br;q=0.5" }, .{ .name = "Accept-Encoding", .value = "zstd;q=0, *;q=0.1" }, }; const req = try example("/", &fields); // A weight does not hide the name it is attached to. try std.testing.expect(req.acceptsEncoding("gzip")); try std.testing.expect(req.acceptsEncoding("BR")); // `q=0` is a refusal, and the wildcard speaks for what is not named. try std.testing.expect(!req.acceptsEncoding("zstd")); try std.testing.expect(req.acceptsEncoding("compress")); // With no field at all, only `identity`. const bare = try example("/", &.{}); try std.testing.expect(!bare.acceptsEncoding("gzip")); try std.testing.expect(bare.acceptsEncoding("identity")); } /// Whether the client offered to switch this connection to `protocol_name`. /// /// The two versions ask entirely different questions and this is the point of /// the question being asked here rather than in the handler. Over HTTP/1.1 it /// is RFC 9110 §7.8's `Upgrade`, and both halves have to be there: `Upgrade` /// lists the protocols on offer, and `Connection: upgrade` is what marks that /// list as meant for this hop rather than forwarded by a proxy that did not /// understand it. Over HTTP/2 there is no `Upgrade` at all — those fields are /// forbidden by §8.2.2 — and the offer is RFC 8441's `:protocol` on an /// extended CONNECT. /// /// So a handler that wants to speak WebSocket writes the same two lines /// whichever version it is serving, which is the whole point of this library /// having a `Request` that is not a wire format. pub fn offersUpgrade(r: *const Request, protocol_name: []const u8) bool { if (r.connect_protocol) |offered| { // RFC 8441 §4: the value comes from the HTTP Upgrade Token registry, // whose tokens are compared case-insensitively like every other // token in HTTP. return protocol.token.eqlIgnoreCase(offered, protocol_name); } if (!r.headers.containsToken("connection", "upgrade")) return false; return r.headers.containsToken("upgrade", protocol_name); } test offersUpgrade { // HTTP/1.1: `Upgrade` lists the offer, and `Connection` makes it this // hop's. var fields = [_]Headers.Field{ .{ .name = "Connection", .value = "Upgrade" }, .{ .name = "Upgrade", .value = "websocket" }, }; const http11 = try example("/chat", &fields); try std.testing.expect(http11.offersUpgrade("websocket")); try std.testing.expect(!http11.offersUpgrade("h2c")); // Without `Connection: upgrade` the offer was not meant for this server. const forwarded = try example("/chat", fields[1..]); try std.testing.expect(!forwarded.offersUpgrade("websocket")); // HTTP/2: RFC 8441's extended CONNECT, and no `Upgrade` field at all. var h2 = try example("/chat", &.{}); h2.version = .http_2; h2.method = .connect; h2.connect_protocol = "websocket"; try std.testing.expect(h2.offersUpgrade("WebSocket")); } /// Whether the client asked for a conditional request to be evaluated — /// any of the `If-` fields. pub fn isConditional(r: *const Request) bool { return r.headers.has("if-match") or r.headers.has("if-none-match") or r.headers.has("if-modified-since") or r.headers.has("if-unmodified-since") or r.headers.has("if-range"); } test isConditional { var fields = [_]Headers.Field{.{ .name = "If-None-Match", .value = "\"v1\"" }}; const conditional = try example("/", &fields); try std.testing.expect(conditional.isConditional()); const plain = try example("/", &.{}); try std.testing.expect(!plain.isConditional()); } /// A request for the doctests, as a driver would have filled it in: `target` /// parsed, `fields` borrowed, and no body. fn example(target: []const u8, fields: []Headers.Field) Target.ParseError!Request { return .{ .io = std.testing.io, .arena = std.testing.allocator, .version = .http_1_1, .method = .get, .target = try .parse(target), .headers = .initBorrowed(fields), .connection = .{}, .body = .{ .reader = Body.empty_reader, .length = .none }, }; } test { std.testing.refAllDecls(@This()); }