// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the parsers must do with input nobody wrote. //! //! Everything here is a property rather than an example: not "this header //! parses to that" — the unit tests have those — but "whatever arrives, the //! parser terminates, stays inside its buffers, frees what it allocated, and //! if it claims to have understood the input then writing it back out and //! reading it again gives the same answer". //! //! Round-tripping is the property that earns its keep. A parser and a writer //! drift apart one small decision at a time — where a fold goes, whether a //! trailing space survives, which of two `@` signs separates an address — and //! a test written against a fixed example cannot see it, because the example //! was written to agree with whatever the code did that day. The message //! target asks for the *second* write to equal the first rather than for the //! output to equal the input: input may legitimately be repaired on the way //! in, but repairing it twice must change nothing. //! //! Each target is an ordinary test as well as a fuzz target. Without `--fuzz` //! it runs the seeds beside it, so `zig build test` exercises the same //! properties on input that has already been interesting once. //! //! With `--fuzz` — `zig build fuzz --fuzz` — Zig's own fuzzer drives them //! with coverage feedback. `tools/fuzz.zig` is a second way in, a loop with a //! corpus and a fixed seed, which is what the workflow runs. const builtin = @import("builtin"); const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const mime = @import("mime"); /// The allocator the targets run against. /// /// Under `zig build test` that is the testing allocator, which reports a leak /// as a failure. `tools/fuzz.zig` cannot name it — it is not a test build — so /// it sets this to a checked allocator of its own instead. pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined; /// One fuzz target: what to call it, what it already knows to be interesting, /// how much of an input it can read, and the property itself. pub const Target = struct { name: []const u8, corpus: []const []const u8, /// The size of the buffer the target reads its slice into. /// /// `Smith.slice` answers a length larger than its buffer with an *empty* /// slice rather than a truncated one, so a generator that does not know /// this number will silently hand the target nothing at all. content_max: usize, run: *const fn (input: []const u8) anyerror!void, }; /// Seeds for `testing.fuzz`, written the way a `Smith` reads them back. /// /// Zig's fuzzer starts from its corpus, and one left empty is random bytes, /// which reach nothing past the first check in a parser that wants a /// `mailto:`, a `<` or a header block. A corpus entry is not the input itself /// but the stream of answers a target asks for: each slice is a little-endian /// `u32` length and then its bytes, one after another for a target that asks /// for more than one. A length larger than the target's buffer reads back as /// an empty slice, so a seed that does not fit is a compile error rather than /// a seed that silently tests nothing. fn smithed(comptime max: usize, comptime slices: []const []const u8) []const u8 { comptime { var out: []const u8 = ""; for (slices) |slice| { if (slice.len > max) @compileError(std.fmt.comptimePrint( "a seed of {d} bytes does not fit a buffer of {d}", .{ slice.len, max }, )); var len: [4]u8 = undefined; std.mem.writeInt(u32, &len, slice.len, .little); out = out ++ len ++ slice; } return out; } } /// A corpus of one slice per input: every seed on its own. fn corpusOf(comptime max: usize, comptime seeds: []const []const u8) []const []const u8 { comptime { var out: [seeds.len][]const u8 = undefined; for (seeds, &out) |seed, *entry| entry.* = smithed(max, &.{seed}); const final = out; return &final; } } /// A corpus of two slices per input: every first seed with every second. fn corpusOfPairs( comptime max: usize, comptime firsts: []const []const u8, comptime seconds: []const []const u8, ) []const []const u8 { comptime { @setEvalBranchQuota(100_000); var out: [firsts.len * seconds.len][]const u8 = undefined; for (firsts, 0..) |first, i| { for (seconds, 0..) |second, j| out[i * seconds.len + j] = smithed(max, &.{ first, second }); } const final = out; return &final; } } /// A corpus of `n` slices per input: each seed followed by the ones after /// it, wrapping round, so that every seed turns up in every position. fn corpusOfRotations( comptime max: usize, comptime n: usize, comptime seeds: []const []const u8, ) []const []const u8 { comptime { var out: [seeds.len][]const u8 = undefined; for (&out, 0..) |*entry, i| { var slices: [n][]const u8 = undefined; for (&slices, 0..) |*slice, j| slice.* = seeds[(i + j) % seeds.len]; entry.* = smithed(max, &slices); } const final = out; return &final; } } pub const all = [_]Target{ .{ .name = "message", .corpus = &message_seeds, .content_max = message_max, .run = runMessage }, .{ .name = "headers", .corpus = &header_seeds, .content_max = header_max, .run = runHeaders }, .{ .name = "address", .corpus = &address_seeds, .content_max = address_max, .run = runAddress }, .{ .name = "date", .corpus = &date_seeds, .content_max = date_max, .run = runDate }, .{ .name = "encoded-word", .corpus = &encoded_word_seeds, .content_max = word_max, .run = runEncodedWord }, .{ .name = "parameters", .corpus = ¶meter_seeds, .content_max = parameter_max, .run = runParameters }, .{ .name = "base64", .corpus = &codec_seeds, .content_max = codec_max, .run = runBase64 }, .{ .name = "quoted-printable", .corpus = &codec_seeds, .content_max = codec_max, .run = runQuotedPrintable }, .{ .name = "flowed", .corpus = &flowed_seeds, .content_max = flowed_max, .run = runFlowed }, .{ .name = "uuencode", .corpus = &uuencode_seeds, .content_max = uuencode_max, .run = runUuencode }, .{ .name = "idn", .corpus = &idn_seeds, .content_max = idn_max, .run = runIdn }, .{ .name = "parser", .corpus = &message_seeds, .content_max = message_max, .run = runParser }, .{ .name = "mailto", .corpus = &mailto_seeds, .content_max = mailto_max, .run = runMailto }, .{ .name = "mailto-write", .corpus = &build_seeds, .content_max = field_max, .run = runMailtoWrite }, .{ .name = "message-ids", .corpus = &message_id_seeds, .content_max = message_id_max, .run = runMessageIds }, .{ .name = "line-endings", .corpus = &codec_seeds, .content_max = codec_max, .run = runLineEndings }, .{ .name = "lexer", .corpus = &lexer_seeds, .content_max = lexer_max, .run = runLexer }, .{ .name = "boundary", .corpus = &boundary_seeds, .content_max = build_max, .run = runBoundary }, .{ .name = "received", .corpus = &received_seeds, .content_max = received_max, .run = runReceived }, .{ .name = "report", .corpus = &report_seeds, .content_max = report_max, .run = runReport }, .{ .name = "build", .corpus = &build_seeds, .content_max = build_max, .run = runBuild }, .{ .name = "compose", .corpus = &build_seeds, .content_max = build_max, .run = runCompose }, .{ .name = "chunks", .corpus = &chunk_seeds, .content_max = chunk_max, .run = runChunks }, .{ .name = "encode-stream", .corpus = &build_seeds, .content_max = chunk_max, .run = runEncodeStream }, .{ .name = "headers-edit", .corpus = &header_seeds, .content_max = header_max, .run = runHeadersEdit }, }; // -- whole messages --------------------------------------------------------- const message_max = 8192; const message_seeds = [_][]const u8{ "From: jeff@example.com\r\nSubject: hello\r\n\r\nbody\r\n", "Content-Type: multipart/mixed; boundary=B\r\n\r\n--B\r\n\r\na\r\n--B\r\n\r\nb\r\n--B--\r\n", "Content-Type: multipart/mixed; boundary=B\r\n\r\n--B\r\n\r\ntruncated", "Content-Type: multipart/mixed\r\n\r\nno boundary at all\r\n", "Content-Type: message/rfc822\r\n\r\nSubject: inner\r\n\r\ninner body\r\n", "Content-Type: multipart/digest; boundary=B\r\n\r\n--B\r\n\r\nSubject: x\r\n\r\ny\r\n--B--\r\n", "Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\nY2Fmw6k=\r\n", "Content-Type: text/plain\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\ncaf=C3=A9=\r\n", "Content-Disposition: attachment; filename*=UTF-8''caf%C3%A9.txt\r\n\r\nx\r\n", "Content-Type: multipart/mixed; boundary=\"\"\r\n\r\n--\r\n\r\na\r\n----\r\n", // Preamble and epilogue, which nothing reads and everything must keep. "Content-Type: multipart/mixed; boundary=B\r\n\r\npreamble\r\n--B\r\n\r\na\r\n--B--\r\nepilogue\r\n", // Not a message. "", "\r\n", "no headers and no blank line", "From nobody Mon Jan 1 00:00:00 2001\r\nFrom: x@y\r\n\r\n", }; /// Parsing, writing and parsing again must reach a fixed point. /// /// The first write may differ from the input — a message whose lines end in LF /// comes back with CRLF, and a header the parser could not make sense of is /// dropped — but the second must not differ from the first. A writer that adds /// a line ending, or a parser that eats one, shows up here as a message that /// grows or shrinks every time it is opened. fn messageProperty(input: []const u8) !void { var first: mime.Message = try .parse(backing, input, .{}); defer first.deinit(); // Everything a reader would ask, because a question that allocates is a // question that can leak, and because a `filename` or a `subject` is read // out of the same bytes the parser has just been handed. var walker = first.root.walk(); while (walker.next()) |part| { _ = try part.subject(); _ = try part.filename(); _ = try part.sentAt(); _ = part.isAttachment(); _ = part.transferEncoding(); var addresses = try part.addresses(backing, "from"); defer addresses.deinit(backing); var mailboxes = addresses.mailboxIterator(); while (mailboxes.next()) |mailbox| _ = mailbox.isValid(); if (part.report()) |report| { try testing.expect(part.media_type.isReport()); _ = report; } _ = part.messageId(); var references = try part.references(); while (references.next()) |_| {} _ = try part.declaredSize(); _ = try part.creationDate(); _ = try part.modificationDate(); _ = try part.readDate(); if (try part.uuencodedFile(backing)) |found| { var file = found; file.deinit(backing); } // A part's own Content-ID finds a part, though not necessarily this // one: two parts may claim the same identifier, and the first wins. if (part.contentId()) |id| try testing.expect(first.root.findContentId(id) != null); const decoded = try part.decodeAlloc(backing); defer backing.free(decoded); // The streaming decoder and the one that allocates are the same // decoder, and must agree to the byte. var streamed: Io.Writer.Allocating = .init(backing); defer streamed.deinit(); try part.decodeWriter(&streamed.writer); try testing.expectEqualStrings(decoded, streamed.written()); // Whatever `find` answers with is what it was asked for. if (first.root.find(part.media_type.type, part.media_type.subtype)) |found| { try testing.expect(found.media_type.is(part.media_type.type, part.media_type.subtype)); } const text = try part.textAlloc(backing); defer backing.free(text); if (part.media_type.isText()) { try testing.expect(std.unicode.utf8ValidateSlice(text)); } } const once = try first.toBytesAlloc(backing); defer backing.free(once); var second: mime.Message = try .parse(backing, once, .{}); defer second.deinit(); const twice = try second.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(once, twice); } test "fuzz messages" { for (message_seeds) |seed| try messageProperty(seed); try testing.fuzz({}, fuzzMessage, .{ .corpus = comptime corpusOf(message_max, &message_seeds) }); } fn fuzzMessage(_: void, smith: *testing.Smith) !void { var buffer: [message_max]u8 = undefined; try messageProperty(buffer[0..smith.slice(&buffer)]); } fn runMessage(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [message_max]u8 = undefined; return messageProperty(buffer[0..smith.slice(&buffer)]); } // -- header blocks ---------------------------------------------------------- const header_max = 4096; const header_seeds = [_][]const u8{ "From: jeff@example.com\r\n", "Subject: =?UTF-8?Q?caf=C3=A9?=\r\n", "To: a@x,\r\n b@y,\r\n\tc@z\r\n", "Received: from a\r\nReceived: from b\r\n", "X: \r\n", ": no name\r\n", "NoColon\r\n", "A:1\r\nA:2\r\nA:3\r\n", " leading continuation with no field\r\n", "Subject: a value that is long enough to need folding when it is written " ++ "back out again, several times over in fact\r\n", }; /// A header block written back out and read again gives the same fields, and /// the bytes reach a fixed point. Values are stored in wire form precisely so /// that this is a copy rather than a reconstruction. fn headersProperty(input: []const u8) !void { var first: mime.Headers = try .parse(backing, input); defer first.deinit(); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try first.write(&once.writer); var second: mime.Headers = try .parse(backing, once.written()); defer second.deinit(); try testing.expectEqual(first.fields.items.len, second.fields.items.len); for (first.fields.items, second.fields.items) |a, b| { try testing.expectEqualStrings(a.name, b.name); try testing.expectEqualStrings(a.value, b.value); } var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try second.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); // Every derived form has to be reachable without crashing or leaking. for (first.fields.items) |f| { _ = try first.getUnfolded(f.name); const utf8 = (try first.getUtf8(f.name)).?; try testing.expect(std.unicode.utf8ValidateSlice(utf8)); } } test "fuzz headers" { for (header_seeds) |seed| try headersProperty(seed); try testing.fuzz({}, fuzzHeaders, .{ .corpus = comptime corpusOf(header_max, &header_seeds) }); } fn fuzzHeaders(_: void, smith: *testing.Smith) !void { var buffer: [header_max]u8 = undefined; try headersProperty(buffer[0..smith.slice(&buffer)]); } fn runHeaders(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [header_max]u8 = undefined; return headersProperty(buffer[0..smith.slice(&buffer)]); } // -- addresses -------------------------------------------------------------- const address_max = 1024; const address_seeds = [_][]const u8{ "jeff@example.com", "Jeff Ollie ", "\"Ollie, Jeff\" , alice@example.net", "Friends: a@x, b@y;, c@z", "undisclosed-recipients:;", "jeff@example.com (Ollie, Jeff)", "=?UTF-8?Q?Jos=C3=A9?= ", "<@relay1,@relay2:jeff@example.com>", "\"quoted\\\"escape\"@example.com", "jeff@[192.0.2.1]", "postmaster", ",,,", "a@b@c", "\"unterminated ", "((nested (comments))) x@y", "", }; /// An address list written back out and parsed again names the same /// mailboxes, and the bytes reach a fixed point. /// /// The local part and the domain are compared only where every mailbox in the /// list is one — `Mailbox.isValid` — because that is the promise worth making: /// **an address that is an address is never changed by being written**. A /// mailbox parsed out of something that was not an address is repaired on the /// way out, quoted or bracketed or stripped of the control characters that /// would end the header line, and there is nothing useful to say about what it /// should turn into. What must hold for those is that the bytes settle, which /// the fixed-point check above says. /// A mailbox's domain converted for the wire is safe on the wire, converts /// to the same thing again from its displayed form, and written back into the /// address reads back as that address. fn domainProperty(mailbox: mime.address.Mailbox) !void { const shown = try mailbox.domainUnicodeAlloc(backing); defer backing.free(shown); const ascii = mailbox.domainAsciiAlloc(backing) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidDomain => return, }; defer backing.free(ascii); try testing.expect(mime.idn.isAscii(ascii)); try testing.expect(!mime.idn.hasControl(ascii)); var displayed = mailbox; displayed.domain = shown; if (displayed.domainAsciiAlloc(backing)) |again| { defer backing.free(again); // Ignoring case: an ASCII domain is copied as it was written, while // its displayed form has been through IDNA's mapping and lowercased, // and a domain is the same domain in either case. if (!std.ascii.eqlIgnoreCase(ascii, again)) try testing.expectEqualStrings(ascii, again); } else |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // The displayed form of a domain that was already ASCII and not a // valid IDN is still that domain, and need not convert. error.InvalidDomain => {}, } var plain: Io.Writer.Allocating = .init(backing); defer plain.deinit(); try mailbox.write(&plain.writer); var formatted: Io.Writer.Allocating = .init(backing); defer formatted.deinit(); try formatted.writer.print("{f}", .{mailbox}); try testing.expectEqualStrings(plain.written(), formatted.written()); if (!mailbox.isValid()) return; var sendable = mailbox; sendable.domain = ascii; var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); try sendable.write(&written.writer); var read: mime.address.List = try .parse(backing, written.written()); defer read.deinit(backing); var mailboxes = read.mailboxIterator(); const back = mailboxes.next() orelse return error.LostAMailbox; try testing.expectEqualStrings(mailbox.local_part, back.local_part); try testing.expectEqualStrings(ascii, back.domain); } fn addressProperty(input: []const u8) !void { var first: mime.address.List = try .parse(backing, input); defer first.deinit(backing); // What a sender asks of each address before sending to it. var needs_utf8 = false; var each = first.mailboxIterator(); while (each.next()) |mailbox| { needs_utf8 = needs_utf8 or mailbox.requiresSmtpUtf8(); try domainProperty(mailbox); } try testing.expectEqual(needs_utf8, first.requiresSmtpUtf8()); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try first.write(&once.writer); var second: mime.address.List = try .parse(backing, once.written()); defer second.deinit(backing); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try second.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); var check = first.mailboxIterator(); while (check.next()) |mailbox| { if (!mailbox.isValid()) return; } var a = first.mailboxIterator(); var b = second.mailboxIterator(); while (a.next()) |expected| { const found = b.next() orelse return error.LostAMailbox; try testing.expectEqualStrings(expected.local_part, found.local_part); try testing.expectEqualStrings(expected.domain, found.domain); } try testing.expectEqual(null, b.next()); } test "fuzz addresses" { for (address_seeds) |seed| try addressProperty(seed); try testing.fuzz({}, fuzzAddress, .{ .corpus = comptime corpusOf(address_max, &address_seeds) }); } fn fuzzAddress(_: void, smith: *testing.Smith) !void { var buffer: [address_max]u8 = undefined; try addressProperty(buffer[0..smith.slice(&buffer)]); } fn runAddress(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [address_max]u8 = undefined; return addressProperty(buffer[0..smith.slice(&buffer)]); } // -- dates ------------------------------------------------------------------ const date_max = 256; const date_seeds = [_][]const u8{ "Tue, 01 Jul 2003 10:52:37 +0200", "1 Jul 2003 9:52 -0500", "Sun, 01 Jul 2003 10:52:37 -0000", "Mon, 3 Jan 94 12:00:00 EST", "Tue, 1 Jul 2003 (the first) 10:52:37 +0200 (CEST)", "31 Feb 2003 00:00:00 +0000", "99 Jan 9999 99:99:99 +0000", "Thu, 01 Jan 1970 00:00:00 +0000", "", }; /// A date that parses must survive being written and read again, and must /// name the same instant both times. fn dateProperty(input: []const u8) !void { const first = mime.date.parse(input) catch return; var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); mime.date.write(&w, first.time) catch return; const second = try mime.date.parse(w.buffered()); try testing.expectEqual(first.time.toInstant().timestamp, second.time.toInstant().timestamp); var again: [256]u8 = undefined; var w2: Io.Writer = .fixed(&again); try mime.date.write(&w2, second.time); try testing.expectEqualStrings(w.buffered(), w2.buffered()); // With the zone unknown: the same moment, and it reads back as unknown // exactly when the zone was UTC, the one offset `-0000` can stand for. var unknown: [256]u8 = undefined; var w3: Io.Writer = .fixed(&unknown); try mime.date.writeUnknownZone(&w3, second.time); const third = try mime.date.parse(w3.buffered()); try testing.expectEqual(first.time.toInstant().timestamp, third.time.toInstant().timestamp); try testing.expectEqual(std.mem.endsWith(u8, w.buffered(), "+0000"), third.zone_unknown); } test "fuzz dates" { for (date_seeds) |seed| try dateProperty(seed); try testing.fuzz({}, fuzzDate, .{ .corpus = comptime corpusOf(date_max, &date_seeds) }); } fn fuzzDate(_: void, smith: *testing.Smith) !void { var buffer: [date_max]u8 = undefined; try dateProperty(buffer[0..smith.slice(&buffer)]); } fn runDate(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [date_max]u8 = undefined; return dateProperty(buffer[0..smith.slice(&buffer)]); } // -- encoded words ---------------------------------------------------------- const word_max = 1024; const encoded_word_seeds = [_][]const u8{ "=?UTF-8?Q?caf=C3=A9?=", "=?UTF-8?B?Y2Fmw6k=?=", "=?iso-8859-1?Q?caf=E9?=", "=?shift_jis?B?gqCCog==?=", "=?UTF-8?Q?a?= =?UTF-8?Q?b?=", "Re: =?UTF-8?Q?caf=C3=A9?= today", "look at =?this?= thing", "=?utf-8*en?Q?x?=", "=?utf-8?Q?unterminated", "=??Q?x?=", "plain ascii", "", }; /// Decoding always produces valid UTF-8, and text that is encoded and decoded /// again is the text that went in. /// /// The first half is what makes the result safe to hand to anything else in /// the program; the second is what makes the encoder and the decoder each /// other's inverse, including across the split that a long subject needs. fn encodedWordProperty(input: []const u8) !void { const decoded = try mime.encoded_word.decodeUtf8Alloc(backing, input); defer backing.free(decoded); try testing.expect(std.unicode.utf8ValidateSlice(decoded)); // And back the other way, from whatever the input happens to be. const encoded = try mime.encoded_word.encodeAlloc(backing, input, .{}); defer backing.free(encoded); for (encoded) |c| try testing.expect(c < 0x80); const again = try mime.encoded_word.decodeUtf8Alloc(backing, encoded); defer backing.free(again); if (std.unicode.utf8ValidateSlice(input)) { try testing.expectEqualStrings(input, again); } } test "fuzz encoded words" { for (encoded_word_seeds) |seed| try encodedWordProperty(seed); try testing.fuzz({}, fuzzEncodedWord, .{ .corpus = comptime corpusOf(word_max, &encoded_word_seeds) }); } fn fuzzEncodedWord(_: void, smith: *testing.Smith) !void { var buffer: [word_max]u8 = undefined; try encodedWordProperty(buffer[0..smith.slice(&buffer)]); } fn runEncodedWord(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [word_max]u8 = undefined; return encodedWordProperty(buffer[0..smith.slice(&buffer)]); } // -- parameters ------------------------------------------------------------- const parameter_max = 1024; const parameter_seeds = [_][]const u8{ "text/plain; charset=utf-8", "attachment; filename=\"a file.txt\"", "attachment; filename*=UTF-8''caf%C3%A9.txt", "attachment; filename*0=\"a \"; filename*1=\"b\"", "attachment; filename*0*=UTF-8''a%20; filename*1*=b", "attachment; filename*0=a; filename*2=c", "attachment; filename=\"=?UTF-8?B?Y2Fmw6kudHh0?=\"", "x; a=1; a=2", "x; ; ; =", "x; unterminated=\"quote", "", }; /// A value written as a parameter reads back as itself, whatever is in it. /// /// This is the property that matters for a filename: the whole apparatus of /// RFC 2231 exists so that a name survives the trip, and a writer that picks /// the wrong form, or splits a continuation in the wrong place, silently /// renames somebody's attachment. fn parameterProperty(input: []const u8) !void { var parsed: mime.parameters.Parameters = try .parse(backing, input); defer parsed.deinit(backing); for (parsed.list) |parameter| { const utf8 = (try parsed.getUtf8Alloc(backing, parameter.name)).?; defer backing.free(utf8); try testing.expect(std.unicode.utf8ValidateSlice(utf8)); } var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); try written.writer.writeAll("x"); try mime.parameters.writeParameter(&written.writer, "filename", input, .{}); var read: mime.parameters.Parameters = try .parse(backing, written.written()); defer read.deinit(backing); // An empty value cannot be told from a missing one, and that is the only // input this does not claim to round-trip. if (input.len != 0) { try testing.expectEqualStrings(input, read.get("filename").?); } // The whole list written back out reads as the same list: every name, // every value, in order. Not the charset: `write` declares the one in its // options, and does not transcode what it was handed into it. var list: Io.Writer.Allocating = .init(backing); defer list.deinit(); try parsed.write(&list.writer, .{}); var reread: mime.parameters.Parameters = try .parse(backing, list.written()); defer reread.deinit(backing); try testing.expectEqual(parsed.list.len, reread.list.len); for (parsed.list, reread.list) |expected, got| { try testing.expectEqualStrings(expected.name, got.name); try testing.expectEqualStrings(expected.value, got.value); } // And the same input as a whole `Content-Type`: what is written reads // back as the same type, and writing that again changes nothing. var media_type: mime.MediaType = try .parse(backing, input); defer media_type.deinit(backing); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try media_type.write(&once.writer, .{}); var again: mime.MediaType = try .parse(backing, once.written()); defer again.deinit(backing); try testing.expectEqualStrings(media_type.type, again.type); try testing.expectEqualStrings(media_type.subtype, again.subtype); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer, .{}); try testing.expectEqualStrings(once.written(), twice.written()); // `{f}` is `write` with the default options. var formatted: Io.Writer.Allocating = .init(backing); defer formatted.deinit(); try formatted.writer.print("{f}", .{media_type}); try testing.expectEqualStrings(once.written(), formatted.written()); _ = media_type.isReport(); if (media_type.reportType()) |_| try testing.expect(media_type.isReport()); } test "fuzz parameters" { for (parameter_seeds) |seed| try parameterProperty(seed); try testing.fuzz({}, fuzzParameters, .{ .corpus = comptime corpusOf(parameter_max, ¶meter_seeds) }); } fn fuzzParameters(_: void, smith: *testing.Smith) !void { var buffer: [parameter_max]u8 = undefined; try parameterProperty(buffer[0..smith.slice(&buffer)]); } fn runParameters(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [parameter_max]u8 = undefined; return parameterProperty(buffer[0..smith.slice(&buffer)]); } // -- the codecs ------------------------------------------------------------- const codec_max = 4096; const codec_seeds = [_][]const u8{ "", "f", "fo", "foo", "plain ASCII text\r\n", "a café in Paris\r\n", "trailing space \r\nand a tab\t\r\n", "From the desk of\r\n.\r\n", "=\r\n=3D\r\n=zz\r\n", "Zm9vYmFy", "Zm9v\r\nYmFy", &@as([200]u8, @splat('x')), "\x00\x01\x02\xff\xfe", }; /// Anything encoded and decoded again is what went in, and anything at all can /// be decoded without failing. fn base64Property(input: []const u8) !void { // Decoding is total: RFC 2045 says to ignore what is not in the alphabet, // so there is no input that is not base64 for something. const decoded = try mime.base64.decodeAlloc(backing, input); defer backing.free(decoded); const encoded = try mime.base64.encodeAlloc(backing, input, .{}); defer backing.free(encoded); var lines = std.mem.splitSequence(u8, encoded, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 76); const again = try mime.base64.decodeAlloc(backing, encoded); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); // What the encoder wrote, the strict decoder accepts, and gives back the // same bytes. And where the strict decoder accepts anything at all, it // agrees with the lenient one: strictness only ever refuses. const scratch = try backing.alloc(u8, @max(encoded.len, input.len)); defer backing.free(scratch); const strict = try mime.base64.decodeStrict(scratch, encoded); try testing.expectEqualSlices(u8, input, strict); if (mime.base64.decodeStrict(scratch, input)) |accepted| { try testing.expectEqualSlices(u8, decoded, accepted); } else |_| {} } test "fuzz base64" { for (codec_seeds) |seed| try base64Property(seed); try testing.fuzz({}, fuzzBase64, .{ .corpus = comptime corpusOf(codec_max, &codec_seeds) }); } fn fuzzBase64(_: void, smith: *testing.Smith) !void { var buffer: [codec_max]u8 = undefined; try base64Property(buffer[0..smith.slice(&buffer)]); } fn runBase64(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [codec_max]u8 = undefined; return base64Property(buffer[0..smith.slice(&buffer)]); } /// Binary mode is exactly lossless; text mode is lossless for input that is /// already in canonical form, which is what it documents itself as needing. fn quotedPrintableProperty(input: []const u8) !void { const decoded = try mime.quoted_printable.decodeAlloc(backing, input); defer backing.free(decoded); const binary = try mime.quoted_printable.encodeAlloc(backing, input, .{ .mode = .binary }); defer backing.free(binary); var lines = std.mem.splitSequence(u8, binary, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 76); const again = try mime.quoted_printable.decodeAlloc(backing, binary); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); // Text mode, over input put into canonical form first, which is what the // library does to a body before encoding it. var canonical: Io.Writer.Allocating = .init(backing); defer canonical.deinit(); try mime.line_ending.toCanonical(&canonical.writer, input); const text = try mime.quoted_printable.encodeAlloc(backing, canonical.written(), .{}); defer backing.free(text); // The fixed-buffer encoder, given what its bound promises is enough, fits // and writes what the allocating one does, in either mode. for ([_]mime.quoted_printable.EncodeOptions{ .{ .mode = .binary }, .{} }, [_][]const u8{ binary, text }, [_][]const u8{ input, canonical.written() }) |options, expected, source| { const dest = try backing.alloc(u8, mime.quoted_printable.encodedLenUpperBound(source.len, options)); defer backing.free(dest); try testing.expectEqualStrings(expected, mime.quoted_printable.encode(dest, source, options)); } const text_again = try mime.quoted_printable.decodeAlloc(backing, text); defer backing.free(text_again); try testing.expectEqualSlices(u8, canonical.written(), text_again); } test "fuzz quoted-printable" { for (codec_seeds) |seed| try quotedPrintableProperty(seed); try testing.fuzz({}, fuzzQuotedPrintable, .{ .corpus = comptime corpusOf(codec_max, &codec_seeds) }); } fn fuzzQuotedPrintable(_: void, smith: *testing.Smith) !void { var buffer: [codec_max]u8 = undefined; try quotedPrintableProperty(buffer[0..smith.slice(&buffer)]); } fn runQuotedPrintable(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [codec_max]u8 = undefined; return quotedPrintableProperty(buffer[0..smith.slice(&buffer)]); } // -- format=flowed ---------------------------------------------------------- const flowed_max = 2048; const flowed_seeds = [_][]const u8{ "one line\r\n", "a wrapped \r\nparagraph\r\n", "> quoted and wrapped \r\n> continued\r\n", ">>nested\r\n>one\r\nnone\r\n", " stuffed\r\n From here\r\n", "the message\r\n-- \r\nsignature\r\n", "hello world with a run of spaces\r\n", "日本語のテキストです\r\n", "a line ending in a space \r\n", ">\r\n>>\r\n>>>\r\n", "", " ", "\r\n\r\n\r\n", }; /// Wrapping text and joining it again gives the text back, at every width. /// /// The input has to be normalised first, and the normalisation is the format's /// own limitation rather than a convenience: a line ending in a space *is* a /// wrapped line, so a paragraph that ends in one cannot be told from one that /// continues, and no encoding can preserve the difference. Stripping those is /// exactly what a generator has to do, and what is left is what the format can /// carry. fn flowedProperty(input: []const u8) !void { // Joining is total: there is no input that is not a flowed body for // something, and it must never fail on one. const joined = try mime.flowed.unflowAlloc(backing, input, .{}); defer backing.free(joined); const deleted = try mime.flowed.unflowAlloc(backing, input, .{ .delete_space = true }); defer backing.free(deleted); const normalised = try normaliseParagraphs(input); defer backing.free(normalised); for ([_]usize{ 1, 5, 20, 72, 998 }) |width| { for ([_]bool{ false, true }) |delete_space| { const wrapped = try mime.flowed.flowAlloc(backing, normalised, .{ .width = width, .delete_space = delete_space, }); defer backing.free(wrapped); // The width is deliberately not asserted here. A line is allowed // to run over it in three different ways -- an unbreakable word, a // break pushed out so that it did not come out as the signature // separator, and the separator itself -- and a property that has // to enumerate its own exceptions tests the exceptions rather than // the rule. The wrapping tests beside `flowWriter` pin the width // on inputs where the answer is known; what is worth checking over // input nobody wrote is that nothing is lost. const back = try mime.flowed.unflowAlloc(backing, wrapped, .{ .delete_space = delete_space, }); defer backing.free(back); try testing.expectEqualStrings(normalised, back); } } } /// The input as paragraphs the format can carry: CRLF endings, and no line /// ending in a space. fn normaliseParagraphs(input: []const u8) ![]u8 { var out: Io.Writer.Allocating = .init(backing); errdefer out.deinit(); var rest = input; while (rest.len != 0) { const nl = std.mem.findScalar(u8, rest, '\n'); const end = if (nl) |at| (if (at != 0 and rest[at - 1] == '\r') at - 1 else at) else rest.len; try out.writer.writeAll(std.mem.trimEnd(u8, rest[0..end], " ")); try out.writer.writeAll("\r\n"); rest = if (nl) |at| rest[at + 1 ..] else rest[rest.len..]; } return out.toOwnedSlice(); } test "fuzz flowed" { for (flowed_seeds) |seed| try flowedProperty(seed); try testing.fuzz({}, fuzzFlowed, .{ .corpus = comptime corpusOf(flowed_max, &flowed_seeds) }); } fn fuzzFlowed(_: void, smith: *testing.Smith) !void { var buffer: [flowed_max]u8 = undefined; try flowedProperty(buffer[0..smith.slice(&buffer)]); } fn runFlowed(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [flowed_max]u8 = undefined; return flowedProperty(buffer[0..smith.slice(&buffer)]); } // -- uuencode --------------------------------------------------------------- const uuencode_max = 4096; const uuencode_seeds = [_][]const u8{ "begin 644 cat.txt\r\n#0V%T\r\n`\r\nend\r\n", "#0V%T\n`\n", "!80 \n \n", "begin 755 script.sh\n#0V%T\n`\nend\n", "a note first\n\nbegin 644 x\n#0V%T\n`\nend\n", "begin 644 truncated\n#0V%T\n", "begin\n", "X0V%T\n`\n", "not uuencode at all\n", "", }; /// Decoding a uuencoded body never fails, and anything encoded and decoded /// again is what went in — including the name, which is the one thing this /// encoding carries that the others do not. fn uuencodeProperty(input: []const u8) !void { const uuencode = mime.transfer_encoding.TransferEncoding.uuencode; // Total, like every other decoder here: a damaged attachment arrives // damaged rather than not arriving. const decoded = try uuencode.decodeAlloc(backing, input); defer backing.free(decoded); var encoded: Io.Writer.Allocating = .init(backing); defer encoded.deinit(); uuencode.encodeWriter(&encoded.writer, input, .{ .name = "fuzz.bin" }) catch return error.OutOfMemory; // Every line is inside what a transport will carry. var lines = std.mem.splitSequence(u8, encoded.written(), "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 998); try testing.expectEqualStrings("fuzz.bin", uuencode.embeddedName(encoded.written()).?); const again = try uuencode.decodeAlloc(backing, encoded.written()); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); } test "fuzz uuencode" { for (uuencode_seeds) |seed| try uuencodeProperty(seed); try testing.fuzz({}, fuzzUuencode, .{ .corpus = comptime corpusOf(uuencode_max, &uuencode_seeds) }); } fn fuzzUuencode(_: void, smith: *testing.Smith) !void { var buffer: [uuencode_max]u8 = undefined; try uuencodeProperty(buffer[0..smith.slice(&buffer)]); } fn runUuencode(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [uuencode_max]u8 = undefined; return uuencodeProperty(buffer[0..smith.slice(&buffer)]); } // -- internationalized domain names ----------------------------------------- const idn_max = 512; const idn_seeds = [_][]const u8{ "example.com", "bücher.example", "xn--bcher-kva.example", "BÜCHER.EXAMPLE", "日本語.jp", "xn--wgv71a119e.jp", "a.b.c.example.com", "mail_1.example.com", "[192.0.2.1]", "a..b.example", "xn--", "xn--not-punycode", "example.com.", "", }; /// The A-label form is ASCII, is free of anything that could end a header /// line, and is a fixed point; and a name that survives the trip to Unicode /// and back is the same name. fn idnProperty(input: []const u8) !void { // Display is total: whatever arrives, something can be shown. const shown = try mime.idn.toUnicodeAlloc(backing, input); defer backing.free(shown); const ascii = mime.idn.toAsciiAlloc(backing, input) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // A name that will not encode is refused, which is the whole point of // that function: an address that cannot be encoded cannot be // delivered to, and guessing would deliver it somewhere else. error.InvalidDomain => return, }; defer backing.free(ascii); // What comes out is safe to put in a header, which is what it is for. try testing.expect(mime.idn.isAscii(ascii)); try testing.expect(!mime.idn.hasControl(ascii)); // Encoding an A-label again changes nothing. A conversion that is not a // fixed point is one that corrupts an address every time it is forwarded. const twice = try mime.idn.toAsciiAlloc(backing, ascii); defer backing.free(twice); try testing.expectEqualStrings(ascii, twice); // And the round trip through the displayed form is the same name, which // is the property that makes it safe to show one and send the other. const back = try mime.idn.toUnicodeAlloc(backing, ascii); defer backing.free(back); const again = mime.idn.toAsciiAlloc(backing, back) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidDomain => return, }; defer backing.free(again); try testing.expectEqualStrings(ascii, again); } test "fuzz idn" { for (idn_seeds) |seed| try idnProperty(seed); try testing.fuzz({}, fuzzIdn, .{ .corpus = comptime corpusOf(idn_max, &idn_seeds) }); } fn fuzzIdn(_: void, smith: *testing.Smith) !void { var buffer: [idn_max]u8 = undefined; try idnProperty(buffer[0..smith.slice(&buffer)]); } fn runIdn(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [idn_max]u8 = undefined; return idnProperty(buffer[0..smith.slice(&buffer)]); } // -- the streaming parser against the tree ---------------------------------- /// The two parsers see the same message. /// /// This is the property that makes a second parser safe to have at all. Two /// implementations of one format drift apart the moment either is touched, and /// the ways they can disagree — where a part begins, which delimiter closed /// what, whether a fold was joined the same way — are exactly the ways a /// message gets misread. Rather than assert that separately for each, both are /// asked to describe what they saw and the descriptions are compared. fn parserProperty(input: []const u8) !void { var message: mime.Message = try .parse(backing, input, .{}); defer message.deinit(); // The one documented difference: a `message/rfc822` that is transfer // encoded is decoded and opened by the tree, and left as bytes by the // stream, because opening it would mean holding it. var walker = message.root.walk(); while (walker.next()) |part| { if (part.media_type.isEncapsulatedMessage() and !part.transferEncoding().isIdentity()) { return; } } var from_tree: Io.Writer.Allocating = .init(backing); defer from_tree.deinit(); try describeTree(&from_tree.writer, &message.root, 0); var from_stream: Io.Writer.Allocating = .init(backing); defer from_stream.deinit(); // A small buffer on purpose: the awkward cases are the ones where a line // does not fit in it. var buffer: [128]u8 = undefined; var fixed: Io.Reader = .fixed(input); var limited = fixed.limited(.unlimited, &buffer); try describeStream(&from_stream.writer, &limited.interface); try testing.expectEqualStrings(from_tree.written(), from_stream.written()); // And once more, taking each leaf's body with `streamBody` rather than // event by event: the convenience must hand over the same bytes. var from_bodies: Io.Writer.Allocating = .init(backing); defer from_bodies.deinit(); var again: Io.Reader = .fixed(input); var limited_again = again.limited(.unlimited, &buffer); try describeStreamBodies(&from_bodies.writer, &limited_again.interface); try testing.expectEqualStrings(from_tree.written(), from_bodies.written()); } /// `describeStream`, but reading every leaf's body with `streamBody`. /// /// Only where the media type says the entity is a leaf: called on a container, /// `streamBody` stops at the first child's `begin` and consumes it, which its /// doc comment calls asking at the wrong moment. It consumes the leaf's `end` /// in the ordinary way, so the depth for that line is taken beforehand. fn describeStreamBodies(w: *Io.Writer, input: *Io.Reader) !void { var parser: mime.Parser = .init(backing, input, .{}); defer parser.deinit(); var body: Io.Writer.Allocating = .init(backing); defer body.deinit(); while (true) switch (try parser.next()) { .begin => |d| try w.print("begin {d}\n", .{d}), .field => |f| try w.print("field {s}={s}\n", .{ f.name, f.value }), .headers_end => { const media_type = parser.mediaType(); try w.print("headers {s}/{s}\n", .{ media_type.type, media_type.subtype }); if (media_type.isMultipart() or media_type.isEncapsulatedMessage()) continue; const depth = parser.depth(); try parser.streamBody(&body.writer); if (body.written().len != 0) { try w.print("body {f}\n", .{std.ascii.hexEscape(body.written(), .lower)}); body.clearRetainingCapacity(); } try w.print("end {d}\n", .{depth}); }, .body => |chunk| try body.writer.writeAll(chunk), .end => |d| { if (body.written().len != 0) { try w.print("body {f}\n", .{std.ascii.hexEscape(body.written(), .lower)}); body.clearRetainingCapacity(); } try w.print("end {d}\n", .{d}); }, .eof => break, }; } fn describeTree(w: *Io.Writer, part: *mime.Message.Part, depth: u8) !void { try w.print("begin {d}\n", .{depth}); for (part.headers.fields.items) |f| { const unfolded = try mime.field.unfoldAlloc(backing, f.value); defer backing.free(unfolded); try w.print("field {s}={s}\n", .{ f.name, std.mem.trim(u8, unfolded, " \t") }); } try w.print("headers {s}/{s}\n", .{ part.media_type.type, part.media_type.subtype }); switch (part.body) { .raw => |bytes| if (bytes.len != 0) { try w.print("body {f}\n", .{std.ascii.hexEscape(bytes, .lower)}); }, .multipart => |multipart| for (multipart.parts.items) |child| { try describeTree(w, child, depth + 1); }, .message => |inner| try describeTree(w, inner, depth + 1), } try w.print("end {d}\n", .{depth}); } fn describeStream(w: *Io.Writer, input: *Io.Reader) !void { var parser: mime.Parser = .init(backing, input, .{}); defer parser.deinit(); // The body arrives in as many chunks as the reader's buffer dictates, and // the tree has it whole, so it is gathered before being described. var body: Io.Writer.Allocating = .init(backing); defer body.deinit(); while (true) switch (try parser.next()) { .begin => |d| try w.print("begin {d}\n", .{d}), .field => |f| try w.print("field {s}={s}\n", .{ f.name, f.value }), .headers_end => try w.print("headers {s}/{s}\n", .{ parser.mediaType().type, parser.mediaType().subtype, }), .body => |chunk| try body.writer.writeAll(chunk), .end => |d| { if (body.written().len != 0) { try w.print("body {f}\n", .{std.ascii.hexEscape(body.written(), .lower)}); body.clearRetainingCapacity(); } try w.print("end {d}\n", .{d}); }, .eof => break, }; } test "fuzz the parser against the tree" { for (message_seeds) |seed| try parserProperty(seed); try testing.fuzz({}, fuzzParser, .{ .corpus = comptime corpusOf(message_max, &message_seeds) }); } fn fuzzParser(_: void, smith: *testing.Smith) !void { var buffer: [message_max]u8 = undefined; try parserProperty(buffer[0..smith.slice(&buffer)]); } fn runParser(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [message_max]u8 = undefined; return parserProperty(buffer[0..smith.slice(&buffer)]); } // -- mailto URLs ------------------------------------------------------------ const mailto_max = 2048; const mailto_seeds = [_][]const u8{ "mailto:alice@example.net", "mailto:alice@example.net?subject=Lunch&body=Shall%20we%3F", "mailto:a@x,b@y?to=c@z&cc=d@w&bcc=e@v", "mailto:?subject=Hello", "mailto:alice@example.net?from=bank@example.com", "mailto:jeff%2Blists@example.com", "mailto:%22Ollie%2C%20Jeff%22%20%3Cjeff@example.com%3E", "mailto:x?subject=%C3%BC&body=%", "mailto:x?=&=&a=b=c", "mailto:", "https://example.com", "", }; /// A URL is attacker-supplied by construction — it arrives in a web page — so /// what matters is what it cannot make the message become. fn mailtoProperty(input: []const u8) !void { var message = mime.mailto.parse(backing, input, .{}) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.NotMailto => return, }; defer message.deinit(); // Nothing outside the safe list was set, however the URL spelled it. // `MIME-Version` and the `Content-*` headers are deliberately absent from // this list: those are written by the library rather than by the URL. const forbidden = [_][]const u8{ "from", "reply-to", "sender", "return-path", "received", "message-id", "date", "resent-from", "disposition-notification-to", }; for (forbidden) |name| try testing.expect(!message.root.headers.has(name)); // The Content-Type is the one this library wrote. try testing.expect(message.root.media_type.is("text", "plain")); try testing.expectEqual(1, message.root.headers.count("content-type")); // What comes out is a message a transport will carry, and — the part that // matters — reading it back finds no field the URL was not allowed to set. // A header injected through a URL would appear here and nowhere else. // // Not asserted: that it is all ASCII. A local part may be UTF-8 under RFC // 6532, a `mailto:` is a UTF-8 URI, and refusing one would be refusing an // address that works. const written = try message.toBytesAlloc(backing); defer backing.free(written); var lines = std.mem.splitSequence(u8, written, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 998); var reread: mime.Message = try .parse(backing, written, .{}); defer reread.deinit(); for (forbidden) |name| try testing.expect(!reread.root.headers.has(name)); // Whatever it parsed to, it parses to the same thing again. var again = try mime.mailto.parse(backing, input, .{}); defer again.deinit(); const twice = try again.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(written, twice); } test "fuzz mailto" { for (mailto_seeds) |seed| try mailtoProperty(seed); try testing.fuzz({}, fuzzMailto, .{ .corpus = comptime corpusOf(mailto_max, &mailto_seeds) }); } fn fuzzMailto(_: void, smith: *testing.Smith) !void { var buffer: [mailto_max]u8 = undefined; try mailtoProperty(buffer[0..smith.slice(&buffer)]); } fn runMailto(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [mailto_max]u8 = undefined; return mailtoProperty(buffer[0..smith.slice(&buffer)]); } // -- writing a mailto: URL --------------------------------------------------- const field_max = 1024; /// A `mailto:` written from fields reads back as those fields. /// /// Two ways round. As a URL, on its own terms: the path percent-decodes to /// the recipients, and the query splits on `&` into exactly the fields that /// were set, in order, each decoding to what it was -- which is what says the /// escaping is complete, since an `&` or a `?` that got through unescaped /// would split something that was one field into two. And as a message, /// through `mailto.parse`: the subject and the body come back. fn mailtoWriteProperty(fields: mime.mailto.Fields) !void { const url = try mime.mailto.writeUrlAlloc(backing, fields); defer backing.free(url); try testing.expect(std.mem.startsWith(u8, url, "mailto:")); const rest = url["mailto:".len..]; const question = std.mem.findScalar(u8, rest, '?'); try expectPercentDecodes(fields.to, rest[0 .. question orelse rest.len]); var query = std.mem.splitScalar(u8, if (question) |at| rest[at + 1 ..] else "", '&'); var any = false; inline for (.{ .{ "cc", fields.cc }, .{ "bcc", fields.bcc }, .{ "subject", fields.subject }, .{ "body", fields.body }, }) |pair| { if (pair[1].len != 0) { any = true; const field = query.next() orelse return error.FieldDisappeared; try testing.expect(std.mem.startsWith(u8, field, pair[0] ++ "=")); try expectPercentDecodes(pair[1], field[pair[0].len + 1 ..]); } } if (any) try testing.expectEqual(null, query.next()) else try testing.expectEqual(null, question); var message = try mime.mailto.parse(backing, url, .{}); defer message.deinit(); if (fields.subject.len != 0 and std.unicode.utf8ValidateSlice(fields.subject)) { const subject = (try message.root.subject()) orelse return error.SubjectDisappeared; try testing.expectEqualStrings(std.mem.trim(u8, fields.subject, " \t"), std.mem.trim(u8, subject, " \t")); } if (std.unicode.utf8ValidateSlice(fields.body)) { const body = try message.root.textAlloc(backing); defer backing.free(body); try expectCanonical(fields.body, body); } } /// `encoded` is `expected` percent-encoded: every `%` begins two hex digits, /// and undoing them gives `expected` exactly. fn expectPercentDecodes(expected: []const u8, encoded: []const u8) !void { var decoded: Io.Writer.Allocating = .init(backing); defer decoded.deinit(); var i: usize = 0; while (i < encoded.len) : (i += 1) { if (encoded[i] != '%') { try decoded.writer.writeByte(encoded[i]); continue; } if (i + 2 >= encoded.len) return error.TruncatedEscape; const byte = std.fmt.parseInt(u8, encoded[i + 1 ..][0..2], 16) catch return error.BadEscape; try decoded.writer.writeByte(byte); i += 2; } try testing.expectEqualStrings(expected, decoded.written()); } test "fuzz mailto-write" { try testing.fuzz({}, fuzzMailtoWrite, .{ .corpus = comptime corpusOfRotations(field_max, 5, &build_seeds) }); } fn fuzzMailtoWrite(_: void, smith: *testing.Smith) !void { var buffers: [5][field_max]u8 = undefined; try mailtoWriteProperty(mailtoFields(smith, &buffers)); } fn runMailtoWrite(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffers: [5][field_max]u8 = undefined; return mailtoWriteProperty(mailtoFields(&smith, &buffers)); } fn mailtoFields(smith: *testing.Smith, buffers: *[5][field_max]u8) mime.mailto.Fields { var slices: [5][]const u8 = undefined; for (&slices, buffers) |*slice, *buffer| slice.* = buffer[0..smith.slice(buffer)]; return .{ .to = slices[0], .cc = slices[1], .bcc = slices[2], .subject = slices[3], .body = slices[4] }; } // -- message identifiers ----------------------------------------------------- const message_id_max = 2048; const message_id_seeds = [_][]const u8{ "", " ", ",\r\n (a comment) ", "a@x b@y", "", "<>", "< spaced @ x >", "not an identifier at all", "", }; /// What a `References` header is read as, it is written back as. /// /// `count`, `first` and `collect` are three questions about the same list /// and must agree. `writeList` drops anything that could close a bracket or /// end the line, so what reads back is each identifier less those, and an /// identifier with nothing else in it is gone; writing what was read back /// changes nothing. And `trim` keeps the thread's first message and its most /// recent ones, which is what threading is built on. fn messageIdProperty(input: []const u8) !void { const ids = try mime.message_id.collect(backing, input); defer backing.free(ids); try testing.expectEqual(ids.len, mime.message_id.count(input)); if (ids.len != 0) try testing.expectEqualStrings(ids[0], mime.message_id.first(input).?); var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); try mime.message_id.writeList(&written.writer, ids); const read = try mime.message_id.collect(backing, written.written()); defer backing.free(read); var kept: usize = 0; for (ids) |id| { var stripped: Io.Writer.Allocating = .init(backing); defer stripped.deinit(); for (id) |c| switch (c) { 0...0x20, 0x7f, '<', '>' => {}, else => try stripped.writer.writeByte(c), }; if (stripped.written().len == 0) continue; if (kept >= read.len) return error.IdentifierDisappeared; try testing.expectEqualStrings(stripped.written(), read[kept]); kept += 1; } try testing.expectEqual(kept, read.len); var again: Io.Writer.Allocating = .init(backing); defer again.deinit(); try mime.message_id.writeList(&again.writer, read); const reread = try mime.message_id.collect(backing, again.written()); defer backing.free(reread); try testing.expectEqual(read.len, reread.len); for (read, reread) |a, b| try testing.expectEqualStrings(a, b); var buffer: [8][]const u8 = undefined; for (0..buffer.len + 1) |max| { const trimmed = mime.message_id.trim(ids, &buffer, max); try testing.expectEqual(@min(max, ids.len), trimmed.len); if (trimmed.len == 0) continue; try testing.expectEqualStrings(ids[0], trimmed[0]); if (trimmed.len > 1) try testing.expectEqualStrings(ids[ids.len - 1], trimmed[trimmed.len - 1]); } } test "fuzz message-ids" { try testing.fuzz({}, fuzzMessageIds, .{ .corpus = comptime corpusOf(message_id_max, &message_id_seeds) }); } fn fuzzMessageIds(_: void, smith: *testing.Smith) !void { var buffer: [message_id_max]u8 = undefined; try messageIdProperty(buffer[0..smith.slice(&buffer)]); } fn runMessageIds(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [message_id_max]u8 = undefined; return messageIdProperty(buffer[0..smith.slice(&buffer)]); } // -- line endings ------------------------------------------------------------- /// Canonical form is CRLF everywhere, and it is a fixed point. /// /// `canonicalLen` is the length `toCanonical` writes, so a caller sizing a /// buffer with one and filling it with the other neither overruns nor leaves /// a gap. Converting canonical text to LF and back gives the canonical text /// again, and converting it to CRLF is no conversion at all. fn lineEndingProperty(input: []const u8) !void { var canonical: Io.Writer.Allocating = .init(backing); defer canonical.deinit(); try mime.line_ending.toCanonical(&canonical.writer, input); try testing.expectEqual(canonical.written().len, mime.line_ending.canonicalLen(input)); // Only where every CR is the start of a line ending. A bare CR in front // of one -- `\r\r\n` -- comes out in LF form as `\r\n`, which LF text // has no way to tell from a line ending, and so cannot come back. if (!hasBareCr(canonical.written())) { var lf: Io.Writer.Allocating = .init(backing); defer lf.deinit(); try mime.line_ending.fromCanonical(&lf.writer, canonical.written(), .lf); var back: Io.Writer.Allocating = .init(backing); defer back.deinit(); try mime.line_ending.toCanonical(&back.writer, lf.written()); try testing.expectEqualStrings(canonical.written(), back.written()); } var crlf: Io.Writer.Allocating = .init(backing); defer crlf.deinit(); try mime.line_ending.fromCanonical(&crlf.writer, canonical.written(), .crlf); try testing.expectEqualStrings(canonical.written(), crlf.written()); } fn hasBareCr(text: []const u8) bool { for (text, 0..) |c, i| { if (c == '\r' and (i + 1 == text.len or text[i + 1] != '\n')) return true; } return false; } test "fuzz line-endings" { try testing.fuzz({}, fuzzLineEndings, .{ .corpus = comptime corpusOf(codec_max, &codec_seeds) }); } fn fuzzLineEndings(_: void, smith: *testing.Smith) !void { var buffer: [codec_max]u8 = undefined; try lineEndingProperty(buffer[0..smith.slice(&buffer)]); } fn runLineEndings(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [codec_max]u8 = undefined; return lineEndingProperty(buffer[0..smith.slice(&buffer)]); } // -- the header lexer ---------------------------------------------------------- const lexer_max = 1024; const lexer_seeds = [_][]const u8{ "jeff@example.com", " (a (nested) comment) jeff", "\"O\\\"Brien, Sean\" ", "\"never closed", "[192.0.2.1]", "[unterminated", "..@example.com", "text/plain; charset=utf-8", "a b", " leading", "\x00\x01\r\n\t", "", }; /// Text written for a grammar is read back by that grammar as itself. /// /// `quoteWriter` writes a bare atom, dot-atom, phrase or token where it can /// and a quoted-string where it cannot, dropping the control bytes nothing may /// carry; scanning that with the matching `Scanner` call, and `unquoteAlloc` /// where it was quoted, gives back the text less those bytes and consumes /// everything. And the scanner itself, walked over arbitrary input with each /// of its calls in turn, always makes progress and only ever returns what its /// grammar allows. fn lexerProperty(input: []const u8) !void { var expected: Io.Writer.Allocating = .init(backing); defer expected.deinit(); for (input) |c| switch (c) { 0...0x1f, 127 => {}, else => try expected.writer.writeByte(c), }; inline for (.{ .atom, .dot_atom, .phrase, .token }) |syntax| { var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); try mime.lexer.quoteWriter(&written.writer, input, syntax); var scanner: mime.lexer.Scanner = .init(written.written()); var got: Io.Writer.Allocating = .init(backing); defer got.deinit(); if (scanner.peek() == '"') { const raw = scanner.quotedString().?; const unquoted = try mime.lexer.unquoteAlloc(backing, raw); defer backing.free(unquoted); try got.writer.writeAll(unquoted); } else switch (syntax) { .atom => try got.writer.writeAll(scanner.atom() orelse ""), .dot_atom => try got.writer.writeAll(scanner.dotAtom() orelse ""), .token => try got.writer.writeAll(scanner.token() orelse ""), .phrase => { // A phrase is words with single spaces between them, which is // the only spacing `needsQuoting` lets through bare. var first = true; while (scanner.atom()) |word| : (first = false) { if (!first) try got.writer.writeByte(' '); try got.writer.writeAll(word); } }, else => unreachable, } try testing.expectEqualStrings(expected.written(), got.written()); scanner.skipCfws(); try testing.expect(scanner.atEnd()); } var scanner: mime.lexer.Scanner = .init(input); var step: usize = 0; while (!scanner.atEnd()) : (step += 1) { const before = scanner.index; switch (step % 6) { 0 => if (scanner.dotAtom()) |run| { for (run) |c| try testing.expect(mime.lexer.isAtext(c) or c == '.'); }, 1 => if (scanner.token()) |run| { for (run) |c| try testing.expect(mime.lexer.isTokenChar(c)); }, 2 => if (scanner.domainLiteral()) |inside| try expectWithin(input, inside), 3 => if (scanner.quotedString()) |inside| { try expectWithin(input, inside); const unquoted = try mime.lexer.unquoteAlloc(backing, inside); defer backing.free(unquoted); try testing.expect(unquoted.len <= inside.len); }, 4 => if (scanner.word()) |word| switch (word) { .atom => |run| for (run) |c| try testing.expect(mime.lexer.isAtext(c)), .quoted => |inside| try expectWithin(input, inside), }, else => _ = scanner.eat(scanner.peek() orelse 0), } try testing.expect(scanner.index >= before); try testing.expect(scanner.index <= input.len); // Six calls that all found nothing to take: step over the byte that // none of them wanted. if (step % 6 == 5 and scanner.index == before) scanner.index += 1; } } /// `inner` is a slice of `outer`, not a copy or something past its end. fn expectWithin(outer: []const u8, inner: []const u8) !void { if (inner.len == 0) return; const start = @intFromPtr(inner.ptr); try testing.expect(start >= @intFromPtr(outer.ptr)); try testing.expect(start + inner.len <= @intFromPtr(outer.ptr) + outer.len); } test "fuzz lexer" { try testing.fuzz({}, fuzzLexer, .{ .corpus = comptime corpusOf(lexer_max, &lexer_seeds) }); } fn fuzzLexer(_: void, smith: *testing.Smith) !void { var buffer: [lexer_max]u8 = undefined; try lexerProperty(buffer[0..smith.slice(&buffer)]); } fn runLexer(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [lexer_max]u8 = undefined; return lexerProperty(buffer[0..smith.slice(&buffer)]); } // -- a multipart with a boundary the caller chose ----------------------------- /// `makeMultipart` refuses exactly the boundaries RFC 2046 does not allow -- /// `isValidBoundary` -- and a generated one from `makeMultipartRandom` stands /// in for those, and must itself be allowed. Where the boundary does not occur /// in what the parts say, which is the half of the rule only the caller can /// keep, the parts that go in are the parts that come out: as many, in order, /// each with its text. fn boundaryProperty(boundary: []const u8, text: []const u8) !void { // A boundary RFC 2046 does not allow is refused, and the caller falls // back on a generated one, as a caller with no boundary of its own does. var prng: std.Random.DefaultPrng = .init(knob(text, 31)); var message: mime.Message = try .init(backing); defer message.deinit(); const chosen = if (message.makeMultipart("mixed", boundary)) true else |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidBoundary => false, }; try testing.expectEqual(mime.Message.isValidBoundary(boundary), chosen); if (!chosen) try message.makeMultipartRandom("mixed", prng.random()); const count = 1 + knob(text, 23) % 3; for (0..count) |i| { const part = try message.root.addPart(); try part.setText(text, .{ .encoding = switch ((knob(text, 29) >> @intCast(i * 2)) & 3) { 0 => null, 1 => .quoted_printable, 2 => .base64, else => .eight_bit, } }); } const wire = try message.toBytesAlloc(backing); defer backing.free(wire); var read: mime.Message = try .parse(backing, wire, .{}); defer read.deinit(); const used = read.root.media_type.boundary() orelse return error.BoundaryDisappeared; if (chosen) try testing.expectEqualStrings(boundary, used); try testing.expect(mime.Message.isValidBoundary(used)); const delimiter = try std.mem.concat(backing, u8, &.{ "--", used }); defer backing.free(delimiter); if (std.mem.find(u8, text, delimiter) != null) return; const parts = switch (read.root.body) { .multipart => |multipart| multipart.parts.items, else => return error.NotMultipart, }; try testing.expectEqual(count, parts.len); if (std.unicode.utf8ValidateSlice(text)) for (parts) |part| { const got = try part.textAlloc(backing); defer backing.free(got); try expectCanonical(text, got); }; } const boundary_seeds = [_][]const u8{ "B", "=_Part_1", "simple boundary", "trailing space ", "----=_NextPart_000_0000_01D00000.00000000", "contains\r\nCRLF", "\"quoted\"", &@as([70]u8, @splat('x')), &@as([71]u8, @splat('x')), "", }; test "fuzz boundary" { try testing.fuzz({}, fuzzBoundary, .{ .corpus = comptime corpusOfPairs(build_max, &boundary_seeds, &build_seeds) }); } fn fuzzBoundary(_: void, smith: *testing.Smith) !void { var boundary: [build_max]u8 = undefined; var text: [build_max]u8 = undefined; const chosen = boundary[0..smith.slice(&boundary)]; try boundaryProperty(chosen, text[0..smith.slice(&text)]); } fn runBoundary(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var boundary: [build_max]u8 = undefined; var text: [build_max]u8 = undefined; const chosen = boundary[0..smith.slice(&boundary)]; return boundaryProperty(chosen, text[0..smith.slice(&text)]); } // -- received --------------------------------------------------------------- const received_max = 1024; const received_seeds = [_][]const u8{ "client.example.com", "evil\r\nBcc: victim@example.test", "evil\nX-Spam-Status: No", "closes) a paren (and opens one", "a\x00b", "\r", "\n", " ", "", }; /// A `Received:` is assembled almost entirely out of things the peer said — /// the `EHLO` name, and whatever the caller passed through from the session — /// so the property is containment: whatever goes into the clauses, what comes /// out is **one** header field, and the fields that were already there are /// still exactly themselves. /// /// The failure this is looking for is a hop that can be made to write a header /// of the sender's choosing into every message it relays. fn receivedProperty(input: []const u8) !void { var when: mime.datetime.DateTime = .{ .year = 2003, .month = .Jul, .day = 1, .hour = 10, .minute = 52, .second = 37, .offset = 2 * 60 * 60, }; when.updateDayOfWeek(); // The protocol a session is named by: five questions, one name, and it // goes into the field as the `with` it is. const bits = knob(input, 17); const protocol = mime.received.protocolFor(.{ .extended = bits & 1 != 0, .tls = bits & 2 != 0, .authenticated = bits & 4 != 0, .lmtp = bits & 8 != 0, .utf8 = bits & 16 != 0, }); { const named: mime.received.Received = .{ .by = "mx.example", .with = protocol, .received_at = when }; var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); try out.writer.print("{f}", .{named}); var plain: Io.Writer.Allocating = .init(backing); defer plain.deinit(); try named.write(&plain.writer); try testing.expectEqualStrings(plain.written(), out.written()); try testing.expect(std.mem.find(u8, out.written(), protocol) != null); if (bits & 2 != 0) try testing.expect(std.mem.findScalar(u8, protocol, 'S') != null); } // Everything a server would take off the wire, taken off the wire. const received: mime.received.Received = .{ .from = input, .from_info = input, .by = input, .by_info = input, .via = input, .with = input, .id = input, .for_recipient = input, .received_at = when, }; var message: mime.Message = try .parse( backing, "From: alice@example.com\r\nSubject: seed\r\n\r\nbody\r\n", .{}, ); defer message.deinit(); try message.addReceived(received); const written = try message.toBytesAlloc(backing); defer backing.free(written); var again: mime.Message = try .parse(backing, written, .{}); defer again.deinit(); // One field, whatever was in it. try testing.expectEqual(1, again.root.headers.count("received")); try testing.expectEqual(3, again.root.headers.fields.items.len); // And it is still the first one: a trace field that has drifted down the // block no longer says when this hop received the message relative to the // hops below it. try testing.expect(std.ascii.eqlIgnoreCase(again.root.headers.fields.items[0].name, "Received")); // The fields that were already there are untouched. try testing.expectEqualStrings("alice@example.com", again.root.headers.get("from") orelse ""); try testing.expectEqualStrings("seed", again.root.headers.get("subject") orelse ""); // And the second write agrees with the first. const twice = try again.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(written, twice); } test "fuzz received" { for (received_seeds) |seed| try receivedProperty(seed); try testing.fuzz({}, fuzzReceived, .{ .corpus = comptime corpusOf(received_max, &received_seeds) }); } fn fuzzReceived(_: void, smith: *testing.Smith) !void { var buffer: [received_max]u8 = undefined; try receivedProperty(buffer[0..smith.slice(&buffer)]); } fn runReceived(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [received_max]u8 = undefined; return receivedProperty(buffer[0..smith.slice(&buffer)]); } // -- report ----------------------------------------------------------------- const report_max = 4096; const report_seeds = [_][]const u8{ "Reporting-MTA: dns; mx.example.net\r\nArrival-Date: Tue, 01 Jul 2003 10:00:00 +0200\r\n" ++ "\r\nFinal-Recipient: rfc822; nobody@example.com\r\nAction: failed\r\nStatus: 5.1.1\r\n" ++ "Diagnostic-Code: smtp; 550 5.1.1 No such user\r\n", // No per-message group at all, which happens. "Final-Recipient: rfc822; a@example.com\r\nAction: delayed\r\nStatus: 4.4.1\r\n", // Two recipients, and a group that is neither. "Reporting-MTA: dns; mx\r\n\r\nFinal-Recipient: rfc822; a@x\r\nAction: failed\r\n" ++ "\r\nFinal-Recipient: rfc822; b@x\r\nAction: delivered\r\n\r\nX-Junk: here\r\n", // A read receipt. "Reporting-UA: mail.example.net; Thunderbird\r\nFinal-Recipient: rfc822; a@x\r\n" ++ "Original-Message-ID: <1@x>\r\nDisposition: manual-action/MDN-sent-manually; displayed\r\n", // A spam complaint. "Feedback-Type: abuse\r\nUser-Agent: SomeGenerator/1.0\r\nVersion: 1\r\n" ++ "Original-Mail-From: \r\nArrival-Date: Tue, 01 Jul 2003 10:00:00 +0200\r\n" ++ "Source-IP: 192.0.2.1\r\nIncidents: 4\r\n", // Values that make no sense where a number or a status is wanted. "Feedback-Type: \r\nVersion: 999999999999\r\nIncidents: -1\r\n", "Final-Recipient: \r\nAction: \r\nStatus: ...\r\nStatus: 999.999.999\r\n", "Status: 5.1\r\nStatus: 5.1.1.1\r\nStatus: a.b.c\r\n", // Blank lines everywhere, which is what separates the groups. "\r\n\r\n\r\n", "\n\na: 1\n\n\nb: 2", "Diagnostic-Code: smtp;\r\n 550 folded\r\n onto three lines\r\n", "", }; /// Touches every accessor, so that the fuzzer reaches the parsing each of them /// does on top of the field it reads — a `Status` of `999.999.999`, a date /// that is not one, a `Version` too big for the integer it goes into. /// /// The answers are not checked against anything: what is being asked is that /// they can all be reached on any input at all, which is the question a /// program walking a bounce it did not write is really asking. fn touchDeliveryStatus(status: *mime.delivery_status.DeliveryStatus) !void { _ = try status.reportingMta(); _ = try status.arrivalDate(); _ = try status.hasPermanentFailure(); for (status.recipients.items) |*recipient| { _ = try recipient.finalRecipient(); _ = try recipient.originalRecipient(); _ = try recipient.action(); if (try recipient.status()) |found| { _ = found.isPermanentFailure(); _ = found.isTransientFailure(); _ = found.isSuccess(); // A status writes back out as the three numbers it holds, and // reading those again gives the same three. var buffer: [32]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try w.print("{f}", .{found}); const again = mime.delivery_status.Status.parse(w.buffered()) orelse return error.StatusDidNotSurviveItsOwnFormat; try testing.expectEqual(found, again); } _ = try recipient.remoteMta(); _ = try recipient.diagnosticCode(); _ = try recipient.lastAttempt(); _ = try recipient.willRetryUntil(); } } fn touchDispositionNotification(mdn: *mime.disposition_notification.DispositionNotification) !void { _ = try mdn.disposition(); _ = try mdn.finalRecipient(); _ = try mdn.originalRecipient(); _ = try mdn.originalMessageId(); _ = try mdn.reportingUa(); _ = try mdn.failure(); _ = try mdn.@"error"(); } fn touchFeedbackReport(arf: *mime.feedback_report.FeedbackReport) !void { _ = try arf.feedbackType(); _ = try arf.userAgent(); _ = try arf.version(); _ = try arf.originalMailFrom(); _ = try arf.originalRcptTo(); _ = try arf.removalRecipient(); _ = try arf.sourceIp(); _ = try arf.reportedDomain(); _ = try arf.arrivalDate(); _ = try arf.incidents(); } /// The bodies of the three report types, which arrive in a bounce and are /// therefore written by a system the recipient has never met — and, in the /// case of a spam complaint about a message the sender did send, partly by /// whoever provoked the report. /// /// The property is the one the message target asks for: parsing and writing /// may repair the input, but doing it twice must change nothing. A parser and /// a writer that disagree about where a group ends are how a bounce for one /// recipient turns into a bounce that names another. fn reportProperty(input: []const u8) !void { // Whatever the groups are, they are non-empty, in order, and inside the // input: the iterator returns subslices, and a caller keeps them. { var groups: mime.report.GroupIterator = .init(input); var end: usize = 0; while (groups.next()) |group| { try testing.expect(group.len != 0); const start = @intFromPtr(group.ptr) - @intFromPtr(input.ptr); try testing.expect(start >= end); end = start + group.len; try testing.expect(end <= input.len); } } { var first = try mime.report.firstGroup(backing, input); defer first.deinit(); } { var status: mime.delivery_status.DeliveryStatus = try .parse(backing, input); defer status.deinit(); try touchDeliveryStatus(&status); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try status.write(&once.writer); var again: mime.delivery_status.DeliveryStatus = try .parse(backing, once.written()); defer again.deinit(); try touchDeliveryStatus(&again); // The groups survive: a recipient lost or gained on the way out is a // bounce that reports on the wrong address. try testing.expectEqual(status.recipients.items.len, again.recipients.items.len); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } { var mdn: mime.disposition_notification.DispositionNotification = try .parse(backing, input); defer mdn.deinit(); try touchDispositionNotification(&mdn); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try mdn.write(&once.writer); var again: mime.disposition_notification.DispositionNotification = try .parse(backing, once.written()); defer again.deinit(); try touchDispositionNotification(&again); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } { var arf: mime.feedback_report.FeedbackReport = try .parse(backing, input); defer arf.deinit(); try touchFeedbackReport(&arf); var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try arf.write(&once.writer); var again: mime.feedback_report.FeedbackReport = try .parse(backing, once.written()); defer again.deinit(); try touchFeedbackReport(&again); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } // And the typed value the report fields are made of, on the raw input: // whatever it makes of it, writing it back gives something it makes the // same thing of. { const typed = mime.report.TypedValue.parse(input); var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); try typed.write(&out.writer); var formatted: Io.Writer.Allocating = .init(backing); defer formatted.deinit(); try formatted.writer.print("{f}", .{typed}); try testing.expectEqualStrings(out.written(), formatted.written()); const again = mime.report.TypedValue.parse(out.written()); try testing.expectEqualStrings(typed.type, again.type); try testing.expectEqualStrings(typed.value, again.value); } } test "fuzz report" { for (report_seeds) |seed| try reportProperty(seed); try testing.fuzz({}, fuzzReport, .{ .corpus = comptime corpusOf(report_max, &report_seeds) }); } fn fuzzReport(_: void, smith: *testing.Smith) !void { var buffer: [report_max]u8 = undefined; try reportProperty(buffer[0..smith.slice(&buffer)]); } fn runReport(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var buffer: [report_max]u8 = undefined; return reportProperty(buffer[0..smith.slice(&buffer)]); } // -- build ------------------------------------------------------------------ const build_max = 4096; const build_seeds = [_][]const u8{ "Hello, world.\r\n", "Hello, world.\n", "line one\rline two\r\nline three\n", "ünïcödé and a very long line that will have to be wrapped somewhere by whatever encoding gets chosen for it", "=3D already looks encoded\r\n", "trailing space \r\nand a tab\t\r\n", "-- \r\nsignature\r\n", ".\r\n", "From the beginning of a line\r\n", "\x00\x01\x02\x7f\xff", &@as([200]u8, @splat('a')), "\r\n\r\n\r\n", "", "résumé.pdf", "a/b/../c.txt", "..", "name with spaces and \"quotes\".txt", "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e.txt", }; /// A deterministic knob, so that the shape of the message being built varies /// with the input rather than with a random number the input cannot reach. fn knob(bytes: []const u8, salt: u8) u8 { var h: u8 = salt; for (bytes) |c| h = h ^ c ^ (h << 1); return h; } /// Composing a message and reading it back: the other direction from every /// other target here, and the one a program that *sends* mail depends on. /// /// The property is that a body survives the trip. A text body, an attachment, /// a subject and a filename go in; the message is written out, parsed by the /// same library, and each of them is asked for again. Nothing about the wire /// form is asserted — which encoding was chosen, where it wrapped, what the /// boundary was — because all of that is free to change. What is not free to /// change is the content. /// /// This is where an encoder and a decoder that disagree show up: a /// quoted-printable wrap that eats a space, a base64 line that loses a byte, /// an RFC 2231 filename that comes back in pieces, an encoded-word subject /// that arrives in the wrong charset. fn buildProperty(text: []const u8, name: []const u8) !void { var prng: std.Random.DefaultPrng = .init(knob(text, 7)); const random = prng.random(); const choice = knob(name, 3); var message: mime.Message = try .init(backing); defer message.deinit(); try message.root.setSubject(text); try message.setText(text, .{ .subtype = if (choice & 1 == 0) "plain" else "html", .format = if (choice & 2 == 0) .fixed else .flowed, .encoding = switch ((choice >> 2) & 3) { 0 => null, 1 => .quoted_printable, 2 => .base64, else => .eight_bit, }, }); const attached = try message.attach(random, text, .{ .filename = if (name.len == 0) null else name, .encoding = switch ((choice >> 4) & 3) { 0 => null, 1 => .quoted_printable, 2 => .base64, else => .uuencode, }, }); _ = attached; const wire = try message.toBytesAlloc(backing); defer backing.free(wire); var read: mime.Message = try .parse(backing, wire, .{}); defer read.deinit(); // The attachment is the thing a receiver saves to disk, and it must be // the bytes that were handed over -- not canonicalised, not re-wrapped. var found: ?*mime.Message.Part = null; var it = read.root.attachments(); while (it.next()) |part| found = part; const attachment = found orelse return error.AttachmentDisappeared; const bytes = try attachment.decodeAlloc(backing); defer backing.free(bytes); try testing.expectEqualStrings(text, bytes); // And the name it is saved under, when the name is one the library // promises to reproduce. `filename` decodes *to UTF-8*, so a name that is // not valid UTF-8 comes back with replacement characters in it and that is // the documented behaviour rather than a loss -- the name is going to be // shown to somebody. if (name.len != 0 and std.unicode.utf8ValidateSlice(name)) { if (try attachment.filename()) |got| { try testing.expectEqualStrings(name, got); } else return error.FilenameDisappeared; } // The text body comes back as what was written, with the line endings // `setText` canonicalised on the way in -- see its doc comment for why it // does that -- and, under `format=flowed`, rewrapped, which is the whole // point of that format and not a loss. // // And only when the text really is UTF-8, which is what `setText` // declared it to be: `textAlloc` decodes *to* UTF-8, so bytes that were // never UTF-8 come back as replacement characters. That is the library // repairing a caller that mislabelled its own text, not losing it. if (choice & 2 == 0 and choice & 1 == 0 and std.unicode.utf8ValidateSlice(text)) { const body = read.root.findText(&.{"plain"}) orelse return error.TextDisappeared; const got = try body.textAlloc(backing); defer backing.free(got); var canonical: Io.Writer.Allocating = .init(backing); defer canonical.deinit(); try mime.line_ending.toCanonical(&canonical.writer, text); try testing.expectEqualStrings(canonical.written(), got); } // Writing what was read gives what was written: the composer and the // parser agree about the message they are both describing. const twice = try read.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(wire, twice); } test "fuzz build" { for (build_seeds) |seed| { for (build_seeds) |name| try buildProperty(seed, name); } try testing.fuzz({}, fuzzBuild, .{ .corpus = comptime corpusOfPairs(build_max, &build_seeds, &build_seeds) }); } // Both buffers are `build_max`, and deliberately: `Smith.slice` answers a // length larger than the buffer it is given with an **empty** slice rather // than a truncated one, and the driver writes both lengths from the same // `content_max`. A smaller buffer for the name would therefore hand this // target no filename at all on most inputs, and the run would report its // millions of iterations without ever having encoded one. fn fuzzBuild(_: void, smith: *testing.Smith) !void { var text: [build_max]u8 = undefined; var name: [build_max]u8 = undefined; const body = text[0..smith.slice(&text)]; try buildProperty(body, name[0..smith.slice(&name)]); } fn runBuild(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var text: [build_max]u8 = undefined; var name: [build_max]u8 = undefined; const body = text[0..smith.slice(&text)]; return buildProperty(body, name[0..smith.slice(&name)]); } // -- composing a whole message --------------------------------------------- /// Every builder at once, and each thing it put in asked for again. /// /// `build` is one text body and one attachment. A real message is more than /// that: a reply, so `In-Reply-To` and `References`; a `From` with a display /// name; a date; a plain and an HTML body side by side; an image the HTML /// refers to by `Content-ID`; a file read from a stream; and a whole message /// forwarded inside it. Each of those wraps the body that was there before in /// a multipart of its own, so the tree that comes out is four levels deep and /// built by code that only ever saw the level it was adding. /// /// As in `build`, nothing about the wire form is asserted, only that what /// went in comes back out -- with the same allowances for text that was never /// UTF-8 and for line endings `setText` canonicalised. fn composeProperty(text: []const u8, name: []const u8) !void { var prng: std.Random.DefaultPrng = .init(@as(u64, knob(text, 11)) << 8 | knob(name, 13)); const random = prng.random(); const choice = knob(name, 5); const text_is_utf8 = std.unicode.utf8ValidateSlice(text); const name_is_utf8 = std.unicode.utf8ValidateSlice(name); // The message this one replies to, and later forwards. var parent: mime.Message = try .init(backing); defer parent.deinit(); try parent.root.setMessageId("example.net", random); try parent.setText(text, .{}); var message: mime.Message = try .init(backing); defer message.deinit(); try message.root.setAddresses("From", &.{.{ .display_name = if (name.len == 0) null else name, .local_part = "sender", .domain = "example.com", }}); // Whole seconds between the years 1900 and 9999: what RFC 5322 can write. const earliest: i64 = -2_208_988_800; const span: u64 = 253_402_300_799 - earliest; const seconds = earliest + @as(i64, @intCast(random.uintLessThan(u64, span))); const when = mime.datetime.Instant.fromMilliTimestamp(seconds * 1000).asDateTime(); try message.root.setDate(when); try message.root.setMessageId("example.org", random); try message.setInReplyTo(&parent, .{}); try message.root.setSubject(text); try message.setAlternative(random, text, name, .{}); const encoding: ?mime.transfer_encoding.TransferEncoding = switch ((choice >> 2) & 3) { 0 => null, 1 => .quoted_printable, 2 => .base64, else => .uuencode, }; var content_id: ?[]const u8 = null; if (choice & 1 != 0) { const embedded = try message.embed(random, name, .{ .content_type = "image/png", .encoding = if (encoding == .uuencode) null else encoding, }); content_id = embedded.contentId(); } var source: Io.Reader = .fixed(text); _ = try message.attachStreaming(random, &source, .{ .filename = if (name.len == 0) null else name, .encoding = encoding, }); const forwarded = choice & 2 != 0; if (forwarded) _ = try message.attachMessage(random, parent, .{}); const wire = try message.toBytesAlloc(backing); defer backing.free(wire); var read: mime.Message = try .parse(backing, wire, .{}); defer read.deinit(); // The composer and the parser agree about the message they describe. const twice = try read.toBytesAlloc(backing); defer backing.free(twice); try testing.expectEqualStrings(wire, twice); // Threading: the reply names its parent, in both headers. const parent_id = parent.root.messageId().?; try testing.expectEqualStrings(parent_id, read.root.headers.get("in-reply-to").?[1..][0..parent_id.len]); var ancestry = try read.root.references(); var last: ?[]const u8 = null; while (ancestry.next()) |id| last = id; try testing.expectEqualStrings(parent_id, last orelse return error.ReferencesDisappeared); try testing.expectEqualStrings(message.root.messageId().?, read.root.messageId().?); // Less the spaces and tabs at either end, which a subject plain enough to // be written unencoded does not keep: the parser trims them, as every // reader does, and an encoded one keeps them only because they are inside // the encoding. if (text_is_utf8) { const subject = (try read.root.subject()) orelse return error.SubjectDisappeared; try testing.expectEqualStrings(std.mem.trim(u8, text, " \t"), std.mem.trim(u8, subject, " \t")); } // The sender, and when. var from = try read.root.addresses(backing, "from"); defer from.deinit(backing); var mailboxes = from.mailboxIterator(); const sender = mailboxes.next() orelse return error.SenderDisappeared; try testing.expectEqualStrings("sender", sender.local_part); try testing.expectEqualStrings("example.com", sender.domain); try testing.expectEqual(null, mailboxes.next()); const sent = (try read.root.sentAt()) orelse return error.DateDisappeared; try testing.expectEqual(when.toInstant().timestamp, sent.time.toInstant().timestamp); // Both forms of the body, each where `findText` looks for it. if (text_is_utf8) try expectText(&read, "plain", text); if (name_is_utf8) try expectText(&read, "html", name); // The image, found by the identifier the HTML would use. if (content_id) |id| { const image = read.root.findContentId(id) orelse return error.EmbeddedDisappeared; try testing.expect(!image.isAttachment()); const bytes = try image.decodeAlloc(backing); defer backing.free(bytes); try testing.expectEqualStrings(name, bytes); } // The file that was streamed in: the first attachment, byte for byte. var attachments = read.root.attachments(); const file = attachments.next() orelse return error.AttachmentDisappeared; const bytes = try file.decodeAlloc(backing); defer backing.free(bytes); try testing.expectEqualStrings(text, bytes); // And the message forwarded whole: its own identity and its own text. if (forwarded) { const wrapper = read.root.find("message", "rfc822") orelse return error.ForwardDisappeared; const inner = switch (wrapper.body) { .message => |inner| inner, else => return error.ForwardNotOpened, }; try testing.expectEqualStrings(parent_id, inner.messageId().?); if (text_is_utf8) { const got = try inner.textAlloc(backing); defer backing.free(got); try expectCanonical(text, got); } } } /// The first `text/` body that is not an attachment says `expected`, /// once its line endings are canonical. fn expectText(message: *mime.Message, subtype: []const u8, expected: []const u8) !void { const part = message.root.findText(&.{subtype}) orelse return error.TextDisappeared; const got = try part.textAlloc(backing); defer backing.free(got); try expectCanonical(expected, got); } fn expectCanonical(expected: []const u8, got: []const u8) !void { var canonical: Io.Writer.Allocating = .init(backing); defer canonical.deinit(); try mime.line_ending.toCanonical(&canonical.writer, expected); try testing.expectEqualStrings(canonical.written(), got); } test "fuzz compose" { for (build_seeds) |seed| { for (build_seeds) |name| try composeProperty(seed, name); } try testing.fuzz({}, fuzzCompose, .{ .corpus = comptime corpusOfPairs(build_max, &build_seeds, &build_seeds) }); } fn fuzzCompose(_: void, smith: *testing.Smith) !void { var text: [build_max]u8 = undefined; var name: [build_max]u8 = undefined; const body = text[0..smith.slice(&text)]; try composeProperty(body, name[0..smith.slice(&name)]); } fn runCompose(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var text: [build_max]u8 = undefined; var name: [build_max]u8 = undefined; const body = text[0..smith.slice(&text)]; return composeProperty(body, name[0..smith.slice(&name)]); } // -- chunks ----------------------------------------------------------------- const chunk_max = 4096; const chunk_seeds = [_][]const u8{ "SGVsbG8sIHdvcmxkLg==\r\n", "SGVsbG8s\r\nIHdvcmxkLg==\r\n", "SGVsbG8sIHdvcmxkLg", "=?", "a=3Db=\r\nc\r\n", "trailing=20\r\n", "=41=42=4", "=\r\n", "begin 644 cat.txt\r\n#0V%T\r\n`\r\nend\r\n", "begin 644 x\n#0V%T\n", "plain text, no encoding at all\r\n", "\x00\x01\x02\xff", "", }; /// The chunk-wise decoders, fed the same body split in every way the input /// asks for. /// /// Streaming extraction exists so that a twenty megabyte attachment does not /// have to be held whole, and the way it goes wrong is at the joins: a base64 /// group split across two chunks, a quoted-printable `=41` whose `4` ended one /// read and whose `1` began the next, a uuencoded line that arrived in /// pieces. None of that is reachable by a test that hands the decoder the /// whole body at once, and all of it is reachable by a reader whose buffer /// happens to fill at the wrong byte. /// /// So the property is that **where the splits fall makes no difference**: the /// same body decoded in one piece, in single bytes, and at the boundaries the /// input picks, gives the same output all three times. The slice decoder is /// the reference, which is also what keeps the two implementations one /// implementation. fn chunkProperty(input: []const u8, splits: []const u8) !void { const encodings = [_]mime.transfer_encoding.TransferEncoding{ .base64, .quoted_printable, .uuencode, .seven_bit, .eight_bit, .binary, }; for (encodings) |encoding| { // The reference: the whole body at once, through the slice form. const whole = try encoding.decodeAlloc(backing, input); defer backing.free(whole); // One byte at a time, which is the worst case for every join there is. { var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); var decoder: mime.transfer_encoding.Decoder = .init(encoding); defer decoder.deinit(backing); for (input) |c| try decoder.write(backing, &out.writer, &.{c}); // What `streams` promises: a decoder that streams has written a // prefix of the body before it is told the body is over, and one // that does not has written nothing yet. if (decoder.streams()) { try testing.expect(std.mem.startsWith(u8, whole, out.written())); } else { try testing.expectEqual(0, out.written().len); } try decoder.finish(backing, &out.writer); try testing.expectEqualStrings(whole, out.written()); } // And at the boundaries the input asks for, so that a join landing on // a particular byte -- the `=` of an escape, the `\r` of a line // ending, the last character of a base64 group -- is reachable. { var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); var decoder: mime.transfer_encoding.Decoder = .init(encoding); defer decoder.deinit(backing); var at: usize = 0; var which: usize = 0; while (at < input.len) { const step = if (splits.len == 0) input.len - at else @min(input.len - at, @as(usize, splits[which % splits.len]) + 1); which += 1; try decoder.write(backing, &out.writer, input[at..][0..step]); at += step; } try decoder.finish(backing, &out.writer); try testing.expectEqualStrings(whole, out.written()); } // An empty chunk is what a reader hands over when it happened to read // nothing, and must change nothing at all. { var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); var decoder: mime.transfer_encoding.Decoder = .init(encoding); defer decoder.deinit(backing); try decoder.write(backing, &out.writer, ""); try decoder.write(backing, &out.writer, input); try decoder.write(backing, &out.writer, ""); try decoder.finish(backing, &out.writer); try testing.expectEqualStrings(whole, out.written()); } } } test "fuzz chunks" { for (chunk_seeds) |seed| { for (chunk_seeds) |splits| try chunkProperty(seed, splits); try chunkProperty(seed, &.{ 0, 1, 2, 3 }); } try testing.fuzz({}, fuzzChunks, .{ .corpus = comptime corpusOfPairs(chunk_max, &chunk_seeds, &chunk_seeds) }); } fn fuzzChunks(_: void, smith: *testing.Smith) !void { var body: [chunk_max]u8 = undefined; var splits: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; try chunkProperty(content, splits[0..smith.slice(&splits)]); } fn runChunks(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var body: [chunk_max]u8 = undefined; var splits: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; return chunkProperty(content, splits[0..smith.slice(&splits)]); } // -- encode-stream ---------------------------------------------------------- /// The other side of `chunks`: encoding a body from a reader must produce /// exactly what encoding it from a slice produces. /// /// `Part.setDataStreaming` exists so that a file can be attached without being /// read into memory, and it reaches a different function from the one /// `setData` uses. Two functions that are supposed to write the same bytes is /// the shape this project keeps trying to avoid, and where it cannot be /// avoided the way to keep it honest is to make the fuzzer compare them — /// which also means the encoded body does not depend on how the file happened /// to be read. /// /// Only the encodings `streams` admits are asked; quoted-printable is not one /// of them, and `setDataStreaming` is the way in that handles that. fn encodeStreamProperty(input: []const u8, name: []const u8) !void { const encodings = [_]mime.transfer_encoding.TransferEncoding{ .base64, .uuencode, .seven_bit, .eight_bit, .binary, }; const options: mime.transfer_encoding.EncodeOptions = .{ .name = if (name.len == 0) null else name, }; for (encodings) |encoding| { try testing.expect(encoding.streams()); var whole: Io.Writer.Allocating = .init(backing); defer whole.deinit(); try encoding.encodeWriter(&whole.writer, input, options); // Through a reader whose buffer is deliberately small, so that the // encoder is handed the body in pieces it did not choose. var streamed: Io.Writer.Allocating = .init(backing); defer streamed.deinit(); var source: Io.Reader = .fixed(input); try encoding.encodeStream(&source, &streamed.writer, options); try testing.expectEqualStrings(whole.written(), streamed.written()); // And what either of them wrote decodes back to what went in. const back = try encoding.decodeAlloc(backing, whole.written()); defer backing.free(back); try testing.expectEqualStrings(input, back); } } test "fuzz encode-stream" { for (build_seeds) |seed| { for (build_seeds) |name| try encodeStreamProperty(seed, name); } try testing.fuzz({}, fuzzEncodeStream, .{ .corpus = comptime corpusOfPairs(chunk_max, &build_seeds, &build_seeds) }); } fn fuzzEncodeStream(_: void, smith: *testing.Smith) !void { var body: [chunk_max]u8 = undefined; var name: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; try encodeStreamProperty(content, name[0..smith.slice(&name)]); } fn runEncodeStream(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var body: [chunk_max]u8 = undefined; var name: [chunk_max]u8 = undefined; const content = body[0..smith.slice(&body)]; return encodeStreamProperty(content, name[0..smith.slice(&name)]); } // -- headers-edit ----------------------------------------------------------- /// Editing a header block, rather than only reading one. /// /// `set` and `remove` walk the list freeing as they go and keeping an index /// that the list is shifting underneath them, which is the shape that produces /// a double free or a value read after it was freed. The `headers` target /// never reaches any of it: it parses and writes and never edits. A program /// that handles mail edits constantly — it sets a `Subject`, removes a /// `Bcc`, prepends a `Received` — and does it to a block somebody else wrote. /// /// The properties are the ones the names promise. `set` leaves exactly one /// field of that name and does not move it; `remove` leaves none; `prepend` /// and `prependTrace` put the field where each says it does; and after all of /// it the block still writes and parses back to itself. fn headersEditProperty(block: []const u8, text: []const u8) !void { var headers: mime.Headers = try .parse(backing, block); defer headers.deinit(); // A name taken from the input, so that the edits land on fields that are // really there as often as on ones that are not. A field name may not // hold a colon or a line ending, and `append` is entitled to assume that. var name_buffer: [64]u8 = undefined; var len: usize = 0; for (text) |c| { if (len == name_buffer.len) break; switch (c) { 0...0x20, 0x7f, ':' => continue, else => {}, } name_buffer[len] = c; len += 1; } const name = if (len == 0) "X-Fuzz" else name_buffer[0..len]; const before = headers.count(name); try testing.expectEqual(before, countByIterator(&headers, name)); try testing.expectEqual(before != 0, headers.has(name)); // `writeField` writes what `append` stores, on a line of its own. { var one: mime.Headers = try .parse(backing, ""); defer one.deinit(); try one.append(name, text); var stored: Io.Writer.Allocating = .init(backing); defer stored.deinit(); try one.writeFields(&stored.writer); var direct: Io.Writer.Allocating = .init(backing); defer direct.deinit(); try mime.field.writeField(&direct.writer, name, text, .{}); try testing.expectEqualStrings(stored.written(), direct.written()); } // `prependRaw` takes a value that is already wire form -- here one the // parser accepted -- and it is written and read back byte for byte. if (headers.fields.items.len != 0) { const last = headers.fields.items[headers.fields.items.len - 1]; const raw = try backing.dupe(u8, last.value); defer backing.free(raw); var copy: mime.Headers = try .parse(backing, block); defer copy.deinit(); // A name of its own: the one above comes from the input and may hold // bytes no field name may, which is the caller's to get right. try copy.prependRaw("X-Prepended", raw); try testing.expectEqualStrings(raw, copy.fields.items[0].value); var out: Io.Writer.Allocating = .init(backing); defer out.deinit(); try copy.write(&out.writer); var reread: mime.Headers = try .parse(backing, out.written()); defer reread.deinit(); try testing.expectEqualStrings("X-Prepended", reread.fields.items[0].name); try testing.expectEqualStrings(raw, reread.fields.items[0].value); } // `append` adds exactly one. try headers.append(name, text); try testing.expectEqual(before + 1, headers.count(name)); try testing.expect(headers.has(name)); // `prepend` puts it at the front. try headers.prepend(name, text); try testing.expect(std.ascii.eqlIgnoreCase(headers.fields.items[0].name, name)); try testing.expectEqual(before + 2, headers.count(name)); // `prependTrace` goes to the front too, unless a `Return-Path` is there, // in which case it goes under it and under no more than the run of them. try headers.prependTrace("Received", "by fuzz.example; Tue, 01 Jul 2003 10:52:37 +0200"); { var at: usize = 0; while (std.ascii.eqlIgnoreCase(headers.fields.items[at].name, "Return-Path")) : (at += 1) {} try testing.expect(std.ascii.eqlIgnoreCase(headers.fields.items[at].name, "Received")); } // `set` leaves exactly one, and leaves it where the first one was. const index_before = firstIndex(&headers, name); try headers.set(name, text); try testing.expectEqual(1, headers.count(name)); try testing.expectEqual(index_before, firstIndex(&headers, name)); // And what comes back is a fixed point: setting the value that was read // back reads back the same again. Asking instead for the text that went // in would need this test to model the folder -- where it breaks a long // line, which runs of whitespace it keeps, which bare line endings it // drops because a header value is one logical line -- and a model of a // thing is not a test of it. What matters to a caller is that a value // read out and put back does not drift on each pass. const read_back = (try headers.getUnfolded(name)) orelse return error.SetThenGetFoundNothing; const kept = try backing.dupe(u8, read_back); defer backing.free(kept); try headers.set(name, kept); if (try headers.getUnfolded(name)) |twice_over| { try testing.expectEqualStrings(kept, twice_over); } else return error.SetThenGetFoundNothing; // `remove` leaves none, and says how many it took. try testing.expectEqual(1, headers.remove(name)); try testing.expectEqual(0, headers.count(name)); try testing.expect(!headers.has(name)); try testing.expect(headers.get(name) == null); try testing.expectEqual(0, headers.remove(name)); // Whatever is left still writes and reads back to itself. var once: Io.Writer.Allocating = .init(backing); defer once.deinit(); try headers.write(&once.writer); var again: mime.Headers = try .parse(backing, once.written()); defer again.deinit(); var twice: Io.Writer.Allocating = .init(backing); defer twice.deinit(); try again.write(&twice.writer); try testing.expectEqualStrings(once.written(), twice.written()); } fn countByIterator(headers: *mime.Headers, name: []const u8) usize { var n: usize = 0; var it = headers.iterator(name); while (it.next() != null) n += 1; return n; } fn firstIndex(headers: *mime.Headers, name: []const u8) ?usize { for (headers.fields.items, 0..) |f, i| { if (std.ascii.eqlIgnoreCase(f.name, name)) return i; } return null; } test "fuzz headers-edit" { for (header_seeds) |seed| { for (header_seeds) |text| try headersEditProperty(seed, text); } try testing.fuzz({}, fuzzHeadersEdit, .{ .corpus = comptime corpusOfPairs(header_max, &header_seeds, &header_seeds) }); } fn fuzzHeadersEdit(_: void, smith: *testing.Smith) !void { var block: [header_max]u8 = undefined; var text: [header_max]u8 = undefined; const parsed = block[0..smith.slice(&block)]; try headersEditProperty(parsed, text[0..smith.slice(&text)]); } fn runHeadersEdit(input: []const u8) anyerror!void { var smith: testing.Smith = .{ .in = input }; var block: [header_max]u8 = undefined; var text: [header_max]u8 = undefined; const parsed = block[0..smith.slice(&block)]; return headersEditProperty(parsed, text[0..smith.slice(&text)]); }