// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the library does to a real file. //! //! Everything that can be decided from bytes alone is tested beside the code //! that decides it. This is the rest, and the rest is the part an mbox library //! actually gets wrong: whether a rewrite keeps the mailbox's permissions, //! whether the handle still refers to the mailbox after the file under it has //! been replaced, whether a lock is released rather than leaked. None of those //! are claims about bytes, and none of them can be tested without a directory. //! //! A module of its own, so that `zig build test` runs these and a consumer of //! the library never compiles them. const std = @import("std"); const Io = std.Io; const Dir = Io.Dir; const File = Io.File; const Allocator = std.mem.Allocator; const testing = std.testing; const io = testing.io; const mbox = @import("mbox"); const Mailbox = mbox.Mailbox; const From = mbox.From; const gpa = testing.allocator; const alice = "From alice@example.com Mon Jan 1 00:00:00 2024"; const bob = "From bob@example.net Tue Jan 2 00:00:00 2024"; const carol = "From carol@example.org Wed Jan 3 00:00:00 2024"; /// A read buffer big enough that the small fixtures below arrive whole, which /// keeps the tests about the file layer rather than about chunking. var buffer: [8 * 1024]u8 = undefined; fn writeFile(dir: Dir, name: []const u8, contents: []const u8) !void { const file = try dir.createFile(io, name, .{}); defer file.close(io); try file.writeStreamingAll(io, contents); } fn readFile(dir: Dir, name: []const u8) ![]u8 { return dir.readFileAlloc(io, name, gpa, .limited(1 << 20)); } /// Every message in the mailbox, each one owned by the caller. fn collect(m: *Mailbox) ![][]u8 { var it = try m.iterate(gpa, io, &buffer); defer it.deinit(); var out: std.ArrayList([]u8) = .empty; errdefer { for (out.items) |one| gpa.free(one); out.deinit(gpa); } while (try it.next()) |entry| try out.append(gpa, try gpa.dupe(u8, entry.bytes)); return out.toOwnedSlice(gpa); } fn freeAll(messages: [][]u8) void { for (messages) |one| gpa.free(one); gpa.free(messages); } fn senderIs(want: []const u8, entry: mbox.Reader.Entry) Allocator.Error!bool { return std.mem.eql(u8, entry.from.address, want); } // -- reading and appending --------------------------------------------------- test "a message appended to a new mailbox is the message that comes back" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const message = "Subject: hello\n\nthe body\n"; _ = try m.append(gpa, io, try From.parse(alice), message); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 1), got.len); try testing.expectEqualStrings(message, got[0]); } test "an empty file is a mailbox with no messages, and create makes one" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 0), got.len); // And it really is a file, so that something else can open it. const contents = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(contents); try testing.expectEqualStrings("", contents); } test "create leaves an existing mailbox alone" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", alice ++ "\n\nkeep me\n\n"); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 1), got.len); try testing.expectEqualStrings("\nkeep me\n", got[0]); } test "appends accumulate, in the order they were made" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); _ = try m.append(gpa, io, try From.parse(alice), "Subject: one\n\nfirst\n"); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); _ = try m.append(gpa, io, try From.parse(carol), "Subject: three\n\nthird\n"); var it = try m.iterate(gpa, io, &buffer); defer it.deinit(); for ([_][]const u8{ "alice@example.com", "bob@example.net", "carol@example.org" }, 0..) |who, i| { const entry = (try it.next()).?; try testing.expectEqualStrings(who, entry.from.address); try testing.expectEqual(i, entry.index); } try testing.expect((try it.next()) == null); } test "a body that could have split its own message survives a round trip" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); // The first line would be a postmark if it were not quoted, and the second // is what a message that was itself quoting a mailbox looks like. const message = "Subject: quoting\n\nFrom alice, in the body\n>From deeper still\n"; _ = try m.append(gpa, io, try From.parse(alice), message); _ = try m.append(gpa, io, try From.parse(bob), "Subject: after\n\nstill here\n"); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 2), got.len); try testing.expectEqualStrings(message, got[0]); // And on disk the dangerous line really was quoted. const contents = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(contents); try testing.expect(std.mem.indexOf(u8, contents, "\n>From alice, in the body\n") != null); try testing.expect(std.mem.indexOf(u8, contents, "\n>>From deeper still\n") != null); } test "a message whose last line has no terminator gets one, and only one" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); _ = try m.append(gpa, io, try From.parse(alice), "Subject: ragged\n\nno newline"); const got = try collect(&m); defer freeAll(got); // The one normalization an mbox cannot avoid: a file of lines cannot hold // a message that does not end in one. try testing.expectEqualStrings("Subject: ragged\n\nno newline\n", got[0]); } test "a mailbox written with CRLF is read and rewritten with CRLF" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); const source = alice ++ "\r\nSubject: one\r\n\r\nfirst\r\n\r\n" ++ bob ++ "\r\nSubject: two\r\n\r\nsecond\r\n\r\n"; try writeFile(tmp.dir, "mail.mbox", source); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const got = try collect(&m); defer freeAll(got); try testing.expectEqualStrings("Subject: one\r\n\r\nfirst\r\n", got[0]); // A rewrite that keeps everything is the identity, carriage returns // included. _ = try m.filterMessages(gpa, io, {}, mbox.filter.keepAll); const after = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(after); try testing.expectEqualStrings(source, after); } // -- filtering --------------------------------------------------------------- test "a filter that keeps everything leaves the file byte for byte as it was" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); const source = alice ++ "\nSubject: one\n\nfirst\n\n" ++ bob ++ "\nSubject: two\n\n>From quoted\n\n"; try writeFile(tmp.dir, "mail.mbox", source); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const stats = try m.filterMessages(gpa, io, {}, mbox.filter.keepAll); try testing.expectEqual(@as(usize, 2), stats.kept); try testing.expectEqual(@as(usize, 0), stats.removed); const after = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(after); try testing.expectEqualStrings(source, after); } test "a filter that keeps nothing leaves an empty mailbox that still opens" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", alice ++ "\n\nfirst\n\n" ++ bob ++ "\n\nsecond\n\n"); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const stats = try m.filterMessages(gpa, io, @as([]const u8, "nobody"), senderIs); try testing.expectEqual(@as(usize, 0), stats.kept); try testing.expectEqual(@as(usize, 2), stats.removed); const after = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(after); try testing.expectEqualStrings("", after); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 0), got.len); } test "removing the middle message leaves the others untouched" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); _ = try m.append(gpa, io, try From.parse(alice), "Subject: one\n\nfirst\n"); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); _ = try m.append(gpa, io, try From.parse(carol), "Subject: three\n\nthird\n"); const Drop = struct { fn keep(_: void, entry: mbox.Reader.Entry) Allocator.Error!bool { return !std.mem.eql(u8, entry.from.address, "bob@example.net"); } }; const stats = try m.filterMessages(gpa, io, {}, Drop.keep); try testing.expectEqual(@as(usize, 2), stats.kept); try testing.expectEqual(@as(usize, 1), stats.removed); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 2), got.len); try testing.expectEqualStrings("Subject: one\n\nfirst\n", got[0]); try testing.expectEqualStrings("Subject: three\n\nthird\n", got[1]); } test "a predicate may parse the message it is deciding about" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); _ = try m.append(gpa, io, try From.parse(alice), "Subject: keep this\n\nreal mail\n"); _ = try m.append(gpa, io, try From.parse(bob), "Subject: [SPAM] buy things\n\nno\n"); const BySubject = struct { fn keep(allocator: Allocator, entry: mbox.Reader.Entry) Allocator.Error!bool { var parsed = try entry.parse(allocator, .{}); defer parsed.deinit(); const subject = (try parsed.root.subject()) orelse return true; return std.mem.indexOf(u8, subject, "[SPAM]") == null; } }; const stats = try m.filterMessages(gpa, io, gpa, BySubject.keep); try testing.expectEqual(@as(usize, 1), stats.kept); try testing.expectEqual(@as(usize, 1), stats.removed); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 1), got.len); try testing.expect(std.mem.indexOf(u8, got[0], "real mail") != null); } // -- what the rewrite has to preserve ---------------------------------------- /// The permission bits of a file, which is not the whole of what `stat` /// reports: that carries the kind of the file in the same number. fn modeOf(dir: Dir, name: []const u8) !u32 { const st = try dir.statFile(io, name, .{}); return @as(u32, @intCast(st.permissions.toMode())) & 0o777; } test "a rewrite keeps the mailbox's permissions" { if (!@hasDecl(File.Permissions, "toMode")) return error.SkipZigTest; var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", alice ++ "\n\nfirst\n\n"); // A spool is private, and a rewrite that made it world-readable would be // a disclosure rather than an inconvenience. const private: File.Permissions = .fromMode(0o600); try tmp.dir.setFilePermissions(io, "mail.mbox", private, .{}); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); try testing.expectEqual(@as(u32, 0o600), try modeOf(tmp.dir, "mail.mbox")); } test "permissions can be said explicitly when the old ones are not wanted" { if (!@hasDecl(File.Permissions, "toMode")) return error.SkipZigTest; var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", alice ++ "\n\nfirst\n\n"); try tmp.dir.setFilePermissions(io, "mail.mbox", .fromMode(0o644), .{}); const wanted: File.Permissions = .fromMode(0o600); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{ .permissions = wanted }); defer m.close(io); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); try testing.expectEqual(@as(u32, 0o600), try modeOf(tmp.dir, "mail.mbox")); } test "the handle still reads the mailbox after the file under it was replaced" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); // Each of these renames a new file over the old one, so each leaves the // previous handle pointing at an inode with no name. Without the reopen // inside `rewrite`, the second append would be writing a copy of a file // nobody can reach and the reads below would find one message. _ = try m.append(gpa, io, try From.parse(alice), "Subject: one\n\nfirst\n"); const first = try collect(&m); freeAll(first); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); _ = try m.append(gpa, io, try From.parse(carol), "Subject: three\n\nthird\n"); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 3), got.len); // And what is at the path is what the handle sees, rather than something // that was left behind. const contents = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(contents); try testing.expect(std.mem.indexOf(u8, contents, "third") != null); } test "a rewrite leaves no temporary file behind" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); _ = try m.append(gpa, io, try From.parse(alice), "Subject: one\n\nfirst\n"); _ = try m.filterMessages(gpa, io, {}, mbox.filter.keepAll); var names: usize = 0; var it = tmp.dir.iterate(); while (try it.next(io)) |entry| { try testing.expectEqualStrings("mail.mbox", entry.name); names += 1; } try testing.expectEqual(@as(usize, 1), names); } // -- locking ----------------------------------------------------------------- test "a lock is released when the operation ends, not when the mailbox closes" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", alice ++ "\n\nfirst\n\n"); // Two handles on one file. If either operation leaked its lock, the next // one through the *other* handle would block on it and this test would // hang rather than fail -- which is exactly the failure worth catching, // because a leaked lock in a mail tool is a mailbox nobody can open. var one = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer one.close(io); var two = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer two.close(io); const read = try collect(&one); freeAll(read); _ = try two.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); const again = try collect(&one); defer freeAll(again); try testing.expectEqual(@as(usize, 2), again.len); _ = try one.filterMessages(gpa, io, {}, mbox.filter.keepAll); const last = try collect(&two); defer freeAll(last); try testing.expectEqual(@as(usize, 2), last.len); } test "locking can be turned off for a mailbox nothing else can reach" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{ .lock = false }); defer m.close(io); _ = try m.append(gpa, io, try From.parse(alice), "Subject: one\n\nfirst\n"); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 1), got.len); } // -- variants ---------------------------------------------------------------- test "an mboxcl2 mailbox is written with lengths and read back by them" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{ .variant = .mboxcl2 }); defer m.close(io); // A body that would split its own message under any variant that does not // quote, which is exactly the case the length exists for. const message = "Subject: one\n\nFrom nowhere, in the body\n"; _ = try m.append(gpa, io, try From.parse(alice), message); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); const contents = try readFile(tmp.dir, "mail.mbox"); defer gpa.free(contents); // Stored exactly as written: nothing was quoted. try testing.expect(std.mem.indexOf(u8, contents, "\nFrom nowhere, in the body\n") != null); try testing.expect(std.mem.indexOf(u8, contents, ">From nowhere") == null); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 2), got.len); try testing.expectEqualStrings(message, got[0]); } test "an mboxcl2 length that lies is not believed past the mailbox" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); // A length far longer than the message it describes. Trusted, it would // swallow everything after it; the scan has to stop at the end of the file // whatever the header claims. try writeFile(tmp.dir, "mail.mbox", alice ++ "\nContent-Length: 999999\n\nfirst\n\n" ++ bob ++ "\nContent-Length: 7\n\nsecond\n\n"); var trusting = try Mailbox.open(tmp.dir, io, "mail.mbox", .{ .variant = .mboxcl2 }); defer trusting.close(io); const swallowed = try collect(&trusting); defer freeAll(swallowed); // One message, because the length said so -- and this is the cost of // trusting it, stated as a test rather than left to be discovered. try testing.expectEqual(@as(usize, 1), swallowed.len); // Told not to trust it, the scan finds both. var searching = try Mailbox.open(tmp.dir, io, "mail.mbox", .{ .variant = .mboxcl2, .trust_content_length = false, }); defer searching.close(io); const found = try collect(&searching); defer freeAll(found); try testing.expectEqual(@as(usize, 2), found.len); } test "every variant round trips a mailbox it wrote itself" { for ([_]mbox.Variant{ .mboxo, .mboxrd, .mboxcl, .mboxcl2 }) |v| { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{ .variant = v }); defer m.close(io); // No `From ` line in the body, so that even the variants whose // quoting cannot be undone are being asked a question they can answer. _ = try m.append(gpa, io, try From.parse(alice), "Subject: one\n\nfirst\n"); _ = try m.append(gpa, io, try From.parse(bob), "Subject: two\n\nsecond\n"); const got = try collect(&m); defer freeAll(got); try testing.expectEqual(@as(usize, 2), got.len); try testing.expectEqualStrings("Subject: one\n\nfirst\n", got[0]); try testing.expectEqualStrings("Subject: two\n\nsecond\n", got[1]); } } // -- damage ------------------------------------------------------------------ test "a file that does not begin with a postmark is refused" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", "this is not a mailbox at all\n"); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); var it = try m.iterate(gpa, io, &buffer); defer it.deinit(); try testing.expectError(error.NotAMailbox, it.next()); } test "a message past the cap is an error rather than an allocation" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); try writeFile(tmp.dir, "mail.mbox", alice ++ "\n\n" ++ &@as([4096]u8, @splat('x')) ++ "\n"); var m = try Mailbox.open(tmp.dir, io, "mail.mbox", .{ .max_message_bytes = 128 }); defer m.close(io); var it = try m.iterate(gpa, io, &buffer); defer it.deinit(); try testing.expectError(error.MessageTooLong, it.next()); } test "a mailbox larger than the read buffer is read in pieces" { var tmp = testing.tmpDir(.{ .iterate = true }); defer tmp.cleanup(); var m = try Mailbox.create(tmp.dir, io, "mail.mbox", .{}); defer m.close(io); const body = "Subject: bulk\n\n" ++ std.mem.asBytes(&@as([400][15]u8, @splat("a line of text\n".*))); for (0..8) |_| _ = try m.append(gpa, io, try From.parse(alice), body); // Deliberately smaller than one message, so that every message spans // several fills and the scanner's line handling is doing real work. var small: [Mailbox.min_buffer]u8 = undefined; var it = try m.iterate(gpa, io, &small); defer it.deinit(); var count: usize = 0; while (try it.next()) |entry| { try testing.expectEqualStrings(body, entry.bytes); count += 1; } try testing.expectEqual(@as(usize, 8), count); }