// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Internationalized domain names: `bücher.example` and `xn--bcher-kva.example` //! are the same domain written two ways, and mail has to be able to get from //! either to the other. //! //! The domain name system carries ASCII. A domain that is not ASCII is encoded //! into an *A-label* — a label beginning `xn--` followed by Punycode, RFC 3492 //! — and it is that form which goes on the wire, into DNS, and into an address //! that has to reach a transport with no opinion about Unicode. The *U-label* //! is the same name as a person writes it, and it is what a person should be //! shown. //! //! Converting between them is not simply Punycode. UTS #46 is a mapping as //! well as an encoding: case folding, Normalization Form C, a table of code //! points that are disallowed outright, and rules about joiners and //! bidirectional text. `Bücher.example` and `bücher.example` are the same //! domain and must produce the same A-label; a domain containing a code point //! nobody should be able to register must be refused rather than encoded. That //! is what [zig-uri][]'s `uri_unicode.idna` does, and it is why this module is a wrapper //! rather than an implementation. //! //! [zig-uri]: https://git.jcollie.dev/jeff/zig-uri //! //! ## The local part is not a domain //! //! Punycode applies to the right of the `@` and nowhere else. An address whose //! *local part* is not ASCII — `జోసెఫ్@example.com` — cannot be encoded into //! ASCII at all, and needs a transport that speaks SMTPUTF8 (RFC 6531) from //! end to end. `address.Mailbox.requiresSmtpUtf8` is that question, and it is //! a different question from whether the domain needs converting. //! //! ## Showing the U-label is a decision, not a default //! //! `раypal.com` with a Cyrillic `а` and `paypal.com` with a Latin one look //! identical in most fonts and are different domains. Displaying the U-label //! is therefore a security decision: it is what a person wants to read and it //! is also how a phishing domain hides. Browsers decide with a script-mixing //! heuristic and show the A-label when a name looks suspicious; nothing here //! does that for you, and nothing here silently prefers one form over the //! other. Both forms are available, and which one a reader shows is the //! reader's problem to think about. const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const idna = @import("uri_unicode").idna; /// The processing options mail wants. /// /// `verify_dns_length` is on because a domain that cannot be looked up is not /// a domain, and `use_std3_ascii_rules` is off because an existing ASCII /// domain with an underscore in it — which a great many mail hosts have — must /// pass through unchanged rather than being refused by a rule that was written /// for something else. pub const options: idna.Options = .{ .use_std3_ascii_rules = false, .verify_dns_length = true, }; pub const Error = error{ /// The name is not a domain that can be encoded: a disallowed code point, /// a label of the wrong length, an `xn--` label whose Punycode is /// nonsense, or text that violates the bidirectional rules. InvalidDomain, }; /// Whether `domain` is already ASCII, and so needs no conversion to be sent /// through a transport that has never heard of Unicode. pub fn isAscii(domain: []const u8) bool { for (domain) |c| if (c >= 0x80) return false; return true; } /// Whether `domain` contains a byte that cannot appear in a domain name in a /// header: a control character, a space, or DEL. /// /// UTS #46's STD3 rules would catch these, and those rules are off here /// because they also refuse the underscore that a good many working mail hosts /// have in their names. Turning them off is a decision about the underscore /// and not about the NUL, so the dangerous half is checked separately: a /// control character in a domain is either a corrupted message or an attempt /// to end the header line early, and never a domain. pub fn hasControl(domain: []const u8) bool { for (domain) |c| if (c <= 0x20 or c == 0x7f) return true; return false; } /// Whether `domain` is a domain-literal — `[192.0.2.1]` — which is an address /// rather than a name and must never be put through IDNA. pub fn isLiteral(domain: []const u8) bool { return domain.len >= 2 and domain[0] == '[' and domain[domain.len - 1] == ']'; } /// The A-label form: `bücher.example` becomes `xn--bcher-kva.example`. /// /// This is what goes into an address that has to reach a transport with no /// SMTPUTF8. It fails rather than guessing, because a domain that cannot be /// encoded is a domain that cannot be delivered to, and silently sending /// something else would deliver to somebody else. /// /// A domain-literal is returned unchanged: it is an address and not a name. pub fn toAsciiAlloc(gpa: Allocator, domain: []const u8) (Allocator.Error || Error)![]u8 { if (hasControl(domain)) return error.InvalidDomain; if (isLiteral(domain)) { // A domain-literal is an address rather than a name and IDNA must not // touch it — but it is still ASCII, because `dtext` is. One with a // high byte in it is not a literal and is not deliverable to, so it // is refused rather than passed through as though it were. if (!isAscii(domain)) return error.InvalidDomain; return gpa.dupe(u8, domain); } const ascii = idna.toAscii(gpa, domain, options) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.InvalidDomain, }; // The output is checked as well as the input, because UTS #46 *maps* as // well as validates: with the STD3 rules off, a code point such as U+00A8 // is mapped to a space and a combining mark, so a name with no space in it // can come back with one. Checking here rather than turning those rules on // keeps the underscore that real mail hosts have and still refuses the // space that no domain can contain. if (hasControl(ascii)) { gpa.free(ascii); return error.InvalidDomain; } return ascii; } /// The U-label form, for showing a person: `xn--bcher-kva.example` becomes /// `bücher.example`. /// /// Total, unlike `toAsciiAlloc`: a name that will not convert is returned as /// it stands. Display has to produce something, and the A-label is a true /// thing to show — it is what the message actually said. Read the module /// comment before showing the result of this to anybody. pub fn toUnicodeAlloc(gpa: Allocator, domain: []const u8) Allocator.Error![]u8 { if (isLiteral(domain)) return gpa.dupe(u8, domain); return idna.toUnicode(gpa, domain, options) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return gpa.dupe(u8, domain), }; } test isAscii { try testing.expect(isAscii("example.com")); try testing.expect(isAscii("xn--bcher-kva.example")); try testing.expect(!isAscii("bücher.example")); } test isLiteral { try testing.expect(isLiteral("[192.0.2.1]")); try testing.expect(isLiteral("[IPv6:2001:db8::1]")); try testing.expect(!isLiteral("example.com")); try testing.expect(!isLiteral("[unterminated")); } test "there and back again" { const ascii = try toAsciiAlloc(testing.allocator, "bücher.example"); defer testing.allocator.free(ascii); try testing.expectEqualStrings("xn--bcher-kva.example", ascii); const unicode = try toUnicodeAlloc(testing.allocator, ascii); defer testing.allocator.free(unicode); try testing.expectEqualStrings("bücher.example", unicode); } test "case and normalisation are part of the mapping" { // The same domain written three ways produces one A-label, which is the // whole reason this is UTS #46 rather than Punycode. for ([_][]const u8{ "Bücher.Example", "BÜCHER.EXAMPLE", "bücher.example" }) |spelling| { const ascii = try toAsciiAlloc(testing.allocator, spelling); defer testing.allocator.free(ascii); try testing.expectEqualStrings("xn--bcher-kva.example", ascii); } } test "an ASCII domain passes through unchanged" { for ([_][]const u8{ "example.com", "mail.example.co.uk", "a_b.example.net" }) |domain| { const ascii = try toAsciiAlloc(testing.allocator, domain); defer testing.allocator.free(ascii); try testing.expectEqualStrings(domain, ascii); } } test "a domain literal is an address and is left alone" { const ascii = try toAsciiAlloc(testing.allocator, "[192.0.2.1]"); defer testing.allocator.free(ascii); try testing.expectEqualStrings("[192.0.2.1]", ascii); const unicode = try toUnicodeAlloc(testing.allocator, "[192.0.2.1]"); defer testing.allocator.free(unicode); try testing.expectEqualStrings("[192.0.2.1]", unicode); } test "a domain that cannot be encoded is refused rather than guessed at" { for ([_][]const u8{ "", "a..b.example", &@as([300]u8, @splat('x')), // A control character, which the relaxed STD3 rules would otherwise // let through: it is how a domain ends a header line early. "a\x00b.example", "example.com\r\nBcc: victim@evil.test", "exa mple.com", // A domain-literal that is not ASCII is not a domain-literal. The // fuzz target found this one. "[192.0.2.\xc3]", // U+00A8 maps to a space and a combining mark, so the conversion // succeeds and produces something that is not a domain. The fuzz // target found this one too. "¨", "a¨b.example", }) |domain| { try testing.expectError(error.InvalidDomain, toAsciiAlloc(testing.allocator, domain)); } // ...and the underscore that turning those rules off was for. const underscored = try toAsciiAlloc(testing.allocator, "mail_1.example.com"); defer testing.allocator.free(underscored); try testing.expectEqualStrings("mail_1.example.com", underscored); } test "a name that will not convert is still shown as itself" { // Display has to produce something, and the A-label is a true thing to // show: it is what the message said. const shown = try toUnicodeAlloc(testing.allocator, "xn--not-valid-punycode-at-all"); defer testing.allocator.free(shown); try testing.expectEqualStrings("xn--not-valid-punycode-at-all", shown); }