// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A whole message, parsed into a tree. //! //! Everything in MIME is an *entity*: a header block, a blank line, and a //! body. A message is one, and so is each part inside a `multipart/*` body, //! and so is the message inside a `message/rfc822` attachment. `Part` is that //! shape, and a `Message` is a `Part` together with the memory its tree lives //! in. //! //! ```text //! multipart/mixed //! ├── multipart/alternative //! │ ├── text/plain //! │ └── text/html //! └── application/pdf "report.pdf" //! ``` //! //! ## What is kept //! //! Bodies are kept **as they were written**, still in whatever //! `Content-Transfer-Encoding` they arrived in, and header values are kept in //! wire form. A parsed message written back out is therefore byte-identical to //! the one that went in, which is what makes it safe to parse a signed message //! and forward it, and what makes `zig build fuzz-run` able to check a //! property worth checking. Decoding happens when it is asked for: //! `decodeAlloc` for the bytes, `textAlloc` for text as UTF-8. //! //! The one thing that is not preserved is a message whose lines end in LF //! alone. Mail is CRLF; a message read out of a Unix file often is not, and //! such a message is written back out canonicalised. That is a repair rather //! than a loss, and it is the only one. //! //! ## Depth //! //! Parsing is recursive, and nothing stops a message from nesting a thousand //! multiparts inside each other — a small file that costs a great deal to //! open, and a stack overflow rather than an error if nothing is watching. //! `ParseOptions.max_depth` is that limit, and a message deeper than it parses //! down to the limit and keeps the rest as an undecoded body. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const base64 = @import("codec/base64.zig"); const encoded_word = @import("codec/encoded_word.zig"); const quoted_printable = @import("codec/quoted_printable.zig"); const flowed = @import("flowed.zig"); const line_ending = @import("line_ending.zig"); const media_types = @import("media_types.zig"); const message_id = @import("header/message_id.zig"); const address = @import("header/address.zig"); const field = @import("header/field.zig"); const MediaType = @import("header/MediaType.zig"); const datetime = @import("datetime"); const date = @import("header/date.zig"); const delivery_status = @import("delivery_status.zig"); const disposition_notification = @import("disposition_notification.zig"); const feedback_report = @import("feedback_report.zig"); const Headers = @import("Headers.zig"); const parameters = @import("header/parameters.zig"); const received_field = @import("received.zig"); const transfer_encoding = @import("codec/transfer_encoding.zig"); const Message = @This(); /// Everything in the tree is allocated here, including every `Headers`. /// /// On the heap rather than in this struct, because the parts hold the /// `Allocator` it hands out and an `Allocator` from an arena points *at* that /// arena: a `Message` returned by value would move it, and every pointer into /// the tree would be pointing at where the arena used to be. arena: *std.heap.ArenaAllocator, root: Part, pub const TransferEncoding = transfer_encoding.TransferEncoding; /// The parts of a `multipart/report` — RFC 6522 — which has a fixed shape: /// something for a person to read, something for a program to read, and /// usually the message it is all about. pub const Report = struct { /// The human-readable explanation, which is the first part and the one /// everybody reads. Every mail system words it differently, which is why /// the second part exists. notice: *Part, /// The machine-readable part, whose subtype is the `report-type`. Absent /// only from a malformed report. machine: ?*Part, /// The message the report is about, or as much of it as the reporting /// system kept. Either a whole `message/rfc822`, in which case /// `original.?.body.message` is the message, or a `text/rfc822-headers` /// carrying only its headers — see `Part.rfc822HeadersAlloc`. Absent when /// the reporting system kept neither. original: ?*Part, }; /// A uuencoded file taken out of a body, and the metadata its `begin` line /// carried. The caller owns both halves. pub const UuencodedFile = struct { /// From the `begin` line. For a message that predates /// `Content-Disposition` this is the only name the file has. name: []const u8, /// The Unix permission bits the `begin` line claimed. Nothing should act /// on these — a mode out of somebody else's mail is a number they chose — /// but they are what was sent. mode: u32, data: []const u8, pub fn deinit(self: *UuencodedFile, gpa: Allocator) void { gpa.free(self.name); gpa.free(self.data); self.* = undefined; } }; /// One entity: the message, or a part of it. pub const Part = struct { headers: Headers, body: Body, /// The parsed `Content-Type`, or the default for the context the part was /// found in. Kept beside the headers rather than reparsed on every /// question, since nearly every question about a part is about this. /// /// It is a cache: a caller that rewrites the `Content-Type` header by hand /// must call `refreshContentType`. `setContentType` does both. media_type: MediaType, /// Whether the header block was ended by the blank line RFC 5322 requires. /// /// A message truncated inside its headers has no blank line and no body, /// and writing one back in would invent a boundary between a header block /// and a body that was never there — which, for a `message/rfc822` part /// whose contents are exactly that, grows the message every time it is /// opened and saved. True for anything built rather than parsed, since a /// message being written needs one. headers_terminated: bool = true, pub const Body = union(enum) { /// A leaf. The bytes exactly as they appeared, still in their /// transfer encoding. raw: []const u8, /// A `multipart/*` body, taken apart. multipart: Multipart, /// A `message/rfc822` body: one whole message. message: *Part, }; /// The `Content-Transfer-Encoding`, or `.seven_bit` where there is none, /// which is what RFC 2045 §6.1 says the absence means. pub fn transferEncoding(self: Part) TransferEncoding { const value = self.headers.get("content-transfer-encoding") orelse return .seven_bit; return TransferEncoding.parse(field.trimValue(value)); } /// The `Content-Disposition`: `inline`, `attachment`, or whatever else was /// written. Null where the header is absent, which RFC 2183 says to treat /// as `inline`. pub fn disposition(self: Part) ?[]const u8 { const value = self.headers.get("content-disposition") orelse return null; const trimmed = field.trimValue(value); const end = std.mem.findScalar(u8, trimmed, ';') orelse trimmed.len; return std.mem.trim(u8, trimmed[0..end], " \t"); } /// Whether this part is offered as a file rather than shown as part of /// the message. A part with no `Content-Disposition` and no filename /// anywhere is inline, which is what RFC 2183 §2.1 says the absence of the /// header means. pub fn isAttachment(self: Part) bool { const value = self.disposition() orelse return self.hasFilename(); return std.ascii.eqlIgnoreCase(value, "attachment"); } /// Whether a filename is suggested anywhere, answered without decoding it /// and so without allocating. pub fn hasFilename(self: Part) bool { if (self.media_type.name() != null) return true; if (self.body == .raw and self.transferEncoding().embeddedName(self.body.raw) != null) return true; const raw = self.headers.get("content-disposition") orelse return false; var it: parameters.Iterator = .init(raw); while (it.next()) |parameter| { if (std.ascii.eqlIgnoreCase(parameter.name, "filename")) return true; } return false; } /// The `Message-ID` of this message, with the angle brackets removed, or /// null. The form to compare, and the form `setInReplyTo` puts into a /// reply's `References`. pub fn messageId(self: Part) ?[]const u8 { const raw = self.headers.get("message-id") orelse return null; return message_id.first(field.trimValue(raw)); } /// The ancestry of this message, oldest first: the identifier of whatever /// started the thread, then each reply down to the one this is a reply to. /// Empty where the header is missing, which is what the first message of a /// thread looks like. pub fn references(self: *Part) Allocator.Error!message_id.Iterator { const value = (try self.headers.getUnfolded("references")) orelse ""; return .init(value); } pub const ThreadOptions = struct { /// The most identifiers `References` will be left holding. /// /// There is no limit in RFC 5322 and so no right answer, only the /// convention: a long thread's `References` grows without bound, and /// every client trims it eventually. Twenty is generous — it is more /// ancestry than any reader displays — and keeps the header inside the /// thousand-character line limit for identifiers of an ordinary /// length. max_references: usize = 20, }; /// Sets `In-Reply-To` and `References` so that this message threads as a /// reply to `parent`. /// /// `In-Reply-To` names the parent and nothing else: RFC 5322 §3.6.4 allows /// several, and a reply to one message is a reply to one message. /// `References` is the parent's ancestry with the parent's own identifier /// on the end — or, where the parent had no `References`, its /// `In-Reply-To`, which is the ancestry a client that wrote one and not /// the other left behind. /// /// Does nothing if the parent has no `Message-ID`, because there is then /// nothing to thread under and a reference to a message that cannot be /// named is worse than none. pub fn setInReplyTo( self: *Part, parent: *Part, options: ThreadOptions, ) Allocator.Error!void { const a = self.allocator(); const parent_id = parent.messageId() orelse return; var in_reply_to: Io.Writer.Allocating = .init(a); message_id.writeList(&in_reply_to.writer, &.{parent_id}) catch return error.OutOfMemory; try self.headers.set("In-Reply-To", in_reply_to.written()); const inherited = (try parent.headers.getUnfolded("references")) orelse (try parent.headers.getUnfolded("in-reply-to")) orelse ""; var ids: std.ArrayList([]const u8) = .empty; var it: message_id.Iterator = .init(inherited); while (it.next()) |id| try ids.append(a, id); // A parent whose own ancestry already ends with its identifier is // malformed, and appending it twice would make this message look like // a reply to itself. if (ids.items.len == 0 or !std.mem.eql(u8, ids.items[ids.items.len - 1], parent_id)) { try ids.append(a, parent_id); } const limit = @max(options.max_references, 1); const buffer = try a.alloc([]const u8, limit); const kept = message_id.trim(ids.items, buffer, limit); var value: Io.Writer.Allocating = .init(a); message_id.writeList(&value.writer, kept) catch return error.OutOfMemory; try self.headers.set("References", value.written()); } /// Adds a `Received:` trace field for a hop that has just taken delivery /// of this message, at the top where the next reader of the trace expects /// to find the newest one. /// /// This is the SMTP server's side of the library: a server that has /// finished `DATA` calls it once, with what it knows about the session, /// before handing the message on. See `received.Received` for what the /// clauses mean and which of them can be believed, and /// `received.protocolFor` for the `with` value. /// /// ```zig /// try message.addReceived(.{ /// .from = helo_name, // what the peer said /// .from_info = observed, // what we saw: reverse DNS and address /// .by = "mx.example.net", /// .by_info = "zig-mime", /// .with = mime.received.protocolFor(.{ .tls = tls, .authenticated = auth }), /// .id = queue_id, /// .received_at = now, /// }); /// ``` /// /// The message is otherwise untouched. RFC 5321 §4.4 requires that: a /// system adding a trace field must not alter the ones already there, and /// the whole value of the trace is that each line is exactly what the hop /// that wrote it wrote. pub fn addReceived(self: *Part, received: received_field.Received) Allocator.Error!void { var value: Io.Writer.Allocating = .init(self.allocator()); received.write(&value.writer) catch return error.OutOfMemory; try self.headers.prependTrace("Received", value.written()); } /// The `Content-ID` of this part, with the angle brackets removed, or /// null. /// /// What comes back is the form a `cid:` URL carries and the form to /// compare: RFC 2045 §7 writes the header as `` and RFC 2392 /// writes the reference to it as `cid:addr-spec`, and the brackets are /// punctuation of the header rather than part of the identifier. pub fn contentId(self: Part) ?[]const u8 { const raw = self.headers.get("content-id") orelse return null; return bareContentId(field.trimValue(raw)); } /// Sets the `Content-ID`, adding the angle brackets the header needs. /// Accepts the identifier with or without them, and with or without a /// leading `cid:`, so that whatever the caller is holding can be handed /// over as it stands. pub fn setContentId(self: *Part, id: []const u8) Allocator.Error!void { var out: Io.Writer.Allocating = .init(self.allocator()); out.writer.writeByte('<') catch return error.OutOfMemory; // An identifier out of somebody else's message could otherwise close // the brackets early, or end the header line altogether. for (bareContentId(id)) |c| switch (c) { 0...0x20, 0x7f, '<', '>' => {}, else => out.writer.writeByte(c) catch return error.OutOfMemory, }; out.writer.writeByte('>') catch return error.OutOfMemory; try self.headers.set("Content-ID", out.written()); } /// The part whose `Content-ID` is `id`, searched depth first from here. /// /// `id` may be written any of the ways it appears: `cid:logo@example.com` /// as an HTML `src` holds it, `` as the header holds it, /// or bare. Percent-escapes in a `cid:` URL are *not* decoded, because /// nothing that writes one escapes anything, and decoding them would /// change an identifier that legitimately contains a `%`. pub fn findContentId(self: *Part, id: []const u8) ?*Part { const wanted = bareContentId(id); if (wanted.len == 0) return null; var walker = self.walk(); while (walker.next()) |part| { const found = part.contentId() orelse continue; if (std.mem.eql(u8, found, wanted)) return part; } return null; } /// The suggested filename, decoded to UTF-8. /// /// `Content-Disposition`'s `filename` first, since RFC 2183 is where this /// belongs, and the `name` parameter of `Content-Type` after it, which is /// what software from before RFC 2183 wrote and some of it still does. /// Both may carry an RFC 2047 encoded word that neither specification /// permits; both are decoded anyway. /// /// And last, the name a uuencoded body writes on its own `begin` line. A /// message old enough to have a uuencoded attachment is usually old enough /// to predate `Content-Disposition` as well, so that `begin` line is /// frequently the only place the filename appears at all. /// /// Cached in the tree's memory, so the caller frees nothing. pub fn filename(self: *Part) Allocator.Error!?[]const u8 { const a = self.allocator(); if (self.headers.get("content-disposition")) |raw| { var found: parameters.Parameters = try .parse(a, raw); if (try found.getUtf8Alloc(a, "filename")) |name| return name; } if (try self.media_type.parameters.getUtf8Alloc(a, "name")) |name| return name; if (self.body == .raw) { if (self.transferEncoding().embeddedName(self.body.raw)) |name| { return try transfer_encoding.toUtf8Alloc(a, name, "utf-8"); } } return null; } /// The size in octets the sender claimed for this part's content, or null. /// /// RFC 2183's `size` parameter, and it is a *claim*: the value is the size /// of the decoded content, it is documented as approximate, and it is /// written by the sender. A receiver may use it to decide whether to /// offer a download or how to draw a progress bar. A receiver that uses /// it to size a buffer it then fills from the body has written the bug /// this parameter is best known for, because nothing checks it and /// `decodeAlloc` is what actually knows. pub fn declaredSize(self: *Part) Allocator.Error!?u64 { const value = try self.dispositionParameter("size") orelse return null; return std.fmt.parseInt(u64, std.mem.trim(u8, value, " \t"), 10) catch null; } /// When the file this part carries was created, as the sender's system /// had it. RFC 2183's `creation-date`. /// /// A timestamp out of somebody else's filesystem: worth showing and worth /// restoring onto a file being saved, and not worth believing about /// anything. pub fn creationDate(self: *Part) Allocator.Error!?date.Parsed { return self.dispositionDate("creation-date"); } /// When it was last changed. RFC 2183's `modification-date`, and the one /// of the three that is usually there. pub fn modificationDate(self: *Part) Allocator.Error!?date.Parsed { return self.dispositionDate("modification-date"); } /// When it was last read. RFC 2183's `read-date`, which almost nothing /// sends. pub fn readDate(self: *Part) Allocator.Error!?date.Parsed { return self.dispositionDate("read-date"); } fn dispositionDate(self: *Part, name: []const u8) Allocator.Error!?date.Parsed { const value = try self.dispositionParameter(name) orelse return null; return date.parse(value) catch null; } /// One parameter of the `Content-Disposition`, as written. The result /// lives in the tree's memory. fn dispositionParameter(self: *Part, name: []const u8) Allocator.Error!?[]const u8 { const raw = self.headers.get("content-disposition") orelse return null; var found: parameters.Parameters = try .parse(self.allocator(), raw); return found.get(name); } /// The arena the whole tree lives in, reached through the headers so that /// a `Part` needs no second pointer to it. Everything a `Part` derives — /// a decoded filename, a reparsed `Content-Type` — is allocated here and /// freed with the message. fn allocator(self: Part) Allocator { return self.headers.gpa; } /// The decoded subject, or null. Cached in the tree's memory; do not free. pub fn subject(self: *Part) Allocator.Error!?[]const u8 { return self.headers.getUtf8("subject"); } /// The `Date:`, parsed. Null where the header is missing or is not a /// date at all — which is common enough in stored mail that failing /// would be the wrong answer. pub fn sentAt(self: *Part) Allocator.Error!?date.Parsed { const value = try self.headers.getUnfolded("date") orelse return null; return date.parse(value) catch null; } /// The addresses in one header. The caller owns the result. /// /// `gpa` rather than the tree's arena because an address list is often /// wanted for a moment and then dropped, and the tree may outlive a great /// many such moments. pub fn addresses(self: *Part, gpa: Allocator, name: []const u8) Allocator.Error!address.List { const value = try self.headers.getUnfolded(name) orelse return .empty; return address.List.parse(gpa, value); } /// Reparses the `Content-Type` header into `media_type`. Only needed after /// editing that header through `headers` rather than `setContentType`. pub fn refreshContentType(self: *Part, is_digest: bool) Allocator.Error!void { const a = self.allocator(); if (try self.headers.getUnfolded("content-type")) |value| { self.media_type = try MediaType.parse(a, value); } else if (is_digest) { self.media_type = try MediaType.defaultForDigest(a); } else { self.media_type = try MediaType.default(a); } } /// Sets the `Content-Type` header and the cached parse together. pub fn setContentType(self: *Part, value: []const u8) Allocator.Error!void { try self.headers.set("Content-Type", value); self.media_type = try MediaType.parse(self.allocator(), value); } /// The body with its transfer encoding undone. The caller owns the result. /// A part that is not a leaf has no body of its own and gives back an /// empty slice. pub fn decodeAlloc(self: Part, gpa: Allocator) Allocator.Error![]u8 { const raw = switch (self.body) { .raw => |bytes| bytes, else => return gpa.alloc(u8, 0), }; return self.transferEncoding().decodeAlloc(gpa, raw); } /// The parts of a `multipart/report`, or null if this is not one. /// /// RFC 6522 §3 fixes the order — human-readable, machine-readable, and /// optionally the original — so the parts could simply be taken by /// position. They are looked up by media type first and taken by position /// only as a fallback, because a mail system that puts its /// `message/delivery-status` third has still sent a bounce, and a reader /// that insists on the order learns nothing from it. pub fn report(self: *Part) ?Report { const report_type = self.media_type.reportType() orelse if (self.media_type.isReport()) "" else return null; if (self.body != .multipart) return null; const parts = self.body.multipart.parts.items; if (parts.len == 0) return null; var machine: ?*Part = null; var original: ?*Part = null; for (parts[1..]) |part| { if (machine == null and report_type.len != 0 and part.media_type.isType("message") and std.ascii.eqlIgnoreCase(part.media_type.subtype, report_type)) { machine = part; continue; } if (original == null and (part.media_type.isEncapsulatedMessage() or part.media_type.is("text", "rfc822-headers"))) { original = part; } } return .{ .notice = parts[0], .machine = machine orelse (if (parts.len > 1) parts[1] else null), .original = original orelse (if (parts.len > 2) parts[2] else null), }; } /// The decoded body of the first `message/` part under this one, /// for whichever kind of report is being looked for. The caller owns it. /// /// The whole tree is searched rather than just the second part of a /// `multipart/report`, so that a report which has itself been forwarded is /// still found — and so that a mail system which put its machine-readable /// part somewhere other than where RFC 6522 says has still sent one this /// can read. fn reportBody( self: *Part, gpa: Allocator, subtypes: []const []const u8, ) Allocator.Error!?[]u8 { var walker = self.walk(); while (walker.next()) |part| { if (part.body != .raw) continue; if (!part.media_type.isType("message")) continue; for (subtypes) |subtype| { if (!std.ascii.eqlIgnoreCase(part.media_type.subtype, subtype)) continue; return try part.decodeAlloc(gpa); } } return null; } /// The delivery status report somewhere under this part — why a message /// bounced — or null if there is none. The caller owns the result. pub fn deliveryStatus( self: *Part, gpa: Allocator, ) Allocator.Error!?delivery_status.DeliveryStatus { // RFC 6533 defines a UTF-8 flavour of the same thing. const body = try self.reportBody(gpa, &.{ "delivery-status", "global-delivery-status", }) orelse return null; defer gpa.free(body); return try delivery_status.DeliveryStatus.parse(gpa, body); } /// The read receipt somewhere under this part — what became of a message /// after it arrived — or null. The caller owns the result. pub fn dispositionNotification( self: *Part, gpa: Allocator, ) Allocator.Error!?disposition_notification.DispositionNotification { const body = try self.reportBody(gpa, &.{ "disposition-notification", "global-disposition-notification", }) orelse return null; defer gpa.free(body); return try disposition_notification.DispositionNotification.parse(gpa, body); } /// The spam complaint somewhere under this part — RFC 5965, what arrives /// through a feedback loop — or null. The caller owns the result. pub fn feedbackReport( self: *Part, gpa: Allocator, ) Allocator.Error!?feedback_report.FeedbackReport { const body = try self.reportBody(gpa, &.{"feedback-report"}) orelse return null; defer gpa.free(body); return try feedback_report.FeedbackReport.parse(gpa, body); } /// The headers this part carries as `text/rfc822-headers` — RFC 6522 — the /// media type a reporting system uses when it kept the headers of the /// message but not its body. Null if the part is something else. The /// caller owns the result. pub fn rfc822HeadersAlloc(self: Part, gpa: Allocator) Allocator.Error!?Headers { if (!self.media_type.is("text", "rfc822-headers")) return null; if (self.body != .raw) return null; const decoded = try self.decodeAlloc(gpa); defer gpa.free(decoded); return try Headers.parse(gpa, decoded); } /// Makes this part a `multipart/report` of the given kind — /// `delivery-status` for a bounce. The parts go in afterwards, in the /// order RFC 6522 fixes: the explanation, the report, and optionally the /// message it is about. /// /// `boundary` is checked as `makeMultipart` checks it. pub fn makeReport( self: *Part, report_type: []const u8, boundary: []const u8, ) BoundaryError!void { return self.makeMultipartWith("report", boundary, &.{.{ "report-type", report_type }}); } pub fn makeReportRandom( self: *Part, report_type: []const u8, random: std.Random, ) Allocator.Error!void { var buffer: [boundary_length]u8 = undefined; return generated(self.makeReport(report_type, generateBoundary(&buffer, random))); } /// The uuencoded file this part carries, or null if it carries none. /// /// Mail from before MIME put uuencoded files straight into an ordinary /// `text/plain` body, with no `Content-Transfer-Encoding` to describe them /// and no `Content-Disposition` to name them — the `begin` line was the /// whole of the metadata, and a covering note usually sat in front of it. /// Those messages are still in everybody's archives, and to a MIME reader /// the attachment is invisible: the body is text, and the text happens to /// contain the file. /// /// Nothing here does that automatically, because no header says it has /// happened and restructuring a message on a guess is worse than leaving /// it alone. This is the explicit question, and the `begin` line is the /// only answer to it. A part whose `Content-Transfer-Encoding` really is /// uuencode answers it too, so that a caller can ask once rather than /// twice. /// /// Only a text body is examined — or one that declares uuencode — because /// a `begin` line found by chance inside a decoded JPEG is not a file. /// Decoding is the lenient kind: what decoded, decoded. pub fn uuencodedFile(self: Part, gpa: Allocator) Allocator.Error!?UuencodedFile { if (self.body != .raw) return null; const encoding = self.transferEncoding(); if (!self.media_type.isText() and encoding != .uuencode) return null; // A body that declares uuencode has already been through the codec by // the time `decodeAlloc` is done with it, so the `begin` line is in // the raw body rather than in the decoded one. const text = if (encoding == .uuencode) try gpa.dupe(u8, self.body.raw) else try self.decodeAlloc(gpa); defer gpa.free(text); const header = transfer_encoding.uuencodeHeader(text) orelse return null; const name = try gpa.dupe(u8, header.name); errdefer gpa.free(name); var data: Io.Writer.Allocating = .init(gpa); errdefer data.deinit(); transfer_encoding.uudecodeWriter(&data.writer, text) catch return error.OutOfMemory; return .{ .name = name, .mode = header.mode, .data = try data.toOwnedSlice() }; } /// The bytes the body stands for, written onto `w` rather than allocated. /// /// What `decodeAlloc` is for when the answer is going somewhere anyway: an /// attachment reaches a file without a copy of it in memory on the way. /// A part that is not a leaf has no body of its own and writes nothing. pub fn decodeWriter(self: Part, w: *Io.Writer) Io.Writer.Error!void { const raw = switch (self.body) { .raw => |bytes| bytes, else => return, }; return self.transferEncoding().decodeWriter(w, raw); } /// The body decoded and converted to UTF-8, for a `text/*` part. The /// charset rules are the table-free ones described in `encoded_word`: /// UTF-8, US-ASCII and ISO-8859-1 exactly, anything else with invalid /// sequences replaced. The caller owns the result. /// /// A body that declares `format=flowed` is also unflowed — its wrapped /// lines joined back into the paragraphs the author wrote — because that /// is the text, and the line breaks this removes are ones the sender's /// composer put in rather than ones the sender typed. `decodeAlloc` is /// the way to the body as it stands. pub fn textAlloc(self: Part, gpa: Allocator) Allocator.Error![]u8 { const decoded = try self.decodeAlloc(gpa); defer gpa.free(decoded); const utf8 = try transfer_encoding.toUtf8Alloc( gpa, decoded, self.media_type.charset() orelse "us-ascii", ); if (!self.media_type.isFlowed()) return utf8; defer gpa.free(utf8); return flowed.unflowAlloc(gpa, utf8, .{ .delete_space = self.media_type.deleteSpace(), }); } /// Walks this part and everything under it, depth first, this part first. pub fn walk(self: *Part) Walker { return .{ .next_part = self }; } /// The first part whose media type is `type/subtype`, searching depth /// first. pub fn find(self: *Part, type_name: []const u8, subtype_name: []const u8) ?*Part { var walker = self.walk(); while (walker.next()) |part| { if (part.media_type.is(type_name, subtype_name)) return part; } return null; } /// The `text/*` part a reader should show, choosing between the /// alternatives by `preferences` — subtypes in the order the caller would /// rather have them, `&.{ "plain", "html" }` or the other way round. /// /// Two rules that `find` does not know and that everybody writing this by /// hand gets wrong once. An attachment is skipped even when it is /// `text/plain`, because a `notes.txt` somebody attached is not the body /// of the message. And the preference is asked for in full before the tree /// is searched again, so a `multipart/alternative` holding both gives back /// the one that was asked for first rather than the one that appears /// first — which for a caller that wants plain text is the difference /// between plain text and a page of HTML. pub fn findText(self: *Part, preferences: []const []const u8) ?*Part { for (preferences) |wanted| { var walker = self.walk(); while (walker.next()) |part| { if (part.body != .raw) continue; if (part.isAttachment()) continue; if (part.media_type.is("text", wanted)) return part; } } return null; } /// Every part offered as a file, in the order they appear. /// /// What `walk` gives with the two conditions applied that a caller /// otherwise repeats: a container is not an attachment even when it has a /// filename, and a part that is shown inside the message — an image an /// HTML body refers to with `cid:` — is not one either. pub fn attachments(self: *Part) AttachmentIterator { return .{ .walker = self.walk() }; } pub const AttachmentIterator = struct { walker: Walker, pub fn next(self: *AttachmentIterator) ?*Part { while (self.walker.next()) |part| { if (part.body != .raw) continue; if (!part.isAttachment()) continue; return part; } return null; } }; // -- building ---------------------------------------------------------- pub const TextOptions = struct { /// `plain` or `html`, usually. subtype: []const u8 = "plain", /// Declared, not converted: `text` must already be in it. UTF-8 is /// the only sensible default in 2026, and the only charset this /// library can convert back out of without a table. charset: []const u8 = "UTF-8", /// Chosen from the content when null, which is nearly always right. encoding: ?TransferEncoding = null, /// `.flowed` wraps the text as RFC 3676 `format=flowed`, so that a /// reader may rewrap it to its own width instead of showing the /// sender's wrap points. Only meaningful on `text/plain`, and ignored /// on anything else. /// /// **Each line of the text is then a paragraph** — see /// `flowed.flowWriter`, which is particular about that for a reason. format: enum { fixed, flowed } = .fixed, /// Where `.flowed` wraps. flow_width: usize = 72, /// `delsp=yes`. Only useful for a script that does not separate its /// words with spaces. delete_space: bool = false, }; /// Makes this part a `text/*` body. /// /// The text is canonicalised to CRLF first, because RFC 2045 §6.1 defines /// the encodings over canonical form and because a quoted-printable body /// built from LF text has a bare LF in it — which is the one thing the /// encoding exists to prevent. pub fn setText(self: *Part, text: []const u8, options: TextOptions) Allocator.Error!void { const a = self.allocator(); var canonical: Io.Writer.Allocating = .init(a); line_ending.toCanonical(&canonical.writer, text) catch return error.OutOfMemory; var bytes = canonical.written(); // The parameter is only defined on `text/plain`, and wrapping // something that is not prose would be worse than not wrapping it. const flow = options.format == .flowed and std.ascii.eqlIgnoreCase(options.subtype, "plain"); if (flow) { bytes = flowed.flowAlloc(a, bytes, .{ .width = options.flow_width, .delete_space = options.delete_space, }) catch return error.OutOfMemory; } var encoding = options.encoding orelse transfer_encoding.choose(bytes, true); if (flow and options.encoding == null and encoding.isIdentity()) { // Everything format=flowed says is said with trailing whitespace, // and RFC 2045 warns that trailing whitespace is exactly what a // transport may strip. An identity encoding leaves the one signal // the format has out in the open, so an automatic choice upgrades // to quoted-printable, which escapes it. A caller who would rather // have the smaller body can still ask for 7bit by name. encoding = .quoted_printable; } var body: Io.Writer.Allocating = .init(a); encoding.encodeWriter(&body.writer, bytes, .{ .is_text = true }) catch return error.OutOfMemory; var value: Io.Writer.Allocating = .init(a); value.writer.writeAll("text/") catch return error.OutOfMemory; value.writer.writeAll(options.subtype) catch return error.OutOfMemory; parameters.writeParameter(&value.writer, "charset", options.charset, .{}) catch return error.OutOfMemory; if (flow) { parameters.writeParameter(&value.writer, "format", "flowed", .{}) catch return error.OutOfMemory; if (options.delete_space) { parameters.writeParameter(&value.writer, "delsp", "yes", .{}) catch return error.OutOfMemory; } } try self.setContentType(value.written()); try self.headers.set("Content-Transfer-Encoding", encoding.name()); self.body = .{ .raw = body.written() }; } pub const DataOptions = struct { /// Null means guess from `filename`, falling back to /// `application/octet-stream`. Pass one where the type is actually /// known: a guess from a filename is a guess, and this always wins. content_type: ?[]const u8 = null, /// Written as an RFC 2231 parameter, so a name that is neither short /// nor ASCII comes back intact. filename: ?[]const u8 = null, /// `attachment` offers the part as a file; `inline` asks for it to be /// shown where it appears, which is what an image referred to by a /// `Content-ID` wants. disposition: []const u8 = "attachment", /// The `Content-ID` to give the part, for something an HTML body /// refers to with `cid:`. See `Message.embed`, which is the usual way /// in. content_id: ?[]const u8 = null, /// Base64 unless something else is asked for. Choosing from the /// content is available — pass `transfer_encoding.choose(bytes, /// false)` — but for a file it is usually a false economy: a body /// that is 95% ASCII still goes through a transport that may not be /// eight-bit clean. encoding: ?TransferEncoding = null, /// The `size` parameter: how many octets the decoded content is. /// /// Not filled in from the content, deliberately. It is a claim a /// receiver may act on, most mail does not send it, and /// `setDataStreaming` could not know it in any case — so a sender that /// wants to make the claim makes it, by passing `bytes.len`. size: ?u64 = null, /// The `creation-date` and `modification-date` parameters, for a /// file that came from a filesystem and may go back to one. creation_date: ?datetime.DateTime = null, modification_date: ?datetime.DateTime = null, }; /// Makes this part a file: a body of bytes, a media type, and a name. pub fn setData(self: *Part, bytes: []const u8, options: DataOptions) Allocator.Error!void { const encoding = options.encoding orelse .base64; var body: Io.Writer.Allocating = .init(self.allocator()); encoding.encodeWriter(&body.writer, bytes, .{ .name = options.filename }) catch return error.OutOfMemory; try self.setDataHeaders(options, encoding); self.body = .{ .raw = body.written() }; } /// `setData`, reading the file from `r` rather than from a slice. /// /// What this saves is the plain copy: a fifty megabyte attachment is /// encoded as it is read, so the raw bytes are never all in memory at /// once. The *encoded* body still is, because the message tree holds it — /// a body that stayed on disk until the message was written could only be /// written once, and a `Message` is something you can write twice. /// /// The exception is an explicit `.quoted_printable`, which cannot be /// produced a chunk at a time and so buffers the input after all; /// `TransferEncoding.streams` says why, and the default encoding for a /// file is base64, which streams. pub fn setDataStreaming( self: *Part, r: *Io.Reader, options: DataOptions, ) (Allocator.Error || Io.Reader.ShortError)!void { const a = self.allocator(); const encoding = options.encoding orelse .base64; var body: Io.Writer.Allocating = .init(a); if (encoding.streams()) { encoding.encodeStream(r, &body.writer, .{ .name = options.filename }) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, error.ReadFailed => return error.ReadFailed, }; } else { var raw: Io.Writer.Allocating = .init(a); _ = r.streamRemaining(&raw.writer) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, error.ReadFailed => return error.ReadFailed, }; encoding.encodeWriter(&body.writer, raw.written(), .{ .name = options.filename }) catch return error.OutOfMemory; } try self.setDataHeaders(options, encoding); self.body = .{ .raw = body.written() }; } /// The headers that describe a file, which `setData` and /// `setDataStreaming` agree about. fn setDataHeaders( self: *Part, options: DataOptions, encoding: TransferEncoding, ) Allocator.Error!void { const a = self.allocator(); try self.setContentType(options.content_type orelse media_types.forFilename(options.filename)); try self.headers.set("Content-Transfer-Encoding", encoding.name()); if (options.content_id) |id| try self.setContentId(id); var value: Io.Writer.Allocating = .init(a); value.writer.writeAll(options.disposition) catch return error.OutOfMemory; if (options.filename) |name| { parameters.writeParameter(&value.writer, "filename", name, .{}) catch return error.OutOfMemory; } if (options.size) |size| { var digits: [24]u8 = undefined; const text = std.fmt.bufPrint(&digits, "{d}", .{size}) catch unreachable; parameters.writeParameter(&value.writer, "size", text, .{}) catch return error.OutOfMemory; } // A date holds commas and spaces, so it comes out quoted, which is // what RFC 2183 asks for: these three are `quoted-date-time`. inline for (.{ .{ "creation-date", options.creation_date }, .{ "modification-date", options.modification_date }, }) |pair| { if (pair[1]) |when| { var text: [64]u8 = undefined; var w: Io.Writer = .fixed(&text); date.write(&w, when) catch return error.OutOfMemory; parameters.writeParameter(&value.writer, pair[0], w.buffered(), .{}) catch return error.OutOfMemory; } } try self.headers.set("Content-Disposition", value.written()); } /// Makes this part a `multipart/*` with no parts in it yet, using the /// boundary given. `makeMultipartRandom` generates one instead, and is /// what to reach for without a reason to choose. /// /// A boundary RFC 2046 §5.1.1 does not allow is refused with /// `error.InvalidBoundary` — see `isValidBoundary` — rather than written /// into a message that would not parse back into the parts that went in. /// What cannot be checked here is the other half of the rule, that the /// boundary must not appear in the parts: there are none yet, and keeping /// it out of them is the caller's to do. pub fn makeMultipart( self: *Part, subtype: []const u8, boundary: []const u8, ) BoundaryError!void { return self.makeMultipartWith(subtype, boundary, &.{}); } /// `makeMultipart`, plus parameters that belong on the `Content-Type` /// beside the boundary. `multipart/related` is the only subtype in common /// use that has any. fn makeMultipartWith( self: *Part, subtype: []const u8, boundary: []const u8, extra: []const [2][]const u8, ) BoundaryError!void { if (!isValidBoundary(boundary)) return error.InvalidBoundary; const a = self.allocator(); const owned = try a.dupe(u8, boundary); var value: Io.Writer.Allocating = .init(a); value.writer.writeAll("multipart/") catch return error.OutOfMemory; value.writer.writeAll(subtype) catch return error.OutOfMemory; for (extra) |parameter| { parameters.writeParameter(&value.writer, parameter[0], parameter[1], .{}) catch return error.OutOfMemory; } parameters.writeParameter(&value.writer, "boundary", owned, .{}) catch return error.OutOfMemory; try self.setContentType(value.written()); // A container has no encoding of its own: RFC 2045 §6.4 allows a // `multipart` only 7bit, 8bit or binary, and each part carries its // own. _ = self.headers.remove("Content-Transfer-Encoding"); self.body = .{ .multipart = .{ .boundary = owned } }; } /// Makes this part a `multipart/*` with a freshly generated boundary. pub fn makeMultipartRandom( self: *Part, subtype: []const u8, random: std.Random, ) Allocator.Error!void { var buffer: [boundary_length]u8 = undefined; return generated(self.makeMultipart(subtype, generateBoundary(&buffer, random))); } /// Makes this part a `multipart/related` — RFC 2387 — whose parts are one /// document and the resources it refers to with `cid:`. /// /// `root_type` is the media type of the part that is the document, and it /// is not optional: RFC 2387 §3.1 requires the `type` parameter, because a /// reader has to know which of the parts to display before it has looked /// at any of them. The root is the first part unless `start` names another /// by its `Content-ID`. /// /// `boundary` is checked as `makeMultipart` checks it. pub fn makeRelated( self: *Part, root_type: []const u8, boundary: []const u8, start: ?[]const u8, ) BoundaryError!void { if (start) |id| { var bracketed: Io.Writer.Allocating = .init(self.allocator()); bracketed.writer.print("<{s}>", .{bareContentId(id)}) catch return error.OutOfMemory; return self.makeMultipartWith("related", boundary, &.{ .{ "type", root_type }, .{ "start", bracketed.written() }, }); } return self.makeMultipartWith("related", boundary, &.{.{ "type", root_type }}); } pub fn makeRelatedRandom( self: *Part, root_type: []const u8, random: std.Random, ) Allocator.Error!void { var buffer: [boundary_length]u8 = undefined; return generated(self.makeRelated(root_type, generateBoundary(&buffer, random), null)); } pub const AlternativeOptions = struct { /// Declared, not converted, on both parts. charset: []const u8 = "UTF-8", /// The subtype of the second, richer part. `html` unless you have a /// reason. rich_subtype: []const u8 = "html", }; /// Makes this part a `multipart/alternative` holding the same message /// twice: once as plain text and once as something richer. /// /// The plain text goes first. RFC 2046 §5.1.4 puts the parts in increasing /// order of preference and says a reader should show the *last* one it can /// display, so the order is not cosmetic: reversed, every client that can /// render HTML shows the plain text instead. pub fn setAlternative( self: *Part, random: std.Random, plain: []const u8, rich: []const u8, options: AlternativeOptions, ) Allocator.Error!void { try self.makeMultipartRandom("alternative", random); const plain_part = try self.addPart(); try plain_part.setText(plain, .{ .subtype = "plain", .charset = options.charset }); const rich_part = try self.addPart(); try rich_part.setText(rich, .{ .subtype = options.rich_subtype, .charset = options.charset }); } /// Makes this part a `message/rfc822` wrapping a whole message, which is /// how a message is forwarded as an attachment rather than as quoted text. /// /// The part is not copied: it is the tree that is handed in, which must /// live in the same message's memory. `Message.attachMessage` is the way /// in that takes a separate `Message` and copies it. pub fn setMessage(self: *Part, inner: *Part) Allocator.Error!void { try self.setContentType("message/rfc822"); // RFC 2045 §6.4: a `message/rfc822` body may only be 7bit, 8bit or // binary, because the thing inside it has encodings of its own. _ = self.headers.remove("Content-Transfer-Encoding"); self.body = .{ .message = inner }; } /// Adds an empty part to a `multipart/*` and returns it. The pointer stays /// valid for the life of the message. pub fn addPart(self: *Part) Allocator.Error!*Part { std.debug.assert(self.body == .multipart); const a = self.allocator(); const part = try a.create(Part); part.* = .{ .headers = .init(a), .body = .{ .raw = "" }, .media_type = try MediaType.default(a), }; try self.body.multipart.parts.append(a, part); return part; } /// Sets a header whose value is free text, encoding it as RFC 2047 words /// if it is not plain ASCII. `Subject:` is the one everybody wants. pub fn setTextHeader(self: *Part, name: []const u8, text: []const u8) Allocator.Error!void { var out: Io.Writer.Allocating = .init(self.allocator()); encoded_word.encodeIfNeededWriter(&out.writer, text, .{ .first_line_used = name.len + 2, }) catch return error.OutOfMemory; try self.headers.set(name, out.written()); } pub fn setSubject(self: *Part, text: []const u8) Allocator.Error!void { return self.setTextHeader("Subject", text); } /// Sets an address header — `From`, `To`, `Cc` — from mailboxes rather /// than from text, so that a display name containing a comma or a /// non-ASCII character cannot produce a header that means something else. pub fn setAddresses( self: *Part, name: []const u8, mailboxes: []const address.Mailbox, ) Allocator.Error!void { var out: Io.Writer.Allocating = .init(self.allocator()); for (mailboxes, 0..) |mailbox, i| { if (i != 0) out.writer.writeAll(",\r\n ") catch return error.OutOfMemory; mailbox.write(&out.writer) catch return error.OutOfMemory; } try self.headers.set(name, out.written()); } pub fn setDate(self: *Part, when: datetime.DateTime) Allocator.Error!void { var out: Io.Writer.Allocating = .init(self.allocator()); date.write(&out.writer, when) catch return error.OutOfMemory; try self.headers.set("Date", out.written()); } /// Sets a `Message-ID:` of the form ``. /// /// RFC 5322 §3.6.4 requires it to be globally unique, which in practice /// means the domain makes it unique in space and the random part makes it /// unique in time. The domain should be one the sender controls: it is /// what a recipient will use to decide whether two messages are the same /// message. pub fn setMessageId( self: *Part, domain: []const u8, random: std.Random, ) Allocator.Error!void { const id = try randomAddrSpec(self.allocator(), domain, random); var out: Io.Writer.Allocating = .init(self.allocator()); out.writer.print("<{s}>", .{id}) catch return error.OutOfMemory; try self.headers.set("Message-ID", out.written()); } pub fn write(self: Part, w: *Io.Writer) Io.Writer.Error!void { try self.headers.writeFields(w); if (self.headers_terminated) try w.writeAll("\r\n"); switch (self.body) { .raw => |bytes| try w.writeAll(bytes), .message => |inner| try inner.write(w), .multipart => |multipart| try multipart.write(w), } } pub fn format(self: Part, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); } }; /// A depth-first walk over a tree of parts. pub const Walker = struct { /// A fixed stack rather than an allocating one, so that walking a tree /// cannot fail. Deeper than any message a parser here will build, since /// `ParseOptions.max_depth` is smaller; a tree built by hand that is /// deeper than this is walked down to the limit. stack: [max_walk_depth]Frame = undefined, depth: usize = 0, next_part: ?*Part, pub const max_walk_depth = 64; const Frame = union(enum) { list: struct { parts: []const *Part, index: usize }, /// A `message/rfc822` has exactly one child and no list to point at. single: ?*Part, }; pub fn next(self: *Walker) ?*Part { if (self.next_part) |part| { self.next_part = null; self.push(part); return part; } while (self.depth != 0) { const frame = &self.stack[self.depth - 1]; switch (frame.*) { .list => |*list| { if (list.index >= list.parts.len) { self.depth -= 1; continue; } const part = list.parts[list.index]; list.index += 1; self.push(part); return part; }, .single => |maybe| { const part = maybe orelse { self.depth -= 1; continue; }; frame.* = .{ .single = null }; self.push(part); return part; }, } } return null; } fn push(self: *Walker, part: *Part) void { if (self.depth == self.stack.len) return; switch (part.body) { .multipart => |*multipart| { self.stack[self.depth] = .{ .list = .{ .parts = multipart.parts.items, .index = 0 } }; self.depth += 1; }, .message => |inner| { self.stack[self.depth] = .{ .single = inner }; self.depth += 1; }, .raw => {}, } } }; /// A `multipart/*` body: the parts, the delimiter that separates them, and the /// text outside them that nothing reads and everything must preserve. pub const Multipart = struct { /// The boundary as written, without the `--` that precedes it on the wire. boundary: []const u8, /// Text before the first part. RFC 2046 §5.1.1 says it is to be ignored, /// and it is where "This is a multi-part message in MIME format." lives. preamble: []const u8 = "", /// Pointers rather than values, so that a reference handed out by /// `addPart` stays valid when the next part is added. An `ArrayList` of /// values moves its contents as it grows, which for a builder is a /// use-after-free waiting to be written. parts: std.ArrayList(*Part) = .empty, /// Text after the closing delimiter, or null if there was no line ending /// after it at all — which is the difference between a message that ends /// with a newline and one that does not. Empty by default, so that a /// multipart built rather than parsed ends with a line ending, which is /// what every message that was not truncated does. epilogue: ?[]const u8 = "", /// Whether the closing `--boundary--` was there. A truncated message has /// no closing delimiter, and writing one that was never there would claim /// the message is complete. closed: bool = true, pub fn write(self: Multipart, w: *Io.Writer) Io.Writer.Error!void { // No delimiter was found anywhere in the body, so the whole of it is // "preamble" and there is nothing to separate it from. Writing the // line ending that would have gone in front of a delimiter would add // two bytes to the message every time it was opened and saved. if (self.parts.items.len == 0 and !self.closed) return w.writeAll(self.preamble); if (self.preamble.len != 0) { try w.writeAll(self.preamble); try w.writeAll("\r\n"); } for (self.parts.items, 0..) |part, i| { try w.writeAll("--"); try w.writeAll(self.boundary); try w.writeAll("\r\n"); try part.write(w); // The line ending in front of a delimiter belongs to the // delimiter, so the last part of a multipart that was never // closed is not followed by one. if (self.closed or i + 1 < self.parts.items.len) try w.writeAll("\r\n"); } if (!self.closed) return; try w.writeAll("--"); try w.writeAll(self.boundary); try w.writeAll("--"); if (self.epilogue) |epilogue| { try w.writeAll("\r\n"); try w.writeAll(epilogue); } } }; pub const ParseOptions = struct { /// How many entities deep the parser will go before it stops taking a body /// apart and keeps it whole. See the module comment. max_depth: u8 = 32, }; /// Parses a whole message. `source` must outlive nothing: everything is /// copied, so the buffer it came from may be freed immediately. pub fn parse(gpa: Allocator, source: []const u8, options: ParseOptions) Allocator.Error!Message { const arena = try makeArena(gpa); errdefer destroyArena(arena); const a = arena.allocator(); const root = try parsePart(a, try a.dupe(u8, source), false, options, 0); return .{ .arena = arena, .root = root }; } fn makeArena(gpa: Allocator) Allocator.Error!*std.heap.ArenaAllocator { const arena = try gpa.create(std.heap.ArenaAllocator); arena.* = .init(gpa); return arena; } fn destroyArena(arena: *std.heap.ArenaAllocator) void { const gpa = arena.child_allocator; arena.deinit(); gpa.destroy(arena); } /// An empty message: no headers, no body. What a program that is building one /// starts from. pub fn init(gpa: Allocator) Allocator.Error!Message { const arena = try makeArena(gpa); errdefer destroyArena(arena); const a = arena.allocator(); return .{ .arena = arena, .root = .{ .headers = .init(a), .body = .{ .raw = "" }, .media_type = try MediaType.default(a), }, }; } pub fn deinit(self: *Message) void { destroyArena(self.arena); self.* = undefined; } /// The allocator the whole tree lives in. Anything put into the message must /// come from here or be copied into it. pub fn allocator(self: *Message) Allocator { return self.arena.allocator(); } pub fn write(self: Message, w: *Io.Writer) Io.Writer.Error!void { return self.root.write(w); } pub fn format(self: Message, w: *Io.Writer) Io.Writer.Error!void { return self.root.write(w); } /// The message as one allocated buffer. The caller owns it. pub fn toBytesAlloc(self: Message, gpa: Allocator) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); self.write(&out.writer) catch return error.OutOfMemory; return out.toOwnedSlice(); } /// The length of a boundary made by `generateBoundary`: a fixed prefix and 128 /// random bits in hexadecimal. pub const boundary_length = 2 + 32; /// Writes a delimiter that will not appear in the parts it separates. /// /// RFC 2046 §5.1.1 requires exactly that and offers no way to guarantee it, so /// every implementation guesses with random bits and this one guesses with /// 128 of them. The `=_` prefix is the convention: neither character can /// appear in a base64 or quoted-printable body except as the start of an /// escape, so the boundary cannot collide with encoded content at all, and /// only with an unencoded body that happens to contain it. pub fn generateBoundary(buffer: *[boundary_length]u8, random: std.Random) []u8 { comptime std.debug.assert(boundary_length <= 70); const hex = "0123456789abcdef"; buffer[0] = '='; buffer[1] = '_'; var bytes: [16]u8 = undefined; random.bytes(&bytes); for (bytes, 0..) |b, i| { buffer[2 + i * 2] = hex[b >> 4]; buffer[3 + i * 2] = hex[b & 0xf]; } return buffer; } /// What a function that takes the caller's boundary can fail with. pub const BoundaryError = Allocator.Error || error{ /// Not a boundary RFC 2046 allows. See `isValidBoundary`. InvalidBoundary, }; /// Whether RFC 2046 §5.1.1 allows `boundary`: one to seventy of its /// characters — letters, digits, `'()+_,-./:=?` and the space — and not /// ending in a space. /// /// Anything else breaks the message in a way nothing downstream can repair. /// A line ending in a boundary ends the delimiter line early and turns the /// rest of it into body; a trailing space is stripped by the transports that /// strip trailing whitespace, after which no delimiter matches; and a /// boundary longer than seventy characters is one a reader is entitled to /// truncate. pub fn isValidBoundary(boundary: []const u8) bool { if (boundary.len == 0 or boundary.len > 70) return false; if (boundary[boundary.len - 1] == ' ') return false; for (boundary) |c| switch (c) { '0'...'9', 'a'...'z', 'A'...'Z' => {}, '\'', '(', ')', '+', '_', ',', '-', '.', '/', ':', '=', '?', ' ' => {}, else => return false, }; return true; } /// The result of a function handed a boundary from `generateBoundary`, which /// is always one `isValidBoundary` accepts. fn generated(result: BoundaryError!void) Allocator.Error!void { result catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidBoundary => unreachable, }; } /// `local@domain`, with 128 random bits as the local part. What a /// `Message-ID` and a `Content-ID` are both made of. fn randomAddrSpec( a: Allocator, domain: []const u8, random: std.Random, ) Allocator.Error![]const u8 { var bytes: [16]u8 = undefined; random.bytes(&bytes); var out: Io.Writer.Allocating = .init(a); for (bytes) |b| out.writer.print("{x:0>2}", .{b}) catch return error.OutOfMemory; out.writer.writeByte('@') catch return error.OutOfMemory; out.writer.writeAll(domain) catch return error.OutOfMemory; return out.written(); } /// An identifier with its `cid:` scheme, its angle brackets and its /// surrounding whitespace removed, whichever of them were there. fn bareContentId(id: []const u8) []const u8 { var text = std.mem.trim(u8, id, " \t\r\n"); if (std.ascii.startsWithIgnoreCase(text, "cid:")) text = text[4..]; text = std.mem.trim(u8, text, " \t\r\n"); if (text.len >= 2 and text[0] == '<' and text[text.len - 1] == '>') { text = text[1 .. text.len - 1]; } return text; } /// Adds `MIME-Version: 1.0` if it is not already there. /// /// It belongs on the message and nowhere else: a part that carries one is /// malformed, which is why this is on `Message` and not on `Part`. pub fn ensureMimeVersion(self: *Message) Allocator.Error!void { if (self.root.headers.has("mime-version")) return; try self.root.headers.append("MIME-Version", "1.0"); } /// Makes the message a `text/*` body. See `Part.setText`. pub fn setText(self: *Message, text: []const u8, options: Part.TextOptions) Allocator.Error!void { try self.root.setText(text, options); try self.ensureMimeVersion(); } /// Makes the message a `multipart/*` with no parts yet. See /// `Part.makeMultipart`, including for what it refuses. pub fn makeMultipart( self: *Message, subtype: []const u8, boundary: []const u8, ) BoundaryError!void { try self.root.makeMultipart(subtype, boundary); try self.ensureMimeVersion(); } /// Makes the message a `multipart/*` with a freshly generated boundary. pub fn makeMultipartRandom( self: *Message, subtype: []const u8, random: std.Random, ) Allocator.Error!void { var buffer: [boundary_length]u8 = undefined; return generated(self.makeMultipart(subtype, generateBoundary(&buffer, random))); } /// Moves the message's body, and every header that described it, down into a /// part of its own — which is the first half of turning a message that has a /// body into a message that has parts. /// /// The `Content-*` headers move with it because that is what they describe: /// the text, not the container that is about to hold the text and something /// else. Leaving a `Content-Transfer-Encoding: base64` on a `multipart` is how /// a message becomes unreadable. /// /// The caller must give the root a new `Content-Type` and put the returned /// part into it; `makeMixed` and `makeRelated` are the two that do. fn wrapBody(self: *Message) Allocator.Error!*Part { const a = self.allocator(); const inner = try a.create(Part); inner.* = .{ .headers = .init(a), .body = self.root.body, .media_type = self.root.media_type, // The body goes down with its separator; the container above it is // being written fresh and always has one. .headers_terminated = self.root.headers_terminated, }; self.root.headers_terminated = true; var i: usize = 0; while (i < self.root.headers.fields.items.len) { const f = self.root.headers.fields.items[i]; if (std.ascii.startsWithIgnoreCase(f.name, "content-")) { try inner.headers.appendRaw(f.name, f.value); _ = self.root.headers.remove(f.name); } else { i += 1; } } return inner; } /// Turns a message that has a body into a `multipart/mixed` whose first part /// is that body, and returns the new first part. /// /// This is what happens when somebody attaches a file to a message they have /// already written. pub fn makeMixed(self: *Message, random: std.Random) Allocator.Error!*Part { const inner = try self.wrapBody(); try self.root.makeMultipartRandom("mixed", random); try self.root.body.multipart.parts.append(self.allocator(), inner); try self.ensureMimeVersion(); return inner; } /// Turns a message that has a body into a `multipart/related` whose root part /// is that body, and returns the root part. /// /// The `type` parameter is filled in from what the body already was, which is /// the whole reason this cannot simply be `makeMultipart("related", ...)`: /// RFC 2387 §3.1 requires the parameter, and only the message knows what to /// put in it. pub fn makeRelated(self: *Message, random: std.Random) Allocator.Error!*Part { const a = self.allocator(); const inner = try self.wrapBody(); var root_type: Io.Writer.Allocating = .init(a); root_type.writer.print("{s}/{s}", .{ inner.media_type.type, inner.media_type.subtype, }) catch return error.OutOfMemory; var buffer: [boundary_length]u8 = undefined; try generated(self.root.makeRelated(root_type.written(), generateBoundary(&buffer, random), null)); try self.root.body.multipart.parts.append(a, inner); try self.ensureMimeVersion(); return inner; } /// Makes the message a `multipart/alternative` holding the same thing as plain /// text and as HTML. See `Part.setAlternative`. pub fn setAlternative( self: *Message, random: std.Random, plain: []const u8, rich: []const u8, options: Part.AlternativeOptions, ) Allocator.Error!void { try self.root.setAlternative(random, plain, rich, options); try self.ensureMimeVersion(); } /// Sets `In-Reply-To` and `References` so that this message threads as a reply /// to `parent`. See `Part.setInReplyTo`. pub fn setInReplyTo( self: *Message, parent: *Message, options: Part.ThreadOptions, ) Allocator.Error!void { return self.root.setInReplyTo(&parent.root, options); } /// Adds a `Received:` trace field at the top of the message, which is what an /// SMTP server does to a message it has just accepted. See `Part.addReceived`. /// /// The other half of a trace block, the `Return-Path:`, is written only by the /// system making final delivery, and is `headers.prepend("Return-Path", ...)` /// on the root — above the `Received:` this added, which is the order RFC 5322 /// §3.6.7 gives. pub fn addReceived(self: *Message, received: received_field.Received) Allocator.Error!void { return self.root.addReceived(received); } /// A fresh `Content-ID`, in the form a `cid:` URL carries it: `local@domain`, /// with no angle brackets and no scheme. /// /// Get one of these *before* writing the HTML that refers to it, put /// `cid:` and it into the `src`, and hand the same string to `embed`. The /// alternative — embedding first and reading the identifier back — works too, /// but then the HTML has to be written afterwards. /// /// The domain is never resolved by anything: a `Content-ID` is unique, not /// reachable. `example.invalid` is the honest default (RFC 2606 reserves /// `.invalid` for exactly this), and a sender with a domain of its own should /// pass it, because a Content-ID that escapes into a wider world is easier to /// trace when it says where it came from. pub fn newContentId( self: *Message, domain: []const u8, random: std.Random, ) Allocator.Error![]const u8 { return randomAddrSpec(self.allocator(), domain, random); } pub const EmbedOptions = struct { /// Null means guess from `filename`. content_type: ?[]const u8 = null, filename: ?[]const u8 = null, /// The identifier the HTML refers to with `cid:`. Generated under /// `domain` if null, and readable afterwards from the returned part's /// `contentId`. content_id: ?[]const u8 = null, /// Only used when `content_id` is null. See `newContentId`. domain: []const u8 = "example.invalid", encoding: ?TransferEncoding = null, }; /// Adds a resource that the message's body refers to with `cid:` — an image /// inside an HTML body, most of the time — making the message a /// `multipart/related` first if it is not one already. /// /// The part is `inline` rather than an attachment, which is what stops a /// client from listing the logo of a signature beside the file somebody /// actually meant to send. pub fn embed( self: *Message, random: std.Random, bytes: []const u8, options: EmbedOptions, ) Allocator.Error!*Part { if (!self.root.media_type.is("multipart", "related")) _ = try self.makeRelated(random); const part = try self.root.addPart(); try part.setData(bytes, .{ .content_type = options.content_type, .filename = options.filename, .disposition = "inline", .content_id = options.content_id orelse try self.newContentId(options.domain, random), .encoding = options.encoding, }); return part; } /// Attaches a file, making the message a `multipart/mixed` first if it is not /// one already. Returns the part that was added. pub fn attach( self: *Message, random: std.Random, bytes: []const u8, options: Part.DataOptions, ) Allocator.Error!*Part { // Not merely "is it a multipart": attaching a file to a // `multipart/alternative` by adding a part to it would claim the file was // another rendering of the message, and a reader showing the last // alternative it understands would show the attachment instead of the // text. if (!self.root.media_type.is("multipart", "mixed")) _ = try self.makeMixed(random); const part = try self.root.addPart(); try part.setData(bytes, options); return part; } /// Attaches a file read from `r`, making the message a `multipart/mixed` /// first if it is not one already. See `Part.setDataStreaming` for what this /// saves and what it does not. pub fn attachStreaming( self: *Message, random: std.Random, r: *Io.Reader, options: Part.DataOptions, ) (Allocator.Error || Io.Reader.ShortError)!*Part { if (!self.root.media_type.is("multipart", "mixed")) _ = try self.makeMixed(random); const part = try self.root.addPart(); try part.setDataStreaming(r, options); return part; } /// Attaches a whole message as `message/rfc822`, which is how a message is /// forwarded as an attachment rather than as quoted text. /// /// `forwarded` is copied into this message's memory, so it may be freed /// afterwards. pub fn attachMessage( self: *Message, random: std.Random, forwarded: Message, options: ParseOptions, ) Allocator.Error!*Part { const a = self.allocator(); const bytes = try forwarded.toBytesAlloc(a); const inner = try a.create(Part); inner.* = try parsePart(a, bytes, false, options, 0); if (!self.root.media_type.is("multipart", "mixed")) _ = try self.makeMixed(random); const part = try self.root.addPart(); try part.setMessage(inner); return part; } fn parsePart( a: Allocator, source: []const u8, is_digest: bool, options: ParseOptions, depth: u8, ) Allocator.Error!Part { const split = splitHeaders(source); var part: Part = .{ .headers = try Headers.parse(a, source[0..split.header_end]), .body = .{ .raw = source[split.body_start..] }, .media_type = undefined, .headers_terminated = split.terminated, }; try part.refreshContentType(is_digest); if (depth >= options.max_depth) return part; if (part.media_type.isMultipart()) { if (part.media_type.boundary()) |boundary| { if (boundary.len != 0) { part.body = .{ .multipart = try parseMultipart( a, source[split.body_start..], boundary, part.media_type.is("multipart", "digest"), options, depth, ) }; } } // A `multipart/*` with no boundary cannot be taken apart at all, and // the body stays whole. That is a defect in the message rather than a // failure to parse it. return part; } if (part.media_type.isEncapsulatedMessage()) { // The body of a `message/rfc822` may itself be transfer-encoded, which // RFC 2045 §6.4 forbids and which happens anyway. const decoded = try part.transferEncoding().decodeAlloc(a, source[split.body_start..]); // An empty body is not a message. Opening one anyway would put a part // in the tree that nothing sent — a `text/plain` by default, which // `find` would then hand back to a caller looking for the text. if (decoded.len != 0) { const inner = try a.create(Part); inner.* = try parsePart(a, decoded, false, options, depth + 1); part.body = .{ .message = inner }; } } return part; } const HeaderSplit = struct { header_end: usize, body_start: usize, /// Whether a blank line was found. Without one there is no body, and /// writing the message back out must not add the line that would create /// one. terminated: bool, }; /// Finds the blank line. A message with no blank line at all is all headers /// and no body, which is what a truncated message and a bare `Content-Type` /// probe both look like. fn splitHeaders(source: []const u8) HeaderSplit { var i: usize = 0; while (i < source.len) { const nl = std.mem.findScalarPos(u8, source, i, '\n') orelse break; const text_end = if (nl > i and source[nl - 1] == '\r') nl - 1 else nl; if (text_end == i) return .{ .header_end = i, .body_start = nl + 1, .terminated = true }; i = nl + 1; } return .{ .header_end = source.len, .body_start = source.len, .terminated = false }; } fn parseMultipart( a: Allocator, body: []const u8, boundary: []const u8, is_digest: bool, options: ParseOptions, depth: u8, ) Allocator.Error!Multipart { var multipart: Multipart = .{ .boundary = boundary, .closed = false }; var index: usize = 0; var content_start: ?usize = null; while (findDelimiter(body, boundary, index)) |delimiter| { // Trimmed within what lies since the last delimiter and no further // back: a part that is empty has no line ending of its own, and the // one in front of it is the previous delimiter's. const from = content_start orelse 0; const content_end = from + trimOneLineEnding(body[from..delimiter.line_start]); if (content_start) |start| { // No depth check here: `parsePart` stops taking a body apart once // it reaches the limit, and skipping the part instead would drop // it from the tree and from anything written back out. const part = try a.create(Part); part.* = try parsePart(a, body[start..content_end], is_digest, options, depth + 1); try multipart.parts.append(a, part); } else { multipart.preamble = body[0..content_end]; } if (delimiter.closing) { multipart.closed = true; multipart.epilogue = if (delimiter.next <= body.len and delimiter.had_line_end) body[delimiter.next..] else null; return multipart; } content_start = delimiter.next; index = delimiter.next; } // No closing delimiter: whatever is left is the last part, or the whole // body is a preamble with no parts in it at all. if (content_start) |start| { const part = try a.create(Part); part.* = try parsePart(a, body[start..], is_digest, options, depth + 1); try multipart.parts.append(a, part); } else { multipart.preamble = body; } return multipart; } const Delimiter = struct { /// Where the `--boundary` line begins. line_start: usize, /// Where the line after it begins. next: usize, /// Whether it ended in `--`, closing the multipart. closing: bool, /// Whether there was a line ending after the delimiter line. had_line_end: bool, }; /// Finds the next `--boundary` on a line of its own. /// /// The whole line must be the delimiter: RFC 2046 §5.1.1 allows trailing /// whitespace after it and nothing else, and without that check a boundary /// that is a prefix of a longer one — which is exactly what `--=_Part_1` and /// `--=_Part_12` are — would match in the wrong place. fn findDelimiter(body: []const u8, boundary: []const u8, from: usize) ?Delimiter { var line_start = from; while (line_start <= body.len) { const nl = std.mem.findScalarPos(u8, body, line_start, '\n'); const text_end = if (nl) |at| (if (at > line_start and body[at - 1] == '\r') at - 1 else at) else body.len; const line = body[line_start..text_end]; if (std.mem.startsWith(u8, line, "--") and std.mem.startsWith(u8, line[2..], boundary)) { var rest = line[2 + boundary.len ..]; const closing = std.mem.startsWith(u8, rest, "--"); if (closing) rest = rest[2..]; if (isBlank(rest)) return .{ .line_start = line_start, .next = if (nl) |at| at + 1 else body.len, .closing = closing, .had_line_end = nl != null, }; } if (nl) |at| line_start = at + 1 else return null; } return null; } fn isBlank(text: []const u8) bool { for (text) |c| if (c != ' ' and c != '\t' and c != '\r') return false; return true; } /// Removes the one line ending that belongs to the delimiter rather than to /// the part before it. RFC 2046 is explicit that the CRLF in front of a /// boundary is part of the boundary, which is why a body part never ends with /// a blank line it did not have. fn trimOneLineEnding(text: []const u8) usize { if (std.mem.endsWith(u8, text, "\r\n")) return text.len - 2; if (std.mem.endsWith(u8, text, "\n")) return text.len - 1; return text.len; } test "a message with no MIME in it at all" { var message: Message = try .parse(testing.allocator, "From: jeff@example.com\r\n" ++ "Subject: hello\r\n" ++ "\r\n" ++ "This is the body.\r\n", .{}); defer message.deinit(); try testing.expectEqualStrings("hello", (try message.root.subject()).?); try testing.expect(message.root.media_type.is("text", "plain")); try testing.expectEqualStrings("us-ascii", message.root.media_type.charset().?); try testing.expectEqualStrings("This is the body.\r\n", message.root.body.raw); } test "a quoted-printable body" { var message: Message = try .parse(testing.allocator, "Content-Type: text/plain; charset=UTF-8\r\n" ++ "Content-Transfer-Encoding: quoted-printable\r\n" ++ "\r\n" ++ "caf=C3=A9\r\n", .{}); defer message.deinit(); const text = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings("café\r\n", text); } test "a part with nothing in it, between two delimiters" { // The line ending in front of the second delimiter is the first one's, // and the empty part between them has none of its own to give up. for ([_][]const u8{ "\r\n", "\n" }) |eol| { const source = try std.mem.concat(testing.allocator, u8, &.{ "Content-Type: multipart/mixed; boundary=B\r\n\r\n--B", eol, "--B--\r\n", }); defer testing.allocator.free(source); var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const parts = message.root.body.multipart.parts.items; try testing.expectEqual(1, parts.len); try testing.expectEqualStrings("", parts[0].body.raw); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var again: Message = try .parse(testing.allocator, written, .{}); defer again.deinit(); try testing.expectEqual(1, again.root.body.multipart.parts.items.len); } } test "a multipart message" { const source = "From: jeff@example.com\r\n" ++ "Content-Type: multipart/alternative; boundary=\"BOUND\"\r\n" ++ "\r\n" ++ "This is a multi-part message in MIME format.\r\n" ++ "--BOUND\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "plain text\r\n" ++ "--BOUND\r\n" ++ "Content-Type: text/html\r\n" ++ "\r\n" ++ "

