Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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 is only ever a question -- `any`, `axfr`, `ixfr`, /// `maila`, `mailb`. There is no such record, so there is no data to /// decode; see `types.Type.isQuestionOnly`. QuestionOnlyType, /// 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,
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), }; }
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); }
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, }); }};
/// 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,
pub fn parse(d: *Decoder) Error!Mx { return .{ .preference = try d.int(u16), .exchange = try d.name() }; }
pub fn writeTo(self: Mx, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.name(self.exchange, .compressed); }
pub fn format(self: Mx, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.preference, self.exchange }); }};
/// 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,
pub fn parse(d: *Decoder) Error!Txt { const bytes = d.takeRest(); // RFC 1035 section 3.3.14 allows any number of them, including none. var i: usize = 0; while (i < bytes.len) { i += 1 + @as(usize, bytes[i]); if (i > bytes.len) return error.MalformedRdata; } return .{ .encoded = bytes }; }
pub const Iterator = struct { txt: Txt, pos: usize = 0,
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]; }, } } };
pub fn iterator(self: Txt) Iterator { return .{ .txt = self }; }
/// 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(); }
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), } }
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); } }};
/// 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,
pub fn parse(d: *Decoder) Error!Hinfo { return .{ .cpu = try d.characterString(), .os = try d.characterString() }; }
pub fn writeTo(self: Hinfo, b: *Builder) Builder.Error!void { try b.characterString(self.cpu); try b.characterString(self.os); }
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); }};
/// 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,
pub fn parse(d: *Decoder) Error!NamePair { return .{ .first = try d.name(), .second = try d.name() }; }
pub fn writeTo(self: NamePair, b: *Builder) Builder.Error!void { try b.name(self.first, .compressed); try b.name(self.second, .compressed); }
pub fn format(self: NamePair, w: *Writer) Writer.Error!void { try w.print("{f} {f}", .{ self.first, self.second }); }};
/// 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,
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(), }; }
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); }
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 }); }};
/// 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,
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(), }; }
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); }
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}); }};
/// 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,
pub fn isCritical(self: Caa) bool { return self.flags & 0x80 != 0; }
pub fn parse(d: *Decoder) Error!Caa { return .{ .flags = try d.int(u8), .tag = try d.characterString(), .value = d.takeRest(), }; }
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); }
pub fn format(self: Caa, w: *Writer) Writer.Error!void { try w.print("{d} {s} ", .{ self.flags, self.tag }); try presentation.writeCharacterString(w, self.value); }};
/// 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,
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 }; }
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); }
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); }};
/// 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; `responseCode` converts the ones that /// fit, which in practice is all of them. 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 @enumFromInt(self.error_code); }
pub fn parse(d: *Decoder) Error!Tsig { const algorithm = try d.name(); 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), }; }
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); }
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); } }};
/// 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,
pub fn parse(d: *Decoder) Error!Self { return .{ .address = (try d.take(len))[0..len].* }; }
pub fn writeTo(self: Self, b: *Builder) Builder.Error!void { try b.writeAll(&self.address); }
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}); } } };}
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,
pub fn parse(d: *Decoder) Error!Locator64 { return .{ .preference = try d.int(u16), .value = (try d.take(8))[0..8].*, }; }
pub fn writeTo(self: Locator64, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.writeAll(&self.value); }
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)}); } }};
/// 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,
pub fn parse(d: *Decoder) Error!Locator32 { return .{ .preference = try d.int(u16), .value = .{ .octets = (try d.take(4))[0..4].* }, }; }
pub fn writeTo(self: Locator32, b: *Builder) Builder.Error!void { try b.int(u16, self.preference); try b.writeAll(&self.value.octets); }
pub fn format(self: Locator32, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.preference, self.value }); }};
/// 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,
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.name(), }; }
pub fn writeTo(self: Dsync, b: *Builder) Builder.Error!void { try b.int(u16, @intFromEnum(self.type)); try b.int(u8, self.scheme); try b.int(u16, self.port); try b.name(self.target, .uncompressed); }
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 }); }};
/// 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,
pub fn writeTo(self: Unknown, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); }
pub fn format(self: Unknown, w: *Writer) Writer.Error!void { try presentation.writeUnknownRdata(w, self.bytes); }};
/// 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, 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)), }; }
/// 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. /// /// 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. 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.isQuestionOnly()) return error.QuestionOnlyType;
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() }, .dname => .{ .dname = try d.name() }, .@"nsap-ptr" => .{ .@"nsap-ptr" = try d.name() },
.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) }, .afsdb => .{ .afsdb = try PrefixedName.parse(d) }, .rt => .{ .rt = try PrefixedName.parse(d) }, .kx => .{ .kx = try PrefixedName.parse(d) }, .lp => .{ .lp = try PrefixedName.parse(d) }, .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) }, .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) }, .rrsig => .{ .rrsig = try Rrsig.parse(d) }, .sig => .{ .sig = try Rrsig.parse(d) }, .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; }
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), inline else => |value| try value.writeTo(b), } }
/// 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}), } }};
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" ++ ("\x00" ** 11) ++ "\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 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 type nobody knows is kept exactly" { const t: Type = @enumFromInt(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.Error` 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, @enumFromInt(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".fields) |field| { if (comptime !std.mem.eql(u8, field.name, "unknown")) { const t = @field(Type, field.name); var d = try Decoder.init(""); if (Data.parse(t, &d)) |data| { try testing.expectEqualStrings(field.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");}
test "the modern zone maintenance types" { try expectRoundTrip( .zonemd, "\x77\x35\x94\x01\x01\x01\xde\xad\xbe\xef", "2000000001 1 1 DEADBEEF", ); 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 type that is only ever a question is not a record" { for ([_]Type{ .any, .axfr, .ixfr, .maila, .mailb }) |t| { var d = try Decoder.init(""); try testing.expectError(error.QuestionOnlyType, Data.parse(t, &d)); }}