// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The end that dials: one QUIC connection to one server. //! //! `Endpoint` is the other half of this file and answers strangers -- it //! binds a port, derives Initial keys from a connection ID somebody else //! chose, and obeys the amplification limit before it knows who it is talking //! to. A client has none of those problems and one the server does not: it //! picks the identifiers, it offers the transport parameters, and it has to //! decide when to give up on a server that is not there. //! //! What it produces is the same `Session` the server serves, which is the //! point. A stream is a stream whoever opened the connection, so everything //! written against a session -- HTTP/3's driver included -- works from either //! end without knowing which it is. //! //! ## Something has to be reading the socket //! //! `connect` pumps the handshake itself, because until it finishes there is //! nothing else for the caller to be doing. Afterwards `run` wants a task of //! its own, and the reason is not the timers: `Stream.Reader` *blocks* on the //! session's condition until a datagram arrives, so a caller that reads a //! stream on the same task that pumps the socket is waiting for something //! only it could deliver. That is a deadlock and it is silent. //! //! `once` is there for a caller that drives everything itself and never //! blocks in a stream -- polling `Connection.readable` rather than reading //! through the seam. Anything using `transport.Session`, HTTP/3's driver //! included, wants `run` on a task. //! //! ## What a failed handshake says //! //! A handshake that does not complete has already said why, in §19.19's //! CONNECTION_CLOSE: a code, and for a cryptographic failure §20.1's //! CRYPTO_ERROR carrying TLS's own alert. The difficulty is that `connect` //! gives back everything it allocated on the way out, so by the time a caller //! has the error the connection that knows is gone -- and one error for every //! way a handshake can end is the least a client can say. //! //! So the code is read while it still exists, and reported twice over. The //! distinction a caller acts on is in the error set: `error.BadCertificate` is //! the one failure that may mean somebody is in the way rather than that the //! other end is having a bad day, and `error.HandshakeFailed` is everything //! else. The rest -- the code itself, whether the peer sent it or this end //! did, and the reason phrase a person was meant to read -- is copied into //! `Options.diagnosis` when a caller offers somewhere to put it: //! //! ```zig //! var why: quic_io.Client.Diagnosis = .{}; //! client.connect(io, gpa, &socket, server, .{ //! .alpn = &.{"doq"}, //! .host = "dns.example", //! .root_ca = trust, //! .rng = rng, //! .diagnosis = &why, //! }) catch |err| switch (err) { //! error.BadCertificate => log.err("{s} is not who it says", .{host}), //! // A server that speaks QUIC and not this: alert 120, which §3.1 of //! // RFC 9114 and RFC 9250 §4.1.2 both rest on. //! else => log.err("handshake failed: {?} {s}", .{ why.code, why.reason() }), //! }; //! ``` const std = @import("std"); const Io = std.Io; const net = Io.net; const Allocator = std.mem.Allocator; const quic = @import("quic"); const Session = @import("Session.zig"); const ecn = @import("ecn.zig"); const Client = @This(); pub const Options = struct { /// §7.4: the transport parameters this end offers. local: quic.parameters.Parameters = .{}, /// How much memory the connection is given. sizes: quic.Connection.Sizes = .{}, /// The largest send window a connection may be grown to; see /// `Endpoint.Options.max_send_window`. max_send_window: ?usize = null, /// §3.1 of RFC 9114 and friends: what to offer in ALPN. alpn: []const []const u8, /// The name to ask for, which is what the certificate is checked against. /// /// Empty sends no `server_name`, which is what a client dialing by /// `raw_public_key` wants: the key names the server, and a name in the /// clear would only tell an observer who is being dialed. host: []const u8, /// Where the trust for that check comes from. root_ca: @FieldType(quic.tls_handshake.Client.Options, "root_ca") = .{ .bytes = .empty, .map = .empty }, /// Whether to accept a certificate that does not verify. For a test, and /// named so that it cannot be set by accident. insecure_skip_verify: bool = false, /// RFC 7250: authenticate the server by its raw Ed25519 key, and this /// client by its own, instead of by certificates. `peer` is required -- /// it is the key being dialed -- and `root_ca` and `insecure_skip_verify` /// are ignored. raw_public_key: ?quic.tls_handshake.RawPublicKey = null, rng: std.Random, /// How long to wait for the handshake before giving up. handshake_timeout_ns: u64 = 10 * std.time.ns_per_s, /// A session ticket from a previous connection, for §4.6's resumption. /// /// A pointer because the handshake keeps it: the ticket is read during /// the exchange rather than copied out of the options. ticket: ?*quic.tls_handshake.Session = null, /// Whether to offer early data with that ticket. early_data: bool = false, /// Where to leave the account of a handshake that failed, or null for a /// caller that wants only the error. /// /// A pointer to the caller's own storage rather than a field on the /// `Client`, because a `connect` that fails has already given back /// everything it allocated: there is no connection left to ask, which is /// exactly why the close code had to be copied somewhere before it went. /// tls.zig's `Diagnostic` is the same arrangement for the same reason. diagnosis: ?*Diagnosis = null, }; /// What ended a handshake, beyond which of `ConnectError` it was. /// /// §19.19 of RFC 9000 gives a CONNECTION_CLOSE an error code, the frame type /// that provoked it, and a reason phrase written for a person. The error set /// below carries the one distinction a caller acts on; this carries the rest, /// for a log line or a bug report -- and it is the only way to see a code that /// belongs to neither category, such as §20.1's TRANSPORT_PARAMETER_ERROR from /// a server that would not have what this end offered. pub const Diagnosis = struct { /// The code the connection ended with, or null when nothing closed it -- /// a handshake that timed out, or a socket that stopped working. code: ?quic.close.Code = null, /// Whether it was §19.19's application variant (0x1d). A handshake cannot /// end that way -- application error codes belong to a protocol that has /// not been negotiated yet -- so this is here to be asserted rather than /// consulted. application: bool = false, /// Whether the peer sent it, rather than this end deciding it. What /// separates "the server refused us" from "we refused the server", which /// is the difference between a certificate this end would not verify and /// one the server would not offer. from_peer: bool = false, reason_buf: [reason_max]u8 = undefined, reason_len: usize = 0, /// As much of §19.19's reason phrase as `Closing` kept. pub const reason_max = @typeInfo(@FieldType(quic.close.Closing, "reason_buf")).array.len; pub fn reason(d: *const Diagnosis) []const u8 { return d.reason_buf[0..d.reason_len]; } /// §20.1: the TLS alert inside a CRYPTO_ERROR, when that is what ended it. pub fn alert(d: *const Diagnosis) ?u8 { return (d.code orelse return null).alert(); } }; pub const ConnectError = error{ /// The socket would not send or receive. NetworkFailed, /// The handshake did not finish in time, which is what a server that is /// not there looks like. HandshakeTimeout, /// A certificate was refused: the connection ended with §20.1's /// CRYPTO_ERROR carrying one of TLS's certificate alerts. /// /// Usually this end refusing the server's -- a chain that leads nowhere /// trusted, a name the certificate does not carry, or dates that have /// passed -- because that is the check a client makes and the alert /// `tls.Handshake` raises for all three. It is the one handshake failure /// that may mean somebody is in the way rather than that the other end is /// having a bad day, which is why it is an error of its own and not a /// field to look up afterwards. BadCertificate, /// The handshake failed for a reason that is not about a certificate: a /// server that would not agree on a protocol, a version or a transport /// parameter, or one that closed the connection. `Options.diagnosis` is /// where the code that says which goes. HandshakeFailed, OutOfMemory, } || Io.Cancelable; io: Io, gpa: Allocator, socket: *net.Socket, server: net.IpAddress, session: *Session, connection: *quic.Connection, memory: quic.Connection.Memory, parameters: quic.parameters.Parameters, stopping: bool = false, /// One reader per socket `openPath` was given. readers: Io.Group = .init, /// Tells those readers to return. A flag they look at between waits rather /// than `readers.cancel`: a cancellation that lands while a timed receive /// is waiting can come back as the timeout, and a reader that took that as /// a reason to wait again would never see it -- `deinit` would wait on it /// for ever. `Endpoint.pump` and `run` stop the same way. closing: std.atomic.Value(bool) = .init(false), /// Dials a server and completes the handshake. /// /// In place, because the session holds pointers into itself and into the TLS /// state beside it -- see `quic.Connection.init`, which says the same about /// its buffers. pub fn connect( c: *Client, io: Io, gpa: Allocator, socket: *net.Socket, server: net.IpAddress, options: Options, ) ConnectError!void { // §13.4.1: ask the kernel for each datagram's ECN field, so markings can // be counted and fed back. Best effort, as on the server. ecn.requestOnReceive(socket.handle); const session = gpa.create(Session) catch return error.OutOfMemory; errdefer gpa.destroy(session); const connection = gpa.create(quic.Connection) catch return error.OutOfMemory; errdefer gpa.destroy(connection); var sizes = options.sizes; if (options.max_send_window) |largest| { var largest_sizes = sizes; largest_sizes.send_window = largest; sizes.tracked = @max(sizes.tracked, largest_sizes.trackedFloor()); } const memory = allocMemory(gpa, sizes) catch return error.OutOfMemory; errdefer freeMemory(gpa, memory); // Cleared before anything can fail, so that what a caller reads afterwards // is this attempt rather than the last one. if (options.diagnosis) |d| d.* = .{}; c.* = .{ .io = io, .gpa = gpa, .socket = socket, .server = server, .session = session, .connection = connection, .memory = memory, .parameters = options.local, }; session.* = .{ .io = io, .socket = socket, .origin = Io.Timestamp.now(io, .awake), .connection = connection, .memory = memory, .tls = undefined, .provisioned = true, .in_use = true, }; // §7.2: the client chooses both identifiers in its first Initial. The // destination is a value it invents, and the server's Initial keys are // derived from it -- which is why it must be random rather than // convenient: anyone who can guess it can forge the server's half of the // handshake. var destination: [8]u8 = undefined; options.rng.bytes(&destination); options.rng.bytes(&session.local_id); session.local_id_len = session.local_id.len; @memcpy(session.original_id[0..destination.len], &destination); session.original_id_len = destination.len; session.peers[0] = server; var parameters = options.local; parameters.initial_source_connection_id = session.local_id[0..session.local_id_len]; // RFC 9368 §3: Version Information, which any endpoint of this library // can state for itself -- one version, chosen and available -- so it is // sent unless the caller has said something else. if (parameters.version_information == null) parameters.version_information = .v1; // §18.2: a client has no `stateless_reset_token` to offer and no // `original_destination_connection_id` -- both are the server's to send, // and a client that sent them would be answering a question nobody asked. const encoded = quic.parameters.write( ¶meters, &session.parameter_bytes, .client, ) catch return error.HandshakeFailed; session.parameter_len = encoded.len; c.parameters = parameters; session.tls = .{ .client = quic.tls_handshake.Client.init(.{ .host = options.host, .root_ca = options.root_ca, .alpn_protocols = options.alpn, .transport_parameters = session.parameter_bytes[0..session.parameter_len], .rng = options.rng, .now_sec = @intCast(@max(Io.Timestamp.now(io, .real).toSeconds(), 0)), .insecure_skip_verify = options.insecure_skip_verify, .session = options.ticket, .early_data = options.early_data, .raw_public_key = options.raw_public_key, }) catch return error.HandshakeFailed }; connection.init(.{ .role = .client, .handshake = session.tls.handshake(), .local_id = session.local_id[0..session.local_id_len], .destination_id = &destination, .memory = memory, .local = parameters, .rng = options.rng, }); // The first flight, and then datagrams until TLS says it is done. session.flush(); try c.pumpUntilEstablished(options.handshake_timeout_ns, options.diagnosis); } pub fn deinit(c: *Client) void { c.closing.store(true, .release); c.readers.await(c.io) catch {}; c.session.finish(); freeMemory(c.gpa, c.memory); c.gpa.destroy(c.connection); c.gpa.destroy(c.session); c.* = undefined; } /// draft-ietf-quic-multipath-21 §3.1: opens a further path to the server /// from `socket`, which the caller has bound to another local address or /// port, and returns its multipath path ID. /// /// The connection must have negotiated multipath with room for the path: /// `Options.local.initial_max_path_id` at least 1, `Options.sizes.paths` at /// least 2, and a server that allows it. The path is validated before data /// goes on it; `pathReady` says when it has been, and `session.useSendPath` /// or `session.setScheduler` puts data on it after that. /// /// A task of the client's own reads `socket` from here on, beside the one in /// `run`: the peer is at the same address on every path, so which socket a /// datagram arrived on is the only thing that names its path, and one task /// cannot wait on two sockets at once. `socket` must outlive the client. pub fn openPath(c: *Client, socket: *net.Socket) !Opened { ecn.requestOnReceive(socket.handle); const opened = try c.session.openPath(socket, c.server); try c.readers.concurrent(c.io, readPath, .{ c, socket, opened.route }); return .{ .id = opened.id, .route = opened.route }; } /// A path `openPath` opened: the protocol's path ID, which `useSendPath`, /// `abandonPath` and `setPathStatus` take, and the caller's route number /// for it, which `pathReady` takes. pub const Opened = struct { id: u32, route: quic.path.Id }; /// Whether a path from `openPath` has been validated. pub fn pathReady(c: *Client, opened: Opened) bool { return c.session.pathValidated(opened.route); } /// Reads the socket of path `route` until the client is torn down. fn readPath(c: *Client, socket: *net.Socket, route: quic.path.Id) Io.Cancelable!void { var datagram: [2048]u8 = undefined; var control: [128]u8 align(@alignOf(usize)) = undefined; while (!c.closing.load(.acquire)) { var messages = [_]net.IncomingMessage{.{ .from = undefined, .data = &datagram, .control = &control, .flags = undefined, }}; const maybe_err, const count = socket.receiveManyTimeout( c.io, &messages, &datagram, .{}, // Short, because it is also how long `deinit` may wait for this // reader to notice it is closing. .{ .duration = .{ .raw = .{ .nanoseconds = 100 * std.time.ns_per_ms }, .clock = .awake, } }, ); if (maybe_err) |err| switch (err) { error.Timeout => continue, error.Canceled => return error.Canceled, else => return, }; if (count == 0) continue; c.session.receiveOn(route, messages[0].data, messages[0].from, ecn.fromControl(messages[0].control)); } } /// Asks `run` to return. pub fn stop(c: *Client) void { c.stopping = true; } /// Reads datagrams and runs timers until `stop`. /// /// Wants a task of its own. Everything that reads a stream through /// `Stream.Reader` blocks until a datagram arrives, and the only thing that /// makes one arrive is this -- so a caller that does both on one task waits /// for itself. §6.2's probe timeout has the same shape: a connection nobody /// pumps never notices a lost packet. pub fn run(c: *Client) !void { while (!c.stopping) { if (c.session.closeState() != null) return; try c.once(std.time.ns_per_s); } } /// Reads one datagram, or runs the timers if none arrives first. /// /// For a caller driving everything on one task, which then must not block in /// a stream read -- see the note at the top of this file. pub fn once(c: *Client, wait_ns: u64) !void { const at = c.session.now(); const due = c.session.timeout(); const wait = if (due) |when| (if (when > at) @min(when - at, wait_ns) else 0) else wait_ns; var datagram: [2048]u8 = undefined; var control: [128]u8 align(@alignOf(usize)) = undefined; var messages = [_]net.IncomingMessage{.{ .from = undefined, .data = &datagram, .control = &control, .flags = undefined, }}; const maybe_err, const count = c.socket.receiveManyTimeout( c.io, &messages, &datagram, .{}, .{ .duration = .{ .raw = .{ .nanoseconds = @intCast(@max(wait, std.time.ns_per_ms)) }, .clock = .awake, } }, ); if (maybe_err) |err| switch (err) { error.Timeout => { c.session.tick(); return; }, else => return err, }; if (count == 0) { c.session.tick(); return; } c.session.receive(messages[0].data, messages[0].from, ecn.fromControl(messages[0].control)); c.session.tick(); } fn pumpUntilEstablished( c: *Client, timeout_ns: u64, diagnosis: ?*Diagnosis, ) ConnectError!void { const started = c.session.now(); while (!c.connection.isEstablished()) { // Asked before anything else, and answered by reading the close code // rather than by returning one error for every way a handshake can // end: this is the last moment it exists. `deinit` has not run, but // the caller's `errdefer`s are about to, and after them the connection // that knows is gone. if (c.session.closeState() != null) return c.diagnose(diagnosis); if (c.session.now() -| started > timeout_ns) return error.HandshakeTimeout; c.once(50 * std.time.ns_per_ms) catch |err| switch (err) { // The caller asked for the handshake to stop, which is not the // socket failing -- and reported as that, it would be taken for // a reason to try somewhere else. error.Canceled => |e| return e, else => return error.NetworkFailed, }; } } /// Copies out why the connection ended, and says which error that is. fn diagnose(c: *Client, into: ?*Diagnosis) ConnectError { // Under the lock because every other reader of this state takes it. The // handshake is pumped on the caller's own task, so there is nobody to // contend with yet -- which is a fact about today's `connect` rather than // a licence to reach past the mutex. c.session.mutex.lockUncancelable(c.io); defer c.session.mutex.unlock(c.io); const closing = &c.connection.closing; if (into) |d| { d.code = closing.code; d.application = closing.application; // §10.2.2: the draining state is the one entered on hearing the peer // say it is over, so it is what distinguishes a close this end sent // from one it was sent. d.from_peer = closing.state == .draining; const why = closing.reason(); const len = @min(why.len, d.reason_buf.len); @memcpy(d.reason_buf[0..len], why[0..len]); d.reason_len = len; } return classify(closing.code); } /// Which `ConnectError` a close code amounts to. /// /// §20.1 of RFC 9000 reserves 0x0100-0x01ff for CRYPTO_ERROR and fills it with /// TLS's own alert numbers, which is how a QUIC endpoint reports that a /// certificate was refused without QUIC knowing what a certificate is. These /// are the alerts §6.2 of RFC 8446 gives to the certificate rather than to the /// protocol; everything else -- a version nobody shares, a transport parameter /// nobody accepts, a connection simply refused -- is a handshake that failed. fn classify(code: quic.close.Code) ConnectError { const alert = code.alert() orelse return error.HandshakeFailed; return switch (alert) { 42, // bad_certificate, which is what tls.zig raises for every // verification failure: §4.4 of RFC 9001 leaves authentication to TLS // and it deliberately does not distinguish "expired" from "wrong // name", since neither is recoverable. 43, // unsupported_certificate 44, // certificate_revoked 45, // certificate_expired 46, // certificate_unknown 48, // unknown_ca 116, // certificate_required => error.BadCertificate, else => error.HandshakeFailed, }; } fn allocMemory(gpa: Allocator, sizes: quic.Connection.Sizes) !quic.Connection.Memory { const streams = quic.Connection.max_streams; const send = try gpa.alloc(u8, streams * sizes.send_window); errdefer gpa.free(send); const recv = try gpa.alloc(u8, streams * sizes.recv_window); errdefer gpa.free(recv); const present = try gpa.alloc(u8, streams * (sizes.recv_window / 8)); errdefer gpa.free(present); // One table each for the Initial and Handshake spaces and one per path. const tracked = try gpa.alloc(quic.recovery.Sent, (2 + sizes.paths) * sizes.tracked); errdefer gpa.free(tracked); const scratch = try gpa.alloc(quic.recovery.Sent, 3 * sizes.tracked); return .{ .send = send, .recv = recv, .present = present, .tracked = tracked, .scratch = scratch, .paths = sizes.paths, }; } fn freeMemory(gpa: Allocator, memory: quic.Connection.Memory) void { gpa.free(memory.send); gpa.free(memory.recv); gpa.free(memory.present); gpa.free(memory.tracked); gpa.free(memory.scratch); } const testing = std.testing; test "a close code says whether a certificate was refused" { // §20.1 of RFC 9000 reserves 0x0100-0x01ff for the handshake's own errors // and RFC 9001 §4.8 fills it with TLS's alert numbers, so this table is // §6.2 of RFC 8446 split into the alerts that are about a certificate and // the alerts that are about the protocol. for ([_]u8{ 42, // bad_certificate 43, // unsupported_certificate 44, // certificate_revoked 45, // certificate_expired 46, // certificate_unknown 48, // unknown_ca 116, // certificate_required }) |alert| { try testing.expectEqual(error.BadCertificate, classify(.crypto(alert))); } for ([_]u8{ 40, // handshake_failure 47, // illegal_parameter 50, // decode_error 70, // protocol_version 80, // internal_error 120, // no_application_protocol -- a server that will not speak this }) |alert| { try testing.expectEqual(error.HandshakeFailed, classify(.crypto(alert))); } // And a transport error rather than a cryptographic one, which cannot be // about a certificate however it is read: the range does not overlap. for ([_]quic.close.Code{ .no_error, .internal_error, .connection_refused, .transport_parameter_error, .protocol_violation, }) |code| { try testing.expectEqual(error.HandshakeFailed, classify(code)); } } test "a diagnosis holds as much of a reason phrase as the frame does" { // The two buffers are the same size on purpose: a reason truncated twice, // once by `Closing` and again here, would be a diagnosis that disagreed // with what arrived. try testing.expectEqual( @typeInfo(@FieldType(quic.close.Closing, "reason_buf")).array.len, Diagnosis.reason_max, ); var d: Diagnosis = .{}; try testing.expectEqual(@as(?quic.close.Code, null), d.code); try testing.expectEqual(@as(?u8, null), d.alert()); try testing.expectEqualStrings("", d.reason()); d.code = .crypto(48); try testing.expectEqual(@as(?u8, 48), d.alert()); // A transport code carries no alert, and saying so is not the same as // saying the alert was zero -- alert 0 is `close_notify`. d.code = .transport_parameter_error; try testing.expectEqual(@as(?u8, null), d.alert()); }