Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A whole DNS message: a header and four sections, read out of a buffer.//!//! `parse` walks the whole message before returning anything. That costs one//! pass and buys two things: a `Message` is known to have sound framing, so//! nothing later can be surprised by a section that ended early, and each//! section's starting offset is known, so reading the answers does not mean//! re-walking the questions. What it does *not* do is decode any record's//! data -- see `Record`.//!//! When even that is too much, `Header.parse` on the first twelve bytes is//! always available: a server that must answer a malformed query with a//! `formerr` needs the identifier out of a message it has already decided not//! to trust.//!//! Everything here borrows the buffer. A `Message` is a view, not a copy.
const std = @import("std");const Writer = std.Io.Writer;
const Header = @import("Header.zig");const Name = @import("Name.zig");const Question = @import("Question.zig");const Record = @import("Record.zig");const edns = @import("edns.zig");const types = @import("types.zig");const wire = @import("wire.zig");
const Message = @This();
/// Which of the four sections.pub const Section = Header.Section;
/// The bytes the message was read from.bytes: []const u8,header: Header,/// Where each section begins. The question section always begins at twelve;/// the rest are only known once what is before them has been walked.starts: [4]u16,/// Where the last section ended. Anything after this is not part of the/// message; see `trailing`.end: u16,
/// Why a message could not be read: it was longer than a message may be, or/// its framing is broken somewhere -- a count, a length or a name.pub const Error = wire.Decoder.InitError || wire.Error || Header.Error;
/// Reads a message, walking every section to check its framing and find/// where each one starts. Record data is not decoded; a record whose data is/// broken is only found to be when `Record.data` is asked for it.pub fn parse(bytes: []const u8) Error!Message { const header = try Header.parse(bytes); var d = try wire.Decoder.init(bytes); d.pos = Header.len;
var starts: [4]u16 = undefined; starts[0] = Header.len; for (0..header.counts.question) |_| _ = try Question.parse(&d);
inline for ([_]Section{ .answer, .authority, .additional }) |which| { starts[@backingInt(which)] = d.pos; for (0..header.counts.get(which)) |_| _ = try Record.parse(&d); }
return .{ .bytes = bytes, .header = header, .starts = starts, .end = d.pos, };}
test parse { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0x1234, .recursion_desired = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a });
const message = try parse(b.finish()); try testing.expectEqual(@as(u16, 0x1234), message.header.id); try testing.expectEqual(@as(u16, 1), message.header.counts.question);
// A header promising an answer that is not there is refused outright. try testing.expectError(error.Truncated, parse("\x00\x01\x80\x00\x00\x00\x00\x01\x00\x00\x00\x00"));}
/// The bytes after the end of the last section. There should be none. A/// message with some is not necessarily an attack -- a datagram may have been/// padded -- but it is not something to parse, and nothing here will.pub fn trailing(self: Message) []const u8 { return self.bytes[self.end..];}
test trailing { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1 }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); const query = b.finish();
// The same query with two bytes of padding after it. var padded: [512]u8 = undefined; @memcpy(padded[0..query.len], query); padded[query.len..][0..2].* = .{ 0, 0 };
const message = try parse(padded[0 .. query.len + 2]); try testing.expectEqualSlices(u8, "\x00\x00", message.trailing());}
/// Walks the question section; see `questions`.pub const QuestionIterator = struct { decoder: wire.Decoder, remaining: u16,
/// The next question, or `null` once as many as the header counted have /// been read. pub fn next(self: *QuestionIterator) wire.Error!?Question { if (self.remaining == 0) return null; self.remaining -= 1; return try Question.parse(&self.decoder); }
test next { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1 }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); const message = try Message.parse(b.finish());
var it = message.questions(); try testing.expectEqual(types.Type.a, (try it.next()).?.type); try testing.expectEqual(@as(?Question, null), try it.next()); }};
/// The questions. There is at most one in any message anybody sends; see/// `Question`.pub fn questions(self: Message) QuestionIterator { return .{ .decoder = .{ .message = self.bytes, .pos = self.starts[0], }, .remaining = self.header.counts.question, };}
test questions { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1 }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); try b.question(.{ .name = Name.literal("example.com"), .type = .aaaa }); const message = try parse(b.finish());
// Two questions, which `question` would not hand back but this does. var count: usize = 0; var it = message.questions(); while (try it.next()) |_| count += 1; try testing.expectEqual(@as(usize, 2), count);}
/// The one question, or `null` unless there is exactly one. A message with/// more than one gets `null` too, because there is no way to answer it and no/// agreement about what it would mean; `questions` reads them all for anybody/// who wants to look anyway.pub fn question(self: Message) wire.Error!?Question { if (self.header.counts.question != 1) return null; var it = self.questions(); return it.next();}
test question { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1 }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .mx }); const message = try parse(b.finish()); try testing.expectFmt("example.com.\tIN\tMX", "{f}", .{(try message.question()).?});}
/// Walks one record section; see `section`.pub const RecordIterator = struct { decoder: wire.Decoder, remaining: u16,
/// The next record, or `null` once as many as the header counted have /// been read. The record's data is not decoded; see `Record.data`. pub fn next(self: *RecordIterator) wire.Error!?Record { if (self.remaining == 0) return null; self.remaining -= 1; return try Record.parse(&self.decoder); }
test next { 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(); try testing.expectEqual(types.Type.a, (try it.next()).?.type); try testing.expectEqual(@as(?Record, null), try it.next()); }};
/// The records in one of the three record sections, for code that is handed/// a section rather than naming one. The question section is not one of/// them; see `questions`.pub fn section(self: Message, which: Section) RecordIterator { std.debug.assert(which != .question); return .{ .decoder = .{ .message = self.bytes, .pos = self.starts[@backingInt(which)], }, .remaining = self.header.counts.get(which), };}
test section { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.record(.authority, .{ .name = Name.literal("example.com"), .data = .{ .ns = Name.literal("ns1.example.com") }, }); const message = try parse(b.finish());
for ([_]Section{ .answer, .authority, .additional }) |which| { var count: usize = 0; var it = message.section(which); while (try it.next()) |_| count += 1; try testing.expectEqual(@as(usize, message.header.counts.get(which)), count); }}
/// The answer section: the records that answer the question.pub fn answers(self: Message) RecordIterator { return self.section(.answer);}
test answers { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = Name.literal("www.example.com"), .type = .a }); try b.record(.answer, .{ .name = Name.literal("www.example.com"), .ttl = 300, .data = .{ .cname = Name.literal("example.com") }, }); try b.record(.answer, .{ .name = Name.literal("example.com"), .ttl = 300, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 1 } } }, }); const message = try parse(b.finish());
// A CNAME and then what it points at, in the order the server sent them. var it = message.answers(); try testing.expectFmt("example.com.", "{f}", .{(try (try it.next()).?.data()).cname}); try testing.expectFmt("192.0.2.1", "{f}", .{(try (try it.next()).?.data()).a});}
/// The authority section: in a referral, the `ns` records of the zone to ask/// next; in a denial, the `soa` that says how long the denial may be cached.pub fn authority(self: Message) RecordIterator { return self.section(.authority);}
test authority { // A referral: no answer, and the servers to ask instead. var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = Name.literal("www.example.com"), .type = .a }); try b.record(.authority, .{ .name = Name.literal("example.com"), .ttl = 172800, .data = .{ .ns = Name.literal("a.iana-servers.net") }, }); const message = try parse(b.finish());
var it = message.authority(); const referral = (try it.next()).?; try testing.expectEqual(types.Type.ns, referral.type); try testing.expectFmt("a.iana-servers.net.", "{f}", .{(try referral.data()).ns});}
/// The additional section: records the server thinks will be wanted next --/// the addresses of the servers it just named -- and the `opt` pseudo-record.pub fn additional(self: Message) RecordIterator { return self.section(.additional);}
test additional { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.record(.additional, .{ .name = Name.literal("ns1.example.com"), .ttl = 172800, .data = .{ .a = .{ .octets = .{ 192, 0, 2, 53 } } }, }); try b.opt(.{}); const message = try parse(b.finish());
// The glue, then the `opt` record, which is in this section too. var it = message.additional(); try testing.expectEqual(types.Type.a, (try it.next()).?.type); try testing.expectEqual(types.Type.opt, (try it.next()).?.type);}
/// The EDNS(0) `opt` record, if there is one. A message may hold at most one;/// a second is a `formerr`, which is what `error.MultipleOptRecords` is for.pub fn opt(self: Message) OptError!?edns.Opt { var it = self.additional(); var found: ?Record = null; while (try it.next()) |record| { if (record.type != .opt) continue; if (found != null) return error.MultipleOptRecords; found = record; } return if (found) |record| try edns.Opt.fromRecord(record) else null;}
test opt { var buf: [512]u8 = undefined; var b = try Builder.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 parse(b.finish());
const edns0 = (try message.opt()).?; try testing.expectEqual(@as(u16, 1232), edns0.udp_payload_size); try testing.expect(edns0.dnssec_ok);}
pub const OptError = wire.Error || edns.Error || error{ /// More than one `opt` record. RFC 6891 §6.1.1 allows exactly one. MultipleOptRecords,};
/// The full twelve-bit response code, with the eight bits an `opt` record/// carries put back on top of the four in the header. Without an `opt` this is/// just the header's four bits, which is why a code above 15 can never be sent/// to a requestor that did not offer EDNS.pub fn responseCode(self: Message) OptError!types.ResponseCode { const high: u8 = if (try self.opt()) |o| o.extended_rcode else 0; return types.ResponseCode.join(self.header.rcode.low(), high);}
test responseCode { // BADVERS is 16, one more than the header's four bits can say. var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true, .rcode = .badvers }, .{}); try b.opt(.{ .extended_rcode = types.ResponseCode.badvers.high() }); const message = try parse(b.finish());
try testing.expectEqual(types.ResponseCode.noerror, message.header.rcode); try testing.expectEqual(types.ResponseCode.badvers, try message.responseCode());}
/// The message laid out the way `dig` lays one out: the header, the EDNS/// pseudo-section, then each section that has anything in it. Everything up to/// the point where something stops decoding, which for a message from `parse`/// is the whole of it.pub fn format(self: Message, w: *Writer) Writer.Error!void { try w.print(";; ->>HEADER<<- {f}\n", .{self.header});
if (self.opt() catch null) |o| try w.print("\n;; OPT PSEUDOSECTION:\n; {f}\n", .{o});
if (self.header.counts.question > 0) { try w.writeAll("\n;; QUESTION SECTION:\n"); var it = self.questions(); while (it.next() catch null) |q| try w.print(";{f}\n", .{q}); }
inline for ([_]Section{ .answer, .authority, .additional }) |which| { // Counted before the heading is written, because a section whose only // contents are the OPT record has nothing left to put under one: an // EDNS query's additional section is exactly that, and dig prints no // heading for it either. var printable: u16 = 0; var counting = self.section(which); while (counting.next() catch null) |record| { if (!skipInFormat(which, record)) printable += 1; }
if (printable > 0) { const heading = comptime blk: { var buf: [@tagName(which).len]u8 = undefined; for (@tagName(which), 0..) |c, i| buf[i] = std.ascii.toUpper(c); const frozen = buf; break :blk &frozen; }; try w.print("\n;; {s} SECTION:\n", .{heading}); var it = self.section(which); while (it.next() catch null) |record| { if (skipInFormat(which, record)) continue; try w.print("{f}\n", .{record}); } } }}
test format { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 7, .response = true, .rcode = .nxdomain }, .{}); try b.question(.{ .name = Name.literal("nope.example.com"), .type = .a }); const message = try parse(b.finish());
try testing.expectFmt( ";; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 7, flags: qr; " ++ "QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0\n" ++ "\n;; QUESTION SECTION:\n" ++ ";nope.example.com.\tIN\tA\n", "{f}", .{message}, );}
/// Whether `format` leaves a record out of its section.////// Only the OPT record, and only where it belongs: it was printed above as a/// pseudo-section, the way dig does it, because its class and TTL do not mean/// what a record's class and TTL mean. One in any other section is malformed,/// and is printed where it is rather than quietly hidden.fn skipInFormat(which: Section, record: Record) bool { return which == .additional and record.type == .opt;}
const testing = std.testing;const Builder = @import("Builder.zig");
test "a response, read back" { var buf: [512]u8 = undefined; var names: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 0x1234, .response = true, .recursion_desired = true, .recursion_available = true, }, .{}); const name = try Name.fromText(&names, "example.com"); try b.question(.{ .name = name, .type = .a }); try b.record(.answer, .{ .name = name, .ttl = 300, .data = .{ .a = .{ .octets = .{ 93, 184, 215, 14 } } }, }); try b.opt(.{ .udp_payload_size = 1232, .dnssec_ok = true });
const message = try Message.parse(b.finish()); try testing.expectEqual(@as(u16, 0x1234), message.header.id); try testing.expectEqual(@as(usize, 0), message.trailing().len); try testing.expectFmt("example.com.\tIN\tA", "{f}", .{(try message.question()).?});
var it = message.answers(); const answer = (try it.next()).?; try testing.expectFmt("example.com.\t300\tIN\tA\t93.184.215.14", "{f}", .{answer}); try testing.expectEqual(@as(?Record, null), try it.next());
const o = (try message.opt()).?; try testing.expect(o.dnssec_ok); try testing.expectEqual(@as(u16, 1232), o.udp_payload_size); try testing.expectEqual(types.ResponseCode.noerror, try message.responseCode());}
test "the whole message prints the way dig does" { var buf: [512]u8 = undefined; var names: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 42, .response = true, .authoritative = true }, .{}); const name = try Name.fromText(&names, "example.com"); try b.question(.{ .name = name, .type = .mx }); try b.record(.answer, .{ .name = name, .ttl = 3600, .data = .{ .mx = .{ .preference = 10, .exchange = name } }, });
const message = try Message.parse(b.finish()); try testing.expectFmt( ";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42, flags: qr aa; " ++ "QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0\n" ++ "\n;; QUESTION SECTION:\n" ++ ";example.com.\tIN\tMX\n" ++ "\n;; ANSWER SECTION:\n" ++ "example.com.\t3600\tIN\tMX\t10 example.com.\n", "{f}", .{message}, );}
test "an extended response code needs the OPT record to be expressed" { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true, .rcode = .badvers }, .{}); try b.opt(.{ .extended_rcode = types.ResponseCode.badvers.high() }); const message = try Message.parse(b.finish()); try testing.expectEqual(types.ResponseCode.noerror, message.header.rcode); try testing.expectEqual(types.ResponseCode.badvers, try message.responseCode());}
test "a message that ends in the middle of a record" { var buf: [512]u8 = undefined; var names: Name.Buffer = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.question(.{ .name = try Name.fromText(&names, "example.com"), .type = .a }); const message = b.finish(); // The header says there is an answer, and there is not. var truncated: [512]u8 = undefined; @memcpy(truncated[0..message.len], message); truncated[7] = 1; try testing.expectError(error.Truncated, Message.parse(truncated[0..message.len]));}
test "two OPT records are a malformed message" { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 1, .response = true }, .{}); try b.opt(.{}); try b.opt(.{}); const message = try Message.parse(b.finish()); try testing.expectError(error.MultipleOptRecords, message.opt());}
test "a section holding nothing but the OPT record gets no heading" { var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0x1234, .recursion_desired = true }, .{}); try b.question(.{ .name = Name.literal("example.com"), .type = .a }); try b.opt(.{});
const message = try Message.parse(b.finish()); try testing.expectEqual(@as(u16, 1), message.header.counts.additional); try testing.expectFmt( ";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 4660, flags: rd; " ++ "QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1\n" ++ "\n;; OPT PSEUDOSECTION:\n; EDNS: version: 0, flags:; udp: 1232\n" ++ "\n;; QUESTION SECTION:\n" ++ ";example.com.\tIN\tA\n", "{f}", .{message}, );}
test "a bad pointer inside record data is found when the data is read" { // A CNAME whose target holds a pointer into its own first label. Built by // hand because no encoder produces it. // // The header, then `a.` as the owner, then a CNAME whose four bytes of // data are a two-byte label holding 00 58 and a pointer to the first of // them. const message = "\x00\x01\x84\x00\x00\x00\x00\x01\x00\x00\x00\x00" ++ "\x01a\x00" ++ "\x00\x05\x00\x01\x00\x00\x00\x00\x00\x05" ++ "\x02\x00X\xc0\x1a";
// The record itself parses -- its framing is sound. It is the name inside // its data that is refused, and only once somebody asks for it. const parsed = try Message.parse(message); var it = parsed.answers(); const record = (try it.next()).?; try testing.expectError(error.BadPointer, record.data());}