Commit Graph
54 Commits
Author SHA1 Message Date
George Barnett a7a0a9a118 Strict concurrency for NIOHPACK (#502)
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.
2025-03-21 17:15:54 +00:00
Peter Adams 1118370ec4 Apply swift-format changes and CI (#472)
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
2024-10-29 13:09:54 +00:00
Peter Adams bc93af21b0 GitHub Actions to parity with existing CI (#469)
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.
2024-10-23 14:02:30 +00:00
Si Beaumont 94ab10b5af Use explicit 64-bit UInt64 to support 32-bit platforms (#430) 2023-12-18 15:11:15 +00:00
Rick Newton-Rogers 285e444b49 Sendability warnings (#417)
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
2023-11-01 14:36:38 +00:00
Rick Newton-Rogers d5f0715865 Tweak formatting of function DocC comments (#407)
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
2023-07-05 05:35:47 -07:00
brennoandCory Benfield 87e96ed89b Replace os() with canImport(Darwin) (#399)
* Replace os() with canImport(Darwin)

* Removed compilation condition since it'll be always true

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-06-23 03:28:57 -07:00
Fabian Fett 145eec4e4f Add HPACKHeader.removeAll(keepingCapacity:) (#393)
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.
2023-05-17 02:09:06 -07:00
Cory Benfield 81b001dd07 Add regression testing for docs and fix the issues. (#389) 2023-04-11 11:04:31 +02:00
Cory Benfield 860622124b Correctly respect changes to HEADER_TABLE_SIZE (#374)
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.
2023-02-24 13:20:51 +00:00
George Barnett c7e4c5162f Provide an iterator for header values (#362)
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
2022-11-30 13:39:03 +00:00
George Barnett b1f1e68683 Replace NIOSendable with Sendable (#358)
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.
2022-11-01 01:47:07 -07:00
David Nadoba a89ddbf0af Remove #if compiler(>=5.5) (#357) 2022-10-13 14:57:50 +01:00
George Barnett 108ac15087 Improve HTTPHeader normalisation performance for large inputs (#347)
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.
2022-05-17 12:13:26 +01:00
David Evans c13f959b10 Adopt Sendable in relevant types (#343)
* Implement Sendable

* Make structs Sendable

* Update HTTP2Error.swift

* Fix compile

* Fix compile (again)

* Remove weird imports

* Cleanup

* Cory PR comments

* Remove Sendable conformance from Errors

* Cleanup

* Cleanup

* Remove unused concurrency import

* Remove NIOSendable from HTTP2Error.swift

* Cleanup

* Revert changes in HTTP2Error
2022-05-06 11:50:26 +01:00
Cory BenfieldandDavid Nadoba c28d13dddd Make HPACKHeaders hashable. (#344)
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>
2022-05-04 08:43:05 -07:00
Cory Benfield 0ad7ff6d41 Use unchecked math in encodeInteger (#328)
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.
2022-02-25 00:30:35 -08:00
Cory Benfield 344e118a88 Remove a retain/release (#327)
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.
2022-02-23 08:54:37 +00:00
George Barnett ba43a95d6b Make UnrepresentableInteger public (#325)
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.
2022-02-11 02:31:06 -08:00
George Barnett 56c60a29b1 Merge pull request from GHSA-w3f6-pc54-gfw7
* 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
2022-02-11 09:18:39 +00:00
Fabian Fett deca1c3227 Remove forbidden HTTP1 headers even if no connection header is present (#311) 2021-11-24 10:19:21 +00:00
Cory Benfield 326f7f9a8c Simplify the canonicalForm subscript further. (#310)
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.
2021-09-29 15:00:31 +01:00
George Barnett 2624ccc6d6 Use case-insensitive comparision rather than lowercasing (#308)
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.
2021-09-29 13:43:18 +01:00
George Barnett cce39c364a Ignore empty values when returning canonical form of header values (#307)
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
2021-09-29 12:55:58 +01:00
George Barnett d34f4b0c0f Don't count CR or LF as whitespace when trimming whitespace from header values (#306)
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.
2021-09-29 10:50:30 +01:00
George Barnett 31db14091d Improve performance of HPACKHeaders.subscript(canonicalForm:) (#304)
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.
2021-09-29 10:13:28 +01:00
Cory Benfield dbfc8fcd1a Clean up imports and dependencies. (#300)
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.
2021-09-14 11:30:04 +01:00
Cory Benfield f4736a3b78 Delete dead code. (#279)
No-one calls this function so we can remove it.
2021-02-17 16:32:48 +00:00
Cory Benfield d4060ac4d0 Make HPACKHeaders inlinable. (#269)
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.
2020-12-08 09:46:30 +00:00
Cory Benfield 1dd123a849 Reduce ARC in HPACK closestMatch (#268)
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.
2020-12-04 09:43:24 +00:00
Cory Benfield f4b49cbed1 Partially revert #263. (#267)
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.
2020-12-03 14:00:16 +00:00
Cory Benfield 46b6e0197c Micro-optimise checked arithmetic in huffman. (#266)
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.
2020-12-03 12:03:41 +00:00
Cory Benfield c61955a870 Use proper String unsafeUninitializedCapacity initializer. (#263)
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.
2020-11-28 15:56:31 +00:00
Cory BenfieldandGeorge Barnett 7d366b1b77 Remove needless branch, clean up variable names. (#234)
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>
2020-08-28 09:38:43 +01:00
George Barnett 9f4eff0603 Bring HPACKHeaders function parity closer to HTTPHeaders (#232)
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
2020-08-20 11:19:39 +01:00
Cory Benfield 32db4dd7c2 Swap Huffman unnecessary var to let. (#203) 2020-05-11 11:49:17 +01:00
Johannes Weiss c1bfb7ce3f fix new NIO and new Swift compiler warnings (#179) 2019-12-10 12:45:48 +00:00
George Barnett a8f89aa368 Add a subscript to HPACKHeaders to return the first value with a matc… (#178)
* 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
2019-12-04 12:07:31 +00:00
Cory Benfield 747e511b11 Force slow path header comparison to not inline. (#170)
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.
2019-11-12 16:30:22 +00:00
Cory Benfield 16c346b4cb Fix partial table lookups. (#168)
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.
2019-11-12 12:20:50 +00:00
George Barnett 58bf1c964d Allow adding a sequence of headeers to HPACKHeaders (#155)
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.
2019-09-10 12:44:09 +01:00
Johannes Weiss 114c4e0022 accept more valid-in-HTTP/1 but invalid-in-H2 messages (#153)
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
2019-09-09 16:15:46 +01:00
Cory Benfield 86ce1dcd0d Merge pull request from GHSA-jchv-x857-q8fq
* 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.
2019-08-13 18:00:41 +01:00
George Barnett d66cd24206 Reserve capacity when decoding HPACK headers (#118)
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.
2019-05-16 14:31:19 +01:00
Cory Benfield 144f9d2a0e Reduce intermediate header copies. (#112)
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
2019-05-03 17:56:35 +01:00
Cory Benfield 492f375a14 Allow inserting overlarge indexed headers. (#99)
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
2019-04-16 11:48:21 +01:00
Cory Benfield ddc982111e Move to String-backed HPACK representations. (#89)
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.
2019-04-12 12:42:24 +01:00
Cory Benfield 70ac404a42 Decrease allocations in encode loop. (#86)
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.
2019-04-05 16:38:21 +01:00
Cory Benfield 4a490f2e04 Refuse to decode indexed header with index 0. (#63)
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.
2019-03-15 12:01:09 +00:00
Tanner 049ba81fcc remove _NIOAPI1Shims since NIO 2 is in convergence (#59)
* remove _NIOAPI1Shims since NIO 2 is in convergence

* remove import in NIOHPACK
2019-03-13 19:45:28 +00:00