Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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,} || Name.Error;
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, /// How forgiving to be about the parts of a name the wire format leaves /// under-specified. See `Name.Options`. names: Name.Options = .{},
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, };
pub fn init(message: []const u8) InitError!Decoder { if (message.len > max_message_len) return error.MessageTooLong; return .{ .message = message }; }
/// 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. pub fn at(self: Decoder, pos: u16) Decoder { return .{ .message = self.message, .pos = pos, .names = self.names }; }
/// How many bytes are left before the end of the message. pub fn remaining(self: Decoder) u16 { return @intCast(self.message.len - self.pos); }
pub fn atEnd(self: Decoder) bool { return self.pos >= self.message.len; }
/// 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); }
/// 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 @enumFromInt(try self.int(@typeInfo(E).@"enum".tag_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.pos..][0..n]; self.pos += n; return out; }
/// Everything from here to the end of the message. pub fn takeRest(self: *Decoder) []const u8 { const out = self.message[self.pos..]; self.pos = @intCast(self.message.len); return out; }
pub fn skip(self: *Decoder, n: u16) Error!void { _ = try self.take(n); }
/// 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.parseCountedWithOptions(self.message, self.pos, self.names); self.pos += parsed.wire_len; return parsed.name; }
/// 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); }};
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);}