// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Writing record data the way a zone file does. //! //! The wire format is one thing and the text a zone file holds is another, and //! the mapping between them is per field rather than per type: a digest is //! hexadecimal, a key is base64, and the hashed owner name in an `nsec3` is //! base32 with the *extended hex* alphabet, chosen because it sorts the same //! way the bytes it encodes do, which is the whole point of hashing the names //! in the first place. //! //! Nothing here decodes. This library reads the wire and writes the wire; //! these functions exist so that what it read can be printed and recognized. const std = @import("std"); const Writer = std.Io.Writer; /// Lowercase hexadecimal, as `sshfp` and `tlsa` are written. pub fn writeHexLower(w: *Writer, bytes: []const u8) Writer.Error!void { for (bytes) |b| try w.print("{x:0>2}", .{b}); } test writeHexLower { // An SSHFP fingerprint begins like this. var buf: [16]u8 = undefined; var w: Writer = .fixed(&buf); try writeHexLower(&w, "\x12\x3a\xbc\xef"); try testing.expectEqualStrings("123abcef", w.buffered()); } /// Uppercase hexadecimal, as `ds` digests and `nsec3` salts are written. pub fn writeHexUpper(w: *Writer, bytes: []const u8) Writer.Error!void { for (bytes) |b| try w.print("{X:0>2}", .{b}); } test writeHexUpper { // An NSEC3 salt. var buf: [16]u8 = undefined; var w: Writer = .fixed(&buf); try writeHexUpper(&w, "\xaa\xbb\xcc\xdd"); try testing.expectEqualStrings("AABBCCDD", w.buffered()); } /// Standard base64 with padding, as keys and signatures are written. pub fn writeBase64(w: *Writer, bytes: []const u8) Writer.Error!void { const encoder = std.base64.standard.Encoder; // A multiple of three, so that every chunk but the last encodes without // padding and the pieces join up. const chunk_len = 48; var out: [encoder.calcSize(chunk_len)]u8 = undefined; var i: usize = 0; while (i < bytes.len) { const n = @min(chunk_len, bytes.len - i); try w.writeAll(encoder.encode(out[0..encoder.calcSize(n)], bytes[i..][0..n])); i += n; } } test writeBase64 { var buf: [16]u8 = undefined; var w: Writer = .fixed(&buf); try writeBase64(&w, "hello"); try testing.expectEqualStrings("aGVsbG8=", w.buffered()); } /// The alphabet of RFC 4648 §7: the digits and then the letters, so that the /// encoding of a hash sorts in the same order as the hash. const base32hex_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; /// Unpadded base32 over the extended hex alphabet, which is how RFC 5155 /// writes both the owner name of an `nsec3` record and the next hashed owner /// inside it. pub fn writeBase32Hex(w: *Writer, bytes: []const u8) Writer.Error!void { // Bits go in eight at a time and come out five at a time, so the leftover // is never more than four and the accumulator never holds more than twelve. var accumulator: u16 = 0; var bits: u4 = 0; for (bytes) |b| { accumulator = accumulator << 8 | b; bits += 8; while (bits >= 5) { bits -= 5; try w.writeByte(base32hex_alphabet[@as(u5, @truncate(accumulator >> bits))]); } } // What is left is the high bits of the last character, padded with zeros. if (bits > 0) { try w.writeByte(base32hex_alphabet[@as(u5, @truncate(accumulator << (5 - bits)))]); } } test writeBase32Hex { // RFC 4648's own vector, without the `======` RFC 5155 leaves off. var buf: [16]u8 = undefined; var w: Writer = .fixed(&buf); try writeBase32Hex(&w, "f"); try testing.expectEqualStrings("CO", w.buffered()); } /// A character-string as a zone file writes one: in double quotes, with a /// backslash before a quote or a backslash and `\DDD` for anything that is not /// printable ASCII. pub fn writeCharacterString(w: *Writer, bytes: []const u8) Writer.Error!void { try w.writeByte('"'); for (bytes) |c| { switch (c) { '"', '\\' => { try w.writeByte('\\'); try w.writeByte(c); }, else => if (c >= 0x20 and c <= 0x7e) try w.writeByte(c) else try w.print("\\{d:0>3}", .{c}), } } try w.writeByte('"'); } test writeCharacterString { var buf: [32]u8 = undefined; var w: Writer = .fixed(&buf); try writeCharacterString(&w, "say \"hi\"\n"); try testing.expectEqualStrings("\"say \\\"hi\\\"\\010\"", w.buffered()); } /// The `\# length hex...` syntax of RFC 3597 §5, which is how a record of a /// type the reader does not know is written down without pretending to /// understand it. pub fn writeUnknownRdata(w: *Writer, bytes: []const u8) Writer.Error!void { try w.print("\\# {d}", .{bytes.len}); if (bytes.len == 0) return; try w.writeByte(' '); try writeHexUpper(w, bytes); } test writeUnknownRdata { // The four bytes of an `a` record, written as though its type were unknown. var buf: [32]u8 = undefined; var w: Writer = .fixed(&buf); try writeUnknownRdata(&w, "\xc0\x00\x02\x01"); try testing.expectEqualStrings("\\# 4 C0000201", w.buffered()); } const testing = std.testing; fn expectWritten(expected: []const u8, comptime f: anytype, bytes: []const u8) !void { var buf: [512]u8 = undefined; var w = Writer.fixed(&buf); try f(&w, bytes); try testing.expectEqualStrings(expected, w.buffered()); } test "hexadecimal" { try expectWritten("00ff10", writeHexLower, "\x00\xff\x10"); try expectWritten("00FF10", writeHexUpper, "\x00\xff\x10"); try expectWritten("", writeHexUpper, ""); } test "base64 matches the standard encoder across chunk boundaries" { var bytes: [200]u8 = undefined; for (&bytes, 0..) |*b, i| b.* = @truncate(i *% 37); const encoder = std.base64.standard.Encoder; var expected: [encoder.calcSize(bytes.len)]u8 = undefined; _ = encoder.encode(&expected, &bytes); try expectWritten(&expected, writeBase64, &bytes); } test "base32hex, as RFC 4648 section 10 gives it" { // The RFC's vectors, with the padding taken off as RFC 5155 requires. try expectWritten("", writeBase32Hex, ""); try expectWritten("CO", writeBase32Hex, "f"); try expectWritten("CPNG", writeBase32Hex, "fo"); try expectWritten("CPNMU", writeBase32Hex, "foo"); try expectWritten("CPNMUOG", writeBase32Hex, "foob"); try expectWritten("CPNMUOJ1", writeBase32Hex, "fooba"); try expectWritten("CPNMUOJ1E8", writeBase32Hex, "foobar"); } test "character-strings are quoted and escaped" { try expectWritten("\"hello\"", writeCharacterString, "hello"); try expectWritten("\"a\\\"b\"", writeCharacterString, "a\"b"); try expectWritten("\"a\\\\b\"", writeCharacterString, "a\\b"); try expectWritten("\"\\009\"", writeCharacterString, "\t"); } test "unknown rdata uses the RFC 3597 syntax" { try expectWritten("\\# 3 01020F", writeUnknownRdata, "\x01\x02\x0f"); try expectWritten("\\# 0", writeUnknownRdata, ""); }