Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! For tests only: an `Endpoint` on loopback with a `Client` already//! connected to it, so that a doctest can show the one call it documents//! rather than the page of setup it takes to reach a live connection.//!//! Nothing outside a `test` block refers to this file, so a normal build never//! compiles it, and `root.zig` does not export it.
const std = @import("std");const Io = std.Io;const net = Io.net;const testing = std.testing;
const quic = @import("quic");const Endpoint = @import("Endpoint.zig");const Client = @import("Client.zig");const Session = @import("Session.zig");const Stream = @import("Stream.zig");
/// The transport parameters both ends offer unless a test says otherwise:/// room for a few streams each way, and an idle timeout long enough that no/// test meets it.pub 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_stream_data_uni = quic.Connection.stream_buffer, .initial_max_streams_bidi = 4, .initial_max_streams_uni = 4, .max_idle_timeout = 5_000, .active_connection_id_limit = 4,};
pub const Options = struct { /// What both ends offer. local: quic.parameters.Parameters = local, /// What both ends are given. sizes: quic.Connection.Sizes = .{}, /// The server's handler, or null for `echo`. serve: ?Endpoint.Serve = null, /// Whether `Client.run` gets a task. Off for a test that pumps the client /// itself with `once`. run: bool = true,};
/// A client and a server, connected. In place, since both hold pointers into/// it; `start` brings it up and `stop` takes it down.pub const Pair = struct { prng: std.Random.DefaultPrng, server_socket: net.Socket, client_socket: net.Socket, endpoint: Endpoint, client: Client, /// Whether `client` and `client_socket` exist, which they do not after /// `listen` alone. dialed: bool = false, /// The endpoint's pump. pumps: Io.Group = .init, /// The client's `run`, when `Options.run` asked for one. runs: Io.Group = .init,
/// `listen`, then `dial`. pub fn start(p: *Pair, options: Options) !void { try p.listen(options); errdefer p.stop(); try p.dial(options); }
/// Brings up the server half alone, with its pump running, for a test /// that dials it some other way. `stop` takes it down. pub fn listen(p: *Pair, options: Options) !void { const io = testing.io; const gpa = testing.allocator; p.* = .{ .prng = .init(0x9a17), .server_socket = undefined, .client_socket = undefined, .endpoint = undefined, .client = undefined, }; const loopback: net.IpAddress = try .parse("127.0.0.1", 0);
p.server_socket = try loopback.bind(io, .{ .mode = .dgram }); errdefer p.server_socket.close(io); p.endpoint = try .init(io, gpa, &p.server_socket, .{ .alpn = &.{"test"}, .local = options.local, .sizes = options.sizes, .rng = p.prng.random(), .reset_key = @splat(0x31), .token_key = @splat(0x32), .max_connections = 4, }, options.serve orelse .{ .context = null, .serveFn = echo }); errdefer p.endpoint.deinit(); try p.pumps.concurrent(io, pump, .{&p.endpoint}); }
/// Connects `client` to the server `listen` started. fn dial(p: *Pair, options: Options) !void { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); p.client_socket = try loopback.bind(io, .{ .mode = .dgram }); errdefer p.client_socket.close(io); try p.client.connect(io, testing.allocator, &p.client_socket, p.server_socket.address, .{ .alpn = &.{"test"}, .host = "pair.example", .insecure_skip_verify = true, .rng = p.prng.random(), .local = options.local, .sizes = options.sizes, }); p.dialed = true; if (options.run) try p.runs.concurrent(io, run, .{&p.client}); }
/// Takes both ends down without waiting a turn for either loop to notice: /// a cancelation ends a wait for a datagram at once, where `stop` alone is /// looked at only between turns. pub fn stop(p: *Pair) void { const io = testing.io; if (p.dialed) { p.client.stop(); p.runs.cancel(io); p.client.deinit(); p.client_socket.close(io); } p.endpoint.stop(); p.pumps.cancel(io); p.endpoint.deinit(); p.server_socket.close(io); }
/// The client's end of the connection. pub fn session(p: *Pair) *Session { return p.client.session; }};
/// `Endpoint.pump`, in the shape a task wants.pub fn pump(endpoint: *Endpoint) void { endpoint.pump() catch {};}
/// A server handler that does nothing, for an endpoint nobody connects to.pub fn ignore(_: ?*anyopaque, _: *Session) void {}
/// `echo`, as a server handler.pub const echo_server: Endpoint.Serve = .{ .context = null, .serveFn = echo };
fn run(client: *Client) void { client.run() catch {};}
/// Sends each stream's octets back on it, once the peer has finished sending.fn echo(_: ?*anyopaque, session: *Session) void { while (session.accept()) |stream| { var read_buffer: [256]u8 = undefined; var reader = stream.reader(&read_buffer); var body: [16 * 1024]u8 = undefined; var collected: Io.Writer = .fixed(&body); _ = reader.interface.streamRemaining(&collected) catch {};
var writer = stream.writer(&.{}); writer.interface.writeAll(collected.buffered()) catch {}; writer.finish() catch {}; }}
/// Writes `request` on a new bidirectional stream, ends it, and reads the/// answer into `into`.pub fn exchange(session: *Session, request: []const u8, into: []u8) ![]const u8 { const stream = try session.openBidirectional(); var writer = stream.writer(&.{}); try writer.interface.writeAll(request); try writer.finish();
var read_buffer: [256]u8 = undefined; var reader = stream.reader(&read_buffer); var sink: Io.Writer = .fixed(into); _ = try reader.interface.streamRemaining(&sink); return sink.buffered();}
/// `local`, with draft-ietf-quic-multipath-21 switched on and room for one/// path past path 0. Pass `.sizes = .{ .paths = 2 }` with it.pub const multipath: quic.parameters.Parameters = blk: { var p = local; p.initial_max_path_id = 1; break :blk p;};
/// A server handler that opens a unidirectional stream, says "hello" on it,/// and then holds the connection open until it is told to stop.pub const greeter: Endpoint.Serve = .{ .context = null, .serveFn = greet };
fn greet(_: ?*anyopaque, session: *Session) void { if (!session.waitEstablished()) return; const stream = session.openUnidirectional() catch return; var writer = stream.writer(&.{}); writer.interface.writeAll("hello") catch return; writer.finish() catch return; // Returning would close the connection, and what is still in flight // with it. while (session.accept()) |_| {}}
/// A server handler that sends each RFC 9221 datagram back as it came.pub const datagram_echo: Endpoint.Serve = .{ .context = null, .serveFn = echoDatagrams };
fn echoDatagrams(_: ?*anyopaque, session: *Session) void { var buffer: [1200]u8 = undefined; while (session.readDatagram(&buffer)) |datagram| { session.sendDatagram(datagram) catch {}; }}
/// Opens a second path from `socket` with `Client.openPath` and waits until/// it has been validated. The server's connection ID for the path arrives/// just after the handshake, so the first attempts may find nothing to open/// it with.pub fn openValidatedPath(p: *Pair, socket: *net.Socket) !Client.Opened { const io = testing.io; var attempts: usize = 0; const opened = while (true) : (attempts += 1) { if (p.client.openPath(socket)) |opened| break opened else |err| { if (err != error.NoPathAvailable or attempts > 200) return err; try io.sleep(.fromMilliseconds(5), .awake); } }; attempts = 0; while (!p.client.pathReady(opened)) : (attempts += 1) { if (attempts > 400) return error.PathNotValidated; try io.sleep(.fromMilliseconds(5), .awake); } return opened;}