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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A QUIC server: one UDP socket, a table of connections, and the loop that//! keeps them running.//!//! What it does that a caller would otherwise write again is all of the same//! shape -- it is the bookkeeping between a socket, which knows about//! addresses and datagrams, and `quic.Connection`, which knows about neither.//! Routing a datagram to a connection by the identifier in its header (§5.1),//! firing a timer while the socket is quiet (§10.1 and RFC 9002), answering a//! packet for a connection that no longer exists (§10.3), and making an//! unverified address prove itself before any state is kept for it (§8.1).//!//! ## One task, and then one per connection//!//! `pump` is the task that owns the socket. It reads datagrams, routes them,//! and fires timers; it never runs application code. Each accepted connection//! gets a task of its own, running whatever the caller gave as `serve`, and//! that task talks to the connection through `Session` -- blocking reads and//! writes, with the lock and the condition underneath.//!//! Where the `Io` cannot provide concurrency there is nowhere for those tasks//! to run, and `pump` says so rather than serving one connection for ever.
const std = @import("std");const Io = std.Io;const net = Io.net;const Allocator = std.mem.Allocator;
const quic = @import("quic");const Session = @import("Session.zig");const ecn = @import("ecn.zig");
const Endpoint = @This();
/// How many connections one endpoint holds at once.////// Bounded like everything else here, and for the same reason: a connection/// costs a `quic.Connection` and every buffer it will ever need, furnished/// when its slot is first claimed and kept afterwards, so this number times/// that is the most memory an endpoint will ever commit. Decided by the/// caller rather than by whoever is sending it datagrams.pub const default_max_connections = 64;
pub const Options = struct { /// The certificate and key this endpoint authenticates itself with. /// /// Optional because the TLS backend's is: a server with none completes a /// handshake that authenticates nobody, which is no use on a network and /// is exactly what a test wants, since generating a certificate to prove /// that a datagram reached a stream is a great deal of ceremony for a /// question that has nothing to do with certificates. auth: ?*quic.tls_handshake.CertKeyPair = null, /// RFC 7250: authenticate with a raw Ed25519 key instead of `auth`, and /// require every client to authenticate with one of its own. /// /// `peer` may name the one client this endpoint will talk to; left null, /// any client that proves which key it holds is admitted, and /// `Connection.peerPublicKey` says which. With a `ticket_key` it resumes /// too: the client's key is sealed into each ticket, since a resumed /// handshake has no CertificateRequest to learn it from, and only a /// ticket naming an admitted client is taken back. raw_public_key: ?quic.tls_handshake.RawPublicKey = null, /// §8.1 of RFC 9001: "endpoints MUST use ALPN". What is offered here is /// what a client has to choose from. alpn: []const []const u8, /// What this endpoint advertises in its transport parameters. The /// connection-ID fields are filled in per connection and whatever is set /// here for them is ignored. local: quic.parameters.Parameters = .{}, /// Randomness for connection IDs, stateless reset tokens, Retry tokens /// and the TLS handshake. Everything unguessable in QUIC comes from here. rng: std.Random, /// §10.3.2: the static key stateless reset tokens are derived from. /// Static on purpose -- a key that survives a restart gives the same /// token after a crash as before it, which is the whole point of a reset /// that needs no state. reset_key: quic.stateless_reset.Key, /// §8.1.4: the key Retry tokens are sealed with. token_key: quic.retry.Token.Key, /// How much memory each connection is given, and so what each may /// promise. See `quic.Connection.Sizes`: the defaults are what a /// connection had when these were constants, and raising them is what /// buys throughput on a fast path. /// /// Paid once for every slot that has ever carried a connection -- see /// `Session.provisioned` -- so up to `max_connections` times over, and /// the arithmetic to do before raising them is per-stream size times /// sixteen streams times the most connections that will be alive at /// once. sizes: quic.Connection.Sizes = .{}, /// The largest send window a connection may be grown to, or null to /// leave every connection at `sizes.send_window`. /// /// What a send window buys is `window / round-trip`, so the right one /// depends on a path this endpoint cannot know in advance: the same /// server answers a peer across a datacenter, where a few kilobytes is /// already past the bandwidth-delay product, and one across an ocean, /// where it is a hundredth of it. Setting `sizes.send_window` for the /// second means every connection of the first kind pays for it, and the /// bill is per stream. /// /// So the window starts small and is raised only for a connection that /// demonstrates it can use one -- see `Connection.bufferBound` for what /// counts as a demonstration, which is deliberately narrow: a stream /// held back by the path or by what the peer has granted is not one a /// larger buffer would help. A connection that never shows the signal /// never costs more than the default. max_send_window: ?usize = null, /// §4.6.1 of RFC 8446: the key session tickets are sealed with, or null /// to issue none and resume nothing. ticket_key: ?quic.tls_handshake.TicketKey = null, /// §4.6 of RFC 9001: whether to accept 0-RTT. Off by default because /// §9.2 makes it the application's decision -- early data can be /// replayed, so it is only safe for a request the application is willing /// to answer twice. early_data: bool = false, /// §8.1: whether to make every client prove its address with a Retry /// before keeping any state for it. Costs the client a round trip and /// costs this endpoint nothing, which is the asymmetry an amplification /// attack depends on, reversed. require_retry: bool = false, /// How many connections to hold at once. max_connections: usize = default_max_connections, /// How long the connection IDs this endpoint issues are. /// /// One length for all of them, and it has to be known rather than read: /// §5.1 puts no length field in a short header, because "the length of /// the Destination Connection ID field is expected to be known to /// endpoints" -- and an endpoint knows because it chose. Everything that /// reads an identifier off a packet addressed here reads exactly this /// many octets, including §10.3's reset, which is answering a packet for /// a connection it has no record of and so has nothing else to go on. connection_id_len: usize = 8,};
/// What an accepted connection is handed to.////// Called on a task of its own, once per connection, and returns when it is/// finished with it. Everything it does goes through `Session`.////// Returning is the end of the connection: one still open is closed then,/// with an application close carrying code zero, and one already closing is/// left to finish closing. A handler wanting to say something else in the/// close says it with `Session.closeApplication` before it returns.pub const Serve = struct { context: ?*anyopaque, serveFn: *const fn (context: ?*anyopaque, session: *Session) void,
/// Runs the handler on `session`, on the caller's task, and returns when /// it does. What `Endpoint` does once per connection, on a task of the /// connection's own. pub fn call(s: Serve, session: *Session) void { s.serveFn(s.context, session); }
test call { // A handler with state of its own, reached through `context`. const Counter = struct { served: usize = 0,
fn serve(context: ?*anyopaque, _: *Session) void { const counter: *@This() = @ptrCast(@alignCast(context.?)); counter.served += 1; } }; var counter: Counter = .{}; const serve: Serve = .{ .context = &counter, .serveFn = Counter.serve };
var session: Session = undefined; serve.call(&session); try testing.expectEqual(@as(usize, 1), counter.served); }};
io: Io,gpa: Allocator,socket: *net.Socket,options: Options,serve: Serve,origin: Io.Timestamp,sessions: []Session,tasks: Io.Group,/// Set when `stop` is called, so that a pump in its own task can be ended/// from outside it. Written by one task and read by another, hence atomic.stopping: std.atomic.Value(bool) = .init(false),
/// An endpoint answering on `socket`, which it does not own: the socket has/// to be bound already, and has to outlive the endpoint.////// Allocates the table of `options.max_connections` slots from `gpa` and/// nothing else -- a connection's buffers are allocated when a slot is/// first claimed -- and asks the kernel for each datagram's ECN field./// Nothing is read or answered until `pump` runs. `serve` is called once/// per accepted connection, on a task of its own. Asserts that/// `options.sizes` is a configuration a connection could be given.pub fn init( io: Io, gpa: Allocator, socket: *net.Socket, options: Options, serve: Serve,) !Endpoint { // §13.4.1: ask the kernel to report each datagram's ECN field, so that // markings can be counted and fed back. Best effort by design -- a // platform that refuses leaves this endpoint reporting no counts, which // is the conforming answer for "an endpoint... [that] does not have // access to received ECN fields" rather than a failure to start. ecn.requestOnReceive(socket.handle);
const sizes = options.sizes; // The same checks `Connection.init` makes, made once here where the // memory is bought rather than once per connection where it is handed // over -- an endpoint that cannot serve its own configuration should say // so before it takes a socket. std.debug.assert(sizes.recv_window % 8 == 0); std.debug.assert(sizes.tracked >= sizes.trackedFloor());
const sessions = try gpa.alloc(Session, options.max_connections); errdefer gpa.free(sessions);
const origin = Io.Timestamp.now(io, .awake); // The slots and nothing in them. What a connection costs is furnished // when a slot is first claimed -- see `Session.provisioned` -- so an // endpoint willing to serve a hundred connections does not hold a // hundred connections' worth of buffers to answer the first one. for (sessions) |*s| { s.* = .{ .io = io, .socket = socket, .origin = origin, .connection = undefined, .memory = undefined, .tls = undefined, }; }
return .{ .io = io, .gpa = gpa, .socket = socket, .options = options, .serve = serve, .origin = origin, .sessions = sessions, .tasks = .init, };}
test init { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io);
var prng: std.Random.DefaultPrng = .init(0x1417); var endpoint: Endpoint = try .init(io, testing.allocator, &socket, .{ .alpn = &.{"h3"}, .rng = prng.random(), // Random, in earnest, and kept across restarts: §10.3.2 wants the // same token from the same identifier after a crash. .reset_key = @splat(0x01), .token_key = @splat(0x02), .max_connections = 16, }, .{ .context = null, .serveFn = test_pair.ignore }); defer endpoint.deinit();
// Sixteen slots, and nothing in them until somebody connects. try testing.expectEqual(@as(usize, 16), endpoint.sessions.len); for (endpoint.sessions) |*s| try testing.expect(!s.provisioned);}
/// One connection's buffers, from the heap this endpoint was given.fn allocMemory(gpa: Allocator, sizes: quic.Connection.Sizes) !quic.Connection.Memory { const streams = quic.Connection.max_streams;
const send = try gpa.alloc(u8, streams * sizes.send_window); errdefer gpa.free(send); const recv = try gpa.alloc(u8, streams * sizes.recv_window); errdefer gpa.free(recv); const present = try gpa.alloc(u8, streams * (sizes.recv_window / 8)); errdefer gpa.free(present); // One table each for the Initial and Handshake spaces and one per path. const tracked = try gpa.alloc(quic.recovery.Sent, (2 + sizes.paths) * sizes.tracked); errdefer gpa.free(tracked); const scratch = try gpa.alloc(quic.recovery.Sent, 3 * sizes.tracked);
return .{ .send = send, .recv = recv, .present = present, .tracked = tracked, .scratch = scratch, .paths = sizes.paths, };}
fn freeMemory(gpa: Allocator, memory: quic.Connection.Memory) void { gpa.free(memory.send); gpa.free(memory.recv); gpa.free(memory.present); gpa.free(memory.tracked); gpa.free(memory.scratch);}
/// Furnishes a slot that has never carried a connection.////// Called on the pump's own task, at the point a slot is claimed, so the/// allocator is only ever entered from one place. A failure here is a/// connection this endpoint cannot serve, which is the same answer as having/// no free slot and is given the same way: §5.2.2's CONNECTION_REFUSED.fn provision(e: *Endpoint, s: *Session) bool { if (s.provisioned) return true;
const connection = e.gpa.create(quic.Connection) catch return false; errdefer e.gpa.destroy(connection); // The loss-tracking table is provisioned for the largest window this // connection could reach, rather than for the one it starts with, // because `growSend` grows the buffers and not the table. That is a few // hundred entries against buffers measured in megabytes, so sizing it // for a window the connection may never ask for is cheap -- and a table // left short would quietly cap the throughput the larger window was // bought for, since a sender whose table is full waits. var sizes = e.options.sizes; if (e.options.max_send_window) |largest| { var largest_sizes = sizes; largest_sizes.send_window = largest; sizes.tracked = @max(sizes.tracked, largest_sizes.trackedFloor()); } const memory = allocMemory(e.gpa, sizes) catch return false;
s.connection = connection; s.memory = memory; s.provisioned = true; return true;}
/// Ends every connection's task and gives back everything the endpoint/// allocated. The socket is the caller's, and is left open.////// `pump` must have returned first -- `stop` and wait for it, or cancel/// its task. Each task is woken, then canceled and waited for. Every/// handler's connection is closed as `Serve` describes when it returns,/// whether it returned on being woken or on the cancelation, so the socket/// must still be open when this is called.pub fn deinit(e: *Endpoint) void { // Before cancelling, not instead of it: `cancel` awaits, and a task // waiting on a condition nobody will signal is a task that takes a // cancellation to notice. Saying so first means the ordinary path ends // the ordinary way and cancellation is left for the tasks that are // genuinely stuck. e.finishAll(); e.tasks.cancel(e.io); for (e.sessions) |*s| { if (!s.provisioned) continue; freeMemory(e.gpa, s.memory); e.gpa.destroy(s.connection); } e.gpa.free(e.sessions); e.* = undefined;}
test "a handler that only returns when canceled still has its connection closed" { // `deinit` wakes every handler, and one that ignores that -- blocked on // something other than its session -- is canceled instead. Its // connection is still owed the close `Serve` promises, or its peer waits // out the idle timeout for an endpoint that has gone. // // This one passes the cancelation on with `recancel`, as std.Io asks of // code that does not handle it there and then. That re-arms it for the // next cancelation point in the task, which is the close's own send. const io = testing.io; const Stubborn = struct { fn serve(_: ?*anyopaque, session: *Session) void { session.io.sleep(.fromSeconds(60), .awake) catch |err| switch (err) { error.Canceled => session.io.recancel(), }; } }; var pair: test_pair.Pair = undefined; try pair.start(.{ .serve = .{ .context = null, .serveFn = Stubborn.serve } });
pair.endpoint.stop(); pair.pumps.cancel(io); pair.endpoint.deinit();
var heard = false; var waited: usize = 0; while (waited < 200) : (waited += 1) { if (pair.client.session.closeState() != null) { heard = true; break; } try io.sleep(.fromMilliseconds(5), .awake); }
// The rest of `Pair.stop`, the endpoint having been taken down above. pair.client.stop(); pair.runs.cancel(io); pair.client.deinit(); pair.client_socket.close(io); pair.server_socket.close(io);
try testing.expect(heard);}
test deinit { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io);
var prng: std.Random.DefaultPrng = .init(0xde17); var endpoint: Endpoint = try .init(io, testing.allocator, &socket, .{ .alpn = &.{"h3"}, .rng = prng.random(), .reset_key = @splat(0x01), .token_key = @splat(0x02), }, .{ .context = null, .serveFn = test_pair.ignore });
var pumps: Io.Group = .init; try pumps.concurrent(io, test_pair.pump, .{&endpoint});
// The order matters, and is the reverse of starting: the pump first, // then the endpoint, then -- deferred above -- the socket. endpoint.stop(); pumps.cancel(io); endpoint.deinit();}
/// Nanoseconds since this endpoint started, which is what the library counts/// in.fn now(e: *const Endpoint) u64 { const at = Io.Timestamp.now(e.io, .awake); return @intCast(@max(at.nanoseconds - e.origin.nanoseconds, 0));}
/// Asks the pump to return after its current turn, which is at most a/// second away: a turn waits for a datagram or the earliest timer, and never/// longer than that. Safe to call from any task, and does not wait.pub fn stop(e: *Endpoint) void { e.stopping.store(true, .release);}
test stop { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io);
var prng: std.Random.DefaultPrng = .init(0x5701); var endpoint: Endpoint = try .init(io, testing.allocator, &socket, .{ .alpn = &.{"h3"}, .rng = prng.random(), .reset_key = @splat(0x01), .token_key = @splat(0x02), }, .{ .context = null, .serveFn = test_pair.ignore }); defer endpoint.deinit();
// Looked at before every turn, so a pump started after it returns at // once -- where one already waiting returns after the turn it is in. endpoint.stop(); try endpoint.pump();}
/// Reads datagrams and runs timers until `stop`.////// This is the only task that touches the socket's receive side and the only/// one that creates connections. It never runs application code, which is/// what stops a slow handler from stalling every other connection on the/// endpoint.////// Wants a task of its own, and an `Io` that can run each connection's/// handler concurrently beside it; a connection with nowhere to run is/// refused with §20.1's CONNECTION_REFUSED. It fails when the socket does,/// `error.Canceled` included. However it ends, it tells every session that/// nothing more will arrive before it returns.pub fn pump(e: *Endpoint) !void { // Nothing else tells a session that the endpoint is finished, and a task // inside one is very likely waiting on a datagram that will now never // come. HTTP/3 makes this the normal case rather than an edge: §6.2.1 of // RFC 9114 forbids either end closing its control stream, so a reader on // one blocks for as long as the connection exists, by design. Ending the // pump without saying so -- on `stop`, on a failed socket, or canceled -- // leaves those readers waiting for a pump that has gone. defer e.finishAll();
var datagram: [2048]u8 = undefined;
while (!e.stopping.load(.acquire)) { // The earliest thing any connection is waiting for, so that a timer // fires even while the socket is quiet. Without this a connection // with a lost packet waits for a retransmission that nothing will // ever send. const at = e.now(); var wake: ?u64 = null; for (e.sessions) |*s| { if (!s.in_use) continue; const when = s.timeout() orelse continue; if (wake == null or when < wake.?) wake = when; } // Capped at a second even when a timer is due, because `stop` is // only looked at between turns. A quiet connection's earliest timer // is its idle timeout, and waiting for that would leave a stopped // pump running for as long as the peer is allowed to stay silent. const wait: u64 = if (wake) |w| (if (w > at) @min(w - at, std.time.ns_per_s) else 0) else std.time.ns_per_s;
// `receiveManyTimeout` rather than `receiveTimeout` for one reason: // the plain one initializes its message with an empty `control`, so // the kernel's ancillary data is discarded and the IP header's ECN // field goes with it. §13.4 needs that field, and this is the only // way to be handed it. var control: [128]u8 align(@alignOf(usize)) = undefined; var messages = [_]net.IncomingMessage{.{ .from = undefined, .data = &datagram, .control = &control, .flags = undefined, }}; const maybe_err, const count = e.socket.receiveManyTimeout( e.io, &messages, &datagram, .{}, .{ .duration = .{ .raw = .{ .nanoseconds = @intCast(@max(wait, std.time.ns_per_ms)) }, .clock = .awake, } }, ); if (maybe_err) |err| switch (err) { error.Timeout => { e.tick(); continue; }, else => return err, }; if (count == 0) { e.tick(); continue; } const message = messages[0];
e.onDatagram(message.data, message.from, ecn.fromControl(message.control)); e.tick(); }}
test "a pump that is canceled still tells its sessions" { // Canceling the pump's task is the prompt way to end it, since `stop` is // looked at only between turns. Its sessions have to hear that nothing // more is coming then, not only once `deinit` gets round to it: a // handler blocked on a stream would otherwise wait for a pump that has // gone. var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop();
pair.pumps.cancel(testing.io); var live: usize = 0; for (pair.endpoint.sessions) |*s| { if (!s.in_use) continue; live += 1; try testing.expect(s.done); } try testing.expect(live > 0);}
test pump { const io = testing.io; const gpa = testing.allocator; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io);
// A server that sends every stream's octets back once the peer has // finished sending them. var prng: std.Random.DefaultPrng = .init(0x9e7e); var endpoint: Endpoint = try .init(io, gpa, &socket, .{ .alpn = &.{"test"}, .local = test_pair.local, .rng = prng.random(), .reset_key = @splat(0x01), .token_key = @splat(0x02), }, test_pair.echo_server); defer endpoint.deinit();
// On a task of its own, and ended by canceling it: `stop` alone is only // looked at between turns. var pumps: Io.Group = .init; defer pumps.cancel(io); try pumps.concurrent(io, struct { fn go(e: *Endpoint) void { e.pump() catch {}; } }.go, .{&endpoint}); defer endpoint.stop();
// And then somebody connects, and is answered. var client_socket = try loopback.bind(io, .{ .mode = .dgram }); defer client_socket.close(io); var client: @import("Client.zig") = undefined; try client.connect(io, gpa, &client_socket, socket.address, .{ .alpn = &.{"test"}, .host = "pump.example", .insecure_skip_verify = true, .rng = prng.random(), .local = test_pair.local, }); defer client.deinit(); const stream = try client.session.openBidirectional(); try client.session.writeStreamFinished(stream.id, "answered"); var turns: usize = 0; while (!stream.received()) : (turns += 1) { if (turns > 1000) return error.NoAnswer; try client.once(10 * std.time.ns_per_ms); }
client.session.mutex.lockUncancelable(io); defer client.session.mutex.unlock(io); try testing.expectEqualStrings("answered", client.connection.readable(stream.id));}
/// Tells every live session that no more datagrams are coming.fn finishAll(e: *Endpoint) void { for (e.sessions) |*s| { if (s.in_use) s.finish(); }}
/// Fires whatever timers are due and retires connections that have ended.////// Called after every datagram as well as on the timeout branch, which is why/// `Session.tick` checks whether anything is actually due: a connection that/// has just heard from its peer is the *last* one that should be probing it.fn tick(e: *Endpoint) void { for (e.sessions) |*s| { if (!s.in_use) continue; s.tick(); e.retune(s); if (s.closeState() == .closed) { // Wake the task if it is still waiting on this connection; the // slot is let go once it has returned, here or in `accept`. s.finish(); if (!s.serving.load(.acquire)) e.retire(s); } }}
/// Raises one connection's send window if it has shown that it wants one.////// Doubling rather than jumping to the limit, which is the same shape as/// every other window in a transport and for the same reason: the right size/// is not knowable in advance, so it is approached from below, and a/// connection that stops asking stops growing. A path that wants sixteen/// times the default gets there in four doublings, each paid for by a/// refusal that actually happened.////// The signal is the *count* of buffer-bound refusals rather than the state,/// so `tuned_at` records the count the last growth answered. Without it a/// single refusal would be answered again at every tick until another/// arrived, and the window would run to the limit on the strength of one/// event -- which is the failure mode of any tuner that reads a level where/// it should read an edge.////// Failing to allocate is not an error. The connection keeps the buffers it/// has and goes on working at the speed it had, which is the whole of what/// is lost, and asking again costs nothing.fn retune(e: *Endpoint, s: *Session) void { const largest = e.options.max_send_window orelse return; if (!s.provisioned) return;
s.mutex.lockUncancelable(e.io); defer s.mutex.unlock(e.io);
const refusals = s.connection.bufferBound(); if (refusals == s.tuned_at) return; s.tuned_at = refusals;
const current = s.connection.sendWindow(); if (current >= largest) return; const want = @min(current * 2, largest);
const streams = quic.Connection.max_streams; const arena = e.gpa.alloc(u8, streams * want) catch return; const old = s.memory.send; s.connection.growSend(arena); s.memory.send = arena; e.gpa.free(old);
// The room is new, so a writer that gave up for want of it is waiting on // a condition nothing else will signal. s.arrived.broadcast(e.io);}
/// Lets go of a connection that has finished: one whose closing period is/// over and whose task has returned. See `Session.serving`.fn retire(e: *Endpoint, s: *Session) void { _ = e; s.finish(); s.in_use = false;}
fn onDatagram(e: *Endpoint, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { // §5.2.2 puts this before the connection lookup: a packet is matched to a // connection only once its version is one this endpoint speaks. A long // header naming a version this does not know cannot belong to any // connection here, whatever its connection ID happens to collide with. if (e.offerVersionNegotiation(datagram, from)) return;
if (e.route(datagram)) |s| { s.receive(datagram, from, codepoint); return; }
// §8.1: before any state is kept for an address, make the client prove it // is there. The cost to this endpoint is one small packet; the cost to // the client is a round trip. var original: ?[]const u8 = null; if (e.options.require_retry) { switch (e.offerRetry(datagram, from)) { .handled => return, .proceed => |validated| original = validated, } }
const s = switch (e.accept(datagram, from, original)) { .session => |session| session, // §5.2.2: "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." A client told nothing retransmits // its Initial until its own timeout, learning only that the server is // slow. .refused => return e.closeStatelessly(datagram, from, .connection_refused), .ignored => { // Nothing here recognises it. §10.3: a packet for a connection // this endpoint does not have gets a stateless reset, so the peer // stops rather than waiting out its idle timeout. e.offerReset(datagram, from); return; }, }; s.receive(datagram, from, codepoint); // One task per connection, and application code runs on it rather // than on the pump. `concurrent` rather than `async` because the // latter is allowed to run the function inline before returning, // which here would mean the pump serving one connection and reading // no more datagrams. s.serving.store(true, .release); e.tasks.concurrent(e.io, runSession, .{ e, s }) catch { // Nowhere to run it. §20.1's CONNECTION_REFUSED says exactly // this, and saying it is better than accepting a connection // nothing will ever serve. The slot stays claimed through the // closing period like any other closed connection's. s.serving.store(false, .release); s.mutex.lockUncancelable(e.io); s.connection.close(.connection_refused, "no task available", s.now()); s.flushLocked(); s.mutex.unlock(e.io); };}
fn runSession(e: *Endpoint, s: *Session) void { e.serve.call(s); // A handler that returns is done with its connection. If the connection // is still open it is closed properly -- §10.2's CONNECTION_CLOSE and // closing period, rather than a slot that vanishes and leaves the peer // to learn of it from a stateless reset. The slot itself is the pump's // to let go of, once the closing period is over. // // Protected from cancelation, because a handler that returned on being // canceled may have re-armed it with `recancel` -- the thing std.Io asks // of code that does not handle it -- and the next cancelation point in // this task would then be the close's own send. One datagram is all // this does, so there is nothing here for a cancelation to rescue. const protection = e.io.swapCancelProtection(.blocked); defer _ = e.io.swapCancelProtection(protection); s.mutex.lockUncancelable(e.io); if (s.connection.closeState() == null) { s.connection.closeApplication(0, "", s.now()); s.flushLocked(); } s.mutex.unlock(e.io); s.serving.store(false, .release);}
/// The session a datagram belongs to, by the connection ID in its header.////// Two identifiers can name a session, and both are needed. The one this/// endpoint issued is what a client uses once it has heard it; the one the/// client invented is what it uses until then -- see `Session.original_id`/// for why a first flight spanning two datagrams depends on the second.fn route(e: *Endpoint, datagram: []const u8) ?*Session { for (e.sessions) |*s| { if (!s.in_use) continue; if (matches(datagram, s.local_id[0..s.local_id_len])) return s; if (matches(datagram, s.original_id[0..s.original_id_len])) return s; } // Every other identifier a connection has issued -- with // NEW_CONNECTION_ID, or with draft-ietf-quic-multipath-21's // PATH_NEW_CONNECTION_ID for a path past path 0 -- is one a short header // may be addressed to, and only the connection knows them all. Asked // second, because the handshake's identifier is what nearly every packet // carries, and asking a connection means taking its lock. // // Only routing by the handshake's identifier used to drop a packet // addressed to any other, which a client does on migrating (§9.5) and // always does on opening a second path. if (datagram.len < 1 or datagram[0] & 0x80 != 0) return null; const id_len = e.options.connection_id_len; if (datagram.len < 1 + id_len) return null; const id = datagram[1..][0..id_len]; for (e.sessions) |*s| { if (!s.in_use or !s.provisioned) continue; s.mutex.lockUncancelable(e.io); defer s.mutex.unlock(e.io); if (s.connection.acceptsId(id)) return s; } return null;}
/// Whether a datagram is addressed to `id`.////// §5.1: every packet carries the Destination Connection ID at a fixed/// offset for its header form, which is what makes routing possible before/// anything has been decrypted. A long header says how long the field is; a/// short one does not, which is why the endpoint has to know the length it/// issues.fn matches(datagram: []const u8, id: []const u8) bool { if (id.len == 0) return false; if (datagram.len < 1) return false; if (datagram[0] & 0x80 != 0) { // Long header: version, then a one-octet length and the field. if (datagram.len < 6) return false; const stated = datagram[5]; if (stated != id.len) return false; if (datagram.len < 6 + id.len) return false; return std.mem.eql(u8, datagram[6..][0..id.len], id); } if (datagram.len < 1 + id.len) return false; return std.mem.eql(u8, datagram[1..][0..id.len], id);}
/// §6.1: tells a client that the version it asked for is not one this server/// speaks. Answers whether the datagram was dealt with here.////// "This system allows a server to process packets with unsupported versions/// without retaining state" -- so nothing is allocated, no session is/// claimed, and the answer is written from the received header alone.fn offerVersionNegotiation(e: *Endpoint, datagram: []const u8, from: net.IpAddress) bool { // A short header carries no version field at all, so there is nothing to // disagree with and nothing to answer. if (datagram.len == 0 or datagram[0] & 0x80 == 0) return false;
const header = quic.packet.peekLongHeader(datagram) catch return false; if (quic.packet.supportsVersion(header.version)) return false;
// §6.1: "An endpoint MUST NOT send a Version Negotiation packet in // response to receiving a Version Negotiation packet." Version 0 is what // one is, so this is that rule rather than a special case around it. if (header.version == 0) return true;
// §5.2.2: "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 anything at all would be an // amplifier for a forged source address; requiring the datagram to be // large enough to have started a connection is what makes the exchange // no worse than the handshake it is refusing. if (datagram.len < quic.Connection.min_initial_datagram) return true;
// §17.2.1 leaves the seven bits after the header form "an arbitrary // value" that clients MUST ignore, and recommends the 0x40 bit be set so // the packet still looks like QUIC to a demultiplexer sharing this port. // The rest are random rather than fixed, because a value clients are // required to ignore is one an implementation will eventually depend on // if it never varies. var noise: [1]u8 = undefined; e.options.rng.bytes(&noise); const unused = 0x40 | (noise[0] & 0x3f);
// §6.3: a reserved version, sent alongside the real one to check that the // client ignores what it does not know. "Endpoints MAY add reserved // versions to any field where unknown or unsupported versions are // ignored... For instance, an endpoint could include a reserved version // in a Version Negotiation packet." A client that picks this instead of // the version beside it is a client that would pick anything. var offered: [quic.packet.supported_versions.len + 1]u32 = undefined; var greased: [4]u8 = undefined; e.options.rng.bytes(&greased); offered[0] = (@as(u32, greased[0]) << 24) | (@as(u32, greased[1]) << 16) | (@as(u32, greased[2]) << 8) | @as(u32, greased[3]); offered[0] = (offered[0] & 0xf0f0f0f0) | 0x0a0a0a0a; @memcpy(offered[1..], &quic.packet.supported_versions);
// §17.2.1: a Version Negotiation packet "consumes an entire UDP // datagram", and a server "MUST NOT send more than one" for each one it // receives -- so this returns having sent at most this. var out: [1024]u8 = undefined; const wire = quic.packet.writeVersionNegotiation(&out, .{ .form = .long, .kind = .version_negotiation, .first = datagram[0], .version = header.version, .destination = header.destination, .source = header.source, .token = &.{}, .number_offset = 0, .end = datagram.len, }, &offered, unused) catch return true; e.socket.send(e.io, &from, wire) catch |err| Session.sendFailed(e.io, err); return true;}
/// §10.3: answers a packet for a connection this endpoint does not have.fn offerReset(e: *Endpoint, datagram: []const u8, from: net.IpAddress) void { // A long header is either a connection starting or one whose handshake is // in flight; neither is something to reset. if (datagram.len == 0 or datagram[0] & 0x80 != 0) return; const id_len = e.options.connection_id_len; if (datagram.len < 1 + id_len + quic.stateless_reset.min_len) return;
// §10.3.2: "the connection ID comes from the packet that the endpoint // receives" -- which is the whole trick, since the identifier is in the // clear and an endpoint with nothing but its static key can still produce // the one value the peer will believe. How much of the packet is the // identifier is the endpoint's own choice, above. const id = datagram[1..][0..id_len]; const value = quic.stateless_reset.token(e.options.reset_key, id);
var out: [128]u8 = undefined; const bytes = quic.stateless_reset.write(&out, e.options.rng, value, datagram.len) catch return; e.socket.send(e.io, &from, bytes) catch |err| Session.sendFailed(e.io, err);}
const Outcome = union(enum) { /// Dealt with here: a Retry or a CONNECTION_CLOSE went out, or it was /// not worth answering. handled, /// Carry on, with the connection ID the client originally chose -- which /// after a Retry is the one inside the token rather than the one this /// packet was addressed to. proceed: ?[]const u8,};
fn offerRetry(e: *Endpoint, datagram: []const u8, from: net.IpAddress) Outcome { const header = quic.packet.parse(datagram, e.options.connection_id_len) catch return .handled; if (header.kind != .initial) return .{ .proceed = null }; if (datagram.len < quic.Connection.min_initial_datagram) return .handled;
const seconds: u64 = @intCast(@max(Io.Timestamp.now(e.io, .real).toSeconds(), 0)); if (header.token.len > 0) { // §8.1.4: the token is bound to the address it was minted for, so one // handed to a client at one address proves nothing about another -- // which is what stops a token being a reusable ticket past the check // it exists to make. var address: [address_bytes_max]u8 = undefined; if (quic.retry.Token.open( header.token, e.options.token_key, addressBytes(from, &address), seconds, )) |opened| { return .{ .proceed = opened }; } else |_| if (quic.retry.Token.shaped(header.token)) { // §8.1.2: a client that has had a Retry "will not accept another // Retry token", so silence would leave it retransmitting until its // own timeout. Instead "the server SHOULD immediately close ... the // connection with an INVALID_TOKEN error". Expired, minted for // another address, or sealed under a key this endpoint has since // replaced: the client cannot fix any of them by trying again. e.closeStatelessly(datagram, from, .invalid_token); return .handled; } // Not a token this endpoint could have minted. It never sends // NEW_TOKEN, so this is one from some other server, and §8.1.3 has an // invalid one treated "as if the client did not have a validated // address, including potentially sending a Retry packet" -- which a // client that has had no Retry yet will accept. }
var token_buf: [512]u8 = undefined; var address: [address_bytes_max]u8 = undefined; const token = quic.retry.Token.mint( &token_buf, e.options.token_key, addressBytes(from, &address), header.destination, seconds, ) catch return .handled;
var new_id: [8]u8 = undefined; e.options.rng.bytes(&new_id); var out: [256]u8 = undefined; // §17.2.5: the Retry is addressed to the identifier the client put in its // Source Connection ID, carries a new one of this endpoint's choosing, // and is authenticated over the identifier the client originally chose -- // which is what stops an off-path attacker injecting one. const bytes = quic.retry.write( &out, header.destination, header.source, &new_id, token, ) catch return .handled; e.socket.send(e.io, &from, bytes) catch |err| Session.sendFailed(e.io, err); return .handled;}
/// §10.2.3's immediate close, sent before any connection exists: an Initial/// carrying a CONNECTION_CLOSE, under the Initial keys the client's own/// Destination Connection ID derives. §8.1.2 notes that "a server has not/// established any state for the connection at this point and so does not/// enter the closing period", which is what lets it be stateless.////// The packet is a few dozen octets against the 1200 or more the client sent,/// so answering an address nobody has validated amplifies nothing.fn closeStatelessly(e: *Endpoint, datagram: []const u8, from: net.IpAddress, code: quic.close.Code) void { const header = quic.packet.parse(datagram, e.options.connection_id_len) catch return; if (header.kind != .initial) return; if (datagram.len < quic.Connection.min_initial_datagram) return;
var source: [8]u8 = undefined; e.options.rng.bytes(&source); var out: [128]u8 = undefined; // §17.2.2: the connection IDs swapped, and no token, which only a client // may put in an Initial. var b = quic.packet.Builder.initLong(&out, .{ .kind = .initial, .destination = header.source, .source = &source, }, 0, 1) catch return; // A transport close with no reason: nothing has been decrypted yet, so // there is no frame to blame and nothing to say that the code does not. b.add(.{ .connection_close = .{ .error_code = @backingInt(code), .frame_type = 0, .reason = &.{}, .application = false, } }) catch return; const keys: quic.protection.Keys = .initialKeys(header.destination, .server); const bytes = b.finish(&keys) catch return; e.socket.send(e.io, &from, bytes) catch |err| Session.sendFailed(e.io, err);}
/// The address a Retry token is bound to, so that a token minted for one/// client cannot be replayed by another (§8.1.4).////// Written out of the address's own fields, into a buffer the caller owns. The/// obvious spelling -- the bytes of the `net.IpAddress` itself -- is wrong, and/// wrong in a way that hides: it is a tagged union, so its memory is the tag,/// whatever padding the compiler chose, and the whole of the arm that is *not*/// in use, none of which is the address. Two calls naming the same peer do not/// agree, because what is behind the unused arm is whatever was last on that/// stack. A token minted over one of those and opened against the other never/// validates, and every client behind `require_retry` is then closed with/// INVALID_TOKEN for a token this endpoint minted correctly.////// The port is in it as well as the address. §8.1.4 asks for a token "to be/// reusable only by the client that received it", and the client that received/// it is the socket that received it; a client whose port changes in between/// has moved, and §9's path validation is what covers that rather than this.fn addressBytes(from: net.IpAddress, into: *[address_bytes_max]u8) []const u8 { switch (from) { .ip4 => |a| { @memcpy(into[0..4], &a.bytes); std.mem.writeInt(u16, into[4..6], a.port, .big); return into[0..6]; }, .ip6 => |a| { // The interface a link-local address names is deliberately left // out: it is this endpoint's own index for a link and means // nothing to the peer, and two datagrams from one client can // arrive with it set and unset. @memcpy(into[0..16], &a.bytes); std.mem.writeInt(u16, into[16..18], a.port, .big); return into[0..18]; }, }}
/// Enough for the longest of them: sixteen octets of IPv6 and a port.const address_bytes_max = 18;
const Accepted = union(enum) { session: *Session, /// An Initial this endpoint has no room or memory for. refused, /// Not something that starts a connection. ignored,};
fn accept( e: *Endpoint, datagram: []const u8, from: net.IpAddress, validated_original: ?[]const u8,) Accepted { const header = quic.packet.parse(datagram, e.options.connection_id_len) catch return .ignored; // §7.2: only an Initial packet starts a connection. Anything else is a // straggler from a connection that has gone, or somebody probing. if (header.kind != .initial) return .ignored; // §14.1: "a server MUST discard an Initial packet that is carried in a // UDP datagram with a payload that is smaller than the smallest allowed // maximum datagram size of 1200 bytes", which is the rule that stops an // Initial being a cheap way to make a server do work. if (datagram.len < quic.Connection.min_initial_datagram) return .ignored;
for (e.sessions) |*s| { if (s.in_use) { // A slot whose connection has closed and whose task has returned // is free, whether or not a tick has come round to say so -- a // closed connection has no timer left to bring one. if (s.serving.load(.acquire) or s.closeState() != .closed) continue; e.retire(s); } if (!e.provision(s)) return .refused;
e.options.rng.bytes(&s.local_id); s.local_id_len = @min(e.options.connection_id_len, s.local_id.len); // What the client will keep addressing until it has heard the above. if (header.destination.len <= s.original_id.len) { @memcpy(s.original_id[0..header.destination.len], header.destination); s.original_id_len = header.destination.len; } else { s.original_id_len = 0; } s.peers = @splat(null); s.peers[0] = from; s.done = false;
var parameters = e.options.local; parameters.initial_source_connection_id = s.local_id[0..s.local_id_len]; // RFC 9368 §3: Version Information, which any endpoint of this library // can state for itself -- one version, chosen and available -- so it is // sent unless the caller has said something else. if (parameters.version_information == null) parameters.version_information = .v1; // §10.3: only a server may name this, because "clients cannot use the // stateless_reset_token transport parameter because their transport // parameters do not have confidentiality protection". parameters.stateless_reset_token = quic.stateless_reset.token( e.options.reset_key, s.local_id[0..s.local_id_len], ); if (validated_original) |original| { // §7.3, after a Retry: the client's first Initial named something // this endpoint no longer sees, so the token is where that value // comes from, and the identifier this packet was addressed to is // the one the Retry itself used. parameters.original_destination_connection_id = original; parameters.retry_source_connection_id = header.destination; } else { parameters.original_destination_connection_id = header.destination; }
const encoded = quic.parameters.write( ¶meters, &s.parameter_bytes, .server, ) catch return .ignored; s.parameter_len = encoded.len;
s.tls = .{ .server = .init(.{ .auth = e.options.auth, .raw_public_key = e.options.raw_public_key, .ticket_key = e.options.ticket_key, .now_sec = @intCast(@max(Io.Timestamp.now(e.io, .real).toSeconds(), 0)), .early_data = e.options.early_data, .transport_parameters = s.parameter_bytes[0..s.parameter_len], .alpn_protocols = e.options.alpn, .rng = e.options.rng, }) }; s.connection.init(.{ .role = .server, .handshake = s.tls.handshake(), .local_id = s.local_id[0..s.local_id_len], .memory = s.memory, .local = parameters, .reset_key = e.options.reset_key, .rng = e.options.rng, // §8.1.2: a Retry token that opened against this address is the // client showing it receives there, so §8.1's limit has nothing // left to guard. .address_validated = validated_original != null, }); s.in_use = true; return .{ .session = s }; } // Every slot taken. return .refused;}
const testing = std.testing;const test_pair = @import("test_pair.zig");