// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Quoted-printable, RFC 2045 §6.7: the encoding for a body that is *mostly* //! text, where base64 would make a legible message unreadable to anything that //! does not decode it and would cost a third more bytes to do so. //! //! The rules are short and every one of them is a scar: //! //! * An octet may be written as `=` followed by two uppercase hexadecimal //! digits. Anything may be written that way; some things must be. //! * Printable ASCII other than `=` may be written as itself. //! * Space and tab may be written as themselves **except at the end of a //! line**, where a transport is entitled to strip them and historically //! did. //! * No line may exceed 76 characters, so the encoder breaks long ones with a //! *soft line break* — an `=` at the end of a line, which the decoder //! removes along with the line ending. That is why the `=` needs escaping //! in the first place. //! //! The distinction between `.text` and `.binary` is the whole of the //! difference between an encoding that is safe and one that is faithful. In //! `.text` a CRLF in the source is a line break in the message and stays one; //! in `.binary` it is two octets and is encoded as `=0D=0A`, so that a body //! survives a transport that rewrites line endings. Text mode expects its //! input in canonical form already — see `line_ending` for why, and for the //! function that puts it there — and encodes a lone CR or LF rather than //! promoting it to a line break, so that both modes round-trip exactly. //! //! The decoder is lenient in the one direction that matters: a `=` that is not //! followed by two hexadecimal digits is passed through as itself. Real mail //! contains `=` signs that were never encoded, usually in a signature or a //! wrapped URL, and a decoder that fails on them fails on the message. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const line_ending = @import("../line_ending.zig"); const hex = "0123456789ABCDEF"; pub const EncodeOptions = struct { /// What the source bytes are. See the module comment: this is the /// difference between a line break and two octets that happen to be CR /// and LF. mode: enum { text, binary } = .text, /// The longest line the encoder will emit, counting the `=` of a soft /// break but not the line ending. RFC 2045 permits at most 76. line_length: usize = 76, /// Emitted for a hard line break in `.text` mode and for a soft one in /// both. Anything but `.crlf` makes text mode lossy, since the CRLF that /// went in does not come back out. ending: line_ending.Ending = .crlf, /// Encode the `F` of a line beginning `From `. Such a line is how an mbox /// file marks the start of a message, so a body containing one can end a /// message early in any tool that reads mbox — which is most of the tools /// that have ever stored mail. Cheap insurance, and invisible after /// decoding. escape_from: bool = true, /// Encode a `.` that is alone on a line, which is how SMTP marks the end /// of the message data. Any conforming SMTP client doubles it instead, so /// this is belt and braces, and likewise invisible. escape_dot: bool = true, }; /// An upper bound on what `encode` will write. The exact figure depends on /// where the line breaks fall, which depends on the content, so a caller that /// needs the exact figure should encode into an `Io.Writer.Allocating`. pub fn encodedLenUpperBound(source_len: usize, options: EncodeOptions) usize { const chars = source_len * 3; if (options.line_length <= 1) return chars; const lines = chars / (options.line_length - 1) + 1; return chars + lines * (options.ending.bytes().len + 1); } /// Encodes into `dest`, which must be at least `encodedLenUpperBound` bytes. pub fn encode(dest: []u8, source: []const u8, options: EncodeOptions) []u8 { var w: Io.Writer = .fixed(dest); encodeWriter(&w, source, options) catch unreachable; // `dest` was sized by the bound. return w.buffered(); } pub fn encodeAlloc(gpa: Allocator, source: []const u8, options: EncodeOptions) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); encodeWriter(&out.writer, source, options) catch return error.OutOfMemory; return out.toOwnedSlice(); } pub fn encodeWriter(w: *Io.Writer, source: []const u8, options: EncodeOptions) Io.Writer.Error!void { var column: usize = 0; var at_line_start = true; // Whitespace that has been read but not written, because whether it may // be written as itself depends on what comes after it: a space is safe in // the middle of a line and must be escaped at the end of one, and where // the end of the line falls is not known until the next character's cost // is known. Getting this wrong loses a space -- and a space in front of a // soft line break is deleted by the decoder, which is how a body can come // back a byte shorter than it went in. var pending: []const u8 = source[0..0]; var i: usize = 0; while (i < source.len) { if (options.mode == .text and source[i] == '\r' and i + 1 < source.len and source[i + 1] == '\n') { // A hard line break, so everything held is at the end of a line // and has to be escaped. try escapeAll(w, pending, options, &column); pending = source[0..0]; try w.writeAll(options.ending.bytes()); column = 0; at_line_start = true; i += 2; continue; } // `From ` and a lone `.` are only dangerous where they begin a line, // and escaping the first character is enough to make them harmless. if (at_line_start and options.escape_from and startsWithFrom(source[i..])) { try writeEscaped(w, 'F', options, &column); at_line_start = false; i += 1; continue; } if (at_line_start and options.escape_dot and isLoneDot(source[i..], options.mode)) { try writeEscaped(w, '.', options, &column); at_line_start = false; i += 1; continue; } const c = source[i]; if (c == ' ' or c == '\t') { if (pending.len == 0) pending = source[i..i]; pending.len += 1; at_line_start = false; i += 1; continue; } const literal = switch (c) { '=' => false, 33...60, 62...126 => true, else => false, }; const cost: usize = if (literal) 1 else 3; try writePending(w, pending, cost, options, &column); pending = source[0..0]; if (literal) { try writeLiteral(w, c, options, &column); } else { try writeEscaped(w, c, options, &column); } at_line_start = false; i += 1; } // Whitespace at the very end of the body is whitespace at the end of a // line, whatever the caller appends next. try escapeAll(w, pending, options, &column); } /// Writes held whitespace, knowing that a character costing `next_cost` will /// follow it. /// /// The rule is that a whitespace byte may be written as itself only if the /// character after it lands on the same line. Not merely "if it is not the /// last byte of the line": a soft line break inserted *after* it is just as /// fatal, because the decoder drops the whitespace in front of a soft break /// along with the break. So the decision is made for the whole run at once — /// either everything in it plus the character that follows fits on a line, or /// none of it is written as itself. /// /// Getting this wrong loses a space or a tab out of the middle of a body, and /// it is invisible in every small test: it needs a run of whitespace that /// happens to end within three columns of the seventy-sixth. The fuzz target's /// round-trip property is what found it. fn writePending( w: *Io.Writer, pending: []const u8, next_cost: usize, options: EncodeOptions, column: *usize, ) Io.Writer.Error!void { if (pending.len == 0) return; if (options.line_length == 0) { try w.writeAll(pending); column.* += pending.len; return; } const room = options.line_length - 1; // On this line, with the character that follows. if (column.* + pending.len + next_cost <= room) { try w.writeAll(pending); column.* += pending.len; return; } // On a line of its own. if (pending.len + next_cost <= room) { try w.writeByte('='); try w.writeAll(options.ending.bytes()); column.* = 0; try w.writeAll(pending); column.* += pending.len; return; } // Longer than any line can hold: escaped, which is safe anywhere. try escapeAll(w, pending, options, column); } fn escapeAll( w: *Io.Writer, bytes: []const u8, options: EncodeOptions, column: *usize, ) Io.Writer.Error!void { for (bytes) |c| try writeEscaped(w, c, options, column); } fn startsWithFrom(rest: []const u8) bool { return std.mem.startsWith(u8, rest, "From "); } fn isLoneDot(rest: []const u8, mode: @FieldType(EncodeOptions, "mode")) bool { if (rest[0] != '.') return false; if (mode != .text) return rest.len == 1; return rest.len == 1 or std.mem.startsWith(u8, rest[1..], "\r\n"); } fn writeLiteral(w: *Io.Writer, c: u8, options: EncodeOptions, column: *usize) Io.Writer.Error!void { try reserve(w, 1, options, column); try w.writeByte(c); column.* += 1; } fn writeEscaped(w: *Io.Writer, c: u8, options: EncodeOptions, column: *usize) Io.Writer.Error!void { try reserve(w, 3, options, column); try w.writeAll(&.{ '=', hex[c >> 4], hex[c & 0xf] }); column.* += 3; } /// Emits a soft line break if `n` more characters would not fit. The `- 1` is /// the `=` that the soft break itself occupies: a line that used all 76 /// characters would have nowhere to put it. fn reserve(w: *Io.Writer, n: usize, options: EncodeOptions, column: *usize) Io.Writer.Error!void { if (options.line_length == 0) return; if (column.* + n <= options.line_length - 1) return; try w.writeByte('='); try w.writeAll(options.ending.bytes()); column.* = 0; } /// Decodes into `dest`, which need never be larger than `source.len`, and /// returns what was written. Decoding only ever shrinks. pub fn decode(dest: []u8, source: []const u8) []u8 { var w: Io.Writer = .fixed(dest); decodeWriter(&w, source) catch unreachable; // Output is never longer than input. return w.buffered(); } pub fn decodeAlloc(gpa: Allocator, source: []const u8) Allocator.Error![]u8 { const scratch = try gpa.alloc(u8, source.len); errdefer gpa.free(scratch); const decoded = decode(scratch, source); if (gpa.resize(scratch, decoded.len)) return scratch[0..decoded.len]; defer gpa.free(scratch); return gpa.dupe(u8, decoded); } /// A decoder that can be fed the encoded text a piece at a time. /// /// The one implementation: `decode`, `decodeAlloc` and `decodeWriter` are all /// this with the pieces arranged differently, for the same reason as in /// `base64` — two decoders for one encoding drift apart the first time either /// is touched. /// /// There is more state here than in base64 because more of this encoding spans /// a boundary. An escape is three characters and a chunk can end after one or /// two of them; a soft line break is two or three; and a run of whitespace has /// to be held until something proves whether it is content or the padding a /// transport added, which may not be decided until the next chunk. pub const Decoder = struct { /// Whitespace read but not yet written, because whether it belongs to the /// message depends on what follows it. /// /// Bounded, unlike the run it holds: a run longer than this is emitted /// rather than held, on the grounds that a quoted-printable line is at /// most 76 characters, so whitespace this long is not the tail of a line /// and cannot be what a transport added. pending: [max_pending]u8 = undefined, pending_len: usize = 0, state: State = .normal, /// The first hexadecimal character of an escape, kept as it was written so /// that an escape which turns out not to be one can be put back. high: u8 = 0, const max_pending = 1024; const State = enum { normal, /// A `=` has been read. equals, /// A `=` and a CR, which is a soft line break if an LF follows. equals_cr, /// A `=` and one hexadecimal character. equals_hex, }; pub fn write(self: *Decoder, w: *Io.Writer, source: []const u8) Io.Writer.Error!void { for (source) |c| try self.byte(w, c); } /// Emits what a half-finished escape at the end of the input is worth, and /// drops the whitespace at the end of a body for the same reason it drops /// the whitespace at the end of a line. pub fn finish(self: *Decoder, w: *Io.Writer) Io.Writer.Error!void { switch (self.state) { // A `=` with nothing after it is a soft break whose line ending // was lost, or a body that stops mid-escape. Either way there is // nothing to emit. .normal, .equals => {}, .equals_cr => { try self.flush(w); try w.writeAll("=\r"); }, .equals_hex => { try self.flush(w); try w.writeAll(&.{ '=', self.high }); }, } self.pending_len = 0; self.state = .normal; } fn byte(self: *Decoder, w: *Io.Writer, c: u8) Io.Writer.Error!void { switch (self.state) { .normal => return self.normalByte(w, c), .equals => switch (c) { '\r' => self.state = .equals_cr, // A soft line break, and with it any whitespace before it. '\n' => { self.pending_len = 0; self.state = .normal; }, else => { if (digit(c) != null) { self.high = c; self.state = .equals_hex; return; } // Not an escape at all. Real mail is full of these. try self.flush(w); try w.writeByte('='); self.state = .normal; return self.normalByte(w, c); }, }, .equals_cr => { if (c == '\n') { self.pending_len = 0; self.state = .normal; return; } try self.flush(w); try w.writeByte('='); self.pending_len = 0; try w.writeByte('\r'); self.state = .normal; return self.normalByte(w, c); }, .equals_hex => { self.state = .normal; if (digit(c)) |low| { try self.flush(w); try w.writeByte(digit(self.high).? << 4 | low); return; } try self.flush(w); try w.writeAll(&.{ '=', self.high }); return self.normalByte(w, c); }, } } fn normalByte(self: *Decoder, w: *Io.Writer, c: u8) Io.Writer.Error!void { switch (c) { '=' => self.state = .equals, ' ', '\t' => { if (self.pending_len == self.pending.len) try self.flush(w); self.pending[self.pending_len] = c; self.pending_len += 1; }, // Whitespace at the end of a line was added by something in the // middle: an encoder would have escaped its own. '\r', '\n' => { self.pending_len = 0; try w.writeByte(c); }, else => { try self.flush(w); try w.writeByte(c); }, } } fn flush(self: *Decoder, w: *Io.Writer) Io.Writer.Error!void { if (self.pending_len == 0) return; try w.writeAll(self.pending[0..self.pending_len]); self.pending_len = 0; } }; pub fn decodeWriter(w: *Io.Writer, source: []const u8) Io.Writer.Error!void { var decoder: Decoder = .{}; try decoder.write(w, source); try decoder.finish(w); } fn digit(c: u8) ?u8 { return switch (c) { '0'...'9' => c - '0', 'A'...'F' => c - 'A' + 10, // Lowercase is not conforming and is everywhere. 'a'...'f' => c - 'a' + 10, else => null, }; } test "encode leaves printable ASCII alone" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings( "Hello, world!", encode(&buffer, "Hello, world!", .{}), ); } test "encode escapes what it must" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings("a=3Db", encode(&buffer, "a=b", .{})); try testing.expectEqualStrings("caf=C3=A9", encode(&buffer, "café", .{})); // A space before a line break, and one at the very end. try testing.expectEqualStrings("a=20\r\nb", encode(&buffer, "a \r\nb", .{})); try testing.expectEqualStrings("a=20", encode(&buffer, "a ", .{})); // A space in the middle of a line is safe as itself. try testing.expectEqualStrings("a b", encode(&buffer, "a b", .{})); } test "encode hides the shapes that end a message early" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings("=46rom here\r\n", encode(&buffer, "From here\r\n", .{})); try testing.expectEqualStrings("a\r\n=2E\r\nb", encode(&buffer, "a\r\n.\r\nb", .{})); // Only where they begin a line. try testing.expectEqualStrings("Not From here", encode(&buffer, "Not From here", .{})); try testing.expectEqualStrings("1.5", encode(&buffer, "1.5", .{})); } test "encode breaks long lines softly" { var buffer: [512]u8 = undefined; const encoded = encode(&buffer, &@as([100]u8, @splat('x')), .{}); var lines = std.mem.splitSequence(u8, encoded, "\r\n"); const first = lines.next().?; try testing.expectEqual(76, first.len); try testing.expectEqual('=', first[75]); try testing.expectEqualStrings(&@as([25]u8, @splat('x')), lines.next().?); try testing.expectEqual(null, lines.next()); } test "text mode keeps line breaks and binary mode does not" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings("a\r\nb", encode(&buffer, "a\r\nb", .{ .mode = .text })); try testing.expectEqualStrings("a=0D=0Ab", encode(&buffer, "a\r\nb", .{ .mode = .binary })); // A lone LF is data in either mode, because canonical text has none. try testing.expectEqualStrings("a=0Ab", encode(&buffer, "a\nb", .{ .mode = .text })); } test "decode undoes escapes and soft breaks" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings("a=b", decode(&buffer, "a=3Db")); try testing.expectEqualStrings("café", decode(&buffer, "caf=C3=A9")); try testing.expectEqualStrings("xy", decode(&buffer, "x=\r\ny")); try testing.expectEqualStrings("xy", decode(&buffer, "x=\ny")); // Lowercase hexadecimal, which no encoder should write and many do. try testing.expectEqualStrings("café", decode(&buffer, "caf=c3=a9")); } test "decode passes a bare equals sign through" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings("a = b", decode(&buffer, "a = b")); try testing.expectEqualStrings("2=2", decode(&buffer, "2=2")); try testing.expectEqualStrings("x", decode(&buffer, "x=")); } test "decode drops the whitespace a transport added" { var buffer: [256]u8 = undefined; try testing.expectEqualStrings("a\r\nb", decode(&buffer, "a \r\nb")); try testing.expectEqualStrings("a b", decode(&buffer, "a b")); try testing.expectEqualStrings("a", decode(&buffer, "a ")); } test "round trip" { var bytes: [2048]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xfeed); prng.random().bytes(&bytes); for ([_]usize{ 0, 1, 75, 76, 77, 2048 }) |len| { const encoded = try encodeAlloc(testing.allocator, bytes[0..len], .{ .mode = .binary }); defer testing.allocator.free(encoded); const decoded = try decodeAlloc(testing.allocator, encoded); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, bytes[0..len], decoded); } } test "round trip of canonical text" { const text = "From the desk of somebody\r\n" ++ "\r\n" ++ ".\r\n" ++ "A line with trailing space \r\n" ++ "An = sign, a café, and a line long enough that it has to be broken " ++ "somewhere in the middle of it\r\n"; const encoded = try encodeAlloc(testing.allocator, text, .{}); defer testing.allocator.free(encoded); var lines = std.mem.splitSequence(u8, encoded, "\r\n"); while (lines.next()) |line| try testing.expect(line.len <= 76); const decoded = try decodeAlloc(testing.allocator, encoded); defer testing.allocator.free(decoded); try testing.expectEqualStrings(text, decoded); } test "whitespace next to a soft line break survives" { // The bug the fuzz target found: a run of whitespace that ends within // three columns of the line limit used to get a soft line break inserted // into the middle of it, and a decoder deletes the whitespace in front of // a soft break. Every offset is tried because only a few of them put the // run in the fatal place. for (60..80) |offset| { var input: std.ArrayList(u8) = .empty; defer input.deinit(testing.allocator); try input.appendNTimes(testing.allocator, 'x', offset); try input.appendSlice(testing.allocator, " \t \t "); try input.appendNTimes(testing.allocator, 'y', 40); const encoded = try encodeAlloc(testing.allocator, input.items, .{ .mode = .binary }); defer testing.allocator.free(encoded); const decoded = try decodeAlloc(testing.allocator, encoded); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, input.items, decoded); } } test "the decoder agrees with itself however the pieces arrive" { const bodies = [_][]const u8{ "caf=C3=A9 and a soft=\r\nbreak", "trailing space \r\nand a tab\t\r\n", "a = b, 2=2, x=", "=\r\n=3D=\n=zz=", "many" ++ &@as([2000]u8, @splat(' ')) ++ "spaces", "", }; for (bodies) |body| { const whole = try decodeAlloc(testing.allocator, body); defer testing.allocator.free(whole); for ([_]usize{ 1, 2, 3, 4, 5, 17, 4096 }) |chunk_len| { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var decoder: Decoder = .{}; var offset: usize = 0; while (offset < body.len) : (offset += chunk_len) { try decoder.write(&out.writer, body[offset..@min(offset + chunk_len, body.len)]); } try decoder.finish(&out.writer); try testing.expectEqualStrings(whole, out.written()); } } }