// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The `Received-SPF` header field of [RFC 7208 //! §9.1](https://datatracker.ietf.org/doc/html/rfc7208#section-9.1). //! //! A check that nobody records is a check nobody can act on later. This //! is how the answer travels with the message: a receiver writes the //! field at the top, and everything downstream — a filter, a mailbox //! rule, somebody reading a header two years later — sees what was //! decided and what it was decided about. //! //! Every value in it is supplied by the client being judged. The sender, //! the greeting and a `problem=` text taken from a domain's own //! explanation are all somebody else's bytes, and they are going into a //! structured header field above the message — so escaping them is not //! tidiness, it is the whole job. A sender who could close the comment //! and open a field of their own would be writing headers on a message //! they do not control. const std = @import("std"); const Io = std.Io; const z46 = @import("z46"); const check = @import("check.zig"); /// Which of the two identities of §2.3 and §2.4 was checked. It matters /// to anything reading the field later: a `pass` for the HELO identity /// says nothing about the envelope sender. pub const Identity = enum { mailfrom, helo, }; pub const Received = struct { result: check.Result, /// The host that did the checking. §9.1 puts it both in the comment /// and in `receiver=`. receiver: []const u8, identity: Identity, client_ip: z46.Address, /// The envelope sender. Null for a HELO check, where there is none /// to report. envelope_from: ?[]const u8 = null, /// What the client greeted as. helo: []const u8, /// `problem=`: what went wrong, for a `temperror` or `permerror`. /// The domain's own explanation text can go here, which is exactly /// why it is escaped on the way out. problem: ?[]const u8 = null, /// Writes the whole field, `Received-SPF:` and the terminating CRLF /// included. Use the `{f}` specifier. pub fn format(received: Received, w: *Io.Writer) Io.Writer.Error!void { try w.writeAll("Received-SPF: "); try w.writeAll(@tagName(received.result)); try w.writeAll(" ("); try received.writeComment(w); // The key/value list goes on a continuation line. §9.1's own // example is folded this way, and it keeps the first line short // however long the sender made their address. try w.writeAll(")\r\n "); var list: List = .{}; try list.pair(w, "receiver", received.receiver); try list.pair(w, "identity", @tagName(received.identity)); var address: [z46.Address.max_text_len]u8 = undefined; try list.pair(w, "client-ip", received.client_ip.bufPrint(&address) catch unreachable); if (received.envelope_from) |from| { try list.pair(w, "envelope-from", from); } try list.pair(w, "helo", received.helo); if (received.problem) |problem| { try list.pair(w, "problem", problem); } try w.writeAll("\r\n"); } pub fn bufPrint(received: Received, buffer: []u8) Io.Writer.Error![]u8 { var w: Io.Writer = .fixed(buffer); try received.format(&w); return buffer[0..w.end]; } /// The human-readable part. The wording is the one every deployed /// implementation uses, because these strings are grepped for by /// filters that were written against Postfix and libspf2 and would /// not recognize better prose. fn writeComment(received: Received, w: *Io.Writer) Io.Writer.Error!void { _ = try writeCommentText(w, received.receiver); try w.writeAll(": "); const identity = received.envelope_from orelse received.helo; switch (received.result) { .pass => { try w.writeAll("domain of "); _ = try writeCommentText(w, identity); try w.writeAll(" designates "); try writeAddress(w, received.client_ip); try w.writeAll(" as permitted sender"); }, .fail => { try w.writeAll("domain of "); _ = try writeCommentText(w, identity); try w.writeAll(" does not designate "); try writeAddress(w, received.client_ip); try w.writeAll(" as permitted sender"); }, .softfail => { try w.writeAll("transitioning domain of "); _ = try writeCommentText(w, identity); try w.writeAll(" does not designate "); try writeAddress(w, received.client_ip); try w.writeAll(" as permitted sender"); }, .neutral => { try writeAddress(w, received.client_ip); try w.writeAll(" is neither permitted nor denied by domain of "); _ = try writeCommentText(w, identity); }, .none => { _ = try writeCommentText(w, identity); try w.writeAll(" does not designate permitted sender hosts"); }, .temperror => { try w.writeAll("error in processing during lookup of "); _ = try writeCommentText(w, identity); }, .permerror => { try w.writeAll("permanent error in processing domain of "); _ = try writeCommentText(w, identity); }, } } fn writeAddress(w: *Io.Writer, address: z46.Address) Io.Writer.Error!void { var buffer: [z46.Address.max_text_len]u8 = undefined; try w.writeAll(address.bufPrint(&buffer) catch unreachable); } }; /// The `key-value-list` of §9.1, written one pair at a time so that the /// separator lands between pairs rather than after the last one and a /// fold carries no trailing space with it. const List = struct { column: usize = 1, written: usize = 0, fn pair(list: *List, w: *Io.Writer, key: []const u8, value: []const u8) Io.Writer.Error!void { if (list.written > 0) { try w.writeByte(';'); list.column += 1; } // The escaped length is not known before writing it, so this is // an estimate: a value that needs quoting grows, and a line that // ends up a little over 78 is still well inside the 998 that is // a limit rather than a recommendation. if (list.column + key.len + value.len + 2 > 76) { try w.writeAll("\r\n "); list.column = 1; } else if (list.written > 0) { try w.writeByte(' '); list.column += 1; } try w.writeAll(key); try w.writeByte('='); list.column += key.len + 1 + try writeValue(w, value); list.written += 1; } }; /// Text inside the comment, with everything that could end it escaped. /// /// RFC 5322's `ccontent` excludes `(`, `)` and `\`, and each may be /// written as a quoted-pair instead. A CR or LF would end the header /// field outright, so those are dropped rather than escaped — there is /// no spelling of them that belongs in a comment. fn writeCommentText(w: *Io.Writer, text: []const u8) Io.Writer.Error!usize { var written: usize = 0; for (text) |byte| switch (byte) { '(', ')', '\\' => { try w.writeByte('\\'); try w.writeByte(byte); written += 2; }, '\r', '\n' => {}, // Anything outside printable ASCII has no meaning here and is // replaced rather than passed through: a header field is not the // place to find out what a receiver's terminal does with it. 0x00...0x08, 0x0b, 0x0c, 0x0e...0x1f, 0x7f...0xff => { try w.writeByte('?'); written += 1; }, else => { try w.writeByte(byte); written += 1; }, }; return written; } /// A key's value, as §9.1's ABNF allows: a bare `dot-atom` when it is /// one, and a `quoted-string` when it is not. /// /// An IPv6 address needs the quotes, because `:` is not `atext` — so /// does every envelope sender, because `@` is not either. Getting this /// wrong produces a field that parses as something shorter than what was /// written, which is the interesting kind of wrong. fn writeValue(w: *Io.Writer, value: []const u8) Io.Writer.Error!usize { if (isDotAtom(value)) { try w.writeAll(value); return value.len; } var written: usize = 2; try w.writeByte('"'); for (value) |byte| switch (byte) { '"', '\\' => { try w.writeByte('\\'); try w.writeByte(byte); written += 2; }, '\r', '\n' => {}, 0x00...0x08, 0x0b, 0x0c, 0x0e...0x1f, 0x7f...0xff => { try w.writeByte('?'); written += 1; }, else => { try w.writeByte(byte); written += 1; }, }; try w.writeByte('"'); return written; } fn isDotAtom(value: []const u8) bool { if (value.len == 0) return false; if (value[0] == '.' or value[value.len - 1] == '.') return false; var previous_dot = false; for (value) |byte| { if (byte == '.') { // `dot-atom-text` is `1*atext *("." 1*atext)`, so two dots in // a row is not one. if (previous_dot) return false; previous_dot = true; continue; } previous_dot = false; if (!isAtext(byte)) return false; } return true; } fn isAtext(byte: u8) bool { return switch (byte) { 'A'...'Z', 'a'...'z', '0'...'9' => true, '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/' => true, '=', '?', '^', '_', '`', '{', '|', '}', '~' => true, else => false, }; } const testing = std.testing; test "the worked example of RFC 7208 section 9.1" { var buffer: [512]u8 = undefined; const received: Received = .{ .result = .pass, .receiver = "mybox.example.org", .identity = .mailfrom, .client_ip = .{ .ipv4 = .init(192, 0, 2, 1) }, .envelope_from = "myname@example.com", .helo = "foo.example.com", }; try testing.expectEqualStrings( "Received-SPF: pass (mybox.example.org: domain of myname@example.com" ++ " designates 192.0.2.1 as permitted sender)\r\n" ++ " receiver=mybox.example.org; identity=mailfrom; client-ip=192.0.2.1;\r\n" ++ " envelope-from=\"myname@example.com\"; helo=foo.example.com\r\n", try received.bufPrint(&buffer), ); } test "an IPv6 client and a HELO check" { var buffer: [512]u8 = undefined; const received: Received = .{ .result = .fail, .receiver = "mx.example.net", .identity = .helo, // A colon is not `atext`, so the address has to be quoted. A // field that left it bare would parse as `client-ip=2001` and a // reader would believe it. .client_ip = .{ .ipv6 = try .parse("2001:db8::1") }, .helo = "claims.example.com", }; const text = try received.bufPrint(&buffer); try testing.expect(std.mem.startsWith(u8, text, "Received-SPF: fail (")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "client-ip=\"2001:db8::1\"")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "identity=helo")); try testing.expect(std.mem.containsAtLeast(u8, text, 1, "helo=claims.example.com")); // No envelope sender to report on a HELO check, so the key is absent // rather than empty. try testing.expect(!std.mem.containsAtLeast(u8, text, 1, "envelope-from")); } test "a sender cannot write their own header fields" { var buffer: [1024]u8 = undefined; const received: Received = .{ .result = .fail, .receiver = "mx.example.net", .identity = .mailfrom, .client_ip = .{ .ipv4 = .init(192, 0, 2, 1) }, // Everything a client supplies arrives like this eventually. .envelope_from = "evil) pass (\r\nX-Spam-Status: No\r\n@example.com", .helo = "a\"b", .problem = "line\r\none", }; const text = try received.bufPrint(&buffer); // One field, one line break pattern: the only CRLFs are the folds // this code wrote and the one that ends the field. var lines = std.mem.splitSequence(u8, text, "\r\n"); while (lines.next()) |line| { if (line.len == 0) continue; try testing.expect(line[0] == 'R' or line[0] == ' '); } try testing.expect(!std.mem.containsAtLeast(u8, text, 1, "X-Spam-Status:\r\n")); // The parens that would have closed the comment are quoted-pairs. try testing.expect(std.mem.containsAtLeast(u8, text, 1, "evil\\) pass \\(")); // And the quote that would have closed the quoted-string. try testing.expect(std.mem.containsAtLeast(u8, text, 1, "helo=\"a\\\"b\"")); } test "every result has wording of its own" { var buffer: [512]u8 = undefined; var seen: std.EnumSet(check.Result) = .initEmpty(); for (std.enums.values(check.Result)) |result| { const received: Received = .{ .result = result, .receiver = "mx.example.net", .identity = .mailfrom, .client_ip = .{ .ipv4 = .init(192, 0, 2, 1) }, .envelope_from = "alice@example.com", .helo = "mail.example.com", }; const text = try received.bufPrint(&buffer); // The result is the first thing after the field name, which is // what anything reading these actually looks at. try testing.expect(std.mem.startsWith( u8, text["Received-SPF: ".len..], @tagName(result), )); seen.insert(result); } try testing.expectEqual(std.enums.values(check.Result).len, seen.count()); }