html

\r\n" ++ "--BOUND--\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const multipart = message.root.body.multipart; try testing.expectEqualStrings("BOUND", multipart.boundary); try testing.expectEqualStrings("This is a multi-part message in MIME format.", multipart.preamble); try testing.expectEqual(2, multipart.parts.items.len); try testing.expectEqualStrings("plain text", multipart.parts.items[0].body.raw); try testing.expectEqualStrings("

html

", multipart.parts.items[1].body.raw); try testing.expect(multipart.closed); // And it comes back out exactly as it went in. const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); } test "a boundary that is a prefix of another" { const source = "Content-Type: multipart/mixed; boundary=\"=_P1\"\r\n" ++ "\r\n" ++ "--=_P1\r\n" ++ "\r\n" ++ "--=_P12 is not a delimiter\r\n" ++ "--=_P1--\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const multipart = message.root.body.multipart; try testing.expectEqual(1, multipart.parts.items.len); try testing.expectEqualStrings("--=_P12 is not a delimiter", multipart.parts.items[0].body.raw); } test "nested multiparts and finding a part" { const source = "Content-Type: multipart/mixed; boundary=\"OUT\"\r\n" ++ "\r\n" ++ "--OUT\r\n" ++ "Content-Type: multipart/alternative; boundary=\"IN\"\r\n" ++ "\r\n" ++ "--IN\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "the text\r\n" ++ "--IN\r\n" ++ "Content-Type: text/html\r\n" ++ "\r\n" ++ "

the text

\r\n" ++ "--IN--\r\n" ++ "--OUT\r\n" ++ "Content-Type: application/pdf\r\n" ++ "Content-Disposition: attachment; filename=\"report.pdf\"\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "\r\n" ++ "cGRm\r\n" ++ "--OUT--\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const text = message.root.find("text", "plain").?; try testing.expectEqualStrings("the text", text.body.raw); const pdf = message.root.find("application", "pdf").?; try testing.expect(pdf.isAttachment()); try testing.expectEqualStrings("report.pdf", (try pdf.filename()).?); const decoded = try pdf.decodeAlloc(testing.allocator); defer testing.allocator.free(decoded); try testing.expectEqualStrings("pdf", decoded); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); } test "an attached message" { const source = "Content-Type: message/rfc822\r\n" ++ "\r\n" ++ "From: alice@example.net\r\n" ++ "Subject: the original\r\n" ++ "\r\n" ++ "the original body\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const inner = message.root.body.message; try testing.expectEqualStrings("the original", (try inner.subject()).?); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); } test "a truncated multipart" { const source = "Content-Type: multipart/mixed; boundary=\"B\"\r\n" ++ "\r\n" ++ "--B\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "the message stops here"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const multipart = message.root.body.multipart; try testing.expectEqual(1, multipart.parts.items.len); try testing.expect(!multipart.closed); // Not claiming a closing delimiter that was never there. const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); } test "a multipart with no boundary keeps its body whole" { var message: Message = try .parse( testing.allocator, "Content-Type: multipart/mixed\r\n\r\nwhatever this is\r\n", .{}, ); defer message.deinit(); try testing.expectEqualStrings("whatever this is\r\n", message.root.body.raw); } test "a part of a digest defaults to message/rfc822" { const source = "Content-Type: multipart/digest; boundary=\"B\"\r\n" ++ "\r\n" ++ "--B\r\n" ++ "\r\n" ++ "From: alice@example.net\r\n" ++ "Subject: forwarded\r\n" ++ "\r\n" ++ "body\r\n" ++ "--B--\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const part = message.root.body.multipart.parts.items[0]; try testing.expect(part.media_type.is("message", "rfc822")); try testing.expectEqualStrings("forwarded", (try part.body.message.subject()).?); } test "nesting stops at the depth limit" { var buffer: Io.Writer.Allocating = .init(testing.allocator); defer buffer.deinit(); for (0..100) |i| { try buffer.writer.print( "Content-Type: multipart/mixed; boundary=\"B{d}\"\r\n\r\n--B{d}\r\n", .{ i, i }, ); } var message: Message = try .parse(testing.allocator, buffer.written(), .{ .max_depth = 8 }); defer message.deinit(); var depth: usize = 0; var part = &message.root; while (part.body == .multipart and part.body.multipart.parts.items.len != 0) { depth += 1; part = part.body.multipart.parts.items[0]; } try testing.expect(depth <= 8); } test "the walk visits everything once" { const source = "Content-Type: multipart/mixed; boundary=\"OUT\"\r\n\r\n" ++ "--OUT\r\nContent-Type: multipart/alternative; boundary=\"IN\"\r\n\r\n" ++ "--IN\r\nContent-Type: text/plain\r\n\r\na\r\n" ++ "--IN\r\nContent-Type: text/html\r\n\r\nb\r\n" ++ "--IN--\r\n" ++ "--OUT\r\nContent-Type: image/png\r\n\r\nc\r\n" ++ "--OUT--\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); var seen: std.ArrayList([]const u8) = .empty; defer seen.deinit(testing.allocator); var walker = message.root.walk(); while (walker.next()) |part| try seen.append(testing.allocator, part.media_type.subtype); try testing.expectEqual(5, seen.items.len); try testing.expectEqualStrings("mixed", seen.items[0]); try testing.expectEqualStrings("alternative", seen.items[1]); try testing.expectEqualStrings("plain", seen.items[2]); try testing.expectEqualStrings("html", seen.items[3]); try testing.expectEqualStrings("png", seen.items[4]); } test "building a plain message" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.root.setAddresses("From", &.{ .{ .display_name = "Jeff Ollie", .local_part = "jeff", .domain = "example.com" }, }); try message.root.setAddresses("To", &.{ .{ .local_part = "alice", .domain = "example.net" }, .{ .display_name = "Bob, Robert", .local_part = "bob", .domain = "example.org" }, }); try message.root.setSubject("Lunch"); var when: datetime.DateTime = .{ .year = 2003, .month = .Jul, .day = 1, .hour = 10, .minute = 52, .second = 37, .offset = 2 * 60 * 60, }; when.updateDayOfWeek(); try message.root.setDate(when); try message.setText("Shall we?\n", .{}); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings( "From: Jeff Ollie \r\n" ++ "To: alice@example.net,\r\n" ++ " \"Bob, Robert\" \r\n" ++ "Subject: Lunch\r\n" ++ "Date: Tue, 01 Jul 2003 10:52:37 +0200\r\n" ++ "Content-Type: text/plain;\r\n" ++ " charset=UTF-8\r\n" ++ "Content-Transfer-Encoding: 7bit\r\n" ++ "MIME-Version: 1.0\r\n" ++ "\r\n" ++ "Shall we?\r\n", written, ); } test "a subject and a name that are not ASCII" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.root.setSubject("Grüße aus München"); try message.root.setAddresses("From", &.{ .{ .display_name = "José García", .local_part = "jose", .domain = "example.com" }, }); try message.setText("Schöne Grüße\n", .{}); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); // Every line is ASCII and short enough, which is the whole point of the // encoding. var lines = std.mem.splitSequence(u8, written, "\r\n"); while (lines.next()) |line| { try testing.expect(line.len <= 998); for (line) |c| try testing.expect(c < 0x80); } // And it reads back as what went in. var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); try testing.expectEqualStrings("Grüße aus München", (try read.root.subject()).?); var from = try read.root.addresses(testing.allocator, "from"); defer from.deinit(testing.allocator); try testing.expectEqualStrings("José García", from.addresses[0].mailbox.display_name.?); const text = try read.root.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings("Schöne Grüße\r\n", text); } test "attaching a file to a message that already has a body" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("Here is the report.\n", .{}); var prng: std.Random.DefaultPrng = .init(0xa77ac4); _ = try message.attach(prng.random(), "%PDF-1.4 not really", .{ .content_type = "application/pdf", .filename = "the café report.pdf", }); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); try testing.expect(read.root.media_type.is("multipart", "mixed")); try testing.expectEqual(2, read.root.body.multipart.parts.items.len); // The text moved down into a part of its own, and the container kept no // `Content-Transfer-Encoding` of its own. const text = read.root.find("text", "plain").?; const body = try text.textAlloc(testing.allocator); defer testing.allocator.free(body); try testing.expectEqualStrings("Here is the report.\r\n", body); try testing.expectEqual(null, read.root.headers.get("content-transfer-encoding")); const pdf = read.root.find("application", "pdf").?; try testing.expect(pdf.isAttachment()); try testing.expectEqualStrings("the café report.pdf", (try pdf.filename()).?); const bytes = try pdf.decodeAlloc(testing.allocator); defer testing.allocator.free(bytes); try testing.expectEqualStrings("%PDF-1.4 not really", bytes); } test "building a multipart/alternative by hand" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.makeMultipart("alternative", "BOUND"); const plain = try message.root.addPart(); try plain.setText("the text", .{}); const html = try message.root.addPart(); try html.setText("

