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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An ordered list of header fields.//!//! Ordered, and a list rather than a map, because HTTP fields are both: order//! is significant within a field name (RFC 9110 §5.3 — two `Set-Cookie` lines//! are two cookies, and two `Via` lines are a path through proxies in order),//! and a name may legitimately appear more than once. A map would lose the//! first and hide the second.//!//! Names are compared without regard to case, and stored exactly as they were//! given. HTTP/1.1 sends them as written; HTTP/2 and HTTP/3 require them//! lower-cased on the wire, so a driver for either lower-cases on the way out//! rather than this type doing it on the way in — a handler that wants//! `X-Request-Id` in its logs should not have to get it back as//! `x-request-id` because of a version it never asked about.//!//! Nothing here copies. A `Headers` parsed out of a request borrows the buffer//! the head was read into and is valid until the next request on that//! connection; one built for a response borrows whatever the handler passed,//! which must outlive the response. `Response.printHeader` is the way to add//! one whose value has to be computed.
const std = @import("std");const Allocator = std.mem.Allocator;
const token = @import("token.zig");
const Headers = @This();
/// One field line: a name and the value it was given, with the optional/// whitespace around the value already stripped.pub const Field = struct { name: []const u8, value: []const u8,};
fields: std.ArrayList(Field),
pub const empty: Headers = .{ .fields = .empty };
/// Wraps a slice of fields that somebody else owns — what a parsed request/// head produces.////// The slice becomes the list's storage without being copied, so the result/// is for reading: appending to it, or calling `deinit` on it, would hand/// memory to an allocator that never gave it out.pub fn initBorrowed(fields: []Field) Headers { return .{ .fields = .fromOwnedSlice(fields) };}
/// Releases the field list. Does not touch the names and values, which this/// type never owned.pub fn deinit(h: *Headers, gpa: Allocator) void { h.fields.deinit(gpa); h.* = undefined;}
/// Empties the list without giving back its memory, so that the next request/// on a kept-alive connection reuses the allocation.pub fn clearRetainingCapacity(h: *Headers) void { h.fields.clearRetainingCapacity();}
/// The value of the first field with this name, or null.////// "First" matters for the fields where a duplicate is an attack rather than/// a list: see `getUnique`, which is what `Content-Length` and `Host` are/// read with.pub fn get(h: *const Headers, name: []const u8) ?[]const u8 { for (h.fields.items) |field| { if (token.eqlIgnoreCase(field.name, name)) return field.value; } return null;}
pub const UniqueError = error{ /// The field appeared more than once with values that are not identical. DuplicateField,};
/// The value of the field with this name, insisting there is at most one.////// Two `Content-Length` lines, or two `Host` lines, are how a request is/// smuggled past a proxy that reads one of them and a server that reads the/// other. RFC 9112 §6.3 requires such a message to be rejected, and this is/// the check that rejects it. Repeats of an identical value are allowed,/// because that is a duplicated header rather than a disagreement.pub fn getUnique(h: *const Headers, name: []const u8) UniqueError!?[]const u8 { var found: ?[]const u8 = null; for (h.fields.items) |field| { if (!token.eqlIgnoreCase(field.name, name)) continue; if (found) |first| { if (!std.mem.eql(u8, first, field.value)) return error.DuplicateField; } else found = field.value; } return found;}
/// Whether any field has this name, whatever its value.pub fn has(h: *const Headers, name: []const u8) bool { return h.get(name) != null;}
/// How many fields have this name.pub fn count(h: *const Headers, name: []const u8) usize { var n: usize = 0; for (h.fields.items) |field| { if (token.eqlIgnoreCase(field.name, name)) n += 1; } return n;}
/// Walks every value given for one name, in the order they arrived.pub const ValueIterator = struct { fields: []const Field, name: []const u8, index: usize = 0,
/// The next value given for the name, or null once there are no more. pub fn next(it: *ValueIterator) ?[]const u8 { while (it.index < it.fields.len) { const field = it.fields[it.index]; it.index += 1; if (token.eqlIgnoreCase(field.name, it.name)) return field.value; } return null; }
test next { var fields = [_]Field{ .{ .name = "Via", .value = "1.1 a" }, .{ .name = "Server", .value = "zig-http" }, .{ .name = "via", .value = "1.1 b" }, }; const h: Headers = .initBorrowed(&fields); var it = h.values("Via"); try std.testing.expectEqualStrings("1.1 a", it.next().?); try std.testing.expectEqualStrings("1.1 b", it.next().?); try std.testing.expect(it.next() == null); }};
/// Walks every value given for `name`, matched without regard to case, in the/// order the fields arrived. The iterator borrows the field list, so the/// headers must not change while it is in use.pub fn values(h: *const Headers, name: []const u8) ValueIterator { return .{ .fields = h.fields.items, .name = name };}
/// Whether any field with this name has `needle` as an element of its value/// read as a comma-separated list.////// Every field that is a list may also be split across several lines with the/// same name, which is why this searches all of them rather than just the/// first: `Connection: keep-alive` followed by `Connection: close` says/// close.pub fn containsToken(h: *const Headers, name: []const u8, needle: []const u8) bool { var it = h.values(name); while (it.next()) |value| { if (token.containsToken(value, needle)) return true; } return false;}
pub const AppendError = Allocator.Error || error{ /// The name is not a `token`, or the value carries an octet that would /// change the framing of the message around it. InvalidField,};
/// Adds a field, keeping any field of the same name that is already there.////// The name and the value are checked: a value with a CR or an LF in it is/// how a response is split in two, and the moment to refuse it is here rather/// than at the point where it is written and the damage is already framed.pub fn append(h: *Headers, gpa: Allocator, name: []const u8, value: []const u8) AppendError!void { if (!token.isToken(name)) return error.InvalidField; if (!token.isFieldValue(value)) return error.InvalidField; try h.fields.append(gpa, .{ .name = name, .value = value });}
/// Adds a field without checking it. For a parser, which has already/// established that what it is holding came off the wire as a well-formed/// field line, and would otherwise validate every field twice.pub fn appendAssumeValid(h: *Headers, gpa: Allocator, name: []const u8, value: []const u8) Allocator.Error!void { try h.fields.append(gpa, .{ .name = name, .value = value });}
/// Replaces every field of this name with one holding `value`.pub fn set(h: *Headers, gpa: Allocator, name: []const u8, value: []const u8) AppendError!void { if (!token.isToken(name)) return error.InvalidField; if (!token.isFieldValue(value)) return error.InvalidField; _ = h.remove(name); try h.fields.append(gpa, .{ .name = name, .value = value });}
/// Removes every field of this name, returning how many went.pub fn remove(h: *Headers, name: []const u8) usize { var kept: usize = 0; var removed: usize = 0; for (h.fields.items) |field| { if (token.eqlIgnoreCase(field.name, name)) { removed += 1; } else { h.fields.items[kept] = field; kept += 1; } } h.fields.items.len = kept; return removed;}
test get { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Content-Type", "text/plain"); try h.append(gpa, "Set-Cookie", "a=1"); try h.append(gpa, "Set-Cookie", "b=2");
try std.testing.expectEqualStrings("text/plain", h.get("content-TYPE").?); try std.testing.expect(h.get("content-length") == null); try std.testing.expectEqual(@as(usize, 2), h.count("set-cookie"));
// Both cookies survive, in order. var it = h.values("Set-Cookie"); try std.testing.expectEqualStrings("a=1", it.next().?); try std.testing.expectEqualStrings("b=2", it.next().?); try std.testing.expect(it.next() == null);}
test getUnique { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Content-Length", "10"); try std.testing.expectEqualStrings("10", (try h.getUnique("content-length")).?);
// An identical repeat is a duplicated header, not a disagreement. try h.append(gpa, "Content-Length", "10"); try std.testing.expectEqualStrings("10", (try h.getUnique("content-length")).?);
// A different value is the shape a smuggled request has. try h.append(gpa, "Content-Length", "0"); try std.testing.expectError(error.DuplicateField, h.getUnique("content-length"));}
test append { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try std.testing.expectError(error.InvalidField, h.append(gpa, "X Bad Name", "v")); try std.testing.expectError(error.InvalidField, h.append(gpa, "Location", "/a\r\nSet-Cookie: stolen=1")); try std.testing.expectEqual(@as(usize, 0), h.fields.items.len);}
test set { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Vary", "Accept"); try h.append(gpa, "Server", "zig-http"); try h.append(gpa, "Vary", "Origin"); try h.set(gpa, "vary", "*");
try std.testing.expectEqual(@as(usize, 1), h.count("Vary")); try std.testing.expectEqualStrings("*", h.get("Vary").?); // Removing the duplicates left the unrelated field alone. try std.testing.expectEqualStrings("zig-http", h.get("Server").?);}
test containsToken { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Connection", "keep-alive"); try h.append(gpa, "Connection", "close"); try std.testing.expect(h.containsToken("connection", "CLOSE")); try std.testing.expect(!h.containsToken("connection", "upgrade"));}
test initBorrowed { // What a parser has: field lines already split, in a buffer it owns. var fields = [_]Field{ .{ .name = "Host", .value = "example.com" }, .{ .name = "Accept", .value = "*/*" }, }; const h: Headers = .initBorrowed(&fields); try std.testing.expectEqualStrings("example.com", h.get("host").?); try std.testing.expectEqual(@as(usize, 2), h.fields.items.len);}
test deinit { var h: Headers = .empty; try h.append(std.testing.allocator, "Server", "zig-http"); h.deinit(std.testing.allocator);}
test clearRetainingCapacity { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Content-Type", "text/plain"); const capacity = h.fields.capacity; h.clearRetainingCapacity(); try std.testing.expect(!h.has("Content-Type")); try std.testing.expectEqual(capacity, h.fields.capacity);}
test has { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
// An empty value is still a field that is present. try h.append(gpa, "X-Empty", ""); try std.testing.expect(h.has("x-empty")); try std.testing.expect(!h.has("X-Missing"));}
test count { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Set-Cookie", "a=1"); try h.append(gpa, "set-cookie", "b=2"); try std.testing.expectEqual(@as(usize, 2), h.count("SET-COOKIE")); try std.testing.expectEqual(@as(usize, 0), h.count("Cookie"));}
test values { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Cache-Control", "no-cache"); try h.append(gpa, "Vary", "Accept"); try h.append(gpa, "Cache-Control", "no-store");
var it = h.values("cache-control"); try std.testing.expectEqualStrings("no-cache", it.next().?); try std.testing.expectEqualStrings("no-store", it.next().?); try std.testing.expect(it.next() == null);}
test appendAssumeValid { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
// Nothing is checked, so this is only for a caller that already has. try h.appendAssumeValid(gpa, "Content-Length", "42"); try std.testing.expectEqualStrings("42", h.get("content-length").?);}
test remove { const gpa = std.testing.allocator; var h: Headers = .empty; defer h.deinit(gpa);
try h.append(gpa, "Connection", "keep-alive"); try h.append(gpa, "Server", "zig-http"); try h.append(gpa, "connection", "close");
try std.testing.expectEqual(@as(usize, 2), h.remove("Connection")); try std.testing.expect(!h.has("Connection")); try std.testing.expectEqualStrings("zig-http", h.get("Server").?); try std.testing.expectEqual(@as(usize, 0), h.remove("Connection"));}