Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor - HTTPServer upgrade handler #88

Merged
merged 2 commits into from
Sep 7, 2018
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
43 changes: 27 additions & 16 deletions Sources/KituraNet/HTTP/HTTPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ public class HTTPServer : Server {
/// The event loop group on which the HTTP handler runs
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)

private var ctx: ChannelHandlerContext?

public init() { }

/// SSL cert configs for handling client requests
Expand All @@ -90,6 +92,28 @@ public class HTTPServer : Server {
/// URI for which the latest WebSocket upgrade was requested by a client
var latestWebSocketURI: String?

/// Determines if the request should be upgraded and adds additional upgrade headers to the request
private func shouldUpgradeToWebSocket(webSocketHandlerFactory: ProtocolHandlerFactory, head: HTTPRequestHead) -> HTTPHeaders? {
self.latestWebSocketURI = head.uri
guard webSocketHandlerFactory.isServiceRegistered(at: head.uri) else { return nil }
var headers = HTTPHeaders()
if let wsProtocol = head.headers["Sec-WebSocket-Protocol"].first {
headers.add(name: "Sec-WebSocket-Protocol", value: wsProtocol)
}
if let key = head.headers["Sec-WebSocket-Key"].first {
headers.add(name: "Sec-WebSocket-Key", value: key)
}
return headers
}

/// Creates upgrade request and adds WebSocket handler to pipeline
private func upgradeHandler(webSocketHandlerFactory: ProtocolHandlerFactory, request: HTTPRequestHead) -> EventLoopFuture<Void> {
guard let ctx = self.ctx else { fatalError("Cannot create ServerRequest") }
///TODO: Handle secure upgrade request ("wss://")
let serverRequest = HTTPServerRequest(ctx: ctx, requestHead: request, enableSSL: false)
return ctx.channel.pipeline.add(handler: webSocketHandlerFactory.handler(for: serverRequest))
}

/// Listens for connections on a socket
///
/// - Parameter on: port number for new connections (eg. 8080)
Expand All @@ -100,26 +124,13 @@ public class HTTPServer : Server {
self.sslContext = try! SSLContext(configuration: tlsConfig)
}

var channelHandlerCtx: ChannelHandlerContext?
var upgraders: [HTTPProtocolUpgrader] = []
if let webSocketHandlerFactory = ConnectionUpgrader.getProtocolHandlerFactory(for: "websocket") {
///TODO: Should `maxFrameSize` be configurable?
let upgrader = KituraWebSocketUpgrader(maxFrameSize: 1 << 24, automaticErrorHandling: false, shouldUpgrade: { (head: HTTPRequestHead) in
self.latestWebSocketURI = head.uri
guard webSocketHandlerFactory.isServiceRegistered(at: head.uri) else { return nil }
var headers = HTTPHeaders()
if let wsProtocol = head.headers["Sec-WebSocket-Protocol"].first {
headers.add(name: "Sec-WebSocket-Protocol", value: wsProtocol)
}
if let key = head.headers["Sec-WebSocket-Key"].first {
headers.add(name: "Sec-WebSocket-Key", value: key)
}
return headers
return self.shouldUpgradeToWebSocket(webSocketHandlerFactory: webSocketHandlerFactory, head: head)
}, upgradePipelineHandler: { (channel: Channel, request: HTTPRequestHead) in
guard let ctx = channelHandlerCtx else { fatalError("Cannot create ServerRequest") }
///TODO: Handle secure upgrade request ("wss://")
let serverRequest = HTTPServerRequest(ctx: ctx, requestHead: request, enableSSL: false)
return channel.pipeline.add(handler: webSocketHandlerFactory.handler(for: serverRequest))
return self.upgradeHandler(webSocketHandlerFactory: webSocketHandlerFactory, request: request)
})
upgraders.append(upgrader)
}
Expand All @@ -135,7 +146,7 @@ public class HTTPServer : Server {
.childChannelInitializer { channel in
let httpHandler = HTTPRequestHandler(for: self)
let config: HTTPUpgradeConfiguration = (upgraders: upgraders, completionHandler: { ctx in
channelHandlerCtx = ctx
self.ctx = ctx
_ = channel.pipeline.remove(handler: httpHandler)
})
return channel.pipeline.add(handler: IdleStateHandler(allTimeout: TimeAmount.seconds(Int(HTTPRequestHandler.keepAliveTimeout)))).then {
Expand Down
4 changes: 2 additions & 2 deletions Sources/KituraNet/HTTP/HTTPServerResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public class HTTPServerResponse: ServerResponse {
self.channel = channel
self.handler = handler
self.buffer = channel.allocator.buffer(capacity: HTTPServerResponse.bufferSize)
let httpVersionMajor = handler.serverRequest?.httpVersionMajor ?? 0
let httpVersionMinor = handler.serverRequest?.httpVersionMinor ?? 0
let httpVersionMajor = handler.serverRequest?.httpVersionMajor ?? 1
let httpVersionMinor = handler.serverRequest?.httpVersionMinor ?? 1
self.httpVersion = HTTPVersion(major: httpVersionMajor, minor: httpVersionMinor)
headers["Date"] = [SPIUtils.httpDate()]
}
Expand Down