// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reading a mailbox: an iterator over the messages in one. //! //! It works over any `Io.Reader`, so the whole of the difficult part of this //! library — deciding where one message stops and the next starts — can be //! tested and fuzzed without a filesystem anywhere near it. `Mailbox` is the //! thin layer that points one of these at a file. //! //! # Where a message ends //! //! At the line before the next postmark, and a postmark is a line beginning //! `From ` that either starts the mailbox or follows an empty line. Both //! halves of that matter. Without the `From ` there is no boundary at all; //! without the empty line every body that quotes a mail header splits its own //! message in two. //! //! The empty line itself is framing rather than body: it is dropped on the way //! in and put back on the way out, which is what makes read-then-write return //! the bytes that went in. //! //! # What is not normalized //! //! Line endings. A mailbox written with CRLF is read with CRLF and written //! back with CRLF, down to the carriage return in the postmark's date. //! Turning a message into something canonical is zig-mime's business, on the //! bytes it is handed; doing it here would mean a mailbox that changed every //! time it was rewritten. //! //! The one exception is unavoidable and is the format's, not this library's: a //! message whose last line has no terminator gets one when it is written, //! because an mbox is a file of lines and a message that does not end in a //! newline would run into the blank line after it. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const mime = @import("mime"); const From = @import("From.zig"); const variant = @import("variant.zig"); const Variant = variant.Variant; const Reader = @This(); /// The smallest read buffer this can work with: enough to recognise a /// postmark, an empty line, and a `Content-Length` header in one piece. pub const min_buffer = 64; pub const Options = struct { variant: Variant = .mboxrd, /// The largest message this will assemble. /// /// There has to be one. A mailbox whose postmarks have been damaged — a /// truncated download, a transfer that ate the blank lines — is not a /// mailbox with a problem, it is one enormous message, and without a cap /// reading it is an attempt to put the whole file in memory at once. max_message_bytes: usize = 64 * 1024 * 1024, /// Whether a `Content-Length` header is allowed to say where the body /// ends, for the two variants that write one. /// /// It is on by default because `mboxcl2` is unreadable without it: that /// variant stores bodies exactly as written, so a body containing a line /// beginning `From ` has nothing marking it as body except the length. /// /// It is worth knowing what trusting it costs. A length longer than the /// message it describes makes the scanner walk past the next postmark and /// return two messages as one, which hides the second — and the length is /// a header, which is to say it is written by whoever sent the message. /// Turning this off makes the scanner ignore the header and search, which /// can never hide a message and can split one. For `mboxo` and `mboxrd`, /// which write no such header, this does nothing. trust_content_length: bool = true, }; pub const Error = error{ /// The mailbox does not begin with a postmark. /// /// An empty file is a valid empty mailbox and is not this. Anything else /// is either not an mbox or has lost its beginning, and both are worth /// saying out loud rather than quietly returning no messages. NotAMailbox, /// A message ran past `Options.max_message_bytes`. MessageTooLong, ReadFailed, } || Allocator.Error; /// One message, as the iterator hands it over. pub const Entry = struct { /// The postmark, borrowing from the same buffer as `bytes`. from: From, /// The message as RFC 5322: the quoting undone, and the framing — the /// postmark above it and the empty line below it — removed. bytes: []const u8, /// Where this message's postmark began, counted from the start of the /// mailbox. Together with the next message's offset it says exactly which /// bytes of the file this message was. offset: u64, /// Which message this is, counting from zero. index: usize, /// What was wrong with this message's framing, if anything. Always /// `.none` for a mailbox nothing has damaged; `check` reports the rest. damage: Damage = .none, pub const Damage = enum { none, /// A `Content-Length` was trusted and the message did not end where /// it said. The message returned is the one the search found, which /// may have swallowed the next. content_length_disagreed, }; /// Hands the bytes to zig-mime. /// /// zig-mime copies them, so the entry may be invalidated straight /// afterwards — and because its parse cannot fail any way except running /// out of memory, this is exactly as fallible as a filter predicate is /// allowed to be. pub fn parse( self: Entry, gpa: Allocator, options: mime.Message.ParseOptions, ) Allocator.Error!mime.Message { return mime.Message.parse(gpa, self.bytes, options); } /// The headers alone, for a predicate that need not pay for the body. pub fn headers(self: Entry, gpa: Allocator) Allocator.Error!mime.Headers { const end = headerBlockEnd(self.bytes); return mime.Headers.parse(gpa, self.bytes[0..end]); } }; gpa: Allocator, input: *Io.Reader, options: Options, /// The postmark of the message `next` is about to return. postmark: std.ArrayList(u8) = .empty, /// The postmark the scan ran into, which belongs to the message *after* the /// one being returned. /// /// Two buffers rather than one, because the scan finds the next message's /// postmark before it has finished with this one's, and `Entry.from` borrows /// from the buffer. Writing both into one slot hands every entry the /// following message's sender. pending: std.ArrayList(u8) = .empty, /// The body of the message being assembled. body: std.ArrayList(u8) = .empty, /// Where `postmark`'s line begins in the mailbox. postmark_offset: u64 = 0, /// Where `pending`'s line begins in the mailbox. pending_offset: u64 = 0, /// How many bytes have been taken from `input`. consumed: u64 = 0, /// An empty line that has been read but not yet decided about: it is either /// the last line of a body or the framing before the next postmark, and which /// one it is depends on the line after it. At most `"\r\n"`. held_buffer: [2]u8 = undefined, held_len: usize = 0, /// Whether the last chunk taken from `input` ended mid-line, which happens /// when a line is longer than the read buffer. A continuation cannot be a /// postmark or an empty line however it begins. mid_line: bool = false, started: bool = false, finished: bool = false, index: usize = 0, pub fn init(gpa: Allocator, input: *Io.Reader, options: Options) Reader { return .{ .gpa = gpa, .input = input, .options = options }; } pub fn deinit(self: *Reader) void { self.postmark.deinit(self.gpa); self.pending.deinit(self.gpa); self.body.deinit(self.gpa); self.* = undefined; } /// The next message, or null at the end of the mailbox. /// /// What it points at is valid until the next call — the same contract as /// `mime.Parser.next`, and for the same reason: the alternative is a copy of /// every message, and a mailbox is the place where that is least affordable. pub fn next(self: *Reader) Error!?Entry { if (self.finished and !self.started) return null; if (!self.started) { self.started = true; const line = try self.takeLine() orelse { // An empty file. A mailbox with no messages in it, which is a // perfectly ordinary thing for a mailbox to be. self.finished = true; return null; }; const bare = stripTerminator(line.bytes); if (line.continued or !From.isFromLine(bare)) return error.NotAMailbox; self.postmark.clearRetainingCapacity(); try self.postmark.appendSlice(self.gpa, bare); self.postmark_offset = 0; } else if (self.finished) { return null; } else { // The scan that ended the previous message left this one's postmark // in `pending`. Swapping rather than copying keeps both allocations. std.mem.swap(std.ArrayList(u8), &self.postmark, &self.pending); self.postmark_offset = self.pending_offset; } const offset = self.postmark_offset; self.body.clearRetainingCapacity(); self.held_len = 0; // Where the body proper starts, which is what a `Content-Length` counts // from: past the header block and the empty line ending it. var body_start: ?usize = null; var declared: ?u64 = null; var damage: Entry.Damage = .none; while (true) { const line = try self.takeLine() orelse { // The end of the mailbox ends the message. A held empty line is // the trailing framing every well-formed mailbox has, and goes // the way the framing before a postmark does. self.finished = true; break; }; const bare = stripTerminator(line.bytes); const starts_line = !line.continued; // Inside a body whose length was declared and is being believed, // nothing is a boundary. That is the whole of what the length buys, // and the whole of what it costs. const inside_declared = if (declared) |want| blk: { const start = body_start orelse break :blk false; break :blk self.bodyLen() - start < want; } else false; if (starts_line and !inside_declared and self.held_len > 0 and From.isFromLine(bare)) { // The held empty line was framing. This is the next message. if (declared != null and body_start != null and self.bodyLen() - body_start.? != declared.?) { damage = .content_length_disagreed; } self.pending.clearRetainingCapacity(); try self.pending.appendSlice(self.gpa, bare); self.pending_offset = self.consumed - line.bytes.len; break; } // Whatever it is, it is not the framing before a postmark, so the // held empty line was a body line after all. if (self.held_len > 0) { try self.appendBody(self.held_buffer[0..self.held_len]); self.held_len = 0; } if (starts_line and isEmptyLine(line.bytes)) { // The end of the header block, the first time it happens. if (body_start == null) body_start = self.body.items.len + line.bytes.len; // Held rather than appended: the line after it decides whether it // was a body line or the framing before the next message. @memcpy(self.held_buffer[0..line.bytes.len], line.bytes); self.held_len = line.bytes.len; continue; } if (starts_line and body_start == null and self.options.trust_content_length and self.options.variant.usesContentLength()) { if (contentLength(bare)) |n| declared = n; } try self.appendBody(line.bytes); } const stored = self.body.items; var bytes = variant.unquoteInPlace(stored, self.options.variant); // `Content-Length` describes the mailbox, not the message: `Writer` puts // it in on the way down and this takes it back out, so that a message // does not collect one more header every time it is stored. if (self.options.variant.usesContentLength()) bytes = stripLength(bytes); const from = From.parse(self.postmarkLine()) catch unreachable; const entry: Entry = .{ .from = from, .bytes = bytes, .offset = offset, .index = self.index, .damage = damage, }; self.index += 1; return entry; } /// The body assembled so far, counting the empty line that is being held /// because it has not yet been decided about. fn bodyLen(self: *const Reader) usize { return self.body.items.len + self.held_len; } fn appendBody(self: *Reader, bytes: []const u8) Error!void { if (self.body.items.len + bytes.len > self.options.max_message_bytes) { return error.MessageTooLong; } try self.body.appendSlice(self.gpa, bytes); } /// The postmark as `From.parse` wants it: the line, without a terminator. /// /// `next` only ever puts a line here that `From.isFromLine` accepted, which is /// the whole of what `From.parse` requires, so the parse below it cannot fail. fn postmarkLine(self: *const Reader) []const u8 { return self.postmark.items; } /// A chunk taken from the input: a whole line, or as much of one as the read /// buffer could hold. const Line = struct { bytes: []const u8, /// Whether this continues a line that began in an earlier chunk, in which /// case nothing about its first bytes means anything. continued: bool, }; /// The next line, or as much of one as fits, or null at the end of the input. fn takeLine(self: *Reader) Error!?Line { const continued = self.mid_line; if (self.input.takeDelimiterInclusive('\n')) |line| { self.consumed += line.len; self.mid_line = false; return .{ .bytes = line, .continued = continued }; } else |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.EndOfStream => { // The input ended without a newline. Whatever is left in the // buffer is the last line, and an empty remainder is the end. const rest = self.input.buffered(); if (rest.len == 0) return null; self.input.toss(rest.len); self.consumed += rest.len; self.mid_line = false; return .{ .bytes = rest, .continued = continued }; }, error.StreamTooLong => { // A line longer than the read buffer. Hand back what there is and // remember that the next chunk continues it, because a // continuation that happens to begin `From ` is not a boundary. const chunk = self.input.buffered(); std.debug.assert(chunk.len > 0); self.input.toss(chunk.len); self.consumed += chunk.len; self.mid_line = true; return .{ .bytes = chunk, .continued = continued }; }, } } /// A line with its newline taken off, and nothing else. /// /// A carriage return before it is left in place deliberately. It is what tells /// `Writer` that this mailbox uses CRLF, and putting the line back together is /// then a matter of adding the newline that was removed -- so a postmark comes /// back exactly as it was written, however many carriage returns it had. /// Trimming it here instead would cost one of them per rewrite. fn stripTerminator(line: []const u8) []const u8 { if (line.len > 0 and line[line.len - 1] == '\n') return line[0 .. line.len - 1]; return line; } /// Whether a line is the empty one that frames a message. A line of spaces is /// not empty: it is a body line that happens to look like one. fn isEmptyLine(line: []const u8) bool { return std.mem.eql(u8, line, "\n") or std.mem.eql(u8, line, "\r\n"); } /// The value of a `Content-Length` header line, if this is one. fn contentLength(line: []const u8) ?u64 { const header = variant.content_length_header; if (line.len <= header.len) return null; if (!std.ascii.eqlIgnoreCase(line[0..header.len], header)) return null; if (line[header.len] != ':') return null; // The carriage return as well as the spaces: in a CRLF mailbox it is the // last byte of the value, and `parseInt` refuses it, so without this the // length is silently never believed in exactly the mailboxes that are // most likely to be carrying one. const value = std.mem.trim(u8, line[header.len + 1 ..], " \t\r"); // A length that does not fit a `u64`, or is not a number at all, is not a // length. Rejecting it here is what keeps the narrowing below honest. return std.fmt.parseInt(u64, value, 10) catch null; } /// Removes the `Content-Length` header `Writer` puts at the top of a message, /// in place, because it only ever shortens. /// /// Exactly one line, and only the first, because that is exactly what was /// injected. Dropping more would be guessing: a line beginning with a space or /// a tab after it is a continuation of *something*, and if the message's own /// first line happened to be one it would be folded into this header and lost. /// A `Content-Length` further down was not put there by this library, so it is /// left where it is and treated as part of the message — the next rewrite /// replaces it with an accurate one at the top, and from then on the message /// comes back unchanged. fn stripLength(message: []u8) []u8 { const header = variant.content_length_header; const end = if (std.mem.findScalar(u8, message, '\n')) |at| at + 1 else message.len; const line = message[0..end]; if (line.len <= header.len) return message; if (!std.ascii.eqlIgnoreCase(line[0..header.len], header)) return message; if (line[header.len] != ':') return message; std.mem.copyForwards(u8, message, message[end..]); return message[0 .. message.len - end]; } /// Where a message's header block ends: the first empty line, or the whole /// message if it has no body. fn headerBlockEnd(message: []const u8) usize { if (std.mem.indexOf(u8, message, "\n\n")) |at| return at + 1; if (std.mem.indexOf(u8, message, "\r\n\r\n")) |at| return at + 2; return message.len; } // -- tests ------------------------------------------------------------------- const Collected = struct { messages: [][]u8, froms: [][]u8, offsets: []u64, fn deinit(self: *Collected, gpa: Allocator) void { for (self.messages) |m| gpa.free(m); for (self.froms) |f| gpa.free(f); gpa.free(self.messages); gpa.free(self.froms); gpa.free(self.offsets); } }; fn collect(gpa: Allocator, source: []const u8, options: Options) !Collected { var input: Io.Reader = .fixed(source); var reader: Reader = .init(gpa, &input, options); defer reader.deinit(); var messages: std.ArrayList([]u8) = .empty; errdefer messages.deinit(gpa); var froms: std.ArrayList([]u8) = .empty; errdefer froms.deinit(gpa); var offsets: std.ArrayList(u64) = .empty; errdefer offsets.deinit(gpa); while (try reader.next()) |entry| { try messages.append(gpa, try gpa.dupe(u8, entry.bytes)); try froms.append(gpa, try gpa.dupe(u8, entry.from.address)); try offsets.append(gpa, entry.offset); } return .{ .messages = try messages.toOwnedSlice(gpa), .froms = try froms.toOwnedSlice(gpa), .offsets = try offsets.toOwnedSlice(gpa), }; } test "an empty file is a mailbox with no messages" { var got = try collect(testing.allocator, "", .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 0), got.messages.len); } test "anything that does not begin with a postmark is not a mailbox" { try testing.expectError(error.NotAMailbox, collect(testing.allocator, "hello\n", .{})); try testing.expectError(error.NotAMailbox, collect(testing.allocator, "\nFrom a b\n", .{})); try testing.expectError(error.NotAMailbox, collect(testing.allocator, ">From a b\n", .{})); } test "two messages, and the empty line between them is framing" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "Subject: one\n" ++ "\n" ++ "first\n" ++ "\n" ++ "From bob Tue Jan 2 00:00:00 2024\n" ++ "Subject: two\n" ++ "\n" ++ "second\n"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), got.messages.len); try testing.expectEqualStrings("Subject: one\n\nfirst\n", got.messages[0]); try testing.expectEqualStrings("Subject: two\n\nsecond\n", got.messages[1]); try testing.expectEqualStrings("alice", got.froms[0]); try testing.expectEqualStrings("bob", got.froms[1]); try testing.expectEqual(@as(u64, 0), got.offsets[0]); try testing.expectEqual( @as(u64, "From alice Mon Jan 1 00:00:00 2024\nSubject: one\n\nfirst\n\n".len), got.offsets[1], ); } test "a postmark not preceded by an empty line is body, not a boundary" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "\n" ++ "quoting a header:\n" ++ "From bob Tue Jan 2 00:00:00 2024\n" ++ "is what somebody wrote\n"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 1), got.messages.len); } test "a body line beginning From is unquoted on the way out" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "\n" ++ ">From the top\n" ++ ">>From below that\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxrd }); defer got.deinit(testing.allocator); try testing.expectEqualStrings("\nFrom the top\n>From below that\n", got.messages[0]); } test "several empty lines in a row keep all but the last" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "\n" ++ "body\n" ++ "\n" ++ "\n" ++ "\n" ++ "From bob Tue Jan 2 00:00:00 2024\n" ++ "\n" ++ "next\n"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), got.messages.len); try testing.expectEqualStrings("\nbody\n\n\n", got.messages[0]); } test "a mailbox with CRLF line endings keeps them" { const source = "From alice Mon Jan 1 00:00:00 2024\r\n" ++ "Subject: one\r\n" ++ "\r\n" ++ "first\r\n" ++ "\r\n" ++ "From bob Tue Jan 2 00:00:00 2024\r\n" ++ "\r\n" ++ "second\r\n"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), got.messages.len); try testing.expectEqualStrings("Subject: one\r\n\r\nfirst\r\n", got.messages[0]); } test "a message whose last line has no terminator is still a message" { const source = "From alice Mon Jan 1 00:00:00 2024\n\nno newline at the end"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqualStrings("\nno newline at the end", got.messages[0]); } test "a message with no body at all" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "\n" ++ "From bob Tue Jan 2 00:00:00 2024\n" ++ "\n" ++ "second\n"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), got.messages.len); try testing.expectEqualStrings("", got.messages[0]); } test "a trusted Content-Length carries the scanner over an unquoted boundary" { const body = "From nowhere, in the body\n"; const source = std.fmt.comptimePrint( "From alice Mon Jan 1 00:00:00 2024\n" ++ "Content-Length: {d}\n" ++ "\n" ++ "{s}" ++ "\n" ++ "From bob Tue Jan 2 00:00:00 2024\n" ++ "\n" ++ "second\n", .{ body.len, body }, ); var trusted = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer trusted.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), trusted.messages.len); // Without the length, the body's own `From ` line is a boundary -- it // follows an empty line -- and the one message becomes three. var searched = try collect(testing.allocator, source, .{ .variant = .mboxcl2, .trust_content_length = false, }); defer searched.deinit(testing.allocator); try testing.expectEqual(@as(usize, 3), searched.messages.len); } test "a Content-Length in a CRLF mailbox is still a length" { const body = "From nowhere, in the body\r\n"; const source = std.fmt.comptimePrint( "From alice Mon Jan 1 00:00:00 2024\r\n" ++ "Content-Length: {d}\r\n" ++ "\r\n" ++ "{s}" ++ "\r\n" ++ "From bob Tue Jan 2 00:00:00 2024\r\n" ++ "\r\n" ++ "second\r\n", .{ body.len, body }, ); var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); // Two, not three: the length carried the scan over the body's own // `From ` line, which is the whole reason the header is there. try testing.expectEqual(@as(usize, 2), got.messages.len); try testing.expectEqualStrings("\r\n" ++ body, got.messages[0]); } test "a Content-Length that is not a number is not a length" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "Content-Length: banana\n" ++ "\n" ++ "body\n" ++ "\n" ++ "From bob Tue Jan 2 00:00:00 2024\n" ++ "\n" ++ "second\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 2), got.messages.len); } test "a message longer than the cap is an error rather than an allocation" { const source = "From alice Mon Jan 1 00:00:00 2024\n\n" ++ ("x" ** 200 ++ "\n"); try testing.expectError(error.MessageTooLong, collect(testing.allocator, source, .{ .max_message_bytes = 64, })); } test "a line longer than the read buffer is body, not a boundary" { const long = "From " ++ ("x" ** 300); const source = "From alice Mon Jan 1 00:00:00 2024\n\nbody\n" ++ long ++ "\n"; // A small buffer, so the long line arrives in several chunks. var input: Io.Reader = .fixed(source); var reader: Reader = .init(testing.allocator, &input, .{}); defer reader.deinit(); var count: usize = 0; while (try reader.next()) |_| count += 1; try testing.expectEqual(@as(usize, 1), count); } test "offsets say exactly which bytes of the file each message was" { const source = "From alice Mon Jan 1 00:00:00 2024\n\none\n\n" ++ "From bob Tue Jan 2 00:00:00 2024\n\ntwo\n\n" ++ "From carol Wed Jan 3 00:00:00 2024\n\nthree\n"; var got = try collect(testing.allocator, source, .{}); defer got.deinit(testing.allocator); try testing.expectEqual(@as(usize, 3), got.offsets.len); for (got.offsets) |at| try testing.expect(From.isFromLine(source[at..])); try testing.expect(got.offsets[0] < got.offsets[1]); try testing.expect(got.offsets[1] < got.offsets[2]); } test "the length header is framing, so it does not come back with the message" { // As this library writes it: at the top, where it can be taken off again // without guessing. const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "Content-Length: 5\n" ++ "Subject: one\n" ++ "X-Other: kept\n" ++ "\n" ++ "body\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); try testing.expectEqualStrings("Subject: one\nX-Other: kept\n\nbody\n", got.messages[0]); // Under a variant that does not use the header, it is an ordinary header // somebody sent and is left exactly where it was. var plain = try collect(testing.allocator, source, .{ .variant = .mboxrd }); defer plain.deinit(testing.allocator); try testing.expect(std.mem.indexOf(u8, plain.messages[0], "Content-Length") != null); } test "a length another tool wrote further down is left in the message" { // Not this library's framing, so not this library's to remove: guessing // would mean taking a header the sender may have written. A rewrite // replaces it with an accurate one at the top, after which the message // comes back unchanged. const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "Subject: one\n" ++ "Content-Length: 5\n" ++ "\n" ++ "body\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); try testing.expectEqualStrings("Subject: one\nContent-Length: 5\n\nbody\n", got.messages[0]); } test "a message whose first line is a continuation keeps it" { // A folded line with nothing above it is malformed, but it is the // message's, and a header taken off the top must not take it along. const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "Content-Length: 0\n" ++ "\tan orphaned continuation\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); try testing.expectEqualStrings("\tan orphaned continuation\n", got.messages[0]); } test "a body line that reads like the length header is body" { const source = "From alice Mon Jan 1 00:00:00 2024\n" ++ "Subject: one\n" ++ "\n" ++ "Content-Length: 99\n" ++ "is something somebody wrote\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); try testing.expectEqualStrings( "Subject: one\n\nContent-Length: 99\nis something somebody wrote\n", got.messages[0], ); } test "a message that is nothing but a length header comes back empty" { const source = "From alice Mon Jan 1 00:00:00 2024\nContent-Length: 0\n"; var got = try collect(testing.allocator, source, .{ .variant = .mboxcl2 }); defer got.deinit(testing.allocator); try testing.expectEqualStrings("", got.messages[0]); }