Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A domain name: a sequence of labels, ending at the root.//!//! A name in a message is not a string and is not necessarily contiguous. RFC//! 1035 §4.1.4 lets any label be replaced by a two-byte pointer to an earlier//! occurrence of the same suffix, so `www.example.com` and `ftp.example.com`//! in one message share a single copy of `example.com`, and reading the second//! one means jumping backwards into the first. That is why a `Name` is a//! message and an offset into it rather than a slice: the labels are found by//! walking, and the walk may leave the region the name appeared to occupy.//!//! The consequence for callers is that **a parsed name borrows the whole//! message**. To keep one past the buffer it came from, copy it out with//! `clone`, which writes the labels uncompressed into a `Buffer` you own.//!//! A name built from text is the same type over a buffer holding just that//! name, so the two are interchangeable everywhere://!//! ```zig//! var buf: dns.Name.Buffer = undefined;//! const name = try dns.Name.fromText(&buf, "www.example.com");//! ```//!//! ### Malformed input//!//! `parse` walks the whole name before returning, so every `Name` this library//! hands out is one whose labels can be read to the end without a further//! error. Two rules make that possible in bounded time: a pointer must point//! strictly backwards, and the expanded name must be 255 bytes or fewer. Every//! cycle a pointer graph can contain must pass through at least one label --//! a cycle made only of pointers would have to increase somewhere -- so the//! length limit is what stops a crafted message from being walked forever.
const std = @import("std");const ascii = std.ascii;const Writer = std.Io.Writer;
const Name = @This();
/// The bytes the name is read out of. For a name in a message this is the/// whole message, because a compression pointer may name any earlier offset in/// it; for a name built by `fromText` it is just that name.message: []const u8,/// Where in `message` the name begins.offset: u16,
/// The longest a name may be once written out in full, including the length/// byte of every label and the zero byte of the root (RFC 1035 §2.3.4).pub const max_encoded_len = 255;/// The longest a single label may be. The limit is not arbitrary: the top two/// bits of a length byte were spent on the compression pointer, leaving six.pub const max_label_len = 63;/// The most labels a name can have, since every label costs at least two bytes/// of the 255 and the root costs the last one.pub const max_labels = (max_encoded_len - 1) / 2;/// The highest offset a compression pointer can name, the other two bits of/// its first byte being the tag that makes it a pointer.pub const max_pointer_offset = 0x3fff;
/// A buffer big enough for any name in wire form. `fromText` and `clone` write/// into one.pub const Buffer = [max_encoded_len]u8;
/// The longest text any name can format to: 250 bytes of data needing a/// four-character escape each, in the four labels that fit alongside them.pub const max_text_len = 1004;
/// A buffer big enough for any name in presentation form.pub const TextBuffer = [max_text_len]u8;
pub const Error = error{ /// A length byte had its top two bits set to `01` or `10`. RFC 1035 §4.1.4 /// reserved both and nothing has ever defined either, so the only thing /// that produces one is a corrupt or hostile message. ReservedLabelType, /// A compression pointer pointed at itself or forwards. RFC 1035 §4.1.4 /// only ever defines a pointer as naming a *prior* occurrence, and /// requiring that is what makes a walk terminate. BadPointer, /// The name ran off the end of the message. Truncated, /// The name is longer than 255 bytes once expanded. NameTooLong,};
/// What a compression pointer has to point at.////// RFC 1035 §4.1.4 says only that a pointer names "a prior occurrence of the/// same name", and the two readings of "prior" in use are not the same/// reading. Both refuse every loop, and no compressor can tell them apart: one/// that only ever points at what it has already written makes the targets/// descend on its own. The difference is reachable only by a message nothing/// generated, which is exactly the kind of message a decoder has to have an/// answer for.pub const PointerRule = enum { /// A pointer must name an offset below the pointer itself. The default, /// and the more permissive of the two. /// /// It still terminates: a cycle made only of pointers would have to /// increase somewhere, so every cycle passes through at least one label, /// and the 255-byte limit on the expanded name is what ends the walk. backwards, /// A pointer must name an offset below where the name began *and* below /// every offset already reached by a pointer in this name. /// /// This is what dnspython requires, and it makes termination obvious /// rather than argued: the offsets strictly descend, so no cycle is /// reachable at all and no name can be made to take more than a bounded /// number of jumps. Choose it when reading messages from somewhere that /// has not earned any benefit of the doubt. descending,};
/// How forgiving to be about the parts of the wire format that are/// under-specified.pub const Options = struct { pointers: PointerRule = .backwards,};
const root_wire = [_]u8{0};
/// The root: the name with no labels, written `.`.pub const root: Name = .{ .message = &root_wire, .offset = 0 };
/// What a walk over a name found.const Scan = struct { /// How many bytes the name occupies *at the offset it was read from*: /// every label up to and including the root byte, or up to and including /// the first pointer. This is what a decoder advances by, and it is not /// the same as `encoded_len` unless the name is uncompressed. wire_len: u16, /// How many bytes the name would occupy written out in full. encoded_len: u16, /// How many labels it has, not counting the root. labels: u8, /// Whether reading it followed a compression pointer. compressed: bool,};
fn scan(message: []const u8, start: u16, options: Options) Error!Scan { var pos: usize = start; var wire_len: ?u16 = null; var encoded_len: u16 = 0; var label_count: u8 = 0; // Under `.descending` a pointer must name an offset below every offset // already reached by one, starting with where the name itself begins. var ceiling: usize = start; while (true) { if (pos >= message.len) return error.Truncated; const byte = message[pos]; switch (byte & 0xc0) { 0x00 => { if (byte == 0) { pos += 1; encoded_len += 1; if (encoded_len > max_encoded_len) return error.NameTooLong; if (wire_len == null) wire_len = @intCast(pos - start); break; } const end = pos + 1 + byte; if (end > message.len) return error.Truncated; encoded_len += 1 + @as(u16, byte); if (encoded_len > max_encoded_len) return error.NameTooLong; label_count += 1; pos = end; }, 0xc0 => { if (pos + 1 >= message.len) return error.Truncated; const target: u16 = @as(u16, byte & 0x3f) << 8 | message[pos + 1]; if (wire_len == null) wire_len = @intCast(pos + 2 - start); switch (options.pointers) { .backwards => if (target >= pos) return error.BadPointer, .descending => { if (target >= ceiling) return error.BadPointer; ceiling = target; }, } pos = target; }, else => return error.ReservedLabelType, } } return .{ .wire_len = wire_len.?, .encoded_len = encoded_len, .labels = label_count, .compressed = wire_len.? != encoded_len, };}
/// A name and how much room it took where it was read from.pub const Parsed = struct { name: Name, /// See `Scan.wire_len`: the bytes to advance by, which for a compressed /// name is the two the pointer took and not the length of what it means. wire_len: u16,};
/// Reads the name at `offset` in `message`, following compression pointers,/// and checks that the whole of it is well formed. The returned name borrows/// `message`.////// This is the one a decoder wants, because walking the name is also how its/// length is discovered and asking twice costs twice.pub fn parseCounted(message: []const u8, offset: u16) Error!Parsed { return parseCountedWithOptions(message, offset, .{});}
pub fn parseCountedWithOptions( message: []const u8, offset: u16, options: Options,) Error!Parsed { const s = try scan(message, offset, options); return .{ .name = .{ .message = message, .offset = offset }, .wire_len = s.wire_len, };}
/// Reads the name at `offset` in `message`, following compression pointers,/// and checks that the whole of it is well formed. The returned name borrows/// `message`.pub fn parse(message: []const u8, offset: u16) Error!Name { return (try parseCounted(message, offset)).name;}
/// As `parse`, with a say in how strict to be. See `Options`.pub fn parseWithOptions(message: []const u8, offset: u16, options: Options) Error!Name { return (try parseCountedWithOptions(message, offset, options)).name;}
/// How many bytes the name occupies at the offset it was read from, which is/// what a decoder advances by. See `Scan.wire_len`. Walking the name again to/// find out, so prefer `parseCounted` where both are wanted.pub fn wireLen(self: Name) u16 { // The default rule, always: it is the permissive one, so a name that // passed either rule passes this, and a name that passed neither could not // have become a `Name`. const s = scan(self.message, self.offset, .{}) catch unreachable; return s.wire_len;}
pub const FromBytesError = Error || error{ /// The name did not use all of the bytes it was given. TrailingBytes, /// The name contained a compression pointer, which cannot be resolved /// without the message the pointer points into. Compressed,};
/// Reads a name from a buffer holding nothing else -- an uncompressed name on/// its own, as it might have been stored or copied out with `clone`.pub fn fromBytes(wire: []const u8) FromBytesError!Name { // Walked here rather than by `scan`, because a pointer is to be reported // as one and not followed. In a buffer holding one name, any pointer must // by the backwards rule point into that same name, so following it would // loop and the caller would be told the name was too long -- true, and no // help at all in finding the mistake. var pos: usize = 0; while (true) { if (pos >= wire.len) return error.Truncated; const byte = wire[pos]; switch (byte & 0xc0) { 0x00 => { pos += 1 + @as(usize, byte); if (pos > wire.len) return error.Truncated; if (byte == 0) break; }, 0xc0 => return error.Compressed, else => return error.ReservedLabelType, } } if (pos != wire.len) return error.TrailingBytes; if (pos > max_encoded_len) return error.NameTooLong; return .{ .message = wire, .offset = 0 };}
pub const TextError = error{ /// Two dots in a row, or a name beginning with one. The root is written /// `.` or as the empty string, and no other name may hold an empty label. EmptyLabel, /// A label longer than 63 bytes. LabelTooLong, /// A name longer than 255 bytes once encoded. NameTooLong, /// A backslash at the end of the text, or `\` followed by one or two /// digits rather than three, or a `\DDD` escape above 255. BadEscape,};
/// Encodes a name written in presentation form -- `www.example.com`, with or/// without the trailing dot -- into `buf`, and returns a name over it.////// The escapes of RFC 1035 §5.1 are understood: `\.` and `\\` for a literal/// dot and backslash, and `\DDD` for a byte by its decimal value, which is how/// a label holding arbitrary bytes is written. Case is preserved exactly as/// given, because the wire preserves it -- comparison is what ignores it.////// A name without a trailing dot is read as though it had one. When that is/// not what is wanted -- a zone file's `$ORIGIN`, a resolver's search list --/// `fromTextRelative` is the one to call.////// The returned name borrows `buf`, which must outlive it.pub fn fromText(buf: *Buffer, text: []const u8) TextError!Name { return fromTextRelative(buf, text, root);}
/// Encodes a name that may be relative, putting `origin` after it when it is.////// This is the other half of the presentation form, and the half a program/// meets as soon as a person types a name: `www` means one thing under/// `example.com` and another under `example.net`, and only a trailing dot/// makes a name mean itself. Two callers need exactly this and neither should/// have to write the escape rules again -- a zone file, where the origin is/// `$ORIGIN`, and a stub resolver, where it is each domain of the search list/// in turn.////// **The trailing dot has to be an unescaped one.** `a\.` is a single label/// holding a dot and is *relative*; deciding otherwise by looking at the last/// byte is the mistake this exists to stop. `textIsAbsolute` answers the same/// question on its own, for a caller that wants to know before encoding.////// The empty name is relative and has no labels, so it encodes to the origin/// itself. `@` is not special here: it is master file syntax rather than name/// syntax, and means nothing to a resolver.////// `origin` may be any name, including one read out of a message with/// compression pointers in it -- its labels are written out in full.pub fn fromTextRelative(buf: *Buffer, text: []const u8, origin: Name) TextError!Name { // The root, written as a lone dot, is the one name that is absolute and // has no labels. if (text.len == 1 and text[0] == '.') { buf[0] = 0; return .{ .message = buf[0..1], .offset = 0 }; }
var out: usize = 0; var i: usize = 0; var absolute = false; while (i < text.len) { const length_at = out; if (out + 1 >= buf.len) return error.NameTooLong; out += 1;
var label_len: usize = 0; while (i < text.len and text[i] != '.') { var c = text[i]; i += 1; if (c == '\\') { if (i >= text.len) return error.BadEscape; if (ascii.isDigit(text[i])) { if (i + 3 > text.len) return error.BadEscape; var value: u16 = 0; for (text[i..][0..3]) |digit| { if (!ascii.isDigit(digit)) return error.BadEscape; value = value * 10 + (digit - '0'); } if (value > 255) return error.BadEscape; c = @intCast(value); i += 3; } else { c = text[i]; i += 1; } } if (label_len == max_label_len) return error.LabelTooLong; if (out + 1 >= buf.len) return error.NameTooLong; buf[out] = c; out += 1; label_len += 1; } if (label_len == 0) return error.EmptyLabel; buf[length_at] = @intCast(label_len);
if (i < text.len) { i += 1; // the dot if (i == text.len) { // A dot at the very end is what makes the name absolute; // anywhere else it is a separator and another label follows. absolute = true; break; } } }
if (absolute) { if (out >= buf.len) return error.NameTooLong; buf[out] = 0; return .{ .message = buf[0 .. out + 1], .offset = 0 }; }
// Written out label by label rather than copied, because an origin read // out of a message may be compressed, and what goes in `buf` has to stand // on its own. var labels_of_origin = origin.labels(); while (labels_of_origin.next()) |label| { // One byte for the length, the label itself, and the root byte that // still has to fit after it. if (out + 1 + label.len >= buf.len) return error.NameTooLong; buf[out] = @intCast(label.len); @memcpy(buf[out + 1 ..][0..label.len], label); out += 1 + label.len; } if (out >= buf.len) return error.NameTooLong; buf[out] = 0; return .{ .message = buf[0 .. out + 1], .offset = 0 };}
/// Whether a name written in presentation form ends where it says it does:/// whether the dot on the end, if there is one, is a real separator rather/// than an escaped dot inside the last label.////// A resolver asks this before applying its search list, and gets it wrong by/// looking at the last byte: `a\.` ends with a dot and is relative.pub fn textIsAbsolute(text: []const u8) bool { var i: usize = 0; var dot = false; while (i < text.len) { if (text[i] == '\\') { // Whatever follows a backslash is part of a label, whether it is // one character or the three digits of a `\DDD`. A backslash with // nothing after it is a malformed name; `fromText` says so, and it // is not absolute either way. if (i + 1 >= text.len) return false; i += 2; dot = false; } else { dot = text[i] == '.'; i += 1; } } return dot;}
/// How many labels a name written in presentation form has, not counting the/// root -- counting the way the DNS counts rather than the way a dot does, so/// that `a\.b` is one label and not two.////// This is what `ndots` is measured against: a resolver's dot count is this/// number minus one.pub fn textLabelCount(text: []const u8) usize { var count: usize = 0; var i: usize = 0; var in_label = false; while (i < text.len) { switch (text[i]) { '\\' => { if (i + 1 >= text.len) break; i += 2; in_label = true; }, '.' => { if (in_label) count += 1; in_label = false; i += 1; }, else => { in_label = true; i += 1; }, } } return count + @intFromBool(in_label);}
/// A name written out at compile time, checked at compile time, and backed by/// constant data -- so it needs no buffer and can be a declaration:////// ```zig/// const localhost = dns.Name.literal("localhost");/// ```////// A name this will not accept is a compile error rather than a runtime one,/// which is the whole reason to reach for it over `fromText`.pub fn literal(comptime text: []const u8) Name { const encoded = comptime blk: { var buf: Buffer = undefined; const name = fromText(&buf, text) catch |err| @compileError("not a domain name: \"" ++ text ++ "\": " ++ @errorName(err)); var out: [name.message.len]u8 = undefined; @memcpy(&out, name.message); break :blk out; }; return .{ .message = &encoded, .offset = 0 };}
/// Walks the labels of a name, following compression pointers, from the/// leftmost to the last before the root.pub const LabelIterator = struct { message: []const u8, pos: u16, /// How many more bytes of expanded name may be read. It exists only for /// names that did not come from `parse`: a validated name can never run it /// out, and for one that was never validated it is what stops a pointer /// cycle rather than the iterator spinning. budget: u16 = max_encoded_len,
/// The next label, or `null` at the root -- and also `null` if the name is /// malformed, which for a name from `parse` cannot happen. pub fn next(self: *LabelIterator) ?[]const u8 { while (true) { if (self.pos >= self.message.len) return null; const byte = self.message[self.pos]; switch (byte & 0xc0) { 0x00 => { if (byte == 0) return null; const start = @as(usize, self.pos) + 1; const end = start + byte; if (end > self.message.len) return null; if (self.budget < 1 + @as(u16, byte)) return null; self.budget -= 1 + @as(u16, byte); self.pos = @intCast(end); return self.message[start..end]; }, 0xc0 => { if (@as(usize, self.pos) + 1 >= self.message.len) return null; const target: u16 = @as(u16, byte & 0x3f) << 8 | self.message[self.pos + 1]; if (target >= self.pos) return null; self.pos = target; }, else => return null, } } }
/// The name made of the labels not yet returned: after `next` has given /// back `www`, this is `example.com`. Every suffix of a name is itself a /// name in the same message, which is the whole basis of compression. pub fn rest(self: LabelIterator) Name { return .{ .message = self.message, .offset = self.pos }; }};
/// The labels of this name, leftmost first.pub fn labels(self: Name) LabelIterator { return .{ .message = self.message, .pos = self.offset };}
/// Whether this is the root, `.`, the one name with no labels.pub fn isRoot(self: Name) bool { var it = self.labels(); return it.next() == null;}
/// How many labels the name has, not counting the root: `www.example.com` has/// three, and the root has none.pub fn labelCount(self: Name) u8 { var count: u8 = 0; var it = self.labels(); while (it.next() != null) count += 1; return count;}
/// How many bytes the name takes written out in full, with no compression.pub fn encodedLen(self: Name) u16 { var total: u16 = 1; // the root's zero byte var it = self.labels(); while (it.next()) |label| total += 1 + @as(u16, @intCast(label.len)); return total;}
/// The name with its first label removed: the parent of `www.example.com` is/// `example.com`. The root has no parent, and answers `null`.pub fn parent(self: Name) ?Name { var it = self.labels(); if (it.next() == null) return null; return it.rest();}
/// Drops the first `n` labels. A name with `n` labels or fewer gives back the/// root, which is what "the zone `n` levels up" means when you run out of/// name.pub fn suffix(self: Name, n: usize) Name { var it = self.labels(); var dropped: usize = 0; while (dropped < n) : (dropped += 1) { if (it.next() == null) return .{ .message = self.message, .offset = it.pos }; } return it.rest();}
/// Whether two names are the same name. Case is ignored, as RFC 4343 requires:/// the comparison is per byte and ASCII-only, so a label holding bytes above/// 127 is compared exactly, which is what makes a name holding UTF-8 behave.pub fn eql(a: Name, b: Name) bool { var ai = a.labels(); var bi = b.labels(); while (true) { const x = ai.next(); const y = bi.next(); if (x == null and y == null) return true; if (x == null or y == null) return false; if (!ascii.eqlIgnoreCase(x.?, y.?)) return false; }}
/// Whether two names are the same name *and* the same bytes.////// `eql` is the comparison DNS defines and almost always the one to use. This/// one exists for the places where the spelling is not free to change: name/// compression, where replacing a name with a pointer to a differently-cased/// copy would alter what was sent, and any check on a query whose name was/// randomly cased to make an off-path answer harder to forge (DNS-0x20), where/// the case *is* the nonce.pub fn eqlExact(a: Name, b: Name) bool { var ai = a.labels(); var bi = b.labels(); while (true) { const x = ai.next(); const y = bi.next(); if (x == null and y == null) return true; if (x == null or y == null) return false; if (!std.mem.eql(u8, x.?, y.?)) return false; }}
/// A hash that agrees with `eql`: two names that compare equal hash the same,/// whatever case their labels were written in. What a cache keyed by name/// wants, since the case a name arrives in is not part of the name.pub fn hash(self: Name) u64 { var hasher = std.hash.Wyhash.init(0); var it = self.labels(); while (it.next()) |label| { // The length goes in as well as the bytes, or `a.bc` and `ab.c` would // be the same name to this and to nothing else. hasher.update(&[_]u8{@intCast(label.len)}); for (label) |c| hasher.update(&[_]u8{ascii.toLower(c)}); } return hasher.final();}
/// Canonical DNS name order (RFC 4034 §6.1): names sort by their labels read/// right to left, from the root outwards, with each label compared as if it/// were lowercase. This is the order a zone is signed in, and the reason/// `*.example.com` sorts where it does.pub fn order(a: Name, b: Name) std.math.Order { var a_labels: [max_labels][]const u8 = undefined; var b_labels: [max_labels][]const u8 = undefined; var a_count: usize = 0; var b_count: usize = 0;
var ai = a.labels(); while (ai.next()) |label| : (a_count += 1) a_labels[a_count] = label; var bi = b.labels(); while (bi.next()) |label| : (b_count += 1) b_labels[b_count] = label;
var i: usize = 0; while (i < a_count and i < b_count) : (i += 1) { const x = a_labels[a_count - 1 - i]; const y = b_labels[b_count - 1 - i]; switch (orderLabel(x, y)) { .eq => {}, else => |o| return o, } } return std.math.order(a_count, b_count);}
fn orderLabel(x: []const u8, y: []const u8) std.math.Order { const shared = @min(x.len, y.len); for (x[0..shared], y[0..shared]) |p, q| { const lp = ascii.toLower(p); const lq = ascii.toLower(q); if (lp != lq) return std.math.order(lp, lq); } return std.math.order(x.len, y.len);}
/// Whether `self` is at or below `ancestor`: `www.example.com` is a subdomain/// of `example.com`, of `com`, and of the root, and also of itself.pub fn isSubdomainOf(self: Name, ancestor: Name) bool { const mine = self.labelCount(); const theirs = ancestor.labelCount(); if (mine < theirs) return false; return self.suffix(mine - theirs).eql(ancestor);}
/// Writes the name out in full, uncompressed. To write one with compression,/// use `Builder`, which is what knows where the earlier copies are.pub fn writeTo(self: Name, w: *Writer) Writer.Error!void { var it = self.labels(); while (it.next()) |label| { try w.writeByte(@intCast(label.len)); try w.writeAll(label); } try w.writeByte(0);}
/// Writes the name in the canonical form of RFC 4034 §6.2: uncompressed, and/// with every label lowercased.////// This is the form a name is *hashed* in rather than the form it is sent in./// DNSSEC signs it, and TSIG (RFC 8945 §4.3.3) digests the key name and the/// algorithm name this way -- so a signature computed over `writeTo` instead/// verifies against one peer and not another, depending on which of them typed/// the name in capitals.pub fn writeCanonical(self: Name, w: *Writer) Writer.Error!void { var it = self.labels(); while (it.next()) |label| { try w.writeByte(@intCast(label.len)); for (label) |c| try w.writeByte(ascii.toLower(c)); } try w.writeByte(0);}
/// Copies the name out uncompressed into `buf`, returning the bytes written./// This is how a name outlives the message it was read from.pub fn toBytes(self: Name, buf: *Buffer) []u8 { var out: usize = 0; var it = self.labels(); while (it.next()) |label| { buf[out] = @intCast(label.len); @memcpy(buf[out + 1 ..][0..label.len], label); out += 1 + label.len; } buf[out] = 0; return buf[0 .. out + 1];}
/// The same name over a buffer of your own, with no pointers left in it and no/// reference to the message it came from.pub fn clone(self: Name, buf: *Buffer) Name { return .{ .message = self.toBytes(buf), .offset = 0 };}
/// Writes the name in presentation form, always with the trailing dot, with/// the escaping of RFC 1035 §5.1: `\.` and `\\`, `\DDD` for any byte that is/// not printable ASCII, and a backslash before the handful of characters a/// zone file gives its own meaning.pub fn format(self: Name, w: *Writer) Writer.Error!void { var it = self.labels(); var any = false; while (it.next()) |label| { any = true; for (label) |c| { switch (c) { '.', '\\', '"', '(', ')', ';', '@', '$', ' ' => { try w.writeByte('\\'); try w.writeByte(c); }, else => if (c >= 0x21 and c <= 0x7e) try w.writeByte(c) else try w.print("\\{d:0>3}", .{c}), } } try w.writeByte('.'); } if (!any) try w.writeByte('.');}
/// The presentation form, written into `buf`. `TextBuffer` is always big/// enough.pub fn toText(self: Name, buf: []u8) error{NoSpaceLeft}![]u8 { var w = Writer.fixed(buf); self.format(&w) catch return error.NoSpaceLeft; return w.buffered();}
const testing = std.testing;
test "a name on its own" { var buf: Buffer = undefined; const name = try fromText(&buf, "www.example.com"); try testing.expectEqual(@as(u8, 3), name.labelCount()); try testing.expectEqual(@as(u16, 17), name.encodedLen()); try testing.expectFmt("www.example.com.", "{f}", .{name}); try testing.expectEqualSlices( u8, "\x03www\x07example\x03com\x00", name.message, );}
test "the root is the empty name" { var buf: Buffer = undefined; for ([_][]const u8{ "", "." }) |text| { const name = try fromText(&buf, text); try testing.expect(name.isRoot()); try testing.expectEqual(@as(u8, 0), name.labelCount()); try testing.expectFmt(".", "{f}", .{name}); } try testing.expect(root.isRoot());}
test "a trailing dot changes nothing" { var a: Buffer = undefined; var b: Buffer = undefined; try testing.expect((try fromText(&a, "example.com")).eql(try fromText(&b, "example.com.")));}
test "text escapes" { var buf: Buffer = undefined; const name = try fromText(&buf, "a\\.b.example"); var it = name.labels(); try testing.expectEqualStrings("a.b", it.next().?); try testing.expectEqualStrings("example", it.next().?); try testing.expectFmt("a\\.b.example.", "{f}", .{name});
const spaced = try fromText(&buf, "a\\032b"); var spaced_labels = spaced.labels(); try testing.expectEqualStrings("a b", spaced_labels.next().?); try testing.expectFmt("a\\ b.", "{f}", .{spaced});
try testing.expectError(error.BadEscape, fromText(&buf, "a\\")); try testing.expectError(error.BadEscape, fromText(&buf, "a\\99")); try testing.expectError(error.BadEscape, fromText(&buf, "a\\256")); try testing.expectError(error.EmptyLabel, fromText(&buf, "a..b")); try testing.expectError(error.EmptyLabel, fromText(&buf, ".a")); try testing.expectError(error.LabelTooLong, fromText(&buf, "a" ** 64)); try testing.expectError(error.NameTooLong, fromText(&buf, ("a" ** 63 ++ ".") ** 4 ++ "b"));}
test "a relative name takes the origin, and an absolute one does not" { var buf: Buffer = undefined; const origin = literal("example.com");
try testing.expectFmt("www.example.com.", "{f}", .{ try fromTextRelative(&buf, "www", origin), }); try testing.expectFmt("a.b.example.com.", "{f}", .{ try fromTextRelative(&buf, "a.b", origin), }); // A trailing dot means the name is already what it is. try testing.expectFmt("www.example.net.", "{f}", .{ try fromTextRelative(&buf, "www.example.net.", origin), }); // The empty name is relative and has no labels of its own. try testing.expectFmt("example.com.", "{f}", .{ try fromTextRelative(&buf, "", origin), }); // And the root is absolute however it is written. try testing.expectFmt(".", "{f}", .{try fromTextRelative(&buf, ".", origin)});
// `fromText` is this with the root as the origin, which is what makes a // name without a trailing dot mean itself. try testing.expectFmt("www.example.com.", "{f}", .{ try fromTextRelative(&buf, "www.example.com", root), });}
test "the trailing dot that decides it has to be an unescaped one" { var buf: Buffer = undefined; const origin = literal("example.com");
// `a\.` is one label holding a dot, and is relative: the origin goes // after it. Deciding by looking at the last byte gets this wrong. const escaped = try fromTextRelative(&buf, "a\\.", origin); try testing.expectEqual(@as(u8, 3), escaped.labelCount()); try testing.expectFmt("a\\..example.com.", "{f}", .{escaped});
try testing.expect(!textIsAbsolute("a\\.")); try testing.expect(textIsAbsolute("a.")); try testing.expect(textIsAbsolute("a\\..")); try testing.expect(!textIsAbsolute("a")); try testing.expect(!textIsAbsolute("")); try testing.expect(!textIsAbsolute("a\\")); // `\046` is a dot by its number, and is no more a separator than `\.` is. try testing.expect(!textIsAbsolute("a\\046"));}
test "labels are counted the way the DNS counts them" { try testing.expectEqual(@as(usize, 0), textLabelCount("")); try testing.expectEqual(@as(usize, 0), textLabelCount(".")); try testing.expectEqual(@as(usize, 1), textLabelCount("www")); try testing.expectEqual(@as(usize, 1), textLabelCount("www.")); try testing.expectEqual(@as(usize, 3), textLabelCount("www.example.com")); try testing.expectEqual(@as(usize, 3), textLabelCount("www.example.com.")); // One label with a dot in it is one label, which is the whole point. try testing.expectEqual(@as(usize, 1), textLabelCount("a\\.b")); try testing.expectEqual(@as(usize, 2), textLabelCount("a\\.b.c")); try testing.expectEqual(@as(usize, 1), textLabelCount("a\\046b"));
// Every name that encodes agrees with what the count said. var buf: Buffer = undefined; for ([_][]const u8{ "", ".", "www", "www.", "www.example.com", "a\\.b", "a\\.b.c" }) |text| { const name = try fromText(&buf, text); try testing.expectEqual(textLabelCount(text), name.labelCount()); }}
test "an origin that does not fit is a name too long" { var buf: Buffer = undefined; const long = literal("a" ** 63 ++ "." ++ "b" ** 63 ++ "." ++ "c" ** 63); // 192 bytes of origin leaves 62 for the name in front of it, root and all. _ = try fromTextRelative(&buf, "d" ** 61, long); try testing.expectError(error.NameTooLong, fromTextRelative(&buf, "d" ** 62, long));}
test "an origin read out of a message is written out in full" { // `example.com` at offset 0, and `www` at 13 pointing back at it. const message = "\x07example\x03com\x00\x03www\xc0\x00"; const compressed = try parse(message, 13); try testing.expect(compressed.encodedLen() != compressed.wireLen());
var buf: Buffer = undefined; const name = try fromTextRelative(&buf, "ftp", compressed); // Nothing in `buf` points anywhere: it is a name that stands on its own. try testing.expect((try fromBytes(name.message)).eql(name)); try testing.expectFmt("ftp.www.example.com.", "{f}", .{name});}
test "a compressed name is followed" { // `example.com` at offset 0, then `www` at offset 13 pointing back at it. const message = "\x07example\x03com\x00" ++ "\x03www\xc0\x00"; const first = try parse(message, 0); const second = try parse(message, 13); try testing.expectFmt("example.com.", "{f}", .{first}); try testing.expectFmt("www.example.com.", "{f}", .{second}); // The second name occupies six bytes where it stands, and seventeen once // it is written out. try testing.expectEqual(@as(u16, 6), second.wireLen()); try testing.expectEqual(@as(u16, 17), second.encodedLen()); try testing.expect(second.parent().?.eql(first)); try testing.expect(second.isSubdomainOf(first)); try testing.expect(!first.isSubdomainOf(second));}
test "malformed names are refused" { try testing.expectError(error.Truncated, parse("\x03ww", 0)); try testing.expectError(error.Truncated, parse("\x03www", 0)); // A pointer to itself, and a pointer forwards. try testing.expectError(error.BadPointer, parse("\xc0\x00", 0)); try testing.expectError(error.BadPointer, parse("\xc0\x04\x00\x00\x00", 0)); // The reserved label types. try testing.expectError(error.ReservedLabelType, parse("\x40\x00", 0)); try testing.expectError(error.ReservedLabelType, parse("\x80\x00", 0));}
test "a pointer loop is bounded by the length limit" { // A label followed by a pointer back to it. Every jump is backwards, as // the rule requires, so what ends the walk is the 255-byte limit: each // time round adds two bytes to the expanded name, and after 127 laps // there is no room for more. try testing.expectError(error.NameTooLong, parse("\x01a\xc0\x00", 0));}
test "comparison ignores case but equality is not order" { var a: Buffer = undefined; var b: Buffer = undefined; const upper = try fromText(&a, "EXAMPLE.COM"); const lower = try fromText(&b, "example.com"); try testing.expect(upper.eql(lower)); try testing.expectEqual(std.math.Order.eq, upper.order(lower)); // The labels are kept exactly as they were given. var upper_labels = upper.labels(); try testing.expectEqualStrings("EXAMPLE", upper_labels.next().?);}
test "canonical order sorts from the root outwards" { // The example from RFC 4034 section 6.1. const texts = [_][]const u8{ "example", "a.example", "yljkjljk.a.example", "Z.a.example", "zABC.a.EXAMPLE", "z.example", "\\001.z.example", "*.z.example", "\\200.z.example", }; var buffers: [texts.len]Buffer = undefined; var names: [texts.len]Name = undefined; for (texts, 0..) |text, i| names[i] = try fromText(&buffers[i], text); for (names[0 .. names.len - 1], names[1..]) |lhs, rhs| { try testing.expectEqual(std.math.Order.lt, lhs.order(rhs)); }}
test "clone leaves the message behind" { const message = "\x07example\x03com\x00" ++ "\x03www\xc0\x00"; var buf: Buffer = undefined; const copied = (try parse(message, 13)).clone(&buf); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", copied.message); try testing.expectFmt("www.example.com.", "{f}", .{copied}); // And a copy is a name that stands on its own. try testing.expect((try fromBytes(copied.message)).eql(copied));}
test "a standalone name must be exactly one name" { try testing.expectError(error.TrailingBytes, fromBytes("\x01a\x00\x00")); try testing.expectError(error.Compressed, fromBytes("\x03www\xc0\x00")); try testing.expectError(error.Truncated, fromBytes("\x03ww"));}
test "suffixes bottom out at the root" { var buf: Buffer = undefined; const name = try fromText(&buf, "a.b.c"); try testing.expectFmt("b.c.", "{f}", .{name.suffix(1)}); try testing.expectFmt("c.", "{f}", .{name.suffix(2)}); try testing.expectFmt(".", "{f}", .{name.suffix(3)}); try testing.expectFmt(".", "{f}", .{name.suffix(99)}); try testing.expect(name.isSubdomainOf(root));}
test "a literal name is checked when it is compiled" { const name = literal("www.example.com"); try testing.expectFmt("www.example.com.", "{f}", .{name}); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", name.message); try testing.expect(literal(".").isRoot());}
test "the hash agrees with equality" { var a: Buffer = undefined; var b: Buffer = undefined; const upper = try fromText(&a, "EXAMPLE.com"); const lower = try fromText(&b, "example.COM"); try testing.expect(upper.eql(lower)); try testing.expectEqual(upper.hash(), lower.hash());
// And a name that only looks the same does not collide by construction. try testing.expect(literal("a.bc").hash() != literal("ab.c").hash());
// A compressed name hashes as what it expands to. const message = "\x07example\x03com\x00" ++ "\x03www\xc0\x00"; try testing.expectEqual(literal("www.example.com").hash(), (try parse(message, 13)).hash());}
test "exact equality keeps the case that plain equality ignores" { const upper = literal("EXAMPLE.com"); const lower = literal("example.com"); try testing.expect(upper.eql(lower)); try testing.expect(!upper.eqlExact(lower)); try testing.expect(upper.eqlExact(literal("EXAMPLE.com")));}
test "the two pointer rules differ only on a message nothing generated" { // A name whose one pointer aims *into its own first label*, at a byte the // label held as content and so nothing ever read as a length. That byte is // zero, so the name ends there and what comes out is well formed. // // 0: 02 a label two bytes long // 1: 00 58 its content, which is also where the pointer lands // 3: c0 01 a pointer to offset 1 const message = "\x02\x00X\xc0\x01";
const permissive = try parse(message, 0); try testing.expectEqual(@as(u8, 1), permissive.labelCount()); var it = permissive.labels(); try testing.expectEqualStrings("\x00X", it.next().?); try testing.expectFmt("\\000X.", "{f}", .{permissive}); try testing.expectEqual(@as(u16, 5), permissive.wireLen());
// The pointer is behind itself, which is all the default rule asks, and // not behind where the name started, which is what the other one asks. try testing.expectError(error.BadPointer, parseWithOptions(message, 0, .{ .pointers = .descending, }));}
test "an ordinary compressed name passes under either rule" { const message = "\x07example\x03com\x00" ++ "\x03www\xc0\x00"; for ([_]Options{ .{}, .{ .pointers = .descending } }) |options| { const name = try parseWithOptions(message, 13, options); try testing.expectFmt("www.example.com.", "{f}", .{name}); } // And a loop is refused under either. for ([_]Options{ .{}, .{ .pointers = .descending } }) |options| { try testing.expectError( if (options.pointers == .backwards) error.NameTooLong else error.BadPointer, parseWithOptions("\x01a\xc0\x00", 0, options), ); }}