// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A DNS-over-QUIC client: RFC 9250, in about as few lines as it takes. //! //! This exists to be pointed at somebody else's server. Everything in the //! test suite is this library talking to itself, which proves that it agrees //! with itself and nothing more — and the parts of QUIC most likely to be //! subtly wrong are exactly the parts two implementations have to agree on. //! So this is the program the interoperability test runs, and the first thing //! in the project to meet a real socket, a real certificate chain and a real //! path MTU. //! //! ## Why DNS over QUIC is the right demonstration //! //! Because RFC 9250 is almost nothing on top of QUIC: a connection, an ALPN //! of `doq`, and on each client-initiated bidirectional stream a two-octet //! length followed by a DNS message, with the stream ended in each direction //! when the message is complete. There is no application protocol to get //! wrong, so what is being tested is the transport. //! //! §4.2 of RFC 9250 also settles a question this library would otherwise have //! had to invent an answer to: "the client MUST send the DNS query over the //! selected stream and MUST indicate through the STREAM FIN mechanism that no //! further data will be sent on that stream", and the server does the same //! with its response. One query, one stream, both halves closed. //! //! ## What it is not //! //! Not a DNS library. The query builder and answer reader here understand //! exactly enough to ask for an A record and print what comes back, and they //! live in this file rather than in a dependency on purpose: zig-dns-client is //! the project that will use *this* for DNS over QUIC, and a demonstration //! that depended on it would be a circle. const std = @import("std"); const Io = std.Io; const net = Io.net; const quic = @import("root.zig"); const usage = \\Usage: doq [options] NAME \\ \\Asks a DNS-over-QUIC server (RFC 9250) for the A records of NAME. \\ \\ --server HOST The server's address (default 127.0.0.1) \\ --host NAME The name to expect in the server's certificate, if it \\ differs from the address it is reached at \\ --port N The server's port (default 853, RFC 9250 §5.1) \\ --ca FILE A PEM file of certificates to trust \\ --insecure Do not verify the server's certificate at all. For \\ testing against a server whose certificate is not \\ signed by anything, and for nothing else. \\ --peer-key HEX Dial the server by its Ed25519 public key, 64 hex \\ digits, instead of checking a certificate (RFC 7250). \\ Sends no server name unless --host gives one. \\ --raw-key FILE This client's own Ed25519 private key, as PEM, for \\ --peer-key. Without it a new key is made for the one \\ run, which is enough to be let in by a server that \\ admits any key. \\ --name NAME The name to ask about, if not given positionally \\ --resume Ask twice on two connections, the second offering the \\ session ticket the first was given (RFC 8446 §4.6.1). \\ Reports whether the server took it. \\ --rotate Between queries, stop using the server's connection ID \\ and move to one it issued later (§5.1.2). Proves that \\ the pool of identifiers is real: the rest of the \\ queries are addressed to a name that only arrived \\ after the handshake. \\ --second-path Open a second path from a second socket once the \\ handshake is done (draft-ietf-quic-multipath-21), and \\ ask over it. Needs a server that allows one. \\ --nat-address A \\ Take part in n0's NAT traversal, offering A at this \\ client's port as a candidate. Once the handshake is \\ done, wait for the server's candidates, punch at \\ them, and ask over the path that opens. May be \\ repeated. \\ --ack-frequency N \\ Once the handshake is done, ask the server to \\ acknowledge only once more than N packets have \\ arrived (draft-ietf-quic-ack-frequency-14). Needs a \\ server that sent min_ack_delay. \\ --repeat N Ask N times on the same connection (default 1), which \\ is what exercises §4.6's stream limits: every query \\ gets its own stream and the peer has to keep granting \\ more of them \\ ; fn fail(comptime message: []const u8) noreturn { std.debug.print("doq: " ++ message ++ "\n", .{}); std.process.exit(1); } pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var server_text: []const u8 = "127.0.0.1"; var port: u16 = 853; var host: ?[]const u8 = null; var ca_path: ?[]const u8 = null; var insecure = false; var name: ?[]const u8 = null; var repeat: usize = 1; var rotate = false; var resume_session = false; var early_data = false; var unidirectional: ?[]const u8 = null; var datagram_text: ?[]const u8 = null; var peer_key_hex: ?[]const u8 = null; var raw_key_path: ?[]const u8 = null; var second_path = false; var ack_threshold: ?u64 = null; var nat_texts: [4][]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, "--server")) { server_text = args.next() orelse fail("--server 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, "--host")) { host = args.next() orelse fail("--host wants a name"); } else if (std.mem.eql(u8, arg, "--ca")) { ca_path = args.next() orelse fail("--ca 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, "--raw-key")) { raw_key_path = args.next() orelse fail("--raw-key wants a path"); } 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, "--ack-frequency")) { const text = args.next() orelse fail("--ack-frequency wants a number"); ack_threshold = std.fmt.parseInt(u64, text, 10) catch fail("--ack-frequency wants a number"); } else if (std.mem.eql(u8, arg, "--second-path")) { second_path = true; } else if (std.mem.eql(u8, arg, "--insecure")) { insecure = true; } else if (std.mem.eql(u8, arg, "--resume")) { resume_session = true; } else if (std.mem.eql(u8, arg, "--datagram")) { datagram_text = args.next() orelse fail("--datagram wants some text"); } else if (std.mem.eql(u8, arg, "--uni")) { unidirectional = args.next() orelse fail("--uni wants some text"); } else if (std.mem.eql(u8, arg, "--0rtt")) { // 0-RTT is resumption spent: there is nothing to send early on a // connection that has never spoken to this server before. resume_session = true; early_data = true; } else if (std.mem.eql(u8, arg, "--rotate")) { rotate = true; } else if (std.mem.eql(u8, arg, "--repeat")) { const text = args.next() orelse fail("--repeat wants a number"); repeat = std.fmt.parseInt(usize, text, 10) catch fail("--repeat wants a number"); } else if (std.mem.eql(u8, arg, "--name")) { name = args.next() orelse fail("--name wants a name"); } else if (std.mem.startsWith(u8, arg, "-")) { std.debug.print("{s}", .{usage}); std.process.exit(2); } else { name = arg; } } const question = name orelse fail("no name to ask about"); var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); const server = net.IpAddress.parse(server_text, port) catch fail("that is not an address"); // Whatever family the server is, bound to a port the kernel picks. const any: net.IpAddress = switch (server) { .ip4 => net.IpAddress.parse("0.0.0.0", 0) catch unreachable, .ip6 => net.IpAddress.parse("::", 0) catch unreachable, }; // One socket for the path the handshake uses, and with --second-path a // second: another 4-tuple, which is what a second path is. var sockets: [2]net.Socket = undefined; sockets[0] = try any.bind(io, .{ .mode = .dgram }); var socket_count: usize = 1; if (second_path) { sockets[1] = try any.bind(io, .{ .mode = .dgram }); socket_count = 2; } defer for (sockets[0..socket_count]) |*s| s.close(io); var routes: Routes = .init(sockets[0..socket_count], server); var trust: std.crypto.Certificate.Bundle = .{ .bytes = .empty, .map = .empty }; defer trust.deinit(gpa); if (ca_path) |path| { // Absolute or relative, so that a test can say `./ca.pem`. if (std.fs.path.isAbsolute(path)) { try trust.addCertsFromFilePathAbsolute(gpa, io, Io.Timestamp.now(io, .real), path); } else { try trust.addCertsFromFilePath(gpa, io, Io.Timestamp.now(io, .real), Io.Dir.cwd(), path); } } // §5.2 of RFC 9001 and §7.3 of RFC 9000 both rest on these being // unpredictable, so the entropy comes from outside the process rather // than from a timestamp. var seed: [32]u8 = undefined; try Io.randomSecure(io, &seed); var csprng: std.Random.DefaultCsprng = .init(seed); const rng = csprng.random(); // RFC 7250: the server named by its key rather than by a certificate, // and this client by a key of its own, since the server asks for one. var raw_public_key: ?quic.tls_handshake.RawPublicKey = null; 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"); const own = if (raw_key_path) |path| quic.tls_handshake.rawKeyPairFromFile(gpa, io, Io.Dir.cwd(), path) catch fail("could not read an Ed25519 key from --raw-key") else std.crypto.sign.Ed25519.KeyPair.generate(io); raw_public_key = .{ .key_pair = own, .peer = peer }; } else if (raw_key_path != null) fail("--raw-key is for --peer-key"); // §5.2 of RFC 9001: the client invents a Destination Connection ID for its // first Initial, and both ends derive the Initial keys from it. It has to // be unpredictable — anyone who can guess it can read the handshake. var destination: [8]u8 = undefined; rng.bytes(&destination); var local_id: [4]u8 = undefined; rng.bytes(&local_id); // What this endpoint will accept. §4.6 of RFC 9000: without a stream // limit the peer can open nothing, and without data limits it can send // nothing — so a client that forgets these gets a connection on which no // answer can arrive. const local: quic.parameters.Parameters = .{ // RFC 9287: this client reads packets with the QUIC Bit clear, and // RFC 9368: it speaks version 1 and nothing else. .grease_quic_bit = true, .version_information = .v1, // draft-ietf-quic-address-discovery-01: asks the server where this // client's datagrams come from, and tells it the same. .address_discovery = .both, // draft-ietf-quic-multipath-21: room for one path past path 0, which // --second-path opens. .initial_max_path_id = 1, // draft-ietf-quic-ack-frequency-14: takes ACK_FREQUENCY and // IMMEDIATE_ACK, and delays an ACK no less than a millisecond -- // noq's value, its timer granularity. .min_ack_delay = 1000, // n0's NAT traversal, with candidates to offer: room for as many of // the server's as iroh offers. .n0_nat_traversal = if (nat_count > 0) 32 else null, .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 4096, .initial_max_stream_data_bidi_remote = 4096, .initial_max_streams_bidi = 4, // §18.2 defaults these to zero. A client that opens a unidirectional // stream still needs the peer's permission for it, which comes from // the *peer's* parameters — these two are what this end would let the // peer open, and it has no reason to expect one. .max_idle_timeout = 10_000, // RFC 9221 §3: what this client will accept, which is what lets the // echo come back. .max_datagram_frame_size = if (datagram_text != null) 1200 else 0, // §18.2: "MUST be at least 2", and §5.1.1 needs a spare for anything // in §9 to be possible at all. .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var parameter_bytes: [128]u8 = undefined; const encoded = try quic.parameters.write(&local, ¶meter_bytes, .client); // §4.6.1: a ticket outlives the connection that issued it, which is the // entire point, so it lives out here rather than in the handshake. var session: quic.tls_handshake.Session = .{}; const attempts: usize = if (resume_session) 2 else 1; var attempt: usize = 0; while (attempt < attempts) : (attempt += 1) { var tls_client: quic.tls_handshake.Client = try .init(.{ // The name the certificate has to match, which is not always the // address the server was reached at: a server on 127.0.0.1 presents a // certificate for whatever it is called. // // Dialing a key, there is no name to match and none is sent // unless asked for: the key says who the server is, and a name in // the clear would only tell an observer. .host = host orelse if (raw_public_key != null) "" else server_text, .root_ca = trust, .alpn_protocols = &.{"doq"}, .transport_parameters = encoded, .rng = rng, .now_sec = Io.Timestamp.now(io, .real).toSeconds(), .insecure_skip_verify = insecure, .session = if (resume_session) &session else null, .early_data = early_data, .raw_public_key = raw_public_key, }); // §4.6 of RFC 9001: whether this attempt will actually carry early // data, which needs a ticket that permitted it as well as a caller // that asked. const sending_early = early_data and session.valid and session.early_data; // §7.4.1 of RFC 9000: "a client that attempts to send 0-RTT data MUST // remember the transport parameters used by the server". It is // sending before the server has spoken, so the limits it spends // against are the ones the server set last time. var remembered_ids: quic.parameters.IdStorage = .{}; const remembered: ?quic.parameters.Parameters = if (sending_early) quic.parameters.parse(session.peerTransportParameters(), &remembered_ids, .server) catch fail("the remembered transport parameters do not parse") else null; // On the heap: a connection holds every buffer it will ever need, which is // more than a stack frame should carry. const connection = try gpa.create(quic.Connection); const memory = try gpa.create(quic.Connection.Storage(.{ .paths = 2 })); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = local, .rng = rng, .remembered = remembered, }); // The one path this client uses, and the address it reports on it // when the server asks. routes = .init(sockets[0..socket_count], server); try connection.setPeerAddress(0, frameAddress(server)); // §10.1 and the whole of RFC 9002 measure durations, never dates, so the // clock has to be one that does not jump. `.monotonic` is that clock, and // the connection is handed nanoseconds from an origin it never sees. const origin = Io.Timestamp.now(io, .awake); var clock: Clock = .{ .io = io, .origin = origin }; var stdout_buffer: [4096]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 stdout: Io.File.Writer = .initStreaming(.stdout(), io, &stdout_buffer); const out = &stdout.interface; // Handshake first, then the query -- unless there is a 0-RTT key, in // which case the query goes into the same flight as the ClientHello // and the handshake happens around it. That is the entire difference, // and it is worth how small it looks: the stream is written the same // way either way, and what changes is only when. if (!sending_early) { try pump(io, &routes, connection, &clock, clock.in(10 * std.time.ns_per_s), .established); if (!connection.isEstablished()) fail("the handshake did not finish"); const protocol = tls_client.alpnProtocol() orelse fail("the server agreed no protocol"); if (!std.mem.eql(u8, protocol, "doq")) fail("the server agreed a protocol that is not doq"); // RFC 9368: what the server said about versions, shown because it // is the half of the exchange this end checks. if (connection.peer) |peer| if (peer.version_information) |v| { try out.print("server versions chosen {x:0>8} available", .{v.chosen}); for (v.availableVersions()) |version| try out.print(" {x:0>8}", .{version}); try out.print("\n", .{}); }; // Always the key that was dialed, or the handshake would have // failed; printed so that a test can see the check was made. if (connection.peerPublicKey()) |key| { try out.print("server key {x}\n", .{&key}); try out.flush(); } // draft-ietf-quic-multipath-21 §3.1: the second path, from the // second socket. It needs the server's identifier for path 1, // which arrives just after the handshake, so a few quiet turns // may pass before it can be opened; then it is validated, and // everything after goes over it. if (second_path) { var tries: usize = 0; const id = while (tries < 20) : (tries += 1) { if (connection.openPath(1, clock.read())) |id| break id else |_| {} try pump(io, &routes, connection, &clock, clock.in(100 * std.time.ns_per_ms), .{ .quiet = {} }); } else fail("the server offered no second path"); try pump(io, &routes, connection, &clock, clock.in(5 * std.time.ns_per_s), .{ .path_validated = 1 }); connection.useSendPath(id) catch fail("the second path was not validated"); try out.print("path {d} open over a second socket\n", .{id}); try out.flush(); } // n0's NAT traversal: this client's candidates, offered in the // round it starts once the server's have arrived -- just after // the handshake. A path through a hole is opened when a probe is // answered; the questions then go over it. if (nat_count > 0) { if (!connection.natNegotiated()) fail("the server does not take part in n0's NAT traversal"); const own_port = switch (sockets[0].address) { .ip4 => |a| a.port, .ip6 => |a| a.port, }; for (nat_texts[0..nat_count]) |text| { const address = net.IpAddress.parse(text, own_port) catch fail("--nat-address wants an address"); connection.addNatAddress(frameAddress(address)) catch fail("the server will take no more candidates"); } try pump(io, &routes, connection, &clock, clock.in(2 * std.time.ns_per_s), .nat_candidates); try out.print("server offered {d} NAT traversal candidates\n", .{connection.natRemoteCount()}); try out.flush(); connection.startNatRound(clock.read()) catch fail("no NAT traversal round could start"); try pump(io, &routes, connection, &clock, clock.in(10 * std.time.ns_per_s), .nat_path); if (natPath(connection)) |extra| { const seen = routes.peers[extra.route].?; try out.print("NAT traversal: path {d} open to {f}\n", .{ extra.id, seen }); try out.flush(); connection.useSendPath(extra.id) catch {}; } else { try out.print("NAT traversal: no path opened\n", .{}); try out.flush(); } } // draft-ietf-quic-ack-frequency-14 §4: fewer ACKs from the // server, with the delay left at its own max_ack_delay and // reordering acknowledged as RFC 9000 has it. if (ack_threshold) |threshold| { const delay = if (connection.peer) |p| p.max_ack_delay * std.time.ns_per_ms else 25 * std.time.ns_per_ms; connection.requestAckFrequency(threshold, delay, 1) catch |err| switch (err) { error.NotSupported => fail("the server does not take ACK_FREQUENCY"), error.InvalidDelay => fail("the server's min_ack_delay is above its max_ack_delay"), }; try out.print("asked for an ACK every {d} packets\n", .{threshold + 1}); try out.flush(); } } // RFC 9221: sent before the question, and waited for afterwards. // §5.2 makes no promise that it arrives at all, which is why the wait // has a deadline and its absence is reported rather than fatal. if (datagram_text) |text| { connection.sendDatagram(text) catch |err| { std.debug.print("doq: no datagram to send: {t}\n", .{err}); std.process.exit(1); }; } // §2.1: a channel rather than a conversation, opened before the // question so that the peer has to have been right about both the // identifier space and the limit before the query can succeed. if (unidirectional) |text| { try sendChannel(connection, text); try pump( io, &routes, connection, &clock, clock.in(std.time.ns_per_s), .{ .quiet = {} }, ); } // §4.2 of RFC 9250: one query per stream, and a new stream each time — // "the client MUST select an available client-initiated bidirectional // stream". A connection asked to repeat is what exercises §4.6's stream // limits, since the peer has to keep granting more of them. for (0..repeat) |asked| { var stream = try ask(connection, question, rng); // Only the first question can have gone out as 0-RTT. const early = sending_early and asked == 0; try pump( io, &routes, connection, &clock, clock.in(10 * std.time.ns_per_s), if (early) .{ .reply_or_refusal = stream } else .{ .reply_on = stream }, ); // §4.6.2 of RFC 9001: a server that refused the early data // refused everything sent with it, and the connection has reset // every stream that carried it -- the "application state bound to // those streams" is this client's to reset, which here means // asking again under the 1-RTT keys. if (early and connection.earlyDataRejected()) { try out.print("0-RTT refused, asking again\n", .{}); try out.flush(); if (unidirectional) |text| try sendChannel(connection, text); stream = try ask(connection, question, rng); try pump( io, &routes, connection, &clock, clock.in(10 * std.time.ns_per_s), .{ .reply_on = stream }, ); } // §10.3: a connection the peer has forgotten ends here rather than // waiting out an idle timeout. Worth saying plainly, because "no // answer" and "the server has no idea who we are" are different // problems with different fixes. if (connection.closeState()) |state| { std.debug.print("doq: connection ended ({t}): {s}", .{ state, connection.closing.reason(), }); // §4.8 of RFC 9001: a TLS alert travels as CRYPTO_ERROR, and // it can arrive after this end thought the handshake was // done -- a server refusing the client's key does it just // there -- so it is worth naming here as well as in a failed // handshake. if (connection.closing.code.alert()) |alert| { std.debug.print(", TLS alert {d}", .{alert}); } std.debug.print("\n", .{}); std.process.exit(1); } const answer = connection.readable(stream); if (answer.len < 2) fail("the server sent no answer"); const length = std.mem.readInt(u16, answer[0..2], .big); if (answer.len < 2 + @as(usize, length)) fail("the server's answer was truncated"); try printAnswer(out, answer[2..][0..length]); try out.flush(); // Reading it is what closes this endpoint's half of the stream, which // is what gives the slot back and lets the next query have one. connection.consume(stream, answer.len); // §5.1.2: a different name for the same connection. Everything after // this is addressed to an identifier the peer issued after the // handshake, which is the only way to find out whether its pool is // real. if (rotate and !connection.rotatePeerId()) { std.debug.print("doq: the server issued nothing to rotate to\n", .{}); std.process.exit(1); } // And one more turn of the loop, so the acknowledgement goes out and // the peer learns it may open more. try pump( io, &routes, connection, &clock, clock.in(std.time.ns_per_s), .{ .quiet = {} }, ); } // RFC 9221 §5.2: unreliable, so its absence is reported rather than // treated as a failure -- what would be a failure is the connection // ending over it, which the check below would have already caught. if (datagram_text != null) { try pump( io, &routes, connection, &clock, clock.in(2 * std.time.ns_per_s), .{ .datagram = {} }, ); if (connection.readDatagram()) |echo| { try out.print("datagram echoed: {s}\n", .{echo}); connection.takeDatagram(); } else { try out.print("datagram not echoed\n", .{}); } try out.flush(); } if (early_data and attempt == 1) { // §4.6.2: a refusal is not a failure. The question was asked // again once the streams were reset, so the answer above is the // same answer either way -- which is the property worth printing, // because it is the one an application depends on. try out.print("{s}\n", .{ if (connection.earlyDataAccepted()) "0-RTT accepted" else "0-RTT refused", }); try out.flush(); } if (resume_session) { try out.print("{s}\n", .{ if (tls_client.inner.resumed) "resumed" else "full handshake", }); try out.flush(); // §4.6.1: the ticket arrives *after* the handshake, in a // post-handshake message. One more turn of the loop collects it. try pump( io, &routes, connection, &clock, clock.in(std.time.ns_per_s), .{ .quiet = {} }, ); } // RFC 9287: evidence that the server greased and that this end read // what it sent, said only when there is some. if (connection.greasedPackets() > 0) { try out.print("QUIC Bit clear on {d} packets\n", .{connection.greasedPackets()}); try out.flush(); } if (second_path or nat_count > 0) { try out.print("sent {d} packets on path 1\n", .{connection.extra[0].space.next_number}); try out.flush(); } // draft-ietf-quic-address-discovery-01: the server's report of where // this client's datagrams come from -- the address a NAT gave it, if // there is one in the way. if (connection.observedAddress()) |seen| { try out.print("server sees this client at {f}\n", .{ipAddress(seen)}); try out.flush(); } // §10.2: saying goodbye rather than vanishing, so the server can free the // connection instead of waiting out its idle timeout. connection.close(.no_error, "done", clock.read()); var buffer: [2048]u8 = undefined; if (try connection.send(&buffer, clock.read())) |datagram| { sockets[0].send(io, &server, datagram.bytes) catch {}; } gpa.destroy(connection); gpa.destroy(memory); } } fn frameAddress(a: net.IpAddress) quic.frame.Address { return switch (a) { .ip4 => |v4| .{ .ip = .{ .v4 = v4.bytes }, .port = v4.port }, .ip6 => |v6| .{ .ip = .{ .v6 = v6.bytes }, .port = v6.port }, }; } fn ipAddress(a: quic.frame.Address) net.IpAddress { return switch (a.ip) { .v4 => |bytes| .{ .ip4 = .{ .bytes = bytes, .port = a.port } }, .v6 => |bytes| .{ .ip6 = .{ .bytes = bytes, .port = a.port } }, }; } /// Nanoseconds since this program started, which is the only shape of time /// this library accepts. const Clock = struct { io: Io, origin: Io.Timestamp, fn read(c: *const Clock) u64 { const d = c.origin.durationTo(Io.Timestamp.now(c.io, .awake)); return @intCast(@max(d.nanoseconds, 0)); } fn in(c: *const Clock, nanoseconds: u64) u64 { return c.read() + nanoseconds; } }; /// What a call to `pump` is waiting for. /// /// A connection always has *something* to wait for — the idle timer, if /// nothing else — so "run until there is nothing left to do" would run until /// the connection timed out. The caller knows what it wanted; the library /// does not. const Goal = union(enum) { established, /// Everything the peer will send on this stream has arrived. reply_on: quic.stream.Id, /// The same, for a stream opened in 0-RTT: or the server has refused /// the early data, which takes the stream with it (§4.6.2 of RFC 9001). reply_or_refusal: quic.stream.Id, /// Nothing more to say — one pass to flush whatever is pending. quiet, /// Until an unreliable datagram has arrived (RFC 9221). /// /// A goal of its own rather than `.quiet`, because "nothing left to send" /// is met the instant this endpoint's own queue empties -- which is /// before anything can have come back. Waiting for what was asked for is /// the only thing that waits for the round trip. datagram, /// Until the caller's path `route` has been validated (§8.2). path_validated: quic.path.Id, /// n0's NAT traversal: until the server has offered a candidate, and /// until a path through a hole is open and validated. nat_candidates, nat_path, fn met(goal: Goal, connection: *quic.Connection) bool { return switch (goal) { .nat_candidates => connection.natRemoteCount() > 0, .nat_path => natPath(connection) != null, .path_validated => |route| if (connection.paths.find(route)) |seen| seen.validated else false, .established => connection.isEstablished(), .reply_on => |id| connection.streamReceived(id), .reply_or_refusal => |id| connection.streamReceived(id) or connection.earlyDataRejected(), .quiet => !connection.hasDataToSend(), .datagram => connection.readDatagram() != null, }; } }; /// Moves datagrams until `goal` is met, the connection ends, or the deadline /// passes. /// /// This is the whole of what a caller of this library has to write, and the /// shape of it is not accidental: send everything that is ready, wait for /// either a datagram or the connection's own timer, and repeat. The library /// decides what goes in a packet and when a timer fires; this decides nothing /// except when it has what it came for. /// A path opened past path 0 whose 4-tuple has been validated, if any. fn natPath(connection: *quic.Connection) ?*const @TypeOf(connection.extra[0]) { for (&connection.extra) |*extra| { if (extra.state != .open) continue; const seen = connection.paths.find(extra.route) orelse continue; if (seen.validated) return extra; } return null; } /// The caller's side of the connection's path numbers: for each, the socket /// it leaves from and the peer address it goes to -- what the library, which /// has no sockets, calls a path. /// /// Route 0 is the handshake's, and with --second-path route 1 is the second /// socket's. Anything else is an address the server was heard from that is /// not the one dialed -- which is what n0's NAT traversal is for, since an /// answer to a probe comes back from the candidate it went to. const Routes = struct { sockets: []net.Socket, peers: [quic.path.capacity]?net.IpAddress = @splat(null), socket_of: [quic.path.capacity]usize = @splat(0), fn init(sockets: []net.Socket, server: net.IpAddress) Routes { var r: Routes = .{ .sockets = sockets }; r.peers[0] = server; if (sockets.len > 1) { r.peers[1] = server; r.socket_of[1] = 1; } return r; } /// The route for a datagram from `from` on socket `socket`, numbering it /// if it is new -- and when the table is full, giving it the number of /// one the connection has finished with. fn routeFor(r: *Routes, connection: *quic.Connection, socket: usize, from: net.IpAddress) ?quic.path.Id { for (r.peers, 0..) |maybe, i| { const seen = maybe orelse continue; if (r.socket_of[i] == socket and seen.eql(&from)) return @intCast(i); } for (&r.peers, 0..) |*slot, i| { if (slot.* != null) continue; slot.* = from; r.socket_of[i] = socket; return @intCast(i); } for (r.peers[1..], 1..) |*slot, i| { const route: quic.path.Id = @intCast(i); if (connection.routeInUse(route)) continue; connection.forgetRoute(route); slot.* = from; r.socket_of[i] = socket; return route; } return null; } }; fn pump( io: Io, routes: *Routes, connection: *quic.Connection, clock: *const Clock, deadline: u64, goal: Goal, ) !void { var buffer: [2048]u8 = undefined; var incoming: [2048]u8 = undefined; while (clock.read() < deadline) { // Everything that is ready, before waiting for anything. This runs // once more after the goal is met, so that the acknowledgement for // whatever met it goes out rather than being left for the peer to // retransmit into. while (try connection.send(&buffer, clock.read())) |datagram| { // Which socket is the route's; where to is the route's peer, or // for a NAT traversal probe the candidate it is aimed at. const socket = &routes.sockets[routes.socket_of[datagram.path]]; const to = if (datagram.to) |address| ipAddress(address) else routes.peers[datagram.path] orelse continue; socket.send(io, &to, datagram.bytes) catch |err| switch (err) { // A probe to a candidate this host cannot reach is a probe // that went nowhere, which is what most of them do. error.NetworkUnreachable, error.HostUnreachable, error.AddressFamilyUnsupported => if (datagram.to == null) return err, else => return err, }; } if (connection.closeState()) |_| return; if (goal.met(connection)) return; const now = clock.read(); const next = connection.timeout() orelse return; const wait = if (next > now) next - now else 0; const until = @min(wait, deadline -| now); if (until == 0) { connection.onTimeout(clock.read()); continue; } // With two sockets each gets a slice of the wait in turn. The timer // then fires only when it is actually due: `onTimeout` does not ask // whether it is, and a probe timeout fired early retransmits a flight // that is still in flight. const slice = if (routes.sockets.len == 1) until else @min(until, 10 * std.time.ns_per_ms); var socket: usize = 0; const message = while (socket < routes.sockets.len) : (socket += 1) { break routes.sockets[socket].receiveTimeout(io, &incoming, .{ .duration = .{ .raw = .{ .nanoseconds = @intCast(slice) }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => continue, else => return err, }; } else { if (clock.read() >= next) connection.onTimeout(clock.read()); continue; }; const route = routes.routeFor(connection, socket, message.from) orelse continue; // Where it came from, which the connection needs for address // discovery's reports and NAT traversal's answers alike. connection.setPeerAddress(route, frameAddress(message.from)) catch {}; connection.receive(message.data, route, clock.read()) catch |err| { // A connection error has already put the connection into the // closing state; sending it is what the next loop does. The TLS // alert is worth printing beside it: "the handshake failed" is // not a diagnosis, and the alert is the peer's own word for what // it objected to. if (connection.handshake.alert()) |a| { std.debug.print("doq: {t}, TLS alert {d}\n", .{ err, a }); } else { std.debug.print("doq: {t}\n", .{err}); } }; } } // -- just enough DNS -------------------------------------------------------- /// A query for the A records of `name`. /// §4.2 of RFC 9250: one query on a stream of its own, length first, and the /// stream finished behind it. fn ask(connection: *quic.Connection, question: []const u8, rng: std.Random) !quic.stream.Id { var query_buf: [512]u8 = undefined; const query = try encodeQuery(&query_buf, question, rng.int(u16)); const stream = connection.openBidirectional() catch |err| { std.debug.print("doq: no stream to ask on: {t}\n", .{err}); std.process.exit(1); }; var prefix: [2]u8 = undefined; std.mem.writeInt(u16, &prefix, @intCast(query.len), .big); try connection.write(stream, &prefix); try connection.write(stream, query); // "The client MUST indicate through the STREAM FIN mechanism that no // further data will be sent on that stream." try connection.finishStream(stream); return stream; } /// `--uni`'s text, on a unidirectional stream of its own. fn sendChannel(connection: *quic.Connection, text: []const u8) !void { const uni = connection.openUnidirectional() catch |err| { std.debug.print("doq: no unidirectional stream to open: {t}\n", .{err}); std.process.exit(1); }; try connection.write(uni, text); try connection.finishStream(uni); } fn encodeQuery(out: []u8, name: []const u8, id: u16) ![]u8 { var at: usize = 0; if (out.len < 12) return error.NoSpace; std.mem.writeInt(u16, out[0..2], id, .big); // Recursion desired, and nothing else. std.mem.writeInt(u16, out[2..4], 0x0100, .big); std.mem.writeInt(u16, out[4..6], 1, .big); // one question std.mem.writeInt(u16, out[6..8], 0, .big); std.mem.writeInt(u16, out[8..10], 0, .big); std.mem.writeInt(u16, out[10..12], 0, .big); at = 12; var labels = std.mem.splitScalar(u8, name, '.'); while (labels.next()) |label| { if (label.len == 0) continue; if (label.len > 63) return error.NameTooLong; if (at + 1 + label.len > out.len) return error.NoSpace; out[at] = @intCast(label.len); @memcpy(out[at + 1 ..][0..label.len], label); at += 1 + label.len; } if (at + 5 > out.len) return error.NoSpace; out[at] = 0; // the root label at += 1; std.mem.writeInt(u16, out[at..][0..2], 1, .big); // A std.mem.writeInt(u16, out[at + 2 ..][0..2], 1, .big); // IN at += 4; return out[0..at]; } /// Prints the answer records of a response, and nothing else. fn printAnswer(out: *Io.Writer, message: []const u8) !void { if (message.len < 12) return error.Truncated; const flags = std.mem.readInt(u16, message[2..4], .big); const rcode = flags & 0x000f; const questions = std.mem.readInt(u16, message[4..6], .big); const answers = std.mem.readInt(u16, message[6..8], .big); try out.print("rcode {d}, {d} answer(s)\n", .{ rcode, answers }); var at: usize = 12; for (0..questions) |_| { at = try skipName(message, at); at += 4; } for (0..answers) |_| { at = try skipName(message, at); if (at + 10 > message.len) return error.Truncated; const kind = std.mem.readInt(u16, message[at..][0..2], .big); const ttl = std.mem.readInt(u32, message[at + 4 ..][0..4], .big); const length = std.mem.readInt(u16, message[at + 8 ..][0..2], .big); at += 10; if (at + length > message.len) return error.Truncated; if (kind == 1 and length == 4) { const a = message[at..][0..4]; try out.print("A {d}.{d}.{d}.{d} ttl {d}\n", .{ a[0], a[1], a[2], a[3], ttl }); } else { try out.print("type {d}, {d} octets, ttl {d}\n", .{ kind, length, ttl }); } at += length; } } /// Steps over a name, following the one indirection a compression pointer /// implies without following it. fn skipName(message: []const u8, start: usize) !usize { var at = start; while (true) { if (at >= message.len) return error.Truncated; const length = message[at]; // RFC 1035 §4.1.4: the two high bits mark a pointer, which is always // the last thing in a name. if (length & 0xc0 == 0xc0) return at + 2; at += 1; if (length == 0) return at; at += length; } } test { var buffer: [512]u8 = undefined; const query = try encodeQuery(&buffer, "example.com", 0x1234); // Twelve octets of header, then 7+1 and 3+1 for the labels, the root // label, and four for the type and class. try std.testing.expectEqual(@as(usize, 12 + 8 + 4 + 1 + 4), query.len); try std.testing.expectEqualSlices(u8, "\x07example\x03com\x00", query[12..][0..13]); try std.testing.expectEqual(@as(u16, 0x1234), std.mem.readInt(u16, query[0..2], .big)); }