diff --git a/Sources/NIOSSL/NIOSSLClientHandler.swift b/Sources/NIOSSL/NIOSSLClientHandler.swift index 9eb4ef89..24f19291 100644 --- a/Sources/NIOSSL/NIOSSLClientHandler.swift +++ b/Sources/NIOSSL/NIOSSLClientHandler.swift @@ -50,6 +50,6 @@ public final class NIOSSLClientHandler: NIOSSLHandler { connection.setVerificationCallback(verificationCallback) } - super.init(connection: connection) + super.init(connection: connection, shutdownTimeout: context.configuration.shutdownTimeout) } } diff --git a/Sources/NIOSSL/NIOSSLHandler.swift b/Sources/NIOSSL/NIOSSLHandler.swift index a4a01f3b..8499ed69 100644 --- a/Sources/NIOSSL/NIOSSLHandler.swift +++ b/Sources/NIOSSL/NIOSSLHandler.swift @@ -35,7 +35,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo case handshaking case active case unwrapping - case closing + case closing(Scheduled) case unwrapped case closed } @@ -48,10 +48,12 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo private var shutdownPromise: EventLoopPromise? private var didDeliverData: Bool = false private var storedContext: ChannelHandlerContext? = nil + private var shutdownTimeout: TimeAmount - internal init(connection: SSLConnection) { + internal init(connection: SSLConnection, shutdownTimeout: TimeAmount) { self.connection = connection self.bufferedWrites = MarkedCircularBuffer(initialCapacity: 96) // 96 brings the total size of the buffer to just shy of one page + self.shutdownTimeout = shutdownTimeout } public func handlerAdded(context: ChannelHandlerContext) { @@ -174,7 +176,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo // We've been asked to close the connection, but we were currently unwrapping. // We don't have to send any CLOSE_NOTIFY, but we now need to upgrade ourselves: // closing is a more extreme activity than unwrapping. - self.state = .closing + self.state = .closing(self.scheduleTimedOutShutdown(context: context)) if let promise = promise, let closePromise = self.closePromise { closePromise.futureResult.cascade(to: promise) } else if let promise = promise { @@ -190,7 +192,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo case .active, .handshaking: // We need to begin processing shutdown now. We can't fire the promise for a // while though. - self.state = .closing + self.state = .closing(self.scheduleTimedOutShutdown(context: context)) closePromise = promise doShutdownStep(context: context) } @@ -254,15 +256,17 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo /// Once `state` has transitioned to `.closed`, further calls to this method will /// do nothing. private func doShutdownStep(context: ChannelHandlerContext) { - guard self.state != .closed else { + if case .closed = self.state { return } let result = connection.doShutdown() + var uncleanScheduledShutdown: Scheduled? let targetCompleteState: ConnectionState switch self.state { - case .closing: + case .closing(let scheduledShutdown): + uncleanScheduledShutdown = scheduledShutdown targetCompleteState = .closed case .unwrapping: targetCompleteState = .unwrapped @@ -274,7 +278,8 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo case .incomplete: writeDataToNetwork(context: context, promise: nil) case .complete: - state = targetCompleteState + uncleanScheduledShutdown?.cancel() + self.state = targetCompleteState writeDataToNetwork(context: context, promise: nil) // TODO(cory): This should probably fire out of the BoringSSL info callback. @@ -289,12 +294,22 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo preconditionFailure("Cannot be in \(targetCompleteState) at this code point") } case .failed(let err): + uncleanScheduledShutdown?.cancel() // TODO(cory): This should probably fire out of the BoringSSL info callback. context.fireErrorCaught(NIOSSLError.shutdownFailed(err)) channelClose(context: context, reason: NIOSSLError.shutdownFailed(err)) } } + /// Creates a scheduled task to perform an unclean shutdown in event of a clean shutdown timing + /// out. This task should be cancelled if the shutdown does not time out. + private func scheduleTimedOutShutdown(context: ChannelHandlerContext) -> Scheduled { + return context.eventLoop.scheduleTask(in: self.shutdownTimeout) { + self.state = .closed + self.channelClose(context: context, reason: NIOSSLCloseTimedOutError()) + } + } + /// Loops over the `SSL` object, decoding encrypted application data until there is /// no more available. private func doDecodeData(context: ChannelHandlerContext) { @@ -334,7 +349,7 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo case .idle, .closed, .unwrapped, .handshaking: preconditionFailure("Should not get zeroReturn in \(self.state)") case .active: - self.state = .closing + self.state = .closing(self.scheduleTimedOutShutdown(context: context)) case .unwrapping, .closing: break } diff --git a/Sources/NIOSSL/NIOSSLServerHandler.swift b/Sources/NIOSSL/NIOSSLServerHandler.swift index 7373a1d8..efeb20e9 100644 --- a/Sources/NIOSSL/NIOSSLServerHandler.swift +++ b/Sources/NIOSSL/NIOSSLServerHandler.swift @@ -29,6 +29,6 @@ public final class NIOSSLServerHandler: NIOSSLHandler { connection.setVerificationCallback(verificationCallback) } - super.init(connection: connection) + super.init(connection: connection, shutdownTimeout: context.configuration.shutdownTimeout) } } diff --git a/Sources/NIOSSL/SSLErrors.swift b/Sources/NIOSSL/SSLErrors.swift index ef3d3389..d5aba0e4 100644 --- a/Sources/NIOSSL/SSLErrors.swift +++ b/Sources/NIOSSL/SSLErrors.swift @@ -82,6 +82,9 @@ extension NIOSSLError: Equatable { } } +/// Closing the TLS channel cleanly timed out, so it was closed uncleanly. +public struct NIOSSLCloseTimedOutError: Error {} + /// An enum that wraps individual BoringSSL errors directly. public enum BoringSSLError: Error { case noError diff --git a/Sources/NIOSSL/TLSConfiguration.swift b/Sources/NIOSSL/TLSConfiguration.swift index 4d7e6a12..e1960294 100644 --- a/Sources/NIOSSL/TLSConfiguration.swift +++ b/Sources/NIOSSL/TLSConfiguration.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import CNIOBoringSSL +import NIO /// Known and supported TLS versions. public enum TLSVersion { @@ -145,9 +146,13 @@ public struct TLSConfiguration { self.encodedApplicationProtocols = newValue.map(encodeALPNIdentifier) } } - + internal var encodedApplicationProtocols: [[UInt8]] + /// The amount of time to wait after initiating a shutdown before performing an unclean + /// shutdown. Defaults to 5 seconds. + public var shutdownTimeout: TimeAmount + /// A callback that can be used to implement `SSLKEYLOGFILE` support. public var keyLogCallback: NIOSSLKeyLogCallback? @@ -159,6 +164,7 @@ public struct TLSConfiguration { certificateChain: [NIOSSLCertificateSource], privateKey: NIOSSLPrivateKeySource?, applicationProtocols: [String], + shutdownTimeout: TimeAmount, keyLogCallback: NIOSSLKeyLogCallback?) { self.cipherSuites = cipherSuites self.minimumTLSVersion = minimumTLSVersion @@ -168,6 +174,7 @@ public struct TLSConfiguration { self.certificateChain = certificateChain self.privateKey = privateKey self.encodedApplicationProtocols = [] + self.shutdownTimeout = shutdownTimeout self.applicationProtocols = applicationProtocols self.keyLogCallback = keyLogCallback } @@ -184,6 +191,7 @@ public struct TLSConfiguration { certificateVerification: CertificateVerification = .none, trustRoots: NIOSSLTrustRoots = .default, applicationProtocols: [String] = [], + shutdownTimeout: TimeAmount = .seconds(5), keyLogCallback: NIOSSLKeyLogCallback? = nil) -> TLSConfiguration { return TLSConfiguration(cipherSuites: cipherSuites, minimumTLSVersion: minimumTLSVersion, @@ -193,6 +201,7 @@ public struct TLSConfiguration { certificateChain: certificateChain, privateKey: privateKey, applicationProtocols: applicationProtocols, + shutdownTimeout: shutdownTimeout, keyLogCallback: keyLogCallback) } @@ -209,6 +218,7 @@ public struct TLSConfiguration { certificateChain: [NIOSSLCertificateSource] = [], privateKey: NIOSSLPrivateKeySource? = nil, applicationProtocols: [String] = [], + shutdownTimeout: TimeAmount = .seconds(5), keyLogCallback: NIOSSLKeyLogCallback? = nil) -> TLSConfiguration { return TLSConfiguration(cipherSuites: cipherSuites, minimumTLSVersion: minimumTLSVersion, @@ -218,6 +228,7 @@ public struct TLSConfiguration { certificateChain: certificateChain, privateKey: privateKey, applicationProtocols: applicationProtocols, + shutdownTimeout: shutdownTimeout, keyLogCallback: keyLogCallback) } } diff --git a/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift b/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift index fe3b857e..067ef537 100644 --- a/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift +++ b/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift @@ -47,6 +47,7 @@ extension NIOSSLIntegrationTest { ("testForcingVerificationFailure", testForcingVerificationFailure), ("testExtractingCertificates", testExtractingCertificates), ("testRepeatedClosure", testRepeatedClosure), + ("testClosureTimeout", testClosureTimeout), ("testReceivingGibberishAfterAttemptingToClose", testReceivingGibberishAfterAttemptingToClose), ("testPendingWritesFailWhenFlushedOnClose", testPendingWritesFailWhenFlushedOnClose), ("testChannelInactiveAfterCloseNotify", testChannelInactiveAfterCloseNotify), diff --git a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift index 16f9d2a5..2597ab38 100644 --- a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift +++ b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift @@ -1285,6 +1285,55 @@ class NIOSSLIntegrationTest: XCTestCase { XCTAssertTrue(closed) } + func testClosureTimeout() throws { + let serverChannel = EmbeddedChannel() + let clientChannel = EmbeddedChannel() + + defer { + // We expect both cases to throw + XCTAssertThrowsError(try serverChannel.finish()) + XCTAssertThrowsError(try clientChannel.finish()) + } + + let context = try assertNoThrowWithValue(configuredSSLContext()) + + XCTAssertNoThrow(try serverChannel.pipeline.addHandler(NIOSSLServerHandler(context: context)).wait()) + XCTAssertNoThrow(try clientChannel.pipeline.addHandler(NIOSSLClientHandler(context: context, serverHostname: nil)).wait()) + let handshakeHandler = HandshakeCompletedHandler() + XCTAssertNoThrow(try clientChannel.pipeline.addHandler(handshakeHandler).wait()) + + // Connect. This should lead to a completed handshake. + let addr: SocketAddress = try SocketAddress(unixDomainSocketPath: "/tmp/whatever") + let connectFuture = clientChannel.connect(to: addr) + serverChannel.pipeline.fireChannelActive() + try interactInMemory(clientChannel: clientChannel, serverChannel: serverChannel) + try connectFuture.wait() + XCTAssertTrue(handshakeHandler.handshakeSucceeded) + + var closed = false + clientChannel.close().whenComplete { _ in + closed = true + } + + clientChannel.close().whenFailure { error in + XCTAssertTrue(error is NIOSSLCloseTimedOutError) + } + + // Send CLOSE_NOTIFY from the client. + while let clientDatum = try clientChannel.readOutbound(as: IOData.self) { + try serverChannel.writeInbound(clientDatum) + } + + XCTAssertFalse(closed) + + // Let the shutdown timeout. + clientChannel.embeddedEventLoop.advanceTime(by: context.configuration.shutdownTimeout) + XCTAssertTrue(closed) + + // Let the server shutdown. + try interactInMemory(clientChannel: clientChannel, serverChannel: serverChannel) + } + func testReceivingGibberishAfterAttemptingToClose() throws { let serverChannel = EmbeddedChannel() let clientChannel = EmbeddedChannel()