// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Connection identifiers beyond the first: RFC 9000 §5.1. //! //! A connection has more than one name, and both ends choose the names the //! other must use. §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". Each is //! numbered, and the numbers are how the two ends agree about which name they //! are talking about. //! //! ## Why more than one //! //! Two reasons, and only one of them is migration. §9.5 is the other and the //! subtler: a connection ID is a stable identifier visible in the clear on //! every packet, so an observer who sees one on two different paths knows //! they are the same connection and the same person. "An endpoint MUST NOT //! reuse a connection ID when sending from more than one local address" — and //! obeying that requires having a spare, which requires the peer to have //! issued one in advance. A pool of connection IDs is what makes changing //! network unobservable rather than merely possible. //! //! The first reason is the obvious one: an endpoint that has exhausted its //! pool cannot migrate at all, because §9 gives it nothing legal to address //! the new path with. //! //! ## All of ours are the same length //! //! §5.1 requires an endpoint to be able to find its own connection ID in a //! short header, which carries no length field: "an endpoint that uses //! multiple connection ID lengths... MUST NOT... " — more precisely, the //! endpoint must know the length before it can parse. Since an endpoint //! chooses its own, the simplest way to always know is to choose one length //! and keep it. A peer's IDs may be any length it likes; it has the same //! problem and its own solution. const std = @import("std"); const assert = std.debug.assert; /// §17.2: the longest connection ID version 1 permits. pub const max_len = 20; /// §10.3's token, which travels with every connection ID an endpoint issues. pub const token_len = 16; /// How many connection IDs each side of this table holds. /// /// §18.2's `active_connection_id_limit` is what an endpoint advertises, and /// "MUST be at least 2" — one to use and one to move to. Four is enough for a /// migration to have somewhere to go without making the table a place a peer /// can spend our memory: §5.1.1 permits limiting issuance precisely "to /// reduce the amount of per-path state it maintains, such as path validation /// status, as its peer might interact with it over as many paths as there are /// issued connection IDs". pub const capacity = 4; pub const Error = error{ /// §5.1.1: "if the number of active connection IDs exceeds the value /// advertised in its active_connection_id_limit transport parameter, an /// endpoint MUST close the connection with an error of type /// CONNECTION_ID_LIMIT_ERROR." ConnectionIdLimitError, /// §19.15: a length outside 1..20, or a Retire Prior To above the /// Sequence Number. FrameEncodingError, /// §19.15 and §19.16: a sequence number reused for a different /// identifier, a NEW_CONNECTION_ID from an endpoint using zero-length /// identifiers, or a RETIRE_CONNECTION_ID for something never issued. ProtocolViolation, /// The table is full of identifiers that cannot be retired yet. NoRoom, }; /// One connection ID and what travels with it. pub const Entry = struct { sequence: u64, bytes: [max_len]u8 = undefined, len: usize = 0, /// §10.3's stateless reset token, when the peer issued one with this /// identifier. /// /// Optional, and the optionality is load-bearing. The identifier the /// handshake used arrives without a token — a server names its token in /// the `stateless_reset_token` transport parameter instead, and a client /// cannot name one at all — so an entry with a placeholder value would be /// a token this endpoint checks against every arriving datagram without /// the peer ever having issued it. §10.3.1: "an endpoint MUST NOT check /// for any stateless reset tokens associated with connection IDs it has /// not used." A zero placeholder is exactly that, and it means any /// datagram ending in sixteen zero octets reads as a teardown. token: ?[token_len]u8 = null, /// Whether this endpoint has asked the peer to stop using it (for one we /// issued) or has told the peer it will not use it again (for one the /// peer issued). retired: bool = false, in_use: bool = false, pub fn id(e: *const Entry) []const u8 { return e.bytes[0..e.len]; } }; /// The identifiers this endpoint has issued and must therefore answer to. pub const Issued = struct { entries: [capacity]Entry = @splat(.{ .sequence = 0 }), /// The next sequence number to use. §5.1.1: "the sequence number on each /// newly issued connection ID MUST increase by 1", and the first one — /// the Source Connection ID of the handshake — is zero. next_sequence: u64 = 0, /// The length every identifier this endpoint issues will have, taken from /// the first. len: usize = 0, /// Records the identifier the handshake used, which is sequence zero. pub fn init(id: []const u8) Issued { assert(id.len <= max_len); var issued: Issued = .{ .len = id.len }; // No token: §5.1.1's sequence-zero identifier is the Source // Connection ID of the handshake, and a token for it travels in the // `stateless_reset_token` transport parameter if it travels at all. _ = issued.add(id, null) catch unreachable; return issued; } /// Adds an identifier, returning its sequence number. pub fn add(issued: *Issued, id: []const u8, token: ?[token_len]u8) Error!u64 { if (id.len != issued.len) return error.ProtocolViolation; for (&issued.entries) |*entry| { if (entry.in_use) continue; entry.* = .{ .sequence = issued.next_sequence, .len = id.len, .token = token, .in_use = true, }; @memcpy(entry.bytes[0..id.len], id); issued.next_sequence += 1; return entry.sequence; } return error.NoRoom; } /// Whether a packet addressed to `id` belongs to this connection. /// /// §5.1.1: "any active connection ID is valid for use with the current /// connection at any time, in any packet type" — so this is every /// identifier that has not been retired, not merely the newest. pub fn accepts(issued: *const Issued, id: []const u8) bool { for (&issued.entries) |*entry| { if (!entry.in_use or entry.retired) continue; if (std.mem.eql(u8, entry.id(), id)) return true; } return false; } /// §19.16: the peer will not use this identifier again, so the slot is /// free and the peer is owed a replacement. /// /// "Receipt of a RETIRE_CONNECTION_ID frame containing a sequence number /// greater than any previously sent to the peer MUST be treated as a /// connection error of type PROTOCOL_VIOLATION" — a peer retiring /// something that was never issued is talking about a connection this is /// not. pub fn retire(issued: *Issued, sequence: u64) Error!void { if (sequence >= issued.next_sequence) return error.ProtocolViolation; for (&issued.entries) |*entry| { if (!entry.in_use or entry.sequence != sequence) continue; entry.* = .{ .sequence = 0 }; return; } // Already gone, which is ordinary: §19.16's frame can arrive twice. } /// How many identifiers the peer currently has of ours. pub fn active(issued: *const Issued) usize { var n: usize = 0; for (&issued.entries) |*entry| { if (entry.in_use and !entry.retired) n += 1; } return n; } /// Whether there is room to issue another. pub fn hasRoom(issued: *const Issued) bool { for (&issued.entries) |*entry| { if (!entry.in_use) return true; } return false; } }; /// The identifiers the peer has issued, any of which may be used to address /// it. pub const Received = struct { entries: [capacity]Entry = @splat(.{ .sequence = 0 }), /// §19.15: "a receiver MUST ignore any Retire Prior To fields that do not /// increase the largest received Retire Prior To value." retire_prior_to: u64 = 0, /// Sequence numbers this endpoint owes a RETIRE_CONNECTION_ID for. owed: [capacity]?u64 = @splat(null), /// One past the highest sequence number the peer has issued so far, as /// far as this endpoint has heard: the "Next Sequence Number" a /// multipath PATH_CIDS_BLOCKED reports. next_sequence: u64 = 0, /// Records the identifier the handshake used, sequence zero. pub fn init(id: []const u8) Received { assert(id.len <= max_len); var received: Received = .{}; received.entries[0] = .{ .sequence = 0, .len = id.len, .in_use = true }; @memcpy(received.entries[0].bytes[0..id.len], id); received.next_sequence = 1; return received; } /// §19.15: one NEW_CONNECTION_ID frame. /// /// `limit` is this endpoint's own `active_connection_id_limit`, which is /// the number it promised to maintain and therefore the number above which /// it must close the connection rather than quietly keep more. pub fn offer( received: *Received, sequence: u64, retire_prior_to: u64, id: []const u8, token: [token_len]u8, limit: u64, ) Error!void { // §19.15: "Values less than 1 and greater than 20 are invalid and // MUST be treated as a connection error of type // FRAME_ENCODING_ERROR." if (id.len < 1 or id.len > max_len) return error.FrameEncodingError; // "Receiving a value in the Retire Prior To field that is greater // than that in the Sequence Number field MUST be treated as a // connection error of type FRAME_ENCODING_ERROR." if (retire_prior_to > sequence) return error.FrameEncodingError; received.next_sequence = @max(received.next_sequence, sequence +| 1); // §19.15: the same frame may arrive more than once and that "MUST NOT // be treated as a connection error". What is not ordinary is the same // sequence number naming a different identifier, or the same // identifier arriving under a different number — either means the // peer has lost track of what it issued. for (&received.entries) |*entry| { if (!entry.in_use) continue; if (entry.sequence == sequence) { if (!std.mem.eql(u8, entry.id(), id)) return error.ProtocolViolation; const known = entry.token orelse return error.ProtocolViolation; if (!std.mem.eql(u8, &known, &token)) return error.ProtocolViolation; return; } if (std.mem.eql(u8, entry.id(), id)) return error.ProtocolViolation; } // §5.1.2: "upon receipt of an increased Retire Prior To field, the // peer MUST stop using the corresponding connection IDs and retire // them with RETIRE_CONNECTION_ID frames before adding the newly // provided connection ID". Before, so that the count cannot exceed // the limit in between. if (retire_prior_to > received.retire_prior_to) { received.retire_prior_to = retire_prior_to; for (&received.entries) |*entry| { if (!entry.in_use or entry.sequence >= retire_prior_to) continue; received.owe(entry.sequence); entry.* = .{ .sequence = 0 }; } } // §19.15: "an endpoint that receives a NEW_CONNECTION_ID frame with a // sequence number smaller than the Retire Prior To field of a // previously received NEW_CONNECTION_ID frame MUST send a // corresponding RETIRE_CONNECTION_ID frame that retires the newly // received connection ID" — it is dead on arrival, so it is retired // rather than stored. if (sequence < received.retire_prior_to) { received.owe(sequence); return; } for (&received.entries) |*entry| { if (entry.in_use) continue; entry.* = .{ .sequence = sequence, .len = id.len, .token = token, .in_use = true }; @memcpy(entry.bytes[0..id.len], id); if (received.active() > limit) return error.ConnectionIdLimitError; return; } // The table is full and nothing was retired to make room, which is // the peer exceeding the limit this endpoint advertised. return error.ConnectionIdLimitError; } /// The identifier to address the peer with: the lowest-numbered one that /// has not been retired. pub fn current(received: *const Received) ?[]const u8 { var best: ?*const Entry = null; for (&received.entries) |*entry| { if (!entry.in_use or entry.retired) continue; if (best == null or entry.sequence < best.?.sequence) best = entry; } return if (best) |entry| entry.id() else null; } /// Stops using one of the peer's identifiers, so that the peer can be /// told and can replace it. pub fn retire(received: *Received, sequence: u64) void { for (&received.entries) |*entry| { if (!entry.in_use or entry.sequence != sequence) continue; received.owe(sequence); entry.* = .{ .sequence = 0 }; return; } } /// An identifier this endpoint has not used before, for a new path. /// /// §9.5: "an endpoint MUST NOT reuse a connection ID when sending from /// more than one local address", so migrating needs one of these and a /// migration with none available cannot legally happen. pub fn spare(received: *const Received, in_use_id: []const u8) ?[]const u8 { for (&received.entries) |*entry| { if (!entry.in_use or entry.retired) continue; if (std.mem.eql(u8, entry.id(), in_use_id)) continue; return entry.id(); } return null; } pub fn active(received: *const Received) usize { var n: usize = 0; for (&received.entries) |*entry| { if (entry.in_use and !entry.retired) n += 1; } return n; } /// The next sequence number a RETIRE_CONNECTION_ID frame is owed for. pub fn nextOwed(received: *const Received) ?u64 { for (received.owed) |maybe| { if (maybe) |sequence| return sequence; } return null; } /// Notes that the frame for `sequence` has gone out. pub fn sentRetire(received: *Received, sequence: u64) void { for (&received.owed) |*slot| { if (slot.* == sequence) slot.* = null; } } fn owe(received: *Received, sequence: u64) void { for (received.owed) |maybe| { if (maybe == sequence) return; } for (&received.owed) |*slot| { if (slot.* == null) { slot.* = sequence; return; } } // Nowhere to record it. Dropping the obligation costs the peer a slot // it will not get back, which is a worse connection and not a broken // one — and it cannot happen while the table and this list are the // same size. } }; const testing = std.testing; test "RFC 9000 5.1.1: the handshake identifier is sequence zero" { var issued: Issued = .init(&.{ 1, 2, 3, 4 }); try testing.expectEqual(@as(u64, 1), issued.next_sequence); try testing.expectEqual(@as(usize, 1), issued.active()); try testing.expect(issued.accepts(&.{ 1, 2, 3, 4 })); try testing.expect(!issued.accepts(&.{ 9, 9, 9, 9 })); // "The sequence number on each newly issued connection ID MUST increase // by 1." try testing.expectEqual(@as(u64, 1), try issued.add(&.{ 5, 6, 7, 8 }, @splat(0xaa))); try testing.expectEqual(@as(u64, 2), try issued.add(&.{ 9, 10, 11, 12 }, @splat(0xbb))); // And every one of them is valid: "any active connection ID is valid for // use with the current connection at any time, in any packet type". try testing.expect(issued.accepts(&.{ 1, 2, 3, 4 })); try testing.expect(issued.accepts(&.{ 5, 6, 7, 8 })); try testing.expect(issued.accepts(&.{ 9, 10, 11, 12 })); } test "RFC 9000 5.1: every identifier an endpoint issues is the same length" { // A short header has no length field, so an endpoint has to know how long // its own identifier is before it can find it. Choosing one length and // keeping it is the simplest way always to know. var issued: Issued = .init(&.{ 1, 2, 3, 4 }); try testing.expectError(error.ProtocolViolation, issued.add(&.{ 1, 2 }, @splat(0))); try testing.expectError(error.ProtocolViolation, issued.add(&.{ 1, 2, 3, 4, 5 }, @splat(0))); } test "RFC 9000 19.16: a peer cannot retire what was never issued" { // "Receipt of a RETIRE_CONNECTION_ID frame containing a sequence number // greater than any previously sent to the peer MUST be treated as a // connection error of type PROTOCOL_VIOLATION." var issued: Issued = .init(&.{ 1, 2, 3, 4 }); _ = try issued.add(&.{ 5, 6, 7, 8 }, @splat(0)); try testing.expectError(error.ProtocolViolation, issued.retire(2)); try issued.retire(1); try testing.expect(!issued.accepts(&.{ 5, 6, 7, 8 })); // And twice is not an error: the frame can arrive more than once. try issued.retire(1); // The slot came back, so another can be issued in its place — which // §5.1.1 asks for: "an endpoint SHOULD supply a new connection ID when // the peer retires a connection ID". try testing.expect(issued.hasRoom()); } test "RFC 9000 19.15: the same frame twice is not an error, and a lie is" { var received: Received = .init(&.{ 1, 2, 3, 4 }); const token: [token_len]u8 = @splat(0x11); try received.offer(1, 0, &.{ 5, 6, 7, 8 }, token, 4); try testing.expectEqual(@as(usize, 2), received.active()); // "Receipt of the same frame multiple times MUST NOT be treated as a // connection error." try received.offer(1, 0, &.{ 5, 6, 7, 8 }, token, 4); try testing.expectEqual(@as(usize, 2), received.active()); // "If an endpoint receives a NEW_CONNECTION_ID frame that repeats a // previously issued connection ID with a different Stateless Reset Token // field value or a different Sequence Number field value, or if a // sequence number is used for different connection IDs, the endpoint MAY // treat that receipt as a connection error of type PROTOCOL_VIOLATION." try testing.expectError( error.ProtocolViolation, received.offer(1, 0, &.{ 5, 6, 7, 8 }, @splat(0x22), 4), ); try testing.expectError( error.ProtocolViolation, received.offer(1, 0, &.{ 9, 9, 9, 9 }, token, 4), ); try testing.expectError( error.ProtocolViolation, received.offer(2, 0, &.{ 5, 6, 7, 8 }, token, 4), ); } test "RFC 9000 19.15: a length or a retirement the frame cannot mean" { var received: Received = .init(&.{ 1, 2, 3, 4 }); const token: [token_len]u8 = @splat(0); // "Values less than 1 and greater than 20 are invalid." try testing.expectError(error.FrameEncodingError, received.offer(1, 0, &.{}, token, 4)); var too_long: [21]u8 = @splat(7); try testing.expectError(error.FrameEncodingError, received.offer(1, 0, &too_long, token, 4)); // "Receiving a value in the Retire Prior To field that is greater than // that in the Sequence Number field MUST be treated as a connection error // of type FRAME_ENCODING_ERROR." try testing.expectError(error.FrameEncodingError, received.offer(1, 2, &.{ 5, 6 }, token, 4)); } test "RFC 9000 5.1.2: Retire Prior To empties the pool before it refills it" { // "Upon receipt of an increased Retire Prior To field, the peer MUST stop // using the corresponding connection IDs and retire them with // RETIRE_CONNECTION_ID frames before adding the newly provided connection // ID to the set of active connection IDs. This ordering allows an // endpoint to replace all active connection IDs without the possibility // of a peer having no available connection IDs and without exceeding the // limit." var received: Received = .init(&.{ 1, 2, 3, 4 }); try received.offer(1, 0, &.{ 5, 6, 7, 8 }, @splat(1), 2); try testing.expectEqual(@as(usize, 2), received.active()); // A limit of two, and a third identifier that retires both of the others. // Without the ordering this would be three at once and a // CONNECTION_ID_LIMIT_ERROR. try received.offer(2, 2, &.{ 9, 10, 11, 12 }, @splat(2), 2); try testing.expectEqual(@as(usize, 1), received.active()); try testing.expectEqualSlices(u8, &.{ 9, 10, 11, 12 }, received.current().?); // And the retirements are owed to the peer, which is how it learns it may // issue more. try testing.expectEqual(@as(?u64, 0), received.nextOwed()); received.sentRetire(0); try testing.expectEqual(@as(?u64, 1), received.nextOwed()); received.sentRetire(1); try testing.expectEqual(@as(?u64, null), received.nextOwed()); // §19.15: a smaller Retire Prior To afterwards has no effect. try received.offer(3, 1, &.{ 13, 14, 15, 16 }, @splat(3), 2); try testing.expectEqual(@as(usize, 2), received.active()); } test "RFC 9000 19.15: an identifier already retired on arrival is retired, not stored" { // "An endpoint that receives a NEW_CONNECTION_ID frame with a sequence // number smaller than the Retire Prior To field of a previously received // NEW_CONNECTION_ID frame MUST send a corresponding RETIRE_CONNECTION_ID // frame that retires the newly received connection ID." var received: Received = .init(&.{ 1, 2, 3, 4 }); try received.offer(3, 3, &.{ 9, 9, 9, 9 }, @splat(9), 4); try testing.expectEqual(@as(usize, 1), received.active()); // Sequence 2 is below the watermark of 3, so it is dead on arrival. try received.offer(2, 0, &.{ 7, 7, 7, 7 }, @splat(7), 4); try testing.expectEqual(@as(usize, 1), received.active()); // The retirement for it is owed, along with the one for sequence zero. var owed: usize = 0; while (received.nextOwed()) |sequence| : (owed += 1) received.sentRetire(sequence); try testing.expectEqual(@as(usize, 2), owed); } test "RFC 9000 5.1.1: more identifiers than were promised ends the connection" { // "After processing a NEW_CONNECTION_ID frame and adding and retiring // active connection IDs, if the number of active connection IDs exceeds // the value advertised in its active_connection_id_limit transport // parameter, an endpoint MUST close the connection with an error of type // CONNECTION_ID_LIMIT_ERROR." var received: Received = .init(&.{ 1, 2, 3, 4 }); try received.offer(1, 0, &.{ 5, 6 }, @splat(1), 2); try testing.expectError( error.ConnectionIdLimitError, received.offer(2, 0, &.{ 7, 8 }, @splat(2), 2), ); } test "RFC 9000 9.5: migrating needs an identifier not already in use" { // "An endpoint MUST NOT reuse a connection ID when sending from more than // one local address" — because a connection ID is visible in the clear on // every packet, so the same one on two paths tells an observer they are // the same connection. A pool is what makes changing network // unobservable rather than merely possible. var received: Received = .init(&.{ 1, 2, 3, 4 }); try testing.expectEqual(@as(?[]const u8, null), received.spare(&.{ 1, 2, 3, 4 })); try received.offer(1, 0, &.{ 5, 6, 7, 8 }, @splat(1), 4); try testing.expectEqualSlices(u8, &.{ 5, 6, 7, 8 }, received.spare(&.{ 1, 2, 3, 4 }).?); }