From d53ee6dafc4d03a342aa32e79d5d282abc0c4f1a Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Wed, 23 May 2018 20:26:24 +0200 Subject: [PATCH] Only forward bytes on removal when we know we can handle it (#430) Motivation: 398b950eeedb8215bfdafdc07ebf92a7e0722980 introduced a change which forwarded bytes that were buffered in HTTPDecoder after it was removed when an upgrade was detected. This may be risky if we dont know that the pipeline can handle it. Modifications: - Add new initializer that allow us to configure if we should forward bytes or not. - Automatically use this if we know that we added an upgrader - Add unit tests. Result: Less risky implementation. --- Sources/NIOHTTP1/HTTPDecoder.swift | 26 ++++++- Sources/NIOHTTP1/HTTPPipelineSetup.swift | 4 +- Sources/NIOHTTP1/HTTPUpgradeHandler.swift | 6 +- .../HTTPDecoderTest+XCTest.swift | 2 + Tests/NIOHTTP1Tests/HTTPDecoderTest.swift | 76 ++++++++++++++++++- 5 files changed, 104 insertions(+), 10 deletions(-) diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index 59a0163c3..f3b0aa4e3 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -145,7 +145,15 @@ private protocol AnyHTTPDecoder: class { /// Rather than set this up manually, consider using `ChannelPipeline.addHTTPServerHandlers`. public final class HTTPRequestDecoder: HTTPDecoder { public convenience init() { - self.init(type: HTTPServerRequestPart.self) + self.init(leftOverBytesStrategy: .dropBytes) + } + + /// Creates a new instance of `HttpRequestDecoder`. + /// + /// - parameters: + /// - leftOverBytesStrategy: the strategy to use when removing the decoder from the pipeline and an upgrade was detected + convenience init(leftOverBytesStrategy: RemoveAfterUpgradeStrategy) { + self.init(type: HTTPServerRequestPart.self, leftOverBytesStrategy: leftOverBytesStrategy) } } @@ -175,7 +183,7 @@ public final class HTTPResponseDecoder: HTTPDecoder, Cha } public convenience init() { - self.init(type: HTTPClientResponsePart.self) + self.init(type: HTTPClientResponsePart.self, leftOverBytesStrategy: .dropBytes) } public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { @@ -187,6 +195,14 @@ public final class HTTPResponseDecoder: HTTPDecoder, Cha } } +/// Strategy to use when a HTTPDecoder is removed from a pipeline after a HTTP upgrade was detected. +enum RemoveAfterUpgradeStrategy { + /// Forward all the remaining bytes that are currently buffered in the deccoder to the next handler in the pipeline. + case forwardBytes + /// Discard all the remaining bytes that are currently buffered in the decoder. + case dropBytes +} + /// A `ChannelInboundHandler` that parses HTTP/1-style messages, converting them from /// unstructured bytes to a sequence of HTTP messages. /// @@ -198,14 +214,16 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { public typealias InboundIn = ByteBuffer public typealias InboundOut = HTTPMessageT + private let leftOverBytesStrategy: RemoveAfterUpgradeStrategy private var parser = http_parser() private var settings = http_parser_settings() fileprivate var state = HTTPParserState() - fileprivate init(type: HTTPMessageT.Type) { + fileprivate init(type: HTTPMessageT.Type, leftOverBytesStrategy: RemoveAfterUpgradeStrategy) { /* this is a private init, the public versions only allow HTTPClientResponsePart and HTTPServerRequestPart */ assert(HTTPMessageT.self == HTTPClientResponsePart.self || HTTPMessageT.self == HTTPServerRequestPart.self) + self.leftOverBytesStrategy = leftOverBytesStrategy } deinit { @@ -238,7 +256,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { } private func bytesToForwardOnRemoval(ctx: ChannelHandlerContext) -> ByteBuffer? { - guard self.parser.upgrade == 1 && ctx.channel.isActive else { + guard self.leftOverBytesStrategy == .forwardBytes && self.parser.upgrade == 1 && ctx.channel.isActive else { return nil } // We take a slice of the cumulationBuffer so the next handler in the pipeline will just see the readable portion of the buffer. diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index 4779194af..78b64911f 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -58,7 +58,7 @@ public extension ChannelPipeline { upgraders: [HTTPProtocolUpgrader], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) -> EventLoopFuture { let responseEncoder = HTTPResponseEncoder() - let requestDecoder = HTTPRequestDecoder() + let requestDecoder = HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes) let upgrader = HTTPServerUpgradeHandler(upgraders: upgraders, httpEncoder: responseEncoder, extraHTTPHandlers: [requestDecoder], @@ -98,7 +98,7 @@ public extension ChannelPipeline { withServerUpgrade upgrade: HTTPUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = false) -> EventLoopFuture { let responseEncoder = HTTPResponseEncoder() - let requestDecoder = HTTPRequestDecoder() + let requestDecoder = HTTPRequestDecoder(leftOverBytesStrategy: upgrade == nil ? .dropBytes : .forwardBytes) var handlers: [ChannelHandler] = [responseEncoder, requestDecoder] diff --git a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift index f2ce85205..0afc63e43 100644 --- a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift @@ -140,15 +140,15 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { if let upgrade = self.upgrade { switch requestPart { - case .head(_): + case .head: ctx.fireErrorCaught(HTTPUpgradeErrors.invalidHTTPOrdering) notUpgrading(ctx: ctx, data: data) return - case .body(_): + 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(_): + case .end: self.seenFirstRequest = true // The request is complete now trigger the upgrade. diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest+XCTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest+XCTest.swift index 1802cf6bf..f762fdffd 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest+XCTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest+XCTest.swift @@ -35,6 +35,8 @@ extension HTTPDecoderTest { ("testDoesNotDecodeHTTP2XResponse", testDoesNotDecodeHTTP2XResponse), ("testToleratesHTTP13Response", testToleratesHTTP13Response), ("testCorrectlyMaintainIndicesWhenDiscardReadBytes", testCorrectlyMaintainIndicesWhenDiscardReadBytes), + ("testDropExtraBytes", testDropExtraBytes), + ("testDontDropExtraBytes", testDontDropExtraBytes), ] } } diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index fd15bf59b..218d885c0 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -15,7 +15,7 @@ import XCTest import Dispatch import NIO -import NIOHTTP1 +@testable import NIOHTTP1 class HTTPDecoderTest: XCTestCase { private var channel: EmbeddedChannel! @@ -232,4 +232,78 @@ class HTTPDecoderTest: XCTestCase { XCTAssertNoThrow(try channel.writeInbound(buffer3)) XCTAssertNoThrow(try channel.finish()) } + + func testDropExtraBytes() throws { + class Receiver: ChannelInboundHandler { + typealias InboundIn = HTTPServerRequestPart + + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + let part = self.unwrapInboundIn(data) + switch part { + case .end: + // ignore + _ = ctx.pipeline.remove(name: "decoder") + default: + break + } + } + } + XCTAssertNoThrow(try channel.pipeline.add(name: "decoder", handler: HTTPRequestDecoder()).wait()) + XCTAssertNoThrow(try channel.pipeline.add(handler: Receiver()).wait()) + + var buffer = channel.allocator.buffer(capacity: 64) + buffer.write(staticString: "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\nXXXX") + + XCTAssertNoThrow(try channel.writeInbound(buffer)) + XCTAssertNoThrow(try channel.pipeline.assertDoesNotContain(handlerType: HTTPRequestDecoder.self)) + XCTAssertNoThrow(try channel.finish()) + } + + func testDontDropExtraBytes() throws { + class ByteCollector: ChannelInboundHandler { + typealias InboundIn = ByteBuffer + var called: Bool = false + + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + var buffer = self.unwrapInboundIn(data) + XCTAssertEqual("XXXX", buffer.readString(length: buffer.readableBytes)!) + self.called = true + } + + func handlerAdded(ctx: ChannelHandlerContext) { + _ = ctx.pipeline.remove(name: "decoder") + } + } + + class Receiver: ChannelInboundHandler { + typealias InboundIn = HTTPServerRequestPart + let collector = ByteCollector() + + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + let part = self.unwrapInboundIn(data) + switch part { + case .end: + _ = ctx.pipeline.remove(handler: self).then { _ in + ctx.pipeline.add(handler: self.collector) + } + default: + // ignore + break + } + } + + func channelInactive(ctx: ChannelHandlerContext) { + XCTAssertTrue(collector.called) + } + } + XCTAssertNoThrow(try channel.pipeline.add(name: "decoder", handler: HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes)).wait()) + XCTAssertNoThrow(try channel.pipeline.add(handler: Receiver()).wait()) + + var buffer = channel.allocator.buffer(capacity: 64) + buffer.write(staticString: "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\nXXXX") + + XCTAssertNoThrow(try channel.writeInbound(buffer)) + XCTAssertNoThrow(try channel.pipeline.assertDoesNotContain(handlerType: HTTPRequestDecoder.self)) + XCTAssertNoThrow(try channel.finish()) + } }