From 178dd7650382a3ab349a67b67d2b2b5ea3aca282 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Mon, 16 Apr 2018 20:13:20 +0200 Subject: [PATCH] Allow to specify the max websockets frame size when using the upgrader. (#315) * Allow to specify the max websockets frame size when using the upgrader. Motivation: At the moment its not possible to adjust the max websockets frame size when using the upgrader while its possible when directly use the WebSocketFrameDecoder. Modifications: Allow to specify max frame size via an init argument (with default value). Result: More flexible way to use the upgrader. --- .../NIOWebSocket/WebSocketFrameDecoder.swift | 2 +- Sources/NIOWebSocket/WebSocketUpgrader.swift | 39 ++++++++++++++++++- .../EndToEndTests+XCTest.swift | 1 + Tests/NIOWebSocketTests/EndToEndTests.swift | 27 ++++++++++++- 4 files changed, 65 insertions(+), 4 deletions(-) diff --git a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift index de22d6de4..f70b8d40b 100644 --- a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift @@ -221,7 +221,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { public var cumulationBuffer: ByteBuffer? = nil /// The maximum frame size the decoder is willing to tolerate from the remote peer. - private let maxFrameSize: Int + /* private but tests */ let maxFrameSize: Int /// Our parser state. private var parser = WSParser() diff --git a/Sources/NIOWebSocket/WebSocketUpgrader.swift b/Sources/NIOWebSocket/WebSocketUpgrader.swift index a95ee6d23..cbced9cba 100644 --- a/Sources/NIOWebSocket/WebSocketUpgrader.swift +++ b/Sources/NIOWebSocket/WebSocketUpgrader.swift @@ -59,6 +59,7 @@ public final class WebSocketUpgrader: HTTPProtocolUpgrader { private let shouldUpgrade: (HTTPRequestHead) -> HTTPHeaders? private let upgradePipelineHandler: (Channel, HTTPRequestHead) -> EventLoopFuture + private let maxFrameSize: Int /// Create a new `WebSocketUpgrader`. /// @@ -73,10 +74,44 @@ public final class WebSocketUpgrader: HTTPProtocolUpgrader { /// websocket protocol. This only needs to add the user handlers: the /// `WebSocketFrameEncoder` and `WebSocketFrameDecoder` will have been added to the /// pipeline automatically. - public init(shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, + /// - maxFrameSize: The maximum frame size the decoder is willing to tolerate from the + /// remote peer. WebSockets in principle allows frame sizes up to `2**64` bytes, but + /// this is an objectively unreasonable maximum value (on AMD64 systems it is not + /// possible to even allocate a buffer large enough to handle this size), so we + /// set a lower one. The default value is the same as the default HTTP/2 max frame + /// size, `2**14` bytes. Users may override this to any value up to `UInt32.max`. + /// Users are strongly encouraged not to increase this value unless they absolutely + /// must, as the decoder will not produce partial frames, meaning that it will hold + /// on to data until the *entire* body is received. + public convenience init(shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, upgradePipelineHandler: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture) { + self.init(maxFrameSize: 1 << 14, shouldUpgrade: shouldUpgrade, upgradePipelineHandler: upgradePipelineHandler) + } + + + /// Create a new `WebSocketUpgrader`. + /// + /// - parameters: + /// - maxFrameSize: The maximum frame size the decoder is willing to tolerate from the + /// remote peer. WebSockets in principle allows frame sizes up to `2**64` bytes, but + /// this is an objectively unreasonable maximum value (on AMD64 systems it is not + /// possible to even. Users may set this to any value up to `UInt32.max`. + /// - shouldUpgrade: A callback that determines whether the websocket request should be + /// 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. + /// - 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, shouldUpgrade: @escaping (HTTPRequestHead) -> HTTPHeaders?, + upgradePipelineHandler: @escaping (Channel, HTTPRequestHead) -> EventLoopFuture) { + precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size") self.shouldUpgrade = shouldUpgrade self.upgradePipelineHandler = upgradePipelineHandler + self.maxFrameSize = maxFrameSize } public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders { @@ -111,7 +146,7 @@ public final class WebSocketUpgrader: HTTPProtocolUpgrader { public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { return ctx.pipeline.add(handler: WebSocketFrameEncoder()).then { - ctx.pipeline.add(handler: WebSocketFrameDecoder()) + ctx.pipeline.add(handler: WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize)) }.then { self.upgradePipelineHandler(ctx.channel, upgradeRequest) } diff --git a/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift b/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift index d80ebce6c..ed2b6270d 100644 --- a/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift +++ b/Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift @@ -34,6 +34,7 @@ extension EndToEndTests { ("testUpgradeMayAddCustomHeaders", testUpgradeMayAddCustomHeaders), ("testMayRegisterMultipleWebSocketEndpoints", testMayRegisterMultipleWebSocketEndpoints), ("testSendAFewFrames", testSendAFewFrames), + ("testMaxFrameSize", testMaxFrameSize), ] } } diff --git a/Tests/NIOWebSocketTests/EndToEndTests.swift b/Tests/NIOWebSocketTests/EndToEndTests.swift index e1fe8b170..4933f5887 100644 --- a/Tests/NIOWebSocketTests/EndToEndTests.swift +++ b/Tests/NIOWebSocketTests/EndToEndTests.swift @@ -15,7 +15,7 @@ import XCTest import NIO import NIOHTTP1 -import NIOWebSocket +@testable import NIOWebSocket extension EmbeddedChannel { func readAllInboundBuffers() -> ByteBuffer { @@ -340,4 +340,29 @@ class EndToEndTests: XCTestCase { XCTAssertEqual(recorder.frames, [dataFrame, pingFrame]) } + + func testMaxFrameSize() throws { + let basicUpgrader = WebSocketUpgrader(maxFrameSize: 16, shouldUpgrade: { head in HTTPHeaders() }, + upgradePipelineHandler: { (channel, req) in + return channel.eventLoop.newSucceededFuture(result: ()) + }) + let (loop, server, client) = createTestFixtures(upgraders: [basicUpgrader]) + defer { + XCTAssertNoThrow(try client.finish()) + XCTAssertNoThrow(try server.finish()) + XCTAssertNoThrow(try loop.syncShutdownGracefully()) + } + + let upgradeRequest = self.upgradeRequest(extraHeaders: ["Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "AQIDBAUGBwgJCgsMDQ4PEC=="]) + XCTAssertNoThrow(try client.writeString(upgradeRequest).wait()) + 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"]) + + let decoder = (try server.pipeline.context(handlerType: WebSocketFrameDecoder.self).wait()).handler as! WebSocketFrameDecoder + XCTAssertEqual(16, decoder.maxFrameSize) + } }