// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! RFC 2047 encoded words: `=?UTF-8?Q?caf=C3=A9?=`, the way a header carries //! text that a header is not allowed to contain. //! //! A header line is US-ASCII, seventy-eight characters to a line by //! convention and a thousand by rule. A subject in Japanese is none of those //! things, so it is spelled as a token that *is* — a charset, a one-letter //! encoding, and the text under it — and a reader that knows the notation puts //! it back. `B` is base64; `Q` is quoted-printable with a narrower idea of //! what may be left alone, plus the rule that `_` is a space. //! //! Three details cost more time than the format itself: //! //! * **An encoded word is a token, not a substring.** `=?utf-8?q?x?=` inside a //! longer atom is not one, and text that merely resembles one must survive //! being written out and read back. Finding them by searching for `=?` is //! how a subject reading "look at =?this?=" becomes mojibake. //! * **Whitespace between two adjacent encoded words is not whitespace.** It //! is how the encoder was able to fold a long run across several lines, and //! the decoder removes it. Whitespace between an encoded word and ordinary //! text *is* whitespace, and removing it joins two words that were never one. //! * **An encoded word may not exceed 75 characters**, which is why a long //! subject becomes several of them, and why the encoder here has to split //! its input — without ever splitting a UTF-8 character in half, since each //! word is decoded on its own and half a character decodes to nothing good. //! //! ## Charsets //! //! What comes out of an encoded word is bytes and the name of the charset they //! are in. This library carries no charset tables, so `Iterator` reports the //! name and hands over the bytes; transcoding is the caller's, and belongs to //! whatever the caller already uses for the rest of its text. //! //! `decodeUtf8Alloc` is the convenience for the common case, and it handles //! exactly the charsets that need no table: UTF-8 and US-ASCII, which are //! already the answer, and ISO-8859-1, whose bytes are their own code points. //! Anything else is passed through with invalid sequences replaced, so that //! the result is always valid UTF-8 and a Shift-JIS subject degrades to //! something legible-ish rather than to an error in the middle of a mailbox //! listing. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const base64 = @import("base64.zig"); const charset_module = @import("../charset.zig"); const lexer = @import("../header/lexer.zig"); /// The maximum length of one encoded word, from `=?` to `?=` inclusive. /// RFC 2047 §2. pub const max_length = 75; pub const Encoding = enum { /// Base64. Costs four characters per three bytes whatever the bytes are, /// so it wins when most of the text is non-ASCII. b, /// Quoted-printable, with `_` for space. Costs one character per ASCII /// byte and three per other, so it wins when most of the text is ASCII — /// and it leaves the result half-readable to a program that does not /// decode it, which is worth something. q, pub fn letter(self: Encoding) u8 { return switch (self) { .b => 'B', .q => 'Q', }; } fn fromLetter(c: u8) ?Encoding { return switch (c) { 'b', 'B' => .b, 'q', 'Q' => .q, else => null, }; } }; /// One `=?charset?encoding?text?=`, taken apart but not decoded. pub const Word = struct { /// The charset name, as written. Compare it case-insensitively. charset: []const u8, /// RFC 2231 §5 allows `=?utf-8*en?...`, naming the language of the text. /// Almost nothing writes it and nothing much reads it, but it is here /// rather than glued to the end of the charset name, where it would /// quietly make every charset comparison fail. language: ?[]const u8, encoding: Encoding, /// The still-encoded text. text: []const u8, /// How many bytes of the source the whole word occupied. len: usize, /// An upper bound on what `decode` will write. pub fn decodedSizeUpperBound(self: Word) usize { return switch (self.encoding) { .b => base64.decodedSizeUpperBound(self.text.len), .q => self.text.len, }; } /// Decodes the text into `dest`, which must be at least /// `decodedSizeUpperBound` bytes, and returns what was written. The result /// is in `charset`, which may be anything at all. pub fn decode(self: Word, dest: []u8) []u8 { return switch (self.encoding) { .b => base64.decode(dest, self.text), .q => decodeQ(dest, self.text), }; } }; /// Reads one encoded word from the start of `source`. Null if there is not one /// there — including the case of a `=?` that begins something which is not a /// well-formed word, which is then ordinary text and must stay so. pub fn parse(source: []const u8) ?Word { if (!std.mem.startsWith(u8, source, "=?")) return null; const charset_start = 2; // A charset name is a token, and in particular contains no `?`. Bounding // the search at the maximum word length is what stops a `=?` in ordinary // text from matching a `?` a thousand characters later. const limit = @min(source.len, max_length); const charset_end = std.mem.findScalarPos(u8, source[0..limit], charset_start, '?') orelse return null; if (charset_end == charset_start) return null; if (charset_end + 2 >= source.len) return null; const encoding = Encoding.fromLetter(source[charset_end + 1]) orelse return null; if (source[charset_end + 2] != '?') return null; const text_start = charset_end + 3; const text_end = std.mem.findPos(u8, source[0..limit], text_start, "?=") orelse return null; var charset = source[charset_start..charset_end]; var language: ?[]const u8 = null; if (std.mem.findScalar(u8, charset, '*')) |star| { language = charset[star + 1 ..]; charset = charset[0..star]; } // A charset name is an RFC 2047 token, and the encoded text is printable // ASCII without `?` or space. A space in either means this was never a // word: the whitespace would have ended it. for (charset) |c| if (!lexer.isTokenChar(c)) return null; for (source[text_start..text_end]) |c| if (!isEncodedTextChar(c)) return null; return .{ .charset = charset, .language = language, .encoding = encoding, .text = source[text_start..text_end], .len = text_end + 2, }; } /// The `Q` encoding of RFC 2047 §4.2: quoted-printable, except that `_` is a /// space and there are no soft line breaks because there are no lines. pub fn decodeQ(dest: []u8, source: []const u8) []u8 { var out: usize = 0; var i: usize = 0; while (i < source.len) { switch (source[i]) { '_' => { dest[out] = ' '; out += 1; i += 1; }, '=' => { if (i + 2 < source.len) { if (hexDigit(source[i + 1])) |high| { if (hexDigit(source[i + 2])) |low| { dest[out] = high << 4 | low; out += 1; i += 3; continue; } } } // Not an escape. Keep it: a decoder that drops bytes turns a // damaged subject into a misleading one. dest[out] = '='; out += 1; i += 1; }, else => { dest[out] = source[i]; out += 1; i += 1; }, } } return dest[0..out]; } /// RFC 2047 §2: the encoded text is printable US-ASCII other than `?` and /// space. The high-bit bytes some senders put here are *not* allowed, and /// admitting them would make every `=?` in an eight-bit subject line the start /// of a word. fn isEncodedTextChar(c: u8) bool { return switch (c) { 33...62, 64...126 => true, // Printable, less `?` (63) and space (32). else => false, }; } fn hexDigit(c: u8) ?u8 { return switch (c) { '0'...'9' => c - '0', 'A'...'F' => c - 'A' + 10, 'a'...'f' => c - 'a' + 10, else => null, }; } /// A run of a header value: either text that was never encoded, or the decoded /// contents of one encoded word together with the charset it is in. pub const Chunk = struct { text: []const u8, /// Null for a run that was not encoded. Such a run is US-ASCII by the /// grammar and UTF-8 in practice. charset: ?[]const u8, language: ?[]const u8 = null, }; /// Walks a header value, yielding its literal runs and its decoded encoded /// words in order, without allocating. /// /// The scratch buffer must be at least as long as the source, which is enough /// for any word in it: decoding never grows. pub const Iterator = struct { source: []const u8, scratch: []u8, index: usize = 0, previous_was_encoded: bool = false, pub fn init(source: []const u8, scratch: []u8) Iterator { std.debug.assert(scratch.len >= source.len); return .{ .source = source, .scratch = scratch }; } /// The next run. The `text` of a decoded run points into the scratch /// buffer and is valid until the next call; the `text` of a literal run /// points into the source and is valid as long as it is. pub fn next(self: *Iterator) ?Chunk { if (self.index >= self.source.len) return null; if (parseAt(self.source, self.index)) |word| { self.index += word.len; self.previous_was_encoded = true; return .{ .text = word.decode(self.scratch), .charset = word.charset, .language = word.language, }; } // A literal run, ending where the next encoded word begins. const start = self.index; var i = self.index; while (i < self.source.len) : (i += 1) { if (self.source[i] == '=' and parseAt(self.source, i) != null) break; } self.index = i; const literal = self.source[start..i]; const was_encoded = self.previous_was_encoded; self.previous_was_encoded = false; // Whitespace between two encoded words is how the encoder folded a // long run onto several lines. It is not part of the text, and the // rule is in RFC 2047 §6.2. if (was_encoded and i < self.source.len and isAllWsp(literal)) return self.next(); return .{ .text = literal, .charset = null }; } }; /// An encoded word is a token: it begins the value, or follows whitespace or /// one of the characters that end a token. Anywhere else, `=?` is two /// characters of an atom. fn parseAt(source: []const u8, index: usize) ?Word { if (index != 0) { const before = source[index - 1]; if (!isSpace(before) and !isPhraseBreak(before)) return null; } const word = parse(source[index..]) orelse return null; // ...and it ends at one, for the same reason. const after_index = index + word.len; if (after_index < source.len) { const after = source[after_index]; if (!isSpace(after) and !isPhraseBreak(after)) return null; } return word; } /// Whitespace, plus the CR and LF of a fold. A value reaching this has /// usually been unfolded already, but a caller handing over a raw header line /// should still find the words in it rather than none of them. fn isSpace(c: u8) bool { return lexer.isWsp(c) or c == '\r' or c == '\n'; } fn isPhraseBreak(c: u8) bool { return switch (c) { '(', ')', '<', '>', '[', ']', ':', ';', '@', ',', '"' => true, else => false, }; } fn isAllWsp(text: []const u8) bool { if (text.len == 0) return false; for (text) |c| if (!isSpace(c)) return false; return true; } /// Whether `value` contains anything an encoded word would have to be decoded /// out of. Cheap enough to call before allocating for a decode that would have /// copied the value unchanged, which is what nearly every header does. pub fn isEncoded(value: []const u8) bool { var i: usize = 0; while (std.mem.findPos(u8, value, i, "=?")) |at| : (i = at + 2) { if (parseAt(value, at) != null) return true; } return false; } /// Decodes a whole header value to UTF-8. /// /// UTF-8, US-ASCII and ISO-8859-1 are converted exactly. Any other charset is /// passed through with invalid UTF-8 sequences replaced by U+FFFD, on the /// grounds that a reader would rather see most of a subject than an error — /// see the module comment, and use `Iterator` where that is not good enough. /// /// **The result is always valid UTF-8**, which is the point of the function: /// it is what gets handed to whatever displays or indexes the header. That /// applies to the text that was never encoded as well, since a header is /// supposed to be ASCII and a great many are not — a sender whose locale was /// ISO-8859-15 puts its bytes straight into the `Subject:` and says nothing, /// and those bytes are not UTF-8 and cannot be made into it without the table /// this library does not carry. They come back with the invalid sequences /// replaced rather than as a subject that crashes a UTF-8 consumer three /// layers away. pub fn decodeUtf8Alloc(gpa: Allocator, value: []const u8) Allocator.Error![]u8 { if (!isEncoded(value)) return charset_module.toUtf8Alloc(gpa, value, "utf-8"); const scratch = try gpa.alloc(u8, value.len); defer gpa.free(scratch); var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); var it: Iterator = .init(value, scratch); while (it.next()) |chunk| { const name = chunk.charset orelse { // A run that was never encoded. The grammar says US-ASCII; RFC // 6532 and reality say UTF-8, and a sender with a locale of its // own says neither. charset_module.writeValidUtf8(&out.writer, chunk.text) catch return error.OutOfMemory; continue; }; charset_module.toUtf8Writer(&out.writer, chunk.text, name) catch return error.OutOfMemory; } return out.toOwnedSlice(); } pub const EncodeOptions = struct { /// The name written into the word. Changing it does not transcode /// anything: the bytes handed in must already be in it. charset: []const u8 = "UTF-8", /// `.auto` encodes each run whichever way is shorter, which for a subject /// that is mostly ASCII with an accent in it is `Q` by a wide margin. encoding: enum { auto, b, q } = .auto, /// What separates the words when the text needs more than one. It has to /// be whitespace, since that is what the decoder deletes; a fold makes the /// header line legal as well as short. separator: []const u8 = "\r\n ", /// How many characters of the first line are already spoken for — the /// `Subject: ` before the value, say — so that the first word is short /// enough to fit beside it. first_line_used: usize = 0, }; /// Writes `text` as one or more encoded words. pub fn encodeWriter(w: *Io.Writer, text: []const u8, options: EncodeOptions) Io.Writer.Error!void { const overhead = options.charset.len + 7; // "=?" charset "?" x "?" "?=" var rest = text; var budget_offset = options.first_line_used; var first = true; while (true) { const limit = blk: { const available = max_length -| (overhead + budget_offset); // Room for at least one Q escape, or the encoder cannot make // progress. A degenerate `first_line_used` is worth a long line // more than it is worth an infinite loop. break :blk @max(available, 3); }; const encoding: Encoding = switch (options.encoding) { .b => .b, .q => .q, .auto => if (qLen(rest) <= base64.encodedLen(rest.len, .{ .line_length = 0, .final_newline = false })) .q else .b, }; const take = switch (encoding) { .q => qFit(rest, limit), .b => bFit(rest, limit), }; if (!first) try w.writeAll(options.separator); try w.writeAll("=?"); try w.writeAll(options.charset); try w.writeByte('?'); try w.writeByte(encoding.letter()); try w.writeByte('?'); switch (encoding) { .q => try encodeQWriter(w, rest[0..take]), .b => try base64.encodeWriter(w, rest[0..take], .{ .line_length = 0, .final_newline = false, }), } try w.writeAll("?="); rest = rest[take..]; if (rest.len == 0) return; first = false; // Every word after the first begins a line of its own, so only the // separator's trailing whitespace is in front of it. budget_offset = options.separator.len - (std.mem.lastIndexOfScalar(u8, options.separator, '\n') orelse (options.separator.len - 1)) - 1; } } pub fn encodeAlloc(gpa: Allocator, text: []const u8, options: EncodeOptions) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); encodeWriter(&out.writer, text, options) catch return error.OutOfMemory; return out.toOwnedSlice(); } /// Whether `text` can be written into a header as itself. Anything that cannot /// — a byte outside ASCII, a control character, or text that would read back /// as an encoded word — has to be encoded. pub fn needsEncoding(text: []const u8) bool { for (text) |c| if (c >= 0x7f or c < 0x20) return true; return isEncoded(text); } /// Writes `text` as itself where that is possible and as encoded words where /// it is not, which is what a header writer wants for a value that is /// ordinarily ASCII and occasionally not. pub fn encodeIfNeededWriter( w: *Io.Writer, text: []const u8, options: EncodeOptions, ) Io.Writer.Error!void { if (!needsEncoding(text)) return w.writeAll(text); return encodeWriter(w, text, options); } /// The characters a `Q` word may carry as themselves. RFC 2047 §4.2 gives a /// wider set for some contexts than for others; this is the narrow one, which /// is valid in all of them, including inside a display name. fn qLiteral(c: u8) bool { return switch (c) { 'A'...'Z', 'a'...'z', '0'...'9' => true, '!', '*', '+', '-', '/' => true, else => false, }; } fn qLen(text: []const u8) usize { var len: usize = 0; for (text) |c| len += if (c == ' ' or qLiteral(c)) 1 else 3; return len; } fn encodeQWriter(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { const hex = "0123456789ABCDEF"; for (text) |c| { if (c == ' ') { try w.writeByte('_'); } else if (qLiteral(c)) { try w.writeByte(c); } else { try w.writeAll(&.{ '=', hex[c >> 4], hex[c & 0xf] }); } } } /// How many bytes of `text` fit in `limit` characters of `Q`, rounded down to /// a UTF-8 character boundary. fn qFit(text: []const u8, limit: usize) usize { var used: usize = 0; var i: usize = 0; while (i < text.len) { const c = text[i]; const cost: usize = if (c == ' ' or qLiteral(c)) 1 else 3; if (used + cost > limit) break; used += cost; i += 1; } if (i == 0) return @min(text.len, 1); // Make progress even in a silly budget. return backOffToBoundary(text, i); } /// How many bytes of `text` fit in `limit` characters of base64, rounded down /// to a UTF-8 character boundary. fn bFit(text: []const u8, limit: usize) usize { const groups = limit / 4; const bytes = @min(groups * 3, text.len); if (bytes == 0) return @min(text.len, 3); return backOffToBoundary(text, bytes); } /// Moves a split point back to the start of whatever UTF-8 character it landed /// inside. Each word is decoded on its own, so half a character in one of them /// is a byte sequence that no decoder can put back together. fn backOffToBoundary(text: []const u8, at: usize) usize { if (at >= text.len) return text.len; var i = at; while (i > 0 and isContinuation(text[i])) i -= 1; if (i == 0) return at; // Not UTF-8 at all; splitting anywhere is equally bad. return i; } fn isContinuation(c: u8) bool { return c & 0xc0 == 0x80; } test parse { const word = parse("=?UTF-8?Q?caf=C3=A9?= and more").?; try testing.expectEqualStrings("UTF-8", word.charset); try testing.expectEqual(null, word.language); try testing.expectEqual(Encoding.q, word.encoding); try testing.expectEqualStrings("caf=C3=A9", word.text); var buffer: [64]u8 = undefined; try testing.expectEqualStrings("café", word.decode(&buffer)); } test "a language tag is not part of the charset" { const word = parse("=?utf-8*en-gb?B?aGk=?=").?; try testing.expectEqualStrings("utf-8", word.charset); try testing.expectEqualStrings("en-gb", word.language.?); var buffer: [64]u8 = undefined; try testing.expectEqualStrings("hi", word.decode(&buffer)); } test "what is not a word" { try testing.expectEqual(null, parse("not encoded")); try testing.expectEqual(null, parse("=?utf-8?X?zz?=")); // Unknown encoding. try testing.expectEqual(null, parse("=??Q?x?=")); // Empty charset. try testing.expectEqual(null, parse("=?utf-8?Q?unterminated")); try testing.expectEqual(null, parse("=?utf 8?Q?x?=")); // Space in the charset. try testing.expectEqual(null, parse("=?utf-8?Q?a b?=")); // Space in the text. // A `?` a very long way off is not this word's terminator. try testing.expectEqual(null, parse("=?" ++ "x" ** 100 ++ "?Q?a?=")); } test "decoding a whole value" { const decoded = try decodeUtf8Alloc(testing.allocator, "=?UTF-8?Q?caf=C3=A9?= au lait"); defer testing.allocator.free(decoded); try testing.expectEqualStrings("café au lait", decoded); } test "whitespace between adjacent words is removed" { const decoded = try decodeUtf8Alloc( testing.allocator, "=?UTF-8?Q?caf?=\r\n =?UTF-8?Q?=C3=A9?=", ); defer testing.allocator.free(decoded); try testing.expectEqualStrings("café", decoded); } test "whitespace next to ordinary text is kept" { const decoded = try decodeUtf8Alloc(testing.allocator, "Re: =?UTF-8?Q?caf=C3=A9?= today"); defer testing.allocator.free(decoded); try testing.expectEqualStrings("Re: café today", decoded); } test "text that merely looks like a word is left alone" { for ([_][]const u8{ "look at =?this?= thing", "x=?UTF-8?Q?y?=", "=?UTF-8?Q?y?=x", }) |value| { const decoded = try decodeUtf8Alloc(testing.allocator, value); defer testing.allocator.free(decoded); try testing.expectEqualStrings(value, decoded); } } test "iso-8859-1 needs no table" { const decoded = try decodeUtf8Alloc(testing.allocator, "=?iso-8859-1?Q?caf=E9?="); defer testing.allocator.free(decoded); try testing.expectEqualStrings("café", decoded); } test "an unknown charset comes back as valid UTF-8" { const decoded = try decodeUtf8Alloc(testing.allocator, "=?shift_jis?B?gqCCog==?="); defer testing.allocator.free(decoded); try testing.expect(std.unicode.utf8ValidateSlice(decoded)); } test "encode and decode" { const text = "Grüße aus München — a subject long enough that it will not " ++ "fit into a single seventy-five character encoded word"; 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 <= max_length + 1); const decoded = try decodeUtf8Alloc(testing.allocator, encoded); defer testing.allocator.free(decoded); try testing.expectEqualStrings(text, decoded); } test "a word is never split in the middle of a character" { // Every character is three bytes, so the split points are the ones a // byte-counting encoder would get wrong. const text = "日本語" ** 20; for ([_]EncodeOptions{ .{ .encoding = .q }, .{ .encoding = .b }, .{} }) |options| { const encoded = try encodeAlloc(testing.allocator, text, options); defer testing.allocator.free(encoded); const decoded = try decodeUtf8Alloc(testing.allocator, encoded); defer testing.allocator.free(decoded); try testing.expectEqualStrings(text, decoded); } } test "auto picks the shorter encoding" { const mostly_ascii = try encodeAlloc(testing.allocator, "A subject with one é in it", .{}); defer testing.allocator.free(mostly_ascii); try testing.expect(std.mem.startsWith(u8, mostly_ascii, "=?UTF-8?Q?")); const mostly_not = try encodeAlloc(testing.allocator, "日本語日本語日本語", .{}); defer testing.allocator.free(mostly_not); try testing.expect(std.mem.startsWith(u8, mostly_not, "=?UTF-8?B?")); } test needsEncoding { try testing.expect(!needsEncoding("An ordinary subject")); try testing.expect(needsEncoding("café")); try testing.expect(needsEncoding("a\r\nb")); // Text that would read back as an encoded word has to be encoded, or it // does not read back as itself. try testing.expect(needsEncoding("=?utf-8?Q?x?=")); } test "encodeIfNeeded leaves ASCII alone" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try encodeIfNeededWriter(&out.writer, "Meeting at 3", .{}); try testing.expectEqualStrings("Meeting at 3", out.written()); } test "a header that is not UTF-8 and says nothing comes back as UTF-8" { // A sender whose locale was ISO-8859-15 puts its bytes straight into the // `Subject:` with no encoded word anywhere. The fast path used to hand // them back unchanged, which is not UTF-8 and is not what this function // promises. for ([_][]const u8{ "caf\xe9", "\xff\xfe\xfd", "a \xc3 truncated sequence", "Re: =?UTF-8?Q?caf=C3=A9?= and then \x80 raw", }) |value| { const decoded = try decodeUtf8Alloc(testing.allocator, value); defer testing.allocator.free(decoded); try testing.expect(std.unicode.utf8ValidateSlice(decoded)); } }