// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Base64 as RFC 2045 §6.8 defines it, which is not quite the base64 in //! `std.base64`. //! //! Two differences, and both of them matter for mail: //! //! * **The encoder wraps.** A `Content-Transfer-Encoding: base64` body is //! broken into lines of at most 76 characters, because the transports this //! was designed for could not carry a longer one. `std.base64` emits one //! unbroken run. //! * **The decoder ignores what it does not recognise.** RFC 2045 is explicit: //! "any characters outside of the base64 alphabet are to be ignored in //! base64-encoded data". That is how the line breaks get in, and in practice //! it is also how a decoder survives the spaces, the stray `>` of a badly //! quoted forward, and the odd byte of MIME armour that real mail arrives //! wrapped in. `std.base64`'s decoder rejects all of it. //! //! Being lenient is a decision about *where* to fail rather than *whether* to. //! A message whose base64 has been mangled is a message whose attachment is //! damaged, and refusing to decode it turns a damaged attachment into an //! unreadable message. `decodeStrict` is here for the caller that would rather //! know. 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 alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// `decode_table[c]` is the six-bit value of `c`, or 0xff if `c` is not in the /// alphabet. `=` is 0xff like anything else: padding carries no bits, and the /// decoder learns where the data ended from how many characters it saw rather /// than from how many `=` followed them, which is the only way to decode the /// mail that omits the padding altogether. const decode_table = blk: { var table: [256]u8 = @splat(0xff); for (alphabet, 0..) |c, i| table[c] = i; break :blk table; }; pub const EncodeOptions = struct { /// Characters per line, not counting the line ending. RFC 2045 permits at /// most 76 and everything in the wild uses exactly that. Zero emits one /// unbroken line, which is what a `Content-Type` parameter value or a /// data URI wants and what a message body must never have. line_length: usize = 76, /// Mail is CRLF, on every platform, whatever the local convention is. ending: line_ending.Ending = .crlf, /// Whether a line ending follows the final line. A body wants one, because /// the boundary that follows it must begin a line of its own; a header /// parameter wants none. final_newline: bool = true, }; /// The exact number of bytes `encode` will write. pub fn encodedLen(source_len: usize, options: EncodeOptions) usize { const groups = (source_len + 2) / 3; const chars = groups * 4; if (options.line_length == 0 or chars == 0) return chars; const lines = (chars + options.line_length - 1) / options.line_length; const endings = if (options.final_newline) lines else lines - 1; return chars + endings * options.ending.bytes().len; } /// Encodes into `dest`, which must be at least `encodedLen` bytes, and returns /// how much of it was written. 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 `encodedLen`. return w.buffered(); } /// Encodes onto the end of an allocated buffer. pub fn encodeAlloc(gpa: Allocator, source: []const u8, options: EncodeOptions) Allocator.Error![]u8 { const dest = try gpa.alloc(u8, encodedLen(source.len, options)); errdefer gpa.free(dest); return encode(dest, source, options); } /// Encodes `source` onto `w`, wrapping as `options` say. pub fn encodeWriter(w: *Io.Writer, source: []const u8, options: EncodeOptions) Io.Writer.Error!void { var column: usize = 0; var i: usize = 0; while (i + 3 <= source.len) : (i += 3) { try writeGroup(w, source[i..][0..3], 3, options, &column); } if (i < source.len) { var tail: [3]u8 = @splat(0); const n = source.len - i; @memcpy(tail[0..n], source[i..]); try writeGroup(w, &tail, n, options, &column); } if (options.final_newline and column != 0) try w.writeAll(options.ending.bytes()); } fn writeGroup( w: *Io.Writer, group: *const [3]u8, len: usize, options: EncodeOptions, column: *usize, ) Io.Writer.Error!void { const bits: u24 = (@as(u24, group[0]) << 16) | (@as(u24, group[1]) << 8) | group[2]; var quad: [4]u8 = .{ alphabet[@as(u6, @truncate(bits >> 18))], alphabet[@as(u6, @truncate(bits >> 12))], alphabet[@as(u6, @truncate(bits >> 6))], alphabet[@as(u6, @truncate(bits))], }; // A group of one byte carries twelve bits of which four are padding, so // two characters say everything and the rest is `=`. if (len < 3) quad[3] = '='; if (len < 2) quad[2] = '='; var written: usize = 0; while (written < quad.len) { if (options.line_length != 0 and column.* == options.line_length) { try w.writeAll(options.ending.bytes()); column.* = 0; } const room = if (options.line_length == 0) quad.len - written else @min(quad.len - written, options.line_length - column.*); try w.writeAll(quad[written..][0..room]); written += room; column.* += room; } } /// An upper bound on what `decode` can produce from `encoded_len` characters, /// reached when every one of them is in the alphabet. pub fn decodedSizeUpperBound(encoded_len: usize) usize { return encoded_len / 4 * 3 + 3; } /// A decoder that can be fed the encoded text a piece at a time. /// /// The one implementation: `decode`, `decodeAlloc` and `decodeStream` are all /// this with the pieces arranged differently. Two decoders for one encoding /// drift apart the first time either is touched, and the drift shows up as an /// attachment that comes out right when it is read one way and wrong when it /// is read the other. /// /// A group is four characters and three bytes, and a chunk boundary has /// nothing to do with where those fall, which is the whole reason there is /// state to keep. pub const Decoder = struct { accumulator: u24 = 0, count: u3 = 0, /// How many bytes have been written since this decoder was made, which is /// what `decodeStream` reports and what a caller writing to a file already /// knows another way. written: u64 = 0, pub fn write(self: *Decoder, w: *Io.Writer, source: []const u8) Io.Writer.Error!void { for (source) |c| { const value = decode_table[c]; if (value == 0xff) continue; self.accumulator = (self.accumulator << 6) | value; self.count += 1; if (self.count == 4) { try w.writeAll(&.{ @truncate(self.accumulator >> 16), @truncate(self.accumulator >> 8), @truncate(self.accumulator), }); self.written += 3; self.count = 0; self.accumulator = 0; } } } /// Emits whatever a trailing partial group is worth. /// /// Two characters are twelve bits, of which the low four are padding that /// was never sent; three are eighteen, of which the low two are. One on /// its own carries six bits, which is not a byte and is dropped. pub fn finish(self: *Decoder, w: *Io.Writer) Io.Writer.Error!void { switch (self.count) { 0, 1 => {}, 2 => { try w.writeByte(@truncate(self.accumulator >> 4)); self.written += 1; }, 3 => { try w.writeAll(&.{ @truncate(self.accumulator >> 10), @truncate(self.accumulator >> 2), }); self.written += 2; }, else => unreachable, } self.accumulator = 0; self.count = 0; } }; /// Decodes leniently into `dest`, which must be at least /// `decodedSizeUpperBound(source.len)` bytes, and returns what was written. /// /// Anything not in the alphabet is skipped, and a run of characters that does /// not divide into complete groups contributes whatever whole bytes it can: a /// truncated attachment decodes to a truncated file rather than to an error. pub fn decode(dest: []u8, source: []const u8) []u8 { var w: Io.Writer = .fixed(dest); var decoder: Decoder = .{}; decoder.write(&w, source) catch unreachable; // `dest` was sized by the bound. decoder.finish(&w) catch unreachable; return w.buffered(); } /// Decodes leniently into a freshly allocated buffer sized to what came out. pub fn decodeAlloc(gpa: Allocator, source: []const u8) Allocator.Error![]u8 { const scratch = try gpa.alloc(u8, decodedSizeUpperBound(source.len)); errdefer gpa.free(scratch); const decoded = decode(scratch, source); // The upper bound assumed every character counted; give the slack back, // since an attachment's worth of it is not slack. if (gpa.resize(scratch, decoded.len)) return scratch[0..decoded.len]; defer gpa.free(scratch); return gpa.dupe(u8, decoded); } pub const StrictError = error{ /// A character that is not in the alphabet, not padding, and not a line /// ending or space. InvalidCharacter, /// The number of alphabet characters is not a multiple of four, or `=` /// appears anywhere but at the very end. InvalidPadding, }; /// Decodes the way `decode` does, but first refuses anything a conforming /// encoder would not have produced. For a caller who would rather hear that an /// attachment is damaged than receive the damage. pub fn decodeStrict(dest: []u8, source: []const u8) StrictError![]u8 { var chars: usize = 0; var padding: usize = 0; for (source) |c| switch (c) { '\r', '\n', ' ', '\t' => {}, '=' => padding += 1, else => { if (decode_table[c] == 0xff) return error.InvalidCharacter; // Data after padding is the mistake `=` was supposed to make // impossible, and the shape a concatenation of two messages takes. if (padding != 0) return error.InvalidPadding; chars += 1; }, }; if (padding > 2) return error.InvalidPadding; if ((chars + padding) % 4 != 0) return error.InvalidPadding; if (padding == 1 and chars % 4 != 3) return error.InvalidPadding; if (padding == 2 and chars % 4 != 2) return error.InvalidPadding; if (padding == 0 and chars % 4 != 0) return error.InvalidPadding; return decode(dest, source); } /// Decodes from a reader onto a writer without holding the whole of either, /// which is the difference between opening a fifty megabyte attachment and /// allocating a hundred megabytes to do it. Returns how many bytes were /// written. /// `ShortError` rather than `Error`: this consumes the reader to its end, so /// reaching the end is how it finishes rather than something it reports. pub fn decodeStream(r: *Io.Reader, w: *Io.Writer) (Io.Reader.ShortError || Io.Writer.Error)!u64 { var decoder: Decoder = .{}; while (true) { const chunk = r.peekGreedy(1) catch |err| switch (err) { error.EndOfStream => break, error.ReadFailed => return error.ReadFailed, }; try decoder.write(w, chunk); r.toss(chunk.len); } try decoder.finish(w); return decoder.written; } /// Encodes from a reader onto a writer, wrapping as `options` say. pub fn encodeStream( r: *Io.Reader, w: *Io.Writer, options: EncodeOptions, ) (Io.Reader.ShortError || Io.Writer.Error)!void { var column: usize = 0; var pending: [3]u8 = @splat(0); var pending_len: usize = 0; while (true) { const chunk = r.peekGreedy(1) catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; var i: usize = 0; // Fill whatever the last chunk left half-finished before taking whole // groups out of this one; the encoding is only defined on triples, and // a chunk boundary is nothing to do with where those fall. while (pending_len != 0 and i < chunk.len) { pending[pending_len] = chunk[i]; pending_len += 1; i += 1; if (pending_len == 3) { try writeGroup(w, &pending, 3, options, &column); pending_len = 0; } } while (i + 3 <= chunk.len) : (i += 3) { try writeGroup(w, chunk[i..][0..3], 3, options, &column); } while (i < chunk.len) : (i += 1) { pending[pending_len] = chunk[i]; pending_len += 1; } r.toss(chunk.len); } if (pending_len != 0) { @memset(pending[pending_len..], 0); try writeGroup(w, &pending, pending_len, options, &column); } if (options.final_newline and column != 0) try w.writeAll(options.ending.bytes()); } test encodedLen { try testing.expectEqual(0, encodedLen(0, .{})); try testing.expectEqual(4 + 2, encodedLen(1, .{})); try testing.expectEqual(4, encodedLen(1, .{ .final_newline = false })); // 57 bytes is exactly 76 characters, the one line length that divides. try testing.expectEqual(76 + 2, encodedLen(57, .{})); try testing.expectEqual(76 + 2 + 4 + 2, encodedLen(58, .{})); } test "encode wraps at 76 characters" { const source = &@as([100]u8, @splat('x')); var buffer: [512]u8 = undefined; const encoded = encode(&buffer, source, .{}); try testing.expectEqual(encodedLen(source.len, .{}), encoded.len); var lines = std.mem.splitSequence(u8, encoded[0 .. encoded.len - 2], "\r\n"); try testing.expectEqual(76, lines.next().?.len); try testing.expectEqual(60, lines.next().?.len); try testing.expectEqual(null, lines.next()); } test "encode pads" { var buffer: [64]u8 = undefined; const options: EncodeOptions = .{ .final_newline = false }; try testing.expectEqualStrings("", encode(&buffer, "", options)); try testing.expectEqualStrings("Zg==", encode(&buffer, "f", options)); try testing.expectEqualStrings("Zm8=", encode(&buffer, "fo", options)); try testing.expectEqualStrings("Zm9v", encode(&buffer, "foo", options)); try testing.expectEqualStrings("Zm9vYmFy", encode(&buffer, "foobar", options)); } test "decode ignores everything outside the alphabet" { var buffer: [64]u8 = undefined; try testing.expectEqualStrings("foobar", decode(&buffer, "Zm9v\r\nYmFy")); try testing.expectEqualStrings("foobar", decode(&buffer, "Zm9 vYm Fy")); try testing.expectEqualStrings("foobar", decode(&buffer, "> Zm9vYmFy")); // Missing padding, which plenty of encoders omit. try testing.expectEqualStrings("f", decode(&buffer, "Zg")); try testing.expectEqualStrings("fo", decode(&buffer, "Zm8")); // A single dangling character is not a byte. try testing.expectEqualStrings("foo", decode(&buffer, "Zm9vY")); } test decodeStrict { var buffer: [64]u8 = undefined; try testing.expectEqualStrings("foobar", try decodeStrict(&buffer, "Zm9v\r\nYmFy")); try testing.expectEqualStrings("f", try decodeStrict(&buffer, "Zg==")); try testing.expectError(error.InvalidPadding, decodeStrict(&buffer, "Zg")); try testing.expectError(error.InvalidPadding, decodeStrict(&buffer, "Zg=")); try testing.expectError(error.InvalidPadding, decodeStrict(&buffer, "Zg==Zg==")); try testing.expectError(error.InvalidCharacter, decodeStrict(&buffer, "Zm9v-YmFy")); } test "round trip through an allocator" { var bytes: [1024]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0x5eed); prng.random().bytes(&bytes); for ([_]usize{ 0, 1, 2, 3, 57, 58, 1024 }) |len| { const encoded = try encodeAlloc(testing.allocator, bytes[0..len], .{}); 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 "streaming agrees with the whole-buffer form" { var bytes: [4096]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xdecaf); prng.random().bytes(&bytes); var encoded: Io.Writer.Allocating = .init(testing.allocator); defer encoded.deinit(); var source: Io.Reader = .fixed(&bytes); try encodeStream(&source, &encoded.writer, .{}); const at_once = try encodeAlloc(testing.allocator, &bytes, .{}); defer testing.allocator.free(at_once); try testing.expectEqualStrings(at_once, encoded.written()); var decoded: Io.Writer.Allocating = .init(testing.allocator); defer decoded.deinit(); var encoded_reader: Io.Reader = .fixed(encoded.written()); const n = try decodeStream(&encoded_reader, &decoded.writer); try testing.expectEqual(bytes.len, n); try testing.expectEqualSlices(u8, &bytes, decoded.written()); } test "streaming survives a group split across two reads" { // A one-byte buffer makes every `peekGreedy` return a single byte, so // every three-byte group spans three of them. var source: Io.Reader = .fixed("foobar!"); var encoded: Io.Writer.Allocating = .init(testing.allocator); defer encoded.deinit(); var tiny: [1]u8 = undefined; var limited = source.limited(.unlimited, &tiny); try encodeStream(&limited.interface, &encoded.writer, .{ .final_newline = false }); try testing.expectEqualStrings("Zm9vYmFyIQ==", encoded.written()); } test "the decoder agrees with itself however the pieces arrive" { var bytes: [3000]u8 = undefined; var prng: std.Random.DefaultPrng = .init(0xc4c4); prng.random().bytes(&bytes); const encoded = try encodeAlloc(testing.allocator, &bytes, .{}); defer testing.allocator.free(encoded); // Every chunk size, including the ones that split a group of four and the // ones that split a line ending. for ([_]usize{ 1, 2, 3, 4, 5, 7, 76, 77, 1024 }) |chunk_len| { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var decoder: Decoder = .{}; var offset: usize = 0; while (offset < encoded.len) : (offset += chunk_len) { try decoder.write(&out.writer, encoded[offset..@min(offset + chunk_len, encoded.len)]); } try decoder.finish(&out.writer); try testing.expectEqualSlices(u8, &bytes, out.written()); try testing.expectEqual(bytes.len, decoder.written); } }