Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A pull parser: a message read from an `Io.Reader`, an event at a time,//! without the message ever being in memory.//!//! `Message.parse` takes a slice, so a message has to fit in memory to be//! opened. That is the right shape for nearly everything — a message is//! usually small, and a tree you can walk and write back out byte for byte is//! worth more than the memory it costs. It is the wrong shape for a mail store//! full of hundred-megabyte attachments, and this is the other one.//!//! ```zig//! var parser: mime.Parser = .init(gpa, reader, .{});//! defer parser.deinit();//!//! while (true) switch (try parser.next()) {//! .begin => {},//! .field => |f| std.debug.print("{s}: {s}\n", .{ f.name, f.value }),//! .headers_end => if (parser.mediaType().is("application", "pdf")) {//! // parser.transferEncoding() says how to decode what follows.//! },//! .body => |chunk| try out.writeAll(chunk),//! .end => {},//! .eof => break,//! };//! ```//!//! Nesting arrives flattened: a `multipart/mixed` produces `begin`, its//! headers, and then a `begin` for each of its parts in turn, each `end`ed//! before the next begins. `depth` says how deep the current entity is, which//! is what a caller reconstructing a tree needs and what a caller looking for//! one part can ignore.//!//! ## What it does not do//!//! **This is not a round trip.** A streaming read discards what a reader does//! not need: the preamble and epilogue of a multipart, the exact spelling of//! the line endings, the whitespace a fold was broken at. `Message.parse` is//! the one to use when the bytes matter — when a signature has to keep//! verifying, or when the message is going to be written back out.//!//! **Header values arrive unfolded**, unlike `Headers`, which keeps them in//! wire form because it has to write them again. A streaming caller cannot ask//! later, so it is given the form it wants.//!//! **Bodies arrive in their transfer encoding**, as they do everywhere else//! here: `transferEncoding()` says which, and `decodeWriter` on it will write//! the chunks out decoded.//!//! **A `message/rfc822` is only opened when it is not encoded.** Decoding it//! in order to parse it would mean holding it, which is the one thing this//! exists not to do. RFC 2045 §6.4 forbids encoding one; a part that does it//! anyway arrives as a leaf, and its bytes are the caller's to decode and//! parse again.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
const MediaType = @import("header/MediaType.zig");const field = @import("header/field.zig");const lexer = @import("header/lexer.zig");const transfer_encoding = @import("codec/transfer_encoding.zig");
const Parser = @This();
pub const TransferEncoding = transfer_encoding.TransferEncoding;
pub const Options = struct { /// How many entities deep the parser will open before it stops taking /// bodies apart and reports them whole. A nesting bomb is a small file /// that costs a great deal to read. max_depth: u8 = 32, /// The most a single header field may accumulate to. Beyond it the value /// is truncated rather than grown, because a folded field is the one part /// of a message whose size a sender chooses and a reader must hold. max_field_bytes: usize = 16 * 1024,};
pub const Field = struct { name: []const u8, /// Unfolded. Valid until the next call to `next`. value: []const u8,};
pub const Event = union(enum) { /// An entity begins; its headers follow. The payload is its depth: 0 for /// the message itself, 1 for a part of it, and so on. begin: u8, /// One header field of the entity that began most recently. field: Field, /// The headers are over. `mediaType`, `transferEncoding` and `disposition` /// describe this entity from here until it ends. headers_end, /// A chunk of the current entity's body, in its transfer encoding. Valid /// until the next call. A container has no body of its own; its parts /// arrive as entities. body: []const u8, /// The current entity is complete, at the depth the payload gives. Several /// arrive in a row where one delimiter closed several entities at once. end: u8, /// The message is complete. eof,};
pub const Error = error{ReadFailed} || Allocator.Error;
const Frame = struct { media_type: MediaType, encoding: TransferEncoding, /// The delimiter of this entity's parts, if it has parts. boundary: ?[]u8, /// Whether `media_type` and `encoding` came from a header rather than a /// default. Only the first of each counts, which is what `Headers.get` /// and so `Message` answer with; a second one must not make the stream /// and the tree read the same entity two different ways. seen_content_type: bool = false, seen_transfer_encoding: bool = false,};
const State = enum { /// An entity is about to begin. begin, /// Reading the header block of the current entity. headers, /// Reading the body of a leaf entity. body, /// Inside a multipart, before its first delimiter. preamble, /// Ending entities until the stack reaches `unwind_to`. unwinding, /// Everything has been read; only `eof` remains. done,};
gpa: Allocator,input: *Io.Reader,options: Options,
stack: std.ArrayList(Frame) = .empty,/// The header field being accumulated: the name, then the value with its/// folds already joined.scratch: std.ArrayList(u8) = .empty,name_len: usize = 0,
state: State = .begin,/// Where the stack must unwind to, and whether the delimiter that caused it/// closed its multipart or opened another part of it.unwind_to: usize = 0,unwind_closing: bool = false,/// The line ending of the last body line, held back because the one in front/// of a delimiter belongs to the delimiter rather than to the body.pending: [2]u8 = undefined,pending_len: usize = 0,/// Whether the last line read was the head of one too long for the reader's/// buffer, so what comes next continues it and is not a line of its own.continuing: bool = false,/// Whether a field was handed out and its storage is due to be reused. It is/// cleared on the *next* call rather than immediately, so that what was handed/// over stays valid until then.pending_field: bool = false,/// Whether a field is being accumulated. Not the same as the scratch buffer/// being non-empty: after one has been handed over its bytes are still there,/// waiting to be cleared.has_field: bool = false,/// A header line being assembled out of however many chunks the reader's/// buffer takes to deliver it. Empty except while a line longer than that/// buffer is being read.line_buf: std.ArrayList(u8) = .empty,/// Whether `line_buf` holds a complete logical line waiting to be looked at.line_ready: bool = false,/// A line that was consumed but whose content has not been emitted yet,/// because the held-back ending of the line before it went out first.held: ?[]const u8 = null,held_terminator: [2]u8 = undefined,held_terminator_len: usize = 0,
pub fn init(gpa: Allocator, input: *Io.Reader, options: Options) Parser { return .{ .gpa = gpa, .input = input, .options = options };}
pub fn deinit(self: *Parser) void { for (self.stack.items) |*frame| { frame.media_type.deinit(self.gpa); if (frame.boundary) |boundary| self.gpa.free(boundary); } self.stack.deinit(self.gpa); self.scratch.deinit(self.gpa); self.line_buf.deinit(self.gpa); self.* = undefined;}
/// How deep the current entity is: 0 for the message itself.pub fn depth(self: *const Parser) u8 { return @intCast(self.stack.items.len -| 1);}
/// The `Content-Type` of the current entity, defaulted as RFC 2045 §5.2 says/// when there is none. Meaningful from `headers_end` until `end`.pub fn mediaType(self: *const Parser) *const MediaType { return &self.stack.items[self.stack.items.len - 1].media_type;}
pub fn transferEncoding(self: *const Parser) TransferEncoding { return self.stack.items[self.stack.items.len - 1].encoding;}
/// The next event.pub fn next(self: *Parser) Error!Event { while (true) { switch (self.state) { .done => return .eof,
.begin => { try self.push(); self.state = .headers; self.scratch.clearRetainingCapacity(); self.name_len = 0; self.has_field = false; return .{ .begin = self.depth() }; },
.headers => if (try self.nextHeaderEvent()) |event| return event,
.body => if (try self.nextBodyEvent()) |event| return event,
.preamble => try self.skipToDelimiter(),
.unwinding => { if (self.stack.items.len > self.unwind_to + 1) { const ended = self.depth(); self.pop(); return .{ .end = ended }; } // The stack is where the delimiter said. Either the multipart // at this level has another part, or it has been closed and // this level ends too. if (self.unwind_closing) { if (self.stack.items.len == 0) { self.state = .done; return .eof; } const ended = self.depth(); self.pop(); self.state = if (self.stack.items.len == 0) .done else .preamble; return .{ .end = ended }; } self.state = .begin; }, } }}
/// Reads the body of the current entity onto `w`, and returns when it ends./// The convenience for a caller that wants the part rather than the events.pub fn streamBody(self: *Parser, w: *Io.Writer) (Error || Io.Writer.Error)!void { while (true) switch (try self.next()) { .body => |chunk| try w.writeAll(chunk), .end, .eof => return, // A container has no body; anything else means the caller asked at the // wrong moment, and stopping is better than swallowing the message. else => return, };}
// -- headers ----------------------------------------------------------------
fn nextHeaderEvent(self: *Parser) Error!?Event { while (true) { const text = try self.peekHeaderLine() orelse { // The message ended inside its headers. if (try self.flushField()) |f| return .{ .field = f }; try self.finishHeaders(); return .headers_end; };
// A line beginning with whitespace continues the field being // accumulated. RFC 5322 §2.2.3: that is the whole of folding. if (self.has_field and text.len != 0 and lexer.isWsp(text[0])) { try self.appendField(text); self.consumeHeaderLine(); continue; }
// A delimiter ends the entity wherever it is found, headers included: // a part cut off before its blank line is still a part that ended. if (self.classify(text)) |found| { if (try self.flushField()) |f| return .{ .field = f }; self.consumeHeaderLine(); try self.finishHeaders(); self.unwind_to = found.level; self.unwind_closing = found.closing; self.state = .unwinding; return .headers_end; }
if (text.len == 0) { // The blank line: the headers are over. if (try self.flushField()) |f| return .{ .field = f }; self.consumeHeaderLine(); try self.finishHeaders(); return .headers_end; }
// A new field begins, so whatever was being accumulated is finished. // The line is left where it is until the next call, which is what // keeps the field that is handed over valid until then. if (try self.flushField()) |f| return .{ .field = f };
// A line that is neither a field nor a continuation is skipped, which // is what the `From ` line of an mbox message is. if (field.split(text)) |split| { self.clearField(); self.has_field = true; self.name_len = split.name.len; try self.scratch.appendSlice(self.gpa, split.name); try self.appendField(split.value); } self.consumeHeaderLine(); }}
/// The next complete header line, assembled from as many chunks as the/// reader's buffer takes to deliver it, and held until `consumeHeaderLine`.////// Assembling is what keeps the two parsers agreeing. A header line longer/// than the buffer arrives in pieces, and a parser that looked at the pieces/// would split the tail of one line into a field of its own, or miss the colon/// of a line whose name ran past the buffer — both of which the tree parser,/// which sees whole lines, does not do.fn peekHeaderLine(self: *Parser) Error!?[]const u8 { if (self.line_ready) return self.line_buf.items; while (true) { const line = try self.peekLine() orelse { if (self.line_buf.items.len == 0) return null; self.line_ready = true; return self.line_buf.items; }; self.consume(line); const room = self.options.max_field_bytes -| self.line_buf.items.len; const take = @min(line.bytes.len, room); try self.line_buf.appendSlice(self.gpa, line.bytes[0..take]); if (!line.partial) { self.line_ready = true; return self.line_buf.items; } }}
fn consumeHeaderLine(self: *Parser) void { self.line_ready = false; self.line_buf.clearRetainingCapacity();}
/// Appends one line's worth of a field value, unfolded.////// The folds themselves are already gone — a continuation is appended straight/// on to what it continues — but a *lone* CR can still be sitting inside a/// line, and RFC 5322 has no such thing. `field.unfoldWriter` is what the tree/// parser puts its values through, and this is the same rule applied a line at/// a time: a CR that something whitespace follows is dropped as though it had/// been a fold, and one that nothing does becomes a space rather than reaching/// a header that will be written out again.////// A line at a time rather than at the end, because by then the real line/// endings have gone: a CR at the end of a line would sit next to the/// continuation's leading whitespace and be read as a fold it never was.fn appendField(self: *Parser, text: []const u8) Allocator.Error!void { var i: usize = 0; var start: usize = 0; while (i < text.len) : (i += 1) { if (text[i] != '\r' and text[i] != '\n') continue; try self.appendCapped(text[start..i]); if (i + 1 >= text.len or !lexer.isWsp(text[i + 1])) try self.appendCapped(" "); start = i + 1; } try self.appendCapped(text[start..]);}
fn appendCapped(self: *Parser, text: []const u8) Allocator.Error!void { const room = self.options.max_field_bytes -| self.scratch.items.len; if (room == 0) return; try self.scratch.appendSlice(self.gpa, text[0..@min(text.len, room)]);}
/// Hands over the accumulated field, if there is one.fn flushField(self: *Parser) Allocator.Error!?Field { if (!self.has_field) return null; self.has_field = false; self.pending_field = true; const name = self.scratch.items[0..self.name_len]; const value = std.mem.trim(u8, self.scratch.items[self.name_len..], " \t"); try self.observe(name, value); return .{ .name = name, .value = value };}
/// Notices the two headers that change how the rest of the entity is read.////// The parser has to read them whether the caller wants them or not: a/// `Content-Type` says whether the body is bytes or parts and what delimits/// the parts, and a `Content-Transfer-Encoding` says whether a/// `message/rfc822` can be opened without decoding it first.fn observe(self: *Parser, name: []const u8, value: []const u8) Allocator.Error!void { const frame = &self.stack.items[self.stack.items.len - 1]; if (std.ascii.eqlIgnoreCase(name, "content-type")) { if (frame.seen_content_type) return; const parsed: MediaType = try .parse(self.gpa, value); frame.media_type.deinit(self.gpa); frame.media_type = parsed; frame.seen_content_type = true; } else if (std.ascii.eqlIgnoreCase(name, "content-transfer-encoding")) { if (frame.seen_transfer_encoding) return; frame.encoding = TransferEncoding.parse(value); frame.seen_transfer_encoding = true; }}
fn clearField(self: *Parser) void { if (!self.pending_field) return; self.pending_field = false; self.scratch.clearRetainingCapacity();}
/// Parses what the headers said, and decides what the body of this entity is.fn finishHeaders(self: *Parser) Error!void { const frame = &self.stack.items[self.stack.items.len - 1]; // At the limit the entity is still reported; what is inside it is not // taken apart, and arrives as a body of bytes. // `stack.items.len` is one more than the depth, and the limit is on the // depth, so that this and `Message.ParseOptions.max_depth` stop in the // same place. if (self.stack.items.len > self.options.max_depth) { self.pending_len = 0; self.state = .body; return; } if (frame.media_type.isMultipart()) { if (frame.media_type.boundary()) |boundary| { if (boundary.len != 0) { frame.boundary = try self.gpa.dupe(u8, boundary); self.state = .preamble; return; } } // A multipart with no boundary cannot be taken apart, and its body is // bytes like any other. } else if (frame.media_type.isEncapsulatedMessage() and frame.encoding.isIdentity()) { if (try self.encapsulatedHasBody()) { self.state = .begin; return; } } self.pending_len = 0; self.state = .body;}
// -- bodies -----------------------------------------------------------------
fn nextBodyEvent(self: *Parser) Error!?Event { const line = try self.peekLine() orelse { // The end of the message ends everything still open. self.unwind_to = 0; self.unwind_closing = true; self.state = .unwinding; // The last line's ending really was the body's. if (self.pending_len != 0) return .{ .body = self.takePending() }; return null; };
if (!self.continuing and !line.partial) { if (self.classify(line.bytes)) |found| { self.consume(line); // The line ending in front of a delimiter belongs to the // delimiter, so what was held back is dropped rather than emitted. self.pending_len = 0; self.unwind_to = found.level; self.unwind_closing = found.closing; self.state = .unwinding; return null; } }
self.consume(line); // Whatever line ending the *previous* line had is emitted now that this // one has proved not to be a delimiter. if (self.pending_len != 0) { const held = self.takePending(); self.pushBack(line); return .{ .body = held }; } self.rememberPending(line.terminator); return .{ .body = line.bytes };}
/// The held-back line ending, copied out of the small buffer it lives in.fn takePending(self: *Parser) []const u8 { const held = self.pending[0..self.pending_len]; self.pending_len = 0; return held;}
/// Whether a `message/rfc822` body has anything in it, which is what decides/// whether to open a message inside it at all.////// An empty body is not a message: opening one would put an entity in front of/// the caller that nothing sent — a `text/plain` by default, which is what a/// caller asking for the text would then be handed. `Message.parse` refuses/// the same way, and the two have to agree about it.////// What makes this more than "is there another line" is that **the line ending/// in front of a delimiter belongs to the delimiter**. A `message/rfc822` that/// is the last thing before `--boundary--` therefore has an empty body whether/// it was written as `…\r\n--boundary--` or as `…\r\n\r\n--boundary--`: in the/// second, the only thing between the header block and the delimiter is an/// empty line whose ending is the delimiter's own. One line of lookahead past/// that empty line settles it, and this is the only place the parser needs/// any.fn encapsulatedHasBody(self: *Parser) Error!bool { const first = try self.peekLine() orelse return false; // A line too long for the reader's buffer is content, and is not something // `classify` is ever asked about — see `nextBodyEvent`. if (first.partial) return true; if (self.classify(first.bytes) != null) return false; if (first.bytes.len != 0) return true;
// An empty line. Its ending is the body's only if something other than a // delimiter follows it. Copy the ending out before consuming, because // reading the line after it may refill the buffer the first one points // into. var terminator: [2]u8 = undefined; const terminator_len = @min(first.terminator.len, terminator.len); @memcpy(terminator[0..terminator_len], first.terminator[0..terminator_len]); self.consume(first);
const empty: Line = .{ .bytes = "", .terminator = terminator[0..terminator_len], .partial = false, .advance = 0, };
const second = try self.peekLine() orelse { // The end of the input, where there is no delimiter to own a line // ending, so the empty line really was the body. self.pushBack(empty); return true; }; if (!second.partial and self.classify(second.bytes) != null) return false; self.pushBack(empty); return true;}
fn rememberPending(self: *Parser, terminator: []const u8) void { self.pending_len = @min(terminator.len, self.pending.len); @memcpy(self.pending[0..self.pending_len], terminator[0..self.pending_len]);}
fn pushBack(self: *Parser, line: Line) void { self.held = line.bytes; self.held_terminator_len = @min(line.terminator.len, self.held_terminator.len); @memcpy(self.held_terminator[0..self.held_terminator_len], line.terminator[0..self.held_terminator_len]);}
// -- multipart --------------------------------------------------------------
/// Reads and discards everything up to the next delimiter: the preamble of a/// multipart, or the epilogue after one has been closed. RFC 2046 §5.1.1 says/// both are to be ignored, and a streaming read ignores them.fn skipToDelimiter(self: *Parser) Error!void { while (true) { const line = try self.peekLine() orelse { self.unwind_to = 0; self.unwind_closing = true; self.state = .unwinding; return; }; const partial = self.continuing or line.partial; self.consume(line); if (partial) continue; if (self.classify(line.bytes)) |found| { self.unwind_to = found.level; self.unwind_closing = found.closing; self.state = .unwinding; return; } }}
const Delimiter = struct { /// The index in the stack of the multipart this delimiter belongs to. level: usize, closing: bool,};
/// Whether a line is the delimiter of any multipart still open.////// Checked from the outermost inwards, because an enclosing delimiter ends/// every multipart inside it — RFC 2046 §5.1.1 forbids one from appearing/// within a part — which is how a message whose inner closing delimiter was/// lost is read at all. It is also how `Message` reads the same bytes, since/// it splits an outer body before it looks inside a part: an inner multipart/// that reuses an enclosing boundary never sees that boundary as its own.fn classify(self: *const Parser, line: []const u8) ?Delimiter { if (!std.mem.startsWith(u8, line, "--")) return null; levels: for (self.stack.items, 0..) |frame, i| { const boundary = frame.boundary orelse continue; if (!std.mem.startsWith(u8, line[2..], boundary)) continue; var rest = line[2 + boundary.len ..]; const closing = std.mem.startsWith(u8, rest, "--"); if (closing) rest = rest[2..]; // The whole line must be the delimiter, or `--=_Part_1` would match // inside `--=_Part_12` -- which may yet be the delimiter of a // multipart further in. for (rest) |c| if (c != ' ' and c != '\t' and c != '\r') continue :levels; return .{ .level = i, .closing = closing }; } return null;}
fn push(self: *Parser) Allocator.Error!void { // A part of a `multipart/digest` with no `Content-Type` is a // `message/rfc822` rather than text — RFC 2046 §5.1.5 — and getting that // wrong turns each message of a digest into its own headers as text. const digest = self.stack.items.len != 0 and self.stack.items[self.stack.items.len - 1].media_type.is("multipart", "digest"); try self.stack.append(self.gpa, .{ .media_type = if (digest) try MediaType.defaultForDigest(self.gpa) else try MediaType.default(self.gpa), .encoding = .seven_bit, .boundary = null, });}
fn pop(self: *Parser) void { var frame = self.stack.pop().?; frame.media_type.deinit(self.gpa); if (frame.boundary) |boundary| self.gpa.free(boundary);}
// -- lines ------------------------------------------------------------------
const Line = struct { /// Without the terminator. bytes: []const u8, /// "", "\n" or "\r\n". terminator: []const u8, /// Whether this is the head of a line too long for the reader's buffer. partial: bool, /// How much to toss to consume it. advance: usize,};
/// The next line, without consuming it. Valid until anything else touches the/// reader.fn peekLine(self: *Parser) Error!?Line { if (self.held) |bytes| { const line: Line = .{ .bytes = bytes, .terminator = self.held_terminator[0..self.held_terminator_len], .partial = false, .advance = 0, }; return line; } const inclusive = self.input.peekDelimiterInclusive('\n') catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.EndOfStream => { const rest = self.input.buffered(); if (rest.len == 0) return null; return .{ .bytes = rest, .terminator = "", .partial = false, .advance = rest.len }; }, error.StreamTooLong => { // A line longer than the reader's whole buffer. What is there is // the head of it; the rest arrives as its own chunk, and // `continuing` stops that chunk being read as a line. const rest = self.input.buffered(); return .{ .bytes = rest, .terminator = "", .partial = true, .advance = rest.len }; }, }; const nl = inclusive.len - 1; const text_end = if (nl > 0 and inclusive[nl - 1] == '\r') nl - 1 else nl; return .{ .bytes = inclusive[0..text_end], .terminator = inclusive[text_end..], .partial = false, .advance = inclusive.len, };}
fn consume(self: *Parser, line: Line) void { self.clearField(); if (self.held != null) { self.held = null; } else { self.input.toss(line.advance); } self.continuing = line.partial;}
// -- tests ------------------------------------------------------------------
/// Runs the parser over `source` and writes what it saw as text, which is far/// easier to read in a failing test than a list of tagged unions.////// `buffer_len` is the reader's buffer, and is a parameter because the awkward/// cases are the ones where a line does not fit in it.fn transcribe(gpa: Allocator, source: []const u8, buffer_len: usize) ![]u8 { const buffer = try gpa.alloc(u8, buffer_len); defer gpa.free(buffer);
var fixed: Io.Reader = .fixed(source); var limited = fixed.limited(.unlimited, buffer);
var parser: Parser = .init(gpa, &limited.interface, .{}); defer parser.deinit();
var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit();
while (true) switch (try parser.next()) { .begin => |d| try out.writer.print("begin {d}\n", .{d}), .field => |f| try out.writer.print("field {s}={s}\n", .{ f.name, f.value }), .headers_end => try out.writer.print("headers {s}/{s}\n", .{ parser.mediaType().type, parser.mediaType().subtype, }), .body => |chunk| try out.writer.print("body {f}\n", .{std.ascii.hexEscape(chunk, .lower)}), .end => |d| try out.writer.print("end {d}\n", .{d}), .eof => break, }; return out.toOwnedSlice();}
test "a message with no MIME in it" { const seen = try transcribe(testing.allocator, "From: jeff@example.com\r\n" ++ "Subject: hello\r\n" ++ "\r\n" ++ "first line\r\n" ++ "second line\r\n", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings( "begin 0\n" ++ "field From=jeff@example.com\n" ++ "field Subject=hello\n" ++ "headers text/plain\n" ++ "body first line\n" ++ "body \\x0d\\x0a\n" ++ "body second line\n" ++ "body \\x0d\\x0a\n" ++ "end 0\n", seen, );}
test "a folded field arrives unfolded" { const seen = try transcribe(testing.allocator, "To: alice@example.net,\r\n" ++ "\tbob@example.org\r\n" ++ "\r\n", 4096); defer testing.allocator.free(seen); try testing.expect(std.mem.find(u8, seen, "field To=alice@example.net,\tbob@example.org\n") != null);}
test "a multipart arrives as its parts" { const seen = try transcribe(testing.allocator, "Content-Type: multipart/mixed; boundary=B\r\n" ++ "\r\n" ++ "a preamble nobody reads\r\n" ++ "--B\r\n" ++ "Content-Type: text/plain\r\n" ++ "\r\n" ++ "one\r\n" ++ "--B\r\n" ++ "Content-Type: text/html\r\n" ++ "\r\n" ++ "two\r\n" ++ "--B--\r\n" ++ "an epilogue nobody reads\r\n", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings( "begin 0\n" ++ "field Content-Type=multipart/mixed; boundary=B\n" ++ "headers multipart/mixed\n" ++ "begin 1\n" ++ "field Content-Type=text/plain\n" ++ "headers text/plain\n" ++ "body one\n" ++ "end 1\n" ++ "begin 1\n" ++ "field Content-Type=text/html\n" ++ "headers text/html\n" ++ "body two\n" ++ "end 1\n" ++ "end 0\n", seen, );}
test "the first Content-Type and Content-Transfer-Encoding are the ones that count" { // As `Headers.get` answers, and so as `Message` reads the same entity. A // second Content-Type that won here would make this a text/plain whose // body the stream hands over as bytes while the tree splits it into parts. const seen = try transcribe(testing.allocator, "Content-Type: multipart/mixed; boundary=B\r\n" ++ "Content-Transfer-Encoding: 7bit\r\n" ++ "Content-Type: text/plain\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "\r\n" ++ "--B\r\n" ++ "\r\n" ++ "one\r\n" ++ "--B--\r\n", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings( "begin 0\n" ++ "field Content-Type=multipart/mixed; boundary=B\n" ++ "field Content-Transfer-Encoding=7bit\n" ++ "field Content-Type=text/plain\n" ++ "field Content-Transfer-Encoding=base64\n" ++ "headers multipart/mixed\n" ++ "begin 1\n" ++ "headers text/plain\n" ++ "body one\n" ++ "end 1\n" ++ "end 0\n", seen, );}
test "an inner multipart that reuses an enclosing boundary never sees it" { // The `--B` after the inner header block is the outer multipart's, as // `Message` reads it: the inner one is empty, and `y` is the outer's // second part rather than the inner's first. const seen = try transcribe(testing.allocator, "Content-Type: multipart/mixed; boundary=B\r\n" ++ "\r\n" ++ "--B\r\n" ++ "Content-Type: multipart/mixed; boundary=B\r\n" ++ "\r\n" ++ "--B\r\n" ++ "\r\n" ++ "y\r\n" ++ "--B--\r\n", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings( "begin 0\n" ++ "field Content-Type=multipart/mixed; boundary=B\n" ++ "headers multipart/mixed\n" ++ "begin 1\n" ++ "field Content-Type=multipart/mixed; boundary=B\n" ++ "headers multipart/mixed\n" ++ "end 1\n" ++ "begin 1\n" ++ "headers text/plain\n" ++ "body y\n" ++ "end 1\n" ++ "end 0\n", seen, );}
test "an outer boundary that is a prefix of an inner one does not hide it" { const seen = try transcribe(testing.allocator, "Content-Type: multipart/mixed; boundary=B\r\n" ++ "\r\n" ++ "--B\r\n" ++ "Content-Type: multipart/mixed; boundary=B1\r\n" ++ "\r\n" ++ "--B1\r\n" ++ "\r\n" ++ "one\r\n" ++ "--B1--\r\n" ++ "--B\r\n" ++ "\r\n" ++ "two\r\n" ++ "--B--\r\n", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings( "begin 0\n" ++ "field Content-Type=multipart/mixed; boundary=B\n" ++ "headers multipart/mixed\n" ++ "begin 1\n" ++ "field Content-Type=multipart/mixed; boundary=B1\n" ++ "headers multipart/mixed\n" ++ "begin 2\n" ++ "headers text/plain\n" ++ "body one\n" ++ "end 2\n" ++ "end 1\n" ++ "begin 1\n" ++ "headers text/plain\n" ++ "body two\n" ++ "end 1\n" ++ "end 0\n", seen, );}
test "a nested multipart, and an inner delimiter that was lost" { 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\nplain\r\n" ++ "--IN\r\nContent-Type: text/html\r\n\r\nhtml\r\n" ++ // No `--IN--`: the outer delimiter closes the inner multipart too, // which is how a message with a lost delimiter is read at all. "--OUT\r\nContent-Type: image/png\r\n\r\npng\r\n" ++ "--OUT--\r\n"; const seen = try transcribe(testing.allocator, source, 4096); defer testing.allocator.free(seen);
// Three ends in a row where the outer delimiter arrived: the html part, // then the alternative, then on to the image. try testing.expect(std.mem.find(u8, seen, "body html\nend 2\nend 1\nbegin 1\n") != null); try testing.expect(std.mem.find(u8, seen, "headers image/png\nbody png\nend 1\nend 0\n") != null);}
test "an attached message is opened" { const seen = try transcribe(testing.allocator, "Content-Type: message/rfc822\r\n\r\n" ++ "Subject: the original\r\n\r\n" ++ "the body\r\n", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings( "begin 0\n" ++ "field Content-Type=message/rfc822\n" ++ "headers message/rfc822\n" ++ "begin 1\n" ++ "field Subject=the original\n" ++ "headers text/plain\n" ++ "body the body\n" ++ "body \\x0d\\x0a\n" ++ "end 1\n" ++ "end 0\n", seen, );}
test "an encoded attached message is left as bytes" { // Opening it would mean decoding it, and decoding it would mean holding // it, which is the one thing this exists not to do. const seen = try transcribe(testing.allocator, "Content-Type: message/rfc822\r\n" ++ "Content-Transfer-Encoding: base64\r\n\r\n" ++ "U3ViamVjdDogeAo=\r\n", 4096); defer testing.allocator.free(seen); try testing.expect(std.mem.find(u8, seen, "begin 1") == null); try testing.expect(std.mem.find(u8, seen, "body U3ViamVjdDogeAo=\n") != null);}
test "a part of a digest is a message" { const seen = try transcribe(testing.allocator, "Content-Type: multipart/digest; boundary=D\r\n\r\n" ++ "--D\r\n\r\nSubject: first\r\n\r\none\r\n" ++ "--D--\r\n", 4096); defer testing.allocator.free(seen); try testing.expect(std.mem.find(u8, seen, "headers message/rfc822\n") != null); try testing.expect(std.mem.find(u8, seen, "field Subject=first\n") != null);}
test "an empty message is not opened, however the delimiter is reached" { // The line ending in front of a delimiter belongs to the delimiter, so a // `message/rfc822` that is the last thing in a part has an empty body both // ways round -- and an empty body is not a message. Opening one puts a // `text/plain` in front of the caller that nothing sent, which is what // `find` would then hand back to somebody asking for the text. // // Both spellings, and at several reader buffer sizes, because the lookahead // that decides this is the only one in the parser and a buffer boundary // landing inside it is exactly what would break it. const sources = [_][]const u8{ "Content-Type: multipart/digest; boundary=B\r\n\r\n" ++ "--B\r\nSubject: x\r\n\r\n--B--\r\n", "Content-Type: multipart/digest; boundary=B\r\n\r\n" ++ "--B\r\nSubject: x\r\n\r\n\r\n--B--\r\n", }; for (sources) |source| { for ([_]usize{ 16, 24, 64, 4096 }) |buffer_len| { const seen = try transcribe(testing.allocator, source, buffer_len); defer testing.allocator.free(seen); try testing.expect(std.mem.find(u8, seen, "headers message/rfc822\n") != null); try testing.expect(std.mem.find(u8, seen, "headers text/plain\n") == null); } }
// But an empty line that is *not* the delimiter's is a body, and the // message inside it is opened. const with_body = "Content-Type: multipart/digest; boundary=B\r\n\r\n" ++ "--B\r\nSubject: x\r\n\r\n\r\n\r\n--B--\r\n"; const seen = try transcribe(testing.allocator, with_body, 4096); defer testing.allocator.free(seen); try testing.expect(std.mem.find(u8, seen, "headers text/plain\n") != null);}
test "a line longer than the reader's buffer" { const long = &@as([500]u8, @splat('x')); const source = "Content-Type: text/plain\r\n\r\n" ++ long ++ "\r\n";
// Reassembled from however many chunks a small buffer produces, the body // is the body. for ([_]usize{ 64, 128, 4096 }) |buffer_len| { const buffer = try testing.allocator.alloc(u8, buffer_len); defer testing.allocator.free(buffer); var fixed: Io.Reader = .fixed(source); var limited = fixed.limited(.unlimited, buffer);
var parser: Parser = .init(testing.allocator, &limited.interface, .{}); defer parser.deinit();
var body: Io.Writer.Allocating = .init(testing.allocator); defer body.deinit(); while (true) switch (try parser.next()) { .body => |chunk| try body.writer.writeAll(chunk), .eof => break, else => {}, }; try testing.expectEqualStrings(long ++ "\r\n", body.written()); }}
test "a boundary that is a prefix of another" { const seen = try transcribe(testing.allocator, // Quoted, because `=` is not a token character: `boundary==_P1` is // malformed and parses to no boundary at all. "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", 4096); defer testing.allocator.free(seen); try testing.expect(std.mem.find(u8, seen, "body --=_P12 is not a delimiter\n") != null); try testing.expectEqual(1, std.mem.count(u8, seen, "begin 1\n"));}
test "nothing at all" { const seen = try transcribe(testing.allocator, "", 4096); defer testing.allocator.free(seen); try testing.expectEqualStrings("begin 0\nheaders text/plain\nend 0\n", seen);}
test "streamBody writes the part and stops at its end" { var fixed: Io.Reader = .fixed( "Content-Type: multipart/mixed; boundary=B\r\n\r\n" ++ "--B\r\n\r\nthe first part\r\n" ++ "--B\r\n\r\nthe second\r\n--B--\r\n", ); var buffer: [256]u8 = undefined; var limited = fixed.limited(.unlimited, &buffer);
var parser: Parser = .init(testing.allocator, &limited.interface, .{}); defer parser.deinit();
// Down to the first part's body. while (true) switch (try parser.next()) { .headers_end => if (parser.depth() == 1) break, .eof => return error.NoPart, else => {}, };
var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try parser.streamBody(&out.writer); try testing.expectEqualStrings("the first part", out.written());}