// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What a record actually holds, once you know its type. //! //! `Data` is one tagged union over every type this library understands, and //! `unknown` for the rest. That last variant is not a failure case: RFC 3597 //! requires a resolver to carry a type it has never heard of, byte for byte, //! so that a new record type does not need every server between its zone and //! its user to be upgraded first. A record whose data this library cannot name //! still decodes, still compares, still re-encodes exactly, and still prints //! -- as `\# 12 0102...`, the syntax RFC 3597 §5 defines for saying "these //! bytes, and no opinion about them". //! //! Every variant borrows the message it was read from. Nothing here allocates, //! and nothing survives the buffer. const std = @import("std"); const Writer = std.Io.Writer; const z46 = @import("z46"); const Builder = @import("Builder.zig"); const Name = @import("Name.zig"); const edns = @import("edns.zig"); const presentation = @import("presentation.zig"); const types = @import("types.zig"); const wire = @import("wire.zig"); const Type = types.Type; const Decoder = wire.Decoder; pub const dnssec = @import("rdata/dnssec.zig"); /// The types that were tried and not kept. pub const legacy = @import("rdata/legacy.zig"); /// Keys and certificates published in the DNS for use somewhere else. pub const security = @import("rdata/security.zig"); pub const svcb = @import("rdata/svcb.zig"); pub const Ds = dnssec.Ds; pub const Dnskey = dnssec.Dnskey; pub const Rrsig = dnssec.Rrsig; pub const Nsec = dnssec.Nsec; pub const Nsec3 = dnssec.Nsec3; pub const Nsec3param = dnssec.Nsec3param; pub const Sshfp = dnssec.Sshfp; pub const Tlsa = dnssec.Tlsa; pub const TypeBitmap = dnssec.TypeBitmap; pub const Csync = dnssec.Csync; pub const Zonemd = dnssec.Zonemd; pub const Svcb = svcb.Svcb; pub const Cert = security.Cert; pub const Gateway = security.Gateway; pub const Ipseckey = security.Ipseckey; pub const Amtrelay = security.Amtrelay; pub const Hip = security.Hip; pub const Tkey = security.Tkey; pub const Blob = security.Blob; pub const Opaque = legacy.Opaque; pub const Wks = legacy.Wks; pub const PrefixedName = legacy.PrefixedName; pub const Px = legacy.Px; pub const X25 = legacy.X25; pub const Isdn = legacy.Isdn; pub const Gpos = legacy.Gpos; pub const Nsap = legacy.Nsap; pub const Loc = legacy.Loc; pub const Nxt = legacy.Nxt; pub const A6 = legacy.A6; pub const Apl = legacy.Apl; pub const Error = wire.Error || error{ /// The record data is not the shape its type requires. MalformedRdata, /// The type is one that never has record data -- `any`, `axfr`, `ixfr`, /// `maila`, `mailb`, `nxname`. There is no such record, so there is no /// data to decode; see `types.Type.isRecordless`. RecordlessType, /// The data was longer than the type needs. A record's length field and /// its type have to agree, and when they do not there is no way to tell /// which one to believe. TrailingRdata, }; /// The start of authority: the record that says a zone begins here. pub const Soa = struct { /// The primary server for the zone -- where the zone is edited, which is /// not necessarily any of the servers the `ns` records name. mname: Name, /// The mailbox of whoever is responsible, with the `@` written as a dot, /// so `hostmaster@example.com` is `hostmaster.example.com`. A first label /// containing an escaped dot is how an address with one is written. rname: Name, /// The version of the zone. A secondary transfers the zone again when this /// goes up, compared as a serial number (RFC 1982) rather than as an /// integer, so that it can wrap. serial: u32, /// How often a secondary should check the serial. refresh: u32, /// How long to wait before checking again after a check failed. retry: u32, /// How long a secondary may keep serving the zone when it cannot reach the /// primary at all. After this it stops answering, which is the one timer /// here that can take a domain off the internet. expire: u32, /// Originally the default TTL for the zone; since RFC 2308 it is how long /// a denial of existence may be cached, which is a different thing that /// happens to live in the same field. minimum: u32, /// Reads the two names and the five counters. `soa` is one of RFC 1035's /// own types, so either name may be a compression pointer, and both are /// followed. pub fn parse(d: *Decoder) Error!Soa { return .{ .mname = try d.name(), .rname = try d.name(), .serial = try d.int(u32), .refresh = try d.int(u32), .retry = try d.int(u32), .expire = try d.int(u32), .minimum = try d.int(u32), }; } test parse { // The responsible mailbox ends in a pointer back to `example.com.`. var d = try Decoder.init("\x03ns1\x07example\x03com\x00" ++ "\x0ahostmaster\xc0\x04" ++ "\x00\x00\x00\x01\x00\x00\x1c\x20\x00\x00\x0e\x10\x00\x12\x75\x00\x00\x00\x01\x2c"); const soa = try Soa.parse(&d); try testing.expectFmt("hostmaster.example.com.", "{f}", .{soa.rname}); try testing.expectEqual(@as(u32, 1), soa.serial); } /// Writes both names compressed when the builder compresses, which RFC /// 1035 allows for its own types, and then the five counters. pub fn writeTo(self: Soa, b: *Builder) Builder.Error!void { try b.name(self.mname, .compressed); try b.name(self.rname, .compressed); try b.int(u32, self.serial); try b.int(u32, self.refresh); try b.int(u32, self.retry); try b.int(u32, self.expire); try b.int(u32, self.minimum); } test writeTo { const soa: Soa = .{ .mname = Name.literal("ns1.example.com."), .rname = Name.literal("hostmaster.example.com."), .serial = 1, .refresh = 7200, .retry = 3600, .expire = 1209600, .minimum = 300, }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{}); try soa.writeTo(&b); // The second name ends in a pointer to the `example.com.` of the first, // which starts after the twelve bytes of header and four of `ns1`. try testing.expectEqualSlices( u8, "\x03ns1\x07example\x03com\x00" ++ "\x0ahostmaster\xc0\x10" ++ "\x00\x00\x00\x01\x00\x00\x1c\x20\x00\x00\x0e\x10\x00\x12\x75\x00\x00\x00\x01\x2c", b.buffer[12..b.pos], ); } /// As a zone file writes it, on one line: the two names and then the /// counters as plain numbers, in the order they are sent. pub fn format(self: Soa, w: *Writer) Writer.Error!void { try w.print("{f} {f} {d} {d} {d} {d} {d}", .{ self.mname, self.rname, self.serial, self.refresh, self.retry, self.expire, self.minimum, }); } test format { const soa: Soa = .{ .mname = Name.literal("ns1.example.com."), .rname = Name.literal("hostmaster.example.com."), .serial = 1, .refresh = 7200, .retry = 3600, .expire = 1209600, .minimum = 300, }; try testing.expectFmt( "ns1.example.com. hostmaster.example.com. 1 7200 3600 1209600 300", "{f}", .{soa}, ); } }; /// Where to deliver mail for a name, and in what order to try. pub const Mx = struct { /// Lower is tried first. Equal preferences are to be tried in a random /// order, which is the only load balancing the DNS ever specified. preference: u16, exchange: Name, /// Reads the preference and the exchange, following a compression /// pointer in the exchange since `mx` is one of RFC 1035's own types. pub fn parse(d: *Decoder) Error!Mx { return .{ .preference = try d.int(u16), .exchange = try d.name() }; } test parse { var d = try Decoder.init("\x00\x0a\x04mail\x07example\x03com\x00"); const mx = try Mx.parse(&d); try testing.expectEqual(@as(u16, 10), mx.preference); try testing.expectFmt("mail.example.com.", "{f}", .{mx.exchange}); } /// Writes the preference and the exchange, compressed when the builder /// compresses. pub fn writeTo(self: Mx, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.name(self.exchange, .compressed); } test writeTo { const mx: Mx = .{ .preference = 10, .exchange = Name.literal("mail.example.com.") }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try mx.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x0a\x04mail\x07example\x03com\x00", b.buffer[12..b.pos]); } /// The preference and then the exchange, as a zone file writes them. pub fn format(self: Mx, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.preference, self.exchange }); } test format { const mx: Mx = .{ .preference = 10, .exchange = Name.literal("mail.example.com.") }; try testing.expectFmt("10 mail.example.com.", "{f}", .{mx}); } }; /// Text: one or more character-strings. /// /// The pieces are an artifact of the encoding rather than of the meaning -- /// a length byte can only count to 255, so a longer value arrives split, and /// every specification built on `txt` says to join them back together with /// nothing in between. The two variants exist so that reading gives back /// exactly the bytes that arrived while writing can be handed the strings. pub const Txt = union(enum) { /// The character-strings in wire form, length bytes and all, as they were /// read. Checked when parsed, so iterating one never fails. encoded: []const u8, /// The strings on their own, each to be written with a length byte in /// front. None may be longer than 255 bytes. strings: []const []const u8, /// Takes the rest of the record data as character-strings, refusing it as /// `MalformedRdata` when there are none at all or when a length byte runs /// past the end. pub fn parse(d: *Decoder) Error!Txt { const bytes = d.takeRest(); // RFC 1035 section 3.3.14 asks for one or more. An empty string is // one; no strings at all is not a record of this shape, and SPF, // NINFO, AVC, RESINFO and WALLET all borrow the shape. if (bytes.len == 0) return error.MalformedRdata; var i: usize = 0; while (i < bytes.len) { i += 1 + @as(usize, bytes[i]); if (i > bytes.len) return error.MalformedRdata; } return .{ .encoded = bytes }; } test parse { var d = try Decoder.init("\x05hello\x05world"); const txt = try Txt.parse(&d); try testing.expectEqualStrings("\x05hello\x05world", txt.encoded); // No strings at all is not a `txt`, though one empty string is. var empty = try Decoder.init(""); try testing.expectError(error.MalformedRdata, Txt.parse(&empty)); } /// Walks the strings of either variant, without their length bytes. pub const Iterator = struct { txt: Txt, pos: usize = 0, /// The next string, or `null` after the last. pub fn next(self: *Iterator) ?[]const u8 { switch (self.txt) { .encoded => |bytes| { if (self.pos >= bytes.len) return null; const length = bytes[self.pos]; const start = self.pos + 1; const end = start + length; if (end > bytes.len) return null; self.pos = end; return bytes[start..end]; }, .strings => |strings| { if (self.pos >= strings.len) return null; defer self.pos += 1; return strings[self.pos]; }, } } test next { const txt: Txt = .{ .encoded = "\x05hello\x00\x05world" }; var it = txt.iterator(); try testing.expectEqualStrings("hello", it.next().?); try testing.expectEqualStrings("", it.next().?); try testing.expectEqualStrings("world", it.next().?); try testing.expectEqual(@as(?[]const u8, null), it.next()); } }; /// The strings one at a time, whichever variant holds them. pub fn iterator(self: Txt) Iterator { return .{ .txt = self }; } test iterator { // A long value arrives split, and is joined back with nothing between. const txt: Txt = .{ .strings = &.{ "v=DKIM1; k=rsa; ", "p=MIIBIjAN" } }; var joined: [64]u8 = undefined; var len: usize = 0; var it = txt.iterator(); while (it.next()) |s| { @memcpy(joined[len..][0..s.len], s); len += s.len; } try testing.expectEqualStrings("v=DKIM1; k=rsa; p=MIIBIjAN", joined[0..len]); } /// The first string, which for the many uses of `txt` that fit in 255 /// bytes is the whole value. pub fn first(self: Txt) ?[]const u8 { var it = self.iterator(); return it.next(); } test first { var d = try Decoder.init("\x0bv=spf1 -all"); const txt = try Txt.parse(&d); try testing.expectEqualStrings("v=spf1 -all", txt.first().?); } /// Writes the strings back as character-strings. `encoded` goes out as it /// came in; each of `strings` gets a length byte, and one longer than 255 /// bytes is `error.RdataTooLong`. pub fn writeTo(self: Txt, b: *Builder) Builder.Error!void { switch (self) { .encoded => |bytes| try b.writeAll(bytes), .strings => |strings| for (strings) |s| try b.characterString(s), } } test writeTo { const txt: Txt = .{ .strings = &.{ "hello", "world" } }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try txt.writeTo(&b); try testing.expectEqualSlices(u8, "\x05hello\x05world", b.buffer[12..b.pos]); } /// Each string quoted, separated by spaces, with quotes, backslashes and /// anything unprintable escaped. pub fn format(self: Txt, w: *Writer) Writer.Error!void { var it = self.iterator(); var first_one = true; while (it.next()) |s| { if (!first_one) try w.writeByte(' '); first_one = false; try presentation.writeCharacterString(w, s); } } test format { const txt: Txt = .{ .strings = &.{ "say \"hi\"", "bye\n" } }; try testing.expectFmt("\"say \\\"hi\\\"\" \"bye\\010\"", "{f}", .{txt}); } }; /// The CPU and operating system of a host, as text. RFC 1035 meant it to be /// drawn from a registry of machine names; what it is used for now is a /// machine-readable comment. pub const Hinfo = struct { cpu: []const u8, os: []const u8, /// Reads the two character-strings, and nothing else may follow them. pub fn parse(d: *Decoder) Error!Hinfo { return .{ .cpu = try d.characterString(), .os = try d.characterString() }; } test parse { var d = try Decoder.init("\x05amd64\x05linux"); const hinfo = try Hinfo.parse(&d); try testing.expectEqualStrings("amd64", hinfo.cpu); try testing.expectEqualStrings("linux", hinfo.os); } /// Writes each as a character-string; one longer than 255 bytes is /// `error.RdataTooLong`. pub fn writeTo(self: Hinfo, b: *Builder) Builder.Error!void { try b.characterString(self.cpu); try b.characterString(self.os); } test writeTo { const hinfo: Hinfo = .{ .cpu = "amd64", .os = "linux" }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try hinfo.writeTo(&b); try testing.expectEqualSlices(u8, "\x05amd64\x05linux", b.buffer[12..b.pos]); } /// The two strings, quoted and escaped the way `txt` writes them. pub fn format(self: Hinfo, w: *Writer) Writer.Error!void { try presentation.writeCharacterString(w, self.cpu); try w.writeByte(' '); try presentation.writeCharacterString(w, self.os); } test format { const hinfo: Hinfo = .{ .cpu = "amd64", .os = "Debian GNU/Linux" }; try testing.expectFmt("\"amd64\" \"Debian GNU/Linux\"", "{f}", .{hinfo}); } }; /// Two names: used by `minfo` for the mailboxes of a mailing list, and by `rp` /// for who is responsible for a host and where to read more about them. pub const NamePair = struct { first: Name, second: Name, /// Reads the two names, following compression pointers in either: `minfo` /// is one of RFC 1035's own types, and RFC 3597 §4 asks a reader to /// decompress `rp` as well. pub fn parse(d: *Decoder) Error!NamePair { return .{ .first = try d.name(), .second = try d.name() }; } test parse { // An `rp` whose second name points back into its first. var d = try Decoder.init("\x05admin\x07example\x03com\x00" ++ "\x04info\xc0\x06"); const rp = try NamePair.parse(&d); try testing.expectFmt("admin.example.com.", "{f}", .{rp.first}); try testing.expectFmt("info.example.com.", "{f}", .{rp.second}); } /// Writes both names. `how` is the type's: `minfo` is one of RFC 1035's /// own types and may be compressed, and RFC 3597 §4 forbids compressing /// `rp`'s, though it asks a reader to follow a pointer there anyway. pub fn writeTo(self: NamePair, b: *Builder, how: Builder.Compressibility) Builder.Error!void { try b.name(self.first, how); try b.name(self.second, how); } test writeTo { const pair: NamePair = .{ .first = Name.literal("admin.example.com."), .second = Name.literal("info.example.com."), }; // As an `rp`: written out in full, even with compression on. var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{}); try pair.writeTo(&b, .uncompressed); try testing.expectEqualSlices( u8, "\x05admin\x07example\x03com\x00" ++ "\x04info\x07example\x03com\x00", b.buffer[12..b.pos], ); // As a `minfo`: the second name points back into the first. b = try Builder.init(&buf, .{ .id = 0 }, .{}); try pair.writeTo(&b, .compressed); try testing.expectEqualSlices( u8, "\x05admin\x07example\x03com\x00" ++ "\x04info\xc0\x12", b.buffer[12..b.pos], ); } /// The two names, separated by a space. pub fn format(self: NamePair, w: *Writer) Writer.Error!void { try w.print("{f} {f}", .{ self.first, self.second }); } test format { const rp: NamePair = .{ .first = Name.literal("admin.example.com."), .second = Name.literal("info.example.com."), }; try testing.expectFmt("admin.example.com. info.example.com.", "{f}", .{rp}); } }; /// Where a service is: the host and port, with a priority and a weight, for a /// named protocol under a name like `_sip._tcp.example.com`. pub const Srv = struct { /// Lower is tried first, and every server at one priority must be tried /// before any at the next. priority: u16, /// Within one priority, the share of the load: a server with twice the /// weight should get twice the traffic. weight: u16, port: u16, /// The root means the service is explicitly not offered here, which is a /// thing no other record type can say. target: Name, /// Reads the three numbers and the target. RFC 2782 says the target is /// never compressed, but RFC 3597 §4 asks a reader to follow a pointer /// there anyway, so one is. pub fn parse(d: *Decoder) Error!Srv { return .{ .priority = try d.int(u16), .weight = try d.int(u16), .port = try d.int(u16), .target = try d.name(), }; } test parse { var d = try Decoder.init("\x00\x01\x00\x00\x14\x51\x04sip1\x07example\x03com\x00"); const srv = try Srv.parse(&d); try testing.expectEqual(@as(u16, 5201), srv.port); try testing.expectFmt("sip1.example.com.", "{f}", .{srv.target}); } /// Writes the three numbers and the target, which is never compressed. pub fn writeTo(self: Srv, b: *Builder) Builder.Error!void { try b.int(u16, self.priority); try b.int(u16, self.weight); try b.int(u16, self.port); // RFC 2782: "Name compression is not to be used for this field." try b.name(self.target, .uncompressed); } test writeTo { const srv: Srv = .{ .priority = 1, .weight = 0, .port = 5201, .target = Name.literal("sip1.example.com."), }; const once = "\x00\x01\x00\x00\x14\x51\x04sip1\x07example\x03com\x00"; // Twice into a builder that compresses, and the target is spelled out // in full both times. var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{}); try srv.writeTo(&b); try srv.writeTo(&b); try testing.expectEqualSlices(u8, once ++ once, b.buffer[12..b.pos]); } /// Priority, weight, port and target, as a zone file writes them. pub fn format(self: Srv, w: *Writer) Writer.Error!void { try w.print("{d} {d} {d} {f}", .{ self.priority, self.weight, self.port, self.target }); } test format { const srv: Srv = .{ .priority = 1, .weight = 0, .port = 5201, .target = Name.literal("sip1.example.com."), }; try testing.expectFmt("1 0 5201 sip1.example.com.", "{f}", .{srv}); } }; /// A rewrite rule: take the name that was asked for, apply the regular /// expression, and look up whatever comes out. The mechanism behind ENUM, and /// behind SIP's service discovery. pub const Naptr = struct { order: u16, preference: u16, /// What to do with the result: `U` means the regular expression yields a /// URI and the lookup stops, `S` means it yields a name to look up as a /// `srv`. flags: []const u8, services: []const u8, /// Applied to the name that was queried. Empty when `replacement` is used /// instead; a record may have one or the other and not both. regexp: []const u8, replacement: Name, /// Reads the two numbers, the three character-strings and the /// replacement. RFC 3403 says the replacement is never compressed, but RFC /// 3597 §4 asks a reader to follow a pointer there anyway, so one is. /// Whether `regexp` and `replacement` are both set is not checked. pub fn parse(d: *Decoder) Error!Naptr { return .{ .order = try d.int(u16), .preference = try d.int(u16), .flags = try d.characterString(), .services = try d.characterString(), .regexp = try d.characterString(), .replacement = try d.name(), }; } test parse { var d = try Decoder.init("\x00\x64\x00\x0a\x01S\x07SIP+D2U\x00" ++ "\x04_sip\x04_udp\x07example\x03com\x00"); const naptr = try Naptr.parse(&d); try testing.expectEqualStrings("SIP+D2U", naptr.services); try testing.expectFmt("_sip._udp.example.com.", "{f}", .{naptr.replacement}); } /// Writes the fields in order, with the replacement never compressed. pub fn writeTo(self: Naptr, b: *Builder) Builder.Error!void { try b.int(u16, self.order); try b.int(u16, self.preference); try b.characterString(self.flags); try b.characterString(self.services); try b.characterString(self.regexp); // RFC 3403 section 4.1: not compressed. try b.name(self.replacement, .uncompressed); } test writeTo { const naptr: Naptr = .{ .order = 100, .preference = 10, .flags = "S", .services = "SIP+D2U", .regexp = "", .replacement = Name.literal("_sip._udp.example.com."), }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try naptr.writeTo(&b); try testing.expectEqualSlices( u8, "\x00\x64\x00\x0a\x01S\x07SIP+D2U\x00" ++ "\x04_sip\x04_udp\x07example\x03com\x00", b.buffer[12..b.pos], ); } /// The two numbers, the three strings quoted, and the replacement -- with /// an empty `regexp` written as `""` so that the field count stays fixed. pub fn format(self: Naptr, w: *Writer) Writer.Error!void { try w.print("{d} {d} ", .{ self.order, self.preference }); try presentation.writeCharacterString(w, self.flags); try w.writeByte(' '); try presentation.writeCharacterString(w, self.services); try w.writeByte(' '); try presentation.writeCharacterString(w, self.regexp); try w.print(" {f}", .{self.replacement}); } test format { const naptr: Naptr = .{ .order = 100, .preference = 10, .flags = "S", .services = "SIP+D2U", .regexp = "", .replacement = Name.literal("_sip._udp.example.com."), }; try testing.expectFmt("100 10 \"S\" \"SIP+D2U\" \"\" _sip._udp.example.com.", "{f}", .{naptr}); } }; /// Which certification authorities may issue certificates for a name. The one /// record type whose audience is not a resolver: it is read by the authority /// at issuance time, and ignored by everything else. pub const Caa = struct { /// Bit 7 is the critical flag: an authority that does not understand the /// tag must refuse to issue rather than ignore the record. flags: u8, /// `issue`, `issuewild`, `iodef`, `contactemail`, `contactphone`. tag: []const u8, /// What the tag means, which for `issue` is the authority's domain. value: []const u8, /// Whether the critical flag is set, which is what tells an authority /// that does not know `tag` to refuse rather than carry on. pub fn isCritical(self: Caa) bool { return self.flags & 0x80 != 0; } test isCritical { const caa: Caa = .{ .flags = 0x80, .tag = "tbs", .value = "unknown" }; try testing.expect(caa.isCritical()); } /// The longest a tag may be (RFC 8659 §4.1). pub const max_tag_len = 15; /// Whether `tag` is one RFC 8659 §4.1 allows: one to fifteen ASCII /// letters and digits. Which tags mean something is a registry's /// business; what one may be spelled with is not. pub fn isValidTag(tag: []const u8) bool { if (tag.len == 0 or tag.len > max_tag_len) return false; for (tag) |c| if (!std.ascii.isAlphanumeric(c)) return false; return true; } test isValidTag { try testing.expect(isValidTag("issuewild")); // A tag nobody has registered is still a tag. try testing.expect(isValidTag("future2")); try testing.expect(!isValidTag("issue-wild")); try testing.expect(!isValidTag("")); } /// Reads the flags, the tag and the value, refusing as `MalformedRdata` a /// tag that `isValidTag` would not accept. The value is the rest of the /// data and not a character-string, so it has no length of its own. pub fn parse(d: *Decoder) Error!Caa { const flags = try d.int(u8); const tag = try d.characterString(); if (!isValidTag(tag)) return error.MalformedRdata; return .{ .flags = flags, .tag = tag, .value = d.takeRest() }; } test parse { var d = try Decoder.init("\x00\x05issueletsencrypt.org"); const caa = try Caa.parse(&d); try testing.expectEqualStrings("issue", caa.tag); try testing.expectEqualStrings("letsencrypt.org", caa.value); // A tag with a space in it is not one. var bad = try Decoder.init("\x00\x06is sue"); try testing.expectError(error.MalformedRdata, Caa.parse(&bad)); } /// Writes the flags, the tag as a character-string and the value as it /// is. The tag is not checked here, so one built by hand goes out as it /// was given. pub fn writeTo(self: Caa, b: *Builder) Builder.Error!void { try b.int(u8, self.flags); try b.characterString(self.tag); try b.writeAll(self.value); } test writeTo { const caa: Caa = .{ .flags = 0, .tag = "issue", .value = "letsencrypt.org" }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try caa.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x05issueletsencrypt.org", b.buffer[12..b.pos]); } /// The flags as a number, the tag bare, and the value quoted. Anything in /// the tag that is not a letter or a digit is written as a `\DDD` escape. pub fn format(self: Caa, w: *Writer) Writer.Error!void { try w.print("{d} ", .{self.flags}); // A decoded tag is letters and digits, but one built by hand need not // be, and printing whatever it holds would let it say anything at all // to whoever is reading -- a newline, a terminal escape. for (self.tag) |c| { if (std.ascii.isAlphanumeric(c)) { try w.writeByte(c); } else { try w.print("\\{d:0>3}", .{c}); } } try w.writeByte(' '); try presentation.writeCharacterString(w, self.value); } test format { const caa: Caa = .{ .flags = 0, .tag = "issue", .value = "letsencrypt.org" }; try testing.expectFmt("0 issue \"letsencrypt.org\"", "{f}", .{caa}); } }; /// A URI, with a priority and a weight like `srv` but pointing at something /// that is not necessarily a host. pub const Uri = struct { priority: u16, weight: u16, /// The URI itself, which is the rest of the data: not a character-string, /// so it is not limited to 255 bytes. target: []const u8, /// Reads the priority, the weight and the target, refusing as /// `MalformedRdata` a record whose target is empty. pub fn parse(d: *Decoder) Error!Uri { const priority = try d.int(u16); const weight = try d.int(u16); const target = d.takeRest(); // RFC 7553 section 4.5: the target must not be empty. A record that // points at nothing is not a shorter way of saying anything. if (target.len == 0) return error.MalformedRdata; return .{ .priority = priority, .weight = weight, .target = target }; } test parse { var d = try Decoder.init("\x00\x0a\x00\x01https://example.com/"); const uri = try Uri.parse(&d); try testing.expectEqualStrings("https://example.com/", uri.target); var empty = try Decoder.init("\x00\x0a\x00\x01"); try testing.expectError(error.MalformedRdata, Uri.parse(&empty)); } /// Writes the priority, the weight and the target, the target with no /// length in front of it. pub fn writeTo(self: Uri, b: *Builder) Builder.Error!void { try b.int(u16, self.priority); try b.int(u16, self.weight); try b.writeAll(self.target); } test writeTo { const uri: Uri = .{ .priority = 10, .weight = 1, .target = "https://example.com/" }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try uri.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x0a\x00\x01https://example.com/", b.buffer[12..b.pos]); } /// The two numbers and then the target, quoted as RFC 7553 writes it. pub fn format(self: Uri, w: *Writer) Writer.Error!void { try w.print("{d} {d} ", .{ self.priority, self.weight }); try presentation.writeCharacterString(w, self.target); } test format { const uri: Uri = .{ .priority = 10, .weight = 1, .target = "https://example.com/" }; try testing.expectFmt("10 1 \"https://example.com/\"", "{f}", .{uri}); } }; /// A transaction signature: authentication of one message by a shared secret /// (RFC 8945). /// /// Like `opt`, this is not really a record. It is added last, it covers the /// message in front of it, it is stripped before the message is processed, and /// its owner name is the key's name rather than anything being asked about. /// Unlike `opt`, it is what protects a zone transfer and a dynamic update, so /// getting it wrong is not a missing feature but an open door. /// /// Nothing here computes or checks a MAC. That needs the shared secret and the /// exact bytes of the message as it was sent -- which is why a `Message` keeps /// the buffer it was read from, and why `Builder` will not compress a name in /// here. pub const Tsig = struct { /// The keyed hash used, as a name: `hmac-sha256.` and friends. algorithm: Name, /// When the message was signed, as seconds since the Unix epoch, in /// **forty-eight** bits -- which is the one field in DNS with no year 2106 /// problem. time_signed: u48, /// How far either side of `time_signed` the receiver should still accept, /// in seconds. Small, because the point is to stop a replay. fudge: u16, /// The hash itself. mac: []const u8, /// The identifier the message had before it was signed, since a forwarder /// may have changed the header's. original_id: u16, /// Why verification failed, when a server is answering with one of these /// to say so. Sixteen bits wide rather than the twelve a response code /// has, so it is kept as a number; `signatureError` reads it in the /// registry it belongs to, which is not the response code one. error_code: u16, /// Present only when `error_code` is `badtime`, where it carries the /// server's own clock so that the requestor can tell which of them is /// wrong. other: []const u8, /// What a receiver says went wrong, which is *not* the response code /// registry however much it looks like one. /// /// The two registries were assigned 16 independently -- `badvers` in the /// one a header carries, `badsig` here -- and RFC 6895 §2.3 records the /// collision rather than resolving it. So a TSIG error read through /// `types.ResponseCode` answers `badvers` for a signature that did not /// verify, which is the wrong word for the wrong problem in the one field /// where being wrong is a security question. pub const ErrorCode = enum(u16) { /// Nothing went wrong, which is what every signed message that is not /// a complaint carries. noerror = 0, /// The signature did not verify. badsig = 16, /// The key name is one the receiver does not know. badkey = 17, /// The signature was outside the time window, and `other` then carries /// the receiver's own clock so that the two ends can tell which of /// them is wrong. badtime = 18, /// A TKEY mode was not understood (RFC 2930). badmode = 19, /// A duplicate key name. badname = 20, /// The algorithm is one the receiver does not implement. badalg = 21, /// The MAC was truncated further than the receiver will accept. badtrunc = 22, _, }; /// `error_code` read in the registry it belongs to. Non-exhaustive, so a /// number nobody has assigned comes back as itself rather than as an /// error. pub fn signatureError(self: Tsig) ErrorCode { return @fromBackingInt(self.error_code); } test signatureError { var tsig: Tsig = .{ .algorithm = Name.literal("hmac-sha256."), .time_signed = 1789421696, .fudge = 300, .mac = "\xde\xad\xbe\xef", .original_id = 0x1234, .error_code = 0, .other = "", }; tsig.error_code = 16; // Sixteen is a bad signature here, whatever a header's 16 means. try testing.expectEqual(ErrorCode.badsig, tsig.signatureError()); } /// Reads every field, each length-prefixed one by its own length. The /// algorithm name is never compressed, and a pointer there is /// `error.CompressionForbidden`. pub fn parse(d: *Decoder) Error!Tsig { const algorithm = try d.uncompressedName(); const high = try d.int(u16); const low = try d.int(u32); const fudge = try d.int(u16); const mac_len = try d.int(u16); const mac = try d.take(mac_len); const original_id = try d.int(u16); const error_code = try d.int(u16); const other_len = try d.int(u16); return .{ .algorithm = algorithm, .time_signed = @as(u48, high) << 32 | low, .fudge = fudge, .mac = mac, .original_id = original_id, .error_code = error_code, .other = try d.take(other_len), }; } test parse { var d = try Decoder.init("\x0bhmac-sha256\x00" ++ "\x00\x00\x6a\xa8\x68\x80" ++ "\x01\x2c" ++ "\x00\x04\xde\xad\xbe\xef" ++ "\x12\x34" ++ "\x00\x00" ++ "\x00\x00"); const tsig = try Tsig.parse(&d); try testing.expectEqual(@as(u48, 1789421696), tsig.time_signed); try testing.expectEqualSlices(u8, "\xde\xad\xbe\xef", tsig.mac); } /// Writes every field, the algorithm name never compressed. A MAC or an /// `other` longer than its sixteen-bit length can say is /// `error.RdataTooLong`. pub fn writeTo(self: Tsig, b: *Builder) Builder.Error!void { try b.name(self.algorithm, .uncompressed); try b.int(u16, @intCast(self.time_signed >> 32)); try b.int(u32, @truncate(self.time_signed)); try b.int(u16, self.fudge); if (self.mac.len > std.math.maxInt(u16)) return error.RdataTooLong; try b.int(u16, @intCast(self.mac.len)); try b.writeAll(self.mac); try b.int(u16, self.original_id); try b.int(u16, self.error_code); if (self.other.len > std.math.maxInt(u16)) return error.RdataTooLong; try b.int(u16, @intCast(self.other.len)); try b.writeAll(self.other); } test writeTo { const tsig: Tsig = .{ .algorithm = Name.literal("hmac-sha256."), .time_signed = 1789421696, .fudge = 300, .mac = "\xde\xad\xbe\xef", .original_id = 0x1234, .error_code = 0, .other = "", }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try tsig.writeTo(&b); try testing.expectEqualSlices( u8, "\x0bhmac-sha256\x00" ++ "\x00\x00\x6a\xa8\x68\x80" ++ "\x01\x2c" ++ "\x00\x04\xde\xad\xbe\xef" ++ "\x12\x34" ++ "\x00\x00" ++ "\x00\x00", b.buffer[12..b.pos], ); } /// The fields in wire order, each binary one as its length and then its /// base64, with `other` left off when it is empty. pub fn format(self: Tsig, w: *Writer) Writer.Error!void { try w.print("{f} {d} {d} {d} ", .{ self.algorithm, self.time_signed, self.fudge, self.mac.len, }); try presentation.writeBase64(w, self.mac); try w.print(" {d} {d} {d}", .{ self.original_id, self.error_code, self.other.len }); if (self.other.len > 0) { try w.writeByte(' '); try presentation.writeBase64(w, self.other); } } test format { const tsig: Tsig = .{ .algorithm = Name.literal("hmac-sha256."), .time_signed = 1789421696, .fudge = 300, .mac = "\xde\xad\xbe\xef", .original_id = 0x1234, .error_code = 0, .other = "", }; try testing.expectFmt("hmac-sha256. 1789421696 300 4 3q2+7w== 4660 0 0", "{f}", .{tsig}); } }; /// A 48-bit or 64-bit MAC address, published so that a name can be resolved /// to the hardware behind it. `Eui48` and `Eui64` differ only in length. fn Eui(comptime len: usize) type { return struct { const Self = @This(); address: [len]u8, /// Reads the address, which is the whole of the data. pub fn parse(d: *Decoder) Error!Self { return .{ .address = (try d.take(len))[0..len].* }; } // These run once for `Eui48` and once for `Eui64`, so the examples // take as many bytes as the type in hand wants. const example = "\x00\x00\x5e\x00\x53\x2a\x00\x01"[0..len]; test parse { var d = try Decoder.init(example); const eui = try Self.parse(&d); try testing.expectEqualSlices(u8, example, &eui.address); } /// Writes the address as it is. pub fn writeTo(self: Self, b: *Builder) Builder.Error!void { try b.writeAll(&self.address); } test writeTo { const eui: Self = .{ .address = example.* }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try eui.writeTo(&b); try testing.expectEqualSlices(u8, example, b.buffer[12..b.pos]); } /// Lowercase hexadecimal pairs joined by hyphens, as RFC 7043 writes /// it: `00-00-5e-00-53-2a`. pub fn format(self: Self, w: *Writer) Writer.Error!void { for (self.address, 0..) |byte, i| { if (i != 0) try w.writeByte('-'); try w.print("{x:0>2}", .{byte}); } } test format { const eui: Self = .{ .address = example.* }; const expected = if (len == 6) "00-00-5e-00-53-2a" else "00-00-5e-00-53-2a-00-01"; try testing.expectFmt(expected, "{f}", .{eui}); } }; } pub const Eui48 = Eui(6); pub const Eui64 = Eui(8); /// Sixty-four bits written as four colon-separated groups: the node identifier /// of a `nid` record and the locator of an `l64`, which ILNP (RFC 6742) splits /// an IPv6 address into so that the half saying *who* and the half saying /// *where* can change independently. pub const Locator64 = struct { preference: u16, value: [8]u8, /// Reads the preference and the eight bytes of the value. pub fn parse(d: *Decoder) Error!Locator64 { return .{ .preference = try d.int(u16), .value = (try d.take(8))[0..8].*, }; } test parse { var d = try Decoder.init("\x00\x0a\x00\x14\x4f\xff\xff\x20\xee\x64"); const nid = try Locator64.parse(&d); try testing.expectEqual(@as(u16, 10), nid.preference); try testing.expectEqualSlices(u8, "\x00\x14\x4f\xff\xff\x20\xee\x64", &nid.value); } /// Writes the preference and the value. pub fn writeTo(self: Locator64, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.writeAll(&self.value); } test writeTo { const nid: Locator64 = .{ .preference = 10, .value = "\x00\x14\x4f\xff\xff\x20\xee\x64".* }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try nid.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x0a\x00\x14\x4f\xff\xff\x20\xee\x64", b.buffer[12..b.pos]); } /// The preference, then the value as four groups of four hexadecimal /// digits separated by colons, leading zeros kept, as RFC 6742 writes it. pub fn format(self: Locator64, w: *Writer) Writer.Error!void { try w.print("{d} ", .{self.preference}); var i: usize = 0; while (i < self.value.len) : (i += 2) { if (i != 0) try w.writeByte(':'); try w.print("{x:0>4}", .{std.mem.readInt(u16, self.value[i..][0..2], .big)}); } } test format { const nid: Locator64 = .{ .preference = 10, .value = "\x00\x14\x4f\xff\xff\x20\xee\x64".* }; try testing.expectFmt("10 0014:4fff:ff20:ee64", "{f}", .{nid}); } }; /// A 32-bit ILNP locator, which is shaped like an IPv4 address and written /// like one. pub const Locator32 = struct { preference: u16, value: z46.Ipv4Address, /// Reads the preference and the four bytes of the locator. pub fn parse(d: *Decoder) Error!Locator32 { return .{ .preference = try d.int(u16), .value = .{ .octets = (try d.take(4))[0..4].* }, }; } test parse { var d = try Decoder.init("\x00\x0a\x0a\x01\x02\x00"); const l32 = try Locator32.parse(&d); try testing.expectFmt("10.1.2.0", "{f}", .{l32.value}); } /// Writes the preference and the locator. pub fn writeTo(self: Locator32, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.writeAll(&self.value.octets); } test writeTo { const l32: Locator32 = .{ .preference = 10, .value = .{ .octets = .{ 10, 1, 2, 0 } } }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try l32.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x0a\x0a\x01\x02\x00", b.buffer[12..b.pos]); } /// The preference and then the locator in dotted-quad form. pub fn format(self: Locator32, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.preference, self.value }); } test format { const l32: Locator32 = .{ .preference = 10, .value = .{ .octets = .{ 10, 1, 2, 0 } } }; try testing.expectFmt("10 10.1.2.0", "{f}", .{l32}); } }; /// Where to send a generalized notify (RFC 9859): a child zone saying that if /// you want to tell it about a change of a given type, here is the host and /// port to tell. pub const Dsync = struct { /// The type whose change is being talked about: `cds` or `csync`. type: Type, /// How to say it. 1 is a DNS NOTIFY. scheme: u8, port: u16, target: Name, /// Reads the type, the scheme, the port and the target. A type or scheme /// nobody has assigned is kept as it is. The target is never compressed, /// and a pointer there is `error.CompressionForbidden`. pub fn parse(d: *Decoder) Error!Dsync { return .{ .type = try d.enumeration(Type), .scheme = try d.int(u8), .port = try d.int(u16), .target = try d.uncompressedName(), }; } test parse { var d = try Decoder.init("\x00\x3b\x01\x14\xef\x02ns\x02ex\x00"); const dsync = try Dsync.parse(&d); try testing.expectEqual(Type.cds, dsync.type); try testing.expectEqual(@as(u16, 5359), dsync.port); } /// Writes the fields in order, with the target never compressed. pub fn writeTo(self: Dsync, b: *Builder) Builder.Error!void { try b.int(u16, @backingInt(self.type)); try b.int(u8, self.scheme); try b.int(u16, self.port); try b.name(self.target, .uncompressed); } test writeTo { const dsync: Dsync = .{ .type = .cds, .scheme = 1, .port = 5359, .target = Name.literal("ns.ex.") }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try dsync.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x3b\x01\x14\xef\x02ns\x02ex\x00", b.buffer[12..b.pos]); } /// The type by its mnemonic, then the scheme, the port and the target. pub fn format(self: Dsync, w: *Writer) Writer.Error!void { try w.print("{f} {d} {d} {f}", .{ self.type, self.scheme, self.port, self.target }); } test format { const dsync: Dsync = .{ .type = .cds, .scheme = 1, .port = 5359, .target = Name.literal("ns.ex.") }; try testing.expectFmt("CDS 1 5359 ns.ex.", "{f}", .{dsync}); } }; /// A record of a type this library has no parser for, kept exactly as it /// arrived. See the note at the top of this file about why this matters. /// /// Copying one of these from one message into another is safe, and safe for /// the same reason it exists: RFC 3597 §4 forbids compressing names inside a /// type the sender may not understand, so there can be no pointer in these /// bytes that would mean something different somewhere else. Building one by /// hand around the data of a *known* type is not safe, for exactly that /// reason -- use the variant for the type instead. pub const Unknown = struct { type: Type, bytes: []const u8, /// Writes the bytes exactly as they are. pub fn writeTo(self: Unknown, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); } test writeTo { const unknown: Unknown = .{ .type = @fromBackingInt(65280), .bytes = "\xde\xad\xbe\xef" }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try unknown.writeTo(&b); try testing.expectEqualSlices(u8, "\xde\xad\xbe\xef", b.buffer[12..b.pos]); } /// In RFC 3597 §5's generic form: `\#`, the length, and the bytes in /// uppercase hexadecimal. pub fn format(self: Unknown, w: *Writer) Writer.Error!void { try presentation.writeUnknownRdata(w, self.bytes); } test format { const unknown: Unknown = .{ .type = @fromBackingInt(65280), .bytes = "\xde\xad\xbe\xef" }; try testing.expectFmt("\\# 4 DEADBEEF", "{f}", .{unknown}); } }; /// The data of a record, by type. pub const Data = union(enum) { a: z46.Ipv4Address, aaaa: z46.Ipv6Address, ns: Name, md: Name, mf: Name, cname: Name, mb: Name, mg: Name, mr: Name, ptr: Name, dname: Name, @"nsap-ptr": Name, soa: Soa, minfo: NamePair, rp: NamePair, mx: Mx, txt: Txt, spf: Txt, hinfo: Hinfo, srv: Srv, naptr: Naptr, caa: Caa, uri: Uri, ninfo: Txt, avc: Txt, resinfo: Txt, wallet: Txt, // The types that were tried and not kept; see `legacy`. null: Opaque, unspec: Opaque, wks: Wks, afsdb: PrefixedName, rt: PrefixedName, kx: PrefixedName, lp: PrefixedName, x25: X25, isdn: Isdn, gpos: Gpos, nsap: Nsap, px: Px, loc: Loc, nxt: Nxt, a6: A6, apl: Apl, // Keys and certificates for use somewhere else; see `security`. cert: Cert, ipseckey: Ipseckey, amtrelay: Amtrelay, dhcid: Blob, openpgpkey: Blob, hhit: Blob, brid: Blob, hip: Hip, tkey: Tkey, // The identifier/locator split of ILNP. nid: Locator64, l64: Locator64, l32: Locator32, eui48: Eui48, eui64: Eui64, dsync: Dsync, sshfp: Sshfp, tlsa: Tlsa, smimea: Tlsa, ds: Ds, cds: Ds, dlv: Ds, ta: Ds, dnskey: Dnskey, cdnskey: Dnskey, /// The first attempt at a zone key; the same shape as `dnskey`. key: Dnskey, rrsig: Rrsig, /// The first attempt at a signature; the same shape as `rrsig`. sig: Rrsig, nsec: Nsec, nsec3: Nsec3, nsec3param: Nsec3param, csync: Csync, zonemd: Zonemd, svcb: Svcb, https: Svcb, /// The transaction signature pseudo-record. See `Tsig`. tsig: Tsig, /// The EDNS(0) pseudo-record's options. See `edns`. opt: edns.Options, unknown: Unknown, /// The type number this data belongs to. It comes from the union's own tag /// rather than being carried alongside it, so a record cannot be built /// whose type and data disagree. pub fn recordType(self: Data) Type { return switch (self) { .unknown => |u| u.type, inline else => |_, tag| @field(Type, @tagName(tag)), }; } test recordType { const mx: Data = .{ .mx = .{ .preference = 10, .exchange = Name.literal("mail.example.com.") } }; try testing.expectEqual(Type.mx, mx.recordType()); // `spf` has the shape of `txt`, and is still `spf`. const spf: Data = .{ .spf = .{ .strings = &.{"v=spf1 -all"} } }; try testing.expectEqual(Type.spf, spf.recordType()); } /// Reads the data of a record of type `t`. /// /// `d` must be a decoder whose message has been cut off at the end of this /// record's data -- which is what `Record.rdataDecoder` gives -- so that a /// field claiming more than the record holds is caught here rather than /// silently reading the record after it. Compression pointers still work, /// because they only ever point backwards, but only in a name the type /// allows one in: RFC 1035's own types and the few RFC 3597 §4 asks a /// reader to decompress anyway. Anywhere else a pointer is /// `error.CompressionForbidden`. /// /// Data that breaks a rule of its type's shape is `error.MalformedRdata`, /// data left over once the type has read what it needs is /// `error.TrailingRdata`, and a type that never has data is /// `error.RecordlessType`. A type this library does not know is not an /// error at all: it comes back as `unknown`. /// /// The type decides the shape and the class is not consulted, even though /// RFC 1035 §3.2.1 makes record data class-specific in principle: an `a` /// record in class `ch` is a Chaos address and not an IPv4 one. Nothing /// worth comparing against acts on that -- dnspython registers every type /// class-independently -- and a record whose class says something this /// library has no opinion about still carries that class for a caller who /// does. Decode `Record.class` before trusting `Record.data` if you are /// one of the few programs that will ever see a class other than `in`. pub fn parse(t: Type, d: *Decoder) Error!Data { // A QTYPE names a question, not a record, and `nxname` names neither. // A message carrying one as a record is malformed however plausible // the bytes look, and treating it as opaque data would be carrying // something that cannot exist. if (t.isRecordless()) return error.RecordlessType; const out: Data = switch (t) { .a => .{ .a = .{ .octets = (try d.take(4))[0..4].* } }, .aaaa => .{ .aaaa = .{ .octets = (try d.take(16))[0..16].* } }, .ns => .{ .ns = try d.name() }, .md => .{ .md = try d.name() }, .mf => .{ .mf = try d.name() }, .cname => .{ .cname = try d.name() }, .mb => .{ .mb = try d.name() }, .mg => .{ .mg = try d.name() }, .mr => .{ .mr = try d.name() }, .ptr => .{ .ptr = try d.name() }, // Defined after RFC 1035, and so never compressed (RFC 3597 §4, // RFC 6672 §2.5). .dname => .{ .dname = try d.uncompressedName() }, .@"nsap-ptr" => .{ .@"nsap-ptr" = try d.uncompressedName() }, .soa => .{ .soa = try Soa.parse(d) }, .minfo => .{ .minfo = try NamePair.parse(d) }, .rp => .{ .rp = try NamePair.parse(d) }, .mx => .{ .mx = try Mx.parse(d) }, .txt => .{ .txt = try Txt.parse(d) }, .spf => .{ .spf = try Txt.parse(d) }, .hinfo => .{ .hinfo = try Hinfo.parse(d) }, .srv => .{ .srv = try Srv.parse(d) }, .naptr => .{ .naptr = try Naptr.parse(d) }, .caa => .{ .caa = try Caa.parse(d) }, .uri => .{ .uri = try Uri.parse(d) }, .ninfo => .{ .ninfo = try Txt.parse(d) }, .avc => .{ .avc = try Txt.parse(d) }, .resinfo => .{ .resinfo = try Txt.parse(d) }, .wallet => .{ .wallet = try Txt.parse(d) }, .null => .{ .null = try Opaque.parse(d) }, .unspec => .{ .unspec = try Opaque.parse(d) }, .wks => .{ .wks = try Wks.parse(d) }, // RFC 3597 §4 asks a reader to decompress `afsdb` and `rt`, which // were compressed before anybody said not to; `kx` and `lp` came // later. .afsdb => .{ .afsdb = try PrefixedName.parse(d, .allowed) }, .rt => .{ .rt = try PrefixedName.parse(d, .allowed) }, .kx => .{ .kx = try PrefixedName.parse(d, .forbidden) }, .lp => .{ .lp = try PrefixedName.parse(d, .forbidden) }, .x25 => .{ .x25 = try X25.parse(d) }, .isdn => .{ .isdn = try Isdn.parse(d) }, .gpos => .{ .gpos = try Gpos.parse(d) }, .nsap => .{ .nsap = try Nsap.parse(d) }, .px => .{ .px = try Px.parse(d) }, .loc => .{ .loc = try Loc.parse(d) }, .nxt => .{ .nxt = try Nxt.parse(d) }, .a6 => .{ .a6 = try A6.parse(d) }, .apl => .{ .apl = try Apl.parse(d) }, .cert => .{ .cert = try Cert.parse(d) }, .ipseckey => .{ .ipseckey = try Ipseckey.parse(d) }, .amtrelay => .{ .amtrelay = try Amtrelay.parse(d) }, .dhcid => .{ .dhcid = try Blob.parse(d) }, .openpgpkey => .{ .openpgpkey = try Blob.parse(d) }, .hhit => .{ .hhit = try Blob.parse(d) }, .brid => .{ .brid = try Blob.parse(d) }, .hip => .{ .hip = try Hip.parse(d) }, .tkey => .{ .tkey = try Tkey.parse(d) }, .nid => .{ .nid = try Locator64.parse(d) }, .l64 => .{ .l64 = try Locator64.parse(d) }, .l32 => .{ .l32 = try Locator32.parse(d) }, .eui48 => .{ .eui48 = try Eui48.parse(d) }, .eui64 => .{ .eui64 = try Eui64.parse(d) }, .dsync => .{ .dsync = try Dsync.parse(d) }, .sshfp => .{ .sshfp = try Sshfp.parse(d) }, .tlsa => .{ .tlsa = try Tlsa.parse(d) }, .smimea => .{ .smimea = try Tlsa.parse(d) }, .ds => .{ .ds = try Ds.parse(d) }, .cds => .{ .cds = try Ds.parse(d) }, .dlv => .{ .dlv = try Ds.parse(d) }, .ta => .{ .ta = try Ds.parse(d) }, .dnskey => .{ .dnskey = try Dnskey.parse(d) }, .cdnskey => .{ .cdnskey = try Dnskey.parse(d) }, .key => .{ .key = try Dnskey.parse(d) }, // RFC 3597 §4 asks a reader to decompress `sig`'s signer, and RFC // 4034 §3.1.7 forbids compressing `rrsig`'s. .rrsig => .{ .rrsig = try Rrsig.parse(d, .forbidden) }, .sig => .{ .sig = try Rrsig.parse(d, .allowed) }, .nsec => .{ .nsec = try Nsec.parse(d) }, .nsec3 => .{ .nsec3 = try Nsec3.parse(d) }, .nsec3param => .{ .nsec3param = try Nsec3param.parse(d) }, .csync => .{ .csync = try Csync.parse(d) }, .zonemd => .{ .zonemd = try Zonemd.parse(d) }, .svcb => .{ .svcb = try Svcb.parse(d) }, .https => .{ .https = try Svcb.parse(d) }, .tsig => .{ .tsig = try Tsig.parse(d) }, .opt => .{ .opt = try edns.Options.parse(d) }, else => .{ .unknown = .{ .type = t, .bytes = d.takeRest() } }, }; if (!d.atEnd()) return error.TrailingRdata; return out; } test parse { var d = try Decoder.init("\xc0\x00\x02\x01"); const data = try Data.parse(.a, &d); try testing.expectFmt("192.0.2.1", "{f}", .{data.a}); // A fifth byte is not part of an address, and not ignored either. var long = try Decoder.init("\xc0\x00\x02\x01\x00"); try testing.expectError(error.TrailingRdata, Data.parse(.a, &long)); } /// Writes the data alone, without the length in front of it, which /// `Builder.record` fills in. Names in RFC 1035's own types are compressed /// when the builder compresses; every other name is written in full, as /// RFC 3597 §4 asks. pub fn writeTo(self: Data, b: *Builder) Builder.Error!void { switch (self) { .a => |address| try b.writeAll(&address.octets), .aaaa => |address| try b.writeAll(&address.octets), // The types RFC 1035 defined, whose names may be compressed. .ns, .md, .mf, .cname, .mb, .mg, .mr, .ptr => |n| try b.name(n, .compressed), // RFC 6672 says a `dname` target is not compressed, and RFC 3597 // §4 says the same of everything else defined after RFC 1035. .dname, .@"nsap-ptr" => |n| try b.name(n, .uncompressed), // The one shape shared across that line: `minfo` is RFC 1035's, // `rp` came after. .minfo => |pair| try pair.writeTo(b, .compressed), .rp => |pair| try pair.writeTo(b, .uncompressed), inline else => |value| try value.writeTo(b), } } test writeTo { // A `dname` target is never compressed, even after the same name. const cname: Data = .{ .cname = Name.literal("www.example.com.") }; const dname: Data = .{ .dname = Name.literal("www.example.com.") }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{}); try cname.writeTo(&b); try dname.writeTo(&b); try testing.expectEqualSlices( u8, "\x03www\x07example\x03com\x00" ++ "\x03www\x07example\x03com\x00", b.buffer[12..b.pos], ); } /// The data in the presentation form a zone file uses, which is what makes /// a decoded message recognizable when it is printed. pub fn format(self: Data, w: *Writer) Writer.Error!void { switch (self) { .a => |address| try w.print("{f}", .{address}), .aaaa => |address| try w.print("{f}", .{address}), .ns, .md, .mf, .cname, .mb, .mg, .mr, .ptr, .dname, .@"nsap-ptr", => |n| try w.print("{f}", .{n}), inline else => |value| try w.print("{f}", .{value}), } } test format { const aaaa: Data = .{ .aaaa = .{ .octets = "\x20\x01\x0d\xb8".* ++ @as([11]u8, @splat(0)) ++ "\x01".* } }; try testing.expectFmt("2001:db8::1", "{f}", .{aaaa}); const unknown: Data = .{ .unknown = .{ .type = @fromBackingInt(65280), .bytes = "\x01\x02" } }; try testing.expectFmt("\\# 2 0102", "{f}", .{unknown}); } }; const testing = std.testing; fn expectRoundTrip(t: Type, bytes: []const u8, expected: []const u8) !void { var d = try Decoder.init(bytes); const data = try Data.parse(t, &d); try testing.expectEqual(t, data.recordType()); try testing.expectFmt(expected, "{f}", .{data}); // And it encodes back to the bytes it came from. The buffer starts with a // header's worth of space because that is where a builder starts. var buf: [1024]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try data.writeTo(&b); try testing.expectEqualSlices(u8, bytes, b.buffer[12..b.pos]); } test "addresses" { try expectRoundTrip(.a, "\xc0\x00\x02\x01", "192.0.2.1"); try expectRoundTrip(.aaaa, "\x20\x01\x0d\xb8" ++ @as([11]u8, @splat(0)) ++ "\x01", "2001:db8::1"); } test "a record that is only a name" { try expectRoundTrip(.cname, "\x03www\x07example\x03com\x00", "www.example.com."); try expectRoundTrip(.ptr, "\x00", "."); } test "the start of authority" { try expectRoundTrip( .soa, "\x03ns1\x07example\x03com\x00" ++ "\x0ahostmaster\x07example\x03com\x00" ++ "\x77\x35\x94\x01\x00\x00\x1c\x20\x00\x00\x0e\x10\x00\x36\xee\x80\x00\x00\x01\x2c", "ns1.example.com. hostmaster.example.com. 2000000001 7200 3600 3600000 300", ); } test "text arrives in pieces" { var d = try Decoder.init("\x05hello\x05world"); const data = try Data.parse(.txt, &d); try testing.expectEqualStrings("hello", data.txt.first().?); try testing.expectFmt("\"hello\" \"world\"", "{f}", .{data}); // And writing takes the strings without their lengths. var buf: [64]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{}); const built: Data = .{ .txt = .{ .strings = &.{ "hello", "world" } } }; try built.writeTo(&b); try testing.expectEqualSlices(u8, "\x05hello\x05world", b.buffer[12..b.pos]); } test "a text record holds at least one string" { var empty = try Decoder.init(""); try testing.expectError(error.MalformedRdata, Data.parse(.txt, &empty)); // One empty string is a string. try expectRoundTrip(.txt, "\x00", "\"\""); } test "a text record whose length runs past the end" { var d = try Decoder.init("\x05hel"); try testing.expectError(error.MalformedRdata, Data.parse(.txt, &d)); } test "mail and service records" { try expectRoundTrip(.mx, "\x00\x0a\x04mail\x07example\x03com\x00", "10 mail.example.com."); try expectRoundTrip( .srv, "\x00\x01\x00\x00\x14\x51\x04sip1\x07example\x03com\x00", "1 0 5201 sip1.example.com.", ); try expectRoundTrip(.hinfo, "\x05amd64\x05linux", "\"amd64\" \"linux\""); try expectRoundTrip( .caa, "\x00\x05issue" ++ "letsencrypt.org", "0 issue \"letsencrypt.org\"", ); try expectRoundTrip( .uri, "\x00\x0a\x00\x01https://example.com/", "10 1 \"https://example.com/\"", ); } test "a CAA tag is letters and digits, and prints as no more than that" { for ([_][]const u8{ "\x00\x00", // an empty tag "\x00\x10issueissueissue1", // sixteen letters "\x00\x06is sue", // a space "\x00\x06issue\n", // a newline }) |bytes| { var d = try Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Data.parse(.caa, &d)); } // One built by hand is still escaped on the way out. const built: Caa = .{ .flags = 0, .tag = "is\x1b[2Jsue", .value = "x" }; try testing.expectFmt("0 is\\027\\0912Jsue \"x\"", "{f}", .{built}); } test "a type nobody knows is kept exactly" { const t: Type = @fromBackingInt(65280); try expectRoundTrip(t, "\xde\xad\xbe\xef", "\\# 4 DEADBEEF"); var d = try Decoder.init("\xde\xad\xbe\xef"); const data = try Data.parse(t, &d); try testing.expectEqual(t, data.unknown.type); } test "data longer than its type needs is refused" { var d = try Decoder.init("\xc0\x00\x02\x01\x00"); try testing.expectError(error.TrailingRdata, Data.parse(.a, &d)); var short = try Decoder.init("\xc0\x00\x02"); try testing.expectError(error.Truncated, Data.parse(.a, &short)); } test "a transaction signature" { const bytes = "\x0bhmac-sha256\x00" ++ // the algorithm, as a name "\x00\x00\x6a\xa8\x68\x80" ++ // 48 bits of time "\x01\x2c" ++ // a five minute fudge "\x00\x04\xde\xad\xbe\xef" ++ // the MAC "\x12\x34" ++ // the original identifier "\x00\x00" ++ // no error "\x00\x00"; // and so nothing else try expectRoundTrip( .tsig, bytes, "hmac-sha256. 1789421696 300 4 3q2+7w== 4660 0 0", ); var d = try Decoder.init(bytes); const tsig = (try Data.parse(.tsig, &d)).tsig; try testing.expectEqual(@as(u48, 1789421696), tsig.time_signed); try testing.expectEqual(Tsig.ErrorCode.noerror, tsig.signatureError()); // Sixteen is `badsig` here and `badvers` in a header, which is the whole // reason `Tsig.ErrorCode` exists. var bad = tsig; bad.error_code = 16; try testing.expectEqual(Tsig.ErrorCode.badsig, bad.signatureError()); try testing.expectEqual(types.ResponseCode.badvers, @as(types.ResponseCode, @fromBackingInt(16))); } test "the types that share a shape with another" { // SMIMEA is a TLSA by another name, and DLV is a DS. try expectRoundTrip(.smimea, "\x03\x00\x01\xab\xcd", "3 0 1 abcd"); try expectRoundTrip(.dlv, "\x09\x41\x08\x02\xab\xcd", "2369 8 2 ABCD"); } test "every variant of the union is reachable from its own type number" { // The dispatch in `parse` and the tags of `Data` are written out // separately, so nothing but a test stops one of them from being missed: // a type with a variant but no arm decodes as `unknown`, quietly, and // looks exactly like a type nobody has implemented. // // Empty data is enough to tell them apart. A type whose data is // "everything left" accepts it and comes back as itself; every other type // refuses it. Neither answer is `unknown` unless the arm is missing. inline for (@typeInfo(Data).@"union".field_names) |name| { if (comptime !std.mem.eql(u8, name, "unknown")) { const t = @field(Type, name); var d = try Decoder.init(""); if (Data.parse(t, &d)) |data| { try testing.expectEqualStrings(name, @tagName(data)); } else |_| {} } } } test "the types that were tried and not kept" { try expectRoundTrip(.rt, "\x00\x02\x04host\x00", "2 host."); try expectRoundTrip(.x25, "\x0c311061700956", "\"311061700956\""); try expectRoundTrip(.nsap, "\x47\x00\x05\x80", "0x47000580"); try expectRoundTrip(.@"nsap-ptr", "\x04host\x00", "host."); try expectRoundTrip(.null, "\xde\xad", "\\# 2 DEAD"); try expectRoundTrip( .loc, "\x00\x33\x16\x13\x89\x17\x2d\xd0\x70\xbe\x15\xf0\x00\x98\x8d\x20", "42 21 54.000 N 71 6 18.000 W -24.00m 30.00m 10000.00m 10.00m", ); try expectRoundTrip( .apl, "\x00\x01\x15\x03\xc0\xa8\x20", "1:192.168.32.0/21", ); } test "the keys that are published here and used elsewhere" { try expectRoundTrip(.cert, "\x00\x01\x00\x00\x08\x01\x02\x03", "PKIX 0 8 AQID"); try expectRoundTrip( .ipseckey, "\x0a\x01\x02\xc0\x00\x02\x26\x01\x02\x03", "10 1 2 192.0.2.38 AQID", ); try expectRoundTrip(.openpgpkey, "\x01\x02\x03", "AQID"); try expectRoundTrip(.dhcid, "\x01\x02\x03", "AQID"); try expectRoundTrip(.hhit, "\x01\x02\x03", "AQID"); try expectRoundTrip(.brid, "\x01\x02\x03", "AQID"); } test "the modern zone maintenance types" { try expectRoundTrip( .zonemd, "\x77\x35\x94\x01\x01\x01\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef", "2000000001 1 1 DEADBEEFDEADBEEFDEADBEEF", ); try expectRoundTrip( .csync, "\x00\x00\x00\x2a\x00\x03\x00\x01\x40", "42 3 A", ); try expectRoundTrip( .dsync, "\x00\x3b\x01\x14\xef\x02ns\x02ex\x00", "CDS 1 5359 ns.ex.", ); } test "identifiers, locators and hardware addresses" { try expectRoundTrip(.eui48, "\x00\x00\x5e\x00\x53\x2a", "00-00-5e-00-53-2a"); try expectRoundTrip(.eui64, "\x00\x00\x5e\xef\x10\x00\x00\x2a", "00-00-5e-ef-10-00-00-2a"); try expectRoundTrip( .nid, "\x00\x0a\x00\x14\x4f\xff\xff\x20\xee\x64", "10 0014:4fff:ff20:ee64", ); try expectRoundTrip(.l32, "\x00\x0a\x0a\x01\x02\x00", "10 10.1.2.0"); try expectRoundTrip(.lp, "\x00\x0a\x02l1\x02ex\x00", "10 l1.ex."); } test "a recordless type is not a record" { for ([_]Type{ .any, .axfr, .ixfr, .maila, .mailb, .nxname }) |t| { var d = try Decoder.init(""); try testing.expectError(error.RecordlessType, Data.parse(t, &d)); } } test "compression is followed only where RFC 3597 allows it" { // Each case is a record's data with a pointer to `example.` where its // name would be, read inside a message that holds `example.` first. const Case = struct { type: Type, data: []const u8, allowed: bool }; const fixed_rrsig = "\x00\x01\x08\x02\x00\x00\x0e\x10" ++ "\x00\x00\x00\x02\x00\x00\x00\x01\x30\x39"; const cases = [_]Case{ // RFC 1035's own types. .{ .type = .cname, .data = "\xc0\x00", .allowed = true }, .{ .type = .mx, .data = "\x00\x0a\xc0\x00", .allowed = true }, // The ones RFC 3597 asks a reader to decompress anyway. .{ .type = .srv, .data = "\x00\x01\x00\x02\x00\x03\xc0\x00", .allowed = true }, .{ .type = .afsdb, .data = "\x00\x01\xc0\x00", .allowed = true }, .{ .type = .sig, .data = fixed_rrsig ++ "\xc0\x00\x01", .allowed = true }, // And everything since, which never compresses. .{ .type = .dname, .data = "\xc0\x00", .allowed = false }, .{ .type = .kx, .data = "\x00\x01\xc0\x00", .allowed = false }, .{ .type = .rrsig, .data = fixed_rrsig ++ "\xc0\x00\x01", .allowed = false }, .{ .type = .nsec, .data = "\xc0\x00\x00\x01\x40", .allowed = false }, .{ .type = .svcb, .data = "\x00\x01\xc0\x00", .allowed = false }, }; const prefix = "\x07example\x00"; var buf: [64]u8 = undefined; for (cases) |case| { @memcpy(buf[0..prefix.len], prefix); @memcpy(buf[prefix.len..][0..case.data.len], case.data); var d: Decoder = .{ .message = buf[0 .. prefix.len + case.data.len], .pos = prefix.len }; if (case.allowed) { _ = try Data.parse(case.type, &d); } else { try testing.expectError(error.CompressionForbidden, Data.parse(case.type, &d)); } } }