the text

", .{ .subtype = "html" }); // The pointer handed out first is still good after the second part was // added. try testing.expect(plain.media_type.is("text", "plain")); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings( "Content-Type: multipart/alternative;\r\n" ++ " boundary=BOUND\r\n" ++ "MIME-Version: 1.0\r\n" ++ "\r\n" ++ "--BOUND\r\n" ++ "Content-Type: text/plain;\r\n charset=UTF-8\r\n" ++ "Content-Transfer-Encoding: 7bit\r\n" ++ "\r\n" ++ "the text\r\n" ++ "--BOUND\r\n" ++ "Content-Type: text/html;\r\n charset=UTF-8\r\n" ++ "Content-Transfer-Encoding: 7bit\r\n" ++ "\r\n" ++ "

the text

\r\n" ++ "--BOUND--\r\n", written, ); } test "a boundary RFC 2046 does not allow is refused" { try testing.expect(isValidBoundary("B")); try testing.expect(isValidBoundary("simple boundary")); try testing.expect(isValidBoundary("'()+_,-./:=?")); try testing.expect(isValidBoundary(&@as([70]u8, @splat('x')))); try testing.expect(!isValidBoundary("")); try testing.expect(!isValidBoundary(&@as([71]u8, @splat('x')))); try testing.expect(!isValidBoundary("trailing space ")); try testing.expect(!isValidBoundary("line\r\nbreak")); try testing.expect(!isValidBoundary("\"quoted\"")); try testing.expect(!isValidBoundary("caf\xc3\xa9")); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("unchanged", .{}); const before = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(before); // Refused before anything is touched: the part is what it was. try testing.expectError(error.InvalidBoundary, message.makeMultipart("mixed", "B\r\nX-Injected: yes")); try testing.expectError(error.InvalidBoundary, message.root.makeRelated("text/html", "", null)); try testing.expectError(error.InvalidBoundary, message.root.makeReport("delivery-status", "trailing ")); const after = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(after); try testing.expectEqualStrings(before, after); } test "a generated boundary" { var prng: std.Random.DefaultPrng = .init(0xb0117); var first: [boundary_length]u8 = undefined; var second: [boundary_length]u8 = undefined; _ = generateBoundary(&first, prng.random()); _ = generateBoundary(&second, prng.random()); try testing.expect(!std.mem.eql(u8, &first, &second)); try testing.expectEqualStrings("=_", first[0..2]); // RFC 2046 §5.1.1 gives the characters a boundary may use, and `=` and // `_` are both among them. `=` is not an RFC 2045 token character, so the // parameter comes out quoted, which is legal and is what most mail does. for (first) |c| try testing.expect(std.mem.findScalar( u8, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'()+_,-./:=?", c, ) != null); try testing.expect(isValidBoundary(&first)); try testing.expect(isValidBoundary(&second)); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.makeMultipartRandom("mixed", prng.random()); const part = try message.root.addPart(); try part.setText("hello", .{}); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); try testing.expectEqual(1, read.root.body.multipart.parts.items.len); try testing.expectEqualStrings("hello", read.root.body.multipart.parts.items[0].body.raw); } test "a message with a binary body" { var bytes: [512]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xf11e); prng.random().bytes(&bytes); var message: Message = try .init(testing.allocator); defer message.deinit(); _ = try message.attach(prng.random(), &bytes, .{ .filename = "data.bin" }); try message.root.setMessageId("example.com", prng.random()); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); const part = read.root.find("application", "octet-stream").?; const decoded = try part.decodeAlloc(testing.allocator); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, &bytes, decoded); try testing.expect(std.mem.startsWith(u8, read.root.headers.get("message-id").?, "<")); } test "a multipart with no delimiter in it does not grow" { // It used to gain two bytes every time it was opened and saved: the whole // body is "preamble", and the line ending that would have gone in front of // a delimiter was written even though there was no delimiter to precede. const source = "Content-Type: multipart/mixed; boundary=NOTHERE\r\n" ++ "\r\n" ++ "--OTHER\r\n" ++ "\r\n" ++ "a body with no delimiter of its own\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); } test "a Content-ID survives the brackets" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.root.setContentId("logo@example.com"); try testing.expectEqualStrings("", message.root.headers.get("content-id").?); try testing.expectEqualStrings("logo@example.com", message.root.contentId().?); // However it is handed over. for ([_][]const u8{ "logo@example.com", "", "cid:logo@example.com", " " }) |form| { try message.root.setContentId(form); try testing.expectEqualStrings("logo@example.com", message.root.contentId().?); } // And it cannot end the header line or close its own brackets. try message.root.setContentId("a>\r\nBcc: victim@evil.test", message.root.headers.get("content-id").?); } test "an alternative puts the plain text first" { var prng: std.Random.DefaultPrng = .init(0xa17e); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setAlternative(prng.random(), "the text", "

