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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `zig-mbox`, a command-line tool over the library.//!//! It exists to show what the library looks like from outside, and to be//! something the interoperability test can point at the same mailbox//! `formail` and Python are reading — a claim about interoperating needs two//! programs, and this is the second one.//!//! `check` is the one that earns its keep beyond that. An mbox has no way to//! say it is damaged, so the damage has to be looked for, and it is always the//! same three things: a file that does not begin with a postmark, a//! `Content-Length` that does not agree with where the next postmark is, and a//! body line that a reader might split on.
const std = @import("std");const Io = std.Io;const Dir = Io.Dir;const Allocator = std.mem.Allocator;
const mime = @import("mime");const mbox = @import("mbox");const Mailbox = mbox.Mailbox;const From = mbox.From;const Variant = mbox.Variant;
const usage = \\usage: zig-mbox <command> <mailbox> [arguments] \\ \\ list <mailbox> every message: number, sender, date, subject \\ get <mailbox> <n> one message, as RFC 5322, to stdout \\ append <mailbox> [file] add a message; `-` or nothing is stdin \\ filter <mailbox> <header> <text> remove messages whose header contains text \\ check <mailbox> report damage, changing nothing \\ \\ --variant <name> mboxo, mboxrd (default), mboxcl or mboxcl2 \\ --no-lock do not take an advisory lock on the mailbox \\ --sender <address> the envelope sender `append` writes into the postmark \\ \\Messages are numbered from 1, as `list` prints them. \\;
/// The largest message `append` will read from a file or a pipe.const read_limit: Io.Limit = .limited(64 * 1024 * 1024);
const Options = struct { variant: Variant = .mboxrd, lock: bool = true, sender: []const u8 = "zig-mbox",
fn mailbox(self: Options) Mailbox.Options { return .{ .variant = self.variant, .lock = self.lock }; }};
pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa;
var stdout_buffer: [64 * 1024]u8 = undefined; var stdout = Io.File.stdout().writer(io, &stdout_buffer); const out = &stdout.interface;
var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip();
var options: Options = .{}; var positional: [4][]const u8 = undefined; var count: usize = 0;
while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--variant")) { const name = args.next() orelse return error.MissingVariant; options.variant = parseVariant(name) orelse return error.UnknownVariant; } else if (std.mem.eql(u8, arg, "--no-lock")) { options.lock = false; } else if (std.mem.eql(u8, arg, "--sender")) { options.sender = args.next() orelse return error.MissingSender; } else if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { try out.writeAll(usage); try out.flush(); return; } else { if (count == positional.len) return error.TooManyArguments; positional[count] = arg; count += 1; } }
if (count < 2) { try out.writeAll(usage); try out.flush(); return error.MissingArguments; }
const command = positional[0]; const path = positional[1]; const rest = positional[2..count]; const cwd: Dir = .cwd();
if (std.mem.eql(u8, command, "list")) { try list(gpa, io, out, cwd, path, options); } else if (std.mem.eql(u8, command, "get")) { if (rest.len < 1) return error.MissingNumber; try get(gpa, io, out, cwd, path, options, try std.fmt.parseInt(usize, rest[0], 10)); } else if (std.mem.eql(u8, command, "append")) { try append(gpa, io, out, cwd, path, options, if (rest.len > 0) rest[0] else "-"); } else if (std.mem.eql(u8, command, "filter")) { if (rest.len < 2) return error.MissingPattern; try filter(gpa, io, out, cwd, path, options, rest[0], rest[1]); } else if (std.mem.eql(u8, command, "check")) { try check(gpa, io, out, cwd, path, options); } else { try out.writeAll(usage); try out.flush(); return error.UnknownCommand; } try out.flush();}
fn parseVariant(name: []const u8) ?Variant { return std.meta.stringToEnum(Variant, name);}
/// A read buffer. Its size is the whole of the throughput, and a mailbox is/// the place where that shows.var buffer: [256 * 1024]u8 = undefined;
fn list( gpa: Allocator, io: Io, out: *Io.Writer, cwd: Dir, path: []const u8, options: Options,) !void { var m = try Mailbox.open(cwd, io, path, options.mailbox()); defer m.close(io);
var it = try m.iterate(gpa, io, &buffer); defer it.deinit();
while (try it.next()) |entry| { var headers = try entry.headers(gpa); defer headers.deinit(); const subject = (try headers.getUtf8("Subject")) orelse "(no subject)";
try out.print("{d: >4} {s: <30} ", .{ entry.index + 1, entry.from.address }); if (entry.from.timestamp()) |when| { // Narrowed after the range check, never before it: `Year` is an // `i32` and a zero-padded signed integer prints its sign. if (when.year >= 0 and when.year <= 9999) { try out.print("{d:0>4}-", .{@as(u16, @intCast(when.year))}); } else { try out.print("{d}-", .{when.year}); } try out.print("{d:0>2}-{d:0>2} ", .{ when.month.as(u8), when.day }); } else { try out.writeAll(" ? "); } try out.print("{s}\n", .{std.mem.trim(u8, subject, " \t\r\n")}); }}
fn get( gpa: Allocator, io: Io, out: *Io.Writer, cwd: Dir, path: []const u8, options: Options, number: usize,) !void { if (number == 0) return error.NoSuchMessage; var m = try Mailbox.open(cwd, io, path, options.mailbox()); defer m.close(io);
var it = try m.iterate(gpa, io, &buffer); defer it.deinit();
while (try it.next()) |entry| { if (entry.index + 1 != number) continue; try out.writeAll(entry.bytes); return; } return error.NoSuchMessage;}
fn append( gpa: Allocator, io: Io, out: *Io.Writer, cwd: Dir, path: []const u8, options: Options, source: []const u8,) !void { const message = if (std.mem.eql(u8, source, "-")) blk: { var stdin_buffer: [64 * 1024]u8 = undefined; var stdin = Io.File.stdin().reader(io, &stdin_buffer); break :blk try stdin.interface.allocRemaining(gpa, read_limit); } else try cwd.readFileAlloc(io, source, gpa, read_limit); defer gpa.free(message);
var m = try Mailbox.create(cwd, io, path, options.mailbox()); defer m.close(io);
// The postmark records delivery, which is now: the `Date:` header says // when the message was written, and the two are not the same claim. var w: Io.Writer.Allocating = .init(gpa); defer w.deinit(); try From.writeLine(&w.writer, options.sender, now(io));
const stats = try m.append(gpa, io, try From.parse(w.writer.buffered()), message); try out.print("appended; {d} messages\n", .{stats.kept});}
/// The time, as a postmark records it: UTC, because `asctime` carries no zone/// and a postmark in local time is one nobody else can place.fn now(io: Io) mime.datetime.DateTime { const stamp = Io.Timestamp.now(io, .real); const instant: mime.datetime.Instant = .fromNanoTimeStamp(stamp.nanoseconds); return instant.asDateTime();}
/// What `filter` is looking for, and what it found.const Pattern = struct { gpa: Allocator, header: []const u8, text: []const u8,};
fn drop(pattern: *Pattern, entry: mbox.Reader.Entry) Allocator.Error!bool { var headers = try entry.headers(pattern.gpa); defer headers.deinit(); const value = (try headers.getUtf8(pattern.header)) orelse return true; return std.mem.indexOf(u8, value, pattern.text) == null;}
fn filter( gpa: Allocator, io: Io, out: *Io.Writer, cwd: Dir, path: []const u8, options: Options, header: []const u8, text: []const u8,) !void { var m = try Mailbox.open(cwd, io, path, options.mailbox()); defer m.close(io);
var pattern: Pattern = .{ .gpa = gpa, .header = header, .text = text }; const stats = try m.filterMessages(gpa, io, &pattern, drop); try out.print("kept {d}, removed {d}\n", .{ stats.kept, stats.removed });}
fn check( gpa: Allocator, io: Io, out: *Io.Writer, cwd: Dir, path: []const u8, options: Options,) !void { var m = try Mailbox.open(cwd, io, path, options.mailbox()); defer m.close(io);
var it = m.iterate(gpa, io, &buffer) catch |err| { try out.print("{s}: cannot be read: {t}\n", .{ path, err }); try out.flush(); std.process.exit(1); }; defer it.deinit();
var messages: usize = 0; var complaints: usize = 0; while (it.next() catch |err| { try out.print("{s}: stopped after {d} messages: {t}\n", .{ path, messages, err }); try out.flush(); std.process.exit(1); }) |entry| { messages += 1;
if (entry.damage == .content_length_disagreed) { complaints += 1; try out.print( "{d}: Content-Length does not agree with where the next postmark is\n", .{entry.index + 1}, ); }
// A body line beginning `From ` after an empty line, which is a // boundary to any reader that goes looking for one. // // Only worth reporting for a variant that does not quote. Under one // that does, the line is stored with a `>` in front of it and cannot // be mistaken for anything; it is only here, in the message handed // back, that it looks alarming. Under `mboxcl2` nothing protects it // but the `Content-Length`, so the mailbox is one damaged header away // from being read as two messages. if (!options.variant.quotes()) { var rest = entry.bytes; var line_number: usize = 1; while (rest.len > 0) { const end = if (std.mem.findScalar(u8, rest, '\n')) |at| at + 1 else rest.len; const preceded_by_blank = line_number > 1 and (std.mem.endsWith(u8, entry.bytes[0 .. entry.bytes.len - rest.len], "\n\n") or std.mem.endsWith(u8, entry.bytes[0 .. entry.bytes.len - rest.len], "\r\n\r\n")); if (preceded_by_blank and mbox.variant.looksLikeBoundary(rest[0..end])) { complaints += 1; try out.print( "{d}: line {d} begins `From ` after an empty line; only the " ++ "Content-Length keeps this from being read as a new message\n", .{ entry.index + 1, line_number }, ); } rest = rest[end..]; line_number += 1; } }
if (entry.from.timestamp() == null) { complaints += 1; try out.print("{d}: postmark has no date this can read\n", .{entry.index + 1}); } }
try out.print("{s}: {d} messages, {d} complaints\n", .{ path, messages, complaints }); // A status rather than an error: this is a tool for reporting damage, and // a stack trace is not a report. if (complaints != 0) { try out.flush(); std.process.exit(1); }}
test { std.testing.refAllDecls(@This());}