Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Writing a message into a buffer you supply.//!//! Nothing here allocates. A `Builder` is a position in a caller's buffer, a//! running tally of what has gone into each section, and a table of where the//! names it has already written begin -- which is all that name compression//! needs.//!//! ### Running out of room is normal//!//! A DNS server does not decide how big its answer will be; it discovers it.//! So `question`, `record` and `opt` are **atomic**: when one returns//! `error.NoSpace` the builder is exactly as it was before the call, with no//! half-written record and no compression pointers aimed at bytes that were//! rolled back. Filling a response is therefore a loop and a `catch`://!//! ```zig//! for (answers) |rr| builder.record(.answer, rr) catch |err| switch (err) {//! error.NoSpace => {//! builder.setTruncated();//! break;//! },//! else => return err,//! };//! const message = builder.finish();//! ```//!//! ### What gets compressed//!//! Owner names and question names always. Inside record data, only the types//! RFC 1035 defined, because RFC 3597 §4 forbids compressing names in anything//! newer: a resolver that does not know the type cannot find the names to//! expand, so a pointer there would be unreadable to exactly the software the//! rule exists to protect. DNSSEC types are additionally never compressed//! because a validator has to be able to reconstruct the bytes that were//! signed, and `Builder` never points a later name at a name it wrote//! uncompressed, for the same reason.//!//! ### What is not checked//!//! Record data is written exactly as it is described. A decoder refuses data//! that breaks a type's shape -- an `ipv4hint` that is not whole addresses, an//! NSEC3 with no next hashed owner name, a CAA tag with a space in it -- but//! `Builder` writes whatever it is handed, so a message built from values//! nobody checked may be one `Message.parse` will not read back. That is//! deliberate: it is how a test makes a malformed message on purpose, and//! anything decoded from a message has passed the checks already. Framing is//! another matter: a record whose data could not be framed, or a section//! count that would overflow, is refused here as it would be there.
const std = @import("std");
const Header = @import("Header.zig");const Name = @import("Name.zig");const Question = @import("Question.zig");const rdata = @import("rdata.zig");const types = @import("types.zig");const wire = @import("wire.zig");
const Builder = @This();
/// How many distinct names are remembered as compression targets. A message/// with more names than this still encodes; the ones past the limit are simply/// written out in full.pub const max_compression_entries = 128;
/// The caller's buffer, capped at the longest a message may be.buffer: []u8,/// How much of it has been written.pos: u16 = Header.len,/// The header as it will be written by `finish`, with the counts replaced by/// what was actually added.header: Header,counts: Header.Counts = .{},/// The last section written to, so that writing them out of order can be/// refused rather than producing a message whose counts lie.last_section: ?Header.Section = null,/// Where each remembered name begins, in the order they were written.targets: [max_compression_entries]u16 = undefined,target_count: u8 = 0,/// Whether to compress at all. Off is the right answer when the bytes are/// going to be hashed or signed, or handed to something that gets compression/// wrong.compression: bool = true,
pub const Error = error{ /// The buffer is full. The builder is unchanged; see the note above. NoSpace, /// A section was written to after a later one had been started. The wire /// format has no way to express that, since a section is found by counting /// past the ones before it. OutOfOrder, /// A section would hold more than 65535 entries, which its count cannot /// express. TooManyRecords, /// One record's data came to more than 65535 bytes, which its length field /// cannot express. RdataTooLong,};
/// How a builder writes.pub const Options = struct { /// Whether names may be compressed. See the note above on what is /// compressed when this is on. compression: bool = true,};
/// Starts a message in `buffer`. The header is written immediately, with/// every count zero, and written again by `finish` with the counts of what/// was actually added -- so a buffer looked at half way through is still a/// message, and the counts in `header` are ignored. A buffer longer than a/// message may be is used only up to that length.pub fn init(buffer: []u8, header: Header, options: Options) Error!Builder { if (buffer.len < Header.len) return error.NoSpace; var self: Builder = .{ .buffer = buffer[0..@min(buffer.len, wire.max_message_len)], .header = header, .compression = options.compression, }; self.writeHeader(); return self;}
test init { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 0x1234, .recursion_desired = true }, .{}); // A header and nothing else is already a message. const message = try Message.parse(b.finish()); try testing.expectEqual(@as(u16, 0x1234), message.header.id);
// Less room than a header is refused before anything is written. var tiny: [Header.len - 1]u8 = undefined; try testing.expectError(error.NoSpace, init(&tiny, .{ .id = 1 }, .{}));}
fn writeHeader(self: *Builder) void { var header = self.header; header.counts = self.counts; const bytes = header.toBytes(); @memcpy(self.buffer[0..Header.len], &bytes);}
/// Marks the message truncated. What is already in the buffer stays: that is/// what the flag means -- this is the beginning of the answer, ask again over/// something that can carry the rest.pub fn setTruncated(self: *Builder) void { self.header.truncated = true;}
test setTruncated { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .txt }); b.setTruncated(); const message = try Message.parse(b.finish()); try testing.expect(message.header.truncated); try testing.expectEqual(@as(u16, 1), message.header.counts.question);}
/// How many bytes are left.pub fn remaining(self: Builder) u16 { return @intCast(self.buffer.len - self.pos);}
test remaining { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1 }, .{}); try testing.expectEqual(@as(u16, 512 - Header.len), b.remaining()); // `example.com` is thirteen bytes, and the type and class four more. try b.question(.{ .name = Name.literal("example.com"), .type = .a }); try testing.expectEqual(@as(u16, 512 - Header.len - 17), b.remaining());}
/// Fills in the counts and returns the message. The builder may be used again/// afterwards; `finish` only writes the header.pub fn finish(self: *Builder) []u8 { self.writeHeader(); return self.buffer[0..self.pos];}
test finish { var buf: [512]u8 = undefined; // The counts given here are not the ones that go out. var b = try init(&buf, .{ .id = 1, .counts = .{ .answer = 5 } }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); const message = try Message.parse(b.finish()); try testing.expectEqual(@as(u16, 1), message.header.counts.question); try testing.expectEqual(@as(u16, 0), message.header.counts.answer);}
/// Everything that has to be undone if a record does not fit.const Mark = struct { pos: u16, target_count: u8 };
fn mark(self: Builder) Mark { return .{ .pos = self.pos, .target_count = self.target_count };}
fn restore(self: *Builder, m: Mark) void { self.pos = m.pos; self.target_count = m.target_count;}
fn beginSection(self: *Builder, section: Header.Section) Error!void { if (self.last_section) |last| { if (@backingInt(section) < @backingInt(last)) return error.OutOfOrder; } if (self.counts.get(section) == std.math.maxInt(u16)) return error.TooManyRecords; self.last_section = section;}
/// Adds an entry to the question section.pub fn question(self: *Builder, q: Question) Error!void { try self.beginSection(.question); const m = self.mark(); errdefer self.restore(m);
try self.name(q.name, .compressed); try self.int(u16, @backingInt(q.type)); try self.int(u16, @backingInt(q.class)); self.counts.question += 1;}
test question { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1, .recursion_desired = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .aaaa }); const message = try Message.parse(b.finish()); try testing.expectFmt("example.com.\tIN\tAAAA", "{f}", .{(try message.question()).?});}
/// A record to be written. The type comes from `data`, which is the only place/// it could come from without the two being able to disagree.pub const RecordSpec = struct { /// The owner: the name the record is about. name: Name, class: types.Class = .in, /// How long the record may be cached, in seconds. Zero means do not cache. ttl: u32 = 0, data: rdata.Data,};
/// Adds a record to one of the three record sections. Sections must be written/// in order; see `Error.OutOfOrder`.pub fn record(self: *Builder, section: Header.Section, rr: RecordSpec) Error!void { std.debug.assert(section != .question); try self.beginSection(section); const m = self.mark(); errdefer self.restore(m);
try self.name(rr.name, .compressed); try self.int(u16, @backingInt(rr.data.recordType())); try self.int(u16, @backingInt(rr.class)); try self.int(u32, rr.ttl);
// The length is not known until the data has been written, so leave room // and come back for it. const length_at = self.pos; try self.int(u16, 0); try rr.data.writeTo(self); const length = self.pos - length_at - 2; std.mem.writeInt(u16, self.buffer[length_at..][0..2], length, .big);
self.counts.getPtr(section).* += 1;}
test record { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .mx }); try b.record(.answer, .{ .name = Name.literal("example.com"), .ttl = 3600, .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.\t3600\tIN\tMX\t10 mail.example.com.", "{f}", .{(try it.next()).?}, );
// The answer section is done once the additional section is started. try b.opt(.{}); try testing.expectError(error.OutOfOrder, b.record(.answer, .{ .name = Name.literal("example.com"), .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }));}
/// Adds the EDNS(0) `opt` pseudo-record, which is how a message says how large/// an answer it can receive, carries the high bits of an extended response/// code, and asks for DNSSEC records. It belongs in the additional section and/// there may be only one.pub fn opt(self: *Builder, o: @import("edns.zig").Opt) Error!void { try self.record(.additional, o.toRecordSpec());}
test opt { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1, .recursion_desired = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); try b.opt(.{ .udp_payload_size = 1232, .dnssec_ok = true });
const message = try Message.parse(b.finish()); const edns0 = (try message.opt()).?; try testing.expectEqual(@as(u16, 1232), edns0.udp_payload_size); try testing.expect(edns0.dnssec_ok);}
// -- the pieces the record data writers use ---------------------------------
/// Raw bytes, as they are. Either all of them fit or none is written.pub fn writeAll(self: *Builder, bytes: []const u8) Error!void { if (self.remaining() < bytes.len) return error.NoSpace; @memcpy(self.buffer[self.pos..][0..bytes.len], bytes); self.pos += @intCast(bytes.len);}
test writeAll { var buf: [Header.len + 3]u8 = undefined; var b = try init(&buf, .{ .id = 1 }, .{}); try b.writeAll("\xde\xad"); try testing.expectEqualSlices(u8, "\xde\xad", b.finish()[Header.len..]); // Two more do not fit in the one byte left, so neither is written. try testing.expectError(error.NoSpace, b.writeAll("\xbe\xef")); try testing.expectEqual(@as(u16, 1), b.remaining());}
/// One raw byte.pub fn writeByte(self: *Builder, byte: u8) Error!void { if (self.remaining() < 1) return error.NoSpace; self.buffer[self.pos] = byte; self.pos += 1;}
test writeByte { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1 }, .{}); try b.writeByte(0x2a); try testing.expectEqualSlices(u8, "\x2a", b.finish()[Header.len..]);}
/// An unsigned big-endian integer of any whole number of bytes.pub fn int(self: *Builder, comptime T: type, value: T) Error!void { const size = @divExact(@typeInfo(T).int.bits, 8); if (self.remaining() < size) return error.NoSpace; std.mem.writeInt(T, self.buffer[self.pos..][0..size], value, .big); self.pos += size;}
test int { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1 }, .{}); try b.int(u16, 0x1234); // TSIG's six-byte time is as easy as any other width. try b.int(u48, 1_700_000_000); try testing.expectEqualSlices( u8, "\x12\x34" ++ "\x00\x00\x65\x53\xf1\x00", b.finish()[Header.len..], );}
/// A character-string: one length byte and up to 255 bytes after it.pub fn characterString(self: *Builder, bytes: []const u8) Error!void { if (bytes.len > 255) return error.RdataTooLong; if (self.remaining() < 1 + bytes.len) return error.NoSpace; try self.writeByte(@intCast(bytes.len)); try self.writeAll(bytes);}
test characterString { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1 }, .{}); try b.characterString("hello"); try testing.expectEqualSlices(u8, "\x05hello", b.finish()[Header.len..]);
// A length byte cannot count past 255. const long: [256]u8 = @splat('x'); try testing.expectError(error.RdataTooLong, b.characterString(&long));}
/// Whether a name may be replaced by a pointer to an earlier copy of it.pub const Compressibility = enum { /// Owner names, question names, and the names inside the record types RFC /// 1035 defined. compressed, /// Everything else. See the note at the top of this file. uncompressed,};
/// Writes a domain name, compressed against the names already in the message/// when that is allowed and one of them shares a suffix with this one.pub fn name(self: *Builder, value: Name, how: Compressibility) Error!void { // So that this is atomic on its own as well as inside a record: a name // that ran out of room half way through would otherwise leave compression // targets pointing at bytes that are about to be written over. const m = self.mark(); errdefer self.restore(m);
const compress = how == .compressed and self.compression;
// The longest suffix of this name that has already been written, if any. // Suffix `i` is this name with its first `i` labels dropped, so the index // of the match is also the number of labels that still have to be written // out in full. var matched_labels: ?usize = null; var matched_offset: u16 = 0; if (compress) { var suffix = value; var dropped: usize = 0; search: while (!suffix.isRoot()) : (dropped += 1) { for (self.targets[0..self.target_count]) |target| { const candidate: Name = .{ .message = self.buffer[0..self.pos], .offset = target }; // Byte for byte, not the case-insensitive comparison DNS // defines elsewhere. Two names that differ only in case are // the same name, but replacing one with a pointer to the other // changes the bytes that go out -- which loses whatever the // sender meant by the case it chose, and that is sometimes a // nonce (DNS-0x20). A fuzzer found this: a message with // `nsz.example.com` and `nsZ.example.com` in it came back with // two of the first. if (suffix.eqlExact(candidate)) { matched_labels = dropped; matched_offset = target; break :search; } } suffix = suffix.parent().?; } }
var labels = value.labels(); var written: usize = 0; while (matched_labels == null or written < matched_labels.?) : (written += 1) { const label = labels.next() orelse break; // Remembered before it is written, because what is remembered is where // the *suffix starting here* begins. Offsets above 0x3fff cannot be // named by a pointer, the other two bits being the tag that makes it // one. if (compress and self.pos <= Name.max_pointer_offset and self.target_count < max_compression_entries) { self.targets[self.target_count] = self.pos; self.target_count += 1; } try self.writeByte(@intCast(label.len)); try self.writeAll(label); }
if (matched_labels != null) { try self.writeByte(0xc0 | @as(u8, @intCast(matched_offset >> 8))); try self.writeByte(@truncate(matched_offset)); } else { try self.writeByte(0); }}
test name { var buf: [512]u8 = undefined; var b = try init(&buf, .{ .id = 1 }, .{}); try b.name(Name.literal("example.com"), .compressed); try b.name(Name.literal("www.example.com"), .compressed); try b.name(Name.literal("www.example.com"), .uncompressed); try testing.expectEqualSlices( u8, "\x07example\x03com\x00" ++ // `www`, then a pointer to `example.com` at offset twelve. "\x03www\xc0\x0c" ++ // The same name again, written out in full because it was asked to be. "\x03www\x07example\x03com\x00", b.finish()[Header.len..], );}
const testing = std.testing;const Message = @import("Message.zig");
test "a query" { var buf: [512]u8 = undefined; var names: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 0x1234, .recursion_desired = true }, .{}); try b.question(.{ .name = try Name.fromText(&names, "example.com"), .type = .a }); try testing.expectEqualSlices( u8, "\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00" ++ "\x07example\x03com\x00\x00\x01\x00\x01", b.finish(), );}
test "names are compressed against earlier ones" { var buf: [512]u8 = undefined; var a: Name.Buffer = undefined; var c: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = try Name.fromText(&a, "www.example.com"), .type = .a }); try b.record(.answer, .{ .name = try Name.fromText(&a, "www.example.com"), .ttl = 300, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); try b.record(.authority, .{ .name = try Name.fromText(&c, "example.com"), .ttl = 300, .data = .{ .ns = try Name.fromText(&a, "ns1.example.com") }, }); const message = b.finish();
// The owner of the answer is the whole question name: two bytes. try testing.expectEqualSlices(u8, "\xc0\x0c", message[33..35]);
// And it all reads back as what went in. const parsed = try Message.parse(message); var answers = parsed.answers(); const answer = (try answers.next()).?; try testing.expectFmt("www.example.com.", "{f}", .{answer.name}); var authority = parsed.authority(); const ns = (try authority.next()).?; try testing.expectFmt("example.com.", "{f}", .{ns.name}); try testing.expectFmt("ns1.example.com.", "{f}", .{(try ns.data()).ns});}
test "names that differ only in case are not compressed together" { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); const lower = Name.literal("nsz.example.com"); const upper = Name.literal("nsZ.example.com"); try b.record(.answer, .{ .name = lower, .data = .{ .ns = lower } }); try b.record(.answer, .{ .name = upper, .data = .{ .ns = upper } });
const message = try Message.parse(b.finish()); var it = message.answers(); var seen: [2][]const u8 = undefined; var text: [2]Name.TextBuffer = undefined; for (0..2) |i| seen[i] = try (try it.next()).?.name.toText(&text[i]); try testing.expectEqualStrings("nsz.example.com.", seen[0]); try testing.expectEqualStrings("nsZ.example.com.", seen[1]);}
test "compression can be turned off" { var buf: [512]u8 = undefined; var a: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 1 }, .{ .compression = false }); const name_value = try Name.fromText(&a, "www.example.com"); try b.question(.{ .name = name_value, .type = .a }); try b.record(.answer, .{ .name = name_value, .data = .{ .a = .{ .octets = .{ 1, 2, 3, 4 } } } }); const message = b.finish(); try testing.expectEqualSlices(u8, "\x03www\x07example\x03com\x00", message[33..50]);}
test "a record that does not fit leaves the message it did not fit in alone" { var names: Name.Buffer = undefined; const name_value = try Name.fromText(&names, "example.com");
// Room for the header, the question, and nothing else. var buf: [12 + 17]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = name_value, .type = .a }); const before = b.pos; try testing.expectError(error.NoSpace, b.record(.answer, .{ .name = name_value, .data = .{ .a = .{ .octets = .{ 1, 2, 3, 4 } } }, })); try testing.expectEqual(before, b.pos);
b.setTruncated(); const message = b.finish(); const parsed = try Message.parse(message); try testing.expect(parsed.header.truncated); try testing.expectEqual(@as(u16, 1), parsed.header.counts.question); try testing.expectEqual(@as(u16, 0), parsed.header.counts.answer);}
test "sections must be written in order" { var buf: [512]u8 = undefined; var names: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 1 }, .{}); try b.record(.authority, .{ .name = try Name.fromText(&names, "example.com"), .data = .{ .ns = Name.root }, }); try testing.expectError(error.OutOfOrder, b.record(.answer, .{ .name = try Name.fromText(&names, "example.com"), .data = .{ .a = .{ .octets = .{ 1, 2, 3, 4 } } }, }));}