// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A QUIC connection, as far as the handshake. //! //! 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. //! //! ## What it does not do yet //! //! No streams, no flow control, no migration and no key update. What is here //! is enough to reach 1-RTT keys across a network that loses packets and //! across one that is congested, which is the milestone that makes all of //! those testable. //! //! ## 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, pub fn of(level: tls.Level) Space { return switch (level) { .initial => .initial, .handshake => .handshake, .early_data, .application => .application, }; } pub fn encryptionLevel(s: Space) tls.Level { return switch (s) { .initial => .initial, .handshake => .handshake, .application => .application, }; } }; /// 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, and this does not yet read transport parameters. 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. Also not yet negotiated. 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, /// 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 = .{}, }; /// 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, /// Whether this is path 0's application space, which is where ECN /// validation lives. primary: bool, /// 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; } }; /// 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, 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, }; } }; } /// 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 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 = .{}, /// §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), /// 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 }, /// Whether a MAX_DATA is owed, which is decided when the application reads. owes_max_data: 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 refusal has already been acted on, so that it is acted on /// once. early_recovered: 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, /// §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 this path is worth marking, and whether it has been /// caught lying about the markings it carries. 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, /// 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. §8.1: "the successful completion of the handshake /// implicitly validates the client's address", so this one is validated /// from the outset. path: paths_mod.Id = 0, /// 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, }; /// Initialises 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`. /// 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. 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; } /// 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; } /// The send window each stream is currently working with. pub fn sendWindow(c: *const Connection) usize { return c.send_window; } /// 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]; } 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); 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); 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 = 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. } } pub fn localId(c: *const Connection) []const u8 { return c.local_id_buf[0..c.local_id_len]; } pub fn peerId(c: *const Connection) []const u8 { return c.peer_id_buf[0..c.peer_id_len]; } pub fn isEstablished(c: *const Connection) bool { return c.handshake.isComplete() and c.spaces[2].hasKeys(); } /// §4.1.2: whether the handshake is confirmed, which is a stronger statement /// than `isEstablished` and the one §6 requires before a key update. pub fn isConfirmed(c: *const Connection) bool { return c.confirmed; } /// §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[@intFromEnum(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. 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; } /// Processes one datagram. /// /// `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. /// /// 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. /// 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); } 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; }; } fn process( c: *Connection, datagram: []u8, path: paths_mod.Id, now: recovery.Instant, ) Error!void { // §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; 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; // §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; } const level = header.kind.level() orelse return; const space_index = @intFromEnum(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. if (c.discarded[space_index]) return; 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 keys = if (header.kind == .zero_rtt) (c.early_read orelse return) else (space.read orelse return); // 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; return; }; // §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 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 rest of the // datagram is abandoned: without decrypting this packet there is // no Length field to be sure of, so where the next one would // start is a guess. // // §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; return; } at += opened.header.end; if (opened.header.first & 0x40 == 0) c.packets_greased +|= 1; // §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; } // 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[@intFromEnum(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; var it: frame.Iterator = .init(opened.payload); while (it.next() catch return error.ProtocolViolation) |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( @enumFromInt(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 = @intFromEnum(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. .data_blocked, .stream_data_blocked, .streams_blocked => {}, .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| { // §9.4: "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. if (validated.id == c.paths.active and validated.id != 0) { c.congestion = .{}; c.rtt = .{}; } } 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." // // Only for path 0. 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." if (non_probing and on == null) { 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 has to send all of it again; 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.3: "the client... MUST NOT... and the client needs to // consider the data as lost". 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_recovered and c.spaces[2].write != null and !c.handshake.earlyDataAccepted()) { c.early_recovered = true; const space = &c.spaces[2]; var lost: [recovery.max_tracked]recovery.Sent = undefined; for (space.loss.takeEarly(&lost)) |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. 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; }, } } /// 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 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; } // -- 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. pub fn openBidirectional(c: *Connection) Error!stream.Id { return c.open(.bidirectional); } /// 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. pub fn openUnidirectional(c: *Connection) Error!stream.Id { return c.open(.unidirectional); } fn open(c: *Connection, which: stream.Directionality) Error!stream.Id { const at = @intFromEnum(which); if (c.next_stream_index[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(); 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 = @intFromEnum(id.directionality()); c.peer_streams_retired[at] = @max(c.peer_streams_retired[at], id.index() + 1); // §4.6: the limit is cumulative, so giving a slot back means // raising the ceiling rather than lowering a count. const initial = switch (id.directionality()) { .bidirectional => c.local.initial_max_streams_bidi, .unidirectional => c.local.initial_max_streams_uni, }; const grown = c.peer_streams_retired[at] + initial; 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; } } } } /// 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; } /// The next stream the peer opened that the application has not been told /// about. 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; } /// Adds to what a stream will send. Nothing goes out until `send` is called. 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, }; } /// 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; } /// Says that a stream has nothing more to send, which puts a FIN on the frame /// carrying its last octet. 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; } /// §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. 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); } /// 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. 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; } /// 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`.** pub fn readDatagram(c: *const Connection) ?[]const u8 { return c.inbound.peek(); } /// Discards what `readDatagram` returned, making room for another. pub fn takeDatagram(c: *Connection) void { c.inbound.pop(); } /// Whether this connection may send unreliable datagrams at all, which is a /// question about what the peer advertised (RFC 9221 §3). pub fn datagramsAllowed(c: *const Connection) bool { const peer = c.peer orelse return false; return peer.max_datagram_frame_size > 0; } /// 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. pub fn streamOpen(c: *Connection, id: stream.Id) bool { return c.find(id.value) != null; } /// §3.5: abandons a stream's sending half. 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); } /// 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(); } /// Takes `n` octets of what `readable` returned, which is also what releases /// the flow control credit they occupied. pub fn consume(c: *Connection, id: stream.Id, n: usize) void { const entry = c.find(id.value) orelse return; if (!entry.has_recv) return; entry.recv.consume(n); c.recv_consumed += n; c.owes_max_data = true; // §3.2's terminal state is "Data Read", so reading is what can close a // stream from this side. c.reclaimStreams(); } /// 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 = @intFromEnum(id.directionality()); if (id.isLocal(c.initiator())) return id.index() < c.next_stream_index[at]; return id.index() < c.peer_streams_retired[at]; } /// 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, }; } /// Whether the peer has ended a stream and everything it sent has been read. pub fn streamFinished(c: *Connection, id: stream.Id) bool { const entry = c.find(id.value) orelse return c.streamRetired(id); return entry.recv.finished(); } /// The peer's RESET_STREAM error code, if it sent one. pub fn streamResetCode(c: *Connection, id: stream.Id) ?u64 { const entry = c.find(id.value) orelse return null; return entry.recv.reset_code; } /// §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 = @intFromEnum(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". if (c.remembered) |was| { if (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. 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; entry.send.grant(c.peerStreamLimit(entry.id)); } } /// §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 = @intFromEnum(id.directionality()); if (!id.isLocal(role) and id.index() < c.peer_streams_retired[at]) 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 is not implemented. So this is 1200 until it is, and /// raising it is a change with a prerequisite rather than a constant to /// edit. 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; } /// draft-ietf-quic-ack-frequency-14 §5: asks the peer to acknowledge now. pub fn requestImmediateAck(c: *Connection) error{NotSupported}!void { if (!c.peerTakesAckFrequency()) return error.NotSupported; c.immediate_ack_owed = true; } /// 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 = @intFromEnum(Space.of(level)); return .{ .space = &c.spaces[index], .rtt = &c.rtt, .congestion = &c.congestion, .application = index == 2, .primary = index == 2, .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, .primary = false, .pmtu = &extra.pmtu, .index = 2, }; } fn onAckIn(c: *Connection, rec: Recovery, a: frame.Ack, now: recovery.Instant) Error!void { const space = rec.space; const space_is_application = rec.primary; // §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; const coupling = if (rec.application) c.linkedIncrease() else null; const first = a.firstRange() catch return error.ProtocolViolation; var it = a.ranges(); var range: ?frame.Ack.Range = first; while (range) |r| : (range = it.next() catch return error.ProtocolViolation) { for (space.loss.ackRange(r.smallest, r.largest, c.acked_scratch)) |sent| { any_newly = true; if (sent.ect0) newly_marked += 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); } // §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; } } 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. if (a.ecn) |ecn| { rec.congestion.onEcn(rec.index, ecn.ce, sent.time, now); } space.peer_ecn = a.ecn; } // §13.4.2.1, and only on the application space: the handshake spaces are // short-lived and their keys are discarded, so a path's behaviour is // learned where there is enough traffic to learn it from. if (space_is_application and advances) { const reported: ?ecn_mod.Counts = if (a.ecn) |e| .{ .ect0 = e.ect0, .ect1 = e.ect1, .ce = e.ce } else null; // The return says validation failed, and nothing has to be done about // it here: §13.4.2.2's "stops setting the ECT codepoint" is what the // validator's own `codepoint` now answers, and the next datagram // built asks it again. _ = c.ecn.onAck(reported, newly_marked); } // §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| { if (!entry.in_use or entry.retired) continue; // Only tokens the peer actually issued. §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." tokens[count] = entry.token orelse continue; count += 1; } if (c.peer) |p| { if (p.stateless_reset_token) |token| { tokens[count] = token; 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]); } /// §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; c.processed_any = true; // §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; } // "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. if (c.role != .client) return error.ProtocolViolation; // "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 Handshake // packet from the server, it MUST discard any subsequent Retry packets" — // by then the handshake is authenticated and a Retry is somebody else's // idea. if (c.spaces[0].loss.largest_acked != null or c.handshake.isComplete()) 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 everything about the first attempt // is void: §17.2.5.1 has the client reset its packet numbers and discard // what it had in flight, since the server that will read the second // Initial has no memory of the first. const space = &c.spaces[0]; c.congestion.onDiscarded(space.loss.unacked()); space.loss.reset(); space.acks = .{}; space.next_number = 0; 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; 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. _ = c.rotatePeerId(); 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; } /// 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; } /// §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; } /// §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 why 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. 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); } /// §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 the /// rotation below finds it like any other spare. 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; return c.startMigration(path, now); } 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; _ = 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. _ = c.rotatePeerId(); c.paths.migrate(path); 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. const rng = c.id_rng orelse return error.StreamStateError; _ = c.paths.challenge(path, rng, now) catch return error.TooManyPaths; } /// 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 { const spare = c.received.spare(c.peerId()) orelse return false; var next: [ids.max_len]u8 = undefined; @memcpy(next[0..spare.len], spare); const len = spare.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. if (c.sequenceOfPeer(c.peerId())) |sequence| c.received.retire(sequence); @memcpy(c.peer_id_buf[0..len], next[0..len]); c.peer_id_len = len; return true; } /// 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); // §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 a CONNECTION_CLOSE frame. /// /// §10.2.3: "the goal is to ensure that the peer will process the frame. /// Generally, this means sending the frame in a packet with the highest level /// of packet protection to avoid the packet being discarded." So this picks /// the highest level whose keys both ends can be assumed to have — which /// before the handshake finishes is not the highest level this endpoint /// itself has. fn sendClose(c: *Connection, out: []u8, now: recovery.Instant) Error!?[]u8 { _ = now; var level: tls.Level = .initial; for ([_]tls.Level{ .handshake, .application }) |candidate| { const index = @intFromEnum(Space.of(candidate)); if (!c.discarded[index] and c.spaces[index].write != null) level = candidate; } const index = @intFromEnum(Space.of(level)); if (c.discarded[index]) return null; const space = &c.spaces[index]; if (space.write == null) return null; const kind: packet.Kind = switch (level) { .initial => .initial, .handshake => .handshake, .application => .one_rtt, .early_data => unreachable, }; var b = if (kind == .one_rtt) packet.Builder.initShort(out, c.peerId(), space.next_number, 4, c.key_phase) catch return error.NoSpace else packet.Builder.initLong(out, .{ .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. b.add(.{ .connection_close = .{ .error_code = @intFromEnum(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. if (c.role == .client and kind == .initial) { if (out.len < min_initial_datagram) return error.NoSpace; b.padTo(min_initial_datagram) catch return error.NoSpace; } c.grease(&b); const wire = b.finish(&space.write.?) catch return error.NoSpace; space.next_number += 1; c.closing.onSent(); return wire; } /// 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 or entry.retired) 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; } /// 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; } /// 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; } /// 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; 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 path `id`'s worth of multipath /// 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. 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; 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; } /// §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". 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; } /// §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; } /// 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; } /// 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 }; } /// 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; } /// Forgets route `route`, which `routeInUse` said is not in use, so that /// its number can name another address. pub fn forgetRoute(c: *Connection, route: paths_mod.Id) void { if (c.routeInUse(route)) return; c.paths.forget(route); } /// 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; } /// 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. 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); } /// Withdraws one. A server says so with REMOVE_ADDRESS. 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); } /// 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. 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); } /// 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(); } /// 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; } /// Sends new data on multipath path `id` rather than path 0, once it has been /// validated. §5.5 leaves scheduling to the implementation; this one sends /// everything on one path the application chooses, and acknowledgements for /// every path on whichever path a packet is going out on. 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; } /// §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. 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); } /// 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. fn issuedEntry(issued: *ids.Issued, sequence: u64) ?*const ids.Entry { for (&issued.entries) |*entry| { if (entry.in_use and !entry.retired 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; } /// 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; } /// 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; } /// §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: "Violations of the protocol lead to an immediate close." The frame /// goes out on the next call to `send`, and after that this connection answers /// incoming packets by repeating it and does nothing else. pub fn close(c: *Connection, code: termination.Code, why: []const u8, now: recovery.Instant) void { c.closing.close(code, null, why, c.closeDeadline(now)); } /// 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 { c.closing.close(@enumFromInt(code), null, why, c.closeDeadline(now)); c.closing.application = true; } /// §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. pub fn closeState(c: *const Connection) ?termination.State { return if (c.closing.state == .open) null else c.closing.state; } /// 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; } } 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. pub fn setScheduler(c: *Connection, scheduler: Scheduler) void { c.scheduler = scheduler; } /// 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. /// /// Two timers in one, as §6.2 has it: 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. 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; }; // 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; } /// 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)); for (&c.spaces, 0..) |*space, i| { 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; } return earliest; } /// 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. 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); 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; } 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; } } /// 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. /// 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, }; 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; // 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 }; 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. const marking = c.ecn.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 }; } } 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[@intFromEnum(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]; // 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.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.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. const pad_preferred = pad_required or (c.paths.nextOwed() != null) or c.owesChallengeOn(destination); const pad = pad_preferred; var at: usize = 0; var padded = false; for ([_]tls.Level{ .initial, .handshake, .application }, 0..) |level, i| { if (!any[i]) continue; const space = &c.spaces[@intFromEnum(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_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; 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; 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; } 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_handshake_done = true; // ack-eliciting carried = true; } 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_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 = @intFromEnum(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_handshake_done = true; // ack-eliciting, for the same reason carried = true; } } if (i == 2) { if (owes_limits) carried = c.addFlowControl(&b) or carried; 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) { 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_ranges.stream_count > 0 or owes_limits or sent_handshake_done or sent_datagram; 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". // ECN validation is path 0's (§13.4.2 validates a path, and this is // the one the validator describes). if (target == null) c.ecn.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 (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 }; } /// §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. /// Nothing above this needs to act on a refusal: the data has already been /// put back and will go out again under 1-RTT keys. pub fn earlyDataAccepted(c: *const Connection) bool { return c.handshake.earlyDataAccepted(); } /// RFC 7250: the raw public key the peer proved it holds, once the handshake /// is complete, or null if the handshake used certificates. /// /// 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(); } /// Whether anything is waiting to go out: CRYPTO data at any level, stream /// data, or a flow control limit that has moved. 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; } /// §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; } /// 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 { 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. if (!entry.open or !entry.has_recv or entry.recv.state == .reset_received) 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. /// /// A MAX_DATA that is lost is not resent: §4.2 has a receiver send these /// "multiple times within a round trip" if it likes, and the next one says /// everything the lost one did and more — the same reason a lost ACK is not /// worth recovering. fn addFlowControl(c: *Connection, b: *packet.Builder) bool { var wrote = false; const window = c.local.initial_max_data; const connection_limit = c.recv_consumed + window; if (window > 0 and 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 rule as in `owesFlowControl`. if (!entry.open or !entry.has_recv or entry.recv.state == .reset_received) continue; const stream_window_ = c.localStreamLimit(entry.id); if (stream_window_ == 0) continue; const limit = entry.recv.limitToAdvertise(stream_window_); if (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; } 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. 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(); wrote = true; } for (&c.streams) |*entry| { if (!entry.open or !entry.has_send) continue; // §3.5: a stream this endpoint has abandoned says so once, 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. // // Neither frame is subject to flow control: §4.1's limits are on data // and these carry none. if (entry.send.reset_pending) { 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(); 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; 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); }