Something went wrong. Try again.
A URI parser and formatter for Zig, modelled on Python's hyperlink package, with LDAP URLs, file: URIs and sdns:// DNS stamps beside it.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! DNS stamps: `sdns://`, the one-string form a DNS resolver is published as.//!//! A stamp is not a URI whose authority happens to be interesting. Everything//! after `sdns://` is one base64url string whose bytes are a binary structure —//! a protocol byte, a properties word, and then fields behind one-byte length//! prefixes — so a generic parser has nothing to work with. `Uri.parse` will//! read one without complaining, because base64url happens to use only//! characters an authority may contain, and then the body is sitting in//! `Host.hostname` where `normalize` lowercases it and destroys the payload.//! That is why this is a parser of its own rather than a view over `Uri`, for//! the same reason `ldap.zig` is.//!//! ```zig//! const s = try uri.stamp.Stamp.parse(alloc, "sdns://AQcAAAAAAAAAAAAQMi5kbnNjcnlwdC1jZXJ0Lg");//! defer s.deinit();//!//! switch (s.body) {//! .dnscrypt => |d| {//! d.address // "94.140.14.14:5443", as written//! d.public_key // the provider's 32 bytes//! d.provider_name // "2.dnscrypt.default.ns1.adguard.com"//! },//! else => {},//! }//! ```//!//! ## The eight protocols//!//! From the DNS Stamps specification, where `LP(x)` is one length byte then//! `x`, and `VLP(x1…xn)` is the same repeated with the high bit of the length//! set on every element but the last://!//! ```text//! 0x00 plain props LP(addr[:port])//! 0x01 dnscrypt props LP(addr[:port]) LP(pk) LP(provider name)//! 0x02 doh props LP(addr) VLP(hashes) LP(host[:port]) LP(path) [VLP(bootstrap)]//! 0x03 dot props LP(addr) VLP(hashes) LP(host[:port]) [VLP(bootstrap)]//! 0x04 doq props LP(addr) VLP(hashes) LP(host[:port]) [VLP(bootstrap)]//! 0x05 odoh target props LP(host[:port]) LP(path)//! 0x81 dnscrypt relay LP(addr[:port])//! 0x85 odoh relay props LP(addr) VLP(hashes) LP(host[:port]) LP(path) [VLP(bootstrap)]//! ```//!//! The relay at `0x81` is the trap in the format: it is the one stamp with no//! properties word, so a reader that takes eight bytes off the front of every//! body reads a relay's address length as a property bit and everything after//! it as rubbish.//!//! ## Addresses come back as text//!//! `address`, `hostname` and the bootstrap entries are the bytes that were//! written, not parsed into anything. This library depends on z46 and could//! hand back an `Endpoint` — but a z46 type crossing into a consumer makes that//! consumer's z46 pin have to match this library's, and a caller who wants one//! writes `z46.Endpoint.parse(s.body.dnscrypt.address)`. One line there against//! a version constraint here is not a close call.//!//! ## What is stored, and what is not//!//! Every slice points into the decoded stamp, which the arena holds — so, as//! everywhere else in this library, the fields are valid until `deinit`. The//! properties word keeps the bits it was given, including any this//! specification has not defined, so a stamp written by something newer//! re-encodes byte for byte.
const std = @import("std");
const Allocator = std.mem.Allocator;const Writer = std.Io.Writer;
/// The scheme, which is the whole of the text outside the base64url.pub const prefix = "sdns://";
/// What the first byte of a stamp says it describes.pub const Protocol = enum(u8) { /// Plain, unencrypted DNS. A stamp for it carries nothing an address does /// not, and exists so that a resolver list can name one. plain = 0x00, dnscrypt = 0x01, doh = 0x02, dot = 0x03, doq = 0x04, /// The target of an oblivious DoH exchange, which is reached through a /// relay and so needs no address of its own. odoh_target = 0x05, /// A relay that forwards DNSCrypt queries without being able to read them /// (Anonymized DNSCrypt). dnscrypt_relay = 0x81, odoh_relay = 0x85,};
/// What a resolver says about itself. Advertisement rather than evidence: a/// stamp is written by whoever publishes the resolver.pub const Properties = packed struct(u64) { /// The resolver validates DNSSEC. dnssec: bool = false, /// The resolver does not keep logs. no_log: bool = false, /// The resolver does not intentionally block names. no_filter: bool = false, /// Bits this specification has not given a meaning, kept so that a stamp /// written by something newer survives a round trip. unknown: u61 = 0,};
pub const Error = error{ /// The text does not begin `sdns://`. NotAStamp, /// The text after `sdns://` is not base64url. InvalidBase64, /// A protocol byte this module does not know. Deliberately an error rather /// than a variant: a stamp names how to reach a resolver, and a caller that /// was handed one it cannot interpret would have to guess. UnknownProtocol, /// A length prefix ran past the end of the stamp. Truncated, /// Bytes after the last field. A stamp with something extra on the end is /// one this module has read wrongly or one written wrongly, and either way /// the fields before it cannot be trusted. TrailingBytes, /// A DNSCrypt provider key that is not 32 bytes. InvalidPublicKey,} || Allocator.Error;
/// A parsed stamp and the memory its strings live in.////// The arena holds one allocation — the decoded stamp — and every slice in/// `body` points into it. It is an arena rather than that one slice so that/// `deinit` takes no allocator, as `Uri.deinit` and `ldap.Url.deinit` do not.pub const Stamp = struct { arena: *std.heap.ArenaAllocator, body: Body,
/// The fields each protocol carries. pub const Body = union(Protocol) { plain: Plain, dnscrypt: DnsCrypt, doh: Endpoint, dot: Endpoint, doq: Endpoint, odoh_target: Target, dnscrypt_relay: Relay, odoh_relay: Endpoint, };
pub const Plain = struct { properties: Properties, /// An IP address, with an optional `:port`; IPv6 in brackets. address: []const u8, };
pub const DnsCrypt = struct { properties: Properties, address: []const u8, /// The provider's long-term Ed25519 public key, which is the whole of /// what a DNSCrypt client trusts. public_key: [32]u8, /// The name whose TXT record carries the resolver's certificate. provider_name: []const u8, };
/// The shape DoH, DoT, DoQ and the oblivious relay share. pub const Endpoint = struct { properties: Properties, /// May be empty, which means the hostname is to be resolved first — /// with the bootstrap resolvers, if the stamp named any. address: []const u8, /// SHA-256 digests of the TBS certificates the chain must contain. /// Empty when the stamp pinned nothing. hashes: []const []const u8 = &.{}, /// Also the name sent in SNI. Port 443 when none is written. hostname: []const u8, /// Empty for DNS over TLS and DNS over QUIC, which have no path. path: []const u8 = "", /// Plain DNS resolvers to look `hostname` up with. Empty when the /// stamp named none. bootstrap: []const []const u8 = &.{}, };
pub const Target = struct { properties: Properties, hostname: []const u8, path: []const u8, };
pub const Relay = struct { /// An address and port. The one stamp with no properties word. address: []const u8, };
// -- construction ------------------------------------------------------
pub fn parse(alloc: Allocator, text: []const u8) Error!Stamp { const arena = try alloc.create(std.heap.ArenaAllocator); arena.* = .init(alloc); errdefer destroyArena(arena); return .{ .arena = arena, .body = try parseInto(arena.allocator(), text) }; }
pub fn deinit(self: Stamp) void { destroyArena(self.arena); }
// -- inspection --------------------------------------------------------
pub fn protocol(self: Stamp) Protocol { return self.body; }
/// What the resolver says about itself, or null for a DNSCrypt relay, /// which says nothing because its stamp has nowhere to say it. pub fn properties(self: Stamp) ?Properties { return switch (self.body) { .plain => |b| b.properties, .dnscrypt => |b| b.properties, .doh, .dot, .doq, .odoh_relay => |b| b.properties, .odoh_target => |b| b.properties, .dnscrypt_relay => null, }; }
/// The address a client connects to, which is empty for the two stamps /// that name a host instead and for a DoH or DoT stamp that leaves it to /// the bootstrap resolvers. pub fn address(self: Stamp) []const u8 { return switch (self.body) { .plain => |b| b.address, .dnscrypt => |b| b.address, .doh, .dot, .doq, .odoh_relay => |b| b.address, .odoh_target => "", .dnscrypt_relay => |b| b.address, }; }
/// Whether two stamps name the same resolver in the same way, field for /// field. Present for the reason `Uri.eql` is: a resolver list is a set, /// and the same resolver is commonly published in more than one place. pub fn eql(a: Stamp, b: Stamp) bool { if (@as(Protocol, a.body) != @as(Protocol, b.body)) return false; return switch (a.body) { .plain => |x| { const y = b.body.plain; return x.properties == y.properties and std.mem.eql(u8, x.address, y.address); }, .dnscrypt => |x| { const y = b.body.dnscrypt; return x.properties == y.properties and std.mem.eql(u8, x.address, y.address) and std.mem.eql(u8, &x.public_key, &y.public_key) and std.mem.eql(u8, x.provider_name, y.provider_name); }, .doh => |x| endpointEql(x, b.body.doh), .dot => |x| endpointEql(x, b.body.dot), .doq => |x| endpointEql(x, b.body.doq), .odoh_relay => |x| endpointEql(x, b.body.odoh_relay), .odoh_target => |x| { const y = b.body.odoh_target; return x.properties == y.properties and std.mem.eql(u8, x.hostname, y.hostname) and std.mem.eql(u8, x.path, y.path); }, .dnscrypt_relay => |x| std.mem.eql(u8, x.address, b.body.dnscrypt_relay.address), }; }
// -- text --------------------------------------------------------------
/// The stamp as `sdns://` and base64url, which for a stamp that was parsed /// is the text it was parsed from. pub fn write(self: Stamp, w: *Writer) Writer.Error!void { try w.writeAll(prefix); var sink: Base64Sink = .init(w); try self.writeBinary(&sink); try sink.finish(); }
pub fn toText(self: Stamp, alloc: Allocator) Allocator.Error![]u8 { var out: Writer.Allocating = .init(alloc); defer out.deinit(); self.write(&out.writer) catch return error.OutOfMemory; return out.toOwnedSlice(); }
pub fn format(self: Stamp, w: *Writer) Writer.Error!void { return self.write(w); }
fn writeBinary(self: Stamp, sink: *Base64Sink) Writer.Error!void { try sink.byte(@backingInt(@as(Protocol, self.body))); switch (self.body) { .plain => |b| { try sink.properties(b.properties); try sink.lp(b.address); }, .dnscrypt => |b| { try sink.properties(b.properties); try sink.lp(b.address); try sink.lp(&b.public_key); try sink.lp(b.provider_name); }, .doh, .odoh_relay => |b| { try sink.properties(b.properties); try sink.lp(b.address); try sink.vlp(b.hashes); try sink.lp(b.hostname); try sink.lp(b.path); if (b.bootstrap.len > 0) try sink.vlp(b.bootstrap); }, .dot, .doq => |b| { try sink.properties(b.properties); try sink.lp(b.address); try sink.vlp(b.hashes); try sink.lp(b.hostname); if (b.bootstrap.len > 0) try sink.vlp(b.bootstrap); }, .odoh_target => |b| { try sink.properties(b.properties); try sink.lp(b.hostname); try sink.lp(b.path); }, .dnscrypt_relay => |b| try sink.lp(b.address), } }};
fn endpointEql(a: Stamp.Endpoint, b: Stamp.Endpoint) bool { if (a.properties != b.properties) return false; if (!std.mem.eql(u8, a.address, b.address)) return false; if (!std.mem.eql(u8, a.hostname, b.hostname)) return false; if (!std.mem.eql(u8, a.path, b.path)) return false; return listEql(a.hashes, b.hashes) and listEql(a.bootstrap, b.bootstrap);}
fn listEql(a: []const []const u8, b: []const []const u8) bool { if (a.len != b.len) return false; for (a, b) |x, y| if (!std.mem.eql(u8, x, y)) return false; return true;}
fn destroyArena(arena: *std.heap.ArenaAllocator) void { const alloc = arena.child_allocator; arena.deinit(); alloc.destroy(arena);}
fn parseInto(alloc: Allocator, text: []const u8) Error!Stamp.Body { if (text.len < prefix.len) return error.NotAStamp; // The scheme, case-insensitively: RFC 3986 §3.1 makes a scheme // case-insensitive, and every published stamp is lower case anyway. if (!std.ascii.eqlIgnoreCase(text[0..prefix.len], prefix)) return error.NotAStamp;
// Stamps are written without padding. A stamp that carries it is accepted // -- somebody's encoder added it, and the bytes underneath are the same -- // and nothing else is. const encoded = std.mem.trimEnd(u8, text[prefix.len..], "="); const decoder = std.base64.url_safe_no_pad.Decoder; const len = decoder.calcSizeForSlice(encoded) catch return error.InvalidBase64; const bytes = try alloc.alloc(u8, len); decoder.decode(bytes, encoded) catch return error.InvalidBase64;
var c: Cursor = .{ .bytes = bytes }; const protocol = protocolOf(try c.byte()) orelse return error.UnknownProtocol;
const body: Stamp.Body = switch (protocol) { .plain => .{ .plain = .{ .properties = try c.properties(), .address = try c.lp(), } }, .dnscrypt => blk: { const props = try c.properties(); const addr = try c.lp(); const key = try c.lp(); if (key.len != 32) return error.InvalidPublicKey; break :blk .{ .dnscrypt = .{ .properties = props, .address = addr, .public_key = key[0..32].*, .provider_name = try c.lp(), } }; }, .doh, .odoh_relay => blk: { const endpoint = try c.endpoint(alloc, .with_path); break :blk if (protocol == .doh) .{ .doh = endpoint } else .{ .odoh_relay = endpoint }; }, .dot, .doq => blk: { const endpoint = try c.endpoint(alloc, .without_path); break :blk if (protocol == .dot) .{ .dot = endpoint } else .{ .doq = endpoint }; }, .odoh_target => .{ .odoh_target = .{ .properties = try c.properties(), .hostname = try c.lp(), .path = try c.lp(), } }, // No properties word. See the note at the top of this file. .dnscrypt_relay => .{ .dnscrypt_relay = .{ .address = try c.lp() } }, };
if (!c.done()) return error.TrailingBytes; return body;}
/// The protocol a first byte names, or null for one this module does not know.////// Written out rather than reached through a cast: the assigned values are not/// contiguous -- the two relays are 0x81 and 0x85 -- so a cast would accept/// every byte in between as an enum value that has no meaning.fn protocolOf(value: u8) ?Protocol { return switch (value) { 0x00 => .plain, 0x01 => .dnscrypt, 0x02 => .doh, 0x03 => .dot, 0x04 => .doq, 0x05 => .odoh_target, 0x81 => .dnscrypt_relay, 0x85 => .odoh_relay, else => null, };}
/// A position in a decoded stamp, and the three readings the format is made/// of. Every field is bounded by a length that came out of the same bytes, so/// every read can run off the end and every one of them says so.const Cursor = struct { bytes: []const u8, at: usize = 0,
fn byte(c: *Cursor) Error!u8 { if (c.at >= c.bytes.len) return error.Truncated; defer c.at += 1; return c.bytes[c.at]; }
fn take(c: *Cursor, n: usize) Error![]const u8 { if (c.bytes.len - c.at < n) return error.Truncated; defer c.at += n; return c.bytes[c.at..][0..n]; }
fn properties(c: *Cursor) Error!Properties { const word = try c.take(8); return @bitCast(std.mem.readInt(u64, word[0..8], .little)); }
/// `LP(x)`: one length byte, then that many. fn lp(c: *Cursor) Error![]const u8 { return c.take(try c.byte()); }
/// `VLP(x1…xn)`: the same, with the high bit of the length set on every /// element but the last. /// /// A list with nothing in it is written as one element of length zero, /// which is what every encoder produces for "no certificate hashes", so /// that is what an empty list reads back as and what `Base64Sink.vlp` /// writes for one. A stamp therefore round-trips whichever way it meant it. fn vlp(c: *Cursor, alloc: Allocator) Error![]const []const u8 { var items: std.ArrayList([]const u8) = .empty; errdefer items.deinit(alloc); while (true) { const marked = try c.byte(); const item = try c.take(marked & 0x7f); if (item.len > 0) try items.append(alloc, item); if (marked & 0x80 == 0) break; } return items.toOwnedSlice(alloc); }
const Path = enum { with_path, without_path };
fn endpoint(c: *Cursor, alloc: Allocator, path: Path) Error!Stamp.Endpoint { const props = try c.properties(); const addr = try c.lp(); const hashes = try c.vlp(alloc); const hostname = try c.lp(); const resource = if (path == .with_path) try c.lp() else ""; // §The bootstrap list is optional and last, so what is left says // whether it is there at all. const bootstrap = if (c.done()) &.{} else try c.vlp(alloc); return .{ .properties = props, .address = addr, .hashes = hashes, .hostname = hostname, .path = resource, .bootstrap = bootstrap, }; }
fn done(c: *const Cursor) bool { return c.at == c.bytes.len; }};
/// A writer that base64url-encodes what is written to it.////// Base64 turns three octets into four characters, so an encoder needs the/// octets in threes. Rather than build the whole binary form somewhere and/// encode it -- which would need an allocator in `write`, where this library's/// other `write` methods take none -- this holds the up-to-two octets left/// over from the last write and emits a group as soon as it has three./// `finish` writes what is left, unpadded, as a stamp is written.const Base64Sink = struct { out: *Writer, pending: [3]u8 = undefined, len: usize = 0,
const alphabet = std.base64.url_safe_alphabet_chars;
fn init(out: *Writer) Base64Sink { return .{ .out = out }; }
fn byte(s: *Base64Sink, value: u8) Writer.Error!void { return s.writeAll(&.{value}); }
fn properties(s: *Base64Sink, value: Properties) Writer.Error!void { var word: [8]u8 = undefined; std.mem.writeInt(u64, &word, @bitCast(value), .little); return s.writeAll(&word); }
fn lp(s: *Base64Sink, item: []const u8) Writer.Error!void { std.debug.assert(item.len <= 0xff); try s.byte(@intCast(item.len)); return s.writeAll(item); }
fn vlp(s: *Base64Sink, items: []const []const u8) Writer.Error!void { if (items.len == 0) return s.byte(0); for (items, 0..) |item, i| { std.debug.assert(item.len <= 0x7f); const last = i == items.len - 1; const marker: u8 = if (last) 0x00 else 0x80; try s.byte(@as(u8, @intCast(item.len)) | marker); try s.writeAll(item); } }
fn writeAll(s: *Base64Sink, bytes: []const u8) Writer.Error!void { for (bytes) |b| { s.pending[s.len] = b; s.len += 1; if (s.len == 3) { try s.group(3); s.len = 0; } } }
fn finish(s: *Base64Sink) Writer.Error!void { if (s.len == 0) return; try s.group(s.len); s.len = 0; }
/// One group: four characters for three octets, and one fewer for each /// octet missing -- which is what "unpadded" means. fn group(s: *Base64Sink, n: usize) Writer.Error!void { const a = s.pending[0]; const b = if (n > 1) s.pending[1] else 0; const c = if (n > 2) s.pending[2] else 0; var chars: [4]u8 = .{ alphabet[a >> 2], alphabet[((a & 0x03) << 4) | (b >> 4)], alphabet[((b & 0x0f) << 2) | (c >> 6)], alphabet[c & 0x3f], }; try s.out.writeAll(chars[0 .. n + 1]); }};