46 Commits
Author SHA1 Message Date
George Barnett 6693a60432 Propagate ChannelShouldQuiesceEvent to child channels (#464)
Motivation:

NIO has a 'ChannelShouldQuiesceEvent' which channels can listen for in
order to know when they should quiesce. This is typically used to
initiate a graceful shutdown of an HTTP/2 server. However, child
channels aren't notified of this event so HTTP/2 servers must keep track
of streams separately in order to notify them when the server is
quiescing.

Modifications:

- Propagate the `ChannelShouldQuiesceEvent` to child channels

Result:

Child channels can watch for `ChannelShouldQuiesceEvent`s
2024-09-18 07:02:53 +01:00
Clinton NkwochaandGeorge Barnett d629013a6e Reject long sequences of CONTINUATION frames (#443)
* Reject long sequences of CONTINUATION frames

Motivation:

Long sequences of CONTINUATION frames can be used to mount attacks by attempting to get a remote peer to consume large amounts of memory.

Modifications:

- Add a limit to the number of sequential CONTINUATION frames that can be received. This limit is configurable by users at the NIOHTTP2Handler level and has a default value of 5. When this limit is exceeded, the recipient responds with a GOAWAY frame and an "Enhance Your Calm" error of a newly created type `ExcessiveContinuationFrames`.

Result:

Long sequences of CONTINUATION frames are now rejected by the recipient.

* Refactor implementation

* Minor adjustments

* Implement adjustments

- Refactor implementation
- Revert unnecessary diffs

* Implement adjustments

- Change `public let maximumSequentialContinuationFrames` to `public var`.
- Refactor implementation.

* Implement minor adjustments

* Store the default `maximumSequentialContinuationFrames` in a `private static let`

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2024-07-04 14:13:49 +01: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 a6c66bcbe7 Mark public generic async methods inlinable (#426)
* Mark generic async methods inlinable

Motivation:

Mark generic async methods inlinable where possible to improve performance.

Modifications:

Multiple methods marked `@inlinable`

Result:

Performance increase
2023-10-30 09:29:37 +00:00
Rick Newton-Rogers 462ded73ad HTTP/2 Async API (#424)
We previously developed an async API for NIO HTTP/2 which was guarded under SPI. Now that the swift-nio async API is released we can reintroduce this code promoted to SPI.

This change introduces:
* `AsyncStreamMultiplexer` - an async variant of the HTTP/2 stream multiplexer which can be used to create outbound streams and provide access to an async sequence (`NIOHTTP2AsyncSequence`) of inbound streams
* New pipeline configuration functions (e.g. `configureAsyncHTTP2Pipeline`) to support the new async mode
2023-10-25 15:49:16 +01:00
Rick Newton-Rogers d6f9a3b90d Bump minimum Swift version to 5.7 (#420)
* Bump minimum Swift version to 5.7

Motivation:

Now that Swift 5.9 is GM we should update the supported versions and
remove 5.6

Modifications:

* Update `Package.swift`
* Remove `#if swift(>=5.7)` guards
* Delete the 5.6 docker compose file and make a 5.10 one
* Update 5.10 alloc limits
* Update docs

Result:

Remove support for Swift 5.6, add 5.10
2023-10-11 00:12:29 -07:00
Rick Newton-Rogers 3798fe5f15 Merge pull request from GHSA-qppj-fm5r-hxr3
* Limit rate of permitted RST frames

Motivation:

Large number of stream reset frames may be used as a DoS (Denial of
Service) vector in an attempt to overload the CPU of the handling server.

Modifications:

Introduce an additional DoS heuristic which evaluates the rate of
incoming stream reset frames. If the rate exceeds that which is
permitted then the connection is closed and a `GOAWAY` issued.

The allowed rate is configurable but defaults to 200 resets within 30
seconds. This should be acceptable for most applications.

Result:

Excessive reset frames result in the connection being closed.

* review comments

* further review comments

* add integration test
2023-10-10 13:00:57 +01:00
Rick Newton-Rogers 2140160e95 Remove dependency on SPI (#419)
Motivation:

Remove dependency on SPI so that we can cut a release without
introducing dependency on code subject to change.

Modifications:

Remove all code which introduces a dependency on the NIOAsyncChannel SPI

Result:

Code inside SPI is removed
2023-10-04 13:21:17 +01:00
Rick Newton-Rogers 8275314739 Async stream initializers order matches existing (#415)
Motivation:

When adding in the SPI methods for exposing async sequences of HTTP/2
streams we moved the stream initialization to a subtly different
location so that it was easier to exfiltrate the outputs of those
initialization functions (such as protocol negotiation outputs).

In some cases this broke ordering expectations.

Modifications:

Yield the (optionally wrapped) channels as initializer outputs to the async stream

Result:

Changes only exist within SPI. Async inbound stream channel
initialization now matches previous behavior.
2023-09-11 14:46:40 +01:00
Rick Newton-Rogers 044339de7b HTTP/2 negotiated connection pipeline config (#408)
Motivation:

This continues the work to expose functionality which allows users to interact
with HTTP/2 connections via async abstractions and using structured
concurrency.

This work enables protocol negotiation between HTTP/1.1 and HTTP/2 in its most generic form.

Modifications:

Enable protocol negotiation between HTTP/1.1 and HTTP/2 using typed
negotiation results (`NIOProtocolNegotiationResult`) from the
`NIOTypedApplicationProtocolNegotiationHandler`.
In the HTTP/2 case the negotiation result will return the HTTP/2 connection
channel and the `NIOHTTP2Handler.AsyncStreamMultiplexer` which exposes
inbound streams as an iterable async stream.

Result:

Users will be able to set up negotiated HTTP/1.1 / HTTP/2 connections and
iterate over inbound streams.
2023-07-12 11:07:53 +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
Rick Newton-RogersandGeorge Barnett e0ffed790a HTTP/2 pipeline NIOAsyncChannel pipeline config (#403)
* HTTP/2 pipeline NIOAsyncChannel pipeline config

Motivation:

This continues the work to expose functionality which allows users to interact
with HTTP/2 connections via async abstractions and using structured
concurrency.

We build atop of previous work to configure pipelines to deal with
HTTP/2 (with no protocol negotiation) and to wrap connection/stream
channels with `NIOAsyncChannel`s. This will allow users to iterate over
streams and HTTP2Frames.

Modifications:

Provide functions which configure channels and pipelines with the HTTP2
handler, expose a multiplexer for dealing with streams and wrap
connection and stream channels with `NIOAsyncChannel`s.

Result:

Users will be able to create and interact with HTTP/2 connections via
`NIOAsyncChannel`s. Because HTTP/2 is a negotiated protocol and we do
not yet handle it, this is of limited utility.

* review comments

* Update Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift

Co-authored-by: George Barnett <gbarnett@apple.com>

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2023-07-04 06:21:57 +01:00
Rick Newton-Rogers 83c04dbddb Generic helpers for HTTP/2 async pipelines (#401)
* Store HTTP/2 inbound streams as async sequence

Motivation:

In preparation for exposing APIs which surface HTTP/2 connections and
streams using structured concurrency this PR introduces a store for
inbound HTTP/2 streams.

Modifications:

Define types and methods for storing generic types which wrap `Channels`
corresponding to inbound HTTP/2 streams in an async sequence.

Result:

The new types are not yet exposed, this work introduces part of the
framework for future functionality.

* Expose (as spi) helpers for H2 async pipelines

Motivation:

This PR is the first step in exposing APIs which surface HTTP/2 connections and
streams using structured concurrency. This PR exposes the most abstract
spelling of this concept, assuming no particular types/forms for the
types involved in the stream channel types.

Modifications:

* Store a generic `streamInitializer` on the common inbound initializer
  which is used to initialize inbound streams before yielding them to
the continuation of streams.
* Expose pipeline configuration functions which assume HTTP/2 but
  nothing else about sream channel types.
* Provide internal functions for creating streams without configuring
  them. Configuring leads to activation so it can be helpful to allow
that step to be performed manually once any provided initialization
closures have beenn executed.

Result:

Adopters of the new SPI should be able to create outbound and deal with
inbound HTTP/2 stream channels using async streams.

Outside of SPI there should be no changes.
2023-07-03 11:19:04 +01:00
Rick Newton-Rogers ec955b609b Inline multiplexer calls writability mgr directly (#386)
Motivation:

The `HTTP2StreamChannel` keeps track of how many bytes have been written
and how many are buffered for use in evaluating the 'writability' of the
stream channel. Bytes are considered 'written' or at least no longer
buffered when the write is completed (successfully or errored). In order to make the
determination of when writes are complete across channel handlers we attach a promise to all
writes and deduct adjust the byte counts on completion. Creating and
attaching these promises requires costly allocations.

Modifications:

We can remove the need to create these promises for the new inline
stream multiplexer because the multiplexer and man HTTP2 channel
operations are now all within the `HTTP2ChannelHandler`. This change
calls the `writabilityManager` directly when writes are completed.

Result:

* Fewer allocations are required for HTTP2 writes.
* Writes are considered 'complete' when they leave the `HTTP2ChannelHandler`
2023-04-11 16:40:37 +01:00
Rick Newton-Rogers 795c1d4a48 Expose a functional NIOHTTP2StreamDelegate (#382)
Motivation:

Allow handlers in the pipeline to be notified when an HTTP2 stream is created or
closed.

Modifications:

Store an instance of a `NIOHTTP2StreamDelegate` on the `NIOHTTP2Handler`
and `InlineStreamMultiplexer` so that it may be called when streams are
created or closed.

Added tests.

Result:

`NIOHTTP2Handler`s init'd with a `streamDelegate` will now call into
that delegate's `streamCreated` and `streamClosed` functions.
2023-03-31 09:14:18 +01:00
Rick Newton-Rogers befe813575 Implement direct stream (de)multiplexing in NIOHTTP2ChannelHandler (#380)
Motivation:

Less expensive stream multiplexing. To implement direct stream multiplexing (with an incomplete public API) to break up delivery and allow testing.

Modifications:

* Factor out common inbound stream multiplexer functionality from `HTTP2StreamMultiplexer` into `CommonInboundStreamMultiplexer` (first commit).
* Direct stream multiplexing is implemented as `InlineStreamMultiplexer`. It implements both the `HTTP2InboundStreamMultiplexer` and `HTTP2OutboundStreamMultiplexer` protocols.
* We expose `NIOHTTP2Hander.StreamMultiplexer` as a `public` view over the new multiplexer to allow stream creation.
* Adds various `propagate...` functions to relay signals such as read complete to the child channels held by the inline stream multiplexer.
* Adds a stub for `HTTP2StreamDelegate`  which will be completed in an upcoming PR. It will be responsible for surfacing stream open/close information.
* Adds conveniences to `NIOHTTP2Handler` for setting up a handler using the inline multiplexer
* Duplicate existing tests and modify to use the inline stream multiplexer where appropriate. `SimpleClientServerFramePayloadStreamTests.swift` and `HTTP2FramePayloadStreamMultiplexerTests.swift` were copied and modified

Result:

Default behavior should be unchanged at this time.
2023-03-30 15:45:20 +01:00
Rick Newton-Rogers 98170fdb0c Add multiplexer protocol abstraction in http2 stream channel (#379)
Motivation:

This change prepares for future work to embed the connection multiplexer within the `HTTP2ChannelHandler` which will improve performance by removing the need for passing expensive `InboundUserEvent`s.

Modifications:

This step defines a new protocol (`HTTP2StreamChannelMultiplexer`; named such to avoid confusion with the legacy handler, `HTTP2StreamMultiplexer`) which will later be used to abstract over the inline and legacy multiplexer code but at the moment should not change the logic.

Result:

Behaviour should be unchanged.
2023-03-06 05:49:13 -08:00
Rick Newton-Rogers 20d0634bcb Add no-op NIOHTTP2ConnectionDemultiplexer (#377)
* Add no-op NIOHTTP2ConnectionDemultiplexer

Motivation:

This change prepares for future work to embed the connection demultiplexer within the `HTTP2ChannelHandler` which will improve performance by removing the need for passing expensive `InboundUserEvent`s.

Modifications:

This first step defines a new protocol (`NIOHTTP2ConnectionDemultiplexer`) which will later be used to abstract over the embedded and legacy separate demultiplexer code but at the moment should not change the logic.

Result:

Behaviour should be unchanged.

* review comments

* no longer `nil` out demultiplexer on channelInactive
* restructure calling `pendingUserEvent` & processing events

* demultiplexer funcs use events, not components

NIOHTTP2ConnectionDemultiplexer stream  events now use event types
directly rather than individual parameters which map to the event
fields.
2023-03-06 03:06:42 -08:00
Cory Benfield 38feec96bc Soften errors when seeing inactive before active (#376)
Motivation:

When we started checking active/inactive ordering, we added code that
rejected some channel pipeline state transitions. That code was too
strict: it is absolutely possible to see channelInactive before
channelActive in well-functioning programs.

We'll still call this an error, but we don't need to crash in debug mode
when we see it.

Modifications:

- Made channelInactive before channelActive tolerated.

Result:

More reliable code
2023-03-02 13:34:42 +00:00
Cory Benfield 8dcda68288 Ensure that we fire channelActive and channelInactive in order (#373)
Motivation:

channelActive must always precede channelInactive. Unfortunately, this
isn't guaranteed right now: if we happen to get channelInactive as a
result of our writing the preamble we'll fire them in the wrong order.
Many systems can tolerate this, but we should avoid doing this anyway.

Modifications:

- Added a state enum to keep track of the state we're in
- Use that state enum to ensure we deliver active/inactive in the right
  order
- Additionally police other unexpected active/inactive behaviours

Result:

We'll appropriately police the state.
2023-02-15 15:52:34 +00:00
carolinacass d6656967f3 Use #fileID/#filePath instead of #file (#359)
Motivation:

#fileID introduced in Swift 5.3, so no longer need to use #file anywhere

Modifications:

Changed #file to #filePath or #fileID depending on situation
2022-11-01 08:27:30 -07:00
Cory Benfield cb6f87d9e0 Use Docc for documentation (#351)
Motivation

Documentation is nice, and we can help support users by providing useful
clear docs.

Modifications

Add Docc to 5.6 and later builds
Make sure symbol references work
Add overview docs

Result

Nice rendering docs
2022-08-09 06:44:21 +01: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.
2022-03-10 10:16:17 +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
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
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 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 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 b66a08e4bc Add debugging info to HTTP2StreamChannel too. (#198)
Motivation:

Sometimes folks will want to print things about the HTTP2StreamChannel,
and we should give them the things we can safely get. We also may want a
shorter log for NIOHTTP2Handler as the standard description, with the
wall of text available in the debug description.

Modifications:

- Conform HTTP2StreamChannel to CustomStringConvertible
- Conform NIOHTTP2Handler to CustomDebugStringConvertible.

Result:

Even better debug info.
2020-05-11 13:28:56 +01:00
Cory Benfield 271b5570e8 Improve debugging output for HTTP2Handler. (#197)
Motivation:

Sometimes it's useful to be able to print out objects and see their
internal state. Somehow, HTTP2Handler can't do this.

Modifications:

Add a conformance to HTTP2Handler.

Result:

Awesome debugging output.
2020-04-28 14:11:17 +01:00
Cory Benfield bde711f760 Account for window size of stream closing frames (#174)
Motivation:

Frames that close a stream may consume some of the connection window. We
were not correctly accounting for that in the code, which meant that
frames that carried END_STREAM would not notify the stream multiplexer
that they had consumed connection window space. In the worst cases this
could lead to resource starvation due to consumption of this window
without causing us to emit new WINDOW_UPDATE frames.

Modifications:

StreamClosedEvents should be followed by flow control change events.

Result:

We will correctly update the connection window when a stream is closed.
2019-11-28 08:41:27 +00: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
Cory Benfield 419cd4eece Drop buffered outbound frames when closing. (#135)
Motivation:

While having outbound buffers is necessary, it's pretty important to
clear then when the connection is closed, or the promise will get
leaked. In this case, leaking the promise is usually pretty dang bad,
and tends to cause awkward things like crashes.

Modifications:

- Added hooks to invalidate the CompoundOutboundBuffer.
- Called those hooks in handlerRemoved, where there is no reentrancy
    risk.

Result:

Less risk of runtime crash.
2019-06-05 12:15:52 -07:00
Cory Benfield 8493ed695a Pass changes in SETTINGS_MAX_CONCURRENT_STREAMS to outbound buffer. (#113)
Motivation:

If the remote peer changes SETTINGS_MAX_CONCURRENT_STREAMS we should ensure that we don't
subsequently violate those bounds.

Modifications:

- Plumb in the SETTINGS_MAX_CONCURRENT_STREAMS change.

Result:

SETTINGS_MAX_CONCURRENT_STREAMS works better
2019-05-16 16:07:44 +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 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
Cory Benfield c2c39c63f6 Basic PRIORITY frame validation. (#71)
Motivation:

In the future we'll want to use PRIORITY frames to provide feedback on
how we emit data. Additionally, RFC 7540 forbids certain kinds of
PRIORITY frame, which right now we tolerate receiving. We can design a
minor PRIORITY shim to ensure that we have a code path for PRIORITY data
to be passed around, and then use this shim to enforce RFC 7540's
requirements.

Modifications:

- Added support for PRIORITY frame data inbound.
- Enforce that frames may not establish self-dependency.

Result:

Better policing of RFC 7540 constraints.
2019-03-25 18:09:46 +00:00
Cory Benfield ed9244267b Allow changing MAX_FRAME_SIZE. (#69)
Motivation:

SETTINGS_MAX_FRAME_SIZE is changeable: we should allow that change to
occur.

Modifications:

- Added fields for communicating MAX_FRAME_SIZE changes.
- Update the encoders/decoders as those settings change.
- Throw errors from the encoders/decoders if violated.

Result:

Users and remote peers can change MAX_FRAMES_SIZE.
2019-03-25 18:31:47 +02:00
Cory Benfield 55daa4cd4e Correctly notify StreamMultiplexer of SETTINGS changes. (#67)
Motivation:

The StreamMultiplexer and StreamChannels are responsible for sending
WINDOW_UPDATE frames, but they were never told if the user changed the
value of SETTINGS_INITIAL_WINDOW_SIZE. They should be.

Modifications:

- Send user events when SETTINGS_INITIAL_WINDOW_SIZE changes.
- Use those window events to change the target window size in
    HTTP2StreamChannel.
- Keep track of the last stream window size we knew.

Result:

Less chance of flow control mess.
2019-03-15 17:37:00 +00:00
Cory Benfield 9e07639b44 Respect changes to INITIAL_WINDOW_SIZE in outbound buffer. (#64)
Motivation:

When the remote peer changes SETTINGS_INITIAL_WINDOW_SIZE, this change
affects the flow control window sizes of all existing streams (as though
they were created with this new initial window size). We should respect
those flow control changes.

Modifications:

- Propagated changes in SETTINGS_INITIAL_WINDOW_SIZE.
- Made NIOHTTP2ConnectionStateChange internal.
- Added support for changing initial window size.

Result:

SETTINGS frames that change initial window size now work properly.
2019-03-15 14:29:53 +00: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 38516fe870 Collapse HTTP/2 channel handlers. (#52)
Motivation:

We attempted to use the NIO channel pipeline to spread out the HTTP/2
implementation across a number of channel handlers. Unfortunately, due
to the concerns of reentrancy it's not really safely possible to do this:
it's too easy for the pipeline ordering to become so confused that the
implementation ends up incorrect.

For this reason, we are going to squash together the three handlers that
provide a complete HTTP/2 protocol implementation into just one.

Modifications:

- Move the ConcurrentStreamsHandler and FlowControlHandler into the
    HTTP2Handler.
- Update setup and test code accordingly.

Result:

More correct implementation
2019-03-13 16:04:38 +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
Johannes Weiss ffe5102b7e update to latest NIO 2 code (#45)
Motivation:

Code should compile and have the latest NIO 2 API.

Modifications:

- rename `ctx` to `context`

Result:

compiles again
2019-02-26 12:57:39 +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