// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Writing a mailbox: putting messages onto any `Io.Writer`, one after //! another. //! //! The inverse of `Reader`, and deliberately the only place that knows what a //! mailbox looks like on the way out, so that the two cannot drift apart. What //! it writes, `Reader` reads back unchanged. //! //! # The one thing that is not reversible //! //! A message whose last line has no terminator gets one. An mbox is a file of //! lines: the empty line that separates one message from the next has to start //! at the beginning of a line, so a body that does not end in a newline would //! run into it. Every mbox writer does this and none of them can avoid it. //! //! Everything else survives. Line endings are taken from the message rather //! than imposed on it, so a CRLF message gets a CRLF postmark terminator and a //! CRLF separator, and a mailbox read and written back is the file that went //! in, byte for byte. const std = @import("std"); const Io = std.Io; const testing = std.testing; const From = @import("From.zig"); const variant = @import("variant.zig"); const Variant = variant.Variant; const Writer = @This(); pub const Options = struct { variant: Variant = .mboxrd, }; out: *Io.Writer, options: Options, pub fn init(out: *Io.Writer, options: Options) Writer { return .{ .out = out, .options = options }; } /// Writes one message: its postmark, its body as this variant stores it, and /// the empty line that ends it. /// /// The empty line goes after every message rather than between them, so that /// appending to a mailbox never has to know whether anything came before. pub fn append(self: *Writer, from: From, message: []const u8) Io.Writer.Error!void { // From the postmark, which is the one line whose terminator is known // exactly. `From.lineEnding` says why it is not asked of the message. const ending = from.lineEnding(); // Just the newline: a postmark out of a CRLF mailbox carries its carriage // return in its own fields, so `write` has already put it there. try from.write(self.out); try self.out.writeByte('\n'); if (self.options.variant.usesContentLength()) { try self.writeWithLength(message, ending); } else { try variant.writeQuoted(self.out, message, self.options.variant); } // The message's own last line, if it did not have one. Both paths write // the message's bytes last, so this is the same question for both. if (message.len > 0 and !endsWithNewline(message)) try self.out.writeAll(ending); try self.out.writeAll(ending); } /// The same message with a `Content-Length` header put at the top of its /// header block, for the two variants that are read by it. /// /// At the top rather than the bottom, which is not a matter of taste. Adding a /// header to the end means first making sure the block ends in a newline, and /// a block whose last line is a bare carriage return becomes an *empty* line /// when one is added — which ends the header block, so the length lands in the /// body, where the next read leaves it in the message. The message then grows /// a `Content-Length` line every time the mailbox is rewritten. Nothing has to /// be terminated to put a header first. /// /// Any length the message already carried is dropped rather than kept: it /// counted the body of whatever mailbox the message came out of, and a second /// one saying something different is how a reader ends up believing the wrong /// one. fn writeWithLength(self: *Writer, message: []const u8, ending: []const u8) Io.Writer.Error!void { const parts = split(message); // What the body will occupy once it is written, which is what the header // has to agree with: quoted if this variant quotes, and with the // terminator that is about to be added if it has none. var length = variant.quotedLen(parts.body, self.options.variant); if (parts.body.len > 0 and !endsWithNewline(parts.body)) length += ending.len; try self.out.print("{s}: {d}{s}", .{ variant.content_length_header, length, ending }); try self.writeHeadersWithoutLength(parts.headers); try self.out.writeAll(parts.blank); try variant.writeQuoted(self.out, parts.body, self.options.variant); } /// The header block, minus any `Content-Length` and the folded continuation /// lines belonging to it. fn writeHeadersWithoutLength(self: *Writer, headers: []const u8) Io.Writer.Error!void { var pos: usize = 0; var dropping = false; while (pos < headers.len) { const end = lineEnd(headers, pos); const line = headers[pos..end]; pos = end; if (isContinuation(line)) { // Part of whatever header came before it, and shares its fate. if (!dropping) try self.out.writeAll(line); continue; } dropping = isLengthHeader(line); if (!dropping) try self.out.writeAll(line); } } /// Where the header block ends and the body begins, and the empty line /// between them. const Parts = struct { /// The headers, including the terminator of the last one. headers: []const u8, /// The empty line ending the header block, as written, or empty if the /// message has no body at all. blank: []const u8, body: []const u8, }; fn split(message: []const u8) Parts { var pos: usize = 0; while (pos < message.len) { const end = lineEnd(message, pos); const line = message[pos..end]; if (isEmptyLine(line)) return .{ .headers = message[0..pos], .blank = line, .body = message[end..], }; pos = end; } return .{ .headers = message, .blank = "", .body = "" }; } fn lineEnd(bytes: []const u8, from: usize) usize { return if (std.mem.findScalarPos(u8, bytes, from, '\n')) |at| at + 1 else bytes.len; } fn isEmptyLine(line: []const u8) bool { return std.mem.eql(u8, line, "\n") or std.mem.eql(u8, line, "\r\n"); } fn isContinuation(line: []const u8) bool { return line.len > 0 and (line[0] == ' ' or line[0] == '\t'); } fn isLengthHeader(line: []const u8) bool { const header = variant.content_length_header; return line.len > header.len and std.ascii.eqlIgnoreCase(line[0..header.len], header) and line[header.len] == ':'; } fn endsWithNewline(message: []const u8) bool { return message.len > 0 and message[message.len - 1] == '\n'; } // -- tests ------------------------------------------------------------------- const postmark = "From alice Mon Jan 1 00:00:00 2024"; fn writeOne(buffer: []u8, message: []const u8, options: Options) ![]u8 { var w: Io.Writer = .fixed(buffer); var mbox: Writer = .init(&w, options); try mbox.append(try From.parse(postmark), message); return w.buffered(); } test "a message is its postmark, its body, and the empty line after it" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\nSubject: hi\n\nbody\n\n", try writeOne(&buffer, "Subject: hi\n\nbody\n", .{}), ); } test "a body line beginning From is quoted so that it cannot split its message" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\n\n>From the top\n\n", try writeOne(&buffer, "\nFrom the top\n", .{}), ); } test "a message with no trailing newline is given one" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\n\nno newline\n\n", try writeOne(&buffer, "\nno newline", .{}), ); } test "an empty message is a postmark and the line after it" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings(postmark ++ "\n\n", try writeOne(&buffer, "", .{})); } test "a body ending in a bare carriage return does not change the framing" { var buffer: [512]u8 = undefined; // Taken from the body, this would read as CRLF once the missing newline // had been added, and the framing would flip every rewrite. The postmark // is LF, so the framing is LF. try testing.expectEqualStrings( postmark ++ "\n\nbody\r\n\n", try writeOne(&buffer, "\nbody\r", .{}), ); } test "a CRLF mailbox keeps CRLF framing" { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); var mbox: Writer = .init(&w, .{}); // A postmark out of a CRLF mailbox, carriage return and all. try mbox.append(try From.parse(postmark ++ "\r"), "Subject: hi\r\n\r\nbody\r\n"); try testing.expectEqualStrings( postmark ++ "\r\nSubject: hi\r\n\r\nbody\r\n\r\n", w.buffered(), ); } test "the Content-Length variants say how long the body is" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\nContent-Length: 5\nSubject: hi\n\nbody\n\n", try writeOne(&buffer, "Subject: hi\n\nbody\n", .{ .variant = .mboxcl2 }), ); } test "the length counts the body as stored, quoting and all" { var buffer: [512]u8 = undefined; // mboxcl quotes, so the stored body is one byte longer than the message. try testing.expectEqualStrings( postmark ++ "\nContent-Length: 11\n\n>From here\n\n", try writeOne(&buffer, "\nFrom here\n", .{ .variant = .mboxcl }), ); } test "a length the message arrived with is replaced, not kept alongside" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\nContent-Length: 5\nSubject: hi\n\nbody\n\n", try writeOne( &buffer, "Content-Length: 99999\n\tand its continuation\nSubject: hi\n\nbody\n", .{ .variant = .mboxcl2 }, ), ); } test "a headers-only message under Content-Length has a body of nothing" { var buffer: [512]u8 = undefined; // No empty line after the header block, because the message being written // had none: the only empty line here is the one that ends the message. try testing.expectEqualStrings( postmark ++ "\nContent-Length: 0\nSubject: hi\n\n", try writeOne(&buffer, "Subject: hi\n", .{ .variant = .mboxcl2 }), ); } test "a header block ending in a bare carriage return does not gain a header a round" { var buffer: [512]u8 = undefined; // Terminating this block would turn its last line into an empty one, and // a length written after that would be body rather than header. try testing.expectEqualStrings( postmark ++ "\nContent-Length: 0\n\x8c\n\r\n\n", try writeOne(&buffer, "\x8c\n\r", .{ .variant = .mboxcl2 }), ); } test "a header block cut off mid-line does not swallow the length header" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\nContent-Length: 0\nSubject: truncated\n\n", try writeOne(&buffer, "Subject: truncated", .{ .variant = .mboxcl2 }), ); } test "a message with nothing in it survives the length variants" { var buffer: [512]u8 = undefined; try testing.expectEqualStrings( postmark ++ "\nContent-Length: 0\n\n", try writeOne(&buffer, "", .{ .variant = .mboxcl2 }), ); }