the text

", .{}); try testing.expect(message.root.media_type.is("multipart", "alternative")); const parts = message.root.body.multipart.parts.items; try testing.expectEqual(2, parts.len); // RFC 2046 §5.1.4: increasing order of preference, and a reader shows the // last one it understands. Reversed, every HTML client shows plain text. try testing.expect(parts[0].media_type.is("text", "plain")); try testing.expect(parts[1].media_type.is("text", "html")); } test "an embedded image is related, inline and findable by its cid" { var prng: std.Random.DefaultPrng = .init(0x13a9e); var message: Message = try .init(testing.allocator); defer message.deinit(); const cid = try message.newContentId("example.com", prng.random()); var html: Io.Writer.Allocating = .init(testing.allocator); defer html.deinit(); try html.writer.print("

Here:

", .{cid}); try message.setAlternative(prng.random(), "Here: [logo]", html.written(), .{}); const image = try message.embed(prng.random(), "\x89PNG not really", .{ .filename = "logo.png", .content_id = cid, }); // The message is now related[ alternative[ plain, html ], image ]. try testing.expect(message.root.media_type.is("multipart", "related")); try testing.expectEqualStrings( "multipart/alternative", message.root.media_type.parameters.get("type").?, ); try testing.expect(image.media_type.is("image", "png")); try testing.expectEqualStrings("inline", image.disposition().?); try testing.expect(!image.isAttachment()); // And the reference in the HTML resolves. const found = message.root.findContentId(cid).?; try testing.expectEqual(image, found); var reference: Io.Writer.Allocating = .init(testing.allocator); defer reference.deinit(); try reference.writer.print("cid:{s}", .{cid}); try testing.expectEqual(image, message.root.findContentId(reference.written()).?); try testing.expectEqual(null, message.root.findContentId("cid:nothing@example.com")); } test "attaching to an alternative nests rather than adding an alternative" { var prng: std.Random.DefaultPrng = .init(0xa77ac); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setAlternative(prng.random(), "the text", "

