// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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. The walk is short as well as finite, because of what a pointer is //! allowed to lead to. //! //! RFC 1035 says a pointer names "a prior occurrence of the same name", and //! this reads *prior* as wholly prior: the name a pointer leads to must end //! before the stretch of name holding the pointer began. So every target is //! below the last, and no loop can be reached at all. A pointer must also lead //! to a label rather than to another pointer, so every jump is paid for with //! at least two bytes of the 255 an expanded name may have, and no name takes //! more than 127 jumps. Without that, a crafted message could make one name //! take thousands, and make every record that names it take them again. //! //! Nothing that compresses a name produces either thing these rules refuse. 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 led somewhere it may not: to a name that does not /// end before the stretch of name holding the pointer began, or to another /// pointer. RFC 1035 §4.1.4 only ever defines a pointer as naming a *prior* /// occurrence of a name, and nothing that compresses one produces either. BadPointer, /// The name ran off the end of the message. Truncated, /// The name is longer than 255 bytes once expanded. NameTooLong, }; 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) Error!Scan { var pos: usize = start; var wire_len: ?u16 = null; var encoded_len: u16 = 0; var label_count: u8 = 0; // Where the stretch of name being read began, and the offset everything // in that stretch must lie below. The first stretch is the name as it was // written and may run to the end of the message; each one after it was // reached by a pointer, and must end before the stretch that pointed at it // began. var stretch: usize = start; var limit: usize = message.len; while (true) { if (pos >= limit) return if (limit == message.len) error.Truncated else error.BadPointer; 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 > limit) return if (limit == message.len) error.Truncated else error.BadPointer; encoded_len += 1 + @as(u16, byte); if (encoded_len > max_encoded_len) return error.NameTooLong; label_count += 1; pos = end; }, 0xc0 => { if (pos + 1 >= limit) return if (limit == message.len) error.Truncated else error.BadPointer; const target: u16 = @as(u16, byte & 0x3f) << 8 | message[pos + 1]; if (wire_len == null) wire_len = @intCast(pos + 2 - start); if (target >= stretch) return error.BadPointer; if (message[target] & 0xc0 == 0xc0) return error.BadPointer; limit = stretch; stretch = 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, /// The bytes to advance by: every label up to and including the root /// byte, or up to and including the first pointer. For a compressed name /// that is the labels written here and the pointer's two bytes, not the /// length of what the pointer leads to. wire_len: u16, /// Whether reading it followed a compression pointer. compressed: bool, }; /// 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 { const s = try scan(message, offset); return .{ .name = .{ .message = message, .offset = offset }, .wire_len = s.wire_len, .compressed = s.compressed, }; } test parseCounted { // `example.com` at 0, and `www` at 13 pointing back at it. const msg = "\x07example\x03com\x00\x03www\xc0\x00"; const parsed = try parseCounted(msg, 13); try testing.expectFmt("www.example.com.", "{f}", .{parsed.name}); // What a decoder moves on by: the six bytes written here, not seventeen. try testing.expectEqual(@as(u16, 6), parsed.wire_len); try testing.expect(parsed.compressed); } /// 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; } test parse { const msg = "\x07example\x03com\x00\x03www\xc0\x00"; try testing.expectFmt("www.example.com.", "{f}", .{try parse(msg, 13)}); // A pointer to itself leads to no prior name, and is refused. try testing.expectError(error.BadPointer, parse("\xc0\x00", 0)); } /// How many bytes the name occupies at the offset it was read from, which is /// what a decoder advances by: for a compressed name, the labels before the /// first pointer and the pointer itself. Walking the name again to find out, /// so prefer `parseCounted` where both are wanted. pub fn wireLen(self: Name) u16 { // A name that did not scan could not have become a `Name`. const s = scan(self.message, self.offset) catch unreachable; return s.wire_len; } test wireLen { const msg = "\x07example\x03com\x00\x03www\xc0\x00"; try testing.expectEqual(@as(u16, 13), (try parse(msg, 0)).wireLen()); // `www` and a two-byte pointer. try testing.expectEqual(@as(u16, 6), (try parse(msg, 13)).wireLen()); } 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 can // only lead back into that same name, so following it would be refused as // a bad pointer -- 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 }; } test fromBytes { const name = try fromBytes("\x03www\x07example\x03com\x00"); try testing.expectFmt("www.example.com.", "{f}", .{name}); // A pointer needs the message it points into, and there is none here. try testing.expectError(error.Compressed, fromBytes("\x03www\xc0\x00")); } 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); } test fromText { var buf: Buffer = undefined; const name = try fromText(&buf, "www.example.com"); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", name.message); // `\.` is a dot inside a label rather than one between two. try testing.expectEqual(@as(u8, 3), (try fromText(&buf, "a\\.b.example.com")).labelCount()); } /// 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 }; } test fromTextRelative { var buf: Buffer = undefined; const origin = literal("example.com"); try testing.expectFmt("www.example.com.", "{f}", .{try fromTextRelative(&buf, "www", origin)}); // A trailing dot says the name is already complete. try testing.expectFmt("www.example.net.", "{f}", .{try fromTextRelative(&buf, "www.example.net.", origin)}); } /// 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; } test textIsAbsolute { try testing.expect(textIsAbsolute("www.example.com.")); try testing.expect(!textIsAbsolute("www")); // It ends in a dot, but an escaped one. try testing.expect(!textIsAbsolute("a\\.")); } /// 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); } test textLabelCount { try testing.expectEqual(@as(usize, 3), textLabelCount("www.example.com.")); // One label, holding a dot. try testing.expectEqual(@as(usize, 1), textLabelCount("a\\.b")); } /// 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 }; } test literal { const localhost = literal("localhost"); try testing.expectEqualSlices(u8, "\x09localhost\x00", localhost.message); } /// 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, } } } test next { var it = literal("www.example.com").labels(); try testing.expectEqualStrings("www", it.next().?); try testing.expectEqualStrings("example", it.next().?); try testing.expectEqualStrings("com", it.next().?); // The root is the end, and has no label of its own. try testing.expectEqual(@as(?[]const u8, null), it.next()); } /// 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 }; } test rest { var it = literal("www.example.com").labels(); _ = it.next(); try testing.expectFmt("example.com.", "{f}", .{it.rest()}); } }; /// The labels of this name, leftmost first. pub fn labels(self: Name) LabelIterator { return .{ .message = self.message, .pos = self.offset }; } test labels { // A compressed name's labels come out as though it were written in full. const msg = "\x07example\x03com\x00\x03www\xc0\x00"; var it = (try parse(msg, 13)).labels(); try testing.expectEqualStrings("www", it.next().?); try testing.expectEqualStrings("example", it.next().?); try testing.expectEqualStrings("com", it.next().?); try testing.expectEqual(@as(?[]const u8, null), it.next()); } /// 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; } test isRoot { try testing.expect(root.isRoot()); try testing.expect(literal(".").isRoot()); try testing.expect(!literal("com").isRoot()); } /// 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; } test labelCount { try testing.expectEqual(@as(u8, 3), literal("www.example.com").labelCount()); try testing.expectEqual(@as(u8, 0), root.labelCount()); } /// 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; } test encodedLen { // Six bytes where it stands, seventeen written out. const msg = "\x07example\x03com\x00\x03www\xc0\x00"; try testing.expectEqual(@as(u16, 17), (try parse(msg, 13)).encodedLen()); try testing.expectEqual(@as(u16, 1), root.encodedLen()); } /// 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(); } test parent { try testing.expectFmt("example.com.", "{f}", .{literal("www.example.com").parent().?}); try testing.expectEqual(@as(?Name, null), root.parent()); } /// 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(); } test suffix { const www = literal("www.example.com"); try testing.expectFmt("com.", "{f}", .{www.suffix(2)}); // Running out of name leaves the root. try testing.expectFmt(".", "{f}", .{www.suffix(5)}); } /// 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; } } test eql { // Case does not matter, and neither does compression. const msg = "\x07example\x03com\x00\x03www\xc0\x00"; try testing.expect(literal("WWW.Example.COM").eql(try parse(msg, 13))); try testing.expect(!literal("www.example.com").eql(literal("www.example.net"))); } /// 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; } } test eqlExact { // A query sent as `wWw.ExAmple.cOm` wants that spelling back (DNS-0x20). const sent = literal("wWw.ExAmple.cOm"); try testing.expect(sent.eqlExact(literal("wWw.ExAmple.cOm"))); try testing.expect(!sent.eqlExact(literal("www.example.com"))); } /// 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(); } test hash { try testing.expectEqual(literal("EXAMPLE.com").hash(), literal("example.COM").hash()); } /// 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); } test order { // Read from the root outwards, `a.example` is under `example`, and // `example` sorts after `b`. try testing.expectEqual(std.math.Order.gt, literal("a.example").order(literal("b"))); // RFC 4034 section 6.1's pair: with case ignored, `z` is a prefix of `zabc`. try testing.expectEqual(std.math.Order.lt, literal("Z.a.example").order(literal("zABC.a.EXAMPLE"))); } 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); } test isSubdomainOf { const www = literal("www.example.com"); try testing.expect(www.isSubdomainOf(literal("example.com"))); try testing.expect(www.isSubdomainOf(www)); try testing.expect(www.isSubdomainOf(root)); // Whole labels only: `badexample.com` is no part of `example.com`. try testing.expect(!literal("badexample.com").isSubdomainOf(literal("example.com"))); } /// 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); } test writeTo { const msg = "\x07example\x03com\x00\x03www\xc0\x00"; var buf: [32]u8 = undefined; var w: Writer = .fixed(&buf); try (try parse(msg, 13)).writeTo(&w); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", w.buffered()); } /// 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); } test writeCanonical { var buf: [32]u8 = undefined; var w: Writer = .fixed(&buf); try literal("WWW.Example.com").writeCanonical(&w); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", w.buffered()); } /// 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]; } test toBytes { const msg = "\x07example\x03com\x00\x03www\xc0\x00"; var buf: Buffer = undefined; const bytes = (try parse(msg, 13)).toBytes(&buf); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", bytes); } /// 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 }; } test clone { var buf: Buffer = undefined; var msg: [19]u8 = "\x07example\x03com\x00\x03www\xc0\x00".*; const kept = (try parse(&msg, 13)).clone(&buf); // The message can be reused for the next one, and the copy does not mind. @memset(&msg, 0); try testing.expectFmt("www.example.com.", "{f}", .{kept}); } /// 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('.'); } test format { var buf: Buffer = undefined; try testing.expectFmt("www.example.com.", "{f}", .{literal("www.example.com")}); // A space and a dot inside labels, escaped so the text reads back the same. try testing.expectFmt("a\\ b.c\\.d.example.", "{f}", .{try fromText(&buf, "a\\032b.c\\.d.example")}); try testing.expectFmt(".", "{f}", .{root}); } /// 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(); } test toText { var buf: TextBuffer = undefined; try testing.expectEqualStrings("www.example.com.", try literal("www.example.com").toText(&buf)); var small: [8]u8 = undefined; try testing.expectError(error.NoSpaceLeft, literal("www.example.com").toText(&small)); } 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, &@as([64]u8, @splat('a')))); try testing.expectError(error.NameTooLong, fromText(&buf, @as([4 * 64]u8, @bitCast(@as([4][64]u8, @splat(@as([63]u8, @splat('a')) ++ ".".*)))) ++ "b")); } test "a decimal escape takes ASCII digits only" { // RFC 1035 section 5.1's \DDD is three ASCII digits. A digit from another // script is not one, so a \DDD it interrupts is refused: here a // superscript two, U+00B2, in the middle of one. var buf: Buffer = undefined; try testing.expectError(error.BadEscape, fromText(&buf, "a\\1\xc2\xb23")); // And a backslash in front of one escapes just that byte, as it would any // other character -- here the first byte of ARABIC-INDIC DIGIT ONE, // U+0661, rather than a decimal escape for the number it means. const escaped = try fromText(&buf, "a\\\xd9\xa1"); var it = escaped.labels(); try testing.expectEqualStrings("a\xd9\xa1", it.next().?); } 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(@as([63]u8, @splat('a')) ++ "." ++ @as([63]u8, @splat('b')) ++ "." ++ @as([63]u8, @splat('c'))); // 192 bytes of origin leaves 62 for the name in front of it, root and all. _ = try fromTextRelative(&buf, &@as([61]u8, @splat('d')), long); try testing.expectError(error.NameTooLong, fromTextRelative(&buf, &@as([62]u8, @splat('d')), 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 back into its own name is refused" { // A label followed by a pointer back to it: a loop, and the pointer leads // into the very stretch of name that holds it. try testing.expectError(error.BadPointer, 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 "an ordinary compressed name is read through each pointer" { // example.com, then www pointing at it, then a pointing at www: two jumps. const message = "\x07example\x03com\x00" ++ "\x03www\xc0\x00" ++ "\x01a\xc0\x0d"; try testing.expectFmt("www.example.com.", "{f}", .{try parse(message, 13)}); try testing.expectFmt("a.www.example.com.", "{f}", .{try parse(message, 19)}); } test "a pointer into its own label is refused" { // A name whose one pointer aims at a byte its first label held as content, // and so nothing ever read as a length. That byte is zero, so following // the pointer would end the name there with nothing malformed in what came // out -- but what it leads to is not a name that came before. // // 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 try testing.expectError(error.BadPointer, parse("\x02\x00X\xc0\x01", 0)); } test "a target that runs on over the pointer is refused" { // The pointer at 3 leads to a four-byte label at 0, whose content is the // pointer's own two bytes. It points backwards, but the name it leads to // does not end before the pointer -- it is made of it. // // 0: 04 a label four bytes long // 1: 78 79 its first two bytes // 3: c0 00 a pointer to offset 0, and the label's last two bytes // 5: 00 the root const message = "\x04xy\xc0\x00\x00"; try testing.expectError(error.BadPointer, parse(message, 3)); // Read from the start, the same bytes are an ordinary name. try testing.expectEqual(@as(u8, 1), (try parse(message, 0)).labelCount()); } test "a pointer to a pointer is refused" { // 0: 07 example 00 a name // 9: c0 00 a pointer to it, which is fine // 11: c0 09 a pointer to the pointer, which is not const message = "\x07example\x00" ++ "\xc0\x00" ++ "\xc0\x09"; try testing.expectFmt("example.", "{f}", .{try parse(message, 9)}); try testing.expectError(error.BadPointer, parse(message, 11)); } test "a long chain of pointers is refused at its first jump" { // A name, then thousands of pointers each aimed at the one before, which // is what a message would hold to make every name in it cost thousands of // jumps. Each pointer is below the last, so only the rule against a // pointer leading to a pointer stops it -- and it stops it at once. var message: [max_pointer_offset + 1]u8 = undefined; @memcpy(message[0..3], "\x01a\x00"); var pos: usize = 3; var previous: u16 = 0; while (pos + 2 <= message.len) : (pos += 2) { message[pos] = 0xc0 | @as(u8, @intCast(previous >> 8)); message[pos + 1] = @truncate(previous); previous = @intCast(pos); } try testing.expectFmt("a.", "{f}", .{try parse(&message, 3)}); try testing.expectError(error.BadPointer, parse(&message, previous)); } test "a name may take more jumps than dnspython allows" { // Eighteen names, each one label in front of a pointer to the one before: // the last takes seventeen jumps, every one of them to a label. dnspython // stops at sixteen; here the 255-byte limit is what bounds the count. var message: [3 + 17 * 4]u8 = undefined; @memcpy(message[0..3], "\x01a\x00"); var previous: u16 = 0; var pos: usize = 3; while (pos < message.len) : (pos += 4) { @memcpy(message[pos..][0..2], "\x01b"); message[pos + 2] = 0xc0; message[pos + 3] = @intCast(previous); previous = @intCast(pos); } try testing.expectEqual(@as(u8, 18), (try parse(&message, previous)).labelCount()); }