Something went wrong. Try again.
Classic Unix mailbox files for Zig 0.16: an iterator to read, a predicate to delete, an atomic rewrite for every change.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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 },};