- Zig 87%
- Nix 10%
- Python 3%
zig-mbox #
Classic Unix mailboxes for Zig 0.16: reading the messages out of one, adding
messages to it, and removing the ones you do not want. The flat file that
/var/mail/$USER still is, that formail and procmail and mutt still write,
and that every mail export in the world falls back to.
$ zig-mbox list ~/mail/lists.mbox
1 alice@example.com 2024-01-01 the first message
2 bob@example.net 2024-01-02 [SPAM] buy things
3 carol@example.org 2024-01-03 the third
$ zig-mbox filter ~/mail/lists.mbox X-Spam-Flag YES
kept 2, removed 1
Three layers, and you can stop at any of them:
From and variant |
the postmark and the quoting — pure functions over bytes, no I/O and no allocation |
Reader, Writer, filter |
messages over any stream: an iterator, an appender, and the copy-with-a-predicate between them |
Mailbox |
the file: the locking, and the atomic rewrite that a change needs |
The message content is zig-mime's: this library frames messages and does
not read them, and Entry.parse hands the bytes straight over. The
API documentation is generated from the
doc comments, which carry most of the explanation of why an mbox is the shape
it is.
Where this lives #
The repository lives in three places that carry the same history. The Forgejo instance at https://git.jcollie.dev/jeff/zig-mbox is the web-visible one, and is where the tests and the documentation are built:
$ git clone https://git.jcollie.dev/jeff/zig-mbox.git
it is mirrored on Tangled at https://tangled.org/jcollie.dev/zig-mbox, and it is also on the Radicle peer-to-peer network, where the repository's identifier is
rad:z3sbrHg5eTbX4HywAKcokBKNQhtMB
and
rad clone rad:z3sbrHg5eTbX4HywAKcokBKNQhtMB
fetches it from any node that seeds it — which is the only name it has there, a Radicle repository being findable by its ID and nothing else. Cloning also seeds it, which helps keep it available. Any of the three is the whole project.
Adding it to a project #
$ zig fetch --save git+https://git.jcollie.dev/jeff/zig-mbox.git
const mbox = b.dependency("zig_mbox", .{ .target = target }).module("mbox");
exe.root_module.addImport("mbox", mbox);
Why an mbox is shaped like this #
An mbox has no index, no length field, no checksum and no version. It is
messages one after another in a file, and the only mark of where one starts is
a line beginning From — the postmark, which is not RFC 5322 and is not
specified anywhere:
From jeff@example.com Mon Jan 1 00:00:00 2024
It carries the envelope sender and the time of delivery, neither of which
need agree with the From: header. The difference is the point: the header
says who wrote the message, the postmark says who handed it over, and a bounce
goes back to the second one.
Everything difficult about the format follows from having no length field. A
message whose body contains a line beginning From is a message that can
split itself in two, so every mbox does something about that, and what it does
is the variant. The four are not compatible and nothing in the file says
which it is, which is why it is a parameter here and not a detection:
| variant | what it stores | undoing it |
|---|---|---|
mboxo |
From becomes >From |
lossy — a >From the sender wrote is the same bytes |
mboxrd |
any >*From gains one more > |
exact, and the default here |
mboxcl |
mboxo, plus a Content-Length |
lossy, like mboxo |
mboxcl2 |
nothing; a Content-Length says where the body ends |
exact, as long as the length is right |
mboxrd is the default because it is the only one whose quoting is a
bijection: the extra > on lines that already had one is what makes reading
and writing give back the bytes that went in.
There is one normalization nothing can avoid. A message whose last line has no terminator gets one, because the empty line separating two messages has to begin at the start of a line. Everything else survives, line endings included: a CRLF mailbox is read and written as CRLF, down to the carriage return in the postmark.
Reading a mailbox #
An iterator, over any Io.Reader — so the difficult part of this library can
be used, tested and fuzzed with no filesystem anywhere near it.
const mbox = @import("mbox");
var input: Io.Reader = .fixed(source);
var reader: mbox.Reader = .init(gpa, &input, .{});
defer reader.deinit();
while (try reader.next()) |entry| {
std.debug.print("{s} at byte {d}\n", .{ entry.from.address, entry.offset });
if (entry.from.timestamp()) |when| { ... }
}
What entry 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. offset
says where the message's postmark begins, so two consecutive offsets say
exactly which bytes of the file a message was.
The message itself is somebody else's subject, and goes to zig-mime:
var parsed = try entry.parse(gpa, .{});
defer parsed.deinit();
std.debug.print("{s}\n", .{(try parsed.root.subject()) orelse "(no subject)"});
// Or the headers alone, for a decision that need not pay for the body.
var headers = try entry.headers(gpa);
defer headers.deinit();
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 matter: without the From there is no boundary at all, and
without the empty line every body that quotes a mail header splits its own
message in two.
Adding a message #
Always an append, and always through a whole rewrite — see the file itself for why.
var mailbox: mbox.Mailbox = try .create(.cwd(), io, "mail.mbox", .{});
defer mailbox.close(io);
var line: Io.Writer.Allocating = .init(gpa);
defer line.deinit();
try mbox.From.writeLine(&line.writer, "jeff@example.com", now);
_ = try mailbox.append(gpa, io, try mbox.From.parse(line.writer.buffered()), message);
From.writeLine composes the postmark in the asctime form every reader
understands, and recomputes the weekday from the date rather than trusting the
one it was handed — a postmark claiming the wrong day is the thing this library
forgives in others and should not commit itself.
Removing messages #
There is no other way to remove a message from an mbox than to write the mailbox again without it: the format has no index and no free list, so taking one out means moving everything after it. So removal is a filter — a predicate over the messages, and one pass:
fn notSpam(gpa: Allocator, entry: mbox.Reader.Entry) Allocator.Error!bool {
var headers = try entry.headers(gpa);
defer headers.deinit();
const flag = (try headers.getUtf8("X-Spam-Flag")) orelse return true;
return !std.mem.eql(u8, std.mem.trim(u8, flag, " \t"), "YES");
}
const stats = try mailbox.filterMessages(gpa, io, gpa, notSpam);
// stats.kept, stats.removed
The predicate may fail only by running out of memory, which is less of a
restriction than it looks: Entry.parse hands the bytes to zig-mime, whose
parse has no other way to fail, so a predicate that reads the message it is
deciding about fits exactly. One that needs to fail some other way should
record it in its context and be asked afterwards — which keeps the error out of
the middle of a rewrite.
The same thing without a file is filter.copy, from any reader to any writer.
The file itself #
Mailbox is the layer that knows there is a file, and it exists for the two
things only a file has: other processes looking at the same one, and the
possibility of being interrupted halfway through writing it.
Every change is a rewrite. A new mailbox is written into an unnamed
temporary file beside the old one and renamed over the top, so the file at that
path is either entirely the old mailbox or entirely the new one and never a
mixture. An interrupted rewrite costs the work and nothing else. append is
the same operation with a predicate that keeps everything, which is why adding
one message costs a copy of the mailbox — a real price, paid deliberately,
because the alternative leaves a half-written message behind when it fails.
The lock is flock, taken shared to read and exclusive to change, released
the moment the operation ends and by the kernel if the process dies. Turn it
off with .lock = false for a mailbox nothing else can reach.
Against another program using this library that is enough, and there is a wrinkle worth knowing about how. A rename leaves the old file nameless, so after any change a handle opened before it is reading a file nobody can reach and a lock held on it guards nothing. Every operation therefore takes the lock and then checks that the inode it holds is still the one at the path, reopening and retaking it if not. Checking after taking the lock is what makes it a check rather than a guess.
Permissions are carried across and ownership is not. A rewrite makes a new
file, and a new file is made with whatever the process's umask says, so without
copying them a 0600 spool comes back readable by anyone. The owning user and
group cannot be carried without privileges this has no business having.
The command-line tool #
$ zig-mbox list mail.mbox # number, sender, date, subject
$ zig-mbox get mail.mbox 2 # one message, as RFC 5322
$ zig-mbox append mail.mbox < message.eml # postmark it and add it
$ zig-mbox filter mail.mbox X-Spam-Flag YES # remove what matches
$ zig-mbox check mail.mbox # report damage, change nothing
--variant, --no-lock and --sender apply to all of them.
check is the one that earns its keep. An mbox has no way to say it is
damaged, so the damage has to be looked for, and it is always the same few
things: a file that does not begin with a postmark, a Content-Length that
does not agree with where the next postmark actually is, a postmark whose date
cannot be read, and — under the variants that do not quote — a body line
beginning From after an empty line, which only the length is keeping from
being read as a new message.
What is deliberately not here #
- Delivery. This is not an MDA and must not be used as one. The rename that makes a change atomic also makes the old file nameless, so a delivery written to it after the rename lands in a file with no path and is lost when the last handle closes. That is what rewrite-and-rename means, and it is why the classic tools rewrite in place and risk the other failure instead. Use this on mailboxes nothing else is delivering into: an archive, an export, a spool that has been moved aside.
- Dot-locking.
<mailbox>.lockfiles are what mutt and procmail expect on a live spool. Not implemented, for the reason above: a library that cannot safely share a spool should not advertise that it can. - Reading the messages. That is zig-mime's, and
Entry.parseis the whole of the connection. - Detecting the variant. Nothing in an mbox says which one it is, and a guess that is wrong corrupts every body it touches. It is a parameter.
- MMDF, Maildir, mh. Other formats. zig-maildir does the second.
Interoperability #
mbox's disagreements between implementations are the whole difficulty of the
format, so a fixture written to suit this parser would hide exactly what is
worth testing. tests/interop.py checks both directions against the two second
opinions that are actually deployed — procmail's formail -s, and Python's
mailbox module — over messages chosen because each one pins a difference: a
body line that would be a boundary unquoted, a body that was already quoted, a
message with no trailing newline, a message with no body.
$ nix flake check # runs it
It is a plain derivation rather than a virtual machine, unlike the sibling projects' interoperability tests. Those boot a guest because what they test is a daemon. An mbox is a file, and reading one is two programs and a directory.
Fuzzing #
$ zig build test # the properties, over the checked-in seeds
$ zig build fuzz-run # a minute of each, with generated input
$ zig build fuzz-run -- --seconds 300 --target scan
$ zig build fuzz-run -- --input fuzz-findings/x.bin --target scan
An mbox has no checksum and no length field, so a damaged mailbox is
byte-for-byte indistinguishable from a strange one and the scanner has to do
something sensible either way. The properties in tests/fuzz.zig say what
"sensible" is — chiefly that reading a mailbox and writing it back reaches a
fixed point after one round and stays there, which is what catches a scanner
and a writer that disagree by one blank line. That property found four real
bugs while this was being written.
Zig 0.16.0 cannot build a test executable in fuzz mode without a patched
standard library, and leaves the fuzzer's coverage table empty even then;
flake.nix says what the patch is and tools/fuzz.zig is the loop that stands
in for coverage feedback.
The API documentation #
https://jeff.jcollie.page/zig-mbox/, rebuilt from main on every push.
$ zig build docs-serve # then open http://127.0.0.1:8000/
$ zig build docs # or just build it, into zig-out/docs
It has to be served rather than opened. What Zig emits is not a page but a
program: a WebAssembly viewer that fetches the source of everything it shows
out of a tar file beside it, and a browser refuses to fetch anything from a
file:// page. That is the same reason zig std runs a server rather than
opening a file.
Licence #
MIT. See LICENSES/MIT.txt.