Files
swift-nio-http2/Sources/NIOHPACK/IndexedHeaderTable.swift
T
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

173 lines
8.3 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
/// The unified header table used by HTTP/2, encompassing both static and dynamic tables.
public struct IndexedHeaderTable {
// private but tests
@usableFromInline
let staticTable: HeaderTableStorage
@usableFromInline
var dynamicTable: DynamicHeaderTable
/// Creates a new header table, optionally specifying a maximum size for the dynamic
/// portion of the table.
///
/// - Parameter maxDynamicTableSize: Maximum size of the dynamic table. Default = 4096.
init(allocator: ByteBufferAllocator, maxDynamicTableSize: Int = DynamicHeaderTable.defaultSize) {
self.staticTable = HeaderTableStorage(allocator: allocator, staticHeaderList: StaticHeaderTable)
self.dynamicTable = DynamicHeaderTable(allocator: allocator, maximumLength: maxDynamicTableSize)
}
/// Obtains the header key/value pair at the given index within the table.
///
/// - note: Per RFC 7541, this uses a *1-based* index.
/// - Parameter index: The index to query.
/// - Returns: A tuple containing the name and value of the stored header.
/// - Throws: `NIOHPACKErrors.InvalidHeaderIndex` if the supplied index was invalid.
public func header(at index: Int) throws -> (name: String, value: String) {
let (nameView, valueView) = try self.headerViews(at: index)
return (String(decoding: nameView, as: UTF8.self), String(decoding: valueView, as: UTF8.self))
}
/// Obtains the header key/value pair at the given index within the table as sequences of
/// raw bytes.
///
/// - note: Per RFC 7541, this uses a *1-based* index.
/// - Parameter index: The index to query.
/// - Returns: A tuple containing the name and value of the stored header.
/// - Throws: `NIOHPACKErrors.InvalidHeaderIndex` if the supplied index was invalid.
public func headerViews(at index: Int) throws -> (name: ByteBufferView, value: ByteBufferView) {
let result: (ByteBufferView, ByteBufferView)
if index < self.staticTable.count {
let entry = self.staticTable[index]
result = (self.staticTable.view(of: entry.name), self.staticTable.view(of: entry.value))
} else if index - self.staticTable.count < self.dynamicTable.count {
let entry = self.dynamicTable[index - self.staticTable.count]
result = (self.dynamicTable.view(of: entry.name), self.dynamicTable.view(of: entry.value))
} else {
throw NIOHPACKErrors.InvalidHeaderIndex(suppliedIndex: index, availableIndex: self.staticTable.count + self.dynamicTable.count - 1)
}
return result
}
/// Searches the table to locate an existing header with the given name and value. If
/// no item exists that contains a matching value, it will return the index of the first
/// item with a matching header name instead, to be encoded as index+value.
///
/// - Parameters:
/// - name: The name of the header to locate.
/// - value: The value for which to search.
/// - Returns: A tuple containing the index of any located header, and a boolean indicating
/// whether the item at that index also contains a matching value. Returns `nil`
/// if no match could be found.
public func firstHeaderMatch(for name: String, value: String?) -> (index: Int, matchesValue: Bool)? {
return self.firstHeaderMatch(for: name.utf8, value: value?.utf8)
}
func firstHeaderMatch<Name: Collection, Value: Collection>(for name: Name, value: Value?) -> (index: Int, matchesValue: Bool)? where Name.Element == UInt8, Value.Element == UInt8 {
guard let value = value else {
// AnySequence only has `first(where:)` method, not `first` property.
return self.staticTable.firstIndex(matching: name).map { ($0, false) }
}
var firstHeaderIndex: Int? = nil
for index in self.staticTable.indices(matching: name) {
// we've found a name, at least
if firstHeaderIndex == nil {
firstHeaderIndex = index
}
if self.staticTable.view(of: self.staticTable[index].value).matches(value) {
return (index, true)
}
}
// no complete match: search the dynamic table now
if let result = self.dynamicTable.findExistingHeader(named: name, value: value) {
if let staticIndex = firstHeaderIndex, result.containsValue == false {
// Dynamic table can't match the value, and we have a name match in the static
// table. In this case, we prefer the static table.
return (staticIndex, false)
} else {
// Either no match in the static table, or the dynamic table has a header with
// a matching value. Return that, but update the index appropriately.
return (result.index + StaticHeaderTable.count, result.containsValue)
}
} else if let staticIndex = firstHeaderIndex {
// nothing in the dynamic table, but the static table had a name match
return (staticIndex, false)
} else {
// no match anywhere, you'll have to encode the whole thing
return nil
}
}
/// Appends a header to the table.
///
/// This call may result in an empty table, as per RFC 7541 § 4.4:
/// > "It is not an error to attempt to add an entry that is larger than the maximum size;
/// > an attempt to add an entry larger than the maximum size causes the table to be
/// > emptied of all existing entries and results in an empty table."
///
/// - Parameters:
/// - name: The name of the header to insert.
/// - value: The value of the header to insert.
/// - Returns: `true` if the header was added to the table, `false` if not.
public mutating func add(headerNamed name: String, value: String) throws {
try self.add(headerNamed: name.utf8, value: value.utf8)
}
/// Appends a header to the table.
///
/// This call may result in an empty table, as per RFC 7541 § 4.4:
/// > "It is not an error to attempt to add an entry that is larger than the maximum size;
/// > an attempt to add an entry larger than the maximum size causes the table to be
/// > emptied of all existing entries and results in an empty table."
///
/// - Parameters:
/// - name: A sequence of contiguous bytes containing the name of the header to insert.
/// - value: A sequence of contiguous bytes containing the value of the header to insert.
public mutating func add<Name: Collection, Value: Collection>(headerNamed name: Name, value: Value) throws where Name.Element == UInt8, Value.Element == UInt8 {
try self.dynamicTable.addHeader(named: name, value: value)
}
/// Internal for test access.
internal func dumpHeaders() -> String {
return "\(staticTable.dumpHeaders())\n\(dynamicTable.dumpHeaders())"
}
/// The length, in bytes, of the dynamic portion of the header table.
public var dynamicTableLength: Int {
return self.dynamicTable.length
}
/// The current allowed length of the dynamic portion of the header table. May be
/// less than the current protocol-assigned maximum supplied by a SETTINGS frame.
public var dynamicTableAllowedLength: Int {
get { return self.dynamicTable.allowedLength }
set { self.dynamicTable.allowedLength = newValue }
}
/// The hard limit on the size to which the dynamic table may grow. Only a SETTINGS
/// frame can change this: it can't grow beyond this size due to changes within
/// header blocks.
public var maxDynamicTableLength: Int {
get { return self.dynamicTable.maximumTableLength }
set { self.dynamicTable.maximumTableLength = newValue }
}
}