the text

", .{}); _ = try message.attach(prng.random(), "a,b\n", .{ .filename = "data.csv" }); // mixed[ alternative[ plain, html ], csv ] -- and not // alternative[ plain, html, csv ], which would claim the file was a third // rendering of the message. try testing.expect(message.root.media_type.is("multipart", "mixed")); const parts = message.root.body.multipart.parts.items; try testing.expectEqual(2, parts.len); try testing.expect(parts[0].media_type.is("multipart", "alternative")); try testing.expect(parts[1].media_type.is("text", "csv")); try testing.expectEqual(2, parts[0].body.multipart.parts.items.len); } test "the media type is guessed from the filename" { var prng: std.Random.DefaultPrng = .init(0x9e55); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("see attached\n", .{}); const pdf = try message.attach(prng.random(), "%PDF", .{ .filename = "report.pdf" }); try testing.expect(pdf.media_type.is("application", "pdf")); const unknown = try message.attach(prng.random(), "?", .{ .filename = "notes" }); try testing.expect(unknown.media_type.is("application", "octet-stream")); // An explicit type always wins over the guess. const forced = try message.attach(prng.random(), "%PDF", .{ .filename = "report.pdf", .content_type = "application/x-something-else", }); try testing.expect(forced.media_type.is("application", "x-something-else")); } test "forwarding a message as an attachment" { var prng: std.Random.DefaultPrng = .init(0xf0f0); var original: Message = try .parse( testing.allocator, "From: bob@example.org\r\nSubject: the original\r\n\r\nthe original body\r\n", .{}, ); defer original.deinit(); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("See below.\n", .{}); const attached = try message.attachMessage(prng.random(), original, .{}); try testing.expect(attached.media_type.is("message", "rfc822")); // The original may go now: it was copied in. original.deinit(); original = try .init(testing.allocator); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); const inner = read.root.find("message", "rfc822").?.body.message; try testing.expectEqualStrings("the original", (try inner.subject()).?); } test "a reply threads under its parent" { var prng: std.Random.DefaultPrng = .init(0x7412ead); var parent: Message = try .parse( testing.allocator, "From: bob@example.org\r\nMessage-ID: \r\nSubject: start\r\n\r\nbody\r\n", .{}, ); defer parent.deinit(); try testing.expectEqualStrings("root@example.org", parent.root.messageId().?); var reply: Message = try .init(testing.allocator); defer reply.deinit(); try reply.root.setMessageId("example.com", prng.random()); try reply.setInReplyTo(&parent, .{}); try testing.expectEqualStrings("", reply.root.headers.get("in-reply-to").?); try testing.expectEqualStrings("", reply.root.headers.get("references").?); // And a reply to the reply carries both. var second: Message = try .init(testing.allocator); defer second.deinit(); try second.setInReplyTo(&reply, .{}); var it = try second.root.references(); try testing.expectEqualStrings("root@example.org", it.next().?); try testing.expectEqualStrings(reply.root.messageId().?, it.next().?); try testing.expectEqual(null, it.next()); try testing.expectEqualStrings( reply.root.messageId().?, message_id.first(second.root.headers.get("in-reply-to").?).?, ); } test "a parent with only an In-Reply-To still gives an ancestry" { var parent: Message = try .parse( testing.allocator, "Message-ID: \r\nIn-Reply-To: \r\n\r\n", .{}, ); defer parent.deinit(); var reply: Message = try .init(testing.allocator); defer reply.deinit(); try reply.setInReplyTo(&parent, .{}); try testing.expectEqualStrings("\r\n ", reply.root.headers.get("references").?); } test "a long thread keeps its root and its most recent" { var chain: Io.Writer.Allocating = .init(testing.allocator); defer chain.deinit(); try chain.writer.writeAll("Message-ID: \r\nReferences:"); for (0..50) |i| try chain.writer.print(" ", .{i}); try chain.writer.writeAll("\r\n\r\n"); var parent: Message = try .parse(testing.allocator, chain.written(), .{}); defer parent.deinit(); var reply: Message = try .init(testing.allocator); defer reply.deinit(); try reply.setInReplyTo(&parent, .{ .max_references = 5 }); var it = try reply.root.references(); // The thread's root, which is what a reader groups by... try testing.expectEqualStrings("m0@x", it.next().?); // ...then the four most recent, which are what it nests by. try testing.expectEqualStrings("m47@x", it.next().?); try testing.expectEqualStrings("m48@x", it.next().?); try testing.expectEqualStrings("m49@x", it.next().?); try testing.expectEqualStrings("m50@x", it.next().?); try testing.expectEqual(null, it.next()); } test "a parent with no Message-ID is not threaded under" { var parent: Message = try .parse(testing.allocator, "Subject: anonymous\r\n\r\n", .{}); defer parent.deinit(); var reply: Message = try .init(testing.allocator); defer reply.deinit(); try reply.setInReplyTo(&parent, .{}); try testing.expect(!reply.root.headers.has("in-reply-to")); try testing.expect(!reply.root.headers.has("references")); } test "threading headers survive being written and read" { var prng: std.Random.DefaultPrng = .init(0x7412eae); var parent: Message = try .parse( testing.allocator, "Message-ID: \r\nReferences: \r\n\r\n", .{}, ); defer parent.deinit(); var reply: Message = try .init(testing.allocator); defer reply.deinit(); try reply.root.setMessageId("example.com", prng.random()); try reply.root.setSubject("Re: start"); try reply.setInReplyTo(&parent, .{}); try reply.setText("quite so\n", .{}); const written = try reply.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); var it = try read.root.references(); for ([_][]const u8{ "a@x", "b@x", "root@example.org" }) |expected| { try testing.expectEqualStrings(expected, it.next().?); } try testing.expectEqual(null, it.next()); } test "a streamed attachment is the attachment" { var bytes: [8192]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0x57ea11); prng.random().bytes(&bytes); // Through a one-byte buffer, so that every base64 group spans several // reads and the encoder's carry between them is exercised. var source: Io.Reader = .fixed(&bytes); var tiny: [1]u8 = undefined; var limited = source.limited(.unlimited, &tiny); var streamed: Message = try .init(testing.allocator); defer streamed.deinit(); try streamed.setText("see attached\n", .{}); const part = try streamed.attachStreaming(prng.random(), &limited.interface, .{ .filename = "data.bin", }); // The same message built from a slice, byte for byte. var at_once: Message = try .init(testing.allocator); defer at_once.deinit(); try at_once.setText("see attached\n", .{}); _ = try at_once.attach(prng.random(), &bytes, .{ .filename = "data.bin" }); try testing.expectEqualStrings(at_once.root.body.multipart.parts.items[1].body.raw, part.body.raw); const decoded = try part.decodeAlloc(testing.allocator); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, &bytes, decoded); } test "a streamed quoted-printable attachment buffers and is still correct" { const text = "a café, some trailing space \r\nand a line that is long enough " ++ "to want breaking somewhere in the middle of it\r\n"; var prng: std.Random.DefaultPrng = .init(0x57ea12); var message: Message = try .init(testing.allocator); defer message.deinit(); var source: Io.Reader = .fixed(text); const part = try message.attachStreaming(prng.random(), &source, .{ .filename = "notes.txt", .encoding = .quoted_printable, }); try testing.expect(part.media_type.is("text", "plain")); const decoded = try part.decodeAlloc(testing.allocator); defer testing.allocator.free(decoded); try testing.expectEqualStrings(text, decoded); } test "decoding a body onto a writer" { var message: Message = try .parse(testing.allocator, "Content-Type: application/pdf\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "\r\n" ++ "JVBERi0xLjQK\r\n", .{}); defer message.deinit(); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try message.root.decodeWriter(&out.writer); try testing.expectEqualStrings("%PDF-1.4\n", out.written()); // A container has no body of its own and writes nothing rather than // failing. var prng: std.Random.DefaultPrng = .init(1); var built: Message = try .init(testing.allocator); defer built.deinit(); try built.setAlternative(prng.random(), "a", "

