// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The `Received:` trace field — RFC 5321 §4.4 — which every system a message //! passes through adds one of. //! //! ```text //! Received: from client.example.com (client.example.com [192.0.2.1]) //! by mx.example.net (Postfix) with ESMTPS id 3F2A1C0A //! for ; Tue, 01 Jul 2003 10:52:37 +0200 //! ``` //! //! A trace field is the one part of a message that is written by somebody //! other than the sender, and the rules about it are about that: //! //! * **It goes at the top, and nothing below it may move.** Each system //! prepends its own, so the list reads newest first and the path a message //! took can be read off it. RFC 5321 §4.4 is explicit that an existing //! `Received:` must not be altered — not reordered, not refolded, not //! rewritten. `Headers.prependTrace` puts a new one in the one place it may //! go. //! * **Almost everything in it comes from the client.** The `from` name is //! whatever the peer said in `EHLO`, which is a string it chose; the address //! literal beside it is what the server observed and is the part worth //! believing. Writing a `Received:` therefore means writing //! attacker-supplied text into a header, and this module drops the //! characters that would end the field early rather than trusting the //! caller to have done it. //! * **`for` names at most one recipient.** RFC 5321 §4.4 says to include it //! only when there is exactly one, and the reason is disclosure: a message //! delivered to several people with all of their addresses in the trace //! tells each of them who else received it, which is how `Bcc:` gets //! broken by the transport rather than by the sender. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const datetime = @import("datetime"); const date = @import("header/date.zig"); /// The registered values of the `with` clause, which say what was spoken and /// whether it was encrypted and authenticated. RFC 3848, and RFC 6531 for the /// `UTF8` forms. /// /// The registry is open and this is not an enum, because a system that speaks /// something else has to be able to say so. `protocolFor` is the way to the /// right one of these without working out the letters by hand. pub const protocol = struct { pub const smtp = "SMTP"; pub const esmtp = "ESMTP"; pub const esmtpa = "ESMTPA"; pub const esmtps = "ESMTPS"; pub const esmtpsa = "ESMTPSA"; pub const lmtp = "LMTP"; pub const lmtpa = "LMTPA"; pub const lmtps = "LMTPS"; pub const lmtpsa = "LMTPSA"; pub const utf8smtp = "UTF8SMTP"; pub const utf8smtpa = "UTF8SMTPA"; pub const utf8smtps = "UTF8SMTPS"; pub const utf8smtpsa = "UTF8SMTPSA"; pub const utf8lmtp = "UTF8LMTP"; pub const utf8lmtpa = "UTF8LMTPA"; pub const utf8lmtps = "UTF8LMTPS"; pub const utf8lmtpsa = "UTF8LMTPSA"; /// What a message that arrived without a network does. Not registered, /// and universal. pub const local = "local"; }; /// What the session was, from which `protocolFor` works out what to write. pub const Session = struct { /// Whether the client used `EHLO` rather than `HELO`. Almost everything /// does, and `AUTH` and `STARTTLS` are extensions, so the two below /// imply it. extended: bool = true, /// Whether the session was encrypted — the `S`. tls: bool = false, /// Whether the client authenticated — the `A`. authenticated: bool = false, /// LMTP rather than SMTP, which is what a final delivery agent speaks. lmtp: bool = false, /// SMTPUTF8, RFC 6531 — the `UTF8` prefix, which says the envelope could /// carry addresses that are not ASCII. utf8: bool = false, }; /// The `with` value for a session. Getting `ESMTPSA` and `ESMTPS` and /// `ESMTPA` the right way round by hand is a thing people get wrong, and it is /// the only part of the trace a later reader can use to tell an authenticated /// submission from an anonymous relay. pub fn protocolFor(session: Session) []const u8 { // `AUTH` and `STARTTLS` are both extensions, so either of them means the // session was extended whatever the caller passed. LMTP has no unextended // form either: it is itself an extension of ESMTP. const extended = session.extended or session.tls or session.authenticated or session.lmtp; if (!extended) return if (session.utf8) protocol.utf8smtp else protocol.smtp; if (session.lmtp) { if (session.tls and session.authenticated) return if (session.utf8) protocol.utf8lmtpsa else protocol.lmtpsa; if (session.tls) return if (session.utf8) protocol.utf8lmtps else protocol.lmtps; if (session.authenticated) return if (session.utf8) protocol.utf8lmtpa else protocol.lmtpa; return if (session.utf8) protocol.utf8lmtp else protocol.lmtp; } if (session.tls and session.authenticated) return if (session.utf8) protocol.utf8smtpsa else protocol.esmtpsa; if (session.tls) return if (session.utf8) protocol.utf8smtps else protocol.esmtps; if (session.authenticated) return if (session.utf8) protocol.utf8smtpa else protocol.esmtpa; return if (session.utf8) protocol.utf8smtp else protocol.esmtp; } /// One `Received:` field, as a server about to add one has it. pub const Received = struct { /// The name the client gave in `EHLO`. A string the peer chose, and worth /// exactly what that is worth. from: ?[]const u8 = null, /// What goes in parentheses after it: what the server observed about the /// peer rather than what the peer said. Conventionally the reverse-DNS /// name and the address literal — `client.example.com [192.0.2.1]` — and /// the part of the trace that can be relied on. from_info: ?[]const u8 = null, /// This system. Required: a trace entry that does not say who made it /// traces nothing. by: []const u8, /// What goes in parentheses after `by`, conventionally the software. by_info: ?[]const u8 = null, /// The `via` clause, which names the link rather than the protocol. /// Almost nothing writes one. via: ?[]const u8 = null, /// The `with` clause. See `protocol` and `protocolFor`. with: ?[]const u8 = null, /// The `id` clause: this system's own identifier for the message, which /// is what ties the trace to a line in its log. id: ?[]const u8 = null, /// The `for` clause, and **only when there is exactly one recipient**. /// Writing several tells each of them who the others were. Without /// brackets; they are added. for_recipient: ?[]const u8 = null, /// When this system received it. Required. received_at: datetime.DateTime, /// Writes the field value — everything after `Received:` — folded the way /// mail systems fold it, at the clause boundaries. /// /// Every piece of it is filtered: a `Received:` is assembled out of things /// the peer said, and a CRLF in an `EHLO` name would otherwise end the /// field and start whatever followed it as a header of its own. pub fn write(self: Received, w: *Io.Writer) Io.Writer.Error!void { if (self.from) |from| { try w.writeAll("from "); try writeSafe(w, from); try self.writeInfo(w, self.from_info); try w.writeAll("\r\n\t"); } try w.writeAll("by "); try writeSafe(w, self.by); try self.writeInfo(w, self.by_info); if (self.via) |via| { try w.writeAll(" via "); try writeSafe(w, via); } if (self.with) |with| { try w.writeAll(" with "); try writeSafe(w, with); } if (self.id) |id| { try w.writeAll(" id "); try writeSafe(w, id); } if (self.for_recipient) |recipient| { try w.writeAll("\r\n\tfor <"); try writeSafe(w, recipient); try w.writeByte('>'); } try w.writeAll("; "); try date.write(w, self.received_at); } fn writeInfo(self: Received, w: *Io.Writer, info: ?[]const u8) Io.Writer.Error!void { _ = self; const text = info orelse return; if (text.len == 0) return; try w.writeAll(" ("); try writeSafe(w, text); try w.writeByte(')'); } pub fn format(self: Received, w: *Io.Writer) Io.Writer.Error!void { return self.write(w); } }; /// Writes text into a trace field with everything that could end the field, or /// close a parenthesis that is not its own, removed. fn writeSafe(w: *Io.Writer, text: []const u8) Io.Writer.Error!void { for (text) |c| switch (c) { 0...0x1f, 0x7f => {}, '(', ')' => {}, else => try w.writeByte(c), }; } test protocolFor { try testing.expectEqualStrings("ESMTP", protocolFor(.{})); try testing.expectEqualStrings("ESMTPS", protocolFor(.{ .tls = true })); try testing.expectEqualStrings("ESMTPA", protocolFor(.{ .authenticated = true })); try testing.expectEqualStrings( "ESMTPSA", protocolFor(.{ .tls = true, .authenticated = true }), ); try testing.expectEqualStrings("SMTP", protocolFor(.{ .extended = false })); // But `AUTH` is an extension, so a session that used it was extended // whatever the caller said. try testing.expectEqualStrings( "ESMTPA", protocolFor(.{ .extended = false, .authenticated = true }), ); try testing.expectEqualStrings("LMTPS", protocolFor(.{ .lmtp = true, .tls = true })); try testing.expectEqualStrings("UTF8SMTPSA", protocolFor(.{ .tls = true, .authenticated = true, .utf8 = true, })); } fn exampleTime() datetime.DateTime { var when: datetime.DateTime = .{ .year = 2003, .month = .Jul, .day = 1, .hour = 10, .minute = 52, .second = 37, .offset = 2 * 60 * 60, }; when.updateDayOfWeek(); return when; } test "what a relay writes" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const received: Received = .{ .from = "client.example.com", .from_info = "client.example.com [192.0.2.1]", .by = "mx.example.net", .by_info = "Postfix", .with = protocolFor(.{ .tls = true }), .id = "3F2A1C0A", .for_recipient = "alice@example.net", .received_at = exampleTime(), }; try received.write(&out.writer); try testing.expectEqualStrings( "from client.example.com (client.example.com [192.0.2.1])\r\n" ++ "\tby mx.example.net (Postfix) with ESMTPS id 3F2A1C0A\r\n" ++ "\tfor ; Tue, 01 Jul 2003 10:52:37 +0200", out.written(), ); } test "the least a trace entry can say" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const received: Received = .{ .by = "mx.example.net", .received_at = exampleTime() }; try received.write(&out.writer); try testing.expectEqualStrings( "by mx.example.net; Tue, 01 Jul 2003 10:52:37 +0200", out.written(), ); } test "a client cannot end the field early" { var out: Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); // Everything here but `by` came off the wire from the peer. const received: Received = .{ .from = "evil\r\nBcc: victim@evil.test", .from_info = "closes) the paren", .by = "mx.example.net", .id = "a\x00b", .received_at = exampleTime(), }; try received.write(&out.writer); // One field, over the two lines its own folding made, and no parenthesis // that is not ours. try testing.expectEqual(1, std.mem.count(u8, out.written(), "\r\n")); try testing.expectEqual(1, std.mem.count(u8, out.written(), "(")); try testing.expectEqual(1, std.mem.count(u8, out.written(), ")")); try testing.expect(std.mem.find(u8, out.written(), "Bcc:") != null); try testing.expect(std.mem.find(u8, out.written(), "\r\nBcc:") == null); try testing.expect(std.mem.find(u8, out.written(), "id ab;") != null); } test "a relay's Received goes above the ones already there" { const Message = @import("Message.zig"); var message: Message = try .parse(testing.allocator, "Received: from a.example.com (a.example.com [192.0.2.1])\r\n" ++ "\tby relay.example.net; Tue, 01 Jul 2003 10:00:00 +0200\r\n" ++ "From: alice@example.com\r\n" ++ "Subject: hello\r\n" ++ "\r\n" ++ "body\r\n", .{}); defer message.deinit(); try message.addReceived(.{ .from = "relay.example.net", .by = "mx.example.net", .with = protocolFor(.{}), .received_at = exampleTime(), }); const out = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(out); // Newest first, and the older entry is byte-for-byte what it was: RFC 5321 // §4.4 does not let a relay touch it, and the folding it arrived with is // part of it. try testing.expect(std.mem.startsWith(u8, out, "Received: from relay.example.net\r\n\tby mx.example.net")); try testing.expect(std.mem.find(u8, out, "Received: from a.example.com (a.example.com [192.0.2.1])\r\n" ++ "\tby relay.example.net; Tue, 01 Jul 2003 10:00:00 +0200\r\n") != null); try testing.expectEqual(2, std.mem.count(u8, out, "\r\nReceived:") + 1); } test "a Return-Path stays above the Received" { const Message = @import("Message.zig"); // A message that has already been delivered once, being taken in again. var message: Message = try .parse(testing.allocator, "Return-Path: \r\n" ++ "Received: from a.example.com by mx.example.net; Tue, 01 Jul 2003 10:00:00 +0200\r\n" ++ "From: alice@example.com\r\n" ++ "\r\n" ++ "body\r\n", .{}); defer message.deinit(); try message.addReceived(.{ .by = "forward.example.org", .received_at = exampleTime() }); const out = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(out); // Above a `Return-Path:` would say the message was received after it was // delivered. try testing.expect(std.mem.startsWith(u8, out, "Return-Path: \r\n" ++ "Received: by forward.example.org; Tue, 01 Jul 2003 10:52:37 +0200\r\n" ++ "Received: from a.example.com by mx.example.net;")); } test "a signature this hop adds sits above this hop's Received" { const Message = @import("Message.zig"); var message: Message = try .parse(testing.allocator, "From: alice@example.com\r\n\r\nbody\r\n", .{}); defer message.deinit(); try message.addReceived(.{ .by = "mx.example.net", .received_at = exampleTime() }); try message.root.headers.prependRaw("DKIM-Signature", "v=1; a=rsa-sha256; d=example.net;\r\n\tb=AAAA"); const out = try message.toBytesAlloc(testing.allocator); defer testing.allocator.free(out); try testing.expect(std.mem.startsWith(u8, out, "DKIM-Signature: v=1;")); try testing.expect(std.mem.find(u8, out, "b=AAAA\r\nReceived: by mx.example.net;") != null); }