// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A DNS-over-QUIC server: RFC 9250, from the other end. //! //! The client in `main.zig` proved that this library can talk to aioquic. //! This is the half that proof left out, and it is the more interesting half: //! a server is the endpoint that answers strangers. It is the one that has to //! derive Initial keys from a connection ID somebody else chose, that has to //! obey §5.2's amplification limit before it knows who it is talking to, and //! that has to send a certificate chain — which, until this existed, no test //! in the project had ever done, because every one of them used a server with //! `auth = null` and no certificate at all. //! //! ## Routing, which is the part a single connection hides //! //! A server owns one socket and many connections, so every datagram has to be //! attributed to one of them before anything else can happen. §5.1 of RFC //! 9000 is what makes that possible: the Destination Connection ID in a //! packet is a value *this* endpoint chose and told the peer to use, so it is //! an index into whatever the server keeps its connections in. A short header //! has nothing else in it — no addresses, no version — which is why §5.1 //! requires an endpoint to know its own connection ID length before it can //! parse one. //! //! An Initial packet that matches nothing starts a connection. A short-header //! packet that matches nothing is either a straggler from a connection that //! has gone or somebody probing the port, and `quic_io.Endpoint` answers it //! with §10.3's stateless reset, so that a peer whose connection was lost — //! to a restart, say — stops at once rather than waiting out its idle //! timeout. `--reset-key` is what lets a restarted server still produce //! tokens the peer believes. Any other long-header packet that matches //! nothing gets no answer at all. const std = @import("std"); const Io = std.Io; const net = Io.net; const quic = @import("quic"); const quic_io = @import("quic_io"); const usage = \\Usage: doqd [options] \\ \\Answers DNS-over-QUIC queries (RFC 9250) from a fixed zone. \\ \\ --address HOST The address to bind (default 127.0.0.1) \\ --port N The port to bind (default 853, RFC 9250 §5.1) \\ --cert FILE The server's certificate chain, leaf first, as PEM \\ --key FILE The private key for the leaf certificate, as PEM \\ --raw-key FILE Authenticate with this Ed25519 private key, as PEM, \\ instead of a certificate (RFC 7250), and require \\ every client to present a key of its own. Prints this \\ server's public key, which is what clients dial. \\ --peer-key HEX With --raw-key, admit only the client holding this \\ Ed25519 public key, 64 hex digits. Without it any \\ client that proves its key is admitted, and the key \\ is printed. \\ --answer NAME=A Add a name to the zone; may be repeated \\ --reset-key HEX 64 hex digits: the static key stateless reset tokens \\ are derived from (§10.3.2). Configured rather than \\ generated on purpose — an endpoint that restarts must \\ compute the same tokens it did before, or the resets \\ it sends mean nothing to the peers it lost. \\ --ticket-key H 64 hex digits: the key session tickets are sealed with \\ (RFC 8446 §4.6.1). Without it this server issues no \\ tickets and resumes nothing, which is a choice a \\ server is entitled to make. \\ --nat-address A Offer A, at this server's port, as a candidate for \\ n0's NAT traversal -- the hole punching iroh does to \\ open a direct path. May be repeated; any use of it \\ turns the extension on. \\ --retry Validate every client's address with a Retry packet \\ before keeping any state for it (§8.1). Costs the \\ client a round trip and costs this server nothing, \\ which is the trade the mechanism exists to offer. \\ --queries N Exit after answering this many queries, at once and \\ without closing any connection -- as a crash would, \\ so that a peer finds out from a stateless reset \\ --verbose Say what arrives and what happens to it \\ ; fn fail(comptime message: []const u8) noreturn { std.debug.print("doqd: " ++ message ++ "\n", .{}); std.process.exit(1); } /// How many connections this server will hold at once. /// /// Bounded like everything else: a server that allocated per arriving Initial /// would be handing its memory to whoever can send a UDP packet, and an /// Initial packet costs nothing to forge because its keys come from a /// connection ID in the clear. const max_connections = 8; /// The zone, which is a list rather than anything cleverer because this /// answers a handful of names in a test. const max_names = 8; const Entry = struct { name: []const u8, address: [4]u8, }; /// Everything the connection tasks share: the zone they answer from, the /// flags, and the counter that stops the server. const Server = struct { io: Io, zone: []const Entry, verbose: bool, datagrams: bool, /// Whether clients authenticate by raw public key, which is when there /// is a client identity worth printing. raw_keys: bool = false, /// n0's NAT traversal: the candidates offered to each client. nat_addresses: []const net.IpAddress = &.{}, /// §4.2 of RFC 9250 puts one query on each stream, so this counts streams /// answered rather than connections served. answered: std.atomic.Value(usize) = .init(0), limit: ?usize, tasks: Io.Group = .init, /// One connection, on a task of its own. /// /// Blocking, all the way down: `accept` waits for a stream, the reader /// waits for its octets, and the writer sends what it is given. What the /// old loop did with a table of sessions and a poll over all of them is /// now the shape of the code -- which is the whole argument for the /// module underneath it. fn serve(context: ?*anyopaque, session: *quic_io.Session) void { const s: *Server = @ptrCast(@alignCast(context.?)); // RFC 7250: who this is, which a raw-key server learns and a // certificate server does not. // RFC 9368: what the client said about versions, which is worth // showing because it is the half of the exchange this end checks. if (session.waitEstablished()) { if (session.peerVersionInformation()) |v| { std.debug.print("client versions chosen {x:0>8} available", .{v.chosen}); for (v.availableVersions()) |version| std.debug.print(" {x:0>8}", .{version}); std.debug.print("\n", .{}); } } if (s.raw_keys and session.waitEstablished()) { if (session.peerPublicKey()) |key| { std.debug.print("client key {x}\n", .{&key}); // A resumed handshake had no Certificate in it, so the key // above came out of the ticket; worth saying which it was. if (session.tls.server.inner.resumed) { std.debug.print("resumed session for {x}\n", .{&key}); } } } // n0's NAT traversal: this server's candidates, offered once the // client has said it takes part. What comes of them is the client's // doing -- a path it opens, which the report below counts. if (s.nat_addresses.len > 0 and session.waitEstablished() and session.natNegotiated()) { var offered: usize = 0; for (s.nat_addresses) |address| { session.addNatAddress(address) catch continue; offered += 1; } std.debug.print("NAT traversal: offered {d} addresses\n", .{offered}); } // RFC 9221: a datagram is not a stream and does not arrive through // `accept`, so it gets a task of its own rather than a place in a // loop that would make it wait behind a request. if (s.datagrams) { s.tasks.concurrent(s.io, echoDatagrams, .{session}) catch {}; } // Said once the connection is over, and only when there is something // to say: evidence that the peer greased and that this end read it. defer { const greased = session.greasedPackets(); if (greased > 0) std.debug.print("QUIC Bit clear on {d} packets\n", .{greased}); if (session.observedAddress()) |seen| std.debug.print("client sees this server at {f}\n", .{seen}); const opened = session.pathsOpened(); if (opened > 0) std.debug.print("client opened {d} more paths\n", .{opened}); if (s.nat_addresses.len > 0) std.debug.print("NAT traversal: {d} paths over the connection's life\n", .{opened}); } while (session.accept()) |stream| { s.answer(session, stream); if (s.limit) |limit| { if (s.answered.load(.monotonic) >= limit) { // Gone, not closed. Returning would have the endpoint // close this connection properly, which is what a // handler that has finished wants -- and not what this // option is for: the interoperability test's §10.3 case // is a server that dies mid-conversation and is replaced // by one that has never heard of the connection. The // answer has already been handed to the socket. std.process.exit(0); } } } } fn echoDatagrams(session: *quic_io.Session) void { var buffer: [1200]u8 = undefined; while (session.readDatagram(&buffer)) |payload| { std.debug.print("datagram: {s}\n", .{payload}); session.sendDatagram(payload) catch {}; } } fn answer(s: *Server, session: *quic_io.Session, stream: quic_io.Stream) void { var read_buffer: [1024]u8 = undefined; var reader = stream.reader(&read_buffer); var request: [1024]u8 = undefined; var collected: Io.Writer = .fixed(&request); // §4.2: "the client MUST indicate through the STREAM FIN mechanism // that no further data will be sent on that stream", so the end of // the query is the end of the stream and there is nothing to guess. _ = reader.interface.streamRemaining(&collected) catch {}; const message = collected.buffered(); // §2.1: a unidirectional stream carries no query, because there is no // half to answer on. Printing what arrived is all there is to do. if (stream.id.directionality() == .unidirectional) { if (message.len > 0) std.debug.print("unidirectional: {s}\n", .{message}); return; } // §4.2: a two-octet length in front of the DNS message, which is what // makes a stream carry a message rather than a byte count. if (message.len < 2) return; const length = std.mem.readInt(u16, message[0..2], .big); if (message.len < 2 + @as(usize, length)) return; var reply: [512]u8 = undefined; const wire = respond(&reply, message[2..][0..length], s.zone) catch return; var write_buffer: [1024]u8 = undefined; var writer = stream.writer(&write_buffer); var prefix: [2]u8 = undefined; std.mem.writeInt(u16, &prefix, @intCast(wire.len), .big); writer.interface.writeAll(&prefix) catch return; writer.interface.writeAll(wire) catch return; // "The server MUST send the response(s) on the same stream and MUST // indicate, after the last response, through the STREAM FIN mechanism // that no further data will be sent on that stream." writer.finish() catch return; _ = s.answered.fetchAdd(1, .monotonic); if (s.verbose) { std.debug.print("answered {d} octets on stream {d}\n", .{ wire.len, stream.id.value }); } _ = session; } }; pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var address_text: []const u8 = "127.0.0.1"; var port: u16 = 853; var cert_path: ?[]const u8 = null; var key_path: ?[]const u8 = null; var raw_key_path: ?[]const u8 = null; var peer_key_hex: ?[]const u8 = null; var zone: [max_names]Entry = undefined; var zone_len: usize = 0; var query_limit: ?usize = null; var verbose = false; var require_retry = false; var reset_key_hex: ?[]const u8 = null; var ticket_key_hex: ?[]const u8 = null; var early_data = false; var unidirectional = false; var datagrams = false; var nat_texts: [8][]const u8 = undefined; var nat_count: usize = 0; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--address")) { address_text = args.next() orelse fail("--address wants an address"); } else if (std.mem.eql(u8, arg, "--port")) { const text = args.next() orelse fail("--port wants a number"); port = std.fmt.parseInt(u16, text, 10) catch fail("--port wants a number"); } else if (std.mem.eql(u8, arg, "--cert")) { cert_path = args.next() orelse fail("--cert wants a path"); } else if (std.mem.eql(u8, arg, "--key")) { key_path = args.next() orelse fail("--key wants a path"); } else if (std.mem.eql(u8, arg, "--raw-key")) { raw_key_path = args.next() orelse fail("--raw-key wants a path"); } else if (std.mem.eql(u8, arg, "--peer-key")) { peer_key_hex = args.next() orelse fail("--peer-key wants 64 hex digits"); } else if (std.mem.eql(u8, arg, "--reset-key")) { reset_key_hex = args.next() orelse fail("--reset-key wants 64 hex digits"); } else if (std.mem.eql(u8, arg, "--ticket-key")) { ticket_key_hex = args.next() orelse fail("--ticket-key wants 64 hex digits"); } else if (std.mem.eql(u8, arg, "--datagram")) { datagrams = true; } else if (std.mem.eql(u8, arg, "--uni")) { unidirectional = true; } else if (std.mem.eql(u8, arg, "--early-data")) { early_data = true; } else if (std.mem.eql(u8, arg, "--retry")) { require_retry = true; } else if (std.mem.eql(u8, arg, "--nat-address")) { if (nat_count == nat_texts.len) fail("too many --nat-address"); nat_texts[nat_count] = args.next() orelse fail("--nat-address wants an address"); nat_count += 1; } else if (std.mem.eql(u8, arg, "--verbose")) { verbose = true; } else if (std.mem.eql(u8, arg, "--queries")) { const text = args.next() orelse fail("--queries wants a number"); query_limit = std.fmt.parseInt(usize, text, 10) catch fail("--queries wants a number"); } else if (std.mem.eql(u8, arg, "--answer")) { const text = args.next() orelse fail("--answer wants NAME=ADDRESS"); const split = std.mem.indexOfScalar(u8, text, '=') orelse fail("--answer wants NAME=ADDRESS"); if (zone_len == max_names) fail("too many names"); const address = net.IpAddress.parse(text[split + 1 ..], 0) catch fail("--answer wants an address after the ="); zone[zone_len] = .{ .name = text[0..split], .address = switch (address) { .ip4 => |v4| v4.bytes, .ip6 => fail("--answer wants an IPv4 address"), }, }; zone_len += 1; } else { std.debug.print("{s}", .{usage}); std.process.exit(2); } } var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); // §4.4 of RFC 9001 leaves authentication to TLS, and a server that cannot // authenticate itself cannot complete a QUIC handshake with anybody who // checks. There is no way to run this without a certificate or a key. var raw_public_key: ?quic.tls_handshake.RawPublicKey = null; var auth_storage: quic.tls_handshake.CertKeyPair = undefined; var auth: ?*quic.tls_handshake.CertKeyPair = null; if (raw_key_path) |path| { if (cert_path != null or key_path != null) fail("--raw-key replaces --cert and --key"); var raw: quic.tls_handshake.RawPublicKey = .{ .key_pair = quic.tls_handshake.rawKeyPairFromFile(gpa, io, Io.Dir.cwd(), path) catch fail("could not read an Ed25519 key from --raw-key"), }; if (peer_key_hex) |text| { var peer: quic.tls.PublicKey = undefined; if (text.len != 2 * peer.len) fail("--peer-key wants 64 hex digits"); _ = std.fmt.hexToBytes(&peer, text) catch fail("--peer-key wants hex digits"); raw.peer = peer; } raw_public_key = raw; std.debug.print("server key {x}\n", .{&raw.key_pair.public_key.toBytes()}); } else { if (peer_key_hex != null) fail("--peer-key is for --raw-key"); const certificate = cert_path orelse fail("--cert or --raw-key is required"); const key = key_path orelse fail("--key is required"); auth_storage = quic.tls_handshake.CertKeyPair.fromFilePath( gpa, io, Io.Dir.cwd(), certificate, key, ) catch fail("could not read the certificate or the key"); auth = &auth_storage; } defer if (auth) |a| a.deinit(gpa); // §5.1.1 and §10.3 both need values a peer cannot guess, so the seed // comes from the system rather than from a clock. var seed: [32]u8 = undefined; try Io.randomSecure(io, &seed); var rng_impl = std.Random.DefaultPrng.init(std.mem.readInt(u64, seed[0..8], .little)); const rng = rng_impl.random(); // §10.3.2: static on purpose. An endpoint that restarts must compute the // same tokens it did before, or the resets it sends mean nothing to the // peers it lost. var reset_key: quic.stateless_reset.Key = undefined; if (reset_key_hex) |text| { if (text.len != 2 * reset_key.len) fail("--reset-key wants 64 hex digits"); _ = std.fmt.hexToBytes(&reset_key, text) catch fail("--reset-key wants hex digits"); } else { try Io.randomSecure(io, &reset_key); } var ticket_key: ?quic.tls_handshake.TicketKey = null; if (ticket_key_hex) |text| { var sealing: quic.tls_handshake.TicketKey = undefined; if (text.len != 2 * sealing.len) fail("--ticket-key wants 64 hex digits"); _ = std.fmt.hexToBytes(&sealing, text) catch fail("--ticket-key wants hex digits"); ticket_key = sealing; } var token_key: quic.retry.Token.Key = undefined; try Io.randomSecure(io, &token_key); const local: quic.parameters.Parameters = .{ // RFC 9287: this server reads packets with the QUIC Bit clear. The // endpoint adds RFC 9368's Version Information itself. .grease_quic_bit = true, // draft-ietf-quic-address-discovery-01: tells a client that asks // where its datagrams come from, and asks the same in return. .address_discovery = .both, // draft-ietf-quic-multipath-21: room for a client to open one path // besides the one the handshake used. .initial_max_path_id = 1, // draft-ietf-quic-ack-frequency-14: takes ACK_FREQUENCY and // IMMEDIATE_ACK from a client that wants fewer acknowledgements. .min_ack_delay = 1000, .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, // §18.2 defaults both of these to zero, which is right for DNS over // QUIC: advertising capacity for something this server would never // read is an invitation to spend its buffers on nothing. .initial_max_streams_uni = if (unidirectional) 3 else 0, .initial_max_stream_data_uni = if (unidirectional) 2048 else 0, .max_idle_timeout = 30_000, // §18.2: "MUST be at least 2" — one to use and one to move to. .active_connection_id_limit = 4, // RFC 9221 §3: the parameter's presence is the whole of the // negotiation, so a zero here is a server that does not implement the // extension as far as any peer can tell. .max_datagram_frame_size = if (datagrams) 1200 else 0, // n0's NAT traversal, when there are candidates to offer: room for // as many of the client's as iroh asks for of the server's. .n0_nat_traversal = if (nat_count > 0) 32 else null, }; var nat_addresses: [nat_texts.len]net.IpAddress = undefined; for (nat_texts[0..nat_count], 0..) |text, i| { nat_addresses[i] = net.IpAddress.parse(text, port) catch fail("--nat-address wants an address"); } const bound = net.IpAddress.parse(address_text, port) catch fail("that is not an address"); var socket = try bound.bind(io, .{ .mode = .dgram }); defer socket.close(io); var server: Server = .{ .io = io, .zone = zone[0..zone_len], .verbose = verbose, .datagrams = datagrams, .raw_keys = raw_public_key != null, .limit = query_limit, .nat_addresses = nat_addresses[0..nat_count], }; var endpoint = try quic_io.Endpoint.init(io, gpa, &socket, .{ .auth = auth, .raw_public_key = raw_public_key, .alpn = &.{"doq"}, .local = local, // Two paths' worth of loss tables, for the one `initial_max_path_id` // allows past path 0. .sizes = .{ .paths = 2 }, .rng = rng, .reset_key = reset_key, .token_key = token_key, .ticket_key = ticket_key, .early_data = early_data, .require_retry = require_retry, .max_connections = max_connections, }, .{ .context = &server, .serveFn = Server.serve }); defer endpoint.deinit(); defer server.tasks.cancel(io); var stderr_buffer: [512]u8 = undefined; // Streaming, not positional: a positional writer starts at offset zero, // so with output redirected to a file it writes over whatever was // printed before it -- another writer's lines, or an earlier attempt's. var stderr: Io.File.Writer = .initStreaming(.stderr(), io, &stderr_buffer); try stderr.interface.print("listening on {f}\n", .{bound}); try stderr.interface.flush(); try endpoint.pump(); } fn respond(out: []u8, query: []const u8, zone: []const Entry) ![]u8 { if (query.len < 12) return error.Truncated; if (out.len < query.len + 16) return error.NoSpace; // The question is copied out of the query, which is also how the name is // read: a response repeats the question section verbatim. var at: usize = 12; const name_start = at; while (true) { if (at >= query.len) return error.Truncated; const length = query[at]; if (length & 0xc0 != 0) return error.Compressed; at += 1; if (length == 0) break; at += length; } const name_end = at; if (at + 4 > query.len) return error.Truncated; at += 4; const question = query[name_start..at]; const found = match(query[name_start..name_end], zone); @memcpy(out[0..2], query[0..2]); // the same identifier // A response, recursion desired echoed, recursion not available, and // NXDOMAIN when the name is not here. const flags: u16 = 0x8000 | (std.mem.readInt(u16, query[2..4], .big) & 0x0100) | @as(u16, if (found == null) 3 else 0); std.mem.writeInt(u16, out[2..4], flags, .big); std.mem.writeInt(u16, out[4..6], 1, .big); std.mem.writeInt(u16, out[6..8], @intFromBool(found != null), .big); std.mem.writeInt(u16, out[8..10], 0, .big); std.mem.writeInt(u16, out[10..12], 0, .big); var written: usize = 12; @memcpy(out[written..][0..question.len], question); written += question.len; if (found) |address| { const name_len = name_end - name_start; @memcpy(out[written..][0..name_len], query[name_start..name_end]); written += name_len; std.mem.writeInt(u16, out[written..][0..2], 1, .big); // A std.mem.writeInt(u16, out[written + 2 ..][0..2], 1, .big); // IN std.mem.writeInt(u32, out[written + 4 ..][0..4], 300, .big); // ttl std.mem.writeInt(u16, out[written + 8 ..][0..2], 4, .big); written += 10; @memcpy(out[written..][0..4], &address); written += 4; } return out[0..written]; } /// Whether a wire-format name is in the zone, which holds them as text. fn match(wire: []const u8, zone: []const Entry) ?[4]u8 { for (zone) |entry| { if (nameEquals(wire, entry.name)) return entry.address; } return null; } fn nameEquals(wire: []const u8, text: []const u8) bool { var at: usize = 0; var labels = std.mem.splitScalar(u8, text, '.'); while (labels.next()) |label| { if (label.len == 0) continue; if (at >= wire.len) return false; if (wire[at] != label.len) return false; at += 1; if (at + label.len > wire.len) return false; if (!std.ascii.eqlIgnoreCase(wire[at..][0..label.len], label)) return false; at += label.len; } return at < wire.len and wire[at] == 0; } test "a name in the zone is answered and one outside it is not" { const zone = [_]Entry{.{ .name = "example.com", .address = .{ 192, 0, 2, 1 } }}; var query: [64]u8 = undefined; @memset(query[0..12], 0); std.mem.writeInt(u16, query[0..2], 0xbeef, .big); std.mem.writeInt(u16, query[4..6], 1, .big); const name = "\x07example\x03com\x00\x00\x01\x00\x01"; @memcpy(query[12..][0..name.len], name); const wire = query[0 .. 12 + name.len]; var out: [256]u8 = undefined; const reply = try respond(&out, wire, &zone); try std.testing.expectEqual(@as(u16, 0xbeef), std.mem.readInt(u16, reply[0..2], .big)); // A response, rcode 0, one answer. try std.testing.expect(std.mem.readInt(u16, reply[2..4], .big) & 0x8000 != 0); try std.testing.expectEqual(@as(u16, 0), std.mem.readInt(u16, reply[2..4], .big) & 0x000f); try std.testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, reply[6..8], .big)); try std.testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, reply[reply.len - 4 ..]); // And a name that is not there comes back NXDOMAIN with no answers, which // is an answer rather than a failure. const empty = try respond(&out, wire, &.{}); try std.testing.expectEqual(@as(u16, 3), std.mem.readInt(u16, empty[2..4], .big) & 0x000f); try std.testing.expectEqual(@as(u16, 0), std.mem.readInt(u16, empty[6..8], .big)); } test "a wire name is compared to text case-insensitively and exactly" { try std.testing.expect(nameEquals("\x07example\x03com\x00", "example.com")); try std.testing.expect(nameEquals("\x07EXAMPLE\x03CoM\x00", "example.com")); try std.testing.expect(!nameEquals("\x07example\x03com\x00", "example.org")); // A prefix is not a match: `example.com` is not `sub.example.com`. try std.testing.expect(!nameEquals("\x03sub\x07example\x03com\x00", "example.com")); try std.testing.expect(!nameEquals("\x07example\x00", "example.com")); }