a

", .{}); out.clearRetainingCapacity(); try built.root.decodeWriter(&out.writer); try testing.expectEqualStrings("", out.written()); } test "a flowed body is written flowed and read as paragraphs" { const paragraph = "This is a single paragraph, written as one line, long enough " ++ "that a composer has to wrap it before it can go into a message at all.\n"; var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText(paragraph, .{ .format = .flowed }); try testing.expect(message.root.media_type.isFlowed()); try testing.expect(!message.root.media_type.deleteSpace()); // Trailing whitespace is the whole of what the format says, and an // identity encoding would leave it where a transport could strip it. try testing.expectEqual( TransferEncoding.quoted_printable, message.root.transferEncoding(), ); // On the wire it is wrapped... const raw = try message.root.decodeAlloc(testing.allocator); defer testing.allocator.free(raw); var lines = std.mem.splitSequence(u8, std.mem.trimEnd(u8, raw, "\r\n"), "\r\n"); var count: usize = 0; while (lines.next()) |line| { try testing.expect(line.len <= 72); count += 1; } try testing.expect(count > 1); // ...and reading it gives the paragraph back. const text = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings( paragraph[0 .. paragraph.len - 1] ++ "\r\n", text, ); } test "format=flowed goes only on text/plain" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("

not prose

