// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A `Content-Type`: `text/plain; charset=utf-8`. //! //! The type and subtype are lowercased on the way in, because they are //! case-insensitive and nothing is ever gained by remembering that a sender //! wrote `TEXT/PLAIN`. Parameter names are lowercased for the same reason; //! parameter *values* are not, since `boundary` and `filename` are both //! case-sensitive and one of them is load-bearing. //! //! The default matters as much as the parsing. A message with no //! `Content-Type` at all is `text/plain; charset=us-ascii` — RFC 2045 §5.2 — //! and a *part* of a `multipart/digest` with no `Content-Type` is //! `message/rfc822` instead. Getting that wrong turns a plain message into an //! unreadable one, so `default` and `defaultForDigest` are here rather than //! left to the caller to remember. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const parameter = @import("parameters.zig"); const lexer = @import("lexer.zig"); const MediaType = @This(); /// Lowercased. `text`, `multipart`, `application`, and so on. type: []const u8, /// Lowercased. `plain`, `mixed`, `octet-stream`. subtype: []const u8, parameters: parameter.Parameters, /// Backs `type` and `subtype`; `parameters` owns its own. bytes: []u8, /// What a message with no `Content-Type` header means. RFC 2045 §5.2. pub fn default(gpa: Allocator) Allocator.Error!MediaType { return parse(gpa, "text/plain; charset=us-ascii"); } /// What a part of a `multipart/digest` with no `Content-Type` means. /// RFC 2046 §5.1.5, and the one place the default is not `text/plain`. pub fn defaultForDigest(gpa: Allocator) Allocator.Error!MediaType { return parse(gpa, "message/rfc822"); } /// Parses a `Content-Type` value. /// /// A value with no `/` in it is not a media type, and rather than failing — /// which would leave the caller holding a message it cannot display — the /// subtype becomes empty, which `is` and `isText` handle and which `write` /// reproduces. A value with no type at all falls back to `text/plain`, since /// that is what a reader has to assume anyway. pub fn parse(gpa: Allocator, source: []const u8) Allocator.Error!MediaType { var scanner: lexer.Scanner = .init(source); const type_token = scanner.token() orelse "text"; var subtype_token: []const u8 = ""; if (scanner.eat('/')) subtype_token = scanner.token() orelse ""; if (subtype_token.len == 0 and std.ascii.eqlIgnoreCase(type_token, "text")) subtype_token = "plain"; const bytes = try gpa.alloc(u8, type_token.len + 1 + subtype_token.len); errdefer gpa.free(bytes); for (type_token, 0..) |c, i| bytes[i] = std.ascii.toLower(c); bytes[type_token.len] = '/'; for (subtype_token, 0..) |c, i| bytes[type_token.len + 1 + i] = std.ascii.toLower(c); var parsed: parameter.Parameters = try .parse(gpa, source); errdefer parsed.deinit(gpa); return .{ .type = bytes[0..type_token.len], .subtype = bytes[type_token.len + 1 ..], .parameters = parsed, .bytes = bytes, }; } pub fn deinit(self: *MediaType, gpa: Allocator) void { self.parameters.deinit(gpa); gpa.free(self.bytes); self.* = undefined; } /// Whether this is exactly `type/subtype`, compared case-insensitively. pub fn is(self: MediaType, type_name: []const u8, subtype_name: []const u8) bool { return std.ascii.eqlIgnoreCase(self.type, type_name) and std.ascii.eqlIgnoreCase(self.subtype, subtype_name); } /// Whether the top-level type is `type_name`. pub fn isType(self: MediaType, type_name: []const u8) bool { return std.ascii.eqlIgnoreCase(self.type, type_name); } /// Whether this entity has parts inside it, which is what decides whether the /// body is text or a structure. pub fn isMultipart(self: MediaType) bool { return self.isType("multipart"); } /// Whether the body is a whole message of its own — `message/rfc822`, and the /// `message/global` of RFC 6532. Not every `message/*` is: `message/partial` /// and `message/external-body` are not messages but references to them. pub fn isEncapsulatedMessage(self: MediaType) bool { if (!self.isType("message")) return false; return std.ascii.eqlIgnoreCase(self.subtype, "rfc822") or std.ascii.eqlIgnoreCase(self.subtype, "global") or std.ascii.eqlIgnoreCase(self.subtype, "news"); } /// Whether the body is text, and so wants its line endings canonicalised on /// the way out and its charset read on the way in. pub fn isText(self: MediaType) bool { return self.isType("text"); } /// The declared charset, or null. Absent means US-ASCII for a `text/*` body by /// RFC 2045 §5.2 — but a body that is not ASCII and does not say so is common /// enough that a caller is usually better off sniffing than assuming, which is /// why this reports the absence rather than papering over it. pub fn charset(self: MediaType) ?[]const u8 { return self.parameters.get("charset"); } /// The delimiter between the parts of a multipart body. A `multipart/*` /// without one is malformed and unparseable: there is nothing to split on. pub fn boundary(self: MediaType) ?[]const u8 { return self.parameters.get("boundary"); } /// Whether this is a `multipart/report` — RFC 6522 — the wrapper a mail /// system puts round a machine-readable report about a message: a bounce, a /// read receipt, a spam complaint. pub fn isReport(self: MediaType) bool { return self.is("multipart", "report"); } /// The `report-type` parameter: the subtype of the machine-readable part, and /// so what kind of report this is. `delivery-status` for a bounce, /// `disposition-notification` for a read receipt, `feedback-report` for a spam /// complaint. /// /// RFC 6522 §3 requires it, because a reader has to know what the second part /// will be before it looks at it. A `multipart/report` without one is /// malformed, and this reports the absence rather than guessing. pub fn reportType(self: MediaType) ?[]const u8 { if (!self.isReport()) return null; return self.parameters.get("report-type"); } /// Whether this is `text/plain; format=flowed` — RFC 3676, where a line /// ending in a space is a line that was wrapped and may be rewrapped. /// /// Only `text/plain` carries the parameter. A `format=flowed` on anything else /// is noise, and acting on it would join the lines of something that is not /// prose. pub fn isFlowed(self: MediaType) bool { if (!self.is("text", "plain")) return false; const declared = self.parameters.get("format") orelse return false; return std.ascii.eqlIgnoreCase(declared, "flowed"); } /// Whether `delsp=yes`: the trailing space of a wrapped line is only a marker /// and is deleted when the lines are joined, rather than being the space /// between two words. For scripts that do not separate their words. pub fn deleteSpace(self: MediaType) bool { const delsp = self.parameters.get("delsp") orelse return false; return std.ascii.eqlIgnoreCase(delsp, "yes"); } /// The suggested name of an attachment, as `Content-Type` spells it. /// `Content-Disposition`'s `filename` is the modern place for this and takes /// precedence; `name` is what software from before RFC 2183 wrote, and what /// some of it still writes. pub fn name(self: MediaType) ?[]const u8 { return self.parameters.get("name"); } pub fn write(self: MediaType, w: *Io.Writer, options: parameter.WriteOptions) Io.Writer.Error!void { try w.writeAll(self.type); if (self.subtype.len != 0) { try w.writeByte('/'); try w.writeAll(self.subtype); } try self.parameters.write(w, options); } /// For `{f}`. Writes the value the way `write` does with the default options. pub fn format(self: MediaType, w: *Io.Writer) Io.Writer.Error!void { return self.write(w, .{}); } test "the ordinary case" { var media: MediaType = try .parse(testing.allocator, "text/plain; charset=UTF-8"); defer media.deinit(testing.allocator); try testing.expectEqualStrings("text", media.type); try testing.expectEqualStrings("plain", media.subtype); try testing.expect(media.is("TEXT", "Plain")); try testing.expect(media.isText()); try testing.expect(!media.isMultipart()); try testing.expectEqualStrings("UTF-8", media.charset().?); } test "the type and subtype are lowercased and the boundary is not" { var media: MediaType = try .parse( testing.allocator, "Multipart/Mixed; Boundary=\"--=_NextPart_ABC\"", ); defer media.deinit(testing.allocator); try testing.expectEqualStrings("multipart", media.type); try testing.expectEqualStrings("mixed", media.subtype); try testing.expect(media.isMultipart()); try testing.expectEqualStrings("--=_NextPart_ABC", media.boundary().?); } test "a value with no subtype is still usable" { var media: MediaType = try .parse(testing.allocator, "text"); defer media.deinit(testing.allocator); try testing.expect(media.is("text", "plain")); var broken: MediaType = try .parse(testing.allocator, "octet-stream; name=x"); defer broken.deinit(testing.allocator); try testing.expectEqualStrings("octet-stream", broken.type); try testing.expectEqualStrings("", broken.subtype); try testing.expectEqualStrings("x", broken.name().?); } test "a report says what kind of report it is" { var bounce: MediaType = try .parse( testing.allocator, "multipart/report; report-type=delivery-status; boundary=B", ); defer bounce.deinit(testing.allocator); try testing.expect(bounce.isReport()); try testing.expectEqualStrings("delivery-status", bounce.reportType().?); // The parameter is required, and its absence is reported rather than // guessed at. var bare: MediaType = try .parse(testing.allocator, "multipart/report; boundary=B"); defer bare.deinit(testing.allocator); try testing.expect(bare.isReport()); try testing.expectEqual(null, bare.reportType()); var mixed: MediaType = try .parse(testing.allocator, "multipart/mixed; report-type=x"); defer mixed.deinit(testing.allocator); try testing.expect(!mixed.isReport()); try testing.expectEqual(null, mixed.reportType()); } test "format=flowed is read only where it means something" { var plain: MediaType = try .parse(testing.allocator, "text/plain; format=Flowed; delsp=YES"); defer plain.deinit(testing.allocator); try testing.expect(plain.isFlowed()); try testing.expect(plain.deleteSpace()); var fixed: MediaType = try .parse(testing.allocator, "text/plain; charset=utf-8"); defer fixed.deinit(testing.allocator); try testing.expect(!fixed.isFlowed()); try testing.expect(!fixed.deleteSpace()); // The parameter belongs to text/plain and to nothing else. var html: MediaType = try .parse(testing.allocator, "text/html; format=flowed"); defer html.deinit(testing.allocator); try testing.expect(!html.isFlowed()); } test "the defaults" { var plain: MediaType = try .default(testing.allocator); defer plain.deinit(testing.allocator); try testing.expect(plain.is("text", "plain")); try testing.expectEqualStrings("us-ascii", plain.charset().?); var digest: MediaType = try .defaultForDigest(testing.allocator); defer digest.deinit(testing.allocator); try testing.expect(digest.isEncapsulatedMessage()); } test "writing a media type" { var media: MediaType = try .parse( testing.allocator, "multipart/mixed; boundary=\"a boundary\"", ); defer media.deinit(testing.allocator); var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try out.writer.print("{f}", .{media}); try testing.expectEqualStrings( "multipart/mixed;\r\n boundary=\"a boundary\"", out.written(), ); }