// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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 carries no parameters that //! mean anything 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), }; } test name { try std.testing.expectEqualStrings("no-default-alpn", ParamKey.@"no-default-alpn".name().?); try std.testing.expectEqual(@as(?[]const u8, null), @as(ParamKey, @fromBackingInt(767)).name()); } /// The key's name, or `keyNNNNN` for one without a name here -- the form /// RFC 9460 §2.1 lets a zone file use for any key, known or not. pub fn format(self: ParamKey, w: *Writer) Writer.Error!void { if (self.name()) |n| return w.writeAll(n); try w.print("key{d}", .{@backingInt(self)}); } test format { try std.testing.expectFmt("alpn", "{f}", .{ParamKey.alpn}); try std.testing.expectFmt("key767", "{f}", .{@as(ParamKey, @fromBackingInt(767))}); } }; /// 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); } test asPort { const port: Param = .{ .key = .port, .value = "\x01\xbb" }; try std.testing.expectEqual(@as(?u16, 443), port.asPort()); // The same two bytes under another key are not a port. const other: Param = .{ .key = .dohpath, .value = "\x01\xbb" }; try std.testing.expectEqual(@as(?u16, null), other.asPort()); } /// Walks a value that is a list of character-strings: `alpn`. pub fn stringList(self: Param) StringListIterator { return .{ .bytes = self.value }; } test stringList { const alpn: Param = .{ .key = .alpn, .value = "\x02h2\x02h3" }; var count: usize = 0; var it = alpn.stringList(); while (it.next()) |_| count += 1; try std.testing.expectEqual(@as(usize, 2), count); } /// The strings of a value that is a list of character-strings, each /// without its length byte. pub const StringListIterator = struct { bytes: []const u8, pos: usize = 0, /// The next string, or `null` at the end of the value. A string that /// claims to run past the end stops the walk rather than being read, /// which `Params.parse` already refuses for `alpn` but a value built /// by hand may hold. 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]; } test next { var it: StringListIterator = .{ .bytes = "\x02h2\x05h3-19" }; try std.testing.expectEqualStrings("h2", it.next().?); try std.testing.expectEqualStrings("h3-19", it.next().?); try std.testing.expectEqual(@as(?[]const u8, null), it.next()); } }; /// `key=value`, with each known key's value in its own presentation form: /// `mandatory` as a list of key names, `alpn` quoted and escaped, `port` /// in decimal, the hints as addresses, `ech` in base64, and anything else /// as a character-string. `no-default-alpn` and `ohttp` have no value and /// print only the key. 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 = @fromBackingInt(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); }, } } test format { // A comma inside a protocol name is escaped, so that it does not read // as the separator between two of them. const alpn: Param = .{ .key = .alpn, .value = "\x02h2\x03a,b" }; try std.testing.expectFmt("alpn=\"h2,a\\,b\"", "{f}", .{alpn}); const hint: Param = .{ .key = .ipv4hint, .value = "\xc0\x00\x02\x01\xc0\x00\x02\x02" }; try std.testing.expectFmt("ipv4hint=192.0.2.1,192.0.2.2", "{f}", .{hint}); } }; /// The parameters of one record, still in wire form. pub const Params = struct { bytes: []const u8, /// No parameters at all, which is what an alias carries. pub const none: Params = .{ .bytes = "" }; /// Reads the rest of the record data as parameters, checking the shape, /// the strictly increasing key order RFC 9460 §2.2 requires, and that the /// value of every key this library knows is the shape its specification /// gives it. A key it does not know is carried with whatever it holds. /// /// The values are checked in alias mode too: RFC 9460 §2.4.2 says to /// ignore parameters there, which is not the same as letting them be /// malformed. 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; const start = i + 4; i = start + @as(usize, length); if (i > bytes.len) return error.MalformedRdata; try checkValue(@fromBackingInt(key), bytes[start..i]); } return .{ .bytes = bytes }; } test parse { // port=443, then ipv4hint=192.0.2.1. var d = try wire.Decoder.init("\x00\x03\x00\x02\x01\xbb" ++ "\x00\x04\x00\x04\xc0\x00\x02\x01"); const params = try Params.parse(&d); try std.testing.expectEqual(@as(?u16, 443), params.get(.port).?.asPort()); // A port of three bytes is not a port whatever it means, and is // refused. var long = try wire.Decoder.init("\x00\x03\x00\x03\x00\x01\xbb"); try std.testing.expectError(error.MalformedRdata, Params.parse(&long)); } /// Whether a value is the shape its key's specification gives it. fn checkValue(key: ParamKey, value: []const u8) Error!void { const ok = switch (key) { // A list of keys, two bytes each; which keys, and whether they are // here, is `checkMandatory`'s business. .mandatory => value.len > 0 and value.len % 2 == 0, // At least one protocol, each a non-empty character-string, since // TLS has no empty protocol name (RFC 7301 §3.1), and the strings // exactly filling the value. .alpn => alpn: { if (value.len == 0) break :alpn false; var pos: usize = 0; while (pos < value.len) { const length = value[pos]; if (length == 0) break :alpn false; pos += 1 + @as(usize, length); } break :alpn pos == value.len; }, .@"no-default-alpn", .ohttp => value.len == 0, .port => value.len == 2, .ipv4hint => value.len > 0 and value.len % 4 == 0, .ipv6hint => value.len > 0 and value.len % 16 == 0, // An ECHConfigList (RFC 9848, RFC 9849 §4): a two-byte length, // then that many bytes of configurations, of which there is at // least one. The configurations themselves are TLS's business. .ech => value.len >= 4 and std.mem.readInt(u16, value[0..2], .big) == value.len - 2, .dohpath, _ => true, }; if (!ok) return error.MalformedRdata; } /// Every parameter, in the order they were written, which `parse` has /// made sure is increasing. pub const Iterator = struct { bytes: []const u8, pos: usize = 0, /// The next parameter, or `null` at the end. One that claims to run /// past the end stops the walk rather than being read. 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 = @fromBackingInt(key), .value = self.bytes[start..end] }; } test next { const params: Params = .{ .bytes = "\x00\x01\x00\x03\x02h2" ++ "\x00\x03\x00\x02\x01\xbb" }; var it = params.iterator(); try std.testing.expectEqual(ParamKey.alpn, it.next().?.key); try std.testing.expectEqual(ParamKey.port, it.next().?.key); try std.testing.expectEqual(@as(?Param, null), it.next()); } }; /// Walks the parameters in key order. pub fn iterator(self: Params) Iterator { return .{ .bytes = self.bytes }; } test iterator { const params: Params = .{ .bytes = "\x00\x01\x00\x03\x02h2" ++ "\x00\x03\x00\x02\x01\xbb" }; var count: usize = 0; var it = params.iterator(); while (it.next()) |_| count += 1; try std.testing.expectEqual(@as(usize, 2), count); } /// 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 (@backingInt(param.key) > @backingInt(key)) return null; } return null; } test get { const params: Params = .{ .bytes = "\x00\x01\x00\x03\x02h2" ++ "\x00\x03\x00\x02\x01\xbb" }; try std.testing.expectEqual(@as(?u16, 443), params.get(.port).?.asPort()); try std.testing.expectEqual(@as(?Param, null), params.get(.ech)); } /// Checks the `mandatory` key against the rest, as RFC 9460 §8 requires: /// the list must not be empty, must not name key 0, must list its keys in /// strictly increasing order (so never the same one twice), and must not /// name a key the record does not carry. Parameters without a `mandatory` /// key pass. /// /// 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 == @backingInt(ParamKey.mandatory)) return error.MalformedRdata; if (previous) |p| if (key <= p) return error.MalformedRdata; previous = key; if (self.get(@fromBackingInt(key)) == null) return error.MalformedRdata; } } test checkMandatory { // mandatory=alpn, with an alpn to back it. const good: Params = .{ .bytes = "\x00\x00\x00\x02\x00\x01" ++ "\x00\x01\x00\x03\x02h2" }; try good.checkMandatory(); // mandatory=alpn, and no alpn: every client would have to ignore it. const bad: Params = .{ .bytes = "\x00\x00\x00\x02\x00\x01" }; try std.testing.expectError(error.MalformedRdata, bad.checkMandatory()); } /// The parameters, separated by spaces, each as `Param.format` writes it. 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}); } } test format { const params: Params = .{ .bytes = "\x00\x01\x00\x03\x02h2" ++ "\x00\x03\x00\x02\x01\xbb" }; try std.testing.expectFmt("alpn=\"h2\" port=443", "{f}", .{params}); } }; /// A `svcb` or `https` record. pub const Svcb = struct { /// Zero means alias mode: `target` is the name to look at instead, and /// any parameters are to be ignored. 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; } test isAlias { const alias: Svcb = .{ .priority = 0, .target = Name.literal("svc.example.net") }; try std.testing.expect(alias.isAlias()); const service: Svcb = .{ .priority = 1, .target = Name.root }; try std.testing.expect(!service.isAlias()); } /// Reads the priority, the target -- refusing a compression pointer in it /// with `error.CompressionForbidden` -- and the parameters, which /// `Params.parse` checks. In service mode the `mandatory` list is then /// checked against the rest with `Params.checkMandatory`; in alias mode /// it is not, since the parameters there mean nothing. 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.uncompressedName(), .params = try Params.parse(d), }; if (!out.isAlias()) try out.params.checkMandatory(); return out; } test parse { // Priority 1, the root as the target (this record's own owner), and // port=8443. var d = try wire.Decoder.init("\x00\x01" ++ "\x00" ++ "\x00\x03\x00\x02\x20\xfb"); const record = try Svcb.parse(&d); try std.testing.expect(record.target.isRoot()); try std.testing.expectEqual(@as(?u16, 8443), record.params.get(.port).?.asPort()); } /// Writes the priority, the target in full -- never compressed, in /// either mode -- and the parameters as they are. 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); } test writeTo { const record: Svcb = .{ .priority = 1, .target = Name.literal("svc.example.net"), .params = .{ .bytes = "\x00\x03\x00\x02\x20\xfb" }, }; var buf: [512]u8 = undefined; var b = try Builder.init(&buf, .{ .id = 0 }, .{}); try record.writeTo(&b); try std.testing.expectEqualSlices( u8, "\x00\x01" ++ "\x03svc\x07example\x03net\x00" ++ "\x00\x03\x00\x02\x20\xfb", b.buffer[12..b.pos], ); } /// The priority, the target as an absolute name, and then the /// parameters, if there are any. 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}); } } test format { const alias: Svcb = .{ .priority = 0, .target = Name.literal("svc.example.net") }; try std.testing.expectFmt("0 svc.example.net.", "{f}", .{alias}); const service: Svcb = .{ .priority = 1, .target = Name.root, .params = .{ .bytes = "\x00\x03\x00\x02\x20\xfb" }, }; try std.testing.expectFmt("1 . port=8443", "{f}", .{service}); } }; 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 "a value has to be the shape its key gives it" { for ([_][]const u8{ "\x00\x00\x00\x00", // mandatory, empty "\x00\x01\x00\x00", // alpn, empty "\x00\x01\x00\x03\x02h2\x00", // alpn, with an empty protocol after h2 "\x00\x01\x00\x03\x03h2", // alpn, a protocol running past the value "\x00\x02\x00\x01\x00", // no-default-alpn, with a value "\x00\x03\x00\x01\x01", // port, one byte "\x00\x03\x00\x03\x00\x01\xbb", // port, three bytes "\x00\x04\x00\x00", // ipv4hint, empty "\x00\x04\x00\x05\xc0\x00\x02\x01\x01", // ipv4hint, five bytes "\x00\x05\x00\x02\x00\x00", // ech, no configuration at all "\x00\x05\x00\x04\x00\x05\x01\x02", // ech, a list longer than it claims "\x00\x06\x00\x04\x20\x01\x0d\xb8", // ipv6hint, four bytes "\x00\x08\x00\x01\x00", // ohttp, with a value }) |params| { // Priority 1 and the root as the target, then the parameter. var buf: [32]u8 = undefined; @memcpy(buf[0..3], "\x00\x01\x00"); @memcpy(buf[3..][0..params.len], params); var service = try wire.Decoder.init(buf[0 .. 3 + params.len]); try testing.expectError(error.MalformedRdata, Svcb.parse(&service)); // And in alias mode, where the parameters are to be ignored but are // still malformed. buf[1] = 0; var alias = try wire.Decoder.init(buf[0 .. 3 + params.len]); try testing.expectError(error.MalformedRdata, Svcb.parse(&alias)); } // A key nobody has defined holds whatever it likes. var unknown = try wire.Decoder.init("\x00\x01\x00" ++ "\x00\x63\x00\x00"); _ = try Svcb.parse(&unknown); // And an ECHConfigList that frames is enough; what is inside it is not // looked at. var ech = try wire.Decoder.init("\x00\x01\x00" ++ "\x00\x05\x00\x04\x00\x02\xfe\x0d"); _ = try Svcb.parse(&ech); } 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); }