// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reading fixed-width fields out of a message, with the bounds check in one //! place rather than at every call site. //! //! Everything on the wire is big-endian, and every read is against a message //! that may have been truncated or made up, so the only two things a decoder //! has to get right are the byte order and the end of the buffer. A `Decoder` //! is a position in a message; `Name` is the one field type that needs the //! whole message rather than the bytes at the position, which is why a decoder //! keeps both. const std = @import("std"); const Name = @import("Name.zig"); /// The largest a DNS message can be. It is not a protocol constant so much as /// a consequence of one: RFC 1035 §4.2.2 frames a message over TCP with a /// two-byte length, so nothing can carry a longer one. pub const max_message_len = 65535; pub const Error = error{ /// The field ran off the end of the message. Truncated, /// A name inside record data held a compression pointer where its type's /// specification says it must be written out in full. RFC 3597 §4 allows /// compression only in the types RFC 1035 defined and a short list after /// them, and every type defined since forbids it, because a server that /// does not know a type cannot rewrite the pointers in it. CompressionForbidden, } || Name.Error; /// Whether a name inside record data may hold a compression pointer, for the /// readers shared by types on both sides of RFC 3597 §4's line. pub const Compression = enum { allowed, forbidden, }; pub const Decoder = struct { /// The whole message. Not a window on it: a compression pointer in a name /// may reach anywhere earlier in the message, so the bytes before `pos` /// have to still be here. message: []const u8, /// How far through the message reading has got. pos: u16 = 0, pub const InitError = error{ /// A message longer than 65535 bytes, which nothing can send and no /// compression pointer could address the far end of. MessageTooLong, }; /// A decoder at the start of `message`, which it borrows. The length is /// checked once here so that every position after it fits a `u16`. pub fn init(message: []const u8) InitError!Decoder { if (message.len > max_message_len) return error.MessageTooLong; return .{ .message = message }; } test init { var d = try Decoder.init("\x12\x34"); try testing.expectEqual(@as(u16, 0x1234), try d.int(u16)); try testing.expectError(error.MessageTooLong, Decoder.init(&@as([max_message_len + 1]u8, @splat(0)))); } /// A decoder over the same message, reading from `pos`. Used to read the /// inside of a record's data without losing the message around it. A /// `pos` past the end is not an error here; every read from it is /// `error.Truncated`, as one at the end would be. pub fn at(self: Decoder, pos: u16) Decoder { return .{ .message = self.message, .pos = pos }; } test at { // `example.com` at 0, and `www` at 13 pointing back at it. const d = try Decoder.init("\x07example\x03com\x00\x03www\xc0\x00"); var inner = d.at(13); try testing.expectFmt("www.example.com.", "{f}", .{try inner.name()}); // The original is where it was. try testing.expectEqual(@as(u16, 0), d.pos); } test "a decoder aimed past the end reads nothing, and does not crash" { const d = try Decoder.init("\x00\x01"); var past = d.at(7); try testing.expectEqual(@as(u16, 0), past.remaining()); try testing.expect(past.atEnd()); try testing.expectError(error.Truncated, past.int(u8)); try testing.expectError(error.Truncated, past.take(1)); try testing.expectEqualSlices(u8, "", try past.take(0)); try testing.expectError(error.Truncated, past.name()); try testing.expectEqualSlices(u8, "", past.takeRest()); } /// How many bytes are left before the end of the message: none, for a /// decoder whose position is past it. pub fn remaining(self: Decoder) u16 { return @intCast(self.message.len -| self.pos); } test remaining { var d = try Decoder.init("\x00\x01\x02\x03\x04"); try d.skip(2); try testing.expectEqual(@as(u16, 3), d.remaining()); } /// Whether everything in the message has been read. Over a record's data, /// it is what tells data that ended where its length said apart from data /// with bytes left over. pub fn atEnd(self: Decoder) bool { return self.pos >= self.message.len; } test atEnd { var d = try Decoder.init("\x00\x2a"); try testing.expect(!d.atEnd()); _ = try d.int(u16); try testing.expect(d.atEnd()); } /// An unsigned big-endian integer of any whole number of bytes. pub fn int(self: *Decoder, comptime T: type) Error!T { const size = @divExact(@typeInfo(T).int.bits, 8); const bytes = try self.take(size); return std.mem.readInt(T, bytes[0..size], .big); } test int { // A TTL of one hour, as it is on the wire. var d = try Decoder.init("\x00\x00\x0e\x10\x01"); try testing.expectEqual(@as(u32, 3600), try d.int(u32)); // One byte left, and a `u16` needs two. try testing.expectError(error.Truncated, d.int(u16)); } /// The number behind an enum, kept even when it is one the enum has no /// name for -- which is the point of every registry enum here being /// non-exhaustive. pub fn enumeration(self: *Decoder, comptime E: type) Error!E { return @fromBackingInt(try self.int(@typeInfo(E).@"enum".tag_type)); } test enumeration { const Type = @import("types.zig").Type; var d = try Decoder.init("\x00\x1c\xff\x00"); try testing.expectEqual(Type.aaaa, try d.enumeration(Type)); // A type nobody has named yet is still that type. try testing.expectFmt("TYPE65280", "{f}", .{try d.enumeration(Type)}); } /// The next `n` bytes, which borrow the message. pub fn take(self: *Decoder, n: u16) Error![]const u8 { if (self.remaining() < n) return error.Truncated; const out = self.message[self.clamped()..][0..n]; self.pos += n; return out; } test take { // The four bytes of an `a` record's data. var d = try Decoder.init("\xc0\x00\x02\x01"); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, try d.take(4)); try testing.expectError(error.Truncated, d.take(1)); } /// Everything from here to the end of the message. pub fn takeRest(self: *Decoder) []const u8 { const out = self.message[self.clamped()..]; self.pos = @intCast(self.message.len); return out; } test takeRest { var d = try Decoder.init("\x00\x10hello"); try d.skip(2); try testing.expectEqualStrings("hello", d.takeRest()); try testing.expect(d.atEnd()); } /// The position, or the end of the message if the position is past it, /// so that slicing from it cannot go out of bounds. fn clamped(self: Decoder) usize { return @min(self.pos, self.message.len); } /// Moves past `n` bytes without looking at them, refusing to move past the /// end of the message. pub fn skip(self: *Decoder, n: u16) Error!void { _ = try self.take(n); } test skip { var d = try Decoder.init("\x00\x00\x00\x2a"); try d.skip(3); try testing.expectEqual(@as(u8, 42), try d.int(u8)); try testing.expectError(error.Truncated, d.skip(1)); } /// A domain name, following any compression pointers in it, leaving the /// position after the name *as it was written here* -- which for a /// compressed name is two bytes for the pointer and not the length of what /// it expands to. pub fn name(self: *Decoder) Error!Name { const parsed = try Name.parseCounted(self.message, self.pos); self.pos += parsed.wire_len; return parsed.name; } test name { // `example.com` at 0, and `www` at 13 pointing back at it. var d = (try Decoder.init("\x07example\x03com\x00\x03www\xc0\x00")).at(13); try testing.expectFmt("www.example.com.", "{f}", .{try d.name()}); // Six bytes read, not the seventeen the name expands to. try testing.expectEqual(@as(u16, 19), d.pos); } /// A domain name in a field whose specification says it is never /// compressed. One that is anyway is refused rather than followed, since /// it can only have come from an encoder that got its own types wrong. pub fn uncompressedName(self: *Decoder) Error!Name { const parsed = try Name.parseCounted(self.message, self.pos); if (parsed.compressed) return error.CompressionForbidden; self.pos += parsed.wire_len; return parsed.name; } test uncompressedName { const d = try Decoder.init("\x07example\x03com\x00\x03www\xc0\x00"); var whole = d.at(0); try testing.expectFmt("example.com.", "{f}", .{try whole.uncompressedName()}); // The same bytes `name` would follow are refused here. var pointed = d.at(13); try testing.expectError(error.CompressionForbidden, pointed.uncompressedName()); } /// `name` or `uncompressedName`, as `compression` says. pub fn nameWith(self: *Decoder, compression: Compression) Error!Name { return switch (compression) { .allowed => self.name(), .forbidden => self.uncompressedName(), }; } test nameWith { const d = try Decoder.init("\x07example\x03com\x00\x03www\xc0\x00"); var allowed = d.at(13); try testing.expectFmt("www.example.com.", "{f}", .{try allowed.nameWith(.allowed)}); var forbidden = d.at(13); try testing.expectError(error.CompressionForbidden, forbidden.nameWith(.forbidden)); } /// A character-string (RFC 1035 §3.3): one length byte and up to 255 bytes /// of anything. This, not a domain name, is what `txt` and `hinfo` are /// made of, and it is why a long TXT value arrives in pieces. pub fn characterString(self: *Decoder) Error![]const u8 { const len = try self.int(u8); return self.take(len); } test characterString { // The data of a TXT record holding two strings. var d = try Decoder.init("\x05hello\x05world"); try testing.expectEqualStrings("hello", try d.characterString()); try testing.expectEqualStrings("world", try d.characterString()); try testing.expect(d.atEnd()); } }; const testing = std.testing; test "reads are big-endian and bounded" { var d = try Decoder.init("\x12\x34\x00\x00\x00\x3c\x05hello"); try testing.expectEqual(@as(u16, 0x1234), try d.int(u16)); try testing.expectEqual(@as(u32, 60), try d.int(u32)); try testing.expectEqualStrings("hello", try d.characterString()); try testing.expect(d.atEnd()); try testing.expectError(error.Truncated, d.int(u8)); } test "a character-string that overruns is refused" { var d = try Decoder.init("\x05hel"); try testing.expectError(error.Truncated, d.characterString()); } test "a decoder can be re-aimed without losing the message" { const message = "\x07example\x03com\x00\x03www\xc0\x00"; var d = try Decoder.init(message); _ = try d.name(); try testing.expectEqual(@as(u16, 13), d.pos); var inner = d.at(13); const name = try inner.name(); try testing.expectFmt("www.example.com.", "{f}", .{name}); try testing.expectEqual(@as(u16, 19), inner.pos); }