// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `quic_io` over a real socket. //! //! Everything in the sans-I/O suite drives connections by handing datagrams //! from one to the other, which proves the protocol and says nothing about //! the loop. This is the other half: an `Endpoint` on a loopback port, a //! client connecting to it over UDP, and the question of whether a task //! blocked reading a stream is woken by a datagram another task received. //! //! That is the part a state machine cannot be wrong about and a loop can. const std = @import("std"); const Io = std.Io; const net = Io.net; const testing = std.testing; const quic = @import("quic"); const quic_io = @import("quic_io"); test "an endpoint costs one allocation, whatever it is willing to serve" { // A connection's buffers are the bulk of what an endpoint spends, and how // much of it is the caller's to choose -- so buying every slot's worth // before a packet arrives makes an endpoint's memory a function of the // connections it is *willing* to serve rather than the ones it is // serving. Measured through zig-http, a server offering a megabyte per // stream on its default limit of sixty-four connections held 2.3 GB at // startup, which is not a configuration anybody can use. // // A `FailingAllocator` set to refuse the second request is how that is // asserted rather than described: the slots are one allocation, and // anything a connection needs is bought when a connection turns up. const io = testing.io; var failing: std.testing.FailingAllocator = .init(testing.allocator, .{ .fail_index = 1 }); const gpa = failing.allocator(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var rng_impl = std.Random.DefaultPrng.init(0x3132); var nothing: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &socket, .{ .alpn = &.{"echo"}, // Sizes nobody would buy a hundred of up front: sixteen streams of a // megabyte each way is sixteen megabytes a connection. .sizes = .{ .send_window = 1024 * 1024, .recv_window = 1024 * 1024, .tracked = 4096, }, .local = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng_impl.random(), .reset_key = @splat(0x31), .token_key = @splat(0x32), .max_connections = 100, }, .{ .context = ¬hing, .serveFn = Echo.serve }); defer endpoint.deinit(); // The one allocation was the slots, and every one of them is empty. try testing.expectEqual(@as(usize, 1), failing.alloc_index); for (endpoint.sessions) |*session| try testing.expect(!session.provisioned); } /// Answers every stream with a body far larger than one send buffer, each on /// a task of its own, so that two writers are blocked for room at once. /// /// The echo handler below cannot show this: it serves its streams one after /// another in a single loop, so there is only ever one writer. A server that /// answers requests concurrently -- which is every HTTP/3 server, and what /// `zig-http` does -- has as many blocked writers as it has streams in /// flight. const Bulk = struct { io: Io, done: std.atomic.Value(u32) = .init(0), tasks: Io.Group = .init, /// What each stream answers with, so that a test may ask for a body /// sized against its own windows rather than against the default ones. len: usize = body_len, /// Sixteen times one stream's buffer, so a writer cannot finish without /// being blocked for room and woken again several times over. const body_len = 16 * quic.Connection.stream_buffer; fn serve(context: ?*anyopaque, session: *quic_io.Session) void { const b: *Bulk = @ptrCast(@alignCast(context.?)); defer b.tasks.cancel(b.io); while (session.accept()) |stream| { b.tasks.concurrent(b.io, answer, .{ b, stream }) catch continue; } b.tasks.await(b.io) catch {}; } fn answer(b: *Bulk, stream: quic_io.Stream) void { var write_buffer: [1024]u8 = undefined; var writer = stream.writer(&write_buffer); const line: [64]u8 = @splat('x'); var sent: usize = 0; while (sent < b.len) : (sent += line.len) { writer.interface.writeAll(&line) catch return; } writer.interface.flush() catch return; writer.finish() catch return; _ = b.done.fetchAdd(1, .monotonic); } }; test "two streams can be writing at once" { // A client that asks for two large things before reading either, which // is what a browser does and what `curl` never does -- it reuses a // connection but waits for each answer before asking again, which is why // every test here and in zig-http missed this. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7702); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var bulk: Bulk = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x41), .token_key = @splat(0x42), .max_connections = 2, }, .{ .context = &bulk, .serveFn = Bulk.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); const parameters: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(¶meters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{})); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = parameters, .rng = rng, }); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var asked = false; var received: [2]usize = @splat(0); var steps: usize = 0; while (steps < 4000) : (steps += 1) { const at: u64 = @intCast(@max( Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0, )); if (connection.isEstablished() and !asked) { // Both asked for before either is read, which is the whole // point: the server ends up with two writers blocked for room. for (0..2) |_| { const id = try connection.openBidirectional(); try connection.write(id, "go"); try connection.finishStream(id); } asked = true; } while (try connection.send(&out, at)) |datagram| { try socket.send(io, &server_address, datagram.bytes); } if (asked) { for (0..2) |i| { const id: quic.stream.Id = .{ .value = @intCast(i * 4) }; const available = connection.readable(id); if (available.len > 0) { received[i] += available.len; connection.consume(id, available.len); } } if (received[0] >= Bulk.body_len and received[1] >= Bulk.body_len) break; } const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 50 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => { connection.onTimeout(at); continue; }, else => return err, }; try connection.receive(message.data, 0, at); } try testing.expectEqual(Bulk.body_len, received[0]); try testing.expectEqual(Bulk.body_len, received[1]); } test "a tracking table too small for the streams using it slows down rather than spinning" { // The table is a send window in its own right, and this is the shape // that proves it: `tracked` is sized for *one* stream's send window -- // `Sizes.trackedFloor` is satisfied exactly -- and then four streams are // asked for at once, so what is in the air is four times what the table // can record. // // The sender used to make room by forgetting its oldest packet, whose // data `forget` then re-queued as lost, which gave it something to send, // which forgot another. Nothing in that cycle waits, so the connection // spun at the speed of the processor, retransmitting octets that were // still in flight and never finishing -- through zig-http it looked like // two concurrent downloads hanging, with the server at a full core and // the pump starved of its own mutex for the whole transfer. // // What it must do instead is stop and wait for the acknowledgements that // empty the table, which costs throughput and finishes. const io = testing.io; const gpa = testing.allocator; const window = 1 << 16; // Exactly one stream's worth of §14.1-sized datagrams, and the floor // `Connection.init` asserts. Four streams need four times this. const tracked = (window + 1199) / 1200; var rng_impl = std.Random.DefaultPrng.init(0x7703); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; // One window a stream, so each writer fills its buffer and has to be // woken for room. var bulk: Bulk = .{ .io = io, .len = window }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = window, .initial_max_stream_data_bidi_remote = window, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x43), .token_key = @splat(0x44), .max_connections = 2, .sizes = .{ .send_window = window, .recv_window = window, .tracked = tracked }, }, .{ .context = &bulk, .serveFn = Bulk.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); // The client has to promise a window this large or the server could // never put two streams' worth in the air and the table would never // fill -- which is how every earlier test missed this. const parameters: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = window, .initial_max_stream_data_bidi_remote = window, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(¶meters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{ .recv_window = window })); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = parameters, .rng = rng, }); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var asked = false; var received: [4]usize = @splat(0); // Bounded, so that a sender which has gone back to spinning fails this // test rather than hanging the suite. var steps: usize = 0; while (steps < 20000) : (steps += 1) { const at: u64 = @intCast(@max( Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0, )); if (connection.isEstablished() and !asked) { for (0..4) |_| { const id = try connection.openBidirectional(); try connection.write(id, "go"); try connection.finishStream(id); } asked = true; } while (try connection.send(&out, at)) |datagram| { try socket.send(io, &server_address, datagram.bytes); } if (asked) { for (0..4) |i| { const id: quic.stream.Id = .{ .value = @intCast(i * 4) }; const available = connection.readable(id); if (available.len > 0) { received[i] += available.len; connection.consume(id, available.len); } } var all = true; for (received) |r| { if (r < window) all = false; } if (all) break; } const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 50 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => { connection.onTimeout(at); continue; }, else => return err, }; try connection.receive(message.data, 0, at); } for (received) |r| try testing.expectEqual(@as(usize, window), r); } test "a connection that fills its send buffer is given a larger one" { // The endpoint starts every connection at the default window and raises // it only for one that shows it can use more, so a server does not have // to choose between paying for the slowest path its clients might be on // and serving them badly. const io = testing.io; const gpa = testing.allocator; const start = quic.Connection.stream_buffer; const ceiling = 1 << 16; const granted = 1 << 16; var rng_impl = std.Random.DefaultPrng.init(0x7704); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var bulk: Bulk = .{ .io = io, .len = 1 << 18 }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = start, .initial_max_stream_data_bidi_remote = start, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x45), .token_key = @splat(0x46), .max_connections = 2, .sizes = .{ .send_window = start, .recv_window = start }, .max_send_window = ceiling, }, .{ .context = &bulk, .serveFn = Bulk.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); // The client grants a window far larger than the server starts with, so // that what holds the server back is its own buffer and nothing else -- // which is the only thing `bufferBound` counts. const parameters: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = granted, .initial_max_stream_data_bidi_remote = granted, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(¶meters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{ .recv_window = granted })); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = parameters, .rng = rng, }); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var asked = false; var received: usize = 0; var steps: usize = 0; while (steps < 20000) : (steps += 1) { const at: u64 = @intCast(@max( Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0, )); if (connection.isEstablished() and !asked) { const id = try connection.openBidirectional(); try connection.write(id, "go"); try connection.finishStream(id); asked = true; } while (try connection.send(&out, at)) |datagram| { try socket.send(io, &server_address, datagram.bytes); } if (asked) { const id: quic.stream.Id = .{ .value = 0 }; const available = connection.readable(id); if (available.len > 0) { received += available.len; connection.consume(id, available.len); } if (received >= bulk.len) break; } const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 50 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => { connection.onTimeout(at); continue; }, else => return err, }; try connection.receive(message.data, 0, at); } try testing.expectEqual(bulk.len, received); // The window the server ended up with. Grown, and never past the ceiling // it was given -- a tuner that cannot stop is worse than none, because // the memory it takes is per stream and per connection. var grown: usize = 0; for (endpoint.sessions) |*s| { if (!s.in_use or !s.provisioned) continue; grown = @max(grown, s.connection.sendWindow()); } try testing.expect(grown > start); try testing.expect(grown <= ceiling); } test "RFC 9000 6.1: a server answers an unknown version instead of ignoring it" { // "If the version selected by the client is not acceptable to the server, // the server responds with a Version Negotiation packet." Without this, a // client offering a version this endpoint does not speak gets silence: the // Initial keys of §5.2 of RFC 9001 are derived with a version-specific // salt, so the packet simply fails to decrypt and is dropped, and the // client waits out its own timeout learning nothing. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7705); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .rng = rng, .reset_key = @splat(0x47), .token_key = @splat(0x48), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); // A long header naming a version nobody speaks, padded to §14.1's // minimum: §5.2.2 has a server "drop smaller packets that specify // unsupported versions", so a short one would be answered with nothing // and would prove the opposite of what this is for. const destination: [8]u8 = @splat(0xd1); const source: [4]u8 = @splat(0x5c); var probe: [quic.Connection.min_initial_datagram]u8 = @splat(0); probe[0] = 0xc0; std.mem.writeInt(u32, probe[1..5], 0xdeadbeef, .big); probe[5] = destination.len; @memcpy(probe[6..][0..destination.len], &destination); probe[6 + destination.len] = source.len; @memcpy(probe[7 + destination.len ..][0..source.len], &source); try socket.send(io, &server_address, &probe); var in: [2048]u8 = undefined; const message = try socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 2 * std.time.ns_per_s }, .clock = .awake, } }); const wire = message.data; // §17.2.1: version zero is what makes it recognisable at all. try testing.expect(wire[0] & 0x80 != 0); try testing.expectEqual(@as(u32, 0), std.mem.readInt(u32, wire[1..5], .big)); // The connection IDs come back swapped, which is what tells a client that // whoever sent this saw the packet rather than guessing it existed. try testing.expectEqual(@as(u8, source.len), wire[5]); try testing.expectEqualSlices(u8, &source, wire[6..][0..source.len]); try testing.expectEqual(@as(u8, destination.len), wire[6 + source.len]); try testing.expectEqualSlices(u8, &destination, wire[7 + source.len ..][0..destination.len]); // The version this endpoint does speak is in the list, and the version it // was asked for is not. var at: usize = 7 + source.len + destination.len; var found_supported = false; var offered: usize = 0; while (at + 4 <= wire.len) : (at += 4) { const version = std.mem.readInt(u32, wire[at..][0..4], .big); try testing.expect(version != 0xdeadbeef); if (version == quic.packet.version_1) found_supported = true; offered += 1; } try testing.expect(found_supported); // §6.3's reserved version travels beside it, so a client that cannot // ignore what it does not know is found out here rather than in the field. try testing.expectEqual(@as(usize, quic.packet.supported_versions.len + 1), offered); } test "RFC 9000 5.2.2: a small datagram with an unknown version is dropped, not answered" { // "Servers MUST drop smaller packets that specify unsupported versions." // The packet is unauthenticated and the answer is larger than nothing, so // a server that replied to whatever arrived would amplify for anyone // willing to forge a source address. Requiring the datagram to be big // enough to have begun a connection is what keeps the exchange no worse // than the handshake it is refusing. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7706); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .rng = rng, .reset_key = @splat(0x49), .token_key = @splat(0x4a), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); // The same packet as the test above and one octet short of the minimum. const destination: [8]u8 = @splat(0xd1); const source: [4]u8 = @splat(0x5c); var probe: [quic.Connection.min_initial_datagram - 1]u8 = @splat(0); probe[0] = 0xc0; std.mem.writeInt(u32, probe[1..5], 0xdeadbeef, .big); probe[5] = destination.len; @memcpy(probe[6..][0..destination.len], &destination); probe[6 + destination.len] = source.len; @memcpy(probe[7 + destination.len ..][0..source.len], &source); try socket.send(io, &server_address, &probe); var in: [2048]u8 = undefined; const answer = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 300 * std.time.ns_per_ms }, .clock = .awake, } }); try testing.expectError(error.Timeout, answer); } /// An Initial from a client that is only beginning: a PING padded to §14.1's /// minimum, under the keys `destination` derives. fn sealInitial( out: *[quic.Connection.min_initial_datagram]u8, destination: []const u8, source: []const u8, token: []const u8, ) ![]u8 { var b = try quic.packet.Builder.initLong(out, .{ .kind = .initial, .destination = destination, .source = source, .token = token, }, 0, 1); try b.add(.ping); try b.padTo(out.len); const keys: quic.protection.Keys = .initialKeys(destination, .client); return b.finish(&keys); } /// Waits for the server's answer to an Initial sent from `source` to /// `destination`, passing over anything addressed elsewhere, and returns its /// first octet and, if it is an Initial, the first frame in it -- which is /// all these tests need of it. fn awaitAnswer( io: Io, socket: *net.Socket, destination: []const u8, source: []const u8, plain: []u8, ) !struct { first: u8, frame: ?quic.frame.Frame } { var in: [2048]u8 = undefined; while (true) { const message = try socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 2 * std.time.ns_per_s }, .clock = .awake, } }); const wire = message.data; const header = quic.packet.parse(wire, source.len) catch continue; if (!std.mem.eql(u8, header.destination, source)) continue; if (header.kind != .initial) return .{ .first = wire[0], .frame = null }; const keys: quic.protection.Keys = .initialKeys(destination, .server); const opened = try quic.packet.open(&keys, 0, wire, source.len, plain); return .{ .first = wire[0], .frame = (try quic.frame.parse(opened.payload)).frame }; } } /// An endpoint for the stateless answers below, with its pump running. const Refusing = struct { socket: net.Socket, echo: Echo, endpoint: quic_io.Endpoint, group: Io.Group = .init, client: net.Socket, fn create(gpa: std.mem.Allocator, io: Io, rng: std.Random, options: struct { require_retry: bool = false, max_connections: usize = 2, }) !*Refusing { const r = try gpa.create(Refusing); errdefer gpa.destroy(r); const bind: net.IpAddress = try .parse("127.0.0.1", 0); r.socket = try bind.bind(io, .{ .mode = .dgram }); errdefer r.socket.close(io); r.echo = .{ .io = io }; r.endpoint = try quic_io.Endpoint.init(io, gpa, &r.socket, .{ .alpn = &.{"echo"}, .rng = rng, .reset_key = @splat(0x4b), .token_key = @splat(0x4c), .max_connections = options.max_connections, .require_retry = options.require_retry, }, .{ .context = &r.echo, .serveFn = Echo.serve }); errdefer r.endpoint.deinit(); r.client = try bind.bind(io, .{ .mode = .dgram }); errdefer r.client.close(io); r.group = .init; try r.group.concurrent(io, pump, .{&r.endpoint}); return r; } fn destroy(r: *Refusing, gpa: std.mem.Allocator, io: Io) void { r.endpoint.stop(); r.group.cancel(io); r.client.close(io); r.endpoint.deinit(); r.socket.close(io); gpa.destroy(r); } }; test "RFC 9000 8.1.2: a Retry token that does not open is answered with INVALID_TOKEN" { // "If a server receives a client Initial that contains an invalid Retry // token but is otherwise valid, it knows the client will not accept // another Retry token. ... the server SHOULD immediately close (Section // 10.2) the connection with an INVALID_TOKEN error." const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7707); const r = try Refusing.create(gpa, io, rng_impl.random(), .{ .require_retry = true }); defer r.destroy(gpa, io); // A token of this endpoint's own making, sealed under some other key: what // a client holds after the server restarts between its Retry and the // Initial that answers it. const destination: [8]u8 = @splat(0xd2); const source: [4]u8 = @splat(0x5d); var token_buf: [quic.retry.Token.max_len]u8 = undefined; const token = try quic.retry.Token.mint(&token_buf, @splat(0x00), "elsewhere", &destination, 1); var out: [quic.Connection.min_initial_datagram]u8 = undefined; try r.client.send(io, &r.socket.address, try sealInitial(&out, &destination, &source, token)); var plain: [2048]u8 = undefined; const answer = try awaitAnswer(io, &r.client, &destination, &source, &plain); const close = answer.frame.?.connection_close; try testing.expectEqual(@backingInt(quic.close.Code.invalid_token), close.error_code); try testing.expect(!close.application); } test "RFC 9000 8.1.3: a token this endpoint never made is answered with a Retry" { // "If the token is invalid, then the server SHOULD proceed as if the // client did not have a validated address, including potentially sending // a Retry packet." A client carrying another server's NEW_TOKEN has had // no Retry from this one, and will take one. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7708); const r = try Refusing.create(gpa, io, rng_impl.random(), .{ .require_retry = true }); defer r.destroy(gpa, io); const destination: [8]u8 = @splat(0xd3); const source: [4]u8 = @splat(0x5e); var out: [quic.Connection.min_initial_datagram]u8 = undefined; try r.client.send(io, &r.socket.address, try sealInitial(&out, &destination, &source, "somebody else's")); var plain: [2048]u8 = undefined; const answer = try awaitAnswer(io, &r.client, &destination, &source, &plain); // §17.2.5: long header, type 0b11. try testing.expectEqual(@as(u8, 0xf0), answer.first & 0xf0); } test "RFC 9000 5.2.2: an endpoint with no room says CONNECTION_REFUSED" { // "If a server refuses to accept a new connection, it SHOULD send an // Initial packet containing a CONNECTION_CLOSE frame with error code // CONNECTION_REFUSED." Silence would leave the client retransmitting its // Initial until its own timeout. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7709); const r = try Refusing.create(gpa, io, rng_impl.random(), .{ .max_connections = 1 }); defer r.destroy(gpa, io); // The one slot, taken by a client that has only just begun. var out: [quic.Connection.min_initial_datagram]u8 = undefined; var plain: [2048]u8 = undefined; const first: [8]u8 = @splat(0xd4); const first_source: [4]u8 = @splat(0x5f); try r.client.send(io, &r.socket.address, try sealInitial(&out, &first, &first_source, &.{})); const accepted = try awaitAnswer(io, &r.client, &first, &first_source, &plain); try testing.expect(accepted.frame.? != .connection_close); const second: [8]u8 = @splat(0xd5); const second_source: [4]u8 = @splat(0x60); try r.client.send(io, &r.socket.address, try sealInitial(&out, &second, &second_source, &.{})); const refused = try awaitAnswer(io, &r.client, &second, &second_source, &plain); const close = refused.frame.?.connection_close; try testing.expectEqual(@backingInt(quic.close.Code.connection_refused), close.error_code); } test "RFC 9000 13.4.2: an endpoint marks its datagrams ECT(0) on a new path" { // "The endpoint sets an ECT(0) codepoint in the IP header of early // outgoing packets sent on a new path to the peer." Two bits that no // packet carries a copy of, so the only way to assert this is to read // them off the IP header on the other side. if (!quic_io.ecn.available) return error.SkipZigTest; const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7707); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .rng = rng, .reset_key = @splat(0x4b), .token_key = @splat(0x4c), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); const parameters: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(¶meters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{})); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = parameters, .rng = rng, }); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); // The client end asks for the field too, which is the only way to see // what the server put there. quic_io.ecn.requestOnReceive(socket.handle); var out: [2048]u8 = undefined; while (try connection.send(&out, 0)) |datagram| { try socket.send(io, &server_address, datagram.bytes); } var data: [2048]u8 = undefined; var control: [256]u8 align(@alignOf(usize)) = undefined; var messages = [_]net.IncomingMessage{.{ .from = undefined, .data = &data, .control = &control, .flags = undefined, }}; const maybe_err, const count = socket.receiveManyTimeout(io, &messages, &data, .{}, .{ .duration = .{ .raw = .{ .nanoseconds = 2 * std.time.ns_per_s }, .clock = .awake }, }); if (maybe_err) |err| return err; try testing.expect(count > 0); // §13.4.2 again: ECT(0) "by default", and a path is testing from its // first datagram rather than after some warm-up -- so the server's very // first answer carries it. try testing.expectEqual( quic.ecn.Codepoint.ect0, quic_io.ecn.fromControl(messages[0].control), ); } /// Echoes each stream back, which is the smallest thing that exercises a /// blocking read and a blocking write on the same stream. const Echo = struct { io: Io, seen: std.atomic.Value(u32) = .init(0), fn serve(context: ?*anyopaque, session: *quic_io.Session) void { const e: *Echo = @ptrCast(@alignCast(context.?)); while (session.accept()) |stream| { var read_buffer: [512]u8 = undefined; var reader = stream.reader(&read_buffer); var body: [512]u8 = undefined; var collected: Io.Writer = .fixed(&body); // Reads until the peer ends its half, which is what a FIN // arriving as `EndOfStream` means here. _ = reader.interface.streamRemaining(&collected) catch {}; const got = collected.buffered(); var write_buffer: [512]u8 = undefined; var writer = stream.writer(&write_buffer); writer.interface.writeAll(got) catch {}; writer.finish() catch {}; _ = e.seen.fetchAdd(1, .monotonic); } } }; /// Answers without waiting for the peer to end its half, which is the shape /// a tunnel has and a request does not. const HalfOpen = struct { answered: std.atomic.Value(u32) = .init(0), fn serve(context: ?*anyopaque, session: *quic_io.Session) void { const h: *HalfOpen = @ptrCast(@alignCast(context.?)); while (session.accept()) |stream| { var read_buffer: [512]u8 = undefined; var reader = stream.reader(&read_buffer); // One `stream` call, and the choice matters. `readSliceShort` // keeps asking until the destination is full or the stream ends, // which is right for a message of known length and wrong for a // tunnel: the peer has not ended its half and is not going to, so // the second ask blocks until the idle timeout closes the // connection. What a tunnel wants is "whatever has arrived", and // that is one call. var got: [512]u8 = undefined; var into: Io.Writer = .fixed(&got); const n = reader.interface.stream(&into, .limited(got.len)) catch 0; if (n == 0) continue; var write_buffer: [512]u8 = undefined; var writer = stream.writer(&write_buffer); writer.interface.writeAll(got[0..n]) catch {}; writer.interface.flush() catch {}; // Deliberately not `finish`: a tunnel's sending half stays open. _ = h.answered.fetchAdd(1, .monotonic); } } }; test "quic_io: an answer on a stream whose halves are both still open" { // The shape RFC 9220's extended CONNECT needs, and the shape nothing else // here has: neither end finishes its sending half, and the exchange has // to work anyway. The sans-I/O suite has a test for this at the protocol // level; this is the same question of the loop, which is the layer that // has to notice there is something to send when nothing has ended. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x0ff0); const rng = rng_impl.random(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var half: HalfOpen = .{}; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x21), .token_key = @splat(0x22), .max_connections = 2, }, .{ .context = &half, .serveFn = HalfOpen.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); try halfOpenClient(io, gpa, server_address, rng); } /// Sends without ending its half, and waits for the answer. fn halfOpenClient(io: Io, gpa: std.mem.Allocator, to: net.IpAddress, rng: std.Random) !void { var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); const parameters: quic.parameters.Parameters = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(¶meters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{})); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = parameters, .rng = rng, }); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var asked = false; var steps: usize = 0; while (steps < 100) : (steps += 1) { const at: u64 = @intCast(@max( Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0, )); if (connection.isEstablished() and !asked) { const id = try connection.openBidirectional(); try connection.write(id, "neither half is ending"); // No `finishStream`. asked = true; } while (try connection.send(&out, at)) |datagram| { try socket.send(io, &to, datagram.bytes); } if (asked) { const id: quic.stream.Id = .{ .value = 0 }; const available = connection.readable(id); if (available.len > 0) { try testing.expectEqualStrings("neither half is ending", available); return; } } const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 200 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => { connection.onTimeout(at); continue; }, else => return err, }; try connection.receive(message.data, 0, at); } return error.NoAnswer; } test "a datagram wakes a task blocked on a stream" { const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x30f0); const rng = rng_impl.random(); // Port zero, so the kernel picks one and nothing in this test can collide // with anything else on the machine. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x11), .token_key = @splat(0x22), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); try client(io, gpa, server_address, rng); endpoint.stop(); try testing.expect(echo.seen.load(.monotonic) >= 1); } fn pump(endpoint: *quic_io.Endpoint) void { endpoint.pump() catch {}; } /// An ordinary sans-I/O client, driven by hand over a socket -- which is what /// the endpoint is being tested against. fn client(io: Io, gpa: std.mem.Allocator, to: net.IpAddress, rng: std.Random) !void { var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); const parameters: quic.parameters.Parameters = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_source_connection_id = &local_id, }; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(¶meters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{})); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = parameters, .rng = rng, }); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var asked = false; var answer: [128]u8 = undefined; var answer_len: usize = 0; var steps: usize = 0; while (steps < 64) : (steps += 1) { const at: u64 = @intCast(@max( Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0, )); if (connection.isEstablished() and !asked) { const id = try connection.openBidirectional(); try connection.write(id, "a datagram woke me"); try connection.finishStream(id); asked = true; } while (try connection.send(&out, at)) |datagram| { try socket.send(io, &to, datagram.bytes); } if (asked) { const id: quic.stream.Id = .{ .value = 0 }; const available = connection.readable(id); if (available.len > 0) { @memcpy(answer[0..available.len], available); answer_len = available.len; break; } } const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 200 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => { connection.onTimeout(at); continue; }, else => return err, }; try connection.receive(message.data, 0, at); } try testing.expectEqualStrings("a datagram woke me", answer[0..answer_len]); } test "the QUIC client against this library's own endpoint" { // `Endpoint` answers strangers and `Client` dials one, and what they // agree on is a `Session` -- so everything written against a session // works from either end, which is what an HTTP/3 client needs and what // this asserts before one is built on it. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x7708); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x51), .token_key = @splat(0x52), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: quic_io.Client = undefined; try dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, }); defer dialer.deinit(); // Its own task, because `Stream.Reader` below blocks until a datagram // arrives and this is what makes one arrive. Reading and pumping on one // task is a client waiting for itself. var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); // A handshake that completed is the whole claim: Initial keys derived // from an identifier this end invented, a certificate chain, ALPN, and // transport parameters crossed in both directions. try testing.expect(dialer.connection.isEstablished()); // And then a stream, which is what a session is for. `Echo` reads until // the peer ends its half and sends the same octets back. const stream = try dialer.session.openBidirectional(); var write_buffer: [128]u8 = undefined; var w = stream.writer(&write_buffer); try w.interface.writeAll("through a real handshake"); try w.finish(); var read_buffer: [128]u8 = undefined; var r = stream.reader(&read_buffer); var collected: [128]u8 = undefined; var sink: Io.Writer = .fixed(&collected); _ = r.interface.streamRemaining(&sink) catch {}; try testing.expectEqualStrings("through a real handshake", sink.buffered()); } test "stop ends the pump promptly while a quiet connection is open" { // A connection that has finished its handshake and gone quiet has // nothing due but its idle timeout, a minute here. The pump used to wait // for exactly that before it looked at `stop` again, so a listener with // one idle client took as long to shut down as the client was allowed to // stay silent. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x570b); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; const local: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 60_000, .active_connection_id_limit = 4, }; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = local, .rng = rng, .reset_key = @splat(0x61), .token_key = @splat(0x62), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: quic_io.Client = undefined; try dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .local = local, }); defer dialer.deinit(); var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); try testing.expect(dialer.connection.isEstablished()); // Long enough for the handshake's last acknowledgments to settle, so // that what is left is a connection with nothing to say. try io.sleep(.fromMilliseconds(200), .awake); const started = Io.Clock.Timestamp.now(io, .awake); endpoint.stop(); try group.await(io); try testing.expect(started.untilNow(io).raw.toMilliseconds() < 3000); } test "a handshake that is canceled says so, rather than blaming the socket" { // Against a socket that never answers, with a handshake allowed five // seconds: the task is canceled a tenth of a second in, and what comes // back has to be the cancelation and has to come back then. It used to be // `NetworkFailed`, which a caller with somewhere else to try reads as a // reason to try there. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0xca9c); const rng = rng_impl.random(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var silent = try bind.bind(io, .{ .mode = .dgram }); defer silent.close(io); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: quic_io.Client = undefined; const started = Io.Clock.Timestamp.now(io, .awake); var future = try io.concurrent(quic_io.Client.connect, .{ &dialer, io, gpa, &socket, silent.address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .handshake_timeout_ns = 5 * std.time.ns_per_s, } }); try io.sleep(.fromMilliseconds(100), .awake); if (future.cancel(io)) |_| { dialer.deinit(); return error.TestExpectedFailure; } else |err| try testing.expectEqual(error.Canceled, err); try testing.expect(started.untilNow(io).raw.toMilliseconds() < 2000); } test "a stream read that is canceled is heard at the next cancelation point" { // An `Io.Reader` can only say `ReadFailed`, so a read canceled while it // waits has no way to say why -- and a cancelation is delivered once. The // reader re-arms it instead, and this is the proof: the read fails, and // the sleep after it, which would otherwise take five seconds, is // canceled at once. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0xca9d); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; const local: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = local, .rng = rng, .reset_key = @splat(0x61), .token_key = @splat(0x62), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: quic_io.Client = undefined; try dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .local = local, }); defer dialer.deinit(); var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); // Written and not finished: `Echo` answers when the peer ends its half, // so this stream will be read from for as long as anybody cares to wait. const stream = try dialer.session.openBidirectional(); var write_buffer: [64]u8 = undefined; var w = stream.writer(&write_buffer); try w.interface.writeAll("never finished"); try w.interface.flush(); const started = Io.Clock.Timestamp.now(io, .awake); var future = try io.concurrent(readThenSleep, .{ stream, io }); try io.sleep(.fromMilliseconds(100), .awake); try testing.expectError(error.Canceled, future.cancel(io)); try testing.expect(started.untilNow(io).raw.toMilliseconds() < 2000); } fn readThenSleep(stream: quic_io.Stream, io: Io) !void { var buffer: [64]u8 = undefined; var r = stream.reader(&buffer); var byte: [1]u8 = undefined; if (r.interface.readSliceAll(&byte)) |_| { return error.TestUnexpectedResult; } else |err| switch (err) { error.ReadFailed => {}, else => |e| return e, } try io.sleep(.fromSeconds(5), .awake); return error.TestUnexpectedResult; } fn runClient(c: *quic_io.Client) void { c.run() catch {}; } /// `Echo`, and a note of who it was talking to and how many of those /// connections were resumed. const KeyEcho = struct { echo: Echo, peer: std.atomic.Value(?*const quic.tls.PublicKey) = .init(null), seen_key: quic.tls.PublicKey = undefined, resumed: std.atomic.Value(u32) = .init(0), fn serve(context: ?*anyopaque, session: *quic_io.Session) void { const k: *KeyEcho = @ptrCast(@alignCast(context.?)); if (session.waitEstablished()) { if (session.peerPublicKey()) |key| { k.seen_key = key; k.peer.store(&k.seen_key, .release); } if (session.tls.server.inner.resumed) _ = k.resumed.fetchAdd(1, .release); } Echo.serve(&k.echo, session); } }; test "RFC 7250: dialing a key rather than a name" { // The iroh shape, end to end over a socket: neither side has a // certificate or a name, the client dials the server's Ed25519 key, and // the server admits whichever client proves which key it holds. What // each learns is the other's key, and what the client learns is exactly // the key it dialed. const io = testing.io; const gpa = testing.allocator; const Ed25519 = std.crypto.sign.Ed25519; var rng_impl = std.Random.DefaultPrng.init(0x7250); const rng = rng_impl.random(); const server_key = try Ed25519.KeyPair.generateDeterministic(@splat(0x5e)); const client_key = try Ed25519.KeyPair.generateDeterministic(@splat(0xc1)); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; const local: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }; var handler: KeyEcho = .{ .echo = .{ .io = io } }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .raw_public_key = .{ .key_pair = server_key }, .local = local, .rng = rng, .reset_key = @splat(0x71), .token_key = @splat(0x72), .ticket_key = @splat(0x73), .max_connections = 6, }, .{ .context = &handler, .serveFn = KeyEcho.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); // Kept from the first connection for the last one to resume with. var ticket: quic.tls_handshake.Session = .{}; { const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: quic_io.Client = undefined; try dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, // No name at all, so no `server_name` goes out. .host = "", .raw_public_key = .{ .key_pair = client_key, .peer = server_key.public_key.toBytes(), }, .rng = rng, .local = local, .ticket = &ticket, }); defer dialer.deinit(); var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); try testing.expectEqualSlices( u8, &server_key.public_key.toBytes(), &dialer.connection.peerPublicKey().?, ); // A stream, so that the server's handler has certainly seen the // connection by the time the answer arrives. const stream = try dialer.session.openBidirectional(); var write_buffer: [64]u8 = undefined; var w = stream.writer(&write_buffer); try w.interface.writeAll("who is this"); try w.finish(); var read_buffer: [64]u8 = undefined; var r = stream.reader(&read_buffer); var collected: [64]u8 = undefined; var sink: Io.Writer = .fixed(&collected); _ = r.interface.streamRemaining(&sink) catch {}; try testing.expectEqualStrings("who is this", sink.buffered()); const seen = handler.peer.load(.acquire) orelse return error.TestExpectedPeerKey; try testing.expectEqualSlices(u8, &client_key.public_key.toBytes(), seen); // The server sends its ticket straight after the client's Finished, // ahead of any answer, so it is here by now -- naming the server's key. try testing.expect(ticket.valid); try testing.expectEqualSlices(u8, &server_key.public_key.toBytes(), &ticket.peer_public_key.?); try testing.expectEqual(0, handler.resumed.load(.acquire)); } { // Dialing a key the server does not hold. The server is reached and // answers; the client is the one that refuses, with §6.2 of RFC // 8446's `bad_certificate`. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); const stranger = try Ed25519.KeyPair.generateDeterministic(@splat(0x99)); var why: quic_io.Client.Diagnosis = .{}; var dialer: quic_io.Client = undefined; const result = dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "", .raw_public_key = .{ .key_pair = client_key, .peer = stranger.public_key.toBytes(), }, .rng = rng, .local = local, .handshake_timeout_ns = 5 * std.time.ns_per_s, .diagnosis = &why, }); // A key that is not the one dialed is a certificate refused, and // `connect` says so in the error itself. try testing.expectError(error.BadCertificate, result); try testing.expectEqual(@as(?u8, 42), why.alert()); // bad_certificate try testing.expect(!why.from_peer); } { // A certificate client, which offers nothing a raw-key endpoint can // use. RFC 7250 section 4.2's `unsupported_certificate`, from the // server's side this time. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var why: quic_io.Client.Diagnosis = .{}; var dialer: quic_io.Client = undefined; const result = dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .local = local, .handshake_timeout_ns = 5 * std.time.ns_per_s, .diagnosis = &why, }); // A certificate alert, so a certificate error -- but `from_peer` is // what says it was the server that would not have it. try testing.expectError(error.BadCertificate, result); try testing.expectEqual(@as(?u8, 43), why.alert()); // unsupported_certificate try testing.expect(why.from_peer); } { // Resuming the first connection's session. No certificate of either // kind goes by, and each end still knows the other's key: the client // from the ticket it kept, the server from the one it sealed. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); handler.peer.store(null, .release); var dialer: quic_io.Client = undefined; try dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "", .raw_public_key = .{ .key_pair = client_key, .peer = server_key.public_key.toBytes(), }, .rng = rng, .local = local, .ticket = &ticket, }); defer dialer.deinit(); var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); try testing.expect(dialer.session.tls.client.inner.resumed); try testing.expectEqualSlices( u8, &server_key.public_key.toBytes(), &dialer.connection.peerPublicKey().?, ); const stream = try dialer.session.openBidirectional(); var write_buffer: [64]u8 = undefined; var w = stream.writer(&write_buffer); try w.interface.writeAll("and again"); try w.finish(); var read_buffer: [64]u8 = undefined; var r = stream.reader(&read_buffer); var collected: [64]u8 = undefined; var sink: Io.Writer = .fixed(&collected); _ = r.interface.streamRemaining(&sink) catch {}; try testing.expectEqualStrings("and again", sink.buffered()); const seen = handler.peer.load(.acquire) orelse return error.TestExpectedPeerKey; try testing.expectEqualSlices(u8, &client_key.public_key.toBytes(), seen); try testing.expectEqual(1, handler.resumed.load(.acquire)); } } test "a handshake that fails says which way it failed" { // The other half of `classify`, which is a table: this is a real client // against a real server, ending the two ways a handshake ends when it is // not the network's fault -- a certificate this end will not take, and a // protocol the other end will not speak. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x4a8); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ // One protocol, and not the one the second client below asks for. .alpn = &.{"echo"}, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x61), .token_key = @splat(0x62), .max_connections = 4, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); { // A server that authenticates nobody, met by a client that actually // verifies. The endpoint above has `auth` null -- no use on a network, // and what the rest of this file wants -- so no Certificate arrives at // all, and what the client objects to is the message that came instead. // // The assertion worth having is the *negative* one: this is a handshake // that went wrong and not a certificate that was refused, so it must // not be reported as one. §6.2 of RFC 8446's `unexpected_message` is // outside the certificate alerts and stays outside them. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var why: quic_io.Client.Diagnosis = .{}; var dialer: quic_io.Client = undefined; const result = dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", // The whole of what this half turns on, and the default. .insecure_skip_verify = false, .rng = rng, .handshake_timeout_ns = 5 * std.time.ns_per_s, .diagnosis = &why, }); try testing.expectError(error.HandshakeFailed, result); // And the account of it, which the error deliberately does not carry: // §20.1's CRYPTO_ERROR with TLS's own alert inside it. try testing.expectEqual(@as(?u8, 10), why.alert()); // unexpected_message try testing.expectEqual(quic.close.Code.crypto(10), why.code.?); // This end decided it, so there is nothing from the peer to report. try testing.expect(!why.from_peer); try testing.expect(!why.application); } { // The other end refusing us, which is not about a certificate at all: // §3.1 of RFC 9114 and §4.1.2 of RFC 9250 both rest on ALPN, and a // server with nothing in common closes with `no_application_protocol`. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var why: quic_io.Client.Diagnosis = .{}; var dialer: quic_io.Client = undefined; const result = dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"doq"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .handshake_timeout_ns = 5 * std.time.ns_per_s, .diagnosis = &why, }); try testing.expectError(error.HandshakeFailed, result); // Alert 120, and the fact that makes it legible: the *peer* said so. // A client that reported this as a bad certificate would be blaming // the wrong end for a disagreement about protocols. try testing.expectEqual(@as(?u8, 120), why.alert()); try testing.expect(why.from_peer); } } test "a diagnosis is cleared by the connect that fills it" { // A caller that keeps one across attempts must not be reading the last // one's answer, and the only place that can be arranged is here. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x4a9); const rng = rng_impl.random(); var why: quic_io.Client.Diagnosis = .{ .code = .crypto(48), .from_peer = true }; const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); // 127.0.0.1 with nothing bound: an ICMP port unreachable or silence, // either of which is a handshake that never finished rather than one that // ended with a code. const nowhere: net.IpAddress = try .parse("127.0.0.1", 1); var dialer: quic_io.Client = undefined; const result = dialer.connect(io, gpa, &socket, nowhere, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .handshake_timeout_ns = 200 * std.time.ns_per_ms, .diagnosis = &why, }); if (result) |_| { dialer.deinit(); return error.TestExpectedFailure; } else |err| switch (err) { error.HandshakeTimeout, error.NetworkFailed => {}, else => return err, } // Nothing closed the connection, so there is no code -- and the stale one // is gone rather than being read as this attempt's. try testing.expectEqual(@as(?quic.close.Code, null), why.code); try testing.expectEqual(@as(?u8, null), why.alert()); try testing.expect(!why.from_peer); } test "RFC 9000 8.1: a client against an endpoint that demands a Retry" { // Address validation, end to end, which nothing exercised before: the // endpoint answers the first Initial with a Retry, the client sends the // token back, and the handshake carries on. // // It did not, and the reason is worth keeping: the token is sealed against // the client's address, `addressBytes` took that address as the bytes of // the `net.IpAddress` union itself, and those bytes include the arm that is // not in use -- whatever was last on that stack. Two calls for one client // disagreed, every retried Initial failed to open its own token, and // `offerRetry` answers a token that does not open with silence. So the // handshake stalled until the idle timeout, which is the hardest kind of // failure to read: nothing is refused, nothing is logged, and both ends // think they are waiting for the other. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x8801); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, .rng = rng, .reset_key = @splat(0x71), .token_key = @splat(0x72), .max_connections = 2, // §8.1: every client proves its address before the handshake goes on, // which is what a busy public server does and what Quad9 does. .require_retry = true, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var why: quic_io.Client.Diagnosis = .{}; var dialer: quic_io.Client = undefined; dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .handshake_timeout_ns = 5 * std.time.ns_per_s, .diagnosis = &why, .local = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }, }) catch |err| { // The diagnosis is in the failure message because a stall says so // little on its own: an idle timeout arrives as `.no_error` from this // end, which is what a handshake that was never refused looks like. std.debug.print("connect failed: {t} code={?} from_peer={} reason='{s}'\n", .{ err, why.code, why.from_peer, why.reason(), }); return err; }; defer dialer.deinit(); var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); try testing.expect(dialer.connection.isEstablished()); const stream = try dialer.session.openBidirectional(); var write_buffer: [128]u8 = undefined; var w = stream.writer(&write_buffer); try w.interface.writeAll("after a retry"); try w.finish(); var read_buffer: [128]u8 = undefined; var r = stream.reader(&read_buffer); var collected: [128]u8 = undefined; var sink: Io.Writer = .fixed(&collected); _ = r.interface.streamRemaining(&sink) catch {}; try testing.expectEqualStrings("after a retry", sink.buffered()); } /// Gives up as soon as the handshake does, the way `doqd`'s handler does, and /// says when it has returned. const GiveUp = struct { returned: std.atomic.Value(bool) = .init(false), fn serve(context: ?*anyopaque, session: *quic_io.Session) void { const g: *GiveUp = @ptrCast(@alignCast(context.?)); _ = session.waitEstablished(); g.returned.store(true, .release); } }; test "RFC 9000 10.2: a handler that gives up does not take the closing period with it" { // A raw-key endpoint admitting only another client refuses this one, and // its handler, finding no connection, returns at once. The connection is // closing, and §10.2.1 wants it to stay that way for a while and answer // the peer's stragglers by repeating the CONNECTION_CLOSE. The slot used // to be let go the moment the handler returned -- so a client that had // already sent its first stream data got a stateless reset for it, which // is how iroh, on a slow enough machine, reported "reset by peer" instead // of the bad_certificate it was refused with. const io = testing.io; const gpa = testing.allocator; const Ed25519 = std.crypto.sign.Ed25519; var rng_impl = std.Random.DefaultPrng.init(0x1021); const rng = rng_impl.random(); const server_key = try Ed25519.KeyPair.generateDeterministic(@splat(0x5e)); const client_key = try Ed25519.KeyPair.generateDeterministic(@splat(0xc1)); const admitted = try Ed25519.KeyPair.generateDeterministic(@splat(0xad)); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; var handler: GiveUp = .{}; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .raw_public_key = .{ .key_pair = server_key, .peer = admitted.public_key.toBytes() }, .rng = rng, .reset_key = @splat(0x81), .token_key = @splat(0x82), .max_connections = 2, }, .{ .context = &handler, .serveFn = GiveUp.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var dialer: quic_io.Client = undefined; const result = dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "", .raw_public_key = .{ .key_pair = client_key, .peer = server_key.public_key.toBytes() }, .rng = rng, .handshake_timeout_ns = 5 * std.time.ns_per_s, }); if (result) |_| { // The client's own handshake can finish before the server's refusal // lands; either way the server has refused it. dialer.deinit(); } else |_| {} // Once the handler has returned, the connection it gave up on is still // in its slot and still closing -- not freed, and not yet closed. var waited: usize = 0; while (!handler.returned.load(.acquire)) : (waited += 1) { if (waited > 200) return error.TestHandlerNeverReturned; try io.sleep(.fromMilliseconds(10), .awake); } var closing: usize = 0; for (endpoint.sessions) |*s| { if (!s.in_use) continue; if (s.serving.load(.acquire)) continue; const state = s.closeState() orelse continue; if (state == .closing or state == .draining) closing += 1; } try testing.expectEqual(1, closing); } test "draft-ietf-quic-multipath-21 3.1: an endpoint accepts a second path from a second socket" { // A client with two sockets -- two 4-tuples, as a second interface would // give it -- opens path 1 from the second. The endpoint has room for two // paths and allows path ID 1; it takes the new identifier as the path // opening, validates the new address, and answers the request that // arrived over it. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x3e20); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; const limits: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_max_path_id = 1, }; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = limits, .sizes = .{ .paths = 2 }, .rng = rng, .reset_key = @splat(0x91), .token_key = @splat(0x92), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); // Two sockets: route 0 and route 1. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var sockets = [_]net.Socket{ try bind.bind(io, .{ .mode = .dgram }), try bind.bind(io, .{ .mode = .dgram }) }; defer for (&sockets) |*s| s.close(io); var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); var client_parameters = limits; client_parameters.initial_source_connection_id = &local_id; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(&client_parameters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{ .paths = 2 })); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = limits, .rng = rng, }); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var opened = false; var asked = false; var answered: ?[]const u8 = null; var steps: usize = 0; while (steps < 2000 and answered == null) : (steps += 1) { const at: u64 = @intCast(@max(Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0)); // Once the handshake is done and the endpoint's identifier for path 1 // has arrived, open the path from the second socket; once it is // validated, ask over it. if (connection.isEstablished() and !opened) { if (connection.openPath(1, at)) |_| opened = true else |_| {} } if (opened and !asked) { if (connection.useSendPath(1)) |_| { const id = try connection.openBidirectional(); try connection.write(id, "which path is this"); try connection.finishStream(id); asked = true; } else |_| {} } while (try connection.send(&out, at)) |datagram| { try sockets[datagram.path].send(io, &server_address, datagram.bytes); } if (asked) { const reply = connection.readable(.{ .value = 0 }); if (reply.len == "which path is this".len) answered = reply; } for (&sockets, 0..) |*socket, route| { const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 5 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => continue, else => return err, }; try connection.receive(message.data, @intCast(route), at); } connection.onTimeout(at); } try testing.expectEqualStrings("which path is this", answered orelse return error.TestNoAnswer); // The request went over path 1: the client numbered packets there, and // the endpoint's connection has path 1 open over its second address. try testing.expect(connection.extra[0].space.next_number > 0); var server_has_path: bool = false; for (endpoint.sessions) |*s| { if (!s.in_use) continue; s.mutex.lockUncancelable(io); defer s.mutex.unlock(io); if (s.connection.extra[0].state == .open) server_has_path = true; } try testing.expect(server_has_path); } test "RFC 9000 9.5: an endpoint follows a client onto a connection ID it issued later" { // A client that migrates moves to a connection ID it has not used before // -- "an endpoint MUST NOT reuse a connection ID when sending from more // than one local address" -- which is one the server issued with // NEW_CONNECTION_ID after the handshake. The endpoint used to route only // by the handshake's identifier, so after a migration nothing the client // sent reached its connection at all. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x95); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; const limits: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, }; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = limits, .rng = rng, .reset_key = @splat(0x95), .token_key = @splat(0x96), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var sockets = [_]net.Socket{ try bind.bind(io, .{ .mode = .dgram }), try bind.bind(io, .{ .mode = .dgram }) }; defer for (&sockets) |*s| s.close(io); var local_id: [8]u8 = undefined; rng.bytes(&local_id); var destination: [8]u8 = undefined; rng.bytes(&destination); var client_parameters = limits; client_parameters.initial_source_connection_id = &local_id; var encoded: [256]u8 = undefined; const written = try quic.parameters.write(&client_parameters, &encoded, .client); var tls_client: quic.tls_handshake.Client = try .init(.{ .host = "endpoint.example", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"echo"}, .transport_parameters = written, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); const connection = try gpa.create(quic.Connection); defer gpa.destroy(connection); const memory = try gpa.create(quic.Connection.Storage(.{})); defer gpa.destroy(memory); connection.init(.{ .memory = memory.memory(), .role = .client, .handshake = tls_client.handshake(), .local_id = &local_id, .destination_id = &destination, .local = limits, .rng = rng, }); const origin = Io.Timestamp.now(io, .awake); var out: [2048]u8 = undefined; var in: [2048]u8 = undefined; var migrated = false; var asked = false; var answered: ?[]const u8 = null; var steps: usize = 0; var established_at: ?usize = null; while (steps < 2000 and answered == null) : (steps += 1) { const at: u64 = @intCast(@max(Io.Timestamp.now(io, .awake).nanoseconds - origin.nanoseconds, 0)); if (connection.isEstablished() and established_at == null) established_at = steps; // A few rounds after the handshake, by when the server's // NEW_CONNECTION_ID frames have arrived. if (!migrated and established_at != null and steps > established_at.? + 5) { try connection.migrateTo(1, at); migrated = true; } if (migrated and !asked and connection.paths.find(1).?.validated) { const id = try connection.openBidirectional(); try connection.write(id, "after moving"); try connection.finishStream(id); asked = true; } while (try connection.send(&out, at)) |datagram| { try sockets[datagram.path].send(io, &server_address, datagram.bytes); } if (asked) { const reply = connection.readable(.{ .value = 0 }); if (reply.len == "after moving".len) answered = reply; } for (&sockets, 0..) |*socket, route| { const message = socket.receiveTimeout(io, &in, .{ .duration = .{ .raw = .{ .nanoseconds = 5 * std.time.ns_per_ms }, .clock = .awake, } }) catch |err| switch (err) { error.Timeout => continue, else => return err, }; try connection.receive(message.data, @intCast(route), at); } connection.onTimeout(at); } try testing.expect(migrated); try testing.expectEqualStrings("after moving", answered orelse return error.TestNoAnswer); } test "draft-ietf-quic-multipath-21 3.1: io.Client opens a second path from a second socket" { // The same thing as the test above, through the client's own API rather // than a connection driven by hand: `openPath` takes a second socket, // reads it on a task of its own, and the path is used once validated. const io = testing.io; const gpa = testing.allocator; var rng_impl = std.Random.DefaultPrng.init(0x3e21); const rng = rng_impl.random(); const bind_server: net.IpAddress = try .parse("127.0.0.1", 0); var server_socket = try bind_server.bind(io, .{ .mode = .dgram }); defer server_socket.close(io); const server_address = server_socket.address; const limits: quic.parameters.Parameters = .{ .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = quic.Connection.stream_buffer, .initial_max_stream_data_bidi_remote = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4, .initial_max_path_id = 1, }; var echo: Echo = .{ .io = io }; var endpoint = try quic_io.Endpoint.init(io, gpa, &server_socket, .{ .alpn = &.{"echo"}, .local = limits, .sizes = .{ .paths = 2 }, .rng = rng, .reset_key = @splat(0x93), .token_key = @splat(0x94), .max_connections = 2, }, .{ .context = &echo, .serveFn = Echo.serve }); defer endpoint.deinit(); var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, pump, .{&endpoint}); defer endpoint.stop(); const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); var second = try bind.bind(io, .{ .mode = .dgram }); defer second.close(io); var dialer: quic_io.Client = undefined; try dialer.connect(io, gpa, &socket, server_address, .{ .alpn = &.{"echo"}, .host = "endpoint.example", .insecure_skip_verify = true, .rng = rng, .local = limits, .sizes = .{ .paths = 2 }, }); defer dialer.deinit(); var client_tasks: Io.Group = .init; defer client_tasks.cancel(io); try client_tasks.concurrent(io, runClient, .{&dialer}); defer dialer.stop(); // The server's identifier for path 1 comes just after the handshake, so // the first attempt may find nothing to open the path with yet. var attempts: usize = 0; const opened = while (true) : (attempts += 1) { if (dialer.openPath(&second)) |opened| break opened else |err| { if (err != error.NoPathAvailable or attempts > 100) return err; try io.sleep(.fromMilliseconds(10), .awake); } }; try testing.expectEqual(@as(u32, 1), opened.id); attempts = 0; while (!dialer.pathReady(opened)) : (attempts += 1) { if (attempts > 200) return error.PathNotValidated; try io.sleep(.fromMilliseconds(10), .awake); } try dialer.session.useSendPath(opened.id); const stream = try dialer.session.openBidirectional(); var write_buffer: [128]u8 = undefined; var w = stream.writer(&write_buffer); try w.interface.writeAll("over the client's second socket"); try w.finish(); var read_buffer: [128]u8 = undefined; var r = stream.reader(&read_buffer); var collected: [128]u8 = undefined; var sink: Io.Writer = .fixed(&collected); _ = r.interface.streamRemaining(&sink) catch {}; try testing.expectEqualStrings("over the client's second socket", sink.buffered()); // The request left by path 1, and the answer came back on it: the // client numbered packets in path 1's space, and read the server's. dialer.session.mutex.lockUncancelable(io); defer dialer.session.mutex.unlock(io); try testing.expect(dialer.connection.extra[0].space.next_number > 0); try testing.expect(!dialer.connection.extra[0].space.acks.isEmpty()); } /// Dials a server that never answers, once `go` is set, and says what the /// handshake returned. const SilentDial = struct { go: Io.Event = .unset, server: net.IpAddress, fn dial(d: *SilentDial) anyerror!void { const io = testing.io; // Bound first, since binding is a cancelation point too. const bind: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try bind.bind(io, .{ .mode = .dgram }); defer socket.close(io); // Not a cancelation point: the cancel asked for meanwhile stays // pending, for whatever `connect` does first that is one -- sending // the first Initial. d.go.waitUncancelable(io); var rng_impl = std.Random.DefaultPrng.init(0x5117); var dialer: quic_io.Client = undefined; try dialer.connect(io, testing.allocator, &socket, d.server, .{ .alpn = &.{"echo"}, .host = "silent.example", .insecure_skip_verify = true, .rng = rng_impl.random(), .local = .{ .initial_max_streams_bidi = 1 }, .handshake_timeout_ns = 2 * std.time.ns_per_s, }); dialer.deinit(); } fn release(d: *SilentDial) Io.Cancelable!void { try testing.io.sleep(.fromMilliseconds(50), .awake); d.go.set(testing.io); } }; test "a cancel that lands on a send is not lost" { // Found by zig-dns-client's test of canceling a DNS over QUIC query in // the handshake, which failed only on a slow machine: a send that // returned `error.Canceled` was taken for a socket that will not carry // any more, the cancel with it, and the handshake waited out its whole // timeout instead. Here the cancel is asked for before the first send, // so that it is the send that meets it every time. const io = testing.io; const wildcard: net.IpAddress = try .parse("127.0.0.1", 0); var silent = try wildcard.bind(io, .{ .mode = .dgram }); defer silent.close(io); var d: SilentDial = .{ .server = silent.address }; var dialing = try io.concurrent(SilentDial.dial, .{&d}); var releasing = try io.concurrent(SilentDial.release, .{&d}); defer releasing.cancel(io) catch {}; const started = Io.Clock.Timestamp.now(io, .awake); try testing.expectError(error.Canceled, dialing.cancel(io)); try testing.expect(started.untilNow(io).raw.toMilliseconds() < 1000); }