// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `Content-Transfer-Encoding`: which of the codecs a body is in, and the //! choice of which to put it in. //! //! RFC 2045 §6.1 defines five values and lets anybody register more. Three of //! them — `7bit`, `8bit` and `binary` — do nothing at all: they are claims //! about what the body already contains, and they differ in what a transport //! is allowed to do with it. `quoted-printable` and `base64` are the two that //! actually encode. //! //! The absence of the header means `7bit`, and an unrecognised value must be //! treated as `application/octet-stream` — RFC 2045 §6.4 — which in practice //! means: do not try to decode it, and do not display it as text. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const zuucode = @import("zuucode"); const base64 = @import("base64.zig"); const quoted_printable = @import("quoted_printable.zig"); const charset = @import("../charset.zig"); pub const toUtf8Alloc = charset.toUtf8Alloc; pub const TransferEncoding = enum { /// The body is US-ASCII, in lines of at most 998 characters. The default, /// and what the absence of the header means. seven_bit, /// The body has bytes with the high bit set, still in lines. Needs an /// `8BITMIME` transport, which is now everything. eight_bit, /// The body has no line structure at all. Needs a `BINARYMIME` /// transport, which is nearly nothing, so this is seen in stored messages /// rather than in transit. binary, quoted_printable, base64, /// Uuencode, which RFC 2045 never defined and which mail carried for /// fifteen years before it did. /// /// It is spelled `x-uuencode` and four other ways, none of them /// registered, and it is the reason an archive of mail from before about /// 1996 has attachments that a strict MIME reader cannot open. Nothing /// should *write* it — base64 is what it was replaced by, and `choose` /// never picks it — but a library that can read old mail has to know it. /// /// The body normally carries the whole uuencoded file, `begin` and `end` /// lines included, and that `begin` line holds a filename which for a /// message this old is often the only one there is. `Part.filename` falls /// back to it. uuencode, /// Something else was written. RFC 2045 §6.4 says to treat the body as /// opaque: it is not decoded and it is not text. unknown, pub fn parse(text: []const u8) TransferEncoding { const trimmed = std.mem.trim(u8, text, " \t\r\n"); const table = .{ .{ "7bit", TransferEncoding.seven_bit }, .{ "8bit", TransferEncoding.eight_bit }, .{ "binary", TransferEncoding.binary }, .{ "quoted-printable", TransferEncoding.quoted_printable }, .{ "base64", TransferEncoding.base64 }, // Five spellings, no registration, all of them in use. .{ "x-uuencode", TransferEncoding.uuencode }, .{ "x-uue", TransferEncoding.uuencode }, .{ "uuencode", TransferEncoding.uuencode }, .{ "uue", TransferEncoding.uuencode }, .{ "x-uuencoded", TransferEncoding.uuencode }, // Written by senders that treated the value as a token with // optional whitespace and hyphens, which it is not. .{ "7-bit", TransferEncoding.seven_bit }, .{ "8-bit", TransferEncoding.eight_bit }, }; inline for (table) |entry| { if (std.ascii.eqlIgnoreCase(trimmed, entry[0])) return entry[1]; } return .unknown; } pub fn name(self: TransferEncoding) []const u8 { return switch (self) { .seven_bit => "7bit", .eight_bit => "8bit", .binary => "binary", .quoted_printable => "quoted-printable", .base64 => "base64", // The commonest of the five spellings. .uuencode => "x-uuencode", .unknown => "application/octet-stream", }; } /// Whether the body is its own decoding, so that decoding is a copy. pub fn isIdentity(self: TransferEncoding) bool { return switch (self) { .seven_bit, .eight_bit, .binary, .unknown => true, .quoted_printable, .base64, .uuencode => false, }; } /// The bytes the body stands for. The caller owns the result. pub fn decodeAlloc(self: TransferEncoding, gpa: Allocator, raw: []const u8) Allocator.Error![]u8 { return switch (self) { .seven_bit, .eight_bit, .binary, .unknown => gpa.dupe(u8, raw), .base64 => base64.decodeAlloc(gpa, raw), .quoted_printable => quoted_printable.decodeAlloc(gpa, raw), .uuencode => { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); uudecodeWriter(&out.writer, raw) catch return error.OutOfMemory; return out.toOwnedSlice(); }, }; } /// Whether this encoding can be produced a chunk at a time, without /// having the whole body to hand. /// /// Everything but quoted-printable can. Quoted-printable cannot, and the /// reason is lookahead rather than laziness: whether a space may be /// written as itself depends on how far the rest of its run reaches and on /// what follows it, whether a `.` must be escaped depends on whether the /// line ends after it, and `From ` has to be recognised five bytes at a /// time. An encoder fed a chunk at a time would have to buffer all of that /// anyway, and a quoted-printable body is a message's text rather than /// somebody's fifty megabyte attachment. pub fn streams(self: TransferEncoding) bool { return self != .quoted_printable; } /// The filename the body names for itself, which only a uuencoded one /// does: it is written on the `begin` line, and for a message old enough /// to be uuencoded it is frequently the only filename anywhere. pub fn embeddedName(self: TransferEncoding, raw: []const u8) ?[]const u8 { if (self != .uuencode) return null; const header = uuencodeHeader(raw) orelse return null; if (header.name.len == 0) return null; return header.name; } /// Writes `bytes` in this encoding, ready to be a body. pub fn encodeWriter( self: TransferEncoding, w: *Io.Writer, bytes: []const u8, options: EncodeOptions, ) Io.Writer.Error!void { return switch (self) { .seven_bit, .eight_bit, .binary, .unknown => w.writeAll(bytes), .base64 => base64.encodeWriter(w, bytes, .{}), .quoted_printable => quoted_printable.encodeWriter(w, bytes, .{ .mode = if (options.is_text) .text else .binary, }), .uuencode => blk: { var buffer: [max_uuencode_name]u8 = undefined; break :blk zuucode.encodeFile(w, .{ .name = safeUuencodeName(&buffer, options.name), }, bytes, .{ .line_ending = .crlf }); }, }; } /// Encodes from a reader onto a writer, without either the plain bytes or the /// encoded ones being held whole. /// /// Only for the encodings `streams` admits, which the caller must check — /// `Message.Part.setDataStreaming` is the way in that handles the other one. pub fn encodeStream( self: TransferEncoding, r: *Io.Reader, w: *Io.Writer, options: EncodeOptions, ) (Io.Reader.ShortError || Io.Writer.Error)!void { switch (self) { .seven_bit, .eight_bit, .binary, .unknown => { _ = r.streamRemaining(w) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.WriteFailed => return error.WriteFailed, }; }, .base64 => try base64.encodeStream(r, w, .{}), .uuencode => { var encoder: zuucode.Encoder = .init(w, .{ .line_ending = .crlf }); var buffer: [max_uuencode_name]u8 = undefined; try encoder.begin(.{ .name = safeUuencodeName(&buffer, options.name) }); while (true) { const chunk = r.peekGreedy(1) catch |err| switch (err) { error.EndOfStream => break, error.ReadFailed => return error.ReadFailed, }; try encoder.write(chunk); r.toss(chunk.len); } try encoder.end(); }, .quoted_printable => unreachable, // See `streams`. } } /// Writes the bytes the body stands for onto `w`, without allocating. /// /// The counterpart of `decodeAlloc` for a caller that is writing the result /// somewhere anyway: a fifty megabyte attachment reaches a file without a /// fifty megabyte buffer in between. pub fn decodeWriter( self: TransferEncoding, w: *Io.Writer, raw: []const u8, ) Io.Writer.Error!void { switch (self) { .seven_bit, .eight_bit, .binary, .unknown => try w.writeAll(raw), .quoted_printable => try quoted_printable.decodeWriter(w, raw), .uuencode => try uudecodeWriter(w, raw), .base64 => { var r: Io.Reader = .fixed(raw); _ = base64.decodeStream(&r, w) catch |err| switch (err) { error.WriteFailed => return error.WriteFailed, // A reader over a slice has nothing that can fail. error.ReadFailed => unreachable, }; }, } } }; /// The longest name a `begin` line will carry. Every filesystem bounds a /// filename well below this, and a header line running to kilobytes is not one /// any decoder is prepared for. const max_uuencode_name = 255; /// A name fit for a uuencoded body's `begin` line. /// /// The header is a single line with the name last on it, so a line ending /// anywhere in the name ends the header early — and a CRLF leaves a blank line /// immediately after `begin`, which is precisely what `uudecodeWriter` reads as /// the end of the body. The attachment then arrives empty, with nothing /// anywhere reporting that it was lost. /// /// A filename usually comes from outside the program — an upload, a directory /// listing, a header of somebody else's message — so this is not a theoretical /// shape, and it is the same reason every other writer here drops bare line /// endings. Spaces inside the name are kept, because the name runs to the end /// of the line and `my holiday.jpg` is an ordinary filename; spaces at the ends /// are not, because a transport that strips trailing whitespace would change /// the name in flight. fn safeUuencodeName(buffer: *[max_uuencode_name]u8, name: ?[]const u8) []const u8 { const source = name orelse return default_uuencode_name; var len: usize = 0; for (source) |c| { if (len == buffer.len) break; switch (c) { 0...0x1f, 0x7f => continue, else => {}, } buffer[len] = c; len += 1; } const trimmed = std.mem.trim(u8, buffer[0..len], " "); if (trimmed.len == 0) return default_uuencode_name; return trimmed; } pub const EncodeOptions = struct { /// Whether the body's line structure means anything, which it does /// exactly when the media type is `text/*`. Quoted-printable is the only /// encoding that asks. is_text: bool = false, /// The name to put on a uuencoded body's `begin` line. Uuencode is the one /// encoding that carries a filename of its own, and it has nowhere to say /// that it does not have one. name: ?[]const u8 = null, }; /// What a uuencoded body is called when nobody said. The format has no way to /// omit the name, so something has to go there. const default_uuencode_name = "attachment"; /// The `begin` line of a uuencoded text: the name and the mode it claims. /// Null if there is no `begin` line, which is how a caller tells a body that /// carries a uuencoded file from one that does not. /// /// The name is borrowed from `text` and does not outlive it. pub fn uuencodeHeader(text: []const u8) ?zuucode.Header { var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |line| { if (zuucode.parseBeginLine(std.mem.trimEnd(u8, line, "\r"))) |header| return header; } return null; } /// Decodes as much of a uuencoded body as decodes, and stops where it stops. /// /// Lenient for the same reason the base64 decoder is: a damaged attachment /// should arrive damaged rather than not arrive. Everything before the `begin` /// line is skipped, which is what makes this work on a body that has the /// covering note some senders put in front of one; a line that will not decode /// ends the body, as does the zero-length terminator, an `end` line, and the /// empty line that a transport leaves behind when it strips the terminator's /// single space. pub fn uudecodeWriter(w: *Io.Writer, raw: []const u8) Io.Writer.Error!void { var scanning = uuencodeHeader(raw) != null; var buffer: [zuucode.bytes_per_line]u8 = undefined; var lines = std.mem.splitScalar(u8, raw, '\n'); while (lines.next()) |raw_line| { const line = std.mem.trimEnd(u8, raw_line, "\r"); if (scanning) { // Before the `begin` line there is prose, not payload. if (zuucode.parseBeginLine(line) != null) scanning = false; continue; } if (line.len == 0 or zuucode.isEndLine(line)) return; const n = zuucode.decodeLine(&buffer, line, .{}) catch return; if (n == 0) return; try w.writeAll(buffer[0..n]); } } /// A decoder that can be fed a body a piece at a time, for a caller that is /// reading a message rather than holding one. /// /// `Message.Part.decodeWriter` is the same thing for a body that is already in /// memory; this is what the streaming parser's chunks want, since neither the /// encoded body nor the decoded one is ever whole. /// /// Uuencode is the exception and buffers. It is line oriented, and its `begin` /// line may sit anywhere after a covering note, so a decoder that could not /// look back would have to decode that note as though it were data. The /// bodies it appears on are from before 1996 and are not the ones anybody /// streams. pub const Decoder = struct { encoding: TransferEncoding, base64_state: base64.Decoder = .{}, quoted_printable_state: quoted_printable.Decoder = .{}, /// Uuencode only; empty for every other encoding. buffered: std.ArrayList(u8) = .empty, pub fn init(encoding: TransferEncoding) Decoder { return .{ .encoding = encoding }; } pub fn deinit(self: *Decoder, gpa: Allocator) void { self.buffered.deinit(gpa); self.* = undefined; } /// Whether this encoding is decoded a chunk at a time. False only for /// uuencode, which holds the body until `finish`. pub fn streams(self: Decoder) bool { return self.encoding != .uuencode; } pub fn write( self: *Decoder, gpa: Allocator, w: *Io.Writer, chunk: []const u8, ) (Allocator.Error || Io.Writer.Error)!void { switch (self.encoding) { .seven_bit, .eight_bit, .binary, .unknown => try w.writeAll(chunk), .base64 => try self.base64_state.write(w, chunk), .quoted_printable => try self.quoted_printable_state.write(w, chunk), .uuencode => try self.buffered.appendSlice(gpa, chunk), } } /// Emits whatever the end of the body is worth: a partial base64 group, a /// half-finished quoted-printable escape, or the whole of a uuencoded /// body. pub fn finish( self: *Decoder, gpa: Allocator, w: *Io.Writer, ) (Allocator.Error || Io.Writer.Error)!void { _ = gpa; switch (self.encoding) { .seven_bit, .eight_bit, .binary, .unknown => {}, .base64 => try self.base64_state.finish(w), .quoted_printable => try self.quoted_printable_state.finish(w), .uuencode => { try uudecodeWriter(w, self.buffered.items); self.buffered.clearRetainingCapacity(); }, } } }; /// Picks an encoding for a body that is about to be written. /// /// The rule is the one every mailer uses, and it is about what a reader sees /// as much as about size: a body that is already safe goes out untouched, a /// body that is mostly text goes out quoted-printable and stays half-readable /// to anything that does not decode it, and a body that is mostly not text /// goes out base64, which costs a third more bytes and does not pretend. /// /// `is_text` decides whether the line structure means anything, and it should /// be true exactly when the media type is `text/*`. pub fn choose(bytes: []const u8, is_text: bool) TransferEncoding { var high: usize = 0; var control: usize = 0; var longest_line: usize = 0; var line: usize = 0; var nul = false; for (bytes) |c| { switch (c) { '\n' => { longest_line = @max(longest_line, line); line = 0; continue; }, '\r', '\t' => {}, 0 => nul = true, 1...8, 11, 12, 14...31, 127 => control += 1, 0x80...0xff => high += 1, else => {}, } line += 1; } longest_line = @max(longest_line, line); // A NUL cannot go through a text encoding at all, and a line long enough // to be mangled has to be broken by something. if (nul) return .base64; if (!is_text and (high != 0 or control != 0)) return chooseEncoded(bytes.len, high + control); if (high == 0 and control == 0 and longest_line <= 998) return .seven_bit; if (longest_line > 998) return chooseEncoded(bytes.len, high + control); return chooseEncoded(bytes.len, high + control); } /// Quoted-printable costs three characters for each byte it has to escape and /// one for the rest; base64 costs four for every three whatever they are. The /// crossover is a little under a fifth, and being generous to quoted-printable /// is deliberate: a body that is half readable in a raw message is worth a few /// per cent. fn chooseEncoded(total: usize, escaped: usize) TransferEncoding { if (total == 0) return .seven_bit; return if (escaped * 5 <= total) .quoted_printable else .base64; } test "parsing the values" { try testing.expectEqual(TransferEncoding.seven_bit, TransferEncoding.parse("7bit")); try testing.expectEqual(TransferEncoding.base64, TransferEncoding.parse(" BASE64 ")); try testing.expectEqual(TransferEncoding.quoted_printable, TransferEncoding.parse("Quoted-Printable")); try testing.expectEqual(TransferEncoding.uuencode, TransferEncoding.parse("x-uuencode")); try testing.expectEqual(TransferEncoding.uuencode, TransferEncoding.parse("X-UUE")); try testing.expectEqual(TransferEncoding.uuencode, TransferEncoding.parse("uuencode")); try testing.expectEqual(TransferEncoding.unknown, TransferEncoding.parse("x-gzip64")); } test "an unknown encoding is not decoded" { const decoded = try TransferEncoding.unknown.decodeAlloc(testing.allocator, "begin 644 x"); defer testing.allocator.free(decoded); try testing.expectEqualStrings("begin 644 x", decoded); } test choose { try testing.expectEqual(TransferEncoding.seven_bit, choose("plain ASCII text\r\n", true)); try testing.expectEqual(TransferEncoding.quoted_printable, choose("a café in Paris\r\n", true)); try testing.expectEqual(TransferEncoding.base64, choose("\x00\x01\x02", true)); try testing.expectEqual(TransferEncoding.base64, choose("日本語の文章です", true)); // A line too long for a transport to be trusted with. try testing.expectEqual(TransferEncoding.quoted_printable, choose("x" ** 2000, true)); } test "a round trip through each encoding" { var bytes: [1024]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xb0d1); prng.random().bytes(&bytes); for ([_]TransferEncoding{ .base64, .quoted_printable, .binary }) |encoding| { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try encoding.encodeWriter(&out.writer, &bytes, .{}); const decoded = try encoding.decodeAlloc(testing.allocator, out.written()); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, &bytes, decoded); } } test "decoding onto a writer agrees with decoding into a buffer" { for ([_]TransferEncoding{ .base64, .quoted_printable, .binary }) |encoding| { var bytes: [2048]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xd3c0de); prng.random().bytes(&bytes); var encoded: Io.Writer.Allocating = .init(testing.allocator); defer encoded.deinit(); try encoding.encodeWriter(&encoded.writer, &bytes, .{}); // Streamed onto a writer... var streamed: Io.Writer.Allocating = .init(testing.allocator); defer streamed.deinit(); try encoding.decodeWriter(&streamed.writer, encoded.written()); // ...is what the allocating form would have returned. const at_once = try encoding.decodeAlloc(testing.allocator, encoded.written()); defer testing.allocator.free(at_once); try testing.expectEqualSlices(u8, &bytes, streamed.written()); try testing.expectEqualSlices(u8, at_once, streamed.written()); } } test "encoding from a reader agrees with encoding from a buffer" { var bytes: [4096]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xe9c0de); prng.random().bytes(&bytes); for ([_]TransferEncoding{ .base64, .binary }) |encoding| { try testing.expect(encoding.streams()); var streamed: Io.Writer.Allocating = .init(testing.allocator); defer streamed.deinit(); var reader: Io.Reader = .fixed(&bytes); try encoding.encodeStream(&reader, &streamed.writer, .{}); var at_once: Io.Writer.Allocating = .init(testing.allocator); defer at_once.deinit(); try encoding.encodeWriter(&at_once.writer, &bytes, .{}); try testing.expectEqualStrings(at_once.written(), streamed.written()); } try testing.expect(!TransferEncoding.quoted_printable.streams()); } test "a uuencoded body, whole and damaged" { var bytes: [500]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0x11ec0de); prng.random().bytes(&bytes); var encoded: Io.Writer.Allocating = .init(testing.allocator); defer encoded.deinit(); try TransferEncoding.uuencode.encodeWriter(&encoded.writer, &bytes, .{ .name = "data.bin" }); // It is a complete uuencoded file, and it says what it is called. try testing.expect(std.mem.startsWith(u8, encoded.written(), "begin 644 data.bin\r\n")); try testing.expect(std.mem.endsWith(u8, encoded.written(), "end\r\n")); try testing.expectEqualStrings( "data.bin", TransferEncoding.uuencode.embeddedName(encoded.written()).?, ); const decoded = try TransferEncoding.uuencode.decodeAlloc(testing.allocator, encoded.written()); defer testing.allocator.free(decoded); try testing.expectEqualSlices(u8, &bytes, decoded); // Truncated, which is what an archive of old mail is full of: what // decoded, decoded. Cut at a line boundary, because a line cut in half is // padded out with spaces rather than dropped -- that leniency is there for // the transports that strip trailing whitespace, and it means the last // line of a mid-line truncation comes back wrong rather than short. const half = encoded.written()[0 .. encoded.written().len / 2]; const cut = encoded.written()[0 .. std.mem.lastIndexOfScalar(u8, half, '\n').? + 1]; const partial = try TransferEncoding.uuencode.decodeAlloc(testing.allocator, cut); defer testing.allocator.free(partial); try testing.expect(partial.len > 0); try testing.expect(partial.len < bytes.len); try testing.expectEqualSlices(u8, bytes[0..partial.len], partial); } test "a covering note in front of the begin line is not payload" { const body = "Here is the file you asked for, uuencoded as usual.\r\n" ++ "\r\n" ++ "begin 755 script.sh\r\n" ++ "#0V%T\r\n" ++ "`\r\n" ++ "end\r\n" ++ "\r\n" ++ "Hope that helps.\r\n"; const decoded = try TransferEncoding.uuencode.decodeAlloc(testing.allocator, body); defer testing.allocator.free(decoded); try testing.expectEqualStrings("Cat", decoded); try testing.expectEqualStrings("script.sh", TransferEncoding.uuencode.embeddedName(body).?); } test "a body with no begin line at all is still decoded" { // Some senders uuencode the body and leave the header off, since the part // already has a filename of its own. const decoded = try TransferEncoding.uuencode.decodeAlloc(testing.allocator, "#0V%T\r\n`\r\n"); defer testing.allocator.free(decoded); try testing.expectEqualStrings("Cat", decoded); try testing.expectEqual(null, TransferEncoding.uuencode.embeddedName("#0V%T\r\n`\r\n")); } test "a body that is not uuencode at all decodes to nothing" { const decoded = try TransferEncoding.uuencode.decodeAlloc( testing.allocator, "This was never uuencoded.\r\n", ); defer testing.allocator.free(decoded); // The first line does not decode, so nothing does. Better than handing // back the prose as though it were the file. try testing.expectEqual(0, decoded.len); } test "uuencode never comes out of an automatic choice" { for ([_][]const u8{ "plain text\r\n", "caf\xc3\xa9\r\n", "\x00\x01\x02" }) |body| { for ([_]bool{ true, false }) |is_text| { try testing.expect(choose(body, is_text) != .uuencode); } } } test "the chunked decoder agrees with the whole-body one" { var bytes: [2000]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xc4c4ed); prng.random().bytes(&bytes); for ([_]TransferEncoding{ .base64, .quoted_printable, .binary, .uuencode }) |encoding| { var encoded: Io.Writer.Allocating = .init(testing.allocator); defer encoded.deinit(); try encoding.encodeWriter(&encoded.writer, &bytes, .{ .name = "chunks.bin" }); const whole = try encoding.decodeAlloc(testing.allocator, encoded.written()); defer testing.allocator.free(whole); try testing.expectEqualSlices(u8, &bytes, whole); for ([_]usize{ 1, 3, 61, 64, 1024 }) |chunk_len| { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var decoder: Decoder = .init(encoding); defer decoder.deinit(testing.allocator); var offset: usize = 0; while (offset < encoded.written().len) : (offset += chunk_len) { const end = @min(offset + chunk_len, encoded.written().len); try decoder.write(testing.allocator, &out.writer, encoded.written()[offset..end]); } try decoder.finish(testing.allocator, &out.writer); try testing.expectEqualSlices(u8, whole, out.written()); } } } test "only uuencode holds the body" { for ([_]TransferEncoding{ .base64, .quoted_printable, .binary, .seven_bit, .unknown }) |encoding| { const decoder: Decoder = .init(encoding); try testing.expect(decoder.streams()); } const uu: Decoder = .init(.uuencode); try testing.expect(!uu.streams()); }