Commit Graph
25 Commits
Author SHA1 Message Date
Gus Cairo 623755c0cd Enable warnings as errors (#517) 2025-05-14 14:17:48 +01:00
George Barnett 61f6aa4142 Add explicit Sendable annotations (#505) 2025-03-27 14:01: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
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
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
George Barnett a0224f3d20 Discard read bytes when accumulating continuation frames (#444)
Motivation:

When accumulating sequences of CONTINUATION frames, each frame is parsed
from a buffer. These bytes are read when the CONTINUATION frame is
parsed, but if more CONTINUATION frames follow then the buffer isn't
reset. This means that long sequences of CONTINUATION frames can result
in a larger than necessary buffer where most of the contents have
already been read.

Modifications:

- Discard the bytes of the accumulation buffer when transitioning back
  to AccumulatingHeaderBlockFragmentsParserState if more than half of
  the buffer has been read.

Result:

Lower memory footprint when parsing sequences of CONTINUATION frames.
2024-06-29 08:20:48 -04:00
Stefana-Ioana Dranca c6afe04165 Avoid CoW while processing the next state when HTTP2FrameDecoder decodes (#438)
Motivation:

CoWs appear when switching over the current state of the parser and holding it while also modifying it - inside `processNExtState()`. Following `append(bytes: ByteBuffer)`'s pattern, we should use a function that sets the state to an intermediary one with no associated data, before making the transformations.

Modifications:
- created the `avoidParserCoW()` helper function for the throwing functions
- used it in the switch cases inside `processNextState()`

Result:

CoW will be avoided when changing the state of the HTTP2FrameDecoder when decoding, so we won't have unnecessary heap allocations.
2024-04-17 09:08:28 +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 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.
2022-03-10 10:16:17 +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 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
Johannes Weiss c1bfb7ce3f fix new NIO and new Swift compiler warnings (#179) 2019-12-10 12:45:48 +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 6a97259a5d Avoid double-counting of flow controlled length of synthesised data frames. (#114)
Motivation:

When synthesising data frames we try to emit the flow controlled length of the entire real
data frame on the first synthetic frame. This allows us to correctly police the window management
of that frame, while still synthesising frames.

However, @glbrntt spotted that we were incorrectly repeatedly counting the flow controlled length
of a partial frame. A patch that had been previously added to ensure we only counted it once was
not working correctly.

Modifications:

- Adjusted the location of the call to flowControlledLength.

Result:

Correct accounting of flow controlled length
2019-05-10 16:56:14 +01:00
Cory Benfield c383bfc958 Avoid CoW when appending inbound frame bytes. (#111)
Motivation:

This is basically a similar issue to #104: we have a CoW data structure (ByteBuffer) in some of
these states, and when calling append on them they force an unnecessary CoW. We can reproduce the
fix from that patch, which is to define an empty state and swap into it before we run the append.
We also define a helper that ensures that we don't screw this up.

Modifications:

- Added new appending state to HTTP2FrameDecoder
- Added helpers for avoiding a CoW
- Avoided CoW in HTTP2FrameDecoder.

Result:

Fewer unnecessary copies
2019-05-03 13:43:04 +01:00
Cory Benfield 4cb9d07b54 Avoid unnecessary heap allocation when parsing frame headers. (#107)
Motivation:

As noted in #105, I spotted that we were heap-allocating an array
when parsing the frame header. That heap allocation isn't necessary, we
can just write directly into an Int, which should save us some heap spray.

Modifications:

- Rewrote code to avoid heap allocating array and instead to use Int.
- Elided some bounds checks by using an unsafe pointer, since I was
    already here and it saved about 1% performance in a hot loop.

Result:

Fewer heap allocations on the hot code path.
2019-04-18 17:32:17 +01:00
George Barnett 99e35a8ebb Allow zero length SETTINGS frames to be parsed. (#88)
Motivation:

Zero length SETTINGS frames are permitted by RFC 7540 but the frame
parser currently throws a FRAME_SIZE_ERROR.

Modifications:

- Allow zero length SETTINGS frames to be parsed
- Added a test

Result:

Parsing zero length SETTINGS frames don't throw an error.
2019-04-10 17:20:24 +01: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 1138881931 CONTINUATION frames must be for the correct stream. (#66)
Motivation:

We mustn't allow CONTINUATION frames to be sent on invalid stream IDs.

Modifications:

- Police that the CONTINUATION frame raw stream ID matches the previous
    frame's raw stream ID.

Result:

Better conformance to the RFC
2019-03-15 15:45:45 +00:00
Cory Benfield d9f1131749 Be emphatic about remote peers making mistakes. (#65)
Motivation:

Receiving a CONTINUATION frame at the wrong stage of a connection is
a PROTOCOL_ERROR, but out of an abundance of caution we were categorising
it as an INTERNAL_ERROR. We should be more confident about our error
categories.

Modifications:

- Changed INTERNAL_ERROR to PROTOCOL_ERROR.
- Added a test for this error case.

Result:

More confidence, more style, more pizazz.
2019-03-15 14:37:17 +00:00
George Barnett ddf2c29493 Support DATA frames with zero-length application data (#51)
Motivation:

DATA frames with zero-length application data would cause the state
machine to wait for more bytes to continue. This could cause consuming
code to deadlock.

Modifications:

Updated the frame parser to only require more data when there are
remaining bytes in the payload and there are zero readable bytes.

Result:

DATA frames with zero-length application data can be parsed.
2019-03-15 12:34:29 +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