// 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 `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: {?any} {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; /// §19.19's reason phrase, as much of it as `reason_max` kept: text /// written for a person, and for a log line rather than for a program to /// act on. Empty when the close carried none -- as this library's own /// closes for a failed handshake do -- or nothing closed the connection. /// Borrowed from `d`. pub fn reason(d: *const Diagnosis) []const u8 { return d.reason_buf[0..d.reason_len]; } test reason { // A server this library runs, refusing a protocol it does not speak, // which it says with a code and no phrase. var pair: test_pair.Pair = undefined; try pair.listen(.{}); defer pair.stop(); var why: Diagnosis = .{}; try testing.expectError(error.HandshakeFailed, dialFor(&pair, &.{"nope"}, &why)); try testing.expectEqualStrings("", why.reason()); try testing.expect(why.code != null); } /// §20.1: the TLS alert inside a CRYPTO_ERROR, when that is what ended /// it, and null for any other code or for no code at all. Zero is /// `close_notify` rather than "none". pub fn alert(d: *const Diagnosis) ?u8 { return (d.code orelse return null).alert(); } test alert { var pair: test_pair.Pair = undefined; try pair.listen(.{}); defer pair.stop(); var why: Diagnosis = .{}; try testing.expectError(error.HandshakeFailed, dialFor(&pair, &.{"nope"}, &why)); // no_application_protocol, and the server is the end that said so. try testing.expectEqual(@as(?u8, 120), why.alert()); try testing.expect(why.from_peer); } }; /// Dials `pair`'s server offering `alpn`, for a test that expects it to /// fail: there is nothing to `deinit` if it does. fn dialFor(pair: *test_pair.Pair, alpn: []const []const u8, why: *Diagnosis) ConnectError!void { const io = testing.io; const loopback: net.IpAddress = net.IpAddress.parse("127.0.0.1", 0) catch unreachable; var socket = loopback.bind(io, .{ .mode = .dgram }) catch return error.NetworkFailed; defer socket.close(io); var c: Client = undefined; try c.connect(io, testing.allocator, &socket, pair.server_socket.address, .{ .alpn = alpn, .host = "pair.example", .insecure_skip_verify = true, .rng = pair.prng.random(), .local = test_pair.local, .diagnosis = why, }); c.deinit(); } 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, /// Set when `stop` is called, so that `run` in its own task can be ended /// from outside it. Written by one task and read by another, hence atomic. stopping: std.atomic.Value(bool) = .init(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. /// /// Blocks, pumping `socket` on the caller's own task, until the handshake /// finishes, fails, or `Options.handshake_timeout_ns` passes. On success /// the client holds what it allocated from `gpa` until `deinit`, and /// `socket` -- which it does not own and does not close -- must outlive it. /// On failure everything allocated has been given back already and `c` is /// left meaningless: there is nothing to `deinit`. A socket that would not /// send or receive is `error.NetworkFailed`, and a cancelation is reported /// as `error.Canceled` rather than as either. 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); } test connect { const io = testing.io; var pair: test_pair.Pair = undefined; try pair.listen(.{}); defer pair.stop(); const server = pair.server_socket.address; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io); var client: Client = undefined; try client.connect(io, testing.allocator, &socket, server, .{ .alpn = &.{"test"}, .host = "pair.example", // The test server has no certificate to verify. .insecure_skip_verify = true, .rng = pair.prng.random(), .local = test_pair.local, }); defer client.deinit(); try testing.expect(client.session.isEstablished()); } /// Gives back everything `connect` allocated. Ends the readers `openPath` /// started, which can take a tenth of a second each to notice, but not /// `run`: a task running that must have been stopped and have returned /// first, since the session it reads into is freed here. The socket is the /// caller's, and is left open. /// /// A connection still open is closed first, with §19.19's application /// variant and code zero, and the CONNECTION_CLOSE is sent before anything is /// freed -- the same as `Endpoint` does for a handler that returns. Without /// it the server would learn of the end only from its idle timeout. A caller /// with something more specific to say calls `session.closeApplication` /// first, and this leaves that close alone. The socket must therefore still /// be open here. pub fn deinit(c: *Client) void { { // Protected from cancelation: teardown is often what a canceled task // does on its way out, and the close's send would otherwise be the // cancelation point that reports it, leaving the server uninformed. const protection = c.io.swapCancelProtection(.blocked); defer _ = c.io.swapCancelProtection(protection); if (c.session.closeState() == null) c.session.closeApplication(0, ""); } 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; } test deinit { const io = testing.io; var pair: test_pair.Pair = undefined; try pair.listen(.{}); defer pair.stop(); const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io); var client: Client = undefined; try client.connect(io, testing.allocator, &socket, pair.server_socket.address, .{ .alpn = &.{"test"}, .host = "pair.example", .insecure_skip_verify = true, .rng = pair.prng.random(), .local = test_pair.local, }); // Closes the connection, telling the server so, and frees it. client.deinit(); } test "a client torn down while open says goodbye" { // Ending a connection without a CONNECTION_CLOSE leaves the server to // find out from its idle timeout, holding the connection's state until // then. The server's own handlers are closed for them when they return, // and a client is owed the same. const io = testing.io; var pair: test_pair.Pair = undefined; try pair.listen(.{}); defer pair.stop(); const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io); var client: Client = undefined; try client.connect(io, testing.allocator, &socket, pair.server_socket.address, .{ .alpn = &.{"test"}, .host = "pair.example", .insecure_skip_verify = true, .rng = pair.prng.random(), .local = test_pair.local, }); client.deinit(); // The server hears it in the time a datagram takes over loopback, not // the five seconds of its idle timeout. var waited: usize = 0; while (waited < 200) : (waited += 1) { const open = for (pair.endpoint.sessions) |*s| { if (s.in_use and s.connection.closeState() == null) break true; } else false; if (!open) return; try io.sleep(.fromMilliseconds(5), .awake); } return error.ServerNeverHeardTheClose; } test "a client torn down by a canceled task still says goodbye" { // Teardown is often what a task does on its way out of a cancelation, // having passed it on with `recancel` as std.Io asks. The close's send // is then the next cancelation point, and must not be the one that // reports it. const io = testing.io; var pair: test_pair.Pair = undefined; try pair.listen(.{}); defer pair.stop(); const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io); var client: Client = undefined; try client.connect(io, testing.allocator, &socket, pair.server_socket.address, .{ .alpn = &.{"test"}, .host = "pair.example", .insecure_skip_verify = true, .rng = pair.prng.random(), .local = test_pair.local, }); const Owner = struct { fn run(c: *Client) void { c.io.sleep(.fromSeconds(60), .awake) catch |err| switch (err) { error.Canceled => c.io.recancel(), }; c.deinit(); } }; var owner = try io.concurrent(Owner.run, .{&client}); owner.cancel(io); var waited: usize = 0; while (waited < 200) : (waited += 1) { const open = for (pair.endpoint.sessions) |*s| { if (s.in_use and s.connection.closeState() == null) break true; } else false; if (!open) return; try io.sleep(.fromMilliseconds(5), .awake); } return error.ServerNeverHeardTheClose; } /// 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. /// /// Fails as `Session.openPath` does -- `error.NoPathAvailable` in particular /// until the server's connection ID for the path has arrived, just after the /// handshake, so a caller opening one at once retries -- and with /// `error.ConcurrencyUnavailable` when there is no task to read `socket` /// with. A path that fails that way is abandoned again, and `socket` is no /// longer held. pub fn openPath(c: *Client, socket: *net.Socket) !Opened { ecn.requestOnReceive(socket.handle); const opened = try c.session.openPath(socket, c.server); errdefer { // The path is open and its PATH_CHALLENGE sent, and nothing will // read its socket: abandoned, so that the server is told and the // route can be reused, and the socket let go, since a caller told // this failed has every reason to close it. c.session.abandonPath(opened.id) catch {}; c.session.mutex.lockUncancelable(c.io); defer c.session.mutex.unlock(c.io); c.session.path_sockets[opened.route] = null; } try c.readers.concurrent(c.io, readPath, .{ c, socket, opened.route }); return .{ .id = opened.id, .route = opened.route }; } test "a path whose reader cannot start is not left open" { // `openPath` needs a task to read the new socket with. An `Io` with none // to give refuses, and by then the session has already opened the path // and sent its PATH_CHALLENGE -- from a socket the caller, told the call // failed, has every reason to think is no longer in use. var pair: test_pair.Pair = undefined; try pair.listen(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); var threaded: Io.Threaded = .init(testing.allocator, .{ .concurrent_limit = .limited(0) }); defer threaded.deinit(); const io = threaded.io(); const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io); var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io); var client: Client = undefined; try client.connect(io, testing.allocator, &socket, pair.server_socket.address, .{ .alpn = &.{"test"}, .host = "pair.example", .insecure_skip_verify = true, .rng = pair.prng.random(), .local = test_pair.multipath, .sizes = .{ .paths = 2 }, }); defer client.deinit(); var attempts: usize = 0; const err = while (true) : (attempts += 1) { if (client.openPath(&second)) |_| { return error.TestExpectedError; } else |err| { if (err != error.NoPathAvailable) break err; if (attempts > 200) return err; try client.once(5 * std.time.ns_per_ms); } }; try testing.expectEqual(error.ConcurrencyUnavailable, err); // Nothing is left that could send from `second`, and the path the call // failed to open is not one the connection still counts as open. try testing.expectEqual(@as(?*net.Socket, null), client.session.path_sockets[1]); try testing.expectError(error.NotAllowed, client.connection.abandonPath(1)); } test openPath { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); // A second local port, to be the client's half of a second 4-tuple. It // outlives the client, which reads it until `deinit`. var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io); var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); const client = &pair.client; var attempts: usize = 0; const opened = while (true) : (attempts += 1) { if (client.openPath(&second)) |opened| break opened else |err| { if (err != error.NoPathAvailable or attempts > 200) return err; try io.sleep(.fromMilliseconds(5), .awake); } }; try testing.expectEqual(@as(u32, 1), opened.id); } /// 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, after which it can be /// given data. Does not wait. pub fn pathReady(c: *Client, opened: Opened) bool { return c.session.pathValidated(opened.route); } test pathReady { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io); var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); // Opened, and then polled with this until its PATH_CHALLENGE has been // answered. const opened = try test_pair.openValidatedPath(&pair, &second); try testing.expect(pair.client.pathReady(opened)); try pair.session().useSendPath(opened.id); } /// 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, which it does at the end of its current turn: at /// most a second away, since a turn waits for a datagram or a timer and /// never longer than that. Safe to call from any task, and does not wait. pub fn stop(c: *Client) void { c.stopping.store(true, .release); } test stop { var pair: test_pair.Pair = undefined; try pair.start(.{ .run = false }); defer pair.stop(); // Looked at before every turn, so a `run` started after it returns at // once -- where one already waiting returns after the turn it is in. pair.client.stop(); try pair.client.run(); } /// Reads datagrams and runs timers until `stop`, or until the connection has /// closed. /// /// 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. /// /// Fails when the socket does, `error.Canceled` included. pub fn run(c: *Client) !void { while (!c.stopping.load(.acquire)) { if (c.session.closeState() != null) return; try c.once(std.time.ns_per_s); } } test run { const io = testing.io; var pair: test_pair.Pair = undefined; try pair.start(.{ .run = false }); defer pair.stop(); const client = &pair.client; var tasks: Io.Group = .init; // A cancelation ends the wait for a datagram at once, where `stop` // alone would be noticed only after it. defer tasks.cancel(io); try tasks.concurrent(io, struct { fn go(cl: *Client) void { cl.run() catch {}; } }.go, .{client}); defer client.stop(); // With `run` on its own task, a stream read can block. var answer: [64]u8 = undefined; try testing.expectEqualStrings("pumped", try test_pair.exchange(client.session, "pumped", &answer)); } /// Reads one datagram, or runs the timers if none arrives first. /// /// Waits at most `wait_ns`, and less when a timer is due sooner -- but /// always at least a millisecond. Fails when the socket does, `error.Canceled` /// included. /// /// 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(); } test once { var pair: test_pair.Pair = undefined; // No `run` task: this test is the pump. try pair.start(.{ .run = false }); defer pair.stop(); const client = &pair.client; // Writing does not need the pump, since a writer sends what it writes... const stream = try client.session.openBidirectional(); try client.session.writeStreamFinished(stream.id, "polled"); // ...but hearing the answer does. Turn until it is all here, which is // a question that does not block, unlike a read. var turns: usize = 0; while (!stream.received()) : (turns += 1) { if (turns > 1000) return error.NoAnswer; try client.once(10 * std.time.ns_per_ms); } client.session.mutex.lockUncancelable(client.io); defer client.session.mutex.unlock(client.io); try testing.expectEqualStrings("polled", client.connection.readable(stream.id)); } 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; const test_pair = @import("test_pair.zig"); 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()); }