// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Modified UTF-7, the encoding IMAP4rev1 uses for mailbox names that are //! not ASCII. //! //! Printable ASCII other than `&` stands for itself. `&` is written `&-`. //! Anything else is written as a run of UTF-16BE encoded in a variant of //! base64 — `,` in place of `/`, no `=` padding — between an `&` and a `-`. //! So "Entwürfe" is "Entw&APw-rfe" and "日本語" is "&ZeVnLIqe-". //! //! IMAP4rev2 does away with this: once `ENABLE UTF8=ACCEPT` has been agreed, //! names are UTF-8 in a quoted string or a literal. Until then, and against //! every rev1 server, this is what a name has to become before it goes on //! the wire and what it has to come back from. //! //! https://datatracker.ietf.org/doc/html/rfc3501#section-5.1.3 //! https://datatracker.ietf.org/doc/html/rfc2152 const std = @import("std"); const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,"; /// Whether `name` needs encoding at all: whether it holds anything outside /// printable ASCII, or an `&`. pub fn needsEncoding(name: []const u8) bool { for (name) |c| { if (c < 0x20 or c > 0x7e or c == '&') return true; } return false; } pub const EncodeError = std.Io.Writer.Error || error{InvalidUtf8}; /// Writes `name`, a UTF-8 mailbox name, in modified UTF-7. pub fn encode(w: *std.Io.Writer, name: []const u8) EncodeError!void { if (!std.unicode.utf8ValidateSlice(name)) return error.InvalidUtf8; var i: usize = 0; while (i < name.len) { const c = name[i]; if (c == '&') { try w.writeAll("&-"); i += 1; } else if (c >= 0x20 and c <= 0x7e) { try w.writeByte(c); i += 1; } else { // A run of everything up to the next directly-encodable byte, // as UTF-16BE, base64'd with the modified alphabet. const start = i; while (i < name.len and (name[i] < 0x20 or name[i] > 0x7e) and name[i] != '&') { i += std.unicode.utf8ByteSequenceLength(name[i]) catch unreachable; } try w.writeByte('&'); try encodeRun(w, name[start..i]); try w.writeByte('-'); } } } fn encodeRun(w: *std.Io.Writer, run: []const u8) std.Io.Writer.Error!void { var bits: u32 = 0; var nbits: u5 = 0; var it = std.unicode.Utf8View.initUnchecked(run).iterator(); while (it.nextCodepoint()) |cp| { var units: [2]u16 = undefined; const n: usize = if (cp < 0x10000) 1 else 2; if (n == 1) { units[0] = @intCast(cp); } else { const v = cp - 0x10000; units[0] = @intCast(0xd800 + (v >> 10)); units[1] = @intCast(0xdc00 + (v & 0x3ff)); } for (units[0..n]) |unit| { for ([_]u8{ @intCast(unit >> 8), @intCast(unit & 0xff) }) |byte| { bits = (bits << 8) | byte; nbits += 8; while (nbits >= 6) { nbits -= 6; try w.writeByte(alphabet[(bits >> nbits) & 0x3f]); } } } } if (nbits > 0) try w.writeByte(alphabet[(bits << (6 - nbits)) & 0x3f]); } /// `encode` into `buf`. pub fn encodeBuf(buf: []u8, name: []const u8) (error{ NoSpaceLeft, InvalidUtf8 })![]u8 { var w: std.Io.Writer = .fixed(buf); encode(&w, name) catch |err| switch (err) { error.WriteFailed => return error.NoSpaceLeft, error.InvalidUtf8 => return error.InvalidUtf8, }; return w.buffered(); } pub const DecodeError = std.Io.Writer.Error || error{InvalidEncoding}; /// Writes a modified-UTF-7 mailbox name as UTF-8. /// /// The encoding is strict, as RFC 3501 requires a server to be: an /// unterminated run, a run with padding bits set, a bare `&`, or UTF-16 that /// does not pair up is `error.InvalidEncoding` rather than a guess. A name /// that fails here is one to leave as it was. pub fn decode(w: *std.Io.Writer, encoded: []const u8) DecodeError!void { var i: usize = 0; while (i < encoded.len) { const c = encoded[i]; if (c != '&') { if (c < 0x20 or c > 0x7e) return error.InvalidEncoding; try w.writeByte(c); i += 1; continue; } const end = std.mem.findScalarPos(u8, encoded, i + 1, '-') orelse return error.InvalidEncoding; const run = encoded[i + 1 .. end]; if (run.len == 0) { try w.writeByte('&'); } else { try decodeRun(w, run); } i = end + 1; } } fn decodeRun(w: *std.Io.Writer, run: []const u8) DecodeError!void { var bits: u32 = 0; var nbits: u5 = 0; var high: ?u16 = null; for (run) |c| { const value: u32 = @intCast(std.mem.findScalar(u8, alphabet, c) orelse return error.InvalidEncoding); bits = (bits << 6) | value; nbits += 6; if (nbits >= 16) { nbits -= 16; const unit: u16 = @intCast((bits >> nbits) & 0xffff); bits &= (@as(u32, 1) << nbits) - 1; if (high) |h| { if (unit < 0xdc00 or unit > 0xdfff) return error.InvalidEncoding; const cp: u21 = 0x10000 + ((@as(u21, h) - 0xd800) << 10) + (unit - 0xdc00); try writeCodepoint(w, cp); high = null; } else if (unit >= 0xd800 and unit <= 0xdbff) { high = unit; } else if (unit >= 0xdc00 and unit <= 0xdfff) { return error.InvalidEncoding; } else if (unit >= 0x20 and unit <= 0x7e) { // RFC 3501 forbids base64 for a character that can stand // for itself, so `&AD0-` is not a spelling of `=`. Accepting // it would make two names of one, and a decoded name that // re-encodes differently cannot be found again. return error.InvalidEncoding; } else { try writeCodepoint(w, unit); } } } // What is left over is padding, and padding is zero bits — fewer than // six of them, or the run would have ended a character earlier. if (nbits >= 6 or bits != 0 or high != null) return error.InvalidEncoding; } fn writeCodepoint(w: *std.Io.Writer, cp: u21) DecodeError!void { var buf: [4]u8 = undefined; const n = std.unicode.utf8Encode(cp, &buf) catch return error.InvalidEncoding; try w.writeAll(buf[0..n]); } /// `decode` into `buf`. pub fn decodeBuf(buf: []u8, encoded: []const u8) (error{ NoSpaceLeft, InvalidEncoding })![]u8 { var w: std.Io.Writer = .fixed(buf); decode(&w, encoded) catch |err| switch (err) { error.WriteFailed => return error.NoSpaceLeft, error.InvalidEncoding => return error.InvalidEncoding, }; return w.buffered(); } fn expectEncodes(utf8: []const u8, utf7: []const u8) !void { var buf: [256]u8 = undefined; try std.testing.expectEqualStrings(utf7, try encodeBuf(&buf, utf8)); var back: [256]u8 = undefined; try std.testing.expectEqualStrings(utf8, try decodeBuf(&back, utf7)); } test "the examples from the RFCs" { // RFC 3501's own: "~peter/mail/台北/日本語". try expectEncodes( "~peter/mail/\xe5\x8f\xb0\xe5\x8c\x97/\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e", "~peter/mail/&U,BTFw-/&ZeVnLIqe-", ); try expectEncodes("Entw\xc3\xbcrfe", "Entw&APw-rfe"); try expectEncodes("Fish & Chips", "Fish &- Chips"); try expectEncodes("INBOX", "INBOX"); try expectEncodes("", ""); // Outside the BMP: a surrogate pair. try expectEncodes("\xf0\x9f\x93\xa7", "&2D3c5w-"); // A run followed directly by an ampersand, and two runs in a row. try expectEncodes("\xc3\xa9&\xc3\xa9", "&AOk-&-&AOk-"); } test "what needs encoding" { try std.testing.expect(!needsEncoding("Sent Items")); try std.testing.expect(needsEncoding("Fish & Chips")); try std.testing.expect(needsEncoding("Entw\xc3\xbcrfe")); try std.testing.expect(needsEncoding("tab\there")); } test "decoding is strict" { var buf: [64]u8 = undefined; try std.testing.expectError(error.InvalidEncoding, decodeBuf(&buf, "&APw")); try std.testing.expectError(error.InvalidEncoding, decodeBuf(&buf, "&*-")); // Padding bits that are not zero. try std.testing.expectError(error.InvalidEncoding, decodeBuf(&buf, "&APx-")); // A lone surrogate. try std.testing.expectError(error.InvalidEncoding, decodeBuf(&buf, "&2D0-")); // A printable character that should have stood for itself; the fuzzer // found this one. try std.testing.expectError(error.InvalidEncoding, decodeBuf(&buf, "&AD0-")); // 8-bit outside a run. try std.testing.expectError(error.InvalidEncoding, decodeBuf(&buf, "caf\xc3\xa9")); // Not UTF-8 on the way in. try std.testing.expectError(error.InvalidUtf8, encodeBuf(&buf, "\xff")); var tiny: [2]u8 = undefined; try std.testing.expectError(error.NoSpaceLeft, encodeBuf(&tiny, "Entw\xc3\xbcrfe")); }