| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300 |
- /*
- * Copyright 2021, gRPC Authors All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- import Logging
- import NIOCore
- import NIOPosix
- import NIOTransportServices
- #if canImport(NIOSSL)
- import NIOSSL
- #endif
- #if canImport(Network)
- import Network
- #endif
- @usableFromInline
- internal protocol ConnectionManagerChannelProvider {
- /// Make an `EventLoopFuture<Channel>`.
- ///
- /// - Parameters:
- /// - connectionManager: The `ConnectionManager` requesting the `Channel`.
- /// - eventLoop: The `EventLoop` to use for the`Channel`.
- /// - connectTimeout: Optional connection timeout when starting the connection.
- /// - logger: A logger.
- func makeChannel(
- managedBy connectionManager: ConnectionManager,
- onEventLoop eventLoop: EventLoop,
- connectTimeout: TimeAmount?,
- logger: Logger
- ) -> EventLoopFuture<Channel>
- }
- @usableFromInline
- internal struct DefaultChannelProvider: ConnectionManagerChannelProvider {
- @usableFromInline
- enum TLSMode {
- #if canImport(NIOSSL)
- case configureWithNIOSSL(Result<NIOSSLContext, Error>)
- #endif // canImport(NIOSSL)
- case configureWithNetworkFramework
- case disabled
- }
- @usableFromInline
- internal var connectionTarget: ConnectionTarget
- @usableFromInline
- internal var connectionKeepalive: ClientConnectionKeepalive
- @usableFromInline
- internal var connectionIdleTimeout: TimeAmount
- @usableFromInline
- internal var tlsMode: TLSMode
- @usableFromInline
- internal var tlsConfiguration: GRPCTLSConfiguration?
- @usableFromInline
- internal var httpTargetWindowSize: Int
- @usableFromInline
- internal var httpMaxFrameSize: Int
- @usableFromInline
- internal var httpMaxResetStreams: Int
- @usableFromInline
- internal var errorDelegate: Optional<ClientErrorDelegate>
- @usableFromInline
- internal var debugChannelInitializer: Optional<(Channel) -> EventLoopFuture<Void>>
- #if canImport(Network)
- @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
- @usableFromInline
- internal var nwParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
- get {
- self._nwParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
- }
- set {
- self._nwParametersConfigurator = newValue
- }
- }
- private var _nwParametersConfigurator: (any Sendable)?
- #endif
- #if canImport(Network)
- @inlinable
- @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
- internal init(
- connectionTarget: ConnectionTarget,
- connectionKeepalive: ClientConnectionKeepalive,
- connectionIdleTimeout: TimeAmount,
- tlsMode: TLSMode,
- tlsConfiguration: GRPCTLSConfiguration?,
- httpTargetWindowSize: Int,
- httpMaxFrameSize: Int,
- httpMaxResetStreams: Int,
- errorDelegate: ClientErrorDelegate?,
- debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?,
- nwParametersConfigurator: (@Sendable (NWParameters) -> Void)?
- ) {
- self.init(
- connectionTarget: connectionTarget,
- connectionKeepalive: connectionKeepalive,
- connectionIdleTimeout: connectionIdleTimeout,
- tlsMode: tlsMode,
- tlsConfiguration: tlsConfiguration,
- httpTargetWindowSize: httpTargetWindowSize,
- httpMaxFrameSize: httpMaxFrameSize,
- httpMaxResetStreams: httpMaxResetStreams,
- errorDelegate: errorDelegate,
- debugChannelInitializer: debugChannelInitializer
- )
- self.nwParametersConfigurator = nwParametersConfigurator
- }
- #endif
- @inlinable
- internal init(
- connectionTarget: ConnectionTarget,
- connectionKeepalive: ClientConnectionKeepalive,
- connectionIdleTimeout: TimeAmount,
- tlsMode: TLSMode,
- tlsConfiguration: GRPCTLSConfiguration?,
- httpTargetWindowSize: Int,
- httpMaxFrameSize: Int,
- httpMaxResetStreams: Int,
- errorDelegate: ClientErrorDelegate?,
- debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
- ) {
- self.connectionTarget = connectionTarget
- self.connectionKeepalive = connectionKeepalive
- self.connectionIdleTimeout = connectionIdleTimeout
- self.tlsMode = tlsMode
- self.tlsConfiguration = tlsConfiguration
- self.httpTargetWindowSize = httpTargetWindowSize
- self.httpMaxFrameSize = httpMaxFrameSize
- self.httpMaxResetStreams = httpMaxResetStreams
- self.errorDelegate = errorDelegate
- self.debugChannelInitializer = debugChannelInitializer
- }
- internal init(configuration: ClientConnection.Configuration) {
- // Making a `NIOSSLContext` is expensive and we should only do it (at most) once per TLS
- // configuration. We do it now and store it in our `tlsMode` and surface any error during
- // channel creation (we're limited by our API in when we can throw any error).
- let tlsMode: TLSMode
- if let tlsConfiguration = configuration.tlsConfiguration {
- if tlsConfiguration.isNetworkFrameworkTLSBackend {
- tlsMode = .configureWithNetworkFramework
- } else {
- #if canImport(NIOSSL)
- // The '!' is okay here, we have a `tlsConfiguration` (so we must be using TLS) and we know
- // it's not backed by Network.framework, so it must be backed by NIOSSL.
- tlsMode = .configureWithNIOSSL(Result { try tlsConfiguration.makeNIOSSLContext()! })
- #else
- // TLS is configured, and we aren't using a Network.framework TLS backend, so we must be
- // using NIOSSL, so we must be able to import it.
- fatalError()
- #endif // canImport(NIOSSL)
- }
- } else {
- tlsMode = .disabled
- }
- self.init(
- connectionTarget: configuration.target,
- connectionKeepalive: configuration.connectionKeepalive,
- connectionIdleTimeout: configuration.connectionIdleTimeout,
- tlsMode: tlsMode,
- tlsConfiguration: configuration.tlsConfiguration,
- httpTargetWindowSize: configuration.httpTargetWindowSize,
- httpMaxFrameSize: configuration.httpMaxFrameSize,
- httpMaxResetStreams: configuration.httpMaxResetStreams,
- errorDelegate: configuration.errorDelegate,
- debugChannelInitializer: configuration.debugChannelInitializer
- )
- #if canImport(Network)
- if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *) {
- self.nwParametersConfigurator = configuration.nwParametersConfigurator
- }
- #endif
- }
- private var serverHostname: String? {
- let hostname = self.tlsConfiguration?.hostnameOverride ?? self.connectionTarget.host
- return hostname.isIPAddress ? nil : hostname
- }
- private var hasTLS: Bool {
- return self.tlsConfiguration != nil
- }
- private func requiresZeroLengthWorkaround(eventLoop: EventLoop) -> Bool {
- return PlatformSupport.requiresZeroLengthWriteWorkaround(group: eventLoop, hasTLS: self.hasTLS)
- }
- @usableFromInline
- internal func makeChannel(
- managedBy connectionManager: ConnectionManager,
- onEventLoop eventLoop: EventLoop,
- connectTimeout: TimeAmount?,
- logger: Logger
- ) -> EventLoopFuture<Channel> {
- let hostname = self.serverHostname
- let needsZeroLengthWriteWorkaround = self.requiresZeroLengthWorkaround(eventLoop: eventLoop)
- var bootstrap = PlatformSupport.makeClientBootstrap(
- group: eventLoop,
- tlsConfiguration: self.tlsConfiguration,
- logger: logger
- )
- bootstrap =
- bootstrap
- .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
- .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
- .channelInitializer { channel in
- let sync = channel.pipeline.syncOperations
- do {
- if needsZeroLengthWriteWorkaround {
- try sync.addHandler(NIOFilterEmptyWritesHandler())
- }
- // We have a NIOSSL context to apply. If we're using TLS from NIOTS then the bootstrap
- // will already have the TLS options applied.
- switch self.tlsMode {
- #if canImport(NIOSSL)
- case let .configureWithNIOSSL(sslContext):
- try sync.configureNIOSSLForGRPCClient(
- sslContext: sslContext,
- serverHostname: hostname,
- customVerificationCallback: self.tlsConfiguration?.nioSSLCustomVerificationCallback,
- logger: logger
- )
- #endif // canImport(NIOSSL)
- // Network.framework TLS configuration is applied when creating the bootstrap so is a
- // no-op here.
- case .configureWithNetworkFramework,
- .disabled:
- ()
- }
- try sync.configureHTTP2AndGRPCHandlersForGRPCClient(
- channel: channel,
- connectionManager: connectionManager,
- connectionKeepalive: self.connectionKeepalive,
- connectionIdleTimeout: self.connectionIdleTimeout,
- httpTargetWindowSize: self.httpTargetWindowSize,
- httpMaxFrameSize: self.httpMaxFrameSize,
- httpMaxResetStreams: self.httpMaxResetStreams,
- errorDelegate: self.errorDelegate,
- logger: logger
- )
- } catch {
- return channel.eventLoop.makeFailedFuture(error)
- }
- // Run the debug initializer, if there is one.
- if let debugInitializer = self.debugChannelInitializer {
- return debugInitializer(channel)
- } else {
- return channel.eventLoop.makeSucceededVoidFuture()
- }
- }
- if let connectTimeout = connectTimeout {
- _ = bootstrap.connectTimeout(connectTimeout)
- }
- #if canImport(Network)
- if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
- let configurator = self.nwParametersConfigurator,
- let transportServicesBootstrap = bootstrap as? NIOTSConnectionBootstrap
- {
- _ = transportServicesBootstrap.configureNWParameters(configurator)
- }
- #endif
- return bootstrap.connect(to: self.connectionTarget)
- }
- }
|