Motivation:
To increase concurrency safety the NIOPHACK module should compile
without warning under strict concurrency checking.
Modifications:
- Add explicit Sendable annotations
Result:
No concurrency warnings.
Motivation:
Standardised formatting makes the project cleaner to look at and work
on.
Modifications:
Setup swift-format with the same settings as Swift-NIO
Result:
Common formatting throughout
Motivation:
Want to move away from legacy CI.
Modifications:
Add configuration and update code to use GitHub actions.
Result:
GitHub Actions can be used for basic CI.
Motivation:
To address warnings revealed with
`.enableExperimentalFeature("StrictConcurrency=complete"),` in Swift 5.8
Modifications:
* Numerous protections of state in tests
* Make the multiplexer instances explicitly loop bound
* Update channel initializers to be marked as Sendable
* Mark error backing storage types as unchecked sendable
Result:
Better thread safety
Motivation:
Tweaking the formatting of the DocC comments enables syntax highlighting
for parameter names in Xcode
Modifications:
Whitespace changes, capitalisation changes and added a parameter
description for `indexing` in HOACKHeaders `replaceOrAdd`, `add`.
Result:
More readable DocC comments
In scenarios, in which we want to send lots of small HTTP/2 requests, we want to reuse a single HPACKHeaders object as often as we can. To support this we should have a removeAll(keepingCapacity:) method.
Motivation:
When remote peers set the value of HEADER_TABLE_SIZE to any non-default
value, or when we update it, we should respect that value when we're
emitting headers.
Unfortunately, right now we don't. In particular, we manage to update
the wrong setting: when the peer sets HEADER_TABLE_SIZE we bound the
maximum size of the dynamic table _they_ can use, not the maximum size
_we_ can use. That's incorrect by the spec, which says:
> This setting allows the sender to inform the remote endpoint of the
> maximum size of the compression table used to decode field blocks,
> in units of octets. The encoder can select any size equal to or less
> than this value by using signaling specific to the compression
> format inside a field block (see [COMPRESSION]).
If a peer sent us SETTINGS_HEADER_TABLE_SIZE with a value of 0, we'd
restrict _them_ to only using a maximum table size of 0, instead of us.
This is wrong.
Additionally, when we updated the encoder we used the wrong method, so
the encoder would never send dynamic table size changes. This was also
incorrect!
In general this managed to get missed because, as RFC 9113 notes:
> Implementers are advised that reducing the value of
> SETTINGS_HEADER_TABLE_SIZE is not widely interoperable. Use of the
> connection preface to reduce the value below the initial value of
> 4,096 is somewhat better supported, but this might fail with some
> implementations.
It turns out one of those implementations this might fail with is us!
The result, however, is that very few implementations actually try to
reduce the value of the header table size, so we rarely ran into this
issue. nginx does actually try this in some cases, however, which is how
we found this problem.
Modifications:
- Correctly invert the application of the value of
SETTINGS_HEADER_TABLE_SIZE
- Correctly use `setDynamicTableSize` on HPACKEncoder instead of just
setting the field manually.
- Deprecate the invalid method of setting the field on HPACKEncoder.
- Add some HTTP/2-level tests that ensure we correctly handle these
changes.
Result:
Vastly better handling of peers reducing the value of
SETTINGS_HEADER_TABLE_SIZE.
Motivation:
We don't always require an array of header values to be extracted.
Sometimes we just need to be able to iterate through them. For 'regular'
header values we incur an allocation for the array, for values in their
canonical form we incure at least two allocations. We can do better than
this by providing a header value sequence.
Modifications:
- Add new API to `HPACKHeaders` for getting a sequence of header values
which can optionally be in their canonical form.
- Update the API of the two existing subscripts to use this new API. For
`subscript(canonicalForm:)` we save an allocation by not going via
`subscript(name:)`.
Result:
- Fewer allocations in `subscript(canonicalForm:)`
- Header values can be iterated without allocating
Motivation:
NIOSendable was deprecated in https://github.com/apple/swift-nio/pull/2291
as the earliest supported Swift version in NIO land is now 5.5.
Modifications:
- s/NIOSendable/Sendable
Result:
Avoids deprecation warnings when the above patch is released.
Motivation:
Header normalisation is expensive when the input headers contain a large
number of connection header values.
Modifications:
- When the headers to normalise contain more than 32 connection header
values use a set to provide constant time lookup, rather than linear.
Result:
Better perf for HTTPHeader normalisation with large connection header
value lists.
Motivation:
HPACKHeaders is equatable, and it rarely makes sense to have a type that
is equatable but not hashable. The definition of equatability is pretty
limited here (see #342) but we can define a definition of hashability
consistent with it.
Modifications:
- Make HPACKHeaders hashable.
Result:
People can store HPACKHeaders in Sets
Co-authored-by: David Nadoba <dnadoba@gmail.com>
Motivation
Checked math is great when you aren't sure what the constraints are, but
in some places we happen to know that all the arithmetic operations
occur in a defined domain and range. In those cases, we can improve the
codegen by adopting unchecked math.
Modifications
Widely adopt unchecked math in encodeInteger.
Result
Better codegen for encodeInteger.
Motivation
Unnecessary ARC traffic hurts performance
Modifications
Restructure the decodeHeaders function to avoid taking a copy of the
bytebuffer but instead to reset the reader index on error.
Result
One less retain/release on header block decode.
Motivation:
A new 'UnrepresentableInteger' error was added in GHSA-w3f6-pc54-gfw7.
This was added as internal so that the advisory could be published as a
patch release rather than a minor.
This error should be public so that callers may hold an instance of it.
Modifications:
- Make UnrepresentableInteger public
Result:
UnrepresentableInteger is part of the public API.
* Refactor HPACK integer decoding
Motivation:
The HPACK integer decoding used a number of unchecked operations which
can trap on some inputs. Since it is network reachable code, it should
throw errors if the operations overflow.
Modifications:
- Add a failure case to the fuzz testing
- Refactor the integer decoding to check for overflow on the arithmetic
- This throws a new 'HPACKErrors.UnrepresentableInteger' error on
overflow
- Add a missing bounds check
- Remove an unnecessary and incorrect path
- Remove the default argument from the function driving the decoding,
the default was not valid and would cause an assertion to fail if used
- Return the decoded value as an `Int` rather than a `UInt`
- More tests
Result:
Integer decoding is safer.
* Use unchecked shifting
* Use truncatingIfNeeded
* make error internal
Motivation:
The canonicalForm subscript was written for clarity, but it didn't do a
good job of avoiding performance costs. Unfortunately, this function can
be a bit costly, for two reasons. Firstly, it used a bunch of eager
collection operations, such that it would allocate intermediate arrays.
Secondly, it computed on the String, rather than the UTF8View backing
that string, in order to perform those collection operations. The result
was that it spent a bit too much time messing about with the headers
than it needed to.
Modifications:
- Define a lazy UTF8 view splitting sequence and use it.
- Change to compute on the UTF8View.
Result:
Better performance in the canonicalForm subscript.
Motivation:
When getting the canonical form of headers we check whether the header
name is 'set-cookie' to avoid splitting values which are not safe to
split.
This check is done against a `lowercased()` version of the header name.
However, we don't need to produce a new `String` here as we already have
a case insensitive string comparision function.
Modifications:
- Add a test to verify that getting the canonical form of "set-cookie"
does not split any header values
- Switch to `isEqualCaseInsensitiveASCIIBytes`
Result:
More tests, cheaper comparision.
Motivation:
The return value from `HPACKHeaders.subscript(canonicalForm:)` is
inconsistent with respect to returning empty strings.
If a value for a header field is an empty string then the canonical form
will not return that empty string. However, if a value is a string
containing only whitespace then an empty string will be returned.
Modifications:
- Filter out empty substrings after trimming whitespace
- Add a test
Result:
- `HPACKHeaders.subscript(canonicalForm:)` does not produce empty strings
Motivation:
The OWS rule from the HTTP semantics draft only considers 'SP' and
'HTAB' to be whitespace. We also (unnecessarily) consider CR and LF to
be whitespace.
Modifications:
- Remove CR and LF from the characters we consider to be whitespace
- Update tests
Result:
We no longer consider CR or LF to be whitespace when trimming
whitespace when producing the canonical form of header values.
Motivation:
When getting the canonical form of header values any ascii whitespace
is stripped from the values. The current implementation does this by
doing equality checks on Character and dropping them from a Substring.
Modifications:
- Update the Substring._trimWhitespace() function to trim on a UTF8 view
- Add test
Result:
Retrieving the canonical form of header values is cheaper, significantly
so when values contain a lot of leading or trailing whitespace.
Motivation:
With NIO 2.32.0 we broke the core NIO module up into modules that split
apart the POSIX layer and the core abstractions. As a result, this
package no longer needs to express a hard dependency on the POSIX layer.
Modifications:
- Rewrote imports of NIO to NIOCore.
- Added NIOEmbedded imports where necessary in tests.
- Note that the main modules still depend on NIO, which is necessary
for backwards-compatibility reasons. This dependency is unused.
Result:
No need to use NIOPosix.
Motivation:
HPACKHeaders is a trivial data structure (a wrapper around Array) that
is present in the public API of all NIO HTTP/2 programs. This makes it a
tempting target for adding inlinable calls, primarily as a way to drive
down ARC. The fact that strings frequently travel across the API
boundary means that otherwise innocuous use-cases can trigger unexpected
ARC traffic.
Making as much of the implementation inlinable as possible reduces a lot
of this overhead and opens up the possibility for better performance in
a number of parts of the code, including in the core HTTP/2 protocol
engine, which operates extensively on this data type.
Modifications:
- Make basically everything inlinable.
Result:
Our benchmarks are about 0.7% faster.
Motivation:
When analysing remaining performance cliffs, we observed that
HeaderTableStorage.closestMatch was the source of a surprising amount of
ARC traffic. Further diagnosis revealed that we were ARCing string
storage as we iterated the table. Given that the table is constructed of
String/String pairs, the effect would be that if we scanned a table we
would emit two retains and two releases for each entry. Whenever we
encode a HTTP/2 header that we think could be indexed, we will scan the
static and possibly the dynamic tables to find a header that matches.
This ends up being a pretty nasty performance cost, as swift_retain and
swift_release are particularly complex on Strings, and often have
trouble with cache coherency and cache misses.
This got root-caused to https://bugs.swift.org/browse/SR-13931.
Modifications:
- Work around SR-13931 by avoiding using the iterator.
- While we're here, remove generics as well, as we aren't using them.
Results:
4% perf gain in 10k requests 100 concurrent streams benchmark and
10k requests 1 concurrent streams benchmark.
Motivation:
In #263 we took advantage of the addition of the
unsafeUninitializedCapacity:initializingWith constructor on String,
added in the latest Swift SDKs and Swift versions.
Unfortunately, there were a few Xcode releases that shipped with Swift
5.3 but _without_ the macOS 11 SDK. These releases therefore had a 5.3
compiler, but no access to the macOS 11 SDK where the constructor is
defined.
This means this change regressed builds on those platforms.
Modifications:
Removed access to the fast-path initializer on Apple platforms in 5.3.
The initializer is present and will continue to work on non-Apple
platforms. Apple platforms will get access to that initializer from 5.4
onwards.
Result:
Fewer build issues for users using Xcode 12.0 and 12.1.
Motivation:
Huffman decoding has rapidly become one of the most expensive parts of
the program. Some of the code here is unavoidably expensive, but there
is some unnecessary checked arithmetic here on offset. Removing that
provides a small but meaningful improvement to the performance of this
function.
Modifications:
- Remove the checked arithmetic on offset, which is bounded by a
previous operation that was already checked.
Result:
This function gets cheaper by about 4%, though the benchmark as a whole
only sees a 0.1% improvement.
Motivation:
A while ago we shimmed out the String unsafeUninitializedCapacity
initializer because while it was on the road to being implemented, it
hadn't actually been implemented. Now it has!
On Apple platforms, the initializer is guarded behind an availability
guard. We need to add that guard here. This means we need to keep hold
of the backport for a good long time, until we raise our minimum Apple
platform support to a new enough version. Happily, Linux on 5.3 should
just see a net win here.
Modifications:
- Updated to enable us to use the proper initializer.
Result:
Fewer allocations when screwing around with HPACK.
Motivation:
No point having conditional branches when the branch is always taken!
This doesn't hurt perf at all, the optimiser will trivially see through
this, but it does hurt readability. Relatedly, the single-letter
variable names here aren't great.
Modifications:
- Removed needless branch.
- Gave the variables better names.
Result:
Easier to understand code.
Co-authored-by: George Barnett <gbarnett@apple.com>
Motivation:
HTTPHeaders and HPACKHeaders have very similar APIs, yet some of the
functionality of HTTPHeaders is missing from HPACKHeaders.
Modifications:
- Add `remove`, `replaceOrAdd`, `capacity` and `reserveCapacity` to
HPACKHeaders
Result:
- HPACKHeaders is closer in feature parity to HTTPHeaders
* Add a subscript to HPACKHeaders to return the first value with a matching name
Motivation:
In some cases you only expect (or care about) a single value for a
header. However, getting this value without allocating an array or
traversing the whole array requres using first(where:) provided by
Sequence. This is not very ergonomic as it requires users to do the
case-insensitive comparison and then exctact the value from the
HPACKHeader. Additionally, users cannot use NIO HTTP/2s case insensitive
ASCII comparison.
Modifications:
- Provide a first(name:) method on HPACKHeaders which returns the value
from the first header whose name is a case insentive match of the
subscript parameter.
Result:
It's easier to get the first
Motivation:
We have a slow path in compareCaseInsensitiveASCIIBytes. On the server
this path will never be hit as to hit it requires having a
non-contiguous String, so we really really want the compiler to use all
its inlining smarts on the fast path instead. Currently it does, but as
Sequence.elementsEqual is inlinable we need to be sure that doesn't
change.
Modifications:
Force the slow path not to be inlined.
Result:
Guarantees about good inlining.
Motivation:
In many cases it's necessary to be able to do HPACK table lookups to
find only a matching header field name, when it isn't going to be
possible to use a fully indexed header. For example, when using
nonIndexable header fields you cannot use an indexed field value, so
there is no point looking at all the header field values anyway.
While we technically supported this, there were two wrinkles. The first
was that if you attempted to search for a header field without any care
for its name, we'd actually only search the static table, missing
anything added into the dynamic table, which is pretty stupid.
The second issue was that nonIndexable header fields did extra
unnecessary work. This is because we asked the header table to search
for an exact match, but then disregarded whether or not one was found.
That meant a bunch of wasted computation.
Modifications:
- Fixed the table lookup to correctly search both dynamic and static
tables for partial matches.
- Correctly indicated that nonIndexable headers shouldn't care about
matching the header value.
Result:
Better handling of non-indexable headers.
Motivation:
HPACKHeaders are similar to HTTPHeaders but are missing a few useful
features:
- adding a sequence of headers to avoid reallocations, and
- being expressible as a dictionary literal.
Modifications:
- Add two `add(contentsOf:)` methods, one for key/value pairs, one for
key/value/indexing triplets.
- Add conformance to `ExpressibleByDictionaryLiteral`
Result:
HPACKHeaders is closer in feature parity to HTTPHeaders.
Motivation:
HTTP/2 is mostly just HTTP(/1) semantics with streams on a new wire
protocol. However, there are certain things that are legal in HTTP/1 but
which are illegal in HTTP/2.
Modification:
Accept more of those messages and transform them into their HTTP/2
equivalent.
Result:
- Easier to write HTTP/2 clients & servers in NIO.
- fixes#152
* Forbid excessive sending of empty DATA frames
Motivation:
One vector for DoS can be sending a large number of essentially "empty"
frames, such as empty DATA frames without END_STREAM set. We should
forbid peers from doing so excessively, but we want to tolerate
implementations that occasionally emit such a frame for buggy reasons.
Modifications:
- Added verification that too many empty DATA frames are not sent.
Result:
Better resistance to DoS attacks.
* Improved buffering in CompoundOutboundBuffer
Motivation:
In HTTP/2 it is possible for remote peers to submit work in a way that
cause the NIOHTTP2Handler to generate a substantial number of control
frames. If the peer is not consuming these frames, we can eventually run
out of memory and die, which is not exactly ideal.
It's hard for us to know how the buffering is going if we always submit
all frames directly to the Channel, so we need to pay attention to
whether the Channel is actually writable. If it isn't, rather than issue
further writes we need to delay those writes so we can keep track of how
big that buffer is getting. If the buffer gets too large we need a
circuit breaker to drop the connection, as we're clearly not able to get
work done.
This patch adds a new buffer for outbound control frames. This new
buffer is the last step in the buffering sequence, and the first to be
drained when a Channel becomes writable.
Additionally, enhancements need to be made to ensure that other buffers
behave correctly in the face of this new model. The
ConcurrentStreamsBuffer needs to be more aggressive about storing
HEADERS frames that cannot be emitted to the wire because it does not
tolerate emitting a HEADERS frame that cannot be immediately written to
the wire. Additionally, the buffers must not be polled when a Channel is
unwritable.
This is a large patch, but it does substantially change the buffering
logic, and protects NIO against a wide range of denial of service
attacks, while providing a clear and coherent defense surface.
Note that one thing this patch does not do is constrain the size of the
buffers in the ConcurrentStreamsBuffer. This is on purpose: the size of
this buffer is controlled entirely by user action. Users that do not
wish to buffer excessively in this buffer can avoid doing so simply by
respecting the peer's value of SETTINGS_MAX_CONCURRENT_STREAMS. As the
entire purpose of this buffer is to tolerate users that do not wish to
abide by this setting, it would be unreasonable to provide an upper
bound on the value used in this setting.
Modifications:
- Moved the various buffers into a directory.
- Built and implemented ControlFrameBuffer.
- Integrated ControlFrameBuffer into CompoundOutboundBuffer.
- Added awareness around channel writability to HTTP2Handler
- Enhanced ConcurrentStreamsBuffer to be writability-aware.
Result:
We'll have somewhere to put control frames.
* Cleanup API for merged security fixes.
Motivation:
After merging the security fixes we ended up with a slightly awkward
API: the argument names differed slightly for no good reason, and it
became impossible to override only one of the two security settings.
Modifications:
- Renamed `max` to `maximum`.
- Gave default values for the security settings.
Result:
Better user experience.
* Prevent DoS with large header lists.
Motivation:
There are two ways malicious peers could attempt to DoS a SwiftNIO
HTTP/2 implementation with header lists. The first would be to attempt
to send an enormous header list, ideally with an amplification factor.
This approach was possible because SwiftNIO never actually enforced the
value of the max header list size it advertised.
In principle the peer can still get a good amplification attack effect
by sending a long header list that contains zero-length headers. We may
as well close this door as well: zero length header field names are
unacceptable, and so we should forbid them.
Modifications:
- Added max header list enforcement.
- Forbade zero-length header field names.
Result:
Peers cannot DoS a SwiftNIO HTTP/2 implementation using large header
lists.
Motivation:
I was seeing frequent reallocations of the headers array as it
resized during decoding.
Modifications:
Reserve capacity for at least 16 HPACK headers during decoding.
Result:
Fewer reallocations at the cost of allocating more than we might need.
Motivation:
We were copying HTTP headers around quite a lot when transforming from HTTP/1 to HTTP/2 and
back. Due to the different underlying representations we cannot get away from needing to do
one copy, as the backing array storage is of a different type, but we were frequently incurring
CoWs as well that were just totally unnecessary.
Modifications:
- Refactored the header code to work more confidently on HPACKHeaders.
- Removed some mutating functions that triggered unnecessary CoWs.
- Improved HPACKHeaders(httpHeaders:) initializer to avoid unnecessary intermediate array
- Improved HTTPHeaders(requestHead:protocolString:) to avoid CoWs and reallocations
- Improved HTTPHeaders(responseHead:) to avoid CoWs and reallocations
Result:
Fewer heap allocations
Motivation:
Inserting an indexed header field that is too large is not an error, and
we shouldn't treat it as one. This was tripping over an example application
that hit Wikipedia.
Modifications:
- Stop throwing errors when we try to insert an overlarge header to the
dynamic table.
- Add a regression test.
Result:
We can speak to Wikipedia
Motivation:
When originally written our HPACK implementation targetted Swift 4.2,
which had performance issues when storing mostly-ASCII data in Strings.
For this reason we had a number of data types that used ByteBuffers as
their backing storage and reified Strings when necessary.
In Swift 5 this is no longer worthwhile: in fact, it imposes performance
penalties above and beyond simply using the Strings. For this reason, we
should move to a simpler model where we simply store Strings again.
Modifications:
- Rewrote all HPACK data structures to use Strings as their backing store.
- Removed now-redundant genericism.
- Removed now-unnecessary StringRing data structure and associated tests.
Result:
Faster performance in almost all cases.
While investigating performance of HTTP/2 I noticed a substantial number
of allocations occuring in a hot loop in header compression. Specifically
I set up a simple harness that encoded headers 100 times, and then ran
that harness 10k times. This harness ended up performing 17 million
allocations, which is frankly a bit too high!
The fact that the number of allocations was in the millions suggested that
we were allocating some resources per header encode. That's not good:
assuming the target `ByteBuffer` is big enough we should not need to
perform new allocations to encode headers.
The allocations came from two places. Firstly, we were allocating in the
`HeaderTableStorage.indices(matching:)` function. This was because that
operation was returning a lazy collection, which required multiple heap
allocations for the closure contexts. Those needed to be eliminated.
Secondly, we were triggering a CoW of the `ByteBuffer` passed in to
`encode()`. This is the result of a complex bit of control flow that
fundamentally meant that the buffer was held in two places in that
method.
Removing these two sources of allocations dropped the count in my test
from 17 million to 176k, a decrease of 100x. We also saw a speed boost
of nearly 66% in terms of runtime of the microbenchmark.
- Removed `HeaderTableStorage.indices(matching:)`
- Implemented `HeaderTableStorage.closestMatch(name:value:), containing
the repeated logic of the body of the two loops over the header
indices.
- Used swap() and an empty byte buffer to ensure that encode does not
cause a CoW operation.
Much faster and more memory efficient header encoding.
Motivation:
RFC 7541 is pretty clear that index 0 is no bueno in the indexed
header representation, so we should forbid it.
Modifications:
- Detected attempts to decode index 0.
Result:
Index 0 is now forbidden.