// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The numbers in a DNS message that are drawn from a registry: record types, //! classes, opcodes and response codes. //! //! Every one of them is non-exhaustive. IANA adds to all four registries, and //! a resolver that cannot carry a number it does not recognize cannot forward //! a query for a type invented after it was compiled — which is most of the //! interesting ones. So `@backingInt` always gives back exactly what was on //! the wire, `name` answers `null` rather than guessing, and the presentation //! syntax of RFC 3597 (`TYPE65534`, `CLASS42`) is what `format` falls back to. const std = @import("std"); const ascii = std.ascii; /// The uppercase mnemonic for an enum field, worked out at compile time from /// the field's name. Every mnemonic in these registries is its field name /// uppercased -- `aaaa` is `AAAA`, `nsap-ptr` is `NSAP-PTR` -- which is why /// the field names were chosen the way they were. fn mnemonic(comptime lowercase: []const u8) []const u8 { const frozen = comptime blk: { var buf: [lowercase.len]u8 = undefined; for (lowercase, 0..) |c, i| buf[i] = ascii.toUpper(c); break :blk buf; }; return &frozen; } /// A resource record type: what a record holds, and -- in a question -- what /// is being asked for. /// /// The registry is one space, but not every number in it may appear in a /// record. `axfr`, `ixfr`, `any`, `maila` and `mailb` are QTYPEs: they are /// meaningful in a question and never label an answer. `nxname` is meaningful /// in neither, and only ever appears in a type bitmap. `opt` is a /// pseudo-record, which exists only in the additional section of the message /// carrying it and is never stored, never cached and never in a zone. pub const Type = enum(u16) { /// A host address: four bytes of IPv4, in network order. a = 1, /// The authoritative name server for a zone. The delegation is the /// presence of this record in the parent, and its absence is the whole /// difference between a zone cut and an ordinary name. ns = 2, /// A mail destination. Obsolete since RFC 973; use `mx`. md = 3, /// A mail forwarder. Obsolete since RFC 973; use `mx`. mf = 4, /// The canonical name of an alias. A name with a `cname` may hold no other /// record type, which is why it cannot sit at the apex of a zone. cname = 5, /// The start of authority: where a zone begins, who is responsible for it, /// and the timers a secondary keeps. soa = 6, /// A mailbox domain name. Experimental, never deployed. mb = 7, /// A mail group member. Experimental, never deployed. mg = 8, /// A mail rename domain name. Experimental, never deployed. mr = 9, /// A null record: anything at all, up to 65535 bytes. Experimental, and /// the reason tunnelling over DNS was ever convenient. null = 10, /// A well known service description. Obsolete; `srv` is what replaced it. wks = 11, /// A domain name pointer. What the reverse tree under `in-addr.arpa` and /// `ip6.arpa` is made of. ptr = 12, /// Host information: the CPU and the operating system, as text. Rarely /// answered truthfully and rarely asked. hinfo = 13, /// Mailbox or mail list information. Experimental. minfo = 14, /// A mail exchange: where mail for this name should be delivered, and in /// what order to try them. mx = 15, /// Text. A sequence of character-strings, which is why a long `txt` value /// arrives in 255-byte pieces that the reader is expected to join. txt = 16, /// The responsible person for a name. rp = 17, /// An AFS database location. afsdb = 18, /// An X.25 PSDN address. x25 = 19, /// An ISDN address. isdn = 20, /// A route through another host. rt = 21, /// An NSAP address. nsap = 22, /// A pointer into the NSAP address space. @"nsap-ptr" = 23, /// A security signature. The first attempt at DNSSEC; `rrsig` replaced it. sig = 24, /// A security key. The first attempt at DNSSEC; `dnskey` replaced it. key = 25, /// An X.400 mail mapping. px = 26, /// A geographical position, superseded by `loc`. gpos = 27, /// A host address: sixteen bytes of IPv6, in network order. aaaa = 28, /// A location: latitude, longitude and altitude. loc = 29, /// The next domain. The first attempt at authenticated denial; `nsec` /// replaced it. nxt = 30, /// A service location: the host and port a named service is on, which is /// what `wks` should have been. srv = 33, /// Naming authority pointer: a rewrite rule, used by ENUM and by SIP. naptr = 35, /// A key exchanger. kx = 36, /// A certificate. cert = 37, /// An IPv6 address with a prefix elsewhere. Never deployed; `aaaa` won. a6 = 38, /// A delegation of an entire subtree, the way `cname` delegates one name. dname = 39, /// The EDNS(0) pseudo-record. It has no owner name that means anything, no /// TTL, and no class: those fields carry the payload size and the flags /// instead. See `edns`. opt = 41, /// An address prefix list. apl = 42, /// A delegation signer: the hash of a child's `dnskey`, held by the /// parent, which is the link in the chain of trust across a zone cut. ds = 43, /// An SSH key fingerprint. sshfp = 44, /// An IPsec key. ipseckey = 45, /// The signature over one RRset. rrsig = 46, /// The next secure record: which names exist, and which types exist at /// this one. Denial of existence, by saying what the gap is. nsec = 47, /// A public key for a zone. dnskey = 48, /// A DHCP identifier. dhcid = 49, /// `nsec` over hashed names, so that a zone cannot be walked. nsec3 = 50, /// The parameters -- algorithm, iterations, salt -- the `nsec3` records in /// a zone were hashed with. nsec3param = 51, /// A TLS certificate association: DANE. tlsa = 52, /// An S/MIME certificate association. smimea = 53, /// A host identity protocol record: a host's identity tag and public key, /// with the rendezvous servers that will forward to it. hip = 55, /// Zone status information. Never standardized. ninfo = 56, /// The child's copy of what its parent's `ds` should say. cds = 59, /// The child's copy of what its parent should publish as a key. cdnskey = 60, /// An OpenPGP public key. openpgpkey = 61, /// A child-to-parent synchronization request. csync = 62, /// A message digest over an entire zone. zonemd = 63, /// Service binding: the parameters for reaching a service, in one record, /// so that a client need not guess at ALPN, port and address separately. svcb = 64, /// `svcb` for HTTPS, with the origin's own name as the owner. https = 65, /// Where a child zone wants to be told that its delegation should be /// re-checked (RFC 9859), so that a `cds` or `csync` is acted on without /// waiting for the parent to poll. dsync = 66, /// A drone's Hierarchical Host Identity Tag record (RFC 9886): its public /// key and certificate, as CBOR. hhit = 67, /// What a drone broadcasts about itself, for looking up from the ground /// (RFC 9886), as CBOR. brid = 68, /// Sender policy framework, as its own type. Deprecated by RFC 7208 in /// favour of a `txt` record, which is what everything actually publishes. spf = 99, /// An unformatted piece of data. Withdrawn, and never assigned a shape. unspec = 103, /// A node identifier, for the identifier/locator split of ILNP (RFC 6742). nid = 104, /// A 32-bit locator for ILNP. l32 = 105, /// A 64-bit locator for ILNP. l64 = 106, /// The name to look up locators at, for ILNP. lp = 107, /// A 48-bit MAC address. eui48 = 108, /// A 64-bit MAC address. eui64 = 109, /// A name that does not exist (RFC 9824). Never a record and never a /// question: it appears only in the type bitmap of an NSEC that answers /// for a name which is not there, so that the answer can say so while /// still being the NODATA that compact denial of existence sends. nxname = 128, /// A transaction key. tkey = 249, /// A transaction signature: authentication of a single message, by a /// shared secret, covering the message as it was sent. tsig = 250, /// An incremental zone transfer. A QTYPE. ixfr = 251, /// A full zone transfer. A QTYPE. axfr = 252, /// A request for mailbox records. A QTYPE. mailb = 253, /// A request for mail agent records. A QTYPE, and obsolete. maila = 254, /// A request for every type at a name. A QTYPE, answered honestly by /// almost nothing any more. any = 255, /// A uniform resource identifier. uri = 256, /// Certification authority authorization: which authorities may issue for /// this name. caa = 257, /// Application visibility and control. A `txt` record by another number. avc = 258, /// Where to find a relay for automatic multicast tunnelling (RFC 8777). amtrelay = 260, /// Resolver information: what a resolver will tell you about itself /// (RFC 9606), as a list of key-value strings. resinfo = 261, /// A public wallet address, as text. wallet = 262, /// A trust anchor, for DNSSEC lookaside. ta = 32768, /// DNSSEC lookaside validation. Decommissioned by RFC 8749. dlv = 32769, _, /// The mnemonic for this type, or `null` if the number is one this library /// has no name for. `format` is usually what you want instead: it falls /// back to the `TYPE1234` syntax of RFC 3597 §5. pub fn name(self: Type) ?[]const u8 { return switch (self) { _ => null, inline else => |t| mnemonic(@tagName(t)), }; } test name { try std.testing.expectEqualStrings("AAAA", Type.aaaa.name().?); // A number with no field has no mnemonic to give. try std.testing.expectEqual(@as(?[]const u8, null), @as(Type, @fromBackingInt(65280)).name()); } /// The type a mnemonic names, matched without regard to case, or `null` /// for a mnemonic this library does not know. Understands the `TYPE1234` /// syntax of RFC 3597 §5, so every number in the registry can be named. pub fn fromName(text: []const u8) ?Type { const info = @typeInfo(Type).@"enum"; inline for (info.field_names, info.field_values) |field_name, value| { if (ascii.eqlIgnoreCase(text, field_name)) return @fromBackingInt(value); } if (text.len > 4 and ascii.eqlIgnoreCase(text[0..4], "TYPE")) { const n = std.fmt.parseUnsigned(u16, text[4..], 10) catch return null; return @fromBackingInt(n); } return null; } test fromName { try std.testing.expectEqual(Type.mx, fromName("mx").?); // The RFC 3597 form reaches named and unnamed types alike. try std.testing.expectEqual(Type.aaaa, fromName("TYPE28").?); try std.testing.expectEqual(@as(u16, 65280), @backingInt(fromName("type65280").?)); try std.testing.expectEqual(@as(?Type, null), fromName("NOSUCH")); } /// True for the types that never have record data: the ones that are /// only ever questions -- `axfr`, `ixfr`, `any`, `maila` and `mailb` -- /// and `nxname`, which is only ever a bit in a bitmap. A record carrying /// one of these is malformed. pub fn isRecordless(self: Type) bool { return switch (self) { .ixfr, .axfr, .mailb, .maila, .any, .nxname => true, else => false, }; } test isRecordless { try std.testing.expect(Type.axfr.isRecordless()); try std.testing.expect(Type.nxname.isRecordless()); // `opt` is a pseudo-record, but it has data. try std.testing.expect(!Type.opt.isRecordless()); } /// The mnemonic, or `TYPE` and the number (RFC 3597 §5) for a type this /// library has no name for, so that every type can be written down. pub fn format(self: Type, w: *std.Io.Writer) std.Io.Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("TYPE{d}", .{@backingInt(self)}); } test format { try std.testing.expectFmt("NSEC3PARAM", "{f}", .{Type.nsec3param}); try std.testing.expectFmt("TYPE65280", "{f}", .{@as(Type, @fromBackingInt(65280))}); } }; /// The class of a record. In practice there is `in` and there is nothing, but /// `none` and `any` are meaningful in the prerequisite and update sections of /// a dynamic update (RFC 2136), and `ch` is still how a name server is asked /// its own version. pub const Class = enum(u16) { /// The internet. Everything. in = 1, /// CSNET. Obsolete even when RFC 1035 was written. cs = 2, /// Chaos. Survives because `version.bind CH TXT` is how a BIND server is /// asked what it is. ch = 3, /// Hesiod. hs = 4, /// "This record must not exist", in a dynamic update prerequisite, and /// "delete exactly this record" in the update section. none = 254, /// Any class. A QCLASS, and in a dynamic update the wildcard in a /// prerequisite or a delete. any = 255, _, /// The mnemonic for this class, or `null` if the number is one this /// library has no name for. pub fn name(self: Class) ?[]const u8 { return switch (self) { _ => null, inline else => |c| mnemonic(@tagName(c)), }; } test name { try std.testing.expectEqualStrings("CH", Class.ch.name().?); try std.testing.expectEqual(@as(?[]const u8, null), @as(Class, @fromBackingInt(42)).name()); } /// The class a mnemonic names, matched without regard to case, including /// the `CLASS1234` syntax of RFC 3597 §5. pub fn fromName(text: []const u8) ?Class { const info = @typeInfo(Class).@"enum"; inline for (info.field_names, info.field_values) |field_name, value| { if (ascii.eqlIgnoreCase(text, field_name)) return @fromBackingInt(value); } if (text.len > 5 and ascii.eqlIgnoreCase(text[0..5], "CLASS")) { const n = std.fmt.parseUnsigned(u16, text[5..], 10) catch return null; return @fromBackingInt(n); } return null; } test fromName { try std.testing.expectEqual(Class.in, fromName("IN").?); try std.testing.expectEqual(Class.ch, fromName("class3").?); try std.testing.expectEqual(@as(?Class, null), fromName("INTERNET")); } /// The mnemonic, or `CLASS` and the number (RFC 3597 §5) for a class this /// library has no name for. pub fn format(self: Class, w: *std.Io.Writer) std.Io.Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("CLASS{d}", .{@backingInt(self)}); } test format { try std.testing.expectFmt("IN", "{f}", .{Class.in}); try std.testing.expectFmt("CLASS42", "{f}", .{@as(Class, @fromBackingInt(42))}); } }; /// What kind of query a message is. Four bits in the header, and the field /// that decides what the four sections mean: in an `update` they are the zone, /// the prerequisites, the updates and additional data rather than question and /// answer. pub const Opcode = enum(u4) { /// A standard query. Everything that is not one of the others. query = 0, /// An inverse query: given an answer, name the question. Never widely /// implemented, and withdrawn by RFC 3425. iquery = 1, /// A server status request. Never specified beyond the opcode. status = 2, /// A primary telling a secondary that a zone has changed (RFC 1996), so /// that the secondary need not wait out the refresh timer. notify = 4, /// A dynamic update (RFC 2136). update = 5, /// DNS stateful operations (RFC 8490): a session-level message on a /// persistent connection, which is why it has no question. dso = 6, _, /// The mnemonic for this opcode, or `null` if the number is one this /// library has no name for -- 3 among them, which was never assigned. pub fn name(self: Opcode) ?[]const u8 { return switch (self) { _ => null, inline else => |o| mnemonic(@tagName(o)), }; } test name { try std.testing.expectEqualStrings("NOTIFY", Opcode.notify.name().?); try std.testing.expectEqual(@as(?[]const u8, null), @as(Opcode, @fromBackingInt(3)).name()); } /// The mnemonic, or `OPCODE` and the number for one this library has no /// name for. RFC 3597 gives no such syntax for opcodes; this follows its /// pattern, as other tools do. pub fn format(self: Opcode, w: *std.Io.Writer) std.Io.Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("OPCODE{d}", .{@backingInt(self)}); } test format { try std.testing.expectFmt("UPDATE", "{f}", .{Opcode.update}); try std.testing.expectFmt("OPCODE3", "{f}", .{@as(Opcode, @fromBackingInt(3))}); } }; /// How a query was answered. /// /// This is twelve bits wide because EDNS(0) made it so: the header holds the /// low four, and an `opt` record in the additional section holds the high /// eight. A code above 15 therefore cannot be sent at all without an `opt` to /// carry it, which is why `badvers` -- the code meaning "I do not speak your /// version of EDNS" -- is 16 and is sent with an `opt` of version 0. /// /// `Message.responseCode` does the reassembly; `Header.rcode` is only ever the /// low four bits, as they arrived. pub const ResponseCode = enum(u12) { /// No error. noerror = 0, /// The query could not be interpreted. formerr = 1, /// The server could not answer, for a reason it will not say. servfail = 2, /// The name does not exist. Authoritative only from an authoritative /// answer; from anything else it is a cached denial. nxdomain = 3, /// The server does not implement this kind of query. notimp = 4, /// The server refuses. A policy answer, not a failure. refused = 5, /// A name exists when it should not (dynamic update prerequisite). yxdomain = 6, /// An RRset exists when it should not (dynamic update prerequisite). yxrrset = 7, /// An RRset that should exist does not (dynamic update prerequisite). nxrrset = 8, /// The server is not authoritative for the zone, or the requestor is not /// permitted to make this update. notauth = 9, /// A name in the update is not within the zone named by the update. notzone = 10, /// The DSO type code is not implemented (RFC 8490). dsotypeni = 11, /// Bad EDNS version. Sixteen, so it needs an `opt` record to be expressed /// at all -- see the note on this type. /// /// **Sixteen means something else in a TSIG's error field**, where it is /// `badsig`: RFC 6895 §2.3 records that the two were assigned the same /// number before anybody noticed, and they are told apart only by which /// field they were read from. `rdata.Tsig.ErrorCode` is that other registry; /// anything reading a TSIG's error wants it and not this. badvers = 16, /// A TSIG key name the receiver does not know. badkey = 17, /// A TSIG signature was outside the time window. badtime = 18, /// A TKEY mode was not understood. badmode = 19, /// A duplicate key name. badname = 20, /// An algorithm was not understood. badalg = 21, /// A TSIG truncation was not acceptable. badtrunc = 22, /// A server cookie was bad or absent (RFC 7873). badcookie = 23, _, /// The mnemonic for this code, or `null` if the number is one this library /// has no name for. pub fn name(self: ResponseCode) ?[]const u8 { return switch (self) { _ => null, inline else => |r| mnemonic(@tagName(r)), }; } test name { try std.testing.expectEqualStrings("NXDOMAIN", ResponseCode.nxdomain.name().?); try std.testing.expectEqual(@as(?[]const u8, null), @as(ResponseCode, @fromBackingInt(4000)).name()); } /// The low four bits, which are what the header can carry. The rest needs /// an `opt` record; see `edns.Opt.extended_rcode`. pub fn low(self: ResponseCode) u4 { return @truncate(@backingInt(self)); } test low { try std.testing.expectEqual(@as(u4, 3), ResponseCode.nxdomain.low()); // `badvers` is sixteen, and all a header can say of it is zero. try std.testing.expectEqual(@as(u4, 0), ResponseCode.badvers.low()); } /// The high eight bits, which are what an `opt` record carries. pub fn high(self: ResponseCode) u8 { return @intCast(@backingInt(self) >> 4); } test high { try std.testing.expectEqual(@as(u8, 0), ResponseCode.nxdomain.high()); try std.testing.expectEqual(@as(u8, 1), ResponseCode.badvers.high()); } /// Reassemble the twelve-bit code from the header's four bits and the /// eight an `opt` record adds. pub fn join(header_bits: u4, opt_bits: u8) ResponseCode { return @fromBackingInt(@as(u12, opt_bits) << 4 | header_bits); } test join { // A header saying `noerror` and an `opt` saying 1 is `badvers`. try std.testing.expectEqual(ResponseCode.badvers, join(0, 1)); try std.testing.expectEqual(ResponseCode.refused, join(5, 0)); } /// The mnemonic, or `RCODE` and the number for a code this library has no /// name for. pub fn format(self: ResponseCode, w: *std.Io.Writer) std.Io.Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("RCODE{d}", .{@backingInt(self)}); } test format { try std.testing.expectFmt("SERVFAIL", "{f}", .{ResponseCode.servfail}); try std.testing.expectFmt("RCODE4000", "{f}", .{@as(ResponseCode, @fromBackingInt(4000))}); } }; test "type mnemonics round trip" { try std.testing.expectEqualStrings("AAAA", Type.aaaa.name().?); try std.testing.expectEqualStrings("NSAP-PTR", Type.@"nsap-ptr".name().?); try std.testing.expectEqualStrings("NULL", Type.null.name().?); try std.testing.expectEqual(Type.cname, Type.fromName("cname").?); try std.testing.expectEqual(Type.cname, Type.fromName("CNAME").?); try std.testing.expectEqual(@as(?Type, null), Type.fromName("NOSUCH")); } test "unknown types use the RFC 3597 syntax" { const t: Type = @fromBackingInt(65534); try std.testing.expectEqual(@as(?[]const u8, null), t.name()); try std.testing.expectFmt("TYPE65534", "{f}", .{t}); try std.testing.expectEqual(t, Type.fromName("TYPE65534").?); try std.testing.expectFmt("CLASS42", "{f}", .{@as(Class, @fromBackingInt(42))}); } test "the response code is split across the header and the OPT record" { try std.testing.expectEqual(@as(u4, 0), ResponseCode.badvers.low()); try std.testing.expectEqual(@as(u8, 1), ResponseCode.badvers.high()); try std.testing.expectEqual(ResponseCode.badvers, ResponseCode.join(0, 1)); try std.testing.expectEqual(ResponseCode.nxdomain, ResponseCode.join(3, 0)); }