// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The name allthemail will give a message: the SHA3-512 of its canonical //! bytes, in lowercase hexadecimal. //! //! ## Why this is computed here at all //! //! The archive is content-addressed, so the hash of a message is the whole of //! its identity there, and knowing it before uploading turns "does the archive //! already hold this?" into a `HEAD /message/{hash}` — a request that reads //! nothing off disk and transfers nothing. Without it the only way to find out //! is to POST the message and read the status code, which means pushing a //! twenty megabyte attachment across a socket to be told it was already there. //! Over a re-run of a whole mailbox that is the difference between a sync that //! costs a few seconds and one that costs an hour. //! //! ## Why it must agree exactly //! //! This is a second implementation of something `allthemail/src/Hash.zig` //! already does, and a second implementation that disagrees is worse than none: //! every `HEAD` would miss, every message would be uploaded again, and nothing //! would report an error. The two are pinned together by the NIST vector in the //! tests below, which is the same vector allthemail pins itself to. //! //! The canonicalization matters as much as the digest. allthemail rewrites //! every submission to CRLF before hashing it, so that a message read out of a //! Unix file and the same message off the wire become one entry rather than //! two. Graph's `$value` returns the message as Exchange stored it, which is //! normally CRLF throughout — but a message Outlook itself composed, or one //! that has been through a store-and-forward that did not care, can come back //! with bare LFs, so the same rewrite has to happen on this side or the hash //! computed here names a file the archive will never create. const Hash = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const Algorithm = std.crypto.hash.sha3.Sha3_512; /// Length of the hexadecimal form: two characters per digest byte. pub const hex_length = Algorithm.digest_length * 2; hex: [hex_length]u8, /// Hashes `source` exactly as given. The caller is responsible for having /// canonicalized it; `ofCanonical` is the one that does both and is almost /// always the one wanted. pub fn of(source: []const u8) Hash { var digest: [Algorithm.digest_length]u8 = undefined; Algorithm.hash(source, &digest, .{}); var self: Hash = undefined; _ = std.fmt.bufPrint(&self.hex, "{x}", .{&digest}) catch unreachable; return self; } /// Canonicalizes `source` to CRLF and hashes the result, without allocating: /// the rewrite is fed through the digest a line at a time rather than into a /// buffer. A whole mailbox passes through here and the messages are the /// largest things this program handles, so not making a second copy of each /// one is worth the dozen lines. pub fn ofCanonical(source: []const u8) Hash { var state: Algorithm = .init(.{}); var start: usize = 0; var previous: u8 = 0; for (source, 0..) |c, i| { if (c == '\n' and previous != '\r') { state.update(source[start..i]); state.update("\r\n"); start = i + 1; } previous = c; } state.update(source[start..]); var digest: [Algorithm.digest_length]u8 = undefined; state.final(&digest); var self: Hash = undefined; _ = std.fmt.bufPrint(&self.hex, "{x}", .{&digest}) catch unreachable; return self; } /// The length `canonicalize` will write: every LF not already preceded by a CR /// gains one. pub fn canonicalLen(source: []const u8) usize { var len: usize = source.len; var previous: u8 = 0; for (source) |c| { if (c == '\n' and previous != '\r') len += 1; previous = c; } return len; } /// `source` with every line ending as CRLF, allocated. A CR that is not part /// of a line ending is passed through untouched rather than being paired with /// the next LF, because a lone CR in text is a character and not a line break. /// /// This is what goes on the wire. The bytes the archive stores are the bytes /// it received, and it canonicalizes them itself, so sending the original /// would work — but then the hash this program computed and the hash the /// archive computed would be over different bytes, and the `HEAD` check would /// be answering a question about a file that does not exist. pub fn canonicalize(gpa: Allocator, source: []const u8) Allocator.Error![]u8 { const out = try gpa.alloc(u8, canonicalLen(source)); errdefer gpa.free(out); var end: usize = 0; var start: usize = 0; var previous: u8 = 0; for (source, 0..) |c, i| { if (c == '\n' and previous != '\r') { const run = source[start..i]; @memcpy(out[end..][0..run.len], run); end += run.len; @memcpy(out[end..][0..2], "\r\n"); end += 2; start = i + 1; } previous = c; } const rest = source[start..]; @memcpy(out[end..][0..rest.len], rest); end += rest.len; std.debug.assert(end == out.len); return out; } /// Whether `source` is already CRLF throughout, in which case `canonicalize` /// would return a copy and the caller can send what it was given. pub fn isCanonical(source: []const u8) bool { return canonicalLen(source) == source.len; } pub fn eql(self: Hash, other: Hash) bool { return std.mem.eql(u8, &self.hex, &other.hex); } pub fn format(self: Hash, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.writeAll(&self.hex); } const testing = std.testing; test "the empty message hashes to the SHA3-512 of nothing" { // NIST's published digest for the empty input. `allthemail/src/Hash.zig` // pins itself to this same vector, which is what ties the two // implementations together: if either drifts, one of these two tests fails. const expected = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6" ++ "15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; try testing.expectEqualStrings(expected, &Hash.of("").hex); try testing.expectEqualStrings(expected, &Hash.ofCanonical("").hex); } test "canonicalization makes an LF message hash like its CRLF twin" { const gpa = testing.allocator; const lf = "Subject: hello\nFrom: a@example.com\n\nbody\n"; const crlf = "Subject: hello\r\nFrom: a@example.com\r\n\r\nbody\r\n"; // The property the whole pre-check rests on. try testing.expect(Hash.ofCanonical(lf).eql(.ofCanonical(crlf))); try testing.expect(Hash.ofCanonical(lf).eql(.of(crlf))); const written = try Hash.canonicalize(gpa, lf); defer gpa.free(written); try testing.expectEqualStrings(crlf, written); try testing.expect(!Hash.isCanonical(lf)); try testing.expect(Hash.isCanonical(crlf)); } test "canonicalization leaves an already-CRLF message alone" { const gpa = testing.allocator; const crlf = "Subject: hello\r\n\r\nbody\r\n"; const written = try Hash.canonicalize(gpa, crlf); defer gpa.free(written); try testing.expectEqualStrings(crlf, written); } test "a lone CR is a character, not half a line ending" { const gpa = testing.allocator; // The CR here is data. Pairing it with the LF two bytes later would lose a // byte and change the hash of a message nobody meant to rewrite. const source = "Subject: a\rb\nc\r\n"; const expected = "Subject: a\rb\r\nc\r\n"; const written = try Hash.canonicalize(gpa, source); defer gpa.free(written); try testing.expectEqualStrings(expected, written); try testing.expect(Hash.ofCanonical(source).eql(.of(expected))); } test "ofCanonical agrees with canonicalize then of, over awkward input" { const gpa = testing.allocator; // The streaming digest and the allocating rewrite are two separate pieces // of code doing the same thing, which is exactly the arrangement that // drifts. Every one of these has a boundary in a different place. for ([_][]const u8{ "", "\n", "\r", "\r\n", "\n\r", "\r\r\n", "a", "a\n", "\na", "a\r\nb\nc\r\rd\n\n", "no line endings at all", }) |source| { const written = try Hash.canonicalize(gpa, source); defer gpa.free(written); try testing.expectEqual(canonicalLen(source), written.len); try testing.expect(Hash.ofCanonical(source).eql(.of(written))); } } test "different content hashes differently" { const message = "Subject: hello\r\n\r\nbody\r\n"; try testing.expect(Hash.ofCanonical(message).eql(.ofCanonical(message))); try testing.expect(!Hash.ofCanonical(message).eql(.ofCanonical(message ++ " "))); }