// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The header block of a message or a part: an ordered list of `Name: value`, //! which is a list and not a map. //! //! Three properties of mail headers rule out the obvious data structure: //! //! * **Order is information.** `Received:` lines are the delivery path in //! reverse, and reordering them destroys it. So does reordering a //! `DKIM-Signature` relative to what it signed. //! * **Names repeat.** `Received:`, `Resent-*`, `Comments:` and `Keywords:` //! may all appear many times, and a `To:` that appears twice is malformed //! but real, and a reader that keeps only one of them shows the wrong //! recipients. //! * **The bytes are evidence.** A message that has been signed must be //! written back out exactly as it arrived, down to where the folds fall, or //! the signature no longer verifies. //! //! So a field stores its value in *wire form*: exactly the bytes that followed //! the colon, folds and all, minus the CRLF that ended the last line. Writing //! is then a copy, and a parsed message written back out is byte-identical. //! `append` folds what it is given on the way in, so a value built in a //! program is in the same form as one that was parsed, and the writer never //! has to know which it has. //! //! Values come back as they were written. `getUnfolded` removes the folds and //! `getUtf8` also undoes RFC 2047, and both keep what they produced, so the //! result lives as long as the headers do and the caller frees nothing. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const encoded_word = @import("codec/encoded_word.zig"); const field = @import("header/field.zig"); const line_ending = @import("line_ending.zig"); const Headers = @This(); /// Where every name, value and derived string is allocated. Pass an arena and /// `deinit` becomes unnecessary, which is how `Message` uses this. gpa: Allocator, fields: std.ArrayList(Field) = .empty, /// What `getUnfolded` and `getUtf8` produced. Keeping them is what lets those /// return a plain slice that the caller never frees; this is where they are /// freed instead. derived: std.ArrayList([]u8) = .empty, /// Whether the last field of the block ended with a line ending. /// /// Every line of a header block ends — except the last line of a block that /// was cut short, which for a `message/rfc822` part holding nothing but /// headers is the ordinary case rather than a defect: the line ending in /// front of a multipart's boundary belongs to the boundary, so the part's own /// last line has none. Writing one that was not there grows the message every /// time it is opened and saved. trailing_newline: bool = true, pub const Field = struct { /// As written: header names are case-insensitive, and a signature over /// them is not. name: []const u8, /// Wire form — folded as it will be written, without the trailing CRLF and /// without the space that followed the colon. value: []const u8, }; pub fn init(gpa: Allocator) Headers { return .{ .gpa = gpa }; } pub fn deinit(self: *Headers) void { for (self.fields.items) |f| { self.gpa.free(f.name); self.gpa.free(f.value); } for (self.derived.items) |bytes| self.gpa.free(bytes); self.fields.deinit(self.gpa); self.derived.deinit(self.gpa); self.* = undefined; } /// Parses a header block: everything up to but not including the blank line /// that ends it. /// /// A line that is neither a `Name: value` nor a continuation is skipped. The /// commonest is the `From ` line an mbox file puts in front of each message, /// which is not a header at all; the next commonest is a message whose headers /// were truncated in the middle of one. pub fn parse(gpa: Allocator, block: []const u8) Allocator.Error!Headers { var self: Headers = .init(gpa); errdefer self.deinit(); var i: usize = 0; while (i < block.len) { const line = lineAt(block, i); const split = field.split(block[i..line.text_end]) orelse { i = line.next; continue; }; // The value begins where the slice `split` handed back begins, which // is just past the colon. const value_start = line.text_end - split.value.len; var value_end = line.text_end; i = line.next; // Continuation lines: anything starting with whitespace belongs to // this field, and the line endings between them belong to the value, // because the value is stored exactly as it was written. while (i < block.len and (block[i] == ' ' or block[i] == '\t')) { const continuation = lineAt(block, i); value_end = continuation.text_end; i = continuation.next; } const name = try gpa.dupe(u8, split.name); errdefer gpa.free(name); // Trimmed of line endings as well as spaces, or a value whose last // continuation line was nothing but whitespace would be stored with a // bare line ending on the end of it -- which, written back out, // becomes the end of the field and loses everything after it. const trimmed = std.mem.trim(u8, block[value_start..value_end], " \t\r\n"); const value = if (std.mem.findScalar(u8, trimmed, '\n') == null) try gpa.dupe(u8, trimmed) else // The folds inside the value are line endings too, and a message // read out of a Unix file has them as bare LFs. Canonicalising // them here is what makes a stored value true wire form, so that // writing it is a copy and reading it back gives this same value. try canonicalFolds(gpa, trimmed); errdefer gpa.free(value); try self.fields.append(gpa, .{ .name = name, .value = value }); } self.trailing_newline = block.len == 0 or block[block.len - 1] == '\n'; return self; } fn canonicalFolds(gpa: Allocator, value: []const u8) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); line_ending.toCanonical(&out.writer, value) catch return error.OutOfMemory; return out.toOwnedSlice(); } const Line = struct { /// Where the line's text ends, before its terminator. text_end: usize, /// Where the next line begins. next: usize, }; fn lineAt(block: []const u8, start: usize) Line { const nl = std.mem.findScalarPos(u8, block, start, '\n') orelse return .{ .text_end = block.len, .next = block.len }; const text_end = if (nl > start and block[nl - 1] == '\r') nl - 1 else nl; return .{ .text_end = text_end, .next = nl + 1 }; } /// The wire-form value of the first field named `name`, compared /// case-insensitively. pub fn get(self: Headers, name: []const u8) ?[]const u8 { var it = self.iterator(name); const found = it.next() orelse return null; return found.value; } /// The value of the first field named `name` with its folds removed, which is /// the form every parser in this library expects. pub fn getUnfolded(self: *Headers, name: []const u8) Allocator.Error!?[]const u8 { const value = self.get(name) orelse return null; if (!field.isFolded(value)) return value; return try self.keep(try field.unfoldAlloc(self.gpa, value)); } /// The value of the first field named `name`, unfolded and with its RFC 2047 /// encoded words decoded: what to show a person. pub fn getUtf8(self: *Headers, name: []const u8) Allocator.Error!?[]const u8 { const unfolded = try self.getUnfolded(name) orelse return null; return try self.keep(try encoded_word.decodeUtf8Alloc(self.gpa, unfolded)); } /// Takes ownership of a string derived from a value, so that the caller of /// `getUnfolded` or `getUtf8` does not have to. fn keep(self: *Headers, bytes: []u8) Allocator.Error![]const u8 { errdefer self.gpa.free(bytes); try self.derived.append(self.gpa, bytes); return bytes; } pub fn has(self: Headers, name: []const u8) bool { return self.get(name) != null; } pub fn count(self: Headers, name: []const u8) usize { var n: usize = 0; var it = self.iterator(name); while (it.next() != null) n += 1; return n; } /// Every field named `name`, in the order they appear. `Received:` is the /// reason this exists. pub fn iterator(self: Headers, name: []const u8) Iterator { return .{ .fields = self.fields.items, .name = name }; } pub const Iterator = struct { fields: []const Field, name: []const u8, index: usize = 0, pub fn next(self: *Iterator) ?Field { while (self.index < self.fields.len) { const found = self.fields[self.index]; self.index += 1; if (std.ascii.eqlIgnoreCase(found.name, self.name)) return found; } return null; } }; /// Adds a field at the end, folding the value so that it can be written as it /// stands. Bare line endings in `value` are removed: see `field`. pub fn append(self: *Headers, name: []const u8, value: []const u8) Allocator.Error!void { try self.fields.append(self.gpa, .{ .name = try self.gpa.dupe(u8, name), .value = try field.foldAlloc(self.gpa, name, value, .{}), }); // A field added to a block that was cut short is a field somebody means // to write, and it needs its line ending. self.trailing_newline = true; } /// Adds a field at the end with its value taken verbatim. For a caller that /// has already produced wire form — one that is copying a field from another /// message, or writing a signature it computed over exact bytes. pub fn appendRaw(self: *Headers, name: []const u8, value: []const u8) Allocator.Error!void { try self.fields.append(self.gpa, .{ .name = try self.gpa.dupe(u8, name), .value = try self.gpa.dupe(u8, value), }); self.trailing_newline = true; } /// Adds a field at the front with its value taken verbatim. /// /// `prepend` folds what it is given, which is right for a value a program /// composed and wrong for one that was composed somewhere else and must not /// change. A `DKIM-Signature` is the case that matters: it was folded by /// whatever produced it, the signature covers the field as it stands, and /// refolding it can break verification under `simple` canonicalization. pub fn prependRaw(self: *Headers, name: []const u8, value: []const u8) Allocator.Error!void { try self.fields.insert(self.gpa, 0, .{ .name = try self.gpa.dupe(u8, name), .value = try self.gpa.dupe(u8, value), }); } /// Adds a field at the front, which is where `Received:` and `Return-Path:` /// belong: each hop prepends its own, so the newest is at the top. pub fn prepend(self: *Headers, name: []const u8, value: []const u8) Allocator.Error!void { try self.fields.insert(self.gpa, 0, .{ .name = try self.gpa.dupe(u8, name), .value = try field.foldAlloc(self.gpa, name, value, .{}), }); } /// Adds a trace field — a `Received:` — at the front, verbatim, below any /// `Return-Path:` already at the top. /// /// The value goes in as it stands, because `received.Received.write` has /// already folded it at the clause boundaries where mail systems fold a trace /// field, and folding it again at the places `prepend` would choose produces /// something no other MTA writes. /// /// The `Return-Path:` is why this is not just `prependRaw`. RFC 5322 §3.6.7 /// gives a trace block as an optional `Return-Path:` followed by one or more /// `Received:`, and the `Return-Path:` is written by the system making final /// delivery — the last thing that happens to a message. Putting a new /// `Received:` above one claims the message was received after it was /// delivered, which reads backwards to anything following the path. A message /// still in transit has no `Return-Path:` and this does nothing but insert at /// the front. /// /// Nothing else at the top is skipped. A `DKIM-Signature:` this same hop is /// adding goes in with `prependRaw` *after* this call, so that it sits above /// the `Received:` it was computed alongside. pub fn prependTrace(self: *Headers, name: []const u8, value: []const u8) Allocator.Error!void { var at: usize = 0; while (at < self.fields.items.len and std.ascii.eqlIgnoreCase(self.fields.items[at].name, "Return-Path")) : (at += 1) {} try self.fields.insert(self.gpa, at, .{ .name = try self.gpa.dupe(u8, name), .value = try self.gpa.dupe(u8, value), }); // A block that was cut short mid-field is not one a trace field can be // added to sensibly, but if a caller does it anyway the field it just // added is the one that must end properly. self.trailing_newline = true; } /// Replaces every field named `name` with a single one, keeping the position /// of the first. Removing and appending instead would move the field to the /// end, which for a `Received:` or a `Content-Type:` changes what the message /// means. pub fn set(self: *Headers, name: []const u8, value: []const u8) Allocator.Error!void { const folded = try field.foldAlloc(self.gpa, name, value, .{}); errdefer self.gpa.free(folded); var found = false; var i: usize = 0; while (i < self.fields.items.len) { if (!std.ascii.eqlIgnoreCase(self.fields.items[i].name, name)) { i += 1; continue; } if (!found) { found = true; self.gpa.free(self.fields.items[i].value); self.fields.items[i].value = folded; i += 1; continue; } const removed = self.fields.orderedRemove(i); self.gpa.free(removed.name); self.gpa.free(removed.value); } if (!found) { const owned = try self.gpa.dupe(u8, name); errdefer self.gpa.free(owned); try self.fields.append(self.gpa, .{ .name = owned, .value = folded }); } } /// Removes every field named `name`, and says how many there were. pub fn remove(self: *Headers, name: []const u8) usize { var removed: usize = 0; var i: usize = 0; while (i < self.fields.items.len) { if (std.ascii.eqlIgnoreCase(self.fields.items[i].name, name)) { const gone = self.fields.orderedRemove(i); self.gpa.free(gone.name); self.gpa.free(gone.value); removed += 1; } else { i += 1; } } return removed; } /// Writes a complete header block: every field, and the blank line that ends /// it. /// /// Complete is the point. A block that was parsed with its last line cut short /// gets that line ending back here, because a blank line after an unterminated /// field is not a header block at all — it is one field run into the next. /// `writeFields` is the one that reproduces exactly what was parsed, and /// `Message.Part` uses it for that reason. pub fn write(self: Headers, w: *Io.Writer) Io.Writer.Error!void { var complete = self; complete.trailing_newline = true; try complete.writeFields(w); try w.writeAll("\r\n"); } /// Writes the fields exactly as they were, without the blank line, for a /// caller assembling something around them. pub fn writeFields(self: Headers, w: *Io.Writer) Io.Writer.Error!void { for (self.fields.items, 0..) |f, i| { try w.writeAll(f.name); try w.writeAll(": "); try w.writeAll(f.value); const last = i + 1 == self.fields.items.len; if (!last or self.trailing_newline) try w.writeAll("\r\n"); } } test "parsing and looking up" { var headers: Headers = try .parse(testing.allocator, \\From: jeff@example.com \\To: alice@example.net \\Subject: hello \\ ); defer headers.deinit(); try testing.expectEqual(3, headers.fields.items.len); try testing.expectEqualStrings("jeff@example.com", headers.get("from").?); try testing.expectEqualStrings("hello", headers.get("SUBJECT").?); try testing.expectEqual(null, headers.get("cc")); try testing.expect(headers.has("To")); } test "a folded value is stored as written and unfolded on request" { var headers: Headers = try .parse( testing.allocator, "To: alice@example.net,\r\n bob@example.org\r\n", ); defer headers.deinit(); try testing.expectEqualStrings("alice@example.net,\r\n bob@example.org", headers.get("to").?); try testing.expectEqualStrings( "alice@example.net, bob@example.org", (try headers.getUnfolded("to")).?, ); } test "repeated fields keep their order" { var headers: Headers = try .parse(testing.allocator, \\Received: from c \\Received: from b \\Received: from a \\ ); defer headers.deinit(); try testing.expectEqual(3, headers.count("received")); var it = headers.iterator("Received"); try testing.expectEqualStrings("from c", it.next().?.value); try testing.expectEqualStrings("from b", it.next().?.value); try testing.expectEqualStrings("from a", it.next().?.value); try testing.expectEqual(null, it.next()); } test "what is not a header is skipped" { var headers: Headers = try .parse(testing.allocator, \\From nobody Mon Jan 1 00:00:00 2001 \\From: jeff@example.com \\ ); defer headers.deinit(); try testing.expectEqual(1, headers.fields.items.len); try testing.expectEqualStrings("jeff@example.com", headers.get("from").?); } test "an encoded subject" { var headers: Headers = try .parse( testing.allocator, "Subject: =?UTF-8?Q?caf=C3=A9?=\r\n", ); defer headers.deinit(); try testing.expectEqualStrings("café", (try headers.getUtf8("subject")).?); } test "building and writing" { var headers: Headers = .init(testing.allocator); defer headers.deinit(); try headers.append("From", "jeff@example.com"); try headers.append("Subject", "hello"); try headers.prepend("Received", "from somewhere"); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try headers.write(&out.writer); try testing.expectEqualStrings( "Received: from somewhere\r\n" ++ "From: jeff@example.com\r\n" ++ "Subject: hello\r\n" ++ "\r\n", out.written(), ); } test "a field prepended verbatim is not refolded" { var headers: Headers = try .parse(testing.allocator, "From: jeff@example.com\r\n"); defer headers.deinit(); // A value that `prepend` would fold differently: long, and with the // whitespace already where whatever produced it put it. const value = "v=1; a=ed25519-sha256; c=relaxed/relaxed; d=example.com; s=ed;\r\n" ++ "\th=from:to:subject; bh=" ++ &@as([43]u8, @splat('A')) ++ "=;\r\n" ++ "\tb=" ++ &@as([86]u8, @splat('B')) ++ "="; try headers.prependRaw("DKIM-Signature", value); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try headers.writeFields(&out.writer); try testing.expectEqualStrings( "DKIM-Signature: " ++ value ++ "\r\nFrom: jeff@example.com\r\n", out.written(), ); } test "set keeps the position of the field it replaces" { var headers: Headers = try .parse(testing.allocator, \\A: 1 \\B: 2 \\A: 3 \\C: 4 \\ ); defer headers.deinit(); try headers.set("a", "9"); try testing.expectEqual(1, headers.count("A")); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try headers.writeFields(&out.writer); try testing.expectEqualStrings("A: 9\r\nB: 2\r\nC: 4\r\n", out.written()); } test "remove" { var headers: Headers = try .parse(testing.allocator, "A: 1\r\nB: 2\r\nA: 3\r\n"); defer headers.deinit(); try testing.expectEqual(2, headers.remove("a")); try testing.expectEqual(1, headers.fields.items.len); try testing.expectEqual(0, headers.remove("z")); } test "a block that was cut short does not grow a line ending" { // What a `message/rfc822` part holding only headers looks like: the line // ending before the boundary belongs to the boundary, so the last header // line has none of its own. const block = "From: jeff@example.com\r\nSubject: Lunch"; var headers: Headers = try .parse(testing.allocator, block); defer headers.deinit(); try testing.expect(!headers.trailing_newline); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try headers.writeFields(&out.writer); try testing.expectEqualStrings(block, out.written()); // And a field added afterwards is a field somebody means to write. try headers.append("To", "alice@example.net"); out.clearRetainingCapacity(); try headers.writeFields(&out.writer); try testing.expectEqualStrings( "From: jeff@example.com\r\nSubject: Lunch\r\nTo: alice@example.net\r\n", out.written(), ); } test "a parsed block is written back byte for byte" { const block = "Received: from a.test (a.test [192.0.2.1])\r\n" ++ "\tby b.test with ESMTP id 42;\r\n" ++ "\tTue, 1 Jul 2003 10:52:37 +0200\r\n" ++ "From: \"Ollie, Jeff\" \r\n" ++ "Subject: =?UTF-8?Q?caf=C3=A9?=\r\n" ++ "\r\n"; var headers: Headers = try .parse(testing.allocator, block); defer headers.deinit(); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try headers.write(&out.writer); try testing.expectEqualStrings(block, out.written()); }