mirror of
https://github.com/apple/swift-nio
synced 2026-11-24 04:37:54 +00:00
## Motivation
`QUICBinaryEncodingStrategy.writeInteger(_:reservedCapacity:to:)`
switches on `max(reservedCapacity, bytesNeededForInteger(integer))` and
handles only 1, 2, 4 and 8, falling through to
`fatalError("Unreachable")` otherwise.
`bytesNeededForInteger` only ever returns those four values, but
`reservedCapacity` is guarded solely against being greater than 8. A
reserved capacity of 3, 5, 6 or 7 therefore reaches the unreachable case
and traps:
```swift
var buffer = ByteBuffer()
let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic
strategy.writeInteger(1, reservedCapacity: 3, to: &buffer)
// NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift:126: Fatal error: Unreachable
```
This is reachable without calling that method directly.
`requiredBytesHint` is a public `var Int` with no validation — the
initialiser takes the 1/2/4/8 `IntegerLength` enum, but the property can
be assigned any value afterwards, and
`writeLengthPrefixed(strategy:writeData:)` passes it straight through as
the reserved capacity:
```swift
var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one)
strategy.requiredBytesHint = 3 // public var, accepted silently
var buffer = ByteBuffer()
buffer.writeLengthPrefixed(strategy: strategy) { $0.writeString("hi") }
// Fatal error: Unreachable
```
## Modifications
Round the length up to the next valid QUIC integer length rather than
trapping, which is what the surrounding comment already intends by "use
more space than necessary in order to fill the reserved space":
```diff
- case 4:
+ case 3, 4:
- case 8:
+ case 5, 6, 7, 8:
```
RFC 9000 § 16 permits encoding a value in more bytes than it strictly
requires, and `writeLengthPrefixed` already shifts the payload when the
integer turns out longer than was reserved (`case reservedCapacity...`),
so writing 4 bytes for a reservation of 3 is handled by existing code.
## Result
No trap for any `reservedCapacity` in `0...8`, and the encoded value
still round-trips.
I checked every combination of `reservedCapacity` in `0...8` against the
boundary values `0, 1, 63, 64, 16383, 16384, 1073741823, 1073741824,
4611686018427387903`: all 81 encode, decode back to the original value,
and leave no bytes behind. On `main` the same check traps.
## Testing
The existing `testRoundtripWithReservedCapacity` iterates over `[0, 1,
2, 4, 8]` — skipping exactly the values that trap, which is presumably
why this went unnoticed. I've added a companion
`testRoundtripWithNonPowerOfTwoReservedCapacity` covering 3, 5, 6 and 7,
asserting both the encoded length and that the value round-trips. It
fails on `main` and passes with this change.
Full test suite: **2455 tests, 0 failures.**
## A note on the alternative
Rounding *down* to the largest valid length that still fits the
reservation would also avoid the trap and waste fewer bytes — for
`reservedCapacity: 3` that would write 2 bytes rather than 4. I went
with rounding up because the existing comment says to use more space
rather than less, and because it keeps the guarantee that at least the
reserved number of bytes is written. Happy to switch if you'd prefer the
other behaviour.
If you would rather fix this at the source by validating
`requiredBytesHint` or changing its type to `IntegerLength`, that would
be source-breaking, so I left it alone — but the public setter is what
makes this reachable in ordinary use.
---------
Co-authored-by: Raphael Hiesgen <r_hiesgen@apple.com>
184 lines
8.3 KiB
Swift
184 lines
8.3 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
extension ByteBuffer {
|
|
/// A ``NIOBinaryIntegerEncodingStrategy`` which encodes bytes as defined in RFC 9000 § 16
|
|
public struct QUICBinaryEncodingStrategy: NIOBinaryIntegerEncodingStrategy, Sendable {
|
|
/// All possible values for how many bytes a QUIC encoded integer can be
|
|
public enum IntegerLength: Int, Sendable {
|
|
case one = 1
|
|
case two = 2
|
|
case four = 4
|
|
case eight = 8
|
|
|
|
/// The QUIC integer length closest to `value`.
|
|
///
|
|
/// A QUIC variable-length integer occupies 1, 2, 4 or 8 bytes, so a value such as
|
|
/// 3 has no exact representation. Values below eight round up to the next valid
|
|
/// length; values above it saturate at ``IntegerLength/eight``.
|
|
@inlinable
|
|
public init(roundingFrom value: Int) {
|
|
switch value {
|
|
case ...1: self = .one
|
|
case 2: self = .two
|
|
case 3, 4: self = .four
|
|
default: self = .eight
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The number of bytes used to write integers with this strategy.
|
|
///
|
|
/// This is only relevant when calling ``ByteBuffer/writeLengthPrefixed(strategy:writeData:)``.
|
|
public var requiredBytesIntegerLength: IntegerLength
|
|
|
|
/// An estimate of the bytes required to write integers using this strategy
|
|
///
|
|
/// A QUIC variable-length integer is 1, 2, 4 or 8 bytes long, so only those values are
|
|
/// representable. Prefer ``requiredBytesIntegerLength``, which can only hold a valid
|
|
/// length. Assigning a value here rounds to the closest valid length.
|
|
@inlinable
|
|
public var requiredBytesHint: Int {
|
|
get {
|
|
self.requiredBytesIntegerLength.rawValue
|
|
}
|
|
@available(
|
|
*,
|
|
deprecated,
|
|
message:
|
|
"Set requiredBytesIntegerLength instead: a QUIC integer is 1, 2, 4 or 8 bytes long, so other values cannot be represented exactly."
|
|
)
|
|
set {
|
|
self.requiredBytesIntegerLength = IntegerLength(roundingFrom: newValue)
|
|
}
|
|
}
|
|
|
|
/// Note: Prefer to use the APIs directly on ByteBuffer such as ``ByteBuffer/writeEncodedInteger(_:strategy:)`` and pass `.quic` rather than directly initialising an instance of this strategy
|
|
/// - Parameter requiredBytesHint: An estimate of the bytes required to write integers using this strategy. This parameter is only relevant if calling ``ByteBuffer/writeLengthPrefixed(strategy:writeData:)``
|
|
@inlinable
|
|
public init(requiredBytesHint: IntegerLength) {
|
|
self.requiredBytesIntegerLength = requiredBytesHint
|
|
}
|
|
|
|
@inlinable
|
|
public func readInteger<IntegerType: FixedWidthInteger>(
|
|
as: IntegerType.Type,
|
|
from buffer: inout ByteBuffer
|
|
) -> IntegerType? {
|
|
guard let firstByte = buffer.getInteger(at: buffer.readerIndex, as: UInt8.self) else {
|
|
return nil
|
|
}
|
|
|
|
// Look at the first two bits to work out the length, then read that, mask off the top two bits, and
|
|
// extend to integer.
|
|
switch firstByte & 0xC0 {
|
|
case 0x00:
|
|
// Easy case.
|
|
buffer.moveReaderIndex(forwardBy: 1)
|
|
return IntegerType(firstByte & ~0xC0)
|
|
case 0x40:
|
|
// Length is two bytes long, read the next one.
|
|
return buffer.readInteger(as: UInt16.self).map { IntegerType($0 & ~(0xC0 << 8)) }
|
|
case 0x80:
|
|
// Length is 4 bytes long.
|
|
return buffer.readInteger(as: UInt32.self).map { IntegerType($0 & ~(0xC0 << 24)) }
|
|
case 0xC0:
|
|
// Length is 8 bytes long.
|
|
return buffer.readInteger(as: UInt64.self).map { IntegerType($0 & ~(0xC0 << 56)) }
|
|
default:
|
|
fatalError("Unreachable")
|
|
}
|
|
}
|
|
|
|
/// Calculates the minimum number of bytes needed to encode an integer using this strategy
|
|
/// - Parameter integer: The integer to be encoded
|
|
/// - Returns: The number of bytes needed to encode it
|
|
@inlinable
|
|
public static func bytesNeededForInteger<IntegerType: FixedWidthInteger>(_ integer: IntegerType) -> Int {
|
|
// We must cast the integer to UInt64 here
|
|
// Otherwise, an integer can fall through to the default case
|
|
// E.g., if someone calls this function with UInt8.max (which is 255), they would not hit the first case (0..<63)
|
|
// The second case cannot be represented at all in UInt8, because 16383 is too big
|
|
// Swift will end up creating the 16383 literal as 0, and thus we will fall all the way through to the default
|
|
switch UInt64(integer) {
|
|
case 0...63:
|
|
return 1
|
|
case 0...16383:
|
|
return 2
|
|
case 0...1_073_741_823:
|
|
return 4
|
|
case 0...4_611_686_018_427_387_903:
|
|
return 8
|
|
default:
|
|
fatalError("QUIC variable-length integer outside of valid range")
|
|
}
|
|
}
|
|
|
|
@inlinable
|
|
public func writeInteger<IntegerType: FixedWidthInteger>(
|
|
_ integer: IntegerType,
|
|
to buffer: inout ByteBuffer
|
|
) -> Int {
|
|
self.writeInteger(integer, reservedCapacity: 0, to: &buffer)
|
|
}
|
|
|
|
@inlinable
|
|
public func writeInteger<IntegerType: FixedWidthInteger>(
|
|
_ integer: IntegerType,
|
|
reservedCapacity: Int,
|
|
to buffer: inout ByteBuffer
|
|
) -> Int {
|
|
if reservedCapacity > 8 {
|
|
fatalError("Reserved space for QUIC encoded integer must be at most 8 bytes")
|
|
}
|
|
// Use more space than necessary in order to fill the reserved space
|
|
// This will avoid a memmove
|
|
// If the needed space is more than the reserved, we can't avoid the move
|
|
switch IntegerLength(roundingFrom: max(reservedCapacity, Self.bytesNeededForInteger(integer))) {
|
|
case .one:
|
|
// Easy, store the value. The top two bits are 0 so we don't need to do any masking.
|
|
return buffer.writeInteger(UInt8(truncatingIfNeeded: integer))
|
|
case .two:
|
|
// Set the top two bit mask, then write the value.
|
|
let value = UInt16(truncatingIfNeeded: integer) | (0x40 << 8)
|
|
return buffer.writeInteger(value)
|
|
case .four:
|
|
// Set the top two bit mask, then write the value.
|
|
let value = UInt32(truncatingIfNeeded: integer) | (0x80 << 24)
|
|
return buffer.writeInteger(value)
|
|
case .eight:
|
|
// Set the top two bit mask, then write the value.
|
|
let value = UInt64(truncatingIfNeeded: integer) | (0xC0 << 56)
|
|
return buffer.writeInteger(value)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension NIOBinaryIntegerEncodingStrategy where Self == ByteBuffer.QUICBinaryEncodingStrategy {
|
|
/// Encodes bytes as defined in RFC 9000 § 16
|
|
/// - Parameter requiredBytesHint: An estimate of the bytes required to write integers using this strategy. This parameter is only relevant if calling ``ByteBuffer/writeLengthPrefixed(strategy:writeData:)``
|
|
/// - Returns: An instance of ``ByteBuffer/QUICBinaryEncodingStrategy``
|
|
@inlinable
|
|
public static func quic(
|
|
requiredBytesHint: ByteBuffer.QUICBinaryEncodingStrategy.IntegerLength
|
|
) -> ByteBuffer.QUICBinaryEncodingStrategy {
|
|
ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: requiredBytesHint)
|
|
}
|
|
|
|
/// Encodes bytes as defined in RFC 9000 § 16
|
|
@inlinable
|
|
public static var quic: ByteBuffer.QUICBinaryEncodingStrategy { .quic(requiredBytesHint: .four) }
|
|
}
|