mirror of
https://github.com/apple/swift-nio
synced 2026-11-30 05:28:44 +00:00
Introduce new typed HTTPServerUpgrader and WebSocketServerUpgrader (#2517)
* Introduce new typed `HTTPServerUpgrader` and `WebSocketServerUpgrader` # Motivation With our new `NIOAsyncChannel` and typed bootstrap APIs we want to be able to let users spell out their pipeline in a typed way. Pipelines can contain handlers that have to make a forking decision such as HTTP upgrading. Our current `HTTPServerUpgradeHandler` is one of those handlers but it lacks strict typing. To interact nicely with our new typed APIs we need to have a new variant of the `HTTPServerUpgradeHandler` that can carry type information. # Modification This PR adds a few things: 1. A new `NIOTypedHTTPServerUpgradeHandler` + `NIOTypedHTTPServeProtocolUpgrader`. I also moved the state handling logic to a separate state machine. I thought about unifying the state machines of the _old_ handler and the new one but they differ in behaviour which makes the state machine more complicated. 2. A new `NIOTypedWebSocketServerUpgrader` that conforms to `NIOTypedHTTPServerProtocolUpgrader` 3. An overhauled WebSocket server example that fully uses Concurrency. # Result We now have a way to fully type the server side of HTTP protocol upgrading. Code review Update parameter names for new API and fix example * Introduce new configuration struct and rename to `UpgradablePipeline` * Review comments
This commit is contained in:
1 parent
67553a7d6d
commit
de07e573d6
10 files changed
+1985
-381
No files matched your search
@@ -0,0 +1,148 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
|
||||
// MARK: - Server pipeline configuration
|
||||
|
||||
/// Configuration for an upgradable HTTP pipeline.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public struct NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult: Sendable> {
|
||||
/// Whether to provide assistance handling HTTP clients that pipeline
|
||||
/// their requests. Defaults to `true`. If `false`, users will need to handle clients that pipeline themselves.
|
||||
public var enablePipelining = true
|
||||
|
||||
/// Whether to provide assistance handling protocol errors (e.g. failure to parse the HTTP
|
||||
/// request) by sending 400 errors. Defaults to `true`.
|
||||
public var enableErrorHandling = true
|
||||
|
||||
/// Whether to validate outbound response headers to confirm that they are
|
||||
/// spec compliant. Defaults to `true`.
|
||||
public var enableResponseHeaderValidation = true
|
||||
|
||||
/// The configuration for the ``HTTPResponseEncoder``.
|
||||
public var httpResponseEncoderConfiguration = HTTPResponseEncoder.Configuration()
|
||||
|
||||
/// The configuration for the ``NIOTypedHTTPServerUpgradeHandler``.
|
||||
public var upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
|
||||
|
||||
/// Initializes a new ``NIOUpgradableHTTPServerPipelineConfiguration`` with default values.
|
||||
///
|
||||
/// The current defaults provide the following features:
|
||||
/// 1. Assistance handling clients that pipeline HTTP requests.
|
||||
/// 2. Assistance handling protocol errors.
|
||||
/// 3. Outbound header fields validation to protect against response splitting attacks.
|
||||
/// 4. HTTP protocol upgrades.
|
||||
///
|
||||
/// The defaults will likely be extended in the future and we recommend to use this initializer to ensure
|
||||
/// you get newer features automatically.
|
||||
public init(
|
||||
upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
|
||||
) {
|
||||
self.upgradeConfiguration = upgradeConfiguration
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelPipeline {
|
||||
/// Configure a `ChannelPipeline` for use as an HTTP server.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - configuration: The HTTP pipeline's configuration.
|
||||
/// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. The future contains an `EventLoopFuture`
|
||||
/// that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
|
||||
configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
|
||||
) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
|
||||
self._configureUpgradableHTTPServerPipeline(
|
||||
configuration: configuration
|
||||
)
|
||||
}
|
||||
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
private func _configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
|
||||
configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
|
||||
) -> EventLoopFuture<EventLoopFuture<UpgradeResult>> {
|
||||
let future: EventLoopFuture<EventLoopFuture<UpgradeResult>>
|
||||
|
||||
if self.eventLoop.inEventLoop {
|
||||
let result = Result<EventLoopFuture<UpgradeResult>, Error> {
|
||||
try self.syncOperations.configureUpgradableHTTPServerPipeline(
|
||||
configuration: configuration
|
||||
)
|
||||
}
|
||||
future = self.eventLoop.makeCompletedFuture(result)
|
||||
} else {
|
||||
future = self.eventLoop.submit {
|
||||
try self.syncOperations.configureUpgradableHTTPServerPipeline(
|
||||
configuration: configuration
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return future
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelPipeline.SynchronousOperations {
|
||||
/// Configure a `ChannelPipeline` for use as an HTTP server.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - configuration: The HTTP pipeline's configuration.
|
||||
/// - Returns: An `EventLoopFuture` that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public func configureUpgradableHTTPServerPipeline<UpgradeResult: Sendable>(
|
||||
configuration: NIOUpgradableHTTPServerPipelineConfiguration<UpgradeResult>
|
||||
) throws -> EventLoopFuture<UpgradeResult> {
|
||||
self.eventLoop.assertInEventLoop()
|
||||
|
||||
let responseEncoder = HTTPResponseEncoder(configuration: configuration.httpResponseEncoderConfiguration)
|
||||
let requestDecoder = ByteToMessageHandler(HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes))
|
||||
|
||||
var extraHTTPHandlers: [RemovableChannelHandler] = [requestDecoder]
|
||||
extraHTTPHandlers.reserveCapacity(3)
|
||||
|
||||
try self.addHandler(responseEncoder)
|
||||
try self.addHandler(requestDecoder)
|
||||
|
||||
if configuration.enablePipelining {
|
||||
let pipeliningHandler = HTTPServerPipelineHandler()
|
||||
try self.addHandler(pipeliningHandler)
|
||||
extraHTTPHandlers.append(pipeliningHandler)
|
||||
}
|
||||
|
||||
if configuration.enableResponseHeaderValidation {
|
||||
let headerValidationHandler = NIOHTTPResponseHeadersValidator()
|
||||
try self.addHandler(headerValidationHandler)
|
||||
extraHTTPHandlers.append(headerValidationHandler)
|
||||
}
|
||||
|
||||
if configuration.enableErrorHandling {
|
||||
let errorHandler = HTTPServerProtocolErrorHandler()
|
||||
try self.addHandler(errorHandler)
|
||||
extraHTTPHandlers.append(errorHandler)
|
||||
}
|
||||
|
||||
let upgrader = NIOTypedHTTPServerUpgradeHandler(
|
||||
httpEncoder: responseEncoder,
|
||||
extraHTTPHandlers: extraHTTPHandlers,
|
||||
upgradeConfiguration: configuration.upgradeConfiguration
|
||||
)
|
||||
try self.addHandler(upgrader)
|
||||
|
||||
return upgrader.upgradeResultFuture
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@_spi(AsyncChannel) import NIOCore
|
||||
|
||||
/// An object that implements `NIOTypedHTTPServerProtocolUpgrader` knows how to handle HTTP upgrade to
|
||||
/// a protocol on a server-side channel.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public protocol NIOTypedHTTPServerProtocolUpgrader<UpgradeResult> {
|
||||
associatedtype UpgradeResult
|
||||
|
||||
/// The protocol this upgrader knows how to support.
|
||||
var supportedProtocol: String { get }
|
||||
|
||||
/// All the header fields the protocol needs in the request to successfully upgrade. These header fields
|
||||
/// will be provided to the handler when it is asked to handle the upgrade. They will also be validated
|
||||
/// against the inbound request's `Connection` header field.
|
||||
var requiredUpgradeHeaders: [String] { get }
|
||||
|
||||
/// Builds the upgrade response headers. Should return any headers that need to be supplied to the client
|
||||
/// in the 101 Switching Protocols response. If upgrade cannot proceed for any reason, this function should
|
||||
/// return a failed future.
|
||||
func buildUpgradeResponse(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead,
|
||||
initialResponseHeaders: HTTPHeaders
|
||||
) -> EventLoopFuture<HTTPHeaders>
|
||||
|
||||
/// Called when the upgrade response has been flushed. At this time it is safe to mutate the channel pipeline
|
||||
/// to add whatever channel handlers are required. Until the returned `EventLoopFuture` succeeds, all received
|
||||
/// data will be buffered.
|
||||
func upgrade(
|
||||
channel: Channel,
|
||||
upgradeRequest: HTTPRequestHead
|
||||
) -> EventLoopFuture<UpgradeResult>
|
||||
}
|
||||
|
||||
/// The upgrade configuration for the ``NIOTypedHTTPServerUpgradeHandler``.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public struct NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult: Sendable> {
|
||||
/// The array of potential upgraders.
|
||||
public var upgraders: [any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>]
|
||||
|
||||
/// A closure that is run once it is determined that no protocol upgrade is happening. This can be used
|
||||
/// to configure handlers that expect HTTP.
|
||||
public var notUpgradingCompletionHandler: @Sendable (Channel) -> EventLoopFuture<UpgradeResult>
|
||||
|
||||
public init(
|
||||
upgraders: [any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>],
|
||||
notUpgradingCompletionHandler: @Sendable @escaping (Channel) -> EventLoopFuture<UpgradeResult>
|
||||
) {
|
||||
self.upgraders = upgraders
|
||||
self.notUpgradingCompletionHandler = notUpgradingCompletionHandler
|
||||
}
|
||||
}
|
||||
|
||||
/// A server-side channel handler that receives HTTP requests and optionally performs an HTTP-upgrade.
|
||||
///
|
||||
/// Removes itself from the channel pipeline after the first inbound request on the connection, regardless of
|
||||
/// whether the upgrade succeeded or not.
|
||||
///
|
||||
/// This handler behaves a bit differently from its Netty counterpart because it does not allow upgrade
|
||||
/// on any request but the first on a connection. This is primarily to handle clients that pipeline: it's
|
||||
/// sufficiently difficult to ensure that the upgrade happens at a safe time while dealing with pipelined
|
||||
/// requests that we choose to punt on it entirely and not allow it. As it happens this is mostly fine:
|
||||
/// the odds of someone needing to upgrade midway through the lifetime of a connection are very low.
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
@_spi(AsyncChannel)
|
||||
public final class NIOTypedHTTPServerUpgradeHandler<UpgradeResult: Sendable>: ChannelInboundHandler, RemovableChannelHandler {
|
||||
public typealias InboundIn = HTTPServerRequestPart
|
||||
public typealias InboundOut = HTTPServerRequestPart
|
||||
public typealias OutboundOut = HTTPServerResponsePart
|
||||
|
||||
private let upgraders: [String: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>]
|
||||
private let notUpgradingCompletionHandler: @Sendable (Channel) -> EventLoopFuture<UpgradeResult>
|
||||
private let httpEncoder: HTTPResponseEncoder
|
||||
private let extraHTTPHandlers: [RemovableChannelHandler]
|
||||
private var stateMachine = NIOTypedHTTPServerUpgraderStateMachine<UpgradeResult>()
|
||||
|
||||
private var _upgradeResultPromise: EventLoopPromise<UpgradeResult>?
|
||||
private var upgradeResultPromise: EventLoopPromise<UpgradeResult> {
|
||||
precondition(
|
||||
self._upgradeResultPromise != nil,
|
||||
"Tried to access the upgrade result before the handler was added to a pipeline"
|
||||
)
|
||||
return self._upgradeResultPromise!
|
||||
}
|
||||
|
||||
/// The upgrade future which will be completed once protocol upgrading has been done.
|
||||
public var upgradeResultFuture: EventLoopFuture<UpgradeResult> {
|
||||
self.upgradeResultPromise.futureResult
|
||||
}
|
||||
|
||||
/// Create a ``NIOTypedHTTPServerUpgradeHandler``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - httpEncoder: The ``HTTPResponseEncoder`` encoding responses from this handler and which will
|
||||
/// be removed from the pipeline once the upgrade response is sent. This is used to ensure
|
||||
/// that the pipeline will be in a clean state after upgrade.
|
||||
/// - extraHTTPHandlers: Any other handlers that are directly related to handling HTTP. At the very least
|
||||
/// this should include the `HTTPDecoder`, but should also include any other handler that cannot tolerate
|
||||
/// receiving non-HTTP data.
|
||||
/// - upgradeConfiguration: The upgrade configuration.
|
||||
public init(
|
||||
httpEncoder: HTTPResponseEncoder,
|
||||
extraHTTPHandlers: [RemovableChannelHandler],
|
||||
upgradeConfiguration: NIOTypedHTTPServerUpgradeConfiguration<UpgradeResult>
|
||||
) {
|
||||
var upgraderMap = [String: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>]()
|
||||
for upgrader in upgradeConfiguration.upgraders {
|
||||
upgraderMap[upgrader.supportedProtocol.lowercased()] = upgrader
|
||||
}
|
||||
self.upgraders = upgraderMap
|
||||
self.notUpgradingCompletionHandler = upgradeConfiguration.notUpgradingCompletionHandler
|
||||
self.httpEncoder = httpEncoder
|
||||
self.extraHTTPHandlers = extraHTTPHandlers
|
||||
}
|
||||
|
||||
public func handlerAdded(context: ChannelHandlerContext) {
|
||||
self._upgradeResultPromise = context.eventLoop.makePromise(of: UpgradeResult.self)
|
||||
}
|
||||
|
||||
public func handlerRemoved(context: ChannelHandlerContext) {
|
||||
switch self.stateMachine.handlerRemoved() {
|
||||
case .failUpgradePromise:
|
||||
self.upgradeResultPromise.fail(ChannelError.inappropriateOperationForState)
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
||||
switch self.stateMachine.channelReadData(data) {
|
||||
case .unwrapData:
|
||||
let requestPart = self.unwrapInboundIn(data)
|
||||
self.channelRead(context: context, requestPart: requestPart)
|
||||
|
||||
case .fireChannelRead:
|
||||
context.fireChannelRead(data)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func channelRead(context: ChannelHandlerContext, requestPart: HTTPServerRequestPart) {
|
||||
switch self.stateMachine.channelReadRequestPart(requestPart) {
|
||||
case .failUpgradePromise(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
|
||||
case .runNotUpgradingInitializer:
|
||||
self.notUpgradingCompletionHandler(context.channel)
|
||||
.hop(to: context.eventLoop)
|
||||
.whenComplete { result in
|
||||
self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: nil)
|
||||
}
|
||||
|
||||
case .findUpgrader(let head, let requestedProtocols, let allHeaderNames, let connectionHeader):
|
||||
let protocolIterator = requestedProtocols.makeIterator()
|
||||
self.handleUpgradeForProtocol(
|
||||
context: context,
|
||||
protocolIterator: protocolIterator,
|
||||
request: head,
|
||||
allHeaderNames: allHeaderNames,
|
||||
connectionHeader: connectionHeader
|
||||
).whenComplete { result in
|
||||
context.eventLoop.assertInEventLoop()
|
||||
self.findingUpgradeCompleted(context: context, requestHead: head, result)
|
||||
}
|
||||
|
||||
case .startUpgrading(let upgrader, let requestHead, let responseHeaders, let proto):
|
||||
self.startUpgrading(
|
||||
context: context,
|
||||
upgrader: upgrader,
|
||||
requestHead: requestHead,
|
||||
responseHeaders: responseHeaders,
|
||||
proto: proto
|
||||
)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func upgradingHandlerCompleted(
|
||||
context: ChannelHandlerContext,
|
||||
_ result: Result<UpgradeResult, Error>,
|
||||
requestHeadAndProtocol: (HTTPRequestHead, String)?
|
||||
) {
|
||||
switch self.stateMachine.upgradingHandlerCompleted(result) {
|
||||
case .fireErrorCaughtAndRemoveHandler(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
|
||||
case .fireErrorCaughtAndStartUnbuffering(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
self.unbuffer(context: context)
|
||||
|
||||
case .startUnbuffering(let value):
|
||||
if let requestHeadAndProtocol = requestHeadAndProtocol {
|
||||
context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: requestHeadAndProtocol.1, upgradeRequest: requestHeadAndProtocol.0))
|
||||
}
|
||||
self.upgradeResultPromise.succeed(value)
|
||||
self.unbuffer(context: context)
|
||||
|
||||
case .removeHandler(let value):
|
||||
if let requestHeadAndProtocol = requestHeadAndProtocol {
|
||||
context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: requestHeadAndProtocol.1, upgradeRequest: requestHeadAndProtocol.0))
|
||||
}
|
||||
self.upgradeResultPromise.succeed(value)
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to upgrade a single protocol.
|
||||
///
|
||||
/// Will recurse through `protocolIterator` if upgrade fails.
|
||||
private func handleUpgradeForProtocol(
|
||||
context: ChannelHandlerContext,
|
||||
protocolIterator: Array<String>.Iterator,
|
||||
request: HTTPRequestHead,
|
||||
allHeaderNames: Set<String>,
|
||||
connectionHeader: Set<String>
|
||||
) -> EventLoopFuture<(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)?> {
|
||||
// We want a local copy of the protocol iterator. We'll pass it to the next invocation of the function.
|
||||
var protocolIterator = protocolIterator
|
||||
guard let proto = protocolIterator.next() else {
|
||||
// We're done! No suitable protocol for upgrade.
|
||||
return context.eventLoop.makeSucceededFuture(nil)
|
||||
}
|
||||
|
||||
guard let upgrader = self.upgraders[proto.lowercased()] else {
|
||||
return self.handleUpgradeForProtocol(context: context, protocolIterator: protocolIterator, request: request, allHeaderNames: allHeaderNames, connectionHeader: connectionHeader)
|
||||
}
|
||||
|
||||
let requiredHeaders = Set(upgrader.requiredUpgradeHeaders.map { $0.lowercased() })
|
||||
guard requiredHeaders.isSubset(of: allHeaderNames) && requiredHeaders.isSubset(of: connectionHeader) else {
|
||||
return self.handleUpgradeForProtocol(context: context, protocolIterator: protocolIterator, request: request, allHeaderNames: allHeaderNames, connectionHeader: connectionHeader)
|
||||
}
|
||||
|
||||
let responseHeaders = self.buildUpgradeHeaders(protocol: proto)
|
||||
return upgrader.buildUpgradeResponse(
|
||||
channel: context.channel,
|
||||
upgradeRequest: request,
|
||||
initialResponseHeaders: responseHeaders
|
||||
)
|
||||
.hop(to: context.eventLoop)
|
||||
.map { (upgrader, $0, proto) }
|
||||
.flatMapError { error in
|
||||
// No upgrade here. We want to fire the error down the pipeline, and then try another loop iteration.
|
||||
context.fireErrorCaught(error)
|
||||
return self.handleUpgradeForProtocol(context: context, protocolIterator: protocolIterator, request: request, allHeaderNames: allHeaderNames, connectionHeader: connectionHeader)
|
||||
}
|
||||
}
|
||||
|
||||
private func findingUpgradeCompleted(
|
||||
context: ChannelHandlerContext,
|
||||
requestHead: HTTPRequestHead,
|
||||
_ result: Result<(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)?, Error>
|
||||
) {
|
||||
switch self.stateMachine.findingUpgraderCompleted(requestHead: requestHead, result) {
|
||||
case .startUpgrading(let upgrader, let responseHeaders, let proto):
|
||||
self.startUpgrading(
|
||||
context: context,
|
||||
upgrader: upgrader,
|
||||
requestHead: requestHead,
|
||||
responseHeaders: responseHeaders,
|
||||
proto: proto
|
||||
)
|
||||
|
||||
case .runNotUpgradingInitializer:
|
||||
self.notUpgradingCompletionHandler(context.channel)
|
||||
.hop(to: context.eventLoop)
|
||||
.whenComplete { result in
|
||||
self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: nil)
|
||||
}
|
||||
|
||||
case .fireErrorCaughtAndStartUnbuffering(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
self.unbuffer(context: context)
|
||||
|
||||
case .fireErrorCaughtAndRemoveHandler(let error):
|
||||
self.upgradeResultPromise.fail(error)
|
||||
context.fireErrorCaught(error)
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func startUpgrading(
|
||||
context: ChannelHandlerContext,
|
||||
upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>,
|
||||
requestHead: HTTPRequestHead,
|
||||
responseHeaders: HTTPHeaders,
|
||||
proto: String
|
||||
) {
|
||||
// Before we finish the upgrade we have to remove the HTTPDecoder and any other non-Encoder HTTP
|
||||
// handlers from the pipeline, to prevent them parsing any more data. We'll buffer the data until
|
||||
// that completes.
|
||||
// While there are a lot of Futures involved here it's quite possible that all of this code will
|
||||
// actually complete synchronously: we just want to program for the possibility that it won't.
|
||||
// Once that's done, we send the upgrade response, then remove the HTTP encoder, then call the
|
||||
// internal handler, then call the user code, and then finally when the user code is done we do
|
||||
// our final cleanup steps, namely we replay the received data we buffered in the meantime and
|
||||
// then remove ourselves from the pipeline.
|
||||
self.removeExtraHandlers(context: context).flatMap {
|
||||
self.sendUpgradeResponse(context: context, responseHeaders: responseHeaders)
|
||||
}.flatMap {
|
||||
context.pipeline.removeHandler(self.httpEncoder)
|
||||
}.flatMap { () -> EventLoopFuture<UpgradeResult> in
|
||||
return upgrader.upgrade(channel: context.channel, upgradeRequest: requestHead)
|
||||
}.hop(to: context.eventLoop)
|
||||
.whenComplete { result in
|
||||
self.upgradingHandlerCompleted(context: context, result, requestHeadAndProtocol: (requestHead, proto))
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends the 101 Switching Protocols response for the pipeline.
|
||||
private func sendUpgradeResponse(context: ChannelHandlerContext, responseHeaders: HTTPHeaders) -> EventLoopFuture<Void> {
|
||||
var response = HTTPResponseHead(version: .http1_1, status: .switchingProtocols)
|
||||
response.headers = responseHeaders
|
||||
return context.writeAndFlush(wrapOutboundOut(HTTPServerResponsePart.head(response)))
|
||||
}
|
||||
|
||||
/// Builds the initial mandatory HTTP headers for HTTP upgrade responses.
|
||||
private func buildUpgradeHeaders(`protocol`: String) -> HTTPHeaders {
|
||||
return HTTPHeaders([("connection", "upgrade"), ("upgrade", `protocol`)])
|
||||
}
|
||||
|
||||
/// Removes any extra HTTP-related handlers from the channel pipeline.
|
||||
private func removeExtraHandlers(context: ChannelHandlerContext) -> EventLoopFuture<Void> {
|
||||
guard self.extraHTTPHandlers.count > 0 else {
|
||||
return context.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
|
||||
return .andAllSucceed(self.extraHTTPHandlers.map { context.pipeline.removeHandler($0) },
|
||||
on: context.eventLoop)
|
||||
}
|
||||
|
||||
private func unbuffer(context: ChannelHandlerContext) {
|
||||
while true {
|
||||
switch self.stateMachine.unbuffer() {
|
||||
case .fireChannelRead(let data):
|
||||
context.fireChannelRead(data)
|
||||
|
||||
case .fireChannelReadCompleteAndRemoveHandler:
|
||||
context.fireChannelReadComplete()
|
||||
context.pipeline.removeHandler(self, promise: nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 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 DequeModule
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
|
||||
struct NIOTypedHTTPServerUpgraderStateMachine<UpgradeResult> {
|
||||
@usableFromInline
|
||||
enum State {
|
||||
/// The state before we received a TLSUserEvent. We are just forwarding any read at this point.
|
||||
case initial
|
||||
|
||||
@usableFromInline
|
||||
struct AwaitingUpgrader {
|
||||
var seenFirstRequest: Bool
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
|
||||
/// The request head has been received. We're currently running the future chain awaiting an upgrader.
|
||||
case awaitingUpgrader(AwaitingUpgrader)
|
||||
|
||||
@usableFromInline
|
||||
struct UpgraderReady {
|
||||
var upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>
|
||||
var requestHead: HTTPRequestHead
|
||||
var responseHeaders: HTTPHeaders
|
||||
var proto: String
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
|
||||
/// We have an upgrader, which means we can begin upgrade we are just waiting for the request end.
|
||||
case upgraderReady(UpgraderReady)
|
||||
|
||||
@usableFromInline
|
||||
struct Upgrading {
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
/// We are either running the upgrading handler.
|
||||
case upgrading(Upgrading)
|
||||
|
||||
@usableFromInline
|
||||
struct Unbuffering {
|
||||
var buffer: Deque<NIOAny>
|
||||
}
|
||||
case unbuffering(Unbuffering)
|
||||
|
||||
case finished
|
||||
|
||||
case modifying
|
||||
}
|
||||
|
||||
private var state = State.initial
|
||||
|
||||
@usableFromInline
|
||||
enum HandlerRemovedAction {
|
||||
case failUpgradePromise
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func handlerRemoved() -> HandlerRemovedAction? {
|
||||
switch self.state {
|
||||
case .initial, .awaitingUpgrader, .upgraderReady, .upgrading, .unbuffering:
|
||||
self.state = .finished
|
||||
return .failUpgradePromise
|
||||
|
||||
case .finished:
|
||||
return .none
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum ChannelReadDataAction {
|
||||
case unwrapData
|
||||
case fireChannelRead
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func channelReadData(_ data: NIOAny) -> ChannelReadDataAction? {
|
||||
switch self.state {
|
||||
case .initial:
|
||||
return .unwrapData
|
||||
|
||||
case .awaitingUpgrader(var awaitingUpgrader):
|
||||
if awaitingUpgrader.seenFirstRequest {
|
||||
// We should buffer the data since we have seen the full request.
|
||||
self.state = .modifying
|
||||
awaitingUpgrader.buffer.append(data)
|
||||
self.state = .awaitingUpgrader(awaitingUpgrader)
|
||||
return nil
|
||||
} else {
|
||||
// We shouldn't buffer. This means we are still expecting HTTP parts.
|
||||
return .unwrapData
|
||||
}
|
||||
|
||||
case .upgraderReady:
|
||||
// We have not seen the end of the HTTP request so this
|
||||
// data is probably an HTTP request part.
|
||||
return .unwrapData
|
||||
|
||||
case .unbuffering(var unbuffering):
|
||||
self.state = .modifying
|
||||
unbuffering.buffer.append(data)
|
||||
self.state = .unbuffering(unbuffering)
|
||||
return nil
|
||||
|
||||
case .finished:
|
||||
return .fireChannelRead
|
||||
|
||||
case .upgrading(var upgrading):
|
||||
// We got a read while running ugprading.
|
||||
// We have to buffer the read to unbuffer it afterwards
|
||||
self.state = .modifying
|
||||
upgrading.buffer.append(data)
|
||||
self.state = .upgrading(upgrading)
|
||||
return nil
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum ChannelReadRequestPartAction {
|
||||
case failUpgradePromise(Error)
|
||||
case runNotUpgradingInitializer
|
||||
case startUpgrading(
|
||||
upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>,
|
||||
requestHead: HTTPRequestHead,
|
||||
responseHeaders: HTTPHeaders,
|
||||
proto: String
|
||||
)
|
||||
case findUpgrader(
|
||||
head: HTTPRequestHead,
|
||||
requestedProtocols: [String],
|
||||
allHeaderNames: Set<String>,
|
||||
connectionHeader: Set<String>
|
||||
)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func channelReadRequestPart(_ requestPart: HTTPServerRequestPart) -> ChannelReadRequestPartAction? {
|
||||
switch self.state {
|
||||
case .initial:
|
||||
guard case .head(let head) = requestPart else {
|
||||
// The first data that we saw was not a head. This is a protocol error and we are just going to
|
||||
// fail upgrading
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
}
|
||||
|
||||
// Ok, we have a HTTP head. Check if it's an upgrade.
|
||||
let requestedProtocols = head.headers[canonicalForm: "upgrade"].map(String.init)
|
||||
guard requestedProtocols.count > 0 else {
|
||||
// We have to buffer now since we got the request head but are not upgrading.
|
||||
// The user is configuring the HTTP pipeline now.
|
||||
var buffer = Deque<NIOAny>()
|
||||
buffer.append(NIOAny(requestPart))
|
||||
self.state = .upgrading(.init(buffer: buffer))
|
||||
return .runNotUpgradingInitializer
|
||||
}
|
||||
|
||||
// We can now transition to awaiting the upgrader. This means that we are trying to
|
||||
// find an upgrade that can handle requested protocols. We are not buffering because
|
||||
// we are waiting for the request end.
|
||||
self.state = .awaitingUpgrader(.init(seenFirstRequest: false, buffer: .init()))
|
||||
|
||||
let connectionHeader = Set(head.headers[canonicalForm: "connection"].map { $0.lowercased() })
|
||||
let allHeaderNames = Set(head.headers.map { $0.name.lowercased() })
|
||||
|
||||
return .findUpgrader(
|
||||
head: head,
|
||||
requestedProtocols: requestedProtocols,
|
||||
allHeaderNames: allHeaderNames,
|
||||
connectionHeader: connectionHeader
|
||||
)
|
||||
|
||||
case .awaitingUpgrader(let awaitingUpgrader):
|
||||
switch (awaitingUpgrader.seenFirstRequest, requestPart) {
|
||||
case (true, _):
|
||||
// This is weird we are seeing more requests parts after we have seen an end
|
||||
// Let's fail upgrading
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case (false, .head):
|
||||
// This is weird we are seeing another head but haven't seen the end for the request before
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case (false, .body):
|
||||
// This is weird we are seeing body parts for a request that indicated that it wanted
|
||||
// to upgrade.
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case (false, .end):
|
||||
// Okay we got the end as expected. Just gotta store this in our state.
|
||||
self.state = .awaitingUpgrader(.init(seenFirstRequest: true, buffer: awaitingUpgrader.buffer))
|
||||
return nil
|
||||
}
|
||||
|
||||
case .upgraderReady(let upgraderReady):
|
||||
switch requestPart {
|
||||
case .head:
|
||||
// This is weird we are seeing another head but haven't seen the end for the request before
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case .body:
|
||||
// This is weird we are seeing body parts for a request that indicated that it wanted
|
||||
// to upgrade.
|
||||
return .failUpgradePromise(HTTPServerUpgradeErrors.invalidHTTPOrdering)
|
||||
|
||||
case .end:
|
||||
// Okay we got the end as expected and our upgrader is ready so let's start upgrading
|
||||
self.state = .upgrading(.init(buffer: upgraderReady.buffer))
|
||||
return .startUpgrading(
|
||||
upgrader: upgraderReady.upgrader,
|
||||
requestHead: upgraderReady.requestHead,
|
||||
responseHeaders: upgraderReady.responseHeaders,
|
||||
proto: upgraderReady.proto
|
||||
)
|
||||
}
|
||||
|
||||
case .upgrading, .unbuffering, .finished:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum UpgradingHandlerCompletedAction {
|
||||
case fireErrorCaughtAndStartUnbuffering(Error)
|
||||
case removeHandler(UpgradeResult)
|
||||
case fireErrorCaughtAndRemoveHandler(Error)
|
||||
case startUnbuffering(UpgradeResult)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func upgradingHandlerCompleted(_ result: Result<UpgradeResult, Error>) -> UpgradingHandlerCompletedAction? {
|
||||
switch self.state {
|
||||
case .initial:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .upgrading(let upgrading):
|
||||
switch result {
|
||||
case .success(let value):
|
||||
if !upgrading.buffer.isEmpty {
|
||||
self.state = .unbuffering(.init(buffer: upgrading.buffer))
|
||||
return .startUnbuffering(value)
|
||||
} else {
|
||||
self.state = .finished
|
||||
return .removeHandler(value)
|
||||
}
|
||||
|
||||
case .failure(let error):
|
||||
if !upgrading.buffer.isEmpty {
|
||||
// So we failed to upgrade. There is nothing really that we can do here.
|
||||
// We are unbuffering the reads but there shouldn't be any handler in the pipeline
|
||||
// that expects a specific type of reads anyhow.
|
||||
self.state = .unbuffering(.init(buffer: upgrading.buffer))
|
||||
return .fireErrorCaughtAndStartUnbuffering(error)
|
||||
} else {
|
||||
self.state = .finished
|
||||
return .fireErrorCaughtAndRemoveHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
case .finished:
|
||||
// We have to tolerate this
|
||||
return nil
|
||||
|
||||
case .awaitingUpgrader, .upgraderReady, .unbuffering:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum FindingUpgraderCompletedAction {
|
||||
case startUpgrading(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)
|
||||
case runNotUpgradingInitializer
|
||||
case fireErrorCaughtAndStartUnbuffering(Error)
|
||||
case fireErrorCaughtAndRemoveHandler(Error)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func findingUpgraderCompleted(
|
||||
requestHead: HTTPRequestHead,
|
||||
_ result: Result<(upgrader: any NIOTypedHTTPServerProtocolUpgrader<UpgradeResult>, responseHeaders: HTTPHeaders, proto: String)?, Error>
|
||||
) -> FindingUpgraderCompletedAction? {
|
||||
switch self.state {
|
||||
case .initial, .upgraderReady:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .awaitingUpgrader(let awaitingUpgrader):
|
||||
switch result {
|
||||
case .success(.some((let upgrader, let responseHeaders, let proto))):
|
||||
if awaitingUpgrader.seenFirstRequest {
|
||||
// We have seen the end of the request. So we can upgrade now.
|
||||
self.state = .upgrading(.init(buffer: awaitingUpgrader.buffer))
|
||||
return .startUpgrading(upgrader: upgrader, responseHeaders: responseHeaders, proto: proto)
|
||||
} else {
|
||||
// We have not yet seen the end so we have to wait until that happens
|
||||
self.state = .upgraderReady(.init(
|
||||
upgrader: upgrader,
|
||||
requestHead: requestHead,
|
||||
responseHeaders: responseHeaders,
|
||||
proto: proto,
|
||||
buffer: awaitingUpgrader.buffer
|
||||
))
|
||||
return nil
|
||||
}
|
||||
|
||||
case .success(.none):
|
||||
// There was no upgrader to handle the request. We just run the not upgrading
|
||||
// initializer now.
|
||||
self.state = .upgrading(.init(buffer: awaitingUpgrader.buffer))
|
||||
return .runNotUpgradingInitializer
|
||||
|
||||
case .failure(let error):
|
||||
if !awaitingUpgrader.buffer.isEmpty {
|
||||
self.state = .unbuffering(.init(buffer: awaitingUpgrader.buffer))
|
||||
return .fireErrorCaughtAndStartUnbuffering(error)
|
||||
} else {
|
||||
self.state = .finished
|
||||
return .fireErrorCaughtAndRemoveHandler(error)
|
||||
}
|
||||
}
|
||||
|
||||
case .upgrading, .unbuffering, .finished:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
enum UnbufferAction {
|
||||
case fireChannelRead(NIOAny)
|
||||
case fireChannelReadCompleteAndRemoveHandler
|
||||
}
|
||||
|
||||
@inlinable
|
||||
mutating func unbuffer() -> UnbufferAction {
|
||||
switch self.state {
|
||||
case .initial, .awaitingUpgrader, .upgraderReady, .upgrading, .finished:
|
||||
preconditionFailure("Invalid state \(self.state)")
|
||||
|
||||
case .unbuffering(var unbuffering):
|
||||
self.state = .modifying
|
||||
|
||||
if let element = unbuffering.buffer.popFirst() {
|
||||
self.state = .unbuffering(unbuffering)
|
||||
|
||||
return .fireChannelRead(element)
|
||||
} else {
|
||||
self.state = .finished
|
||||
|
||||
return .fireChannelReadCompleteAndRemoveHandler
|
||||
}
|
||||
|
||||
case .modifying:
|
||||
fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user