mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +00:00
Only forward bytes on removal when we know we can handle it (#430)
Motivation:
398b950eee 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.
This commit is contained in:
1 parent
9e0eb8347a
commit
d53ee6dafc
5 files changed
+104
-10
No files matched your search
@@ -145,7 +145,15 @@ private protocol AnyHTTPDecoder: class {
|
||||
/// Rather than set this up manually, consider using `ChannelPipeline.addHTTPServerHandlers`.
|
||||
public final class HTTPRequestDecoder: HTTPDecoder<HTTPServerRequestPart> {
|
||||
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<HTTPClientResponsePart>, 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<Void>?) {
|
||||
@@ -187,6 +195,14 @@ public final class HTTPResponseDecoder: HTTPDecoder<HTTPClientResponsePart>, 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<HTTPMessageT>: 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<HTTPMessageT>: 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.
|
||||
|
||||
@@ -58,7 +58,7 @@ public extension ChannelPipeline {
|
||||
upgraders: [HTTPProtocolUpgrader],
|
||||
_ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) -> EventLoopFuture<Void> {
|
||||
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<Void> {
|
||||
let responseEncoder = HTTPResponseEncoder()
|
||||
let requestDecoder = HTTPRequestDecoder()
|
||||
let requestDecoder = HTTPRequestDecoder(leftOverBytesStrategy: upgrade == nil ? .dropBytes : .forwardBytes)
|
||||
|
||||
var handlers: [ChannelHandler] = [responseEncoder, requestDecoder]
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -35,6 +35,8 @@ extension HTTPDecoderTest {
|
||||
("testDoesNotDecodeHTTP2XResponse", testDoesNotDecodeHTTP2XResponse),
|
||||
("testToleratesHTTP13Response", testToleratesHTTP13Response),
|
||||
("testCorrectlyMaintainIndicesWhenDiscardReadBytes", testCorrectlyMaintainIndicesWhenDiscardReadBytes),
|
||||
("testDropExtraBytes", testDropExtraBytes),
|
||||
("testDontDropExtraBytes", testDontDropExtraBytes),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user