Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A small tool for looking at mail files, which exists to show what the//! library looks like from outside and to be something to point at a message//! that is not behaving.//!//! It is not a mail client. There is no network, no mailbox, no configuration//! — the interesting parts are all in the library, and everything here is the//! twenty lines it takes to reach them.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;
const mime = @import("mime");
const usage = \\usage: zig-mime <command> [arguments] \\ \\ tree <file> the structure of a message, one part per line \\ tree --stream <file> the same, read a piece at a time and never held \\ headers <file> the headers, decoded \\ text <file> the text of a message, decoded to UTF-8 \\ extract <file> <dir> write every attachment into a directory \\ extract --stream <f> <d> the same, never holding the message \\ build <file> a message assembled from the library, for \\ feeding to something else; "-" is stdout \\ mailto <url> the message a mailto: link asks for \\ \\A file of "-" is read from standard input. \\;
/// A message has to fit in memory to be parsed, and a limit is the difference/// between a malformed file and an out-of-memory kill. Sixty-four megabytes is/// larger than any message any transport will carry.const message_limit: Io.Limit = .limited(64 * 1024 * 1024);
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator());
var stdout_buffer: [16 * 1024]u8 = undefined; var stdout_file: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file.interface; defer stdout.flush() catch {};
if (args.len < 2) { try stdout.writeAll(usage); try stdout.flush(); return error.MissingCommand; }
const command = args[1]; const rest = args[2..]; if (std.mem.eql(u8, command, "tree")) { try tree(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "headers")) { try headers(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "text")) { try text(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "extract")) { try extract(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "build")) { try build(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "mailto")) { try fromMailto(gpa, stdout, rest); } else if (std.mem.eql(u8, command, "help") or std.mem.eql(u8, command, "-h") or std.mem.eql(u8, command, "--help")) { try stdout.writeAll(usage); } else { try stdout.print("zig-mime: unknown command \"{s}\"\n\n{s}", .{ command, usage }); try stdout.flush(); return error.UnknownCommand; }}
fn readInput(io: Io, gpa: Allocator, path: []const u8) ![]u8 { if (std.mem.eql(u8, path, "-")) { var buffer: [64 * 1024]u8 = undefined; var stdin: Io.File.Reader = .initStreaming(.stdin(), io, &buffer); return stdin.interface.allocRemaining(gpa, message_limit); } return Io.Dir.cwd().readFileAlloc(io, path, gpa, message_limit);}
fn openMessage(io: Io, gpa: Allocator, args: []const [:0]const u8) !mime.Message { if (args.len < 1) return error.MissingFile; const source = try readInput(io, gpa, args[0]); defer gpa.free(source); return mime.Message.parse(gpa, source, .{});}
fn tree(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { if (args.len >= 1 and std.mem.eql(u8, args[0], "--stream")) { return streamTree(io, gpa, out, args[1..]); } var message = try openMessage(io, gpa, args); defer message.deinit(); try writeTree(out, &message.root, 0);}
/// The same structure, from the streaming parser.////// The point of it is what it does not do: the message is never in memory, so/// this runs in the same space on a message of a kilobyte and on one of a/// gigabyte. What it gives up is everything a second pass would need — the/// preamble, the exact bytes — which is why `tree` without it is the default.fn streamTree(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { if (args.len < 1) return error.MissingFile;
var file_buffer: [64 * 1024]u8 = undefined; var stdin_buffer: [64 * 1024]u8 = undefined;
var file: ?Io.File = null; defer if (file) |f| f.close(io);
var reader: Io.File.Reader = if (std.mem.eql(u8, args[0], "-")) .initStreaming(.stdin(), io, &stdin_buffer) else blk: { file = try Io.Dir.cwd().openFile(io, args[0], .{}); break :blk .init(file.?, io, &file_buffer); };
var parser: mime.Parser = .init(gpa, &reader.interface, .{}); defer parser.deinit();
// A line is left unfinished until it is known whether the entity has a // size to report or parts to list, since the two arrive from opposite // ends: the size only at `end`, and the parts in between. var bytes: u64 = 0; var unfinished = false; while (true) switch (try parser.next()) { .field => {}, .begin => if (unfinished) { try out.writeByte('\n'); unfinished = false; }, .headers_end => { try out.splatByteAll(' ', parser.depth() * 2); try out.print("{s}/{s}", .{ parser.mediaType().type, parser.mediaType().subtype, }); const encoding = parser.transferEncoding(); if (!encoding.isIdentity()) try out.print(" [{s}]", .{encoding.name()}); bytes = 0; unfinished = true; }, .end => if (unfinished) { if (bytes != 0) try out.print(" {d} bytes", .{bytes}); try out.writeByte('\n'); unfinished = false; }, .body => |chunk| bytes += chunk.len, .eof => break, };}
fn writeTree(out: *Io.Writer, part: *mime.Message.Part, depth: usize) !void { try out.splatByteAll(' ', depth * 2); try out.print("{s}/{s}", .{ part.media_type.type, part.media_type.subtype });
const encoding = part.transferEncoding(); if (!encoding.isIdentity()) try out.print(" [{s}]", .{encoding.name()}); if (try part.filename()) |name| try out.print(" \"{s}\"", .{name}); if (part.isAttachment()) try out.writeAll(" (attachment)"); // What an HTML body refers to with `cid:`, which is the one thing about a // part that cannot be worked out by looking at it. if (part.contentId()) |id| try out.print(" cid:{s}", .{id}); if (part.media_type.reportType()) |kind| try out.print(" report-type={s}", .{kind}); switch (part.body) { .raw => |bytes| try out.print(" {d} bytes", .{bytes.len}), .multipart => |multipart| try out.print(" {d} parts", .{multipart.parts.items.len}), .message => {}, } try out.writeByte('\n');
switch (part.body) { .raw => {}, .multipart => |multipart| { for (multipart.parts.items) |child| try writeTree(out, child, depth + 1); }, .message => |inner| try writeTree(out, inner, depth + 1), }}
fn headers(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { var message = try openMessage(io, gpa, args); defer message.deinit();
for (message.root.headers.fields.items) |f| { const value = (try message.root.headers.getUtf8(f.name)) orelse f.value; try out.print("{s}: {s}\n", .{ f.name, value }); }
// The two that are worth showing taken apart rather than as text. var from = try message.root.addresses(gpa, "from"); defer from.deinit(gpa); var it = from.mailboxIterator(); while (it.next()) |mailbox| { try out.print(" from: <{s}@{s}>", .{ mailbox.local_part, mailbox.domain }); if (mailbox.display_name) |name| try out.print(" {s}", .{name}); try out.writeByte('\n'); } if (try message.root.sentAt()) |sent| { try out.print(" date: {f}", .{mime.date.fmt(sent.time)}); if (sent.zone_unknown) try out.writeAll(" (zone not stated)"); try out.writeByte('\n'); }
// And if this is a report of some kind, what the machine-readable part // says -- which is the half that can be read the same way twice. if (try message.root.dispositionNotification(gpa)) |found| { var receipt = found; defer receipt.deinit(); if (try receipt.disposition()) |what| { try out.print(" disposition: {s}", .{what.type.name()}); // Whether a person was involved is the only thing a receipt can // honestly report about itself. if (what.action == .automatic) try out.writeAll(" (nobody was asked)"); if (what.modifiers.len != 0) try out.print(" /{s}", .{what.modifiers}); try out.writeByte('\n'); } if (try receipt.originalMessageId()) |id| { try out.print(" about: <{s}>\n", .{id}); } }
if (try message.root.feedbackReport(gpa)) |found| { var complaint = found; defer complaint.deinit(); try out.print(" complaint: {s}", .{(try complaint.feedbackType()).name()}); const count = try complaint.incidents(); if (count != 1) try out.print(" ({d} incidents)", .{count}); try out.writeByte('\n'); if (try complaint.originalMailFrom()) |sender| { try out.print(" about mail from: {s}\n", .{sender}); } if (try complaint.sourceIp()) |ip| try out.print(" sent from: {s}\n", .{ip}); }
if (try message.root.deliveryStatus(gpa)) |found| { var status = found; defer status.deinit(); if (try status.reportingMta()) |mta| { try out.print(" reported by: {s}\n", .{mta.value}); } for (status.recipients.items) |*recipient| { const address = if (try recipient.finalRecipient()) |final| final.value else "(unnamed)"; try out.print(" {s}: {s}", .{ address, (try recipient.action()).name() }); if (try recipient.status()) |code| try out.print(" {f}", .{code}); try out.writeByte('\n'); if (try recipient.diagnosticCode()) |diagnostic| { try out.print(" {s}\n", .{diagnostic.value}); } } }}
fn text(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { var message = try openMessage(io, gpa, args); defer message.deinit();
// What a reader shows: the plain text alternative if there is one, and // the HTML only if there is not. const part = message.root.find("text", "plain") orelse message.root.find("text", "html") orelse return error.NoTextPart; const body = try part.textAlloc(gpa); defer gpa.free(body); try mime.line_ending.fromCanonical(out, body, .lf);}
fn extract(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { if (args.len >= 1 and std.mem.eql(u8, args[0], "--stream")) { return streamExtract(io, gpa, out, args[1..]); } if (args.len < 2) return error.MissingDirectory; var message = try openMessage(io, gpa, args[0..1]); defer message.deinit();
var dir = try Io.Dir.cwd().openDir(io, args[1], .{}); defer dir.close(io);
var index: usize = 0; var walker = message.root.walk(); while (walker.next()) |part| { if (part.body != .raw) continue;
if (part.isAttachment()) { index += 1; const name = try chooseName(try part.filename(), index); // Decoded straight into the file. A hundred megabyte attachment is // never in memory: `decodeWriter` is the reason the buffer below // is sixty-four kilobytes rather than the size of the part. var file = try dir.createFile(io, name.slice(), .{}); defer file.close(io); var buffer: [64 * 1024]u8 = undefined; var writer: Io.File.Writer = .init(file, io, &buffer); try part.decodeWriter(&writer.interface); try writer.interface.flush(); try out.print("{s} ({d} bytes)\n", .{ name.slice(), writer.pos }); continue; }
// A message from before MIME carries its attachment inside the text, // where no header mentions it. Nothing finds that by itself, which is // why `uuencodedFile` has to be asked. var embedded = (try part.uuencodedFile(gpa)) orelse continue; defer embedded.deinit(gpa); index += 1; const name = try chooseName(embedded.name, index); try dir.writeFile(io, .{ .sub_path = name.slice(), .data = embedded.data }); try out.print("{s} ({d} bytes, uuencoded in the body)\n", .{ name.slice(), embedded.data.len, }); }}
/// Every attachment written out, with neither the message nor any one part/// ever in memory.////// The chunks arrive encoded and leave decoded: `transfer_encoding.Decoder`/// keeps the few bytes of state that span a chunk boundary — a partial base64/// group, a half-finished quoted-printable escape — so nothing has to be held/// to be decoded. What this cannot do is the uuencoded file hidden inside a/// text body, which needs a second look at bytes that have already gone past;/// `extract` without `--stream` finds those.fn streamExtract(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { if (args.len < 2) return error.MissingDirectory;
var read_buffer: [64 * 1024]u8 = undefined; var stdin_buffer: [64 * 1024]u8 = undefined; var source: ?Io.File = null; defer if (source) |f| f.close(io);
var reader: Io.File.Reader = if (std.mem.eql(u8, args[0], "-")) .initStreaming(.stdin(), io, &stdin_buffer) else blk: { source = try Io.Dir.cwd().openFile(io, args[0], .{}); break :blk .init(source.?, io, &read_buffer); };
var dir = try Io.Dir.cwd().openDir(io, args[1], .{}); defer dir.close(io);
var parser: mime.Parser = .init(gpa, &reader.interface, .{}); defer parser.deinit();
var disposition: std.ArrayList(u8) = .empty; defer disposition.deinit(gpa);
var write_buffer: [64 * 1024]u8 = undefined; var open: ?Io.File = null; var writer: Io.File.Writer = undefined; var decoder: mime.transfer_encoding.Decoder = undefined; var name_buffer: [256]u8 = undefined; var name_len: usize = 0; var index: usize = 0; defer if (open) |f| f.close(io);
while (true) switch (try parser.next()) { .begin => disposition.clearRetainingCapacity(),
.field => |f| if (std.ascii.eqlIgnoreCase(f.name, "content-disposition")) { disposition.clearRetainingCapacity(); try disposition.appendSlice(gpa, f.value); },
.headers_end => { index += 1; const suggested = try suggestedName(gpa, &name_buffer, disposition.items, parser.mediaType()); if (!isAttached(disposition.items, suggested != null)) continue;
// A safe suggestion is already sitting in the buffer; an unsafe // one is overwritten by the number that replaces it. name_len = if (safeName(suggested)) |safe| safe.len else (try std.fmt.bufPrint(&name_buffer, "part-{d}", .{index})).len;
open = try dir.createFile(io, name_buffer[0..name_len], .{}); writer = .init(open.?, io, &write_buffer); decoder = .init(parser.transferEncoding()); },
.body => |chunk| if (open != null) { try decoder.write(gpa, &writer.interface, chunk); },
.end => if (open) |f| { try decoder.finish(gpa, &writer.interface); try writer.interface.flush(); decoder.deinit(gpa); f.close(io); open = null; try out.print("{s} ({d} bytes)\n", .{ name_buffer[0..name_len], writer.pos }); },
.eof => break, };}
/// The filename a part suggests, copied into `buffer`, or null.fn suggestedName( gpa: Allocator, buffer: []u8, disposition: []const u8, media: *const mime.MediaType,) !?[]const u8 { var parameters: mime.parameters.Parameters = try .parse(gpa, disposition); defer parameters.deinit(gpa);
if (try parameters.getUtf8Alloc(gpa, "filename")) |found| { defer gpa.free(found); return copyInto(buffer, found); } if (try media.parameters.getUtf8Alloc(gpa, "name")) |found| { defer gpa.free(found); return copyInto(buffer, found); } return null;}
fn copyInto(buffer: []u8, name: []const u8) ?[]const u8 { if (name.len == 0 or name.len > buffer.len) return null; @memcpy(buffer[0..name.len], name); return buffer[0..name.len];}
/// Whether a part is offered as a file. The same rule as `Part.isAttachment`,/// from the two things a streaming reader has to hand.fn isAttached(disposition: []const u8, has_filename: bool) bool { const end = std.mem.findScalar(u8, disposition, ';') orelse disposition.len; const token = std.mem.trim(u8, disposition[0..end], " \t"); if (token.len == 0) return has_filename; return std.ascii.eqlIgnoreCase(token, "attachment");}
/// A name to write a part under: the one it suggests if that is safe, and a/// number if it is not.const ChosenName = struct { buffer: [64]u8, len: usize, suggested: ?[]const u8,
fn slice(self: *const ChosenName) []const u8 { return self.suggested orelse self.buffer[0..self.len]; }};
fn chooseName(suggested: ?[]const u8, index: usize) !ChosenName { var chosen: ChosenName = .{ .buffer = undefined, .len = 0, .suggested = safeName(suggested) }; if (chosen.suggested == null) { chosen.len = (try std.fmt.bufPrint(&chosen.buffer, "part-{d}", .{index})).len; } return chosen;}
/// A filename out of a message is attacker-controlled/// A filename out of a message is attacker-controlled, so the only one worth/// trusting is one that is a plain name: no directory separators, no `..`, no/// leading dot, nothing that could escape the directory it is being written/// into. Anything else is refused and the part is numbered instead.fn safeName(suggested: ?[]const u8) ?[]const u8 { const name = suggested orelse return null; if (name.len == 0 or name.len > 200) return null; if (name[0] == '.') return null; for (name) |c| switch (c) { '/', '\\' => return null, 0...0x1f, 0x7f => return null, else => {}, }; return name;}
fn build(io: Io, gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { var source: std.Random.IoSource = .{ .io = io }; const random = source.interface();
var message: mime.Message = try .init(gpa); defer message.deinit();
try message.root.setAddresses("From", &.{ .{ .display_name = "Jeff Ollie", .local_part = "jeff", .domain = "example.com" }, }); try message.root.setAddresses("To", &.{ .{ .display_name = "Ollie, Jeff", .local_part = "jeff", .domain = "example.net" }, }); try message.root.setSubject("A message built by zig-mime — including a café"); try message.root.setDate(datetimeNow(io)); try message.root.setMessageId("example.com", random);
// The identifier has to exist before the HTML that refers to it does, // which is why `newContentId` is separate from `embed`. const logo = try message.newContentId("example.com", random); var html: std.Io.Writer.Allocating = .init(gpa); defer html.deinit(); try html.writer.print( "<html><body><p>This is the body, with a café in it.</p>" ++ "<img src=\"cid:{s}\" alt=\"a logo\"></body></html>\n", .{logo}, );
try message.setAlternative( random, "This is the body, with a café in it.\n\n[a logo]\n", html.written(), .{}, ); _ = try message.embed(random, "\x89PNG\r\n\x1a\n not really a PNG", .{ .filename = "logo.png", .content_id = logo, }); // No media type given: it is taken from the name. _ = try message.attach(random, "not really a PDF", .{ .filename = "le café.pdf" });
if (args.len == 0 or std.mem.eql(u8, args[0], "-")) { try message.write(out); return; } const bytes = try message.toBytesAlloc(gpa); defer gpa.free(bytes); try Io.Dir.cwd().writeFile(io, .{ .sub_path = args[0], .data = bytes }); try out.print("wrote {s} ({d} bytes)\n", .{ args[0], bytes.len });}
/// The message a `mailto:` link asks for, written out.////// The safe list is the default one, so a link that tries to set `From` or a/// `Content-Type` gets neither: a `mailto:` arrives from a web page and is/// attacker-supplied by construction.fn fromMailto(gpa: Allocator, out: *Io.Writer, args: []const [:0]const u8) !void { if (args.len < 1) return error.MissingUrl; var message = try mime.mailto.parse(gpa, args[0], .{}); defer message.deinit(); try message.write(out);}
fn datetimeNow(io: Io) mime.datetime.DateTime { return mime.datetime.DateTime.utc(io);}
test safeName { try std.testing.expectEqualStrings("report.pdf", safeName("report.pdf").?); try std.testing.expectEqual(null, safeName(null)); try std.testing.expectEqual(null, safeName("../../etc/passwd")); try std.testing.expectEqual(null, safeName("/etc/passwd")); try std.testing.expectEqual(null, safeName(".bashrc")); try std.testing.expectEqual(null, safeName("a\nb")); try std.testing.expectEqual(null, safeName(""));}