// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Transport parameters: RFC 9000 §18, carried in the TLS handshake. //! //! Everything two QUIC endpoints have to agree before they can use a //! connection, and it is not a negotiation: each end states what it will //! accept and the other end obeys. There is no reply and nothing to converge //! on, which is why the whole exchange fits in one extension in each //! direction. //! //! §8.2 of RFC 9001 puts them in the `quic_transport_parameters` TLS //! extension — the ClientHello in one direction, the EncryptedExtensions in //! the other, which is why a server's parameters are encrypted and a client's //! are not. This library has carried that extension's body as an opaque blob //! since the handshake first worked; this is what goes in it. //! //! ## The encoding, and the one rule worth stating //! //! §18: "Each transport parameter is encoded as an (identifier, length, //! value) tuple", all varints. An unknown identifier is skipped, and §18.1 //! reserves a whole arithmetic progression of identifiers — "31 * N + 27" — //! purely so that an endpoint can send one and find out whether its peer //! really does ignore what it does not understand. A parser that rejected //! unknown parameters would pass every test until the day QUIC gained an //! extension. //! //! ## Absent is not zero, except when it is //! //! §18.2: "Transport parameters have a default value of 0 if the transport //! parameter is absent, unless otherwise stated" — and four of them state //! otherwise, each with a different default that matters. This is the kind of //! rule that produces a connection which works against one implementation and //! stalls against another, so the defaults live in `Parameters`'s field //! initialisers where they cannot be forgotten. const std = @import("std"); const varint = @import("varint.zig"); pub const Error = error{ /// §18: a parameter ran off the end of the extension, or a value did not /// fit the shape its identifier requires. TransportParameterError, /// The buffer offered was too small to write into. NoSpace, }; /// §18.2's identifiers. pub const Id = enum(u64) { original_destination_connection_id = 0x00, max_idle_timeout = 0x01, stateless_reset_token = 0x02, max_udp_payload_size = 0x03, initial_max_data = 0x04, initial_max_stream_data_bidi_local = 0x05, initial_max_stream_data_bidi_remote = 0x06, initial_max_stream_data_uni = 0x07, initial_max_streams_bidi = 0x08, initial_max_streams_uni = 0x09, ack_delay_exponent = 0x0a, max_ack_delay = 0x0b, disable_active_migration = 0x0c, preferred_address = 0x0d, active_connection_id_limit = 0x0e, initial_source_connection_id = 0x0f, retry_source_connection_id = 0x10, /// RFC 9221 §3, which is not one of RFC 9000's. The registry is shared, /// so an extension's parameter sits in the same table as the core ones /// and an endpoint that does not implement it simply does not recognise /// the identifier -- §18.1: "an endpoint MUST ignore transport parameters /// that it does not support", which is what makes an extension an /// extension rather than a new version. max_datagram_frame_size = 0x20, /// draft-ietf-quic-multipath-21 §2.1: this endpoint supports multipath, /// and the largest path ID it will maintain from the start. initial_max_path_id = 0x3e, /// RFC 9368 §10.1: which version this endpoint chose, and which it could /// have. version_information = 0x11, /// RFC 9287 §3: this endpoint accepts packets whose QUIC Bit is zero. grease_quic_bit = 0x2ab2, /// draft-ietf-quic-address-discovery-01 §3: whether this endpoint will /// report the address it sees its peer at, wants such reports, or both. address_discovery = 0x9f81a176, /// n0's NAT traversal, as noq has it: not a standard, and not /// `draft-seemann-quic-nat-traversal-02`, whose parameter is /// `0x3d7e9f0bca12fea6`. See `docs/iroh-transport.md`, Stage 5. n0_nat_traversal = 0x3d7f91120401, /// draft-ietf-quic-ack-frequency-14 §3: this endpoint takes ACK_FREQUENCY /// and IMMEDIATE_ACK frames, and the least it will delay an ACK. min_ack_delay = 0xff04de1b, _, /// Where this identifier comes among the ones this library understands, /// or null for one it does not. fn known(id: Id) ?u5 { for (std.enums.values(Id), 0..) |each, index| { if (each == id) return @intCast(index); } return null; } /// §18.2: "A client MUST NOT include any server-only transport /// parameter... A server MUST treat receipt of any of these transport /// parameters as a connection error of type TRANSPORT_PARAMETER_ERROR." /// /// Three of the four hand the client something it is meant to verify — /// which connection ID the server saw, where to migrate to, what token /// proves a stateless reset — so a client that could send them would be /// telling the server what the server itself did. pub fn isServerOnly(id: Id) bool { return switch (id) { .original_destination_connection_id, .stateless_reset_token, .preferred_address, .retry_source_connection_id, => true, else => false, }; } test isServerOnly { try std.testing.expect(Id.stateless_reset_token.isServerOnly()); // Both ends say which connection ID they put in their Initials. try std.testing.expect(!Id.initial_source_connection_id.isServerOnly()); } }; /// §16: the largest value a varint can carry, which bounds every integer /// parameter here. pub const max_varint = (1 << 62) - 1; /// draft-ietf-quic-multipath-21 §2.1: the largest path ID there can be, since /// §2.4 puts it in 32 bits of the nonce. pub const max_path_id: u64 = (1 << 32) - 1; /// The longest connection ID §17.2 permits, and so the longest any /// connection-ID-valued parameter can be. pub const max_connection_id_len = 20; /// What one endpoint tells the other. /// /// The defaults are §18.2's, and the four that are not zero are the ones /// worth reading twice: an absent `max_udp_payload_size` means 65527 rather /// than nothing, an absent `ack_delay_exponent` means 8 as a multiplier /// rather than 1, an absent `max_ack_delay` means 25ms rather than none, and /// an absent `active_connection_id_limit` means 2 rather than zero. pub const Parameters = struct { /// §10.1, in milliseconds. Zero disables it, and it is disabled only if /// *both* ends say zero. max_idle_timeout: u64 = 0, /// §18.2: "The default for this parameter is the maximum permitted UDP /// payload of 65527. Values below 1200 are invalid." max_udp_payload_size: u64 = 65527, /// §4.1's connection-level limit. initial_max_data: u64 = 0, /// §4.1's per-stream limits, which differ by who opened the stream and /// which way it runs. The naming is from the sender's point of view: /// `bidi_local` is the limit this endpoint grants on streams *it* opened. initial_max_stream_data_bidi_local: u64 = 0, initial_max_stream_data_bidi_remote: u64 = 0, initial_max_stream_data_uni: u64 = 0, /// §4.6: how many streams the peer may open. "If this parameter is absent /// or zero, the peer cannot open bidirectional streams until a /// MAX_STREAMS frame is sent" — so a server that forgets this accepts a /// connection on which no request can be made. initial_max_streams_bidi: u64 = 0, initial_max_streams_uni: u64 = 0, /// §19.3: "If this value is absent, a default value of 3 is assumed /// (indicating a multiplier of 8). Values above 20 are invalid." ack_delay_exponent: u64 = 3, /// §13.2.1, in milliseconds. "If this value is absent, a default of 25 /// milliseconds is assumed. Values of 2^14 or greater are invalid." max_ack_delay: u64 = 25, /// §9: a zero-length parameter, so its presence is the whole of it. disable_active_migration: bool = false, /// §18.2: "MUST be at least 2... If this transport parameter is absent, a /// default of 2 is assumed." active_connection_id_limit: u64 = 2, /// §9.6, server only: where this server would rather be talked to. preferred_address: ?PreferredAddress = null, /// RFC 9221 §3: the largest DATAGRAM frame this endpoint will accept, /// measured as the whole frame rather than its payload. /// /// "An endpoint that includes this parameter supports the DATAGRAM frame /// types and is willing to receive such frames on this connection." Zero /// is the default and means no: the extension is negotiated by the /// parameter being there at all, which is why this is a size and not a /// flag -- a peer that says how big is also saying yes. max_datagram_frame_size: u64 = 0, /// RFC 9287 §3: a zero-length parameter saying this endpoint accepts /// packets with the QUIC Bit -- 0x40 of the first octet, the "fixed" bit /// of RFC 9000 §17 -- cleared. A peer that has heard it SHOULD then set /// the bit unpredictably, so that nothing on the path can come to rely on /// it being one, which is the ossification the extension exists to /// prevent. grease_quic_bit: bool = false, /// RFC 9368 §3: the version this endpoint chose and the versions it could /// have, which is what lets each end check that no forged Version /// Negotiation packet steered the connection onto a version neither would /// have picked. Absent is allowed at both ends -- §4: servers "MAY /// complete the handshake even if the Version Information is missing", /// and so may a client that did not act on a Version Negotiation packet, /// which is every client of a library that speaks one version. version_information: ?VersionInformation = null, /// draft-ietf-quic-address-discovery-01 §3: this endpoint's part in /// address discovery, or null for none. Reports flow one way only when /// one end provides and the other receives, so each end's role is half /// of a question neither can answer alone -- see `AddressDiscovery`. address_discovery: ?AddressDiscovery = null, /// draft-ietf-quic-multipath-21 §2.1: the largest path ID this endpoint /// is willing to maintain at the start, or null for no multipath at all. /// /// Zero is not "no": "the peer aims to enable the multipath extension /// without allowing extra paths immediately", which switches on PATH_ACK /// and the per-path nonce with only path 0 in use. And the extension is /// in use only if both ends send it -- "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." initial_max_path_id: ?u64 = null, /// n0's NAT traversal: how many candidate addresses this endpoint lets /// its peer advertise to it, 1 to 255, or null for none. In use only when /// both ends send it *and* multipath is negotiated. The value is one raw /// octet rather than a varint -- noq writes and reads it so, and a varint /// would differ from 64 up. n0_nat_traversal: ?u8 = null, /// draft-ietf-quic-ack-frequency-14 §3: the least time, in *microseconds* /// -- max_ack_delay is milliseconds -- this endpoint is willing to delay /// an acknowledgement, or null for an endpoint that does not take /// ACK_FREQUENCY. "A unilateral indication of support": the peer may /// then send the frames whether or not it sends the parameter itself. min_ack_delay: ?u64 = null, /// §7.3's connection ID checks. Each is the value its sender put in a /// Source Connection ID field, echoed back so the other end can be sure /// nothing rewrote it in flight — which is the whole of QUIC's defence /// against an off-path attacker splicing two connections together. initial_source_connection_id: ?[]const u8 = null, /// Server only: the Destination Connection ID from the client's first /// Initial, which the client chose at random and which therefore only the /// real server can echo. original_destination_connection_id: ?[]const u8 = null, retry_source_connection_id: ?[]const u8 = null, /// Server only, §10.3. stateless_reset_token: ?[16]u8 = null, /// §4.1's limit for a stream, given who opened it and which way it runs. /// /// The four names in §18.2 describe two endpoints' views of the same two /// streams, and getting the pairing backwards gives a connection where /// each end grants the credit the other was not waiting for. Written out: /// these are the limits *this* endpoint grants to its peer, so a stream /// the peer opened is `bidi_remote` and one this endpoint opened is /// `bidi_local`. pub fn streamLimit(p: *const Parameters, kind: StreamKind) u64 { return switch (kind) { .local_bidirectional => p.initial_max_stream_data_bidi_local, .remote_bidirectional => p.initial_max_stream_data_bidi_remote, .unidirectional => p.initial_max_stream_data_uni, }; } test streamLimit { // What this endpoint grants on a stream its peer opens, which is // how much the peer may send on it before the first MAX_STREAM_DATA. const mine: Parameters = .{ .initial_max_stream_data_bidi_local = 16_384, .initial_max_stream_data_bidi_remote = 65_536, }; try std.testing.expectEqual(@as(u64, 65_536), mine.streamLimit(.remote_bidirectional)); } pub const StreamKind = enum { local_bidirectional, remote_bidirectional, unidirectional }; /// §18.2's range checks, applied to what a peer sent. /// /// Every one of these is a value that would otherwise be used in /// arithmetic: an `ack_delay_exponent` of 60 shifts a delay past the end /// of a u64, and a `max_ack_delay` of 2^62 milliseconds is a timer that /// never fires. The RFC calls them invalid; this is where that is /// enforced rather than assumed. /// /// `from` is the side that sent them. From a client, three of the four /// server-only parameters are refused here; the fourth, /// `preferred_address`, is refused only by `parse`, which sees the /// identifier before there is a field to check. `parse` calls this /// itself, so a caller needs it only for parameters it built by hand. pub fn validate(p: *const Parameters, from: Side) Error!void { if (p.max_udp_payload_size < 1200) return error.TransportParameterError; if (p.ack_delay_exponent > 20) return error.TransportParameterError; if (p.max_ack_delay >= 1 << 14) return error.TransportParameterError; // draft-ietf-quic-ack-frequency-14 §3: "Endpoints that support this // extension MUST treat receipt of a min_ack_delay that is greater // than the max_ack_delay as a connection error of type // TRANSPORT_PARAMETER_ERROR" -- microseconds against milliseconds. if (p.min_ack_delay) |least| { if (least > p.max_ack_delay * 1000) return error.TransportParameterError; } if (p.active_connection_id_limit < 2) return error.TransportParameterError; // §4.6: "If a max_streams transport parameter... is received with a // value greater than 2^60, this would allow a maximum stream ID that // cannot be expressed as a variable-length integer." if (p.initial_max_streams_bidi > 1 << 60) return error.TransportParameterError; if (p.initial_max_streams_uni > 1 << 60) return error.TransportParameterError; if (from == .client) { if (p.original_destination_connection_id != null) return error.TransportParameterError; if (p.stateless_reset_token != null) return error.TransportParameterError; if (p.retry_source_connection_id != null) return error.TransportParameterError; } } test validate { const sane: Parameters = .{ .max_idle_timeout = 30_000 }; try sane.validate(.server); // §18.2: "Values of 2^14 or greater are invalid." const lazy: Parameters = .{ .max_ack_delay = 1 << 14 }; try std.testing.expectError(error.TransportParameterError, lazy.validate(.server)); } }; /// Which end of a connection sent, or is about to send, a set of /// parameters -- which decides what they may contain. pub const Side = enum { client, server }; /// draft-ietf-quic-address-discovery-01 §3's three values. pub const AddressDiscovery = enum(u64) { /// "Willing to provide address observations to its peer, but is not /// interested in receiving address observations itself." provide = 0, /// "Interested in receiving address observations, but it is not willing /// to provide address observations." receive = 1, /// Both. both = 2, /// Whether an endpoint in this role is willing to send OBSERVED_ADDRESS /// frames: `provide` or `both`. pub fn provides(role: AddressDiscovery) bool { return role != .receive; } test provides { try std.testing.expect(AddressDiscovery.both.provides()); try std.testing.expect(!AddressDiscovery.receive.provides()); } /// Whether an endpoint in this role wants OBSERVED_ADDRESS frames: /// `receive` or `both`. pub fn receives(role: AddressDiscovery) bool { return role != .provide; } test receives { try std.testing.expect(AddressDiscovery.receive.receives()); try std.testing.expect(!AddressDiscovery.provide.receives()); } /// Whether an endpoint in role `mine` sends reports to a peer in role /// `theirs`. §4.1: "An endpoint MUST NOT send an OBSERVED_ADDRESS frame /// to a node that did not request the receipt of address observations." /// /// Null is an endpoint that did not send the parameter, and takes no /// part in either direction. pub fn reportsTo(mine: ?AddressDiscovery, theirs: ?AddressDiscovery) bool { const a = mine orelse return false; const b = theirs orelse return false; return a.provides() and b.receives(); } test reportsTo { // A server that provides, and a client behind a NAT that wants to // know what it looks like from outside. try std.testing.expect(AddressDiscovery.reportsTo(.provide, .receive)); // The client does not report back: the server never asked. try std.testing.expect(!AddressDiscovery.reportsTo(.receive, .provide)); try std.testing.expect(!AddressDiscovery.reportsTo(.both, null)); } }; /// RFC 9368 §3's Version Information: a Chosen Version and the Available /// Versions. /// /// The list is held by value and bounded. Every version a peer sends is /// checked while parsing -- §4 makes a zero anywhere a parsing failure -- but /// only the first `max_available` are kept, since the only use this library /// has for the list is to find one value in it, and a peer that sends a /// thousand grease versions is not owed a thousand words of memory. pub const VersionInformation = struct { chosen: u32, available: [max_available]u32 = @splat(0), available_len: u8 = 0, pub const max_available = 8; /// What an endpoint that speaks only version 1 sends: chose it, and could /// have chosen nothing else. pub const v1: VersionInformation = .{ .chosen = 1, .available = .{ 1, 0, 0, 0, 0, 0, 0, 0 }, .available_len = 1, }; /// The Available Versions kept, in the order the peer listed them: at /// most `max_available`, so a longer list is cut short. Borrowed from /// this value. pub fn availableVersions(v: *const VersionInformation) []const u32 { return v.available[0..v.available_len]; } test availableVersions { const v: VersionInformation = .v1; try std.testing.expectEqualSlices(u32, &.{1}, v.availableVersions()); } /// Whether `version` is among the Available Versions kept. Only the /// first `max_available` are, so a version listed after them is /// reported as not offered. pub fn offers(v: *const VersionInformation, version: u32) bool { return std.mem.findScalar(u32, v.availableVersions(), version) != null; } test offers { // A server that chose version 1 and could also have spoken QUIC // version 2 (RFC 9369). const v: VersionInformation = .{ .chosen = 1, .available = .{ 1, 0x6b3343cf, 0, 0, 0, 0, 0, 0 }, .available_len = 2, }; try std.testing.expect(v.offers(0x6b3343cf)); try std.testing.expect(!v.offers(0xff00001d)); } }; /// Writes the parameters into `out`, returning what was used. /// /// Only what differs from the default is written, which §18.2 makes /// equivalent to writing all of it and is how every implementation keeps a /// ClientHello small. /// /// `from` is the side doing the writing. A client that has set any of /// §18.2's server-only parameters gets `error.TransportParameterError`, as /// does a value no encoding can carry: a connection ID longer than 20 /// octets, an `initial_max_path_id` above 2^32-1, an `n0_nat_traversal` of /// zero. Nothing else is checked -- `validate` is for that -- and /// `error.NoSpace` means `out` was too small, with a partial encoding left /// in it. pub fn write(p: *const Parameters, out: []u8, from: Side) Error![]u8 { var at: usize = 0; const integers = [_]struct { Id, u64, u64 }{ .{ .max_idle_timeout, p.max_idle_timeout, 0 }, .{ .max_udp_payload_size, p.max_udp_payload_size, 65527 }, .{ .initial_max_data, p.initial_max_data, 0 }, .{ .initial_max_stream_data_bidi_local, p.initial_max_stream_data_bidi_local, 0 }, .{ .initial_max_stream_data_bidi_remote, p.initial_max_stream_data_bidi_remote, 0 }, .{ .initial_max_stream_data_uni, p.initial_max_stream_data_uni, 0 }, .{ .initial_max_streams_bidi, p.initial_max_streams_bidi, 0 }, .{ .initial_max_streams_uni, p.initial_max_streams_uni, 0 }, .{ .ack_delay_exponent, p.ack_delay_exponent, 3 }, .{ .max_ack_delay, p.max_ack_delay, 25 }, .{ .active_connection_id_limit, p.active_connection_id_limit, 2 }, .{ .max_datagram_frame_size, p.max_datagram_frame_size, 0 }, }; for (integers) |entry| { const id, const value, const default = entry; if (value == default) continue; try writeId(out, &at, id); try writeLength(out, &at, varint.encodedLen(value)); try writeVarint(out, &at, value); } if (p.disable_active_migration) { try writeId(out, &at, .disable_active_migration); try writeLength(out, &at, 0); } if (p.grease_quic_bit) { try writeId(out, &at, .grease_quic_bit); try writeLength(out, &at, 0); } if (p.initial_max_path_id) |max| { if (max > max_path_id) return error.TransportParameterError; try writeId(out, &at, .initial_max_path_id); try writeLength(out, &at, varint.encodedLen(max)); try writeVarint(out, &at, max); } if (p.min_ack_delay) |least| { try writeId(out, &at, .min_ack_delay); try writeLength(out, &at, varint.encodedLen(least)); try writeVarint(out, &at, least); } if (p.n0_nat_traversal) |limit| { if (limit == 0) return error.TransportParameterError; try writeId(out, &at, .n0_nat_traversal); try writeLength(out, &at, 1); if (at >= out.len) return error.NoSpace; out[at] = limit; at += 1; } if (p.address_discovery) |role| { const value = @backingInt(role); try writeId(out, &at, .address_discovery); try writeLength(out, &at, varint.encodedLen(value)); try writeVarint(out, &at, value); } if (p.version_information) |v| { const versions = v.availableVersions(); const len = 4 * (1 + versions.len); try writeId(out, &at, .version_information); try writeLength(out, &at, len); if (out.len - at < len) return error.NoSpace; std.mem.writeInt(u32, out[at..][0..4], v.chosen, .big); at += 4; for (versions) |version| { std.mem.writeInt(u32, out[at..][0..4], version, .big); at += 4; } } const ids = [_]struct { Id, ?[]const u8 }{ .{ .initial_source_connection_id, p.initial_source_connection_id }, .{ .original_destination_connection_id, p.original_destination_connection_id }, .{ .retry_source_connection_id, p.retry_source_connection_id }, }; for (ids) |entry| { const id, const maybe = entry; const bytes = maybe orelse continue; if (from == .client and id.isServerOnly()) return error.TransportParameterError; if (bytes.len > max_connection_id_len) return error.TransportParameterError; try writeId(out, &at, id); try writeLength(out, &at, bytes.len); if (out.len - at < bytes.len) return error.NoSpace; @memcpy(out[at..][0..bytes.len], bytes); at += bytes.len; } if (p.preferred_address) |a| { // §18.2 makes this server-only, like everything else that tells a // client something about the server it could not have known. if (from == .client) return error.TransportParameterError; if (a.connection_id.len < 1 or a.connection_id.len > max_connection_id_len) { return error.TransportParameterError; } try writeId(out, &at, .preferred_address); try writeLength(out, &at, 25 + a.connection_id.len + 16); if (out.len - at < 25 + a.connection_id.len + 16) return error.NoSpace; @memcpy(out[at..][0..4], &a.ipv4); at += 4; std.mem.writeInt(u16, out[at..][0..2], a.ipv4_port, .big); at += 2; @memcpy(out[at..][0..16], &a.ipv6); at += 16; std.mem.writeInt(u16, out[at..][0..2], a.ipv6_port, .big); at += 2; out[at] = @intCast(a.connection_id.len); at += 1; @memcpy(out[at..][0..a.connection_id.len], a.connection_id); at += a.connection_id.len; @memcpy(out[at..][0..16], &a.stateless_reset_token); at += 16; } if (p.stateless_reset_token) |token| { if (from == .client) return error.TransportParameterError; try writeId(out, &at, .stateless_reset_token); try writeLength(out, &at, token.len); if (out.len - at < token.len) return error.NoSpace; @memcpy(out[at..][0..token.len], &token); at += token.len; } return out[0..at]; } test write { // What a client puts in its ClientHello: its own limits and the // connection ID it chose, and nothing that was already the default. const client_cid = [_]u8{ 0xc1, 0x1e, 0x47, 0x01 }; const mine: Parameters = .{ .initial_max_data = 1 << 20, .initial_max_streams_bidi = 16, .initial_source_connection_id = &client_cid, }; var buf: [256]u8 = undefined; const encoded = try write(&mine, &buf, .client); var storage: IdStorage = .{}; const back = try parse(encoded, &storage, .client); try std.testing.expectEqual(@as(u64, 1 << 20), back.initial_max_data); try std.testing.expectEqualSlices(u8, &client_cid, back.initial_source_connection_id.?); } /// Reads what a peer sent. /// /// `storage` holds the connection IDs, which are copied out of `input` /// because `input` is a buffer inside the TLS handshake that the caller does /// not own past this call. Its previous contents are overwritten, so it has /// to outlive the `Parameters` returned and cannot be shared between two /// of them. /// /// `from` is the side that sent `input`. Unknown identifiers are skipped; /// anything malformed, server-only from a client, or out of §18.2's range /// (see `Parameters.validate`, which this calls) is /// `error.TransportParameterError`. pub fn parse(input: []const u8, storage: *IdStorage, from: Side) Error!Parameters { var p: Parameters = .{}; var at: usize = 0; storage.used = 0; // §7.4: "An endpoint MUST NOT send a parameter more than once in a given // transport parameters extension. An endpoint SHOULD treat receipt of // duplicate transport parameters as a connection error of type // TRANSPORT_PARAMETER_ERROR." Only for the ones understood here; the // rest are skipped whatever they say, however often they say it. var seen: u32 = 0; while (at < input.len) { const id_raw = varint.parse(input[at..]) catch return error.TransportParameterError; at += id_raw.len; const length = varint.parse(input[at..]) catch return error.TransportParameterError; at += length.len; if (length.value > input.len - at) return error.TransportParameterError; const body = input[at..][0..@intCast(length.value)]; at += body.len; const id: Id = @fromBackingInt(@intCast(id_raw.value)); // §18.2: a client may not send these, and §18.1 reserves a run of // identifiers purely to check that an implementation ignores what it // does not know. Both rules are about the same thing — an endpoint // must not be able to steer its peer with a parameter the peer was // not expecting — and they pull in opposite directions, so each has // to be applied on purpose. if (from == .client and id.isServerOnly()) return error.TransportParameterError; if (id.known()) |index| { const bit = @as(u32, 1) << index; if (seen & bit != 0) return error.TransportParameterError; seen |= bit; } switch (id) { .max_idle_timeout => p.max_idle_timeout = try integer(body), .max_udp_payload_size => p.max_udp_payload_size = try integer(body), .initial_max_data => p.initial_max_data = try integer(body), .initial_max_stream_data_bidi_local => p.initial_max_stream_data_bidi_local = try integer(body), .initial_max_stream_data_bidi_remote => p.initial_max_stream_data_bidi_remote = try integer(body), .initial_max_stream_data_uni => p.initial_max_stream_data_uni = try integer(body), .initial_max_streams_bidi => p.initial_max_streams_bidi = try integer(body), .initial_max_streams_uni => p.initial_max_streams_uni = try integer(body), .ack_delay_exponent => p.ack_delay_exponent = try integer(body), .max_ack_delay => p.max_ack_delay = try integer(body), .active_connection_id_limit => p.active_connection_id_limit = try integer(body), .max_datagram_frame_size => p.max_datagram_frame_size = try integer(body), .disable_active_migration => { if (body.len != 0) return error.TransportParameterError; p.disable_active_migration = true; }, // RFC 9287 §3: "an endpoint that understands this transport // parameter MUST treat receipt of a non-empty value of the // transport parameter as a connection error of type // TRANSPORT_PARAMETER_ERROR." .grease_quic_bit => { if (body.len != 0) return error.TransportParameterError; p.grease_quic_bit = true; }, .version_information => p.version_information = try versionInformation(body, from), // draft-ietf-quic-multipath-21 §2.1: "If an initial_max_path_id // transport parameter value higher than 2^32-1 is received, the // receiver MUST close the connection with an error of type // TRANSPORT_PARAMETER_ERROR" -- the limit the nonce's 32 bits of // path ID impose. .initial_max_path_id => { const max = try integer(body); if (max > max_path_id) return error.TransportParameterError; p.initial_max_path_id = max; }, .min_ack_delay => p.min_ack_delay = try integer(body), // One raw octet, and never zero: noq refuses a length other than // one as malformed and a zero as an illegal value, both as // TRANSPORT_PARAMETER_ERROR. .n0_nat_traversal => { if (body.len != 1 or body[0] == 0) return error.TransportParameterError; p.n0_nat_traversal = body[0]; }, // draft-ietf-quic-address-discovery-01 §3: "Implementations that // understand this transport parameter MUST treat the receipt of // any other value than these as a connection error of type // TRANSPORT_PARAMETER_ERROR." .address_discovery => p.address_discovery = switch (try integer(body)) { 0 => .provide, 1 => .receive, 2 => .both, else => return error.TransportParameterError, }, .initial_source_connection_id => p.initial_source_connection_id = try storage.keep(body), .original_destination_connection_id => p.original_destination_connection_id = try storage.keep(body), .retry_source_connection_id => p.retry_source_connection_id = try storage.keep(body), .stateless_reset_token => { if (body.len != 16) return error.TransportParameterError; p.stateless_reset_token = body[0..16].*; }, .preferred_address => { // §18.2's shape: two addresses and ports, then a // length-prefixed connection ID, then a reset token. Fixed // except for the identifier, so the length is known before // anything is read out of it. if (body.len < 4 + 2 + 16 + 2 + 1 + 16) return error.TransportParameterError; var a: PreferredAddress = .{}; a.ipv4 = body[0..4].*; a.ipv4_port = std.mem.readInt(u16, body[4..6], .big); a.ipv6 = body[6..22].*; a.ipv6_port = std.mem.readInt(u16, body[22..24], .big); const id_len = body[24]; // §18.2: "A server that chooses a zero-length connection ID // MUST NOT provide a preferred address. Similarly, a server // MUST NOT include a zero-length connection ID in this // transport parameter." A client that moved to the preferred // address would otherwise have no identifier to address it // with and no way to say so. if (id_len < 1 or id_len > max_connection_id_len) { return error.TransportParameterError; } if (body.len != 25 + @as(usize, id_len) + 16) { return error.TransportParameterError; } a.connection_id = try storage.keep(body[25..][0..id_len]); a.stateless_reset_token = body[25 + @as(usize, id_len) ..][0..16].*; p.preferred_address = a; }, // §18.1: "transport parameters with an identifier of the form // 31 * N + 27 are reserved to exercise the requirement that // unknown transport parameters be ignored". Everything unknown is // skipped, which is what that requirement asks for. _ => {}, } } try p.validate(from); return p; } test "RFC 9000 7.4: a parameter sent twice is refused" { // "An endpoint SHOULD treat receipt of duplicate transport parameters // as a connection error of type TRANSPORT_PARAMETER_ERROR." Two values // for one setting leave the receiver guessing which one the sender // meant. const twice = [_]u8{ 0x01, 0x01, 0x10, 0x01, 0x01, 0x20 }; var storage: IdStorage = .{}; try std.testing.expectError(error.TransportParameterError, parse(&twice, &storage, .server)); } test parse { // A server's parameters: an idle timeout of 30,000ms (id 0x01, a // four-octet varint) and a stateless reset token (id 0x02, sixteen // octets). const token: [16]u8 = @splat(0x7e); const input = [_]u8{ 0x01, 0x04, 0x80, 0x00, 0x75, 0x30, 0x02, 0x10 } ++ token; var storage: IdStorage = .{}; const theirs = try parse(&input, &storage, .server); try std.testing.expectEqual(@as(u64, 30_000), theirs.max_idle_timeout); try std.testing.expectEqualSlices(u8, &token, &theirs.stateless_reset_token.?); // Anything absent has §18.2's default. try std.testing.expectEqual(@as(u64, 25), theirs.max_ack_delay); // The same octets from a client are a TRANSPORT_PARAMETER_ERROR: only // a server issues reset tokens. try std.testing.expectError(error.TransportParameterError, parse(&input, &storage, .client)); } /// RFC 9368 §4's parsing rules, each of which is a TRANSPORT_PARAMETER_ERROR /// in version 1: "if it is too short or if its length is not divisible by /// four", a Chosen Version or "any Available Version equal to zero", and -- /// from a client only -- a Chosen Version that is not among its own /// Available Versions. fn versionInformation(body: []const u8, from: Side) Error!VersionInformation { if (body.len < 4 or body.len % 4 != 0) return error.TransportParameterError; var v: VersionInformation = .{ .chosen = std.mem.readInt(u32, body[0..4], .big) }; if (v.chosen == 0) return error.TransportParameterError; var chosen_offered = false; var at: usize = 4; while (at < body.len) : (at += 4) { const version = std.mem.readInt(u32, body[at..][0..4], .big); if (version == 0) return error.TransportParameterError; if (version == v.chosen) chosen_offered = true; if (v.available_len < VersionInformation.max_available) { v.available[v.available_len] = version; v.available_len += 1; } } // A server's list need not name its Chosen Version -- §3: "the server // operator could be in the process of removing support for this version" // -- but a client's must, since it is the client's statement of what it // prefers. if (from == .client and !chosen_offered) return error.TransportParameterError; return v; } /// §18.2's `preferred_address`: where a server would rather the client talked /// to it, and the identifier and reset token to use once it does. /// /// The addresses are raw octets rather than any address type, which is the /// sans-I/O rule applied to the one place in QUIC where an address appears on /// the wire: this library cannot connect to anything, so an address here is /// data to hand back to the caller and not something to act on. What it is /// *for* is §9.6 -- "servers MAY communicate a preferred address... at the /// end of the handshake" -- and what acts on it is the caller, which then /// drives the ordinary §8.2 path validation before anything moves. pub const PreferredAddress = struct { /// §18.2: "Servers MAY choose to only send a preferred address of one /// address family by sending an all-zero address and port (0.0.0.0:0 or /// [::]:0) for the other family." So an all-zero entry is an absence /// rather than a destination, and `ipv4Given`/`ipv6Given` are how to ask. ipv4: [4]u8 = @splat(0), ipv4_port: u16 = 0, ipv6: [16]u8 = @splat(0), ipv6_port: u16 = 0, /// §5.1.1: this identifier's sequence number is 1, fixed by the /// specification rather than carried in the parameter -- "the sequence /// number of the connection ID in the preferred_address transport /// parameter is 1". connection_id: []const u8 = &.{}, stateless_reset_token: [16]u8 = @splat(0), /// Whether the server gave an IPv4 address, which is anything but the /// all-zero 0.0.0.0:0 that §18.2 uses to say it did not. pub fn ipv4Given(a: *const PreferredAddress) bool { return a.ipv4_port != 0 or !std.mem.allEqual(u8, &a.ipv4, 0); } test ipv4Given { // A server that moves IPv4 clients to 203.0.113.9:443 and says // nothing about IPv6. const a: PreferredAddress = .{ .ipv4 = .{ 203, 0, 113, 9 }, .ipv4_port = 443 }; try std.testing.expect(a.ipv4Given()); try std.testing.expect(!a.ipv6Given()); } /// Whether the server gave an IPv6 address, which is anything but the /// all-zero [::]:0 that §18.2 uses to say it did not. pub fn ipv6Given(a: *const PreferredAddress) bool { return a.ipv6_port != 0 or !std.mem.allEqual(u8, &a.ipv6, 0); } test ipv6Given { var ipv6: [16]u8 = @splat(0); ipv6[0..4].* = .{ 0x20, 0x01, 0x0d, 0xb8 }; ipv6[15] = 9; const a: PreferredAddress = .{ .ipv6 = ipv6, .ipv6_port = 443 }; try std.testing.expect(a.ipv6Given()); try std.testing.expect(!a.ipv4Given()); } }; /// The sequence number §5.1.1 assigns to a preferred address's connection ID. pub const preferred_address_sequence: u64 = 1; /// Room for the connection IDs a peer's parameters can name. /// /// Four of them -- `initial_source_connection_id`, /// `original_destination_connection_id`, `retry_source_connection_id` and /// the one inside `preferred_address` -- each at most 20 octets, borrowed by /// the `Parameters` that parsing produces. So this has to outlive them, /// which in practice means it lives in the connection beside the parameters /// themselves. pub const IdStorage = struct { bytes: [4 * max_connection_id_len]u8 = undefined, used: usize = 0, fn keep(s: *IdStorage, body: []const u8) Error![]const u8 { if (body.len > max_connection_id_len) return error.TransportParameterError; if (s.used + body.len > s.bytes.len) return error.TransportParameterError; const at = s.used; @memcpy(s.bytes[at..][0..body.len], body); s.used += body.len; return s.bytes[at..][0..body.len]; } }; fn integer(body: []const u8) Error!u64 { const decoded = varint.parse(body) catch return error.TransportParameterError; // §18: the Length field "contains the length of the Transport Parameter // Value field in bytes", so a value with anything after it is malformed // rather than merely odd. if (decoded.len != body.len) return error.TransportParameterError; return decoded.value; } fn writeId(out: []u8, at: *usize, id: Id) Error!void { try writeVarint(out, at, @backingInt(id)); } fn writeLength(out: []u8, at: *usize, len: usize) Error!void { try writeVarint(out, at, len); } fn writeVarint(out: []u8, at: *usize, value: u64) Error!void { if (value > varint.max) return error.TransportParameterError; if (out.len - at.* < varint.encodedLen(value)) return error.NoSpace; at.* += varint.write(out[at.*..], value).len; } const testing = std.testing; test "RFC 9000 18.2: absent does not mean zero for four of them" { // "Transport parameters have a default value of 0 if the transport // parameter is absent, unless otherwise stated." The four that state // otherwise are the ones that produce a connection working against one // implementation and stalling against another. var storage: IdStorage = .{}; const p = try parse(&.{}, &storage, .server); try testing.expectEqual(@as(u64, 65527), p.max_udp_payload_size); try testing.expectEqual(@as(u64, 3), p.ack_delay_exponent); try testing.expectEqual(@as(u64, 25), p.max_ack_delay); try testing.expectEqual(@as(u64, 2), p.active_connection_id_limit); // And everything else really is zero, including the two that make a // connection useless when forgotten: with no stream limits the peer can // open nothing and send nothing. try testing.expectEqual(@as(u64, 0), p.initial_max_data); try testing.expectEqual(@as(u64, 0), p.initial_max_streams_bidi); } test "what is written comes back" { const p: Parameters = .{ .max_idle_timeout = 30_000, .initial_max_data = 1 << 20, .initial_max_stream_data_bidi_local = 65536, .initial_max_stream_data_bidi_remote = 32768, .initial_max_stream_data_uni = 16384, .initial_max_streams_bidi = 100, .initial_max_streams_uni = 3, .ack_delay_exponent = 5, .max_ack_delay = 10, .disable_active_migration = true, .active_connection_id_limit = 4, .initial_source_connection_id = &.{ 1, 2, 3, 4 }, }; var buffer: [256]u8 = undefined; const encoded = try write(&p, &buffer, .client); var storage: IdStorage = .{}; const back = try parse(encoded, &storage, .client); try testing.expectEqual(p.max_idle_timeout, back.max_idle_timeout); try testing.expectEqual(p.initial_max_data, back.initial_max_data); try testing.expectEqual(p.initial_max_stream_data_bidi_local, back.initial_max_stream_data_bidi_local); try testing.expectEqual(p.initial_max_stream_data_bidi_remote, back.initial_max_stream_data_bidi_remote); try testing.expectEqual(p.initial_max_stream_data_uni, back.initial_max_stream_data_uni); try testing.expectEqual(p.initial_max_streams_bidi, back.initial_max_streams_bidi); try testing.expectEqual(p.initial_max_streams_uni, back.initial_max_streams_uni); try testing.expectEqual(p.ack_delay_exponent, back.ack_delay_exponent); try testing.expectEqual(p.max_ack_delay, back.max_ack_delay); try testing.expect(back.disable_active_migration); try testing.expectEqual(p.active_connection_id_limit, back.active_connection_id_limit); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, back.initial_source_connection_id.?); } test "only what differs from the default is written" { // §18.2 makes an absent parameter and one carrying its default the same // statement, so a ClientHello need not carry eleven varints to say // nothing. const nothing: Parameters = .{}; var buffer: [256]u8 = undefined; try testing.expectEqual(@as(usize, 0), (try write(¬hing, &buffer, .client)).len); // One parameter, and the tuple is its identifier, a length and a value. const one: Parameters = .{ .initial_max_data = 3 }; const encoded = try write(&one, &buffer, .client); try testing.expectEqualSlices(u8, &.{ 0x04, 0x01, 0x03 }, encoded); } test "RFC 9000 18.1: an unknown parameter is skipped, not refused" { // "Transport parameters with an identifier of the form 31 * N + 27 are // reserved to exercise the requirement that unknown transport parameters // be ignored." A parser that rejected them would pass every test until // the day QUIC gained an extension -- which is precisely why the RFC // reserves identifiers for peers to probe with. var buffer: [64]u8 = undefined; var at: usize = 0; // 31 * 1 + 27 = 58, carrying four arbitrary octets. at += varint.write(buffer[at..], 58).len; at += varint.write(buffer[at..], 4).len; @memcpy(buffer[at..][0..4], "junk"); at += 4; // And something known after it, so that a parser which gave up silently // would be caught. at += varint.write(buffer[at..], 0x04).len; at += varint.write(buffer[at..], 1).len; buffer[at] = 42; at += 1; var storage: IdStorage = .{}; const p = try parse(buffer[0..at], &storage, .client); try testing.expectEqual(@as(u64, 42), p.initial_max_data); } test "RFC 9000 18.2: a client may not tell a server what the server did" { // "A client MUST NOT include any server-only transport parameter... A // server MUST treat receipt of any of these transport parameters as a // connection error of type TRANSPORT_PARAMETER_ERROR." Three of the four // are values the client is supposed to *check* against what it saw, so a // client that could send them would be authenticating the server to // itself. var buffer: [64]u8 = undefined; var at: usize = 0; at += varint.write(buffer[at..], @backingInt(Id.original_destination_connection_id)).len; at += varint.write(buffer[at..], 4).len; @memcpy(buffer[at..][0..4], &[_]u8{ 1, 2, 3, 4 }); at += 4; var storage: IdStorage = .{}; try testing.expectError(error.TransportParameterError, parse(buffer[0..at], &storage, .client)); // From a server it is ordinary, and is what lets a client check that // nothing rewrote the connection ID it chose. const p = try parse(buffer[0..at], &storage, .server); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, p.original_destination_connection_id.?); } test "RFC 9000 18.2: values the RFC calls invalid are refused" { var buffer: [64]u8 = undefined; var storage: IdStorage = .{}; const cases = [_]struct { Id, u64 }{ // "Values below 1200 are invalid" -- a peer claiming to accept 100 // octet datagrams cannot receive a QUIC Initial at all. .{ .max_udp_payload_size, 1199 }, // "Values above 20 are invalid" -- and an exponent of 60 would shift // an ACK delay past the end of a u64. .{ .ack_delay_exponent, 21 }, // "Values of 2^14 or greater are invalid." .{ .max_ack_delay, 1 << 14 }, // "MUST be at least 2. An endpoint that receives a value less than 2 // MUST close the connection." .{ .active_connection_id_limit, 1 }, // §4.6: above 2^60 the stream identifier could not be encoded. .{ .initial_max_streams_bidi, (1 << 60) + 1 }, }; for (cases) |entry| { const id, const value = entry; var at: usize = 0; at += varint.write(buffer[at..], @backingInt(id)).len; at += varint.write(buffer[at..], varint.encodedLen(value)).len; at += varint.write(buffer[at..], value).len; try testing.expectError( error.TransportParameterError, parse(buffer[0..at], &storage, .server), ); } } test "a truncated or overlong parameter is malformed" { var storage: IdStorage = .{}; // A length reaching past the end of the extension. try testing.expectError( error.TransportParameterError, parse(&.{ 0x04, 0x08, 0x01 }, &storage, .server), ); // An integer parameter with trailing octets inside its own value: §18 // says the Length field is the length of the value, so this is not a // varint with something after it, it is a malformed parameter. try testing.expectError( error.TransportParameterError, parse(&.{ 0x04, 0x02, 0x01, 0x00 }, &storage, .server), ); // A zero-length parameter that is not the one zero-length parameter. try testing.expectError( error.TransportParameterError, parse(&.{ 0x0c, 0x01, 0x00 }, &storage, .server), ); } test "RFC 9000 18.2: the four stream limits are two endpoints' views of two streams" { // Getting this pairing backwards gives a connection where each end grants // the credit the other was not waiting for, and it is invisible until // something tries to send more than the smaller of the two. const p: Parameters = .{ .initial_max_stream_data_bidi_local = 100, .initial_max_stream_data_bidi_remote = 200, .initial_max_stream_data_uni = 300, }; try testing.expectEqual(@as(u64, 100), p.streamLimit(.local_bidirectional)); try testing.expectEqual(@as(u64, 200), p.streamLimit(.remote_bidirectional)); try testing.expectEqual(@as(u64, 300), p.streamLimit(.unidirectional)); } test "RFC 9000 18.2: a preferred address survives a round trip" { // The one parameter with a structure rather than a number in it, and the // one place in QUIC where an address appears on the wire. Its shape is // fixed except for the connection ID, which is length-prefixed in the // middle -- so a reader that got the prefix wrong would read the reset // token out of the wrong sixteen octets and find out much later. const id = [_]u8{ 0xc1, 0xd0, 0x0d }; const token: [16]u8 = @splat(0x7e); var p: Parameters = .{ .initial_source_connection_id = &.{ 1, 2, 3 }, .original_destination_connection_id = &.{ 4, 5, 6 }, .preferred_address = .{ .ipv4 = .{ 192, 0, 2, 1 }, .ipv4_port = 8853, .ipv6_port = 0, .connection_id = &id, .stateless_reset_token = token, }, }; var buffer: [256]u8 = undefined; const written = try write(&p, &buffer, .server); var storage: IdStorage = .{}; const back = try parse(written, &storage, .server); const a = back.preferred_address.?; try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, &a.ipv4); try testing.expectEqual(@as(u16, 8853), a.ipv4_port); try testing.expectEqualSlices(u8, &id, a.connection_id); try testing.expectEqualSlices(u8, &token, &a.stateless_reset_token); // §18.2: "Servers MAY choose to only send a preferred address of one // address family by sending an all-zero address and port... for the other // family." So the absent family is an absence rather than a destination, // and an endpoint that read it as one would try to reach [::]:0. try testing.expect(a.ipv4Given()); try testing.expect(!a.ipv6Given()); } test "RFC 9000 18.2: a preferred address is the server's to send" { // Server-only, like everything else that tells a client something about // the server it could not have found out for itself. var p: Parameters = .{ .initial_source_connection_id = &.{ 1, 2, 3 }, .preferred_address = .{ .connection_id = &.{9}, .ipv4_port = 443 }, }; var buffer: [256]u8 = undefined; try testing.expectError(error.TransportParameterError, write(&p, &buffer, .client)); // And "a server MUST NOT include a zero-length connection ID in this // transport parameter" -- a client that moved there would have no name to // address the server by and no way to say so. var empty: Parameters = .{ .initial_source_connection_id = &.{ 1, 2, 3 }, .original_destination_connection_id = &.{ 4, 5, 6 }, .preferred_address = .{ .connection_id = &.{}, .ipv4_port = 443 }, }; try testing.expectError(error.TransportParameterError, write(&empty, &buffer, .server)); // Nor may one arrive that way. The length is an octet in the middle of // the parameter, so a zero there is a thing a peer can write. var wire: [25 + 16]u8 = @splat(0); wire[24] = 0; // connection ID length var body: [64]u8 = undefined; var at: usize = 0; try writeId(&body, &at, .preferred_address); try writeLength(&body, &at, wire.len); @memcpy(body[at..][0..wire.len], &wire); at += wire.len; var storage: IdStorage = .{}; try testing.expectError(error.TransportParameterError, parse(body[0..at], &storage, .server)); } test "RFC 9287 3: grease_quic_bit is a zero-length parameter, and nothing else" { const p: Parameters = .{ .grease_quic_bit = true }; var buffer: [16]u8 = undefined; const encoded = try write(&p, &buffer, .client); // 0x2ab2 is a two-octet varint, 0x6ab2, then a length of zero. try testing.expectEqualSlices(u8, &.{ 0x6a, 0xb2, 0x00 }, encoded); var storage: IdStorage = .{}; try testing.expect((try parse(encoded, &storage, .client)).grease_quic_bit); try testing.expect(!(try parse(&.{}, &storage, .client)).grease_quic_bit); // "MUST treat receipt of a non-empty value... as a connection error of // type TRANSPORT_PARAMETER_ERROR." try testing.expectError(error.TransportParameterError, parse(&.{ 0x6a, 0xb2, 0x01, 0x00 }, &storage, .server)); } test "RFC 9368 3: version information survives a round trip" { const p: Parameters = .{ .version_information = .v1 }; var buffer: [32]u8 = undefined; const encoded = try write(&p, &buffer, .client); // Identifier 0x11, eight octets: the Chosen Version, then one Available. try testing.expectEqualSlices(u8, &.{ 0x11, 0x08, 0, 0, 0, 1, 0, 0, 0, 1 }, encoded); var storage: IdStorage = .{}; const back = (try parse(encoded, &storage, .client)).version_information.?; try testing.expectEqual(@as(u32, 1), back.chosen); try testing.expectEqualSlices(u32, &.{1}, back.availableVersions()); try testing.expect(back.offers(1)); try testing.expect(!back.offers(2)); } test "RFC 9368 4: version information that does not parse is refused" { var storage: IdStorage = .{}; const refused = error.TransportParameterError; // "Too short or... its length is not divisible by four." try testing.expectError(refused, parse(&.{ 0x11, 0x00 }, &storage, .server)); try testing.expectError(refused, parse(&.{ 0x11, 0x06, 0, 0, 0, 1, 0, 0 }, &storage, .server)); // "A Chosen Version equal to zero, or any Available Version equal to zero." try testing.expectError(refused, parse(&.{ 0x11, 0x04, 0, 0, 0, 0 }, &storage, .server)); try testing.expectError(refused, parse(&.{ 0x11, 0x08, 0, 0, 0, 1, 0, 0, 0, 0 }, &storage, .server)); // A client whose Chosen Version is not among its Available Versions. try testing.expectError(refused, parse(&.{ 0x11, 0x08, 0, 0, 0, 1, 0x6b, 0x33, 0x43, 0xcf }, &storage, .client)); // The same from a server is allowed -- it may be retiring the version -- // and so is a server with no Available Versions at all. _ = try parse(&.{ 0x11, 0x08, 0, 0, 0, 1, 0x6b, 0x33, 0x43, 0xcf }, &storage, .server); _ = try parse(&.{ 0x11, 0x04, 0, 0, 0, 1 }, &storage, .server); } test "RFC 9368 3: a long list of versions is checked in full and kept in part" { // Grease versions, 0x?a?a?a?a, are allowed in the list and are what a // long one is likely to be full of. Every entry is read -- a zero at the // end is still a zero -- but only the first few are held. var body: [4 * 12]u8 = undefined; std.mem.writeInt(u32, body[0..4], 1, .big); for (1..12) |i| std.mem.writeInt(u32, body[4 * i ..][0..4], if (i == 11) 1 else 0x1a2a3a4a, .big); var encoded: [2 + body.len]u8 = undefined; encoded[0] = 0x11; encoded[1] = body.len; @memcpy(encoded[2..], &body); var storage: IdStorage = .{}; const v = (try parse(&encoded, &storage, .client)).version_information.?; try testing.expectEqual(VersionInformation.max_available, v.availableVersions().len); std.mem.writeInt(u32, encoded[encoded.len - 4 ..][0..4], 0, .big); try testing.expectError(error.TransportParameterError, parse(&encoded, &storage, .client)); } test "draft-ietf-quic-address-discovery-01 3: a role is 0, 1 or 2, and nothing else" { var buffer: [16]u8 = undefined; var storage: IdStorage = .{}; inline for (.{ AddressDiscovery.provide, .receive, .both }) |role| { const encoded = try write(&.{ .address_discovery = role }, &buffer, .client); try testing.expectEqual(role, (try parse(encoded, &storage, .client)).address_discovery.?); } // 0x9f81a176 is past a four-octet varint's 2^30, so it takes eight: then // a length of one, and 2. try testing.expectEqualSlices(u8, &.{ 0xc0, 0, 0, 0, 0x9f, 0x81, 0xa1, 0x76, 0x01, 0x02 }, try write(&.{ .address_discovery = .both }, &buffer, .client)); try testing.expectError(error.TransportParameterError, parse(&.{ 0xc0, 0, 0, 0, 0x9f, 0x81, 0xa1, 0x76, 0x01, 0x03 }, &storage, .client)); // Absent is not the same as any of the three. try testing.expectEqual(@as(?AddressDiscovery, null), (try parse(&.{}, &storage, .client)).address_discovery); } test "draft-ietf-quic-address-discovery-01 4.1: reports flow only where one end gives and the other asks" { try testing.expect(AddressDiscovery.reportsTo(.provide, .receive)); try testing.expect(AddressDiscovery.reportsTo(.both, .both)); try testing.expect(!AddressDiscovery.reportsTo(.receive, .both)); try testing.expect(!AddressDiscovery.reportsTo(.both, .provide)); try testing.expect(!AddressDiscovery.reportsTo(.both, null)); try testing.expect(!AddressDiscovery.reportsTo(null, .both)); } test "draft-ietf-quic-ack-frequency-14 3: min_ack_delay, in microseconds, no more than max_ack_delay" { var buffer: [64]u8 = undefined; var storage: IdStorage = .{}; // noq's value: its timer granularity, one millisecond. const encoded = try write(&.{ .min_ack_delay = 1000 }, &buffer, .client); try testing.expectEqualSlices(u8, &.{ 0xc0, 0, 0, 0, 0xff, 0x04, 0xde, 0x1b, 0x02, 0x43, 0xe8 }, encoded); const p = try parse(encoded, &storage, .client); try testing.expectEqual(@as(?u64, 1000), p.min_ack_delay); try p.validate(.client); // 25 ms is the default max_ack_delay; 25001 µs is past it. const over: Parameters = .{ .min_ack_delay = 25_001 }; try testing.expectError(error.TransportParameterError, over.validate(.client)); const equal: Parameters = .{ .min_ack_delay = 25_000 }; try equal.validate(.client); } test "n0 NAT traversal: the parameter is one raw octet" { var buffer: [64]u8 = undefined; var storage: IdStorage = .{}; // noq's own encoding, value 5. try testing.expectEqualSlices( u8, &.{ 0xc0, 0x00, 0x3d, 0x7f, 0x91, 0x12, 0x04, 0x01, 0x01, 0x05 }, try write(&.{ .n0_nat_traversal = 5 }, &buffer, .client), ); // Above 63, where a varint would have taken two octets: still one. const iroh = try write(&.{ .n0_nat_traversal = 200 }, &buffer, .server); try testing.expectEqual(@as(usize, 10), iroh.len); try testing.expectEqual(@as(?u8, 200), (try parse(iroh, &storage, .server)).n0_nat_traversal); // Zero is an illegal value, and any length but one is malformed. try testing.expectError(error.TransportParameterError, parse( &.{ 0xc0, 0x00, 0x3d, 0x7f, 0x91, 0x12, 0x04, 0x01, 0x01, 0x00 }, &storage, .client, )); try testing.expectError(error.TransportParameterError, parse( &.{ 0xc0, 0x00, 0x3d, 0x7f, 0x91, 0x12, 0x04, 0x01, 0x02, 0x40, 0x80 }, &storage, .client, )); try testing.expectError(error.TransportParameterError, write(&.{ .n0_nat_traversal = 0 }, &buffer, .client)); } test "draft-ietf-quic-multipath-21 2.1: initial_max_path_id, and its ceiling" { var buffer: [16]u8 = undefined; var storage: IdStorage = .{}; // Zero is a value, not an absence: multipath with only path 0 for now. const zero = try write(&.{ .initial_max_path_id = 0 }, &buffer, .client); try testing.expectEqualSlices(u8, &.{ 0x3e, 0x01, 0x00 }, zero); try testing.expectEqual(@as(?u64, 0), (try parse(zero, &storage, .client)).initial_max_path_id); try testing.expectEqual(@as(?u64, null), (try parse(&.{}, &storage, .client)).initial_max_path_id); // 2^32 - 1 is allowed and one more is not, in either direction. const top = try write(&.{ .initial_max_path_id = max_path_id }, &buffer, .server); try testing.expectEqual(@as(?u64, max_path_id), (try parse(top, &storage, .server)).initial_max_path_id); try testing.expectError(error.TransportParameterError, write(&.{ .initial_max_path_id = max_path_id + 1 }, &buffer, .client)); try testing.expectError(error.TransportParameterError, parse(&.{ 0x3e, 0x08, 0xc0, 0, 0, 1, 0, 0, 0, 0 }, &storage, .client)); }