// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Field values taken apart the way RFC 9110 §5.6 says they go together: //! tokens, quoted strings, optional whitespace, and lists of the three. //! //! None of this is specific to a version of HTTP. HTTP/2 and HTTP/3 carry the //! same field values in a different frame, and a `Connection: close` in an //! HTTP/1.1 head and a `te: trailers` in an HPACK block are the same grammar //! either side of the compression. //! //! Every comparison here is ASCII-only and deliberately so. HTTP field names //! and the tokens inside field values are ASCII by definition, and a //! Unicode-aware case fold would make `İ` match `i` — which is how a //! `Transfer-Encoding: CHUNKED` check comes to miss a header that some other //! participant in the chain will honor. const std = @import("std"); /// The characters a `token` may be made of (RFC 9110 §5.6.2). /// /// Worth reading once, because the surprises are in what is allowed rather /// than what is not: `!`, `#`, `$`, `%`, `&`, `'`, `*`, `+`, `-`, `.`, `^`, /// `_`, `` ` ``, `|` and `~` are all perfectly good header-name characters, /// which is why a name cannot be validated by testing it for letters. pub fn isTokenChar(c: u8) bool { return switch (c) { '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~' => true, '0'...'9', 'a'...'z', 'A'...'Z' => true, else => false, }; } /// Whether `s` is a `token`: one or more token characters. The empty string /// is not one, which is why a field line with nothing before the colon is a /// bad request rather than a field with an empty name. pub fn isToken(s: []const u8) bool { if (s.len == 0) return false; for (s) |c| if (!isTokenChar(c)) return false; return true; } /// Optional whitespace: the space and the horizontal tab, and nothing else. /// A carriage return or a line feed inside a field value is a response /// splitting attack rather than whitespace, which is why `isFieldValue` /// rejects them. pub fn isOws(c: u8) bool { return c == ' ' or c == '\t'; } /// Whether `s` can be sent as a field value without changing the framing of /// the message around it. /// /// This is the check that stops response splitting: a value carrying a CR or /// an LF would end the field line early in HTTP/1.1 and let whatever follows /// be read as a header of its own, or as a second response. HTTP/2 and /// HTTP/3 reject such a value at the connection level instead, so a value /// that fails here is malformed in every version and the check belongs where /// both can reach it. /// /// Leading and trailing whitespace is rejected as well, because it is not /// part of the value: RFC 9112 §5 has the recipient strip it, so a value that /// carries it will not survive a round trip and the caller is better told. pub fn isFieldValue(s: []const u8) bool { if (s.len != 0 and (isOws(s[0]) or isOws(s[s.len - 1]))) return false; for (s) |c| switch (c) { // field-content is field-vchar with SP and HTAB allowed between. 0x09, 0x20, 0x21...0x7e => {}, // obs-text. Deprecated, and its meaning is not defined, but it is // still what a header holding a Latin-1 filename is made of. 0x80...0xff => {}, // CTLs, which includes CR, LF and NUL, and DEL. else => return false, }; return true; } /// ASCII case-insensitive equality, which is what HTTP means by /// case-insensitive everywhere it says so: field names, and the tokens /// inside `Connection`, `Transfer-Encoding`, `Expect` and their like. pub fn eqlIgnoreCase(a: []const u8, b: []const u8) bool { return std.ascii.eqlIgnoreCase(a, b); } /// Strips leading and trailing optional whitespace. pub fn trimOws(s: []const u8) []const u8 { return std.mem.trim(u8, s, " \t"); } /// Walks a comma-separated list field value (RFC 9110 §5.6.1), yielding each /// element with its surrounding whitespace removed and empty elements /// skipped — `"a,, b"` is the two-element list `a`, `b`, because senders are /// allowed to emit empty elements and recipients are required to ignore them. /// /// Commas inside a quoted string do not separate elements, which matters for /// the fields whose members carry parameters: `Accept: /// text/plain;q="0.5,x"` is one member, not two. pub const List = struct { rest: []const u8, /// The next non-empty element with its optional whitespace trimmed, or /// null at the end of the value. pub fn next(it: *List) ?[]const u8 { while (true) { if (it.rest.len == 0) return null; const end = splitPoint(it.rest); const element = trimOws(it.rest[0..end]); it.rest = if (end == it.rest.len) it.rest[end..] else it.rest[end + 1 ..]; if (element.len != 0) return element; } } test next { var it = list("no-cache, max-age=0"); try std.testing.expectEqualStrings("no-cache", it.next().?); try std.testing.expectEqualStrings("max-age=0", it.next().?); try std.testing.expect(it.next() == null); } /// The index of the comma that ends the first element, or the length of /// `s` when there is no such comma. fn splitPoint(s: []const u8) usize { var i: usize = 0; var quoted = false; while (i < s.len) : (i += 1) { switch (s[i]) { '"' => quoted = !quoted, // Inside a quoted string a backslash quotes the next octet, // including a quote or a comma. '\\' => if (quoted) { i += 1; }, ',' => if (!quoted) return i, else => {}, } } return s.len; } }; /// Starts a walk over `field_value` as a comma-separated list. pub fn list(field_value: []const u8) List { return .{ .rest = field_value }; } /// Whether `field_value`, read as a comma-separated list, has an element /// equal to `needle` ignoring case. /// /// This is the shape of nearly every decision HTTP/1.1 makes about framing: /// whether `Connection` says `close`, whether `Transfer-Encoding` says /// `chunked`, whether `Expect` says `100-continue`. Note that it tests whole /// elements: `Connection: close-enough` does not say `close`, where a /// substring search would have said it did. pub fn containsToken(field_value: []const u8, needle: []const u8) bool { var it = list(field_value); while (it.next()) |element| { if (eqlIgnoreCase(element, needle)) return true; } return false; } /// The last element of `field_value` read as a list, or null when the list is /// empty. /// /// `Transfer-Encoding` is defined by its last element — chunked must be the /// final coding applied, so it is the final element — and that is the only /// reason this exists. pub fn lastElement(field_value: []const u8) ?[]const u8 { var it = list(field_value); var last: ?[]const u8 = null; while (it.next()) |element| last = element; return last; } test isTokenChar { try std.testing.expect(isTokenChar('a')); try std.testing.expect(isTokenChar('7')); // Punctuation a name may hold, and is easy to forget. try std.testing.expect(isTokenChar('~')); try std.testing.expect(isTokenChar('\'')); try std.testing.expect(!isTokenChar(':')); try std.testing.expect(!isTokenChar(' ')); try std.testing.expect(!isTokenChar('"')); } test isOws { try std.testing.expect(isOws(' ')); try std.testing.expect(isOws('\t')); try std.testing.expect(!isOws('\r')); try std.testing.expect(!isOws('\n')); } test eqlIgnoreCase { try std.testing.expect(eqlIgnoreCase("Transfer-Encoding", "transfer-encoding")); try std.testing.expect(eqlIgnoreCase("CHUNKED", "chunked")); try std.testing.expect(!eqlIgnoreCase("chunked", "chunked ")); } test trimOws { try std.testing.expectEqualStrings("gzip", trimOws(" \tgzip \t")); // Only the ends: whitespace inside the value is part of it. try std.testing.expectEqualStrings("a b", trimOws(" a b ")); try std.testing.expectEqualStrings("", trimOws(" ")); } test list { var it = list("gzip, , chunked"); try std.testing.expectEqualStrings("gzip", it.next().?); try std.testing.expectEqualStrings("chunked", it.next().?); try std.testing.expect(it.next() == null); } test isToken { try std.testing.expect(isToken("GET")); try std.testing.expect(isToken("x-forwarded-for")); try std.testing.expect(isToken("!#$%&'*+-.^_`|~")); try std.testing.expect(!isToken("")); try std.testing.expect(!isToken("has space")); try std.testing.expect(!isToken("colon:")); try std.testing.expect(!isToken("(comment)")); } test isFieldValue { try std.testing.expect(isFieldValue("")); try std.testing.expect(isFieldValue("text/plain; charset=utf-8")); try std.testing.expect(isFieldValue("a\tb")); try std.testing.expect(!isFieldValue(" leading")); try std.testing.expect(!isFieldValue("trailing ")); try std.testing.expect(!isFieldValue("split\r\nInjected: yes")); try std.testing.expect(!isFieldValue("bare\nlf")); try std.testing.expect(!isFieldValue("nul\x00")); } test List { var it = list("gzip, chunked"); try std.testing.expectEqualStrings("gzip", it.next().?); try std.testing.expectEqualStrings("chunked", it.next().?); try std.testing.expect(it.next() == null); // Empty elements are skipped rather than yielded. var empties = list(", ,a,,"); try std.testing.expectEqualStrings("a", empties.next().?); try std.testing.expect(empties.next() == null); // A comma inside a quoted string does not split. var quoted = list("one;p=\"a,b\", two"); try std.testing.expectEqualStrings("one;p=\"a,b\"", quoted.next().?); try std.testing.expectEqualStrings("two", quoted.next().?); try std.testing.expect(quoted.next() == null); // A backslash inside a quoted string quotes the next octet, including a // quote -- so the string does not end there and the comma stays inside. var escaped = list("one;p=\"a\\\",b\", two"); try std.testing.expectEqualStrings("one;p=\"a\\\",b\"", escaped.next().?); try std.testing.expectEqualStrings("two", escaped.next().?); } test containsToken { try std.testing.expect(containsToken("keep-alive, Upgrade", "upgrade")); try std.testing.expect(containsToken("close", "CLOSE")); try std.testing.expect(!containsToken("close-enough", "close")); try std.testing.expect(!containsToken("", "close")); } test lastElement { try std.testing.expectEqualStrings("chunked", lastElement("gzip, chunked").?); try std.testing.expectEqualStrings("gzip", lastElement("gzip").?); try std.testing.expect(lastElement("") == null); }