mirror of
https://github.com/apple/swift-nio
synced 2026-11-30 05:28:44 +00:00
Add ALPN handler
This commit is contained in:
1 parent
b9e70f6e42
commit
8efedf33fa
8 files changed
+348
-6
No files matched your search
@@ -164,7 +164,7 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler {
|
||||
writeDataToNetwork(ctx: ctx, promise: nil)
|
||||
|
||||
// TODO(cory): This event should probably fire out of the OpenSSL info callback.
|
||||
ctx.fireUserInboundEventTriggered(event: wrapInboundUserEventOut(TLSUserEvent.handshakeCompleted))
|
||||
ctx.fireUserInboundEventTriggered(event: wrapInboundUserEventOut(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)))
|
||||
|
||||
// We need to unbuffer any pending writes. We will have pending writes if the user attempted to write
|
||||
// before we completed the handshake.
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIO
|
||||
|
||||
public enum ALPNResult: Equatable {
|
||||
case negotiated(String)
|
||||
case fallback
|
||||
|
||||
public static func ==(lhs: ALPNResult, rhs: ALPNResult) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.negotiated(let p1), .negotiated(let p2)):
|
||||
return p1 == p2
|
||||
case (.fallback, .fallback):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler {
|
||||
public typealias InboundIn = Any
|
||||
public typealias InboundOut = Any
|
||||
public typealias InboundUserEventIn = TLSUserEvent
|
||||
|
||||
private let completionHandler: (ALPNResult) -> Future<Void>
|
||||
private var waitingForUser: Bool
|
||||
private var eventBuffer: [NIOAny]
|
||||
|
||||
public init(alpnCompleteHandler: @escaping (ALPNResult) -> Future<Void>) {
|
||||
self.completionHandler = alpnCompleteHandler
|
||||
self.waitingForUser = false
|
||||
self.eventBuffer = []
|
||||
}
|
||||
|
||||
public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) {
|
||||
guard let tlsEvent = tryUnwrapInboundUserEventIn(event) else {
|
||||
ctx.fireUserInboundEventTriggered(event: event)
|
||||
return
|
||||
}
|
||||
|
||||
switch tlsEvent {
|
||||
case .handshakeCompleted(let p):
|
||||
handshakeCompleted(context: ctx, negotiatedProtocol: p)
|
||||
default:
|
||||
ctx.fireUserInboundEventTriggered(event: event)
|
||||
}
|
||||
}
|
||||
|
||||
public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
|
||||
if waitingForUser {
|
||||
eventBuffer.append(data)
|
||||
} else {
|
||||
ctx.fireChannelRead(data: data)
|
||||
}
|
||||
}
|
||||
|
||||
private func handshakeCompleted(context: ChannelHandlerContext, negotiatedProtocol: String?) {
|
||||
waitingForUser = true
|
||||
|
||||
let result: ALPNResult
|
||||
if let negotiatedProtocol = negotiatedProtocol {
|
||||
result = .negotiated(negotiatedProtocol)
|
||||
} else {
|
||||
result = .fallback
|
||||
}
|
||||
|
||||
let switchFuture = completionHandler(result)
|
||||
switchFuture.whenComplete { _ in
|
||||
self.unbuffer(context: context)
|
||||
_ = context.pipeline?.remove(handler: self)
|
||||
}
|
||||
}
|
||||
|
||||
private func unbuffer(context: ChannelHandlerContext) {
|
||||
for datum in eventBuffer {
|
||||
context.fireChannelRead(data: datum)
|
||||
}
|
||||
let buffer = eventBuffer
|
||||
eventBuffer = []
|
||||
waitingForUser = false
|
||||
if buffer.count > 0 {
|
||||
context.fireChannelReadComplete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,17 @@
|
||||
|
||||
/// Common user events sent by all TLS implementations.
|
||||
public enum TLSUserEvent: Equatable {
|
||||
case handshakeCompleted
|
||||
case handshakeCompleted(negotiatedProtocol: String?)
|
||||
case shutdownCompleted
|
||||
|
||||
public static func ==(lhs: TLSUserEvent, rhs: TLSUserEvent) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.handshakeCompleted(let p1), .handshakeCompleted(let p2)):
|
||||
return p1 == p2
|
||||
case (.shutdownCompleted, .shutdownCompleted):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import XCTest
|
||||
|
||||
XCTMain([
|
||||
testCase(AdaptiveRecvByteBufferAllocatorTest.allTests),
|
||||
testCase(ApplicationProtocolNegotiationHandlerTests.allTests),
|
||||
testCase(BaseObjectTest.allTests),
|
||||
testCase(ByteBufferTest.allTests),
|
||||
testCase(ByteToMessageDecoderTest.allTests),
|
||||
|
||||
@@ -295,7 +295,7 @@ class OpenSSLIntegrationTest: XCTestCase {
|
||||
let expectedEvents: [EventRecorderHandler<TLSUserEvent>.RecordedEvents] = [
|
||||
.Registered,
|
||||
.Active,
|
||||
.UserEvent(TLSUserEvent.handshakeCompleted),
|
||||
.UserEvent(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)),
|
||||
.Read,
|
||||
.ReadComplete
|
||||
]
|
||||
@@ -337,7 +337,7 @@ class OpenSSLIntegrationTest: XCTestCase {
|
||||
let expectedEvents: [EventRecorderHandler<TLSUserEvent>.RecordedEvents] = [
|
||||
.Registered,
|
||||
.Active,
|
||||
.UserEvent(TLSUserEvent.handshakeCompleted),
|
||||
.UserEvent(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)),
|
||||
.Read,
|
||||
.ReadComplete,
|
||||
.UserEvent(TLSUserEvent.shutdownCompleted),
|
||||
@@ -565,7 +565,7 @@ class OpenSSLIntegrationTest: XCTestCase {
|
||||
|
||||
// At this point the handshake should be complete.
|
||||
try group.next().submit {
|
||||
XCTAssertEqual(recorderHandler.events[..<3], [.Registered, .Active, .UserEvent(.handshakeCompleted)])
|
||||
XCTAssertEqual(recorderHandler.events[..<3], [.Registered, .Active, .UserEvent(.handshakeCompleted(negotiatedProtocol: nil))])
|
||||
}.wait()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
///
|
||||
/// ApplicationProtocolNegotiationHandlerTests+XCTest.swift
|
||||
///
|
||||
import XCTest
|
||||
|
||||
///
|
||||
/// NOTE: This file was generated by generate_linux_tests.rb
|
||||
///
|
||||
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
|
||||
///
|
||||
|
||||
extension ApplicationProtocolNegotiationHandlerTests {
|
||||
|
||||
static var allTests : [(String, (ApplicationProtocolNegotiationHandlerTests) -> () throws -> Void)] {
|
||||
return [
|
||||
("testIgnoresUnknownUserEvents", testIgnoresUnknownUserEvents),
|
||||
("testCallbackReflectsNotificationResult", testCallbackReflectsNotificationResult),
|
||||
("testCallbackNotesFallbackForNoNegotiation", testCallbackNotesFallbackForNoNegotiation),
|
||||
("testNoBufferingBeforeEventFires", testNoBufferingBeforeEventFires),
|
||||
("testBufferingWhileWaitingForFuture", testBufferingWhileWaitingForFuture),
|
||||
("testNothingBufferedDoesNotFireReadCompleted", testNothingBufferedDoesNotFireReadCompleted),
|
||||
("testUnbufferingFiresReadCompleted", testUnbufferingFiresReadCompleted),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import NIO
|
||||
import NIOTLS
|
||||
|
||||
private class ReadCompletedHandler: ChannelInboundHandler {
|
||||
public typealias InboundIn = Any
|
||||
public var readCompleteCount: Int
|
||||
|
||||
init() {
|
||||
readCompleteCount = 0
|
||||
}
|
||||
|
||||
public func channelReadComplete(ctx: ChannelHandlerContext) {
|
||||
readCompleteCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
class ApplicationProtocolNegotiationHandlerTests: XCTestCase {
|
||||
private enum EventType {
|
||||
case basic
|
||||
}
|
||||
|
||||
func testIgnoresUnknownUserEvents() throws {
|
||||
let channel = EmbeddedChannel()
|
||||
let loop = channel.eventLoop as! EmbeddedEventLoop
|
||||
|
||||
let handler = ApplicationProtocolNegotiationHandler { result in
|
||||
XCTFail("Negotiation fired")
|
||||
return loop.newSucceedFuture(result: ())
|
||||
}
|
||||
|
||||
try channel.pipeline.add(handler: handler).wait()
|
||||
|
||||
// Fire a pair of events that should be ignored.
|
||||
channel.pipeline.fireUserInboundEventTriggered(event: EventType.basic)
|
||||
channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.shutdownCompleted)
|
||||
|
||||
// The channel handler should still be in the pipeline.
|
||||
try channel.pipeline.assertContains(handler: handler)
|
||||
}
|
||||
|
||||
private func negotiateTest(event: TLSUserEvent, expectedResult: ALPNResult) throws {
|
||||
let channel = EmbeddedChannel()
|
||||
let loop = channel.eventLoop as! EmbeddedEventLoop
|
||||
let continuePromise: Promise<Void> = loop.newPromise()
|
||||
|
||||
let expectedResult: ALPNResult = .negotiated("h2")
|
||||
var called = false
|
||||
|
||||
let handler = ApplicationProtocolNegotiationHandler { result in
|
||||
XCTAssertEqual(expectedResult, result)
|
||||
called = true
|
||||
return continuePromise.futureResult
|
||||
}
|
||||
|
||||
try channel.pipeline.add(handler: handler).wait()
|
||||
|
||||
// Fire the handshake complete event.
|
||||
channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2"))
|
||||
|
||||
// At this time the callback should have fired, but the handler should still be in
|
||||
// the pipeline.
|
||||
XCTAssertTrue(called)
|
||||
try channel.pipeline.assertContains(handler: handler)
|
||||
|
||||
// Now we fire the future.
|
||||
continuePromise.succeed(result: ())
|
||||
|
||||
// Now the handler should have removed itself from the pipeline.
|
||||
try channel.pipeline.assertDoesNotContain(handler: handler)
|
||||
}
|
||||
|
||||
func testCallbackReflectsNotificationResult() throws {
|
||||
try negotiateTest(event: .handshakeCompleted(negotiatedProtocol: "h2"), expectedResult: .negotiated("h2"))
|
||||
}
|
||||
|
||||
func testCallbackNotesFallbackForNoNegotiation() throws {
|
||||
try negotiateTest(event: .handshakeCompleted(negotiatedProtocol: ""), expectedResult: .fallback)
|
||||
}
|
||||
|
||||
func testNoBufferingBeforeEventFires() throws {
|
||||
let channel = EmbeddedChannel()
|
||||
let loop = channel.eventLoop as! EmbeddedEventLoop
|
||||
|
||||
let handler = ApplicationProtocolNegotiationHandler { result in
|
||||
XCTFail("Should not be called")
|
||||
return loop.newSucceedFuture(result: ())
|
||||
}
|
||||
|
||||
try channel.pipeline.add(handler: handler).wait()
|
||||
|
||||
// The data we write should not be buffered.
|
||||
try channel.writeInbound(data: "hello")
|
||||
XCTAssertEqual(channel.readInbound()!, "hello")
|
||||
}
|
||||
|
||||
func testBufferingWhileWaitingForFuture() throws {
|
||||
let channel = EmbeddedChannel()
|
||||
let loop = channel.eventLoop as! EmbeddedEventLoop
|
||||
let continuePromise: Promise<Void> = loop.newPromise()
|
||||
|
||||
let handler = ApplicationProtocolNegotiationHandler { result in
|
||||
return continuePromise.futureResult
|
||||
}
|
||||
|
||||
try channel.pipeline.add(handler: handler).wait()
|
||||
|
||||
// Fire in the event.
|
||||
channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2"))
|
||||
|
||||
// At this point all writes should be buffered.
|
||||
try channel.writeInbound(data: "writes")
|
||||
try channel.writeInbound(data: "are")
|
||||
try channel.writeInbound(data: "buffered")
|
||||
XCTAssertNil(channel.readInbound())
|
||||
|
||||
// Complete the pipeline swap.
|
||||
continuePromise.succeed(result: ())
|
||||
|
||||
// Now everything should have been unbuffered.
|
||||
XCTAssertEqual(channel.readInbound()!, "writes")
|
||||
XCTAssertEqual(channel.readInbound()!, "are")
|
||||
XCTAssertEqual(channel.readInbound()!, "buffered")
|
||||
}
|
||||
|
||||
func testNothingBufferedDoesNotFireReadCompleted() throws {
|
||||
let channel = EmbeddedChannel()
|
||||
let loop = channel.eventLoop as! EmbeddedEventLoop
|
||||
let continuePromise: Promise<Void> = loop.newPromise()
|
||||
|
||||
let handler = ApplicationProtocolNegotiationHandler { result in
|
||||
return continuePromise.futureResult
|
||||
}
|
||||
let readCompleteHandler = ReadCompletedHandler()
|
||||
|
||||
try channel.pipeline.add(handler: handler).wait()
|
||||
try channel.pipeline.add(handler: readCompleteHandler).wait()
|
||||
|
||||
// Fire in the event.
|
||||
channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2"))
|
||||
|
||||
// At this time, readComplete hasn't fired.
|
||||
XCTAssertEqual(readCompleteHandler.readCompleteCount, 0)
|
||||
|
||||
// Now satisfy the future, which forces data unbuffering. As we haven't buffered any data,
|
||||
// readComplete should not be fired.
|
||||
continuePromise.succeed(result: ())
|
||||
XCTAssertEqual(readCompleteHandler.readCompleteCount, 0)
|
||||
}
|
||||
|
||||
func testUnbufferingFiresReadCompleted() throws {
|
||||
let channel = EmbeddedChannel()
|
||||
let loop = channel.eventLoop as! EmbeddedEventLoop
|
||||
let continuePromise: Promise<Void> = loop.newPromise()
|
||||
|
||||
let handler = ApplicationProtocolNegotiationHandler { result in
|
||||
return continuePromise.futureResult
|
||||
}
|
||||
let readCompleteHandler = ReadCompletedHandler()
|
||||
|
||||
try channel.pipeline.add(handler: handler).wait()
|
||||
try channel.pipeline.add(handler: readCompleteHandler).wait()
|
||||
|
||||
// Fire in the event.
|
||||
channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2"))
|
||||
|
||||
// Send a write, which is buffered.
|
||||
try channel.writeInbound(data: "a write")
|
||||
|
||||
// At this time, readComplete hasn't fired.
|
||||
XCTAssertEqual(readCompleteHandler.readCompleteCount, 1)
|
||||
|
||||
// Now satisfy the future, which forces data unbuffering. This should fire readComplete.
|
||||
continuePromise.succeed(result: ())
|
||||
XCTAssertEqual(channel.readInbound()!, "a write")
|
||||
|
||||
XCTAssertEqual(readCompleteHandler.readCompleteCount, 2)
|
||||
}
|
||||
}
|
||||
@@ -228,7 +228,7 @@ q6U/lEvy1/7zGQ==
|
||||
|
||||
private let ludicrouslyTruncatedPacket = "FgMBAAEB"
|
||||
|
||||
private extension ChannelPipeline {
|
||||
internal extension ChannelPipeline {
|
||||
func contains(handler: ChannelHandler) throws -> Bool {
|
||||
do {
|
||||
let _ = try self.context(handler: handler).wait()
|
||||
|
||||
Reference in new issue
Block a user