// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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; } test bitmapLen { // One bit an octet, rounded up to whole octets. try testing.expectEqual(@as(usize, 0), bitmapLen(0)); try testing.expectEqual(@as(usize, 1), bitmapLen(8)); try testing.expectEqual(@as(usize, 2), bitmapLen(9)); try testing.expectEqual(@as(usize, 512), bitmapLen(4096)); } /// Borrows both slices for the life of the reassembler. /// /// `present` must hold at least `bitmapLen(buffer.len)` octets, which is /// asserted, and is cleared here, so neither slice needs initializing /// first. The stream starts at offset zero. /// /// 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. Initialize 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 }; } test init { // The window and its bitmap are the caller's, sized together. var window: [64]u8 = undefined; var present: [bitmapLen(window.len)]u8 = undefined; const r: Reassembler = .init(&window, &present); try testing.expectEqual(@as(u64, 0), r.nextOffset()); try testing.expectEqualStrings("", r.readable()); } 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: `data`, which belongs at stream offset `offset`. /// /// The octets are copied, so `data` need not outlive the call. Whatever /// part of the fragment lies below `nextOffset` has already been handed /// out and is dropped without complaint, since a retransmission of it is /// ordinary. A fragment reaching past the window is refused whole with /// `WindowExceeded`, and one reaching past 2^62-1 with `OffsetTooLarge`; /// neither changes anything. /// /// 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; } test insert { var window: [16]u8 = undefined; var present: [bitmapLen(window.len)]u8 = undefined; var r: Reassembler = .init(&window, &present); // Arriving out of order: the later fragment waits for the earlier. try r.insert(5, "world"); try r.insert(0, "hello"); try testing.expectEqualStrings("helloworld", r.readable()); // Further ahead than the window reaches is refused. try testing.expectError(error.WindowExceeded, r.insert(12, "too far")); } /// The contiguous run starting at `nextOffset`, which may be empty. /// /// The slice points into the window, so it is valid only until the next /// `insert` or `consume`. Reading it does not use it up: the same octets /// come back until `consume` says they have been taken. 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]; } test readable { var window: [16]u8 = undefined; var present: [bitmapLen(window.len)]u8 = undefined; var r: Reassembler = .init(&window, &present); try r.insert(0, "abc"); try r.insert(4, "efg"); // Stops at the hole at offset 3, however much lies beyond it. try testing.expectEqualStrings("abc", r.readable()); } /// The stream offset the next unconsumed octet sits at. pub fn nextOffset(r: *const Reassembler) u64 { return r.base; } test nextOffset { var window: [16]u8 = undefined; var present: [bitmapLen(window.len)]u8 = undefined; var r: Reassembler = .init(&window, &present); try r.insert(0, "abcdef"); try testing.expectEqual(@as(u64, 0), r.nextOffset()); r.consume(4); try testing.expectEqual(@as(u64, 4), r.nextOffset()); } /// Discards the first `n` readable octets, sliding the window forward. /// /// `n` must not exceed `readable().len`, which is asserted. A slice /// `readable` returned before the call no longer describes the stream. /// /// 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; } test consume { var window: [8]u8 = undefined; var present: [bitmapLen(window.len)]u8 = undefined; var r: Reassembler = .init(&window, &present); try r.insert(0, "abcdefgh"); r.consume(5); try testing.expectEqualStrings("fgh", r.readable()); // The window has moved with it: offsets up to 13 now fit. try r.insert(8, "ijklm"); try testing.expectEqualStrings("fghijklm", r.readable()); } 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()); }