// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! HTTP semantics: what a request and a response *mean*, with nothing in it //! about how either is written down. //! //! RFC 9110 made this separation explicit and it is the whole shape of this //! library. A method, a status, a target, a set of header fields and a body //! are the same things in HTTP/1.1, HTTP/2 and HTTP/3; what changes between //! the versions is the framing, and the framing lives in `http1` and in //! whatever is one day written beside it. Anything in this namespace can be //! used by all three, and nothing in it may know about a wire. //! //! Nothing here allocates unless it is handed an allocator, and nothing here //! does I/O. const std = @import("std"); pub const Headers = @import("protocol/Headers.zig"); pub const Method = @import("protocol/Method.zig"); pub const Target = @import("protocol/Target.zig"); pub const coding = @import("protocol/coding.zig"); pub const date = @import("protocol/date.zig"); pub const token = @import("protocol/token.zig"); /// The status codes, taken from the standard library rather than written out /// again. It is a non-exhaustive `enum(u10)`, so a code the registry has and /// this table does not is still `@fromBackingInt(599)`, and `phrase` returns /// null for it rather than refusing to compile. pub const Status = std.http.Status; /// A single header field, as `Headers` stores them. pub const Field = Headers.Field; /// Which version of HTTP a message is framed in. /// /// HTTP/0.9 is deliberately absent. It has no version on the request line, no /// headers and no status, so a server that accepts it cannot tell a 0.9 /// request from a mangled 1.0 one — and since 0.9 responses carry no headers, /// accepting it is a way to have a proxy read a response body as a set of /// headers. RFC 9112 §2.3 allows a server to refuse it and this one does. pub const Version = enum { http_1_0, http_1_1, http_2, http_3, pub const ParseError = error{ /// Not `HTTP/` followed by a digit, a dot and a digit. InvalidVersion, /// Well-formed, but a major version this cannot speak over a byte /// stream — which is what `505 HTTP Version Not Supported` is for. UnsupportedVersion, }; /// Reads the `HTTP-version` of an HTTP/1.x request line. /// /// A minor version above 1 is read as 1.1, which RFC 9112 §2.3 requires: /// a recipient that speaks 1.1 must treat `HTTP/1.9` as the highest /// minor version it knows, because minor versions were meant to be /// compatible and a future one would be wasted if every server refused /// it. A major version other than 1 is refused, because HTTP/2 and /// HTTP/3 are not framed like this at all and a request line claiming to /// be one is either confused or an attempt to get a `2.0` past /// something. pub fn parseHttp1(s: []const u8) ParseError!Version { if (s.len != "HTTP/1.1".len) return error.InvalidVersion; if (!std.mem.eql(u8, s[0..5], "HTTP/")) return error.InvalidVersion; if (s[6] != '.') return error.InvalidVersion; const major = std.fmt.charToDigit(s[5], 10) catch return error.InvalidVersion; const minor = std.fmt.charToDigit(s[7], 10) catch return error.InvalidVersion; if (major != 1) return error.UnsupportedVersion; return if (minor == 0) .http_1_0 else .http_1_1; } test parseHttp1 { try std.testing.expectEqual(Version.http_1_0, try Version.parseHttp1("HTTP/1.0")); try std.testing.expectEqual(Version.http_1_1, try Version.parseHttp1("HTTP/1.1")); // A future minor version is the highest one we know, not an error. try std.testing.expectEqual(Version.http_1_1, try Version.parseHttp1("HTTP/1.9")); try std.testing.expectError(error.UnsupportedVersion, Version.parseHttp1("HTTP/0.9")); try std.testing.expectError(error.UnsupportedVersion, Version.parseHttp1("HTTP/2.0")); try std.testing.expectError(error.InvalidVersion, Version.parseHttp1("HTTP/1")); try std.testing.expectError(error.InvalidVersion, Version.parseHttp1("http/1.1")); try std.testing.expectError(error.InvalidVersion, Version.parseHttp1("HTTP/x.1")); try std.testing.expectError(error.InvalidVersion, Version.parseHttp1("")); } /// How the version is written on an HTTP/1.x status line. HTTP/2 and /// HTTP/3 never write it down — the version is which connection you are /// on — so this is what they would be called if they did. pub fn toString(v: Version) []const u8 { return switch (v) { .http_1_0 => "HTTP/1.0", .http_1_1 => "HTTP/1.1", .http_2 => "HTTP/2", .http_3 => "HTTP/3", }; } test toString { try std.testing.expectEqualStrings("HTTP/1.1", Version.http_1_1.toString()); try std.testing.expectEqualStrings("HTTP/2", Version.http_2.toString()); } /// Whether a connection speaking this version stays open after a response /// unless something says otherwise. /// /// HTTP/1.0 is the odd one: it closes unless the client asked for /// `Connection: keep-alive`, where every later version keeps the /// connection until somebody closes it. pub fn isPersistentByDefault(v: Version) bool { return v != .http_1_0; } test isPersistentByDefault { try std.testing.expect(!Version.http_1_0.isPersistentByDefault()); try std.testing.expect(Version.http_1_1.isPersistentByDefault()); try std.testing.expect(Version.http_3.isPersistentByDefault()); } /// Writes `toString`, so that a version can be printed with `{f}`. pub fn format(v: Version, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.writeAll(v.toString()); } test format { var buf: [32]u8 = undefined; const line = try std.fmt.bufPrint(&buf, "{f} 200 OK", .{Version.http_1_1}); try std.testing.expectEqualStrings("HTTP/1.1 200 OK", line); } }; /// How much body there is, which is a different question from how the body is /// framed. /// /// A handler says which of these it means and the driver for the version in /// use picks the framing: `.exact` becomes a `Content-Length` in HTTP/1.1 and /// nothing at all in HTTP/2, where the frame layer carries the length; /// `.unknown` becomes `Transfer-Encoding: chunked` in HTTP/1.1, a closed /// connection in HTTP/1.0, and an ordinary sequence of DATA frames in HTTP/2. /// Keeping the choice at this level is what lets one handler serve all three. pub const Length = union(enum) { /// There is no body. Not a body of zero octets — no body at all, which /// is what a `204`, a `304` and a response to `HEAD` have, and which is /// why none of them carry a `Content-Length` of `0`. none, /// Exactly this many octets, known before the first is written. exact: u64, /// However many get written. The framing carries the end. unknown, }; /// `Content-Length` is a string of digits and nothing else. /// /// `parseInt` would accept a leading `+`, a leading `-` and an underscore /// between digits, each of which is a value that this server and something /// else in the chain would read differently. pub fn parseContentLength(value: []const u8) ?u64 { if (value.len == 0 or value.len > 20) return null; var n: u64 = 0; for (value) |c| { if (!std.ascii.isDigit(c)) return null; n = std.math.mul(u64, n, 10) catch return null; n = std.math.add(u64, n, c - '0') catch return null; } return n; } test parseContentLength { try std.testing.expectEqual(@as(u64, 0), parseContentLength("0").?); try std.testing.expectEqual(@as(u64, 42), parseContentLength("42").?); try std.testing.expectEqual(@as(u64, 7), parseContentLength("0007").?); // Everything `parseInt` would have taken and a server must not. try std.testing.expect(parseContentLength("") == null); try std.testing.expect(parseContentLength("+5") == null); try std.testing.expect(parseContentLength("-5") == null); try std.testing.expect(parseContentLength("1_0") == null); try std.testing.expect(parseContentLength(" 5") == null); try std.testing.expect(parseContentLength("5 ") == null); try std.testing.expect(parseContentLength("0x10") == null); // Longer than any body can be. try std.testing.expect(parseContentLength("99999999999999999999") == null); } test { std.testing.refAllDecls(@This()); } /// How long a *response* body is, which §6.3 of RFC 9112 answers with eight /// rules in order of precedence. /// /// A separate question from the request side, and the differences are the /// interesting part. A request without framing has no body; a response /// without framing runs until the connection closes, which is HTTP/1.0's /// only way of saying "that is all" and the reason `until_close` exists at /// all. And what the response is *to* decides more than the response's own /// fields do: a `HEAD` is answered with the head of what a `GET` would have /// returned, `Content-Length` and all, and none of it is body. pub const ResponseFraming = union(enum) { /// No body, whatever the fields say. none, /// Exactly this many octets. exact: u64, /// Chunked, ending when the coding says so. chunked, /// Until the connection closes, which is also how a truncated response /// looks -- §6.3 says so in as many words, which is why a sender "SHOULD /// generate encoding or length-delimited messages whenever possible". until_close, /// The framing is unusable and the response cannot be believed: §6.3's /// rule 5, where a recipient "MUST treat it as an unrecoverable error". invalid, }; /// Applies §6.3 to a response. /// /// `status` and `headers` are the response's own. `to_head` says whether the /// request was a `HEAD`, and `to_connect` whether it was a `CONNECT`, because /// neither is knowable from the response. pub fn responseFraming( status: u16, to_head: bool, to_connect: bool, headers: *const Headers, ) ResponseFraming { // Rule 1: "any response to a HEAD request and any response with a 1xx // (Informational), 204 (No Content), or 304 (Not Modified) status code is // always terminated by the first empty line after the header fields, // regardless of the header fields present in the message". if (to_head) return .none; if (status >= 100 and status < 200) return .none; if (status == 204 or status == 304) return .none; // Rule 2: a 2xx to CONNECT becomes a tunnel, and "a client MUST ignore // any Content-Length or Transfer-Encoding header fields received in such // a message". What follows the head is the tunnel, not a body. if (to_connect and status >= 200 and status < 300) return .none; // Both fields are lists, and a list may be split across several field // lines with the same name (RFC 9110 §5.3), so every line is read: the // second of two `Content-Length` lines that disagree is exactly the // response splitting rule 5 is there to refuse. if (headers.has("transfer-encoding")) { // Rule 3: "If a message is received with both a Transfer-Encoding and // a Content-Length header field, the Transfer-Encoding overrides the // Content-Length. Such a message might indicate an attempt to perform // request smuggling or response splitting and ought to be handled as // an error." Handled as an error here: a message two participants // would frame differently is the whole shape of response splitting, // and this library is not a proxy that has to forward it. if (headers.has("content-length")) return .invalid; // Rule 4: chunked as the final coding is chunked; anything else in a // *response* runs to the close. Unlike a request, where the same // ambiguity is a 400 -- a response has somewhere to go. var lines = headers.values("transfer-encoding"); var last: ?[]const u8 = null; while (lines.next()) |value| { var it = token.list(value); // A *transfer* coding, which §7 of RFC 9112 keeps separate from // the content codings in `protocol.coding`: this one is the // framing and hop by hop, that one is the representation and end // to end. while (it.next()) |transfer_coding| last = transfer_coding; } const final = last orelse return .invalid; if (token.eqlIgnoreCase(final, "chunked")) return .chunked; return .until_close; } if (headers.has("content-length")) { // Rules 5 and 6. A list whose values all agree is permitted and means // that value; anything else is unrecoverable. var lines = headers.values("content-length"); var agreed: ?u64 = null; while (lines.next()) |value| { var it = token.list(value); var any = false; while (it.next()) |one| { any = true; const n = parseContentLength(one) orelse return .invalid; if (agreed) |previous| { if (previous != n) return .invalid; } else agreed = n; } if (!any) return .invalid; } return .{ .exact = agreed.? }; } // Rule 8: no declared length, so the body is whatever arrives before the // connection closes. return .until_close; } const testing = std.testing; /// Builds a header set from pairs, for the framing tests below. fn framingHeaders(gpa: std.mem.Allocator, pairs: []const [2][]const u8) !Headers { var headers: Headers = .empty; for (pairs) |pair| try headers.append(gpa, pair[0], pair[1]); return headers; } test responseFraming { const gpa = testing.allocator; var headers: Headers = .empty; defer headers.deinit(gpa); try headers.append(gpa, "Content-Length", "11"); try testing.expectEqual(ResponseFraming{ .exact = 11 }, responseFraming(200, false, false, &headers)); // The same head answering a `HEAD` describes a body that is not sent. try testing.expectEqual(ResponseFraming.none, responseFraming(200, true, false, &headers)); headers.clearRetainingCapacity(); try headers.append(gpa, "Transfer-Encoding", "chunked"); try testing.expectEqual(ResponseFraming.chunked, responseFraming(200, false, false, &headers)); } test "RFC 9112 6.3 rule 1: some responses have no body whatever they claim" { // "regardless of the header fields present in the message" -- a `HEAD` is // answered with the head a `GET` would have had, `Content-Length` and // all, and none of it is body. A client that believed the field would // read the next response as this one's content. const gpa = testing.allocator; var headers = try framingHeaders(gpa, &.{.{ "content-length", "1234" }}); defer headers.deinit(gpa); try testing.expectEqual(ResponseFraming.none, responseFraming(200, true, false, &headers)); try testing.expectEqual(ResponseFraming.none, responseFraming(204, false, false, &headers)); try testing.expectEqual(ResponseFraming.none, responseFraming(304, false, false, &headers)); try testing.expectEqual(ResponseFraming.none, responseFraming(100, false, false, &headers)); // And the same fields on an ordinary response mean what they say. try testing.expectEqual(ResponseFraming{ .exact = 1234 }, responseFraming(200, false, false, &headers)); } test "RFC 9112 6.3 rule 2: a 2xx to CONNECT is a tunnel, not a body" { const gpa = testing.allocator; var headers = try framingHeaders(gpa, &.{.{ "content-length", "5" }}); defer headers.deinit(gpa); try testing.expectEqual(ResponseFraming.none, responseFraming(200, false, true, &headers)); // A refusal is an ordinary response with an ordinary body. try testing.expectEqual(ResponseFraming{ .exact = 5 }, responseFraming(403, false, true, &headers)); } test "RFC 9112 6.3 rule 3: both framings at once is unusable" { // "Such a message might indicate an attempt to perform request smuggling // or response splitting and ought to be handled as an error." Two // participants that frame one message differently is the whole of that // attack, so this refuses rather than picking a winner. const gpa = testing.allocator; var headers = try framingHeaders(gpa, &.{ .{ "transfer-encoding", "chunked" }, .{ "content-length", "5" }, }); defer headers.deinit(gpa); try testing.expectEqual(ResponseFraming.invalid, responseFraming(200, false, false, &headers)); } test "RFC 9112 6.3 rule 4: chunked last is chunked, anything else runs to the close" { const gpa = testing.allocator; var chunked = try framingHeaders(gpa, &.{.{ "transfer-encoding", "gzip, chunked" }}); defer chunked.deinit(gpa); try testing.expectEqual(ResponseFraming.chunked, responseFraming(200, false, false, &chunked)); // "If a Transfer-Encoding header field is present in a response and the // chunked transfer coding is not the final encoding, the message body // length is determined by reading the connection until it is closed" -- // where the same thing in a *request* is a 400, because a request has // nowhere to put an unframed body. var trailing = try framingHeaders(gpa, &.{.{ "transfer-encoding", "chunked, gzip" }}); defer trailing.deinit(gpa); try testing.expectEqual(ResponseFraming.until_close, responseFraming(200, false, false, &trailing)); } test "RFC 9112 6.3 rules 5 and 6: a length list may repeat itself but not disagree" { const gpa = testing.allocator; var agreed = try framingHeaders(gpa, &.{.{ "content-length", "42, 42" }}); defer agreed.deinit(gpa); try testing.expectEqual(ResponseFraming{ .exact = 42 }, responseFraming(200, false, false, &agreed)); var disagreed = try framingHeaders(gpa, &.{.{ "content-length", "42, 43" }}); defer disagreed.deinit(gpa); try testing.expectEqual(ResponseFraming.invalid, responseFraming(200, false, false, &disagreed)); // Not a number at all. `parseInt` would have taken `+5`, which is a value // this and something else in the chain would read differently. var bad = try framingHeaders(gpa, &.{.{ "content-length", "+5" }}); defer bad.deinit(gpa); try testing.expectEqual(ResponseFraming.invalid, responseFraming(200, false, false, &bad)); } test "RFC 9112 6.3 rule 8: a response that declares nothing runs to the close" { // HTTP/1.0's only way of saying "that is all", and indistinguishable from // a truncated response -- which is why §6.3 asks senders not to rely on // it. const gpa = testing.allocator; var headers = try framingHeaders(gpa, &.{}); defer headers.deinit(gpa); try testing.expectEqual(ResponseFraming.until_close, responseFraming(200, false, false, &headers)); } test "RFC 9112 6.3 rule 5: two Content-Length field lines that disagree are invalid" { // The same list as "2, 5", split over two lines. Reading only the first // would hand the caller two octets and parse the rest as the next // response. const gpa = testing.allocator; var headers = try framingHeaders(gpa, &.{ .{ "content-length", "2" }, .{ "content-length", "5" }, }); defer headers.deinit(gpa); try testing.expectEqual(ResponseFraming.invalid, responseFraming(200, false, false, &headers)); var agreed = try framingHeaders(gpa, &.{ .{ "content-length", "5" }, .{ "content-length", "5" }, }); defer agreed.deinit(gpa); try testing.expectEqual(ResponseFraming{ .exact = 5 }, responseFraming(200, false, false, &agreed)); } test "RFC 9112 6.3 rule 4: Transfer-Encoding split over two field lines is one list" { const gpa = testing.allocator; var headers = try framingHeaders(gpa, &.{ .{ "transfer-encoding", "chunked" }, .{ "transfer-encoding", "gzip" }, }); defer headers.deinit(gpa); // "chunked, gzip": chunked is not last, so the body runs to the close. try testing.expectEqual(ResponseFraming.until_close, responseFraming(200, false, false, &headers)); }