// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A QUIC connection. //! //! Datagrams in one end, datagrams out the other, and everything in between //! is the bookkeeping the rest of this library provides: three packet number //! spaces, each with its own keys, its own acknowledgement tracker and its own //! CRYPTO stream, and a TLS handshake behind `tls.Handshake` being fed by all //! three. //! //! This is `tests/handshake.zig` with the hand-driving taken out. That test //! wrote the sequence down first on purpose — a state machine written before //! the sequence works is a state machine encapsulating a guess — and what is //! here is that sequence with the decisions made in one place. //! //! ## Time comes in from outside //! //! `receive`, `send` and `onTimeout` all take the current time, and //! `timeout` says when the caller should next call `onTimeout`. Nothing here //! reads a clock, for the same reason nothing here opens a socket: a caller //! driving this from a simulated network wants to move time in whatever steps //! the test needs, and a caller driving it from an event loop already has the //! time in hand from whatever woke it. //! //! ## Three spaces, and why they are not one //! //! §12.3: each space numbers its packets from zero, and a packet in one can //! only be acknowledged in a packet of the same kind. That is cryptographic //! separation rather than bookkeeping convenience — the keys differ, so a //! number reused across two spaces is protected by two different keys and //! means two different things. 0-RTT and 1-RTT share a space because they //! share keys closely enough that loss recovery would otherwise have to //! reason about both at once. const std = @import("std"); const assert = std.debug.assert; const ack = @import("ack.zig"); const ecn_mod = @import("ecn.zig"); // §10 is titled "Connection Termination", which is also how this is named // here: `close` is the method that ends a connection, and the module it comes // from needs a name of its own. const termination = @import("close.zig"); const congestion_mod = @import("congestion.zig"); const Congestion = congestion_mod.Controller; const ids = @import("connection_id.zig"); const frame = @import("frame.zig"); const mtu = @import("mtu.zig"); const nat_mod = @import("nat.zig"); const outgoing = @import("outgoing.zig"); const packet = @import("packet.zig"); const paths_mod = @import("path.zig"); const parameters = @import("parameters.zig"); const protection = @import("protection.zig"); const recovery = @import("recovery.zig"); const reset = @import("stateless_reset.zig"); const retry_mod = @import("retry.zig"); const stream = @import("stream.zig"); const reassembly = @import("reassembly.zig"); const tls = @import("tls.zig"); const varint = @import("varint.zig"); const Connection = @This(); /// §14.1: "A client MUST expand the payload of all UDP datagrams carrying /// Initial packets to at least 1200 bytes". /// /// The rule is an anti-amplification measure: a server may not send more than /// three times what it has received from an address it has not validated, so /// a client that sent a small Initial would be asking for an answer the /// server is not allowed to give. pub const min_initial_datagram = 1200; pub const Role = enum { client, server }; /// The three packet number spaces of §12.3. pub const Space = enum(u2) { initial = 0, handshake = 1, /// 0-RTT and 1-RTT share one. application = 2, /// The space a packet sealed at `level` is numbered in. /// /// Four levels and three spaces: §12.3 puts 0-RTT and 1-RTT packets in /// the one application space, so a 1-RTT acknowledgement can acknowledge /// a 0-RTT packet and loss recovery does not have to reason about two /// spaces that share a peer's view of the connection. pub fn of(level: tls.Level) Space { return switch (level) { .initial => .initial, .handshake => .handshake, .early_data, .application => .application, }; } test of { try std.testing.expectEqual(Space.handshake, Space.of(.handshake)); // 0-RTT and 1-RTT number their packets in the same space. try std.testing.expectEqual(Space.application, Space.of(.early_data)); try std.testing.expectEqual(Space.application, Space.of(.application)); } /// The encryption level a space's packets are sealed at once the /// handshake has finished with it. /// /// Not quite the inverse of `of`: the application space answers 1-RTT, /// because 0-RTT is the exception a client lives with for one flight and /// not the level the space is for. pub fn encryptionLevel(s: Space) tls.Level { return switch (s) { .initial => .initial, .handshake => .handshake, .application => .application, }; } test encryptionLevel { try std.testing.expectEqual(tls.Level.initial, Space.initial.encryptionLevel()); try std.testing.expectEqual(tls.Level.application, Space.application.encryptionLevel()); // A round trip through `of` is the identity for every space. for ([_]Space{ .initial, .handshake, .application }) |s| { try std.testing.expectEqual(s, Space.of(s.encryptionLevel())); } } }; /// How much out-of-order CRYPTO data each space will hold. /// /// The handshake space is the one that needs room: a server's Certificate /// message carries a whole chain and routinely spans several packets. The /// other two carry a ClientHello and the occasional NewSessionTicket. const crypto_window = [3]usize{ 4096, 16384, 4096 }; /// How much of the *outgoing* CRYPTO stream each space keeps. /// /// Kept rather than forgotten because a lost packet is recovered by sending /// its frames again (§13.3 of RFC 9000), and `tls.Handshake.emit` hands its /// bytes over exactly once — so if this does not keep a copy, nothing can. /// The handshake level is the large one for the same reason as above: a /// certificate chain. const crypto_out_window = [3]usize{ 4096, 16384, 4096 }; /// How much CRYPTO data one packet will carry. /// /// Small enough that a frame plus its header plus the packet's own overhead /// fits inside any plausible path MTU, so a flight longer than that is split /// across packets rather than refused. Splitting only became possible once /// there was something to recover a lost piece with. const max_crypto_chunk = 1000; /// The smallest buffer worth starting another coalesced packet in: a long /// header with two connection IDs, a token, a length and a packet number, /// §5.4.2's three octets of frames, and the AEAD tag. const min_packet_room = 128; /// What a CRYPTO frame costs before its data: a type octet and two varints, /// each of which may be eight octets wide. Assuming the worst rather than /// measuring it can leave a few octets of a packet unused, which is cheaper /// than being wrong in the other direction. const crypto_frame_overhead = 1 + 8 + 8; /// What a STREAM frame costs before its data: a type octet and three varints /// — the stream identifier, the offset and the length — each of which may be /// eight octets wide. const stream_frame_overhead = 1 + 8 + 8 + 8; /// §6.6 of RFC 9001: "For AEAD_AES_128_GCM and AEAD_AES_256_GCM, the /// confidentiality limit is 2^23 encrypted packets." /// /// The lowest of the three limits the QUIC-legal suites have, applied to all /// of them. Being early costs a key update that was not strictly needed; /// being late costs the guarantee the limit exists for. const confidentiality_limit: u64 = 1 << 23; /// §6.6: "For AEAD_AES_128_GCM and AEAD_AES_256_GCM, the integrity limit is /// 2^52 invalid packets", and 2^36 for ChaCha20-Poly1305 — the lower of which /// is what is applied here. /// /// This one has teeth in a way the confidentiality limit does not: a peer /// cannot make an endpoint encrypt packets, but anyone who can reach the /// socket can make it *try* to decrypt them. §6.6 requires the connection to /// close rather than carry on counting. const integrity_limit: u64 = 1 << 36; /// §19.3 of RFC 9000: the default `ack_delay_exponent`, which scales the ACK /// frame's delay field. Both ends use 3 until a transport parameter says /// otherwise; `ackDelayExponent` is what reads the peer's. const ack_delay_exponent = 3; /// §18.2: the default `max_ack_delay`, 25ms — how long a peer may sit on an /// acknowledgement before sending it, used until the peer's transport /// parameters say otherwise. `maxAckDelay` is what reads theirs. const default_max_ack_delay: recovery.Duration = 25 * std.time.ns_per_ms; /// draft-ietf-quic-multipath-21: the most paths one connection will hold at /// once, path 0 included. A bound on memory rather than on the protocol, /// which allows 2^32; `Sizes.paths` is how many a connection actually has /// room for, up to this. pub const max_paths = 4; /// A path other than path 0, when multipath is in use. /// /// Path 0 keeps living where it always has -- `spaces[2]`, `rtt` and /// `congestion` -- so that a connection with one path is the same /// connection it was before multipath existed, down to the field. A further /// path has the same three things of its own: §2.4 gives each path its own /// packet number space, and §5.3 and §5.4 its own congestion control and /// RTT. What it does not have is keys or a CRYPTO stream, which belong to /// the encryption level and are shared. /// /// Its multipath path ID is a different number from `route`, the caller's /// number for the 4-tuple the path runs over, and conflating the two is the /// first mistake this code invites: a path ID names a packet number space /// and a set of connection IDs, and the 4-tuple under it can change. const ExtraPath = struct { state: enum { unused, open, abandoned } = .unused, /// The multipath path ID. id: u32 = 0, /// The caller's path this one runs over. route: paths_mod.Id = 0, /// The route `rtt`, `congestion`, `pmtu` and `ecn` were learned on; see /// `Connection.measured_route`, which is the same for path 0. measured_route: paths_mod.Id = 0, /// RFC 9000 §9.3: the highest packet number a non-probing packet on this /// path has carried, so that a reordered one from an address the path /// has left does not drag it back there. Per path rather than per route /// as path 0's is, because each path numbers its packets on its own. highest_seen: u64 = 0, /// Only the numbering fields are used: `next_number`, `acks`, /// `peer_ecn` and `loss`. Keys and CRYPTO are `spaces[2]`'s. space: SpaceState = .{}, rtt: recovery.Rtt = .{}, congestion: Congestion = .{}, /// §3.2: each path's connection IDs, with sequence numbers of their own /// starting at zero. The ones this endpoint issued for the path, which /// is how an arriving packet is known to be on it; and the ones the peer /// issued, which address what this endpoint sends on it. issued: ids.Issued = .{}, received: ids.Received = .{}, /// §3.4: a PATH_ABANDON is owed for this path, and whether one has gone. owes_abandon: bool = false, sent_abandon: bool = false, /// The sequence number of a PATH_NEW_CONNECTION_ID for this path that /// was lost and is owed again. offer_owed: ?u64 = null, /// §3.4: whether the peer has abandoned this path, and when this /// endpoint stops keeping its state -- "3 PTO after the PATH_ABANDON /// frame has been received" -- and gives the slot to a new path ID. peer_abandoned: bool = false, discard_at: ?recovery.Instant = null, /// §3.3: the status each end has advertised for this path. status: PathStatus = .{}, /// §4.7: a PATH_CIDS_BLOCKED is owed for this path, and the Next /// Sequence Number the last one reported, which is not reported twice. cids_blocked_owed: bool = false, cids_blocked_sent: ?u64 = null, /// §5.8: this path's own PMTU search. "The DPLPMTUD Maximum Packet Size /// (MPS) is maintained for each combination of local and remote IP /// addresses", and a second path is usually a second such combination /// -- sized by path 0's search, it could be sent datagrams its route /// cannot carry. pmtu: mtu.Search = .{}, /// §13.4.2 of RFC 9000: this path's own ECN validation. A path is "a /// different set of network elements", and one that erases or rewrites /// markings says nothing about another that does not -- so each is /// tested, marked and failed on its own, against the counts its own /// packet number space's PATH_ACK frames report. ecn: ecn_mod.Validator = .{}, }; /// draft-ietf-quic-multipath-21 §3.3: one path's PATH_STATUS_AVAILABLE and /// PATH_STATUS_BACKUP, in both directions. Each direction has its own /// sequence numbers, and "each peer indicates its preference of path usage /// independently of the other peer". const PathStatus = struct { /// What this endpoint asked for, whether it is owed, the sequence number /// the next one goes out with, and the one the last one went out with. local: ?frame.PathStatus.Status = null, owed: bool = false, next_sequence: u64 = 0, sent_sequence: ?u64 = null, /// What the peer asked for, and the sequence number it came with: "a /// peer MUST ignore an incoming PATH_STATUS_AVAILABLE or /// PATH_STATUS_BACKUP frame if it previously received another... for /// the same path ID with a Path Status sequence number equal to or higher". peer: ?frame.PathStatus.Status = null, peer_sequence: ?u64 = null, fn onPeer(s: *PathStatus, p: frame.PathStatus) void { if (s.peer_sequence) |seen| if (p.sequence <= seen) return; s.peer = p.status; s.peer_sequence = p.sequence; } fn peerBackup(s: *const PathStatus) bool { return s.peer == .backup; } }; /// The loss-recovery state one packet number space answers to: its table, /// and the RTT estimator and congestion controller of the path it runs over. /// For the Initial and Handshake spaces and path 0 those are the /// connection's own; for a further path they are the path's. const Recovery = struct { space: *SpaceState, rtt: *recovery.Rtt, congestion: *Congestion, /// Whether this is an application space, whose acknowledgement delay is /// scaled and counted (§5.3 of RFC 9002, §6.2.1). application: bool, /// The ECN validator of the path this space numbers, for an application /// space; null for Initial and Handshake, which §13.4.2.1's checks are /// not run on. ecn: ?*ecn_mod.Validator, /// The PMTU search of the path this space numbers, for an application /// space. pmtu: ?*mtu.Search, /// The congestion controller's own index for the space, which it keys /// its Congestion Experienced counts by. index: u2, }; const SpaceState = struct { /// Null until the keys for this space exist. §12.5: a packet that cannot /// be decrypted is discarded, not queued, and that includes one that /// arrives before its keys do. write: ?protection.Keys = null, read: ?protection.Keys = null, next_number: u64 = 0, acks: ack.Tracker = .{}, /// The ECN counts the peer reported for this space in the last ACK frame /// that advanced the largest acknowledged. /// /// §13.4.2.1 validates an ACK's counts "by comparing newly received /// counts against those from the last successfully processed ACK frame", /// which is what this is for; it is also the answer to whether the peer /// reports counts at all, since "ECN validation fails if the /// corresponding ECN counts are not present in the ACK frame". peer_ecn: ?frame.Ack.Ecn = null, /// The incoming CRYPTO stream for this level. stream: reassembly.Reassembler = undefined, /// The outgoing CRYPTO stream for this level. §19.6 gives each encryption /// level a stream of its own, each starting at offset zero — and says a /// CRYPTO frame "is similar to a STREAM frame, except that it does not /// have a Stream ID, it is not flow controlled, and it does not have a /// FIN", which is why the machinery for sending one is shared with /// streams rather than written twice. crypto: outgoing.Outgoing = .init(&.{}), /// What has been sent in this space and not yet acknowledged. loss: recovery.Space = .{}, fn hasKeys(s: *const SpaceState) bool { return s.read != null and s.write != null; } /// Merges a lost packet's CRYPTO contribution into the range to send /// again. The stream contributions are the connection's business, since /// the streams are not in this space. fn markLost(s: *SpaceState, sent: recovery.Sent) void { s.crypto.markLost(sent.crypto_offset, sent.crypto_len); } }; const Chunk = outgoing.Chunk; /// How many streams one connection will hold at once. /// /// Bounded like everything a peer can ask for: §4.6 has an endpoint limit /// "the cumulative number of incoming streams a peer can open", and this is /// the number behind the limit that is advertised. A stream costs a send /// buffer, a receive buffer and a bitmap, so the memory a connection commits /// is this times that — decided here rather than by whoever is talking to it. /// /// Sixteen because of what runs on top. DNS over QUIC needs one stream at a /// time and four was generous for it; HTTP/3 opens *six* before it will /// answer anything, three unidirectional in each direction (§6.2 of RFC /// 9114: a control stream and the two QPACK streams, per peer), and every /// request is another. A table of four is not a tight budget for that, it is /// a connection that cannot complete its own setup -- which is how this /// number was found, as a `NoRoom` from the third stream an HTTP/3 server /// opens. pub const max_streams = 16; /// How much each stream will hold in each direction, absent a caller saying /// otherwise. pub const stream_buffer = 4096; /// How much memory a connection is to be given, and therefore what it can /// promise. /// /// Every one of these is a number the protocol lets an endpoint choose and /// the path decides the value of, which is why they are the caller's rather /// than this file's. The defaults are what a connection had when they were /// constants, so a caller that says nothing gets what it had before. /// /// They are not independent, and the ways they are coupled are the ways this /// goes wrong: /// /// * `recv_window` is a promise. It is advertised in the transport /// parameters, §4.1 of RFC 9000 lets a window grow and never shrink, and a /// peer that takes the advertisement at its word fills the buffer behind /// it. Advertising more than the buffer holds is how a connection ends up /// with octets it has nowhere to put, which `init` asserts against. /// * `send_window` is not a promise but a ceiling on throughput: §13.3 has a /// retransmission carry the contents of a lost frame, so an octet is held /// until the peer says it arrived, and a stream can have no more than this /// in the air. It is what bounds a download, and it is the one to raise /// first. /// * `tracked` is how many unacknowledged packets a space remembers, and it /// has to cover what `send_window` puts in the air -- the same packets /// counted from the other end. Too few and the connection forgets a packet /// for every packet it sends, which is not a slowdown but a livelock. pub const Sizes = struct { /// Per stream, and what bounds a download. send_window: usize = stream_buffer, /// Per stream, and what may be advertised. recv_window: usize = stream_buffer, /// Unacknowledged packets remembered, per packet number space. /// /// A send window in its own right, and the one counted in packets rather /// than octets: an ack-eliciting packet needs a slot before it may go, /// so a connection whose table is full waits for an acknowledgement /// exactly as one whose congestion window is closed does. Sizing it /// short is therefore a throughput decision and not a correctness one -- /// see `recovery.Space.full` for what it used to be instead. /// /// The floor `init` asserts covers *one* stream's `send_window`, which /// is all it can know there. A connection whose streams are all busy /// wants a multiple of that, and gets a slower connection rather than a /// broken one if it does not. tracked: usize = recovery.max_tracked, /// draft-ietf-quic-multipath-21: how many paths the connection can hold /// at once, path 0 included. Each path past the first numbers its own /// packets and so needs its own `tracked` table; one is a connection /// that can negotiate multipath and use only path 0. paths: usize = 1, /// The floor `tracked` has to clear for `send_window`, which is the /// number of smallest-permitted datagrams that window holds. /// /// A floor and not an estimate: a sender whose packets are smaller than /// §14.1's minimum -- which is every sender with something small to say /// -- puts more of them in the air than this, and wants more than this. pub fn trackedFloor(s: Sizes) usize { return (s.send_window + min_initial_datagram - 1) / min_initial_datagram; } test trackedFloor { // A 64 KiB window is 55 datagrams of 1200 octets, rounded up. const sizes: Sizes = .{ .send_window = 64 * 1024 }; try std.testing.expectEqual(@as(usize, 55), sizes.trackedFloor()); // The defaults clear their own floor with room to spare. const defaults: Sizes = .{}; try std.testing.expect(defaults.tracked >= defaults.trackedFloor()); } }; /// The memory a connection runs on, which the caller owns. /// /// Slices rather than a length and an allocator, because this library does /// not allocate: a caller with a heap hands it slices from one, and a caller /// without hands it a `Storage` declared wherever it likes. pub const Memory = struct { /// `max_streams` send buffers, end to end. send: []u8, /// `max_streams` receive buffers, end to end. recv: []u8, /// The reassembly bitmaps behind those receive buffers, one bit an octet. present: []u8, /// One table of tracked packets for each of the Initial and Handshake /// spaces and one for each path's application space, end to end: `2 + /// paths` tables of equal length. tracked: []recovery.Sent, /// Three scratch buffers, each one table long, for what loss detection /// removes. scratch: []recovery.Sent, /// How many paths `tracked` has tables for. See `Sizes.paths`. paths: usize = 1, }; /// Storage for one connection, for a caller that would rather declare it than /// allocate it. /// /// ```zig /// var storage: quic.Connection.Storage(.{}) = .{}; /// var connection: quic.Connection = undefined; /// connection.init(.{ .memory = storage.memory(), ... }); /// ``` pub fn Storage(comptime sizes: Sizes) type { comptime { if (sizes.recv_window % 8 != 0) @compileError("recv_window must be a multiple of 8, since the reassembly bitmap is one bit an octet"); if (sizes.tracked < sizes.trackedFloor()) @compileError("tracked is too small for send_window: one stream could not put its window in the air without waiting for the table"); if (sizes.paths < 1 or sizes.paths > max_paths) @compileError("paths must be between 1 and max_paths"); } return struct { send: [max_streams * sizes.send_window]u8 = undefined, recv: [max_streams * sizes.recv_window]u8 = undefined, present: [max_streams * (sizes.recv_window / 8)]u8 = undefined, tracked: [(2 + sizes.paths) * sizes.tracked]recovery.Sent = undefined, scratch: [3 * sizes.tracked]recovery.Sent = undefined, /// The `Memory` for `Options.memory`: slices of this struct's own /// arrays, so the storage must stay where it is, and outlive the /// connection built on it. pub fn memory(self: *@This()) Memory { return .{ .send = &self.send, .recv = &self.recv, .present = &self.present, .tracked = &self.tracked, .scratch = &self.scratch, .paths = sizes.paths, }; } }; } test Storage { // Room for multipath with one path besides path 0, and a send window // twice the default. var storage: Storage(.{ .send_window = 2 * stream_buffer, .paths = 2 }) = .{}; const memory = storage.memory(); try testing.expectEqual(@as(usize, max_streams * 2 * stream_buffer), memory.send.len); try testing.expectEqual(@as(usize, 2), memory.paths); // One table for each of Initial and Handshake, and one per path. try testing.expectEqual(@as(usize, 4 * recovery.max_tracked), memory.tracked.len); // What `init` divides it into is what the connection then works with. var tls_client = try testTlsClient(&test_client_parameters); var connection: Connection = undefined; connection.init(.{ .role = .client, .handshake = tls_client.handshake(), .local_id = &test_client_id, .destination_id = &test_destination_id, .memory = memory, }); try testing.expectEqual(@as(usize, 2 * stream_buffer), connection.sendWindow()); } /// How many unreliable datagrams (RFC 9221) this connection will hold in each /// direction at once, and how large each may be. /// /// Bounded like everything else, and here the bound is less of a compromise /// than usual: §5.3 of RFC 9221 says a receiver "MAY drop" a datagram it /// cannot hold, and an application that chose an unreliable transport has /// already agreed that dropping is an outcome. A full queue is therefore a /// legitimate answer rather than a failure to provide for. /// /// The length bound is the largest frame this endpoint advertises it will /// accept, and a datagram has to fit in one packet whatever else is true -- /// §5.1: "a receiver is not required to reassemble", because there is nothing /// to reassemble from. So a value above what §14 guarantees the path will /// carry would be advertising room the network does not have. pub const max_datagrams = 4; pub const max_datagram_len = 1200; pub const Error = error{ /// The peer broke the protocol in a way that ends the connection. ProtocolViolation, /// The TLS handshake failed; `alert` says what it would have sent. HandshakeFailed, /// A frame arrived at an encryption level §12.4 does not permit it at. FrameNotPermitted, /// §18.2 or §7.3: the peer's transport parameters were malformed, out of /// range, or did not match the connection IDs actually used. TransportParameterError, /// RFC 9368 §4: the peer's Version Information names a version other /// than the one this connection is using. VersionNegotiationError, /// §4.1: the peer sent more stream data than it was given credit for. FlowControlError, /// §4.5: the peer said a stream ends in two different places. FinalSizeError, /// §4.6: the peer opened more streams than it was allowed to. StreamLimitError, /// §9.3: a packet arrived from an address this connection has no room to /// track. Not a protocol error — the peer is entitled to move, and this /// endpoint is entitled to a bounded table. TooManyPaths, /// §5.1.1: the peer issued more connection IDs than this endpoint said /// it would maintain. ConnectionIdLimitError, /// §19.15: a frame whose fields cannot mean what they say. FrameEncodingError, /// §6.6 of RFC 9001: this connection has used an AEAD key, or been asked /// to try one, more times than its security margin allows. AeadLimitReached, /// §3.3: a frame that the stream it names does not permit. StreamStateError, /// No room in this connection's stream table, or in a stream's buffer. /// /// Not a protocol error: the peer stayed inside the limits it was given, /// and this endpoint chose those limits. A caller meeting it is being /// told to read what has already arrived. NoRoom, /// Building a packet did not fit in the buffer offered. NoSpace, OutOfMemory, } || reassembly.Error; role: Role, handshake: tls.Handshake, spaces: [3]SpaceState = .{ .{}, .{}, .{} }, /// The connection ID this endpoint puts in the packets it sends, which is the /// one the peer chose for itself. peer_id_buf: [packet.max_connection_id_len]u8 = undefined, peer_id_len: usize = 0, /// The connection ID this endpoint asks the peer to use, and the one it /// expects to see in a short header. local_id_buf: [packet.max_connection_id_len]u8 = undefined, local_id_len: usize = 0, /// Whether the client's first Initial has gone out, which is what decides /// whether a datagram has to be padded to 1200 octets. sent_initial: bool = false, /// §7.2: "Upon first receiving an Initial or Retry packet from the server, /// the client uses the Source Connection ID supplied by the server as the /// Destination Connection ID for subsequent packets." Until then a client is /// addressing packets to a connection ID it made up, which is the only thing /// it can do and the reason §7.3's checks exist. peer_id_confirmed: bool = false, /// The Source Connection ID that confirmed it, which every long header from /// the server must carry from then on (§7.2). Kept apart from `peer_id_buf`, /// which moves on when the client rotates. server_source_buf: [packet.max_connection_id_len]u8 = undefined, server_source_len: usize = 0, /// The Destination Connection ID a client put in its first Initial, kept /// because §7.3 has the server echo it back for the client to check. A /// client chose it at random, so only an endpoint that actually received that /// packet can repeat it. original_destination_buf: [packet.max_connection_id_len]u8 = undefined, original_destination_len: usize = 0, /// §10.3.1: the stateless reset tokens this endpoint is holding, one per /// connection ID the peer has issued and this endpoint has used. /// /// "An endpoint MUST NOT check for any stateless reset tokens associated with /// connection IDs it has not used or for connection IDs that have been /// retired" — an unused token is one the peer could not have chosen to send, /// and a retired one is invalidated by §10.3, so matching either would be /// accepting a teardown nobody authorised. /// /// The key this endpoint mints its *own* tokens with lives in `Options`: a /// static key is what lets §10.3.2 recompute a token after the state it /// described is gone. reset_key: ?reset.Key = null, /// §8.1.2: the token to put in the Token field of an Initial packet, from a /// Retry packet in this attempt or a NEW_TOKEN frame in an earlier one. /// /// Sized for somebody else's format, not ours. §8.1.4: "there is no need for /// a single well-defined format for the token because the server that /// generates the token also consumes it" — so a client has to hold whatever /// it is handed, and this was found to be too small by aioquic, whose Retry /// tokens are 256 octets where ours are 61. §17.2.2 permits more still; a /// token that does not fit is one this client cannot use, which is why the /// check happens before anything is committed rather than after. token_buf: [512]u8 = undefined, token_len: usize = 0, /// §17.2.5.2: "a client MUST accept and process at most one Retry packet for /// each connection attempt" — a second is either an attacker's or a server /// that has lost track, and either way answering it would let somebody walk /// a connection attempt in circles forever. retry_seen: bool = false, /// §7.3: the Source Connection ID of the Retry, which the server must then /// name in its `retry_source_connection_id` transport parameter. Null when no /// Retry happened — and §7.3 makes *that* checkable too: "presence of the /// retry_source_connection_id transport parameter when no Retry packet was /// received" is an error. retry_source_buf: [packet.max_connection_id_len]u8 = undefined, retry_source_len: ?usize = null, /// §14.3: the search for the largest datagram this path will carry. /// /// Until it finds something, every datagram is 1200 octets — the size §14.1 /// guarantees and §14.2 requires an endpoint to stay at "in the absence of /// these mechanisms". Staying there is correct and slow. pmtu: mtu.Search = .{}, /// §8.2 and §9: the paths this connection knows about, and which one it /// sends on. paths: paths_mod.Paths = .{}, /// §9.4: the path `congestion`, `rtt`, `ecn` and `pmtu` were learned on. /// /// Not always the active one: a connection that has moved to an address not /// yet validated keeps sending by the old path's numbers until the move is /// confirmed, and one that moves back before then -- §9.3.3's spurious /// migration, which anyone who can forge a source address can cause -- is /// still on the path those numbers describe, and keeps them. measured_route: paths_mod.Id = 0, /// §5.1: the identifiers this endpoint has issued and must answer to, and /// the ones the peer has issued and may be addressed by. Both start with the /// one the handshake used, which §5.1.1 numbers zero. issued: ids.Issued = .{}, received: ids.Received = .{}, /// Entropy for the identifiers and reset tokens this endpoint issues. /// /// §5.1.1 does not say they must be unpredictable, but §10.3's stateless /// reset token travelling beside each one does — a guessable token is a way /// to tear down somebody else's connection — and an identifier a third party /// can guess is an identifier it can use to probe for the connection's /// existence. id_rng: ?std.Random = null, /// The peer's transport parameters, once the handshake has produced them. peer: ?parameters.Parameters = null, /// Whether `peer` is what the server said on *this* connection, rather than /// what it said on the one that issued the session ticket. /// /// §7.4.1: the remembered values stand in until the real ones arrive, so the /// question "do we have the peer's parameters?" has two different answers /// depending on who is asking -- a 0-RTT sender needs limits, and the checks /// of §7.3 need the real ones. peer_confirmed: bool = false, peer_id_storage: parameters.IdStorage = .{}, /// What this endpoint advertised, which decides what it will accept. local: parameters.Parameters = .{}, streams: [max_streams]StreamEntry = @splat(.{}), /// §4.1's connection-level limits: what the peer will let this endpoint send /// across all streams, and what this endpoint will let the peer send. send_credit: stream.Credit = .init(0), recv_credit: stream.Credit = .init(0), /// §4.1 and §4.6: the limit the last DATA_BLOCKED went out for, and, for each /// kind of stream, the limit an open was refused at and the limit the last /// STREAMS_BLOCKED went out for. Each is said once per limit, and again only /// if the packet carrying it is lost while the limit stands (§13.3). data_blocked_sent: ?u64 = null, streams_blocked_at: [2]?u64 = .{ null, null }, streams_blocked_sent: [2]?u64 = .{ null, null }, /// What the peer last said it was blocked at: the connection's limit, one /// stream's, and each kind of stream's. §4.2 asks nothing of a receiver /// told so -- it "MUST NOT wait for a STREAM_DATA_BLOCKED or DATA_BLOCKED /// frame before sending a MAX_STREAM_DATA or MAX_DATA frame" -- so these are /// for an application that wants to know who is waiting on it. peer_data_blocked: ?u64 = null, peer_stream_data_blocked: ?frame.StreamDataBlocked = null, peer_streams_blocked: [2]?u64 = .{ null, null }, /// How much stream data the application has read, across all streams, which /// is what a MAX_DATA is computed from. recv_consumed: u64 = 0, /// §4.6: how many streams of each directionality each end may open. The first /// comes from the peer's `initial_max_streams_bidi` or `_uni` and then /// MAX_STREAMS; the second is what this endpoint advertised. /// /// §2.1 gives the two directionalities separate identifier spaces and §4.6 /// gives them separate limits — "these limits apply to streams of each type", /// and MAX_STREAMS carries which type it is about. One counter for both would /// let a peer that opened many unidirectional streams exhaust the allowance /// for bidirectional ones, which is precisely what two spaces exist to /// prevent. peer_stream_limit: [2]u64 = .{ 0, 0 }, local_stream_limit: [2]u64 = .{ 0, 0 }, /// The next index this endpoint will use for a stream it opens, per /// directionality. next_stream_index: [2]u64 = .{ 0, 0 }, /// §4.6: the cumulative limit this endpoint has advertised, which only ever /// grows — "once a receiver advertises a stream limit using the MAX_STREAMS /// frame, advertising a smaller limit has no effect". /// /// It grows as peer-initiated streams close, which is what §4.6 suggests: /// "implementations might choose to increase limits as streams are closed, to /// keep the number of streams available to peers roughly consistent". Without /// that, a peer gets `initial_max_streams_bidi` streams for the life of the /// connection and then nothing — which for DNS over QUIC, where §4.2 of RFC /// 9250 puts every query on its own stream, means a fixed number of queries /// and then silence. advertised_stream_limit: [2]u64 = .{ 0, 0 }, /// Whether a MAX_STREAMS frame is owed, and for which directionality. §19.11 /// gives the frame a type bit rather than a list, so the two are separate /// frames and separately owed. owes_max_streams: [2]bool = .{ false, false }, /// The index below which every peer-initiated stream of each directionality /// has been closed and forgotten. /// /// §4.5 permits forgetting: "requiring that an endpoint generate these errors /// also means that the endpoint needs to maintain the final size state for /// closed streams, which could mean a significant state commitment". So a /// frame naming a stream below this watermark is ignored rather than treated /// as an error — the alternative is remembering every stream that ever /// existed, which is the state commitment the RFC is excusing us from. peer_streams_retired: [2]u64 = .{ 0, 0 }, /// Peer-initiated streams above `peer_streams_retired` that have closed /// already: bit `i` is the stream with index `peer_streams_retired + i`. /// /// Streams close in whatever order their exchanges finish, so the watermark /// can only be the lowest stream still open. Moving it to the highest one /// closed instead would forget the streams below that are still to arrive, /// and §4.6's limit would grow by every identifier skipped over rather than /// by the streams that actually closed. peer_streams_closed_ahead: [2]u64 = .{ 0, 0 }, /// §13.3: whether a packet carrying MAX_DATA or MAX_STREAM_DATA was lost, /// so that the current limits are owed again whatever `owesFlowControl`'s /// thresholds say. Those thresholds compare against the limit last *sent*, /// which the peer never heard, and a peer blocked at the old one sends /// nothing that would move them. flow_control_lost: bool = false, /// §5: one estimator for the whole connection, not one per space. The three /// spaces travel the same path, so a sample taken from any of them describes /// all of them — and the Initial space, which has the fewest samples, is the /// one that needs the estimate most. rtt: recovery.Rtt = .{}, /// §7: one controller for the whole connection, because it is per *path* and /// the three spaces share one. What the spaces do not share is packet /// numbers, which is why loss detection is per space and this is not. congestion: Congestion = .{}, /// §4.1.2 of RFC 9001: whether the handshake is *confirmed*, which is not /// the same as complete and is asked at different moments by the two roles. /// "The TLS handshake is considered confirmed at the server when the /// handshake completes. At the client, the handshake is considered confirmed /// when a HANDSHAKE_DONE frame is received." /// /// The asymmetry is the point: when a server's handshake completes it has the /// client's Finished, so both ends are done. When a client's completes, its /// own Finished has only been *queued* — and an endpoint that discarded its /// handshake keys then would have thrown away the means to send the one /// message the other end is still waiting for. confirmed: bool = false, /// Whether a server owes its peer a HANDSHAKE_DONE frame. owes_handshake_done: bool = false, /// §4.9.1 and §4.9.2 of RFC 9001: whether each space's keys have been /// discarded. A discarded space sends nothing and reads nothing, and its /// loss recovery state is abandoned — "endpoints MUST NOT send Initial /// packets after this point". discarded: [3]bool = .{ false, false, false }, /// §4.6 of RFC 9001: the 0-RTT keys, which live beside the application /// space's rather than in it. /// /// Beside, because 0-RTT and 1-RTT share a packet number space (§12.3 of RFC /// 9000) and do not share keys: a client writes 0-RTT under `early_write` and /// 1-RTT under `spaces[2].write`, numbering both out of the same counter. And /// only one direction of each exists, because only a client sends 0-RTT -- /// so a client has a write key with no read key and a server the reverse, /// which is why these are not a `SpaceState`. early_write: ?protection.Keys = null, early_read: ?protection.Keys = null, /// Whether this client has sent anything in a 0-RTT packet, and so has /// something to take back if the server refuses it (§4.6.3). sent_early: bool = false, /// Whether the server refused this client's 0-RTT data; set once, when the /// refusal is acted on (§4.6.2 of RFC 9001). early_rejected: bool = false, /// §6 of RFC 9001: key update, which applies only to the application space. /// "Keys of packets other than the 1-RTT packets are never updated; their /// keys are derived solely from the TLS handshake state." key_phase: bool = false, /// The secrets the current phase's keys came from, kept so the next phase can /// be derived from them. write_secret: ?protection.OwnedSecret = null, read_secret: ?protection.OwnedSecret = null, /// §6.3: "Endpoints are generally expected to have current and next receive /// packet protection keys available", so that responding to a key update /// costs no key derivation and leaks no timing. next_read: ?protection.Keys = null, next_read_secret: ?protection.OwnedSecret = null, /// §6.5: "Retaining old packet protection keys allows [delayed packets] to be /// successfully processed." Kept until the deadline, then dropped. previous_read: ?protection.Keys = null, previous_read_until: recovery.Instant = 0, /// §6.1: "An endpoint MUST NOT initiate a subsequent key update unless it has /// received an acknowledgment for a packet that was sent protected with keys /// from the current key phase." This is the lowest packet number sent in the /// current phase; once the peer has acknowledged something at least this high, /// another update is permitted. phase_first_sent: u64 = 0, /// The lowest packet number seen in the current read phase, which is how a /// late packet from the phase before it is recognised (§6.5). phase_first_read: u64 = 0, /// §6.6: "Endpoints MUST count the number of encrypted packets for each set /// of keys", and the count that matters for the integrity limit is across the /// whole connection. packets_encrypted: u64 = 0, packets_failed: u64 = 0, /// RFC 9287: how many packets arrived with the QUIC Bit clear and were read /// anyway. Counted after authentication, so it says what the peer did rather /// than what anyone on the path could have written. packets_greased: u64 = 0, /// draft-ietf-quic-address-discovery-01 §4.1: the sequence number the next /// OBSERVED_ADDRESS goes out with. One counter for the connection, since /// the numbers "MUST be monotonically increasing for OBSERVED_ADDRESS frames /// in the same connection" and not merely on one path. next_observed_sequence: u64 = 0, /// draft-ietf-quic-multipath-21: paths past path 0, and how many of them /// this connection has memory for. extra: [max_paths - 1]ExtraPath = @splat(.{}), path_limit: usize = 1, /// draft-ietf-quic-multipath-21 §4.6: the largest path ID the peer has said /// this endpoint may use, raised by MAX_PATH_ID and never lowered. peer_max_path_id: u64 = 0, /// The largest path ID this endpoint allows its peer: initial_max_path_id, /// raised by one each time an abandoned path's state is let go of, so that /// the number of paths the two ends can have at once stays what it was. local_max_path_id: u64 = 0, /// The path ID the next slot to be let go of takes. §3.4: "the path ID MUST /// NOT be reused for new paths", so a slot comes back under a new one. next_path_id: u64 = 0, /// §4.6: a MAX_PATH_ID announcing `local_max_path_id` is owed. max_path_id_owed: bool = false, /// §4.7: a PATHS_BLOCKED is owed, with the peer's limit that is in the way, /// and the limit the last one reported, which is not reported twice. paths_blocked_owed: ?u64 = null, paths_blocked_sent: ?u64 = null, /// §3.3 for path 0. path0_status: PathStatus = .{}, /// draft-ietf-quic-ack-frequency-14: what the peer's newest ACK_FREQUENCY /// asked of this end's acknowledgements, and its sequence number. Null until /// one arrives, which leaves acknowledgement as it always was. ack_frequency: ?ack.Frequency = null, ack_frequency_sequence: ?u64 = null, /// The other direction: what this end has asked of the peer. The request /// last made, whether it is owed, the sequence number the next goes out /// with, the one in flight and its delay in microseconds, and the delay the /// peer is known to be using, once it has acknowledged one. ack_frequency_request: ?AckFrequencyRequest = null, ack_frequency_owed: bool = false, ack_frequency_next: u64 = 0, ack_frequency_in_flight: ?struct { sequence: u64, max_delay_us: u64 } = null, peer_max_ack_delay_us: ?u64 = null, /// An IMMEDIATE_ACK is owed. immediate_ack_owed: bool = false, /// n0's NAT traversal, once both ends have asked for it and multipath is in /// use; null otherwise, which is every connection that did not. nat: ?nat_mod.State = null, /// Routes over which a probe has been answered, waiting for the client to /// open a path over them -- which may have to wait for a path ID or an /// identifier from the peer. nat_opens: [4]?paths_mod.Id = @splat(null), /// The multipath path new data goes on; see `useSendPath`. send_path: u32 = 0, /// How new data is spread over paths; see `setScheduler`. scheduler: Scheduler = .chosen, /// How many paths past path 0 have been opened over the connection's life, /// by either end -- including ones since abandoned and let go of. paths_opened: u64 = 0, /// §3.4 for path 0, which the peer can abandon while another path carries /// the connection on. path0_abandoned: bool = false, path0_owes_abandon: bool = false, path0_sent_abandon: bool = false, /// §7.4.1: what the server's transport parameters were on the connection /// that issued the session ticket, kept so that the ones that arrive on this /// connection can be checked against them. remembered: ?parameters.Parameters = null, /// RFC 9221: unreliable datagrams waiting to go out, and ones that have /// arrived and not yet been read. /// /// Two plain queues and no retransmission state, which is the whole of what /// makes them unreliable: §5.2 says a lost DATAGRAM frame "SHOULD NOT be /// retransmitted", so once one has been written there is nothing left to /// remember about it. An application that wanted it sent again would have /// used a stream. outbound: Datagrams = .{}, inbound: Datagrams = .{}, /// §10: how this connection ended, if it has. closing: termination.Closing = .{}, /// §10.1: when this connection last heard from its peer, or last said /// something after hearing from it. The idle timer is measured from here. last_activity: recovery.Instant = 0, /// §10.1: "An endpoint also restarts its idle timer when sending an /// ack-eliciting packet if no other ack-eliciting packets have been sent /// since last receiving and processing a packet." This is that condition. sent_since_receive: bool = false, /// Whether the next datagram is a probe, which §7.5 exempts from the /// congestion window: "Probe packets MUST NOT be blocked by the congestion /// controller." A sender that let the window silence its probes would have no /// way to discover that the path had stopped answering, which is the one /// thing a probe exists to find out. probe_pending: bool = false, /// RFC 9002 §6.2.2.1: whether a client's probe timeout fired with nothing in /// flight to send again, so that the next datagram carries a PING at the /// highest handshake level there are keys for. See `awaitsServerValidation`. handshake_ping_owed: bool = false, /// §9.6.3: the path a server's preferred address is being probed on, until /// it answers or fails to, and the connection ID the probe addresses the /// server by there. The connection moves only once the answer arrives: /// "If path validation fails, the client MUST continue sending all future /// packets to the server's original IP address." preferred_probe: ?paths_mod.Id = null, preferred_probe_id: [ids.max_len]u8 = undefined, preferred_probe_id_len: usize = 0, /// §9.3.3: the path that was active before the peer apparently moved, while /// it is being challenged, and the connection ID it was addressed by there. /// That identifier is kept from retirement until the challenge is settled: /// §9.5 forbids carrying the new path's identifier to the old address, and /// the old address already knows this one. old_path: ?paths_mod.Id = null, old_path_id: [ids.max_len]u8 = undefined, old_path_id_len: usize = 0, /// §6.2.1: how many probe timeouts have expired in a row without an /// acknowledgement, which doubles the next one. Reset when anything is /// acknowledged, because an acknowledgement proves the path is working and /// whatever the backoff was compensating for is over. pto_count: u32 = 0, /// §13.4.2: whether path 0 is worth marking, and whether it has been caught /// lying about the markings it carries. Every other path has its own, in /// `ExtraPath.ecn`. ecn: ecn_mod.Validator = .{}, /// The ECN field of the datagram being processed, for the duration of one /// `receiveEcn` call. See `receiveEcn`. inbound_ecn: ack.Codepoint = .not_ect, /// Whether any packet from the peer has been received and processed. /// /// §6.2 turns on this exact distinction: a client must discard a Version /// Negotiation packet "if it has received and successfully processed any /// other packet", because by then the server has demonstrably spoken this /// version and whatever claims otherwise arrived too late to be telling the /// truth. processed_any: bool = false, /// See `bufferBound`. buffer_bound: u64 = 0, /// Where the loss detector puts what it removes, so that the removal does /// not need a buffer on the stack. /// /// `undefined` is filled with a pattern wherever runtime safety is on, which /// is every build but `ReleaseFast`, so a local of this shape is a memset of /// its whole length every time the function is entered -- and these functions /// are entered once per acknowledgement. At the sixty-four entries this /// library tracks that was about twenty-seven kilobytes of memset per /// acknowledgement across the three of them, and at the five hundred and /// twelve a large flow control window needs it was eighty per cent of the /// entire profile: the transfer was spending more time filling scratch /// buffers with `0xaa` than encrypting. /// /// Three rather than one because two of them are live at the same time: the /// packets an ACK newly acknowledged are still being read when loss detection /// runs behind it. acked_scratch: []recovery.Sent = &.{}, lost_scratch: []recovery.Sent = &.{}, real_scratch: []recovery.Sent = &.{}, windows: [3][16384]u8 = undefined, bitmaps: [3][2048]u8 = undefined, out_storage: [crypto_out_window[0] + crypto_out_window[1] + crypto_out_window[2]]u8 = undefined, /// The caller's memory, carved in `init`: `max_streams` buffers end to end /// in each, addressed by `sendBuffer` and friends rather than indexed /// directly, so that the arithmetic lives in one place. stream_send: []u8 = &.{}, stream_recv: []u8 = &.{}, stream_present: []u8 = &.{}, /// What one stream gets of each, which is also what may be advertised. send_window: usize = 0, recv_window: usize = 0, /// A bounded queue of whole datagrams. /// /// Whole, because a datagram is not a stream: it arrives entire or not at /// all, and there is no offset to reassemble from. So the storage is one /// fixed slot per datagram rather than a ring of octets -- the simpler shape /// is also the only correct one here. const Datagrams = struct { storage: [max_datagrams][max_datagram_len]u8 = undefined, lengths: [max_datagrams]usize = @splat(0), /// The slots in use, as a half-open range over `storage`, oldest first. head: usize = 0, len: usize = 0, fn push(q: *Datagrams, bytes: []const u8) bool { if (bytes.len > max_datagram_len) return false; if (q.len == max_datagrams) return false; const at = (q.head + q.len) % max_datagrams; @memcpy(q.storage[at][0..bytes.len], bytes); q.lengths[at] = bytes.len; q.len += 1; return true; } fn peek(q: *const Datagrams) ?[]const u8 { if (q.len == 0) return null; return q.storage[q.head][0..q.lengths[q.head]]; } fn pop(q: *Datagrams) void { if (q.len == 0) return; q.head = (q.head + 1) % max_datagrams; q.len -= 1; } }; /// One stream, and the storage its two halves borrow. const StreamEntry = struct { id: stream.Id = .{ .value = 0 }, open: bool = false, /// §3.1: "a unidirectional stream has a sending part only at the end that /// opened it", and a receiving part only at the other. Both halves are /// built either way — they cost buffers this connection already owns — /// and these say which of them is real. /// /// Without them a unidirectional stream would never close: the half that /// does not exist starts in a non-terminal state and stays there, because /// nothing will ever write to it or read from it, and §3.4 closes a /// stream only when both halves are terminal. has_send: bool = false, has_recv: bool = false, /// Whether the application has been told about it. A peer-opened stream /// exists the moment a frame mentions it; `accept` is how it reaches /// whoever is going to read it. accepted: bool = false, send: stream.Send = undefined, recv: stream.Recv = undefined, /// The limit the last STREAM_DATA_BLOCKED for this stream went out for. data_blocked_sent: ?u64 = null, /// Whether the sending half is finished with, which for a half that does /// not exist is true from the outset. fn sendDone(e: *const StreamEntry) bool { return !e.has_send or e.send.isTerminal(); } fn recvDone(e: *const StreamEntry) bool { return !e.has_recv or e.recv.isTerminal(); } }; pub const Options = struct { role: Role, handshake: tls.Handshake, /// The connection ID this endpoint wants the peer to address it by. local_id: []const u8, /// A client's chosen Destination Connection ID, from which both ends /// derive the Initial keys (§5.2 of RFC 9001). A server leaves this null /// and learns it from the first packet. destination_id: ?[]const u8 = null, /// §10.3.2: the static key this endpoint derives its stateless reset /// tokens from, as `HMAC(key, connection_id)`. /// /// Static on purpose, and §10.3.2 explains why a random token per /// connection is the wrong answer: "stateless reset specifically exists /// to handle the case where state is lost, so this approach is /// suboptimal". A key that survives a restart gives the same token after /// a crash as before it, and the same token on every machine in a /// cluster. reset_key: ?reset.Key = null, /// §8.1.2: a token from a NEW_TOKEN frame in an earlier connection, which /// lets a returning client skip the round trip a Retry would cost. token: []const u8 = &.{}, /// The path the connection starts on, in whatever numbering the caller /// uses for addresses. path: paths_mod.Id = 0, /// A server's: whether the client has already proved it receives at the /// address its first Initial came from -- with a Retry token, say, which /// §8.1.2 counts as validating it. /// /// Otherwise §8.1 holds the server to three times what arrived from that /// address until the client's first Handshake packet does the proving: /// "Prior to validating the client address, servers MUST NOT send more /// than three times as many bytes as the number of bytes they have /// received." A client is never limited on its first path, which it /// chose itself. address_validated: bool = false, /// The memory this connection is to run on, which the caller owns and /// which decides what the connection can promise. See `Sizes`. memory: Memory, /// Randomness for the additional connection IDs this endpoint issues and /// the stateless reset tokens beside them (§5.1.1, §10.3). Without it no /// further identifiers are issued, which costs migration and nothing /// else. rng: ?std.Random = null, /// What this endpoint advertises in its transport parameters. /// /// The same value has to reach the peer, and this library does not put it /// there: the TLS handshake is built by the caller, so the caller encodes /// these with `parameters.write` and hands the result to it. Passing one /// thing to TLS and another here gives a connection that grants credit /// its peer is not expecting, which is invisible until something fills a /// window — so build the `Parameters` once and use it twice. local: parameters.Parameters = .{}, /// §7.4.1 of RFC 9000: the server's transport parameters as they were on /// the connection that issued the session ticket. /// /// A client sending 0-RTT is sending before the server has said what it /// will accept, so it has to act on what the server said last time. /// "A client that attempts to send 0-RTT data MUST remember the transport /// parameters used by the server" -- and only some of them: what is /// remembered here is the flow control and stream limits, because the /// rest (the connection IDs, the stateless reset token, the idle timeout) /// describe *that* connection and mean nothing about this one. /// /// Null for a server, which is not the endpoint that acts early, and for /// a client that is not attempting 0-RTT. remembered: ?parameters.Parameters = null, }; /// Takes a larger arena for the send buffers, keeping what every stream /// holds. /// /// The counterpart to `bufferBound`: that says a window is too small, and /// this is how a caller that owns the memory does something about it. The /// library still allocates nothing -- the new arena is the caller's, exactly /// as the first one was -- and the old one is the caller's to free once this /// returns, because nothing points into it any more. /// /// Only the sending side grows. `recv_window` is advertised in the transport /// parameters and §4.1 makes it a promise, so raising it means telling the /// peer, and lowering it is forbidden outright; the sending window is purely /// local and may be chosen again at any time. /// /// `tracked` is not grown with it, and a caller that wants the larger window /// to be worth having should have provisioned the table for it up front -- /// the table is a few hundred entries where the buffers are megabytes, so /// sizing it for the largest window a connection may reach costs little. A /// table left short is not a fault, only a lower ceiling: a sender whose /// table is full waits, exactly as one whose congestion window is closed /// does. /// /// The arena is `max_streams` windows end to end, each larger than the /// current one; anything else is a caller mistake and is asserted. It is /// borrowed for as long as the connection lives, or until the next /// `growSend`. pub fn growSend(c: *Connection, arena: []u8) void { const window = arena.len / max_streams; // Growing only. Shrinking would have to discard unacknowledged octets, // which §13.3 still expects this endpoint to be able to send again. assert(window > c.send_window); assert(arena.len % max_streams == 0); for (&c.streams, 0..) |*entry, i| { entry.send.data.rehome(arena[i * window ..][0..window]); } c.stream_send = arena; c.send_window = window; } test growSend { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); // A stream with a full buffer: the write after it is refused. const id = try p.client.openBidirectional(); const full: [stream_buffer]u8 = @splat('a'); try p.client.write(id, &full); try testing.expectError(error.NoRoom, p.client.write(id, "b")); // Twice the room, and the octets already written come along. const bigger = try testing.allocator.alloc(u8, max_streams * 2 * stream_buffer); defer testing.allocator.free(bigger); p.client.growSend(bigger); try testing.expectEqual(@as(usize, 2 * stream_buffer), p.client.sendWindow()); try p.client.write(id, "b"); } /// What the peer last reported about the ECN markings on packets this /// endpoint sent in the application space, or null if it has reported none. /// /// Null is the answer that matters: §13.4.1 has an endpoint with no access to /// its platform's IP header report nothing at all, and §13.4.2.1 turns that /// absence into a reason to stop marking -- so a caller watching this is /// watching the one signal that says whether ECN is worth attempting. pub fn peerEcnCounts(c: *const Connection) ?frame.Ack.Ecn { return c.spaces[2].peer_ecn; } test peerEcnCounts { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); // `receive` reports no codepoints, so the server has had none to count. try testing.expectEqual(@as(?frame.Ack.Ecn, null), p.client.peerEcnCounts()); // A server that can read the IP header says what it saw, and the // client learns of it from the next acknowledgement. const id = try p.client.openBidirectional(); try p.client.write(id, "marked"); var buffer: [2048]u8 = undefined; while (try p.client.send(&buffer, p.now)) |datagram| { try p.server.receiveEcn(datagram.bytes, datagram.path, p.now, .ect0); } const answer = (try p.server.send(&buffer, p.now)).?; try p.client.receive(answer.bytes, answer.path, p.now); try testing.expect(p.client.peerEcnCounts().?.ect0 >= 1); } test "RFC 9000 13.4.2: marked packets that are all lost fail ECN on the path" { // "An endpoint can also mark the ECN state for a path as 'failed' if // marked packets are all declared lost." A path that drops anything // marked and carries everything else -- a faulty middlebox, in §13.4.2's // words -- is otherwise never found out, because nothing marked is ever // acknowledged for the counts to be checked against. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.client.ecn = .{}; const id = try p.client.openBidirectional(); // The testing period's ten marked packets, all lost. for (0..ecn_mod.testing_packets) |_| { try p.client.write(id, "x"); const lost = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(ecn_mod.Codepoint.ect0, lost.ecn); } try testing.expectEqual(ecn_mod.State.unknown, p.client.ecn.state); // Then an unmarked one that arrives, and whose acknowledgement leaves // every marked packet behind it to be declared lost. try p.client.write(id, "y"); const arrives = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(ecn_mod.Codepoint.not_ect, arrives.ecn); try p.server.receive(arrives.bytes, arrives.path, p.now); try p.settle(); while (p.client.ecn.state != .failed) { const at = p.client.timeout() orelse break; if (at > p.now + std.time.ns_per_s) break; p.now = at; p.client.onTimeout(p.now); try p.settle(); } try testing.expectEqual(ecn_mod.State.failed, p.client.ecn.state); } /// Runs `q` until it is quiet, delivering what the client sends to a server /// that reads the ECN field after `rewrite` has had its way with it. fn testThroughEcn(q: *TestPair, comptime rewrite: fn (ecn_mod.Codepoint) ecn_mod.Codepoint) !void { var rounds: usize = 0; while (rounds < 200) : (rounds += 1) { var moved = false; if (try q.client.send(&q.buffer, q.now)) |d| { q.now += std.time.ns_per_ms; try q.server.receiveEcn(d.bytes, d.path, q.now, rewrite(d.ecn)); moved = true; } if (try q.server.send(&q.buffer, q.now)) |d| { q.now += std.time.ns_per_ms; try q.client.receive(d.bytes, d.path, q.now); moved = true; } if (!moved) break; } } test "RFC 9000 9: a client is not moved by where the server's packets arrive" { // "Clients are responsible for initiating all migrations." A client // that has moved back to path 0 still hears from the server on path 1 // until the server notices -- and following that would undo the move, // and restart what the client had learned about path 0, for every // packet the server sent before it caught up. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try p.client.migrateTo(1, p.now); try p.settle(); try testing.expect(p.client.pathValidated(1)); const id = try p.client.openBidirectional(); try p.client.write(id, "on path one"); const late = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(late.bytes, late.path, p.now); try p.client.migrateTo(0, p.now); var delivered = false; while (try p.server.send(&p.buffer, p.now)) |d| { try testing.expectEqual(@as(paths_mod.Id, 1), d.path); p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); delivered = true; } try testing.expect(delivered); try testing.expectEqual(@as(paths_mod.Id, 0), p.client.paths.active); } test "RFC 9000 13.4.2: a marked packet from the old path does not prove the new one" { // The client sends a marked packet on path 1 and moves back to path 0, // which restarts ECN validation there. The acknowledgement for that // packet comes afterwards; it is counted, since the peer's counts cover // it, but it is no evidence that path 0 carries marks. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try p.client.migrateTo(1, p.now); try p.settle(); try testing.expect(p.client.pathValidated(1)); // `settle` delivers without a codepoint, which failed path 1's ECN; // test it afresh, against a server that reads the field from here on. p.client.ecn.restart(p.client.spaces[2].next_number); const id = try p.client.openBidirectional(); try p.client.write(id, "on path one"); const marked = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(ecn_mod.Codepoint.ect0, marked.ecn); p.now += std.time.ns_per_ms; try p.server.receiveEcn(marked.bytes, marked.path, p.now, marked.ecn); try p.client.migrateTo(0, p.now); try testing.expect(!p.client.ecn.onPath(p.client.spaces[2].next_number - 1)); while (try p.server.send(&p.buffer, p.now)) |d| { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); } try testing.expect(p.client.spaces[2].loss.largest_acked.? >= p.client.ecn.first_on_path - 1); try testing.expect(!p.client.ecn.acked_marked); try testing.expect(p.client.ecn.state != .failed); } test "RFC 9000 A.4: a path that turns every mark into CE loses ECN" { // "An endpoint can also mark the ECN state for a path as 'failed'... if // they are all ECN-CE marked." The counts all add up, so nothing else // would catch it, and believing them would keep halving the window. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.client.ecn = .{}; const Rewrite = struct { fn allCe(c: ecn_mod.Codepoint) ecn_mod.Codepoint { return if (c == .not_ect) c else .ce; } }; const id = try p.client.openBidirectional(); for (0..2 * ecn_mod.testing_packets) |_| { try p.client.write(id, "marked"); try testThroughEcn(p, Rewrite.allCe); } try testing.expectEqual(ecn_mod.State.failed, p.client.ecn.state); try testing.expectEqual(ecn_mod.Codepoint.not_ect, p.client.ecn.codepoint()); } test "RFC 9000 13.4.2.1: CE marks in counts that fail validation are not congestion" { // "An endpoint that receives an ACK frame with ECN counts therefore // validates the counts before using them." Here a packet comes back // ECT(1), which this end never sends, beside one marked CE: the same // ACK reports both, fails validation, and its CE is not believed. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.client.ecn = .{}; const id = try p.client.openBidirectional(); try p.client.write(id, "one"); const first = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receiveEcn(first.bytes, first.path, p.now, .ce); try p.client.write(id, "two"); const second = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receiveEcn(second.bytes, second.path, p.now, .ect1); const window = p.client.congestion.window; var delivered = false; while (try p.server.send(&p.buffer, p.now)) |d| { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); delivered = true; } try testing.expect(delivered); try testing.expectEqual(ecn_mod.State.failed, p.client.ecn.state); try testing.expect(p.client.congestion.window >= window); } test "draft-ietf-quic-multipath-21: each path's ECN is validated on its own" { // §13.4.2 of RFC 9000 validates a path, and a second path is a second // set of network elements. Here path 0 reaches a server that reads the // ECN field, and path 1 runs through something that zeroes it, so the // server's PATH_ACKs for path 1 carry no counts. Path 1 has to stop // marking for that; path 0 has no reason to. const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); // Everything so far went through `receive`, which reports no codepoint, // so start path 0's validation from here, against a server that counts. p.client.ecn = .{}; _ = try p.client.openPath(1, p.now); const Exchange = struct { fn run(q: *TestPair) !struct { zero: ?ecn_mod.Codepoint, one: ?ecn_mod.Codepoint } { var last_zero: ?ecn_mod.Codepoint = null; var last_one: ?ecn_mod.Codepoint = null; var rounds: usize = 0; while (rounds < 200) : (rounds += 1) { var moved = false; if (try q.client.send(&q.buffer, q.now)) |d| { q.now += std.time.ns_per_ms; if (d.path == 0) { last_zero = d.ecn; try q.server.receiveEcn(d.bytes, d.path, q.now, d.ecn); } else { last_one = d.ecn; try q.server.receive(d.bytes, d.path, q.now); } moved = true; } if (try q.server.send(&q.buffer, q.now)) |d| { q.now += std.time.ns_per_ms; try q.client.receive(d.bytes, d.path, q.now); moved = true; } if (!moved) break; } return .{ .zero = last_zero, .one = last_one }; } }; _ = try Exchange.run(p); try testing.expect(p.client.pathValidated(1)); const id = try p.client.openBidirectional(); for (0..2 * ecn_mod.testing_packets) |_| { try p.client.useSendPath(1); try p.client.write(id, "on path one"); _ = try Exchange.run(p); try p.client.useSendPath(0); try p.client.write(id, "on path zero"); _ = try Exchange.run(p); } try p.client.useSendPath(1); try p.client.write(id, "after"); const one = try Exchange.run(p); try testing.expectEqual(ecn_mod.Codepoint.not_ect, one.one.?); try p.client.useSendPath(0); try p.client.write(id, "after"); const zero = try Exchange.run(p); try testing.expectEqual(ecn_mod.Codepoint.ect0, zero.zero.?); } test "RFC 9000 13.4.1: ECN totals count only the space whose counts are checked" { // The peer counts each packet number space separately, and the validator // checks the application space's. A first flight is Initial packets // alone: marked while the path is tested, and nothing the application // space's counts will ever include. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const first = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(ecn_mod.Codepoint.ect0, first.ecn); try testing.expectEqual(@as(u64, 0), p.client.ecn.sent_ect0); } test "RFC 9000 9.4: a validated new path starts its ECN and MTU learning again" { // §13.4.2: ECN is validated "on active connection migration to a new // path", and §14.3's search is for "each combination of local and remote // IP addresses". What the old path proved says nothing about the new one. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.client.ecn.state = .failed; // A search the old path finished: it would never probe again by itself. p.client.pmtu.state = .complete; p.client.pmtu.current = 1300; // A server that can read the IP header, so that the new path's marks are // counted and reported rather than failing for want of a report. try p.client.migrateTo(1, p.now); var rounds: usize = 0; var probed_after = false; while (rounds < 100) : (rounds += 1) { var moved = false; if (try p.client.send(&p.buffer, p.now)) |d| { if (p.client.pathValidated(1) and d.bytes.len > 1300) probed_after = true; p.now += std.time.ns_per_ms; try p.server.receiveEcn(d.bytes, d.path, p.now, d.ecn); moved = true; } if (try p.server.send(&p.buffer, p.now)) |d| { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); moved = true; } if (!moved) break; } try testing.expect(p.client.pathValidated(1)); try testing.expect(p.client.ecn.state != .failed); try testing.expectEqual(ecn_mod.Codepoint.ect0, p.client.ecn.codepoint()); // The search started over on the new path, and probed past what the old // one had settled on. try testing.expect(probed_after); } test "RFC 9000 9.4: moving back to a path validated earlier starts its learning again" { // The handshake validated path 0, so a move back to it has no challenge // to wait for -- and what the connection knows by then was learned on // path 1, which is not path 0. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try p.client.migrateTo(1, p.now); try p.settle(); try testing.expect(p.client.pathValidated(1)); try testing.expect(p.client.rtt.sampled); // What path 1 taught. p.client.ecn.state = .failed; p.client.pmtu.state = .complete; p.client.pmtu.current = 1300; p.client.congestion.window = 100_000; try p.client.migrateTo(0, p.now); try testing.expect(p.client.ecn.state != .failed); try testing.expect(p.client.pmtu.state != .complete); try testing.expectEqual( congestion_mod.initialWindow(congestion_mod.min_datagram_size), p.client.congestion.window, ); try testing.expect(!p.client.rtt.sampled); } /// The server of `p` told that its route 0 and route 1 lead to `zero` and /// `one` from its own `local_zero` and `local_one`, then left with what a /// long-lived path would have taught it, then followed by the client to route /// 1 and through validation there. fn testRebindTo( p: *TestPair, local_zero: frame.Address, zero: frame.Address, local_one: frame.Address, one: frame.Address, ) !void { try p.server.setLocalAddress(0, local_zero); try p.server.setPeerAddress(0, zero); try p.server.setLocalAddress(1, local_one); try p.server.setPeerAddress(1, one); p.server.ecn.state = .failed; p.server.pmtu.state = .complete; p.server.pmtu.current = 1300; p.server.congestion.window = 100_000; const id = try p.client.openBidirectional(); const body: [400]u8 = @splat('r'); try p.client.write(id, &body); try testRebound(p, 0, 1); try testing.expectEqual(@as(paths_mod.Id, 1), p.server.paths.active); try testing.expect(p.server.pathValidated(1)); try testing.expectEqualSlices(u8, &body, p.server.readable(id)); } const test_server_address: frame.Address = .{ .ip = .{ .v4 = .{ 203, 0, 113, 9 } }, .port = 443 }; test "RFC 9000 9.4: a peer whose port alone changed keeps its congestion and RTT state" { // "Because port-only changes are commonly the result of NAT rebinding or // other middlebox activity, the endpoint MAY instead retain its // congestion control state and round-trip estimate in those cases // instead of reverting to initial values." The packets take the route // they took before, so what was measured on it is still true -- and §14.3 // keys the PMTU on the IP addresses, which have not changed either. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testRebindTo( p, test_server_address, .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 40001 }, test_server_address, .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 50123 }, ); try testing.expect(p.server.congestion.window >= 100_000); try testing.expect(p.server.rtt.sampled); try testing.expectEqual(mtu.State.complete, p.server.pmtu.state); try testing.expectEqual(@as(u16, 1300), p.server.pmtu.current); // A middlebox that rebinds may also be one that rewrites the markings, // and checking again costs nothing but a few packets' wait. Started // again, that is: this pair carries no markings, so the new test fails // in turn once enough of the new path's packets are acknowledged. try testing.expect(p.server.ecn.first_on_path != 0); } test "RFC 9000 9.4: a peer at a new IP address starts its congestion and RTT state again" { // The exception is for a port and nothing else. A new IP address is a // new network path; and a new local address is one too, even when the // peer's own looks only to have changed port -- a client moving to the // server's preferred address from a fresh socket is exactly that. const cases = [_][4]frame.Address{ .{ test_server_address, .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 40001 }, test_server_address, .{ .ip = .{ .v4 = .{ 192, 0, 2, 33 } }, .port = 40001 }, }, .{ test_server_address, .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 40001 }, .{ .ip = .{ .v4 = .{ 203, 0, 113, 10 } }, .port = 443 }, .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 50123 }, }, }; for (cases) |case| { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testRebindTo(p, case[0], case[1], case[2], case[3]); try testing.expect(p.server.congestion.window != 100_000); try testing.expect(p.server.pmtu.current != 1300 or p.server.pmtu.state != .complete); } } test "RFC 9000 9.3.3: a peer pulled away by a forged address and back keeps what it knew" { // §9.3: "if an endpoint returns to a previously validated path after // detecting some form of spurious migration, skipping address validation // and restoring loss detection and congestion state can reduce the // performance impact of the attack." Nothing was learned on the forged // path, so what the server knows is still path 0's -- and an attacker // who could reset it with one forged datagram could keep the connection // in slow start for as long as it liked. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.server.ecn.state = .failed; p.server.pmtu.state = .complete; p.server.pmtu.current = 1300; p.server.congestion.window = 100_000; const id = try p.client.openBidirectional(); try p.client.write(id, "one"); const forged = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(forged.bytes, 1, p.now); try testing.expectEqual(@as(paths_mod.Id, 1), p.server.paths.active); try p.client.write(id, "two"); const genuine = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(genuine.bytes, 0, p.now); try testing.expectEqual(@as(paths_mod.Id, 0), p.server.paths.active); try testing.expectEqual(ecn_mod.State.failed, p.server.ecn.state); try testing.expectEqual(mtu.State.complete, p.server.pmtu.state); try testing.expectEqual(@as(usize, 100_000), p.server.congestion.window); try testing.expect(p.server.rtt.sampled); } test "RFC 9000 8.2.1: a peer that moves with a small packet is still challenged at once" { // §21.1.1.1 allows three times what arrived, and a packet carrying only // a few octets of data -- or nothing but an ACK -- buys too little for a // whole packet with everything else this end might say. The challenge // is a few dozen octets and goes anyway: "unless the anti-amplification // limit for the path does not permit sending a datagram of this size" // is §8.2.1 allowing a short one, not forbidding it. Waiting would cost // the peer a probe timeout before its new address is even questioned. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "x"); const moved = (try p.client.send(&p.buffer, p.now)).?; try testing.expect(moved.bytes.len * paths_mod.Paths.amplification_factor < min_packet_room); p.now += std.time.ns_per_ms; try p.server.receive(moved.bytes, 1, p.now); try testing.expectEqual(@as(paths_mod.Id, 1), p.server.paths.active); const challenge = (try p.server.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), challenge.path); try testing.expect(challenge.bytes.len <= moved.bytes.len * paths_mod.Paths.amplification_factor); try testing.expect(p.server.paths.find(1).?.sent_challenge); // And it is answered like any other. p.now += std.time.ns_per_ms; try p.client.receive(challenge.bytes, 0, p.now); try testRebound(p, 0, 1); try testing.expect(p.server.pathValidated(1)); } test "RFC 9000 8.2.1: a challenge that had to go out small is repeated at 1200 octets" { // "When an endpoint is unable to expand the datagram size to 1200 bytes // due to the anti-amplification limit, the path MTU will not be // validated. To ensure that the path MTU is large enough, the endpoint // MUST perform a second path validation by sending a PATH_CHALLENGE // frame in a datagram of at least 1200 bytes." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const challenge = try testMoveToOne(p); try testing.expect(challenge.bytes.len < min_initial_datagram); p.now += std.time.ns_per_ms; try p.client.receive(challenge.bytes, 0, p.now); const response = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(response.bytes, 1, p.now); try testing.expect(p.server.pathValidated(1)); const seen = p.server.paths.find(1).?; try testing.expect(seen.challenge != null and !seen.sent_challenge); const second = (try p.server.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), second.path); try testing.expect(second.bytes.len >= min_initial_datagram); try testing.expect(seen.sent_challenge); // Answered at full size, and that is the end of it. p.now += std.time.ns_per_ms; try p.client.receive(second.bytes, 0, p.now); try testRebound(p, 0, 1); try testing.expectEqual(@as(?[paths_mod.challenge_len]u8, null), seen.challenge); try testing.expectEqual(@as(paths_mod.Id, 1), p.server.paths.active); } /// Moves `p`'s client to the server's route 1 with one small packet, and /// returns the server's challenge there, which the caller may lose. fn testMoveToOne(p: *TestPair) !Datagram { const id = try p.client.openBidirectional(); try p.client.write(id, "x"); const moved = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(moved.bytes, 1, p.now); try testing.expectEqual(@as(paths_mod.Id, 1), p.server.paths.active); const challenge = (try p.server.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), challenge.path); return challenge; } test "RFC 9000 9.3.3: an apparent migration has the old path challenged" { // "In response to an apparent migration, endpoints MUST validate the // previously active path using a PATH_CHALLENGE frame. This induces the // sending of new packets on that path" -- which is what moves the // connection back if the migration was an attacker's copy. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var old_id: [ids.max_len]u8 = undefined; const old_len = p.server.peerId().len; @memcpy(old_id[0..old_len], p.server.peerId()); var first: [2048]u8 = undefined; const challenge = try testMoveToOne(p); const forward = first[0..challenge.bytes.len]; @memcpy(forward, challenge.bytes); const old = p.server.paths.find(0).?; try testing.expect(old.challenge != null); const back = (try p.server.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 0), back.path); try testing.expect(back.bytes.len >= min_initial_datagram); try testing.expect(old.sent_challenge); // §9.5: by the identifier the old path already knew, not the one the // new path is now being sent. try testing.expectEqualSlices(u8, old_id[0..old_len], back.bytes[1..][0..old_len]); try testing.expect(!std.mem.eql(u8, old_id[0..old_len], p.server.peerId())); // The client answers both, and the old identifier is retired after. p.now += std.time.ns_per_ms; try p.client.receive(back.bytes, 0, p.now); p.now += std.time.ns_per_ms; try p.client.receive(forward, 0, p.now); try testRebound(p, 0, 1); try testing.expectEqual(@as(?[paths_mod.challenge_len]u8, null), old.challenge); try testing.expectEqual(@as(?paths_mod.Id, null), p.server.old_path); try testing.expectEqual(@as(paths_mod.Id, 1), p.server.paths.active); try testing.expect(!p.client.acceptsId(old_id[0..old_len])); } /// Runs only `c`'s timers, discarding what it sends, until `done` says so, /// a minute has passed, or a thousand timers have fired. `done` is asked /// between a timer and the sending it causes, so what the timer queued is /// left for the caller to send. fn testWaitFor(p: *TestPair, c: *Connection, comptime done: fn (*Connection) bool) !void { const limit = p.now + 60 * std.time.ns_per_s; var rounds: usize = 0; while (!done(c) and p.now < limit and rounds < 1000) : (rounds += 1) { p.now = @max(p.now + 1, c.timeout() orelse limit); c.onTimeout(p.now); if (done(c)) return; while (try c.send(&p.buffer, p.now)) |_| {} } } test "RFC 9000 8.2.1: a lost challenge is sent again" { // "An endpoint MAY send multiple PATH_CHALLENGE frames to guard against // packet loss" -- and without it, a server that followed a client // somewhere new and lost its one challenge would hold that client to // three times what it sends for the rest of the connection. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); _ = try testMoveToOne(p); // and lost const seen = p.server.paths.find(1).?; const first = seen.challenge.?; const Again = struct { fn done(c: *Connection) bool { return !c.paths.find(1).?.sent_challenge; } }; try testWaitFor(p, &p.server, Again.done); try testing.expect(!seen.sent_challenge); try testing.expectEqualSlices(u8, &first, &seen.challenge.?); // The first challenge spent all §21.1.1.1 allowed, so the second waits // for the client to send something more -- which a client whose data // went unacknowledged does. try testing.expectEqual(@as(usize, 0), p.server.paths.sendable(1)); const more = (try p.client.send(&p.buffer, p.now)) orelse blk: { p.now = @max(p.now, p.client.timeout().?); p.client.onTimeout(p.now); break :blk (try p.client.send(&p.buffer, p.now)).?; }; p.now += std.time.ns_per_ms; try p.server.receive(more.bytes, 1, p.now); const again = (try p.server.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), again.path); try testing.expect(seen.sent_challenge); p.now += std.time.ns_per_ms; try p.client.receive(again.bytes, 0, p.now); try testRebound(p, 0, 1); try testing.expect(p.server.pathValidated(1)); } test "RFC 9000 9.3.2: a validation that fails goes back to the last validated address" { // "An endpoint MUST revert to using the last validated peer address when // validation of a new peer address fails." A packet copied to a forged // address moves the connection there, and the forger cannot read the // challenge -- so it goes unanswered, and the connection comes back. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); _ = try testMoveToOne(p); const Back = struct { fn done(c: *Connection) bool { return c.paths.active == 0; } }; try testWaitFor(p, &p.server, Back.done); try testing.expectEqual(@as(paths_mod.Id, 0), p.server.paths.active); try testing.expectEqual(@as(?termination.State, null), p.server.closeState()); try testing.expect(!p.server.pathValidated(1)); // And nothing more is sent to the forged address. try testing.expectEqual(@as(?recovery.Instant, null), p.server.paths.validationDeadline(std.time.ns_per_s)); } test "RFC 9000 9.3.2: with no validated address to go back to, the connection ends silently" { // "If an endpoint has no state about the last validated peer address, it // MUST close the connection silently by discarding all connection state." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); _ = try testMoveToOne(p); p.server.paths.forget(0); const Ended = struct { fn done(c: *Connection) bool { return c.closeState() != null; } }; try testWaitFor(p, &p.server, Ended.done); try testing.expectEqual(@as(?termination.State, .closed), p.server.closeState()); } test "draft-ietf-quic-multipath-21 3.1.2: a path whose new 4-tuple never answers goes back to its old one" { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); _ = try p.client.openPath(1, p.now); try p.settle(); const extra = p.server.extraFor(1).?; const id = try p.client.openBidirectional(); try p.client.useSendPath(1); const body: [400]u8 = @splat('r'); try p.client.write(id, &body); const moved = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), moved.path); p.now += std.time.ns_per_ms; try p.server.receive(moved.bytes, 2, p.now); try testing.expectEqual(@as(paths_mod.Id, 2), extra.route); const Back = struct { fn done(c: *Connection) bool { return c.extraFor(1).?.route == 1; } }; try testWaitFor(p, &p.server, Back.done); try testing.expectEqual(@as(paths_mod.Id, 1), extra.route); try testing.expect(extra.state == .open); try testing.expect(!p.server.pathValidated(2)); } /// Runs `q` until it is quiet, delivering what the client sends on route /// `from` to the server as though it came from route `to`, and the server's /// replies to `to` back to the client on `from` -- a NAT in the middle that /// has given the client's path a new outside address. fn testRebound(q: *TestPair, from: paths_mod.Id, to: paths_mod.Id) !void { var rounds: usize = 0; while (rounds < 200) : (rounds += 1) { var moved = false; if (try q.client.send(&q.buffer, q.now)) |d| { q.now += std.time.ns_per_ms; try q.server.receive(d.bytes, if (d.path == from) to else d.path, q.now); moved = true; } if (try q.server.send(&q.buffer, q.now)) |d| { q.now += std.time.ns_per_ms; try q.client.receive(d.bytes, if (d.path == to) from else d.path, q.now); moved = true; } if (!moved) break; } } test "draft-ietf-quic-multipath-21 3.1.2: a path whose 4-tuple changes is followed, validated and measured again" { // "An endpoint could receive a packet with a connection ID associated to // an active path ID where the packet's 4-tuple does not match the 4-tuple // currently used with that path ID. This MUST be treated as path // migration" -- of that path, and only that one. const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); _ = try p.client.openPath(1, p.now); try p.settle(); const extra = p.server.extraFor(1).?; try testing.expectEqual(@as(paths_mod.Id, 1), extra.route); try testing.expect(extra.rtt.sampled); // What the old 4-tuple taught. extra.congestion.window = 100_000; extra.ecn.state = .failed; extra.pmtu.state = .complete; extra.pmtu.current = 1300; // The client's NAT rebinds path 1 to an address the server will call // route 2. The client knows nothing of it. const id = try p.client.openBidirectional(); try p.client.useSendPath(1); // Enough of it that three times as much leaves room to challenge. const body: [400]u8 = @splat('r'); try p.client.write(id, &body); try testRebound(p, 1, 2); try testing.expectEqual(@as(paths_mod.Id, 2), extra.route); try testing.expect(p.server.pathValidated(2)); // Path 0 did not move. try testing.expectEqual(@as(paths_mod.Id, 0), p.server.paths.active); // §9.4 for the path that moved: started again once the new 4-tuple // proved itself. try testing.expect(extra.congestion.window != 100_000); try testing.expect(extra.ecn.state != .failed); // A finished search never probes again by itself; this one searched the // new 4-tuple and settled somewhere else. try testing.expect(extra.pmtu.current != 1300); try testing.expectEqualSlices(u8, &body, p.server.readable(id)); } test "draft-ietf-quic-multipath-21 3.1.2: a path whose port alone changed keeps what it measured" { // RFC 9000 §9.4's NAT rebinding, for one path: the same local address, // the peer at the same IP address on another port. const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); _ = try p.client.openPath(1, p.now); try p.settle(); const extra = p.server.extraFor(1).?; for ([_]paths_mod.Id{ 1, 2 }, [_]u16{ 40001, 50123 }) |route, port| { try p.server.setLocalAddress(route, test_server_address); try p.server.setPeerAddress(route, .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = port }); } extra.congestion.window = 100_000; extra.ecn.state = .failed; extra.pmtu.state = .complete; extra.pmtu.current = 1300; const id = try p.client.openBidirectional(); try p.client.useSendPath(1); const body: [400]u8 = @splat('r'); try p.client.write(id, &body); try testRebound(p, 1, 2); try testing.expectEqual(@as(paths_mod.Id, 2), extra.route); try testing.expect(p.server.pathValidated(2)); try testing.expect(extra.congestion.window >= 100_000); try testing.expect(extra.rtt.sampled); try testing.expectEqual(mtu.State.complete, extra.pmtu.state); try testing.expectEqual(@as(u16, 1300), extra.pmtu.current); try testing.expect(extra.ecn.state != .failed); try testing.expectEqualSlices(u8, &body, p.server.readable(id)); } test "draft-ietf-quic-multipath-21 3.1.2: a path pulled away by a forged address and back keeps what it knew" { // RFC 9000 §9.3's spurious migration, for one path: nothing was learned // on the forged 4-tuple, so nothing learned before it is thrown away -- // and a stale packet from it, once the path is back, does not move it // again. const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); _ = try p.client.openPath(1, p.now); try p.settle(); const extra = p.server.extraFor(1).?; extra.congestion.window = 100_000; const id = try p.client.openBidirectional(); try p.client.useSendPath(1); try p.client.write(id, "one"); const older = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), older.path); var held: [2048]u8 = undefined; @memcpy(held[0..older.bytes.len], older.bytes); const held_len = older.bytes.len; try p.client.write(id, "two"); const forged = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(forged.bytes, 2, p.now); try testing.expectEqual(@as(paths_mod.Id, 2), extra.route); try p.client.write(id, "three"); const genuine = (try p.client.send(&p.buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(genuine.bytes, 1, p.now); try testing.expectEqual(@as(paths_mod.Id, 1), extra.route); try testing.expectEqual(@as(usize, 100_000), extra.congestion.window); try testing.expect(extra.rtt.sampled); // The oldest of the three, replayed from the forged address. p.now += std.time.ns_per_ms; try p.server.receive(held[0..held_len], 2, p.now); try testing.expectEqual(@as(paths_mod.Id, 1), extra.route); } /// The send window each stream is currently working with: what `init` made /// of `Memory.send`, or what the last `growSend` raised it to. pub fn sendWindow(c: *const Connection) usize { return c.send_window; } test sendWindow { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expectEqual(@as(usize, stream_buffer), p.client.sendWindow()); } /// One stream's slice of each buffer, by slot. fn sendBuffer(c: *Connection, slot: usize) []u8 { return c.stream_send[slot * c.send_window ..][0..c.send_window]; } fn recvBuffer(c: *Connection, slot: usize) []u8 { return c.stream_recv[slot * c.recv_window ..][0..c.recv_window]; } fn presentBuffer(c: *Connection, slot: usize) []u8 { const bytes = c.recv_window / 8; return c.stream_present[slot * bytes ..][0..bytes]; } /// Initializes in place. /// /// In place because the reassemblers borrow this struct's own buffers, so a /// connection returned by value would hand back one whose streams pointed at /// the local it was built in — see `reassembly.Reassembler.init`. The same /// goes for what `options` lends: `memory`, the TLS object behind /// `handshake` and the state behind `rng` are borrowed for the life of the /// connection, while `local_id`, `destination_id` and `token` are copied. /// /// Nothing here can fail at run time. What could go wrong is a caller /// mistake — `memory` not cut into whole buffers or with too short a /// `tracked` table, flow control windows advertised in `local` that the /// receive buffers cannot keep, a preferred address on a client or with an /// identifier of a different length, an `initial_max_path_id` past /// `Memory.paths` — and each is an assertion. /// /// A client passes `destination_id` and has its Initial keys at once; a /// server leaves it null and derives them from the first packet that /// arrives (§5.2 of RFC 9001). pub fn init(c: *Connection, options: Options) void { assert(options.local_id.len <= packet.max_connection_id_len); const memory = options.memory; // Whole buffers, or a stream would be handed a fraction of one and the // arithmetic in `sendBuffer` would quietly overlap two streams. assert(memory.send.len % max_streams == 0); assert(memory.recv.len % max_streams == 0); assert(memory.present.len % max_streams == 0); const send_window = memory.send.len / max_streams; const recv_window = memory.recv.len / max_streams; // One bit an octet, which `reassembly.Reassembler` asserts again on the // slice it is actually given. assert(memory.present.len / max_streams >= (recv_window + 7) / 8); // One table for each of the Initial and Handshake spaces and one for // each path's application space; three scratch buffers of the same // length. assert(memory.paths >= 1 and memory.paths <= max_paths); assert(memory.tracked.len % (2 + memory.paths) == 0); const tracked = memory.tracked.len / (2 + memory.paths); assert(memory.scratch.len == 3 * tracked); // What a window puts in the air has to be a number of packets this // endpoint can still remember, because a packet with no slot does not go // -- the table blocks the sender the way the congestion window does. The // floor is one stream's worth, counted in §14.1's smallest permitted // datagram; a sender with small things to say, or with several streams // busy at once, needs more than the floor and merely runs slower on it. assert(tracked >= (send_window + min_initial_datagram - 1) / min_initial_datagram); // A flow control window is a promise, and `recv_window` is the most this // connection can keep. A caller that advertises more has not asked for // more throughput, it has arranged for the connection to accept octets it // has nowhere to put -- which surfaces as an INTERNAL_ERROR close, on the // first body large enough, to a peer that did nothing wrong and cannot // tell what happened. // // Said in a doc comment since the window was a constant, and that turned // out not to be enough: zig-http advertised sixty-four times it and // nothing said so until a two hundred kilobyte upload killed a // connection. A caller mistake this quiet is worth an assertion, which is // how the identifier length above is handled and for the same reason. assert(options.local.initial_max_stream_data_bidi_local <= recv_window); assert(options.local.initial_max_stream_data_bidi_remote <= recv_window); assert(options.local.initial_max_stream_data_uni <= recv_window); // The peer may have as many streams open at once as these two allow, // and each needs a slot in a table of `max_streams`. A caller offering // more has promised room this connection does not have, and a peer that // takes it up is closed with INTERNAL_ERROR for keeping to its limits. // Whatever is left over is what this endpoint can open itself. assert(options.local.initial_max_streams_bidi + options.local.initial_max_streams_uni <= max_streams); // §5.1.1: a peer may keep this many identifiers with this endpoint, and // the table keeps `ids.capacity`. One past it is // CONNECTION_ID_LIMIT_ERROR for a peer that sent no more than it was // told it could. assert(options.local.active_connection_id_limit <= ids.capacity); c.* = .{ .role = options.role, .handshake = options.handshake, .local = options.local }; c.stream_send = memory.send; c.stream_recv = memory.recv; c.stream_present = memory.present; c.send_window = send_window; c.recv_window = recv_window; c.acked_scratch = memory.scratch[0..tracked]; c.lost_scratch = memory.scratch[tracked..][0..tracked]; c.real_scratch = memory.scratch[2 * tracked ..][0..tracked]; for (&c.spaces, 0..) |*space, i| space.loss.init(memory.tracked[i * tracked ..][0..tracked]); // Path 0's application table is `spaces[2]`'s; each further path has the // one after it. c.path_limit = memory.paths; for (c.extra[0 .. memory.paths - 1], 0..) |*extra, i| { extra.space.loss.init(memory.tracked[(3 + i) * tracked ..][0..tracked]); extra.id = @intCast(i + 1); // Every identifier this endpoint issues is the same length -- a // short header has no field for it -- so each path's are too. extra.issued.len = options.local_id.len; } // A limit this endpoint could not honour is a caller mistake, and a // quiet one: the peer would open a path there was no room for. if (options.local.initial_max_path_id) |max| assert(max < memory.paths); c.local_max_path_id = options.local.initial_max_path_id orelse 0; c.next_path_id = memory.paths; c.id_rng = options.rng; c.reset_key = options.reset_key; if (options.token.len > 0) { assert(options.token.len <= c.token_buf.len); @memcpy(c.token_buf[0..options.token.len], options.token); c.token_len = options.token.len; } c.paths = .init(options.path); // §8.1: a server's first path is the client's word until something proves // it -- see `address_validated`. if (options.role == .server and !options.address_validated) { c.paths.find(options.path).?.validated = false; } c.measured_route = options.path; c.issued = .init(options.local_id); // §5.1.1: "if the preferred_address transport parameter is sent, the // sequence number of the supplied connection ID is 1." Reserved by the // specification rather than negotiated, so a server that advertises one // and then issues its own identifiers from 1 would be naming two // different values with one number -- which the peer reads as an endpoint // that has lost track of what it issued, and closes the connection over. // // Registering it here is also what makes the server answer to it: a // client that takes the invitation addresses its packets to this // identifier, and a server that had not entered it in its own table would // not recognise the connection it had just invited the client to move to. if (options.local.preferred_address) |a| { assert(options.role == .server); // The same length as every other identifier this endpoint issues. A // short header carries no connection ID length field (§17.3.1), so an // endpoint can only find the field in packets addressed to itself if // it knows the size in advance -- which means one size for all of // them, and a caller that chose otherwise has built a server that // cannot read its own mail. assert(a.connection_id.len == options.local_id.len); _ = c.issued.add(a.connection_id, a.stateless_reset_token) catch unreachable; } c.recv_credit = .init(options.local.initial_max_data); c.local_stream_limit = .{ options.local.initial_max_streams_bidi, options.local.initial_max_streams_uni, }; c.advertised_stream_limit = c.local_stream_limit; @memcpy(c.local_id_buf[0..options.local_id.len], options.local_id); c.local_id_len = options.local_id.len; for (&c.streams, 0..) |*entry, i| { entry.* = .{}; entry.send = .init(c.sendBuffer(i), 0); entry.recv = .init(c.recvBuffer(i), c.presentBuffer(i), 0); } var out_at: usize = 0; for (&c.spaces, 0..) |*s, i| { s.stream = .init(c.windows[i][0..crypto_window[i]], &c.bitmaps[i]); s.crypto = .init(c.out_storage[out_at..][0..crypto_out_window[i]]); out_at += crypto_out_window[i]; } // §4.6: a client that is resuming already has a 0-RTT write key, and had // it before this connection existed. Nothing will be provided to TLS // before the first `send`, so this is the only chance to notice. c.collectKeys(); // §7.4.1: the limits a 0-RTT sender acts on, which are the ones the // server set last time. They are left in place when the real ones arrive // rather than replaced, because `grant` only ever raises a limit -- a // server is free to be more generous than it was and forbidden to be less // (see `reducesLimits`), so the maximum of the two is always the right // answer. if (options.remembered) |was| { c.remembered = was; c.peer = rememberable(was); c.send_credit.grant(was.initial_max_data); c.peer_stream_limit = .{ was.initial_max_streams_bidi, was.initial_max_streams_uni }; } if (options.destination_id) |id| { assert(id.len <= packet.max_connection_id_len); @memcpy(c.peer_id_buf[0..id.len], id); c.peer_id_len = id.len; @memcpy(c.original_destination_buf[0..id.len], id); c.original_destination_len = id.len; c.deriveInitialKeys(id); // §5.1.1: the identifier a client invents for its first Destination // Connection ID "[is] not assigned sequence numbers" — the server's // own choice, which arrives in that packet's Source Connection ID, is // sequence zero, and this is replaced by it below. } } test init { var memory: Storage(.{}) = .{}; var tls_client = try testTlsClient(&test_client_parameters); var client: Connection = undefined; client.init(.{ .role = .client, .handshake = tls_client.handshake(), .memory = memory.memory(), .local_id = &test_client_id, // The client's invention, from which both ends derive Initial keys. .destination_id = &test_destination_id, // What was encoded into `test_client_parameters` for TLS: the two // have to agree. .local = test_limits, }); try testing.expectEqualSlices(u8, &test_client_id, client.localId()); try testing.expect(!client.isEstablished()); // Nothing has happened yet but a ClientHello waiting to go out. var buffer: [2048]u8 = undefined; const first = (try client.send(&buffer, 0)).?; try testing.expectEqual(@as(usize, min_initial_datagram), first.bytes.len); } /// The connection ID this endpoint asked to be addressed by: `Options.local_id` /// as it was passed to `init`. /// /// Not every identifier this endpoint answers to. Further ones go to the peer /// in NEW_CONNECTION_ID frames (§5.1.1), and `acceptsId` is the question that /// covers all of them. pub fn localId(c: *const Connection) []const u8 { return c.local_id_buf[0..c.local_id_len]; } test localId { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expectEqualSlices(u8, &test_server_id, p.server.localId()); // The peer learned it from the handshake, and addresses this end by it. try testing.expectEqualSlices(u8, p.server.localId(), p.client.peerId()); } /// The connection ID packets to the peer are addressed with now. /// /// It changes. A client starts with the `destination_id` it invented and /// takes the server's choice from the server's first packet (§7.2), and /// either end moves to a spare one with `rotatePeerId` or when it migrates /// (§9.5). The slice is borrowed until the next call that changes it. pub fn peerId(c: *const Connection) []const u8 { return c.peer_id_buf[0..c.peer_id_len]; } test peerId { var memory: Storage(.{}) = .{}; var tls_client = try testTlsClient(&test_client_parameters); var client: Connection = undefined; client.init(.{ .role = .client, .handshake = tls_client.handshake(), .memory = memory.memory(), .local_id = &test_client_id, .destination_id = &test_destination_id, .local = test_limits, }); // Before the server has said anything, the identifier the client made up. try testing.expectEqualSlices(u8, &test_destination_id, client.peerId()); // After the handshake, the one the server chose. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expectEqualSlices(u8, &test_server_id, p.client.peerId()); try testing.expectEqualSlices(u8, &test_client_id, p.server.peerId()); } /// Whether the TLS handshake is complete and 1-RTT keys are in place in /// both directions, so that streams can carry data under them. /// /// Complete is not confirmed (§4.1.2 of RFC 9001): a client is established /// once it has sent its Finished, before it knows the server read it. See /// `isConfirmed` for the stronger statement. pub fn isEstablished(c: *const Connection) bool { return c.handshake.isComplete() and c.spaces[2].hasKeys(); } test isEstablished { const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); try testing.expect(!p.client.isEstablished()); try p.handshake(); try testing.expect(p.client.isEstablished()); try testing.expect(p.server.isEstablished()); } /// §4.1.2 of RFC 9001: whether the handshake is confirmed, which is a /// stronger statement than `isEstablished` and the one §6 requires before a /// key update or §9 of RFC 9000 before a migration. /// /// A server's handshake is confirmed as soon as it completes; a client's /// when a HANDSHAKE_DONE frame arrives. pub fn isConfirmed(c: *const Connection) bool { return c.confirmed; } test isConfirmed { const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); try testing.expect(!p.client.isConfirmed()); try p.handshake(); try testing.expect(p.server.isConfirmed()); try testing.expect(p.client.isConfirmed()); } /// §5.2: the Initial keys come from the client's first Destination Connection /// ID and a fixed salt, so both ends can derive them before anything has been /// agreed — and so can anyone who saw the packet, which is why an Initial /// packet has no confidentiality worth the name. fn deriveInitialKeys(c: *Connection, destination_id: []const u8) void { const s = &c.spaces[0]; switch (c.role) { .client => { s.write = .initialKeys(destination_id, .client); s.read = .initialKeys(destination_id, .server); }, .server => { s.write = .initialKeys(destination_id, .server); s.read = .initialKeys(destination_id, .client); }, } } /// Takes whatever keys TLS has produced since the last look. /// /// §4.1.4 of RFC 9001: "the availability of new keys is always a result of /// providing inputs to TLS", so this runs after every `provide` rather than /// on a schedule of its own. fn collectKeys(c: *Connection) void { // §4.6: the 0-RTT keys, which arrive earlier than any of the others and // in one direction only. A client has its write key the moment it has // written a ClientHello -- before it has heard anything at all, which is // the entire point -- so this is also asked at `init`, where nothing has // been provided yet and the loop below has nothing to find. switch (c.role) { .client => if (c.early_write == null) { if (c.handshake.writeSecret(.early_data)) |secret| { c.early_write = .fromSecret(secret); } }, .server => if (c.early_read == null) { if (c.handshake.readSecret(.early_data)) |secret| { c.early_read = .fromSecret(secret); } }, } for ([_]tls.Level{ .handshake, .application }) |level| { const s = &c.spaces[@backingInt(Space.of(level))]; if (s.write == null) { if (c.handshake.writeSecret(level)) |secret| { s.write = .fromSecret(secret); // §6.1 derives each key phase from the one before it, so the // application secrets are kept where `tls.Secret`'s borrowed // ones cannot be. if (level == .application) c.write_secret = .from(secret); } } if (s.read == null) { if (c.handshake.readSecret(level)) |secret| { s.read = .fromSecret(secret); if (level == .application) { c.read_secret = .from(secret); c.prepareNextKeys(); } } } } } /// §6.3: derives the next phase's read keys before they are needed. /// /// Ahead of time on purpose. "The process of creating new packet protection /// keys for receiving packets could reveal that a key update has occurred. An /// endpoint MAY generate new keys as part of packet processing, but this /// creates a timing signal that could be used by an attacker to learn when /// key updates happen and thus leak the value of the Key Phase bit." fn prepareNextKeys(c: *Connection) void { const current = c.read_secret orelse return; const keys = c.spaces[2].read orelse return; const next = current.next(); c.next_read_secret = next; c.next_read = protection.nextKeys(&keys, next); } /// §6.1 and §6.2: moves both directions to the next key phase. /// /// Both directions, and that is the part that differs from TLS. §6: "Initiating /// a key update results in both endpoints updating keys. This differs from TLS /// where endpoints can update keys independently." The Key Phase bit is one /// bit for the whole connection, so there is only one phase to be in. fn rotateKeys(c: *Connection, now: recovery.Instant) void { const space = &c.spaces[2]; // §6.5: the old read keys stay for a while, because packets protected // with them may still be in the network. "An endpoint SHOULD retain old // read keys for no more than three times the PTO after having received a // packet protected using the new keys." c.previous_read = space.read; // draft-ietf-quic-multipath-21 §2.5: "three times the largest Probe // Timeout (PTO) among all the paths", since a packet from the old phase // can still be on its way down the slowest of them. c.previous_read_until = now +| (c.largestProbeTimeout() *| 3); space.read = c.next_read; c.read_secret = c.next_read_secret; c.next_read = null; c.next_read_secret = null; c.prepareNextKeys(); if (c.write_secret) |current| { const next = current.next(); if (space.write) |keys| space.write = protection.nextKeys(&keys, next); c.write_secret = next; } c.key_phase = !c.key_phase; c.phase_first_sent = space.next_number; // §6.6 counts encrypted packets "for each set of keys", so the count // starts again with them. c.packets_encrypted = 0; } /// Starts a key update, if §6 permits one now. /// /// §6.1: "An endpoint MUST NOT initiate a key update prior to having confirmed /// the handshake", and "MUST NOT initiate a subsequent key update unless it /// has received an acknowledgment for a packet that was sent protected with /// keys from the current key phase. This ensures that keys are available to /// both peers before another key update can be initiated" — an endpoint that /// ratcheted twice in a row would be using keys its peer had not derived. /// /// True if the update started, in which case the next packet goes out in the /// new key phase; false if §6 does not permit one yet, which changes nothing. /// A caller does not normally need this — §6.6's confidentiality limit starts /// one on its own — but may ask for one sooner. pub fn updateKeys(c: *Connection, now: recovery.Instant) bool { // §6: "Once the handshake is confirmed (see Section 4.1.2), an endpoint // MAY initiate a key update" -- and MUST NOT before, because a peer that // has not confirmed may not yet have the keys the update is derived from. if (!c.confirmed) return false; if (c.next_read == null) return false; const acked = c.spaces[2].loss.largest_acked orelse return false; if (c.phase_first_sent > 0 and acked < c.phase_first_sent) return false; c.rotateKeys(now); return true; } test updateKeys { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expect(p.client.updateKeys(p.now)); // Nothing sent in the new phase has been acknowledged, so not again yet. try testing.expect(!p.client.updateKeys(p.now)); // Once a packet of the new phase is acknowledged, another is allowed. const id = try p.client.openBidirectional(); try p.client.write(id, "new keys"); try p.settle(); try testing.expectEqualStrings("new keys", p.server.readable(id)); try testing.expect(p.client.updateKeys(p.now)); } /// Hands a datagram to the connection, saying what its IP header's ECN field /// held. /// /// The codepoint arrives beside the datagram rather than inside it, because a /// QUIC packet carries no copy of it: it is read from the IP header, which is /// the caller's to reach and not this library's. `receive` is the same thing /// for a caller that cannot reach it, and §13.4.1 makes that a position /// rather than an omission -- an endpoint "that does not have access to /// received ECN fields... does not report ECN counts for packets it /// receives", and a peer reading the absence correctly disables ECN. pub fn receiveEcn( c: *Connection, datagram: []u8, path: paths_mod.Id, now: recovery.Instant, codepoint: ack.Codepoint, ) Error!void { c.inbound_ecn = codepoint; defer c.inbound_ecn = .not_ect; return c.receive(datagram, path, now); } test receiveEcn { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "hello"); var buffer: [2048]u8 = undefined; const datagram = (try p.client.send(&buffer, p.now)).?; // The caller read ECT(0) from the IP header of the datagram it received // (in a real network; here, whatever `send` asked for will do). try p.server.receiveEcn(datagram.bytes, datagram.path, p.now, .ect0); try testing.expectEqualStrings("hello", p.server.readable(id)); } /// Processes one datagram that arrived on the caller's path `path`. /// /// `datagram` is modified in place — removing header protection is an /// in-place operation on the octets that arrived — and may hold several /// coalesced packets (§12.2), which are handled in order. Nothing keeps a /// reference to it once this returns. /// /// A packet that cannot be read is dropped rather than answered. §5.2 of RFC /// 9000 is explicit that an endpoint MUST NOT respond to a packet it could /// not process, because anything sent to an unvalidated address is an /// amplification vector; and §5.5 of RFC 9001 says a packet that fails /// authentication is simply discarded, since anyone can send rubbish to a UDP /// port. /// /// An error is the peer breaking the protocol, or this endpoint running out /// of room for what the peer was entitled to send. Either way the connection /// is already closing when the error comes back: the next `send` carries a /// CONNECTION_CLOSE with the matching §20 code, so the caller has nothing to /// clean up beyond going on calling `send` and `onTimeout`. For a caller /// that can read the IP header's ECN field, `receiveEcn` is the same thing. pub fn receive( c: *Connection, datagram: []u8, path: paths_mod.Id, now: recovery.Instant, ) Error!void { // §10.2: "Violations of the protocol lead to an immediate close." The // caller is told what happened *and* the connection is put into the // closing state, so the next `send` carries the news to the peer rather // than leaving it to time out wondering. c.process(datagram, path, now) catch |e| { c.close(c.codeFor(e), "", now); return e; }; } test receive { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "hello"); var buffer: [2048]u8 = undefined; const datagram = (try p.client.send(&buffer, p.now)).?; // A copy damaged in transit fails authentication and is dropped, which // is neither an error nor anything the server answers. var damaged: [2048]u8 = undefined; @memcpy(damaged[0..datagram.bytes.len], datagram.bytes); damaged[datagram.bytes.len - 1] ^= 0xff; try p.server.receive(damaged[0..datagram.bytes.len], datagram.path, p.now); try testing.expectEqual(@as(usize, 0), p.server.readable(id).len); // The real one is read. try p.server.receive(datagram.bytes, datagram.path, p.now); try testing.expectEqualStrings("hello", p.server.readable(id)); } fn process( c: *Connection, datagram: []u8, path: paths_mod.Id, now: recovery.Instant, ) Error!void { // §9: "Clients are responsible for initiating all migrations", so every // path a client has is one it chose. "If a client receives packets from // an unknown server address, the client MUST discard these packets." // n0's NAT traversal is the exception: the answers to its probes come // from the candidates the server advertised, on routes the caller has // only just numbered. if (c.role == .client and c.nat == null and c.paths.find(path) == null) return; // §10.3.1: the check has to happen when nothing in the datagram could be // processed — "the comparison MUST be performed when the first packet in // an incoming datagram either cannot be associated with a connection or // cannot be decrypted" — but doing it first is permitted and simpler, and // costs one constant-time comparison per datagram against a list that is // never longer than four. if (c.isStatelessReset(datagram)) { // §10.3.1: "if the last 16 bytes of the datagram are identical in // value to a stateless reset token, the endpoint MUST enter the // draining period and not send any further packets on this // connection." Draining rather than closing: the peer has already // forgotten the connection, so there is nobody to tell. c.closing.drain(.no_error, false, "stateless reset", c.closeDeadline(now)); return; } // §10.2: the wait is over and this connection is gone. A packet arriving // now belongs to nothing. if (c.closing.expired(now)) { c.closing.state = .closed; return; } if (c.closing.state != .open) { // §10.2.1: "An endpoint in the closing state sends a packet // containing a CONNECTION_CLOSE frame in response to any incoming // packet that it attributes to the connection" — and does not process // it. "An endpoint that is closing is not required to process any // received frame." c.closing.onPacket(); return; } // §21.1.1.1: what arrived from here is the allowance for what may be // sent back to it, until the path has been validated. { const seen = c.paths.observe(path) catch return error.TooManyPaths; seen.received +|= datagram.len; } var at: usize = 0; var first_destination: ?[]const u8 = null; while (at < datagram.len) { const rest = datagram[at..]; // RFC 9287 §3: whether a clear Fixed Bit is allowed is this // connection's own promise, made in its transport parameters. const header = packet.parseWith(rest, c.local_id_len, c.local.grease_quic_bit) catch return; // §12.2: "Receivers SHOULD ignore any subsequent packets with a // different Destination Connection ID than the first packet in the // datagram" -- a sender "MUST NOT coalesce" them, so one that does // is not the peer. const first = first_destination orelse header.destination; first_destination = first; // §7.2: "Once a client has received a valid Initial packet from the // server, it MUST discard any subsequent packet it receives on that // connection with a different Source Connection ID." A Retry or // Version Negotiation packet goes to its own checks below. const foreign_source = c.role == .client and c.peer_id_confirmed and header.form == .long and header.kind != .retry and header.kind != .version_negotiation and !std.mem.eql(u8, header.source, c.server_source_buf[0..c.server_source_len]); if (foreign_source or !std.mem.eql(u8, header.destination, first)) { // Only a long header says where it ends. if (header.form == .short or header.kind == .retry or header.kind == .version_negotiation) return; at += header.end; continue; } // §5.1.1: "when an endpoint issues a connection ID, it MUST accept // packets that carry this connection ID for the duration of the // connection or until its peer invalidates the connection ID". A // packet addressed to something this endpoint never issued, or has // retired, belongs to another connection or to nobody — and a server // that answered it would be answering on behalf of a connection it // does not have. // // draft-ietf-quic-multipath-21 §3.2: with multipath, each identifier // belongs to one path, so the one a packet is addressed to also says // which path's packet number space it is in. var on: ?*ExtraPath = null; if (header.form == .short and !c.issued.accepts(header.destination)) { on = c.extraAddressedBy(header.destination) orelse return; } // A server learns the connection IDs from the first Initial it sees. if (c.role == .server and c.spaces[0].read == null and header.kind == .initial) { c.deriveInitialKeys(header.destination); @memcpy(c.peer_id_buf[0..header.source.len], header.source); c.peer_id_len = header.source.len; c.received = .init(header.source); @memcpy(c.original_destination_buf[0..header.destination.len], header.destination); c.original_destination_len = header.destination.len; } // §17.2.5: a Retry packet has no packet number, no payload and no // encryption level — it is handled whole or not at all. if (header.kind == .retry) { try c.onRetry(rest, header); return; } // §17.2.1: no packet number and no payload either, and it "consumes // an entire UDP datagram", so there is nothing after it to go on to. if (header.kind == .version_negotiation) { c.onVersionNegotiation(rest, header, now); return; } // §12.2: "if decryption fails (because the keys are not available or // for any other reason), the receiver MAY either discard or buffer // the packet for later processing and MUST attempt to process the // remaining packets." A long header's Length is outside the header // protection, so where the next packet starts is known whether or not // this one can be read; a short header's packet is the last anyway. const skip = header.end; const level = header.kind.level() orelse { at += skip; continue; }; const space_index = @backingInt(Space.of(level)); // §4.9.1: a packet at a level whose keys are gone is not merely // undecryptable, it is one this endpoint has decided to stop reading. // The ordinary case is a client still acknowledging the handshake, // with its 1-RTT data coalesced behind. if (c.discarded[space_index]) { at += skip; continue; } const space = &c.spaces[space_index]; // §4.6: a 0-RTT packet shares the application space's numbers and // none of its keys. A server that reached for `space.read` here would // be trying to open the client's early data with a key derived from a // handshake that had not finished when the client sent it. const maybe_keys = if (header.kind == .zero_rtt) c.early_read else space.read; const keys = maybe_keys orelse { at += skip; continue; }; // A packet on a path past path 0 is numbered in that path's space, // under the same keys: §2.4 separates paths by the nonce, not the key. const numbering: *SpaceState = if (on) |e| &e.space else space; const nonce_path: u32 = if (on) |e| e.id else 0; var payload: [2048]u8 = undefined; const largest = numbering.acks.largest() orelse 0; // Header protection first, on its own, because §6.1 does not update // the header protection key and §17.3.1 puts the Key Phase bit under // it: which packet protection keys a 1-RTT packet used cannot be known // until the header has been unmasked, and unmasking is in place, so // there is no trying again with a different guess. const revealed = packet.reveal(&keys, largest, rest, c.local_id_len, c.local.grease_quic_bit) catch { c.packets_failed +|= 1; at += skip; continue; }; // §6.5: a short header's Key Phase bit has two values and a // connection has more than two phases, so a bit that differs from the // current one means one of two things — a straggler protected with // the *previous* keys, or the peer initiating an update with the // *next* ones. Both are tried, oldest first, which is what §6.5's // "retain only two sets of packet protection keys" alternative // amounts to when the packet numbers cannot settle it. // // Trying two AEAD openings reveals that the first failed, which §6.3 // warns about — but what it warns about is *deriving* keys during // packet processing, which `prepareNextKeys` has already done off the // critical path. What is left is two constant-time openings. var candidates: [2]?*const protection.Keys = .{ null, null }; var rotates: [2]bool = .{ false, false }; if (header.form == .long or revealed.keyPhase() == c.key_phase) { candidates[0] = &keys; } else { if (c.previous_read) |*old_keys| { if (now < c.previous_read_until) candidates[0] = old_keys; } if (c.next_read) |*next| { candidates[1] = next; rotates[1] = true; } } var opened: packet.Opened = undefined; var rotate = false; var got = false; for (candidates, rotates) |maybe, rotates_on_success| { const candidate = maybe orelse continue; opened = packet.decryptOn(candidate, nonce_path, revealed, rest, &payload) catch |err| switch (err) { // §17.2 and §17.3.1: "An endpoint MUST treat receipt of a // packet that has a non-zero value for these bits, after // removing both packet and header protection, as a // connection error of type PROTOCOL_VIOLATION." It // authenticated, so the peer sent it as it is. error.ReservedBitsSet => return error.ProtocolViolation, else => continue, }; rotate = rotates_on_success; got = true; break; } if (!got) { // Undecryptable, malformed, or protected with keys this endpoint // does not have. Nothing is said about it, and the next packet // in the datagram is tried, as above. // // §6.6 counts these: "endpoints MUST count the number of received // packets that fail authentication during the lifetime of a // connection", because each one is a forgery attempt and enough // of them mean the AEAD's integrity margin is spent. c.packets_failed +|= 1; if (c.packets_failed >= integrity_limit) return error.AeadLimitReached; at += skip; continue; } at += opened.header.end; // §12.3: "a receiver MUST discard a newly unprotected packet unless // it is certain that it has not processed another packet with the // same packet number from the same packet number space." The network // duplicates packets and an attacker can replay them, and most frames // shrug off a repeat -- but a DATAGRAM would reach the application // twice. It was acknowledged the first time, so it is simply dropped. if (numbering.acks.seen(opened.number)) continue; if (opened.header.first & 0x40 == 0) c.packets_greased +|= 1; // §8.1: "Once an endpoint has successfully processed a Handshake // packet from the peer, it can consider the peer address to have // been validated" -- only a client that read the server's Initial // can have the keys to write one, so whoever sent it receives at the // address it came from. if (c.role == .server and level == .handshake) { if (c.paths.find(path)) |seen| seen.validated = true; } // §6.2: "If a packet is successfully processed using the next key and // IV, then the peer has initiated a key update. The endpoint MUST // update its send keys to the corresponding key phase in response." // Only now, after the packet authenticated — a Key Phase bit is one // bit that anyone can flip, and rotating on an unauthenticated one // would let a passer-by desynchronise the connection with a forgery // that never had to decrypt. if (rotate) { c.rotateKeys(now); c.phase_first_read = opened.number; } // §7.2: "Upon first receiving an Initial or Retry packet from the // server, the client uses the Source Connection ID supplied by the // server as the Destination Connection ID for subsequent packets." // // Only once, and only on a packet that decrypted: a client that // adopted a connection ID out of an unauthenticated header would let // anyone who can write a UDP packet redirect the rest of the // handshake. That it decrypted means it was sent by someone who knew // the client's original Destination Connection ID, which for an // Initial is a low bar — and is exactly why §7.3 makes the peer prove // the same value again inside the encrypted handshake. if (c.role == .client and !c.peer_id_confirmed and header.form == .long) { @memcpy(c.peer_id_buf[0..header.source.len], header.source); c.peer_id_len = header.source.len; c.received = .init(header.source); c.peer_id_confirmed = true; @memcpy(c.server_source_buf[0..header.source.len], header.source); c.server_source_len = header.source.len; } // draft-ietf-quic-multipath-21 §3.1: a packet addressed to an // identifier for a path ID nothing has used yet is the client opening // that path. "Such packets are valid if they can be properly decrypted // given a valid connection ID" -- which this one just was. if (on) |e| try c.onPathPacket(e, path, now); try c.processFrames(level, opened, path, numbering, on, now); // §4.9.1, and "successfully processes" is the phrase: the packet // authenticated and its frames were accepted, which is what proves // both ends are past needing Initial keys. c.maybeDiscardInitial(level); c.maybeConfirm(); c.maybeDiscardHandshake(); } } fn processFrames( c: *Connection, level: tls.Level, opened: packet.Opened, path: paths_mod.Id, /// The packet number space the packet was numbered in: the level's own, /// or a path's past path 0. numbering: *SpaceState, /// The path past path 0 the packet arrived on, if it did. on: ?*ExtraPath, now: recovery.Instant, ) Error!void { const space = &c.spaces[@backingInt(Space.of(level))]; var eliciting = false; // §9.1: "PATH_CHALLENGE, PATH_RESPONSE, NEW_CONNECTION_ID, and PADDING // frames are 'probing frames', and all other frames are 'non-probing // frames'" -- and OBSERVED_ADDRESS, which draft-ietf-quic-address- // discovery-01 §4.1 declares one. Only a non-probing packet says the peer has *moved*: probing // is what an endpoint does to a path it is not yet using, so treating a // probe as a migration would let anyone move a connection by sending one. var non_probing = false; // §12.4: "An endpoint MUST treat receipt of a packet containing no // frames as a connection error of type PROTOCOL_VIOLATION." if (opened.payload.len == 0) return error.ProtocolViolation; // §12.4 and §19: a frame that cannot be parsed -- an unknown type, one // cut short, or fields that contradict each other -- is a // FRAME_ENCODING_ERROR. PROTOCOL_VIOLATION is §20.1's catch-all for // what no more specific code covers, and this has one. var it: frame.Iterator = .init(opened.payload); while (it.next() catch return error.FrameEncodingError) |f| { // §12.4: "An endpoint MUST treat receipt of a frame in a packet type // that is not permitted as a connection error of type // PROTOCOL_VIOLATION." if (!f.allowedIn(level)) return error.FrameNotPermitted; if (f.isAckEliciting()) eliciting = true; switch (f) { .path_challenge, .path_response, .new_connection_id, .padding, .observed_address => {}, else => non_probing = true, } switch (f) { .crypto => |crypto| try space.stream.insert(crypto.offset, crypto.data), .ack => |a| try c.onAck(level, a, now), .connection_close => |cc| { // §10.2: "After receiving a CONNECTION_CLOSE frame, endpoints // enter the draining state." Nothing further is sent — not // even an acknowledgement, which is why this returns rather // than finishing the packet. c.closing.drain( @fromBackingInt(@intCast(cc.error_code)), cc.application, cc.reason, c.closeDeadline(now), ); return; }, .stream => |sf| try c.onStreamFrame(sf), // §4.1: a limit that does not increase has no effect, which // `grant` is what makes true. .max_data => |m| c.send_credit.grant(m), .max_stream_data => |m| { const entry = try c.findOrOpen(m.stream) orelse continue; // §19.10: "An endpoint that receives a MAX_STREAM_DATA frame // for a receive-only stream MUST terminate the connection // with error STREAM_STATE_ERROR." Credit for a stream this // endpoint cannot send on is credit for nothing. if (!entry.id.canSend(c.initiator())) return error.StreamStateError; entry.send.grant(m.maximum); }, .max_streams => |m| { // §4.6: "If a max_streams... frame is received with a value // greater than 2^60... the connection MUST be closed // immediately with a connection error... of type // FRAME_ENCODING_ERROR if it was received in a frame." The // check is on the frame rather than on the kind, so a // nonsensical limit for a directionality this endpoint never // uses is still an error rather than something to shrug at. if (m.maximum > 1 << 60) return error.ProtocolViolation; const at = @backingInt(streamDirection(m.kind)); c.peer_stream_limit[at] = @max(c.peer_stream_limit[at], m.maximum); }, .datagram => |d| { // §3: "An endpoint that receives a DATAGRAM frame when it has // not sent the max_datagram_frame_size transport parameter // MUST terminate the connection with an error of type // PROTOCOL_VIOLATION." Not having asked for them is a // statement, and a peer that ignores it is not one to keep // talking to. if (c.local.max_datagram_frame_size == 0) return error.ProtocolViolation; if (datagramFrameLen(d.data.len) > c.local.max_datagram_frame_size) { return error.ProtocolViolation; } // §5.3: "A receiver... MAY drop" one it has no room for, and // an application that chose an unreliable transport has // already agreed that dropping is an outcome. Dropping the // newest keeps the oldest, which is the order an application // reading a queue expects to lose things in. _ = c.inbound.push(d.data); }, .reset_stream => |r| try c.onResetStream(r), .stop_sending => |ss| { // §3.5: the peer does not want what this endpoint is sending. // The answer is a RESET_STREAM, which is what `reset` queues. const entry = try c.findOrOpen(ss.stream) orelse continue; if (!entry.id.canSend(c.initiator())) return error.StreamStateError; entry.send.reset(ss.error_code); }, // §4.1 and §4.6: a blocked peer says so for the benefit of // whoever is debugging. §4.2 is explicit that a receiver "MUST // NOT wait for a STREAM_DATA_BLOCKED or DATA_BLOCKED frame before // sending a MAX_STREAM_DATA or MAX_DATA frame", so there is // nothing to do about one but note it. .data_blocked => |maximum| c.peer_data_blocked = maximum, .streams_blocked => |blocked| c.peer_streams_blocked[@backingInt(blocked.kind)] = blocked.maximum, .stream_data_blocked => |blocked| { c.peer_stream_data_blocked = blocked; // §19.13: "An endpoint that receives a STREAM_DATA_BLOCKED // frame for a send-only stream MUST terminate the connection // with error STREAM_STATE_ERROR." And like any frame naming // a stream, it opens a peer's stream not yet seen (§3.2). const entry = try c.findOrOpen(blocked.stream) orelse continue; if (!entry.id.canReceive(c.initiator())) return error.StreamStateError; }, .new_token => |token| { // §19.7: "A server MUST treat receipt of a NEW_TOKEN frame as // a connection error of type PROTOCOL_VIOLATION", and "a // client MUST treat receipt of a NEW_TOKEN frame with an // empty Token field as a connection error of type // FRAME_ENCODING_ERROR." A token to keep for a later // connection is otherwise not kept: this library has nowhere // that outlives the connection to keep it. if (c.role == .server) return error.ProtocolViolation; if (token.len == 0) return error.FrameEncodingError; }, .new_connection_id => |n| try c.onNewConnectionId(n), .retire_connection_id => |sequence| try c.onRetireConnectionId(sequence, opened.header.destination), // draft-ietf-quic-multipath-21 §4. With one path in use, which is // all this endpoint opens so far, each frame that names path 0 // means exactly what its RFC 9000 counterpart does -- §2.3: "ACK // frames when used with the multipath extension acknowledge // packets for the path with path ID 0" -- and one naming any // other permitted path is about a path this endpoint never had. .path_ack => |p| if (try c.onPathFrame(p.path)) |which| switch (which) { .zero => try c.onAck(level, p.ack, now), // §3.4.3: "PATH_ACK frames received with an abandoned path ID // are silently ignored", and so is one for a path nothing has // sent on. .extra => |e| if (e.state == .open) try c.onAckIn(recoveryOfPath(e), p.ack, now), }, .path_new_connection_id => |p| if (try c.onPathFrame(p.path)) |which| switch (which) { .zero => try c.onNewConnectionId(p.id), // §3.2: a path's identifiers can arrive before the path is in // use -- that is how a client comes to have one to open it // with -- so they are kept whatever the path's state. .extra => |e| if (e.state != .abandoned) e.received.offer( p.id.sequence, p.id.retire_prior_to, p.id.id, p.id.token.*, c.local.active_connection_id_limit, ) catch |err| switch (err) { error.ConnectionIdLimitError => return error.ConnectionIdLimitError, error.FrameEncodingError => return error.FrameEncodingError, else => return error.ProtocolViolation, }, }, .path_retire_connection_id => |p| if (try c.onPathFrame(p.path)) |which| switch (which) { .zero => try c.onRetireConnectionId(p.sequence, opened.header.destination), .extra => |e| e.issued.retire(p.sequence) catch return error.ProtocolViolation, }, .path_abandon => |p| if (try c.onPathFrame(p.path)) |which| switch (which) { // §3.4: "If a PATH_ABANDON frame is received for the only // open path of a QUIC connection, the receiving peer SHOULD // send a CONNECTION_CLOSE frame and enter the closing state." .zero => if (!c.anyExtraOpen()) { c.close(.no_error, "the only path was abandoned", now); return; } else { // Another path is open, so the connection lives on it: // answer, stop sending on path 0, and move new data to // a path that is still there. if (!c.path0_sent_abandon) c.path0_owes_abandon = true; c.abandonZero(); }, .extra => |e| { c.abandon(e); // §3.4: the state is kept "for 3 PTO after the // PATH_ABANDON frame has been received", so that late // packets on the path are acknowledged rather than // answered with a stateless reset. if (!e.peer_abandoned) { e.peer_abandoned = true; e.discard_at = now +| c.largestProbeTimeout() *| 3; } }, }, // §3.3: advice about a path's use, which `sendTarget` follows. // Refused if it names a path this endpoint never allowed. .path_status => |p| if (try c.onPathFrame(p.path)) |which| switch (which) { .zero => c.path0_status.onPeer(p), .extra => |e| e.status.onPeer(p), }, .path_cids_blocked => |p| if (try c.onPathFrame(p.path)) |which| { // §4.7: "Receipt of a value of Next Sequence Number that is // higher than the sequence number of the next expected to be // issued connection ID for this path MUST be treated as a // connection error of type PROTOCOL_VIOLATION." Otherwise it // obliges nothing: this endpoint issues a path's identifier // as soon as the path is allowed and replaces a retired one. const next = switch (which) { .zero => c.issued.next_sequence, .extra => |e| e.issued.next_sequence, }; if (p.next_sequence > next) return error.ProtocolViolation; }, .max_path_id => |max| { if (!c.multipathNegotiated()) return error.ProtocolViolation; // §4.6: "MUST NOT exceed 2^32-1" and "MUST NOT be lower than // the value advertised in the initial_max_path_id transport // parameter"; one that does not raise the limit is a // reordered old one, and ignored. if (max > parameters.max_path_id) return error.ProtocolViolation; if (max < c.peer.?.initial_max_path_id.?) return error.ProtocolViolation; c.peer_max_path_id = @max(c.peer_max_path_id, max); }, .paths_blocked => |max| { if (!c.multipathNegotiated()) return error.ProtocolViolation; // §4.7: "Receipt of a value of Maximum Path Identifier... // that is higher than the local maximum value MUST be treated // as a connection error of type PROTOCOL_VIOLATION." if (max > c.localMaxPathId()) return error.ProtocolViolation; }, .path_challenge => |data| { // §8.2.2: "on receiving a PATH_CHALLENGE frame, an endpoint // MUST respond by echoing the data contained in the // PATH_CHALLENGE frame in a PATH_RESPONSE frame" — on the // path it arrived on, and without delay. c.paths.owe(path, data.*); }, .path_response => |data| { if (c.paths.onResponse(data.*)) |validated| { // §8.2.1's second validation, at full size this time: // the path is validated now, so nothing holds it back. // It is tracked already, so there is no room to lack. if (validated.challenge_short) if (c.id_rng) |rng| { _ = c.paths.challenge(validated.id, rng, now) catch unreachable; }; if (c.preferred_probe == validated.id) c.finishPreferredProbe(validated.id); if (c.old_path == validated.id) c.finishOldPath(); c.measureActivePath(); for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state == .open) c.measureExtraPath(extra); } } else if (c.nat) |*state| { // n0's NAT traversal: the answer to a probe, which counts // only if it came from the address the probe went to. // The server has nothing more to do; the client opens a // path over the route it came by. const seen = c.paths.find(path) orelse continue; const from = seen.peer_address orelse continue; if (state.onResponse(data.*, from) and c.role == .client) c.queueNatOpen(path); } }, // draft-ietf-quic-ack-frequency-14 §3: the frames this end said it // takes by sending min_ack_delay, and from a peer it did not tell, // a violation. .ack_frequency => |request| { const least = c.local.min_ack_delay orelse return error.ProtocolViolation; // §4: "values of 2^14 milliseconds or greater are invalid for // max_ack_delay", and so is one below this end's own // min_ack_delay -- "Receipt of an invalid value MUST be // treated as a connection error of type PROTOCOL_VIOLATION." if (request.requested_max_ack_delay >= (1 << 14) * 1000) return error.ProtocolViolation; if (request.requested_max_ack_delay < least) return error.ProtocolViolation; // "A receiving endpoint MUST ignore a received ACK_FREQUENCY // frame unless the Sequence Number value in the frame is // greater than the largest processed value." if (c.ack_frequency_sequence) |seen| if (request.sequence <= seen) continue; c.ack_frequency_sequence = request.sequence; c.ack_frequency = .{ .threshold = request.ack_eliciting_threshold, .max_delay = request.requested_max_ack_delay *| std.time.ns_per_us, .reordering = request.reordering_threshold, }; }, // §5: "An endpoint SHOULD send a packet containing an ACK frame // immediately upon receiving an IMMEDIATE_ACK frame" -- for every // path, since the frame names none. .immediate_ack => { if (c.local.min_ack_delay == null) return error.ProtocolViolation; c.spaces[2].acks.immediate = true; for (c.extra[0 .. c.path_limit - 1]) |*extra| extra.space.acks.immediate = true; }, // n0's NAT traversal. Refused unless negotiated, and each only in // the direction it goes: ADD_ADDRESS and REMOVE_ADDRESS from the // server, REACH_OUT from the client. .add_address => |a| { const state = if (c.nat) |*n| n else return error.ProtocolViolation; if (c.role != .client) return error.ProtocolViolation; _ = state.onAddAddress(a.sequence, a.address); }, .remove_address => |sequence| { const state = if (c.nat) |*n| n else return error.ProtocolViolation; if (c.role != .client) return error.ProtocolViolation; _ = state.onRemoveAddress(sequence); }, .reach_out => |r| { const state = if (c.nat) |*n| n else return error.ProtocolViolation; if (c.role != .server) return error.ProtocolViolation; // Too many addresses in one round is the one this end holds // the peer to: noq closes the connection over it. state.onReachOut(r.sequence, r.address, now) catch return error.ProtocolViolation; }, .observed_address => |o| { // draft-ietf-quic-address-discovery-01 §4.1: "A node that did // not request the receipt of address observations MUST close // the connection with a PROTOCOL_VIOLATION error if it // receives an OBSERVED_ADDRESS frame" -- nor may a peer that // never offered to provide them send one. const peer_role = if (c.peer) |p| p.address_discovery else null; if (!parameters.AddressDiscovery.reportsTo(peer_role, c.local.address_discovery)) { return error.ProtocolViolation; } const seen = c.paths.find(path) orelse continue; // "A peer SHOULD ignore an incoming OBSERVED_ADDRESS frame if // it previously received another OBSERVED_ADDRESS frame for // the same path with a Sequence Number equal to or higher" -- // frames can be reordered, and the older report is the one // that is out of date. if (seen.observed != null and o.sequence <= seen.observed_sequence) continue; seen.observed = o.address; seen.observed_sequence = o.sequence; }, .handshake_done => { // §19.20: "A server MUST treat receipt of a HANDSHAKE_DONE // frame as a connection error of type PROTOCOL_VIOLATION." // It is the server's word, and a server has no business being // told its own handshake is done. if (c.role == .server) return error.ProtocolViolation; c.confirmed = true; c.pmtu.begin(); }, // Everything else is either nothing (PADDING, PING) or something // this does not implement yet. else => {}, } } // §9.3: "receiving a packet from a new peer address containing a // non-probing frame indicates that the peer has migrated to that // address." // // draft-ietf-quic-multipath-21 §3.1.2: "the reception of any packet, // no matter if 'probing' or 'non-probing', on a new path with a new, so // far unused path ID does not impact the path status of any existing // path" -- but one on a path ID already open, from a 4-tuple that path // does not use, "MUST be treated as path migration", of that path alone. // // On a server only. §9: "Clients are responsible for initiating all // migrations. Servers do not send non-probing packets toward a client // address until they see a non-probing packet from that address." A // server's packet reaching a client somewhere it has left is a server // that has not caught up yet, and following it would undo the client's // own move. if (non_probing and c.role == .server) { if (on) |extra| { if (path != extra.route and opened.number > extra.highest_seen) try c.onPathMigration(extra, path, now); extra.highest_seen = @max(extra.highest_seen, opened.number); } else { if (c.paths.isMigration(path, opened.number)) try c.onMigration(path, now); if (c.paths.find(path)) |seen| { seen.highest_seen = @max(seen.highest_seen, opened.number); } } } // draft-ietf-quic-ack-frequency-14 governs the application level only: // the frame cannot arrive before 1-RTT, and the handshake's own spaces // are acknowledged as RFC 9000 has it. numbering.acks.arrived( opened.number, eliciting, c.inbound_ecn == .ce, now, if (level == .application) c.ack_frequency else null, ); // §13.4.1: counted here, after the packet has been decrypted and accepted // rather than when the datagram arrived, because "ECN counts are only // incremented when QUIC packets from the received IP packet are // processed" -- and because a datagram holding coalesced packets reaches // this line once for each of them, which is exactly the "incremented once // for each coalesced QUIC packet" the section asks for. numbering.acks.countEcn(c.inbound_ecn); // §4.1.3 of RFC 9001 wants handshake bytes in order and exactly once, // which is what the reassembler is for: handing frames straight to TLS // would deliver them in whatever order the network chose. // §10.1: "An endpoint restarts its idle timer when a packet from its peer // is received and processed successfully" — processed, so this is after // the frames rather than before them. c.last_activity = now; c.sent_since_receive = false; c.processed_any = true; const handshake_bytes = space.stream.readable(); if (handshake_bytes.len > 0) { c.handshake.provide(level, handshake_bytes) catch return error.HandshakeFailed; space.stream.consume(handshake_bytes.len); // The parameters before the keys, deliberately. Both become available // from the same `provide`, and if §7.3's checks fail this connection // is over — so the keys that would let it carry application data are // never installed, and an endpoint that rejected the handshake cannot // be found afterwards in a state that says it succeeded. try c.collectParameters(); c.collectKeys(); c.settleEarlyData(); } } /// §4.6.3 and §4.9.3 of RFC 9001: what becomes of the 0-RTT keys, and of what /// was sent under them. /// /// Two separate endings, and only the first is an event. A client that is /// told its early data was refused starts its streams again from nothing; a /// client whose early data was accepted simply stops having any use for the /// keys. fn settleEarlyData(c: *Connection) void { switch (c.role) { .client => { // §4.6.2: the refusal is knowable as soon as EncryptedExtensions // has been read, which is the same message that produces the // 1-RTT keys -- so the test is "we have the answer and it was // no", and `earlyDataAccepted` is false both when refused and // when never asked, which is why `sent_early` is the other half // of it. if (c.sent_early and !c.early_rejected and c.spaces[2].write != null and !c.handshake.earlyDataAccepted()) { c.early_rejected = true; // "The client therefore MUST reset the state of all // streams". First, so that the packets put back below find // no stream to resend data for, and resend only what was // never about a stream. c.resetStreams(); const space = &c.spaces[2]; // As long as the table, since `takeEarly` drops whatever does // not fit; a fixed 64 lost every 0-RTT packet past that on a // connection whose table had been made larger. for (space.loss.takeEarly(c.lost_scratch)) |sent| { // Not a congestion signal: nothing was lost on the path, // and §7 of RFC 9002 reacts to congestion rather than to // a peer changing its mind. But the packet is out of // flight all the same, since nothing will ever // acknowledge it, so it leaves the count the way a // forgotten packet does. c.congestion.onForgotten(sent); c.recover(space, sent); } } // §4.9.3: "a client SHOULD discard 0-RTT keys as soon as it // installs 1-RTT keys, as they have no use after that moment" -- // 0-RTT and 1-RTT share a packet number space and a client does // not go back to the earlier one. if (c.spaces[2].write != null) c.early_write = null; }, // §4.9.3: a server "MAY discard 0-RTT keys as soon as it receives a // 1-RTT packet", and keeping them a little longer is explicitly // allowed so that reordered 0-RTT packets can still be read. The // handshake being confirmed is the later, safer moment: by then the // client has certainly stopped sending them. .server => if (c.confirmed) { c.early_read = null; }, } } /// §4.6.2 of RFC 9001: every stream as though none had been opened, after a /// refusal of the 0-RTT data they were opened in. /// /// They are all this client's own: the refusal arrives with the first keys /// the server could have sent stream data under. And the server read none of /// them, so nothing it knows of is forgotten -- not the data, the credit it /// used, the identifiers, or that this client was blocked. fn resetStreams(c: *Connection) void { c.streams = @splat(.{}); c.next_stream_index = .{ 0, 0 }; c.send_credit.used = 0; c.data_blocked_sent = null; c.streams_blocked_at = .{ null, null }; c.streams_blocked_sent = .{ null, null }; } /// One STREAM frame. fn onStreamFrame(c: *Connection, f: frame.Stream) Error!void { const entry = try c.findOrOpen(f.stream) orelse return; // §3.1: a unidirectional stream has no receiving part at the end that // opened it, so a frame for one is a peer talking on a stream it has no // sending half of. if (!entry.id.canReceive(c.initiator())) return error.StreamStateError; const charged = entry.recv.receive(f.offset, f.data, f.fin) catch |e| switch (e) { error.FlowControlError => return error.FlowControlError, error.FinalSizeError => return error.FinalSizeError, error.StreamLimitError, error.StreamStateError => return error.StreamStateError, // §19.8: "the sum of the offset and data length... cannot exceed // 2^62-1", so a frame claiming otherwise is malformed rather than // merely unwelcome. error.OffsetTooLarge => return error.ProtocolViolation, // A peer that stayed inside its flow control limit and still overran // the buffer means this endpoint advertised more than it kept room // for, which is a bug here rather than a protocol error there. error.WindowExceeded => return error.NoRoom, }; // §4.1: connection flow control counts "the total bytes of stream data // sent in STREAM frames on all streams", and it is charged the same way // as the stream's own — by how much further this frame reached. c.recv_credit.spend(charged) catch return error.FlowControlError; } /// §19.4: the peer abandoned its sending half. fn onResetStream(c: *Connection, r: frame.ResetStream) Error!void { const entry = try c.findOrOpen(r.stream) orelse return; // §19.4: "An endpoint that receives a RESET_STREAM frame for a send-only // stream MUST terminate the connection with error STREAM_STATE_ERROR." // A peer abandoning a half it does not have is talking about a stream // that is not the one it named. if (!entry.id.canReceive(c.initiator())) return error.StreamStateError; // The error `reset` found, not always FINAL_SIZE_ERROR: a final size past // the limit this end granted is §4.1's FLOW_CONTROL_ERROR, and calling it // a disagreement about where the stream ended sent the last person to // debug it looking in the wrong place. const repeated = entry.recv.state == .reset_received; const charged = entry.recv.reset(r.error_code, r.final_size) catch |err| return switch (err) { error.FlowControlError => error.FlowControlError, else => error.FinalSizeError, }; c.recv_credit.spend(charged) catch return error.FlowControlError; // §4.5: the connection is charged the final size, and the octets the // peer abandoned are never going to be read, so nothing the application // does would release them. They count as consumed now — what is still // unread with them, which `consume` then leaves out — or every reset // shrinks the connection's window for good. if (!repeated) c.recv_consumed += r.final_size -| entry.recv.consumed; } // -- what the application does with a stream -------------------------------- /// Opens a bidirectional stream, or says why not. /// /// §4.6: the peer decides how many. Before the handshake has produced its /// transport parameters that number is zero, so a client cannot open a stream /// until it knows it may — which is what `initial_max_streams_bidi` is for and /// why a server that forgets it accepts a connection on which no request can /// be made. /// /// `error.StreamLimitError` when the peer's limit is reached, which a later /// MAX_STREAMS may lift; `error.NoRoom` when this connection's own table of /// `max_streams` is full, which closing a stream will. The table is full /// sooner than it looks: a slot the peer may still claim under this /// endpoint's `initial_max_streams_bidi` and `_uni` is kept for it, so those /// two are also what this endpoint leaves itself. pub fn openBidirectional(c: *Connection) Error!stream.Id { return c.open(.bidirectional); } test openBidirectional { const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); // Before the handshake the peer has allowed nothing. try testing.expectError(error.StreamLimitError, p.client.openBidirectional()); try p.handshake(); // §2.1: a client's bidirectional streams are 0, 4, 8, ... const first = try p.client.openBidirectional(); try testing.expectEqual(@as(u64, 0), first.value); try testing.expectEqual(@as(u64, 4), (try p.client.openBidirectional()).value); // The server allowed four. _ = try p.client.openBidirectional(); _ = try p.client.openBidirectional(); try testing.expectError(error.StreamLimitError, p.client.openBidirectional()); } /// Opens a unidirectional stream, on which this endpoint may write and the /// peer may only read. /// /// §3.1: the stream has no receiving part at this end, so `readable` on one /// of these will never have anything to say and `consume` has nothing to /// consume. The identifier space and the limit are separate from the /// bidirectional ones (§2.1, §4.6), so opening one of these costs nothing /// from the other allowance. /// /// This is what an application protocol uses for a channel that is not a /// request and a response: HTTP/3's control stream and its two QPACK streams /// are all of this shape, and they are the reason this exists. /// /// Fails as `openBidirectional` does, against `initial_max_streams_uni`. pub fn openUnidirectional(c: *Connection) Error!stream.Id { return c.open(.unidirectional); } test openUnidirectional { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); // §2.1: a client's unidirectional streams are 2, 6, 10, ... const id = try p.client.openUnidirectional(); try testing.expectEqual(@as(u64, 2), id.value); try p.client.write(id, "one way"); try p.client.finishStream(id); try p.settle(); // The server can read it and cannot write back. try testing.expectEqual(id, p.server.accept().?); try testing.expectEqualStrings("one way", p.server.readable(id)); try testing.expectError(error.StreamStateError, p.server.write(id, "no")); } fn open(c: *Connection, which: stream.Directionality) Error!stream.Id { const at = @backingInt(which); if (c.next_stream_index[at] >= c.peer_stream_limit[at]) { // §4.6: wanting a stream the limit will not allow is what a // STREAMS_BLOCKED reports. c.streams_blocked_at[at] = c.peer_stream_limit[at]; return error.StreamLimitError; } const kind: stream.Kind = switch (c.role) { .client => switch (which) { .bidirectional => .client_bidirectional, .unidirectional => .client_unidirectional, }, .server => switch (which) { .bidirectional => .server_bidirectional, .unidirectional => .server_unidirectional, }, }; const id: stream.Id = .make(kind, c.next_stream_index[at]); const role = c.initiator(); // The table is shared with the peer's streams, and those were promised: // a peer keeping to the limits this endpoint advertised has done nothing // wrong if they do not fit, and would be closed with INTERNAL_ERROR for // it. So a slot one of them may yet need is not this endpoint's to take. var free: usize = 0; for (&c.streams) |*entry| free += @intFromBool(!entry.open); if (free <= c.peerStreamsOwed()) return error.NoRoom; for (&c.streams) |*entry| { if (entry.open) continue; entry.* = .{ .id = id, .open = true, .accepted = true, .has_send = id.canSend(role), .has_recv = id.canReceive(role), }; entry.send = .init(c.sendBuffer(c.slotOf(entry)), c.peerStreamLimit(id)); entry.recv = .init( c.recvBuffer(c.slotOf(entry)), c.presentBuffer(c.slotOf(entry)), c.localStreamLimit(id), ); c.next_stream_index[at] += 1; return id; } return error.NoRoom; } /// §3.4: frees the slots of streams that have closed, and notes that the /// peer may be allowed to open more. /// /// A stream is closed when both halves are terminal, and both halves being /// terminal is a statement about the application as much as the network: the /// sending half waits for its data to be acknowledged, and the receiving half /// waits for the application to have read what arrived. So this runs wherever /// either could have changed — after an acknowledgement, and after the /// application consumes. fn reclaimStreams(c: *Connection) void { for (&c.streams) |*entry| { if (!entry.open) continue; if (!entry.sendDone() or !entry.recvDone()) continue; const id = entry.id; entry.* = .{}; if (!id.isLocal(c.initiator())) { const at = @backingInt(id.directionality()); const ahead = id.index() - c.peer_streams_retired[at]; c.peer_streams_closed_ahead[at] |= @as(u64, 1) << @intCast(ahead); while (c.peer_streams_closed_ahead[at] & 1 != 0) { c.peer_streams_closed_ahead[at] >>= 1; c.peer_streams_retired[at] += 1; } // §4.6: the limit is cumulative, so giving a slot back means // raising the ceiling rather than lowering a count. It rises by // the streams that closed, and no further than the bits above the // watermark can remember, so that every stream the peer may open // can be told apart from one already closed. const initial = switch (id.directionality()) { .bidirectional => c.local.initial_max_streams_bidi, .unidirectional => c.local.initial_max_streams_uni, }; const closed = c.peer_streams_retired[at] + @popCount(c.peer_streams_closed_ahead[at]); const grown = @min(closed + initial, c.peer_streams_retired[at] + 64); if (grown > c.advertised_stream_limit[at]) { c.advertised_stream_limit[at] = grown; c.local_stream_limit[at] = grown; c.owes_max_streams[at] = true; } } } } /// How many more streams the peer may open without passing the limits this /// endpoint has given it: every one below the limit that has neither closed /// nor got a slot already. fn peerStreamsOwed(c: *const Connection) usize { const role = c.initiator(); var owed: u64 = 0; for (0..2) |at| { const closed = c.peer_streams_retired[at] + @popCount(c.peer_streams_closed_ahead[at]); owed += c.local_stream_limit[at] -| closed; } for (&c.streams) |*entry| { if (entry.open and !entry.id.isLocal(role)) owed -|= 1; } return @intCast(@min(owed, max_streams)); } /// The identifier of the stream in slot `index`, or null if that slot is /// empty. /// /// For a caller that has to look at every stream — a server deciding which /// requests have arrived in full, say. The table is a fixed array, so this is /// the whole of iterating it, and a slot's index means nothing beyond being a /// slot. pub fn streamAt(c: *Connection, index: usize) ?stream.Id { if (index >= c.streams.len) return null; const entry = &c.streams[index]; return if (entry.open) entry.id else null; } test streamAt { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); _ = try p.client.openBidirectional(); _ = try p.client.openUnidirectional(); // Every slot, in table order, which need not be the order of opening. var in_use: usize = 0; for (0..max_streams) |i| { if (p.client.streamAt(i) != null) in_use += 1; } try testing.expectEqual(@as(usize, 2), in_use); try testing.expectEqual(@as(?stream.Id, null), p.client.streamAt(max_streams)); } /// The next stream the peer opened that the application has not been told /// about, or null when there is none. /// /// Each stream is handed out once. A stream exists from the first frame that /// names it, so by the time it is accepted something has usually arrived on /// it already. pub fn accept(c: *Connection) ?stream.Id { for (&c.streams) |*entry| { if (!entry.open or entry.accepted) continue; entry.accepted = true; return entry.id; } return null; } test accept { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expectEqual(@as(?stream.Id, null), p.server.accept()); const id = try p.client.openBidirectional(); try p.client.write(id, "request"); try p.settle(); try testing.expectEqual(id, p.server.accept().?); try testing.expectEqualStrings("request", p.server.readable(id)); // Once only. try testing.expectEqual(@as(?stream.Id, null), p.server.accept()); } /// Adds to what a stream will send. Nothing goes out until `send` is called. /// /// All or nothing: `bytes` is copied into the stream's send buffer, or /// refused with `error.NoRoom` when it does not fit, and the caller tries /// again once acknowledgements have made room (`bufferBound` says whether a /// bigger buffer would have been the answer instead). `error.StreamStateError` /// is a stream this connection does not have, one it has no sending half on /// (§3.1), or one already finished or reset. pub fn write(c: *Connection, id: stream.Id, bytes: []const u8) Error!void { const entry = c.find(id.value) orelse return error.StreamStateError; // §3.1: a unidirectional stream has a sending part only at the end that // opened it, so writing to one the peer opened is not a thing that can be // done rather than a thing that is refused. if (!entry.has_send) return error.StreamStateError; entry.send.write(bytes) catch |e| switch (e) { error.BufferFull => { c.noteNoRoom(entry); return error.NoRoom; }, else => return error.StreamStateError, }; } test write { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "GET /"); try p.client.write(id, " HTTP/0.9"); // Buffered, not sent: the server has nothing until datagrams move. try testing.expect(p.client.hasDataToSend()); try p.settle(); try testing.expectEqualStrings("GET / HTTP/0.9", p.server.readable(id)); // A write that does not fit is refused whole. const too_much: [stream_buffer + 1]u8 = @splat('x'); try testing.expectError(error.NoRoom, p.client.write(id, &too_much)); // And a stream that has been finished takes no more. try p.client.finishStream(id); try testing.expectError(error.StreamStateError, p.client.write(id, "more")); } /// Counts a refusal that a larger send buffer would have avoided. /// /// A send buffer fills for any number of reasons and a full one says /// nothing on its own: a slow path fills it exactly as a small one does, /// and so does a peer that has granted little flow control. What /// distinguishes a buffer that is too *small* is that everything in it has /// already gone -- there is nothing left to send, so the sender is idle -- /// while the congestion window and both flow control limits would all still /// have taken more. In that state, and only in that state, the buffer is the /// one thing standing between this stream and a faster one. /// /// It is deliberately a count of refusals rather than a measurement of the /// window that would have sufficed, because the second is not knowable from /// here: how much more would have helped depends on the path, and the only /// honest answer this side of trying is "more than it has". A caller that /// owns the buffers -- `quic_io.Endpoint` does -- can watch this and decide; /// see `bufferBound`. fn noteNoRoom(c: *Connection, entry: anytype) void { if (entry.send.data.pending()) return; if (c.congestion.available() == 0) return; if (entry.send.credit.available() == 0) return; if (c.send_credit.available() == 0) return; c.buffer_bound +|= 1; } /// How many times a write was refused for room that nothing but a larger /// send buffer would have provided. /// /// Zero on a connection bounded by its path or by what its peer has granted, /// which is most of them, and that is the point: it rises only where more /// buffer would have bought more throughput. Saturating, so a long-lived /// connection cannot wrap it into a small number and look idle. pub fn bufferBound(c: *const Connection) u64 { return c.buffer_bound; } test bufferBound { // The peer grants 2048 octets a stream and this end buffers 1024, so a // full buffer whose contents have all been sent is a buffer that is too // small rather than a peer or a path that is too slow. const Small = TestPairSized(.{ .send_window = 1024, .recv_window = 2048 }); const p = try Small.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); const full: [1024]u8 = @splat('a'); try p.client.write(id, &full); var buffer: [2048]u8 = undefined; // Sent, and not yet acknowledged: the octets are gone and still held. while (try p.client.send(&buffer, p.now)) |_| {} try testing.expectEqual(@as(u64, 0), p.client.bufferBound()); try testing.expectError(error.NoRoom, p.client.write(id, "b")); try testing.expectEqual(@as(u64, 1), p.client.bufferBound()); } /// Says that a stream has nothing more to send, which puts a FIN on the frame /// carrying its last octet. /// /// The final size is settled here (§4.5), so `write` refuses anything after /// it. `error.StreamStateError` for a stream this connection does not have, /// has no sending half on, or has already finished or reset. pub fn finishStream(c: *Connection, id: stream.Id) Error!void { const entry = c.find(id.value) orelse return error.StreamStateError; if (!entry.has_send) return error.StreamStateError; entry.send.finish() catch return error.StreamStateError; } test finishStream { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "the whole query"); try p.client.finishStream(id); try p.settle(); // The server knows nothing more is coming. try testing.expect(p.server.streamReceived(id)); try testing.expectError(error.StreamStateError, p.client.finishStream(id)); } /// §3.5: asks the peer to stop sending on a stream, because what it is /// sending is no longer wanted. /// /// A request and not a state change: data already in flight still arrives, /// and §3.5 expects the peer to answer with a RESET_STREAM. Both halves of /// that exchange are here, which matters more than it sounds — an endpoint /// that could send this but not answer it, or answer it but not send it, /// leaves the other end waiting on a conversation it cannot finish. /// /// The frame goes out with the next `send`, and the peer's code comes back /// through `streamResetCode`. `error.StreamStateError` for a stream this /// connection does not have or has no receiving half on. pub fn stopSending(c: *Connection, id: stream.Id, code: u64) Error!void { const entry = c.find(id.value) orelse return error.StreamStateError; // §19.5: "A STOP_SENDING frame can be sent for streams in the 'Recv' or // 'Size Known' states", which are the states a receiving half has. // Sending one for a stream this endpoint does not receive on is the // error it would be at the far end (§19.5 again), read from this side. if (!entry.has_recv) return error.StreamStateError; entry.recv.stopSending(code); } test stopSending { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "an upload nobody wants"); try p.settle(); // The server has read enough. The client sees the STOP_SENDING and // resets its half with the server's code (§3.5), which comes back to the // server in the RESET_STREAM. try p.server.stopSending(id, 0x10c); try p.settle(); try testing.expectEqual(@as(?u64, 0x10c), p.server.streamResetCode(id)); try testing.expectError(error.StreamStateError, p.client.write(id, "more")); } /// RFC 9221 §4: queues an unreliable datagram. /// /// The peer's `max_datagram_frame_size` decides whether this is possible at /// all and how large it may be, and §3 measures that limit against the whole /// frame rather than its payload -- so the type octet and the length field /// come out of the same allowance the data does. /// /// Queued rather than sent: the frame goes out in the next packet that has /// room for it, under the congestion controller like everything else. §5.2: /// "DATAGRAM frames... are subject to congestion control" -- what they are /// not subject to is retransmission, which is a different question. /// /// `bytes` is copied. `error.StreamStateError` when the peer did not ask for /// datagrams, or has not said yet (see `datagramsAllowed`); `error.NoRoom` /// when the frame is larger than the peer takes or than a packet on the /// path holds, or when `max_datagrams` are already queued. pub fn sendDatagram(c: *Connection, bytes: []const u8) Error!void { const peer = c.peer orelse return error.StreamStateError; // §3: "An endpoint that receives the parameter with a value of 0, or that // does not receive it at all, MUST NOT send DATAGRAM frames." if (peer.max_datagram_frame_size == 0) return error.StreamStateError; if (datagramFrameLen(bytes.len) > peer.max_datagram_frame_size) return error.NoRoom; // §3 is careful to say that the parameter "is not a guarantee that the // path can carry" such a frame, and the two numbers answer different // questions: the peer's limit is what it is willing to receive, and this // is what will fit in a packet on the path as it is currently known. // // Refused here rather than queued, because a datagram that cannot be // written is not merely delayed -- there is no offset to split it at // (§5.1: "a receiver is not required to reassemble") and nothing that // will ever make it smaller, so queuing one would be queuing it forever. // An application told no can send something smaller; an application told // nothing cannot. if (datagramFrameLen(bytes.len) > c.datagramRoom()) return error.NoRoom; if (!c.outbound.push(bytes)) return error.NoRoom; } test sendDatagram { const p = try TestPair.connect(test_datagram_limits, test_datagram_limits); defer p.destroy(); try p.client.sendDatagram("ping"); try p.settle(); try testing.expectEqualStrings("ping", p.server.readDatagram().?); // Larger than a packet will hold, so not merely late but impossible. const huge: [max_datagram_len]u8 = @splat(0); try testing.expectError(error.NoRoom, p.client.sendDatagram(&huge)); } /// The largest DATAGRAM frame that will fit in a packet on the current path. /// /// A 1-RTT packet's overhead: the first octet, the peer's connection ID, a /// four-octet packet number and the AEAD tag. Anything else in the packet /// makes this an overestimate, which costs a datagram a round trip rather /// than its life -- it stays queued and goes in the next packet that has room. fn datagramRoom(c: *const Connection) u64 { const overhead = 1 + c.peer_id_len + 4 + tls.tag_len; const room = c.smallestDatagram(); return if (room > overhead) room - overhead else 0; } /// The oldest unreliable datagram that has arrived and not been taken, or /// null. /// /// **Borrowed until the next `takeDatagram`.** Asking again without taking /// returns the same one. pub fn readDatagram(c: *const Connection) ?[]const u8 { return c.inbound.peek(); } test readDatagram { const p = try TestPair.connect(test_datagram_limits, test_datagram_limits); defer p.destroy(); try testing.expectEqual(@as(?[]const u8, null), p.server.readDatagram()); try p.client.sendDatagram("first"); try p.client.sendDatagram("second"); try p.settle(); // Oldest first, each read and then taken. var seen: usize = 0; while (p.server.readDatagram()) |datagram| : (p.server.takeDatagram()) { try testing.expectEqualStrings(if (seen == 0) "first" else "second", datagram); seen += 1; } try testing.expectEqual(@as(usize, 2), seen); } /// Discards what `readDatagram` returned, making room for another. Does /// nothing when nothing is queued. /// /// The queue holds `max_datagrams`, and §5.3 of RFC 9221 lets a receiver /// drop what it cannot hold, so a caller that does not take datagrams loses /// the ones that arrive after the queue fills. pub fn takeDatagram(c: *Connection) void { c.inbound.pop(); } test takeDatagram { const p = try TestPair.connect(test_datagram_limits, test_datagram_limits); defer p.destroy(); try p.client.sendDatagram("stale"); try p.client.sendDatagram("fresh"); try p.settle(); p.server.takeDatagram(); try testing.expectEqualStrings("fresh", p.server.readDatagram().?); } /// Whether this connection may send unreliable datagrams at all, which is a /// question about what the peer advertised (RFC 9221 §3). /// /// False until the peer's transport parameters have arrived, which for a /// client is partway through the handshake. pub fn datagramsAllowed(c: *const Connection) bool { const peer = c.peer orelse return false; return peer.max_datagram_frame_size > 0; } test datagramsAllowed { const p = try TestPair.connect(test_datagram_limits, test_limits); defer p.destroy(); // The client asked for datagrams and the server did not, so only the // server may send them. try testing.expect(p.server.datagramsAllowed()); try testing.expect(!p.client.datagramsAllowed()); try testing.expectError(error.StreamStateError, p.client.sendDatagram("no")); } /// RFC 9221 §3: the size of the whole DATAGRAM frame carrying `payload_len` /// octets, which is the number the transport parameter bounds. /// /// The type is one octet and the length is a varint of the payload's size. /// Written out rather than approximated because §3's limit is exact, and an /// endpoint that measured only the payload would send a frame one or two /// octets over a limit the peer will close the connection for. fn datagramFrameLen(payload_len: usize) u64 { return 1 + varint.encodedLen(payload_len) + payload_len; } /// Whether a stream is still in this connection's table. /// /// A stream leaves the table when both its halves are done (§3.4): what it /// sent acknowledged or reset, and what it received read or reset. A stream /// that has left is indistinguishable here from one that never existed; /// `streamFinished` is the question that tells them apart. pub fn streamOpen(c: *Connection, id: stream.Id) bool { return c.find(id.value) != null; } test streamOpen { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try testing.expect(p.client.streamOpen(id)); // A request and its answer, both ends finished and everything read. try p.client.write(id, "q"); try p.client.finishStream(id); try p.settle(); try p.server.write(id, "a"); try p.server.finishStream(id); p.server.consume(id, p.server.readable(id).len); try p.settle(); p.client.consume(id, p.client.readable(id).len); try p.settle(); // Gone from both tables, and its slot free for another. try testing.expect(!p.client.streamOpen(id)); try testing.expect(!p.server.streamOpen(id)); } /// §3.5: abandons a stream's sending half. /// /// A RESET_STREAM carrying `code` goes out with the next `send`, in place of /// whatever was still waiting to be sent or sent again; the peer reads the /// code with `streamResetCode`. Resetting a half that is already reset, or /// whose data has all been acknowledged, changes nothing. /// `error.StreamStateError` for a stream this connection does not have or /// has no sending half on. pub fn resetStream(c: *Connection, id: stream.Id, code: u64) Error!void { const entry = c.find(id.value) orelse return error.StreamStateError; if (!entry.has_send) return error.StreamStateError; entry.send.reset(code); } test resetStream { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "an upload, abandoned"); try p.client.resetStream(id, 0x2a); try p.settle(); try testing.expectEqual(@as(?u64, 0x2a), p.server.streamResetCode(id)); // Reset is an end, as far as receiving goes. try testing.expect(p.server.streamReceived(id)); } /// What has arrived on a stream, in order, from where the application last /// stopped. /// /// **Borrowed until the next `consume` on this stream.** Consuming slides the /// reassembly window down, so a slice taken before it points at octets that /// have moved — read what was returned, and only then say how much of it was /// taken. pub fn readable(c: *Connection, id: stream.Id) []const u8 { const entry = c.find(id.value) orelse return &.{}; // §3.1 again, from the other side: a stream this endpoint opened // unidirectionally has no receiving part, and nothing will ever arrive on // it. Empty rather than an error, because "nothing has arrived" is the // honest answer and the caller's loop is the same either way. if (!entry.has_recv) return &.{}; return entry.recv.readable(); } test readable { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "hello, world"); try p.settle(); // Copy out what is wanted before consuming it. var word: [5]u8 = undefined; @memcpy(&word, p.server.readable(id)[0..5]); p.server.consume(id, 5); try testing.expectEqualStrings("hello", &word); try testing.expectEqualStrings(", world", p.server.readable(id)); // A stream that is not there has nothing to read, rather than an error. try testing.expectEqual(@as(usize, 0), p.server.readable(.{ .value = 400 }).len); } /// Takes `n` octets of what `readable` returned, which is also what releases /// the flow control credit they occupied. /// /// `n` must not exceed what `readable` returned. The credit goes back to /// the peer in MAX_DATA and MAX_STREAM_DATA frames with a later `send`, and /// reading the last octet of a finished stream may close it (§3.2's "Data /// Read") and free its slot. A stream this connection does not have, or has /// no receiving half on, is ignored. pub fn consume(c: *Connection, id: stream.Id, n: usize) void { const entry = c.find(id.value) orelse return; if (!entry.has_recv) return; // A reset already counted everything up to the final size. if (entry.recv.state != .reset_received) c.recv_consumed += n; entry.recv.consume(n); // §3.2's terminal state is "Data Read", so reading is what can close a // stream from this side. c.reclaimStreams(); } test consume { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); // The server grants 2048 octets a stream; fill it. const block: [2048]u8 = @splat('z'); try p.client.write(id, &block); try p.settle(); try testing.expectEqual(@as(usize, 2048), p.server.readable(id).len); // The client cannot send more until the server reads and says so. try p.client.write(id, "more"); try p.settle(); try testing.expectEqual(@as(usize, 2048), p.server.readable(id).len); p.server.consume(id, 2048); try p.settle(); try testing.expectEqualStrings("more", p.server.readable(id)); } test "RFC 9000 4.5: a reset stream gives its connection credit back" { // §4.5: "the receiver MUST use the final size of the stream to account // for all bytes sent on the stream in its connection-level flow // controller". The octets a reset abandoned will never be read, so // nothing the application does releases them; unless closing the stream // does, every reset shrinks the connection window for good. var limits = test_limits; limits.initial_max_data = 1000; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const block: [900]u8 = @splat('r'); const abandoned = try p.client.openUnidirectional(); try p.client.write(abandoned, &block); try p.settle(); try p.client.resetStream(abandoned, 0x2a); try p.settle(); // Counted once, however many copies of the RESET_STREAM arrive. try testing.expectEqual(@as(u64, 900), p.server.recv_consumed); const next = try p.client.openUnidirectional(); try p.client.write(next, &block); try p.settle(); try testing.expectEqual(@as(usize, 900), p.server.readable(next).len); } test "RFC 9000 4.6: a stream that closes early does not retire the ones below it" { // Streams close in whatever order their exchanges finish. The client // opens two, finishes the second first, and only then sends on the // first, which must still be delivered rather than taken for a stream // that was closed and forgotten. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const first = try p.client.openBidirectional(); const second = try p.client.openBidirectional(); try p.client.write(second, "second"); try p.client.finishStream(second); try p.settle(); try testing.expectEqualStrings("second", p.server.readable(second)); p.server.consume(second, 6); try p.server.finishStream(second); try p.settle(); try testing.expect(p.server.find(second.value) == null); // §4.6: one stream closed, so one more may be opened -- not two, which // is what counting from the highest closed identifier would grant. try testing.expectEqual(test_limits.initial_max_streams_bidi + 1, p.server.advertised_stream_limit[0]); try p.client.write(first, "first"); try p.client.finishStream(first); try p.settle(); try testing.expectEqualStrings("first", p.server.readable(first)); } /// Whether a stream existed and has since been closed and forgotten. /// /// The awkward consequence of reclaiming slots eagerly, and the reason the /// questions below answer from it: a stream that is gone is a stream that /// completed, and an application that asks about one after reading its last /// octet should be told so rather than told nothing. An identifier that was /// never used is a different matter, and answers false. fn streamRetired(c: *const Connection, id: stream.Id) bool { const at = @backingInt(id.directionality()); if (id.isLocal(c.initiator())) return id.index() < c.next_stream_index[at]; return c.peerStreamClosed(id); } /// Whether a peer-initiated stream has been closed and forgotten, either /// below the watermark or one of those that closed ahead of it. fn peerStreamClosed(c: *const Connection, id: stream.Id) bool { const at = @backingInt(id.directionality()); const retired = c.peer_streams_retired[at]; if (id.index() < retired) return true; const ahead = id.index() - retired; return ahead < 64 and c.peer_streams_closed_ahead[at] >> @intCast(ahead) & 1 != 0; } /// Whether everything the peer is going to send on a stream has arrived. /// /// Distinct from `streamFinished`, which is about the application: this says /// the octets are here, that one says they have been read. A caller waiting /// for a reply wants this one — it is the moment there is nothing left to /// wait for. pub fn streamReceived(c: *Connection, id: stream.Id) bool { const entry = c.find(id.value) orelse return c.streamRetired(id); return switch (entry.recv.state) { .data_received, .reset_received => true, .receiving, .size_known => false, }; } test streamReceived { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "partial"); try p.settle(); try testing.expect(!p.server.streamReceived(id)); try p.client.finishStream(id); try p.settle(); // All here, though not yet read. try testing.expect(p.server.streamReceived(id)); try testing.expect(!p.server.streamFinished(id)); } /// Whether the peer has ended a stream and everything it sent has been read. /// /// True as well for a stream that has closed and left the table, which got /// there by being finished; false for one that was reset before all of it /// was read, and for one that never existed. pub fn streamFinished(c: *Connection, id: stream.Id) bool { const entry = c.find(id.value) orelse return c.streamRetired(id); return entry.recv.finished(); } test streamFinished { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openUnidirectional(); try p.client.write(id, "done"); try p.client.finishStream(id); try p.settle(); try testing.expect(!p.server.streamFinished(id)); // Reading the last octet finishes it -- and, the stream having no other // half, closes it, which still answers true. p.server.consume(id, p.server.readable(id).len); try testing.expect(!p.server.streamOpen(id)); try testing.expect(p.server.streamFinished(id)); } /// The peer's RESET_STREAM error code, if it sent one. /// /// Null when it did not, and also once the stream has closed and left the /// table (see `streamOpen`), so a caller that cares about the code reads it /// before it reads the stream to its end. pub fn streamResetCode(c: *Connection, id: stream.Id) ?u64 { const entry = c.find(id.value) orelse return null; return entry.recv.reset_code; } test streamResetCode { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "x"); try p.settle(); try testing.expectEqual(@as(?u64, null), p.server.streamResetCode(id)); try p.client.resetStream(id, 7); try p.settle(); try testing.expectEqual(@as(?u64, 7), p.server.streamResetCode(id)); } /// §4.9: throws away a space's keys, and everything that depended on them. /// /// "This results in abandoning loss recovery state for the Initial encryption /// level and ignoring any outstanding Initial packets." Outstanding packets /// are not merely forgotten: §B.9 of RFC 9002 has them leave the congestion /// controller's bytes in flight as well, because a packet whose keys are gone /// will never be acknowledged and leaving it counted would shrink the usable /// window for the rest of the connection. fn discardKeys(c: *Connection, space: Space) void { const index = @backingInt(space); if (c.discarded[index]) return; c.discarded[index] = true; const state = &c.spaces[index]; c.congestion.onDiscarded(state.loss.unacked()); state.loss.reset(); state.read = null; state.write = null; state.acks = .{}; } /// §4.9.1: "a server MUST discard Initial keys when it first successfully /// processes a Handshake packet." /// /// The rule is about Initial packets being unauthenticated: their keys come /// from a connection ID in the clear, so anyone who saw the first datagram /// can write one. The successful use of Handshake packets proves there is /// nothing left that needs them, and every moment they are kept is a moment /// a spoofed Initial can still disrupt the connection. fn maybeDiscardInitial(c: *Connection, level: tls.Level) void { if (level != .handshake) return; c.discardKeys(.initial); } /// §4.9.2: "An endpoint MUST discard its Handshake keys when the TLS /// handshake is confirmed." fn maybeDiscardHandshake(c: *Connection) void { if (!c.confirmed) return; if (!c.spaces[2].hasKeys()) return; // On confirmation, and not when the space happens to be quiet. §4.9.1 // describes what this costs and accepts it: "this results in abandoning // loss recovery state for the [handshake] encryption level and ignoring // any outstanding [handshake] packets". A server that discards here will // never acknowledge the client's Finished, and the client abandons that // packet when it confirms in turn — both ends stop caring about the space // at the same moment, which is why neither is left waiting. c.discardKeys(.handshake); } /// §4.1.2: a server's handshake is confirmed when it completes, and it then /// owes its peer the frame that says so. fn maybeConfirm(c: *Connection) void { if (c.confirmed) return; if (c.role != .server) return; if (!c.handshake.isComplete()) return; c.confirmed = true; // §4.9.3: with the handshake confirmed the client has certainly stopped // sending 0-RTT, so the key that read it has nothing left to read. c.settleEarlyData(); // §14.3.1: "a QUIC sender can therefore enter the DPLPMTUD BASE state // when the QUIC connection handshake has been completed." c.pmtu.begin(); // §19.20: "The HANDSHAKE_DONE frame is used by the server to signal // confirmation of the handshake to the client." Without it a client // cannot confirm, cannot discard its handshake keys, and cannot start a // key update — all of which wait on a frame that costs one octet. c.owes_handshake_done = true; } /// Reads the peer's transport parameters, once TLS has them, and checks what /// §7.3 says to check. /// /// §7.4 puts the connection IDs of the handshake inside the encrypted /// handshake itself, and §7.3 says why: "Including connection ID values in /// transport parameters and verifying them ensures that an attacker cannot /// influence the choice of connection ID for a successful connection by /// injecting packets carrying attacker-chosen connection IDs during the /// handshake." An Initial packet is readable and writable by anyone who saw /// the client's first datagram, so the headers of the handshake are not /// trustworthy on their own; this is where they become so. fn collectParameters(c: *Connection) Error!void { if (c.peer_confirmed) return; const raw = c.handshake.peerTransportParameters() orelse return; const from: parameters.Side = switch (c.role) { .client => .server, .server => .client, }; const p = parameters.parse(raw, &c.peer_id_storage, from) catch return error.TransportParameterError; // §7.3: "An endpoint MUST treat the absence of the // initial_source_connection_id transport parameter from either endpoint // or the absence of the original_destination_connection_id transport // parameter from the server as a connection error." const source = p.initial_source_connection_id orelse return error.TransportParameterError; if (!std.mem.eql(u8, source, c.peerId())) return error.TransportParameterError; if (c.role == .client) { const original = p.original_destination_connection_id orelse return error.TransportParameterError; if (!std.mem.eql(u8, original, c.original_destination_buf[0..c.original_destination_len])) { return error.TransportParameterError; } // §7.3 has two halves here, and both are errors: "absence of the // retry_source_connection_id transport parameter from the server // after receiving a Retry packet" and "presence of the // retry_source_connection_id transport parameter when no Retry packet // was received". A mismatch is the third — and together they are what // stops an on-path attacker steering a connection onto a connection // ID of its own by injecting a Retry. if (c.retry_source_len) |len| { const named = p.retry_source_connection_id orelse return error.TransportParameterError; if (!std.mem.eql(u8, named, c.retry_source_buf[0..len])) { return error.TransportParameterError; } } else if (p.retry_source_connection_id != null) { return error.TransportParameterError; } } // §7.4.1: "A server MUST NOT reduce any limits or alter any values that // might be violated by the client with its 0-RTT packets" -- and it is // the client that has to check, because it is the client that has // already acted. A server that lowers a limit the client has already // spent against has made the client's own behaviour retroactively // illegal, which "MUST be treated as a connection error of type // PROTOCOL_VIOLATION". // // Only for 0-RTT the server accepted. One it refused was never read, so // nothing the client did under the remembered limits stands, and the // server's new ones replace them rather than being raised to meet them. // Both answers come in EncryptedExtensions, with these parameters. const replaces_remembered = c.remembered != null and !c.handshake.earlyDataAccepted(); if (c.remembered) |was| { if (!replaces_remembered and c.sent_early and reducesLimits(was, p)) return error.ProtocolViolation; } // draft-ietf-quic-multipath-21 §2.1: "When advertising the // initial_max_path_id transport parameter, endpoints MUST use Source and // Destination Connection IDs with non-zero lengths. If an // initial_max_path_id transport parameter is received and the carrying // packet contains a zero-length connection ID, the receiver MUST treat // this as a connection error of type PROTOCOL_VIOLATION." Every path // needs identifiers of its own, and a connection addressed by nothing // has none to give. if (p.initial_max_path_id != null and (c.peer_id_len == 0 or c.local_id_len == 0)) { return error.ProtocolViolation; } // RFC 9368 §4, with the one version this library speaks. A server // "MUST validate that the client's Chosen Version matches the version in // use for the connection"; a client "MUST close the connection" if the // server's Chosen Version "was not sent by the client as part of its // Available Versions", and "MUST validate that the server's Chosen // Version is equal to the Negotiated Version". All three come to the // same comparison here. What they guard against is a forged Version // Negotiation packet, and a client that never acts on one has nothing // more to check -- so a missing parameter is accepted, which §4 allows // a server always and a client that did not react to one. if (p.version_information) |v| { if (v.chosen != packet.version_1) return error.VersionNegotiationError; if (c.role == .client) { const offered = c.local.version_information orelse parameters.VersionInformation.v1; if (!offered.offers(v.chosen)) return error.VersionNegotiationError; } } c.peer = p; c.peer_confirmed = true; // n0's NAT traversal: on only when both ends sent the parameter and // multipath is negotiated, and otherwise silently off -- noq's rule. if (c.local.n0_nat_traversal) |mine| { if (p.n0_nat_traversal) |theirs| { if (c.multipathNegotiated()) c.nat = .init(switch (c.role) { .client => .client, .server => .server, }, mine, theirs); } } // §5.1.1: "the sequence number of the connection ID in the // preferred_address transport parameter is 1." Fixed by the // specification rather than carried in the parameter, and registering it // here is what makes the identifier usable at all -- a client that moved // to the preferred address without it would be addressing the server by // a name it never entered in its own table, and would not recognise the // stateless reset token that goes with it either. if (p.preferred_address) |a| { c.received.offer( parameters.preferred_address_sequence, 0, a.connection_id, a.stateless_reset_token, c.local.active_connection_id_limit, ) catch return error.TransportParameterError; } // §4.1: "A receiver sets initial limits for all streams through transport // parameters during the handshake", which is what those parameters are // before any MAX_DATA or MAX_STREAM_DATA moves them. if (replaces_remembered) { c.send_credit.limit = p.initial_max_data; c.peer_stream_limit = .{ p.initial_max_streams_bidi, p.initial_max_streams_uni }; } c.send_credit.grant(p.initial_max_data); c.peer_stream_limit[0] = @max(c.peer_stream_limit[0], p.initial_max_streams_bidi); c.peer_stream_limit[1] = @max(c.peer_stream_limit[1], p.initial_max_streams_uni); for (&c.streams) |*entry| { if (!entry.open) continue; if (replaces_remembered) entry.send.credit.limit = c.peerStreamLimit(entry.id); entry.send.grant(c.peerStreamLimit(entry.id)); } } /// §7.4.1: the remembered parameters a client may act on before the /// server's new ones arrive. "A client MUST NOT use remembered values for /// the following parameters: ack_delay_exponent, max_ack_delay, /// initial_source_connection_id, original_destination_connection_id, /// preferred_address, retry_source_connection_id, and /// stateless_reset_token" -- each describes the connection that named it, /// and a reset token in particular would be one this connection's server /// never issued. Until the handshake says otherwise they are the defaults. fn rememberable(was: parameters.Parameters) parameters.Parameters { const defaults: parameters.Parameters = .{}; var p = was; p.ack_delay_exponent = defaults.ack_delay_exponent; p.max_ack_delay = defaults.max_ack_delay; p.initial_source_connection_id = null; p.original_destination_connection_id = null; p.preferred_address = null; p.retry_source_connection_id = null; p.stateless_reset_token = null; return p; } /// §7.4.1: whether the server has gone back on something a 0-RTT sender may /// already have relied on. /// /// Only the limits are compared. The parameters left out are not laxity but /// the point: a connection ID, a stateless reset token or an idle timeout /// describes the connection that named it, so "the same as last time" is not /// a meaningful thing to ask of them. fn reducesLimits(was: parameters.Parameters, now: parameters.Parameters) bool { return now.initial_max_data < was.initial_max_data or now.initial_max_stream_data_bidi_local < was.initial_max_stream_data_bidi_local or now.initial_max_stream_data_bidi_remote < was.initial_max_stream_data_bidi_remote or now.initial_max_stream_data_uni < was.initial_max_stream_data_uni or now.initial_max_streams_bidi < was.initial_max_streams_bidi or now.initial_max_streams_uni < was.initial_max_streams_uni or now.active_connection_id_limit < was.active_connection_id_limit; } /// §18.2's per-stream limit for one stream, from the peer's point of view. /// /// The four parameters describe two endpoints' views of the same two streams, /// and the pairing is the part that is easy to get backwards: what the peer /// grants *this* endpoint on a stream this endpoint opened is the peer's /// `bidi_remote`, because from the peer's side the stream is remotely /// initiated. Getting it the other way round gives a connection where each /// end grants the credit the other was not waiting for, which nothing notices /// until something fills a window. fn peerStreamLimit(c: *const Connection, id: stream.Id) u64 { const p = c.peer orelse return 0; const role: stream.Initiator = switch (c.role) { .client => .client, .server => .server, }; if (id.directionality() == .unidirectional) return p.initial_max_stream_data_uni; return if (id.isLocal(role)) p.initial_max_stream_data_bidi_remote else p.initial_max_stream_data_bidi_local; } /// The limit this endpoint grants the peer on one stream, which is the same /// table read from the other side. fn localStreamLimit(c: *const Connection, id: stream.Id) u64 { const role: stream.Initiator = switch (c.role) { .client => .client, .server => .server, }; if (id.directionality() == .unidirectional) return c.local.initial_max_stream_data_uni; return if (id.isLocal(role)) c.local.initial_max_stream_data_bidi_local else c.local.initial_max_stream_data_bidi_remote; } fn initiator(c: *const Connection) stream.Initiator { return switch (c.role) { .client => .client, .server => .server, }; } fn find(c: *Connection, id: u64) ?*StreamEntry { for (&c.streams) |*entry| { if (entry.open and entry.id.value == id) return entry; } return null; } /// Finds a stream, opening it if the peer is entitled to have opened it. /// /// §2.1: "A stream ID that is used out of order results in all streams of /// that type with lower-numbered stream IDs also being opened." This does not /// do that — it opens the one named — which is a simplification worth /// stating: a peer that skips ahead gets the stream it asked for and the ones /// it skipped are never created, so a later frame naming one of them opens it /// then. What that costs is the ordering guarantee between streams, which /// nothing here relies on; what it saves is opening a run of streams because /// a peer named a large identifier. fn findOrOpen(c: *Connection, raw: u64) Error!?*StreamEntry { if (c.find(raw)) |entry| return entry; if (raw > stream.Id.max) return error.ProtocolViolation; const id: stream.Id = .{ .value = raw }; const role = c.initiator(); // A stream that existed and was closed and forgotten. §4.5 permits // exactly this and says why: remembering the final size of every stream // that ever existed "could mean a significant state commitment". So the // frame is ignored — which is not the same as accepted, and not the same // as an error. const at = @backingInt(id.directionality()); if (!id.isLocal(role) and c.peerStreamClosed(id)) return null; if (id.isLocal(role)) { // §19.8: "An endpoint MUST terminate the connection with error // STREAM_STATE_ERROR if it receives a STREAM frame for a locally // initiated stream that has not yet been created". A peer naming a // stream this endpoint has not opened is talking about something that // does not exist. if (id.index() >= c.next_stream_index[at]) return error.StreamStateError; // It existed and was closed and forgotten — the same §4.5 allowance, // for a stream this endpoint opened. return null; } // §4.6: "An endpoint that receives a frame with a stream ID exceeding the // limit it has sent MUST treat this as a connection error of type // STREAM_LIMIT_ERROR." if (id.index() >= c.local_stream_limit[at]) return error.StreamLimitError; for (&c.streams) |*entry| { if (entry.open) continue; entry.* = .{ .id = id, .open = true, .has_send = id.canSend(role), .has_recv = id.canReceive(role), }; entry.send = .init(c.sendBuffer(c.slotOf(entry)), c.peerStreamLimit(id)); entry.recv = .init( c.recvBuffer(c.slotOf(entry)), c.presentBuffer(c.slotOf(entry)), c.localStreamLimit(id), ); return entry; } // The peer stayed inside the limit it was given and the table is still // full, which means this endpoint advertised more streams than it kept // room for. That is a bug here rather than a protocol error there. return error.NoRoom; } fn slotOf(c: *Connection, entry: *const StreamEntry) usize { return (@intFromPtr(entry) - @intFromPtr(&c.streams)) / @sizeOf(StreamEntry); } /// §19.3's `ack_delay_exponent`, from the peer if it said and 3 if it did not. fn ackDelayExponent(c: *const Connection) u6 { const p = c.peer orelse return ack_delay_exponent; return @intCast(p.ack_delay_exponent); } /// The largest datagram this connection will send. /// /// Two limits, and the smaller wins. §18.2's `max_udp_payload_size` is what /// the peer said it is "willing to receive" — "UDP datagrams with payloads /// larger than this limit are not likely to be processed by the receiver", /// which is the politest possible way of saying they are dropped. /// /// The other is the path, and it is the one that binds here. §14: "endpoints /// SHOULD NOT send UDP datagrams that exceed the maximum size of the path... /// unless they have received acknowledgment... that the path supports that /// size". 1200 octets is the size §14.1 guarantees every QUIC path supports, /// and finding out whether a path supports more is §14.3's path MTU /// discovery, which `mtu.Search` does: this is 1200 until a probe of a larger /// size has been acknowledged on path 0, and that size after. fn maxDatagram(c: *const Connection) usize { return c.maxDatagramFor(&c.pmtu); } /// The same for the path whose search is `search`. fn maxDatagramFor(c: *const Connection, search: *const mtu.Search) usize { const advertised: u64 = if (c.peer) |p| p.max_udp_payload_size else min_initial_datagram; // §14.3's search is what lifts this above the guaranteed minimum, and the // peer's own limit is what caps it: a datagram larger than either is one // that does not arrive. const learned = @max(search.current, @as(usize, min_initial_datagram)); return @intCast(@min(advertised, @as(u64, learned))); } /// The smallest datagram any open path carries: what fits wherever a frame /// that can go on any path ends up going. fn smallestDatagram(c: *const Connection) usize { var smallest = c.maxDatagram(); for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open) continue; smallest = @min(smallest, c.maxDatagramFor(&extra.pmtu)); } return smallest; } /// The space whose CRYPTO stream a packet numbered in `space` carried from: /// `space` itself for the three levels, and the application level's for a /// path past path 0, which numbers packets and has no stream of its own. fn cryptoHome(c: *Connection, space: *SpaceState) *SpaceState { for (&c.spaces) |*level| { if (level == space) return space; } return &c.spaces[2]; } /// The PMTU search that probes numbered in `space` belong to, if any. fn pmtuOf(c: *Connection, space: *SpaceState) ?*mtu.Search { if (space == &c.spaces[2]) return &c.pmtu; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (space == &extra.space) return &extra.pmtu; } return null; } /// §13.2.1's `max_ack_delay`, in nanoseconds. fn maxAckDelay(c: *const Connection) recovery.Duration { const p = c.peer orelse return default_max_ack_delay; // draft-ietf-quic-ack-frequency-14 §7: once the peer has acknowledged an // ACK_FREQUENCY, its requested delay is the one in use; and "until the // packet carrying the ACK_FREQUENCY frame is acknowledged, the endpoint // MUST use the greater of the current max_ack_delay and the value that // is in flight", since the peer may already be using either. const current: recovery.Duration = if (c.peer_max_ack_delay_us) |us| us *| std.time.ns_per_us else p.max_ack_delay *| std.time.ns_per_ms; const pending = c.ack_frequency_in_flight orelse return current; return @max(current, pending.max_delay_us *| std.time.ns_per_us); } /// What `requestAckFrequency` asked for, kept so a lost frame can be sent /// again with the same values under a new sequence number. const AckFrequencyRequest = struct { threshold: u64, max_delay_us: u64, reordering: u64, }; /// 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` /// has passed, and at once for reordering of `reordering` or more (0 for /// never, 1 for any). Only of a peer that sent min_ack_delay, and never for /// a delay below it or at 2^14 milliseconds or more, which the peer would /// close the connection over. pub fn requestAckFrequency( c: *Connection, threshold: u64, max_ack_delay: recovery.Duration, reordering: u64, ) error{ NotSupported, InvalidDelay }!void { const peer = c.peer orelse return error.NotSupported; const least = peer.min_ack_delay orelse return error.NotSupported; const micros = max_ack_delay / std.time.ns_per_us; if (micros < least or micros >= (1 << 14) * 1000) return error.InvalidDelay; c.ack_frequency_request = .{ .threshold = threshold, .max_delay_us = micros, .reordering = reordering }; c.ack_frequency_owed = true; } test requestAckFrequency { // min_ack_delay is in microseconds: each end can delay an ACK by as // little as a millisecond. var limits = test_limits; limits.min_ack_delay = 1000; const p = try TestPair.connect(limits, limits); defer p.destroy(); // One ACK for every ten packets, or every 50ms, and none sooner for // reordering. try p.server.requestAckFrequency(9, 50 * std.time.ns_per_ms, 0); try p.settle(); try testing.expectEqual(@as(u64, 9), p.client.ack_frequency.?.threshold); // Below what the client said it can do. try testing.expectError(error.InvalidDelay, p.server.requestAckFrequency(9, 500 * std.time.ns_per_us, 0)); } /// draft-ietf-quic-ack-frequency-14 §5: asks the peer to acknowledge now. /// /// An IMMEDIATE_ACK goes out with the next `send`. `error.NotSupported` when /// the peer did not advertise min_ack_delay, and so does not take the frame. pub fn requestImmediateAck(c: *Connection) error{NotSupported}!void { if (!c.peerTakesAckFrequency()) return error.NotSupported; c.immediate_ack_owed = true; } test requestImmediateAck { var limits = test_limits; limits.min_ack_delay = 1000; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); // The server takes the frame, and the client did not say it does. try p.client.requestImmediateAck(); try testing.expectError(error.NotSupported, p.server.requestImmediateAck()); try p.settle(); } /// Whether the peer said, with min_ack_delay, that it takes ACK_FREQUENCY /// and IMMEDIATE_ACK frames. fn peerTakesAckFrequency(c: *const Connection) bool { const peer = c.peer orelse return false; return peer.min_ack_delay != null; } /// Processes one ACK frame: §5 of RFC 9002 for what it says about the path, /// §6.1 for what it says about the packets it does not mention. fn onAck(c: *Connection, level: tls.Level, a: frame.Ack, now: recovery.Instant) Error!void { return c.onAckIn(c.recoveryOf(level), a, now); } /// The recovery state of an encryption level's space: the connection's own /// RTT and congestion, which for the application level is path 0's. fn recoveryOf(c: *Connection, level: tls.Level) Recovery { const index = @backingInt(Space.of(level)); return .{ .space = &c.spaces[index], .rtt = &c.rtt, .congestion = &c.congestion, .application = index == 2, .ecn = if (index == 2) &c.ecn else null, .pmtu = if (index == 2) &c.pmtu else null, .index = @intCast(index), }; } /// The encryption level whose space is `spaces[i]`. fn levelOf(i: usize) tls.Level { return switch (i) { 0 => .initial, 1 => .handshake, else => .application, }; } /// The recovery state of a path past path 0. fn recoveryOfPath(extra: *ExtraPath) Recovery { return .{ .space = &extra.space, .rtt = &extra.rtt, .congestion = &extra.congestion, .application = true, .ecn = &extra.ecn, .pmtu = &extra.pmtu, .index = 2, }; } fn onAckIn(c: *Connection, rec: Recovery, a: frame.Ack, now: recovery.Instant) Error!void { const space = rec.space; // §13.1: "An endpoint SHOULD treat receipt of an acknowledgment for a // packet it did not send as a connection error of type // PROTOCOL_VIOLATION, if it is able to detect the condition." Packet // numbers only go up, so anything at or past the next one never went -- // and a peer acknowledging it is acknowledging optimistically, to be sent // faster than the path allows. if (a.largest >= space.next_number) return error.ProtocolViolation; // §13.4.2.1: "An endpoint MUST NOT fail ECN validation as a result of // processing an ACK frame that does not increase the largest acknowledged // packet number" -- reordered ACK frames carry stale counts, and a // validator fed them would fail a path for arriving out of order. Asked // before `onLargestAcked` moves the mark. const advances = space.loss.largest_acked == null or a.largest > space.loss.largest_acked.?; space.loss.onLargestAcked(a.largest); var largest_sample: ?recovery.Sent = null; var any_newly = false; var newly_marked: u64 = 0; var newly_marked_on_path: u64 = 0; const coupling = if (rec.application) c.linkedIncrease() else null; // §19.3.1: "If any computed packet number is negative, an endpoint MUST // generate a connection error of type FRAME_ENCODING_ERROR." const first = a.firstRange() catch return error.FrameEncodingError; var it = a.ranges(); var range: ?frame.Ack.Range = first; while (range) |r| : (range = it.next() catch return error.FrameEncodingError) { for (space.loss.ackRange(r.smallest, r.largest, c.acked_scratch)) |sent| { any_newly = true; if (sent.ect0) { newly_marked += 1; if (rec.ecn) |validator| if (validator.onPath(sent.number)) { newly_marked_on_path += 1; }; } rec.congestion.onAckedCoupled(sent, now, coupling); // §3.1: a stream's sending half ends when its data has been // acknowledged, so this is the only place a stream can learn // that it is done. if (rec.pmtu) |search| search.acknowledged(sent.number); // draft-ietf-quic-ack-frequency-14 §7: the peer has the request, // and its delay is now the one to allow for. if (sent.ack_frequency) |sequence| { if (c.ack_frequency_in_flight) |in_flight| if (in_flight.sequence == sequence) { c.peer_max_ack_delay_us = in_flight.max_delay_us; c.ack_frequency_in_flight = null; }; } for (sent.streamRanges()) |piece| { const entry = c.find(piece.stream) orelse continue; entry.send.onAcked(piece.offset, piece.len, piece.fin); } if (sent.reset_stream) |id| { if (c.find(id)) |entry| if (entry.has_send) entry.send.resetAcked(); } if (sent.retire_connection_id) |sequence| c.received.ackedRetire(sequence); // §5.1: a sample is taken only from the largest acknowledged // packet, and only when it is newly acknowledged. Any other // packet in the range may have been acknowledged before, in which // case the time since it was sent measures the peer's delay in // repeating itself rather than the path. if (sent.number == a.largest) largest_sample = sent; } } // §13.4.2.1, and only on an application space -- path 0's, or the path's // own: the handshake spaces are short-lived and their keys are // discarded, so a path's behavior is learned where there is enough // traffic to learn it from. // // Before the counts are used rather than after: "an endpoint that // receives an ACK frame with ECN counts therefore validates the counts // before using them". A failure needs nothing more done about it here // -- §13.4.2.2's "stops setting the ECT codepoint" is what the // validator's own `codepoint` now answers -- except that the CE marks // that failed it are not taken as congestion. var ecn_trusted = true; if (rec.ecn) |validator| { if (advances) { const reported: ?ecn_mod.Counts = if (a.ecn) |e| .{ .ect0 = e.ect0, .ect1 = e.ect1, .ce = e.ce } else null; ecn_trusted = validator.onAck(reported, newly_marked, newly_marked_on_path); } else { ecn_trusted = validator.state != .failed; } } if (largest_sample) |sent| { // §5.3: "an endpoint MUST ignore the acknowledgment delay field of // the ACK frame if it was not sent in a 1-RTT packet" -- the Initial // and Handshake spaces have no negotiated exponent to scale it by and // no reason to delay in the first place. const delay: recovery.Duration = if (rec.application) scaledAckDelay(a.delay, c.ackDelayExponent()) else 0; rec.rtt.sample(now -| sent.time, delay, c.maxAckDelay(), c.isEstablished()); rec.congestion.onRttSample(now); // §B.7: the peer reporting more Congestion Experienced marks than // before is the path itself saying it is loaded, rather than an // inference drawn from a packet that failed to arrive. Nothing here // sets the codepoint — that lives in the IP header, which a QUIC // library never touches — so this only ever fires for a caller that // marks its own datagrams. // // Marks that failed validation are recorded as seen all the same, // so that a path tested afterwards does not read them as its own. if (a.ecn) |ecn| { if (ecn_trusted) { rec.congestion.onEcn(rec.index, ecn.ce, sent.time, now); } else { rec.congestion.ce_count[rec.index] = @max(rec.congestion.ce_count[rec.index], ecn.ce); } } space.peer_ecn = a.ecn; } // §6.2.1: the backoff exists to survive a path that has stopped // answering, and an acknowledgement is the proof that it has started // again. if (any_newly) c.pto_count = 0; c.reclaimStreams(); c.detectLostIn(rec, now); } /// Whether a PATH_CHALLENGE is waiting to go out. /// Whether a PATH_CHALLENGE is waiting to go out on one particular path, /// which is the question §8.2.1's expansion rule turns on -- the datagram /// being built is addressed to one path, and another path's pending challenge /// says nothing about how large this one should be. fn owesChallengeOn(c: *Connection, path: paths_mod.Id) bool { const seen = c.paths.find(path) orelse return false; return seen.challenge != null and !seen.sent_challenge; } fn owesChallenge(c: *const Connection) bool { for (&c.paths.entries) |*seen| { if (!seen.in_use) continue; if (seen.challenge != null and !seen.sent_challenge) return true; } return false; } /// §10.3.1: whether a datagram is a stateless reset for this connection. /// /// The tokens checked are the ones the peer issued alongside connection IDs /// this endpoint has actually used, plus the server's /// `stateless_reset_token` transport parameter — which §10.3 notes "applies /// to the connection ID that it selected during the handshake", and which /// only a server can send, because a client's transport parameters travel in /// a ClientHello and "do not have confidentiality protection". fn isStatelessReset(c: *const Connection, datagram: []const u8) bool { if (datagram.len < reset.min_len) return false; var tokens: [ids.capacity + 1 + max_paths][reset.token_len]u8 = undefined; var count: usize = 0; for (&c.received.entries) |*entry| { // Only tokens the peer actually issued, for identifiers this // endpoint is sending to. §10.3.1: "an endpoint MUST NOT check for // any stateless reset tokens associated with connection IDs it has // not used or for connection IDs that have been retired." One given // up is retired, so the identifiers being sent to are all of the // used ones left. if (!entry.in_use or !c.sendsTo(entry.id())) continue; // The handshake's identifier came with the server's transport // parameter rather than a frame. const issued = if (entry.sequence == 0) if (c.peer) |p| p.stateless_reset_token else null else entry.token; tokens[count] = issued orelse continue; count += 1; } // draft-ietf-quic-multipath-21: the identifier in use on each other path // came with a token too, and a reset can arrive for it -- but only one // this endpoint has sent on, for §10.3.1's reason above. for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open or extra.space.next_number == 0) continue; const token = currentToken(&extra.received) orelse continue; tokens[count] = token; count += 1; } if (count == 0) return false; return reset.matches(datagram, tokens[0..count]); } /// Whether path 0 addresses packets to `id`: the identifier in use, the one /// the old path is being challenged by, or the one a preferred address is /// being probed with. fn sendsTo(c: *const Connection, id: []const u8) bool { if (std.mem.eql(u8, id, c.peerId())) return true; if (c.old_path != null and std.mem.eql(u8, id, c.old_path_id[0..c.old_path_id_len])) return true; if (c.preferred_probe == null) return false; return std.mem.eql(u8, id, c.preferred_probe_id[0..c.preferred_probe_id_len]); } test "RFC 9000 10.3.1: a token for an identifier never used is not checked" { // "An endpoint MUST NOT check for any stateless reset tokens associated // with connection IDs it has not used." The preferred address's // identifier arrives with a token, but this client never moves there. const p = try TestPair.connect(test_limits, test_preferred_limits); defer p.destroy(); try testing.expect(!std.mem.eql(u8, &test_preferred_id, p.client.peerId())); var out: [64]u8 = undefined; const forged = try reset.write(&out, p.rng.random(), @splat(0x7e), 60); try p.client.receive(forged, 0, p.now); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); } test "RFC 9000 10.3.1: the handshake's token is not checked once its identifier is retired" { // The server's `stateless_reset_token` transport parameter is the token // for the identifier the handshake used, and §10.3.1 forbids checking a // token "for connection IDs that have been retired". var server_limits = test_limits; server_limits.stateless_reset_token = @splat(0x5a); const p = try TestPair.connect(test_limits, server_limits); defer p.destroy(); try testing.expect(p.client.rotatePeerId()); try p.settle(); var out: [64]u8 = undefined; const forged = try reset.write(&out, p.rng.random(), @splat(0x5a), 60); try p.client.receive(forged, 0, p.now); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); } /// §17.2.5: a server has asked the client to try again with a token. /// /// §6.2: what a client does with a Version Negotiation packet. /// /// Three rules, and two of them are about *not* acting on it, because this /// packet cannot be authenticated — there is no key that could have protected /// it, the whole claim being that the two ends share no version. Everything /// that makes it safe to have at all is a restriction on when it may be /// believed. fn onVersionNegotiation( c: *Connection, datagram: []const u8, header: packet.Header, now: recovery.Instant, ) void { // §17.2.1: "It is only sent by servers." One arriving at a server is not // something any conforming peer sends. if (c.role == .server) return; // §6.2: "A client MUST discard any Version Negotiation packet if it has // received and successfully processed any other packet, including an // earlier Version Negotiation packet." By then the server has answered in // this version, so anything saying otherwise is an off-path attacker who // has guessed that a connection attempt is underway. if (c.processed_any) return; // §6.2: "A client MUST discard a Version Negotiation packet that lists // the QUIC version selected by the client." A server that supported what // was asked for would not have sent this, so one that lists it anyway is // confused or forged -- §21.12's downgrade attack is what the rule guards // against. var at = header.number_offset; while (at + 4 <= header.end) : (at += 4) { const offered = std.mem.readInt(u32, datagram[at..][0..4], .big); if (offered == packet.version_1) return; } // Processed only now: one discarded above was not, and must not stop a // Retry from being accepted afterwards (§17.2.5.2). c.processed_any = true; // "A client that supports only this version of QUIC MUST abandon the // current connection attempt if it receives a Version Negotiation // packet." Draining rather than closing: a CONNECTION_CLOSE would be // protected with keys derived for a version the peer has just said it // cannot read, so there is nobody to tell. c.closing.drain(.no_error, false, "version negotiation", c.closeDeadline(now)); } /// Retry is how a server refuses to keep state for an address it has not /// checked: it answers the Initial with a token and nothing else, and commits /// nothing until the token comes back from the same address. §8.1 is the /// reason — until then, everything the server sends is bounded by three times /// what it received, and a server under load would rather send one small /// packet than carry a handshake for whoever asked. /// /// Almost all of this function is rules about *not* believing it. fn onRetry(c: *Connection, datagram: []const u8, header: packet.Header) Error!void { // §17.2.5.2: "a client MUST discard a Retry packet that contains a // Source Connection ID field that is identical to the Destination // Connection ID field of its Initial packet", and a server does not // receive Retry at all. One that arrives anyway is dropped rather than // treated as an error: nothing in its header is authenticated, so // closing over it would let anyone who knew a connection ID close the // connection. if (c.role != .client) return; // "A client MUST accept and process at most one Retry packet for each // connection attempt." if (c.retry_seen) return; // "After the client has received and processed an Initial or Retry // packet from the server, it MUST discard any subsequent Retry // packets" -- by then the server has answered without asking for one, // and a Retry is somebody else's idea. Processed, whatever it carried: // a server Initial need not acknowledge anything. if (c.processed_any) return; if (header.token.len == 0) return; // §17.2.5.2: a zero-length token if (std.mem.eql(u8, header.source, c.peerId())) return; // Before anything is changed. A Retry carrying a token this client cannot // hold is a Retry it cannot act on, and acting on half of it — adopting // the new connection ID, re-deriving the Initial keys, then sending an // Initial with no token — is worse than ignoring it, because the server // will Retry again and the client will do the same thing forever. That // is not hypothetical: it is what this did against aioquic, whose tokens // are four times the size of the ones in the tests here. if (header.token.len > c.token_buf.len) return; // §5.8 of RFC 9001: the integrity tag proves the sender saw the client's // Initial packet, which an off-path attacker did not. It is not a secret // and authenticates nobody — an on-path attacker can compute it too, and // §21.2 says so — but it is what makes injecting a Retry from a distance // impossible. const original = c.original_destination_buf[0..c.original_destination_len]; retry_mod.verify(datagram[0..header.end], original) catch return; c.retry_seen = true; // §7.3: the server must name this in `retry_source_connection_id`, and // the client checks it there. Without that, an on-path attacker could // substitute a connection ID of its own choosing and the handshake would // not notice. @memcpy(c.retry_source_buf[0..header.source.len], header.source); c.retry_source_len = header.source.len; // §17.2.5.1: "the client MUST use the value from the Retry packet in the // Destination Connection ID field of subsequent packets." @memcpy(c.peer_id_buf[0..header.source.len], header.source); c.peer_id_len = header.source.len; c.received = .init(header.source); @memcpy(c.token_buf[0..header.token.len], header.token); c.token_len = header.token.len; // §5.2 of RFC 9001: the Initial keys come from the Destination Connection // ID, so a new one means new keys. This is the part that makes a Retry // cost a client its whole first flight rather than just a header field. c.deriveInitialKeys(header.source); // The ClientHello has to go again, and what the first attempt had in // flight is void, since the server that will read the second Initial has // no memory of the first. The packet numbers carry on: §17.2.5.3 says // "the client MUST NOT reset the packet number for any packet number // space after processing a Retry packet", because the new Initial keys // and the old packet numbers would otherwise produce nonces the first // attempt already used. const space = &c.spaces[0]; c.congestion.onDiscarded(space.loss.unacked()); space.loss.reset(); space.acks = .{}; space.crypto.sent = 0; space.crypto.acked_prefix = 0; space.crypto.resend_lo = 0; space.crypto.resend_hi = 0; } /// §9.3: the peer has moved. /// /// "If the recipient permits the migration, it MUST send subsequent packets /// to the new peer address and MUST initiate path validation (§8.2) to verify /// the peer's ownership of the address if validation is not already /// underway." /// /// Both halves matter and they are in that order. Sending to the new address /// immediately is what makes migration work at all; validating it is what /// keeps a forged source address from turning the connection into a weapon — /// and until the validation succeeds, §21.1.1.1's three-times limit is what /// bounds the damage in between. fn onMigration(c: *Connection, path: paths_mod.Id, now: recovery.Instant) Error!void { _ = c.paths.observe(path) catch return error.TooManyPaths; // "Any subsequent migration to another path restarts this entire // process": an earlier old path is of no more interest. c.finishOldPath(); const old = c.paths.active; c.paths.migrate(path); // §9.5: "an endpoint MUST NOT reuse a connection ID when sending from // more than one local address" — and the mirror of it here, that a peer // which has moved should be addressed by an identifier not used on the // old path, so an observer cannot link the two. // // §9.3.3: "In response to an apparent migration, endpoints MUST // validate the previously active path using a PATH_CHALLENGE frame", // since a packet copied by an off-path attacker looks just like a move, // and the challenge is what brings packets back down the real path. It // goes by the identifier the old path already knew, which stays // unretired until then. const was_validated = if (c.paths.find(old)) |was| was.validated else false; const rng_for_old = if (was_validated) c.id_rng else null; if (rng_for_old) |rng| { const held = c.peerId(); @memcpy(c.old_path_id[0..held.len], held); c.old_path_id_len = held.len; if (c.received.spare(held)) |spare| { @memcpy(c.peer_id_buf[0..spare.len], spare); c.peer_id_len = spare.len; } c.old_path = old; _ = c.paths.challenge(old, rng, now) catch unreachable; } else { _ = c.rotatePeerId(); } c.measureActivePath(); if (c.paths.find(path)) |seen| { if (seen.validated or seen.challenge != null) return; } const rng = c.id_rng orelse return; _ = c.paths.challenge(path, rng, now) catch return error.TooManyPaths; } /// §9.4: starts the congestion controller, round-trip estimate, ECN /// validation and PMTU search again when the active path is validated and is /// not the one they were learned on. /// /// "On confirming a peer's ownership of its new address, an endpoint MUST /// immediately reset the congestion controller and round-trip time estimator /// for the new path to initial values". The capacity of the new path is not /// the capacity of the old one, and carrying the old estimate over is how a /// sender floods a path it has never measured. And what the old path taught /// about markings and size goes for the same reason: §13.4.2 validates ECN /// "on active connection migration to a new path", and §14.3's PMTU belongs /// to "each combination of local and remote IP addresses". /// /// Called when a validation succeeds and when the connection moves, since a /// move to a path validated earlier -- back to the one the handshake used, /// say -- has no validation left to wait for. A move back to the path the /// numbers came from resets nothing: that is §9.3's "returns to a previously /// validated path after detecting some form of spurious migration", where /// "restoring loss detection and congestion state can reduce the performance /// impact of the attack". /// /// A move that changed only the peer's port keeps all but the ECN /// validation; see `onlyPortMoved`. fn measureActivePath(c: *Connection) void { const active = c.paths.active; if (active == c.measured_route) return; const seen = c.paths.find(active) orelse return; if (!seen.validated) return; const rebound = c.onlyPortMoved(c.measured_route, active); c.measured_route = active; c.ecn.restart(c.spaces[2].next_number); if (rebound) return; c.congestion = .{}; c.rtt = .{}; c.pmtu.reset(); } /// `measureActivePath` for a path past path 0. fn measureExtraPath(c: *Connection, extra: *ExtraPath) void { if (extra.route == extra.measured_route) return; const seen = c.paths.find(extra.route) orelse return; if (!seen.validated) return; const rebound = c.onlyPortMoved(extra.measured_route, extra.route); extra.measured_route = extra.route; extra.ecn.restart(extra.space.next_number); if (rebound) return; extra.congestion = .{}; extra.rtt = .{}; extra.pmtu.reset(); } /// §9.4: whether the caller's routes `from` and `to` differ only in the /// peer's port -- the same local address, and a peer at the same IP address /// on another port. /// /// "Because port-only changes are commonly the result of NAT rebinding or /// other middlebox activity, the endpoint MAY instead retain its congestion /// control state and round-trip estimate in those cases instead of /// reverting to initial values." The packets still cross the network they /// crossed before, and §14.3 keys the PMTU on "each combination of local /// and remote IP addresses", which is unchanged too. ECN is checked again /// all the same: a middlebox that rebinds is one that might also rewrite /// the markings, and validation costs only a few packets' wait. /// /// The local address matters as much as the peer's: a client moving to the /// server's preferred address from a fresh socket looks, to the server, like /// the same IP address on another port, and reaches it at another address /// entirely. So both ends of both routes have to be known, from /// `setLocalAddress` and `setPeerAddress`, and anything unknown is a new /// path. fn onlyPortMoved(c: *Connection, from: paths_mod.Id, to: paths_mod.Id) bool { const old = c.paths.find(from) orelse return false; const new = c.paths.find(to) orelse return false; const old_local = (old.local_address orelse return false).canonical(); const new_local = (new.local_address orelse return false).canonical(); if (!old_local.eql(new_local)) return false; const old_peer = (old.peer_address orelse return false).canonical(); const new_peer = (new.peer_address orelse return false).canonical(); if (old_peer.port == new_peer.port) return false; return old_peer.eql(.{ .ip = new_peer.ip, .port = old_peer.port }); } /// draft-ietf-quic-multipath-21 §3.1.2: a path past path 0 has moved to the /// caller's route `route` -- a NAT rebinding, most likely, since §5.1 has /// an endpoint that means to move open a new path instead. /// /// `onMigration` for one path: it follows, and validates the new route /// unless that is already done or under way. The path keeps its connection /// ID. RFC 9000 §9.5 allows that for a move the peer did not choose: "an /// endpoint might receive packets from a new source address with the same /// Destination Connection ID field value, in which case it MAY continue to /// use the current connection ID with the new remote address". fn onPathMigration(c: *Connection, extra: *ExtraPath, route: paths_mod.Id, now: recovery.Instant) Error!void { _ = c.paths.observe(route) catch return error.TooManyPaths; extra.route = route; c.measureExtraPath(extra); if (c.paths.find(route)) |seen| { if (seen.validated or seen.challenge != null) return; } const rng = c.id_rng orelse return; _ = c.paths.challenge(route, rng, now) catch return error.TooManyPaths; } /// The sequence number of one of this endpoint's own identifiers. fn sequenceOf(c: *const Connection, id: []const u8) ?u64 { for (&c.issued.entries) |*entry| { if (!entry.in_use) continue; if (std.mem.eql(u8, entry.id(), id)) return entry.sequence; } return null; } /// §5.1.1: "an endpoint SHOULD ensure that its peer has a sufficient number /// of available and unused connection IDs." /// /// Sufficient means the peer's own `active_connection_id_limit`, which is the /// number it said it would maintain — issuing fewer leaves it unable to /// migrate (§9.5 forbids reusing an identifier on a new path), and issuing /// more is a connection error at its end. /// /// Only once the handshake is confirmed, because §12.4 permits /// NEW_CONNECTION_ID only in 0-RTT and 1-RTT packets and there is nothing to /// be gained by racing the handshake with it. fn owesNewId(c: *const Connection) bool { if (!c.confirmed) return false; if (c.id_rng == null) return false; // §19.15: an endpoint that asked to be addressed by nothing cannot issue // anything to replace it with. if (c.issued.len == 0) return false; if (!c.issued.hasRoom()) return false; const limit: u64 = if (c.peer) |p| p.active_connection_id_limit else 2; return c.issued.active() < limit; } /// §8.2: whether a path has answered a challenge and may be trusted with /// traffic. /// /// False for a path this connection has never seen, which is the same answer /// as for one that has not answered -- neither is a path to send on, and the /// caller's next move is the same either way. pub fn pathValidated(c: *Connection, path: paths_mod.Id) bool { const seen = c.paths.find(path) orelse return false; return seen.validated; } test pathValidated { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); // §8.1: the handshake validated the path it ran on. try testing.expect(p.client.pathValidated(0)); try testing.expect(!p.client.pathValidated(1)); // A new path is validated by its PATH_CHALLENGE being answered. try p.client.migrateTo(1, p.now); try testing.expect(!p.client.pathValidated(1)); try p.settle(); try testing.expect(p.client.pathValidated(1)); } /// §9.6: where the server would rather be talked to, if it said. /// /// Null for a server, which is the end that advertises this rather than the /// end that acts on it, and for a client whose server did not. /// /// The addresses are raw octets: this library has no address type and cannot /// connect to anything, so acting on one is the caller's job. What the caller /// does with it is open a socket to that address, give the connection a new /// path identifier for it, and call `migrateToPreferredAddress`. pub fn preferredAddress(c: *const Connection) ?parameters.PreferredAddress { const p = c.peer orelse return null; return p.preferred_address; } test preferredAddress { const p = try TestPair.connect(test_limits, test_preferred_limits); defer p.destroy(); const where = p.client.preferredAddress().?; try testing.expectEqual([4]u8{ 192, 0, 2, 1 }, where.ipv4); try testing.expectEqual(@as(u16, 8853), where.ipv4_port); try testing.expectEqualSlices(u8, &test_preferred_id, where.connection_id); // The server is the end that offers one, never the end told of one. try testing.expect(p.server.preferredAddress() == null); } /// §9: moves this connection to a path the caller has chosen. /// /// The path is whatever the caller's numbering says it is -- this library /// never learns an address -- so "moving" here means addressing the peer from /// a new local vantage point and proving it works. Both halves of §9 follow /// immediately: a fresh connection ID, so that an observer cannot link the /// old path to the new one (§9.5), and a PATH_CHALLENGE, because §8.2 makes /// an unvalidated path one this endpoint may not yet trust with its traffic. /// /// §9: "an endpoint MUST NOT initiate connection migration before the /// handshake is confirmed", which is one reason this can fail. Before /// confirmation the peer may still be completing a handshake whose packets /// are addressed to the old path, and moving underneath it loses them. /// /// The others: `error.ProtocolViolation` when the server sent /// disable_active_migration (§18.2); `error.StreamStateError` before /// confirmation, on a server — only a client migrates here — with no /// `Options.rng` to make a challenge from, or with no spare connection ID to /// move to (§9.5); `error.TooManyPaths` when the path table is full. pub fn migrateTo(c: *Connection, path: paths_mod.Id, now: recovery.Instant) Error!void { // §18.2: "A client that receives disable_active_migration MUST NOT use a // new local address when sending to the address that the server // provided." The preferred address is the exception, and it has its own // entry point below rather than a flag here -- an exemption that has to // be asked for by name is one that cannot be taken by accident. if (c.peer) |p| { if (p.disable_active_migration) return error.ProtocolViolation; } return c.startMigration(path, now); } test migrateTo { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const before = try testing.allocator.dupe(u8, p.client.peerId()); defer testing.allocator.free(before); // The caller has opened a socket on a new interface and calls it path 1. try p.client.migrateTo(1, p.now); // A fresh identifier at once, so the two paths cannot be linked (§9.5). try testing.expect(!std.mem.eql(u8, before, p.client.peerId())); var buffer: [2048]u8 = undefined; const datagram = (try p.client.send(&buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), datagram.path); try p.server.receive(datagram.bytes, datagram.path, p.now); try p.settle(); try testing.expect(p.client.pathValidated(1)); // Only a client moves. try testing.expectError(error.StreamStateError, p.server.migrateTo(1, p.now)); } /// §9.6: moves this connection to the address the server said it preferred. /// /// Separate from `migrateTo` because §18.2 gives it an exemption that nothing /// else has: "this transport parameter does not prohibit connection migration /// after a client has acted on a preferred_address transport parameter", so a /// server that forbade migration in general has still invited this one. /// /// The identifier comes with the invitation. §5.1.1 numbers it 1, and it was /// entered in this endpoint's table when the parameters were parsed, so it is /// found like any other spare. /// /// Unlike `migrateTo`, this does not move the connection at once. §9.6.3: /// "the client SHOULD ... perform path validation of the server's preferred /// address", and "if path validation fails, the client MUST continue sending /// all future packets to the server's original IP address." So `path` is /// sent a PATH_CHALLENGE, by a connection ID the original path does not use, /// and everything else stays where it is. The connection moves when the /// answer arrives -- `pathValidated(path)` says when -- and stays put if it /// never does. /// /// `error.StreamStateError` when the server named no preferred address or /// there is no spare connection ID to probe with; otherwise it fails as /// `migrateTo` does, less the disable_active_migration refusal. pub fn migrateToPreferredAddress( c: *Connection, path: paths_mod.Id, now: recovery.Instant, ) Error!void { const p = c.peer orelse return error.StreamStateError; if (p.preferred_address == null) return error.StreamStateError; // §9: "an endpoint MUST NOT initiate connection migration before the // handshake is confirmed". if (!c.confirmed) return error.StreamStateError; if (c.role != .client) return error.StreamStateError; const rng = c.id_rng orelse return error.StreamStateError; // §9.5: the probe may not carry the identifier the original path does, // or the two are linkable by anyone watching both. c.finishOldPath(); const spare = c.received.spare(c.peerId()) orelse return error.StreamStateError; _ = c.paths.observe(path) catch return error.TooManyPaths; // The caller chose the address, so §21.1.1.1's limit does not apply, as // in `startMigration`. c.paths.choose(path); _ = c.paths.challenge(path, rng, now) catch return error.TooManyPaths; @memcpy(c.preferred_probe_id[0..spare.len], spare); c.preferred_probe_id_len = spare.len; c.preferred_probe = path; } /// Ends §9.3.3's challenge to the path the peer left, answered or not, and /// retires the identifier it was being sent by unless that is the one in /// use. Nothing to do when there is no such challenge. fn finishOldPath(c: *Connection) void { if (c.old_path == null) return; c.old_path = null; const held = c.old_path_id[0..c.old_path_id_len]; if (std.mem.eql(u8, held, c.peerId())) return; // Too many retirements unacknowledged leaves it held as an ordinary // spare, which §5.1.2 permits; it is never forgotten unretired. if (c.sequenceOfPeer(held)) |sequence| c.received.retire(sequence) catch {}; } /// §9.6.3: the preferred address answered, so the connection moves there, /// addressed by the identifier the probe used. Should that identifier have /// been retired meanwhile, any other spare does as well. fn finishPreferredProbe(c: *Connection, path: paths_mod.Id) void { c.preferred_probe = null; const probed = c.preferred_probe_id[0..c.preferred_probe_id_len]; const renamed = if (c.sequenceOfPeer(probed) == null) c.rotatePeerId() else std.mem.eql(u8, probed, c.peerId()) or c.usePeerId(probed); // §9.5: not onto a new path under the old name. if (!renamed) return; c.paths.migrate(path); } /// The PATH_CHALLENGE due on a path that is not the active one -- a /// server's preferred address being probed (§9.6.3), or the path the peer /// apparently left (§9.3.3) -- alone in a datagram padded to 1200 octets as /// §8.2.1 asks, if one is due. /// /// Built apart from `send`'s packets because it goes to a path that is not /// the active one and by a connection ID the active path does not use. Not /// tracked for loss, like `sendProbeAlone`'s: an unanswered challenge is /// sent again by `Paths.expire`'s timer instead. fn sendChallengeAlone(c: *Connection, out: []u8, now: recovery.Instant) ?Datagram { const path, const addressed_to = if (c.preferred_probe) |path| .{ path, c.preferred_probe_id[0..c.preferred_probe_id_len] } else if (c.old_path) |path| .{ path, c.old_path_id[0..c.old_path_id_len] } else return null; // The path the peer moved to is challenged first: that is the one the // connection is now sending on. if (path == c.old_path and c.owesChallengeOn(c.paths.active)) return null; const seen = c.paths.find(path) orelse return null; if (seen.sent_challenge) return null; const data = seen.challenge orelse return null; const keys = if (c.spaces[2].write) |*k| k else return null; const size = @min(out.len, min_initial_datagram, c.paths.sendable(path)); if (size == 0) return null; const space = &c.spaces[2]; var b = packet.Builder.initShort(out[0..size], addressed_to, space.next_number, 4, c.key_phase) catch return null; b.add(.{ .path_challenge = &data }) catch return null; b.padTo(size) catch {}; c.grease(&b); const wire = b.finishOn(keys, 0) catch return null; seen.sent_challenge = true; seen.challenge_short = wire.len < min_initial_datagram; seen.challenge_sent_at = now; space.next_number += 1; c.packets_encrypted +|= 1; seen.sent +|= wire.len; return .{ .path = path, .bytes = wire }; } test migrateToPreferredAddress { // A server that names a preferred address and forbids migration // otherwise -- which does not forbid this. var server_limits = test_preferred_limits; server_limits.disable_active_migration = true; const p = try TestPair.connect(test_limits, server_limits); defer p.destroy(); try testing.expectError(error.ProtocolViolation, p.client.migrateTo(1, p.now)); // The caller opened a socket to `preferredAddress()` and calls it path 1. const before = try testing.allocator.dupe(u8, p.client.peerId()); defer testing.allocator.free(before); try p.client.migrateToPreferredAddress(1, p.now); // §9.6.3: probed first, and until it answers, the original address is // the one being talked to, by the identifier it was talked to by. try testing.expectEqual(@as(paths_mod.Id, 0), p.client.paths.active); try testing.expectEqualSlices(u8, before, p.client.peerId()); try p.settle(); try testing.expect(p.client.pathValidated(1)); // Then moved, and addressed by an identifier the old path never used. try testing.expectEqual(@as(paths_mod.Id, 1), p.client.paths.active); try testing.expect(!std.mem.eql(u8, before, p.client.peerId())); } test "RFC 9000 9.6.3: a preferred address that does not answer is never used" { // "If path validation fails, the client MUST continue sending all future // packets to the server's original IP address." Nothing but the probe // goes to the new address, so a server that is not there costs the // connection nothing. const p = try TestPair.connect(test_limits, test_preferred_limits); defer p.destroy(); try p.client.migrateToPreferredAddress(1, p.now); const id = try p.client.openBidirectional(); try p.client.write(id, "still here"); try p.client.finishStream(id); var probes: usize = 0; for (0..200) |_| { var moved = false; if (try p.client.send(&p.buffer, p.now)) |d| { moved = true; if (d.path == 1) { probes += 1; } else { p.now += std.time.ns_per_ms; try p.server.receive(d.bytes, d.path, p.now); } } if (try p.server.send(&p.buffer, p.now)) |d| { moved = true; p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); } try testing.expectEqual(@as(paths_mod.Id, 0), p.client.paths.active); if (moved) continue; const next = @min( p.client.timeout() orelse std.math.maxInt(u64), p.server.timeout() orelse std.math.maxInt(u64), ); if (next == std.math.maxInt(u64)) break; p.now = @max(p.now, next); p.client.onTimeout(p.now); p.server.onTimeout(p.now); if (p.client.paths.find(1)) |seen| if (seen.challenge == null) break; } try testing.expect(probes > 0); try testing.expect(!p.client.pathValidated(1)); try testing.expectEqual(termination.State.open, p.client.closing.state); try testing.expectEqualStrings("still here", p.server.readable(id)); } fn startMigration(c: *Connection, path: paths_mod.Id, now: recovery.Instant) Error!void { // §9: "an endpoint MUST NOT initiate connection migration before the // handshake is confirmed". if (!c.confirmed) return error.StreamStateError; if (c.role != .client) return error.StreamStateError; const rng = c.id_rng orelse return error.StreamStateError; // §9.5: "an endpoint MUST NOT reuse a connection ID when sending from // more than one local address", so with no spare there is no moving. // A peer addressed by a zero-length identifier has none to reuse. if (c.peer_id_len != 0 and c.received.spare(c.peerId()) == null) return error.StreamStateError; _ = c.paths.observe(path) catch return error.TooManyPaths; // §21.1.1.1's limit is about answering an address somebody else supplied, // and this one came from the caller. Without this the challenge below // could never leave: nothing has arrived from a path nothing has been // sent to, and three times nothing is nothing. c.paths.choose(path); // §9.5: a new path gets a name the old one never used, or the two are // linkable by anyone watching both. Too many retirements unacknowledged // can still refuse it, and then the move waits. if (c.peer_id_len != 0 and !c.rotatePeerId()) return error.StreamStateError; c.paths.migrate(path); c.measureActivePath(); if (c.paths.find(path)) |seen| { if (seen.validated or seen.challenge != null) return; } // §8.2: unvalidated until the echo comes back, and §21.1.1.1's // three-times limit is what bounds the damage until it does. _ = c.paths.challenge(path, rng, now) catch return error.TooManyPaths; } test "RFC 9000 9.5: no migration without a connection ID the old path never used" { // "An endpoint MUST NOT reuse a connection ID when sending from more // than one local address -- for example, when initiating connection // migration as described in Section 9.2." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); while (p.client.received.spare(p.client.peerId())) |spare| { try p.client.received.retire(p.client.sequenceOfPeer(spare).?); } try testing.expectError(error.StreamStateError, p.client.migrateTo(1, p.now)); try testing.expectEqual(@as(paths_mod.Id, 0), p.client.paths.active); try testing.expectEqual(@as(?*paths_mod.Path, null), p.client.paths.find(1)); } /// Stops using the peer's current connection ID and moves to a spare. /// /// §5.1.2: "an endpoint can change the connection ID it uses for a peer to /// another available one at any time during the connection", and §9.5 makes /// it compulsory before sending from a new local address — a connection ID is /// visible in the clear on every packet, so carrying the same one onto a new /// path tells an observer that both paths are the same connection. /// /// False when there is no spare, which is a peer that has not issued enough /// and an endpoint that therefore cannot migrate. §5.1.1 warns about exactly /// that: "an endpoint that initiates migration and requires non-zero-length /// connection IDs SHOULD ensure that the pool of connection IDs available to /// its peer allows the peer to use a new connection ID on migration, as the /// peer will be unable to respond if the pool is exhausted." pub fn rotatePeerId(c: *Connection) bool { c.finishOldPath(); const spare = c.received.spare(c.peerId()) orelse return false; return c.usePeerId(spare); } /// Addresses the peer by `next`, one of its identifiers, and retires the /// one in use. False, changing nothing, when the one in use cannot be /// retired yet. fn usePeerId(c: *Connection, next_id: []const u8) bool { var next: [ids.max_len]u8 = undefined; @memcpy(next[0..next_id.len], next_id); const len = next_id.len; // The retirement goes out in a packet addressed to the *new* identifier, // because §19.16 forbids retiring the one a packet is addressed to. // Too many retirements unacknowledged already: keep the one in use // rather than forget it unretired (§5.1.2). if (c.sequenceOfPeer(c.peerId())) |sequence| c.received.retire(sequence) catch return false; @memcpy(c.peer_id_buf[0..len], next[0..len]); c.peer_id_len = len; return true; } test rotatePeerId { const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); // Before the server has said anything it has issued nothing to move to. try testing.expect(!p.client.rotatePeerId()); // Once its NEW_CONNECTION_ID frames have arrived there are spares. try p.handshake(); try p.settle(); var before: [ids.max_len]u8 = undefined; const len = p.client.peerId().len; @memcpy(before[0..len], p.client.peerId()); try testing.expect(p.client.rotatePeerId()); try testing.expect(!std.mem.eql(u8, before[0..len], p.client.peerId())); // The server still answers: the new identifier is one it issued. try testing.expect(p.server.acceptsId(p.client.peerId())); try p.settle(); } /// The sequence number of one of the peer's identifiers. fn sequenceOfPeer(c: *const Connection, id: []const u8) ?u64 { for (&c.received.entries) |*entry| { if (!entry.in_use) continue; if (std.mem.eql(u8, entry.id(), id)) return entry.sequence; } return null; } /// Issues another connection ID, or says why not. /// /// §5.1.1 permits an endpoint to stop: "an endpoint MAY limit the total /// number of connection IDs issued for each connection to avoid the risk of /// running out of connection IDs". Here the limits are the table's size, the /// peer's `active_connection_id_limit`, and having been given a source of /// randomness at all — without one there is nothing safe to issue, since /// §10.3's token beside each identifier must be unguessable. fn issueId(c: *Connection) ?*const ids.Entry { const rng = c.id_rng orelse return null; const limit: u64 = if (c.peer) |p| p.active_connection_id_limit else 2; if (c.issued.active() >= limit) return null; var id: [ids.max_len]u8 = undefined; rng.bytes(id[0..c.issued.len]); // §10.3.2: derived from the static key and this connection ID, so that // an endpoint which has lost everything can still recompute it from the // identifier on an arriving packet. A random token would be one more // thing to remember, and remembering is what a stateless reset is for // not doing. var token: [ids.token_len]u8 = undefined; if (c.reset_key) |key| { token = reset.token(key, id[0..c.issued.len]); } else { rng.bytes(&token); } const sequence = c.issued.add(id[0..c.issued.len], token) catch return null; for (&c.issued.entries) |*entry| { if (entry.in_use and entry.sequence == sequence) return entry; } return null; } /// Moves to one of the peer's identifiers if the one in use has been retired. fn useCurrentId(c: *Connection) void { const current = c.received.current() orelse return; if (std.mem.eql(u8, current, c.peerId())) return; @memcpy(c.peer_id_buf[0..current.len], current); c.peer_id_len = current.len; } /// §19.3's Ack Delay field, in nanoseconds. /// /// The field is a varint, so a peer may write any value below 2^62 in it, and /// it is then scaled by a power of two and again by a thousand to reach /// nanoseconds. Both of those overflow a `u64` for values a peer can write in /// four octets, and an overflow in Zig is a panic rather than a wrong answer /// — so the arithmetic saturates. What a saturated value means is "longer /// than any round trip", which `Rtt.sample` already handles: §5.3's floor at /// `min_rtt` refuses to subtract a delay that would put the sample below /// anything ever measured, so an absurd claim is ignored rather than believed. fn scaledAckDelay(delay: u64, exponent: u6) recovery.Duration { return (delay *| (@as(u64, 1) << exponent)) *| std.time.ns_per_us; } /// Moves whatever §6.1 declares lost into the range to be sent again, and /// tells the controller what the path just did. fn detectLostIn(c: *Connection, r: Recovery, now: recovery.Instant) void { const space = r.space; const lost = space.loss.detectLost(r.rtt, now, c.lost_scratch); for (lost) |sent| c.recover(space, sent); // §13.4.2: "An endpoint can also mark the ECN state for a path as // 'failed' if marked packets are all declared lost" -- asked whenever a // marked one is, on the space and path the validator describes, and of // the packets sent since that path became the one in use: one still in // flight from the path before is not this path's to vouch for. if (r.ecn) |validator| { const marked_lost = for (lost) |sent| { if (sent.ect0 and validator.onPath(sent.number)) break true; } else false; if (marked_lost) { const marked_outstanding = for (space.loss.unacked()) |sent| { if (sent.ect0 and validator.onPath(sent.number)) break true; } else false; validator.onMarkedLost(marked_outstanding); } } // §14.4: a lost PMTU probe is not evidence about congestion. It is // evidence about the path's size, which `recover` has already passed to // the search — so what is left is to keep it away from the controller. // The probes are filtered out rather than the whole batch skipped, // because a datagram that was too large says nothing while the ordinary // packets lost beside it say a great deal. const real = c.real_scratch; var real_len: usize = 0; for (lost) |sent| { if (sent.probe) continue; real[real_len] = sent; real_len += 1; } // §14.4: "loss of a QUIC packet that is carried in a PMTU probe is // therefore not a reliable indication of congestion and SHOULD NOT // trigger a congestion control reaction." A probe is *meant* to be lost // when it is too large, and an endpoint that halved its window each time // would be punishing itself for asking. // §7.6.1: unlike §6.2.1's timer, the persistent congestion duration // includes `max_ack_delay` whatever space the loss was established in. r.congestion.onLost(real[0..real_len], r.rtt.probeTimeout(c.maxAckDelay()), now); } /// §14.4: a PMTU probe — a packet of nothing but PING and PADDING, sized to /// the question being asked. /// /// "Endpoints could limit the content of PMTU probes to PING and PADDING /// frames, since packets that are larger than the current maximum datagram /// size are more likely to be dropped by the network." A probe carrying /// stream data would make every failed probe a retransmission, and probes are /// *expected* to fail — that is what they are for. fn sendProbe(c: *Connection, out: []u8, now: recovery.Instant) Error!?Datagram { const space = &c.spaces[2]; if (!space.hasKeys() or c.discarded[2]) return null; // Path 0 first, then each further path with a search of its own (§5.8 // of draft-ietf-quic-multipath-21), begun once the path is usable: a // probe to an address not yet validated would be spent against §8.1's // amplification limit rather than on the question. if (!c.path0_abandoned) { if (try c.probeOn(out, now, &c.pmtu, space, &c.congestion, c.peerId(), 0, c.paths.active)) |d| return d; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (!c.usablePath(extra.id)) continue; extra.pmtu.begin(); const id = extra.received.current() orelse continue; if (try c.probeOn(out, now, &extra.pmtu, &extra.space, &extra.congestion, id, extra.id, extra.route)) |d| return d; } return null; } /// One PMTU probe on one path: numbered in `numbering`, addressed to /// `addressed_to`, sealed with `nonce_path` in the nonce, and counted /// against `congestion`. fn probeOn( c: *Connection, out: []u8, now: recovery.Instant, search: *mtu.Search, numbering: *SpaceState, congestion: *Congestion, addressed_to: []const u8, nonce_path: u32, route: paths_mod.Id, ) Error!?Datagram { const size = search.next() orelse return null; if (out.len < size) return null; const space = &c.spaces[2]; var b = packet.Builder.initShort( out[0..size], addressed_to, numbering.next_number, 4, c.key_phase, ) catch return null; // Ack-eliciting, because §14.4 says so and because the whole mechanism is // "send this and see whether it is acknowledged". b.add(.ping) catch return null; b.padTo(size) catch return null; c.grease(&b); const wire = b.finishOn(&space.write.?, nonce_path) catch return null; search.sent(size, numbering.next_number); if (numbering.loss.onSent(.{ .number = numbering.next_number, .time = now, .ack_eliciting = true, .size = wire.len, .probe = true, })) |forgotten| c.forgetIn(numbering, congestion, forgotten); // §14.4: "PMTU probes consume congestion window, which could delay // subsequent transmission by an application" — they are exempt from // *reacting* to loss, not from the window. congestion.onSent(wire.len); numbering.next_number += 1; c.packets_encrypted +|= 1; if (c.paths.find(route)) |seen| seen.sent +|= wire.len; return .{ .path = route, .bytes = wire }; } /// Builds a datagram carrying nothing but CONNECTION_CLOSE frames. /// /// §10.2.3: "the goal is to ensure that the peer will process the frame", /// and before the handshake is confirmed there is no knowing which keys the /// peer has: "Prior to confirming the handshake, a peer might be unable to /// process 1-RTT packets, so an endpoint SHOULD send a CONNECTION_CLOSE frame /// in both Handshake and 1-RTT packets. A server SHOULD also send a /// CONNECTION_CLOSE frame in an Initial packet." So there is one packet for /// every level this endpoint can still write, coalesced. A server that has /// read a ClientHello already has 1-RTT keys, and a close sent only in a /// 1-RTT packet reaches a client that cannot read it. Once the handshake is /// confirmed the Initial and Handshake keys are gone and only 1-RTT is left. fn sendClose(c: *Connection, out: []u8, now: recovery.Instant) Error!?[]u8 { _ = now; var usable: [3]bool = undefined; var last: ?usize = null; for (&usable, 0..) |*u, i| { u.* = !c.discarded[i] and c.spaces[i].write != null; if (u.*) last = i; } const last_index = last orelse return null; var at: usize = 0; for ([_]packet.Kind{ .initial, .handshake, .one_rtt }, 0..) |kind, i| { if (!usable[i]) continue; const space = &c.spaces[i]; const rest = out[at..]; var b = if (kind == .one_rtt) packet.Builder.initShort(rest, c.peerId(), space.next_number, 4, c.key_phase) catch return error.NoSpace else packet.Builder.initLong(rest, .{ .kind = kind, .destination = c.peerId(), .source = c.localId(), }, space.next_number, 4) catch return error.NoSpace; // §19.19: the transport variant names the frame type that caused the // error; the application variant has no such field, because an // application error is not about a frame. // // §10.2.3: the application variant only in a 1-RTT packet. "A // CONNECTION_CLOSE of type 0x1d MUST be replaced by a // CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or // Handshake packets. Otherwise, information about the application // state might be revealed. Endpoints MUST clear the value of the // Reason Phrase field and SHOULD use the APPLICATION_ERROR code when // converting." Those packets are protected with keys anyone watching // the handshake can work out. const hidden = c.closing.application and kind != .one_rtt; b.add(.{ .connection_close = if (hidden) .{ .error_code = @backingInt(termination.Code.application_error), .frame_type = 0, .reason = "", .application = false, } else .{ .error_code = @backingInt(c.closing.code), .frame_type = if (c.closing.application) null else c.closing.frame_type orelse 0, .reason = c.closing.reason(), .application = c.closing.application, } }) catch return error.NoSpace; // §14.1 still applies: a client's datagram carrying an Initial is // padded, even when all it carries is the news that the connection // is over. The padding goes in the last packet, as `send` puts it. if (i == last_index and c.role == .client and usable[0]) { if (out.len < min_initial_datagram) return error.NoSpace; b.padTo(min_initial_datagram - at) catch return error.NoSpace; } c.grease(&b); const wire = b.finish(&space.write.?) catch return error.NoSpace; space.next_number += 1; at += wire.len; } c.closing.onSent(); return out[0..at]; } /// RFC 9287 §3.1: clears the QUIC Bit of a packet about to be sealed, half /// the time, once the peer has said it can take that. /// /// "Endpoints that receive the grease_quic_bit transport parameter from a /// peer SHOULD set the QUIC Bit to an unpredictable value" -- unpredictable /// rather than always zero, because the point is that nothing on the path /// can learn a rule about the bit at all. Only after the peer's transport /// parameters are in hand, since an endpoint "MUST NOT set the QUIC Bit to 0 /// without knowing whether the peer supports the extension", and never on /// the first flight, which the rule covers by construction. /// /// Before sealing, not after: the first octet is part of the header, and /// the header is the AEAD's associated data. Header protection masks only /// the low bits, so the one set here is sent as it is written. fn grease(c: *Connection, b: *packet.Builder) void { const peer = c.peer orelse return; if (!peer.grease_quic_bit) return; const rng = c.id_rng orelse return; if (rng.boolean()) b.buffer[0] &= ~@as(u8, 0x40); } /// §19.15's NEW_CONNECTION_ID, and draft-ietf-quic-multipath-21's /// PATH_NEW_CONNECTION_ID for path 0. fn onNewConnectionId(c: *Connection, n: frame.NewConnectionId) Error!void { // §19.15: "an endpoint that is sending packets with a zero-length // Destination Connection ID MUST treat receipt of a NEW_CONNECTION_ID // frame as a connection error of type PROTOCOL_VIOLATION" — a peer that // asked to be addressed by nothing has nothing to replace. if (c.peer_id_len == 0) return error.ProtocolViolation; c.received.offer( n.sequence, n.retire_prior_to, n.id, n.token.*, c.local.active_connection_id_limit, ) catch |err| switch (err) { error.ConnectionIdLimitError => return error.ConnectionIdLimitError, error.FrameEncodingError => return error.FrameEncodingError, else => return error.ProtocolViolation, }; // The identifier being used may have just been retired out from under // us, in which case §5.1.2 requires moving to one of the others. c.useCurrentId(); } /// §19.16's RETIRE_CONNECTION_ID, and PATH_RETIRE_CONNECTION_ID for path 0. fn onRetireConnectionId(c: *Connection, sequence: u64, addressed_to: []const u8) Error!void { // §19.16: "an endpoint MUST NOT send this frame if it has a Sequence // Number matching the connection ID in the Destination Connection ID // field of the packet in which the frame is contained" — retiring the // identifier you are addressing this very packet to. if (c.sequenceOf(addressed_to)) |used| { if (used == sequence) return error.ProtocolViolation; } c.issued.retire(sequence) catch return error.ProtocolViolation; // The slot is free, so `owesNewId` will now say yes — §5.1.1: "an // endpoint SHOULD supply a new connection ID when the peer retires a // connection ID." } /// The token of the identifier `current` would address the peer with. fn currentToken(received: *const ids.Received) ?[reset.token_len]u8 { var best: ?*const ids.Entry = null; for (&received.entries) |*entry| { if (!entry.in_use) continue; if (best == null or entry.sequence < best.?.sequence) best = entry; } const entry = best orelse return null; return entry.token; } /// The probe timeout of whichever open path has the longest -- path 0's when /// it is the only one, which is every connection without multipath. fn largestProbeTimeout(c: *const Connection) recovery.Duration { var largest = c.rtt.probeTimeout(c.maxAckDelay()); for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open) continue; largest = @max(largest, extra.rtt.probeTimeout(c.maxAckDelay())); } return largest; } /// §8.2.4: the probe timeout path validation is timed by -- "the larger of /// the current PTO or the PTO for the new path (using kInitialRtt...)". The /// new path has not been measured, so its PTO is the one an unmeasured /// estimate gives. fn validationProbeTimeout(c: *const Connection) recovery.Duration { const unmeasured: recovery.Rtt = .{}; return @max(c.largestProbeTimeout(), unmeasured.probeTimeout(c.maxAckDelay())); } /// §8.2.4: route `route` did not answer its challenge in time, and "when an /// endpoint abandons path validation, it determines that the path is /// unusable". /// /// When it is where the connection was sending, §9.3.2 says where to go /// instead: "an endpoint MUST revert to using the last validated peer /// address when validation of a new peer address fails" -- which is what /// makes a forged packet's migration harmless once its challenge goes /// unanswered -- and "if an endpoint has no state about the last validated /// peer address, it MUST close the connection silently". A path past path 0 /// that moved goes back to the route it came from the same way; one that /// never had a validated route is abandoned. fn onValidationFailed(c: *Connection, route: paths_mod.Id) void { // §9.6.3: a preferred address that did not answer is given up on, and // the connection, which never left the original, stays there. if (c.preferred_probe == route) c.preferred_probe = null; if (c.old_path == route) c.finishOldPath(); // A second challenge to a route already proved -- `openPath` over one a // path already runs on -- leaves it as proved as it was. if (c.pathValidated(route)) return; if (route == c.paths.active) { if (c.measured_route == route or !c.pathValidated(c.measured_route)) { c.closing.state = .closed; c.closing.code = .no_error; return; } c.paths.migrate(c.measured_route); } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open or extra.route != route) continue; if (extra.measured_route != route and c.pathValidated(extra.measured_route)) { extra.route = extra.measured_route; } else { c.abandonPath(extra.id) catch {}; } } } /// draft-ietf-quic-multipath-21 §2: whether both ends advertised /// initial_max_path_id, which is the whole of the negotiation. "If either of /// the endpoints does not advertise the initial_max_path_id transport /// parameter, then both endpoints MUST NOT use any frame or mechanism /// defined in this document." pub fn multipathNegotiated(c: *const Connection) bool { if (c.local.initial_max_path_id == null) return false; const peer = c.peer orelse return false; return peer.initial_max_path_id != null; } test multipathNegotiated { const both = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer both.destroy(); try testing.expect(both.client.multipathNegotiated()); try testing.expect(both.server.multipathNegotiated()); // Asked for by one end only, it is off at both. const one = try TestPair.connect(test_multipath_limits, test_limits); defer one.destroy(); try testing.expect(!one.client.multipathNegotiated()); try testing.expect(!one.server.multipathNegotiated()); } /// The largest path ID this endpoint has allowed its peer. fn localMaxPathId(c: *const Connection) u64 { return c.local_max_path_id; } /// §4's rules for a frame naming a path, answering whether it names one this /// endpoint can act on. /// /// A multipath frame on a connection that did not negotiate multipath, or /// naming a path above the limit this endpoint set, is a PROTOCOL_VIOLATION /// -- "receipt of multipath-specific frames that use a path ID that is /// greater than the announced Maximum Paths value... MUST be treated as a /// connection error". One naming a path within the limit that this endpoint /// has no state for "MUST silently ignore the frame", which with only path 0 /// in use is every path but 0. fn onPathFrame(c: *Connection, path: u64) Error!?PathRef { if (!c.multipathNegotiated()) return error.ProtocolViolation; if (path > c.localMaxPathId()) return error.ProtocolViolation; if (path == 0) return .zero; const extra = c.extraFor(path) orelse return null; return .{ .extra = extra }; } /// A path a frame names: path 0, or one past it. const PathRef = union(enum) { zero, extra: *ExtraPath, }; /// The slot holding multipath path ID `id`, if one does. Slots start out as /// paths 1 up, and one that is let go of comes back under a new ID, so the /// ID is looked for rather than computed. fn extraFor(c: *Connection, id: u64) ?*ExtraPath { if (id == 0) return null; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.id == id) return extra; } return null; } /// §3.3's state for path `id`, if this connection has any. fn statusFor(c: *Connection, id: u64) ?*PathStatus { if (id == 0) return &c.path0_status; const extra = c.extraFor(id) orelse return null; return &extra.status; } /// Whether `id` is one this connection issued and has not seen retired, on /// any path. §5.1.1: "when an endpoint issues a connection ID, it MUST accept /// packets that carry this connection ID for the duration of the connection /// or until its peer invalidates the connection ID" -- which is every /// NEW_CONNECTION_ID and PATH_NEW_CONNECTION_ID it ever sent, and not only /// the one the handshake used. pub fn acceptsId(c: *Connection, id: []const u8) bool { return c.issued.accepts(id) or c.extraAddressedBy(id) != null; } test acceptsId { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); // An endpoint routing datagrams to connections asks this of each one. try testing.expect(p.server.acceptsId(&test_server_id)); try testing.expect(p.server.acceptsId(p.client.peerId())); try testing.expect(!p.server.acceptsId(&test_client_id)); try testing.expect(!p.server.acceptsId(&.{ 0xde, 0xad })); } /// The path past path 0 whose identifiers include `id`, if any. fn extraAddressedBy(c: *Connection, id: []const u8) ?*ExtraPath { for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.issued.accepts(id)) return extra; } return null; } fn anyExtraOpen(c: *const Connection) bool { for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state == .open) return true; } return false; } /// A packet arrived on a path past path 0. /// /// On a server, the first one is the client opening the path. §3.1: "if /// the server decides to use the new path, the server MUST validate the /// peer's address before sending any data", which is §8.2's challenge on the /// 4-tuple the packet came over -- and until it is answered, §21.1.1.1's /// three-times limit governs what goes back, exactly as for a migration. fn onPathPacket(c: *Connection, extra: *ExtraPath, route: paths_mod.Id, now: recovery.Instant) Error!void { if (extra.state != .unused) return; if (c.role == .client) return; // only a client opens paths, and it did extra.state = .open; extra.route = route; extra.measured_route = route; c.paths_opened += 1; if (c.paths.find(route)) |seen| { if (seen.validated or seen.challenge != null) return; } const rng = c.id_rng orelse return; _ = c.paths.challenge(route, rng, now) catch return error.TooManyPaths; } /// draft-ietf-quic-multipath-21 §3.1: opens a new multipath path over the /// caller's path `route`, returning the path ID chosen. /// /// Only a client opens paths (§3: "this extension only enables clients to /// open a new path"), and only on a path ID for which both ends have issued /// an identifier -- "the client can open a new path when both endpoints have /// issued available connection IDs for at least one unused, common path /// ID". The lowest such ID is taken, which is §3.2.1's "consume path IDs in a /// continuous way". The new path is validated before anything but probing /// goes on it: a PATH_CHALLENGE is owed on `route`, and the answer comes /// back on the same path ID. /// /// `error.NotAllowed` on a server, before the handshake is complete, when /// multipath was not negotiated, or with no `Options.rng`; /// `error.NoPathAvailable` when no path ID is both free and supplied with /// identifiers, in which case the peer is told what is missing (§4.7); /// `error.TooManyPaths` when the table of routes is full. pub fn openPath(c: *Connection, route: paths_mod.Id, now: recovery.Instant) error{ NotAllowed, NoPathAvailable, TooManyPaths }!u32 { if (c.role != .client or !c.multipathNegotiated() or !c.isEstablished()) return error.NotAllowed; const peer_max = @max(c.peer.?.initial_max_path_id.?, c.peer_max_path_id); for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .unused or extra.id > peer_max) continue; if (extra.received.current() == null or extra.issued.active() == 0) continue; const rng = c.id_rng orelse return error.NotAllowed; extra.state = .open; extra.route = route; extra.measured_route = route; c.paths_opened += 1; const seen = c.paths.observe(route) catch return error.TooManyPaths; // Chosen by this endpoint, so §21.1.1.1's limit on answering an // unknown address does not apply to it -- see `Path.chosen`. seen.chosen = true; _ = c.paths.challenge(route, rng, now) catch return error.TooManyPaths; return extra.id; } c.noteBlocked(peer_max); return error.NoPathAvailable; } test openPath { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); // Route 1 is the caller's name for a second 4-tuple; path ID 1 is the // protocol's, the lowest both ends have identifiers for. try testing.expectEqual(@as(u32, 1), try p.client.openPath(1, p.now)); try p.settle(); try testing.expect(p.client.pathValidated(1)); try testing.expect(p.server.pathValidated(1)); // The storage has room for one path besides path 0, and it is taken. try testing.expectError(error.NoPathAvailable, p.client.openPath(2, p.now)); try testing.expectError(error.NotAllowed, p.server.openPath(2, p.now)); } /// §4.7: why `openPath` found nothing, told to the peer if the peer is the /// reason. PATHS_BLOCKED when a slot is free but its path ID is past the /// peer's limit; PATH_CIDS_BLOCKED when the path ID is allowed but the peer /// has issued no identifier for it. Each is said once for a given limit or /// sequence number: "if the successful reception of a /// PATHS_BLOCKED/PATH_CIDS_BLOCKED frame was acknowledged but no action is /// taken by the peer, this is likely a deliberate decision by the peer and /// repeating the... frame will not change that." fn noteBlocked(c: *Connection, peer_max: u64) void { const limit = @min(c.localMaxPathId(), peer_max); var past_limit = false; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .unused) continue; if (extra.id > peer_max) { if (extra.id <= c.localMaxPathId()) past_limit = true; continue; } if (extra.id > limit or extra.received.current() != null) continue; const next = extra.received.next_sequence; if (extra.cids_blocked_sent != next) extra.cids_blocked_owed = true; return; } if (past_limit and c.paths_blocked_sent != peer_max) c.paths_blocked_owed = peer_max; } /// draft-ietf-quic-multipath-21 §3.3: tells the peer how this endpoint would /// like path `id` used -- `.backup` asks that "no traffic should be sent on /// that path if another path is available and usable". Any path up to the /// limit may be named, "even if the path is not in active use yet". /// /// The PATH_STATUS frame goes out with a later `send`, and the peer reads it /// with `peerPathStatus`. `error.NotAllowed` when multipath was not /// negotiated, or `id` is past the peer's limit, abandoned, or beyond what /// this connection's memory has room for. pub fn setPathStatus(c: *Connection, id: u32, status: frame.PathStatus.Status) error{NotAllowed}!void { if (!c.multipathNegotiated()) return error.NotAllowed; // The peer holds the frame to its own limit, which is this end's // `peer_max_path_id`. if (id > @max(c.peer.?.initial_max_path_id.?, c.peer_max_path_id)) return error.NotAllowed; if (id == 0 and c.path0_abandoned) return error.NotAllowed; if (id != 0) { const extra = c.extraFor(id) orelse return error.NotAllowed; if (extra.state == .abandoned) return error.NotAllowed; } const state = c.statusFor(id).?; state.local = status; state.owed = true; } test setPathStatus { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); _ = try p.client.openPath(1, p.now); try p.settle(); // The client would rather keep path 1 for when path 0 fails. try p.client.setPathStatus(1, .backup); try p.settle(); try testing.expectEqual(frame.PathStatus.Status.backup, p.server.peerPathStatus(1).?); // Past the server's initial_max_path_id of 1. try testing.expectError(error.NotAllowed, p.client.setPathStatus(2, .available)); } /// §3.3: the status the peer last advertised for path `id`, or null if it /// has said nothing about it -- in which case "the preference of the peer /// is unknown". pub fn peerPathStatus(c: *Connection, id: u32) ?frame.PathStatus.Status { const state = c.statusFor(id) orelse return null; return state.peer; } test peerPathStatus { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); try testing.expectEqual(@as(?frame.PathStatus.Status, null), p.client.peerPathStatus(0)); try p.server.setPathStatus(0, .available); try p.settle(); try testing.expectEqual(frame.PathStatus.Status.available, p.client.peerPathStatus(0).?); } /// n0's NAT traversal: a probe to the next candidate address that is due. /// /// A 1-RTT packet holding one PATH_CHALLENGE and nothing else, numbered, /// addressed and sealed as a packet of an existing path -- path 0, or the /// first open path past it when path 0 is gone -- and sent to the /// candidate instead of that path's peer. It opens no path and is not /// padded: all it has to show is that the address can be reached, and a /// probe is expected to be lost more often than not. And, as in noq, it is /// not tracked: nothing is recovered when it is lost, since `nat.State`'s /// retry timer is what sends the next, and it counts against no congestion /// window, since it does not travel the path whose window that is. An /// acknowledgement of its packet number finds nothing to acknowledge. /// /// Only after the handshake is confirmed, before which noq drops a probe. fn sendNatProbe(c: *Connection, out: []u8) ?Datagram { const state = if (c.nat) |*n| n else return null; if (!c.confirmed) return null; const to = state.nextProbe() orelse return null; const rng = c.id_rng orelse return null; const keys = if (c.spaces[2].write) |*k| k else return null; const carrier = c.natCarrier() orelse return null; var token: [paths_mod.challenge_len]u8 = undefined; rng.bytes(&token); var b = packet.Builder.initShort(out, carrier.addressed_to, carrier.numbering.next_number, 4, c.key_phase) catch return null; b.add(.{ .path_challenge = &token }) catch return null; c.grease(&b); const wire = b.finishOn(keys, carrier.nonce_path) catch return null; carrier.numbering.next_number += 1; c.packets_encrypted +|= 1; state.sentProbe(to, token); return .{ .path = carrier.route, .bytes = wire, .to = to }; } /// The path a NAT traversal probe or answer is numbered and sealed on: /// path 0, or the first usable path past it when path 0 is gone. const NatCarrier = struct { numbering: *SpaceState, addressed_to: []const u8, nonce_path: u32, route: paths_mod.Id, }; fn natCarrier(c: *Connection) ?NatCarrier { if (!c.path0_abandoned) return .{ .numbering = &c.spaces[2], .addressed_to = c.peerId(), .nonce_path = 0, .route = c.paths.active, }; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (!c.usablePath(extra.id)) continue; return .{ .numbering = &extra.space, .addressed_to = extra.received.current().?, .nonce_path = extra.id, .route = extra.route, }; } return null; } /// A PATH_RESPONSE owed on a path of path 0's that is not the active one, /// alone but for any challenge due there. /// /// §9.1 lets an endpoint answer on a path it is not using, and §9.2 is /// what it must not do there: "an endpoint migrates to a new path by /// sending packets containing non-probing frames from that address." An ACK /// or stream data beside the response would be exactly that -- and when /// the peer is challenging the path this endpoint left (§9.3.3), it would /// take the connection back there, to be challenged on the other, and so /// on for ever. fn sendResponseAway(c: *Connection, out: []u8, now: recovery.Instant) ?Datagram { const owed = c.paths.nextOwed() orelse return null; if (owed.path == c.paths.active or c.extraOnRoute(owed.path) != null) return null; const size = @min(out.len, min_initial_datagram, c.paths.sendable(owed.path)); if (size == 0) return null; return c.sendProbeAlone(out[0..size], null, owed.path, now); } /// n0's NAT traversal: the answer to a probe that came from an address no /// path runs over, as a datagram of its own. /// /// Its own, and holding nothing but the PATH_RESPONSE: an ACK or anything /// else in the same packet would make it a non-probing packet from a new /// address, which the peer would take for this end migrating there (§9.3) /// -- and a hole found by a probe is a path to be opened beside the old /// one, not a reason to leave it. Padded as far as §8.2.2 and the /// amplification limit allow, and, as in noq, not tracked. /// /// A client adds a PATH_CHALLENGE of its own. Its probe to the server may /// never have got through the server's NAT; this one goes out through the /// hole the server's probe has just made, and the answer to it is what /// tells the client the hole is there. fn sendNatAnswer(c: *Connection, out: []u8) ?Datagram { const state = if (c.nat) |*n| n else return null; const owed = c.paths.nextOwed() orelse return null; if (c.routeCarriesPath(owed.path)) return null; const carrier = c.natCarrier() orelse return null; const keys = if (c.spaces[2].write) |*k| k else return null; const size = @min(out.len, c.paths.sendable(owed.path), min_initial_datagram); var b = packet.Builder.initShort(out[0..size], carrier.addressed_to, carrier.numbering.next_number, 4, c.key_phase) catch return null; b.add(.{ .path_response = &owed.data }) catch return null; if (c.role == .client) { if (c.paths.find(owed.path)) |seen| { if (!seen.validated) if (seen.peer_address) |address| if (c.id_rng) |rng| { var token: [paths_mod.challenge_len]u8 = undefined; rng.bytes(&token); if (b.add(.{ .path_challenge = &token })) |_| { state.recordChallenge(token, address); } else |_| {} }; } } b.padTo(size) catch {}; c.grease(&b); const wire = b.finishOn(keys, carrier.nonce_path) catch return null; c.paths.sentResponse(owed.data); carrier.numbering.next_number += 1; c.packets_encrypted +|= 1; if (c.paths.find(owed.path)) |seen| seen.sent +|= wire.len; return .{ .path = owed.path, .bytes = wire }; } /// A PATH_CHALLENGE or PATH_RESPONSE owed on `destination`, alone in a /// packet, when §21.1.1.1's allowance is too small for anything more. /// /// Three times a peer's smallest packet is less than `min_packet_room`, so /// a peer that moved with a packet holding a few octets of data, or only an /// ACK, would otherwise not be challenged until its probe timeout had sent /// more. The two frames are a few dozen octets with their header, and §8.2.1 /// pads them to 1200 only where "the anti-amplification limit for the path" /// permits it. Padded to the allowance and, like `sendNatAnswer`'s, not /// tracked: a lost challenge is lost either way, and a response is only /// ever owed once. fn sendProbeAlone(c: *Connection, out: []u8, target: ?*ExtraPath, destination: paths_mod.Id, now: recovery.Instant) ?Datagram { const keys = if (c.spaces[2].write) |*k| k else return null; const seen = c.paths.find(destination) orelse return null; const owed: ?paths_mod.Paths.Owed = if (c.paths.nextOwed()) |o| (if (o.path == destination) o else null) else null; const challenge: ?[paths_mod.challenge_len]u8 = if (seen.sent_challenge) null else seen.challenge; if (owed == null and challenge == null) return null; const numbering: *SpaceState = if (target) |t| &t.space else &c.spaces[2]; const addressed_to: []const u8 = if (target) |t| t.received.current().? else c.peerId(); var b = packet.Builder.initShort(out, addressed_to, numbering.next_number, 4, c.key_phase) catch return null; if (owed) |o| b.add(.{ .path_response = &o.data }) catch return null; if (challenge) |data| b.add(.{ .path_challenge = &data }) catch return null; b.padTo(out.len) catch {}; c.grease(&b); const wire = b.finishOn(keys, if (target) |t| t.id else 0) catch return null; if (owed) |o| c.paths.sentResponse(o.data); if (challenge != null) { seen.sent_challenge = true; seen.challenge_short = wire.len < min_initial_datagram; seen.challenge_sent_at = now; } numbering.next_number += 1; c.packets_encrypted +|= 1; seen.sent +|= wire.len; return .{ .path = destination, .bytes = wire }; } /// Whether an ADD_ADDRESS, REMOVE_ADDRESS or REACH_OUT is owed. fn natOwesFrame(c: *const Connection) bool { const state = c.nat orelse return false; return state.owedAdd() != null or state.owedRemove() != null or state.owedReach() != null; } /// Notes that a probe was answered over `route`, for `openNatPaths`. fn queueNatOpen(c: *Connection, route: paths_mod.Id) void { for (&c.nat_opens) |slot| if (slot == route) return; for (&c.nat_opens) |*slot| { if (slot.* == null) { slot.* = route; return; } } } /// n0's NAT traversal, the client's part after a probe is answered: a /// multipath path over the route it came by, marked backup -- noq opens it /// so -- unless a path already runs there. One that cannot be opened for /// want of a path ID or an identifier stays queued and is tried again on /// the next send, which is after whatever MAX_PATH_ID or /// PATH_NEW_CONNECTION_ID has arrived. fn openNatPaths(c: *Connection, now: recovery.Instant) void { if (c.role != .client) return; for (&c.nat_opens) |*slot| { const route = slot.* orelse continue; if (c.routeCarriesPath(route)) { slot.* = null; continue; } const id = c.openPath(route, now) catch |err| switch (err) { error.NoPathAvailable => continue, else => { slot.* = null; continue; }, }; c.setPathStatus(id, .backup) catch {}; slot.* = null; } } /// Whether the caller's route `route` still means anything to this /// connection: the route in use, one a path past path 0 runs over, one /// being validated or owed an answer, or one waiting to become a NAT /// traversal path. A route that is none of these can be forgotten and its /// number given to another address -- which a caller with a fixed table of /// addresses has to do once NAT traversal has it hearing from candidates. pub fn routeInUse(c: *Connection, route: paths_mod.Id) bool { if (route == c.paths.active) return true; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .unused and extra.route == route) return true; } for (c.nat_opens) |slot| if (slot == route) return true; for (c.paths.owed) |slot| if (slot) |owed| if (owed.path == route) return true; const seen = c.paths.find(route) orelse return false; return seen.challenge != null and !seen.validated; } test routeInUse { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expect(p.client.routeInUse(0)); try testing.expect(!p.client.routeInUse(1)); // Once the connection has moved to route 1, route 0 is history. try p.client.migrateTo(1, p.now); try p.settle(); try testing.expect(p.client.routeInUse(1)); try testing.expect(!p.client.routeInUse(0)); } /// Forgets route `route`, so that its number can name another address. /// /// Does nothing to a route `routeInUse` says is still in use, so a caller /// can call it on any route it wants back without asking first. pub fn forgetRoute(c: *Connection, route: paths_mod.Id) void { if (c.routeInUse(route)) return; c.paths.forget(route); } test forgetRoute { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try p.client.migrateTo(1, p.now); try p.settle(); // Route 0 is no longer used, and forgetting it forgets that it was // validated: the number may now name some other address. try testing.expect(p.client.pathValidated(0)); p.client.forgetRoute(0); try testing.expect(!p.client.pathValidated(0)); // The route in use is not forgotten. p.client.forgetRoute(1); try testing.expect(p.client.pathValidated(1)); } /// Whether a path that is not abandoned already runs over `route`. fn routeCarriesPath(c: *const Connection, route: paths_mod.Id) bool { if (!c.path0_abandoned and c.paths.active == route) return true; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state == .open and extra.route == route) return true; } return false; } /// n0's NAT traversal: whether both ends asked for it with multipath in use. pub fn natNegotiated(c: *const Connection) bool { return c.nat != null; } test natNegotiated { const p = try TestPair.connect(test_nat_limits, test_nat_limits); defer p.destroy(); try testing.expect(p.client.natNegotiated() and p.server.natNegotiated()); // Without multipath there is nothing for it to open paths with. var no_multipath = test_limits; no_multipath.n0_nat_traversal = 8; const q = try TestPair.connect(no_multipath, no_multipath); defer q.destroy(); try testing.expect(!q.client.natNegotiated()); } /// n0's NAT traversal: offers one of this endpoint's addresses. A server /// advertises it with ADD_ADDRESS at once; a client sends it in REACH_OUT /// when it next starts a round. No more than the peer said it would take, /// which is `error.TooManyAddresses`. pub fn addNatAddress(c: *Connection, address: frame.Address) error{ NotNegotiated, TooManyAddresses }!void { const state = if (c.nat) |*n| n else return error.NotNegotiated; try state.addLocal(address); } test addNatAddress { const p = try TestPair.connect(test_nat_limits, test_nat_limits); defer p.destroy(); // The server's address on a second network, as its caller knows it. try p.server.addNatAddress(.{ .ip = .{ .v4 = .{ 10, 0, 2, 1 } }, .port = 443 }); try p.settle(); try testing.expectEqual(@as(usize, 1), p.client.natRemoteCount()); } /// Withdraws an address `addNatAddress` offered. A server says so with /// REMOVE_ADDRESS; a client simply leaves it out of the next round. /// Withdrawing one never offered changes nothing. pub fn removeNatAddress(c: *Connection, address: frame.Address) error{NotNegotiated}!void { const state = if (c.nat) |*n| n else return error.NotNegotiated; state.removeLocal(address); } test removeNatAddress { const p = try TestPair.connect(test_nat_limits, test_nat_limits); defer p.destroy(); const address: frame.Address = .{ .ip = .{ .v4 = .{ 10, 0, 2, 1 } }, .port = 443 }; try p.server.addNatAddress(address); try p.settle(); try p.server.removeNatAddress(address); try p.settle(); try testing.expectEqual(@as(usize, 0), p.client.natRemoteCount()); } /// The client starts a round of hole punching: each of its addresses goes to /// the server in REACH_OUT, and each of the server's is probed. What comes /// of it is a path, opened by `openPath` when a probe is answered. /// /// `error.NoLocalAddresses` when the client has offered none with /// `addNatAddress`, since a round with nothing to reach out from is no /// round at all. pub fn startNatRound(c: *Connection, now: recovery.Instant) error{ NotNegotiated, NotClient, NoLocalAddresses }!void { const state = if (c.nat) |*n| n else return error.NotNegotiated; if (c.role != .client) return error.NotClient; try state.startRound(now); } test startNatRound { const p = try TestPair.connect(test_nat_limits, test_nat_limits); defer p.destroy(); try testing.expectError(error.NoLocalAddresses, p.client.startNatRound(p.now)); try testing.expectError(error.NotClient, p.server.startNatRound(p.now)); try p.client.addNatAddress(.{ .ip = .{ .v4 = .{ 10, 0, 2, 7 } }, .port = 40001 }); try p.client.startNatRound(p.now); // The REACH_OUT is waiting to go. try testing.expect((try p.client.send(&p.buffer, p.now)) != null); } /// How many of the peer's candidate addresses this endpoint holds: the /// server's, on a client, or the current round's, on a server. pub fn natRemoteCount(c: *const Connection) usize { const state = c.nat orelse return 0; return state.remoteCount(); } test natRemoteCount { const p = try TestPair.connect(test_nat_limits, test_nat_limits); defer p.destroy(); try testing.expectEqual(@as(usize, 0), p.client.natRemoteCount()); try p.server.addNatAddress(.{ .ip = .{ .v4 = .{ 10, 0, 2, 1 } }, .port = 443 }); try p.server.addNatAddress(.{ .ip = .{ .v4 = .{ 10, 0, 3, 1 } }, .port = 443 }); try p.settle(); try testing.expectEqual(@as(usize, 2), p.client.natRemoteCount()); } /// A path whose PATH_STATUS is owed, if one is. fn owesPathStatus(c: *Connection) ?u32 { if (c.path0_status.owed) return 0; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.status.owed and extra.state != .abandoned) return extra.id; } return null; } /// A path whose PATH_CIDS_BLOCKED is owed, if one is. fn owesCidsBlocked(c: *Connection) ?*ExtraPath { for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.cids_blocked_owed) return extra; } return null; } /// Chooses multipath path `id` for new data rather than path 0, once it has /// been validated. /// /// §5.5 leaves scheduling to the implementation. Under the default /// `Scheduler.chosen` everything new goes on the path chosen here -- unless /// the peer has marked it backup or it stops being usable, when another /// path stands in until it is usable again -- and acknowledgements for every /// path go on whichever path a packet is leaving by. Under /// `Scheduler.lowest_rtt` the choice is overridden packet by packet, and /// matters only when no path has room. /// /// Path 0 can always be chosen. `error.NotAllowed` for any other path that /// is not open and validated. pub fn useSendPath(c: *Connection, id: u32) error{NotAllowed}!void { if (id == 0) { c.send_path = 0; return; } const extra = c.extraFor(id) orelse return error.NotAllowed; if (extra.state != .open) return error.NotAllowed; const seen = c.paths.find(extra.route) orelse return error.NotAllowed; if (!seen.validated) return error.NotAllowed; c.send_path = id; } test useSendPath { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); const path = try p.client.openPath(1, p.now); // Not until the new path has answered its challenge. try testing.expectError(error.NotAllowed, p.client.useSendPath(path)); try p.settle(); try p.client.useSendPath(path); // New data now leaves by route 1, the 4-tuple path 1 runs over. const id = try p.client.openBidirectional(); try p.client.write(id, "over path 1"); const datagram = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(paths_mod.Id, 1), datagram.path); try p.server.receive(datagram.bytes, datagram.path, p.now); try testing.expectEqualStrings("over path 1", p.server.readable(id)); } /// §3.4: abandons a path past path 0, whichever end decided to. When it /// was the peer, "it MUST send a corresponding PATH_ABANDON frame, if it has /// not already done so", which is the same PATH_ABANDON either way. fn abandon(c: *Connection, extra: *ExtraPath) void { if (extra.state == .abandoned) return; extra.state = .abandoned; if (!extra.sent_abandon) extra.owes_abandon = true; // "Endpoints that send a PATH_ABANDON frame MUST treat all connection IDs // received from the peer for the path ID indicated in the PATH_ABANDON as // immediately retired, and subsequently cannot send any packet on that // path anymore." extra.received = .{}; if (c.send_path == extra.id) c.send_path = 0; c.giveUpInFlight(&extra.space, &extra.congestion); } /// §3.4 for path 0: nothing more is sent on it, and new data moves to a path /// that is still open. fn abandonZero(c: *Connection) void { if (c.path0_abandoned) return; c.path0_abandoned = true; if (c.send_path == 0) { for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state == .open) { c.send_path = extra.id; break; } } } c.giveUpInFlight(&c.spaces[2], &c.congestion); } /// What is in flight on a path that nothing more will be sent on. /// /// §3.4.3: "when an endpoint finally deletes all state associated with the /// path, the packets sent over the path and not yet acknowledged MUST be /// considered lost". This does it at the moment the path is abandoned rather /// than 3 PTO later: nothing is sent on the path after that, so its loss /// timers would never be answered, and whatever those packets carried -- /// stream data, most of all -- would sit waiting for an acknowledgement that /// might never come instead of going out again on a path that works. A late /// PATH_ACK for one of them finds nothing, which costs a duplicate at most. fn giveUpInFlight(c: *Connection, space: *SpaceState, congestion: *Congestion) void { const unacked = space.loss.unacked(); congestion.onDiscarded(unacked); for (unacked) |sent| c.recover(space, sent); space.loss.reset(); } /// §3.4: an abandoned path's state is let go of, and its slot becomes a /// path ID that has never been used -- "the path ID MUST NOT be reused for /// new paths, as the path ID is part of the nonce calculation". The limit /// this endpoint allows its peer goes up by one with it, which a MAX_PATH_ID /// announces, so a connection that closes paths can go on opening new ones. fn release(c: *Connection, extra: *ExtraPath) void { // The 4-tuple goes too, unless another path runs over it. const route = extra.route; var shared = !c.path0_abandoned and c.paths.active == route; for (c.extra[0 .. c.path_limit - 1]) |*other| { if (other != extra and other.state != .unused and other.route == route) shared = true; } if (!shared) c.paths.forget(route); const storage = extra.space.loss.sent; const len = extra.issued.len; extra.* = .{}; extra.space.loss.init(storage); extra.issued.len = len; // "MUST NOT exceed 2^32-1": a connection that has used them all keeps the // slot, abandoned and without a timer, for good. if (c.next_path_id > parameters.max_path_id) { extra.state = .abandoned; return; } extra.id = @intCast(c.next_path_id); c.next_path_id += 1; if (c.multipathNegotiated() and c.local_max_path_id < parameters.max_path_id) { c.local_max_path_id += 1; c.max_path_id_owed = true; } } /// Abandons multipath path `id`, telling the peer with PATH_ABANDON. /// /// Path 0 can be abandoned too, while another path is open -- §3.4 puts no /// path above the others -- after which everything goes on the paths left. /// /// `error.NotAllowed` for a path that is not open, and for path 0 when /// multipath was not negotiated or it is the only path left. pub fn abandonPath(c: *Connection, id: u32) error{NotAllowed}!void { if (id == 0) { if (!c.multipathNegotiated() or !c.anyExtraOpen() or c.path0_abandoned) return error.NotAllowed; c.path0_owes_abandon = true; c.abandonZero(); return; } const extra = c.extraFor(id) orelse return error.NotAllowed; if (extra.state != .open) return error.NotAllowed; c.abandon(extra); } test abandonPath { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); // The only path cannot be given up. try testing.expectError(error.NotAllowed, p.client.abandonPath(0)); const path = try p.client.openPath(1, p.now); try p.settle(); try p.client.abandonPath(path); try p.settle(); try testing.expectError(error.NotAllowed, p.client.useSendPath(path)); // Path 0 carries on. const id = try p.client.openBidirectional(); try p.client.write(id, "still here"); try p.settle(); try testing.expectEqualStrings("still here", p.server.readable(id)); } /// A lost PATH_NEW_CONNECTION_ID to send again, if one is. fn owedPathOffer(c: *Connection) ?recovery.PathOffer { for (c.extra[0 .. c.path_limit - 1]) |*extra| { const sequence = extra.offer_owed orelse continue; return .{ .path = extra.id, .sequence = sequence }; } return null; } /// The entry for `sequence` in `issued`, while it is still in use. /// An identifier this endpoint issued whose NEW_CONNECTION_ID was lost and /// has not gone again yet. fn idToResend(c: *Connection) ?*ids.Entry { for (&c.issued.entries) |*entry| { if (entry.in_use and entry.resend) return entry; } return null; } fn issuedEntry(issued: *ids.Issued, sequence: u64) ?*const ids.Entry { for (&issued.entries) |*entry| { if (entry.in_use and entry.sequence == sequence) return entry; } return null; } /// A path whose PATH_ABANDON has not gone out yet. fn owesAbandon(c: *Connection) ?*ExtraPath { for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.owes_abandon) return extra; } return null; } /// The path past path 0 whose identifier the peer is owed, if any: one per /// path the two ends' limits allow, §3.2.1's "proactively issue at least one /// Connection ID for each unused path ID up to the minimum of the peer's and /// the local maximum path ID limits". fn owesPathId(c: *Connection) ?*ExtraPath { if (!c.multipathNegotiated()) return null; const peer_max = @max(c.peer.?.initial_max_path_id.?, c.peer_max_path_id); const limit = @min(c.localMaxPathId(), peer_max); for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.id > limit or extra.state == .abandoned) continue; if (extra.issued.active() == 0) return extra; } return null; } /// Issues one identifier for a path past path 0, with its reset token. fn issuePathId(c: *Connection, extra: *ExtraPath) ?*const ids.Entry { const rng = c.id_rng orelse return null; var id: [ids.max_len]u8 = undefined; rng.bytes(id[0..extra.issued.len]); var token: [ids.token_len]u8 = undefined; if (c.reset_key) |key| { token = reset.token(key, id[0..extra.issued.len]); } else { rng.bytes(&token); } const sequence = extra.issued.add(id[0..extra.issued.len], token) catch return null; for (&extra.issued.entries) |*entry| { if (entry.in_use and entry.sequence == sequence) return entry; } return null; } /// draft-ietf-quic-address-discovery-01: tells the connection where the /// peer's datagrams on `path` come from. /// /// The library has no sockets and so no addresses of its own; this is how an /// endpoint that offered to provide address observations learns what to /// report. Called for every datagram, cheaply -- only an address that is new /// for the path owes a report, which is §5's "every new path" and its "when /// it detects a change in the remote address on an existing path" in one. pub fn setPeerAddress(c: *Connection, path: paths_mod.Id, address: frame.Address) error{TooManyPaths}!void { const seen = c.paths.observe(path) catch return error.TooManyPaths; if (seen.peer_address) |known| if (known.eql(address)) return; seen.peer_address = address; seen.observation_owed = true; } test setPeerAddress { var limits = test_limits; limits.address_discovery = .both; const p = try TestPair.create(limits, limits); defer p.destroy(); // Each end's caller says where the other's datagrams come from. const client_seen_at: frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 40001 }; const server_seen_at: frame.Address = .{ .ip = .{ .v4 = .{ 203, 0, 113, 9 } }, .port = 853 }; try p.server.setPeerAddress(0, client_seen_at); try p.client.setPeerAddress(0, server_seen_at); try p.handshake(); try p.settle(); // And each end learns the other's view of it. try testing.expect(p.client.observedAddress().?.eql(client_seen_at)); try testing.expect(p.server.observedAddress().?.eql(server_seen_at)); } /// Tells the connection which of this endpoint's addresses `path` uses. /// /// Optional, and read only by RFC 9000 §9.4: a peer that moves is a new /// path, and the congestion controller, round-trip estimate and PMTU start /// again on it -- unless "the only change in the peer's address is its port /// number", which is a NAT rebinding far more often than anything else, and /// then they are kept. Telling that apart needs both ends of both paths, so /// the exception applies only once this and `setPeerAddress` have been /// called for the old path and the new one; until then every move starts /// again, which is never wrong, only slower. /// /// `quic_io` calls it for every datagram that arrives on a socket bound to /// one address, and never for one bound to the unspecified address, which /// cannot say which of the host's addresses a datagram was sent to. pub fn setLocalAddress(c: *Connection, path: paths_mod.Id, address: frame.Address) error{TooManyPaths}!void { const seen = c.paths.observe(path) catch return error.TooManyPaths; seen.local_address = address; } /// draft-ietf-quic-address-discovery-01: the address the peer last reported /// seeing this endpoint at, on the path packets are sent on -- or null if it /// has reported nothing, which it does only when this endpoint asked. /// /// §6.1: "nodes cannot be trusted to report the correct address". This is /// the peer's word, authenticated as coming from the peer and no further. pub fn observedAddress(c: *Connection) ?frame.Address { const seen = c.paths.find(c.paths.active) orelse return null; return seen.observed; } test observedAddress { // The client only receives reports and the server only provides them. var client_limits = test_limits; client_limits.address_discovery = .receive; var server_limits = test_limits; server_limits.address_discovery = .provide; const p = try TestPair.create(client_limits, server_limits); defer p.destroy(); const client_seen_at: frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 40001 }; try p.server.setPeerAddress(0, client_seen_at); try p.client.setPeerAddress(0, .{ .ip = .{ .v4 = .{ 203, 0, 113, 9 } }, .port = 853 }); try p.handshake(); try p.settle(); // The client is behind a NAT, and now knows what it looks like outside. try testing.expect(p.client.observedAddress().?.eql(client_seen_at)); try testing.expectEqual(@as(?frame.Address, null), p.server.observedAddress()); } /// The address to report on `path`, if a report is owed there and the two /// ends' roles allow one. fn owesObservation(c: *Connection, path: paths_mod.Id) ?frame.Address { const peer = c.peer orelse return null; if (!parameters.AddressDiscovery.reportsTo(c.local.address_discovery, peer.address_discovery)) return null; const seen = c.paths.find(path) orelse return null; if (!seen.observation_owed) return null; return seen.peer_address; } /// RFC 9287: how many authenticated packets have arrived with the QUIC Bit /// clear. Zero from a peer that does not grease, or from any peer when this /// endpoint did not advertise grease_quic_bit -- such packets are dropped /// before they could be counted. pub fn greasedPackets(c: *const Connection) u64 { return c.packets_greased; } test greasedPackets { var limits = test_limits; limits.grease_quic_bit = true; const p = try TestPair.connect(limits, limits); defer p.destroy(); // The QUIC Bit is cleared at random, so traffic enough to see it. const id = try p.client.openBidirectional(); for (0..32) |_| { try p.client.write(id, "grease"); p.now += 30 * std.time.ns_per_ms; try p.settle(); p.server.consume(id, p.server.readable(id).len); } try testing.expect(p.server.greasedPackets() > 0); // Without the parameter, none: such packets would not be read at all. const q = try TestPair.connect(test_limits, test_limits); defer q.destroy(); try testing.expectEqual(@as(u64, 0), q.server.greasedPackets()); } /// §20.1's code for one of this library's errors. /// /// Every connection error has a code, and choosing the right one is not /// decoration: a peer reads it to decide whether to retry, to report a bug, /// or to stop trying. PROTOCOL_VIOLATION is the catch-all §20.1 provides for /// "an error with protocol compliance that was not covered by more specific /// error codes", and reaching for it when a specific code exists tells the /// peer less than the truth. fn codeFor(c: *const Connection, err: Error) termination.Code { return switch (err) { error.FlowControlError => .flow_control_error, error.StreamLimitError => .stream_limit_error, error.StreamStateError => .stream_state_error, error.FinalSizeError => .final_size_error, error.TransportParameterError => .transport_parameter_error, error.VersionNegotiationError => .version_negotiation_error, error.FrameNotPermitted, error.ProtocolViolation => .protocol_violation, // §20.1: CRYPTO_ERROR carries the TLS alert the handshake would have // sent, which is how the peer learns that its certificate was refused // rather than merely that something went wrong. error.HandshakeFailed => if (c.handshake.alert()) |a| .crypto(a) else .crypto(80), // internal_error // Nothing the peer did: this endpoint ran out of room or could not // build a packet. §20.1's INTERNAL_ERROR is the honest answer. error.NoSpace, error.NoRoom, error.OutOfMemory => .internal_error, error.AeadLimitReached => .aead_limit_reached, error.ConnectionIdLimitError => .connection_id_limit_error, error.TooManyPaths => .internal_error, error.FrameEncodingError => .frame_encoding_error, error.WindowExceeded => .crypto_buffer_exceeded, error.OffsetTooLarge => .frame_encoding_error, }; } /// Ends the connection, saying why: §10.2's immediate close, with one of /// §20.1's transport error codes. /// /// The CONNECTION_CLOSE goes out on the next call to `send`, and after that /// this connection answers incoming packets by repeating it, ever less often /// (§10.2.1), and does nothing else. `timeout` then says when the closing /// state is over. `why` is copied, and cut short at 64 octets. Only the first /// close counts: a connection already closing or draining keeps the code it /// has. pub fn close(c: *Connection, code: termination.Code, why: []const u8, now: recovery.Instant) void { c.closing.close(code, null, why, c.closeDeadline(now)); } test close { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.client.close(.no_error, "done", p.now); try testing.expectEqual(termination.State.closing, p.client.closeState().?); try p.settle(); // The server heard it, and drains rather than answering. try testing.expectEqual(termination.State.draining, p.server.closeState().?); try testing.expectEqual(termination.Code.no_error, p.server.closing.code); try testing.expectEqualStrings("done", p.server.closing.reason()); } /// The same, for an application protocol's own error code — §19.19's 0x1d /// variant, whose codes belong to whatever is running over QUIC rather than /// to QUIC. pub fn closeApplication(c: *Connection, code: u64, why: []const u8, now: recovery.Instant) void { // `Closing.close` ignores every close after the first, and the variant // has to be ignored with it. if (c.closing.state != .open) return; c.closing.close(@fromBackingInt(@intCast(code)), null, why, c.closeDeadline(now)); c.closing.application = true; } test closeApplication { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); // HTTP/3's H3_NO_ERROR, which means nothing to QUIC itself. p.server.closeApplication(0x100, "", p.now); try p.settle(); try testing.expectEqual(termination.State.draining, p.client.closeState().?); try testing.expect(p.client.closing.application); try testing.expectEqual(@as(u64, 0x100), @backingInt(p.client.closing.code)); } test "an application close after a transport close leaves the transport close alone" { // Only the first close counts, and that has to include which kind it // was: a transport code sent in §19.19's application variant is a code // the peer reads as its application protocol's. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); p.client.close(.protocol_violation, "first", p.now); p.client.closeApplication(0x100, "second", p.now); try testing.expect(!p.client.closing.application); try testing.expectEqual(termination.Code.protocol_violation, p.client.closing.code); try p.settle(); try testing.expect(!p.server.closing.application); try testing.expectEqual(termination.Code.protocol_violation, p.server.closing.code); try testing.expectEqualStrings("first", p.server.closing.reason()); } /// §10.2: "These states SHOULD persist for at least three times the current /// PTO interval." The point of the wait is the packets already in flight, not /// anything either end still has to say. fn closeDeadline(c: *const Connection, now: recovery.Instant) recovery.Instant { // draft-ietf-quic-multipath-21 §2.6: with several paths, the closing // and draining states "SHOULD instead persist for at least three times // the largest PTO among all paths". return now +| (c.largestProbeTimeout() *| termination.close_timeout_multiplier); } /// How this connection ended, or null while it has not. /// /// `.closing` after this end closed it (§10.2.1) and `.draining` after the /// peer did (§10.2.2), both for as long as §10.2 says to wait; `.closed` /// once that wait is over or the idle timeout has fired (§10.1), at which /// point the caller may free the connection. pub fn closeState(c: *const Connection) ?termination.State { return if (c.closing.state == .open) null else c.closing.state; } test closeState { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); p.client.close(.no_error, "", p.now); try p.settle(); try testing.expectEqual(termination.State.closing, p.client.closeState().?); // Three probe timeouts later the wait is over. const until = p.client.timeout().?; p.client.onTimeout(until); try testing.expectEqual(termination.State.closed, p.client.closeState().?); } /// Puts everything one lost packet carried back where it came from. /// /// §13.3 of RFC 9000: QUIC does not retransmit packets, it retransmits the /// frames that were in them, in new packets with new numbers. So a lost /// CRYPTO frame's octets go back into that level's handshake stream and a /// lost STREAM frame's go back into the stream that produced them, and both /// leave again in frames numbered afresh — which is what keeps every /// acknowledgement unambiguous and is the property the whole of RFC 9002 /// rests on. /// /// Both ways a packet can be declared gone end up here: loss detection, which /// knows a later packet arrived, and the probe timeout, which knows only that /// nothing has. fn recover(c: *Connection, space: *SpaceState, sent: recovery.Sent) void { // §14.4: a PMTU probe that has not come back is the answer the search was // waiting for. Both ways a packet can be given up on lead here — loss // detection, which knows a later packet arrived, and the probe timeout, // which knows only that nothing has — and for a probe the second is the // usual one, because a probe too large for the path has nothing behind it // to overtake it. if (c.pmtuOf(space)) |search| { if (search.isProbe(sent.number)) search.lost(sent.number); } // CRYPTO belongs to its level, not to the path that numbered the packet: // a piece lost on a path past path 0 goes back into the application // level's stream, which is the one it came out of. c.cryptoHome(space).markLost(sent); // draft-ietf-quic-address-discovery-01 §4.1: a lost report is owed // again, on the path it was about -- if that path is still one this // connection knows. if (sent.observed_path) |id| { if (c.paths.find(id)) |seen| seen.observation_owed = true; } // draft-ietf-quic-multipath-21: a lost PATH_NEW_CONNECTION_ID goes again // while its identifier is still one the path uses, and a lost // PATH_ABANDON goes again, as §4.2 asks. if (sent.path_offer) |offer| { if (c.extraFor(offer.path)) |extra| { if (extra.state != .abandoned and issuedEntry(&extra.issued, offer.sequence) != null) { extra.offer_owed = offer.sequence; } } } if (sent.abandoned_path) |id| { if (id == 0) { c.path0_owes_abandon = true; } else if (c.extraFor(id)) |extra| { extra.owes_abandon = true; } } // §4.6: again only if no larger limit has been announced since; §4.3: // again only if it was the last status sent for the path. if (sent.max_path_id) |max| { if (max == c.local_max_path_id) c.max_path_id_owed = true; } // draft-ietf-quic-ack-frequency-14 §4: "the sender is encouraged to send // another ACK_FREQUENCY frame, unless an ACK_FREQUENCY frame with a // larger Sequence Number value has already been sent". if (sent.ack_frequency) |sequence| { if (c.ack_frequency_in_flight) |in_flight| if (in_flight.sequence == sequence) { c.ack_frequency_owed = true; }; } if (c.nat) |*state| { if (sent.nat_add) |sequence| state.lostAdd(sequence); if (sent.nat_remove) |sequence| state.lostRemove(sequence); if (sent.nat_reach) |r| state.lostReach(r.sequence, r.address); } if (sent.path_status) |status| { if (c.statusFor(status.path)) |state| { if (state.sent_sequence == status.sequence and state.local != null) state.owed = true; } } // §13.3: RESET_STREAM, STOP_SENDING and RETIRE_CONNECTION_ID are each // sent again, as long as there is still something for them to say. if (sent.reset_stream) |id| { if (c.find(id)) |entry| if (entry.has_send) entry.send.resetLost(); } if (sent.stop_sending) |id| { if (c.find(id)) |entry| if (entry.has_recv) entry.recv.stopLost(); } if (sent.retire_connection_id) |sequence| c.received.lostRetire(sequence); // §13.3: a BLOCKED frame "is sent if a packet containing the most recent // frame for a scope is lost, but only while the endpoint is blocked on // the corresponding limit" -- which is what the `owes` functions ask, // once they no longer think it said. if (sent.data_blocked) |maximum| { if (c.data_blocked_sent == maximum) c.data_blocked_sent = null; } if (sent.stream_data_blocked) |blocked| { if (c.find(blocked.stream)) |entry| if (entry.data_blocked_sent == blocked.maximum) { entry.data_blocked_sent = null; }; } if (sent.streams_blocked) |blocked| { const at = @backingInt(blocked.kind); if (c.streams_blocked_sent[at] == blocked.maximum) c.streams_blocked_sent[at] = null; } // §13.3: the same identifier again, while it is still one the peer may // use; HANDSHAKE_DONE again, until acknowledged; and the current limits // again, since "an updated value is sent" when the packet carrying the // last one is lost. if (sent.new_connection_id) |sequence| { for (&c.issued.entries) |*entry| { if (entry.in_use and entry.sequence == sequence) entry.resend = true; } } if (sent.handshake_done) c.owes_handshake_done = true; if (sent.flow_control) c.flow_control_lost = true; for (sent.max_streams, 0..) |carried, at| { if (carried) c.owes_max_streams[at] = true; } for (sent.streamRanges()) |range| { const entry = c.find(range.stream) orelse continue; entry.send.data.markLost(range.offset, range.len); // The end of a stream travels on the frame carrying its last octet // (§4.5), so a lost frame took the end with it and it has to be sent // again too. if (range.fin) entry.send.data.fin_sent = false; } } /// A packet this endpoint has stopped tracking because its table was full. /// /// Everything a lost packet needs, except the conclusion that the network /// lost it. Its bytes leave `bytes_in_flight`, because nothing will ever /// acknowledge a packet there is no record of, and whatever it carried is /// marked for sending again, because nothing will ever acknowledge that /// either. /// /// The second half is the one that was missing, and its absence was a /// deadlock rather than a slowdown. §13.3 has a retransmission carry the /// *contents* of a lost frame, so an octet stays held in its stream's send /// buffer until the peer says it arrived; a forgotten packet's octets were /// neither acknowledged nor queued to go again, so they stayed held for ever. /// `Outgoing.compact` frees the acknowledged prefix and nothing beyond it, so /// one such hole near the front pins the whole buffer, and the stream fills /// and never empties. What that looks like from outside is a connection that /// stops dead with an open congestion window, nothing in flight, and every /// thread asleep. /// /// The congestion window is deliberately untouched: §B.8's reduction answers /// evidence of congestion, and a table that overflowed is evidence about this /// endpoint's bookkeeping. fn forget(c: *Connection, space: *SpaceState, forgotten: recovery.Sent) void { c.forgetIn(space, &c.congestion, forgotten); } fn forgetIn(c: *Connection, space: *SpaceState, congestion: *Congestion, forgotten: recovery.Sent) void { congestion.onForgotten(forgotten); c.recover(space, forgotten); } /// The path past path 0 the next datagram is for, or null for path 0. /// /// In order: a PATH_RESPONSE owed on a path's 4-tuple goes on that path /// (§3.1: "it MUST be sent on the same path as used by the packet that /// contained the PATH_CHALLENGE... using a connection ID associated with the /// same path ID"); then a path whose PATH_CHALLENGE has not gone out yet; /// then the path the application chose for data, once it is usable. A path /// with no identifier from the peer cannot be addressed at all. fn sendTarget(c: *Connection) ?*ExtraPath { if (c.paths.nextOwed()) |owed| return c.extraOnRoute(owed.path); for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open or extra.received.current() == null) continue; const seen = c.paths.find(extra.route) orelse continue; if (seen.challenge != null and !seen.sent_challenge) return extra; } return c.extraFor(c.dataPath()); } /// draft-ietf-quic-multipath-21 §5.5: "a packet scheduler is needed to /// decide which path to use for sending the next packet, among those paths /// with an open congestion window... The scheduling is a local decision". pub const Scheduler = enum { /// Everything on the path chosen with `useSendPath`, unless the peer /// has marked it backup. Predictable, and what a connection that is not /// trying to aggregate paths wants. chosen, /// Each packet on the usable path with the lowest smoothed RTT whose /// congestion window has room -- so the fastest path carries what it /// can, and the others take the overflow. Paths the peer marked backup /// are used only if every path is. Stream data spread over paths /// arrives at the pace of the slowest one used (§5.5), which is the /// price of the extra capacity. lowest_rtt, }; /// Chooses how new data is spread over paths. `.chosen` until this says /// otherwise; without multipath there is one path and the choice is moot. pub fn setScheduler(c: *Connection, scheduler: Scheduler) void { c.scheduler = scheduler; } test setScheduler { const p = try TestPair.connect(test_multipath_limits, test_multipath_limits); defer p.destroy(); _ = try p.client.openPath(1, p.now); try p.settle(); // Aggregate both paths rather than keeping to one. p.client.setScheduler(.lowest_rtt); const id = try p.client.openBidirectional(); const body: [2048]u8 = @splat('m'); try p.client.write(id, &body); try p.settle(); try testing.expectEqual(@as(usize, 2048), p.server.readable(id).len); } /// The multipath path ID new data goes on. /// /// The one the application chose with `useSendPath`, unless it cannot be /// used or the peer has marked it backup. §3.3: PATH_STATUS_BACKUP "suggests /// that a path should only be used as backup, i.e., that no traffic should /// be sent on that path if another path is available and usable" -- so a /// usable path the peer has not marked backup is taken in its place, and the /// chosen one comes back as soon as the peer marks it available again. "If /// all established paths are indicated as backup paths, no guidance is /// provided", and the choice stands. fn dataPath(c: *Connection) u32 { if (c.scheduler == .lowest_rtt) { if (c.fastestWithRoom(false) orelse c.fastestWithRoom(true)) |id| return id; } if (c.usablePath(c.send_path) and !c.peerBackup(c.send_path)) return c.send_path; if (c.usablePath(0) and !c.peerBackup(0)) return 0; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (c.usablePath(extra.id) and !extra.status.peerBackup()) return extra.id; } if (c.usablePath(c.send_path)) return c.send_path; if (c.usablePath(0)) return 0; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (c.usablePath(extra.id)) return extra.id; } return 0; } /// draft-ietf-quic-multipath-21 §5.3: RFC 6356's linked increases across /// the paths data is spread over, or null when it is not spread. /// /// Only under `.lowest_rtt`, and only with two or more usable paths. RFC /// 6356 assumes every subflow carries data; under `.chosen` one path does, /// and coupling it to an idle one would slow the only path in use for the /// sake of fairness to traffic it is not competing with. fn linkedIncrease(c: *Connection) ?congestion_mod.Coupling { if (c.scheduler != .lowest_rtt) return null; var paths: [max_paths]congestion_mod.Coupling.Path = undefined; var len: usize = 0; if (c.usablePath(0)) { paths[len] = .{ .window = c.congestion.window, .rtt = c.rtt.smoothed }; len += 1; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (!c.usablePath(extra.id)) continue; paths[len] = .{ .window = extra.congestion.window, .rtt = extra.rtt.smoothed }; len += 1; } if (len < 2) return null; return congestion_mod.Coupling.linked(paths[0..len]); } /// The usable path with the lowest smoothed RTT whose congestion window and /// loss table have room, among those the peer has not marked backup -- or, /// with `backup`, among all of them, but only when every usable path is /// marked backup: a full non-backup path is still "available and usable", /// and waiting for it is what §3.3 asks. fn fastestWithRoom(c: *Connection, backup: bool) ?u32 { if (backup) { if (c.usablePath(0) and !c.peerBackup(0)) return null; for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (c.usablePath(extra.id) and !extra.status.peerBackup()) return null; } } var best: ?u32 = null; var best_rtt: recovery.Duration = std.math.maxInt(recovery.Duration); if (c.usablePath(0) and (backup or !c.peerBackup(0)) and c.congestion.available() > 0 and !c.spaces[2].loss.full()) { best = 0; best_rtt = c.rtt.smoothed; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (!c.usablePath(extra.id) or (!backup and extra.status.peerBackup())) continue; if (extra.congestion.available() == 0 or extra.space.loss.full()) continue; if (extra.rtt.smoothed < best_rtt) { best = extra.id; best_rtt = extra.rtt.smoothed; } } return best; } /// Whether new data can go on path `id`: it is open, the peer has given it /// an identifier, and -- past path 0 -- its 4-tuple has been validated. fn usablePath(c: *Connection, id: u32) bool { if (id == 0) return !c.path0_abandoned; const extra = c.extraFor(id) orelse return false; if (extra.state != .open or extra.received.current() == null) return false; const seen = c.paths.find(extra.route) orelse return false; return seen.validated; } fn peerBackup(c: *Connection, id: u32) bool { const state = c.statusFor(id) orelse return false; return state.peerBackup(); } /// The open path past path 0 that runs over the caller's path `route`. fn extraOnRoute(c: *Connection, route: paths_mod.Id) ?*ExtraPath { for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state == .open and extra.route == route and extra.received.current() != null) return extra; } return null; } /// Whether any path other than `except` has acknowledgements owed now -- /// or, with `due` false, waiting at all, which is enough to ride along in a /// packet that is going anyway. fn otherAcksOwed(c: *Connection, except: ?*ExtraPath, now: recovery.Instant, due: bool) bool { if (except != null) { if (c.ackOwed(&c.spaces[2].acks, now, due)) return true; } // §3.4.3: an abandoned path's packets are still acknowledged, "promptly", // for as long as its state is kept. for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (except == extra or extra.state == .unused) continue; if (c.ackOwed(&extra.space.acks, now, due)) return true; } return false; } /// Whether an application-level space's ACK is owed now (`due`), or merely /// waiting. draft-ietf-quic-ack-frequency-14 is what can make the two differ: /// without an ACK_FREQUENCY from the peer, anything waiting is due. fn ackOwed(c: *const Connection, acks: *const ack.Tracker, now: recovery.Instant, due: bool) bool { if (acks.isEmpty() or !acks.ack_eliciting_pending) return false; return !due or acks.due(now, c.ack_frequency); } /// §19.3's ACK Delay for `acks`, in this end's own `ack_delay_exponent`: /// how long its largest packet waited before this ACK. Once /// draft-ietf-quic-ack-frequency-14 has acknowledgements held back, that is /// no longer negligible, and a peer that took it for path delay would /// overestimate the RTT by it. fn ackDelayField(c: *const Connection, acks: *const ack.Tracker, now: recovery.Instant) u64 { const micros = acks.delaySince(now) / std.time.ns_per_us; return micros >> @intCast(@min(c.local.ack_delay_exponent, 20)); } /// Writes `numbering`'s acknowledgement into `b`: an ACK for path 0, a /// PATH_ACK for any other. fn addAck(b: *packet.Builder, numbering: *SpaceState, path: u32, delay: u64) Error!void { var buf: [512]u8 = undefined; const len = numbering.acks.writeAck(&buf, delay) catch return error.NoSpace; const parsed = frame.parse(buf[0..len]) catch unreachable; const f: frame.Frame = if (path == 0) parsed.frame else .{ .path_ack = .{ .path = path, .ack = parsed.frame.ack } }; b.add(f) catch return error.NoSpace; numbering.acks.sent(); } /// §10.1's effective idle timeout, in nanoseconds, or null if neither end /// asked for one. /// /// "Each endpoint advertises a max_idle_timeout, but the effective value at /// an endpoint is computed as the minimum of the two advertised values (or /// the sole advertised value, if only one endpoint advertises a non-zero /// value)." Zero is not a short timeout; it means the endpoint did not ask /// for one, which is why this is a minimum over the non-zero values rather /// than over both. fn idleTimeout(c: *const Connection) ?recovery.Duration { const mine = c.local.max_idle_timeout; const theirs = if (c.peer) |p| p.max_idle_timeout else 0; const chosen = if (mine == 0) theirs else if (theirs == 0) mine else @min(mine, theirs); if (chosen == 0) return null; // §10.1: "To avoid excessively small idle timeout periods, endpoints MUST // increase the idle timeout period to be at least three times the current // Probe Timeout. This allows for multiple PTOs to expire, and therefore // multiple probes to be sent and lost, prior to idle timeout." Without // this a connection on a slow path times out while its own retransmissions // are still in flight. const floor = c.largestProbeTimeout() *| 3; return @max(chosen *| std.time.ns_per_ms, floor); } /// When the caller should next call `onTimeout`, or null if nothing is /// waiting on a timer. /// /// The earliest of several. §6.2's two loss recovery timers: the loss timer, /// set when a packet is waiting on the time threshold rather than the packet /// threshold, and the probe timeout behind it -- the loss timer wins /// whenever it is armed, because it is the more informed of the two: it /// knows a later packet arrived, where the probe timeout knows only that /// nothing has. Beside them, §10.1's idle timeout, an acknowledgement held /// back under draft-ietf-quic-ack-frequency-14, the next round of NAT /// traversal probes, and the end of an abandoned path's grace period. Once /// the connection is closing or draining it is the end of that wait alone, /// and null once it is closed. /// /// Ask again after every `receive`, `send` and `onTimeout`: any of them can /// move it. pub fn timeout(c: *const Connection) ?recovery.Instant { // §10.2: once a connection is ending, the only thing left to wait for is // the end of the wait. if (c.closing.state != .open) { return if (c.closing.state == .closed) null else c.closing.deadline; } // The idle timer is always in the running: it is the one that fires when // nothing else is going to, and a connection with nothing outstanding has // no other timer at all. var earliest: ?recovery.Instant = null; if (c.idleTimeout()) |idle| earliest = c.last_activity +| idle; // draft-ietf-quic-multipath-21 §3.4: an abandoned path's state is kept // for a while and then let go of. for (c.extra[0 .. c.path_limit - 1]) |*extra| { const at = extra.discard_at orelse continue; if (earliest == null or at < earliest.?) earliest = at; } // n0's NAT traversal: the next round of probes. if (c.nat) |state| if (state.retry_at) |at| { if (earliest == null or at < earliest.?) earliest = at; }; // §8.2: a challenge to send again, or a validation to give up on. if (c.paths.validationDeadline(c.validationProbeTimeout())) |at| { if (earliest == null or at < earliest.?) earliest = at; } // draft-ietf-quic-ack-frequency-14: an ACK held back falls due. if (c.spaces[2].acks.deadline(c.ack_frequency)) |at| { if (earliest == null or at < earliest.?) earliest = at; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state == .unused) continue; const at = extra.space.acks.deadline(c.ack_frequency) orelse continue; if (earliest == null or at < earliest.?) earliest = at; } var loss_armed = false; for (&c.spaces, 0..) |*space, i| { if (c.discarded[i]) continue; const at = space.loss.lossTime(&c.rtt) orelse continue; loss_armed = true; if (earliest == null or at < earliest.?) earliest = at; } // draft-ietf-quic-multipath-21 §5.7: loss is detected "on each // individual path", against that path's own RTT. for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open) continue; const at = extra.space.loss.lossTime(&extra.rtt) orelse continue; loss_armed = true; if (earliest == null or at < earliest.?) earliest = at; } // §6.2: the loss timer wins over the probe timeout whenever it is armed, // because it is the more informed of the two — it knows a later packet // arrived, where the probe timeout knows only that nothing has. if (loss_armed) return earliest; if (c.probeDeadline()) |at| { if (earliest == null or at < earliest.?) earliest = at; } return earliest; } test timeout { var limits = test_limits; limits.max_idle_timeout = 30_000; // milliseconds const p = try TestPair.connect(limits, limits); defer p.destroy(); // Nothing in flight, so the idle timeout is the only timer running. const idle = p.client.timeout().?; try testing.expectEqual(p.client.last_activity + 30 * std.time.ns_per_s, idle); // Something sent and not yet acknowledged arms the probe timeout, // which is sooner. const id = try p.client.openBidirectional(); try p.client.write(id, "are you there?"); _ = (try p.client.send(&p.buffer, p.now)).?; try testing.expect(p.client.timeout().? < idle); } /// When §6.2's probe timeout expires, or null when nothing is in flight. /// /// Asked by `timeout`, to say when to wake, and by `onTimeout`, to say /// whether this waking is the probe timeout's -- it is not the only timer: /// an ACK held back, a round of NAT traversal probes and an abandoned path's /// state all wake the connection too, and a probe fired early puts a whole /// flight that is still in flight back on the wire and doubles a backoff /// nothing triggered. fn probeDeadline(c: *const Connection) ?recovery.Instant { var earliest: ?recovery.Instant = null; // Saturating, and bounded at sixteen doublings: the backoff is meant to // stop asking a peer that has gone away, and by 2^16 round trips it has // stopped. Letting it run further would overflow the arithmetic, which // in Zig is a panic. const backoff = @as(u64, 1) << @intCast(@min(c.pto_count, 16)); // RFC 9002 §6.2.2.1: "If no additional data can be sent, the server's // PTO timer MUST NOT be armed until datagrams have been received from the // client" -- a server at §8.1's limit could only wake to find it may not // send. A datagram from the client raises the limit, and this is asked // again then. const stalled = c.role == .server and c.paths.sendable(c.paths.active) < min_packet_room; for (&c.spaces, 0..) |*space, i| { if (stalled) break; if (c.discarded[i] or space.loss.inFlight() == 0) continue; const last = space.loss.last_ack_eliciting orelse continue; // §6.2.1: `max_ack_delay` is included only for the application space. // A peer does not deliberately delay acknowledging a handshake // packet, so counting on it would make the handshake's timer slower // than it needs to be at exactly the moment a stall is most costly. const max_delay: recovery.Duration = if (i == 2) c.maxAckDelay() else 0; const at = last +| (c.rtt.probeTimeout(max_delay) *| backoff); if (earliest == null or at < earliest.?) earliest = at; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open or extra.space.loss.inFlight() == 0) continue; const last = extra.space.loss.last_ack_eliciting orelse continue; const at = last +| (extra.rtt.probeTimeout(c.maxAckDelay()) *| backoff); if (earliest == null or at < earliest.?) earliest = at; } // RFC 9002 §6.2.2.1: the client "MUST set the PTO timer if the client // has not received an acknowledgment for any of its Handshake packets and // the handshake is not confirmed..., even if there are no packets in // flight". Counted from the last thing that happened, since nothing in // flight means no packet to count from. if (earliest == null and c.awaitsServerValidation()) { earliest = c.last_activity +| (c.rtt.probeTimeout(0) *| backoff); } return earliest; } /// RFC 9002 §6.2.2.1: whether this is a client that cannot yet be sure the /// server has validated its address, and so may be all that stands between /// a server at §8.1's limit and a handshake that never finishes. /// /// Sure once a Handshake packet of its own is acknowledged -- the server /// read it, and §8.1 has a Handshake packet validate the address it came /// from -- or once the handshake is confirmed. fn awaitsServerValidation(c: *const Connection) bool { if (c.role != .client or c.confirmed) return false; return c.spaces[1].loss.largest_acked == null; } /// Runs whichever timer `timeout` was waiting on. /// /// Calling it early is harmless — it finds nothing and changes nothing — so a /// caller with a coarse timer may simply call it whenever it wakes. /// /// What it does is queue rather than send: a probe timeout puts what was in /// flight back to be sent again, and the caller's next `send` sends it. The /// idle timeout and the end of the closing or draining state are the /// exceptions, and leave the connection `.closed` (see `closeState`) with /// nothing more to send. pub fn onTimeout(c: *Connection, now: recovery.Instant) void { if (c.closing.state != .open) { if (c.closing.expired(now)) c.closing.state = .closed; return; } // §10.1: "the connection is silently closed and its state is discarded // when it remains idle for longer than the minimum of the max_idle_timeout // value advertised by both endpoints." Silently: no CONNECTION_CLOSE, and // no draining state to sit in either, because the peer is doing the same // arithmetic and has reached the same conclusion. if (c.idleTimeout()) |idle| { if (now >= c.last_activity +| idle) { c.closing.state = .closed; c.closing.code = .no_error; return; } } for (c.extra[0 .. c.path_limit - 1]) |*extra| { const at = extra.discard_at orelse continue; if (at <= now) c.release(extra); } if (c.nat) |*state| state.onTimeout(now); while (c.paths.expire(now, c.validationProbeTimeout())) |route| { c.onValidationFailed(route); if (c.closing.state != .open) return; } var found_loss = false; for (&c.spaces, 0..) |*space, i| { if (c.discarded[i]) continue; const at = space.loss.lossTime(&c.rtt) orelse continue; if (at > now) continue; c.detectLostIn(c.recoveryOf(levelOf(i)), now); found_loss = true; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open) continue; const at = extra.space.loss.lossTime(&extra.rtt) orelse continue; if (at > now) continue; c.detectLostIn(recoveryOfPath(extra), now); found_loss = true; } if (found_loss) return; // Woken for something else -- an ACK falling due, say -- and the probe // timeout is not yet up. const probe_at = c.probeDeadline() orelse return; if (now < probe_at) return; // §6.2.4: nothing has been acknowledged and nothing can be declared lost, // because nothing later arrived to say so. The way out is to send // something and see: everything still in flight goes again, which for a // handshake is the whole outstanding flight and is what gets a stalled // connection moving. `pto_count` doubles the wait before asking a second // time, so a peer that is gone is asked a bounded number of times. // // §6.2.1 arms the probe timeout for one space — the one expiring // soonest — and probes only that one. This probes every space with // anything outstanding, which sends more than the RFC asks for on the // rare occasion that two spaces have both stalled. It is a deliberate // simplification and not a misreading: during a handshake the Initial and // Handshake spaces stall together, their flights are what the peer is // missing, and both fit in one datagram anyway. var probed = false; for (&c.spaces, 0..) |*space, i| { if (c.discarded[i] or space.loss.inFlight() == 0) continue; for (space.loss.unacked()) |sent| c.recover(space, sent); probed = true; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra.state != .open or extra.space.loss.inFlight() == 0) continue; for (extra.space.loss.unacked()) |sent| c.recover(&extra.space, sent); probed = true; } // §8.1: "To prevent this deadlock, clients MUST send a packet on a Probe // Timeout (PTO)" -- something new when there is nothing to send again. if (!probed and c.awaitsServerValidation()) { c.handshake_ping_owed = true; probed = true; } if (probed) { c.pto_count +|= 1; c.probe_pending = true; // draft-ietf-quic-ack-frequency-14 §7: "When sending PTO packets, one // can include an IMMEDIATE_ACK frame to elicit an immediate // acknowledgment" -- so that the answer to a probe is not itself held // back by the delay the peer was asked for. if (c.peerTakesAckFrequency()) c.immediate_ack_owed = true; } } test onTimeout { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "lost once"); // The network loses the only packet carrying it. _ = (try p.client.send(&p.buffer, p.now)).?; try testing.expectEqual(@as(?[]u8, null), if (try p.client.send(&p.buffer, p.now)) |d| d.bytes else null); // Early, it does nothing. p.client.onTimeout(p.now); try testing.expect(!p.client.hasDataToSend()); // On time, the probe timeout puts the data back, and the next `send` // carries it again. p.now = p.client.timeout().?; p.client.onTimeout(p.now); try p.settle(); try testing.expectEqualStrings("lost once", p.server.readable(id)); // With an idle timeout and silence for long enough, it is the end. var limits = test_limits; limits.max_idle_timeout = 10_000; const q = try TestPair.connect(limits, limits); defer q.destroy(); q.client.onTimeout(q.client.timeout().?); try testing.expectEqual(termination.State.closed, q.client.closeState().?); } /// Loses the next datagram `c` sends, then lets its probe timeout fire. fn testLoseOne(p: anytype, c: *Connection) !void { _ = (try c.send(&p.buffer, p.now)).?; p.now = c.timeout().?; c.onTimeout(p.now); } test "RFC 9000 3.1: a FIN on a frame of its own is repeated until it is acknowledged" { // The data goes first and arrives; the end follows in an empty STREAM // frame, which is lost. The acknowledgement of the data must not be // taken for the end's, or the stream is "Data Recvd" with the FIN never // having arrived and nothing left that would send it again. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "abc"); const data = (try p.client.send(&p.buffer, p.now)).?; try p.server.receive(data.bytes, data.path, p.now); try p.client.finishStream(id); _ = (try p.client.send(&p.buffer, p.now)).?; // The server acknowledges the data -- once its acknowledgement delay is // up, if it is holding back -- and the client hears that before its own // probe timer has said anything about the lost end. const acknowledgement = (try p.server.send(&p.buffer, p.now)) orelse ack: { p.now = p.server.timeout().?; p.server.onTimeout(p.now); break :ack (try p.server.send(&p.buffer, p.now)).?; }; try p.client.receive(acknowledgement.bytes, acknowledgement.path, p.now); p.now = p.client.timeout().?; p.client.onTimeout(p.now); try p.settle(); try testing.expect(p.server.streamReceived(id)); } test "RFC 9000 13.3: a lost RESET_STREAM is sent again" { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "x"); try p.settle(); try p.client.resetStream(id, 7); try testLoseOne(p, &p.client); try p.settle(); try testing.expectEqual(@as(?u64, 7), p.server.streamResetCode(id)); } test "RFC 9000 13.3: a lost STOP_SENDING is sent again" { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "an upload nobody wants"); try p.settle(); try p.server.stopSending(id, 0x10c); try testLoseOne(p, &p.server); try p.settle(); // The client heard it the second time, and reset its half in answer. try testing.expectEqual(@as(?u64, 0x10c), p.server.streamResetCode(id)); } test "RFC 9000 13.3: a lost RETIRE_CONNECTION_ID is sent again" { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var old: [ids.max_len]u8 = undefined; const len = p.client.peerId().len; @memcpy(old[0..len], p.client.peerId()); try testing.expect(p.client.rotatePeerId()); try testLoseOne(p, &p.client); try p.settle(); // The server has let the old identifier go, which it does only on // hearing that the client retired it. try testing.expect(!p.server.acceptsId(old[0..len])); } /// A datagram to send, and where to send it. /// /// The path is here because §8.2.2 requires a PATH_RESPONSE to go out on the /// path its challenge arrived on, and §9.2 has an endpoint probe a path it is /// not yet using. A caller handed only octets could not obey either — and a /// library with no sockets cannot send them itself, so saying where is the /// most it can do. pub const Datagram = struct { path: paths_mod.Id, bytes: []u8, /// §13.4: what to set the IP header's ECN field to when sending this. /// /// Advice a caller is free to ignore, and ignoring it is conforming: an /// endpoint that never marks simply never has ECN validated, which /// §13.4.2 treats as one of the ordinary outcomes. A caller that cannot /// reach its platform's IP header has no other choice. ecn: ecn_mod.Codepoint = .not_ect, /// Where to send it instead of `path`'s peer, when it is a NAT traversal /// probe to a candidate address that is not yet anybody's path. `path` /// still says which of the caller's sockets it leaves from. to: ?frame.Address = null, }; /// Builds the next datagram to send, or null when there is nothing to say. /// /// Packets for different encryption levels are coalesced into one datagram /// where both have something to carry (§12.2), which is what makes a QUIC /// handshake take two round trips rather than four: a server's ServerHello /// and the encrypted flight after it travel together. /// /// The datagram is built in `out_buffer` and `Datagram.bytes` points into /// it, so it is the caller's to send before reusing the buffer. It is never /// longer than the buffer, nor than the path is known to carry (§14) and /// the peer will accept (§18.2). Give it at least the 1200 octets §14.1 /// guarantees every path; a larger one lets §14.3's search use more. /// /// Call this until it returns null: one datagram is one call, and a /// connection with a flight to send has several. Null is also what a sender /// held back by its congestion window or §8.1's anti-amplification limit /// gets, so the caller tries again after the next `receive` or `onTimeout`. /// /// An error is this endpoint failing to build a packet or TLS failing to /// produce one, and is not something the peer did; unlike `receive`, this /// does not close the connection over it. pub fn send(c: *Connection, out_buffer: []u8, now: recovery.Instant) Error!?Datagram { // §18.2: a datagram larger than the peer said it would accept is a // datagram that does not arrive. Capping here rather than asking the // caller to is deliberate — the caller has a buffer, and what fits in it // is not the same question as what the peer will read. const out_capped = out_buffer[0..@min(out_buffer.len, c.maxDatagram())]; if (c.closing.state != .open) { if (c.closing.expired(now)) c.closing.state = .closed; if (!c.closing.owesClose()) return null; const wire = try c.sendClose(out_capped, now) orelse return null; return .{ .path = c.paths.active, .bytes = wire }; } // n0's NAT traversal: a path over a hole a probe found, and then any // probe that is due, ahead of everything else -- it is one small // datagram, and a probe held back behind a full congestion window // would reach the peer's NAT after the mapping it was meant to meet. c.openNatPaths(now); if (c.sendNatAnswer(out_capped)) |answer| return answer; if (c.sendNatProbe(out_capped)) |probe| return probe; if (c.sendChallengeAlone(out_capped, now)) |probe| return probe; if (c.sendResponseAway(out_capped, now)) |response| return response; // What each level wants to say, gathered before anything is built. // // Two passes, because the padding rule needs to know the answer to a // question the first pass asks: §14.1 is about the size of the // *datagram*, so whether the last packet needs padding depends on what // the earlier ones took. Asking TLS twice is not an option -- `emit` // hands bytes over once -- so what it says is held here. var has_crypto: [3]bool = .{ false, false, false }; var has_streams = false; var owes_limits = false; var owes_ack: [3]bool = .{ false, false, false }; var any: [3]bool = .{ false, false, false }; // §8.1: "the client MUST send an Initial packet in a UDP datagram that // contains at least 1200 bytes if it does not have Handshake keys, and // otherwise send a Handshake packet." The padding is the Initial's own, // below. const ping_level: ?usize = if (!c.handshake_ping_owed) null else if (!c.discarded[1] and c.spaces[1].hasKeys()) 1 else if (!c.discarded[0] and c.spaces[0].hasKeys()) 0 else null; var last: ?usize = null; // Whether the application-level packet in this datagram will be a 0-RTT // one rather than a 1-RTT one. Decided in the first pass and used in the // second, because by then TLS has been asked what it has and asking again // is not allowed. It describes the application level and no other, which // is why the second pass narrows it with `i == 2` rather than reading it // directly -- an Initial packet sealed under a 0-RTT key is a packet the // peer silently discards, and nothing downstream of that says why. var early_application = false; // §7: "An endpoint MUST NOT send a packet if it would cause // bytes_in_flight to be larger than the congestion window, unless the // packet is sent on a PTO timer expiration." A blocked sender may still // acknowledge, because §7 exempts ACK-only packets from the window // entirely — a sender that throttled its own acknowledgements would be // throttling the feedback the controller runs on, and would deadlock a // peer waiting for one. // // The test is coarser than the rule: it asks whether there is any room // left rather than whether this datagram would fit in what remains, so a // sender can overshoot by at most the one datagram that closes the // window. Being exact would mean knowing a packet's encrypted size before // building it, and the overshoot is bounded and one-off where the error // in the other direction — refusing to send while room remains — stalls a // connection for a round trip each time. // §8.2.2: a response goes out on the path its challenge arrived on, even // when that is not the path the connection is using. Everything else goes // on the active path. // // draft-ietf-quic-multipath-21: or on a path past path 0, which numbers // its packets, addresses its peer and counts its congestion by itself. const target = c.sendTarget(); const destination: paths_mod.Id = if (c.paths.nextOwed()) |owed| owed.path else if (target) |t| t.route else c.paths.active; const nonce_path: u32 = if (target) |t| t.id else 0; // §21.1.1.1 and §9.3.1: until a path is validated, no more than three // times what arrived from it may be sent to it. An endpoint that ignored // this would be a reflector for anyone willing to forge a source address. const allowance = c.paths.sendable(destination); if (allowance == 0) return null; // draft-ietf-quic-multipath-21 §5.8: sized for the path it goes on. const cap = if (target) |t| c.maxDatagramFor(&t.pmtu) else c.maxDatagram(); const out = out_buffer[0..@min(out_buffer.len, cap, allowance)]; // Two windows, not one. The congestion window bounds the octets that may // be in flight; the loss-tracking table bounds the *packets*, because // every ack-eliciting packet needs a slot and a packet without one cannot // be recovered -- see `recovery.Space.full` for what a sender that // ignores it does instead of slowing down. Both are lifted for a probe: // §7.5's "probe packets MUST NOT be blocked by the congestion controller" // is the reason the table cannot deadlock either, since the probe is what // makes the acknowledgements that empty it. // // Streams and DATAGRAM frames live only at the application level, so its // space is the one that gates them. During the handshake that space has // sent nothing and is not full, so this says nothing about a handshake. const blocked = !c.probe_pending and if (target) |t| (t.congestion.available() == 0 or t.space.loss.full()) else (c.congestion.available() == 0 or c.spaces[2].loss.full()); // §13.4.2: one codepoint for the whole datagram, because the ECN field is // in the IP header and coalesced QUIC packets "share the same IP header". // Decided once, here, so that every packet built into this datagram is // recorded as having carried what the datagram actually carries. Asked // of the path it goes out on, since each path is validated on its own. const validator: *ecn_mod.Validator = if (target) |t| &t.ecn else &c.ecn; const marking = validator.codepoint(); // §6.6: "Endpoints MUST initiate a key update before sending more // protected packets than the confidentiality limit for the selected AEAD // permits. If a key update is not possible... the endpoint MUST stop // using the connection... It is RECOMMENDED that endpoints immediately // close the connection with a connection error of type AEAD_LIMIT_REACHED // before reaching a state where key updates are not possible." if (c.packets_encrypted >= confidentiality_limit) { if (!c.updateKeys(now)) { c.close(.aead_limit_reached, "confidentiality limit", now); const wire = try c.sendClose(out, now) orelse return null; return .{ .path = c.paths.active, .bytes = wire }; } } if (out.len < min_packet_room) return c.sendProbeAlone(out, target, destination, now); for ([_]tls.Level{ .initial, .handshake, .application }, 0..) |level, i| { if (c.discarded[i]) continue; // A path past path 0 only ever carries 1-RTT packets. if (target != null and i < 2) continue; const space = &c.spaces[@backingInt(Space.of(level))]; const numbering: *SpaceState = if (i == 2 and target != null) &target.?.space else space; // §4.6: the application level can be reached before the handshake // has produced keys for it, by a client that kept a session ticket. // What it can say there is much less -- §12.4 permits no ACK and no // CRYPTO in a 0-RTT packet -- so the level is present with almost // everything about it switched off. // // Only when the handshake level has nothing to say, which keeps // §12.2's coalescing order (Initial, 0-RTT, Handshake, 1-RTT) without // reordering this loop: a datagram never holds both, so 0-RTT is // never the packet after a Handshake one. const early = i == 2 and space.write == null and c.early_write != null and !any[1]; if (i == 2) early_application = early; if (!space.hasKeys() and !early) continue; // Anything TLS has produced since the last look is copied into this // connection's own buffer before a packet is built from it. `emit` // hands its bytes over once, and a retransmission needs them again. if (c.handshake.emit(level) catch return error.HandshakeFailed) |data| { space.crypto.write(data) catch return error.NoSpace; } // Only whether there is something to say, not what: how much of it // fits depends on what the earlier levels took, which this pass does // not know yet. // At the application level CRYPTO can go on any path -- it is the // level's one stream whichever packet number space carries it, and // `recover` puts a lost piece back there -- which matters once path 0 // is abandoned and a NewSessionTicket has nowhere else to go. has_crypto[i] = !early and !blocked and (target == null or i == 2) and space.crypto.pending(); owes_ack[i] = !early and (if (i == 2) c.ackOwed(&numbering.acks, now, true) or c.otherAcksOwed(target, now, true) else !numbering.acks.isEmpty() and numbering.acks.ack_eliciting_pending); any[i] = has_crypto[i] or owes_ack[i] or ping_level == i; // Streams live only at the application level, and only once there are // keys for it. if (i == 2) { has_streams = !blocked and c.hasStreamData(); owes_limits = c.owesFlowControl(); // A 0-RTT packet carries stream data and the flow control that // goes with it, and nothing else. Everything in the list below is // either forbidden there by §12.4 -- HANDSHAKE_DONE, PATH_RESPONSE // -- or connection bookkeeping that has waited this long and can // wait for 1-RTT, where it costs no special case. any[i] = any[i] or has_streams or owes_limits or // RFC 9221 §4: a DATAGRAM frame may go in a 0-RTT packet as // well as a 1-RTT one, so this is outside the `!early` guard // below. An application that is willing to send unreliably is // willing to send early, and §9.2's replay warning is the // same warning it already accepted. (!blocked and c.outbound.len > 0) or (!early and (c.owes_handshake_done or c.owesMaxStreams() or c.received.nextOwed() != null or c.owesNewId() or c.idToResend() != null or c.paths.nextOwed() != null or c.owesChallenge() or c.owesObservation(destination) != null or c.owesPathId() != null or c.owesAbandon() != null or c.owedPathOffer() != null or c.path0_owes_abandon or c.max_path_id_owed or c.paths_blocked_owed != null or c.owesBlocked() or c.owesCidsBlocked() != null or c.owesPathStatus() != null or c.natOwesFrame() or c.ack_frequency_owed or c.immediate_ack_owed)); } if (any[i]) last = i; } // Nothing ordinary to send, which is when a probe costs least: §14.4 // notes that probes "consume congestion window, which could delay // subsequent transmission by an application", so they wait for a quiet // moment rather than competing with one. const last_index = last orelse return c.sendProbe(out_buffer, now); // §14.1 applies to a client's datagram carrying an Initial, and the // padding goes in a packet rather than after one: octets after the last // packet are not part of any packet, and a receiver would try to read // them as another. // const pad_required = c.role == .client and any[0]; // §8.2.1 and §8.2.2: "an endpoint MUST expand datagrams that contain a // PATH_CHALLENGE frame to at least 1200 bytes", and the same for // PATH_RESPONSE. What is being proved is not that the peer is there but // that the path carries what QUIC requires of it -- a path that passes // validation with a sixty-octet datagram and then cannot carry a real one // has been validated into uselessness. // // It is also what makes validation terminate. The answering endpoint is // held to three times what arrived (§21.1.1.1), so a challenge that // arrives small buys an answer that may be too small to send -- and then // neither end has anything left to do and the path is never validated. // // "Unless the anti-amplification limit for the path does not permit // sending a datagram of this size", which is why this one is preferred // rather than required: `out` has already been capped by the allowance // above, so a limit that forbids 1200 octets simply leaves the datagram // short instead of refusing to send it. // // A server's datagram carrying an ack-eliciting Initial is the same: // "a server MUST expand the payload of all UDP datagrams carrying // ack-eliciting Initial packets to at least the smallest allowed maximum // datagram size of 1200 bytes" -- but before the client's address is // validated `out` is capped by §8.1's allowance, which can leave less // than 1200. The limit wins: a large certificate chain outgrows the // allowance, and refusing to send the rest of the flight unpadded would // stop the handshake there. CRYPTO is what makes a server's Initial // ack-eliciting; one carrying only an ACK may stay small. const pad_preferred = pad_required or (c.role == .server and has_crypto[0]) or (c.paths.nextOwed() != null) or c.owesChallengeOn(destination); const pad = pad_preferred; var at: usize = 0; var padded = false; // The path a PATH_CHALLENGE went out on, to note once the datagram's // size is known whether it was the 1200 octets §8.2.1 asks for. var challenged: ?*paths_mod.Path = null; for ([_]tls.Level{ .initial, .handshake, .application }, 0..) |level, i| { if (!any[i]) continue; const space = &c.spaces[@backingInt(Space.of(level))]; const numbering: *SpaceState = if (i == 2 and target != null) &target.?.space else space; const early = i == 2 and early_application; // Room for another packet at all: a long header, its connection IDs, // enough frame octets for §5.4.2's sample and the AEAD tag. Stopping // here rather than failing is what lets a flight larger than one // datagram go in several — the levels that did not fit still have // everything they were going to say, and say it next time. if (out.len - at < min_packet_room) break; // §12.2: packets are coalesced in increasing order of encryption // level, and a short header has no Length field so it can only be // last -- which it is, being last in this loop. const kind: packet.Kind = switch (level) { .initial => .initial, .handshake => .handshake, // §17.2.3: 0-RTT has a long header, because a receiver has to be // told which keys to try and a short header says nothing about // that -- the packet is being read by an endpoint whose handshake // has not finished. .application => if (early) .zero_rtt else .one_rtt, .early_data => unreachable, }; const addressed_to: []const u8 = if (target) |t| t.received.current().? else c.peerId(); var b = if (kind == .one_rtt) packet.Builder.initShort(out[at..], addressed_to, numbering.next_number, 4, c.key_phase) catch return error.NoSpace else packet.Builder.initLong(out[at..], .{ .kind = kind, .destination = c.peerId(), .source = c.localId(), // §17.2.2: the Token field, which only an Initial has. A // client that was sent a Retry must echo its token, and one // that kept a NEW_TOKEN from an earlier connection may send // that instead. .token = if (kind == .initial) c.token_buf[0..c.token_len] else &.{}, }, space.next_number, 4) catch return error.NoSpace; var carried = false; // An ACK held back by draft-ietf-quic-ack-frequency-14 still goes in // any packet that is leaving anyway: it costs a few octets there, and // the point of holding it was to save a packet. const with_acks = owes_ack[i] or (i == 2 and !early and (c.ackOwed(&numbering.acks, now, false) or c.otherAcksOwed(target, now, false))); if (with_acks) { if (!numbering.acks.isEmpty()) { try addAck(&b, numbering, if (i == 2) nonce_path else 0, c.ackDelayField(&numbering.acks, now)); carried = true; } // draft-ietf-quic-multipath-21 §3.1: "PATH_ACK frames can be // returned on any path", so every other path's acknowledgement // rides along rather than waiting for a packet of its own. if (i == 2) { if (target != null and !c.spaces[2].acks.isEmpty() and c.spaces[2].acks.ack_eliciting_pending) { try addAck(&b, &c.spaces[2], 0, c.ackDelayField(&c.spaces[2].acks, now)); carried = true; } for (c.extra[0 .. c.path_limit - 1]) |*extra| { if (extra == target or extra.state == .unused) continue; if (extra.space.acks.isEmpty() or !extra.space.acks.ack_eliciting_pending) continue; try addAck(&b, &extra.space, extra.id, c.ackDelayField(&extra.space.acks, now)); carried = true; } } } var sent_chunk: ?Chunk = null; if (has_crypto[i]) fit: { const room = b.remaining(); if (room <= crypto_frame_overhead) break :fit; // As much of it as fits after the ACK, the rest next time. A // CRYPTO frame can be split anywhere — §19.6 gives it an offset // and a length and says nothing about message boundaries — which // is the whole reason a handshake message larger than a packet is // expressible at all. const avail = @min(room - crypto_frame_overhead, max_crypto_chunk); const chunk = space.crypto.next(avail) orelse break :fit; b.add(.{ .crypto = .{ .offset = chunk.offset, .data = chunk.data } }) catch return error.NoSpace; space.crypto.advance(chunk); sent_chunk = chunk; carried = true; } var sent_ping = false; if (ping_level == i) { b.add(.ping) catch return error.NoSpace; c.handshake_ping_owed = false; sent_ping = true; carried = true; } var sent_ranges: recovery.Sent = .{ .number = numbering.next_number, .time = now, .ack_eliciting = false, .size = 0, .early = early, }; var sent_handshake_done = false; var sent_datagram = false; if (i == 2 and !early) { if (c.owes_handshake_done) { b.add(.handshake_done) catch return error.NoSpace; c.owes_handshake_done = false; sent_handshake_done = true; sent_ranges.handshake_done = true; carried = true; } if (c.paths.nextOwed()) |owed| { if (owed.path == destination) { b.add(.{ .path_response = &owed.data }) catch return error.NoSpace; c.paths.sentResponse(owed.data); sent_handshake_done = true; // ack-eliciting carried = true; } } if (c.paths.find(destination)) |seen| { if (seen.challenge) |data| { if (!seen.sent_challenge) { b.add(.{ .path_challenge = &data }) catch return error.NoSpace; seen.sent_challenge = true; challenged = seen; seen.challenge_sent_at = now; sent_handshake_done = true; // ack-eliciting carried = true; } } } // draft-ietf-quic-address-discovery-01 §5: "An endpoint that // negotiated this extension and offered to provide address // observations to the peer MUST send an OBSERVED_ADDRESS frame on // every new path", including the handshake's, and "SHOULD" do so // "as early as possible" -- which for a server is its first 1-RTT // packet, before the handshake has finished. Only on the path it // describes: a report of one path's address sent down another // would tell the peer about a path it is not using. if (c.owesObservation(destination)) |address| { b.add(.{ .observed_address = .{ .sequence = c.next_observed_sequence, .address = address, } }) catch return error.NoSpace; c.next_observed_sequence += 1; c.paths.find(destination).?.observation_owed = false; sent_ranges.observed_path = destination; sent_handshake_done = true; // ack-eliciting carried = true; } // draft-ietf-quic-multipath-21 §3.2.1: an identifier for each // path the two ends' limits allow, so that the client can open // one; and §3.4's PATH_ABANDON, which "can be sent on any open // path". // A lost offer goes again as it was: the peer may already hold // it, and an identifier issued twice under two sequence numbers // is one §19.15 has the peer treat as an error. const resend = c.owedPathOffer(); if (resend orelse if (c.owesPathId()) |extra| if (c.issuePathId(extra)) |entry| recovery.PathOffer{ .path = extra.id, .sequence = entry.sequence, } else null else null) |offer| { const extra = c.extraFor(offer.path).?; if (issuedEntry(&extra.issued, offer.sequence)) |entry| { b.add(.{ .path_new_connection_id = .{ .path = extra.id, .id = .{ .sequence = entry.sequence, .retire_prior_to = 0, .id = entry.id(), .token = &(entry.token orelse @as([ids.token_len]u8, @splat(0))), } } }) catch return error.NoSpace; sent_ranges.path_offer = offer; sent_handshake_done = true; // ack-eliciting carried = true; } if (resend != null) extra.offer_owed = null; } if (c.owesAbandon()) |extra| { b.add(.{ .path_abandon = .{ .path = extra.id, .error_code = 0 } }) catch return error.NoSpace; extra.owes_abandon = false; extra.sent_abandon = true; sent_ranges.abandoned_path = extra.id; sent_handshake_done = true; // ack-eliciting carried = true; } else if (c.path0_owes_abandon) { b.add(.{ .path_abandon = .{ .path = 0, .error_code = 0 } }) catch return error.NoSpace; c.path0_owes_abandon = false; c.path0_sent_abandon = true; sent_ranges.abandoned_path = 0; sent_handshake_done = true; // ack-eliciting carried = true; } // §4.6: the limit, raised as abandoned paths are let go of. if (c.max_path_id_owed) { b.add(.{ .max_path_id = c.local_max_path_id }) catch return error.NoSpace; c.max_path_id_owed = false; sent_ranges.max_path_id = c.local_max_path_id; sent_handshake_done = true; // ack-eliciting carried = true; } // §4.7: why a path could not be opened. Informational, and not // sent again when lost -- "MAY be retransmitted", and `openPath` // failing again says it again. if (c.paths_blocked_owed) |max| { b.add(.{ .paths_blocked = max }) catch return error.NoSpace; c.paths_blocked_owed = null; c.paths_blocked_sent = max; sent_handshake_done = true; // ack-eliciting carried = true; } // RFC 9000 §4.1 and §4.6: what flow control is holding back. // After this packet's stream data, not before, would be the // natural place -- but the stream data is what fills a packet, // and a frame of a few octets that never fits is never said. if (c.owesDataBlocked()) |maximum| { b.add(.{ .data_blocked = maximum }) catch return error.NoSpace; c.data_blocked_sent = maximum; sent_ranges.data_blocked = maximum; sent_handshake_done = true; // ack-eliciting carried = true; } if (c.owesStreamDataBlocked()) |entry| { const maximum = entry.send.credit.limit; b.add(.{ .stream_data_blocked = .{ .stream = entry.id.value, .maximum = maximum } }) catch return error.NoSpace; entry.data_blocked_sent = maximum; sent_ranges.stream_data_blocked = .{ .stream = entry.id.value, .maximum = maximum }; sent_handshake_done = true; // ack-eliciting carried = true; } if (c.owesStreamsBlocked()) |which| { const maximum = c.peer_stream_limit[which]; const directionality: frame.Directionality = if (which == 0) .bidirectional else .unidirectional; b.add(.{ .streams_blocked = .{ .kind = directionality, .maximum = maximum } }) catch return error.NoSpace; c.streams_blocked_sent[which] = maximum; sent_ranges.streams_blocked = .{ .kind = directionality, .maximum = maximum }; sent_handshake_done = true; // ack-eliciting carried = true; } if (c.owesCidsBlocked()) |extra| { const next = extra.received.next_sequence; b.add(.{ .path_cids_blocked = .{ .path = extra.id, .next_sequence = next } }) catch return error.NoSpace; extra.cids_blocked_owed = false; extra.cids_blocked_sent = next; sent_handshake_done = true; // ack-eliciting carried = true; } // draft-ietf-quic-ack-frequency-14: what this end asks of the // peer's acknowledgements, and a request for one now. The second // is not recorded -- "IMMEDIATE_ACK frames do not need to be // retransmitted". if (c.ack_frequency_owed) if (c.ack_frequency_request) |request| { const sequence = c.ack_frequency_next; b.add(.{ .ack_frequency = .{ .sequence = sequence, .ack_eliciting_threshold = request.threshold, .requested_max_ack_delay = request.max_delay_us, .reordering_threshold = request.reordering, } }) catch return error.NoSpace; c.ack_frequency_next += 1; c.ack_frequency_owed = false; c.ack_frequency_in_flight = .{ .sequence = sequence, .max_delay_us = request.max_delay_us }; sent_ranges.ack_frequency = sequence; sent_handshake_done = true; // ack-eliciting carried = true; }; if (c.immediate_ack_owed) { b.add(.immediate_ack) catch return error.NoSpace; c.immediate_ack_owed = false; sent_handshake_done = true; // ack-eliciting carried = true; } // n0's NAT traversal: a server's candidates offered and withdrawn, // and a client's for the current round. if (c.nat) |*state| { if (state.owedAdd()) |a| { b.add(.{ .add_address = a }) catch return error.NoSpace; state.sentAdd(a.sequence); sent_ranges.nat_add = a.sequence; sent_handshake_done = true; // ack-eliciting carried = true; } if (state.owedRemove()) |sequence| { b.add(.{ .remove_address = sequence }) catch return error.NoSpace; state.sentRemove(sequence); sent_ranges.nat_remove = sequence; sent_handshake_done = true; // ack-eliciting carried = true; } if (state.owedReach()) |r| { b.add(.{ .reach_out = r }) catch return error.NoSpace; state.sentReach(r.address); sent_ranges.nat_reach = r; sent_handshake_done = true; // ack-eliciting carried = true; } } // §4.3: a path's status, numbered afresh each time it is sent, // since the numbers need only increase. if (c.owesPathStatus()) |id| { const state = c.statusFor(id).?; b.add(.{ .path_status = .{ .path = id, .sequence = state.next_sequence, .status = state.local.?, } }) catch return error.NoSpace; sent_ranges.path_status = .{ .path = id, .sequence = state.next_sequence }; state.sent_sequence = state.next_sequence; state.next_sequence += 1; state.owed = false; sent_handshake_done = true; // ack-eliciting carried = true; } if (c.received.nextOwed()) |sequence| { b.add(.{ .retire_connection_id = sequence }) catch return error.NoSpace; c.received.sentRetire(sequence); sent_ranges.retire_connection_id = sequence; sent_handshake_done = true; // ack-eliciting carried = true; } // One identifier a packet, a lost one first: §13.3 sends the // same identifier again, and it still counts against the peer's // limit, so issuing another in its place would leave the peer // short. if (c.idToResend()) |entry| { b.add(.{ .new_connection_id = .{ .sequence = entry.sequence, .retire_prior_to = 0, .id = entry.id(), .token = &(entry.token orelse @as([ids.token_len]u8, @splat(0))), }, }) catch return error.NoSpace; entry.resend = false; sent_ranges.new_connection_id = entry.sequence; sent_handshake_done = true; // ack-eliciting carried = true; } else if (c.owesNewId()) { // Every identifier issued after the handshake carries a // token: §19.15's frame has a field for it and no way to // leave it out, which is why `issueId` never produces one // without. if (c.issueId()) |offer| { b.add(.{ .new_connection_id = .{ .sequence = offer.sequence, // Nothing is being retired: §5.1.2 reserves Retire // Prior To for an endpoint that needs its peer to // stop using identifiers, and this is replacing one // the peer has already stopped using. .retire_prior_to = 0, .id = offer.id(), .token = &(offer.token orelse @as([ids.token_len]u8, @splat(0))), }, }) catch return error.NoSpace; sent_ranges.new_connection_id = offer.sequence; sent_handshake_done = true; // ack-eliciting carried = true; } } // §19.11: one frame per directionality, since the type bit // carries which one it is about and a single frame cannot speak // for both. for ([_]stream.Directionality{ .bidirectional, .unidirectional }) |which| { const slot = @backingInt(which); if (!c.owes_max_streams[slot]) continue; b.add(.{ .max_streams = .{ .kind = wireDirection(which), .maximum = c.advertised_stream_limit[slot], } }) catch return error.NoSpace; c.owes_max_streams[slot] = false; sent_ranges.max_streams[slot] = true; sent_handshake_done = true; // ack-eliciting, for the same reason carried = true; } } if (i == 2) { if (owes_limits and c.addFlowControl(&b)) { sent_ranges.flow_control = true; carried = true; } if (has_streams and c.addStreams(&b, &sent_ranges)) carried = true; // RFC 9221 §5.2: written and forgotten. Nothing about the // datagram is recorded in `sent_ranges`, which is what makes a // lost one stay lost -- "DATAGRAM frames... SHOULD NOT be // retransmitted", and the way to not retransmit something is to // keep no copy of it. if (!blocked and c.addDatagrams(&b)) { carried = true; sent_datagram = true; } } // Nothing fitted after all, which can only happen at the tail of a // full datagram. An empty packet is not worth sending and §5.4.2 // would refuse to build one anyway. if (!carried) break; var padded_here = false; if (i == last_index and pad and out.len >= min_initial_datagram) { // `at` may already be past 1200, and then the datagram is as // large as it has to be without any padding at all. if (b.padTo(min_initial_datagram -| at)) |_| { padded = true; padded_here = true; } else |_| { // Only §14.1's is a MUST that cannot be met another way. if (pad_required) return error.NoSpace; } } c.grease(&b); const wire = b.finishOn(if (early) &c.early_write.? else &space.write.?, if (i == 2) nonce_path else 0) catch return error.NoSpace; // §2: a packet carrying only an ACK (and padding) is not // ack-eliciting, so the peer will never acknowledge it and there is // nothing to recover if it is lost -- a later ACK says everything an // earlier one did. // §13.2.1: everything but ACK, PADDING and CONNECTION_CLOSE is // ack-eliciting, and HANDSHAKE_DONE is emphatically one of them — a // lost one leaves a client unable to confirm its handshake for the // life of the connection, so it has to be a packet loss recovery // knows about. // §5.2 of RFC 9221: "DATAGRAM frames are ack-eliciting". They are // acknowledged like anything else -- what differs is only what // happens when the acknowledgement does not come. sent_ranges.ack_eliciting = sent_chunk != null or sent_ping or sent_ranges.stream_count > 0 or owes_limits or sent_handshake_done or sent_datagram or sent_ranges.reset_stream != null or sent_ranges.stop_sending != null; sent_ranges.size = wire.len; sent_ranges.crypto_offset = if (sent_chunk) |chunk| chunk.offset else 0; sent_ranges.crypto_len = if (sent_chunk) |chunk| chunk.data.len else 0; sent_ranges.ect0 = marking == .ect0; // Counted per QUIC packet rather than per datagram, so that it is // comparable with what a peer reports: §13.4.1 has a receiver // increment its counts "once for each coalesced QUIC packet", and // §13.4.2.1 compares a reported total against "the total number of // packets sent with each corresponding ECT codepoint". // Counted by the validator of the path the packet goes out on, and // only for the application space: that is the only space whose // acknowledgements it checks, and §13.4.1 has the peer count each // space separately, so a total that took in Initial and Handshake // packets too would be held against counts that never did. if (i == 2) validator.onSent(sent_ranges.ect0); const congestion: *Congestion = if (i == 2 and target != null) &target.?.congestion else &c.congestion; if (numbering.loss.onSent(sent_ranges)) |forgotten| c.forgetIn(numbering, congestion, forgotten); // §B.2, precisely: bytes in flight are "all sent packets that contain // at least one ack-eliciting or PADDING frame". The exclusion is // narrower than it first looks — a packet of nothing but an ACK is // out, but the same packet padded to satisfy §14.1 is in, because the // padding occupies the path whatever it is there for. if (sent_ranges.ack_eliciting or padded_here) congestion.onSent(wire.len); at += wire.len; numbering.next_number += 1; // §6.6: "Endpoints MUST count the number of encrypted packets for each // set of keys." A 0-RTT packet is a different set, and one that is // never updated and never used for enough packets to matter, so it // does not count against the limit that drives 1-RTT key update. if (i == 2 and !early) c.packets_encrypted +|= 1; if (early) c.sent_early = true; } // §14.1 is a MUST, so a datagram carrying a client's Initial that could // not be padded is not one to send. This needs a buffer smaller than the // 1200 octets the rule names, or a level ahead of the last one filling // it — and in either case the caller has offered less room than a QUIC // endpoint is allowed to use. if (pad_required and !padded) return error.NoSpace; if (challenged) |seen| seen.challenge_short = at < min_initial_datagram; if (c.role == .client and any[0]) c.sent_initial = true; c.probe_pending = false; // §4.9.1: "a client MUST discard Initial keys when it first sends a // Handshake packet", and §4.9.2's condition can become true here too -- // a server's handshake space empties when its last acknowledgement goes // out. if (c.role == .client and any[1]) c.discardKeys(.initial); c.maybeDiscardHandshake(); // §10.1: "Restarting this timer when sending a packet ensures that // connections are not closed after new activity is initiated." Only the // first such packet counts, which is what stops a sender that is talking // into a void from keeping its own idle timer alive indefinitely. if (!c.sent_since_receive and at > 0) { c.last_activity = now; c.sent_since_receive = true; } // §B.5: a sender that has said everything it has to say is application // limited, and the window it did not use is not evidence the path would // have carried it. A handshake is almost all of it, so without this the // window would grow on the strength of four packets. c.congestion.app_limited = !c.hasDataToSend(); if (c.paths.find(destination)) |seen| seen.sent +|= at; // Nothing was built after all, which is not the same as nothing having // been wanted: a level can want to say something that does not fit in // what is left of the datagram. An empty datagram is not a thing to send, // and a caller that was handed one and treated it as progress would spin. if (at == 0) return null; return .{ .path = destination, .bytes = out[0..at], .ecn = marking }; } test send { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openBidirectional(); try p.client.write(id, "query"); // The loop at the heart of every caller: send until there is nothing // left, handing each datagram to the socket `path` names. var buffer: [1500]u8 = undefined; var datagrams: usize = 0; while (try p.client.send(&buffer, p.now)) |datagram| { try testing.expect(datagram.bytes.len <= buffer.len); try p.server.receive(datagram.bytes, datagram.path, p.now); datagrams += 1; } try testing.expect(datagrams >= 1); try testing.expectEqualStrings("query", p.server.readable(id)); } /// §4.6.3 of RFC 9001: whether the server agreed to read this connection's /// 0-RTT data. /// /// False on a connection that never offered any, so it answers "did the early /// data count?" rather than "was it refused?" — the two differ only for a /// caller that did not attempt 0-RTT, and that caller has nothing to ask. /// `earlyDataRejected` is the other question, and the one to act on. pub fn earlyDataAccepted(c: *const Connection) bool { return c.handshake.earlyDataAccepted(); } /// §4.6.2 of RFC 9001: whether this client sent 0-RTT data and the server /// refused it. Becomes true during the `receive` that completes the /// handshake, and stays true. /// /// A refusal means "all connection characteristics that the client assumed /// might be incorrect", and "the client therefore MUST reset the state of /// all streams, including application state bound to those streams". This /// connection has done its part: every stream is gone, nothing sent on them /// will be sent again, and stream numbering starts from zero, so an /// identifier the application still holds may come back naming a different /// stream. The application does the rest -- forget every stream it opened, /// and open new ones for whatever is still worth sending under the /// parameters the server has now given. pub fn earlyDataRejected(c: *const Connection) bool { return c.early_rejected; } test earlyDataAccepted { // A first connection has no ticket to send 0-RTT under, so there was no // early data to accept. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expect(!p.client.earlyDataAccepted()); try testing.expect(!p.server.earlyDataAccepted()); } /// RFC 7250: the raw public key the peer proved it holds, once the handshake /// is complete, or null if the handshake used certificates or the peer /// presented nothing. /// /// On a client this is always the key it dialed, since any other fails the /// handshake. On a server it is the answer to "who is this?", and the one /// piece of identity a raw-key server learns about a client at all. pub fn peerPublicKey(c: *const Connection) ?tls.PublicKey { return c.handshake.peerPublicKey(); } test peerPublicKey { // The test pair authenticates with neither raw keys nor certificates -- // the client skips verification -- so there is no key to report. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expectEqual(@as(?tls.PublicKey, null), p.client.peerPublicKey()); try testing.expectEqual(@as(?tls.PublicKey, null), p.server.peerPublicKey()); } /// Whether anything is waiting to go out: CRYPTO data at any level, stream /// data or unreliable datagrams, a flow control or stream limit that has /// moved, or a PATH_CHALLENGE or PATH_RESPONSE that is owed. /// /// Not everything `send` might send: acknowledgements, probes and the /// frames of the protocol extensions are left out. It is the question §7.8 /// of RFC 9002 asks -- whether the sender is limited by the application /// rather than by the congestion window -- more than a promise that `send` /// returns null. pub fn hasDataToSend(c: *const Connection) bool { for (&c.spaces, 0..) |*space, i| { if (c.discarded[i] or !space.hasKeys()) continue; if (space.crypto.pending()) return true; } if (c.outbound.len > 0 and (c.spaces[2].hasKeys() or c.early_write != null)) return true; // §4.6: stream data a client can send before the handshake finishes. if (c.early_write != null and c.spaces[2].write == null and (c.hasStreamData() or c.owesFlowControl())) return true; if (c.spaces[2].hasKeys() and (c.hasStreamData() or c.owesFlowControl() or c.owesMaxStreams() or c.paths.nextOwed() != null or c.owesChallenge())) return true; return false; } test hasDataToSend { const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); try testing.expect(!p.client.hasDataToSend()); const id = try p.client.openBidirectional(); try p.client.write(id, "pending"); try testing.expect(p.client.hasDataToSend()); try p.settle(); try testing.expect(!p.client.hasDataToSend()); } /// §2.1's directionality, crossing between the wire vocabulary and the stream /// one. /// /// Two enums for one bit, and deliberately: `frame.zig` imports nothing but /// `std`, `tls` and `varint` so that it can be fuzzed with nothing else /// compiled, and a shared type would end that. The switch is written out /// rather than cast so that adding a third directionality — which will not /// happen, but the compiler does not know that — fails here rather than /// silently mapping to the wrong one. fn wireDirection(which: stream.Directionality) frame.Directionality { return switch (which) { .bidirectional => .bidirectional, .unidirectional => .unidirectional, }; } fn streamDirection(which: frame.Directionality) stream.Directionality { return switch (which) { .bidirectional => .bidirectional, .unidirectional => .unidirectional, }; } /// Whether a MAX_STREAMS is owed for either directionality. fn owesMaxStreams(c: *const Connection) bool { return c.owes_max_streams[0] or c.owes_max_streams[1]; } /// Whether any stream has octets to send that flow control will allow. fn hasStreamData(c: *const Connection) bool { // §3.5: a RESET_STREAM that has been decided on and not yet written is // something to send, and is not held by flow control -- the octets it // reports were counted when they were written, and §4.1's limit is on // data rather than on frames. Asked before the credit test for exactly // that reason: a connection out of credit must still be able to say that // it has given up on a stream. for (&c.streams) |*entry| { if (entry.open and entry.has_send and entry.send.reset_pending) return true; if (entry.open and entry.has_recv and entry.recv.stop_pending) return true; } if (c.send_credit.blocked()) return false; for (&c.streams) |*entry| { if (!entry.open or !entry.has_send) continue; // `Send.next` answers both questions at once: null when there is // nothing to say *and* when flow control forbids saying it. if (entry.send.next(1) != null) return true; } return false; } /// §4.1: the connection's limit, when new stream data is waiting that it /// will not let out and no DATA_BLOCKED has said so at this limit yet. /// Retransmissions spend no credit and do not count. fn owesDataBlocked(c: *Connection) ?u64 { if (!c.send_credit.blocked()) return null; const maximum = c.send_credit.limit; if (c.data_blocked_sent == maximum) return null; for (&c.streams) |*entry| { if (!entry.open or !entry.has_send) continue; if (entry.send.data.len > entry.send.data.sent) return maximum; } return null; } /// §4.1: a stream whose own limit is holding back new data, and that has /// not said so at this limit yet. fn owesStreamDataBlocked(c: *Connection) ?*StreamEntry { for (&c.streams) |*entry| { if (!entry.open or !entry.has_send or !entry.send.blocked()) continue; if (entry.data_blocked_sent == entry.send.credit.limit) continue; return entry; } return null; } /// §4.6: the kind of stream an open was refused for, while the limit that /// refused it stands and no STREAMS_BLOCKED has said so yet; an index into /// `peer_stream_limit`. fn owesStreamsBlocked(c: *const Connection) ?usize { for (c.streams_blocked_at, c.streams_blocked_sent, c.peer_stream_limit, 0..) |at, sent, limit, i| { if (at == limit and sent != limit) return i; } return null; } /// Whether any of §4.1's and §4.6's BLOCKED frames is owed. fn owesBlocked(c: *Connection) bool { return c.owesDataBlocked() != null or c.owesStreamDataBlocked() != null or c.owesStreamsBlocked() != null; } /// Whether a MAX_DATA or MAX_STREAM_DATA is worth sending. /// /// §4.2: "frequently sending MAX_STREAM_DATA and MAX_DATA frames with small /// changes is undesirable", and waiting too long blocks the sender for a /// round trip. Half a window is the usual middle, and it has a liveness /// argument: the peer can only stall after filling the window, which means /// the application must have been given a window's worth to read, which means /// reading half of it crosses this threshold. fn owesFlowControl(c: *const Connection) bool { if (c.flow_control_lost) return true; const window = c.local.initial_max_data; // An endpoint that advertised no credit is not extending any: a peer with // a limit of zero is waiting for a MAX_DATA that says something, and this // connection has nothing to say until its application asks it to. if (window > 0 and c.recv_consumed + window >= c.recv_credit.limit + window / 2) { return true; } for (&c.streams) |*entry| { // §19.10: MAX_STREAM_DATA is the receiver extending credit, so there // is none to extend on a stream this endpoint only sends on -- and a // peer receiving one for what is, from its side, a receive-only // stream "MUST terminate the connection with error // STREAM_STATE_ERROR". Offering credit to a stream with no receiving // half is not generosity; it is a connection error at the far end. // // Nor once the final size is known, from a FIN or a RESET_STREAM: // §3.2's "Size Known" state "no longer needs to send MAX_STREAM_DATA // frames", since the peer may send nothing past it. if (!entry.open or !entry.has_recv or entry.recv.final_size != null) continue; const stream_window_ = c.localStreamLimit(entry.id); if (stream_window_ == 0) continue; if (entry.recv.limitToAdvertise(stream_window_) >= entry.recv.credit.limit + stream_window_ / 2) { return true; } } return false; } /// Writes whatever flow control updates are owed, and records the new limits /// as granted. /// /// Ordinarily only a limit that has moved far enough is worth a frame. After /// a loss (`flow_control_lost`) every current limit goes, whether or not it /// has moved: §13.3 sends "an updated value" when the packet carrying the /// last one is lost, and the limit recorded here is one the peer may never /// have heard. Which frames the lost packet held is not remembered, so all /// of them go -- a loss is rare, and a frame too many costs a few octets. fn addFlowControl(c: *Connection, b: *packet.Builder) bool { var wrote = false; const again = c.flow_control_lost; const window = c.local.initial_max_data; const connection_limit = @max(c.recv_consumed + window, c.recv_credit.limit); if (window > 0 and (again or connection_limit >= c.recv_credit.limit + window / 2)) { b.add(.{ .max_data = connection_limit }) catch return wrote; c.recv_credit.limit = connection_limit; wrote = true; } for (&c.streams) |*entry| { // The same §19.10 and §3.2 rules as in `owesFlowControl`. if (!entry.open or !entry.has_recv or entry.recv.final_size != null) continue; const stream_window_ = c.localStreamLimit(entry.id); if (stream_window_ == 0) continue; const limit = @max(entry.recv.limitToAdvertise(stream_window_), entry.recv.credit.limit); if (!again and limit < entry.recv.credit.limit + stream_window_ / 2) continue; b.add(.{ .max_stream_data = .{ .stream = entry.id.value, .maximum = limit } }) catch return wrote; entry.recv.credit.limit = limit; wrote = true; } // Only once everything owed has gone; a packet too full for the rest // leaves the flag for the next one. c.flow_control_lost = false; return wrote; } /// RFC 9221 §4: puts as many queued datagrams in the packet as fit. /// /// Each goes with a Length field even though the last one in a packet need /// not have: the saving is one or two octets and the cost is that nothing may /// follow, and a packet is built by adding frames in an order this function /// does not get to see the end of. A frame that cannot be followed has to be /// the last thing written, and knowing that it is means knowing what the /// caller will do next. fn addDatagrams(c: *Connection, b: *packet.Builder) bool { var wrote = false; while (c.outbound.peek()) |payload| { if (b.remaining() < datagramFrameLen(payload.len)) break; b.add(.{ .datagram = .{ .data = payload, .had_length = true } }) catch break; c.outbound.pop(); wrote = true; } return wrote; } /// Puts as much stream data in the packet as fits, the window allows, and the /// loss record can remember. fn addStreams(c: *Connection, b: *packet.Builder, record: *recovery.Sent) bool { var wrote = false; // §3.5's request to the peer, which belongs to the receiving half and so // is gathered separately from everything below. One per packet, because // the loss record remembers one: any other waits for the next packet. for (&c.streams) |*entry| { if (!entry.open or !entry.has_recv or !entry.recv.stop_pending) continue; b.add(.{ .stop_sending = .{ .stream = entry.id.value, .error_code = entry.recv.stop_code, } }) catch return wrote; entry.recv.stopSent(); record.stop_sending = entry.id.value; wrote = true; break; } for (&c.streams) |*entry| { if (!entry.open or !entry.has_send) continue; // §3.5: a stream this endpoint has abandoned says so, until the // peer acknowledges it (§13.3), and says nothing else. "A sender MUST // NOT send any STREAM... frames on a stream in the 'Reset Sent' // state", so the reset replaces the data rather than accompanying // it. One reset per packet, for the same reason as above. // // Neither frame is subject to flow control: §4.1's limits are on data // and these carry none. if (entry.send.reset_pending) { if (record.reset_stream != null) continue; b.add(.{ .reset_stream = .{ .stream = entry.id.value, .error_code = entry.send.reset_code orelse 0, .final_size = entry.send.finalSize(), } }) catch return wrote; entry.send.resetSent(); record.reset_stream = entry.id.value; wrote = true; continue; } if (entry.send.state == .reset_sent) continue; if (record.stream_count == recovery.max_stream_ranges) break; const room = b.remaining(); if (room <= stream_frame_overhead) break; var budget = room - stream_frame_overhead; // §4.1: connection flow control limits "the total bytes of stream // data sent in STREAM frames on all streams", so it is spent here // rather than in the stream, which knows only about itself. // §4.1 counts connection flow control in offsets rather than in // transmissions: "the sum of the final sizes on all streams". So a // retransmission of octets already counted spends nothing, and -- // the half that matters -- may not be refused when there is nothing // left to spend. Refusing it deadlocks the connection, because the // credit that would pay for it is granted by a peer that is waiting // for exactly those octets. const resending = entry.send.data.resending(); if (!resending) { const connection_room = c.send_credit.available(); if (connection_room == 0) break; budget = @min(budget, @as(usize, @intCast(@min(connection_room, @as(u64, budget))))); } const chunk = entry.send.next(budget) orelse continue; b.add(.{ .stream = .{ .stream = entry.id.value, .offset = chunk.offset, .data = chunk.data, .fin = chunk.fin, // An explicit Length, so that another frame may follow. §19.8 // lets it be omitted, and then "the Stream Data field consumes // all the remaining bytes in the packet" — which is only ever // right for the last frame of a packet and is a trap to reach for // while building one. .had_length = true, }, }) catch break; // The watermark's movement and not the chunk's length, which are the // same thing for new data and differ for a retransmission: charging // per transmission burns credit the peer never granted, and a // connection that retransmits enough runs out of a window it has // barely used. Two streams and a tracking table too small to hold // both of their flights was enough to spend sixty-four megabytes of // credit on a hundred and thirty kilobytes of body. const before = entry.send.data.sent; entry.send.advance(chunk); c.send_credit.used += entry.send.data.sent - before; _ = record.addStream(.{ .stream = entry.id.value, .offset = chunk.offset, .len = chunk.data.len, .fin = chunk.fin, }); wrote = true; } return wrote; } const testing = std.testing; // -- the fixture the doctests share ------------------------------------------ // // Referenced only from tests, so none of it reaches a normal build. const tls_handshake = @import("tls_handshake.zig"); /// The connection IDs a test pair chooses for itself, and the one the client /// invents for the server's Initial keys (§7.2). const test_client_id = [_]u8{ 0xc1, 0xc2, 0xc3, 0xc4 }; const test_server_id = [_]u8{ 0x5e, 0x51 }; const test_destination_id = [_]u8{ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08 }; /// What a test pair advertises unless a doctest says otherwise. §18.2's /// defaults are zero streams and zero credit, a connection that can carry /// nothing, so these are the least that makes streams possible. const test_limits: parameters.Parameters = .{ .initial_max_data = 8192, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_stream_data_uni = 2048, .initial_max_streams_bidi = 4, .initial_max_streams_uni = 3, }; /// `test_limits`, taking unreliable datagrams (RFC 9221). const test_datagram_limits: parameters.Parameters = limits: { var p = test_limits; p.max_datagram_frame_size = max_datagram_len; break :limits p; }; /// `test_limits`, with multipath and one path besides path 0. const test_multipath_limits: parameters.Parameters = limits: { var p = test_limits; p.initial_max_path_id = 1; break :limits p; }; /// `test_multipath_limits`, with n0's NAT traversal. const test_nat_limits: parameters.Parameters = limits: { var p = test_multipath_limits; p.n0_nat_traversal = 8; break :limits p; }; /// A server's limits naming a preferred address. Its identifier is the same /// length as `test_server_id`, as every identifier one endpoint issues is. const test_preferred_id = [_]u8{ 0xc1, 0xd0 }; const test_preferred_limits: parameters.Parameters = limits: { var p = test_limits; p.preferred_address = .{ .ipv4 = .{ 192, 0, 2, 1 }, .ipv4_port = 8853, .connection_id = &test_preferred_id, .stateless_reset_token = @splat(0x7e), }; break :limits p; }; /// `test_limits` as a client hands them to TLS. const test_client_parameters = encoded: { var buffer: [128]u8 = undefined; var p = test_limits; p.initial_source_connection_id = &test_client_id; const written = parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; /// Randomness for a TLS client built outside a `TestPair`. A global so that /// the `std.Random` handed out cannot outlive what it points at. var test_rng: std.Random.DefaultPrng = .init(0x9000); fn testTlsClient(encoded: []const u8) !tls_handshake.Client { return .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = encoded, .rng = test_rng.random(), .now_sec = 0, .insecure_skip_verify = true, }); } /// The default test pair: default sizes, with room for one path besides /// path 0 so that the multipath doctests can share it. const TestPair = TestPairSized(.{ .paths = 2 }); /// A client and a server, each a `Connection`, and the datagrams between /// them carried by hand. Heap allocated, because a connection may not move /// once initialized and neither may the TLS it borrows. fn TestPairSized(comptime sizes: Sizes) type { return struct { const Pair = @This(); client: Connection, server: Connection, client_tls: tls_handshake.Client, server_tls: tls_handshake.Server, client_memory: Storage(sizes), server_memory: Storage(sizes), client_params: [256]u8, server_params: [256]u8, rng: std.Random.DefaultPrng, /// The clock: each datagram delivered moves it a millisecond. now: recovery.Instant, /// Scratch for a doctest's own `send` calls. buffer: [2048]u8, /// Two connections that have exchanged nothing yet, each /// advertising its own limits -- to TLS and to `init` alike. fn create(client_local: parameters.Parameters, server_local: parameters.Parameters) !*Pair { const p = try testing.allocator.create(Pair); errdefer testing.allocator.destroy(p); p.now = 0; p.rng = .init(0x9000); const rng = p.rng.random(); var c = client_local; c.initial_source_connection_id = &test_client_id; const client_encoded = try parameters.write(&c, &p.client_params, .client); var s = server_local; s.initial_source_connection_id = &test_server_id; s.original_destination_connection_id = &test_destination_id; const server_encoded = try parameters.write(&s, &p.server_params, .server); p.client_tls = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = client_encoded, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); p.server_tls = .init(.{ .auth = null, .transport_parameters = server_encoded, .alpn_protocols = &.{"doq"}, .rng = rng, }); p.client_memory = .{}; p.server_memory = .{}; p.client.init(.{ .role = .client, .memory = p.client_memory.memory(), .handshake = p.client_tls.handshake(), .local_id = &test_client_id, .destination_id = &test_destination_id, .local = client_local, .rng = rng, }); p.server.init(.{ .role = .server, .memory = p.server_memory.memory(), .handshake = p.server_tls.handshake(), .local_id = &test_server_id, .local = server_local, .rng = rng, }); return p; } /// Two connections with the handshake done and everything after it /// delivered. fn connect(client_local: parameters.Parameters, server_local: parameters.Parameters) !*Pair { const p = try create(client_local, server_local); errdefer p.destroy(); try p.handshake(); try p.settle(); return p; } fn destroy(p: *Pair) void { testing.allocator.destroy(p); } /// Moves datagrams until both ends are established and the client's /// handshake is confirmed. fn handshake(p: *Pair) !void { for (0..16) |_| { if (p.client.isEstablished() and p.server.isEstablished() and p.client.isConfirmed()) return; if (!try p.step()) break; } try testing.expect(p.client.isEstablished() and p.server.isEstablished() and p.client.isConfirmed()); } /// Moves datagrams until neither end has anything more to say. fn settle(p: *Pair) !void { for (0..256) |_| { if (!try p.step()) return; } return error.NeverSettled; } /// One datagram each way, if either end has one; false if neither did. fn step(p: *Pair) !bool { var moved = false; if (try p.client.send(&p.buffer, p.now)) |datagram| { p.now += std.time.ns_per_ms; try p.server.receive(datagram.bytes, datagram.path, p.now); moved = true; } if (try p.server.send(&p.buffer, p.now)) |datagram| { p.now += std.time.ns_per_ms; try p.client.receive(datagram.bytes, datagram.path, p.now); moved = true; } return moved; } }; } /// Everything `p.server` sends over `rounds` of its own timers, with nothing /// from the client in between. fn testServerAlone(p: anytype, rounds: usize) !u64 { var total: u64 = 0; for (0..rounds) |_| { while (try p.server.send(&p.buffer, p.now)) |d| total += d.bytes.len; const deadline = p.server.timeout() orelse break; p.now = @max(p.now, deadline); p.server.onTimeout(p.now); } return total; } test "RFC 9000 8.1: a server sends no more than three times what an unvalidated client sent" { // "Prior to validating the client address, servers MUST NOT send more // than three times as many bytes as the number of bytes they have // received." An Initial from a forged address gets the handshake flight // and its retransmissions back -- at someone else -- for as long as the // server keeps trying, and only this limit keeps that from being an // amplifier. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const first = (try p.client.send(&p.buffer, p.now)).?; const received = first.bytes.len; try p.server.receive(first.bytes, first.path, p.now); const sent = try testServerAlone(p, 20); try testing.expect(sent > 0); try testing.expect(sent <= received * paths_mod.Paths.amplification_factor); } test "RFC 9000 8.1: a client with nothing in flight still unblocks a server at its limit" { // "To prevent this deadlock, clients MUST send a packet on a Probe // Timeout (PTO)... Specifically, the client MUST send an Initial packet // in a UDP datagram that contains at least 1200 bytes if it does not // have Handshake keys, and otherwise send a Handshake packet." The case // it is for: the client's Initial has been acknowledged, so it has // nothing in flight and no reason of its own to send; the server's // Handshake flight was lost, and it has spent its allowance sending it // again. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const first = (try p.client.send(&p.buffer, p.now)).?; try p.server.receive(first.bytes, first.path, p.now); // The server's first datagram is its Initial and its Handshake packets // together. Only the Initial gets through. const flight = (try p.server.send(&p.buffer, p.now)).?; const initial = try packet.parse(flight.bytes, test_client_id.len); try testing.expect(initial.end < flight.bytes.len); p.now += std.time.ns_per_ms; try p.client.receive(flight.bytes[0..initial.end], flight.path, p.now); // The client acknowledges it, and the acknowledgement arrives. while (try p.client.send(&p.buffer, p.now)) |d| try p.server.receive(d.bytes, d.path, p.now); // Everything else the server sends is lost, until it may send no more. _ = try testServerAlone(p, 100); try testing.expect(p.server.paths.sendable(0) < min_packet_room); // And a server that cannot send has no business waking to try. try testing.expectEqual(@as(?recovery.Instant, null), p.server.probeDeadline()); // From here the network is perfect, and the client's timer is what // starts it moving again. for (0..50) |_| { if (p.client.isConfirmed()) break; if (!try p.step()) { const client_at = p.client.timeout() orelse std.math.maxInt(u64); const server_at = p.server.timeout() orelse std.math.maxInt(u64); const next = @min(client_at, server_at); if (next == std.math.maxInt(u64)) break; p.now = @max(p.now, next); p.client.onTimeout(p.now); p.server.onTimeout(p.now); } } try testing.expect(p.client.isConfirmed()); } test "RFC 9000 8.1: a client's Handshake packet validates its address" { // "In particular, receipt of a packet protected with Handshake keys // confirms that the peer successfully processed an Initial packet." const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); try testing.expect(!p.server.pathValidated(0)); try p.handshake(); try testing.expect(p.server.pathValidated(0)); try testing.expect(p.client.pathValidated(0)); } test "RFC 9000 8.1: a server told the client's address is proved sends without the limit" { // §8.1.2: a client that came back with a valid Retry token has shown it // receives at the address it claims, which is all validation asks. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); p.server.init(.{ .role = .server, .memory = p.server_memory.memory(), .handshake = p.server_tls.handshake(), .local_id = &test_server_id, .local = test_limits, .rng = p.rng.random(), .address_validated = true, }); const first = (try p.client.send(&p.buffer, p.now)).?; try p.server.receive(first.bytes, first.path, p.now); try testing.expectEqual(@as(usize, std.math.maxInt(usize)), p.server.paths.sendable(0)); } /// Runs `p`, timers and all, until `done(p)`, losing one datagram on the /// way: the first one `from_client` (or from the server) across whose /// sending `marker(p)` changes -- the one that carried the frame under test. /// The server's application reads `read`, if given, as it arrives. fn testLoseOnce( p: *TestPair, comptime from_client: bool, comptime marker: fn (*TestPair) u64, comptime done: fn (*TestPair) bool, read: ?stream.Id, ) !void { var dropped = false; for (0..400) |_| { if (done(p)) break; var moved = false; { const before = marker(p); if (try p.client.send(&p.buffer, p.now)) |d| { moved = true; if (from_client and !dropped and marker(p) != before) { dropped = true; } else { p.now += std.time.ns_per_ms; try p.server.receive(d.bytes, d.path, p.now); } } } if (read) |id| p.server.consume(id, p.server.readable(id).len); { const before = marker(p); if (try p.server.send(&p.buffer, p.now)) |d| { moved = true; if (!from_client and !dropped and marker(p) != before) { dropped = true; } else { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); } } } if (moved) continue; const client_at = p.client.timeout() orelse std.math.maxInt(u64); const server_at = p.server.timeout() orelse std.math.maxInt(u64); const next = @min(client_at, server_at); if (next == std.math.maxInt(u64)) break; p.now = @max(p.now, next); p.client.onTimeout(p.now); p.server.onTimeout(p.now); } try testing.expect(dropped); try testing.expect(done(p)); } test "RFC 9000 13.3: a lost HANDSHAKE_DONE is sent again" { // "The HANDSHAKE_DONE frame MUST be retransmitted until it is // acknowledged." It is the only way this client learns its handshake is // confirmed, and an unconfirmed client cannot migrate, update keys or // drop its Handshake keys. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const S = struct { fn marker(q: *TestPair) u64 { return @intFromBool(q.server.owes_handshake_done); } fn done(q: *TestPair) bool { return q.client.isConfirmed(); } }; try testLoseOnce(p, false, S.marker, S.done, null); } test "RFC 9000 4.1: a sender held back by the connection's limit says so" { // "A sender SHOULD send a STREAM_DATA_BLOCKED or DATA_BLOCKED frame to // indicate to the receiver that it has data to write but is blocked by // flow control limits." var limits = test_limits; limits.initial_max_data = 1000; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const id = try p.client.openBidirectional(); const body: [1500]u8 = @splat('d'); try p.client.write(id, &body); try p.settle(); try testing.expectEqual(@as(?u64, 1000), p.server.peer_data_blocked); } test "RFC 9000 4.1: a sender held back by a stream's limit says so" { var limits = test_limits; limits.initial_max_stream_data_bidi_remote = 500; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const id = try p.client.openBidirectional(); const body: [800]u8 = @splat('d'); try p.client.write(id, &body); try p.settle(); try testing.expectEqual(@as(u64, 500), p.server.peer_stream_data_blocked.?.maximum); // Once per limit: nothing more is owed while it stands. try testing.expect(!p.client.owesBlocked()); } test "RFC 9000 4.6: a sender that cannot open a stream says so" { // "A sender SHOULD send a STREAMS_BLOCKED frame (type=0x16 or 0x17) // when it wishes to open a stream but is unable to do so due to the // maximum stream limit set by its peer." var limits = test_limits; limits.initial_max_streams_bidi = 1; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); _ = try p.client.openBidirectional(); try testing.expectError(error.StreamLimitError, p.client.openBidirectional()); try p.settle(); try testing.expectEqual(@as(?u64, 1), p.server.peer_streams_blocked[0]); try testing.expectEqual(@as(?u64, null), p.server.peer_streams_blocked[1]); } test "RFC 9000 13.3: a lost DATA_BLOCKED is sent again while still blocked" { // "A new frame is sent if a packet containing the most recent frame for // a scope is lost, but only while the endpoint is blocked on the // corresponding limit." var limits = test_limits; limits.initial_max_data = 1000; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const id = try p.client.openBidirectional(); const body: [1500]u8 = @splat('d'); try p.client.write(id, &body); const S = struct { fn marker(q: *TestPair) u64 { return q.client.data_blocked_sent orelse 0; } fn done(q: *TestPair) bool { return q.server.peer_data_blocked != null; } }; try testLoseOnce(p, true, S.marker, S.done, null); } /// Three thousand octets on a stream the client opens, against a server /// whose `limits` hold them back until its application has read some. fn testLoseCredit(limits: parameters.Parameters, comptime marker: fn (*TestPair) u64) !void { const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const id = try p.client.openBidirectional(); const body: [3000]u8 = @splat('c'); try p.client.write(id, &body); const S = struct { fn done(q: *TestPair) bool { return q.server.recv_consumed == body.len; } }; try testLoseOnce(p, false, marker, S.done, id); } test "RFC 9000 13.3: a lost MAX_DATA is sent again" { // "An updated value is sent in a MAX_DATA frame if the packet containing // the most recently sent MAX_DATA frame is declared lost". Without it a // sender blocked at the old limit waits for credit the receiver believes // it has given. var limits = test_limits; limits.initial_max_data = 1000; const S = struct { fn marker(q: *TestPair) u64 { return q.server.recv_credit.limit; } }; try testLoseCredit(limits, S.marker); } test "RFC 9000 13.3: a lost MAX_STREAM_DATA is sent again" { // "...updated value is sent when the packet containing the most recent // MAX_STREAM_DATA frame for a stream is lost or when the limit is // updated". var limits = test_limits; limits.initial_max_data = 8192; limits.initial_max_stream_data_bidi_remote = 1000; const S = struct { fn marker(q: *TestPair) u64 { const entry = q.server.find(0) orelse return 0; return entry.recv.credit.limit; } }; try testLoseCredit(limits, S.marker); } test "a stream this endpoint opens leaves room for the ones its peer may" { // The table is shared, and the peer's streams are promised: an endpoint // that advertised four and three may be sent seven at once, and a peer // that keeps to that has done nothing wrong if they do not fit. So this // endpoint's own streams stop where the peer's begin, and the refusal is // a `NoRoom` to the caller here rather than an INTERNAL_ERROR there. // Thirteen for the client, which leaves the server three of its own. var generous = test_limits; generous.initial_max_streams_bidi = 13; generous.initial_max_streams_uni = 0; const p = try TestPair.connect(test_limits, generous); defer p.destroy(); var opened: usize = 0; while (p.client.openBidirectional()) |_| { opened += 1; } else |err| try testing.expectEqual(error.NoRoom, err); try testing.expectEqual(max_streams - 4 - 3, opened); // Every slot left is one the server may still claim. try testing.expectEqual(@as(usize, 4 + 3), p.client.peerStreamsOwed()); // And once the server has used some, they are no longer held for it. try p.server.write(try p.server.openUnidirectional(), "u"); try p.settle(); try testing.expectEqual(@as(usize, 4 + 2), p.client.peerStreamsOwed()); try testing.expectEqual(error.NoRoom, p.client.openBidirectional()); } test "RFC 9000 3.2: no MAX_STREAM_DATA once the final size is known" { // "When a STREAM frame with a FIN bit is received, the final size of the // stream is known ... In this state, the endpoint no longer needs to send // MAX_STREAM_DATA frames". The peer can send nothing past the final size, // so more credit is a frame spent on nothing. var limits = test_limits; limits.initial_max_data = 8192; limits.initial_max_stream_data_bidi_remote = 1000; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const id = try p.client.openBidirectional(); const body: [900]u8 = @splat('f'); try p.client.write(id, &body); try p.client.finishStream(id); try p.settle(); // More than half the window read: without the final size, worth a frame. try testing.expectEqual(body.len, p.server.readable(id).len); p.server.consume(id, 600); try testing.expect(!p.server.owesFlowControl()); try p.settle(); try testing.expectEqual(@as(u64, 1000), p.server.find(id.value).?.recv.credit.limit); } test "RFC 9000 13.3: a lost MAX_STREAMS is sent again" { // "...updated value is sent when a packet containing the most recent // MAX_STREAMS for a stream type frame is declared lost". A client that // has used every stream it was given has no other way to get more. var limits = test_limits; limits.initial_max_streams_uni = 1; const p = try TestPair.connect(test_limits, limits); defer p.destroy(); const id = try p.client.openUnidirectional(); try p.client.write(id, "the only one"); try p.client.finishStream(id); try testing.expectError(error.StreamLimitError, p.client.openUnidirectional()); const S = struct { fn marker(q: *TestPair) u64 { return @intFromBool(q.server.owes_max_streams[1]); } fn done(q: *TestPair) bool { return q.client.peer_stream_limit[1] >= 2; } }; try testLoseOnce(p, false, S.marker, S.done, id); _ = try p.client.openUnidirectional(); } test "RFC 9000 13.3: a lost NEW_CONNECTION_ID is sent again" { // "New connection IDs are sent in NEW_CONNECTION_ID frames and // retransmitted if the packet containing them is lost." The lost one // still counts against the peer's limit, so issuing a fresh one instead // is not an option -- the peer would be left without a spare to migrate // with. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const S = struct { fn marker(q: *TestPair) u64 { return q.client.issued.next_sequence; } fn done(q: *TestPair) bool { return q.server.received.active() >= 2; } }; try testLoseOnce(p, true, S.marker, S.done, null); } test "an absurd ack delay saturates rather than overflowing" { // A peer writes the Ack Delay field, and §19.3 lets it be any varint // below 2^62. Scaling that by 8 and then by 1000 to reach nanoseconds // overflows a u64 for values that fit in four octets -- and an overflow // is a panic, which is to say a remote crash. try testing.expectEqual(@as(u64, 8000), scaledAckDelay(1, ack_delay_exponent)); try testing.expectEqual(@as(u64, 25 * std.time.ns_per_ms), scaledAckDelay(3125, ack_delay_exponent)); try testing.expectEqual( @as(u64, std.math.maxInt(u64)), scaledAckDelay((1 << 62) - 1, ack_delay_exponent), ); // And a peer that negotiated a larger exponent cannot use it to overflow // either: §18.2 caps it at 20, and even the cap saturates. try testing.expectEqual(@as(u64, std.math.maxInt(u64)), scaledAckDelay((1 << 62) - 1, 20)); // And what a saturated delay does to the estimator is nothing, because // §5.3 refuses to subtract a delay that would put the sample below the // minimum ever measured. var rtt: recovery.Rtt = .{}; rtt.sample(100 * std.time.ns_per_ms, 0, 0, false); const before = rtt.smoothed; rtt.sample(100 * std.time.ns_per_ms, scaledAckDelay((1 << 62) - 1, ack_delay_exponent), default_max_ack_delay, false); try testing.expectEqual(before, rtt.smoothed); } test "RFC 9000 12.3: a duplicated packet is processed once" { // §12.3: "a receiver MUST discard a newly unprotected packet unless it is // certain that it has not processed another packet with the same packet // number from the same packet number space." Most frames are harmless to // repeat; a DATAGRAM is not, since the application would read it twice. const p = try TestPair.connect(test_datagram_limits, test_datagram_limits); defer p.destroy(); try p.client.sendDatagram("once"); const d = (try p.client.send(&p.buffer, p.now)).?; // Receiving unmasks the header in place, so each delivery gets a copy. var first: [max_datagram_len]u8 = undefined; var second: [max_datagram_len]u8 = undefined; @memcpy(first[0..d.bytes.len], d.bytes); @memcpy(second[0..d.bytes.len], d.bytes); try p.server.receive(first[0..d.bytes.len], d.path, p.now); try p.server.receive(second[0..d.bytes.len], d.path, p.now); try testing.expectEqualStrings("once", p.server.readDatagram().?); p.server.takeDatagram(); try testing.expectEqual(@as(?[]const u8, null), p.server.readDatagram()); } test "RFC 9000 13.1: an acknowledgment of a packet never sent is an error" { // §13.1: "An endpoint SHOULD treat receipt of an acknowledgment for a // packet it did not send as a connection error of type // PROTOCOL_VIOLATION, if it is able to detect the condition." A peer // claiming to have received packets ahead of the sender is acknowledging // optimistically, to be sent faster than the path allows. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const unsent = p.client.spaces[2].next_number; const a: frame.Ack = .{ .largest = unsent, .delay = 0, .first_range = 0, .range_count = 0, .encoded_ranges = &.{}, .ecn = null, }; try testing.expectError(error.ProtocolViolation, p.client.onAck(.application, a, p.now)); // One below is a packet that went, and is no error. var sent = a; sent.largest = unsent - 1; try p.client.onAck(.application, sent, p.now); } test "RFC 9000 17.2.5.2: no Retry is acted on after a server Initial without an ACK" { // "After the client has received and processed an Initial or Retry // packet from the server, it MUST discard any subsequent Retry packets // that it receives." Processed, whatever it carried: a server Initial // holding only a PING acknowledges nothing, and still counts. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const hello = (try p.client.send(&p.buffer, p.now)).?; try p.server.receive(hello.bytes, 0, p.now); const space = &p.server.spaces[0]; var buffer: [1300]u8 = undefined; var b = try packet.Builder.initLong(&buffer, .{ .kind = .initial, .destination = p.server.peerId(), .source = p.server.localId(), }, space.next_number, 4); b.buffer[b.at] = 0x01; // PING b.at += 1; try b.padTo(1200 - b.at); space.next_number += 1; const ping = try b.finish(&space.write.?); try p.client.receive(ping, 0, p.now); try testing.expect(p.client.peer_id_confirmed); var retry_buffer: [128]u8 = undefined; const retry = try retry_mod.write(&retry_buffer, &test_destination_id, &test_client_id, &.{ 5, 6 }, "token"); try p.client.receive(retry, 0, p.now); try testing.expect(!p.client.retry_seen); try testing.expectEqualSlices(u8, p.server.localId(), p.client.peerId()); } test "RFC 9000 6.2: a discarded Version Negotiation packet does not block a Retry" { // A Version Negotiation packet listing the version the client chose is // discarded (§6.2), so it was never "received and processed" -- and a // forged one must not stop the client accepting the server's Retry. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); _ = (try p.client.send(&p.buffer, p.now)).?; var negotiation = [_]u8{ 0x80, 0, 0, 0, 0, test_client_id.len } ++ test_client_id ++ [_]u8{test_destination_id.len} ++ test_destination_id ++ [_]u8{ 0, 0, 0, 1 }; try p.client.receive(&negotiation, 0, p.now); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); var retry_buffer: [128]u8 = undefined; const retry = try retry_mod.write(&retry_buffer, &test_destination_id, &test_client_id, &.{ 5, 6 }, "token"); try p.client.receive(retry, 0, p.now); try testing.expect(p.client.retry_seen); } test "RFC 9000 17.2.5: a Retry sent to a server is dropped" { // Only a server sends Retry, and §17.2.5.2 has a client discard the ones // it cannot use. One arriving at a server can only have been written by // somebody else, and the header is unauthenticated -- if it closed the // connection, anyone who knew the server's connection ID could close // every connection it has. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const retry = try retry_mod.write(&buffer, &.{ 1, 2, 3, 4 }, p.server.localId(), &.{ 5, 6 }, "token"); try p.server.receive(retry, 0, p.now); try testing.expectEqual(termination.State.open, p.server.closing.state); const id = try p.client.openBidirectional(); try p.client.write(id, "unbothered"); try p.settle(); try testing.expectEqualStrings("unbothered", p.server.readable(id)); } /// A 1-RTT packet from `from` to its peer carrying `payload` as it is, with /// `first_bits` or'd into the first octet before protection -- for the /// packets `send` would never build. fn testSealShort(from: *Connection, out: []u8, payload: []const u8, first_bits: u8) ![]u8 { const space = &from.spaces[2]; var b = try packet.Builder.initShort(out, from.peerId(), space.next_number, 4, from.key_phase); b.buffer[0] |= first_bits; @memcpy(b.buffer[b.at..][0..payload.len], payload); b.at += payload.len; space.next_number += 1; return b.finishOn(&space.write.?, 0); } test "RFC 9000 7.2: a client discards a packet from another Source Connection ID" { // "Once a client has received a valid Initial packet from the server, it // MUST discard any subsequent packet it receives on that connection with // a different Source Connection ID." const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); while (!p.client.peer_id_confirmed or p.client.spaces[1].read == null) { try testing.expect(try p.step()); } // A Handshake packet the server's keys protect, carrying a // CONNECTION_CLOSE that would end the connection if it were read. const space = &p.server.spaces[1]; var buffer: [128]u8 = undefined; var b = try packet.Builder.initLong(&buffer, .{ .kind = .handshake, .destination = p.server.peerId(), .source = &.{ 0xab, 0xcd }, }, space.next_number, 4); const close_frame = [_]u8{ 0x1c, 0x00, 0x00, 0x00 }; @memcpy(b.buffer[b.at..][0..close_frame.len], &close_frame); b.at += close_frame.len; space.next_number += 1; const sealed = try b.finish(&space.write.?); try p.client.receive(sealed, 0, p.now); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); } test "RFC 9000 12.2: a coalesced packet for another Destination Connection ID is ignored" { // "Senders MUST NOT coalesce QUIC packets with different connection IDs // into a single UDP datagram. Receivers SHOULD ignore any subsequent // packets with a different Destination Connection ID than the first // packet in the datagram." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var datagram: [256]u8 = undefined; // An Initial addressed elsewhere, which this client has no keys left // to read... const initial = [_]u8{ 0xc3, 0, 0, 0, 1, 4, 0xee, 0xee, 0xee, 0xee, 0, 0, 20 } ++ @as([20]u8, @splat(0x55)); @memcpy(datagram[0..initial.len], &initial); // ...and behind it a 1-RTT packet addressed to the client, which would // close the connection if it were read. const close_frame = [_]u8{ 0x1c, 0x00, 0x00, 0x00 }; const short = try testSealShort(&p.server, datagram[initial.len..], &close_frame, 0); try p.client.receive(datagram[0 .. initial.len + short.len], 0, p.now); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); } test "RFC 9000 9: a client discards packets from an unknown server address" { // "Servers do not send non-probing packets (see Section 9.1) toward a // client address until they see a non-probing packet from that address. // If a client receives packets from an unknown server address, the // client MUST discard these packets." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const close_frame = [_]u8{ 0x1c, 0x00, 0x00, 0x00 }; const sealed = try testSealShort(&p.server, &buffer, &close_frame, 0); try p.client.receive(sealed, 3, p.now); try testing.expectEqual(@as(?termination.State, null), p.client.closeState()); try testing.expectEqual(@as(?*paths_mod.Path, null), p.client.paths.find(3)); } test "RFC 9000 17.3.1: reserved bits that are set close the connection" { // "An endpoint MUST treat receipt of a packet that has a non-zero value // for these bits, after removing both packet and header protection, as a // connection error of type PROTOCOL_VIOLATION." Not a packet to drop: // it authenticated, so the peer sent it. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const bad = try testSealShort(&p.client, &buffer, &.{0x01}, 0x18); try testing.expectError(error.ProtocolViolation, p.server.receive(bad, 0, p.now)); try testing.expectEqual(termination.Code.protocol_violation, p.server.closing.code); } test "RFC 9000 12.4: a packet with no frames closes the connection" { // "An endpoint MUST treat receipt of a packet containing no frames as a // connection error of type PROTOCOL_VIOLATION." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const empty = try testSealShort(&p.client, &buffer, &.{}, 0); try testing.expectError(error.ProtocolViolation, p.server.receive(empty, 0, p.now)); try testing.expectEqual(termination.Code.protocol_violation, p.server.closing.code); } test "RFC 9000 12.4: an unknown frame type is a FRAME_ENCODING_ERROR" { // "An endpoint MUST treat the receipt of a frame of unknown type as a // connection error of type FRAME_ENCODING_ERROR." Saying // PROTOCOL_VIOLATION instead tells the peer less than the truth. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const bad = try testSealShort(&p.client, &buffer, &.{0x21}, 0); try testing.expectError(error.FrameEncodingError, p.server.receive(bad, 0, p.now)); try testing.expectEqual(termination.Code.frame_encoding_error, p.server.closing.code); } test "RFC 9000 19.3.1: an ACK range below zero is a FRAME_ENCODING_ERROR" { // "If any computed packet number is negative, an endpoint MUST generate // a connection error of type FRAME_ENCODING_ERROR." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; // Largest Acknowledged 1, no delay, no further ranges, and a First ACK // Range of 5, which reaches down to -4. const bad = try testSealShort(&p.client, &buffer, &.{ 0x02, 0x01, 0x00, 0x00, 0x05 }, 0); try testing.expectError(error.FrameEncodingError, p.server.receive(bad, 0, p.now)); try testing.expectEqual(termination.Code.frame_encoding_error, p.server.closing.code); } test "RFC 9000 19.7: a NEW_TOKEN is the server's to send" { // "A server MUST treat receipt of a NEW_TOKEN frame as a connection // error of type PROTOCOL_VIOLATION." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const bad = try testSealShort(&p.client, &buffer, &.{ 0x07, 0x02, 0xab, 0xcd }, 0); try testing.expectError(error.ProtocolViolation, p.server.receive(bad, 0, p.now)); } test "RFC 9000 19.7: an empty NEW_TOKEN is a FRAME_ENCODING_ERROR" { // "A client MUST treat receipt of a NEW_TOKEN frame with an empty Token // field as a connection error of type FRAME_ENCODING_ERROR." const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); var buffer: [128]u8 = undefined; const bad = try testSealShort(&p.server, &buffer, &.{ 0x07, 0x00 }, 0); try testing.expectError(error.FrameEncodingError, p.client.receive(bad, 0, p.now)); // One with a token in it is fine. const q = try TestPair.connect(test_limits, test_limits); defer q.destroy(); const good = try testSealShort(&q.server, &buffer, &.{ 0x07, 0x02, 0xab, 0xcd }, 0); try q.client.receive(good, 0, q.now); } test "RFC 9000 19.13: STREAM_DATA_BLOCKED on a send-only stream is an error" { // "An endpoint that receives a STREAM_DATA_BLOCKED frame for a send-only // stream MUST terminate the connection with error STREAM_STATE_ERROR." // The client's unidirectional stream 2 is one the server can only read, // so the server has nothing to be blocked sending on it. const p = try TestPair.connect(test_limits, test_limits); defer p.destroy(); const id = try p.client.openUnidirectional(); try testing.expectEqual(@as(u64, 2), id.value); var buffer: [128]u8 = undefined; const bad = try testSealShort(&p.server, &buffer, &.{ 0x15, 0x02, 0x00 }, 0); try testing.expectError(error.StreamStateError, p.client.receive(bad, 0, p.now)); } test "RFC 9000 12.2: a packet that cannot be read does not cost the ones after it" { // "If decryption fails (because the keys are not available or for any // other reason), the receiver MAY either discard or buffer the packet // for later processing and MUST attempt to process the remaining // packets." A Handshake packet reaching a server that has discarded its // Handshake keys is the ordinary case: a client still acknowledging the // handshake coalesces that with its 1-RTT data. const p = try TestPair.connect(test_datagram_limits, test_datagram_limits); defer p.destroy(); try testing.expect(p.server.discarded[1]); var datagram: [512]u8 = undefined; const stale_keys: protection.Keys = .initialKeys(&.{0xab}, .client); var b = try packet.Builder.initLong(&datagram, .{ .kind = .handshake, .destination = p.server.localId(), .source = p.client.localId(), }, 9, 4); try b.add(.ping); try b.padTo(64); const first = try b.finish(&stale_keys); // A DATAGRAM frame after it, which arrives only if the 1-RTT packet is // read. var payload: [16]u8 = undefined; const written = try frame.write(&payload, .{ .datagram = .{ .data = "after", .had_length = false } }); const second = try testSealShort(&p.client, datagram[first.len..], payload[0..written], 0); try p.server.receive(datagram[0 .. first.len + second.len], 0, p.now); try testing.expectEqualStrings("after", p.server.readDatagram() orelse ""); } test "RFC 9000 14.1: a server pads a datagram carrying an ack-eliciting Initial" { // "Similarly, a server MUST expand the payload of all UDP datagrams // carrying ack-eliciting Initial packets to at least the smallest // allowed maximum datagram size of 1200 bytes." A server's handshake // that happens to fit in less still proves the path carries 1200. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const hello = (try p.client.send(&p.buffer, p.now)).?; try p.server.receive(hello.bytes, hello.path, p.now); const answer = (try p.server.send(&p.buffer, p.now)).?; try testing.expect(answer.bytes.len >= min_initial_datagram); } test "RFC 9000 10.2.3: an application close during the handshake does not say why" { // "A CONNECTION_CLOSE of type 0x1d MUST be replaced by a // CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or // Handshake packets. Otherwise, information about the application state // might be revealed. Endpoints MUST clear the value of the Reason Phrase // field and SHOULD use the APPLICATION_ERROR code when converting." const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const hello = (try p.client.send(&p.buffer, p.now)).?; try p.server.receive(hello.bytes, hello.path, p.now); p.server.closeApplication(0x100, "the application's secret", p.now); const news = (try p.server.send(&p.buffer, p.now)).?; try p.client.receive(news.bytes, news.path, p.now); try testing.expect(!p.client.closing.application); try testing.expectEqual(termination.Code.application_error, p.client.closing.code); try testing.expectEqualStrings("", p.client.closing.reason()); } test "RFC 9000 14.1: a server short of allowance sends its Initial unpadded" { // §14.1's padding is "subject to the anti-amplification limit": a server // with less than 1200 octets of §8.1's allowance left cannot pad, and // the limit is the rule that wins. Treating the padding as a MUST there // refused to send at all -- a handshake whose flight outgrew the // allowance, as an RSA certificate chain does, then never finished. const p = try TestPair.create(test_limits, test_limits); defer p.destroy(); const first = (try p.client.send(&p.buffer, p.now)).?; // Fifty octets past the Initial, which count toward the allowance and // are not a packet: three padded datagrams leave 150 octets over. var datagram: [min_initial_datagram + 50]u8 = @splat(0); @memcpy(datagram[0..first.bytes.len], first.bytes); try p.server.receive(datagram[0 .. first.bytes.len + 50], first.path, p.now); const sent = try testServerAlone(p, 20); try testing.expect(sent > 3 * min_initial_datagram); try testing.expect(sent <= (first.bytes.len + 50) * paths_mod.Paths.amplification_factor); }