19 Commits
Author SHA1 Message Date
George Barnett 1251530b26 Allow max reset stream frames to be configured (#494)
Motivation:

The maximum number of recently reset stream frames to track is limited
to a fixed value of 32. This should be configurable.

Modifications:

- Add it to the connection config and propagate it through

Result:

- Resolves #493
2025-02-28 13:54:05 +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
Clinton Nkwocha 376312d334 Handle race condition between sending GOAWAY and HEADERS (#457)
Motivation:

A potential race exists between a server sending a GOAWAY frame and a
client opening a new stream (i.e., sending a HEADERS frame before
receiving an already sent GOAWAY frame). If there are no open streams
when the server sends the GOAWAY frame, the connection state on the
server transitions to being fully quiesced, which throws a connection
error on receipt of a HEADERS frame.

Modifications:

- Adjust the connection state machine on the server to throw a stream
error (instead of a connection error), and consequently, send a
RST_STREAM frame to the client.

Result:

This condition will be treated as a stream-level error instead.
2024-09-06 11:59:15 +01:00
Clinton Nkwocha 9f6d865c81 Accept PING frames even when fully quiesced (#455)
Motivation:

When the connection is fully quiesced, an endpoint responds with a
connection error when it receives or tries to respond to a PING frame.
This behaviour is unnecessary.

Modifications:

- Adjust `HTTP2ConnectionStateMachine` to successfully receive and send
PING frames even when the connection is fully quiesced.

Result:

When the connection is fully quiesced, an endpoint will treat receipt
and sending of a PING frame as it would when the connection is active.
2024-08-30 03:50:01 -07:00
aryan-25 35b0b8f7e5 Fix bug where client ignores HEADERS frames on open stream when locally quiescing (#445)
Motivation:

Currently, HEADERS frames are ignored by the client on a client-initiated stream after the client sends a GOAWAY.

As per [Section 6.8 (GOAWAY) in RFC 9113](https://httpwg.org/specs/rfc9113#GOAWAY):
_"Once the GOAWAY is sent, the sender will ignore frames sent on streams **initiated by the receiver** if the stream has an identifier higher than the included last stream identifier."_

In this case, the client (sender) should **not** ignore the HEADERS frame as the stream is initiated by the _client_, not the receiver.

Modifications:

Fixed the condition in the `receiveHeaders` function (given `LocallyQuiescingState`) in `ReceivingHeadersState.swift` to work for _both_ the client and server roles -- before this change, the condition is only correct when `self.role == ConnectionRole.server`

Result:

HEADERS frames are not ignored by the client on a client-initiated stream when locally quiescing.
2024-07-18 06:55:30 -07:00
Eric Rosenberg 6af2cf64cb Implement RFC8441 Extended CONNECT (#441)
Implement RFC8441 Extended CONNECT
2024-06-24 08:33:39 +01: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
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 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.
2022-02-11 09:19:11 +00: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
George Barnett 7774067c43 Add properties to HTTP2StreamID to determine stream initiator (#259)
Motivation:

It's not possible (at least trivially) from the public API to determine
which peer in a connection initiated a given stream ID. In some cases
it's possible with prior knowledge (i.e. in a given application the
client may always initiate streams), however, such conditions aren't
guaranteed to always hold.

Modifications:

- Add `isClientInitiated` and `isServerInitiated` computed properties to
  `HTTP2StreamID`.
- Add a few tests.

Result:

Users can easily get the answer to the question 'did a client/server
create this stream?'
2020-11-24 14:41:26 +00:00
George Barnett 440d64d99a Add a location to each of 'NIOHTTP2Errors' (#247)
Motivation:

Without knowing where an error was thrown it can be unnecessarily
difficult to work out the reasons an application ended up in an error
state.

Modifications:

- Add a 'file' string to each of the 'NIOHTTP2Errors' denoting the file
  and line where an error was created
- Add static methods to create errors to 'NIOHTTP2Errors' defaulting
  file and line, this is unfortunately necessary as defaulting file and
  line in the `init` makes the defaulted and non-defaulted errors
  indistinguishable, and the compiler will pick the one with fewest
  defaulted values.
- Add equatable conformance manually so as to ignore 'file'
- Add backing storage to errors which no longer be stored in an existential
  container
- Add 'CustomStringConvertible' conformance to the errors using backing
  storage so that the 'file' is actually visible when converting the
  error
- Deprecate the old `init`s
- Fix all deprecation warnings

Result:

- NIOHTTP2Errors carry a 'file' with them indicating where they were
  created
2020-09-24 15:21:58 +01:00
Cory Benfield ee31368790 Remove unnecessary state CoWs. (#104)
Motivation:

When benchmarking the HTTP/2 implementation I noticed that we were
performing a large number of CoW operations on the Dictionary that backs
the ConnectionStreamState structure: specifically, once per frame sent or
received.

This is substantial and unnecessary allocation overhead that drags down
the performance of the program, sprays the heap with small allocations, and
generally just leads to nasty performance costs with no gain.

Sadly, this turns out not to be the easiest CoW to get rid of, because
the ConnectionStreamState structure is stored in associated data on the
connection state machine state enumeration. This means that our usual tricks
for avoiding the CoW (such as swap()) no longer work.

The only solution is to add a new state that corresponds to no state at all
so that we can make the connection state go away while we mutate it. This is
all a bit gross, frankly. Unfortunately, the act of making this simple change
leads to a huge diff as we have to tweak basically every state machine
function in order to ensure that it does the right thing.

Modifications:

- Added a function to control CoWing the state machine.
- Used that function basically everywhere.
- Made sure that function had assertions.
- Annoyingly had to increase the visibility of a bunch of structs.

Result:

Fewer CoWs, better performance, sadder code reviewers.
2019-04-18 14:28:45 +01:00
Cory Benfield aaaeca77f9 Police correct content-length headers. (#98)
Motivation:

RFC 7540 requires that compliant specifications emit errors if content-length has been incorrectly
set. We should have this behaviour by default, though we should allow it to be disabled if necessary.

Modifications:

- Added content-length checking.
- Added flag to disable content-length checking.

Result:

Better RFC 7540 compliance.
2019-04-15 16:57:16 +01:00
Cory Benfield 08db9d8cd4 Resolve off-by-one errors in settings bounds. (#97)
Motivation:

When we're validating that settings are in their bounds, we should probably endeavour to
express those bounds correctly.

Modifications:

- Fixed the bounds checks on SETTINGS_INITIAL_WINDOW_SIZE and SETTINGS_MAX_FRAME_SIZE.
- Added regression tests.

Result:

Better correctness.
2019-04-15 12:06:10 +01:00
Cory Benfield 74b8f4f110 Validate no uppercase characters in header field names. (#84)
Motivation:

RFC 7540 forbids uppercase characters in header field names, but we
currently allow them. We shouldn't.

This is the first in a series of patches that will validate header blocks
when reasonable. As a result, it seems larger than necessary, as it adds
a bunch of scaffolding for extending with further validation code.

Modifications:

- Added header field validation scaffolding.
- Validates that header field names do not contain uppercase chars.
- Allows sending RST_STREAM frame before stream setup.

Result:

Better header field validation.
2019-04-05 18:01:22 +02:00
George Barnett 348a10ee19 Ensure preamble only gets sent once. (#61)
Motivation:

In certain cases it was possible for preamble to be sent once; this
would lead to frames getting sent more than once which in turn would
break state machines.

Modifications:

- Check the state of the connection before sending preamble.
- Include a test to check.

Result:

More correct implementation
2019-03-15 12:40:50 +00:00
Cory Benfield 24f67d855e New HTTP/2 currency types. (#44)
Motivation:

As discussed in our HTTP/2 types manifesto, it is helpful to run more
metadata through the HTTP/2 pipeline. This makes it easier to write
ChannelHandlers that fully participate in the HTTP/2 state machine
while avoiding needing to too tightly couple the handlers.

Modifications:

- Added new HTTP/2 pipeline data types.
- Removed HTTP2Frame.FrameFlags, moved flags into relevant payloads.

Result:

Right now, not much. All tests pass with new payload types. The full
data path rewrite will follow in a separate patch, as this one is large
enough.
2019-02-26 14:04:58 +00:00
Cory Benfield 3c90345c36 Pure-Swift HTTP/2 implementation (#40)
* Updated to use SwiftNIO 1.10+ to gain access to HTTPHeaders internals.

* Add pure-Swift HTTP/2 protocol implementation.

Motivation:

Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.

This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.

Modifications:

- Add pure Swift protocol implementations.
- Test them.

Results:

Another step towards protocol independence.

* Initial basic parser code.

* Adding unit tests.

* Add NIOHTTP2FlowControlHandler

Motivation:

One of the things that nghttp2 used to do for us was to handle buffering
DATA frames until flow control allowed them to go out. For users that
want that behaviour, we need to replace the nghttp2 code with a new
ChannelHandler that can do this work.

Modifications:

- Added NIOHTTP2FlowControlHandler.

Result:

Users will have the same feature set as they did with nghttp2.

* Generate Linux test information.

* Documentation comment.

* Updated new tests from master to use new payload types.

* Updated following review.

Notable changes:

- Implemented unit tests for the ALTSVC (0xa) and ORIGIN (0xc) frame types.
- Additional DATA frames are synthesized to wrap individual payload chunks as they arrive. If the payload of a DATA frame with 4MB data arrives in 4 separate 1MB chunks, the decoder will emit 4 DATA frames, with only the last containing the END_STREAM flag (if that was set on the incoming frame).
- HEADERS / PUSH_PROMISE frames and any following CONTINUATION frames are now handled properly: header fragments from all frames are gathered up into a single buffer. Once a frame with END_HEADERS is encountered, the resultant accumulated buffer is sent for decoding along with the flags and stream ID of the original HEADERS / PUSH_PROMISE frame.
- HPACK encoders/decoders now live in the frame encoder/decoder types, rather than being attached to a stream.

* Updated Linux tests.

* Headers placed in relevant files.

* Add pure-Swift HTTP/2 protocol implementation.

Motivation:

Currently we use nghttp2 for our basic protocol implementation. This is
plenty workable, but provides us a number of limitations. It adds
complexity to our build system, provides us with external dependencies we
have little control over, limits our users' ability to express low-level
protocol semantics if they so wish, causes us to heap-allocate like crazy over
the lifetime of a connection, and brings a world of pain around reentrancy.

This set of limitations has motivated a desire to move away from using
nghttp2. This is a part of that dream.

Modifications:

- Add pure Swift protocol implementations.
- Test them.

Results:

Another step towards protocol independence.

* Revamped frame decoder state machine and API. Now uses separate input and output methods to manage multiple frames in a single buffer.

* Updated Linux tests.

* Bumped swift-nio version to 1.12.0 and updated `HTTPHeaders` -> `HPACKHeaders` conversion initializer to directly copy the buffer and map the header name/value indices.

* Set up HTTP2Parser in handlerAdded if the channel had been previously activated. (#36)

By setting up the handler in the handlerAdded hook, HTTP2Parser supports
being added dynamically in a channelRead event, after the channel has sent
the channelActive event.

(cherry picked from commit 88bd6d369a)

* Minor tweaks to get the tests passing

* Initial integration here

* Minor clearing up of the handler

* Get the tests compiling

* Fix header issues.

We now pass the frame parser to the various setting operations to let it
update the state. We also fixed some issues with specific settings.

* Remove ngthttp2-based impl, clean up stream ID

* Tests with new HTTP2StreamID

* Simple test cleanup

* Get remaining non-core tests passing

* Allow GOAWAY even when fully quiesced

* We don't buffer outbound frames any more

* Emit StreamClosed events on GoAway frame

* Notify stream creation and closure

* This test started failing

* Goodbye, C code! 🎉

* Send PING ACK automatically

* Updated based on PR feedback.

* Correctly handle 1XX responses

* Add SETTINGS_MAX_FRAME_SIZE support to flow controller

* Correctly account for flow control

* Define ConcurrentStreamsHandler

* Prepare for signalling connection state changes

* Better state change message propagation

* Refactor to use result with effect everywhere

* Don't lose flow control info on stream error

* Add basic flow control management to stream multiplexer

* Better pipeline in sample server

* Clean up some reentrancy concerns

* Move to Swift 5 and NIO 2

* Move to new Swift 5 for CI

* Allow wider range of choices of years

* Catch up to NIO 2 again
2019-02-21 11:52:49 +00:00