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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! One QUIC connection, with a lock around it and somewhere to send.//!//! The `quic.Connection` inside is a state machine that is not safe to touch//! from two tasks at once, and in a server it is touched by at least two: the//! endpoint's pump, which feeds it datagrams and fires its timers, and//! whatever task is serving the connection, which reads and writes streams.//! Everything here that reaches the connection does so under `mutex`, and//! everything that might have given it something to say calls `flush` before//! it returns.//!//! `arrived` is the other half. A task waiting to read is waiting for a//! datagram that will be delivered by a different task entirely, so it waits//! on a condition rather than spinning, and the pump broadcasts after every//! datagram and every timer. Broadcast rather than signal, deliberately: the//! waiters have different predicates — one wants a stream to exist, another//! wants octets on a particular stream, a third wants the handshake to//! finish — so waking one of them can wake the wrong one and stall the rest.
const std = @import("std");const Io = std.Io;const net = Io.net;const assert = std.debug.assert;
const quic = @import("quic");const ecn = @import("ecn.zig");const Stream = @import("Stream.zig");
const Session = @This();
/// How many peer addresses one session tracks, which is what §9 migration/// needs and is bounded by what the library will hold.const max_paths = quic.path.capacity;
io: Io,socket: *net.Socket,/// Nanoseconds since the endpoint's origin. The library measures durations/// and never dates (§10.1 of RFC 9000 and the whole of RFC 9002), so what it/// is given is a monotonic count from an origin it never sees.origin: Io.Timestamp,
/// Undefined until `provisioned`, like `tls` below and for the same reason: a/// slot that has never carried a connection has nothing to say about one.connection: *quic.Connection,/// The buffers behind that connection, which the endpoint allocated and will/// free. Held here rather than inside the connection because the connection/// does not allocate and so cannot be the thing that frees.memory: quic.Connection.Memory,/// The `bufferBound` count this session's send window was last grown at, so/// that one refusal is acted on once rather than at every tick that follows/// it. See `Endpoint.retune`.tuned_at: u64 = 0,/// Whether the two above exist yet.////// A connection's buffers are the bulk of what an endpoint spends, and how/// much of it is the caller's choice -- so allocating every slot's worth/// before a single packet arrives makes the memory an endpoint holds a/// function of the connections it is *willing* to serve rather than the ones/// it is serving. A megabyte-per-stream window on a hundred permitted/// connections is gigabytes committed to answer one request.////// So a slot is furnished when it is first claimed, and keeps what it was/// given afterwards: the footprint follows the peak number of connections/// alive at once, and a slot that is never claimed costs nothing. Keeping/// rather than freeing on release is deliberate -- a busy endpoint would/// otherwise return a connection's buffers to the allocator and ask for them/// again microseconds later, for ever.provisioned: bool = false,/// Whether the application's task for this connection is still running.////// A slot has two lifetimes and is only free when both have ended: the/// connection's, which runs on past a CONNECTION_CLOSE for §10.2's closing/// period, and the task's. Freeing it when the task returned let a handler/// that gave up on a failed handshake take the closing period with it, so/// the peer's next packet found no connection and was answered with a/// stateless reset instead of the close. Freeing it when the connection/// closed let a slot be claimed again while the old task was still on its/// way out. Written by that task as it returns and read by the pump, hence/// atomic.serving: std.atomic.Value(bool) = .init(false),tls: Tls,/// This session's encoded transport parameters, which the TLS handshake reads/// while building its EncryptedExtensions -- so they have to outlive the call/// that starts it, which means living here rather than on a stack frame.parameter_bytes: [256]u8 = undefined,parameter_len: usize = 0,
/// The connection ID this endpoint told the peer to use, which is what routes/// a datagram back to this session once the peer has heard it.local_id: [8]u8 = undefined,local_id_len: usize = 0,
/// The connection ID the *client* invented and addressed its first packet to,/// which routes a datagram here until the client has learnt the one above.////// §7.2 of RFC 9000: a client "MUST change the Destination Connection ID it/// uses to the value selected by the server" -- but only once it has seen/// that value, and the first thing it sends is addressed to a value it chose/// itself. Everything a client sends before the server's first packet reaches/// it therefore carries the client's own identifier, and a server that routed/// only by what it issued would not recognise any of it.////// Which matters more than it sounds, because a ClientHello does not always/// fit in one packet. A client whose first flight spans two datagrams sends/// both to the identifier it chose, and an endpoint that failed to route the/// second would hand each half of the ClientHello to a *different*/// connection -- and then neither could complete a handshake, with nothing/// anywhere reporting an error.original_id: [20]u8 = undefined,original_id_len: usize = 0,
/// The addresses this session has heard from, indexed by the path number the/// connection was given. §8.2 of RFC 9000 defines a path as "the 2-tuple of/// IP address and port"; this is where that 2-tuple lives, because the/// library deals in small integers and has never seen an address.peers: [max_paths]?net.IpAddress = @splat(null),/// The local socket each path leaves from, where it is not `socket`.////// draft-ietf-quic-multipath-21: a client's second path is a second 4-tuple,/// and the half of it that is the client's own is a second socket -- bound/// to another interface, or only another port. The peer's address is the/// same for both, so it is the socket that tells the paths apart.path_sockets: [max_paths]?*net.Socket = @splat(null),
/// Taken with `lockUncancelable` everywhere, on purpose. Nothing is held/// across a blocking call -- the only I/O under it is a UDP `sendTo`, which/// does not wait for anybody -- so a cancellation point here would buy/// nothing and would leave every caller with an error to handle that can only/// mean "we were cancelled while not waiting". The cancellation point is/// `arrived.wait`, which is where a task actually stops.mutex: Io.Mutex = .init,/// Broadcast after anything that might make a waiter's question have a new/// answer: a datagram, a timer, or the connection ending.arrived: Io.Condition = .init,
in_use: bool = false,/// Whether the pump has finished with this session. A reader waiting for/// octets that will now never come has to be told, or it waits for the idle/// timeout and then for ever.done: bool = false,
/// The datagram being built, used only under `mutex`.outgoing: [2048]u8 = undefined,
/// Nanoseconds since `origin` -- the endpoint's, or the client's -- on the/// monotonic clock, which is the instant every call into the connection is/// given. Never negative, and takes no lock.pub fn now(s: *Session) u64 { const at = Io.Timestamp.now(s.io, .awake); return @intCast(@max(at.nanoseconds - s.origin.nanoseconds, 0));}
test now { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
const before = session.now(); try testing.io.sleep(.fromMilliseconds(2), .awake); try testing.expect(session.now() - before >= 2 * std.time.ns_per_ms);}
/// Sends whatever the connection has to say, until it has nothing.////// For a task that has just given the connection something to send by/// reaching into it under `mutex`, and has let go of the lock since. The/// lock is taken here rather than by the caller because that is the rule/// this type exists to enforce: every datagram a connection sends leaves/// through `flushLocked`, and so under the lock -- which a caller already/// holding it reaches directly, as every method here does after it changes/// the connection's state.pub fn flush(s: *Session) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.flushLocked();}
test flush { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// Straight to the state machine, which sends nothing by itself... const stream = try session.openBidirectional(); { session.mutex.lockUncancelable(session.io); defer session.mutex.unlock(session.io); try session.connection.write(stream.id, "by hand"); try session.connection.finishStream(stream.id); } // ...so it is flushed afterwards, and the test pair's server echoes it. session.flush();
var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("by hand", answer[0..n]);}
/// A send that failed, which ends a flush: whatever is left goes with the/// next one, or is lost and found missing by loss recovery.////// Except that `error.Canceled` is not the socket failing but the task being/// asked to stop, and reporting it is what uses the request up. Swallowed/// here, a cancel landing on a send was lost, and a handshake it was meant/// to end waited out its whole timeout; re-armed, the next cancelation point/// -- the wait for a datagram -- reports it instead.pub fn sendFailed(io: Io, err: anyerror) void { if (err == error.Canceled) io.recancel();}
test sendFailed { 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);
// How every send in this module that has nobody to report to ends: a // datagram that did not go is loss recovery's to find, and the only // thing worth keeping from the error is a cancelation. socket.send(io, &socket.address, "a probe") catch |err| sendFailed(io, err); // So anything else is let go of, and this returns having done nothing. sendFailed(io, error.NetworkUnreachable);}
/// `flush`, for a caller that already holds the lock.////// Stops at the first send that fails -- see `sendFailed` -- and at a/// datagram for a path with no address to send it to.pub fn flushLocked(s: *Session) void { while (true) { const at = s.now(); const datagram = s.connection.send(&s.outgoing, at) catch break orelse break; const socket = s.path_sockets[datagram.path] orelse s.socket; // n0's NAT traversal: a probe goes to a candidate address rather than // to the path's peer. const to = if (datagram.to) |address| forSocket(socket, address) else s.peers[datagram.path] orelse break; // §13.4: the connection says what the IP header's ECN field should // hold and the socket is what can set it, which is this seam. An // unmarked datagram asks for no control message at all, so the // ordinary path costs nothing. var control: ecn.Control = .{}; const ancillary = control.forSend(&to, datagram.ecn); if (ancillary.len == 0) { socket.send(s.io, &to, datagram.bytes) catch |err| return sendFailed(s.io, err); } else { var messages = [_]net.OutgoingMessage{.{ .address = &to, .data_ptr = datagram.bytes.ptr, .data_len = datagram.bytes.len, .control = ancillary, }}; socket.sendMany(s.io, &messages, .{}) catch |err| return sendFailed(s.io, err); } }}
test flushLocked { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
const stream = try session.openBidirectional(); session.mutex.lockUncancelable(session.io); try session.connection.write(stream.id, "under the lock"); try session.connection.finishStream(stream.id); // The lock is already held, so `flush` would deadlock. session.flushLocked(); session.mutex.unlock(session.io);
var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("under the lock", answer[0..n]);}
/// Writes to a stream, waiting when there is no room rather than failing.////// `Connection.write` is all or nothing against a fixed per-stream buffer, so/// a body larger than that buffer cannot be handed over in one call -- and/// failing would be the wrong answer, because the room is not gone but/// pending: it comes back as the peer acknowledges what has been sent and/// extends more credit (§4.1 of RFC 9000). So this is where a writer waits,/// and it is the reason the writer blocks at all.////// Flushing before each wait is not an optimization. The room this is waiting/// for only appears when the octets already written reach the peer, and/// nothing else in this design will send them -- a writer that slept without/// flushing would be waiting for a consequence of an action it had not taken.////// Returns once all of `bytes` is in the connection and flushed./// `error.WriteFailed` when the stream will not take them -- one this end/// cannot send on, or has finished or reset -- or when the connection ends,/// or the wait is canceled, first; in that case some of `bytes` may already/// have been written.pub fn writeStream(s: *Session, id: quic.stream.Id, bytes: []const u8) error{WriteFailed}!void { return s.writeStreamMaybeFinished(id, bytes, false);}
test writeStream { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// Twice the per-stream buffer, which `Connection.write` would refuse in // one call and which this hands over as the peer makes room. var body: [2 * quic.Connection.stream_buffer]u8 = undefined; for (&body, 0..) |*octet, i| octet.* = @truncate(i);
const stream = try session.openBidirectional(); try session.writeStream(stream.id, &body); try session.writeStreamFinished(stream.id, "");
var answer: [body.len]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualSlices(u8, &body, answer[0..n]);}
/// Writes the last of a stream and ends this endpoint's half of it, in one/// packet.////// `writeStream` followed by `finishStream` would do the same thing and takes/// a packet more to do it: the write is flushed on its way out, so the FIN has/// nothing left to travel with and goes in a STREAM frame of its own carrying/// no data. §19.8 allows that -- a zero-length frame with the FIN bit at the/// final offset is a valid frame -- and it is still the wrong thing to send.////// Every other implementation puts the FIN on the frame carrying the last/// octet, and a peer that has only ever been spoken to by those is a peer that/// has never had to handle the other shape. Quad9's DNS-over-QUIC server/// answers a query whose FIN arrives with it and silently ignores one whose FIN/// arrives behind it -- no close, no reset, an acknowledgement for both packets/// and no answer -- and its DNS-over-HTTP/3 server does the same to a request./// Both were reached by `zig-dns-client` and neither could be explained from/// this side of the wire. Sending what everybody else sends is also a packet/// cheaper, so there is nothing to weigh.////// Waits and fails as `writeStream` does, and fails too if the stream cannot/// be finished. Empty `bytes` sends the FIN alone.pub fn writeStreamFinished(s: *Session, id: quic.stream.Id, bytes: []const u8) error{WriteFailed}!void { return s.writeStreamMaybeFinished(id, bytes, true);}
test writeStreamFinished { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// The whole of a request, and the end of it, in one packet. const stream = try session.openBidirectional(); try session.writeStreamFinished(stream.id, "a request");
var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("a request", answer[0..n]);
// Nothing more may follow the FIN. try testing.expectError(error.WriteFailed, session.writeStream(stream.id, "more"));}
/// Waits on `arrived`, with the lock held, for the callers whose answer has/// no room for `error.Canceled`: a stream's reader and writer, which can only/// say that they failed, and `accept`, `readDatagram` and `waitEstablished`,/// which can only say null or false. False when the wait was canceled.////// The cancelation is re-armed before that false is returned, and that is the/// point of having one function for it. A cancelation is delivered to one/// cancelation point and no more, and this is where every one of those/// callers stops -- so a wait that turned it into "failed" and nothing else/// would be the end of it, and the task that was asked to stop would go on/// with whatever it did after a failure: the next server, the next attempt./// Re-armed, it is the caller's next cancelation point that reports it.////// A wake is not an answer: the caller checks its own condition again, and/// `done` and `closeState` with it, every time this returns true.pub fn waitArrived(s: *Session) bool { s.arrived.wait(s.io, &s.mutex) catch |err| switch (err) { error.Canceled => { s.io.recancel(); return false; }, }; return true;}
test waitArrived { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
const stream = try session.openBidirectional(); try session.writeStreamFinished(stream.id, "wait for me");
// A predicate of the caller's own, checked under the lock and checked // again after every wake. session.mutex.lockUncancelable(session.io); defer session.mutex.unlock(session.io); while (!session.connection.streamReceived(stream.id)) { if (session.done or session.connection.closeState() != null) return error.Closed; if (!session.waitArrived()) return error.Canceled; } try testing.expectEqualStrings("wait for me", session.connection.readable(stream.id));}
fn writeStreamMaybeFinished( s: *Session, id: quic.stream.Id, bytes: []const u8, fin: bool,) error{WriteFailed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io);
var at: usize = 0; while (at < bytes.len) { const chunk = @min(bytes.len - at, max_write_chunk); if (s.connection.write(id, bytes[at..][0..chunk])) { at += chunk; continue; } else |err| switch (err) { error.NoRoom => {}, else => return error.WriteFailed, }
s.flushLocked(); if (s.done or s.connection.closeState() != null) return error.WriteFailed; if (!s.waitArrived()) return error.WriteFailed; } // Before the flush rather than after it, which is the whole point: the // packet builder reads the stream's send state, so a FIN set now leaves on // the frame carrying the octets above and a FIN set afterwards cannot. if (fin) s.connection.finishStream(id) catch return error.WriteFailed; s.flushLocked();}
/// How much is offered to `Connection.write` at a time.////// Smaller than the per-stream buffer on purpose: the call is all or nothing,/// so offering the whole buffer's worth would fail whenever anything at all/// was still outstanding, and the writer would wait for the stream to empty/// completely before making any progress at all.const max_write_chunk = 1024;
/// Hands the connection a datagram that arrived from `from`, with the ECN/// `codepoint` its IP header carried, then flushes whatever that gave the/// connection to say and wakes every waiter.////// The path number is looked up or assigned here, which is the whole of what/// this type adds to `Connection.receive`: the library speaks in path/// numbers and the socket speaks in addresses, and something has to hold the/// table between them. A datagram from a new address when the table is full/// is dropped. So is one the connection will not take: an error from the/// connection is not the caller's to handle, since a connection that has to/// close over it has already closed.////// `datagram` is decrypted in place, so it is the caller's buffer and is/// garbage afterwards.pub fn receive(s: *Session, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io);
const path = s.pathOf(from) orelse return; s.receiveLocked(path, datagram, from, codepoint);}
test receive { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// What `Client.once` and the endpoint's pump do with every datagram the // socket hands them. This one is noise -- a short header that will not // decrypt -- and §12.2 has an endpoint drop such a packet and carry on. var noise: [64]u8 = @splat(0x5a); session.receive(&noise, pair.server_socket.address, .not_ect);
try testing.expectEqual(@as(?quic.close.State, null), session.closeState()); var answer: [64]u8 = undefined; try testing.expectEqualStrings("still here", try test_pair.exchange(session, "still here", &answer));}
/// `receive`, for a datagram that arrived on the socket of path `path` --/// which, with the peer at one address for every path, is the only thing/// that says which path it came by. `path` is the caller's route number, as/// `openPath` returned it, and is not looked up.pub fn receiveOn(s: *Session, path: quic.path.Id, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.receiveLocked(path, datagram, from, codepoint);}
test receiveOn { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// Path 0 is the one the handshake ran on; `Client.openPath`'s reader // hands over what arrives on a second socket the same way, with the // route that path was given. var noise: [64]u8 = @splat(0x5a); session.receiveOn(0, &noise, pair.server_socket.address, .not_ect);
try testing.expectEqual(@as(?quic.close.State, null), session.closeState());}
fn receiveLocked(s: *Session, path: quic.path.Id, datagram: []u8, from: net.IpAddress, codepoint: quic.ack.Codepoint) void { // draft-ietf-quic-address-discovery-01: the one thing the connection // cannot know for itself, and what it reports when the peer asks. s.connection.setPeerAddress(path, frameAddress(from)) catch {}; // RFC 9000 §9.4: the other half of telling a NAT rebinding, which keeps // what the path measured, from a move to a new path, which starts again. if (localAddress(s.path_sockets[path] orelse s.socket)) |local| { s.connection.setLocalAddress(path, local) catch {}; } s.connection.receiveEcn(datagram, path, s.now(), codepoint) catch {}; s.flushLocked(); s.arrived.broadcast(s.io);}
test "RFC 9000 9.4: a socket bound to one address tells the connection where it is" { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// The handshake's datagrams arrived on the client's socket, which is // bound to 127.0.0.1 -- one address, so every datagram on it arrived // there, and the connection can tell a port-only move from a new path. session.mutex.lockUncancelable(session.io); defer session.mutex.unlock(session.io); const seen = session.connection.paths.find(0).?; try testing.expect(seen.local_address.?.eql(frameAddress(pair.client_socket.address)));}
/// draft-ietf-quic-multipath-21 §3.1: opens a path to `peer` from `socket`,/// returning the caller's path number for it -- which datagrams arriving on/// `socket` are to be handed to `receiveOn` with -- and the multipath path/// ID the connection chose.////// A client's call, on a connection that has negotiated multipath and/// finished its handshake; `error.NotAllowed` otherwise. `NoPathAvailable`/// until the peer has issued a connection ID for the new path, which it/// does just after the handshake, and `TooManyPaths` when every route is/// taken. Nothing here reads `socket`: whoever calls this has to, which is/// what `Client.openPath` adds. `socket` must outlive the session.pub fn openPath(s: *Session, socket: *net.Socket, peer: net.IpAddress) error{ NotAllowed, NoPathAvailable, TooManyPaths }!struct { route: quic.path.Id, id: u32 } { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const route: quic.path.Id = for (s.peers[1..], 1..) |seen, i| { if (seen == null) break @intCast(i); } else return error.TooManyPaths; const id = try s.connection.openPath(route, s.now()); s.peers[route] = peer; s.path_sockets[route] = socket; s.flushLocked(); return .{ .route = route, .id = id };}
test openPath { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); // Declared first, so that it is closed after the pair has stopped // sending from it. var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io);
var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
var attempts: usize = 0; const opened = while (true) : (attempts += 1) { if (session.openPath(&second, pair.server_socket.address)) |opened| break opened else |err| { // The server's identifier for path 1 is on its way. if (err != error.NoPathAvailable or attempts > 200) return err; try io.sleep(.fromMilliseconds(5), .awake); } }; try testing.expectEqual(@as(quic.path.Id, 1), opened.route); try testing.expectEqual(@as(u32, 1), opened.id);}
/// Whether the caller's path `route` -- as `openPath` returned it -- has/// been validated (§8.2 of RFC 9000), after which it can carry data.pub fn pathValidated(s: *Session, route: quic.path.Id) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const seen = s.connection.paths.find(route) orelse return false; return seen.validated;}
test pathValidated { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io);
var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop();
// Path 0 was validated by the handshake itself. try testing.expect(pair.session().pathValidated(0)); // A path opened later is validated by a PATH_CHALLENGE answered, which // `openValidatedPath` waits for by asking this. const opened = try test_pair.openValidatedPath(&pair, &second); try testing.expect(pair.session().pathValidated(opened.route));}
/// draft-ietf-quic-multipath-21: sends new data on path `id` -- the/// protocol's path ID, as `openPath` returned it -- under the/// `Connection.Scheduler.chosen` scheduler. `error.NotAllowed` for a path/// that is not open or not yet validated. See `Connection.useSendPath`.pub fn useSendPath(s: *Session, id: u32) error{NotAllowed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.useSendPath(id); s.flushLocked();}
test useSendPath { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io);
var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
const opened = try test_pair.openValidatedPath(&pair, &second); try session.useSendPath(opened.id);
var answer: [64]u8 = undefined; try testing.expectEqualStrings("by path 1", try test_pair.exchange(session, "by path 1", &answer));}
/// draft-ietf-quic-multipath-21: chooses how new data is spread over paths./// Takes effect from the next packet built. See `Connection.Scheduler`.pub fn setScheduler(s: *Session, scheduler: quic.Connection.Scheduler) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.connection.setScheduler(scheduler);}
test setScheduler { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// Whichever path is fastest and has room. With only path 0 open there is // one candidate, so this changes nothing yet. session.setScheduler(.lowest_rtt); var answer: [64]u8 = undefined; try testing.expectEqualStrings("scheduled", try test_pair.exchange(session, "scheduled", &answer));}
/// draft-ietf-quic-multipath-21 §3.3: closes path `id`, the protocol's path/// ID, with a PATH_ABANDON. `error.NotAllowed` for a path that is not open,/// and for path 0 when it is the only path open. See/// `Connection.abandonPath`.pub fn abandonPath(s: *Session, id: u32) error{NotAllowed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.abandonPath(id); s.flushLocked();}
test abandonPath { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io);
var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
const opened = try test_pair.openValidatedPath(&pair, &second); try session.abandonPath(opened.id); // Gone, so it can carry nothing more, and path 0 carries on. try testing.expectError(error.NotAllowed, session.useSendPath(opened.id)); var answer: [64]u8 = undefined; try testing.expectEqualStrings("on path 0", try test_pair.exchange(session, "on path 0", &answer));}
/// draft-ietf-quic-ack-frequency-14 §4: asks the peer to acknowledge once/// more than `threshold` ack-eliciting packets have arrived or/// `max_ack_delay` *nanoseconds* have passed, and at once on reordering of/// `reordering` packets or more (0 for never). Less often than the/// default, usually, which is what makes it worth asking.////// `error.NotSupported` unless the peer sent `min_ack_delay`, and/// `error.InvalidDelay` for a delay below it or of 2^14 milliseconds or more./// See `Connection.requestAckFrequency`.pub fn requestAckFrequency(s: *Session, threshold: u64, max_ack_delay: u64, reordering: u64) error{ NotSupported, InvalidDelay }!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.requestAckFrequency(threshold, max_ack_delay, reordering); s.flushLocked();}
test requestAckFrequency { var local = test_pair.local; // Microseconds, where the delay asked for below is nanoseconds. local.min_ack_delay = 1000; var pair: test_pair.Pair = undefined; try pair.start(.{ .local = local }); defer pair.stop(); const session = pair.session();
// Every tenth packet, or 50 ms, and never early for reordering. try session.requestAckFrequency(10, 50 * std.time.ns_per_ms, 0); // Below what the peer said it can do. try testing.expectError( error.InvalidDelay, session.requestAckFrequency(10, 100 * std.time.ns_per_us, 0), );}
/// draft-ietf-quic-ack-frequency-14 §5: asks the peer to acknowledge now,/// with an IMMEDIATE_ACK. `error.NotSupported` unless the peer sent/// `min_ack_delay`.pub fn requestImmediateAck(s: *Session) error{NotSupported}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.requestImmediateAck(); s.flushLocked();}
test requestImmediateAck { var local = test_pair.local; local.min_ack_delay = 1000; var pair: test_pair.Pair = undefined; try pair.start(.{ .local = local }); defer pair.stop();
try pair.session().requestImmediateAck();}
/// n0's NAT traversal: offers one of this endpoint's addresses to the peer./// A server advertises it at once; a client sends it with its next/// `startNatRound`. `error.NotNegotiated` unless `natNegotiated`, and/// `error.TooManyAddresses` past what the peer said it would take. See/// `Connection.addNatAddress`.pub fn addNatAddress(s: *Session, address: net.IpAddress) error{ NotNegotiated, TooManyAddresses }!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.addNatAddress(frameAddress(address)); s.flushLocked();}
test addNatAddress { var pair: test_pair.Pair = undefined; try pair.start(.{ .local = nat_local, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
// The address the client's socket is bound to, which is a candidate the // server could reach it at. try session.addNatAddress(pair.client_socket.address);}
/// n0's NAT traversal: withdraws an address `addNatAddress` offered, which/// a server says so with REMOVE_ADDRESS. An address that was never offered/// is no error. `error.NotNegotiated` unless `natNegotiated`.pub fn removeNatAddress(s: *Session, address: net.IpAddress) error{NotNegotiated}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.removeNatAddress(frameAddress(address)); s.flushLocked();}
test removeNatAddress { var pair: test_pair.Pair = undefined; try pair.start(.{ .local = nat_local, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
try session.addNatAddress(pair.client_socket.address); try session.removeNatAddress(pair.client_socket.address); // With nothing left to offer, there is no round to start. try testing.expectError(error.NoLocalAddresses, session.startNatRound());}
/// n0's NAT traversal: a client starts a round of hole punching, sending/// its `addNatAddress` addresses to the server and probing the server's./// `error.NotClient` on a server, and `error.NoLocalAddresses` when nothing/// has been offered. See `Connection.startNatRound`.pub fn startNatRound(s: *Session) error{ NotNegotiated, NotClient, NoLocalAddresses }!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.startNatRound(s.now()); s.flushLocked();}
test startNatRound { var pair: test_pair.Pair = undefined; try pair.start(.{ .local = nat_local, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
try session.addNatAddress(pair.client_socket.address); try session.startNatRound();}
/// Whether both ends asked for n0's NAT traversal, with multipath in use./// False until the peer's transport parameters have arrived.pub fn natNegotiated(s: *Session) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.natNegotiated();}
test natNegotiated { var pair: test_pair.Pair = undefined; try pair.start(.{ .local = nat_local, .sizes = .{ .paths = 2 } }); defer pair.stop();
try testing.expect(pair.session().natNegotiated());}
/// `local` with n0's NAT traversal asked for, which needs multipath too.const nat_local: quic.parameters.Parameters = blk: { var p = test_pair.multipath; p.n0_nat_traversal = 4; break :blk p;};
/// draft-ietf-quic-multipath-21 §3.3: tells the peer, with PATH_STATUS,/// whether path `id` is one to use or a backup to use only when nothing/// else is. Any path ID up to the peer's limit may be named, even one not in/// use yet; `error.NotAllowed` without multipath, past that limit, or for a/// path that has been abandoned. See `Connection.setPathStatus`.pub fn setPathStatus(s: *Session, id: u32, status: quic.frame.PathStatus.Status) error{NotAllowed}!void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.setPathStatus(id, status); s.flushLocked();}
test setPathStatus { var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
try session.setPathStatus(0, .backup); try session.setPathStatus(0, .available); // Both ends allowed path IDs up to 1, so there is no path 5 to name. try testing.expectError(error.NotAllowed, session.setPathStatus(5, .backup));}
/// Fires the connection's timers, but only those that are due.////// The distinction is the whole of this function. `Connection.onTimeout` does/// not ask whether a timer expired -- it *is* the expiry: §6.2 of RFC 9002's/// probe timeout puts the entire outstanding flight back on the wire and/// doubles the backoff, because the only reason to call it is that nothing/// has been heard. Calling it on a connection whose timer is not due/// retransmits a flight that is still perfectly in flight and doubles a/// backoff that was never triggered, which is invisible on a small exchange/// and takes a large one apart.pub fn tick(s: *Session) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io);
const at = s.now(); const due = s.connection.timeout() orelse return; if (due > at) return;
s.connection.onTimeout(at); s.flushLocked(); s.arrived.broadcast(s.io);}
test tick { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// What a pump does at the end of every turn, whether or not a timer is // due. Called with nothing due, as here, it does nothing at all. session.tick(); try testing.expect(session.isEstablished()); try testing.expectEqual(@as(?quic.close.State, null), session.closeState());}
/// When this connection next wants `tick`, in `now`'s nanoseconds, or null/// if it is waiting on nothing.pub fn timeout(s: *Session) ?u64 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.timeout();}
test timeout { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// An open connection always has its idle timer (§10.1), so a pump knows // how long it may wait for a datagram before it has to tick. const due = session.timeout() orelse return error.NoTimer; const at = session.now(); const wait = if (due > at) due - at else 0; try testing.expect(wait <= 5 * std.time.ns_per_s);}
/// Says that nothing further will arrive, and wakes everything waiting:/// `accept`, `readDatagram` and `waitEstablished` answer null or false from/// then on, and a stream's reader and writer fail.////// The pump's to call, once it will deliver nothing more to this session./// It does not close the connection.pub fn finish(s: *Session) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.done = true; s.arrived.broadcast(s.io);}
test finish { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
session.finish(); // A task waiting for a stream would otherwise wait for ever. try testing.expectEqual(@as(?Stream, null), session.accept());}
/// The path number for an address, assigning one if this is the first time it/// has been heard from.////// Null when the table is full, which means a peer has been seen at more/// addresses than §9 migration needs -- the datagram is dropped rather than/// evicting a path the connection is still using.fn pathOf(s: *Session, from: net.IpAddress) ?quic.path.Id { for (&s.peers, 0..) |maybe, i| { const seen = maybe orelse continue; if (seen.eql(&from)) return @intCast(i); } for (&s.peers, 0..) |*slot, i| { if (slot.* != null) continue; slot.* = from; return @intCast(i); } // Full. A route the connection has finished with -- a candidate NAT // traversal probed that went nowhere, say -- is given to the new // address; one it is still using never is. for (s.peers[1..], 1..) |*slot, i| { const route: quic.path.Id = @intCast(i); if (s.connection.routeInUse(route)) continue; s.connection.forgetRoute(route); slot.* = from; s.path_sockets[route] = null; return route; } return null;}
/// `address` as `socket` can send to it: an IPv4 address in its IPv4-mapped/// IPv6 form for an IPv6 socket, which is dual-stack and says so for every/// IPv4 peer it hears from.fn forSocket(socket: *const net.Socket, address: quic.frame.Address) net.IpAddress { if (socket.address == .ip6) switch (address.ip) { .v4 => |v4| { var mapped: [16]u8 = @splat(0); mapped[10] = 0xff; mapped[11] = 0xff; @memcpy(mapped[12..16], &v4); return .{ .ip6 = .{ .bytes = mapped, .port = address.port } }; }, .v6 => {}, }; return ipAddress(address);}
// -- what the application sees ---------------------------------------------
/// The next stream the peer opened that has not been handed over yet.////// Blocks until there is one or until the connection is finished with, so a/// caller's loop is `while (session.accept()) |stream|` and null is the end/// of it.////// There is no deadline, and it does not need one. §10.1 of RFC 9000 gives/// every connection an idle timeout, so a connection that has gone quiet is/// one the pump will close on its own -- at which point `done` is set and/// this returns. The same fact was a trap when writing the drivers, where/// "run until there is nothing left to do" ran until the connection timed/// out; here it is the guarantee that makes an unbounded wait safe, because/// the thing being waited for always eventually arrives or stops existing.////// Null too when the wait is canceled, with the cancelation re-armed for/// the caller's next cancelation point -- see `waitArrived`.pub fn accept(s: *Session) ?Stream { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io);
while (true) { if (s.connection.accept()) |id| { return .{ .session = s, .id = id }; } if (s.done or s.connection.closeState() != null) return null; if (!s.waitArrived()) return null; }}
test accept { // A server that opens a stream of its own and says "hello" on it. var pair: test_pair.Pair = undefined; try pair.start(.{ .serve = test_pair.greeter }); defer pair.stop(); const session = pair.session();
const stream = session.accept() orelse return error.NoStream; try testing.expectEqual(quic.stream.Directionality.unidirectional, stream.id.directionality());
var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("hello", answer[0..n]);}
/// RFC 9221: the next unreliable datagram, copied into `buffer`, which it/// answers a slice of. A datagram longer than `buffer` is cut short to fit,/// and the rest of it is lost.////// Blocks like `accept`, and ends the same way -- null when the connection is/// finished with. A datagram is not a stream, so it does not arrive through/// `accept`, and an application that wants both runs a task for each. That is/// not a workaround: the two are genuinely independent, and an application/// that folded them into one loop would be deciding for its caller that a/// datagram may wait behind a request.pub fn readDatagram(s: *Session, buffer: []u8) ?[]u8 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io);
while (true) { if (s.connection.readDatagram()) |payload| { const n = @min(payload.len, buffer.len); @memcpy(buffer[0..n], payload[0..n]); s.connection.takeDatagram(); return buffer[0..n]; } if (s.done or s.connection.closeState() != null) return null; if (!s.waitArrived()) return null; }}
test readDatagram { var local = test_pair.local; local.max_datagram_frame_size = 1200; // A server that sends every datagram back. var pair: test_pair.Pair = undefined; try pair.start(.{ .local = local, .serve = test_pair.datagram_echo }); defer pair.stop(); const session = pair.session();
try session.sendDatagram("unreliable"); var buffer: [1200]u8 = undefined; const got = session.readDatagram(&buffer) orelse return error.Closed; try testing.expectEqualStrings("unreliable", got);}
/// RFC 9221: queues an unreliable datagram and sends it.////// `error.StreamStateError` when the peer did not offer/// `max_datagram_frame_size`, or the handshake has not given its answer yet,/// and `error.NoRoom` for a datagram too large for what it offered or with/// the queue full. That it was sent is no promise that it will arrive.pub fn sendDatagram(s: *Session, bytes: []const u8) !void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.sendDatagram(bytes); s.flushLocked();}
test sendDatagram { var local = test_pair.local; local.max_datagram_frame_size = 1200; var pair: test_pair.Pair = undefined; try pair.start(.{ .local = local, .serve = test_pair.datagram_echo }); defer pair.stop(); const session = pair.session();
try session.sendDatagram("ping"); var buffer: [1200]u8 = undefined; try testing.expectEqualStrings("ping", session.readDatagram(&buffer) orelse return error.Closed);
// A datagram is one packet and is never split across two. const large: [2000]u8 = @splat(0); try testing.expectError(error.NoRoom, session.sendDatagram(&large));}
/// Waits for the handshake to finish.////// What it is for is the moment before a connection can be used at all. An/// application protocol that opens streams of its own -- HTTP/3 opens three/// before it will answer anything -- cannot open them until the peer's/// transport parameters have arrived, because those parameters are what say/// how many streams it may open (§4.6 of RFC 9000). Before the handshake/// those limits are zero and every open is a STREAM_LIMIT_ERROR, which looks/// like a bug in the application and is a bug in its timing.////// False when the connection ended first, which is the other thing that can/// happen to a handshake -- and when the wait was canceled, as with/// `accept`.pub fn waitEstablished(s: *Session) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io);
while (!s.connection.isEstablished()) { if (s.done or s.connection.closeState() != null) return false; if (!s.waitArrived()) return false; } return true;}
test waitEstablished { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// `Client.connect` has already waited, so this answers at once; a server // handler, handed its session at the first Initial, is where the wait is // real -- see the test pair's `greet`. if (!session.waitEstablished()) return error.HandshakeFailed; const stream = try session.openUnidirectional(); try testing.expect(stream.id.isLocal(.client));}
/// Whether the handshake has finished. Does not wait; see `waitEstablished`.pub fn isEstablished(s: *Session) bool { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.isEstablished();}
test isEstablished { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop();
try testing.expect(pair.session().isEstablished());}
/// draft-ietf-quic-address-discovery-01: the address the peer says this/// endpoint's datagrams arrive from, or null if it has said nothing -- which/// it does only if this endpoint asked, in `address_discovery`.pub fn observedAddress(s: *Session) ?net.IpAddress { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const observed = s.connection.observedAddress() orelse return null; return ipAddress(observed);}
test observedAddress { var local = test_pair.local; local.address_discovery = .both; var pair: test_pair.Pair = undefined; try pair.start(.{ .local = local }); defer pair.stop(); const session = pair.session();
// The report arrives in a frame of its own, so it may follow the // handshake by a moment. var turns: usize = 0; const observed = while (true) : (turns += 1) { if (session.observedAddress()) |address| break address; if (turns > 1000) return error.NoObservation; try testing.io.sleep(.fromMilliseconds(1), .awake); }; // On loopback there is no NAT, so it is the address the socket is bound // to; behind one it would be the NAT's. try testing.expect(observed.eql(&pair.client_socket.address));}
/// A socket address as the library carries one. `ipAddress` is the way/// back./// The address datagrams arriving on `socket` were sent to, if the socket/// can say: null for one bound to the unspecified address.////// Such a socket takes datagrams for every address the host has, and Zig/// 0.17 has no way to ask which one a datagram was sent to -- so its own/// address names none of them, and telling the connection it did would let/// RFC 9000 §9.4 mistake a move to another of the host's addresses for a/// NAT rebinding.fn localAddress(socket: *const net.Socket) ?quic.frame.Address { const octets: []const u8 = switch (socket.address) { .ip4 => |v4| &v4.bytes, .ip6 => |v6| &v6.bytes, }; for (octets) |octet| if (octet != 0) return frameAddress(socket.address); return null;}
test localAddress { var socket: net.Socket = .{ .handle = undefined, .address = try .parse("192.0.2.7", 4433) }; try testing.expect(localAddress(&socket).?.eql(frameAddress(socket.address))); socket.address = try .parse("0.0.0.0", 4433); try testing.expectEqual(@as(?quic.frame.Address, null), localAddress(&socket)); socket.address = try .parse("::", 4433); try testing.expectEqual(@as(?quic.frame.Address, null), localAddress(&socket));}
pub fn frameAddress(a: net.IpAddress) quic.frame.Address { return switch (a) { .ip4 => |v4| .{ .ip = .{ .v4 = v4.bytes }, .port = v4.port }, .ip6 => |v6| .{ .ip = .{ .v6 = v6.bytes }, .port = v6.port }, };}
test frameAddress { const socket_address: net.IpAddress = try .parse("192.0.2.7", 4433); const carried = frameAddress(socket_address); try testing.expectEqual(@as(u16, 4433), carried.port); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 7 }, &carried.ip.v4);}
/// The library's address as a socket address, which is `frameAddress`/// undone. An IPv6 address comes back with no interface index, since the/// library carries none.pub fn ipAddress(a: quic.frame.Address) net.IpAddress { return switch (a.ip) { .v4 => |bytes| .{ .ip4 = .{ .bytes = bytes, .port = a.port } }, .v6 => |bytes| .{ .ip6 = .{ .bytes = bytes, .port = a.port } }, };}
test ipAddress { const original: net.IpAddress = try .parse("2001:db8::1", 853); const back = ipAddress(frameAddress(original)); try testing.expect(back.eql(&original));}
/// RFC 9368: the Version Information the peer sent, if it sent any. Null/// before its transport parameters have arrived.pub fn peerVersionInformation(s: *Session) ?quic.parameters.VersionInformation { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const peer = s.connection.peer orelse return null; return peer.version_information;}
test peerVersionInformation { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop();
// Both ends of this library send it unless told otherwise. const info = pair.session().peerVersionInformation() orelse return error.NoVersionInformation; try testing.expectEqual(quic.packet.version_1, info.chosen);}
/// RFC 9287: how many packets from the peer arrived with the QUIC Bit clear./// Only a peer this endpoint told it may, with `grease_quic_bit`, sends any.pub fn greasedPackets(s: *Session) u64 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.greasedPackets();}
test greasedPackets { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop();
// Neither end offered `grease_quic_bit`, so every packet set the bit. try testing.expectEqual(@as(u64, 0), pair.session().greasedPackets());}
/// draft-ietf-quic-multipath-21: how many paths past path 0 have been/// opened on this connection, whether or not they are still open -- and/// whether or not their slots have since been given to new path IDs.pub fn pathsOpened(s: *Session) u64 { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.paths_opened;}
test pathsOpened { const io = testing.io; const loopback: net.IpAddress = try .parse("127.0.0.1", 0); var second = try loopback.bind(io, .{ .mode = .dgram }); defer second.close(io);
var pair: test_pair.Pair = undefined; try pair.start(.{ .local = test_pair.multipath, .sizes = .{ .paths = 2 } }); defer pair.stop(); const session = pair.session();
try testing.expectEqual(@as(u64, 0), session.pathsOpened()); const opened = try test_pair.openValidatedPath(&pair, &second); try session.abandonPath(opened.id); // Abandoned, and still counted. try testing.expectEqual(@as(u64, 1), session.pathsOpened());}
/// RFC 7250: the raw public key the peer proved it holds, or null for a/// certificate handshake or one that has not finished. On an endpoint that/// admits any key, this is who the session is with.pub fn peerPublicKey(s: *Session) ?quic.tls.PublicKey { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.peerPublicKey();}
test peerPublicKey { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop();
// The test pair authenticates nobody, and certainly not by key. try testing.expectEqual(@as(?quic.tls.PublicKey, null), pair.session().peerPublicKey());}
/// §3.5 of RFC 9000: abandons one stream, without touching the connection.////// The thing HTTP/1.1 cannot do, and the reason an application protocol over/// QUIC can refuse one request without dropping the others: the error code is/// the application's own -- RFC 9114's H3_REQUEST_REJECTED, for instance,/// which tells a client that nothing happened and the request may be sent/// again elsewhere.////// Ends only this end's sending half, with a RESET_STREAM; what the peer/// sends still arrives. `error.StreamStateError` for a stream this end/// cannot send on.pub fn resetStream(s: *Session, id: quic.stream.Id, code: u64) !void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.resetStream(id, code); s.flushLocked();}
test resetStream { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
const stream = try session.openBidirectional(); try session.writeStream(stream.id, "half a req"); // RFC 9114's H3_REQUEST_CANCELLED. try session.resetStream(stream.id, 0x10c);
try testing.expectError(error.WriteFailed, session.writeStream(stream.id, "uest")); // The connection, and every other stream on it, carries on. var answer: [64]u8 = undefined; try testing.expectEqualStrings("unharmed", try test_pair.exchange(session, "unharmed", &answer));}
/// §3.5: asks the peer to stop sending on a stream, with a STOP_SENDING.////// A request rather than a state change: what is already in flight still/// arrives, and the peer answers with a RESET_STREAM. `error.StreamStateError`/// for a stream this end does not receive on.pub fn stopSending(s: *Session, id: quic.stream.Id, code: u64) !void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); try s.connection.stopSending(id, code); s.flushLocked();}
test stopSending { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
const stream = try session.openBidirectional(); try session.stopSending(stream.id, 0x10c);
// A stream of this end's own, one way, has nothing coming to stop. const outbound = try session.openUnidirectional(); try testing.expectError(error.StreamStateError, session.stopSending(outbound.id, 0x10c));}
/// §19.19: ends the connection with an error code belonging to whatever is/// running over QUIC rather than to QUIC.////// The 0x1d variant of CONNECTION_CLOSE, which is the one an application/// protocol gets: HTTP/3's H3_FRAME_UNEXPECTED and the rest are codes in that/// space, and sending one as a transport error would tell the peer that QUIC/// itself had been broken.pub fn closeApplication(s: *Session, code: u64, why: []const u8) void { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); s.connection.closeApplication(code, why, s.now()); s.flushLocked(); s.arrived.broadcast(s.io);}
test closeApplication { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// RFC 9114's H3_NO_ERROR, which is how HTTP/3 says it is finished. session.closeApplication(0x100, "done"); try testing.expect(session.closeState() != null); // And everything waiting on the connection is told. try testing.expectEqual(@as(?Stream, null), session.accept());}
/// §10: how this connection ended, if it has -- closing, draining or/// closed -- or null while it is open.pub fn closeState(s: *Session) ?quic.close.State { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.closeState();}
test closeState { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
try testing.expectEqual(@as(?quic.close.State, null), session.closeState()); // §10.2.1: this end sent the CONNECTION_CLOSE, so it is closing rather // than draining. session.closeApplication(0, ""); try testing.expectEqual(@as(?quic.close.State, .closing), session.closeState());}
/// Opens a stream this endpoint will send on and the peer will only read.////// `error.StreamLimitError` when the peer has allowed no more (§4.6), which/// before the handshake is every stream.pub fn openUnidirectional(s: *Session) !Stream { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const id = try s.connection.openUnidirectional(); return .{ .session = s, .id = id };}
test openUnidirectional { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
// The shape of HTTP/3's control stream: written, never answered. const stream = try session.openUnidirectional(); try testing.expectEqual(quic.stream.Directionality.unidirectional, stream.id.directionality()); var w = stream.writer(&.{}); try w.interface.writeAll("settings"); try w.finish();}
/// Opens a stream both ends send on, which is the shape of a request and its/// response.////// `error.StreamLimitError` when the peer has allowed no more (§4.6), which/// before the handshake is every stream.pub fn openBidirectional(s: *Session) !Stream { s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); const id = try s.connection.openBidirectional(); return .{ .session = s, .id = id };}
test openBidirectional { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const session = pair.session();
const stream = try session.openBidirectional(); var w = stream.writer(&.{}); try w.interface.writeAll("request"); try w.finish();
var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("request", answer[0..n]);}
/// The TLS state the connection's handshake points into.////// Owned by the session because the connection does not allocate and the/// handshake must outlive it, and a union because the two ends of a QUIC/// connection run different halves of the same handshake. Nothing else about/// a session differs between them: a stream is a stream whoever opened the/// connection, which is what makes one `Session` serve both.pub const Tls = union(enum) { server: quic.tls_handshake.Server, client: quic.tls_handshake.Client,
/// Whichever half is in use, as the interface `Connection.init` takes. /// It points into `t`, so `t` must not move while the connection is /// using it. pub fn handshake(t: *Tls) quic.tls.Handshake { return switch (t.*) { .server => |*v| v.handshake(), .client => |*v| v.handshake(), }; }
test handshake { var prng: std.Random.DefaultPrng = .init(0x7150); var tls: Tls = .{ .client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"h3"}, .transport_parameters = &.{}, .rng = prng.random(), .now_sec = 0, }) }; const h = tls.handshake(); // A view of the client half, not a copy of it. try testing.expect(h.context == @as(*anyopaque, &tls.client)); try testing.expect(!h.isComplete()); }};
const testing = std.testing;const test_pair = @import("test_pair.zig");