327 Commits
Author SHA1 Message Date
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.
1.22.0
2022-05-17 12:13:26 +01:00
George Barnett ed25fecd40 HPACKHeaders performance test for HTTPHeader normalisation (#346)
Motivation:

`HPACKHeaders` has an `init` which will normalize `HTTPHeaders`, this
includes removing any headers which are illegal in HTTP2 and any headers
which present as a 'connection' header value. As written this is
expensive in some edges cases. With perf tests we can validate that
implementation changes improve performance.

Modifications:

Add a performance test to normalize `HTTPHeaders`. This is run on two
configurations.

Result:

More insight into header normalisation perf.
2022-05-17 09:31:47 +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
George Barnett eb1d696793 Remove build_podspec.sh (#341)
Motivation:

We no longer support Cocoapods.

Modifications:

- Remove build_podspec.sh and associated scripts

Result:

Less unused code.
2022-05-04 11:02:50 +01:00
George Barnett ef83310fe9 Add script to list transitive dependencies (#340)
See https://github.com/apple/swift-nio/pull/2082
2022-05-03 10:16:09 +01:00
Fabian Fett 72bcaf607b Fix warnings, that appeared after requiring Swift 5.4 (#338) 1.21.0 2022-04-21 09:19:52 -07:00
Fabian Fett dbfca164c1 Drop support for Swift 5.2 and 5.3 (#337)
As outlined in a [Swift forums post in November ’21](https://forums.swift.org/t/swiftnio-swift-version-support/53232), SwiftNIO will only support the latest non-patch Swift release and the 2 immediately prior non-patch versions.

- drop support for Swift 5.2 and 5.3. 
- update CI for Swift 5.4 to run on bionic instead of focal to ensure that we still test bionic.
2022-04-20 08:57:26 +02:00
Franz Busch c897189177 Use SPM API diff checker (#334)
### Motivation:

SPM has built in functionality to check the API of modules against a target git treeish. We can use this to simplify our `check_no_api_breakages.sh` script. Closes https://github.com/apple/swift-nio/issues/1239

### Modifications:

This PR, exchanges the direct calls to Swift's API checker with the new SPM `diagnose-api-breaking-changes` tool. This allows us to get rid of the manual module parsing, build invocations and result comparisons.

### Result:

We are now using SPMs `diagnose-api-breaking-changes` to check for breaking changes.
2022-03-23 09:56:16 -07:00
Cory BenfieldandGeorge Barnett 50c25c132b Clients can't push! (#332)
Motivation:

Nowhere in the PUSH_PROMISE code do we explicitly check whether or not
we're a client or a server, and we don't provide special handling for
SETTINGS_ENABLE_PUSH contingent on that fact. As a result, we do
technically allow clients to push. This eventually gets caught, but not
until we've created an idle stream, which we shouldn't do.

Modifications:

- Forbid clients from pushing.

Result:

Clients won't be allowed to push.

Co-authored-by: George Barnett <gbarnett@apple.com>
1.20.1
2022-03-17 10:43:11 -07:00
tomer doronandCory Benfield 2c87ffecc3 ci update (#329)
* ci update

motivation: 5.6 is out

changes:
* use release version of 5.6
* add docker setup for 5.7 (using nightly for now)

* Update to new alloc counts

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-03-17 17:14:08 +00:00
Cory Benfieldandtom doron 2d5d718d90 Update alloc limits and clean up soundness (#331)
* Lower allocation limits

Our recent fixes reduced our allocation count, which is good.

* fix code soundness check

motivation: code should be sound!

changes:
* update one case of inappropriate langauge
* update header years check regex

(cherry picked from commit a89e8ae4e0)

Co-authored-by: tom doron <tomer@apple.com>
2022-03-17 09:08:42 +00:00
Cory Benfield ac2a5afce3 Merge pull request from GHSA-q36x-r5x4-h4q6
Motivation

The HTTP2FrameDecoder is a complex object that was written early in the
development of swift-nio-http2. Its logical flow is complex, and it
hasn't been meaningfully rewritten in quite some time, so it's difficult
to work with and understand.

Annoyingly, some bugs have crept in over the years. Because of the
structure of the code it can be quite difficult to understand how the
parser actually works, and fixing a given issue can be difficult.

This patch aims to produce a substantial change to the HTTP2FrameDecoder
to make it easier to understand and maintain in the long run.

Modifications

This patch provides a complete rewrite of HTTP2FrameDecoder. It doesn't
do this by having a ground-up rewrite: instead, it's more like a
renovation, with the general scaffolding kept. The rewrite was performed
incrementally, keeping the existing test suite passing and writing new
tests when necessary.

The following major changes were made:

1. New states and edges were added to the state machine to handle
   padding.

   Prior to this change, padding was handled as part of frame payload
   decoding. This is not totally unreasonable, but it dispersed padding
   management widely and made it easy to have bugs slip in. This patch
   replaces this with a smaller set of locations.

   Padding is now handled in two distinct ways. For HEADERS and
   PUSH_PROMISE frames, trailing padding is still stripped as part of
   frame payload decode, but it's done so generically, and the padding
   bytes are never exposed to the individual frame parser. For DATA,
   there is a new state to handle trailing padding removal, which
   simplifies the highly complex logic around synthesised data frames.

   For all frames, the leading padding byte is handled by a new
   dedicated state which is used unconditionally, instead of attempting
   to opportunistically strip it. This simplifies the code flow.

   As a side benefit, this change means we can now accurately report the
   padding used on HEADERS and PUSH_PROMISE frames, even when they are
   part of a CONTINUATION sequence.

2. The synthesised DATA frame logic has been substantially reworked.

   With the removal of the padding logic from the state, we now know
   that so long as we have either got a byte of data to emit _or_ the
   DATA frame is zero length, we will always emit a frame. This has made
   it simpler to understand the control flow when synthesising DATA
   frames.

3. The monolithic state switch has been refactored into per-state
   methods.

   This helps manage the amount of state that each method can see, as
   well as to logically split them up. In addition, it allows us to
   recast state transformations as (fairly) pure functions.

   Additionally, this allowed the larger methods to be refactored with
   smaller helpers that are more obviously correct.

4. The frame payload parsers have been rewritten.

   The main goal here was to remove preflight length checks and unsafe
   code. The preflight length checks cause trouble when they disagree
   with the parsing code, so we now rely on the parsing code being
   correct with regard to length.

   Relatedly, we previously had two separate places where we
   communicated length: a frame header length and a ByteBuffer length.
   This was unnecessary duplication of information, so we instead use a
   ByteBuffer slice to manage the length. This ensures that we cannot
   over-parse a message.

   Finally, in places that used unsafe code or separate integer reads,
   we have refactored to stop using that unsafe code and to use combined
   integer reads.

5. Extraneous serialization code has been extracted.

   The HTTP2FrameEncoder was unnecessarily in this file, which took a
   large file and made it larger. I moved this out.

Result

The resulting parser is clearer and safer. Complex logic has been broken
out into smaller methods with less access to global data. The code
should be generally clearer.
1.20.0
2022-03-10 10:16:17 +00: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 fdffed7efb Update minimum dependency version in README (#326) 2022-02-11 03:28:11 -08: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 000ca94f9d Merge pull request from GHSA-pgfx-g6rc-8cjv
Motivation:

We don't currently support ALTSVC and ORIGIN frames. At the moment when
receiving or attempting to write these frames we trap. Trapping when
receiving an unsupported frame can lead to DoS attacks. Moreover these
frames are non critical so can safely be ignored.

Modifications:

- Forward inbound and outbound ALTSVC and ORIGIN frames to the
  connection state machine
- The connection state machine now ignores inbound frames of this type
- The connection state machine traps on outbound frames of this type (as
  per the current behaviour)
- Document this behaviour on `HTTP2Frame.FramePayload`
- Tests and fuzz testing failure case

Result:

We don't trap when receiving unsupported frames.
1.19.2
2022-02-11 09:19:11 +00: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
George Barnett 93215774aa Merge pull request from GHSA-ccw9-q5h2-8c2w
* Validate HEADERS frame length accounts for priority data

Motivation:

When parsing a HEADERS frame payload which includes priority data the
expected length of the frame is not validated to ensure that it is large
enough to account for the stream data. This can lead to the expected
payload length being negative.

Modifications:

- Validate that when stream priority data is present that the frame
  length is at least that size
- Add fuzz testing failure case

Result:

The frame decoder will throw a protocol error when parsing a HEADERS
frame if the length of the frame is less than the number of bytes
required for stream priority data and the priority flag is set.

* Add additional tests

* Fix weirdo formatting
2022-02-11 09:17:56 +00:00
Cory Benfield 3cbebafccb Add 5.6 nightly CI (#324)
* Add 5.6 nightly CI

The 5.6 nightly images are available, let's use them.

* Update alloc limits
2022-01-18 02:19:40 -08:00
George Barnett bec04abc90 Update doc generation script (#322)
Motivation:

The docs haven't been generated for a while.

See also: https://github.com/apple/swift-nio/pull/2013

Modifications:

- Pass `--spm` flag to sourcekitten
- Update source location of sourcekitten
- Fix link to NIO docs

Result:

Docs build.
2021-12-17 11:39:37 +00:00
George Barnett 6e94a7be32 Update nightly allocation limits (#321)
Motivation:

Recent nightly builds have introduced small allocation regressions.

Modifications:

Update allocation limits for nightly Swift builds.

Result:

CI passes.
1.19.1
2021-12-15 10:40:29 +00:00
George Barnett 39a0aa47f8 Only flush when necessary in the HTTP2ChannelHandler (#320)
Motivation:

The `wroteFrame` flag in `HTTP2ChannelHandler` indicates whether a frame
has been written. This flag is checked before flushing in order to avoid
unnecessary flushes. Unfortunately this is only ever set to `true`.

Modifications:

- Add a `flushIfNecessary` to check and toggle `wroteFrame` and flush if
  necessary
- Add a test

Result:

- Few unnecessary flushes
- Resolves https://github.com/apple/swift-nio-http2/issues/245
2021-12-15 09:33:30 +00:00
Franz Busch ff53cbc704 Protect against HTT2ChannelHandler reentrancy (#319)
In rare cases the `HTTP2ChannelHandler`s method `unbufferAndFlushAutomaticFrames` and the `HTTP2StreaMultiplexer`s `newConnectionWindowSize` method were recursively calling themselves. This was causing a stack overflow. To protect our selves from this stack overflow I added a variable to protect ourselves against reentrancy inside the `unbufferAndFlushAutomaticFrames` method
2021-12-13 03:36:15 -08:00
Fabian Fett 39ed0e7535 Forward all reads before stream channel inactive (#317)
### Motivation

In the AsyncHTTPClient the read event is not always forwarded right away. We have seen instances, in which we see a `HTTPClientError.remoteConnectionClosed` error, on requests that finish normally. https://github.com/swift-server/async-http-client/issues/488 

On deeper inspection, I noticed: If there is no unsatisfied read event, when a stream is closed, the pending reads are not forwarded. This can lead to response bytes being ignored on successful requests. NIOHTTP2 should behave as NIO and force forward all pending reads on channelInactive.

### Changes

- Forward all pending reads on channelInactive even if no read event has hit the channel

### Result

All requests will receive the complete request body.
1.19.0
2021-11-30 18:24:42 +01:00
Fabian FettandCory Benfield 1aba7771c8 Add Transfer-Encoding chunked to HTTP1 requests and responses. (#316)
* Add Transfer-Encoding chunked to HTTP1 requests and responses.

* Apply suggestions from code review

Co-authored-by: Cory Benfield <lukasa@apple.com>

* Code review II

* Fixed deprecated tests

Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-11-30 10:25:05 +00:00
Cory Benfield f0adfc1d6d Deliver outbound stream errors to channels. (#315)
Motivation:

When we hit a stream error on an outbound frame, we don't currently
distinguish between them and channel errors. This makes it impossible
for anyone to tell them apart. It also makes it impossible for the
multiplexer to deliver these errors into the relevant stream channels
that triggered them, making it essentially certain they'll be lost.

Better diagnostics would be good, so we are providing them.

Modifications:

- Add new StreamError type that carries a stream ID and an underlying
  error.
- Emit this StreamError type for outbound stream errors.
- Deliver this StreamError type into the relevant child channels when
  possible.

Result:

Better diagnostics for stream errors.
2021-11-26 17:38:36 +00:00
Cory Benfield b5919e4621 Swift nightly has improved alloc counts. (#314)
This patch updates the alloc counter to enforce the new numbers.
1.18.5
2021-11-25 10:26:32 +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.
1.18.4
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
George Barnett 80f02ef18a Add perf and alloc tests for getting headers (#303)
Motivation:

To justify performance changes we need to measure the code being
changed. We believe that `HPACKHeaders.subscript(canonicalForm:)` is a
little slow.

Modifications:

- Add allocation and performance tests for fetching header values in
  their canonical form

Results:

More benchmarks.
2021-09-27 12:43:35 +01:00
Cory Benfield 24acfe2a88 Update to 5.5 release in CI (#301) 2021-09-22 14:47:36 +02:00
Cory Benfield f475cb4c9b Account for improved allocs on nightly (#302) 2021-09-22 13:08:49 +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.
1.18.3
2021-09-14 11:30:04 +01:00
George Barnett dbe7fb05fe Fix doc generation and jazzy version (#298)
From: https://github.com/apple/swift-nio-extras/pull/141

Motivation:

The combination of Ruby and Jazzy are throwing up issues in CI on older
Ubuntu versions.

Modifications:

- Only install Jazzy on focal
- Fix doc generation script to use more recent source-kitten syntax

Results:

- CI doesn't complain
- Docs get built
2021-09-03 14:38:04 +01:00
Fabian Fett 42bdcae4ac Use non-deprecated API for removing handlers (#297)
### Motivation:

`removeHandlers(channel:)` was deprecated in NIO 2.32.0.

### Modifications:

- Raise minimum required `NIO` version to 2.32.0
- Use `removeHandlers(pipeline:)`

### Result:

We don't use deprecated API.
1.18.2
2021-08-18 16:22:51 +02:00
George Barnett f6cde03ef8 Bump Swift version in build_podspec.sh (#294)
Motivation:

SwiftNIO recently dropped support for Swift 5.0 and Swift 5.1 but our
build_podspec.sh script doesn't reflect this change. Additionally the
list_topsorted_dependencies.sh script always assumed named depenencies
when listing module depenencies. Since our tools version has now been
bumped to 5.2 that's no longer the case and the script produces a bunch
of nulls which throws the build_podspec.sh script off course.

Modifications:

- Bump the Swift version in build_podspec.sh to 5.2
- Include "product" dependencies when listing module dependencies in
  list_topsorted_dependencies.sh

Result:

Podspecs are created as expected
1.18.1
2021-08-17 10:11:26 +01:00
buttaface 94d3652e37 Enable tests for Android (#296)
Motivation:

Run the tests on Android.

Modifications:

- Enable the tests on Android.
- Replace '/tmp' with 'FileManager.default.temporaryDirectory'.

Result:

All the tests pass on Android AArch64 and x86_64.
2021-08-16 19:05:52 +01:00
Fabian Fett 1f64743098 Fix receiving empty body byte buffer before .end (#295) 2021-08-12 11:29:39 +01:00
David Evans 13b6a7a838 Update NIO to 2.30.0 (#293) 1.18.0 2021-06-23 14:04:28 +01:00
David Evans 488444b14c Remove support for Swift 5.0 and 5.1 (#292)
* Update package

* Update CI

* Add to readme
2021-06-23 08:37:07 +01:00
Johannes WeissandCory Benfield a5aef08b10 stop publishing the executable produts (#289)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-06-09 09:33:15 +01:00
Cory Benfield 798079d137 Update our allocation counter numbers. (#290)
Motivation:

Our 5.5 allocation counts were off. Rather than just update that by hand
we should bring over some tooling to do it automatically.

Modifications:

- Bring over and adapt the update-alloc-limits scripts from NIO.
- Run them and commit the updates.

Result:

CI should pass again.
2021-06-08 16:27:22 +01:00
Cory Benfield 1ef8bac96a Add fuzzing harness to swift-nio-http2. (#288)
Motivation:

Fuzzing is great, we should have a good sensible place to centralise a
harness.

Modifications:

- Add a fuzzing harness.

Result:

There's a common way to do fuzzing.
2021-05-27 16:33:43 +01:00
Johannes Weiss 000f5ee297 add Swift 5.5 job (#287) 2021-05-05 07:40:13 +01:00