Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Service binding: `svcb` and its alias `https`.//!//! One record answers what used to take several round trips and a guess://! which protocols the service speaks, which port it is on, which addresses to//! try, and the encrypted-client-hello configuration to use -- all before the//! first connection. That is why `https` records are fetched in parallel with//! `a` and `aaaa` rather than after them.//!//! A priority of zero means alias mode: this record has no parameters and just//! says "look at that name instead", which finally gives the apex of a zone//! something a `cname` could never be allowed to be.//!//! The parameters are a list sorted by key, and the sort is normative: RFC//! 9460 §2.2 requires strictly increasing keys, so a duplicate or an//! out-of-order key makes the record malformed rather than merely odd.
const std = @import("std");const Writer = std.Io.Writer;const z46 = @import("z46");
const Builder = @import("../Builder.zig");const Name = @import("../Name.zig");const presentation = @import("../presentation.zig");const wire = @import("../wire.zig");
const Decoder = wire.Decoder;
pub const Error = wire.Error || error{ /// The record data is not the shape its type requires. MalformedRdata,};
/// A service parameter key. The names are lowercase on the wire's own terms:/// unlike a record type, a parameter is written in a zone file exactly as it/// is spelled here.pub const ParamKey = enum(u16) { /// Which of the other keys a client must understand to use this record at /// all. A key listed here and not understood means the whole record is to /// be ignored. mandatory = 0, /// The application protocols, as a list of character-strings: `h2`, `h3`. alpn = 1, /// Present, with no value, to say that the protocol implied by the record /// type is *not* offered -- that an `https` record does not mean HTTP/1.1 /// over TLS is available. @"no-default-alpn" = 2, /// The port, when it is not the protocol's default. port = 3, /// Addresses to try while the `a` lookup is still in flight. A hint, not /// an answer: the authoritative addresses are still the address records. ipv4hint = 4, /// The encrypted client hello configuration, which is the point of the /// whole record for anyone who cares that the name being connected to is /// not sent in the clear. ech = 5, ipv6hint = 6, /// The URI template for DNS over HTTPS (RFC 9461). dohpath = 7, /// The service offers Oblivious HTTP (RFC 9540). ohttp = 8, _,
/// The name a zone file writes, or `null` for a key this library does not /// know. `format` falls back to the `keyNNNNN` syntax of RFC 9460 §2.1. pub fn name(self: ParamKey) ?[]const u8 { return switch (self) { _ => null, inline else => |k| @tagName(k), }; }
pub fn format(self: ParamKey, w: *Writer) Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("key{d}", .{@intFromEnum(self)}); }};
/// One parameter: a key and its value, which is whatever that key says it is.pub const Param = struct { key: ParamKey, value: []const u8,
/// The port, for a `port` parameter that is the two bytes it should be. pub fn asPort(self: Param) ?u16 { if (self.key != .port or self.value.len != 2) return null; return std.mem.readInt(u16, self.value[0..2], .big); }
/// Walks a value that is a list of character-strings: `alpn`. pub fn stringList(self: Param) StringListIterator { return .{ .bytes = self.value }; }
pub const StringListIterator = struct { bytes: []const u8, pos: usize = 0,
pub fn next(self: *StringListIterator) ?[]const u8 { if (self.pos >= self.bytes.len) return null; const length = self.bytes[self.pos]; const start = self.pos + 1; const end = start + length; if (end > self.bytes.len) return null; self.pos = end; return self.bytes[start..end]; } };
pub fn format(self: Param, w: *Writer) Writer.Error!void { try w.print("{f}", .{self.key}); switch (self.key) { .@"no-default-alpn", .ohttp => return, // valueless by definition .mandatory => { try w.writeByte('='); var i: usize = 0; while (i + 2 <= self.value.len) : (i += 2) { if (i > 0) try w.writeByte(','); const key: ParamKey = @enumFromInt(std.mem.readInt(u16, self.value[i..][0..2], .big)); try w.print("{f}", .{key}); } }, .alpn => { // Quoted, because a protocol name may hold a comma -- which // is then escaped, and the quotes are what make the escape // readable. RFC 9460 appendix A.1 writes it this way and so // does `dig`. try w.writeAll("=\""); var it = self.stringList(); var first = true; while (it.next()) |protocol| { if (!first) try w.writeByte(','); first = false; for (protocol) |c| { if (c == ',' or c == '\\' or c == '"') try w.writeByte('\\'); try w.writeByte(c); } } try w.writeByte('"'); }, .port => { if (self.asPort()) |port| return w.print("={d}", .{port}); try w.writeByte('='); try presentation.writeCharacterString(w, self.value); }, .ipv4hint => { try w.writeByte('='); var i: usize = 0; while (i + 4 <= self.value.len) : (i += 4) { if (i > 0) try w.writeByte(','); const address: z46.Ipv4Address = .{ .octets = self.value[i..][0..4].* }; try w.print("{f}", .{address}); } }, .ipv6hint => { try w.writeByte('='); var i: usize = 0; while (i + 16 <= self.value.len) : (i += 16) { if (i > 0) try w.writeByte(','); const address: z46.Ipv6Address = .{ .octets = self.value[i..][0..16].* }; try w.print("{f}", .{address}); } }, .ech => { try w.writeByte('='); try presentation.writeBase64(w, self.value); }, else => { try w.writeByte('='); try presentation.writeCharacterString(w, self.value); }, } }};
/// The parameters of one record, still in wire form.pub const Params = struct { bytes: []const u8,
pub const none: Params = .{ .bytes = "" };
/// Reads the rest of the record data as parameters, checking the shape and /// the strictly increasing key order RFC 9460 §2.2 requires. pub fn parse(d: *Decoder) Error!Params { const bytes = d.takeRest(); var i: usize = 0; var previous: ?u16 = null; while (i < bytes.len) { if (i + 4 > bytes.len) return error.MalformedRdata; const key = std.mem.readInt(u16, bytes[i..][0..2], .big); const length = std.mem.readInt(u16, bytes[i + 2 ..][0..2], .big); if (previous) |p| if (key <= p) return error.MalformedRdata; previous = key; i += 4 + @as(usize, length); if (i > bytes.len) return error.MalformedRdata; } return .{ .bytes = bytes }; }
pub const Iterator = struct { bytes: []const u8, pos: usize = 0,
pub fn next(self: *Iterator) ?Param { if (self.pos + 4 > self.bytes.len) return null; const key = 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 .{ .key = @enumFromInt(key), .value = self.bytes[start..end] }; } };
pub fn iterator(self: Params) Iterator { return .{ .bytes = self.bytes }; }
/// The value of one key, or `null` if the record does not carry it. pub fn get(self: Params, key: ParamKey) ?Param { var it = self.iterator(); while (it.next()) |param| { if (param.key == key) return param; // The keys are in increasing order, so once we are past it, it is // not here. if (@intFromEnum(param.key) > @intFromEnum(key)) return null; } return null; }
/// Checks the `mandatory` key against the rest, as RFC 9460 §8 requires: /// the list must not be empty, must not name key 0, must not repeat a key, /// and must not name a key the record does not carry. /// /// The point of the key is that a client which does not understand /// everything named in it must ignore the whole record. A list naming a /// key that is not there would make every client ignore it, which is not /// something anybody means to publish. pub fn checkMandatory(self: Params) Error!void { const mandatory = self.get(.mandatory) orelse return; if (mandatory.value.len == 0 or mandatory.value.len % 2 != 0) { return error.MalformedRdata; } var previous: ?u16 = null; var i: usize = 0; while (i < mandatory.value.len) : (i += 2) { const key = std.mem.readInt(u16, mandatory.value[i..][0..2], .big); if (key == @intFromEnum(ParamKey.mandatory)) return error.MalformedRdata; if (previous) |p| if (key <= p) return error.MalformedRdata; previous = key; if (self.get(@enumFromInt(key)) == null) return error.MalformedRdata; } }
pub fn format(self: Params, w: *Writer) Writer.Error!void { var it = self.iterator(); var first = true; while (it.next()) |param| { if (!first) try w.writeByte(' '); first = false; try w.print("{f}", .{param}); } }};
/// A `svcb` or `https` record.pub const Svcb = struct { /// Zero means alias mode: `target` is the name to look at instead, and /// there are no parameters. Anything else is service mode, and lower is /// preferred. priority: u16, /// In service mode, the root means "this record's own owner name", which /// is how an apex record avoids repeating itself. target: Name, params: Params = .none,
/// Whether this is an alias: a redirection to another name. An alias has /// no parameters, and RFC 9460 §2.4.2 says that any it carries anyway are /// to be ignored rather than treated as an error -- so `params` may not be /// empty even here, and must not be acted on when this is true. pub fn isAlias(self: Svcb) bool { return self.priority == 0; }
pub fn parse(d: *Decoder) Error!Svcb { // An alias should carry no parameters, and RFC 9460 section 2.4.2 says // what to do when one does: ignore them, not reject the record. So // they are kept and handed back, and `isAlias` is what says they mean // nothing. const out: Svcb = .{ .priority = try d.int(u16), .target = try d.name(), .params = try Params.parse(d), }; if (!out.isAlias()) try out.params.checkMandatory(); return out; }
pub fn writeTo(self: Svcb, b: *Builder) Builder.Error!void { try b.int(u16, self.priority); // RFC 9460 section 2.2: never compressed, in either mode. try b.name(self.target, .uncompressed); try b.writeAll(self.params.bytes); }
pub fn format(self: Svcb, w: *Writer) Writer.Error!void { try w.print("{d} {f}", .{ self.priority, self.target }); if (self.params.bytes.len > 0) { try w.writeByte(' '); try w.print("{f}", .{self.params}); } }};
const testing = std.testing;
test "the alias form" { var d = try wire.Decoder.init("\x00\x00\x03foo\x07example\x03com\x00"); const record = try Svcb.parse(&d); try testing.expect(record.isAlias()); try testing.expectFmt("0 foo.example.com.", "{f}", .{record});}
test "the service form with parameters" { // RFC 9460 appendix D.1, the example with alpn and port and hints. const bytes = "\x00\x10" ++ "\x03foo\x07example\x03com\x00" ++ "\x00\x01\x00\x09\x02h2\x05h3-19" ++ // alpn = h2,h3-19 "\x00\x03\x00\x02\x01\xbb" ++ // port = 443 "\x00\x04\x00\x08\xc0\x00\x02\x01\xc0\x00\x02\x02"; // two ipv4 hints var d = try wire.Decoder.init(bytes); const record = try Svcb.parse(&d); try testing.expect(!record.isAlias()); try testing.expectEqual(@as(u16, 443), record.params.get(.port).?.asPort().?); try testing.expectEqual(@as(?Param, null), record.params.get(.ech)); try testing.expectFmt( "16 foo.example.com. alpn=\"h2,h3-19\" port=443 ipv4hint=192.0.2.1,192.0.2.2", "{f}", .{record}, );}
test "an unknown key keeps its number and its bytes" { const bytes = "\x00\x01" ++ "\x00" ++ "\x02\xff\x00\x02\x68\x69"; var d = try wire.Decoder.init(bytes); const record = try Svcb.parse(&d); try testing.expectFmt("1 . key767=\"hi\"", "{f}", .{record});}
test "parameters must be in increasing key order" { for ([_][]const u8{ "\x00\x01\x00\x00\x03\x00\x02\x01\xbb\x00\x01\x00\x00", // port then alpn "\x00\x01\x00\x00\x03\x00\x02\x01\xbb\x00\x03\x00\x00", // port twice "\x00\x01\x00\x00\x03\x00", // a header cut in half "\x00\x01\x00\x00\x03\x00\x09\x01\xbb", // a value shorter than it claims }) |bytes| { var d = try wire.Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Svcb.parse(&d)); }}
test "an alias that carries parameters anyway is not an error" { // RFC 9460 section 2.4.2 says to ignore them rather than refuse the // record, so they survive the decode and `isAlias` is what says not to // look at them. var d = try wire.Decoder.init("\x00\x00\x00\x00\x03\x00\x02\x01\xbb"); const record = try Svcb.parse(&d); try testing.expect(record.isAlias()); try testing.expectEqual(@as(u16, 443), record.params.get(.port).?.asPort().?);}
test "a mandatory list has to agree with the rest of the record" { // mandatory=alpn, alpn=h2: consistent. var good = try wire.Decoder.init( "\x00\x01" ++ "\x00" ++ "\x00\x00\x00\x02\x00\x01" ++ "\x00\x01\x00\x03\x02h2", ); const record = try Svcb.parse(&good); try testing.expectFmt("1 . mandatory=alpn alpn=\"h2\"", "{f}", .{record});
for ([_][]const u8{ // mandatory names alpn, which is not here. "\x00\x01\x00\x00\x00\x00\x02\x00\x01", // mandatory names itself. "\x00\x01\x00\x00\x00\x00\x02\x00\x00", // mandatory is empty. "\x00\x01\x00\x00\x00\x00\x00", // mandatory has an odd number of bytes. "\x00\x01\x00\x00\x00\x00\x01\x00", }) |bytes| { var d = try wire.Decoder.init(bytes); try testing.expectError(error.MalformedRdata, Svcb.parse(&d)); }
// An alias is not checked, because its parameters mean nothing. var alias = try wire.Decoder.init("\x00\x00\x00\x00\x00\x00\x02\x00\x01"); _ = try Svcb.parse(&alias);}