Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The lexical layer of RFC 5322 §3.2: the character classes, and a scanner//! that walks a header value in terms of them.//!//! Everything structured in a mail header is built from four shapes, and every//! parser above this one is written in them rather than in bytes://!//! * an **atom**, a run of `atext` — the printable characters that are not//! `specials`;//! * a **quoted-string**, `"..."`, in which `\` escapes the next character and//! so anything at all can appear;//! * a **domain-literal**, `[...]`, which is how an address carries an IP//! address instead of a name;//! * a **comment**, `(...)`, which may nest, may appear between any two of the//! above, and which the grammar says to ignore. Mail from before 1982 put//! the sender's name in one, so ignoring it is not quite free; the scanner//! remembers the last one it skipped for the benefit of the address parser.//!//! Between any two of those, whitespace and comments may appear in any//! quantity — *CFWS*, in the grammar — including the folding whitespace that a//! line break was turned into. `skipCfws` is called at the start of nearly//! every function here, which is why none of them need to think about it.//!//! ## Eight-bit bytes//!//! The grammar says US-ASCII; a great deal of real mail says otherwise, and//! RFC 6532 now says it may. Every class here admits a byte with the high bit//! set, so a `From:` line carrying a UTF-8 display name parses as the one atom//! it looks like rather than as a run of nothing. Nothing in this library//! *emits* such a byte where the grammar forbids it — `quoteWriter` and the//! encoded-word encoder are the ways out — so the leniency is confined to//! reading.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
/// Space or horizontal tab. A line ending is not whitespace here: by the time/// a value reaches this layer it has been unfolded, and a bare CR or LF left/// in it is a defect rather than a separator.pub fn isWsp(c: u8) bool { return c == ' ' or c == '\t';}
/// RFC 5322 §3.2.3. The printable characters that may appear in an atom/// without quoting.pub fn isAtext(c: u8) bool { return switch (c) { 'A'...'Z', 'a'...'z', '0'...'9' => true, '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~' => true, 0x80...0xff => true, // RFC 6532, and reality. else => false, };}
/// RFC 5322 §3.2.3. The characters whose presence forces quoting, because each/// of them means something to the grammar.pub fn isSpecial(c: u8) bool { return switch (c) { '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"' => true, else => false, };}
/// RFC 5322 §3.2.4. What may appear inside a quoted-string without a/// backslash: everything printable but `"` and `\`.pub fn isQtext(c: u8) bool { return switch (c) { 33, 35...91, 93...126 => true, 0x80...0xff => true, else => false, };}
/// RFC 5322 §3.2.2. What may appear inside a comment without a backslash:/// everything printable but the parentheses and `\`.pub fn isCtext(c: u8) bool { return switch (c) { 33...39, 42...91, 93...126 => true, 0x80...0xff => true, else => false, };}
/// RFC 5322 §3.4.1. What may appear inside a domain-literal.pub fn isDtext(c: u8) bool { return switch (c) { 33...90, 94...126 => true, 0x80...0xff => true, else => false, };}
/// RFC 2045 §5.1. The characters a `Content-Type` parameter may use unquoted./// A narrower set than `atext`: `.` is a token character here and a special/// there, and `=` and `?` are the other way round.pub fn isTokenChar(c: u8) bool { return switch (c) { // CTLs, space, and the tspecials. 0...32, 127 => false, '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=' => false, else => true, };}
/// A walk over one unfolded header value.pub const Scanner = struct { source: []const u8, index: usize = 0, /// The text of the most recent comment `skipCfws` passed over, with its /// parentheses removed and its escapes left in place. `null` until one is /// seen. Mail that predates `From: Name <addr>` wrote the name here, and /// the address parser falls back to it. last_comment: ?[]const u8 = null,
pub fn init(source: []const u8) Scanner { return .{ .source = source }; }
pub fn atEnd(self: *const Scanner) bool { return self.index >= self.source.len; }
/// The next byte without consuming it. pub fn peek(self: *const Scanner) ?u8 { if (self.atEnd()) return null; return self.source[self.index]; }
/// What has not been consumed. pub fn rest(self: *const Scanner) []const u8 { return self.source[self.index..]; }
/// Consumes `c` if it is next, and says whether it was. pub fn eat(self: *Scanner, c: u8) bool { if (self.peek() != c) return false; self.index += 1; return true; }
/// Consumes whitespace and comments, of which there may be any number in /// any order. RFC 5322 calls this CFWS and permits it between every pair /// of tokens in the grammar. pub fn skipCfws(self: *Scanner) void { while (!self.atEnd()) { const c = self.source[self.index]; if (isWsp(c) or c == '\r' or c == '\n') { // A CR or LF should have been removed by unfolding. Treating // one as whitespace costs nothing and rescues a value that was // never folded properly. self.index += 1; } else if (c == '(') { self.skipComment(); } else { return; } } }
/// Consumes a comment, and the comments inside it. A comment nests, which /// is why this cannot be "scan to the next `)`". fn skipComment(self: *Scanner) void { std.debug.assert(self.source[self.index] == '('); const start = self.index + 1; var depth: usize = 0; while (!self.atEnd()) { switch (self.source[self.index]) { '(' => { depth += 1; self.index += 1; }, ')' => { depth -= 1; self.index += 1; if (depth == 0) { self.last_comment = self.source[start .. self.index - 1]; return; } }, '\\' => self.index += @min(2, self.source.len - self.index), else => self.index += 1, } } // An unterminated comment. The rest of the value is inside it, which // is a defect, but there is nothing to be gained by pretending it is // not a comment at all. self.last_comment = self.source[start..]; }
/// A run of `atext`, or null if there is none here. pub fn atom(self: *Scanner) ?[]const u8 { self.skipCfws(); return self.run(isAtext); }
/// A run of RFC 2045 token characters. pub fn token(self: *Scanner) ?[]const u8 { self.skipCfws(); return self.run(isTokenChar); }
/// `atom *("." atom)`, with the dots included in what is returned. The /// left hand side of an address and a domain name are both this. /// /// Consecutive dots, and a leading or trailing one, are all defects that /// this accepts: `..@example.com` exists, and rejecting it here would /// leave the caller nothing to report about. pub fn dotAtom(self: *Scanner) ?[]const u8 { self.skipCfws(); const start = self.index; while (!self.atEnd()) { const c = self.source[self.index]; if (isAtext(c) or c == '.') { self.index += 1; } else break; } if (self.index == start) return null; return self.source[start..self.index]; }
/// The inside of a `"..."`, with the quotes removed and the backslash /// escapes still in place — `unquoteWriter` takes them out. Null if the /// next thing is not a quoted-string. /// /// An unterminated quoted-string swallows the rest of the value, which is /// what every other parser does with one and is the only reading that does /// not silently change where an address ends. pub fn quotedString(self: *Scanner) ?[]const u8 { self.skipCfws(); if (self.peek() != '"') return null; self.index += 1; const start = self.index; while (!self.atEnd()) { switch (self.source[self.index]) { '"' => { self.index += 1; return self.source[start .. self.index - 1]; }, '\\' => self.index += @min(2, self.source.len - self.index), else => self.index += 1, } } return self.source[start..]; }
/// The inside of a `[...]`, with the brackets removed. This is how an /// address names a host by address rather than by name: /// `<jeff@[192.0.2.1]>`. pub fn domainLiteral(self: *Scanner) ?[]const u8 { self.skipCfws(); if (self.peek() != '[') return null; self.index += 1; const start = self.index; while (!self.atEnd()) { switch (self.source[self.index]) { ']' => { self.index += 1; return self.source[start .. self.index - 1]; }, '\\' => self.index += @min(2, self.source.len - self.index), else => self.index += 1, } } return self.source[start..]; }
/// An atom or a quoted-string, which is what the grammar calls a `word` /// and what a display name is a sequence of. pub const Word = union(enum) { atom: []const u8, /// Escapes still in place. quoted: []const u8, };
pub fn word(self: *Scanner) ?Word { self.skipCfws(); if (self.peek() == '"') return .{ .quoted = self.quotedString().? }; if (self.atom()) |a| return .{ .atom = a }; return null; }
fn run(self: *Scanner, comptime predicate: fn (u8) bool) ?[]const u8 { const start = self.index; while (!self.atEnd() and predicate(self.source[self.index])) self.index += 1; if (self.index == start) return null; return self.source[start..self.index]; }};
/// Writes the contents of a quoted-string or a comment with its backslash/// escapes removed.pub fn unquoteWriter(w: *Io.Writer, raw: []const u8) Io.Writer.Error!void { var start: usize = 0; var i: usize = 0; while (i < raw.len) { if (raw[i] == '\\' and i + 1 < raw.len) { try w.writeAll(raw[start..i]); try w.writeByte(raw[i + 1]); i += 2; start = i; } else { i += 1; } } try w.writeAll(raw[start..]);}
pub fn unquoteAlloc(gpa: Allocator, raw: []const u8) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); unquoteWriter(&out.writer, raw) catch return error.OutOfMemory; return out.toOwnedSlice();}
/// Which grammar a value is being written into, since what may go unquoted/// differs between them.pub const Syntax = enum { /// RFC 5322: a single atom — one word, with no `.` in it. atom, /// RFC 5322: a `dot-atom`, which is atoms joined by full stops. The left /// hand side of an address and a domain name are both this, and it is the /// only place a `.` may appear unquoted. dot_atom, /// RFC 5322: a *phrase*, which is a sequence of atoms and so may hold the /// spaces between them. A display name is one. Reading a phrase back /// joins its words with a single space, so a phrase whose spacing is not /// single-spaced-between-words has to be quoted to survive. phrase, /// RFC 2045: a `Content-Type` or `Content-Disposition` parameter value. token,
fn allows(self: Syntax, c: u8) bool { return switch (self) { .atom => isAtext(c), .dot_atom => isAtext(c) or c == '.', .phrase => isAtext(c) or c == ' ', .token => isTokenChar(c), }; }};
/// Whether `text` would have to be quoted to appear in `syntax`.pub fn needsQuoting(text: []const u8, syntax: Syntax) bool { if (text.len == 0) return true; // An empty atom is not an atom. for (text) |c| if (!syntax.allows(c)) return true; if (syntax == .phrase) { // A space at either end, or two in a row, does not survive the trip // through a phrase, so such a name has to be quoted even though every // character in it is allowed. if (isWsp(text[0]) or isWsp(text[text.len - 1])) return true; for (text[1..], text[0 .. text.len - 1]) |c, previous| { if (isWsp(c) and isWsp(previous)) return true; } } return false;}
/// Writes `text` so that it reads back as itself: as a bare atom or token/// where that is possible, and as a quoted-string where it is not.////// A byte below 0x20, which cannot legally appear even inside quotes, is/// dropped rather than written: a header is a line, and a CR, an LF or a NUL/// in the middle of one is how a header injection works. The caller that/// wanted those bytes wanted an encoded word.pub fn quoteWriter(w: *Io.Writer, text: []const u8, syntax: Syntax) Io.Writer.Error!void { if (!needsQuoting(text, syntax)) return w.writeAll(text); try w.writeByte('"'); for (text) |c| switch (c) { 0...0x1f, 127 => {}, '"', '\\' => try w.writeAll(&.{ '\\', c }), else => try w.writeByte(c), }; try w.writeByte('"');}
test "an atom stops at a special" { var s: Scanner = .init("jeff@example.com"); try testing.expectEqualStrings("jeff", s.atom().?); try testing.expect(s.eat('@')); try testing.expectEqualStrings("example.com", s.dotAtom().?); try testing.expect(s.atEnd());}
test "comments are skipped and remembered" { var s: Scanner = .init(" (a (nested) comment) jeff"); try testing.expectEqualStrings("jeff", s.atom().?); try testing.expectEqualStrings("a (nested) comment", s.last_comment.?);}
test "an unterminated comment swallows the rest" { var s: Scanner = .init("jeff (and then"); try testing.expectEqualStrings("jeff", s.atom().?); s.skipCfws(); try testing.expect(s.atEnd()); try testing.expectEqualStrings("and then", s.last_comment.?);}
test "a quoted string keeps its escapes" { var s: Scanner = .init("\"O\\\"Brien, Sean\" <sean@example.com>"); const raw = s.quotedString().?; try testing.expectEqualStrings("O\\\"Brien, Sean", raw); const unquoted = try unquoteAlloc(testing.allocator, raw); defer testing.allocator.free(unquoted); try testing.expectEqualStrings("O\"Brien, Sean", unquoted);}
test "an unterminated quoted string takes the remainder" { var s: Scanner = .init("\"never closed"); try testing.expectEqualStrings("never closed", s.quotedString().?); try testing.expect(s.atEnd());}
test "a domain literal is an address in brackets" { var s: Scanner = .init("[192.0.2.1]"); try testing.expectEqualStrings("192.0.2.1", s.domainLiteral().?);}
test "a token is not an atom" { var s: Scanner = .init("text/plain; charset=utf-8"); try testing.expectEqualStrings("text", s.token().?); try testing.expect(s.eat('/')); try testing.expectEqualStrings("plain", s.token().?); try testing.expect(s.eat(';')); try testing.expectEqualStrings("charset", s.token().?); try testing.expect(s.eat('=')); try testing.expectEqualStrings("utf-8", s.token().?);}
test quoteWriter { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit();
try quoteWriter(&out.writer, "Jeff", .atom); try testing.expectEqualStrings("Jeff", out.written());
out.clearRetainingCapacity(); try quoteWriter(&out.writer, "Ollie, Jeff", .atom); try testing.expectEqualStrings("\"Ollie, Jeff\"", out.written());
// A phrase holds the spaces between its words, so a name needs no quotes // until it holds something else. out.clearRetainingCapacity(); try quoteWriter(&out.writer, "Jeff Ollie", .phrase); try testing.expectEqualStrings("Jeff Ollie", out.written()); out.clearRetainingCapacity(); try quoteWriter(&out.writer, "Jeff Ollie", .atom); try testing.expectEqualStrings("\"Jeff Ollie\"", out.written()); out.clearRetainingCapacity(); try quoteWriter(&out.writer, "Ollie, Jeff", .phrase); try testing.expectEqualStrings("\"Ollie, Jeff\"", out.written()); out.clearRetainingCapacity(); try quoteWriter(&out.writer, "Jeff Ollie", .phrase); try testing.expectEqualStrings("\"Jeff Ollie\"", out.written()); out.clearRetainingCapacity(); try quoteWriter(&out.writer, " Jeff", .phrase); try testing.expectEqualStrings("\" Jeff\"", out.written());
out.clearRetainingCapacity(); try quoteWriter(&out.writer, "a\"b\\c", .atom); try testing.expectEqualStrings("\"a\\\"b\\\\c\"", out.written());
// A dot is a token character and not an atom character, so the same text // is quoted in one grammar and bare in the other. out.clearRetainingCapacity(); try quoteWriter(&out.writer, "jeff.ollie", .dot_atom); try testing.expectEqualStrings("jeff.ollie", out.written()); out.clearRetainingCapacity(); try quoteWriter(&out.writer, "jeff>ollie", .dot_atom); try testing.expectEqualStrings("\"jeff>ollie\"", out.written());
out.clearRetainingCapacity(); try quoteWriter(&out.writer, "file.txt", .token); try testing.expectEqualStrings("file.txt", out.written()); out.clearRetainingCapacity(); try quoteWriter(&out.writer, "file.txt", .atom); try testing.expectEqualStrings("\"file.txt\"", out.written());}
test "a header cannot be injected through a quoted string" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try quoteWriter(&out.writer, "Jeff\r\nBcc: victim@example.com", .atom); try testing.expectEqualStrings("\"JeffBcc: victim@example.com\"", out.written());}