diff --git a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift index e4c6f7250..0551304bc 100644 --- a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift @@ -41,8 +41,8 @@ public protocol HTTPServerProtocolUpgrader { /// 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 - /// throw. - func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders + /// fail the future. + func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture /// 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 @@ -74,8 +74,8 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa private var seenFirstRequest = false /// The closure that should be invoked when the end of the upgrade request is received if any. - private var upgrade: (() -> Void)? - private var receivedMessages: [NIOAny] = [] + private var upgradeState: UpgradeState = .idle + private var receivedMessages: CircularBuffer = CircularBuffer() /// Create a `HTTPServerUpgradeHandler`. /// @@ -108,74 +108,99 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa let requestPart = unwrapInboundIn(data) - if let upgrade = self.upgrade { - switch requestPart { - case .head: - context.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) - notUpgrading(context: context, data: data) - return - case .body: - // TODO: In the future way may want to add some API to also allow special handling of the body during the - // upgrade. For now just ignore it. - break - case .end: + switch self.upgradeState { + case .idle: + self.firstRequestHeadReceived(context: context, requestPart: requestPart) + case .awaitingUpgrader: + if case .end = requestPart { + // This is the end of the first request. Swallow it, we're buffering the rest. + self.seenFirstRequest = true + } + case .upgraderReady(let upgrade): + if case .end = requestPart { + // This is the end of the first request, and we can upgrade. Time to kick it off. self.seenFirstRequest = true - - // The request is complete now trigger the upgrade. upgrade() } - } else { - // We should decide if we're going to upgrade based on the first request header: if we aren't upgrading, - // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're - // upgrading, the only thing we should see is a request head. Anything else in an error. - guard case .head(let request) = requestPart else { - context.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) - notUpgrading(context: context, data: data) - return - } - - // Ok, we have a HTTP request. Check if it's an upgrade. If it's not, we want to pass it on and remove ourselves - // from the channel pipeline. - let requestedProtocols = request.headers[canonicalForm: "upgrade"] - guard requestedProtocols.count > 0 else { - notUpgrading(context: context, data: data) - return - } - - // Cool, this is an upgrade! Let's go. - if let upgrade = handleUpgrade(context: context, request: request, requestedProtocols: requestedProtocols) { - self.upgrade = upgrade + case .upgradeFailed: + // We were re-entrantly called while delivering the request head. We can just pass this through. + context.fireChannelRead(data) + case .upgradeComplete: + preconditionFailure("Upgrade has completed but we have not seen a whole request and still got re-entrantly called.") + case .upgrading: + preconditionFailure("We think we saw .end before and began upgrading, but somehow we have not set seenFirstRequest") + } + } + + private func firstRequestHeadReceived(context: ChannelHandlerContext, requestPart: HTTPServerRequestPart) { + // We should decide if we're going to upgrade based on the first request header: if we aren't upgrading, + // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're + // upgrading, the only thing we should see is a request head. Anything else in an error. + guard case .head(let request) = requestPart else { + context.fireErrorCaught(HTTPServerUpgradeErrors.invalidHTTPOrdering) + self.notUpgrading(context: context, data: requestPart) + return + } + + // Ok, we have a HTTP request. Check if it's an upgrade. If it's not, we want to pass it on and remove ourselves + // from the channel pipeline. + let requestedProtocols = request.headers[canonicalForm: "upgrade"] + guard requestedProtocols.count > 0 else { + self.notUpgrading(context: context, data: requestPart) + return + } + + // Cool, this is an upgrade request. + // We'll attempt to upgrade. This may take a while, so while we're waiting more data can come in. + self.upgradeState = .awaitingUpgrader + + self.handleUpgrade(context: context, request: request, requestedProtocols: requestedProtocols).whenSuccess { callback in + if let callback = callback { + self.gotUpgrader(upgrader: callback) } else { - notUpgrading(context: context, data: data) + self.notUpgrading(context: context, data: requestPart) } } } /// The core of the upgrade handling logic. - private func handleUpgrade(context: ChannelHandlerContext, request: HTTPRequestHead, requestedProtocols: [String]) -> (() -> Void)? { + /// + /// - returns: An `EventLoopFuture` that will contain a callback to invoke if upgrade is requested, or nil if upgrade has failed. Never returns a failed future. + private func handleUpgrade(context: ChannelHandlerContext, request: HTTPRequestHead, requestedProtocols: [String]) -> EventLoopFuture<(() -> Void)?> { let connectionHeader = Set(request.headers[canonicalForm: "connection"].map { $0.lowercased() }) let allHeaderNames = Set(request.headers.map { $0.name.lowercased() }) - for proto in requestedProtocols { - guard let upgrader = upgraders[proto.lowercased()] else { - continue - } + // We now set off a chain of Futures to try to find a protocol upgrade. While this is blocking, we need to buffer inbound data. + let protocolIterator = requestedProtocols.makeIterator() + 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 { - continue - } + /// Attempt to upgrade a single protocol. + /// + /// Will recurse through `protocolIterator` if upgrade fails. + private func handleUpgradeForProtocol(context: ChannelHandlerContext, protocolIterator: Array.Iterator, request: HTTPRequestHead, allHeaderNames: Set, connectionHeader: Set) -> EventLoopFuture<(() -> Void)?> { + // 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) + } - var responseHeaders = buildUpgradeHeaders(protocol: proto) - do { - responseHeaders = try upgrader.buildUpgradeResponse(upgradeRequest: request, initialResponseHeaders: responseHeaders) - } catch { - // We should fire this error so the user can log it, but keep going. - context.fireErrorCaught(error) - continue - } - + guard let upgrader = 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).map { finalResponseHeaders in return { + // Ok, we're upgrading. + self.upgradeState = .upgrading + // 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. @@ -186,7 +211,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa // 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, upgradeRequest: request, responseHeaders: responseHeaders) + self.sendUpgradeResponse(context: context, upgradeRequest: request, responseHeaders: finalResponseHeaders) }.flatMap { self.removeHandler(context: context, handler: self.httpEncoder) }.map { @@ -195,24 +220,42 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa upgrader.upgrade(context: context, upgradeRequest: request) }.map { context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: proto, upgradeRequest: request)) - - self.upgrade = nil - + + self.upgradeState = .upgradeComplete + // We unbuffer any buffered data here and, if we sent any, // we also fire readComplete. - let bufferedMessages = self.receivedMessages - self.receivedMessages = [] - bufferedMessages.forEach { context.fireChannelRead($0) } - if bufferedMessages.count > 0 { + let fireReadComplete = self.receivedMessages.count > 0 + while self.receivedMessages.count > 0 { + let bufferedPart = self.receivedMessages.removeFirst() + context.fireChannelRead(bufferedPart) + } + if fireReadComplete { context.fireChannelReadComplete() } }.whenComplete { (_: Result) in context.pipeline.removeHandler(context: context, promise: nil) } } + }.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) } + } - return nil + private func gotUpgrader(upgrader: @escaping (() -> Void)) { + switch self.upgradeState { + case .awaitingUpgrader: + self.upgradeState = .upgraderReady(upgrader) + if self.seenFirstRequest { + // Ok, we're good to go, we can upgrade. Otherwise we're waiting for .end, which + // will trigger the upgrade. + upgrader() + } + case .idle, .upgradeComplete, .upgraderReady, .upgradeFailed, .upgrading: + preconditionFailure("Unexpected upgrader state: \(self.upgradeState)") + } } /// Sends the 101 Switching Protocols response for the pipeline. @@ -223,9 +266,31 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa } /// Called when we know we're not upgrading. Passes the data on and then removes this object from the pipeline. - private func notUpgrading(context: ChannelHandlerContext, data: NIOAny) { - assert(self.receivedMessages.count == 0) - context.fireChannelRead(data) + private func notUpgrading(context: ChannelHandlerContext, data: HTTPServerRequestPart) { + self.upgradeState = .upgradeFailed + + if !self.seenFirstRequest { + // We haven't seen the first request .end. That means we're not buffering anything, and we can + // just deliver data. + assert(self.receivedMessages.count == 0) + context.fireChannelRead(self.wrapInboundOut(data)) + } else { + // This is trickier. We've seen the first request .end, so we now need to deliver the .head we + // got passed, as well as the .end we swallowed, and any buffered parts. While we're doing this + // we may be re-entrantly called, which will cause us to buffer new parts. To make that safe, we + // must ensure we aren't holding the buffer mutably, so no for loop for us. + context.fireChannelRead(self.wrapInboundOut(data)) + context.fireChannelRead(self.wrapInboundOut(.end(nil))) + + while self.receivedMessages.count > 0 { + let bufferedPart = self.receivedMessages.removeFirst() + context.fireChannelRead(bufferedPart) + } + } + + context.fireChannelReadComplete() + + // Ok, we've delivered all the parts. We can now remove ourselves, which should happen synchronously. context.pipeline.removeHandler(context: context, promise: nil) } @@ -253,3 +318,26 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHa on: context.eventLoop) } } + +extension HTTPServerUpgradeHandler { + /// The state of the upgrade handler. + private enum UpgradeState { + /// Awaiting some activity. + case idle + + /// The request head has been received. We're currently running the future chain awaiting an upgrader. + case awaitingUpgrader + + /// We have an upgrader, which means we can begin upgrade. + case upgraderReady(() -> Void) + + /// The upgrade is in process. + case upgrading + + /// The upgrade has failed, and we are being removed from the pipeline. + case upgradeFailed + + /// The upgrade has succeeded, and we are being removed from the pipeline. + case upgradeComplete + } +} diff --git a/Sources/NIOWebSocket/WebSocketUpgrader.swift b/Sources/NIOWebSocket/WebSocketUpgrader.swift index aeb325349..77de3ca2e 100644 --- a/Sources/NIOWebSocket/WebSocketUpgrader.swift +++ b/Sources/NIOWebSocket/WebSocketUpgrader.swift @@ -57,7 +57,7 @@ public final class WebSocketUpgrader: HTTPServerProtocolUpgrader { /// which NIO requires. We check for these manually. public let requiredUpgradeHeaders: [String] = [] - private let shouldUpgrade: (HTTPRequestHead) -> HTTPHeaders? + private let shouldUpgrade: (Channel, HTTPRequestHead) -> EventLoopFuture private let upgradePipelineHandler: (Channel, HTTPRequestHead) -> EventLoopFuture private let maxFrameSize: Int private let automaticErrorHandling: Bool @@ -72,13 +72,13 @@ public final class WebSocketUpgrader: HTTPServerProtocolUpgrader { /// upgraded. This callback is responsible for creating a `HTTPHeaders` object with /// any headers that it needs on the response *except for* the `Upgrade`, `Connection`, /// and `Sec-WebSocket-Accept` headers, which this upgrader will handle. Should return - /// `nil` if the upgrade should be refused. + /// an `EventLoopFuture` containing `nil` if the upgrade should be refused. /// - upgradePipelineHandler: A function that will be called once the upgrade response is /// flushed, and that is expected to mutate the `Channel` appropriately to handle the /// websocket protocol. This only needs to add the user handlers: the /// `WebSocketFrameEncoder` and `WebSocketFrameDecoder` will have been added to the /// pipeline automatically. - public convenience init(automaticErrorHandling: Bool = true, shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, + public convenience init(automaticErrorHandling: Bool = true, shouldUpgrade: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture, upgradePipelineHandler: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture) { self.init(maxFrameSize: 1 << 14, automaticErrorHandling: automaticErrorHandling, shouldUpgrade: shouldUpgrade, upgradePipelineHandler: upgradePipelineHandler) @@ -99,13 +99,13 @@ public final class WebSocketUpgrader: HTTPServerProtocolUpgrader { /// upgraded. This callback is responsible for creating a `HTTPHeaders` object with /// any headers that it needs on the response *except for* the `Upgrade`, `Connection`, /// and `Sec-WebSocket-Accept` headers, which this upgrader will handle. Should return - /// `nil` if the upgrade should be refused. + /// an `EventLoopFuture` containing `nil` if the upgrade should be refused. /// - upgradePipelineHandler: A function that will be called once the upgrade response is /// flushed, and that is expected to mutate the `Channel` appropriately to handle the /// websocket protocol. This only needs to add the user handlers: the /// `WebSocketFrameEncoder` and `WebSocketFrameDecoder` will have been added to the /// pipeline automatically. - public init(maxFrameSize: Int, automaticErrorHandling: Bool = true, shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, + public init(maxFrameSize: Int, automaticErrorHandling: Bool = true, shouldUpgrade: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture, upgradePipelineHandler: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture) { precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size") self.shouldUpgrade = shouldUpgrade @@ -114,34 +114,46 @@ public final class WebSocketUpgrader: HTTPServerProtocolUpgrader { self.automaticErrorHandling = automaticErrorHandling } - public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { - let key = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Key") - let version = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Version") + public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { + let key: String + let version: String + + do { + key = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Key") + version = try upgradeRequest.headers.nonListHeader("Sec-WebSocket-Version") + } catch { + return channel.eventLoop.makeFailedFuture(error) + } // The version must be 13. guard version == "13" else { - throw NIOWebSocketUpgradeError.invalidUpgradeHeader + return channel.eventLoop.makeFailedFuture(NIOWebSocketUpgradeError.invalidUpgradeHeader) } - guard var extraHeaders = self.shouldUpgrade(upgradeRequest) else { - throw NIOWebSocketUpgradeError.unsupportedWebSocketTarget + return self.shouldUpgrade(channel, upgradeRequest).flatMapThrowing { extraHeaders in + guard let extraHeaders = extraHeaders else { + throw NIOWebSocketUpgradeError.unsupportedWebSocketTarget + } + return extraHeaders + }.map { (extraHeaders: HTTPHeaders) in + var extraHeaders = extraHeaders + + // Cool, we're good to go! Let's do our upgrade. We do this by concatenating the magic + // GUID to the base64-encoded key and taking a SHA1 hash of the result. + let acceptValue: String + do { + var hasher = SHA1() + hasher.update(string: key) + hasher.update(string: magicWebSocketGUID) + acceptValue = String(base64Encoding: hasher.finish()) + } + + extraHeaders.replaceOrAdd(name: "Upgrade", value: "websocket") + extraHeaders.add(name: "Sec-WebSocket-Accept", value: acceptValue) + extraHeaders.replaceOrAdd(name: "Connection", value: "upgrade") + + return extraHeaders } - - // Cool, we're good to go! Let's do our upgrade. We do this by concatenating the magic - // GUID to the base64-encoded key and taking a SHA1 hash of the result. - let acceptValue: String - do { - var hasher = SHA1() - hasher.update(string: key) - hasher.update(string: magicWebSocketGUID) - acceptValue = String(base64Encoding: hasher.finish()) - } - - extraHeaders.replaceOrAdd(name: "Upgrade", value: "websocket") - extraHeaders.add(name: "Sec-WebSocket-Accept", value: acceptValue) - extraHeaders.replaceOrAdd(name: "Connection", value: "upgrade") - - return extraHeaders } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { diff --git a/Sources/NIOWebSocketServer/main.swift b/Sources/NIOWebSocketServer/main.swift index 463f1a7e9..e04fd402e 100644 --- a/Sources/NIOWebSocketServer/main.swift +++ b/Sources/NIOWebSocketServer/main.swift @@ -202,7 +202,7 @@ private final class WebSocketTimeHandler: ChannelInboundHandler { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) -let upgrader = WebSocketUpgrader(shouldUpgrade: { (head: HTTPRequestHead) in HTTPHeaders() }, +let upgrader = WebSocketUpgrader(shouldUpgrade: { (channel: Channel, head: HTTPRequestHead) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel: Channel, _: HTTPRequestHead) in channel.pipeline.addHandler(WebSocketTimeHandler()) }) diff --git a/Tests/NIOHTTP1Tests/HTTPUpgradeTests+XCTest.swift b/Tests/NIOHTTP1Tests/HTTPUpgradeTests+XCTest.swift index 258f93b9b..a3c56f266 100644 --- a/Tests/NIOHTTP1Tests/HTTPUpgradeTests+XCTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPUpgradeTests+XCTest.swift @@ -39,6 +39,10 @@ extension HTTPUpgradeTestCase { ("testUpgradeIsCaseInsensitive", testUpgradeIsCaseInsensitive), ("testDelayedUpgradeBehaviour", testDelayedUpgradeBehaviour), ("testBuffersInboundDataDuringDelayedUpgrade", testBuffersInboundDataDuringDelayedUpgrade), + ("testDelayedUpgradeResponse", testDelayedUpgradeResponse), + ("testChainsDelayedUpgradesAppropriately", testChainsDelayedUpgradesAppropriately), + ("testDelayedUpgradeResponseDeliversFullRequest", testDelayedUpgradeResponseDeliversFullRequest), + ("testDelayedUpgradeResponseDeliversFullRequestAndPendingBits", testDelayedUpgradeResponseDeliversFullRequestAndPendingBits), ("testRemovesAllHTTPRelatedHandlersAfterUpgrade", testRemovesAllHTTPRelatedHandlersAfterUpgrade), ("testUpgradeWithUpgradePayloadInlineWithRequestWorks", testUpgradeWithUpgradePayloadInlineWithRequestWorks), ] diff --git a/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift index 42e542ec6..7b012a693 100644 --- a/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPUpgradeTests.swift @@ -70,6 +70,11 @@ extension EmbeddedChannel { return buffer } + + func readAllOutboundString() -> String { + var buffer = self.readAllOutboundBuffers() + return buffer.readString(length: buffer.readableBytes)! + } } private func serverHTTPChannelWithAutoremoval(group: EventLoopGroup, @@ -175,9 +180,9 @@ private class ExplodingUpgrader: HTTPServerProtocolUpgrader { self.requiredUpgradeHeaders = requiringHeaders } - public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { + public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { XCTFail("buildUpgradeResponse called") - throw Explosion.KABOOM + return channel.eventLoop.makeFailedFuture(Explosion.KABOOM) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { @@ -198,8 +203,8 @@ private class UpgraderSaysNo: HTTPServerProtocolUpgrader { self.supportedProtocol = `protocol` } - public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { - throw No.no + public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { + return channel.eventLoop.makeFailedFuture(No.no) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { @@ -219,10 +224,10 @@ private class SuccessfulUpgrader: HTTPServerProtocolUpgrader { self.onUpgradeComplete = onUpgradeComplete } - public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { + public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { var headers = initialResponseHeaders headers.add(name: "X-Upgrade-Complete", value: "true") - return headers + return channel.eventLoop.makeSucceededFuture(headers) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { @@ -242,10 +247,10 @@ private class UpgradeDelayer: HTTPServerProtocolUpgrader { self.supportedProtocol = `protocol` } - public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { + public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { var headers = initialResponseHeaders headers.add(name: "X-Upgrade-Complete", value: "true") - return headers + return channel.eventLoop.makeSucceededFuture(headers) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { @@ -259,6 +264,31 @@ private class UpgradeDelayer: HTTPServerProtocolUpgrader { } } +private class UpgradeResponseDelayer: HTTPServerProtocolUpgrader { + let supportedProtocol: String + let requiredUpgradeHeaders: [String] = [] + + private var context: ChannelHandlerContext? + private let buildUpgradeResponseHandler: () -> EventLoopFuture + + public init(forProtocol `protocol`: String, buildUpgradeResponseHandler: @escaping () -> EventLoopFuture) { + self.supportedProtocol = `protocol` + self.buildUpgradeResponseHandler = buildUpgradeResponseHandler + } + + public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { + return self.buildUpgradeResponseHandler().map { + var headers = initialResponseHeaders + headers.add(name: "X-Upgrade-Complete", value: "true") + return headers + } + } + + public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + return context.eventLoop.makeSucceededFuture(()) + } +} + private class UserEventSaver: ChannelInboundHandler { public typealias InboundIn = Any public var events: [EventType] = [] @@ -766,6 +796,275 @@ class HTTPUpgradeTestCase: XCTestCase { XCTAssertEqual(resultString, appData) } + func testDelayedUpgradeResponse() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + var upgradeRequested = false + + let delayedPromise = channel.eventLoop.makePromise(of: Void.self) + let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { + XCTAssertFalse(upgradeRequested) + upgradeRequested = true + return delayedPromise.futureResult + } + + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in })).wait()) + + // Let's send in an upgrade request. + let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" + XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) + + // Upgrade has been requested but not proceeded. + XCTAssertTrue(upgradeRequested) + XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + + // Ok, now we can upgrade. Upgrader should be out of the pipeline, and we should have seen the 101 response. + delayedPromise.succeed(()) + XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) + let response = channel.readAllOutboundString() + assertResponseIs(response: response, + expectedResponseLine: "HTTP/1.1 101 Switching Protocols", + expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) + } + + func testChainsDelayedUpgradesAppropriately() throws { + enum No: Error { + case no + } + + let channel = EmbeddedChannel() + defer { + do { + let complete = try channel.finish() + XCTAssertFalse(complete) + } catch No.no { + // ok + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + var upgradingProtocol = "" + + let failingProtocolPromise = channel.eventLoop.makePromise(of: Void.self) + let failingProtocolUpgrader = UpgradeResponseDelayer(forProtocol: "failingProtocol") { + XCTAssertEqual(upgradingProtocol, "") + upgradingProtocol = "failingProtocol" + return failingProtocolPromise.futureResult + } + + let myprotoPromise = channel.eventLoop.makePromise(of: Void.self) + let myprotoUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { + XCTAssertEqual(upgradingProtocol, "failingProtocol") + upgradingProtocol = "myproto" + return myprotoPromise.futureResult + } + + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [myprotoUpgrader, failingProtocolUpgrader], completionHandler: { context in })).wait()) + + // Let's send in an upgrade request. + let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: failingProtocol, myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" + XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) + + // Upgrade has been requested but not proceeded for the failing protocol. + XCTAssertEqual(upgradingProtocol, "failingProtocol") + XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + XCTAssertNoThrow(try channel.throwIfErrorCaught()) + + // Ok, now we'll fail the promise. This will catch an error, but the upgrade won't happen: instead, the second handler will be fired. + failingProtocolPromise.fail(No.no) + XCTAssertEqual(upgradingProtocol, "myproto") + XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + do { + try channel.throwIfErrorCaught() + XCTFail("Did not throw") + } catch No.no { + // ok + } catch { + XCTFail("Unexpected error: \(error)") + } + + // Ok, now we can upgrade. Upgrader should be out of the pipeline, and we should have seen the 101 response. + myprotoPromise.succeed(()) + XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) + let response = channel.readAllOutboundString() + assertResponseIs(response: response, + expectedResponseLine: "HTTP/1.1 101 Switching Protocols", + expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) + } + + func testDelayedUpgradeResponseDeliversFullRequest() throws { + enum No: Error { + case no + } + + let channel = EmbeddedChannel() + defer { + do { + let complete = try channel.finish() + XCTAssertFalse(complete) + } catch No.no { + // ok + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + var upgradeRequested = false + + let delayedPromise = channel.eventLoop.makePromise(of: Void.self) + let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { + XCTAssertFalse(upgradeRequested) + upgradeRequested = true + return delayedPromise.futureResult + } + + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in })).wait()) + + // Let's send in an upgrade request. + let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" + XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) + + // Upgrade has been requested but not proceeded. + XCTAssertTrue(upgradeRequested) + XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + XCTAssertNoThrow(try channel.throwIfErrorCaught()) + + // Ok, now we fail the upgrade. This fires an error, and then delivers the original request. + delayedPromise.fail(No.no) + XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + + do { + try channel.throwIfErrorCaught() + XCTFail("Did not throw") + } catch No.no { + // ok + } catch { + XCTFail("Unexpected error: \(error)") + } + + switch channel.readInbound(as: HTTPServerRequestPart.self) { + case .some(.head): + // ok + break + case let t: + XCTFail("Expected .head, got \(String(describing: t))") + } + + switch channel.readInbound(as: HTTPServerRequestPart.self) { + case .some(.end): + // ok + break + case let t: + XCTFail("Expected .head, got \(String(describing: t))") + } + + XCTAssertNil(channel.readInbound(as: HTTPServerRequestPart.self)) + } + + func testDelayedUpgradeResponseDeliversFullRequestAndPendingBits() throws { + enum No: Error { + case no + } + + let channel = EmbeddedChannel() + defer { + do { + let complete = try channel.finish() + XCTAssertFalse(complete) + } catch No.no { + // ok + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + var upgradeRequested = false + + let delayedPromise = channel.eventLoop.makePromise(of: Void.self) + let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { + XCTAssertFalse(upgradeRequested) + upgradeRequested = true + return delayedPromise.futureResult + } + + // Here we're disabling the pipeline handler, because otherwise it makes this test case impossible to reach. + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false, + withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in })).wait()) + + // Let's send in an upgrade request. + let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" + XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) + + // Upgrade has been requested but not proceeded. + XCTAssertTrue(upgradeRequested) + XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + XCTAssertNoThrow(try channel.throwIfErrorCaught()) + + // We now need to inject an extra buffered request. To do this we grab the context for the HTTPRequestDecoder and inject some reads. + XCTAssertNoThrow(try channel.pipeline.context(handlerType: HTTPRequestDecoder.self).map { context in + let requestHead = HTTPServerRequestPart.head(.init(version: .init(major: 1, minor: 1), method: .GET, uri: "/test")) + context.fireChannelRead(NIOAny(requestHead)) + context.fireChannelRead(NIOAny(HTTPServerRequestPart.end(nil))) + }.wait()) + + // Ok, now we fail the upgrade. This fires an error, and then delivers the original request and the buffered one. + delayedPromise.fail(No.no) + XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) + XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)) + + do { + try channel.throwIfErrorCaught() + XCTFail("Did not throw") + } catch No.no { + // ok + } catch { + XCTFail("Unexpected error: \(error)") + } + + switch channel.readInbound(as: HTTPServerRequestPart.self) { + case .some(.head(let h)): + XCTAssertEqual(h.method, .OPTIONS) + case let t: + XCTFail("Expected .head, got \(String(describing: t))") + } + + switch channel.readInbound(as: HTTPServerRequestPart.self) { + case .some(.end): + // ok + break + case let t: + XCTFail("Expected .head, got \(String(describing: t))") + } + + + switch channel.readInbound(as: HTTPServerRequestPart.self) { + case .some(.head(let h)): + XCTAssertEqual(h.method, .GET) + case let t: + XCTFail("Expected .head, got \(String(describing: t))") + } + + switch channel.readInbound(as: HTTPServerRequestPart.self) { + case .some(.end): + // ok + break + case let t: + XCTFail("Expected .head, got \(String(describing: t))") + } + + XCTAssertNil(channel.readInbound(as: HTTPServerRequestPart.self)) + } + func testRemovesAllHTTPRelatedHandlersAfterUpgrade() throws { let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: []) { req in } let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(pipelining: true, diff --git a/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift b/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift index 5181c4806..61dbb9249 100644 --- a/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift +++ b/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift @@ -29,6 +29,7 @@ extension EndToEndTests { ("testBasicUpgradeDance", testBasicUpgradeDance), ("testUpgradeWithProtocolName", testUpgradeWithProtocolName), ("testCanRejectUpgrade", testCanRejectUpgrade), + ("testCanDelayAcceptingUpgrade", testCanDelayAcceptingUpgrade), ("testRequiresVersion13", testRequiresVersion13), ("testRequiresVersionHeader", testRequiresVersionHeader), ("testRequiresKeyHeader", testRequiresKeyHeader), diff --git a/Tests/NIOWebSocketTests/EndToEndTests.swift b/Tests/NIOWebSocketTests/EndToEndTests.swift index 693e01915..b09b57255 100644 --- a/Tests/NIOWebSocketTests/EndToEndTests.swift +++ b/Tests/NIOWebSocketTests/EndToEndTests.swift @@ -126,7 +126,7 @@ class EndToEndTests: XCTestCase { } func testBasicUpgradeDance() throws { - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) defer { @@ -146,7 +146,7 @@ class EndToEndTests: XCTestCase { } func testUpgradeWithProtocolName() throws { - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) defer { @@ -166,7 +166,7 @@ class EndToEndTests: XCTestCase { } func testCanRejectUpgrade() throws { - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in nil }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(nil) }, upgradePipelineHandler: { (channel, req) in XCTFail("Should not have called") return channel.eventLoop.makeSucceededFuture(()) @@ -197,8 +197,52 @@ class EndToEndTests: XCTestCase { XCTAssertEqual(server.readAllOutboundBuffers().allAsString(), "") } + func testCanDelayAcceptingUpgrade() throws { + // This accept promise is going to be written to from a callback. This is only safe because we use + // embedded channels. + var acceptPromise: EventLoopPromise? = nil + var upgradeComplete = false + + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in + acceptPromise = channel.eventLoop.makePromise() + return acceptPromise!.futureResult + }, + upgradePipelineHandler: { (channel, req) in + upgradeComplete = true + return channel.eventLoop.makeSucceededFuture(()) + }) + let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) + defer { + XCTAssertNoThrow(try client.finish()) + XCTAssertNoThrow(try server.finish()) + XCTAssertNoThrow(try loop.syncShutdownGracefully()) + } + + XCTAssertNil(acceptPromise) + + let upgradeRequest = self.upgradeRequest(extraHeaders: ["Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "AQIDBAUGBwgJCgsMDQ4PEC=="]) + XCTAssertNoThrow(try client.writeString(upgradeRequest).wait()) + XCTAssertNoThrow(try interactInMemory(client, server)) + + XCTAssertNotNil(acceptPromise) + + // No upgrade should have occurred yet. + XCTAssertNil(client.readInbound(as: ByteBuffer.self)) + XCTAssertFalse(upgradeComplete) + + // Satisfy the promise. This will cause the upgrade to complete. + acceptPromise?.succeed(HTTPHeaders()) + XCTAssertTrue(upgradeComplete) + XCTAssertNoThrow(try interactInMemory(client, server)) + + let receivedResponse = client.readAllInboundBuffers().allAsString() + assertResponseIs(response: receivedResponse, + expectedResponseLine: "HTTP/1.1 101 Switching Protocols", + expectedResponseHeaders: ["Upgrade: websocket", "Sec-WebSocket-Accept: OfS0wDaT5NoxF2gqm7Zj2YtetzM=", "Connection: upgrade"]) + } + func testRequiresVersion13() throws { - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) defer { @@ -226,7 +270,7 @@ class EndToEndTests: XCTestCase { } func testRequiresVersionHeader() throws { - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) defer { @@ -254,7 +298,7 @@ class EndToEndTests: XCTestCase { } func testRequiresKeyHeader() throws { - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) defer { @@ -282,10 +326,10 @@ class EndToEndTests: XCTestCase { } func testUpgradeMayAddCustomHeaders() throws { - let upgrader = WebSocketUpgrader(shouldUpgrade: { head in + let upgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in var hdrs = HTTPHeaders() hdrs.add(name: "TestHeader", value: "TestValue") - return hdrs + return channel.eventLoop.makeSucceededFuture(hdrs) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) let (loop, server, client) = createTestFixtures(upgraders: [upgrader]) @@ -307,11 +351,11 @@ class EndToEndTests: XCTestCase { func testMayRegisterMultipleWebSocketEndpoints() throws { func buildHandler(path: String) -> WebSocketUpgrader { - return WebSocketUpgrader(shouldUpgrade: { head in - guard head.uri == "/\(path)" else { return nil } + return WebSocketUpgrader(shouldUpgrade: { (channel, head) in + guard head.uri == "/\(path)" else { return channel.eventLoop.makeSucceededFuture(nil) } var hdrs = HTTPHeaders() hdrs.add(name: "Target", value: path) - return hdrs + return channel.eventLoop.makeSucceededFuture(hdrs) }, upgradePipelineHandler: { (channel, req) in channel.eventLoop.makeSucceededFuture(()) }) } @@ -338,7 +382,7 @@ class EndToEndTests: XCTestCase { func testSendAFewFrames() throws { let recorder = WebSocketRecorderHandler() - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.pipeline.addHandler(recorder) @@ -377,7 +421,7 @@ class EndToEndTests: XCTestCase { } func testMaxFrameSize() throws { - let basicUpgrader = WebSocketUpgrader(maxFrameSize: 16, shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(maxFrameSize: 16, shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in return channel.eventLoop.makeSucceededFuture(()) }) @@ -403,7 +447,7 @@ class EndToEndTests: XCTestCase { func testAutomaticErrorHandling() throws { let recorder = WebSocketRecorderHandler() - let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { head in HTTPHeaders() }, + let basicUpgrader = WebSocketUpgrader(shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.pipeline.addHandler(recorder) @@ -449,7 +493,7 @@ class EndToEndTests: XCTestCase { func testNoAutomaticErrorHandling() throws { let recorder = WebSocketRecorderHandler() let basicUpgrader = WebSocketUpgrader(automaticErrorHandling: false, - shouldUpgrade: { head in HTTPHeaders() }, + shouldUpgrade: { (channel, head) in channel.eventLoop.makeSucceededFuture(HTTPHeaders()) }, upgradePipelineHandler: { (channel, req) in channel.pipeline.addHandler(recorder) diff --git a/docs/public-api-changes-NIO1-to-NIO2.md b/docs/public-api-changes-NIO1-to-NIO2.md index 95c4c90a1..1b22c5c4e 100644 --- a/docs/public-api-changes-NIO1-to-NIO2.md +++ b/docs/public-api-changes-NIO1-to-NIO2.md @@ -70,3 +70,5 @@ - change `ChannelPipeline.addHandler[s](_:first:)` to `ChannelPipeline.addHandler(_:postion:)` where `position` can be `.first`, `.last`, `.before(ChannelHandler)`, and `.after(ChannelHandler)` - change `ChannelPipeline.addHandler(_:before:)` to `ChannelPipeline.addHandler(_:postion:)` where `position` can be `.first`, `.last`, `.before(ChannelHandler)`, and `.after(ChannelHandler)` - change `ChannelPipeline.addHandler(_:after:)` to `ChannelPipeline.addHandler(_:postion:)` where `position` can be `.first`, `.last`, `.before(ChannelHandler)`, and `.after(ChannelHandler)` +- Change `HTTPServerProtocolUpgrader` `protocol` to require `buildUpgradeResponse` to take a `channel` and return an `EventLoopFuture`. +