// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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. // // A name written both ways -- `filename="cafe.pdf"` beside // `filename*=utf-8''caf%C3%A9.pdf`, which is what Django sends and // a good deal of mail software writes -- is read from the RFC 2231 // pieces, whichever order they came in. The plain one is the // fallback for a reader that knows nothing better, and is usually // the same name with what ASCII could not hold taken out. RFC 2231 // is silent on it; RFC 6266 section 4.3 says to prefer the // extended form. var rfc2231 = false; for (pieces.items) |other| { if (!std.ascii.eqlIgnoreCase(other.name, piece.name)) continue; if (other.extended or other.section != null) rfc2231 = true; } var section: u32 = 0; var any = false; while (true) : (section += 1) { const part = find(pieces.items, piece.name, section, rfc2231) 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 }; } /// The piece of `name` holding `section`, an unnumbered piece counting as /// section 0. With `rfc2231` set, a plain unnumbered piece is passed over /// in favor of the extended or numbered ones. fn find(pieces: []const Raw, name: []const u8, section: u32, rfc2231: bool) ?Raw { for (pieces) |piece| { if (!std.ascii.eqlIgnoreCase(piece.name, name)) continue; if (rfc2231 and !piece.extended and piece.section == null) 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 "an extended value wins over a plain one written after it" { var parameters: Parameters = try .parse( testing.allocator, "attachment; filename*=utf-8''caf%C3%A9.pdf; filename=\"caf.pdf\"", ); defer parameters.deinit(testing.allocator); try testing.expectEqual(1, parameters.list.len); const utf8 = (try parameters.getUtf8Alloc(testing.allocator, "filename")).?; defer testing.allocator.free(utf8); try testing.expectEqualStrings("café.pdf", utf8); } test "an extended value wins over a plain one written before it" { // What Django sends for a download whose name is not ASCII: the plain // form first, with what ASCII could not hold dropped from it. var parameters: Parameters = try .parse( testing.allocator, "attachment; filename=\"caf.pdf\"; filename*=utf-8''caf%C3%A9.pdf", ); defer parameters.deinit(testing.allocator); try testing.expectEqual(1, parameters.list.len); const parameter = parameters.getParameter("filename").?; try testing.expectEqualStrings("utf-8", parameter.charset.?); const utf8 = (try parameters.getUtf8Alloc(testing.allocator, "filename")).?; defer testing.allocator.free(utf8); try testing.expectEqualStrings("café.pdf", utf8); } test "continuations win over a plain value" { var parameters: Parameters = try .parse( testing.allocator, "attachment; FILENAME=\"cafe au lait.txt\"; filename*0*=UTF-8''caf%C3%A9%20; filename*1*=au%20lait.txt", ); defer parameters.deinit(testing.allocator); try testing.expectEqual(1, parameters.list.len); const parameter = parameters.getParameter("filename").?; try testing.expectEqualStrings("café au lait.txt", parameter.value); try testing.expectEqualStrings("UTF-8", parameter.charset.?); } 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", std.mem.asBytes(&@as([20][6]u8, @splat("café ".*))) ++ ".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", &@as([300]u8, @splat('x')), }; 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").?); } }