// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `Message-ID`, `In-Reply-To` and `References`: the three headers that turn a //! pile of messages into a conversation. //! //! Each is a list of `msg-id`, which is an `addr-spec` in angle brackets — //! `<1a2b3c@example.com>`. `Message-ID` holds one, `In-Reply-To` holds the //! identifiers of whatever is being replied to, and `References` holds the //! whole ancestry: the parent's `References`, with the parent's own //! `Message-ID` on the end. //! //! That last rule is the whole of threading, and it is why `References` grows //! without bound on a long thread. RFC 5322 §3.6.4 does not say what to do //! about that; the convention every mail client follows comes from netnews, //! and it is specific about *which* entries to drop: **the first is kept and //! the trimming is done from the second onwards**. The first identifier is the //! message that started the thread, and it is what a reader groups by; the //! last few are the immediate ancestry, and they are what a reader uses to //! nest replies. Everything between them is the part nobody looks at. //! //! ## What is accepted //! //! Identifiers are found by their angle brackets and everything between them //! is ignored, which is what makes this survive the comments, the commas and //! the stray text that real `References` headers carry. A value with no //! brackets anywhere falls back to splitting on whitespace and taking the //! tokens that look like an address, because a client that writes //! `In-Reply-To: 1a2b3c@example.com` exists and its threading should still //! work. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const field = @import("field.zig"); /// Walks the identifiers of a value, yielding each without its angle brackets /// — the form to compare, and the form `writeList` takes back. pub const Iterator = struct { source: []const u8, index: usize = 0, /// Set at construction: whether the value had any angle brackets at all. /// Without them, the whitespace-separated fallback applies. bracketed: bool, pub fn init(value: []const u8) Iterator { return .{ .source = value, .bracketed = std.mem.findScalar(u8, value, '<') != null, }; } pub fn next(self: *Iterator) ?[]const u8 { if (self.bracketed) return self.nextBracketed(); return self.nextBare(); } fn nextBracketed(self: *Iterator) ?[]const u8 { const open = std.mem.findScalarPos(u8, self.source, self.index, '<') orelse { self.index = self.source.len; return null; }; const close = std.mem.findScalarPos(u8, self.source, open + 1, '>') orelse { // An unterminated `<` takes the rest, which is a defect and is // still the most plausible reading of what was meant. self.index = self.source.len; const rest = self.source[open + 1 ..]; return if (rest.len == 0) null else rest; }; self.index = close + 1; const id = self.source[open + 1 .. close]; if (id.len == 0) return self.next(); return id; } fn nextBare(self: *Iterator) ?[]const u8 { while (self.index < self.source.len) { while (self.index < self.source.len and isSeparator(self.source[self.index])) { self.index += 1; } const start = self.index; while (self.index < self.source.len and !isSeparator(self.source[self.index])) { self.index += 1; } const token = self.source[start..self.index]; // An `@` is what tells an identifier apart from the words some // clients put in these headers. if (token.len != 0 and std.mem.findScalar(u8, token, '@') != null) return token; if (token.len == 0) return null; } return null; } fn isSeparator(c: u8) bool { return c == ' ' or c == '\t' or c == '\r' or c == '\n' or c == ','; } }; /// The first identifier in a value, which for a `Message-ID` is the only one. pub fn first(value: []const u8) ?[]const u8 { var it: Iterator = .init(value); return it.next(); } /// How many identifiers a value holds. pub fn count(value: []const u8) usize { var n: usize = 0; var it: Iterator = .init(value); while (it.next() != null) n += 1; return n; } /// Collects the identifiers of a value. The caller owns the list; the slices /// in it point into `value`. pub fn collect(gpa: Allocator, value: []const u8) Allocator.Error![][]const u8 { var list: std.ArrayList([]const u8) = .empty; errdefer list.deinit(gpa); var it: Iterator = .init(value); while (it.next()) |id| try list.append(gpa, id); return list.toOwnedSlice(gpa); } /// Writes identifiers as a header value: ` `, with a fold between /// each so that a long ancestry does not become a long line. /// /// Anything that could not appear inside the brackets is dropped, for the same /// reason it is dropped everywhere else here: an identifier taken from /// somebody else's message must not be able to close its own brackets or end /// the header line. pub fn writeList(w: *Io.Writer, ids: []const []const u8) Io.Writer.Error!void { for (ids, 0..) |id, i| { if (i != 0) try w.writeAll("\r\n "); try w.writeByte('<'); for (id) |c| switch (c) { 0...0x20, 0x7f, '<', '>' => {}, else => try w.writeByte(c), }; try w.writeByte('>'); } } /// Shortens an ancestry to `max` identifiers, keeping the first and the most /// recent. /// /// The first is the message that started the thread and is what a reader /// groups the conversation by; the last few are the immediate ancestry and are /// what a reader nests replies with. Dropping either end breaks threading; /// dropping from the middle is invisible. Returns a prefix-and-suffix copy /// written into `buffer`, which must be at least `max` long. pub fn trim(ids: []const []const u8, buffer: [][]const u8, max: usize) [][]const u8 { std.debug.assert(buffer.len >= max); if (max == 0) return buffer[0..0]; if (ids.len <= max) { @memcpy(buffer[0..ids.len], ids); return buffer[0..ids.len]; } buffer[0] = ids[0]; const tail = max - 1; @memcpy(buffer[1..max], ids[ids.len - tail ..]); return buffer[0..max]; } test "the ordinary shapes" { var it: Iterator = .init(" "); try testing.expectEqualStrings("a@x.test", it.next().?); try testing.expectEqualStrings("b@y.test", it.next().?); try testing.expectEqual(null, it.next()); // Folded, comma-separated, and with a comment in it, all of which happen. try testing.expectEqual(3, count(",\r\n (a comment) ")); try testing.expectEqualStrings("a@x", first(" ").?); try testing.expectEqual(null, first("")); } test "a value with no brackets still threads" { var it: Iterator = .init("1a2b3c@example.com 4d5e6f@example.com"); try testing.expectEqualStrings("1a2b3c@example.com", it.next().?); try testing.expectEqualStrings("4d5e6f@example.com", it.next().?); try testing.expectEqual(null, it.next()); // Words that are not identifiers are not identifiers. try testing.expectEqual(0, count("your message of yesterday")); } test "the shapes that are broken" { try testing.expectEqual(0, count("<>")); try testing.expectEqualStrings("unterminated@x", first(" trailing text")); } test writeList { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try writeList(&out.writer, &.{ "a@x.test", "b@y.test" }); try testing.expectEqualStrings("\r\n ", out.written()); // And an identifier cannot end the header line. out.clearRetainingCapacity(); try writeList(&out.writer, &.{"a@x\r\nBcc: victim@evil.test"}); try testing.expectEqualStrings("", out.written()); } test trim { const ids = [_][]const u8{ "1", "2", "3", "4", "5", "6", "7" }; var buffer: [8][]const u8 = undefined; // Nothing to do. try testing.expectEqual(7, trim(&ids, &buffer, 8).len); // The root and the four most recent; the middle goes. const trimmed = trim(&ids, &buffer, 5); try testing.expectEqual(5, trimmed.len); try testing.expectEqualStrings("1", trimmed[0]); try testing.expectEqualStrings("4", trimmed[1]); try testing.expectEqualStrings("7", trimmed[4]); try testing.expectEqual(1, trim(&ids, &buffer, 1).len); try testing.expectEqualStrings("1", trim(&ids, &buffer, 1)[0]); }