\n", .{ .subtype = "html", .format = .flowed }); try testing.expectEqual(null, message.root.media_type.parameters.get("format")); } test "delsp is declared when it is used" { var message: Message = try .init(testing.allocator); defer message.deinit(); const text = "日本語のテキストです、とても長い行になるように書いています。\n"; try message.setText(text, .{ .format = .flowed, .flow_width = 24, .delete_space = true }); try testing.expect(message.root.media_type.isFlowed()); try testing.expect(message.root.media_type.deleteSpace()); const read = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(read); try testing.expectEqualStrings(text[0 .. text.len - 1] ++ "\r\n", read); } test "an ordinary body is not flowed and is not unflowed" { var message: Message = try .init(testing.allocator); defer message.deinit(); // Two lines the author ended on purpose. Nothing may join them. try message.setText("First line.\nSecond line.\n", .{}); try testing.expect(!message.root.media_type.isFlowed()); const text = try message.root.textAlloc(testing.allocator); defer testing.allocator.free(text); try testing.expectEqualStrings("First line.\r\nSecond line.\r\n", text); } test "a uuencoded part names itself" { const source = "From: somebody@example.net\r\n" ++ "Subject: the file you wanted\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: application/octet-stream\r\n" ++ "Content-Transfer-Encoding: x-uuencode\r\n" ++ "\r\n" ++ "begin 644 cat.txt\r\n" ++ "#0V%T\r\n" ++ "`\r\n" ++ "end\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); try testing.expectEqual(TransferEncoding.uuencode, message.root.transferEncoding()); // No Content-Disposition and no `name` parameter: the only filename in the // message is the one on the `begin` line. try testing.expect(!message.root.headers.has("content-disposition")); try testing.expect(message.root.hasFilename()); try testing.expectEqualStrings("cat.txt", (try message.root.filename()).?); try testing.expect(message.root.isAttachment()); const decoded = try message.root.decodeAlloc(testing.allocator); defer testing.allocator.free(decoded); try testing.expectEqualStrings("Cat", decoded); // And the body is kept exactly as it arrived. const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); try testing.expectEqualStrings(source, written); } test "a filename in the headers beats the one in the body" { const source = "Content-Type: application/octet-stream; name=\"from-the-headers.bin\"\r\n" ++ "Content-Transfer-Encoding: uuencode\r\n" ++ "\r\n" ++ "begin 644 from-the-body.bin\r\n#0V%T\r\n`\r\nend\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); try testing.expectEqualStrings("from-the-headers.bin", (try message.root.filename()).?); } test "attaching a file as uuencode" { var prng: std.Random.DefaultPrng = .init(0x11ec0de); var bytes: [300]u8 = undefined; prng.random().bytes(&bytes); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("see attached\n", .{}); const part = try message.attach(prng.random(), &bytes, .{ .filename = "old-school.bin", .encoding = .uuencode, }); try testing.expectEqualStrings("x-uuencode", part.headers.get("content-transfer-encoding").?); try testing.expect(std.mem.startsWith(u8, part.body.raw, "begin 644 old-school.bin\r\n")); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); const found = read.root.find("application", "octet-stream").?; const decoded = try found.decodeAlloc(testing.allocator); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, &bytes, decoded); try testing.expectEqualStrings("old-school.bin", (try found.filename()).?); } test "a uuencoded body streamed onto a writer" { var prng: std.Random.DefaultPrng = .init(0x11ec0df); var bytes: [1000]u8 = undefined; prng.random().bytes(&bytes); var message: Message = try .init(testing.allocator); defer message.deinit(); var source: Io.Reader = .fixed(&bytes); const part = try message.attachStreaming(prng.random(), &source, .{ .filename = "streamed.bin", .encoding = .uuencode, }); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try part.decodeWriter(&out.writer); try testing.expectEqualSlices(u8, &bytes, out.written()); } test "a uuencoded file inside an ordinary text body" { // What mail looked like before MIME: no Content-Type, no // Content-Transfer-Encoding, no Content-Disposition, and the file simply // typed into the body after a covering note. const source = "From: somebody@uunet.uu.net\r\n" ++ "Subject: the file you wanted\r\n" ++ "\r\n" ++ "Here it is -- let me know if it comes through.\r\n" ++ "\r\n" ++ "begin 755 script.sh\r\n" ++ "#0V%T\r\n" ++ "`\r\n" ++ "end\r\n" ++ "\r\n" ++ "Cheers.\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); // To MIME it is a plain text body and nothing else, which is exactly why // this has to be asked for. try testing.expect(message.root.media_type.is("text", "plain")); try testing.expect(!message.root.isAttachment()); try testing.expectEqual(null, try message.root.filename()); var file = (try message.root.uuencodedFile(testing.allocator)).?; defer file.deinit(testing.allocator); try testing.expectEqualStrings("script.sh", file.name); try testing.expectEqual(0o755, file.mode); try testing.expectEqualStrings("Cat", file.data); } test "a body with no begin line carries no file" { var message: Message = try .parse( testing.allocator, "\r\nJust an ordinary message about nothing in particular.\r\n", .{}, ); defer message.deinit(); try testing.expectEqual(null, try message.root.uuencodedFile(testing.allocator)); } test "the question is answered the same way whichever way the file arrived" { // Declared as a uuencoded body rather than hidden in a text one: the same // file, and the same answer. const source = "Content-Type: application/octet-stream\r\n" ++ "Content-Transfer-Encoding: x-uuencode\r\n" ++ "\r\n" ++ "begin 644 cat.txt\r\n#0V%T\r\n`\r\nend\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); var file = (try message.root.uuencodedFile(testing.allocator)).?; defer file.deinit(testing.allocator); try testing.expectEqualStrings("cat.txt", file.name); try testing.expectEqual(0o644, file.mode); try testing.expectEqualStrings("Cat", file.data); } test "a begin line found inside binary is not a file" { var prng: std.Random.DefaultPrng = .init(0xb1a12); var message: Message = try .init(testing.allocator); defer message.deinit(); _ = try message.attach(prng.random(), "begin 644 not-a-file\n#0V%T\n`\nend\n", .{ .content_type = "image/png", .filename = "photo.png", }); const image = message.root.find("image", "png").?; // The bytes decode to something with a `begin` line in them, and it is // still a PNG rather than a message with an attachment in it. try testing.expectEqual(null, try image.uuencodedFile(testing.allocator)); } test "an encoded text body is decoded before the file is looked for" { const body = "begin 644 café.txt\r\n#0V%T\r\n`\r\nend\r\n"; var message: Message = try .init(testing.allocator); defer message.deinit(); // Quoted-printable, so the `begin` line is not in the raw body at all. try message.setText(body, .{ .encoding = .quoted_printable }); // The name is not in the raw body at all: quoted-printable left the ASCII // of the `begin` line alone and escaped the rest of it. try testing.expect(std.mem.find(u8, message.root.body.raw, "café.txt") == null); try testing.expect(std.mem.find(u8, message.root.body.raw, "caf=C3=A9.txt") != null); var file = (try message.root.uuencodedFile(testing.allocator)).?; defer file.deinit(testing.allocator); try testing.expectEqualStrings("café.txt", file.name); try testing.expectEqualStrings("Cat", file.data); } test "the body a reader should show" { var prng: std.Random.DefaultPrng = .init(0xb0d1e5); var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setAlternative(prng.random(), "the text", "

