Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! EDNS(0): the extension mechanism that let DNS outgrow the twelve-byte//! header without changing it.//!//! RFC 6891 found room the only place there was any -- in a record. An `opt`//! record in the additional section is not a record at all: it is never//! stored, never cached, never in a zone, and its owner name means nothing.//! What it carries is in the fields a real record would use for something//! else. The class holds the largest response the sender can reassemble, the//! TTL holds eight more bits of response code, the version and the DNSSEC OK//! flag, and the record data holds a list of options.//!//! Almost everything after 1999 needs one: a response larger than 512 bytes, a//! response code above 15, DNSSEC records in an answer, cookies, the client's//! subnet, a reason for a failure. A query without an `opt` is a query saying//! it understands none of it.
const std = @import("std");const Writer = std.Io.Writer;const z46 = @import("z46");
const Builder = @import("Builder.zig");const Name = @import("Name.zig");const Record = @import("Record.zig");const presentation = @import("presentation.zig");const types = @import("types.zig");const wire = @import("wire.zig");
/// What RFC 6891 §6.2.5 suggests a requestor advertise, and what RFC 9715/// recommends after fragmented UDP turned out to be worse than a retry over/// TCP. Larger is not better: a response that has to be fragmented is a/// response that may never arrive.pub const default_payload_size = 1232;
/// The smallest a requestor may advertise, and what a message with no `opt`/// record is taken to mean (RFC 1035 §4.2.1).pub const min_payload_size = 512;
/// What reading the option list itself can go wrong with.pub const ParseError = wire.Error || error{ /// The record data is not a well-formed list of options. MalformedRdata,};
/// What reading an `opt` record can go wrong with, beyond its options.pub const Error = ParseError || error{ /// The record was not an `opt` record. NotAnOptRecord, /// An `opt` record whose owner name is not the root. RFC 6891 §6.1.2 says /// it must be, and a message with anything else there is either broken or /// trying something. BadOwnerName,};
/// The `opt` pseudo-record, with each of its fields read out of whichever/// part of a record it was hidden in.pub const Opt = struct { /// The largest UDP response the sender can reassemble. Kept in the class /// field, where a real record keeps `in`. udp_payload_size: u16 = default_payload_size, /// The high eight bits of the response code, which the header has no room /// for. Kept in the first byte of the TTL. extended_rcode: u8 = 0, /// Always 0. A server that does not speak the version it is sent answers /// `badvers` with its own highest version here. version: u8 = 0, /// The requestor understands DNSSEC and wants the records; the responder /// has included them. Without it, a server omits every signature, which is /// what keeps DNSSEC from breaking resolvers that never asked. dnssec_ok: bool = false, /// The other fifteen flag bits, all reserved. Kept so that a message /// carrying one survives being decoded and encoded again. reserved_flags: u15 = 0, /// The options themselves. options: Options = .none,
/// The four TTL bytes, which is where the version, the flags and the high /// bits of the response code live. pub fn ttlBits(self: Opt) u32 { return @as(u32, self.extended_rcode) << 24 | @as(u32, self.version) << 16 | @as(u32, @intFromBool(self.dnssec_ok)) << 15 | self.reserved_flags; }
test ttlBits { const o: Opt = .{ .extended_rcode = 1, .dnssec_ok = true }; // The high bits of `badvers` on top, then version 0, then the DO bit. try testing.expectEqual(@as(u32, 0x01008000), o.ttlBits()); }
/// Reads an `opt` record's fields out of the places they are kept. pub fn fromRecord(record: Record) Error!Opt { if (record.type != .opt) return error.NotAnOptRecord; if (!record.name.isRoot()) return error.BadOwnerName; var d = record.rdataDecoder(); return .{ .udp_payload_size = @backingInt(record.class), .extended_rcode = @truncate(record.ttl >> 24), .version = @truncate(record.ttl >> 16), .dnssec_ok = record.ttl & 0x8000 != 0, .reserved_flags = @truncate(record.ttl), .options = try Options.parse(&d), }; }
test fromRecord { // The root, type 41, a class of 1232, a TTL with only DO set, and no // options. var d = try wire.Decoder.init("\x00" ++ "\x00\x29" ++ "\x04\xd0" ++ "\x00\x00\x80\x00" ++ "\x00\x00"); const o = try Opt.fromRecord(try Record.parse(&d)); try testing.expectEqual(@as(u16, 1232), o.udp_payload_size); try testing.expect(o.dnssec_ok); }
/// The record to write for this `opt`, with each field back where the wire /// format keeps it. `Builder.opt` is the usual way to reach this. pub fn toRecordSpec(self: Opt) Builder.RecordSpec { return .{ .name = Name.root, .class = @fromBackingInt(self.udp_payload_size), .ttl = self.ttlBits(), .data = .{ .opt = self.options }, }; }
test toRecordSpec { const spec = (Opt{ .udp_payload_size = 4096, .dnssec_ok = true }).toRecordSpec(); try testing.expect(spec.name.isRoot()); try testing.expectEqual(@as(u16, 4096), @backingInt(spec.class)); try testing.expectEqual(@as(u32, 0x8000), spec.ttl); }
/// As `dig` prints the pseudo-section, with each option on a line of its /// own after it and any reserved flag bit shown rather than dropped. pub fn format(self: Opt, w: *Writer) Writer.Error!void { try w.print("EDNS: version: {d}, flags:", .{self.version}); if (self.dnssec_ok) try w.writeAll(" do"); // The bits nobody has defined, which are to be sent as zero -- shown // when they are not, the way dig shows them, rather than lost. if (self.reserved_flags != 0) try w.print("; MBZ: 0x{x:0>4}", .{self.reserved_flags}); try w.print("; udp: {d}", .{self.udp_payload_size}); var it = self.options.iterator(); while (it.next()) |option| try w.print("\n{f}", .{option}); }
test format { var buf: [16]u8 = undefined; const o: Opt = .{ .dnssec_ok = true, .options = try Options.encode(&buf, &.{.{ .code = .cookie, .data = "\x01\x02\x03\x04\x05\x06\x07\x08" }}), }; try testing.expectFmt("EDNS: version: 0, flags: do; udp: 1232\nCOOKIE: 0102030405060708", "{f}", .{o}); }};
/// An option code from the EDNS(0) option registry.pub const OptionCode = enum(u16) { /// Long-lived queries. Never standardized. llq = 1, /// A name server identifier: ask an anycast address which instance /// answered (RFC 5001). The first thing to reach for when one node out of /// a hundred is wrong. nsid = 3, /// Which DNSSEC algorithms the requestor understands (RFC 6975). dau = 5, /// Which DS hash algorithms it understands. dhu = 6, /// Which NSEC3 hash algorithms it understands. n3u = 7, /// The client's subnet, so that an authoritative server can answer /// according to where the client is rather than where its resolver is /// (RFC 7871). A privacy trade, and one the RFC itself is uneasy about. client_subnet = 8, /// How much longer the response will remain valid (RFC 7314). expire = 9, /// A cookie, which is what makes off-path spoofing and reflection /// amplification hard over UDP without needing TCP (RFC 7873). cookie = 10, /// How long a TCP connection should be held open (RFC 7828). tcp_keepalive = 11, /// Bytes of nothing, to make every query the same size so that its length /// leaks nothing (RFC 7830). padding = 12, /// The closest ancestor the requestor already has, so a chain of trust can /// be completed in one round trip (RFC 7901). chain = 13, /// Which keys the requestor has as trust anchors (RFC 8145). key_tag = 14, /// Why a server answered the way it did (RFC 8914). The difference between /// a `servfail` and a `servfail` that says "the signature had expired". extended_error = 15, /// Where to report a resolution failure (RFC 9567). report_channel = 18, /// Which version of the zone the answer came from (RFC 9660). zoneversion = 19, _,
/// The code's name as `dig` spells it, so that printed options read the /// same as dig's -- `CLIENT-SUBNET`, `EDE`, and `Report-Channel` in the /// mixed case BIND gives it -- or `null` for a code this has no name for. pub fn name(self: OptionCode) ?[]const u8 { return switch (self) { .llq => "LLQ", .nsid => "NSID", .dau => "DAU", .dhu => "DHU", .n3u => "N3U", .client_subnet => "CLIENT-SUBNET", .expire => "EXPIRE", .cookie => "COOKIE", .tcp_keepalive => "TCP-KEEPALIVE", .padding => "PADDING", .chain => "CHAIN", .key_tag => "KEY-TAG", .extended_error => "EDE", .report_channel => "Report-Channel", .zoneversion => "ZONEVERSION", _ => null, }; }
test name { try testing.expectEqualStrings("CLIENT-SUBNET", OptionCode.client_subnet.name().?); try testing.expectEqual(@as(?[]const u8, null), @as(OptionCode, @fromBackingInt(65001)).name()); }
/// The name, or `OPT=` and the number for a code without one, as `dig` /// writes it. pub fn format(self: OptionCode, w: *Writer) Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("OPT={d}", .{@backingInt(self)}); }
test format { try testing.expectFmt("COOKIE", "{f}", .{OptionCode.cookie}); try testing.expectFmt("OPT=65001", "{f}", .{@as(OptionCode, @fromBackingInt(65001))}); }};
/// One option: a code and the bytes that go with it.pub const Option = struct { code: OptionCode, data: []const u8,
/// The reason a server gives for its answer, if this is an extended DNS /// error and it has at least the two bytes of its info code. pub fn asExtendedError(self: Option) ?ExtendedError { if (self.code != .extended_error or self.data.len < 2) return null; return .{ .info_code = @fromBackingInt(std.mem.readInt(u16, self.data[0..2], .big)), .text = self.data[2..], }; }
test asExtendedError { const option: Option = .{ .code = .extended_error, .data = "\x00\x12" }; const extended = option.asExtendedError().?; try testing.expectEqual(ExtendedError.InfoCode.prohibited, extended.info_code); try testing.expectEqual(@as(usize, 0), extended.text.len); }
/// The cookie, if this is one. A query carries the client's eight bytes /// alone; a response adds the server's eight to thirty-two. pub fn asCookie(self: Option) ?Cookie { if (self.code != .cookie) return null; if (self.data.len != 8 and (self.data.len < 16 or self.data.len > 40)) return null; return .{ .client = self.data[0..8].*, .server = self.data[8..] }; }
test asCookie { const query: Option = .{ .code = .cookie, .data = "\x01\x02\x03\x04\x05\x06\x07\x08" }; try testing.expectEqual(@as(usize, 0), query.asCookie().?.server.len); // Twelve bytes is too long for a client's cookie and too short for both. const odd: Option = .{ .code = .cookie, .data = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c" }; try testing.expectEqual(@as(?Cookie, null), odd.asCookie()); }
/// The client's subnet, if this is one and it is the right shape: an /// address exactly as many bytes as the source prefix needs, no bit set /// past the prefix, and for IPv4 and IPv6 neither prefix longer than the /// address. A family nobody has defined is not judged on its lengths. pub fn asClientSubnet(self: Option) ?ClientSubnet { if (self.code != .client_subnet or self.data.len < 4) return null; const family = std.mem.readInt(u16, self.data[0..2], .big); const source = self.data[2]; const scope = self.data[3]; const address = self.data[4..]; // RFC 7871 section 6: the address carries only the significant bits, // rounded up to a byte, and no more than that -- with the bits past // the prefix in that last byte set to zero. if (address.len != (@as(usize, source) + 7) / 8) return null; if (source % 8 != 0 and address[address.len - 1] & (@as(u8, 0xff) >> @intCast(source % 8)) != 0) { return null; } // And neither prefix may be longer than the family's addresses. const max_prefix: ?u8 = switch (family) { 1 => 32, 2 => 128, else => null, }; if (max_prefix) |max| if (source > max or scope > max) return null; return .{ .family = @fromBackingInt(family), .source_prefix_len = source, .scope_prefix_len = scope, .address = address, }; }
test asClientSubnet { // 192.0.2.0/24: three bytes of address for a 24-bit prefix. const option: Option = .{ .code = .client_subnet, .data = "\x00\x01\x18\x00\xc0\x00\x02" }; try testing.expectEqual(@as(u8, 24), option.asClientSubnet().?.source_prefix_len); // A bit set past a 23-bit prefix is a subnet nobody could have meant. const stray: Option = .{ .code = .client_subnet, .data = "\x00\x01\x17\x00\xc0\x00\x03" }; try testing.expectEqual(@as(?ClientSubnet, null), stray.asClientSubnet()); }
/// An extended error or a client subnet as its own type prints it, padding /// as how many bytes of it there are, and anything else as its code and /// its data in hexadecimal. pub fn format(self: Option, w: *Writer) Writer.Error!void { if (self.asExtendedError()) |extended| return w.print("{f}", .{extended}); if (self.asClientSubnet()) |subnet| return w.print("{f}", .{subnet}); try w.print("{f}: ", .{self.code}); switch (self.code) { .nsid => try presentation.writeHexLower(w, self.data), .cookie => try presentation.writeHexLower(w, self.data), .padding => try w.print("({d} bytes)", .{self.data.len}), else => try presentation.writeHexLower(w, self.data), } }
test format { const nsid: Option = .{ .code = .nsid, .data = "ns1" }; try testing.expectFmt("NSID: 6e7331", "{f}", .{nsid}); const zeros: [16]u8 = @splat(0); const padding: Option = .{ .code = .padding, .data = &zeros }; try testing.expectFmt("PADDING: (16 bytes)", "{f}", .{padding}); }};
/// Why a server answered the way it did.pub const ExtendedError = struct { info_code: InfoCode, /// Free text for a human, which a program must not parse and a server need /// not send. text: []const u8,
/// The extended DNS error codes of RFC 8914 §5.2. pub const InfoCode = enum(u16) { other = 0, unsupported_dnskey_algorithm = 1, unsupported_ds_digest_type = 2, stale_answer = 3, forged_answer = 4, dnssec_indeterminate = 5, dnssec_bogus = 6, signature_expired = 7, signature_not_yet_valid = 8, dnskey_missing = 9, rrsigs_missing = 10, no_zone_key_bit_set = 11, nsec_missing = 12, cached_error = 13, not_ready = 14, blocked = 15, censored = 16, filtered = 17, prohibited = 18, stale_nxdomain_answer = 19, not_authoritative = 20, not_supported = 21, no_reachable_authority = 22, network_error = 23, invalid_data = 24, signature_expired_before_valid = 25, too_early = 26, unsupported_nsec3_iterations = 27, unable_to_conform_to_policy = 28, synthesized = 29, _,
/// The code's name in this enum, or `null` for one it has no name /// for. pub fn name(self: InfoCode) ?[]const u8 { return switch (self) { _ => null, inline else => |c| @tagName(c), }; }
test name { try testing.expectEqualStrings("stale_answer", InfoCode.stale_answer.name().?); try testing.expectEqual(@as(?[]const u8, null), @as(InfoCode, @fromBackingInt(4000)).name()); } };
/// `EDE:`, the info code with its name when it has one, and the text /// quoted and escaped, since it comes from the server and may say /// anything. pub fn format(self: ExtendedError, w: *Writer) Writer.Error!void { try w.writeAll("EDE: "); if (self.info_code.name()) |n| { try w.print("{d} ({s})", .{ @backingInt(self.info_code), n }); } else { try w.print("{d}", .{@backingInt(self.info_code)}); } if (self.text.len > 0) { try w.writeAll(": "); try presentation.writeCharacterString(w, self.text); } }
test format { const extended: ExtendedError = .{ .info_code = .signature_expired, .text = "expired" }; try testing.expectFmt("EDE: 7 (signature_expired): \"expired\"", "{f}", .{extended}); }};
/// The eight bytes a client picks and the server echoes, plus whatever the/// server adds. Nothing here generates or verifies one: that is a keyed hash/// over the addresses and a server secret, and it belongs wherever the secret/// is.pub const Cookie = struct { client: [8]u8, /// Empty in a query. Eight to thirty-two bytes in a response. server: []const u8,};
/// The client's subnet, as RFC 7871 sends it.pub const ClientSubnet = struct { family: Family, /// How many bits of the address the requestor is disclosing. source_prefix_len: u8, /// In a response: how many bits of it the answer actually depended on, /// which is what a cache must key on. scope_prefix_len: u8, /// The significant bits, rounded up to whole bytes. address: []const u8,
/// The IANA address family numbers, of which two are ever seen. pub const Family = enum(u16) { ipv4 = 1, ipv6 = 2, _, };
/// The subnet as a network, with the bits that were not sent filled in as /// zero. `null` for an address family this does not know, or for a prefix /// or an address longer than the family allows. pub fn network(self: ClientSubnet) ?z46.Network { switch (self.family) { .ipv4 => { if (self.source_prefix_len > 32 or self.address.len > 4) return null; var octets: [4]u8 = @splat(0); @memcpy(octets[0..self.address.len], self.address); return .{ .ipv4 = .{ .address = .{ .octets = octets }, .prefix_len = @intCast(self.source_prefix_len), } }; }, .ipv6 => { if (self.source_prefix_len > 128 or self.address.len > 16) return null; var octets: [16]u8 = @splat(0); @memcpy(octets[0..self.address.len], self.address); return .{ .ipv6 = .{ .address = .{ .octets = octets }, .prefix_len = @intCast(self.source_prefix_len), } }; }, _ => return null, } }
test network { // Six bytes of a 48-bit IPv6 prefix, and the other ten are zero. const subnet: ClientSubnet = .{ .family = .ipv6, .source_prefix_len = 48, .scope_prefix_len = 0, .address = "\x20\x01\x0d\xb8\x00\x01", }; try testing.expectFmt("2001:db8:1::/48", "{f}", .{subnet.network().?}); }
/// `CLIENT-SUBNET:`, then the network and the scope prefix length. For a /// family `network` does not know, the three numbers instead. pub fn format(self: ClientSubnet, w: *Writer) Writer.Error!void { try w.writeAll("CLIENT-SUBNET: "); if (self.network()) |n| { try w.print("{f}/{d}", .{ n, self.scope_prefix_len }); } else { try w.print("family {d}/{d}/{d}", .{ @backingInt(self.family), self.source_prefix_len, self.scope_prefix_len, }); } }
test format { const subnet: ClientSubnet = .{ .family = .ipv4, .source_prefix_len = 24, .scope_prefix_len = 0, .address = "\xc0\x00\x02", }; try testing.expectFmt("CLIENT-SUBNET: 192.0.2.0/24/0", "{f}", .{subnet}); }};
/// The list of options in an `opt` record, still in wire form.pub const Options = struct { bytes: []const u8,
/// No options at all. pub const none: Options = .{ .bytes = "" };
/// Reads the rest of the record data as a list of options, checking that /// each one's length fits in what is left. Unlike the parameters of a /// `svcb` record, options have no required order and may repeat. pub fn parse(d: *wire.Decoder) ParseError!Options { const bytes = d.takeRest(); var i: usize = 0; while (i < bytes.len) { if (i + 4 > bytes.len) return error.MalformedRdata; const length = std.mem.readInt(u16, bytes[i + 2 ..][0..2], .big); i += 4 + @as(usize, length); if (i > bytes.len) return error.MalformedRdata; } return .{ .bytes = bytes }; }
test parse { var d = try wire.Decoder.init("\x00\x03\x00\x03ns1" ++ "\x00\x0c\x00\x00"); const options = try Options.parse(&d); try testing.expectEqual(@as(usize, 11), options.bytes.len); // An option claiming four bytes with two left is refused. var short = try wire.Decoder.init("\x00\x03\x00\x04ns"); try testing.expectError(error.MalformedRdata, Options.parse(&short)); }
/// Walks the options in the order they were sent. pub const Iterator = struct { bytes: []const u8, pos: usize = 0,
/// The next option, or `null` after the last. A list from `parse` /// or `encode` is whole, so `null` means the end and nothing else. pub fn next(self: *Iterator) ?Option { if (self.pos + 4 > self.bytes.len) return null; const code = std.mem.readInt(u16, self.bytes[self.pos..][0..2], .big); const length = std.mem.readInt(u16, self.bytes[self.pos + 2 ..][0..2], .big); const start = self.pos + 4; const end = start + length; if (end > self.bytes.len) return null; self.pos = end; return .{ .code = @fromBackingInt(code), .data = self.bytes[start..end] }; }
test next { const options: Options = .{ .bytes = "\x00\x03\x00\x03ns1" ++ "\x00\x0c\x00\x00" }; var it = options.iterator(); try testing.expectEqualStrings("ns1", it.next().?.data); try testing.expectEqual(OptionCode.padding, it.next().?.code); try testing.expectEqual(@as(?Option, null), it.next()); } };
/// Every option, including repeats, in the order they were sent. pub fn iterator(self: Options) Iterator { return .{ .bytes = self.bytes }; }
test iterator { // A requestor may send `key_tag` more than once; `get` sees only the // first. const options: Options = .{ .bytes = "\x00\x0e\x00\x02\x4f\x66" ++ "\x00\x0e\x00\x02\x50\x34" }; var count: usize = 0; var it = options.iterator(); while (it.next()) |option| { if (option.code == .key_tag) count += 1; } try testing.expectEqual(@as(usize, 2), count); }
/// The first option with this code, or `null`. pub fn get(self: Options, code: OptionCode) ?Option { var it = self.iterator(); while (it.next()) |option| { if (option.code == code) return option; } return null; }
test get { const options: Options = .{ .bytes = "\x00\x03\x00\x03ns1" }; try testing.expectEqualStrings("ns1", options.get(.nsid).?.data); try testing.expectEqual(@as(?Option, null), options.get(.cookie)); }
/// Writes the options as they are held, already in wire form. pub fn writeTo(self: Options, b: *Builder) Builder.Error!void { try b.writeAll(self.bytes); }
test writeTo { const options: Options = .{ .bytes = "\x00\x03\x00\x00" }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{ .compression = false }); try options.writeTo(&b); try testing.expectEqualSlices(u8, "\x00\x03\x00\x00", b.buffer[12..b.pos]); }
/// Each option as `Option.format` writes it, separated by spaces. pub fn format(self: Options, w: *Writer) Writer.Error!void { var it = self.iterator(); var first = true; while (it.next()) |option| { if (!first) try w.writeByte(' '); first = false; try w.print("{f}", .{option}); } }
test format { const options: Options = .{ .bytes = "\x00\x03\x00\x03ns1" ++ "\x00\x0c\x00\x02\x00\x00" }; try testing.expectFmt("NSID: 6e7331 PADDING: (2 bytes)", "{f}", .{options}); }
pub const EncodeError = error{ /// The buffer was too small. NoSpace, /// An option longer than 65535 bytes, which its length cannot express. OptionTooLong, };
/// Writes a list of options into `buf` and returns them, which is how an /// `Opt` to be sent gets its data without an allocator. pub fn encode(buf: []u8, options: []const Option) EncodeError!Options { var out: usize = 0; for (options) |option| { if (option.data.len > std.math.maxInt(u16)) return error.OptionTooLong; if (out + 4 + option.data.len > buf.len) return error.NoSpace; std.mem.writeInt(u16, buf[out..][0..2], @backingInt(option.code), .big); std.mem.writeInt(u16, buf[out + 2 ..][0..2], @intCast(option.data.len), .big); @memcpy(buf[out + 4 ..][0..option.data.len], option.data); out += 4 + option.data.len; } return .{ .bytes = buf[0..out] }; }
test encode { var buf: [64]u8 = undefined; const options = try Options.encode(&buf, &.{ .{ .code = .nsid, .data = "" }, .{ .code = .cookie, .data = "\x01\x02\x03\x04\x05\x06\x07\x08" }, }); try testing.expectEqualSlices(u8, "\x00\x03\x00\x00" ++ "\x00\x0a\x00\x08\x01\x02\x03\x04\x05\x06\x07\x08", options.bytes); // Even an empty option is four bytes of code and length. var tiny: [3]u8 = undefined; try testing.expectError(error.NoSpace, Options.encode(&tiny, &.{.{ .code = .nsid, .data = "" }})); }};
const testing = std.testing;
test "options round trip through encode" { var buf: [128]u8 = undefined; const options = try Options.encode(&buf, &.{ .{ .code = .nsid, .data = "" }, .{ .code = .cookie, .data = "\x01\x02\x03\x04\x05\x06\x07\x08" }, }); try testing.expectEqual(@as(?Option, null), options.get(.padding)); const cookie = options.get(.cookie).?.asCookie().?; try testing.expectEqualSlices(u8, "\x01\x02\x03\x04\x05\x06\x07\x08", &cookie.client); try testing.expectEqual(@as(usize, 0), cookie.server.len);
var d = try wire.Decoder.init(options.bytes); const reparsed = try Options.parse(&d); try testing.expectEqualSlices(u8, options.bytes, reparsed.bytes);}
test "a truncated option list is refused" { for ([_][]const u8{ "\x00\x03\x00", "\x00\x03\x00\x04\x01\x02" }) |bytes| { var d = try wire.Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Options.parse(&d)); }}
test "an extended error carries a reason" { var buf: [128]u8 = undefined; const options = try Options.encode(&buf, &.{ .{ .code = .extended_error, .data = "\x00\x07expired" }, }); const extended = options.get(.extended_error).?.asExtendedError().?; try testing.expectEqual(ExtendedError.InfoCode.signature_expired, extended.info_code); try testing.expectFmt("EDE: 7 (signature_expired): \"expired\"", "{f}", .{extended});}
test "reserved flag bits are printed rather than lost" { const plain: Opt = .{}; try testing.expectFmt("EDNS: version: 0, flags:; udp: 1232", "{f}", .{plain}); const odd: Opt = .{ .dnssec_ok = true, .reserved_flags = 0x0005 }; try testing.expectFmt("EDNS: version: 0, flags: do; MBZ: 0x0005; udp: 1232", "{f}", .{odd});}
test "a client subnet becomes a network" { var buf: [128]u8 = undefined; // 192.0.2.0/24, with the server saying it used all 24 bits. const options = try Options.encode(&buf, &.{ .{ .code = .client_subnet, .data = "\x00\x01\x18\x18\xc0\x00\x02" }, }); const subnet = options.get(.client_subnet).?.asClientSubnet().?; try testing.expectEqual(@as(u8, 24), subnet.source_prefix_len); try testing.expectFmt("CLIENT-SUBNET: 192.0.2.0/24/24", "{f}", .{subnet});
// An address longer than the prefix needs is not a client subnet. const wrong = try Options.encode(&buf, &.{ .{ .code = .client_subnet, .data = "\x00\x01\x18\x18\xc0\x00\x02\x01" }, }); try testing.expectEqual(@as(?ClientSubnet, null), wrong.get(.client_subnet).?.asClientSubnet());
for ([_][]const u8{ "\x00\x01\x17\x00\xc0\x00\x03", // a bit set past a 23-bit prefix "\x00\x01\x21\x00\xc0\x00\x02\x01\x80", // a 33-bit IPv4 prefix "\x00\x01\x18\x21\xc0\x00\x02", // a 33-bit IPv4 scope "\x00\x02\x08\x81\x20", // a 129-bit IPv6 scope }) |data| { const malformed = try Options.encode(&buf, &.{.{ .code = .client_subnet, .data = data }}); try testing.expectEqual(@as(?ClientSubnet, null), malformed.get(.client_subnet).?.asClientSubnet()); }
// A family nobody has defined is not judged. const other = try Options.encode(&buf, &.{ .{ .code = .client_subnet, .data = "\x00\x09\xf8\xf8" ++ @as([31]u8, @splat(0xff)) }, }); try testing.expect(other.get(.client_subnet).?.asClientSubnet() != null);}