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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The postmark: the `From ` line in front of every message in a mailbox.//!//! It is the one line in an mbox that is not RFC 5322, it is the only thing//! separating one message from the next, and it is not specified anywhere.//! What it holds is the *envelope* sender and the time of delivery — neither//! of which need agree with the `From:` header, and the difference is the//! whole point: the header says who wrote the message and the postmark says//! who handed it over, which is what a bounce goes back to.//!//! Nothing here allocates, and nothing here normalizes. Every field borrows//! from the line it was parsed out of, a trailing carriage return included, so//! that a mailbox written with CRLF postmarks can be read and written back//! byte for byte.
const std = @import("std");const Io = std.Io;const testing = std.testing;
const mime = @import("mime");const DateTime = mime.datetime.DateTime;
const From = @This();
/// The prefix that makes a line a postmark. The trailing space is part of it:/// a line reading `Fromage` is not a boundary, and neither is `From` alone.pub const prefix = "From ";
/// The envelope sender, as written.////// May be empty. A deliverer with no return path to record — a bounce, most/// often — writes either `MAILER-DAEMON` or nothing at all, and nothing at all/// gives a postmark with two spaces after `From`.address: []const u8,
/// The timestamp, as written and undecoded, in the `asctime` form/// `Mon Jan 1 00:00:00 2024`. Ask `timestamp` for it decoded.////// Undecoded because a great many mailboxes carry a date this cannot read, and/// a postmark whose date is strange is still a perfectly good boundary. Losing/// the message because the clock that stamped it was odd would be the wrong/// trade.date: []const u8,
/// Whatever followed the timestamp, without its leading space, which is/// almost always nothing.////// Deliverers of a certain age wrote ` remote from <host>` here, and that is/// the only form recognised: anything else stays part of `date`, because/// guessing where a date ends is how a postmark gets silently truncated.trailer: []const u8,
/// The trailer that UUCP-era deliverers appended, with its leading space.const remote_from = " remote from ";
pub const ParseError = error{ /// The line does not begin `From `. NotAFromLine,};
/// Whether `line` is a postmark. The test the scanner uses.////// Deliberately the loosest test that is still a test, because the scanner's/// two failure modes are not equally bad. Splitting one message in two leaves/// both halves on disk and visible; merging two into one hides the second/// entirely. A reader that demanded a parseable date would do exactly that to/// every mailbox written by something whose clock it could not read — and/// there are a lot of those.pub fn isFromLine(line: []const u8) bool { return std.mem.startsWith(u8, line, prefix);}
/// Splits a postmark into its parts. `line` must not include its newline; a/// trailing carriage return is part of the line and is kept, so that `write`/// reproduces it and a CRLF mailbox survives being rewritten.pub fn parse(line: []const u8) ParseError!From { if (!isFromLine(line)) return error.NotAFromLine; const rest = line[prefix.len..];
// Exactly one space is consumed after the address, so that `write` can put // exactly one back and reproduce the line. const space = std.mem.findScalar(u8, rest, ' ') orelse return .{ .address = rest, .date = "", .trailer = "", }; const after = rest[space + 1 ..];
if (std.mem.indexOf(u8, after, remote_from)) |at| return .{ .address = rest[0..space], .date = after[0..at], .trailer = after[at + 1 ..], }; return .{ .address = rest[0..space], .date = after, .trailer = "" };}
/// The timestamp, decoded, or null if it could not be understood.////// The weekday is thrown away rather than checked. It is redundant — the date/// already says which day it was — and it is wrong often enough in real/// mailboxes that checking it would cost the timestamp on messages whose date/// is perfectly good. The month, day, hour, minute and second are all/// range-checked by the parser before they are narrowed, which is the whole/// reason this goes through it rather than reading the digits itself: `99` in/// the day field must be a rejection, not a panic.pub fn timestamp(self: From) ?DateTime { const date = std.mem.trim(u8, self.date, " \t\r\n");
// Past the weekday, which is what `asctime` leads with. if (std.mem.findScalar(u8, date, ' ')) |space| { if (DateTime.parse(asctime, date[space + 1 ..])) |parsed| { return parsed.value; } else |_| {} } // A postmark with no weekday at all, which some deliverers write. const parsed = DateTime.parse(asctime, date) catch return null; return parsed.value;}
/// `asctime` without its weekday, plus the numeric zone that is not part of/// `asctime` but is written by enough deliverers to be worth reading. `ZZ`/// steps over a zone it cannot read — `PST` and the like — rather than/// failing, which leaves the fields as the wall-clock reading they are.const asctime = "MMM D HH:mm:ss YYYY ZZ";
/// Writes the postmark, without a terminator.pub fn write(self: From, w: *Io.Writer) Io.Writer.Error!void { try w.writeAll(prefix); try w.writeAll(self.address); if (self.date.len > 0 or self.trailer.len > 0) { try w.writeByte(' '); try w.writeAll(self.date); } if (self.trailer.len > 0) { try w.writeByte(' '); try w.writeAll(self.trailer); }}
pub fn format(self: From, w: *Io.Writer) Io.Writer.Error!void { return self.write(w);}
/// The line ending the mailbox this postmark came from uses.////// The postmark is the one line whose terminator is known exactly: the/// scanner takes off the newline and leaves the carriage return, so a/// postmark that still ends in one came out of a CRLF mailbox.////// This is why the answer is asked of the postmark rather than of the message/// under it. A body does not reliably say: a message whose last line ends in a/// bare carriage return is given a newline when it is written, which turns/// that line into a CRLF one, and a writer looking at the body would see a/// different answer every time the mailbox was rewritten and never settle.pub fn lineEnding(self: From) []const u8 { const last: u8 = if (self.trailer.len > 0) self.trailer[self.trailer.len - 1] else if (self.date.len > 0) self.date[self.date.len - 1] else if (self.address.len > 0) self.address[self.address.len - 1] else prefix[prefix.len - 1]; return if (last == '\r') "\r\n" else "\n";}
/// The widest postmark `writeLine` produces for a plausible year, which is/// what a caller wanting a stack buffer should size it by.pub const max_date_bytes = "Mon Jan 1 00:00:00 -2147483648".len;
/// Composes a postmark, in the `asctime` form every reader understands.////// The weekday is recomputed from the date rather than taken from `when`,/// because a `DateTime` assembled field by field carries whatever weekday it/// was given and a postmark claiming the wrong day is the thing this library/// forgives in others and should not commit itself. The month and day names/// are the C locale's, which is not a default but a requirement: `asctime`/// is defined in terms of them, and a postmark in French is a postmark no/// other reader can date.pub fn writeLine(w: *Io.Writer, address: []const u8, when: DateTime) Io.Writer.Error!void { try w.writeAll(prefix); try w.writeAll(address); try w.print(" {s} {s} {d: >2} {d:0>2}:{d:0>2}:{d:0>2} ", .{ @tagName(when.asDate().dayOfWeek()), @tagName(when.month), when.day, when.hour, when.minute, when.second, }); // Four digits, padded. An `asctime` year is always four wide, and a year // written as `24` is read back as 2024 by anything that takes a two-digit // year to mean this century -- which is most things, `timestamp` above // included. The cast is after the range check rather than before it, // because that is the only order in which it cannot panic. if (when.year >= 0 and when.year <= 9999) { try w.print("{d:0>4}", .{@as(u16, @intCast(when.year))}); } else { // Outside what `asctime` has room for. Written plainly, and not // claimed to be a date any other reader will accept. try w.print("{d}", .{when.year}); }}
// -- tests -------------------------------------------------------------------
test "a postmark splits into sender and date" { const f = try From.parse("From jeff@example.com Mon Jan 1 00:00:00 2024"); try testing.expectEqualStrings("jeff@example.com", f.address); try testing.expectEqualStrings("Mon Jan 1 00:00:00 2024", f.date); try testing.expectEqualStrings("", f.trailer);}
test "a bounce with no return path has an empty sender" { const f = try From.parse("From Mon Jan 1 00:00:00 2024"); try testing.expectEqualStrings("", f.address); try testing.expectEqualStrings("Mon Jan 1 00:00:00 2024", f.date);}
test "the UUCP trailer is kept out of the date" { const f = try From.parse("From jeff Mon Jan 1 00:00:00 2024 remote from ihnp4"); try testing.expectEqualStrings("Mon Jan 1 00:00:00 2024", f.date); try testing.expectEqualStrings("remote from ihnp4", f.trailer); try testing.expect(f.timestamp() != null);}
test "what is not a postmark" { try testing.expect(!isFromLine("Fromage is not a boundary")); try testing.expect(!isFromLine("From")); try testing.expect(!isFromLine(">From quoted")); try testing.expect(!isFromLine("")); try testing.expectError(error.NotAFromLine, From.parse("X-From: no"));}
test "a wrong weekday does not cost the timestamp" { // 1999-12-31 was a Friday. The postmark says Thursday, and is believed // about everything except the part it cannot be wrong about. const f = try From.parse("From jeff Thu Dec 31 23:59:59 1999"); const when = f.timestamp().?; try testing.expectEqual(@as(i32, 1999), when.year); try testing.expectEqual(@as(u6, 31), when.day); try testing.expectEqual(@as(u6, 59), when.second);}
test "an impossible date is no date rather than a panic" { // Every one of these would be a `@intCast` panic in a parser that // narrowed the digits before checking their range. for ([_][]const u8{ "From jeff Mon Jan 99 00:00:00 2024", "From jeff Mon Jan 1 25:00:00 2024", "From jeff Mon Jan 1 00:99:00 2024", "From jeff Mon Feb 30 00:00:00 2023", "From jeff not a date at all", "From jeff", "From ", }) |line| { const f = try From.parse(line); try testing.expect(f.timestamp() == null); }}
test "a leap day is a date" { const f = try From.parse("From jeff Thu Feb 29 12:00:00 2024"); try testing.expectEqual(@as(u6, 29), f.timestamp().?.day);}
test "a numeric zone is read, and an alphabetic one stepped over" { const numeric = try From.parse("From jeff Mon Jan 1 00:00:00 2024 -0600"); try testing.expectEqual(@as(i32, -6 * 60 * 60), numeric.timestamp().?.offset); const named = try From.parse("From jeff Mon Jan 1 00:00:00 2024 PST"); try testing.expectEqual(@as(i32, 0), named.timestamp().?.offset);}
test "a postmark says which line ending its mailbox used" { try testing.expectEqualStrings("\n", (try From.parse("From a Mon Jan 1 00:00:00 2024")).lineEnding()); try testing.expectEqualStrings("\r\n", (try From.parse("From a Mon Jan 1 00:00:00 2024\r")).lineEnding()); try testing.expectEqualStrings("\r\n", (try From.parse("From a b remote from host\r")).lineEnding()); try testing.expectEqualStrings("\r\n", (try From.parse("From a\r")).lineEnding()); try testing.expectEqualStrings("\n", (try From.parse("From ")).lineEnding());}
test "writing a postmark reproduces the line it was parsed from" { for ([_][]const u8{ "From jeff@example.com Mon Jan 1 00:00:00 2024", "From Mon Jan 1 00:00:00 2024", "From jeff Mon Jan 1 00:00:00 2024 remote from ihnp4", // A mailbox written with CRLF: the carriage return is part of the // date, so it survives the round trip. So does a second one, which is // how a postmark that was already odd stays exactly as odd. "From jeff Mon Jan 1 00:00:00 2024\r", "From jeff Mon Jan 1 00:00:00 2024\r\r", "From jeff", }) |line| { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try (try From.parse(line)).write(&w); try testing.expectEqualStrings(line, w.buffered()); }}
test "a composed postmark carries the weekday the date actually fell on" { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); // Claims Sunday; 2024-01-01 was a Monday. try writeLine(&w, "jeff@example.com", .{ .year = 2024, .month = .Jan, .day = 1, .hour = 9, .minute = 5, .second = 3, .weekday = .Sun, }); try testing.expectEqualStrings( "From jeff@example.com Mon Jan 1 09:05:03 2024", w.buffered(), ); try testing.expect(w.buffered().len <= prefix.len + "jeff@example.com".len + 1 + max_date_bytes);}
test "a year is written four digits wide, as asctime has it" { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeLine(&w, "jeff", .{ .year = 24, .month = .Jan, .day = 1 }); try testing.expectEqualStrings("From jeff Mon Jan 1 00:00:00 0024", w.buffered()); // And reads back as the year it was, rather than as this century. try testing.expectEqual(@as(i32, 24), (try From.parse(w.buffered())).timestamp().?.year);}
test "a composed postmark parses back to the time that went in" { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); const when: DateTime = .{ .year = 2006, .month = .Jul, .day = 4, .hour = 12, .minute = 30, .second = 5 }; try writeLine(&w, "jeff", when); const back = (try From.parse(w.buffered())).timestamp().?; try testing.expectEqual(when.year, back.year); try testing.expectEqual(when.month, back.month); try testing.expectEqual(when.day, back.day); try testing.expectEqual(when.hour, back.hour); try testing.expectEqual(when.minute, back.minute); try testing.expectEqual(when.second, back.second);}