Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The `; name=value` tail of a `Content-Type` or `Content-Disposition`, and//! the two ways it was extended to carry a filename that is neither short nor//! ASCII.//!//! RFC 2045 gave parameters a value that is a token or a quoted-string, both//! of which are ASCII and neither of which may be folded. RFC 2231 then added//! two things on top, which combine://!//! * **Continuations.** `name*0="first"; name*1="second"` is one parameter//! whose value is the concatenation, so a long filename can be spread over//! as many lines as it needs.//! * **An extended value.** A `*` on the end of the name means the value is//! `charset'language'text`, with the text percent-encoded — so//! `filename*=UTF-8''caf%C3%A9.txt` names a file whose name is not ASCII,//! and says what charset the bytes are in.//!//! And then there is what mail actually contains. A great deal of software//! ignored RFC 2231 and put an RFC 2047 encoded word inside an ordinary quoted//! parameter instead — `filename="=?UTF-8?B?Y2Fmw6kudHh0?="` — which is//! forbidden by both specifications and is, all the same, how a large share of//! non-ASCII attachment names arrive. The parser here accepts it, because the//! alternative is showing the user the encoded word; the writer never produces//! it.//!//! Values come back as bytes with the charset named, as everywhere else in//! this library. `Parameters.getUtf8` is the convenience that applies the same//! table-free rule as `encoded_word.decodeUtf8Alloc`.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
const charset_module = @import("../charset.zig");const encoded_word = @import("../codec/encoded_word.zig");const lexer = @import("lexer.zig");
/// One `name=value` exactly as it was written, with no continuations joined/// and no percent-decoding done.pub const Raw = struct { /// The name with any `*N` section number and trailing `*` removed. name: []const u8, /// The `N` of `name*N`, or null if the parameter was not split. section: ?u32, /// Whether the name ended in `*`, making the value a `charset'lang'text` /// for the first section and percent-encoded text for the rest. extended: bool, /// The value with its quotes removed if it had them, and with backslash /// escapes still in place. value: []const u8, /// Whether `value` came out of a quoted-string, and so may contain /// escapes. quoted: bool,};
/// Walks the parameters of a header value without allocating, yielding each/// one as it was written. `Parameters.parse` is what puts the pieces back/// together; this is for a caller that wants a single simple parameter — a/// `charset` or a `boundary` — out of a value it already has.pub const Iterator = struct { scanner: lexer.Scanner,
pub fn init(source: []const u8) Iterator { return .{ .scanner = .init(source) }; }
pub fn next(self: *Iterator) ?Raw { // Find the `;` that starts the next parameter, skipping anything left // over from a malformed one rather than giving up on the rest. while (true) { self.scanner.skipCfws(); if (self.scanner.atEnd()) return null; if (self.scanner.eat(';')) break; // Not a separator: step over whatever this is. A value like // `text/plain, charset=utf-8` is not legal and is not rare. _ = self.scanner.quotedString() orelse { self.scanner.index += 1; continue; }; } self.scanner.skipCfws(); const raw_name = self.scanner.token() orelse return self.next();
// The name is taken apart before looking for a value, so that a // parameter with none is named the way it would be with one: a bare // `filename*` is `filename`, not a parameter whose name ends in the // RFC 2231 marker, which no writer could put back. var name = raw_name; var extended = false; var section: ?u32 = null; if (std.mem.endsWith(u8, name, "*")) { extended = true; name = name[0 .. name.len - 1]; } if (std.mem.findScalarLast(u8, name, '*')) |star| { if (std.fmt.parseInt(u32, name[star + 1 ..], 10)) |n| { section = n; name = name[0..star]; } else |_| {} }
self.scanner.skipCfws(); if (!self.scanner.eat('=')) { // A parameter with no value. Some senders write `; multipart` and // mean nothing by it. return .{ .name = name, .section = section, .extended = extended, .value = "", .quoted = false }; } self.scanner.skipCfws();
var quoted = false; const value = if (self.scanner.quotedString()) |q| blk: { quoted = true; break :blk q; } else self.scanner.token() orelse "";
return .{ .name = name, .section = section, .extended = extended, .value = value, .quoted = quoted, }; }};
/// A parameter with its continuations joined and its percent-encoding undone.pub const Parameter = struct { /// Lowercased, since parameter names are case-insensitive and comparing /// them is the only thing anybody does with them. name: []const u8, /// The bytes of the value, in `charset`. value: []const u8, /// The charset the extended form declared, or null when the value came /// from an ordinary token or quoted-string — which the grammar says is /// US-ASCII and which is in practice whatever the sender's locale was. charset: ?[]const u8 = null, language: ?[]const u8 = null,};
/// The parameters of one header value, owned.pub const Parameters = struct { list: []Parameter = &.{}, /// One allocation holding every name, value, charset and language, which /// the slices in `list` point into. Parameters are read far more often /// than they are built, and this way freeing them is two calls whatever /// their number. bytes: []u8 = &.{},
pub const empty: Parameters = .{};
pub fn deinit(self: *Parameters, gpa: Allocator) void { gpa.free(self.list); gpa.free(self.bytes); self.* = .empty; }
/// Parses the `; name=value` tail of `source`. Everything before the first /// `;` is ignored, so a whole `Content-Type` value may be passed in. pub fn parse(gpa: Allocator, source: []const u8) Allocator.Error!Parameters { var pieces: std.ArrayList(Raw) = .empty; defer pieces.deinit(gpa);
var it: Iterator = .init(source); while (it.next()) |raw| try pieces.append(gpa, raw); if (pieces.items.len == 0) return .empty;
var list: std.ArrayList(Parameter) = .empty; errdefer list.deinit(gpa); var bytes: Io.Writer.Allocating = .init(gpa); errdefer bytes.deinit();
// Offsets rather than slices, because the buffer moves as it grows. const Span = struct { start: usize, len: usize }; var spans: std.ArrayList(struct { name: Span, value: Span, charset: ?Span, language: ?Span, }) = .empty; defer spans.deinit(gpa);
var done: std.ArrayList([]const u8) = .empty; defer done.deinit(gpa);
for (pieces.items) |piece| { // A name that was nothing but the RFC 2231 markers -- `*`, `*0*` -- // names nothing, and one with a `*` left in it once they are taken // off -- `name**` -- is not a name RFC 2231 allows, since // `attribute-char` excludes it. Neither can be written back out // and read as itself, so neither is kept. if (piece.name.len == 0 or std.mem.findScalar(u8, piece.name, '*') != null) continue; // Each name is assembled once, from every piece that carries it. var seen = false; for (done.items) |name| { if (std.ascii.eqlIgnoreCase(name, piece.name)) seen = true; } if (seen) continue; try done.append(gpa, piece.name);
const name_start = bytes.written().len; for (piece.name) |c| bytes.writer.writeByte(std.ascii.toLower(c)) catch return error.OutOfMemory; const name_span: Span = .{ .start = name_start, .len = piece.name.len };
var charset_span: ?Span = null; var language_span: ?Span = null; const value_start = bytes.written().len;
// Sections in order. A missing section is a hole, and stopping at // it is what keeps a truncated header from splicing two halves of // a filename together. var section: u32 = 0; var any = false; while (true) : (section += 1) { const part = find(pieces.items, piece.name, section) orelse break; any = true; if (part.extended and section == 0) { // `charset'language'text`, and the charset is only on the // first section. var rest = part.value; if (std.mem.findScalar(u8, rest, '\'')) |first_quote| { const charset_text = rest[0..first_quote]; rest = rest[first_quote + 1 ..]; var language_text: []const u8 = ""; if (std.mem.findScalar(u8, rest, '\'')) |second_quote| { language_text = rest[0..second_quote]; rest = rest[second_quote + 1 ..]; } if (charset_text.len != 0) { const start = bytes.written().len; bytes.writer.writeAll(charset_text) catch return error.OutOfMemory; charset_span = .{ .start = start, .len = charset_text.len }; } if (language_text.len != 0) { const start = bytes.written().len; bytes.writer.writeAll(language_text) catch return error.OutOfMemory; language_span = .{ .start = start, .len = language_text.len }; } // The charset and language went into the buffer before // the value did, so the value begins after them. percentDecode(&bytes.writer, rest) catch return error.OutOfMemory; } else { percentDecode(&bytes.writer, part.value) catch return error.OutOfMemory; } } else if (part.extended) { percentDecode(&bytes.writer, part.value) catch return error.OutOfMemory; } else if (part.quoted) { lexer.unquoteWriter(&bytes.writer, part.value) catch return error.OutOfMemory; } else { bytes.writer.writeAll(part.value) catch return error.OutOfMemory; } // A parameter written without a section number is the whole of // its value; there is no section 1 to look for. if (part.section == null) break; } if (!any) continue;
// The charset and language were written into the middle of what // would otherwise be the value, so the value's span has to skip // them. var value_span: Span = .{ .start = value_start, .len = bytes.written().len - value_start }; if (charset_span) |c| value_span = .{ .start = c.start + c.len, .len = bytes.written().len - (c.start + c.len) }; if (language_span) |l| value_span = .{ .start = l.start + l.len, .len = bytes.written().len - (l.start + l.len) };
try spans.append(gpa, .{ .name = name_span, .value = value_span, .charset = charset_span, .language = language_span, }); }
const owned = bytes.toOwnedSlice() catch return error.OutOfMemory; errdefer gpa.free(owned); try list.ensureTotalCapacityPrecise(gpa, spans.items.len); for (spans.items) |span| list.appendAssumeCapacity(.{ .name = owned[span.name.start..][0..span.name.len], .value = owned[span.value.start..][0..span.value.len], .charset = if (span.charset) |c| owned[c.start..][0..c.len] else null, .language = if (span.language) |l| owned[l.start..][0..l.len] else null, }); return .{ .list = try list.toOwnedSlice(gpa), .bytes = owned }; }
fn find(pieces: []const Raw, name: []const u8, section: u32) ?Raw { for (pieces) |piece| { if (!std.ascii.eqlIgnoreCase(piece.name, name)) continue; if (section == 0 and piece.section == null) return piece; if (piece.section == section) return piece; } return null; }
/// The value of `name`, compared case-insensitively, or null. pub fn get(self: Parameters, name: []const u8) ?[]const u8 { const parameter = self.getParameter(name) orelse return null; return parameter.value; }
pub fn getParameter(self: Parameters, name: []const u8) ?Parameter { for (self.list) |parameter| { if (std.ascii.eqlIgnoreCase(parameter.name, name)) return parameter; } return null; }
/// The value of `name` as UTF-8, undoing an RFC 2047 encoded word if some /// sender put one where the grammar does not allow one. Caller owns the /// result; null if there is no such parameter. pub fn getUtf8Alloc(self: Parameters, gpa: Allocator, name: []const u8) Allocator.Error!?[]u8 { const parameter = self.getParameter(name) orelse return null; if (parameter.charset) |declared| { // An extended value says what it is, so it converts the same way // an encoded word's contents do. return try charset_module.toUtf8Alloc(gpa, parameter.value, declared); } return try encoded_word.decodeUtf8Alloc(gpa, parameter.value); }
/// Writes the parameters back out, each as `; name=value`, choosing the /// narrowest form that holds the value. pub fn write(self: Parameters, w: *Io.Writer, options: WriteOptions) Io.Writer.Error!void { for (self.list) |parameter| { try writeParameter(w, parameter.name, parameter.value, options); } }};
pub const WriteOptions = struct { /// The charset named in an extended value. As everywhere else, this does /// not transcode: the bytes must already be in it. charset: []const u8 = "UTF-8", /// The longest `name=value` this will write before splitting it into /// continuations. Zero never splits. max_length: usize = 60,};
/// Writes one `; name=value`, as a token where the value is one, as a/// quoted-string where it is printable ASCII, and as RFC 2231 continuations/// where it is neither.pub fn writeParameter( w: *Io.Writer, name: []const u8, value: []const u8, options: WriteOptions,) Io.Writer.Error!void { if (!needsExtended(value)) { const plain_len = name.len + 1 + value.len + 2; if (options.max_length == 0 or plain_len <= options.max_length) { try w.writeAll(";\r\n "); try w.writeAll(name); try w.writeByte('='); try lexer.quoteWriter(w, value, .token); return; } } try writeExtended(w, name, value, options);}
/// Whether a value has to go out in the RFC 2231 extended form, which is the/// case exactly when it is not printable ASCII.fn needsExtended(value: []const u8) bool { for (value) |c| if (c < 0x20 or c >= 0x7f) return true; return false;}
fn writeExtended( w: *Io.Writer, name: []const u8, value: []const u8, options: WriteOptions,) Io.Writer.Error!void { const extended = needsExtended(value); // The first section carries `charset''`, which costs room that the others // have for content. const prefix_len = if (extended) options.charset.len + 2 else 0; var rest = value; var section: u32 = 0; while (true) : (section += 1) { var budget: usize = if (options.max_length == 0) std.math.maxInt(usize) else options.max_length -| (name.len + 8 + if (section == 0) prefix_len else 0); if (budget < 3) budget = 3;
const take = if (extended) percentFit(rest, budget) else plainFit(rest, budget);
// A value that fits in one section is written without a section // number at all -- `filename*=UTF-8''...` rather than `filename*0*=`. // Both are RFC 2231, and the unnumbered form is the one that older // software recognises, since the numbering was added for // continuations and plenty of readers only ever learned the simple // case. const only_section = section == 0 and take == rest.len; try w.writeAll(";\r\n "); try w.writeAll(name); if (!only_section) try w.print("*{d}", .{section}); if (extended) try w.writeByte('*'); try w.writeByte('='); if (extended) { if (section == 0) { try w.writeAll(options.charset); try w.writeAll("''"); } try percentEncode(w, rest[0..take]); } else { try lexer.quoteWriter(w, rest[0..take], .token); } rest = rest[take..]; if (rest.len == 0) return; }}
/// The characters RFC 2231 calls `attribute-char`: a token character that is/// not `*`, `'` or `%`, each of which means something in an extended value.fn isAttributeChar(c: u8) bool { // ASCII only, unlike `isTokenChar`, which admits eight-bit bytes so that // reading a malformed header still finds the tokens in it. An extended // value exists precisely to spell those bytes out, so writing one raw // would defeat the form. return c < 0x80 and lexer.isTokenChar(c) and c != '*' and c != '\'' and c != '%';}
fn percentEncode(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { const hex = "0123456789ABCDEF"; for (text) |c| { if (isAttributeChar(c)) { try w.writeByte(c); } else { try w.writeAll(&.{ '%', hex[c >> 4], hex[c & 0xf] }); } }}
fn percentDecode(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { var i: usize = 0; while (i < text.len) { if (text[i] == '%' and i + 2 < text.len) { const high = hexDigit(text[i + 1]); const low = hexDigit(text[i + 2]); if (high != null and low != null) { try w.writeByte(high.? << 4 | low.?); i += 3; continue; } } try w.writeByte(text[i]); i += 1; }}
fn hexDigit(c: u8) ?u8 { return switch (c) { '0'...'9' => c - '0', 'A'...'F' => c - 'A' + 10, 'a'...'f' => c - 'a' + 10, else => null, };}
/// How many bytes fit in `budget` characters of percent-encoding, without/// splitting a UTF-8 character: a section is decoded with the others, but a/// reader that stops early should still see whole characters.fn percentFit(text: []const u8, budget: usize) usize { var used: usize = 0; var i: usize = 0; while (i < text.len) : (i += 1) { const cost: usize = if (isAttributeChar(text[i])) 1 else 3; if (used + cost > budget) break; used += cost; } if (i == 0) return @min(text.len, 1); while (i > 0 and i < text.len and text[i] & 0xc0 == 0x80) i -= 1; return if (i == 0) @min(text.len, 1) else i;}
fn plainFit(text: []const u8, budget: usize) usize { return @min(text.len, budget);}
test "an ordinary parameter" { var parameters: Parameters = try .parse(testing.allocator, "text/plain; charset=utf-8; format=flowed"); defer parameters.deinit(testing.allocator); try testing.expectEqualStrings("utf-8", parameters.get("charset").?); try testing.expectEqualStrings("flowed", parameters.get("FORMAT").?); try testing.expectEqual(null, parameters.get("name"));}
test "a quoted parameter keeps what the quotes protected" { var parameters: Parameters = try .parse( testing.allocator, "application/octet-stream; name=\"a file; with a semicolon.txt\"", ); defer parameters.deinit(testing.allocator); try testing.expectEqualStrings("a file; with a semicolon.txt", parameters.get("name").?);}
test "continuations are joined" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*0=\"a very long \"; filename*1=\"file name.txt\"", ); defer parameters.deinit(testing.allocator); try testing.expectEqualStrings("a very long file name.txt", parameters.get("filename").?);}
test "an extended value carries its charset" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*=UTF-8'en'caf%C3%A9.txt", ); defer parameters.deinit(testing.allocator); const parameter = parameters.getParameter("filename").?; try testing.expectEqualStrings("café.txt", parameter.value); try testing.expectEqualStrings("UTF-8", parameter.charset.?); try testing.expectEqualStrings("en", parameter.language.?);}
test "an extended value in continuations" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*0*=UTF-8''caf%C3%A9%20; filename*1*=au%20lait.txt", ); defer parameters.deinit(testing.allocator); const parameter = parameters.getParameter("filename").?; try testing.expectEqualStrings("café au lait.txt", parameter.value); try testing.expectEqualStrings("UTF-8", parameter.charset.?);}
test "an encoded word where the grammar does not allow one" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename=\"=?UTF-8?B?Y2Fmw6kudHh0?=\"", ); defer parameters.deinit(testing.allocator); const utf8 = (try parameters.getUtf8Alloc(testing.allocator, "filename")).?; defer testing.allocator.free(utf8); try testing.expectEqualStrings("café.txt", utf8);}
test "an extended value converted to UTF-8" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*=iso-8859-1''caf%E9.txt", ); defer parameters.deinit(testing.allocator); const utf8 = (try parameters.getUtf8Alloc(testing.allocator, "filename")).?; defer testing.allocator.free(utf8); try testing.expectEqualStrings("café.txt", utf8);}
test "a missing section stops the value rather than splicing it" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*0=\"first\"; filename*2=\"third\"", ); defer parameters.deinit(testing.allocator); try testing.expectEqualStrings("first", parameters.get("filename").?);}
test "a parameter with no value is named as if it had one" { // The bare `filename*` is a second piece of the same parameter rather than // a parameter of its own whose name ends in a `*`. var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*0*=UTF-8''a%20; filename*; size", ); defer parameters.deinit(testing.allocator); try testing.expectEqual(2, parameters.list.len); try testing.expectEqualStrings("filename", parameters.list[0].name); try testing.expectEqualStrings("a ", parameters.list[0].value); try testing.expectEqualStrings("size", parameters.list[1].name);}
test "a name that is only RFC 2231 markers, or keeps a star, is dropped" { var parameters: Parameters = try .parse( testing.allocator, "text/plain; *=x; *0*=y; name**=z; charset=utf-8", ); defer parameters.deinit(testing.allocator); try testing.expectEqual(1, parameters.list.len); try testing.expectEqualStrings("utf-8", parameters.get("charset").?);}
test "writing a parameter picks the narrowest form" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit();
try writeParameter(&out.writer, "charset", "utf-8", .{}); try testing.expectEqualStrings(";\r\n charset=utf-8", out.written());
out.clearRetainingCapacity(); try writeParameter(&out.writer, "name", "two words.txt", .{}); try testing.expectEqualStrings(";\r\n name=\"two words.txt\"", out.written());
out.clearRetainingCapacity(); try writeParameter(&out.writer, "filename", "café.txt", .{}); try testing.expectEqualStrings(";\r\n filename*=UTF-8''caf%C3%A9.txt", out.written());
// Long enough to need continuations, and then the sections are numbered. out.clearRetainingCapacity(); try writeParameter(&out.writer, "filename", "café " ** 20 ++ ".txt", .{}); try testing.expect(std.mem.find(u8, out.written(), "filename*0*=UTF-8''") != null); try testing.expect(std.mem.find(u8, out.written(), "filename*1*=") != null);}
test "a written parameter reads back" { const names = [_][]const u8{ "short.txt", "a name with spaces and a ; in it.txt", "café au lait.txt", "日本語のファイル名がとても長い場合はどうなるでしょうか.txt", "x" ** 300, }; for (names) |name| { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try out.writer.writeAll("attachment"); try writeParameter(&out.writer, "filename", name, .{});
var parameters: Parameters = try .parse(testing.allocator, out.written()); defer parameters.deinit(testing.allocator); try testing.expectEqualStrings(name, parameters.get("filename").?); }}