Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/NIOWebSocket/WebSocketFrameDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it make even more sense to test behavior (e.g., ability and inability to transfer more than the limit when the limit is appropriately changed) rather than checking whether we set the maxFrameSize. It'll have a nice side effect of eliminating this comment.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vlm I will add more tests as a followup to test max frame size handling. But I think this is ok to test what the change did.


/// Our parser state.
private var parser = WSParser()
Expand Down
39 changes: 37 additions & 2 deletions Sources/NIOWebSocket/WebSocketUpgrader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public final class WebSocketUpgrader: HTTPProtocolUpgrader {

private let shouldUpgrade: (HTTPRequestHead) -> HTTPHeaders?
private let upgradePipelineHandler: (Channel, HTTPRequestHead) -> EventLoopFuture<Void>
private let maxFrameSize: Int

/// Create a new `WebSocketUpgrader`.
///
Expand All @@ -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<Void>) {
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<Void>) {
precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size")
self.shouldUpgrade = shouldUpgrade
self.upgradePipelineHandler = upgradePipelineHandler
self.maxFrameSize = maxFrameSize
}
Copy link
Contributor

@vlm vlm Apr 16, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curious, what is the motivation for providing two public constructors rather than a constructor with the default value?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vlm Short answer is "to preserve the trailing closure".


public func buildUpgradeResponse(upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) throws -> HTTPHeaders {
Expand Down Expand Up @@ -111,7 +146,7 @@ public final class WebSocketUpgrader: HTTPProtocolUpgrader {

public func upgrade(ctx: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
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)
}
Expand Down
1 change: 1 addition & 0 deletions Tests/NIOWebSocketTests/EndToEndTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ extension EndToEndTests {
("testUpgradeMayAddCustomHeaders", testUpgradeMayAddCustomHeaders),
("testMayRegisterMultipleWebSocketEndpoints", testMayRegisterMultipleWebSocketEndpoints),
("testSendAFewFrames", testSendAFewFrames),
("testMaxFrameSize", testMaxFrameSize),
]
}
}
Expand Down
27 changes: 26 additions & 1 deletion Tests/NIOWebSocketTests/EndToEndTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import XCTest
import NIO
import NIOHTTP1
import NIOWebSocket
@testable import NIOWebSocket

extension EmbeddedChannel {
func readAllInboundBuffers() -> ByteBuffer {
Expand Down Expand Up @@ -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)
}
}