Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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: `<a> <b> <c>`, 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("<a@x.test> <b@y.test>"); 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("<a@x>,\r\n <b@x> (a comment) <c@x>")); try testing.expectEqualStrings("a@x", first("<a@x> <b@x>").?); 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("<unterminated@x").?); try testing.expectEqual(1, count("<a@x> 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("<a@x.test>\r\n <b@y.test>", 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("<a@xBcc:victim@evil.test>", 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]);}