// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Header lines: how a value that is longer than a line is written on several //! of them, and how it is put back together. //! //! RFC 5322 §2.2.3 calls it *folding*. A line ending followed by a space or a //! tab is not a line ending: the header continues, and unfolding removes the //! CRLF and keeps the whitespace. That is the whole mechanism, and it is why //! every parser above this one is written against a value that has already //! been unfolded — a `To:` line broken across four lines is one value, and a //! parser that sees the breaks has to handle them everywhere instead of here. //! //! Two lengths matter. A line **must not** exceed 998 characters plus the //! CRLF, which is a hard limit that a transport is entitled to enforce by //! mangling the message; it **should not** exceed 78, which is a courtesy to //! whoever reads the source. The folder aims at 78 and gives up gracefully: //! a single unfoldable token longer than that — a long URL in a //! `Message-ID`, a base64 DKIM signature — goes out over-length rather than //! being broken, because breaking it would change it. //! //! ## Injection //! //! A header value that contains a bare CR or LF is how a program that //! interpolates user input into a header is turned into a program that sends //! whatever headers an attacker likes — a `Subject` ending in //! `\r\nBcc: everyone` adds a recipient. Everything here that writes a value //! strips bare CR and LF. It is not a configurable strictness: there is no //! legitimate value that contains one, so nothing is lost, and the failure //! mode of getting it wrong is not a malformed message but a security hole. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const lexer = @import("lexer.zig"); /// RFC 5322 §2.1.1. The hard limit, not counting the CRLF. pub const max_line_length = 998; /// RFC 5322 §2.1.1. What a line should not exceed. pub const preferred_line_length = 78; /// Whether a field name is one: printable ASCII other than `:`, which is what /// would otherwise end it. RFC 5322 §3.6.8. pub fn isValidName(name: []const u8) bool { if (name.len == 0) return false; for (name) |c| if (c < 33 or c > 126 or c == ':') return false; return true; } /// Splits `Name: value` at the first colon. Null if there is no colon, which /// is what a continuation line handed here on its own looks like, and what the /// `From ` line at the top of an mbox message looks like. /// /// The value keeps its leading space: it is optional in the grammar, and a /// caller comparing values wants it gone, so `trimValue` is a separate step /// rather than a silent one. pub fn split(line: []const u8) ?struct { name: []const u8, value: []const u8 } { const colon = std.mem.findScalar(u8, line, ':') orelse return null; const name = line[0..colon]; // A space before the colon is a defect that RFC 5322 does not allow and // that some senders produce. Trimming it makes the name usable; keeping // the field is better than dropping it. const trimmed = std.mem.trimEnd(u8, name, " \t"); if (!isValidName(trimmed)) return null; return .{ .name = trimmed, .value = line[colon + 1 ..] }; } /// Removes the whitespace around a value, which is what every parser above /// wants and what no parser should have to remember to do. pub fn trimValue(value: []const u8) []const u8 { return std.mem.trim(u8, value, " \t\r\n"); } /// Whether `value` contains a fold, and so needs unfolding before it is /// parsed. Nearly all values do not, and the ones that do not can be parsed /// out of the message buffer without a copy. pub fn isFolded(value: []const u8) bool { return std.mem.findScalar(u8, value, '\n') != null or std.mem.findScalar(u8, value, '\r') != null; } /// Writes `value` with its folds removed: a CRLF, CR or LF that is followed by /// a space or a tab disappears and the whitespace stays. /// /// A line ending that is *not* followed by whitespace is not a fold. It should /// not be in a value at all, and it is replaced by a space rather than kept, /// so that nothing downstream can be tricked into treating what follows as a /// new header. pub fn unfoldWriter(w: *Io.Writer, value: []const u8) Io.Writer.Error!void { var i: usize = 0; var start: usize = 0; while (i < value.len) { const c = value[i]; if (c != '\r' and c != '\n') { i += 1; continue; } try w.writeAll(value[start..i]); var end = i + 1; if (c == '\r' and end < value.len and value[end] == '\n') end += 1; if (end < value.len and lexer.isWsp(value[end])) { // A fold: drop the line ending and keep the whitespace that // continued the line. } else { try w.writeByte(' '); } i = end; start = end; } try w.writeAll(value[start..]); } pub fn unfoldAlloc(gpa: Allocator, value: []const u8) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); unfoldWriter(&out.writer, value) catch return error.OutOfMemory; return out.toOwnedSlice(); } pub const FoldOptions = struct { /// The column to aim for. Lines still run over it when there is nowhere to /// break. width: usize = preferred_line_length, /// How many columns are already used on the first line — the `Subject: ` /// that the caller is about to write, or has just written. first_line_used: usize = 0, }; /// Writes a value, folding it at whitespace so that no line is longer than it /// has to be. /// /// Folds already present in `value` are honoured and reset the column, which /// is what makes it safe to hand this something an address or parameter writer /// has already broken up. Bare line endings are stripped; see the module /// comment. pub fn foldWriter(w: *Io.Writer, value: []const u8, options: FoldOptions) Io.Writer.Error!void { var column = options.first_line_used; var i: usize = 0; while (i < value.len) { // An existing fold: pass it through and start a new line. if (value[i] == '\r' or value[i] == '\n') { var end = i + 1; if (value[i] == '\r' and end < value.len and value[end] == '\n') end += 1; if (end < value.len and lexer.isWsp(value[end])) { try w.writeAll("\r\n"); try w.writeByte(value[end]); column = 1; i = end + 1; continue; } // Not a fold, and so not allowed to reach the output at all. i = end; continue; } if (lexer.isWsp(value[i])) { // A break opportunity. Measure the word that follows it and // decide whether it fits on this line. var run_end = i; while (run_end < value.len and lexer.isWsp(value[run_end])) run_end += 1; var word_end = run_end; while (word_end < value.len and !lexer.isWsp(value[word_end]) and value[word_end] != '\r' and value[word_end] != '\n') word_end += 1; // Folding *inserts* a line ending before whitespace that is // already there; it does not replace it. RFC 5322 §2.2.3 unfolds // by removing the CRLF and keeping the WSP, so a fold that wrote // a space where the value had a tab -- or one space where it had // three -- would come back from the unfolder as a different // value. Whitespace is content in a quoted string, and this // library's whole claim is that what goes in comes out. const run_len = run_end - i; const word_len = word_end - run_end; if (word_len != 0 and column + run_len + word_len > options.width) { try w.writeAll("\r\n"); column = 0; } try w.writeAll(value[i..run_end]); column += run_len; try w.writeAll(value[run_end..word_end]); column += word_len; i = word_end; continue; } // The first word of the value, which has no whitespace before it to // break at. var word_end = i; while (word_end < value.len and !lexer.isWsp(value[word_end]) and value[word_end] != '\r' and value[word_end] != '\n') word_end += 1; try w.writeAll(value[i..word_end]); column += word_end - i; i = word_end; } } /// Writes a whole header line: `Name: value`, folded, with the CRLF at the /// end. pub fn writeField( w: *Io.Writer, name: []const u8, value: []const u8, options: FoldOptions, ) Io.Writer.Error!void { try w.writeAll(name); try w.writeAll(": "); var folding = options; folding.first_line_used = name.len + 2; try foldWriter(w, trimValue(value), folding); try w.writeAll("\r\n"); } /// Folds a value the way `writeField` would, without the name or the CRLF. /// This is what `Headers` stores, so that writing a message is a copy. pub fn foldAlloc( gpa: Allocator, name: []const u8, value: []const u8, options: FoldOptions, ) Allocator.Error![]u8 { var out: Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); var folding = options; folding.first_line_used = name.len + 2; foldWriter(&out.writer, trimValue(value), folding) catch return error.OutOfMemory; return out.toOwnedSlice(); } test split { const field = split("Subject: hello").?; try testing.expectEqualStrings("Subject", field.name); try testing.expectEqualStrings(" hello", field.value); try testing.expectEqualStrings("hello", trimValue(field.value)); // A space before the colon, which is a defect and is not rare. try testing.expectEqualStrings("Subject", split("Subject : hello").?.name); try testing.expectEqual(null, split("From nobody Mon Jan 1 00:00:00 2001")); try testing.expectEqual(null, split(" a continuation line")); try testing.expectEqual(null, split(": no name")); } test unfoldWriter { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try unfoldWriter(&out.writer, " a\r\n b\r\n\tc"); try testing.expectEqualStrings(" a b\tc", out.written()); // A bare line ending is not a fold and must not survive as one. out.clearRetainingCapacity(); try unfoldWriter(&out.writer, "hello\r\nBcc: victim@example.com"); try testing.expectEqualStrings("hello Bcc: victim@example.com", out.written()); } test "folding a long value" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const value = "one two three four five six seven eight nine ten " ++ "eleven twelve thirteen fourteen fifteen sixteen seventeen"; try writeField(&out.writer, "Subject", value, .{}); var lines = std.mem.splitSequence(u8, out.written(), "\r\n"); var count: usize = 0; while (lines.next()) |line| { try testing.expect(line.len <= preferred_line_length); count += 1; } try testing.expect(count > 2); // And it unfolds back to what went in. const field = split(out.written()).?; const unfolded = try unfoldAlloc(testing.allocator, trimValue(field.value)); defer testing.allocator.free(unfolded); try testing.expectEqualStrings(value, unfolded); } test "a word that cannot be broken goes out long" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const value = "<" ++ "x" ** 200 ++ "@example.com>"; try writeField(&out.writer, "Message-ID", value, .{}); try testing.expectEqualStrings("Message-ID: " ++ value ++ "\r\n", out.written()); } test "an existing fold is honoured" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try writeField(&out.writer, "To", "a@x.test,\r\n b@x.test", .{}); try testing.expectEqualStrings("To: a@x.test,\r\n b@x.test\r\n", out.written()); } test "a fold keeps the whitespace it folded at" { // Folding inserts a line ending before whitespace that is already there. // Replacing the whitespace with a space -- a tab becoming a space, three // spaces becoming one -- would make the value that comes back out of // `unfoldWriter` a different value from the one that went in, and inside // a quoted string that whitespace is content. var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const value = "x" ** 70 ++ "\ty" ** 2; try writeField(&out.writer, "Subject", value, .{}); var back: Io.Writer.Allocating = .init(testing.allocator); defer back.deinit(); const folded = out.written()["Subject: ".len .. out.written().len - 2]; try unfoldWriter(&back.writer, folded); try testing.expectEqualStrings(value, back.written()); // And it really did fold, so the test is testing something. try testing.expect(std.mem.find(u8, folded, "\r\n\t") != null); } test "a header cannot be injected through a value" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try writeField(&out.writer, "Subject", "hello\r\nBcc: victim@example.com", .{}); try testing.expectEqualStrings("Subject: helloBcc: victim@example.com\r\n", out.written()); // One line, whatever was asked for. try testing.expectEqual(1, std.mem.count(u8, out.written(), "\r\n")); }