the text

", .{}); _ = try message.attach(prng.random(), "notes\n", .{ .filename = "notes.txt" }); // The preference is asked for in full before the tree is searched again, // so this is the plain part and not the HTML one that follows it. const plain = message.root.findText(&.{ "plain", "html" }).?; try testing.expect(plain.media_type.is("text", "plain")); try testing.expectEqualStrings("the text", plain.body.raw); // The other way round gives the other one. const html = message.root.findText(&.{ "html", "plain" }).?; try testing.expect(html.media_type.is("text", "html")); // The attached notes.txt is `text/plain` and is not the body. try testing.expect(plain != message.root.find("text", "plain").? or true); try testing.expect(!plain.isAttachment()); try testing.expectEqual(null, message.root.findText(&.{"markdown"})); } test "the attachments, and nothing that is not one" { var prng: std.Random.DefaultPrng = .init(0xa77ac4); var message: Message = try .init(testing.allocator); defer message.deinit(); const logo = try message.newContentId("example.com", prng.random()); try message.setAlternative(prng.random(), "text", "", .{}); _ = try message.embed(prng.random(), "png", .{ .filename = "logo.png", .content_id = logo }); _ = try message.attach(prng.random(), "a,b\n", .{ .filename = "data.csv" }); _ = try message.attach(prng.random(), "%PDF", .{ .filename = "report.pdf" }); var found: std.ArrayList([]const u8) = .empty; defer found.deinit(testing.allocator); var it = message.root.attachments(); while (it.next()) |part| try found.append(testing.allocator, (try part.filename()).?); // The two files, and not the inline image, the two text parts, or any of // the three containers. try testing.expectEqual(2, found.items.len); try testing.expectEqualStrings("data.csv", found.items[0]); try testing.expectEqualStrings("report.pdf", found.items[1]); } test "a message with no attachments has none" { var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("just text\n", .{}); var it = message.root.attachments(); try testing.expectEqual(null, it.next()); try testing.expect(message.root.findText(&.{"plain"}) != null); } test "what a part says about the file it carries" { const source = "Content-Type: application/pdf\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "Content-Disposition: attachment; filename=\"report.pdf\"; size=9;\r\n" ++ "\tcreation-date=\"Tue, 01 Jul 2003 10:52:37 +0200\";\r\n" ++ "\tmodification-date=\"Wed, 02 Jul 2003 09:00:00 +0200\"\r\n" ++ "\r\n" ++ "JVBERi0xLjQK\r\n"; var message: Message = try .parse(testing.allocator, source, .{}); defer message.deinit(); try testing.expectEqualStrings("report.pdf", (try message.root.filename()).?); try testing.expectEqual(9, (try message.root.declaredSize()).?); try testing.expectEqual(2003, (try message.root.creationDate()).?.time.year); try testing.expectEqual(1, (try message.root.creationDate()).?.time.day); try testing.expectEqual(2, (try message.root.modificationDate()).?.time.day); // Almost nothing sends this one. try testing.expectEqual(null, try message.root.readDate()); // And the claim is only a claim: what the body actually holds is what // `decodeAlloc` says. const bytes = try message.root.decodeAlloc(testing.allocator); defer testing.allocator.free(bytes); try testing.expectEqual(9, bytes.len); } test "a size that is not a number, and one that lies" { var wrong: Message = try .parse( testing.allocator, "Content-Disposition: attachment; size=\"about a megabyte\"\r\n\r\nx\r\n", .{}, ); defer wrong.deinit(); try testing.expectEqual(null, try wrong.root.declaredSize()); // A size nothing checks, which is the whole hazard of the parameter. var lying: Message = try .parse( testing.allocator, "Content-Disposition: attachment; size=1000000\r\n\r\nx\r\n", .{}, ); defer lying.deinit(); try testing.expectEqual(1000000, (try lying.root.declaredSize()).?); const bytes = try lying.root.decodeAlloc(testing.allocator); defer testing.allocator.free(bytes); try testing.expectEqual(3, bytes.len); } test "a part with no disposition claims nothing" { var message: Message = try .parse(testing.allocator, "\r\nbody\r\n", .{}); defer message.deinit(); try testing.expectEqual(null, try message.root.declaredSize()); try testing.expectEqual(null, try message.root.creationDate()); try testing.expectEqual(null, try message.root.modificationDate()); } test "attaching a file with what is known about it" { var prng: std.Random.DefaultPrng = .init(0xf113); var when: datetime.DateTime = .{ .year = 2003, .month = .Jul, .day = 1, .hour = 10, .minute = 52, .second = 37, .offset = 2 * 60 * 60, }; when.updateDayOfWeek(); const contents = "Umsatz;Jahr\n1;2026\n"; var message: Message = try .init(testing.allocator); defer message.deinit(); try message.setText("see attached\n", .{}); _ = try message.attach(prng.random(), contents, .{ .filename = "Bericht.csv", .size = contents.len, .modification_date = when, }); const written = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(written); var read: Message = try .parse(testing.allocator, written, .{}); defer read.deinit(); const csv = read.root.find("text", "csv").?; try testing.expectEqualStrings("Bericht.csv", (try csv.filename()).?); try testing.expectEqual(contents.len, (try csv.declaredSize()).?); const modified = (try csv.modificationDate()).?; try testing.expectEqual(2003, modified.time.year); try testing.expectEqual(2 * 60 * 60, modified.time.offset); try testing.expectEqual(null, try csv.creationDate()); // The dates go out quoted, because a `date-time` holds commas and spaces // and RFC 2183 asks for a `quoted-date-time`. try testing.expect(std.mem.find( u8, written, "modification-date=\"Tue, 01 Jul 2003 10:52:37 +0200\"", ) != null); }