// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What this library must do with a mailbox nobody wrote. //! //! Which, for this format, is most mailboxes. An mbox has no length field, no //! checksum and no version: a damaged one is byte-for-byte indistinguishable //! from a strange one, and the scanner has to do something sensible either //! way. "Sensible" here is not "the right answer" — there often is not one — //! but a small number of properties that have to hold whatever the bytes are: //! //! * Nothing crashes, and nothing reads past the end of anything. //! * Quoting is why a body cannot split its own message, so no line a quoting //! variant stores may look like a boundary. //! * Reading a mailbox and writing it back reaches a fixed point after one //! round, and stays there. This is the property that catches the real bugs: //! a scanner and a writer that disagree by one blank line will pass every //! handwritten test and fail this on the third message. //! * Trusting a `Content-Length` can only ever merge messages, never invent //! them, so a mailbox read without trusting it has at least as many. //! //! Each target runs against every variant, rather than asking the generator to //! pick one. That is partly coverage — one input exercises four code paths — //! and partly because `Smith.value` returns a range's minimum for input it //! cannot use, so a target that asked would have been testing `mboxo` and //! nothing else without ever saying so. //! //! Each target is an ordinary test as well as a fuzz target. Without `--fuzz` //! it runs the seeds beside it, so `zig build test` exercises the same //! properties on input that has already been interesting once. //! //! With `--fuzz` — `zig build fuzz --fuzz` — Zig's own fuzzer drives them //! with coverage feedback. `tools/fuzz.zig` is a second way in, a loop with a //! fixed seed, which is what the workflow runs. const builtin = @import("builtin"); const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const Smith = std.testing.Smith; const mbox = @import("mbox"); const From = mbox.From; const Reader = mbox.Reader; const Writer = mbox.Writer; const variant = mbox.variant; const Variant = mbox.Variant; /// The allocator the targets run against. /// /// Under `zig build test` that is the testing allocator, which reports a leak /// as a failure. `tools/fuzz.zig` cannot name it — it is not a test build — so /// it sets this to a checked allocator of its own instead. pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined; const every_variant = [_]Variant{ .mboxo, .mboxrd, .mboxcl, .mboxcl2 }; // -- the postmark ------------------------------------------------------------ const from_max = 256; const from_seeds = [_][]const u8{ "From jeff@example.com Mon Jan 1 00:00:00 2024", "From jeff@example.com Mon Jan 01 00:00:00 2024", // No return path, which is what a bounce looks like. "From Mon Jan 1 00:00:00 2024", "From MAILER-DAEMON Mon Jan 1 00:00:00 2024", // The UUCP trailer, and a wrong weekday, both of which are real. "From jeff Mon Jan 1 00:00:00 2024 remote from ihnp4", "From jeff Thu Dec 31 23:59:59 1999", "From jeff Mon Jan 1 00:00:00 2024 -0600", "From jeff Mon Jan 1 00:00:00 2024 PST", // A carriage return, because a CRLF mailbox keeps one here. "From jeff Mon Jan 1 00:00:00 2024\r", // Dates that must be refused rather than narrowed into a panic. "From jeff Mon Jan 99 00:00:00 2024", "From jeff Mon Jan 1 99:99:99 2024", "From jeff Mon Feb 30 00:00:00 2023", "From jeff Mon Jan 1 00:00:00 999999999999999999999", // Not postmarks. "From", "From ", "Fromage", ">From quoted", "", "From \x00\x00 \xff\xff", }; fn fromProperty(line: []const u8) !void { // The two ways of asking are the same question. const parsed = From.parse(line) catch |err| { try testing.expect(err == error.NotAFromLine); try testing.expect(!From.isFromLine(line)); return; }; try testing.expect(From.isFromLine(line)); // Every part borrows from the line rather than pointing somewhere else. for ([_][]const u8{ parsed.address, parsed.date, parsed.trailer }) |part| { try testing.expect(part.len <= line.len); } // A date this cannot read is no date. What it must never be is a panic: // every field in an `asctime` is two digits wide and every one of them is // narrower than two digits in the type it lands in. const when = parsed.timestamp(); // Writing it and reading it back gives the same answer, whatever it was. var buffer: [from_max * 2]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try parsed.write(&w); const again = try From.parse(w.buffered()); try testing.expectEqualStrings(parsed.address, again.address); try testing.expectEqualStrings(parsed.date, again.date); try testing.expectEqualStrings(parsed.trailer, again.trailer); // And a composed postmark says the time it was given. Years outside the // four digits `asctime` has room for are left alone: what comes out is // not an `asctime` and is not claimed to parse as one. if (when) |t| { if (t.year >= 0 and t.year <= 9999) { var composed: [from_max * 2]u8 = undefined; var cw: Io.Writer = .fixed(&composed); try From.writeLine(&cw, parsed.address, t); const back = (try From.parse(cw.buffered())).timestamp().?; try testing.expectEqual(t.year, back.year); try testing.expectEqual(t.month, back.month); try testing.expectEqual(t.day, back.day); try testing.expectEqual(t.hour, back.hour); try testing.expectEqual(t.minute, back.minute); try testing.expectEqual(t.second, back.second); } } } test "fuzz the postmark" { for (from_seeds) |seed| try fromProperty(seed); try testing.fuzz({}, fuzzFrom, .{}); } fn fuzzFrom(_: void, smith: *Smith) !void { var buffer: [from_max]u8 = undefined; try fromProperty(buffer[0..smith.slice(&buffer)]); } fn runFrom(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return fuzzFrom({}, &smith); } // -- the quoting ------------------------------------------------------------- const quote_max = 1024; const quote_seeds = [_][]const u8{ "Subject: hi\n\nbody\n", "From at the very start\n", "\nFrom after a blank line\n", ">From already quoted\n", ">>>>From quoted rather a lot\n", "Fromage is not a boundary\n", "From", "From ", "no trailing newline", "\n", "\r\n", "From x\r\nFrom y\r\n", "", &@as([32]u8, @splat('\n')), std.mem.asBytes(&@as([32][6]u8, @splat("From \n".*))), std.mem.asBytes(&@as([32][7]u8, @splat(">From \n".*))), }; fn quoteProperty(message: []const u8) !void { for (every_variant) |v| { var stored: [quote_max * 3]u8 = undefined; var w: Io.Writer = .fixed(&stored); try variant.writeQuoted(&w, message, v); const written = w.buffered(); // The length is computed before the buffer is, so being wrong about // it would be a bounds failure somewhere else rather than here. try testing.expectEqual(variant.quotedLen(message, v), written.len); // The whole point of quoting: nothing a quoting variant stores can be // mistaken for the start of a message. If this ever fails, a body has // been given the power to split its own message in two. if (v.quotes()) { var rest = written; while (rest.len > 0) { const end = if (std.mem.findScalar(u8, rest, '\n')) |at| at + 1 else rest.len; try testing.expect(!variant.looksLikeBoundary(rest[0..end])); rest = rest[end..]; } } // Undoing it never grows, which is what lets it work in place. var scratch: [quote_max * 3]u8 = undefined; @memcpy(scratch[0..written.len], written); const back = variant.unquoteInPlace(scratch[0..written.len], v); try testing.expect(back.len <= written.len); // And for the variants that promise it, undoing it is exact. if (v.reversible()) try testing.expectEqualStrings(message, back); } } test "fuzz the quoting" { for (quote_seeds) |seed| try quoteProperty(seed); try testing.fuzz({}, fuzzQuote, .{}); } fn fuzzQuote(_: void, smith: *Smith) !void { var buffer: [quote_max]u8 = undefined; try quoteProperty(buffer[0..smith.slice(&buffer)]); } fn runQuote(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return fuzzQuote({}, &smith); } // -- the scanner ------------------------------------------------------------- const scan_max = 4096; const scan_seeds = [_][]const u8{ "", "From a b\n", "From a b\n\n", "From a b\n\nbody\n\n", "From a b\n\nbody\n\nFrom c d\n\nmore\n", // A postmark with nothing before it but a body line: not a boundary. "From a b\n\nbody\nFrom c d\nstill body\n", // Quoted bodies, at every depth. "From a b\n\n>From x\n>>From y\n>>>From z\n", // Blank lines in every arrangement, which is where the framing lives. "From a b\n\n\n\n\nFrom c d\n\n\n", "From a b\n\nbody\n\n\nFrom c d\n\n", // CRLF throughout, and mixed. "From a b\r\n\r\nbody\r\n\r\nFrom c d\r\n\r\nmore\r\n", "From a b\r\n\nbody\r\n\n", // Lengths, honest and otherwise. "From a b\nContent-Length: 5\n\nbody\n\nFrom c d\n\nmore\n", "From a b\nContent-Length: 99999\n\nbody\n\nFrom c d\n\nmore\n", "From a b\nContent-Length: 0\n\n\nFrom c d\n\nmore\n", "From a b\nContent-Length: -1\n\nbody\n", "From a b\nContent-Length: 99999999999999999999999999\n\nbody\n", "From a b\ncontent-length: 5\n\nbody\n", "From a b\nContent-Length: 5\n\tfolded\n\nbody\n", // Not mailboxes. "hello\n", "\n", "\nFrom a b\n", // No terminator at the end, which is how a truncated download arrives. "From a b\n\nbody", "From a b", "From ", // A great many tiny messages. std.mem.asBytes(&@as([64][11]u8, @splat("From a b\n\n\n".*))), }; /// Every message in a mailbox, owned. const Messages = struct { items: []Owned, const Owned = struct { postmark: []u8, body: []u8 }; fn deinit(self: *Messages, gpa: Allocator) void { for (self.items) |one| { gpa.free(one.postmark); gpa.free(one.body); } gpa.free(self.items); self.* = undefined; } fn eql(a: Messages, b: Messages) bool { if (a.items.len != b.items.len) return false; for (a.items, b.items) |one, two| { if (!std.mem.eql(u8, one.postmark, two.postmark)) return false; if (!std.mem.eql(u8, one.body, two.body)) return false; } return true; } }; /// Reads a whole mailbox, checking as it goes the things that must be true of /// any sequence of messages the scanner returns. fn readAll(gpa: Allocator, source: []const u8, options: Reader.Options) !?Messages { var input: Io.Reader = .fixed(source); var reader: Reader = .init(gpa, &input, options); defer reader.deinit(); var items: std.ArrayList(Messages.Owned) = .empty; errdefer { for (items.items) |one| { gpa.free(one.postmark); gpa.free(one.body); } items.deinit(gpa); } var previous: ?u64 = null; var index: usize = 0; while (true) { const entry = reader.next() catch |err| { switch (err) { // The declared ways to fail, and the only ones. error.NotAMailbox, error.MessageTooLong, error.ReadFailed => {}, error.OutOfMemory => return err, } for (items.items) |one| { gpa.free(one.postmark); gpa.free(one.body); } items.deinit(gpa); return null; } orelse break; // Every message starts after the one before it, and where it says it // does. Together these are what rule out two messages overlapping. if (previous) |before| try testing.expect(entry.offset > before); previous = entry.offset; try testing.expect(entry.offset < source.len); try testing.expect(From.isFromLine(source[@intCast(entry.offset)..])); try testing.expectEqual(index, entry.index); index += 1; var pw: Io.Writer.Allocating = .init(gpa); defer pw.deinit(); try entry.from.write(&pw.writer); try items.append(gpa, .{ .postmark = try gpa.dupe(u8, pw.writer.buffered()), .body = try gpa.dupe(u8, entry.bytes), }); } return .{ .items = try items.toOwnedSlice(gpa) }; } /// Writes a whole mailbox back out. fn writeAll(gpa: Allocator, messages: Messages, v: Variant) ![]u8 { var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); var writer: Writer = .init(&out.writer, .{ .variant = v }); for (messages.items) |one| { try writer.append(try From.parse(one.postmark), one.body); } return gpa.dupe(u8, out.writer.buffered()); } fn scanProperty(source: []const u8) !void { const gpa = backing; for (every_variant) |v| { const options: Reader.Options = .{ .variant = v, .max_message_bytes = scan_max * 8 }; var first = (try readAll(gpa, source, options)) orelse continue; defer first.deinit(gpa); // Reading and writing reaches a fixed point, and after one round it // stays there. The `mboxo` family needs that round: its quoting // cannot be undone, so the first pass may change a body. Nothing may // change on the second, and this is what catches a scanner and a // writer that disagree about the framing by one blank line. const once = try writeAll(gpa, first, v); defer gpa.free(once); var second = (try readAll(gpa, once, options)) orelse { // What this library wrote, it must be able to read. return error.WroteAnUnreadableMailbox; }; defer second.deinit(gpa); const twice = try writeAll(gpa, second, v); defer gpa.free(twice); try testing.expectEqualStrings(once, twice); var third = (try readAll(gpa, twice, options)) orelse return error.WroteAnUnreadableMailbox; defer third.deinit(gpa); try testing.expect(Messages.eql(second, third)); // The variants that quote reversibly have nothing to settle: the // first pass is already the fixed point. // `mboxrd` has nothing to settle: the first pass is already the fixed // point, up to the one normalization an mbox cannot avoid. A message // whose last line had no terminator has one now, because the empty // line that ends a message has to begin at the start of a line -- and // it has gained exactly that and nothing else, which is what this // checks rather than waving at. // // The other three are held to the weaker property above and not this // one, each for a reason of its own. `mboxo` and `mboxcl` quote // irreversibly. `mboxcl2` quotes nothing at all, but its // `Content-Length` is framing rather than message: one the mailbox // arrived with describes whatever file it came out of, so it is // replaced with an accurate one, and a message that was carrying a // stale one is a message that changes on its first rewrite. if (v == .mboxrd) { try testing.expectEqual(first.items.len, second.items.len); for (first.items, second.items) |a, b| { try testing.expectEqualStrings(a.postmark, b.postmark); if (a.body.len == 0 or a.body[a.body.len - 1] == '\n') { try testing.expectEqualStrings(a.body, b.body); } else { // Exactly one line ending longer, and the same bytes up to // it -- not merely "similar". try testing.expect(b.body.len >= a.body.len); try testing.expectEqualStrings(a.body, b.body[0..a.body.len]); const added = b.body[a.body.len..]; try testing.expect(std.mem.eql(u8, added, "\n") or std.mem.eql(u8, added, "\r\n")); } } } } } test "fuzz the scanner" { for (scan_seeds) |seed| try scanProperty(seed); try testing.fuzz({}, fuzzScan, .{}); } fn fuzzScan(_: void, smith: *Smith) !void { var buffer: [scan_max]u8 = undefined; try scanProperty(buffer[0..smith.slice(&buffer)]); } fn runScan(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return fuzzScan({}, &smith); } // -- the declared length ----------------------------------------------------- const length_max = 4096; const length_seeds = scan_seeds; fn lengthProperty(source: []const u8) !void { const gpa = backing; for ([_]Variant{ .mboxcl, .mboxcl2 }) |v| { var trusting = (try readAll(gpa, source, .{ .variant = v, .trust_content_length = true, .max_message_bytes = length_max * 8, })) orelse continue; defer trusting.deinit(gpa); var searching = (try readAll(gpa, source, .{ .variant = v, .trust_content_length = false, .max_message_bytes = length_max * 8, })) orelse continue; defer searching.deinit(gpa); // Believing a length can only ever carry the scanner *past* a // boundary, never make one up. So a mailbox read without believing it // has at least as many messages in it — which is the precise sense in // which trusting the header is the dangerous choice: what it risks is // hiding a message, and nothing else. try testing.expect(searching.items.len >= trusting.items.len); } } test "fuzz the declared length" { for (length_seeds) |seed| try lengthProperty(seed); try testing.fuzz({}, fuzzLength, .{}); } fn fuzzLength(_: void, smith: *Smith) !void { var buffer: [length_max]u8 = undefined; try lengthProperty(buffer[0..smith.slice(&buffer)]); } fn runLength(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return fuzzLength({}, &smith); } // -- the same targets, for a driver that is not the test runner -------------- /// One fuzz target, as `tools/fuzz.zig` sees it. /// /// `zig build test` reaches these through the `test` blocks above and Zig's /// own fuzzer reaches them through `std.testing.fuzz`. This is the third way /// in, for `tools/fuzz.zig`, the loop with a fixed seed that the workflow /// runs. pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run, which are /// what stands in for the coverage feedback a real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time. content_max: usize, }; pub const all = [_]Target{ .{ .name = "from", .run = runFrom, .corpus = &from_seeds, .content_max = from_max }, .{ .name = "quote", .run = runQuote, .corpus = "e_seeds, .content_max = quote_max }, .{ .name = "scan", .run = runScan, .corpus = &scan_seeds, .content_max = scan_max }, .{ .name = "length", .run = runLength, .corpus = &length_seeds, .content_max = length_max }, };