// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `From:`, `To:`, `Cc:` and the rest: RFC 5322 §3.4. //! //! An address list looks simple and is not. Four shapes appear in real mail, //! and a parser that handles three of them mangles the fourth: //! //! ```text //! jeff@example.com an addr-spec alone //! Jeff Ollie a name and an address //! "Ollie, Jeff" a name with a comma in it //! Friends: alice@example.com, bob@example.net; a group //! ``` //! //! The comma is the whole difficulty. It separates addresses, *and* it is the //! most common character in a display name, *and* a group holds commas of its //! own between a `:` and a `;`. So the entries cannot be found by splitting: //! the parser has to know where the quotes, the angle brackets, the //! domain-literals, the comments and the groups begin and end before it can //! say which commas are separators. Splitting on commas is why so much //! software shows a message from `"Ollie` addressed to `Jeff" `. //! //! Display names come back decoded — RFC 2047 undone, quotes removed, //! backslash escapes resolved — because that is the only form anything wants //! to display. The local part and the domain come back *as written*, because //! they are identifiers: an address is compared, stored and sent to, and a //! local part is case-sensitive by rule even though nearly every host ignores //! that. //! //! ## What is accepted //! //! Nearly anything. A parser for mail that already exists cannot afford to //! fail: a `To:` line that does not parse is a message that cannot be filed. //! An address with no domain, an unterminated quoted string, an unclosed //! group, an empty entry between two commas — each of these parses into the //! most plausible reading rather than an error, and `Mailbox.isValid` is how a //! caller that is about to *send* something asks whether what it has is //! actually an address. 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 idn = @import("../idn.zig"); const lexer = @import("lexer.zig"); /// One addressable person or place. pub const Mailbox = struct { /// Decoded to UTF-8, with quotes and escapes removed. Null where the /// address stood on its own. display_name: ?[]const u8 = null, /// The part before the `@`, as written: still quoted if it was quoted, /// because the quotes are part of what identifies it. local_part: []const u8, /// The part after the `@`, as written, with the brackets of a /// domain-literal kept. Empty for an address that had no `@` — a local /// alias such as `postmaster`, or a defect. domain: []const u8 = "", /// Whether this looks like something that could be delivered to: both /// halves present, each of them one of the shapes the grammar allows, and /// no character in either that the grammar does not. /// /// This is what a program about to *send* should ask. The parser accepts /// far more than this, because a message that has already arrived has to /// be filed whatever is in its `To:`; `isValid` is the other question, and /// it is also exactly the condition under which writing the mailbox back /// out reproduces it byte for byte. pub fn isValid(self: Mailbox) bool { if (self.local_part.len == 0 or self.domain.len == 0) return false; if (self.local_part[0] == '"') { if (!isQuotedString(self.local_part)) return false; } else if (lexer.needsQuoting(self.local_part, .dot_atom)) return false; if (self.domain[0] == '[') return isDomainLiteral(self.domain); return !lexer.needsQuoting(self.domain, .dot_atom); } /// Whether this address needs a transport that speaks SMTPUTF8 — RFC 6531 /// — even after its domain has been converted. /// /// The domain can always be made ASCII: that is what `domainAsciiAlloc` /// does. The *local part* cannot. Punycode applies to the right of the /// `@` and nowhere else, so an address like `జోసెఫ్@example.com` needs an /// eight-bit-clean path from end to end, and a sender that cannot provide /// one has no way to send to it at all. /// /// A different question from `isValid`, which asks whether the address is /// well formed rather than what it takes to deliver it. pub fn requiresSmtpUtf8(self: Mailbox) bool { return !idn.isAscii(self.local_part); } /// The domain in its A-label form — `bücher.example` becomes /// `xn--bcher-kva.example` — which is what goes on the wire to a transport /// with no SMTPUTF8. The caller owns the result. /// /// A domain that is already ASCII is copied rather than converted. That is /// not an optimisation: putting an existing ASCII domain through IDNA /// would refuse some that already work, and the conversion is a no-op for /// all the rest. /// /// To send to the converted address, put it back: /// /// ```zig /// const ascii = try mailbox.domainAsciiAlloc(gpa); /// defer gpa.free(ascii); /// var sendable = mailbox; /// sendable.domain = ascii; /// try sendable.write(w); /// ``` pub fn domainAsciiAlloc( self: Mailbox, gpa: Allocator, ) (Allocator.Error || idn.Error)![]u8 { if (idn.isAscii(self.domain) and !idn.hasControl(self.domain)) { return gpa.dupe(u8, self.domain); } return idn.toAsciiAlloc(gpa, self.domain); } /// The domain as a person writes it — `xn--bcher-kva.example` becomes /// `bücher.example`. The caller owns the result. /// /// Read `idn`'s module comment before showing this to anybody: two domains /// that look identical in most fonts are still two domains, and choosing /// to display the readable form is a security decision rather than a /// formatting one. pub fn domainUnicodeAlloc(self: Mailbox, gpa: Allocator) Allocator.Error![]u8 { return idn.toUnicodeAlloc(gpa, self.domain); } /// Whether writing this mailbox would produce nothing at all: no display /// name, and an address made entirely of the control characters that /// `writeAddrSpec` refuses to write. /// /// Such a thing is not an address, and `List.write` leaves it out rather /// than writing a comma with nothing on either side of it — which would /// otherwise mean a list that came back one shorter every time it was /// written. pub fn isEmpty(self: Mailbox) bool { if (self.display_name) |name| { if (name.len != 0) return false; } return writableLen(self.local_part) == 0 and self.domain.len == 0; } /// Writes `local@domain` with nothing around it. /// /// Control characters are dropped rather than written. A header is a /// line, and a CR or an LF in the middle of one ends the field and starts /// whatever an attacker chose — so a program that builds a `Mailbox` out /// of a form field and writes it into a `To:` would otherwise be a /// program that sends mail to whoever asked. There is no legitimate /// address containing one, so nothing is lost. pub fn writeAddrSpec(self: Mailbox, w: *Io.Writer) Io.Writer.Error!void { try writeLocalPart(w, self.local_part); if (self.domain.len != 0) { try w.writeByte('@'); try writeDomain(w, self.domain); } } /// Writes the mailbox as a header would carry it: the display name /// encoded and quoted as needed, then the address in angle brackets. pub fn write(self: Mailbox, w: *Io.Writer) Io.Writer.Error!void { const name = self.display_name orelse return self.writeAddrSpec(w); if (name.len == 0) return self.writeAddrSpec(w); if (encoded_word.needsEncoding(name)) { try encoded_word.encodeWriter(w, name, .{}); } else { try lexer.quoteWriter(w, name, .phrase); } try w.writeAll(" <"); try self.writeAddrSpec(w); try w.writeByte('>'); } /// For `{f}`. pub fn format(self: Mailbox, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); } }; /// Writes a local part so that it reads back as itself. /// /// A parsed local part is kept exactly as it was written, which for a /// well-formed address means a dot-atom or a quoted-string and for a malformed /// one means anything at all — including a `<` or a `>`, which written bare /// inside the angle brackets would move where the address appears to end. /// Anything that is not already one of the two legal shapes is written as a /// quoted-string, which is the shape that can hold anything. fn writeLocalPart(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { if (text.len == 0) return; if (!lexer.needsQuoting(text, .dot_atom)) return w.writeAll(text); if (isQuotedString(text)) return w.writeAll(text); return lexer.quoteWriter(w, text, .dot_atom); } /// Writes a domain so that it reads back as itself. /// /// The same problem as the local part and a different answer, because a domain /// has no quoted form: what it has instead is the domain-literal, `[...]`, /// which is how an address names a host by address. Anything that is not a /// plain name goes out as one of those, escaped, rather than as bare bytes /// that would change where the address ends. fn writeDomain(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { if (!lexer.needsQuoting(text, .dot_atom)) return w.writeAll(text); if (isDomainLiteral(text)) return w.writeAll(text); try w.writeByte('['); for (text) |c| switch (c) { 0...0x1f, 0x7f => {}, '[', ']', '\\' => try w.writeAll(&.{ '\\', c }), else => try w.writeByte(c), }; try w.writeByte(']'); } /// Whether `text` is a well-formed `"..."` whose closing quote is its last /// character — which is how a quoted local part is stored, quotes and all. fn isQuotedString(text: []const u8) bool { if (text.len < 2 or text[0] != '"') return false; var i: usize = 1; while (i < text.len) { switch (text[i]) { '"' => return i == text.len - 1, '\\' => i += 2, 0...0x1f, 0x7f => return false, else => i += 1, } } return false; } /// Whether `text` is a well-formed `[...]`, which is how a domain-literal is /// stored. fn isDomainLiteral(text: []const u8) bool { if (text.len < 2 or text[0] != '[') return false; var i: usize = 1; while (i < text.len) { switch (text[i]) { ']' => return i == text.len - 1, '\\' => i += 2, '[', 0...0x1f, 0x7f => return false, else => i += 1, } } return false; } fn writableLen(text: []const u8) usize { var len: usize = 0; for (text) |c| { if (c >= 0x20 and c != 0x7f) len += 1; } return len; } fn writeSafe(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { var start: usize = 0; for (text, 0..) |c, i| { if (c >= 0x20 and c != 0x7f) continue; try w.writeAll(text[start..i]); start = i + 1; } try w.writeAll(text[start..]); } /// `Friends: alice@example.com, bob@example.net;` — a named list, which /// RFC 5322 allows anywhere a mailbox is allowed. /// /// A group with no members is how a message hides its recipients: /// `To: undisclosed-recipients:;` is a valid `To` line naming nobody. pub const Group = struct { name: []const u8, members: []const Mailbox, pub fn write(self: Group, w: *Io.Writer) Io.Writer.Error!void { if (encoded_word.needsEncoding(self.name)) { try encoded_word.encodeWriter(w, self.name, .{}); } else { try lexer.quoteWriter(w, self.name, .phrase); } try w.writeByte(':'); var written: usize = 0; for (self.members) |member| { if (member.isEmpty()) continue; if (written != 0) try w.writeByte(','); try w.writeByte(' '); try member.write(w); written += 1; } try w.writeByte(';'); } pub fn format(self: Group, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); } }; pub const Address = union(enum) { mailbox: Mailbox, group: Group, pub fn write(self: Address, w: *Io.Writer) Io.Writer.Error!void { return switch (self) { .mailbox => |mailbox| mailbox.write(w), .group => |group| group.write(w), }; } pub fn format(self: Address, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); } }; /// The parsed contents of one address header, and the memory its strings live /// in. pub const List = struct { addresses: []const Address = &.{}, arena: std.heap.ArenaAllocator.State = .{}, pub const empty: List = .{}; pub fn deinit(self: *List, gpa: Allocator) void { self.arena.promote(gpa).deinit(); self.* = .empty; } /// Parses an address list. Never fails except on allocation: see the /// module comment on why. pub fn parse(gpa: Allocator, source: []const u8) Allocator.Error!List { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const a = arena.allocator(); var addresses: std.ArrayList(Address) = .empty; var index: usize = 0; while (index < source.len) { const entry = findEntry(source, index); index = entry.next; // Handed over untrimmed, because `entry.colon` is an offset into // exactly these bytes: trimming first moves everything left and // the colon then points past the end of a short entry. const raw = source[entry.start..entry.end]; if (std.mem.trim(u8, raw, " \t\r\n").len == 0) continue; try addresses.append(a, try parseEntry(a, raw, entry.colon)); } return .{ .addresses = try addresses.toOwnedSlice(a), .arena = arena.state, }; } /// Every mailbox in the list, including the members of its groups, in the /// order they were written. What a program that is about to send /// something actually wants. pub fn mailboxIterator(self: List) MailboxIterator { return .{ .addresses = self.addresses }; } pub const MailboxIterator = struct { addresses: []const Address, index: usize = 0, member: usize = 0, pub fn next(self: *MailboxIterator) ?Mailbox { while (self.index < self.addresses.len) { switch (self.addresses[self.index]) { .mailbox => |mailbox| { self.index += 1; return mailbox; }, .group => |group| { if (self.member < group.members.len) { defer self.member += 1; return group.members[self.member]; } self.index += 1; self.member = 0; }, } } return null; } }; /// Whether any address in the list needs an SMTPUTF8 transport. What a /// sender asks before it decides whether it can send at all. pub fn requiresSmtpUtf8(self: List) bool { var it = self.mailboxIterator(); while (it.next()) |mailbox| { if (mailbox.requiresSmtpUtf8()) return true; } return false; } /// Writes the list as a header value, separating entries with `,` and a /// fold so that no line runs away. The caller has already written /// `To: `, so the first entry goes on that line. pub fn write(self: List, w: *Io.Writer) Io.Writer.Error!void { var written: usize = 0; for (self.addresses) |address| { if (address == .mailbox and address.mailbox.isEmpty()) continue; if (written != 0) try w.writeAll(",\r\n "); try address.write(w); written += 1; } } pub fn format(self: List, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); } }; /// Where one entry of an address list ends. const Entry = struct { start: usize, end: usize, /// Index of the `:` that makes this entry a group, relative to `start`. colon: ?usize, /// Where to look for the next entry. next: usize, }; /// Finds the extent of the entry beginning at `start`, which means finding the /// one comma that separates it from the next — the one that is not inside a /// quoted-string, a comment, a domain-literal, an angle-addr or a group. fn findEntry(source: []const u8, start: usize) Entry { var i = start; var colon: ?usize = null; var seen_at = false; var in_angle = false; while (i < source.len) { switch (source[i]) { '"' => i = skipQuoted(source, i), '(' => i = skipComment(source, i), '[' => i = skipBracketed(source, i), '<' => { in_angle = true; i += 1; }, '>' => { in_angle = false; i += 1; }, '@' => { seen_at = true; i += 1; }, ':' => { // A `:` inside `<...>` is the end of an obsolete source route // (`<@relay:user@host>`), not the start of a group. A `:` // after an `@` at this level is not one either: it would have // to have come before the address it names. if (!in_angle and !seen_at and colon == null) colon = i - start; i += 1; }, ';' => { if (colon != null) return .{ .start = start, .end = i + 1, .colon = colon, .next = i + 1 }; i += 1; }, ',' => { // Inside a group, a comma separates members rather than // entries, so the entry continues to the `;`. Inside angle // brackets it is part of an obsolete source route, and the // entry continues to the `>`. if (colon == null and !in_angle) { return .{ .start = start, .end = i, .colon = null, .next = i + 1 }; } i += 1; }, else => i += 1, } } return .{ .start = start, .end = source.len, .colon = colon, .next = source.len }; } fn skipQuoted(source: []const u8, start: usize) usize { var i = start + 1; while (i < source.len) { switch (source[i]) { '"' => return i + 1, '\\' => i += 2, else => i += 1, } } return source.len; } fn skipComment(source: []const u8, start: usize) usize { var i = start; var depth: usize = 0; while (i < source.len) { switch (source[i]) { '(' => { depth += 1; i += 1; }, ')' => { depth -= 1; i += 1; if (depth == 0) return i; }, '\\' => i += 2, else => i += 1, } } return source.len; } fn skipBracketed(source: []const u8, start: usize) usize { var i = start + 1; while (i < source.len) { switch (source[i]) { ']' => return i + 1, '\\' => i += 2, else => i += 1, } } return source.len; } fn parseEntry(a: Allocator, raw: []const u8, colon: ?usize) Allocator.Error!Address { if (colon) |at| { const name = try decodePhrase(a, raw[0..at]); var members: std.ArrayList(Mailbox) = .empty; // The group's contents run from after the `:` to the `;`, if there // was one. An unterminated group takes the rest of the header. var body = raw[at + 1 ..]; if (std.mem.endsWith(u8, body, ";")) body = body[0 .. body.len - 1]; var index: usize = 0; while (index < body.len) { const entry = findEntry(body, index); index = entry.next; const member = std.mem.trim(u8, body[entry.start..entry.end], " \t\r\n"); if (member.len == 0) continue; // A member is never itself a group: the grammar does not nest // them, and treating a second colon as one more group would let a // header of nothing but colons recurse as deep as it is long. switch (try parseEntry(a, member, null)) { .mailbox => |mailbox| try members.append(a, mailbox), .group => unreachable, } } return .{ .group = .{ .name = name, .members = try members.toOwnedSlice(a) } }; } const text = std.mem.trim(u8, raw, " \t\r\n"); // `Name `: the angle brackets settle where the address is, so find // them before anything else. if (findAngle(text)) |angle| { const display = std.mem.trim(u8, text[0..angle.open], " \t\r\n"); var mailbox = try parseAddrSpec(a, text[angle.open + 1 .. angle.close]); if (display.len != 0) { mailbox.display_name = try decodePhrase(a, display); } else { // ` (Jeff Ollie)` — the name is in a comment, // which is where mail put it before angle brackets existed. mailbox.display_name = try commentName(a, text[@min(angle.close + 1, text.len)..]); } return .{ .mailbox = mailbox }; } var mailbox = try parseAddrSpec(a, text); mailbox.display_name = try commentName(a, text); return .{ .mailbox = mailbox }; } const Angle = struct { open: usize, close: usize }; /// The outermost `<...>`, ignoring any inside a quoted-string, a comment or a /// domain-literal. All three may contain an angle bracket, and a `<` inside /// `[192.0.2.1<]` is a character of the address rather than the start of one. fn findAngle(text: []const u8) ?Angle { var i: usize = 0; var open: ?usize = null; while (i < text.len) { switch (text[i]) { '"' => i = skipQuoted(text, i), '(' => i = skipComment(text, i), '[' => i = skipBracketed(text, i), '<' => { if (open == null) open = i; i += 1; }, '>' => { if (open) |at| return .{ .open = at, .close = i }; i += 1; }, else => i += 1, } } // An unterminated `<` still says where the address starts. if (open) |at| return .{ .open = at, .close = text.len }; return null; } /// Splits `local@domain` at the last `@` that is not inside a quoted-string or /// a domain-literal. /// /// The last, because a domain may not contain one and a local part may: taking /// the first would cut `"a@b"@example.com` in the wrong place. Not inside a /// quoted-string, because that is exactly where a local part is allowed to /// keep one, and a scan that ignores the quotes reads the address as having a /// domain of whatever follows the `@` inside them. fn parseAddrSpec(a: Allocator, source: []const u8) Allocator.Error!Mailbox { var text = std.mem.trim(u8, source, " \t\r\n"); // The obsolete source route of RFC 5322 §4.4: `<@relay1,@relay2:user@host>` // names the path the message should take. Nothing has honoured it since // the 1980s and the address is what follows the colon. if (text.len != 0 and text[0] == '@') { // At the top level, like every other scan here: a `:` inside a // domain-literal is part of an IPv6 address, and taking it for the end // of a route throws away everything in front of it. if (findTopLevel(text, ':')) |at| text = std.mem.trim(u8, text[at + 1 ..], " \t\r\n"); } // Comments may sit anywhere, including in the middle of the address. const cleaned = try stripComments(a, text); const at = findSeparator(cleaned) orelse return .{ .local_part = cleaned, .domain = "", }; return .{ .local_part = std.mem.trim(u8, cleaned[0..at], " \t\r\n"), .domain = std.mem.trim(u8, cleaned[at + 1 ..], " \t\r\n"), }; } /// The last `@` at the top level of an address, which is the one that /// separates the local part from the domain. fn findSeparator(text: []const u8) ?usize { var i: usize = 0; var found: ?usize = null; while (i < text.len) { switch (text[i]) { '"' => i = skipQuoted(text, i), '[' => i = skipBracketed(text, i), '(' => i = skipComment(text, i), '@' => { found = i; i += 1; }, else => i += 1, } } return found; } /// The first `wanted` that is not inside a quoted-string, a domain-literal or /// a comment. fn findTopLevel(text: []const u8, wanted: u8) ?usize { var i: usize = 0; while (i < text.len) { if (text[i] == wanted) return i; switch (text[i]) { '"' => i = skipQuoted(text, i), '[' => i = skipBracketed(text, i), '(' => i = skipComment(text, i), else => i += 1, } } return null; } /// Removes comments and the whitespace around them, which is the one /// transformation an address needs before it can be compared. fn stripComments(a: Allocator, text: []const u8) Allocator.Error![]const u8 { // Every byte this would remove, so that the fast path cannot let one // through: a newline left in a local part is written straight back into // the header, where it is no longer part of the address at all. if (std.mem.findAny(u8, text, "([ \t\r\n") == null) return text; var out: Io.Writer.Allocating = .init(a); var i: usize = 0; while (i < text.len) { switch (text[i]) { '(' => i = skipComment(text, i), '"' => { const end = skipQuoted(text, i); out.writer.writeAll(text[i..end]) catch return error.OutOfMemory; i = end; }, '[' => { // A domain-literal is not a name and its contents are not // whitespace-insensitive, so it is copied as it stands. const end = skipBracketed(text, i); out.writer.writeAll(text[i..end]) catch return error.OutOfMemory; i = end; }, ' ', '\t', '\r', '\n' => i += 1, else => { out.writer.writeByte(text[i]) catch return error.OutOfMemory; i += 1; }, } } return out.written(); } /// The text of the first comment in `text`, decoded, or null if there is none. /// /// Like every other scan over an address, this has to agree with the rest /// about which stretches are opaque: a `(` inside a quoted-string or a /// domain-literal is a character and not the start of a comment, and treating /// one as a comment invents a display name out of somebody's domain. fn commentName(a: Allocator, text: []const u8) Allocator.Error!?[]const u8 { var i: usize = 0; while (i < text.len) { switch (text[i]) { '"' => i = skipQuoted(text, i), '[' => i = skipBracketed(text, i), '(' => { const end = skipComment(text, i); const inside = text[i + 1 .. @max(i + 1, end -| 1)]; if (inside.len == 0) return null; return try decodePhrase(a, inside); }, else => i += 1, } } return null; } /// Turns the raw text of a display name into what should be shown: words /// joined by single spaces, quotes and escapes removed, encoded words decoded. fn decodePhrase(a: Allocator, raw: []const u8) Allocator.Error![]const u8 { var joined: Io.Writer.Allocating = .init(a); var scanner: lexer.Scanner = .init(raw); var first = true; while (true) { scanner.skipCfws(); if (scanner.atEnd()) break; const word = scanner.word() orelse { // Something that is neither an atom nor a quoted-string — a `.` // in an unquoted name, most often, which is a defect and is // everywhere. Take the character and carry on. joined.writer.writeByte(scanner.source[scanner.index]) catch return error.OutOfMemory; scanner.index += 1; first = false; continue; }; if (!first) joined.writer.writeByte(' ') catch return error.OutOfMemory; first = false; switch (word) { .atom => |atom| joined.writer.writeAll(atom) catch return error.OutOfMemory, // A quoted display name may still hold an encoded word: the // grammar forbids it and a good deal of software writes it // anyway, and the decode below picks it up. .quoted => |quoted| lexer.unquoteWriter(&joined.writer, quoted) catch return error.OutOfMemory, } } return encoded_word.decodeUtf8Alloc(a, joined.written()); } test "a bare address" { var list: List = try .parse(testing.allocator, "jeff@example.com"); defer list.deinit(testing.allocator); try testing.expectEqual(1, list.addresses.len); const mailbox = list.addresses[0].mailbox; try testing.expectEqual(null, mailbox.display_name); try testing.expectEqualStrings("jeff", mailbox.local_part); try testing.expectEqualStrings("example.com", mailbox.domain); try testing.expect(mailbox.isValid()); } test "a name and an address" { var list: List = try .parse(testing.allocator, "Jeff Ollie "); defer list.deinit(testing.allocator); const mailbox = list.addresses[0].mailbox; try testing.expectEqualStrings("Jeff Ollie", mailbox.display_name.?); try testing.expectEqualStrings("jeff", mailbox.local_part); try testing.expectEqualStrings("example.com", mailbox.domain); } test "a comma inside a quoted display name is not a separator" { var list: List = try .parse( testing.allocator, "\"Ollie, Jeff\" , alice@example.net", ); defer list.deinit(testing.allocator); try testing.expectEqual(2, list.addresses.len); try testing.expectEqualStrings("Ollie, Jeff", list.addresses[0].mailbox.display_name.?); try testing.expectEqualStrings("alice", list.addresses[1].mailbox.local_part); } test "a comma inside a comment is not a separator either" { var list: List = try .parse(testing.allocator, "jeff@example.com (Ollie, Jeff)"); defer list.deinit(testing.allocator); try testing.expectEqual(1, list.addresses.len); try testing.expectEqualStrings("Ollie, Jeff", list.addresses[0].mailbox.display_name.?); } test "an encoded display name" { var list: List = try .parse( testing.allocator, "=?UTF-8?Q?Jos=C3=A9_Garc=C3=ADa?= ", ); defer list.deinit(testing.allocator); try testing.expectEqualStrings("José García", list.addresses[0].mailbox.display_name.?); } test "a group" { var list: List = try .parse( testing.allocator, "Friends: alice@example.com, Bob ;, carol@example.org", ); defer list.deinit(testing.allocator); try testing.expectEqual(2, list.addresses.len); const group = list.addresses[0].group; try testing.expectEqualStrings("Friends", group.name); try testing.expectEqual(2, group.members.len); try testing.expectEqualStrings("alice", group.members[0].local_part); try testing.expectEqualStrings("Bob", group.members[1].display_name.?); try testing.expectEqualStrings("carol", list.addresses[1].mailbox.local_part); } test "a group with no members" { var list: List = try .parse(testing.allocator, "undisclosed-recipients:;"); defer list.deinit(testing.allocator); try testing.expectEqual(1, list.addresses.len); try testing.expectEqualStrings("undisclosed-recipients", list.addresses[0].group.name); try testing.expectEqual(0, list.addresses[0].group.members.len); } test "the mailbox iterator flattens groups" { var list: List = try .parse( testing.allocator, "a@x.test, Group: b@x.test, c@x.test;, d@x.test", ); defer list.deinit(testing.allocator); var it = list.mailboxIterator(); for ([_][]const u8{ "a", "b", "c", "d" }) |expected| { try testing.expectEqualStrings(expected, it.next().?.local_part); } try testing.expectEqual(null, it.next()); } test "a quoted local part keeps its quotes" { var list: List = try .parse(testing.allocator, "\"jeff ollie\"@example.com"); defer list.deinit(testing.allocator); const mailbox = list.addresses[0].mailbox; try testing.expectEqualStrings("\"jeff ollie\"", mailbox.local_part); try testing.expect(mailbox.isValid()); } test "a domain literal" { var list: List = try .parse(testing.allocator, "jeff@[192.0.2.1]"); defer list.deinit(testing.allocator); try testing.expectEqualStrings("[192.0.2.1]", list.addresses[0].mailbox.domain); try testing.expect(list.addresses[0].mailbox.isValid()); } test "an obsolete source route names the mailbox at the end of it" { var list: List = try .parse(testing.allocator, "<@relay1.test,@relay2.test:jeff@example.com>"); defer list.deinit(testing.allocator); const mailbox = list.addresses[0].mailbox; try testing.expectEqualStrings("jeff", mailbox.local_part); try testing.expectEqualStrings("example.com", mailbox.domain); } test "the shapes that are not addresses" { var list: List = try .parse(testing.allocator, "postmaster, , jeff@"); defer list.deinit(testing.allocator); try testing.expectEqual(2, list.addresses.len); try testing.expectEqualStrings("postmaster", list.addresses[0].mailbox.local_part); try testing.expect(!list.addresses[0].mailbox.isValid()); try testing.expect(!list.addresses[1].mailbox.isValid()); } test "an empty list" { var list: List = try .parse(testing.allocator, ""); defer list.deinit(testing.allocator); try testing.expectEqual(0, list.addresses.len); } test "writing a mailbox" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const plain: Mailbox = .{ .local_part = "jeff", .domain = "example.com" }; try out.writer.print("{f}", .{plain}); try testing.expectEqualStrings("jeff@example.com", out.written()); out.clearRetainingCapacity(); var named = plain; named.display_name = "Jeff Ollie"; try out.writer.print("{f}", .{named}); try testing.expectEqualStrings("Jeff Ollie ", out.written()); out.clearRetainingCapacity(); named.display_name = "Ollie, Jeff"; try out.writer.print("{f}", .{named}); try testing.expectEqualStrings("\"Ollie, Jeff\" ", out.written()); // Four ASCII characters and one that is not: base64 spends eight // characters on it and `Q` spends nine, so `auto` takes base64. out.clearRetainingCapacity(); named.display_name = "José"; try out.writer.print("{f}", .{named}); try testing.expectEqualStrings("=?UTF-8?B?Sm9zw6k=?= ", out.written()); } test "a written list reads back" { const sources = [_][]const u8{ "jeff@example.com", "Jeff Ollie , alice@example.net", "\"Ollie, Jeff\" ", "=?UTF-8?Q?Jos=C3=A9_Garc=C3=ADa?= ", "Friends: alice@example.com, bob@example.net;", }; for (sources) |source| { var first: List = try .parse(testing.allocator, source); defer first.deinit(testing.allocator); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try first.write(&out.writer); var second: List = try .parse(testing.allocator, out.written()); defer second.deinit(testing.allocator); try testing.expectEqual(first.addresses.len, second.addresses.len); var a = first.mailboxIterator(); var b = second.mailboxIterator(); while (a.next()) |expected| { const found = b.next().?; try testing.expectEqualStrings(expected.local_part, found.local_part); try testing.expectEqualStrings(expected.domain, found.domain); if (expected.display_name) |name| { try testing.expectEqualStrings(name, found.display_name.?); } else { try testing.expectEqual(null, found.display_name); } } try testing.expectEqual(null, b.next()); } } test "a control character never reaches the header" { // Parsed out of a malformed address, and written straight back used to be // header injection arrived at from the parsing side. var list: List = try .parse(testing.allocator, "je\r\nBcc: victim@evil.test\rff@example.com"); defer list.deinit(testing.allocator); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try list.write(&out.writer); try testing.expectEqual(null, std.mem.findAny(u8, out.written(), "\r\n")); } test "every scan agrees about what a domain-literal contains" { // A `(` inside `[...]` is not a comment, a `<` is not an angle-addr, and a // `:` is not the end of a source route. Four separate scans used to // disagree about that, and each disagreement changed what the address was. for ([_][]const u8{ "jeff@[a(b]", "jeff@[a"); defer list.deinit(testing.allocator); const mailbox = list.addresses[0].mailbox; const ascii = try mailbox.domainAsciiAlloc(testing.allocator); defer testing.allocator.free(ascii); try testing.expectEqualStrings("xn--bcher-kva.example", ascii); // And the address that goes on the wire is the one with it put back. var sendable = mailbox; sendable.domain = ascii; var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try sendable.write(&out.writer); try testing.expectEqualStrings("Jeff ", out.written()); // Which is ASCII, and so needs nothing of the transport. for (out.written()) |c| try testing.expect(c < 0x80); try testing.expect(!sendable.requiresSmtpUtf8()); } test "an A-label reads back as a name" { var list: List = try .parse(testing.allocator, "jeff@xn--bcher-kva.example"); defer list.deinit(testing.allocator); const shown = try list.addresses[0].mailbox.domainUnicodeAlloc(testing.allocator); defer testing.allocator.free(shown); try testing.expectEqualStrings("bücher.example", shown); } test "the local part is what decides whether SMTPUTF8 is needed" { var ascii: List = try .parse(testing.allocator, "jeff@bücher.example"); defer ascii.deinit(testing.allocator); // A non-ASCII *domain* does not need it: it can be encoded. try testing.expect(!ascii.requiresSmtpUtf8()); var utf8: List = try .parse(testing.allocator, "jöseph@example.com, plain@example.net"); defer utf8.deinit(testing.allocator); // A non-ASCII *local part* does, and there is nothing to be done about it. try testing.expect(utf8.requiresSmtpUtf8()); try testing.expect(utf8.addresses[0].mailbox.requiresSmtpUtf8()); try testing.expect(!utf8.addresses[1].mailbox.requiresSmtpUtf8()); } test "a domain literal is not put through IDNA" { var list: List = try .parse(testing.allocator, "jeff@[192.0.2.1]"); defer list.deinit(testing.allocator); const ascii = try list.addresses[0].mailbox.domainAsciiAlloc(testing.allocator); defer testing.allocator.free(ascii); try testing.expectEqualStrings("[192.0.2.1]", ascii); } test "a domain that cannot be encoded says so" { // A control character, whether or not the rest of the domain is ASCII: // the short-circuit for an ASCII domain must not be a way past the check. for ([_][]const u8{ "a\u{0}b.exämple", "a\u{0}b.example", "x.example\r\n" }) |domain| { const mailbox: Mailbox = .{ .local_part = "jeff", .domain = domain }; try testing.expectError(error.InvalidDomain, mailbox.domainAsciiAlloc(testing.allocator)); } }