Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Putting an offset-addressed byte stream back in order.//!//! CRYPTO frames (§19.6) and STREAM frames (§19.8) both carry an offset and a//! run of bytes, and neither carries any promise about the order they arrive//! in or whether they overlap. What the consumer needs is the opposite: a//! contiguous run starting where the last one ended, because TLS handshake//! messages are a stream and reading one out of order is reading a different//! message.//!//! This is the piece that feeds `tls.Handshake.provide`, and its contract is//! the one that makes the seam usable: bytes go in addressed by offset and//! come out in order, exactly once each.//!//! ## Everything here is a bound on an attacker//!//! A CRYPTO frame arrives inside an Initial packet, which anyone who can//! reach the port can send, and §19.6 gives the stream no length and no end.//! So all three of the obvious implementations are wrong://!//! * Growing a buffer to fit whatever offset arrives lets a peer ask for//! 2^62 octets with one small frame.//! * Keeping a list of fragments lets a peer send a great many tiny ones.//! * Trusting that fragments do not overlap lets a peer rewrite bytes that//! have already been handed to TLS.//!//! What is here instead is a fixed window, supplied by the caller, with a//! bitmap of which octets within it have arrived. The window is the largest//! reordering that will be tolerated, data beyond it is refused with//! `WindowExceeded` — which §19.6 names CRYPTO_BUFFER_EXCEEDED — and data//! below `consumed` is discarded because it has already been delivered and//! cannot be delivered differently.
const std = @import("std");const assert = std.debug.assert;
const varint = @import("varint.zig");
pub const Error = error{ /// Data past the end of the window: an offset further ahead than this /// reassembler is willing to remember. /// /// §19.6 calls the CRYPTO-stream version of this CRYPTO_BUFFER_EXCEEDED /// and makes it a connection error, which is the right answer — a peer /// that sends handshake data far beyond what has been consumed is not /// suffering from reordering. WindowExceeded, /// §19.6 and §19.8: "the sum of the offset and data length -- cannot /// exceed 2^62-1". OffsetTooLarge,};
/// Reassembles one stream.////// `buffer`'s length is the window: the furthest ahead of what has been/// consumed that out-of-order data will be kept. For a CRYPTO stream a few/// tens of kilobytes is generous — a TLS ClientHello with a large key share/// is a few thousand octets — and the number is the caller's because how much/// memory a connection costs is the server's policy.pub const Reassembler = struct { buffer: []u8, /// One bit per octet of `buffer`, saying whether it has arrived. present: []u8, /// The stream offset that `buffer[0]` corresponds to: everything below /// this has been handed out. base: u64 = 0, /// The highest offset any fragment has reached, so that `readable` knows /// where to stop looking. high_water: u64 = 0,
/// How many octets of `present` a window of `window_len` octets needs. pub fn bitmapLen(window_len: usize) usize { return (window_len + 7) / 8; }
/// Borrows both slices for the life of the reassembler. /// /// Worth saying plainly because of the shape it rules out: a struct that /// owns a window, a bitmap *and* a `Reassembler` over them cannot be /// returned by value, since the copy's reassembler would still point at /// the original's buffers. Initialise such a thing in place. The compiler /// will not say a word, and what goes wrong afterwards is that `readable` /// describes octets nobody wrote. pub fn init(buffer: []u8, present: []u8) Reassembler { assert(present.len >= bitmapLen(buffer.len)); @memset(present, 0); return .{ .buffer = buffer, .present = present }; }
fn isSet(r: *const Reassembler, i: usize) bool { return r.present[i / 8] & (@as(u8, 1) << @intCast(i % 8)) != 0; }
fn set(r: *Reassembler, i: usize) void { r.present[i / 8] |= @as(u8, 1) << @intCast(i % 8); }
/// Adds a fragment. /// /// Overlapping data is *ignored* rather than written again. A peer is not /// supposed to send a fragment that disagrees with one already received, /// but nothing stops it, and the first arrival is the one that may already /// have been handed to TLS — so it is the one that has to win. Writing the /// second would let a peer change bytes it has already been credited for. pub fn insert(r: *Reassembler, offset: u64, data: []const u8) Error!void { if (offset > varint.max or data.len > varint.max - offset) return error.OffsetTooLarge; if (data.len == 0) return;
const end = offset + data.len; if (end <= r.base) return; // entirely consumed already if (end > r.base + r.buffer.len) return error.WindowExceeded;
// The part of the fragment that is not already behind us. const from = if (offset < r.base) r.base - offset else 0; const start = offset + from - r.base;
for (data[@intCast(from)..], 0..) |b, i| { const at: usize = @intCast(start + i); if (r.isSet(at)) continue; // first arrival wins r.buffer[at] = b; r.set(at); } if (end > r.high_water) r.high_water = end; }
/// The contiguous run starting at the current offset, which may be empty. pub fn readable(r: *const Reassembler) []const u8 { const limit: usize = @intCast(@min(r.high_water - r.base, r.buffer.len)); var n: usize = 0; while (n < limit and r.isSet(n)) n += 1; return r.buffer[0..n]; }
/// The stream offset the next unconsumed octet sits at. pub fn nextOffset(r: *const Reassembler) u64 { return r.base; }
/// Discards the first `n` readable octets, sliding the window forward. /// /// Called once the bytes have been handed to whatever consumes them — /// which for a CRYPTO stream is `tls.Handshake.provide`, and which must /// not be given the same octets twice. pub fn consume(r: *Reassembler, n: usize) void { assert(n <= r.readable().len); if (n == 0) return;
// Slide the window down. A ring buffer would avoid the copy; a copy // is what is here because the window is small, the move happens once // per delivery rather than per octet received, and a ring makes every // other function in this file harder to read than the rule it // implements. const keep = r.buffer.len - n; std.mem.copyForwards(u8, r.buffer[0..keep], r.buffer[n..]); for (0..keep) |i| { if (r.isSet(i + n)) r.set(i) else r.clear(i); } for (keep..r.buffer.len) |i| r.clear(i); r.base += n; }
fn clear(r: *Reassembler, i: usize) void { r.present[i / 8] &= ~(@as(u8, 1) << @intCast(i % 8)); }};
const testing = std.testing;
fn make(buffer: []u8, present: []u8) Reassembler { return .init(buffer, present);}
test "fragments in order come straight back out" { var buf: [64]u8 = undefined; var bits: [8]u8 = undefined; var r = make(&buf, &bits);
try r.insert(0, "hello "); try testing.expectEqualStrings("hello ", r.readable()); try r.insert(6, "world"); try testing.expectEqualStrings("hello world", r.readable());}
test "fragments out of order wait for the gap to be filled" { var buf: [64]u8 = undefined; var bits: [8]u8 = undefined; var r = make(&buf, &bits);
// The middle is missing, so nothing is readable even though octets have // arrived -- which is the whole point: a TLS message read with a hole in // it is a different message. try r.insert(6, "world"); try testing.expectEqualStrings("", r.readable());
try r.insert(0, "hello "); try testing.expectEqualStrings("hello world", r.readable());}
test "consuming slides the window and is not repeated" { var buf: [16]u8 = undefined; var bits: [2]u8 = undefined; var r = make(&buf, &bits);
try r.insert(0, "abcdef"); try testing.expectEqualStrings("abcdef", r.readable()); try testing.expectEqual(@as(u64, 0), r.nextOffset());
r.consume(3); try testing.expectEqualStrings("def", r.readable()); try testing.expectEqual(@as(u64, 3), r.nextOffset());
r.consume(3); try testing.expectEqualStrings("", r.readable()); try testing.expectEqual(@as(u64, 6), r.nextOffset());
// And the window really did move: an offset that was once out of range // now fits. try r.insert(16, "beyond"); try testing.expectEqualStrings("", r.readable()); try r.insert(6, "0123456789"); try testing.expectEqualStrings("0123456789beyond", r.readable());}
test "the first arrival of an octet is the one that wins" { // A peer must not send a fragment disagreeing with one already sent, and // nothing stops it. The first is the one that may already have been given // to TLS, so it is the one that has to stand. var buf: [32]u8 = undefined; var bits: [4]u8 = undefined; var r = make(&buf, &bits);
try r.insert(0, "original"); try r.insert(0, "OVERWRIT"); try testing.expectEqualStrings("original", r.readable());
// Partially overlapping, where only the new octets are taken. try r.insert(4, "XXXXnew"); try testing.expectEqualStrings("originalnew", r.readable());}
test "data already consumed is discarded rather than reinserted" { var buf: [16]u8 = undefined; var bits: [2]u8 = undefined; var r = make(&buf, &bits);
try r.insert(0, "abcdef"); r.consume(6); // A retransmission of what has gone. Accepting it would deliver the same // octets twice. try r.insert(0, "abcdef"); try testing.expectEqualStrings("", r.readable()); try testing.expectEqual(@as(u64, 6), r.nextOffset());
// And one that straddles the boundary keeps only the new part. try r.insert(4, "efghij"); try testing.expectEqualStrings("ghij", r.readable());}
test "data beyond the window is refused rather than remembered" { // §19.6's CRYPTO_BUFFER_EXCEEDED. Without this a peer chooses how much // memory the connection costs, with one small frame at a large offset. var buf: [16]u8 = undefined; var bits: [2]u8 = undefined; var r = make(&buf, &bits);
try r.insert(10, "abcdef"); // ends at 16, exactly the window try testing.expectError(error.WindowExceeded, r.insert(11, "abcdef")); try testing.expectError(error.WindowExceeded, r.insert(1 << 40, "x"));}
test "an offset past what a varint can hold is refused" { var buf: [16]u8 = undefined; var bits: [2]u8 = undefined; var r = make(&buf, &bits); try testing.expectError(error.OffsetTooLarge, r.insert(varint.max, "xx")); try testing.expectError(error.OffsetTooLarge, r.insert(varint.max - 1, "xx"));}
test "an empty fragment is nothing at all" { var buf: [16]u8 = undefined; var bits: [2]u8 = undefined; var r = make(&buf, &bits); try r.insert(0, ""); try r.insert(1 << 40, ""); // beyond the window, but there is nothing in it try testing.expectEqualStrings("", r.readable());}
test "a stream delivered one octet at a time, backwards, still comes out right" { var buf: [64]u8 = undefined; var bits: [8]u8 = undefined; var r = make(&buf, &bits);
const message = "the quick brown fox jumps over the lazy dog"; var i: usize = message.len; while (i > 0) { i -= 1; try r.insert(i, message[i..][0..1]); } try testing.expectEqualStrings(message, r.readable());}