// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! RFC 9000 §19: the twenty frame types a packet payload is made of. //! //! A packet payload, once decrypted, is a sequence of complete frames and //! nothing else — no length, no count, no terminator. A frame's type says how //! long it is, so a parser that mistakes one type for another does not //! discover its mistake, it silently reads the next frame as though it were //! part of this one. That is why nearly every rule in §12.4 is about framing //! rather than semantics, and why they are all enforced here rather than //! anywhere later. //! //! ## Nothing here allocates //! //! A frame's variable-length parts — CRYPTO data, STREAM data, a token, a //! reason phrase, the ACK ranges — are slices of the payload they were parsed //! out of. That payload is the plaintext buffer `packet.open` wrote into, so //! it outlives the parse and a caller that wants to keep a frame past the next //! packet copies it. //! //! The ACK ranges go further and are not decoded at all until asked for: //! `Ack.ranges()` walks them on demand. An ACK frame can describe a great many //! ranges and most callers want the largest acknowledged and nothing else. //! //! ## PADDING is counted, not repeated //! //! §19.1's PADDING frame is a single zero octet with no fields, and a packet //! is padded by sending a great many of them — RFC 9001's Appendix A client //! Initial has 917 in a row. Yielding those one at a time would be faithful //! and useless, so `Iterator` coalesces a run into one frame carrying the //! count. Nothing is lost: PADDING has no content, and the only thing anybody //! wants to know is how much of the packet was padding. const std = @import("std"); const assert = std.debug.assert; const tls = @import("tls.zig"); const varint = @import("varint.zig"); /// §19.15: "Values less than 1 and greater than 20 are invalid." pub const max_connection_id_len = 20; /// §19.15: the Stateless Reset Token is 128 bits. pub const stateless_reset_token_len = 16; /// §19.11: "This value cannot exceed 2^60, as it is not possible to encode /// stream IDs larger than 2^62-1." pub const max_streams_limit = @as(u64, 1) << 60; pub const Kind = enum { padding, ping, ack, reset_stream, stop_sending, crypto, new_token, stream, max_data, max_stream_data, max_streams, data_blocked, stream_data_blocked, streams_blocked, new_connection_id, retire_connection_id, path_challenge, path_response, connection_close, handshake_done, /// RFC 9221's extension frame, which is not in RFC 9000's table at all. datagram, /// draft-ietf-quic-address-discovery-01 §4.1: the peer's report of the /// address this endpoint's packets arrive from. observed_address, /// draft-ietf-quic-multipath-21 §4: an ACK for one path's packet number /// space, and the frames that manage paths and their connection IDs. path_ack, path_abandon, path_status, path_new_connection_id, path_retire_connection_id, max_path_id, paths_blocked, path_cids_blocked, /// n0's NAT traversal: a server's candidate address, one withdrawn, and /// a client's candidate for a round of hole punching. add_address, remove_address, reach_out, /// draft-ietf-quic-ack-frequency-14: how often the peer asks to be /// acknowledged, and a request to be acknowledged now. ack_frequency, immediate_ack, }; /// draft-ietf-quic-multipath-21 §6's frame types -- the suggested final /// values, not §6.1's provisional ones, which are a disjoint set and would /// negotiate nothing with an implementation that has moved on. pub const path_ack_type: u64 = 0x3e; pub const path_ack_ecn_type: u64 = 0x3f; pub const path_abandon_type: u64 = 0x3e75; pub const path_status_backup_type: u64 = 0x3e76; pub const path_status_available_type: u64 = 0x3e77; pub const path_new_connection_id_type: u64 = 0x3e78; pub const path_retire_connection_id_type: u64 = 0x3e79; pub const max_path_id_type: u64 = 0x3e7a; pub const paths_blocked_type: u64 = 0x3e7b; pub const path_cids_blocked_type: u64 = 0x3e7c; /// draft-ietf-quic-address-discovery-01 §4.1's two frame types. "The least /// significant bit of the frame type" says which address family follows -- /// the same trick RFC 9221 plays with the length and §19.11 with /// directionality. pub const observed_address_ipv4: u64 = 0x9f81a6; pub const observed_address_ipv6: u64 = 0x9f81a7; /// n0's NAT traversal, as noq has it -- `0x3d7f..`, one hex digit away from /// `draft-seemann-quic-nat-traversal-02`'s `0x3d7e..`, and not that draft. /// As with OBSERVED_ADDRESS the frame type says the address family, and /// there is no field for it. pub const add_address_ipv4: u64 = 0x3d7f90; pub const add_address_ipv6: u64 = 0x3d7f91; pub const reach_out_ipv4: u64 = 0x3d7f92; pub const reach_out_ipv6: u64 = 0x3d7f93; pub const remove_address_type: u64 = 0x3d7f94; /// draft-ietf-quic-ack-frequency-14 §4 and §5, the values noq uses too. pub const ack_frequency_type: u64 = 0xaf; pub const immediate_ack_type: u64 = 0x1f; pub const Error = error{ /// §12.4: "An endpoint MUST treat the receipt of a frame of unknown type /// as a connection error of type FRAME_ENCODING_ERROR." /// /// Note that this is *not* HTTP/2's rule, where an unknown frame type /// must be discarded. HTTP/2 can afford that because every frame carries /// its own length and a reader can skip one it does not understand; a /// QUIC frame's length is implied by its type, so an unknown type means /// the rest of the packet cannot be located at all. UnknownType, /// §12.4: "a frame type MUST use the shortest possible encoding" — the /// sole exception to §16's tolerance of non-minimal varints, and the one /// place in QUIC where two spellings of one value is refused. NonMinimalType, /// A frame that extends past the end of the packet. Truncated, /// §19.3.1: "If any computed packet number is negative, an endpoint MUST /// generate a connection error of type FRAME_ENCODING_ERROR." InvalidAckRange, /// §19.15: a connection ID length outside 1..20, or a Retire Prior To /// greater than the Sequence Number. InvalidConnectionId, /// §19.11: a stream limit above 2^60. StreamLimitTooLarge, /// §19.8: "The largest offset delivered on a stream -- the sum of the /// offset and data length -- cannot exceed 2^62-1." OffsetTooLarge, }; pub const Ack = struct { largest: u64, /// §19.3: in microseconds, scaled by the peer's `ack_delay_exponent`. /// Left encoded here, because the exponent is a transport parameter this /// layer does not know. delay: u64, first_range: u64, range_count: u64, /// The encoded Gap and ACK Range Length pairs, walked by `ranges`. encoded_ranges: []const u8, ecn: ?Ecn, /// §19.3.2. pub const Ecn = struct { ect0: u64, ect1: u64, ce: u64 }; /// An inclusive range of acknowledged packet numbers. pub const Range = struct { smallest: u64, largest: u64 }; /// The range the Largest Acknowledged and First ACK Range describe, which /// every ACK frame has. /// /// `error.InvalidAckRange` when First ACK Range is larger than Largest /// Acknowledged, which would put the smallest below zero -- §19.3.1 /// makes that a FRAME_ENCODING_ERROR rather than something to clamp. pub fn firstRange(a: Ack) Error!Range { if (a.first_range > a.largest) return error.InvalidAckRange; return .{ .smallest = a.largest - a.first_range, .largest = a.largest }; } test firstRange { // Largest Acknowledged 20, First ACK Range 4: packets 16 to 20. const ack = (try parse(&.{ 0x02, 20, 0, 0, 4 })).frame.ack; try std.testing.expectEqual(Range{ .smallest = 16, .largest = 20 }, try ack.firstRange()); } /// An iterator over the ranges after the first, newest first, decoded /// from `encoded_ranges` as it goes. The first range is `firstRange`'s, /// and the iterator does not repeat it. /// /// The iterator holds a copy of this `Ack`, and its slices point into the /// payload the frame was parsed from, which has to outlive it. pub fn ranges(a: Ack) RangeIterator { return .{ .rest = a.encoded_ranges, .remaining = a.range_count, .ack = a }; } test ranges { // Largest 50, first range 40..50, then a gap of 0 and a range of 4: // 34..38, the one unacknowledged packet 39 between them. const ack = (try parse(&.{ 0x02, 50, 0, 1, 10, 0, 4 })).frame.ack; var acknowledged: u64 = 0; const first = try ack.firstRange(); acknowledged += first.largest - first.smallest + 1; var it = ack.ranges(); while (try it.next()) |r| acknowledged += r.largest - r.smallest + 1; try std.testing.expectEqual(@as(u64, 16), acknowledged); } /// Walks the additional ranges, newest first. /// /// §19.3.1's arithmetic is subtractive and every step of it can go below /// zero on hostile input, which the RFC makes a connection error rather /// than something to clamp. Each subtraction is checked. pub const RangeIterator = struct { rest: []const u8, remaining: u64, ack: Ack, previous_smallest: ?u64 = null, /// The next range down, or null after the last of Range Count. /// /// `error.InvalidAckRange` when a Gap or ACK Range Length would take /// a packet number below zero, or when the first range itself is /// invalid; a caller treats either as §19.3.1's FRAME_ENCODING_ERROR /// and stops. pub fn next(it: *RangeIterator) Error!?Range { if (it.remaining == 0) return null; it.remaining -= 1; const smallest = it.previous_smallest orelse blk: { const first = try it.ack.firstRange(); break :blk first.smallest; }; const gap = try varint.parse(it.rest); it.rest = it.rest[gap.len..]; const length = try varint.parse(it.rest); it.rest = it.rest[length.len..]; // §19.3.1: "largest = previous_smallest - gap - 2". if (smallest < gap.value + 2) return error.InvalidAckRange; const largest = smallest - gap.value - 2; if (length.value > largest) return error.InvalidAckRange; const range: Range = .{ .smallest = largest - length.value, .largest = largest }; it.previous_smallest = range.smallest; return range; } test next { // Largest 10, first range 10..10, then a gap of 1 and a range of // 2 (packets 5 to 7), then a gap of 0 and a range of 0 (packet 3). const ack = (try parse(&.{ 0x02, 10, 0, 2, 0, 1, 2, 0, 0 })).frame.ack; var it = ack.ranges(); try std.testing.expectEqual(Range{ .smallest = 5, .largest = 7 }, (try it.next()).?); try std.testing.expectEqual(Range{ .smallest = 3, .largest = 3 }, (try it.next()).?); try std.testing.expectEqual(@as(?Range, null), try it.next()); } }; }; pub const ResetStream = struct { stream: u64, error_code: u64, final_size: u64 }; pub const StopSending = struct { stream: u64, error_code: u64 }; pub const Crypto = struct { offset: u64, data: []const u8 }; pub const MaxStreamData = struct { stream: u64, maximum: u64 }; pub const StreamDataBlocked = struct { stream: u64, maximum: u64 }; /// §19.11 and §19.14: the type's low bit says which kind of stream is meant. pub const Directionality = enum { bidirectional, unidirectional }; pub const StreamLimit = struct { kind: Directionality, maximum: u64 }; pub const Stream = struct { stream: u64, offset: u64, data: []const u8, fin: bool, /// Whether the frame carried a Length field. §19.8: without one, "the /// Stream Data field consumes all the remaining bytes in the packet", /// which means such a frame can only be the last one. had_length: bool, }; /// RFC 9221 §4: an unreliable datagram. /// /// The extension exists because some applications want QUIC's handshake, /// congestion control and path validation without its retransmissions -- /// real-time media, and the tunnelling of somebody else's unreliable /// protocol. §5.2: "DATAGRAM frames... SHOULD NOT be retransmitted", because /// an application that wanted them retransmitted would have used a stream. pub const Datagram = struct { data: []const u8, /// Whether the frame carried a Length field. §4: without one (type 0x30) /// "the datagram data extends to the end of the QUIC packet", so such a /// frame can only be the last one -- the same rule, and the same saving, /// as a STREAM frame with no length. had_length: bool, }; pub const NewConnectionId = struct { sequence: u64, retire_prior_to: u64, id: []const u8, token: *const [stateless_reset_token_len]u8, }; pub const ConnectionClose = struct { error_code: u64, /// §19.19: present only on the transport variant (0x1c), and it names the /// frame type that caused the close — zero when none did. frame_type: ?u64, reason: []const u8, /// Whether this is the application variant, 0x1d. /// /// The distinction is not cosmetic: 0x1d may not appear in an Initial or /// Handshake packet, because at that point no application protocol has /// been negotiated and there is nothing whose error codes would mean /// anything. application: bool, }; /// An address and port, as OBSERVED_ADDRESS carries them. /// /// Raw octets rather than any address type, for the reason /// `parameters.PreferredAddress` gives: this library has no sockets, so an /// address is data it hands back to the caller rather than something it can /// act on. pub const Address = struct { ip: Ip, port: u16, pub const Ip = union(enum) { v4: [4]u8, v6: [16]u8, }; /// Whether two addresses are the same family, octets and port. /// /// Exact, so an IPv4 address and its IPv4-mapped IPv6 form are not /// equal; compare their `canonical` forms to treat them as one. pub fn eql(a: Address, b: Address) bool { if (a.port != b.port) return false; return switch (a.ip) { .v4 => |x| b.ip == .v4 and std.mem.eql(u8, &x, &b.ip.v4), .v6 => |x| b.ip == .v6 and std.mem.eql(u8, &x, &b.ip.v6), }; } test eql { const a: Address = .{ .ip = .{ .v4 = .{ 192, 0, 2, 1 } }, .port = 4433 }; try std.testing.expect(a.eql(.{ .ip = .{ .v4 = .{ 192, 0, 2, 1 } }, .port = 4433 })); // Same host, another port: another address. try std.testing.expect(!a.eql(.{ .ip = .{ .v4 = .{ 192, 0, 2, 1 } }, .port = 4434 })); } /// The address with an IPv4-mapped IPv6 one (`::ffff:a.b.c.d`) written /// as the IPv4 address it is, and everything else as it was. /// /// A dual-stack socket reports an IPv4 peer in the mapped form, so the /// same peer can arrive written two ways; comparing canonical forms is /// what makes them one. n0's NAT traversal also sends only canonical /// addresses -- a mapped one goes in the IPv4 frame. pub fn canonical(a: Address) Address { switch (a.ip) { .v4 => return a, .v6 => |x| { const prefix = @as([10]u8, @splat(0)) ++ [_]u8{ 0xff, 0xff }; if (!std.mem.eql(u8, x[0..12], &prefix)) return a; return .{ .ip = .{ .v4 = x[12..16].* }, .port = a.port }; }, } } test canonical { // ::ffff:198.51.100.7, as a dual-stack socket reports an IPv4 peer. var mapped: [16]u8 = @splat(0); mapped[10] = 0xff; mapped[11] = 0xff; mapped[12..16].* = .{ 198, 51, 100, 7 }; const seen: Address = .{ .ip = .{ .v6 = mapped }, .port = 853 }; const announced: Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 853 }; try std.testing.expect(!seen.eql(announced)); try std.testing.expect(seen.canonical().eql(announced)); } }; /// A number and an address, which is the shape of OBSERVED_ADDRESS and of /// n0's ADD_ADDRESS and REACH_OUT alike -- the number being a sequence /// number in the first two and a round in the third. pub const NumberedAddress = struct { sequence: u64, address: Address, }; /// draft-ietf-quic-address-discovery-01 §4.1. Its sequence number "MUST be /// monotonically increasing for OBSERVED_ADDRESS frames in the same /// connection", which is what lets a reordered old report be told from a new /// one. pub const ObservedAddress = NumberedAddress; /// draft-ietf-quic-multipath-21 §4.1: an ACK frame with a path in front. pub const PathAck = struct { path: u64, ack: Ack, }; /// §4.2. pub const PathAbandon = struct { path: u64, error_code: u64, }; /// §4.3: PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP, which differ only in /// their type and share one sequence number space per path -- so one frame /// here with the difference in a field. pub const PathStatus = struct { path: u64, sequence: u64, status: Status, pub const Status = enum { available, backup }; }; /// §4.4: a NEW_CONNECTION_ID for one path, whose sequence numbers are that /// path's own. pub const PathNewConnectionId = struct { path: u64, id: NewConnectionId, }; /// §4.5. pub const PathRetireConnectionId = struct { path: u64, sequence: u64, }; /// §4.7. pub const PathCidsBlocked = struct { path: u64, next_sequence: u64, }; /// draft-ietf-quic-ack-frequency-14 §4. pub const AckFrequency = struct { /// "Monotonically increasing", so that a reordered old one is ignored. sequence: u64, /// The most ack-eliciting packets to receive without acknowledging; 1 is /// RFC 9000's every other packet, 0 is every one. ack_eliciting_threshold: u64, /// In microseconds, unlike the max_ack_delay parameter it replaces. requested_max_ack_delay: u64, /// The reordering that triggers an immediate ACK: 1 is RFC 9000's any /// at all, 0 is none. reordering_threshold: u64, }; pub const Frame = union(Kind) { /// How many PADDING frames were coalesced into this one. padding: u64, ping, ack: Ack, reset_stream: ResetStream, stop_sending: StopSending, crypto: Crypto, new_token: []const u8, stream: Stream, max_data: u64, max_stream_data: MaxStreamData, max_streams: StreamLimit, data_blocked: u64, stream_data_blocked: StreamDataBlocked, streams_blocked: StreamLimit, new_connection_id: NewConnectionId, retire_connection_id: u64, path_challenge: *const [8]u8, path_response: *const [8]u8, connection_close: ConnectionClose, handshake_done, datagram: Datagram, observed_address: ObservedAddress, path_ack: PathAck, path_abandon: PathAbandon, path_status: PathStatus, path_new_connection_id: PathNewConnectionId, path_retire_connection_id: PathRetireConnectionId, max_path_id: u64, paths_blocked: u64, path_cids_blocked: PathCidsBlocked, /// n0's NAT traversal. ADD_ADDRESS's number is its sequence number, and /// REACH_OUT's is its round. add_address: NumberedAddress, remove_address: u64, reach_out: NumberedAddress, ack_frequency: AckFrequency, immediate_ack, /// §13.2.1: whether a packet containing this frame must be acknowledged. /// /// Table 3's "N" marking, inverted. Everything is ack-eliciting except /// ACK, PADDING and CONNECTION_CLOSE — and the reason those three are not /// is the same in each case: acknowledging them would start an exchange /// that never ends, since the acknowledgement is itself a packet that /// would need acknowledging. Multipath's PATH_ACK is an ACK, and is not /// ack-eliciting either. pub fn isAckEliciting(f: Frame) bool { return switch (f) { // PATH_ACK is an ACK, and is not acknowledged for the same // reason. .padding, .ack, .path_ack, .connection_close => false, else => true, }; } test isAckEliciting { // A packet is ack-eliciting if any frame in it is, so a packet of an // ACK and some PADDING is not, and adding a PING makes it one. const payload = [_]u8{ 0x02, 10, 0, 0, 0, 0x00, 0x00 }; var it: Iterator = .init(&payload); var eliciting = false; while (try it.next()) |f| eliciting = eliciting or f.isAckEliciting(); try std.testing.expect(!eliciting); try std.testing.expect((@as(Frame, .ping)).isAckEliciting()); } /// Table 3's "Pkts" column: whether this frame may appear in a packet at /// this encryption level. /// /// §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." pub fn allowedIn(f: Frame, level: tls.Level) bool { return switch (f) { // IH01 — anywhere. .padding, .ping => true, // IH_1 — everywhere but 0-RTT, which cannot carry an // acknowledgement because it is sent before anything to // acknowledge has arrived. .ack, .crypto => level != .early_data, // ___1 — only once the handshake has produced 1-RTT keys. .new_token, .path_response, .handshake_done => level == .application, // RFC 9221 §4: "DATAGRAM frames... MAY be sent in 0-RTT or 1-RTT // packets", and nowhere else -- there is no application to hand // one to before an application protocol has been negotiated. .datagram => level == .early_data or level == .application, // draft-ietf-quic-address-discovery-01 §4.1: "This frame MUST // only appear in the application data packet number space" -- // 0-RTT included, which §3 relies on when it lets the frame be // sent in early data. .observed_address => level == .early_data or level == .application, // draft-ietf-quic-multipath-21 §4: "All frames defined in this // document MUST only be sent in 1-RTT packets" -- not even 0-RTT, // since whether multipath is in use is not known until the // handshake says so. .path_ack, .path_abandon, .path_status, .path_new_connection_id, .path_retire_connection_id, .max_path_id, .paths_blocked, .path_cids_blocked, => level == .application, // noq sends these only in 1-RTT packets, since whether the // extension is in use depends on multipath, which 0-RTT never // has. .add_address, .remove_address, .reach_out => level == .application, // draft-ietf-quic-ack-frequency-14 §3: min_ack_delay is not // remembered for a later connection, so "ACK_FREQUENCY and // IMMEDIATE_ACK frames cannot be sent in 0-RTT packets". .ack_frequency, .immediate_ack => level == .application, // ih01 for the transport variant and __01 for the application // one: an application error code means nothing before an // application protocol has been negotiated. .connection_close => |c| if (c.application) level == .early_data or level == .application else true, // __01 — everything else is about streams or paths, neither of // which exists during the handshake. else => level == .early_data or level == .application, }; } test allowedIn { // A STREAM frame found in a Handshake packet is a PROTOCOL_VIOLATION. const f = (try parse(&[_]u8{ 0x0a, 0x00, 0x02 } ++ "hi".*)).frame; try std.testing.expect(!f.allowedIn(.handshake)); try std.testing.expect(f.allowedIn(.application)); } }; pub const Parsed = struct { frame: Frame, /// How many octets of the payload it occupied. len: usize, }; /// Reads one frame from the front of `payload`. /// /// `payload` must be the rest of the packet, not just the rest of the frame: /// a STREAM frame without a Length field runs to the end of the packet, and /// there is no other way to know where that is. /// /// Any slice in the frame points into `payload`, which has to outlive it. A /// PADDING frame comes back as a count of one; `Iterator` is what coalesces /// a run of them. Whether the frame is allowed at the encryption level it /// arrived at is not checked here -- that is `Frame.allowedIn`. pub fn parse(payload: []const u8) Error!Parsed { const t = try varint.parse(payload); // §12.4's one exception to §16. A frame type is the only field in QUIC // where two spellings of one value is refused, and it is refused because // frame parsing has to be cheap: a reader that had to canonicalise the // type before switching on it would do so for every frame in every // packet. if (t.len != varint.encodedLen(t.value)) return error.NonMinimalType; var at = t.len; switch (t.value) { 0x00 => return .{ .frame = .{ .padding = 1 }, .len = at }, 0x01 => return .{ .frame = .ping, .len = at }, 0x02, 0x03 => { const f = try takeAck(payload, &at, t.value == 0x03); return .{ .frame = .{ .ack = f }, .len = at }; }, path_ack_type, path_ack_ecn_type => { const path = try take(payload, &at); const f = try takeAck(payload, &at, t.value == path_ack_ecn_type); return .{ .frame = .{ .path_ack = .{ .path = path.value, .ack = f } }, .len = at }; }, path_abandon_type => { const path = try take(payload, &at); const code = try take(payload, &at); return .{ .frame = .{ .path_abandon = .{ .path = path.value, .error_code = code.value } }, .len = at }; }, path_status_backup_type, path_status_available_type => { const path = try take(payload, &at); const sequence = try take(payload, &at); return .{ .frame = .{ .path_status = .{ .path = path.value, .sequence = sequence.value, .status = if (t.value == path_status_available_type) .available else .backup, } }, .len = at }; }, path_new_connection_id_type => { const path = try take(payload, &at); const id = try takeNewConnectionId(payload, &at); return .{ .frame = .{ .path_new_connection_id = .{ .path = path.value, .id = id } }, .len = at }; }, path_retire_connection_id_type => { const path = try take(payload, &at); const sequence = try take(payload, &at); return .{ .frame = .{ .path_retire_connection_id = .{ .path = path.value, .sequence = sequence.value } }, .len = at }; }, max_path_id_type, paths_blocked_type => { const v = try take(payload, &at); return .{ .frame = if (t.value == max_path_id_type) .{ .max_path_id = v.value } else .{ .paths_blocked = v.value }, .len = at, }; }, path_cids_blocked_type => { const path = try take(payload, &at); const next = try take(payload, &at); return .{ .frame = .{ .path_cids_blocked = .{ .path = path.value, .next_sequence = next.value } }, .len = at }; }, 0x04 => { const stream = try take(payload, &at); const code = try take(payload, &at); const final = try take(payload, &at); return .{ .frame = .{ .reset_stream = .{ .stream = stream.value, .error_code = code.value, .final_size = final.value, } }, .len = at }; }, 0x05 => { const stream = try take(payload, &at); const code = try take(payload, &at); return .{ .frame = .{ .stop_sending = .{ .stream = stream.value, .error_code = code.value, } }, .len = at }; }, 0x06 => { const offset = try take(payload, &at); const data = try takeBytes(payload, &at); if (offset.value + data.len > varint.max) return error.OffsetTooLarge; return .{ .frame = .{ .crypto = .{ .offset = offset.value, .data = data, } }, .len = at }; }, 0x07 => { const token = try takeBytes(payload, &at); return .{ .frame = .{ .new_token = token }, .len = at }; }, 0x08...0x0f => { const off_bit = t.value & 0x04 != 0; const len_bit = t.value & 0x02 != 0; const fin_bit = t.value & 0x01 != 0; const stream = try take(payload, &at); var offset: u64 = 0; if (off_bit) offset = (try take(payload, &at)).value; const data = if (len_bit) try takeBytes(payload, &at) else blk: { // §19.8: "When the LEN bit is set to 0, the Stream Data field // consumes all the remaining bytes in the packet." const d = payload[at..]; at = payload.len; break :blk d; }; if (offset + data.len > varint.max) return error.OffsetTooLarge; return .{ .frame = .{ .stream = .{ .stream = stream.value, .offset = offset, .data = data, .fin = fin_bit, .had_length = len_bit, } }, .len = at }; }, 0x10 => { const v = try take(payload, &at); return .{ .frame = .{ .max_data = v.value }, .len = at }; }, 0x11 => { const stream = try take(payload, &at); const max = try take(payload, &at); return .{ .frame = .{ .max_stream_data = .{ .stream = stream.value, .maximum = max.value, } }, .len = at }; }, 0x12, 0x13 => { const max = try take(payload, &at); if (max.value > max_streams_limit) return error.StreamLimitTooLarge; return .{ .frame = .{ .max_streams = .{ .kind = if (t.value == 0x12) .bidirectional else .unidirectional, .maximum = max.value, } }, .len = at }; }, 0x14 => { const v = try take(payload, &at); return .{ .frame = .{ .data_blocked = v.value }, .len = at }; }, 0x15 => { const stream = try take(payload, &at); const max = try take(payload, &at); return .{ .frame = .{ .stream_data_blocked = .{ .stream = stream.value, .maximum = max.value, } }, .len = at }; }, 0x16, 0x17 => { const max = try take(payload, &at); if (max.value > max_streams_limit) return error.StreamLimitTooLarge; return .{ .frame = .{ .streams_blocked = .{ .kind = if (t.value == 0x16) .bidirectional else .unidirectional, .maximum = max.value, } }, .len = at }; }, 0x18 => { const n = try takeNewConnectionId(payload, &at); return .{ .frame = .{ .new_connection_id = n }, .len = at }; }, 0x19 => { const v = try take(payload, &at); return .{ .frame = .{ .retire_connection_id = v.value }, .len = at }; }, 0x1a, 0x1b => { if (payload.len - at < 8) return error.Truncated; const data = payload[at..][0..8]; at += 8; return .{ .frame = if (t.value == 0x1a) .{ .path_challenge = data } else .{ .path_response = data }, .len = at, }; }, 0x1c, 0x1d => { const code = try take(payload, &at); const frame_type: ?u64 = if (t.value == 0x1c) (try take(payload, &at)).value else null; const reason = try takeBytes(payload, &at); return .{ .frame = .{ .connection_close = .{ .error_code = code.value, .frame_type = frame_type, .reason = reason, .application = t.value == 0x1d, } }, .len = at }; }, 0x1e => return .{ .frame = .handshake_done, .len = at }, immediate_ack_type => return .{ .frame = .immediate_ack, .len = at }, ack_frequency_type => { const sequence = try take(payload, &at); const threshold = try take(payload, &at); const delay = try take(payload, &at); const reordering = try take(payload, &at); return .{ .frame = .{ .ack_frequency = .{ .sequence = sequence.value, .ack_eliciting_threshold = threshold.value, .requested_max_ack_delay = delay.value, .reordering_threshold = reordering.value, } }, .len = at }; }, observed_address_ipv4, observed_address_ipv6 => { const numbered = try takeNumberedAddress(payload, &at, t.value == observed_address_ipv6); return .{ .frame = .{ .observed_address = numbered }, .len = at }; }, add_address_ipv4, add_address_ipv6 => { const numbered = try takeNumberedAddress(payload, &at, t.value == add_address_ipv6); return .{ .frame = .{ .add_address = numbered }, .len = at }; }, reach_out_ipv4, reach_out_ipv6 => { const numbered = try takeNumberedAddress(payload, &at, t.value == reach_out_ipv6); return .{ .frame = .{ .reach_out = numbered }, .len = at }; }, remove_address_type => { const sequence = try take(payload, &at); return .{ .frame = .{ .remove_address = sequence.value }, .len = at }; }, // RFC 9221 §4: 0x30 has no Length and runs to the end of the packet; // 0x31 carries one. Nothing here decides whether a DATAGRAM frame was // welcome -- §3 makes that a question about the transport parameters, // which this file does not see. 0x30, 0x31 => { const data = if (t.value == 0x31) try takeBytes(payload, &at) else rest: { const all = payload[at..]; at = payload.len; break :rest all; }; return .{ .frame = .{ .datagram = .{ .data = data, .had_length = t.value == 0x31, } }, .len = at }; }, else => return error.UnknownType, } } test parse { // A MAX_DATA frame raising the connection's limit to 1,000,000, and a // PING after it in the same packet. const payload = [_]u8{ 0x10, 0x80, 0x0f, 0x42, 0x40, 0x01 }; const got = try parse(&payload); try std.testing.expectEqual(@as(u64, 1_000_000), got.frame.max_data); try std.testing.expectEqual(@as(usize, 5), got.len); // The next frame starts where this one ended. try std.testing.expectEqual(Kind.ping, (try parse(payload[got.len..])).frame); } /// A number, then an IPv4 or IPv6 address and a big-endian port, as /// OBSERVED_ADDRESS, ADD_ADDRESS and REACH_OUT all have them. fn takeNumberedAddress(payload: []const u8, at: *usize, v6: bool) Error!NumberedAddress { const sequence = try take(payload, at); const ip: Address.Ip = if (v6) ip: { if (payload.len - at.* < 16) return error.Truncated; const bytes = payload[at.*..][0..16].*; at.* += 16; break :ip .{ .v6 = bytes }; } else ip: { if (payload.len - at.* < 4) return error.Truncated; const bytes = payload[at.*..][0..4].*; at.* += 4; break :ip .{ .v4 = bytes }; }; if (payload.len - at.* < 2) return error.Truncated; const port = std.mem.readInt(u16, payload[at.*..][0..2], .big); at.* += 2; return .{ .sequence = sequence.value, .address = .{ .ip = ip, .port = port } }; } /// §19.3's ACK body, from Largest Acknowledged on -- shared by ACK and by /// draft-ietf-quic-multipath-21's PATH_ACK, which is the same thing with a /// path in front. fn takeAck(payload: []const u8, at: *usize, with_ecn: bool) Error!Ack { const largest = try take(payload, at); const delay = try take(payload, at); const range_count = try take(payload, at); const first_range = try take(payload, at); const ranges_start = at.*; var i: u64 = 0; while (i < range_count.value) : (i += 1) { _ = try take(payload, at); _ = try take(payload, at); } var f: Ack = .{ .largest = largest.value, .delay = delay.value, .range_count = range_count.value, .first_range = first_range.value, .encoded_ranges = payload[ranges_start..at.*], .ecn = null, }; if (with_ecn) { const ect0 = try take(payload, at); const ect1 = try take(payload, at); const ce = try take(payload, at); f.ecn = .{ .ect0 = ect0.value, .ect1 = ect1.value, .ce = ce.value }; } return f; } /// §19.15's NEW_CONNECTION_ID body, shared with PATH_NEW_CONNECTION_ID. fn takeNewConnectionId(payload: []const u8, at: *usize) Error!NewConnectionId { const sequence = try take(payload, at); const retire = try take(payload, at); // §19.15: "MUST be less than or equal to the value in the Sequence Number // field." if (retire.value > sequence.value) return error.InvalidConnectionId; if (payload.len - at.* < 1) return error.Truncated; const id_len = payload[at.*]; at.* += 1; if (id_len < 1 or id_len > max_connection_id_len) return error.InvalidConnectionId; if (payload.len - at.* < @as(usize, id_len) + stateless_reset_token_len) { return error.Truncated; } const id = payload[at.*..][0..id_len]; at.* += id_len; const token = payload[at.*..][0..stateless_reset_token_len]; at.* += stateless_reset_token_len; return .{ .sequence = sequence.value, .retire_prior_to = retire.value, .id = id, .token = token }; } /// Reads a varint at `at.*` and advances past it. fn take(payload: []const u8, at: *usize) Error!varint.Parsed { const got = try varint.parse(payload[at.*..]); at.* += got.len; return got; } /// Reads a length-prefixed byte string and advances past it. fn takeBytes(payload: []const u8, at: *usize) Error![]const u8 { const len = try varint.parse(payload[at.*..]); at.* += len.len; if (payload.len - at.* < len.value) return error.Truncated; const n: usize = @intCast(len.value); const out = payload[at.*..][0..n]; at.* += n; return out; } /// Walks the frames of a decrypted packet payload. /// /// Coalesces runs of PADDING, for the reason given at the top of this file. pub const Iterator = struct { payload: []const u8, at: usize = 0, /// An iterator positioned at the first frame of `payload`, the whole /// decrypted payload of one packet, which the frames it yields point /// into and which has to outlive them. pub fn init(payload: []const u8) Iterator { return .{ .payload = payload }; } test init { const payload = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; var it: Iterator = .init(&payload); try std.testing.expectEqual(Kind.ping, (try it.next()).?); } /// The next frame, or null at the end of the payload. /// /// An error is §12.4's FRAME_ENCODING_ERROR for the whole packet, not /// for one frame: a frame's length is implied by its type, so nothing /// after a frame that fails to parse can be located, and the iterator is /// not to be advanced again. pub fn next(it: *Iterator) Error!?Frame { if (it.at >= it.payload.len) return null; const got = try parse(it.payload[it.at..]); it.at += got.len; if (got.frame != .padding) return got.frame; // A run of PADDING, counted rather than repeated. var count: u64 = 1; while (it.at < it.payload.len and it.payload[it.at] == 0x00) { count += 1; it.at += 1; } return .{ .padding = count }; } test next { // A CRYPTO frame carrying "hello", padded out with 20 zeros. const payload = [_]u8{ 0x06, 0x00, 0x05 } ++ "hello".* ++ @as([20]u8, @splat(0x00)); var it: Iterator = .init(&payload); while (try it.next()) |f| switch (f) { .crypto => |c| try std.testing.expectEqualStrings("hello", c.data), .padding => |n| try std.testing.expectEqual(@as(u64, 20), n), else => return error.TestUnexpectedResult, }; } }; const testing = std.testing; test "the frame type must use the shortest encoding, unlike every other varint" { // §12.4's sole exception to §16. PING as one octet is a PING; PING said // in two octets is a connection error. try testing.expectEqual(Kind.ping, (try parse(&.{0x01})).frame); try testing.expectError(error.NonMinimalType, parse(&.{ 0x40, 0x01 })); try testing.expectError(error.NonMinimalType, parse(&.{ 0x80, 0, 0, 0x01 })); // And PADDING, which is the one whose non-minimal spelling would // otherwise be indistinguishable from something else entirely. try testing.expectError(error.NonMinimalType, parse(&.{ 0x40, 0x00 })); } test "an unknown frame type is refused rather than skipped" { // The opposite of HTTP/2's rule, and for a structural reason: an HTTP/2 // frame carries its own length so a reader can skip one it does not know, // while a QUIC frame's length is implied by its type. try testing.expectError(error.UnknownType, parse(&.{0x22})); try testing.expectError(error.UnknownType, parse(&.{0x20})); try testing.expectError(error.UnknownType, parse(&.{ 0x7f, 0xff })); } test "the frames with no fields" { try testing.expectEqual(Frame{ .padding = 1 }, (try parse(&.{0x00})).frame); try testing.expectEqual(Kind.ping, (try parse(&.{0x01})).frame); try testing.expectEqual(Kind.handshake_done, (try parse(&.{0x1e})).frame); } test "a CRYPTO frame carries an offset and a length-prefixed slice" { const bytes = [_]u8{ 0x06, 0x00, 0x05 } ++ "hello".*; const got = try parse(&bytes); try testing.expectEqual(bytes.len, got.len); try testing.expectEqual(@as(u64, 0), got.frame.crypto.offset); try testing.expectEqualStrings("hello", got.frame.crypto.data); // And the slice points into what was handed in, rather than a copy. try testing.expectEqual(@intFromPtr(&bytes[3]), @intFromPtr(got.frame.crypto.data.ptr)); } test "a STREAM frame's three bits decide its shape" { // 0x08: no offset, no length, no fin. The data runs to the end. { const bytes = [_]u8{ 0x08, 0x04 } ++ "abcdef".*; const got = try parse(&bytes); const s = got.frame.stream; try testing.expectEqual(@as(u64, 4), s.stream); try testing.expectEqual(@as(u64, 0), s.offset); try testing.expectEqualStrings("abcdef", s.data); try testing.expect(!s.fin); try testing.expect(!s.had_length); try testing.expectEqual(bytes.len, got.len); } // 0x0f: offset, length and fin all present. { const bytes = [_]u8{ 0x0f, 0x04, 0x0a, 0x03 } ++ "xyz".* ++ [_]u8{0x01}; const got = try parse(&bytes); const s = got.frame.stream; try testing.expectEqual(@as(u64, 4), s.stream); try testing.expectEqual(@as(u64, 10), s.offset); try testing.expectEqualStrings("xyz", s.data); try testing.expect(s.fin); try testing.expect(s.had_length); // The trailing PING is not part of this frame, because the Length // said where the data ended. try testing.expectEqual(@as(usize, 7), got.len); } } test "RFC 9000 19.3.1: the ACK range arithmetic, and its underflow" { // Every value here is written as a bare octet, which is only correct // below 64: a varint's top two bits are its length, so 100 as `0x64` // would announce a two-octet encoding and everything after it would be // read at the wrong offset. The values are kept small for that reason // rather than by accident. // // Largest 50, first range 10 -> 40..50. Then a gap of 0 (meaning one // unacknowledged packet) and a range of 4: largest = 40 - 0 - 2 = 38, // smallest = 38 - 4 = 34. const bytes = [_]u8{ 0x02, 50, 0, 1, 10, 0, 4 }; const got = try parse(&bytes); const a = got.frame.ack; try testing.expectEqual(@as(u64, 50), a.largest); try testing.expectEqual(@as(u64, 1), a.range_count); try testing.expectEqual(bytes.len, got.len); const first = try a.firstRange(); try testing.expectEqual(Ack.Range{ .smallest = 40, .largest = 50 }, first); var it = a.ranges(); try testing.expectEqual(Ack.Range{ .smallest = 34, .largest = 38 }, (try it.next()).?); try testing.expectEqual(@as(?Ack.Range, null), try it.next()); // A first range larger than the largest acknowledged describes a negative // packet number, which §19.3.1 makes a connection error. const bad = [_]u8{ 0x02, 5, 0, 0, 9 }; try testing.expectError(error.InvalidAckRange, (try parse(&bad)).frame.ack.firstRange()); // And so does a gap that reaches below zero. The gap of 200 is written // as a two-octet varint: as a bare 200 the first octet would be 0xc8, // whose top two bits say "eight octets follow", and the frame would be // truncated rather than invalid. const bad_gap = [_]u8{ 0x02, 10, 0, 1, 0, 0x40, 0xc8, 0 }; var bad_it = (try parse(&bad_gap)).frame.ack.ranges(); try testing.expectError(error.InvalidAckRange, bad_it.next()); } test "an ACK frame of type 0x03 carries ECN counts" { const plain = [_]u8{ 0x02, 10, 0, 0, 0 }; try testing.expectEqual(@as(?Ack.Ecn, null), (try parse(&plain)).frame.ack.ecn); const with_ecn = [_]u8{ 0x03, 10, 0, 0, 0, 1, 2, 3 }; const got = try parse(&with_ecn); try testing.expectEqual(Ack.Ecn{ .ect0 = 1, .ect1 = 2, .ce = 3 }, got.frame.ack.ecn.?); try testing.expectEqual(with_ecn.len, got.len); } test "RFC 9000 19.15: a NEW_CONNECTION_ID's lengths are checked" { const good = [_]u8{ 0x18, 1, 0, 4, 0xaa, 0xbb, 0xcc, 0xdd } ++ @as([16]u8, @splat(0x11)); const got = try parse(&good); const n = got.frame.new_connection_id; try testing.expectEqual(@as(u64, 1), n.sequence); try testing.expectEqualSlices(u8, &.{ 0xaa, 0xbb, 0xcc, 0xdd }, n.id); try testing.expectEqual(good.len, got.len); // "Values less than 1 and greater than 20 are invalid." const zero_len = [_]u8{ 0x18, 1, 0, 0 } ++ @as([16]u8, @splat(0x11)); try testing.expectError(error.InvalidConnectionId, parse(&zero_len)); const too_long = [_]u8{ 0x18, 1, 0, 21 } ++ @as([37]u8, @splat(0x11)); try testing.expectError(error.InvalidConnectionId, parse(&too_long)); // "The value in the Retire Prior To field MUST be less than or equal to // the value in the Sequence Number field." const retire_too_high = [_]u8{ 0x18, 1, 2, 4, 0xaa, 0xbb, 0xcc, 0xdd } ++ @as([16]u8, @splat(0x11)); try testing.expectError(error.InvalidConnectionId, parse(&retire_too_high)); } test "RFC 9000 19.11: a stream limit above 2^60 is refused" { // 2^60 exactly is the largest legal value. var buf: [9]u8 = undefined; buf[0] = 0x12; _ = varint.write(buf[1..], max_streams_limit); try testing.expectEqual(max_streams_limit, (try parse(&buf)).frame.max_streams.maximum); _ = varint.write(buf[1..], max_streams_limit + 1); try testing.expectError(error.StreamLimitTooLarge, parse(&buf)); } test "CONNECTION_CLOSE has two variants and they are not interchangeable" { // 0x1c, the transport one, names the frame type that caused the close. const transport = [_]u8{ 0x1c, 0x07, 0x06, 0x03 } ++ "bad".*; const t = (try parse(&transport)).frame.connection_close; try testing.expectEqual(@as(u64, 0x07), t.error_code); try testing.expectEqual(@as(?u64, 0x06), t.frame_type); try testing.expectEqualStrings("bad", t.reason); try testing.expect(!t.application); // 0x1d, the application one, has no such field. const application = [_]u8{ 0x1d, 0x07, 0x03 } ++ "bye".*; const a = (try parse(&application)).frame.connection_close; try testing.expectEqual(@as(?u64, null), a.frame_type); try testing.expectEqualStrings("bye", a.reason); try testing.expect(a.application); } test "RFC 9000 12.4: which frames may appear at which encryption level" { const ping: Frame = .ping; const crypto: Frame = .{ .crypto = .{ .offset = 0, .data = "" } }; const stream: Frame = .{ .stream = .{ .stream = 0, .offset = 0, .data = "", .fin = false, .had_length = true, } }; const done: Frame = .handshake_done; // PADDING and PING go anywhere; CRYPTO everywhere but 0-RTT, which is // sent before there is anything to carry handshake messages about. inline for (comptime std.enums.values(tls.Level)) |level| { try testing.expect(ping.allowedIn(level)); } try testing.expect(crypto.allowedIn(.initial)); try testing.expect(crypto.allowedIn(.handshake)); try testing.expect(!crypto.allowedIn(.early_data)); // Streams do not exist during the handshake. try testing.expect(!stream.allowedIn(.initial)); try testing.expect(!stream.allowedIn(.handshake)); try testing.expect(stream.allowedIn(.early_data)); try testing.expect(stream.allowedIn(.application)); // HANDSHAKE_DONE is 1-RTT only. try testing.expect(done.allowedIn(.application)); try testing.expect(!done.allowedIn(.handshake)); // The two CONNECTION_CLOSEs differ, which is Table 3's `ih01`. const transport: Frame = .{ .connection_close = .{ .error_code = 0, .frame_type = 0, .reason = "", .application = false, } }; const application: Frame = .{ .connection_close = .{ .error_code = 0, .frame_type = null, .reason = "", .application = true, } }; try testing.expect(transport.allowedIn(.initial)); try testing.expect(!application.allowedIn(.initial)); try testing.expect(!application.allowedIn(.handshake)); try testing.expect(application.allowedIn(.application)); } test "RFC 9000 13.2.1: three frames do not elicit an acknowledgement" { // Acknowledging any of them would start an exchange with no end, because // the acknowledgement is itself a packet that would need one. try testing.expect(!(Frame{ .padding = 1 }).isAckEliciting()); try testing.expect(!(Frame{ .ack = undefined }).isAckEliciting()); try testing.expect(!(Frame{ .connection_close = .{ .error_code = 0, .frame_type = null, .reason = "", .application = true, } }).isAckEliciting()); try testing.expect((@as(Frame, .ping)).isAckEliciting()); try testing.expect((Frame{ .crypto = .{ .offset = 0, .data = "" } }).isAckEliciting()); } test "a frame that runs past the end of the packet is refused" { // §12.4: a frame "cannot span multiple packets", so one that claims to is // a connection error rather than a request for more octets. try testing.expectError(error.Truncated, parse(&.{ 0x06, 0x00, 0x05, 'h' })); try testing.expectError(error.Truncated, parse(&.{0x06})); try testing.expectError(error.Truncated, parse(&.{ 0x1a, 1, 2, 3 })); try testing.expectError(error.Truncated, parse(&.{ 0x18, 1, 0, 4, 0xaa })); } test "the iterator counts a run of PADDING rather than repeating it" { const payload = @as([100]u8, @splat(0x00)) ++ [_]u8{0x01} ++ @as([3]u8, @splat(0x00)); var it: Iterator = .init(&payload); try testing.expectEqual(Frame{ .padding = 100 }, (try it.next()).?); try testing.expectEqual(Kind.ping, (try it.next()).?); try testing.expectEqual(Frame{ .padding = 3 }, (try it.next()).?); try testing.expectEqual(@as(?Frame, null), try it.next()); } test "the iterator walks a packet's worth of mixed frames" { const payload = [_]u8{ 0x02, 10, 0, 0, 0 } ++ // ACK [_]u8{ 0x06, 0x00, 0x02 } ++ "hi".* ++ // CRYPTO [_]u8{0x01} ++ // PING @as([5]u8, @splat(0x00)); // PADDING var it: Iterator = .init(&payload); try testing.expectEqual(@as(u64, 10), (try it.next()).?.ack.largest); try testing.expectEqualStrings("hi", (try it.next()).?.crypto.data); try testing.expectEqual(Kind.ping, (try it.next()).?); try testing.expectEqual(Frame{ .padding = 5 }, (try it.next()).?); try testing.expectEqual(@as(?Frame, null), try it.next()); } pub const WriteError = error{ /// `out` is not long enough for this frame. NoSpace, }; /// Writes `f` into the front of `out` and returns how many octets it took. /// /// The inverse of `parse`: a frame `write` produced parses back to the same /// frame. The other way round is not quite exact, because `write` always /// uses the shortest encoding and a peer need not. §16 lets a peer spell a /// varint longer than it needs to, and such a frame comes back shorter than /// it went in; a STREAM frame that sets the OFF bit to carry an offset of /// zero comes back without the bit, and so with a different type. What /// §12.4 makes every peer spell minimally, and so what the round trip does /// pin, is the varint that encodes the frame type. /// /// `write` encodes what it is given and checks it against nothing in §19, /// so a frame built by hand may be one `parse` refuses -- a stream limit /// above 2^60, a connection ID of 21 octets. Every integer in it must fit a /// varint, below 2^62, which is asserted rather than returned as an error. /// A PADDING frame's count is how many zero octets to write, and is the one /// frame `parse` reads back differently: one octet at a time, leaving the /// count to `Iterator`. /// /// An ACK is written from the encoded ranges it was parsed with rather than /// from decoded ones. Constructing an ACK from a set of received packet /// numbers is a different job, and it belongs to whatever is tracking them. pub fn write(out: []u8, f: Frame) WriteError!usize { var at: usize = 0; switch (f) { .padding => |count| { const n: usize = @intCast(count); if (out.len < n) return error.NoSpace; @memset(out[0..n], 0); return n; }, .ping => return putType(out, 0x01), .ack => |a| { at = try putType(out, if (a.ecn == null) 0x02 else 0x03); try putAck(out, &at, a); }, .path_ack => |p| { at = try putType(out, if (p.ack.ecn == null) path_ack_type else path_ack_ecn_type); try put(out, &at, p.path); try putAck(out, &at, p.ack); }, .path_abandon => |p| { at = try putType(out, path_abandon_type); try put(out, &at, p.path); try put(out, &at, p.error_code); }, .path_status => |p| { at = try putType(out, switch (p.status) { .available => path_status_available_type, .backup => path_status_backup_type, }); try put(out, &at, p.path); try put(out, &at, p.sequence); }, .path_new_connection_id => |p| { at = try putType(out, path_new_connection_id_type); try put(out, &at, p.path); try putNewConnectionId(out, &at, p.id); }, .path_retire_connection_id => |p| { at = try putType(out, path_retire_connection_id_type); try put(out, &at, p.path); try put(out, &at, p.sequence); }, .max_path_id => |v| { at = try putType(out, max_path_id_type); try put(out, &at, v); }, .paths_blocked => |v| { at = try putType(out, paths_blocked_type); try put(out, &at, v); }, .path_cids_blocked => |p| { at = try putType(out, path_cids_blocked_type); try put(out, &at, p.path); try put(out, &at, p.next_sequence); }, .reset_stream => |r| { at = try putType(out, 0x04); try put(out, &at, r.stream); try put(out, &at, r.error_code); try put(out, &at, r.final_size); }, .stop_sending => |s| { at = try putType(out, 0x05); try put(out, &at, s.stream); try put(out, &at, s.error_code); }, .crypto => |c| { at = try putType(out, 0x06); try put(out, &at, c.offset); try putBytes(out, &at, c.data); }, .new_token => |t| { at = try putType(out, 0x07); try putBytes(out, &at, t); }, .stream => |s| { var t: u64 = 0x08; if (s.offset != 0) t |= 0x04; if (s.had_length) t |= 0x02; if (s.fin) t |= 0x01; at = try putType(out, t); try put(out, &at, s.stream); // §19.8: the Offset field is present when the OFF bit is set, and // an offset of zero is written by leaving the bit clear rather // than by writing a zero. if (s.offset != 0) try put(out, &at, s.offset); if (s.had_length) { try putBytes(out, &at, s.data); } else { if (out.len - at < s.data.len) return error.NoSpace; @memcpy(out[at..][0..s.data.len], s.data); at += s.data.len; } }, .max_data => |v| { at = try putType(out, 0x10); try put(out, &at, v); }, .max_stream_data => |m| { at = try putType(out, 0x11); try put(out, &at, m.stream); try put(out, &at, m.maximum); }, .max_streams => |m| { at = try putType(out, if (m.kind == .bidirectional) 0x12 else 0x13); try put(out, &at, m.maximum); }, .data_blocked => |v| { at = try putType(out, 0x14); try put(out, &at, v); }, .stream_data_blocked => |b| { at = try putType(out, 0x15); try put(out, &at, b.stream); try put(out, &at, b.maximum); }, .streams_blocked => |m| { at = try putType(out, if (m.kind == .bidirectional) 0x16 else 0x17); try put(out, &at, m.maximum); }, .new_connection_id => |n| { at = try putType(out, 0x18); try putNewConnectionId(out, &at, n); }, .retire_connection_id => |v| { at = try putType(out, 0x19); try put(out, &at, v); }, .path_challenge, .path_response => |data| { at = try putType(out, if (f == .path_challenge) 0x1a else 0x1b); if (out.len - at < 8) return error.NoSpace; @memcpy(out[at..][0..8], data); at += 8; }, .connection_close => |c| { at = try putType(out, if (c.application) 0x1d else 0x1c); try put(out, &at, c.error_code); if (c.frame_type) |t| try put(out, &at, t); try putBytes(out, &at, c.reason); }, .handshake_done => return putType(out, 0x1e), .immediate_ack => return putType(out, immediate_ack_type), .ack_frequency => |a| { at = try putType(out, ack_frequency_type); try put(out, &at, a.sequence); try put(out, &at, a.ack_eliciting_threshold); try put(out, &at, a.requested_max_ack_delay); try put(out, &at, a.reordering_threshold); }, .datagram => |d| { // RFC 9221 §4: the LEN bit, exactly as §19.8's works for a STREAM // frame. Leaving it clear saves the length's own octets and costs // the frame its ability to be followed by another. at = try putType(out, if (d.had_length) 0x31 else 0x30); if (d.had_length) { try putBytes(out, &at, d.data); } else { if (out.len - at < d.data.len) return error.NoSpace; @memcpy(out[at..][0..d.data.len], d.data); at += d.data.len; } }, .observed_address => |o| { at = try putType(out, switch (o.address.ip) { .v4 => observed_address_ipv4, .v6 => observed_address_ipv6, }); try putNumberedAddress(out, &at, o); }, .add_address => |a| { at = try putType(out, switch (a.address.ip) { .v4 => add_address_ipv4, .v6 => add_address_ipv6, }); try putNumberedAddress(out, &at, a); }, .reach_out => |r| { at = try putType(out, switch (r.address.ip) { .v4 => reach_out_ipv4, .v6 => reach_out_ipv6, }); try putNumberedAddress(out, &at, r); }, .remove_address => |sequence| { at = try putType(out, remove_address_type); try put(out, &at, sequence); }, } return at; } test write { // A STREAM frame with an offset, a length and FIN, into a packet buffer. var packet: [64]u8 = undefined; const len = try write(&packet, .{ .stream = .{ .stream = 4, .offset = 1000, .data = "last bytes", .fin = true, .had_length = true, } }); const back = (try parse(packet[0..len])).frame.stream; try std.testing.expectEqual(@as(u64, 1000), back.offset); try std.testing.expectEqualStrings("last bytes", back.data); try std.testing.expect(back.fin); // Too little room is an error, never a truncated frame. try std.testing.expectError(error.NoSpace, write(packet[0..4], .{ .max_data = 1 << 40 })); } /// §12.4: a frame type is always written in the fewest octets it fits in. fn putType(out: []u8, value: u64) WriteError!usize { if (out.len < varint.encodedLen(value)) return error.NoSpace; return varint.write(out, value).len; } fn put(out: []u8, at: *usize, value: u64) WriteError!void { if (out.len - at.* < varint.encodedLen(value)) return error.NoSpace; at.* += varint.write(out[at.*..], value).len; } /// The body `takeNumberedAddress` reads: a number, the address octets and a /// big-endian port. fn putNumberedAddress(out: []u8, at: *usize, n: NumberedAddress) WriteError!void { try put(out, at, n.sequence); const ip: []const u8 = switch (n.address.ip) { .v4 => |*v4| v4, .v6 => |*v6| v6, }; if (out.len - at.* < ip.len + 2) return error.NoSpace; @memcpy(out[at.*..][0..ip.len], ip); at.* += ip.len; std.mem.writeInt(u16, out[at.*..][0..2], n.address.port, .big); at.* += 2; } /// §19.3's ACK body, shared with PATH_ACK. fn putAck(out: []u8, at: *usize, a: Ack) WriteError!void { try put(out, at, a.largest); try put(out, at, a.delay); try put(out, at, a.range_count); try put(out, at, a.first_range); if (out.len - at.* < a.encoded_ranges.len) return error.NoSpace; @memcpy(out[at.*..][0..a.encoded_ranges.len], a.encoded_ranges); at.* += a.encoded_ranges.len; if (a.ecn) |e| { try put(out, at, e.ect0); try put(out, at, e.ect1); try put(out, at, e.ce); } } /// §19.15's NEW_CONNECTION_ID body, shared with PATH_NEW_CONNECTION_ID. fn putNewConnectionId(out: []u8, at: *usize, n: NewConnectionId) WriteError!void { try put(out, at, n.sequence); try put(out, at, n.retire_prior_to); if (out.len - at.* < 1 + n.id.len + stateless_reset_token_len) return error.NoSpace; out[at.*] = @intCast(n.id.len); at.* += 1; @memcpy(out[at.*..][0..n.id.len], n.id); at.* += n.id.len; @memcpy(out[at.*..][0..stateless_reset_token_len], n.token); at.* += stateless_reset_token_len; } fn putBytes(out: []u8, at: *usize, bytes: []const u8) WriteError!void { try put(out, at, bytes.len); if (out.len - at.* < bytes.len) return error.NoSpace; @memcpy(out[at.*..][0..bytes.len], bytes); at.* += bytes.len; } test "every frame survives being written and read back" { const token: [stateless_reset_token_len]u8 = @splat(0x5a); const path: [8]u8 = .{ 1, 2, 3, 4, 5, 6, 7, 8 }; const cases = [_]Frame{ .ping, .{ .reset_stream = .{ .stream = 4, .error_code = 9, .final_size = 1000 } }, .{ .stop_sending = .{ .stream = 8, .error_code = 2 } }, .{ .crypto = .{ .offset = 1234, .data = "handshake bytes" } }, .{ .new_token = "a token" }, .{ .stream = .{ .stream = 4, .offset = 0, .data = "abc", .fin = false, .had_length = true } }, .{ .stream = .{ .stream = 4, .offset = 99, .data = "abc", .fin = true, .had_length = true } }, .{ .datagram = .{ .data = "unreliable", .had_length = true } }, .{ .max_data = 1 << 20 }, .{ .max_stream_data = .{ .stream = 4, .maximum = 65536 } }, .{ .max_streams = .{ .kind = .bidirectional, .maximum = 100 } }, .{ .max_streams = .{ .kind = .unidirectional, .maximum = 3 } }, .{ .data_blocked = 42 }, .{ .stream_data_blocked = .{ .stream = 4, .maximum = 17 } }, .{ .streams_blocked = .{ .kind = .unidirectional, .maximum = 0 } }, .{ .new_connection_id = .{ .sequence = 2, .retire_prior_to = 1, .id = &.{ 0xaa, 0xbb, 0xcc }, .token = &token, } }, .{ .retire_connection_id = 1 }, .{ .path_challenge = &path }, .{ .path_response = &path }, .{ .connection_close = .{ .error_code = 7, .frame_type = 6, .reason = "no", .application = false, } }, .{ .connection_close = .{ .error_code = 1, .frame_type = null, .reason = "", .application = true, } }, .handshake_done, .{ .observed_address = .{ .sequence = 3, .address = .{ .ip = .{ .v4 = .{ 192, 0, 2, 1 } }, .port = 853 } } }, .{ .observed_address = .{ .sequence = 1 << 20, .address = .{ .ip = .{ .v6 = @splat(0x20) }, .port = 65535 } } }, .{ .add_address = .{ .sequence = 0, .address = .{ .ip = .{ .v4 = .{ 192, 0, 2, 9 } }, .port = 4433 } } }, .{ .add_address = .{ .sequence = 70000, .address = .{ .ip = .{ .v6 = @splat(0xfe) }, .port = 1 } } }, .{ .reach_out = .{ .sequence = 1, .address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 4 } }, .port = 51820 } } }, .{ .remove_address = 12 }, .immediate_ack, .{ .ack_frequency = .{ .sequence = 3, .ack_eliciting_threshold = 10, .requested_max_ack_delay = 25_000, .reordering_threshold = 1 } }, .{ .path_abandon = .{ .path = 3, .error_code = 0x3e76 } }, .{ .path_status = .{ .path = 1, .sequence = 7, .status = .available } }, .{ .path_status = .{ .path = 1, .sequence = 8, .status = .backup } }, .{ .path_new_connection_id = .{ .path = 2, .id = .{ .sequence = 1, .retire_prior_to = 0, .id = &.{ 0xaa, 0xbb, 0xcc, 0xdd }, .token = &token, } } }, .{ .path_retire_connection_id = .{ .path = 2, .sequence = 0 } }, .{ .max_path_id = 4 }, .{ .paths_blocked = 4 }, .{ .path_cids_blocked = .{ .path = 1, .next_sequence = 2 } }, }; for (cases) |want| { var buf: [128]u8 = undefined; const len = try write(&buf, want); const got = try parse(buf[0..len]); try testing.expectEqual(len, got.len); try testing.expectEqual(@as(Kind, want), @as(Kind, got.frame)); // Writing what was parsed gives the same octets back. var again: [128]u8 = undefined; const again_len = try write(&again, got.frame); try testing.expectEqualSlices(u8, buf[0..len], again[0..again_len]); } } test "PADDING is written as a run and read back as a count" { // The one frame where writing and parsing are not symmetric, because // there is nothing to be symmetric about: a PADDING frame is a single // zero octet with no fields, so `write` emits a run and `parse` sees the // first of them. Counting the run is the iterator's job. var buf: [16]u8 = undefined; const len = try write(&buf, .{ .padding = 7 }); try testing.expectEqual(@as(usize, 7), len); for (buf[0..len]) |b| try testing.expectEqual(@as(u8, 0), b); try testing.expectEqual(Frame{ .padding = 1 }, (try parse(buf[0..len])).frame); var it: Iterator = .init(buf[0..len]); try testing.expectEqual(Frame{ .padding = 7 }, (try it.next()).?); try testing.expectEqual(@as(?Frame, null), try it.next()); } test "a STREAM frame without a length runs to the end and comes back the same" { // The one frame whose extent is not self-describing, so a round trip has // to hand `parse` exactly the octets `write` produced and no more. const want: Frame = .{ .stream = .{ .stream = 4, .offset = 0, .data = "to the end", .fin = false, .had_length = false, } }; var buf: [64]u8 = undefined; const len = try write(&buf, want); const got = try parse(buf[0..len]); try testing.expect(!got.frame.stream.had_length); try testing.expectEqualStrings("to the end", got.frame.stream.data); try testing.expectEqual(len, got.len); } test "writing into a buffer that is too small fails rather than truncating" { var tiny: [2]u8 = undefined; try testing.expectError(error.NoSpace, write(&tiny, .{ .padding = 3 })); try testing.expectError( error.NoSpace, write(&tiny, .{ .crypto = .{ .offset = 0, .data = "hello" } }), ); try testing.expectError(error.NoSpace, write(tiny[0..0], .ping)); } test "draft-ietf-quic-address-discovery-01 4.1: OBSERVED_ADDRESS on the wire" { // The type in its four-octet varint form, the sequence number, the // address, and the port in network order -- the octets noq writes for // 192.0.2.1:853 with sequence number 3. var buf: [32]u8 = undefined; const len = try write(&buf, .{ .observed_address = .{ .sequence = 3, .address = .{ .ip = .{ .v4 = .{ 192, 0, 2, 1 } }, .port = 853 }, } }); try testing.expectEqualSlices(u8, &.{ 0x80, 0x9f, 0x81, 0xa6, 0x03, 192, 0, 2, 1, 0x03, 0x55 }, buf[0..len]); // The low bit of the type picks the family, and the port follows sixteen // octets of address instead of four. const v6 = [_]u8{ 0x80, 0x9f, 0x81, 0xa7, 0x00 } ++ @as([15]u8, @splat(0)) ++ [_]u8{ 1, 0x1f, 0x90 }; const got = try parse(&v6); try testing.expectEqual(v6.len, got.len); const o = got.frame.observed_address; try testing.expectEqual(@as(u16, 8080), o.address.port); try testing.expectEqual(@as(u8, 1), o.address.ip.v6[15]); // A frame that ends inside the address or the port is truncated. try testing.expectError(error.Truncated, parse(&.{ 0x80, 0x9f, 0x81, 0xa6, 0x03, 192, 0, 2 })); try testing.expectError(error.Truncated, parse(&.{ 0x80, 0x9f, 0x81, 0xa6, 0x03, 192, 0, 2, 1, 0x03 })); // Ack-eliciting, and only in the application data space. const f: Frame = .{ .observed_address = o }; try testing.expect(f.isAckEliciting()); try testing.expect(f.allowedIn(.application) and f.allowedIn(.early_data)); try testing.expect(!f.allowedIn(.initial) and !f.allowedIn(.handshake)); } test "draft-ietf-quic-multipath-21 4: the frames on the wire, at section 6's codepoints" { // PATH_ACK is an ACK with the path in front: path 1, largest 10, no // delay, no extra ranges, a first range of 2. const plain = [_]u8{ 0x3e, 0x01, 0x0a, 0x00, 0x00, 0x02 }; const got = try parse(&plain); try testing.expectEqual(plain.len, got.len); const pa = got.frame.path_ack; try testing.expectEqual(@as(u64, 1), pa.path); try testing.expectEqual(@as(u64, 10), pa.ack.largest); try testing.expectEqual(@as(?Ack.Ecn, null), pa.ack.ecn); var buf: [64]u8 = undefined; try testing.expectEqualSlices(u8, &plain, buf[0..try write(&buf, got.frame)]); // 0x3f carries §19.3.2's three ECN counts after the ranges. const ecn = [_]u8{ 0x3f, 0x02, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03 }; const with = (try parse(&ecn)).frame.path_ack; try testing.expectEqual(@as(u64, 2), with.path); try testing.expectEqual(Ack.Ecn{ .ect0 = 1, .ect1 = 0, .ce = 3 }, with.ack.ecn.?); // The rest are two-octet varint types: 0x3e75 is 0x7e 0x75. try testing.expectEqualSlices(u8, &.{ 0x7e, 0x75, 0x03, 0x00 }, buf[0..try write(&buf, .{ .path_abandon = .{ .path = 3, .error_code = 0 } })]); try testing.expectEqualSlices(u8, &.{ 0x7e, 0x76, 0x01, 0x05 }, buf[0..try write(&buf, .{ .path_status = .{ .path = 1, .sequence = 5, .status = .backup } })]); try testing.expectEqualSlices(u8, &.{ 0x7e, 0x77, 0x01, 0x06 }, buf[0..try write(&buf, .{ .path_status = .{ .path = 1, .sequence = 6, .status = .available } })]); try testing.expectEqualSlices(u8, &.{ 0x7e, 0x7a, 0x04 }, buf[0..try write(&buf, .{ .max_path_id = 4 })]); try testing.expectEqualSlices(u8, &.{ 0x7e, 0x7b, 0x04 }, buf[0..try write(&buf, .{ .paths_blocked = 4 })]); try testing.expectEqualSlices(u8, &.{ 0x7e, 0x7c, 0x01, 0x02 }, buf[0..try write(&buf, .{ .path_cids_blocked = .{ .path = 1, .next_sequence = 2 } })]); try testing.expectEqualSlices(u8, &.{ 0x7e, 0x79, 0x02, 0x00 }, buf[0..try write(&buf, .{ .path_retire_connection_id = .{ .path = 2, .sequence = 0 } })]); // §19.15's own check applies to PATH_NEW_CONNECTION_ID's inner half. try testing.expectError(error.InvalidConnectionId, parse(&[_]u8{ 0x7e, 0x78, 0x01, 0x01, 0x02, 0x04, 1, 2, 3, 4 } ++ @as([16]u8, @splat(0)))); // "All frames defined in this document MUST only be sent in 1-RTT // packets", and only PATH_ACK is exempt from being acknowledged. const abandon: Frame = .{ .path_abandon = .{ .path = 1, .error_code = 0 } }; try testing.expect(abandon.allowedIn(.application)); try testing.expect(!abandon.allowedIn(.early_data) and !abandon.allowedIn(.handshake)); try testing.expect(abandon.isAckEliciting()); try testing.expect(!got.frame.isAckEliciting()); try testing.expect(!got.frame.allowedIn(.early_data)); } test "n0 NAT traversal: the frames, byte for byte as noq writes them" { var buf: [64]u8 = undefined; // noq's round-trip test inputs, from its frame.rs. const add = [_]u8{ 0x80, 0x3d, 0x7f, 0x90, 0x2a, 0x7f, 0x00, 0x00, 0x01, 0x10, 0x92 }; var len = try write(&buf, .{ .add_address = .{ .sequence = 42, .address = .{ .ip = .{ .v4 = .{ 127, 0, 0, 1 } }, .port = 4242 } } }); try testing.expectEqualSlices(u8, &add, buf[0..len]); const got = try parse(&add); try testing.expectEqual(@as(u64, 42), got.frame.add_address.sequence); try testing.expectEqual(@as(usize, add.len), got.len); const reach = [_]u8{ 0x80, 0x3d, 0x7f, 0x93, 0x2a } ++ @as([15]u8, @splat(0)) ++ [_]u8{ 0x01, 0x10, 0x92 }; var loopback6: [16]u8 = @splat(0); loopback6[15] = 1; len = try write(&buf, .{ .reach_out = .{ .sequence = 42, .address = .{ .ip = .{ .v6 = loopback6 }, .port = 4242 } } }); try testing.expectEqualSlices(u8, &reach, buf[0..len]); const remove = [_]u8{ 0x80, 0x3d, 0x7f, 0x94, 0x0a }; len = try write(&buf, .{ .remove_address = 10 }); try testing.expectEqualSlices(u8, &remove, buf[0..len]); // A frame cut short anywhere is refused, not read past. for (0..add.len) |cut| try testing.expectError(error.Truncated, parse(add[0..cut])); } test "an IPv4-mapped IPv6 address is canonically the IPv4 address" { const mapped: Address = .{ .ip = .{ .v6 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 7 } }, .port = 51820 }; try testing.expect(mapped.canonical().eql(.{ .ip = .{ .v4 = .{ 192, 0, 2, 7 } }, .port = 51820 })); // ::192.0.2.7, the long-deprecated IPv4-compatible form, is left alone, // as Rust's to_canonical leaves it. const compatible: Address = .{ .ip = .{ .v6 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 2, 7 } }, .port = 1 }; try testing.expect(compatible.canonical().eql(compatible)); } test "draft-ietf-quic-ack-frequency-14: the two frames, byte for byte" { var buf: [32]u8 = undefined; // 0xaf needs a two-octet varint, 25000 microseconds a four-octet one. const f = [_]u8{ 0x40, 0xaf, 0x01, 0x0a, 0x80, 0x00, 0x61, 0xa8, 0x01 }; const len = try write(&buf, .{ .ack_frequency = .{ .sequence = 1, .ack_eliciting_threshold = 10, .requested_max_ack_delay = 25_000, .reordering_threshold = 1, } }); try testing.expectEqualSlices(u8, &f, buf[0..len]); const got = try parse(&f); try testing.expectEqual(@as(u64, 25_000), got.frame.ack_frequency.requested_max_ack_delay); for (0..f.len) |cut| try testing.expectError(error.Truncated, parse(f[0..cut])); try testing.expectEqual(@as(usize, 1), try write(&buf, .immediate_ack)); try testing.expectEqual(@as(u8, 0x1f), buf[0]); try testing.expectEqual(Kind.immediate_ack, (try parse(&.{0x1f})).frame); }