// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The twelve bytes every DNS message begins with: an identifier, sixteen bits //! of flags, and how many entries are in each of the four sections. //! //! It is worth reading on its own, before the rest of the message is parsed or //! when the rest of it cannot be. A server that cannot understand a query //! still has to answer it with a `formerr` carrying the same `id`, and a //! client waiting on a UDP socket has to match a reply to its question before //! it decides whether to trust a single byte after the header. const std = @import("std"); const Writer = std.Io.Writer; const types = @import("types.zig"); const Opcode = types.Opcode; const ResponseCode = types.ResponseCode; const Header = @This(); /// How many bytes a header occupies. Always twelve, in every message there /// has ever been. pub const len = 12; /// The identifier the requestor chose, copied into the reply. Over UDP it is /// most of what makes an answer hard to forge, so it wants to come from a /// cryptographically strong source rather than a counter. id: u16, /// Whether this is a response. The one bit that says which direction the /// message is going. response: bool = false, /// What kind of query this is, which also decides what the four sections /// hold: in an `update` they are the zone, the prerequisites, the updates and /// additional data. opcode: Opcode = .query, /// Set in a response by a server that is authoritative for the name in the /// question -- for that name, not for the whole message. authoritative: bool = false, /// The message was too long for the transport and what is here is only the /// beginning. Over UDP this is the signal to ask again over TCP. truncated: bool = false, /// The requestor asks the server to chase the answer rather than returning a /// referral. Copied into the response. recursion_desired: bool = false, /// Set by a server that is willing to recurse for this requestor. recursion_available: bool = false, /// The one bit still reserved. RFC 1035 says it must be zero, and this field /// exists so that a message which sets it anyway survives a decode and encode /// unchanged rather than being quietly corrected. reserved: bool = false, /// In a response: the data was authenticated by the server's own DNSSEC /// validation. In a query: the requestor understands it (RFC 6840 §5.7). /// Meaningless unless you trust the path to the server that set it. authentic_data: bool = false, /// The requestor will do its own DNSSEC validation, so the server should not /// withhold data that failed the server's. checking_disabled: bool = false, /// How the query was answered -- the low four bits of it. The other eight /// live in an `opt` record; `Message.responseCode` is what puts them back /// together. rcode: ResponseCode = .noerror, /// How many entries each section holds. counts: Counts = .{}, /// Which of the four sections of a message. In a dynamic update these are the /// zone, prerequisite, update and additional sections instead, but the header /// fields are the same fields. pub const Section = enum { question, answer, authority, additional, }; pub const Counts = struct { question: u16 = 0, answer: u16 = 0, authority: u16 = 0, additional: u16 = 0, pub fn get(self: Counts, section: Section) u16 { return switch (section) { .question => self.question, .answer => self.answer, .authority => self.authority, .additional => self.additional, }; } pub fn getPtr(self: *Counts, section: Section) *u16 { return switch (section) { .question => &self.question, .answer => &self.answer, .authority => &self.authority, .additional => &self.additional, }; } }; pub const Error = error{ /// Fewer than twelve bytes were given. Truncated, }; pub fn parse(bytes: []const u8) Error!Header { if (bytes.len < len) return error.Truncated; const flag_bits = std.mem.readInt(u16, bytes[2..4], .big); return .{ .id = std.mem.readInt(u16, bytes[0..2], .big), .response = flag_bits & 0x8000 != 0, .opcode = @enumFromInt(@as(u4, @truncate(flag_bits >> 11))), .authoritative = flag_bits & 0x0400 != 0, .truncated = flag_bits & 0x0200 != 0, .recursion_desired = flag_bits & 0x0100 != 0, .recursion_available = flag_bits & 0x0080 != 0, .reserved = flag_bits & 0x0040 != 0, .authentic_data = flag_bits & 0x0020 != 0, .checking_disabled = flag_bits & 0x0010 != 0, .rcode = @enumFromInt(@as(u4, @truncate(flag_bits))), .counts = .{ .question = std.mem.readInt(u16, bytes[4..6], .big), .answer = std.mem.readInt(u16, bytes[6..8], .big), .authority = std.mem.readInt(u16, bytes[8..10], .big), .additional = std.mem.readInt(u16, bytes[10..12], .big), }, }; } /// The sixteen flag bits as they go on the wire. Only the low four bits of /// `rcode` fit; the rest needs an `opt` record to carry it. pub fn flags(self: Header) u16 { var bits: u16 = 0; if (self.response) bits |= 0x8000; bits |= @as(u16, @intFromEnum(self.opcode)) << 11; if (self.authoritative) bits |= 0x0400; if (self.truncated) bits |= 0x0200; if (self.recursion_desired) bits |= 0x0100; if (self.recursion_available) bits |= 0x0080; if (self.reserved) bits |= 0x0040; if (self.authentic_data) bits |= 0x0020; if (self.checking_disabled) bits |= 0x0010; bits |= self.rcode.low(); return bits; } pub fn toBytes(self: Header) [len]u8 { var out: [len]u8 = undefined; std.mem.writeInt(u16, out[0..2], self.id, .big); std.mem.writeInt(u16, out[2..4], self.flags(), .big); std.mem.writeInt(u16, out[4..6], self.counts.question, .big); std.mem.writeInt(u16, out[6..8], self.counts.answer, .big); std.mem.writeInt(u16, out[8..10], self.counts.authority, .big); std.mem.writeInt(u16, out[10..12], self.counts.additional, .big); return out; } pub fn writeTo(self: Header, w: *Writer) Writer.Error!void { try w.writeAll(&self.toBytes()); } /// The header much as `dig` prints it, minus the leading semicolons and on /// one line rather than two: the opcode, the status, the identifier, then /// whichever flags are set, then the four counts. pub fn format(self: Header, w: *Writer) Writer.Error!void { try w.print("opcode: {f}, status: {f}, id: {d}, flags:", .{ self.opcode, self.rcode, self.id, }); const set = [_]struct { bool, []const u8 }{ .{ self.response, "qr" }, .{ self.authoritative, "aa" }, .{ self.truncated, "tc" }, .{ self.recursion_desired, "rd" }, .{ self.recursion_available, "ra" }, .{ self.reserved, "z" }, .{ self.authentic_data, "ad" }, .{ self.checking_disabled, "cd" }, }; for (set) |flag| if (flag[0]) try w.print(" {s}", .{flag[1]}); try w.print("; QUERY: {d}, ANSWER: {d}, AUTHORITY: {d}, ADDITIONAL: {d}", .{ self.counts.question, self.counts.answer, self.counts.authority, self.counts.additional, }); } const testing = std.testing; test "a query header" { // `dig +norecurse example.com A` with the identifier 0x1234. const bytes = "\x12\x34\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00"; const header = try parse(bytes); try testing.expectEqual(@as(u16, 0x1234), header.id); try testing.expect(!header.response); try testing.expectEqual(Opcode.query, header.opcode); try testing.expectEqual(@as(u16, 1), header.counts.question); try testing.expectEqualSlices(u8, bytes, &header.toBytes()); } test "every flag survives a round trip" { const header: Header = .{ .id = 0xbeef, .response = true, .opcode = .update, .authoritative = true, .truncated = true, .recursion_desired = true, .recursion_available = true, .reserved = true, .authentic_data = true, .checking_disabled = true, .rcode = .refused, .counts = .{ .question = 1, .answer = 2, .authority = 3, .additional = 4 }, }; try testing.expectEqual(header, try parse(&header.toBytes())); } test "only the low four bits of an extended rcode reach the header" { const header: Header = .{ .id = 0, .rcode = .badvers }; try testing.expectEqual(@as(u16, 0), header.flags()); // Which is why sending one needs an OPT record; see `edns`. try testing.expectEqual(ResponseCode.noerror, (try parse(&header.toBytes())).rcode); } test "a short header is not a header" { try testing.expectError(error.Truncated, parse("\x12\x34")); } test "the header prints the way dig does" { const header: Header = .{ .id = 4660, .response = true, .recursion_desired = true, .recursion_available = true, .counts = .{ .question = 1, .answer = 2 }, }; try testing.expectFmt( "opcode: QUERY, status: NOERROR, id: 4660, flags: qr rd ra; " ++ "QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0", "{f}", .{header}, ); }