Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! One resource record: an owner name, a type and class, a time to live, and//! the data.//!//! The data is **not** parsed when the record is. A resolver walking a//! response for one type should not pay to decode the twelve records it is not//! looking for, and a record of a type it has never heard of should cost it//! nothing at all. So a `Record` holds the data's bytes and where they sit in//! the message, and `data` decodes them when asked.
const std = @import("std");const Writer = std.Io.Writer;
const Name = @import("Name.zig");const record_data = @import("rdata.zig");const types = @import("types.zig");const wire = @import("wire.zig");
const Record = @This();
/// The name this record is about.name: Name,/// What kind of record it is. For an `opt` record this is the only field that/// means what it says; see `edns`.type: types.Type,/// Nearly always `in`. An `opt` record keeps its payload size here instead.class: types.Class,/// How many seconds this may be cached for. An `opt` record keeps its version/// and flags here instead.ttl: u32,/// The record data exactly as it appeared, borrowing the message.rdata: []const u8,/// The whole message, because a name inside the data may be compressed and so/// may reach back into it.message: []const u8,/// Where the data begins in `message`.rdata_offset: u16,/// Where the record begins in `message` -- the first byte of its owner name,/// which is where `rdata_offset` minus the ten fixed bytes minus the name's/// encoded length would land. Kept rather than recomputed because the/// arithmetic needs `Name.wireLen`, which walks the name again, and because/// anything hashing a record (TSIG, RFC 8945 §4.3.4, which digests a message/// up to where its signature begins) needs it to be exact rather than/// approximately right.start: u16,
/// Reads one record: the owner, the fixed fields, and the length that frames/// the data -- but not the data itself, which `data` decodes when asked. `d`/// has to be a decoder over the whole message, because the owner may be a/// pointer back into it. Most callers want `Message.answers` and its siblings,/// which do this at the right offset.pub fn parse(d: *wire.Decoder) wire.Error!Record { const start = d.pos; const name = try d.name(); const record_type = try d.enumeration(types.Type); const class = try d.enumeration(types.Class); const ttl = try d.int(u32); const length = try d.int(u16); const offset = d.pos; return .{ .name = name, .type = record_type, .class = class, .ttl = ttl, .rdata = try d.take(length), .message = d.message, .rdata_offset = offset, .start = start, };}
test parse { // `example.com. 300 IN A 192.0.2.1`, on its own. var d = try wire.Decoder.init("\x07example\x03com\x00" ++ "\x00\x01\x00\x01\x00\x00\x01\x2c\x00\x04" ++ "\xc0\x00\x02\x01"); const record = try parse(&d); try testing.expectEqual(types.Type.a, record.type); try testing.expectEqual(@as(u32, 300), record.ttl); try testing.expectEqualSlices(u8, "\xc0\x00\x02\x01", record.rdata);}
/// The record exactly as it appeared, owner name and all, borrowing the/// message.////// `rdata` is the data alone; this is the whole record, which is what/// something re-encoding it or hashing what came before it needs. Note that/// the owner name inside it may be a compression pointer, so these bytes mean/// what they say only in the message they came from.pub fn bytes(self: Record) []const u8 { return self.message[self.start .. self.rdata_offset + self.rdata.len];}
test bytes { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); try b.record(.answer, .{ .name = Name.literal("example.com"), .ttl = 300, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); const message = try Message.parse(b.finish()); var it = message.answers(); const record = (try it.next()).?; // The owner is a pointer to the question's name, so the whole record is // two bytes of that, ten fixed ones, and four of data. try testing.expectEqualSlices( u8, "\xc0\x0c" ++ "\x00\x01\x00\x01\x00\x00\x01\x2c\x00\x04" ++ "\xc0\x00\x02\x01", record.bytes(), );}
/// A decoder over the record's data, with the message cut off at the end of/// it. Cutting it off is what makes a field inside the data unable to read/// past the record it belongs to, while leaving everything a compression/// pointer could name still in place -- a pointer has to lead to a name that/// ends before the pointer begins.pub fn rdataDecoder(self: Record) wire.Decoder { return .{ .message = self.message[0 .. self.rdata_offset + self.rdata.len], .pos = self.rdata_offset, };}
test rdataDecoder { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.record(.answer, .{ .name = Name.literal("example.com"), .data = .{ .mx = .{ .preference = 10, .exchange = Name.literal("mail.example.com") } }, }); const message = try Message.parse(b.finish()); var it = message.answers(); const record = (try it.next()).?;
// Reading the MX by hand. The exchange was compressed against the owner, // and the pointer still has the owner to land on. var d = record.rdataDecoder(); try testing.expectEqual(@as(u16, 10), try d.int(u16)); try testing.expectFmt("mail.example.com.", "{f}", .{try d.name()}); try testing.expect(d.atEnd());}
/// Decodes the record data. Records of a type this library has no parser for/// come back as `unknown` rather than as an error; see `rdata`.////// Data that breaks its type's shape -- a length that does not fit the type,/// a name with a bad pointer, a compressed name in a type that forbids/// compression -- is refused. Data that breaks only a rule about what a field/// currently means is carried through, because a later registry entry may/// make it correct.pub fn data(self: Record) record_data.Error!record_data.Data { var d = self.rdataDecoder(); return record_data.Data.parse(self.type, &d);}
test data { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.record(.answer, .{ .name = Name.literal("example.com"), .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); const message = try Message.parse(b.finish()); var it = message.answers(); switch (try (try it.next()).?.data()) { .a => |address| try testing.expectFmt("192.0.2.1", "{f}", .{address}), else => return error.TestUnexpectedResult, }}
/// Whether two records are the same record: same owner, class, type and data.////// The time to live is deliberately not compared, because it is not part of/// what a record says -- two caches holding the same record will disagree/// about it, and RFC 2181 §5.2 says the difference is not a difference.////// The data is compared as bytes, which means two records that say the same/// thing but compressed a name inside it differently are not equal here. That/// is the right answer for "did this record arrive twice" and the wrong one/// for "do these two messages agree"; for the second, compare what `data`/// gives back, or compare the two records' printed forms.pub fn eql(a: Record, b: Record) bool { return a.type == b.type and a.class == b.class and a.name.eql(b.name) and std.mem.eql(u8, a.rdata, b.rdata);}
test eql { // The same record twice, the second from a cache that has counted its TTL // down and that spells the owner in capitals. var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); const address: record_data.Data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }; try b.record(.answer, .{ .name = Name.literal("example.com"), .ttl = 300, .data = address }); try b.record(.answer, .{ .name = Name.literal("EXAMPLE.com"), .ttl = 60, .data = address }); const message = try Message.parse(b.finish()); var it = message.answers(); const first = (try it.next()).?; const second = (try it.next()).?; try testing.expect(first.eql(second));}
/// As a zone file writes it: owner, TTL, class, type, then the data. When the/// data cannot be decoded it is written in the `\# length hex` form of RFC/// 3597, which is the honest thing to print for bytes that did not make sense.pub fn format(self: Record, w: *Writer) Writer.Error!void { try w.print("{f}\t{d}\t{f}\t{f}\t", .{ self.name, self.ttl, self.class, self.type }); if (self.data()) |decoded| { try w.print("{f}", .{decoded}); } else |_| { try @import("presentation.zig").writeUnknownRdata(w, self.rdata); }}
test format { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.record(.answer, .{ .name = Name.literal("example.com"), .ttl = 300, .data = .{ .mx = .{ .preference = 10, .exchange = Name.literal("mail.example.com") } }, }); const message = try Message.parse(b.finish()); var it = message.answers(); try testing.expectFmt( "example.com.\t300\tIN\tMX\t10 mail.example.com.", "{f}", .{(try it.next()).?}, );}
const testing = std.testing;const Builder = @import("Builder.zig");const Message = @import("Message.zig");
test "a record and its data" { const message = "\x07example\x03com\x00\x00\x01\x00\x01\x00\x00\x01\x2c\x00\x04\xc0\x00\x02\x01"; var d = try wire.Decoder.init(message); const record = try Record.parse(&d); try testing.expect(d.atEnd()); try testing.expectEqual(types.Type.a, record.type); try testing.expectEqual(@as(u32, 300), record.ttl); try testing.expectFmt("example.com.\t300\tIN\tA\t192.0.2.1", "{f}", .{record}); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, &(try record.data()).a.octets);}
test "the data cannot read past the record it belongs to" { // A CNAME whose length says four bytes, holding a name that would run on // into the record after it if the decoder let it. const message = "\x00\x00\x05\x00\x01\x00\x00\x00\x00\x00\x04\x03www\x07example\x03com\x00"; var d = try wire.Decoder.init(message); const record = try Record.parse(&d); try testing.expectError(error.Truncated, record.data());}
test "a record whose data does not decode still prints" { const message = "\x00\x00\x01\x00\x01\x00\x00\x00\x00\x00\x03\x01\x02\x03"; var d = try wire.Decoder.init(message); const record = try Record.parse(&d); try testing.expectError(error.Truncated, record.data()); try testing.expectFmt(".\t0\tIN\tA\t\\# 3 010203", "{f}", .{record});}