GRPCClientConnection.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import NIO
  18. import NIOHTTP2
  19. import NIOSSL
  20. import NIOTLS
  21. /// Underlying channel and HTTP/2 stream multiplexer.
  22. ///
  23. /// Different service clients implementing `GRPCClient` may share an instance of this class.
  24. ///
  25. /// The connection is initially setup with a handler to verify that TLS was established
  26. /// successfully (assuming TLS is being used).
  27. ///
  28. /// ▲ |
  29. /// HTTP2Frame│ │HTTP2Frame
  30. /// ┌─┴───────────────────────▼─┐
  31. /// │ HTTP2StreamMultiplexer |
  32. /// └─▲───────────────────────┬─┘
  33. /// HTTP2Frame│ │HTTP2Frame
  34. /// ┌─┴───────────────────────▼─┐
  35. /// │ NIOHTTP2Handler │
  36. /// └─▲───────────────────────┬─┘
  37. /// ByteBuffer│ │ByteBuffer
  38. /// ┌─┴───────────────────────▼─┐
  39. /// │ GRPCTLSVerificationHandler│
  40. /// └─▲───────────────────────┬─┘
  41. /// ByteBuffer│ │ByteBuffer
  42. /// ┌─┴───────────────────────▼─┐
  43. /// │ NIOSSLHandler │
  44. /// └─▲───────────────────────┬─┘
  45. /// ByteBuffer│ │ByteBuffer
  46. /// │ ▼
  47. ///
  48. /// The `GRPCTLSVerificationHandler` observes the outcome of the SSL handshake and determines
  49. /// whether a `GRPCClientConnection` should be returned to the user. In either eventuality, the
  50. /// handler removes itself from the pipeline once TLS has been verified. There is also a delegated
  51. /// error handler after the `HTTPStreamMultiplexer` in the main channel which uses the error
  52. /// delegate associated with this connection (see `GRPCDelegatingErrorHandler`).
  53. ///
  54. /// See `BaseClientCall` for a description of the remainder of the client pipeline.
  55. open class GRPCClientConnection {
  56. /// Makes and configures a `ClientBootstrap` using the provided configuration.
  57. ///
  58. /// Enables `SO_REUSEADDR` and `TCP_NODELAY` and configures the `channelInitializer` to use the
  59. /// handlers detailed in the documentation for `GRPCClientConnection`.
  60. ///
  61. /// - Parameter configuration: The configuration to prepare the bootstrap with.
  62. public class func makeBootstrap(configuration: Configuration) -> ClientBootstrap {
  63. let bootstrap = ClientBootstrap(group: configuration.eventLoopGroup)
  64. // Enable SO_REUSEADDR and TCP_NODELAY.
  65. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  66. .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  67. .channelInitializer { channel in
  68. let tlsConfigured = configuration.tlsConfiguration.map { tlsConfiguration in
  69. channel.configureTLS(tlsConfiguration, errorDelegate: configuration.errorDelegate)
  70. }
  71. return (tlsConfigured ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  72. channel.configureHTTP2Pipeline(mode: .client)
  73. }.flatMap { _ in
  74. let errorHandler = GRPCDelegatingErrorHandler(delegate: configuration.errorDelegate)
  75. return channel.pipeline.addHandler(errorHandler)
  76. }
  77. }
  78. return bootstrap
  79. }
  80. /// Verifies that a TLS handshake was successful by using the `GRPCTLSVerificationHandler`.
  81. ///
  82. /// - Parameter channel: The channel to verify successful TLS setup on.
  83. public class func verifyTLS(channel: Channel) -> EventLoopFuture<Void> {
  84. return channel.pipeline.handler(type: GRPCTLSVerificationHandler.self).flatMap {
  85. $0.verification
  86. }
  87. }
  88. /// Makes a `GRPCClientConnection` from the given channel and configuration.
  89. ///
  90. /// - Parameter channel: The channel to use for the connection.
  91. /// - Parameter configuration: The configuration used to create the channel.
  92. public class func makeGRPCClientConnection(
  93. channel: Channel,
  94. configuration: Configuration
  95. ) -> EventLoopFuture<GRPCClientConnection> {
  96. return channel.pipeline.handler(type: HTTP2StreamMultiplexer.self).map { multiplexer in
  97. GRPCClientConnection(channel: channel, multiplexer: multiplexer, configuration: configuration)
  98. }
  99. }
  100. /// Starts a client connection using the given configuration.
  101. ///
  102. /// This involves: creating a `ClientBootstrap`, connecting to a target, verifying that the TLS
  103. /// handshake was successful (if TLS was configured) and creating the `GRPCClientConnection`.
  104. /// See the individual functions for more information:
  105. /// - `makeBootstrap(configuration:)`,
  106. /// - `verifyTLS(channel:)`, and
  107. /// - `makeGRPCClientConnection(channel:configuration:)`.
  108. ///
  109. /// - Parameter configuration: The configuration to start the connection with.
  110. public class func start(_ configuration: Configuration) -> EventLoopFuture<GRPCClientConnection> {
  111. return makeBootstrap(configuration: configuration)
  112. .connect(to: configuration.target)
  113. .flatMap { channel in
  114. let tlsVerified: EventLoopFuture<Void>?
  115. if configuration.tlsConfiguration != nil {
  116. tlsVerified = verifyTLS(channel: channel)
  117. } else {
  118. tlsVerified = nil
  119. }
  120. return (tlsVerified ?? channel.eventLoop.makeSucceededFuture(())).flatMap {
  121. makeGRPCClientConnection(channel: channel, configuration: configuration)
  122. }
  123. }
  124. }
  125. public let channel: Channel
  126. public let multiplexer: HTTP2StreamMultiplexer
  127. public let configuration: Configuration
  128. init(channel: Channel, multiplexer: HTTP2StreamMultiplexer, configuration: Configuration) {
  129. self.channel = channel
  130. self.multiplexer = multiplexer
  131. self.configuration = configuration
  132. }
  133. /// Fired when the client shuts down.
  134. public var onClose: EventLoopFuture<Void> {
  135. return channel.closeFuture
  136. }
  137. public func close() -> EventLoopFuture<Void> {
  138. return channel.close(mode: .all)
  139. }
  140. }
  141. // MARK: - Configuration structures
  142. /// A target to connect to.
  143. public enum ConnectionTarget {
  144. /// The host and port.
  145. case hostAndPort(String, Int)
  146. /// The path of a Unix domain socket.
  147. case unixDomainSocket(String)
  148. /// A NIO socket address.
  149. case socketAddress(SocketAddress)
  150. var host: String? {
  151. guard case .hostAndPort(let host, _) = self else {
  152. return nil
  153. }
  154. return host
  155. }
  156. }
  157. extension GRPCClientConnection {
  158. /// The configuration for a connection.
  159. public struct Configuration {
  160. /// The target to connect to.
  161. public var target: ConnectionTarget
  162. /// The event loop group to run the connection on.
  163. public var eventLoopGroup: EventLoopGroup
  164. /// An error delegate which is called when errors are caught. Provided delegates **must not
  165. /// maintain a strong reference to this `GRPCClientConnection`**. Doing so will cause a retain
  166. /// cycle.
  167. public var errorDelegate: ClientErrorDelegate?
  168. /// TLS configuration for this connection. `nil` if TLS is not desired.
  169. public var tlsConfiguration: TLSConfiguration?
  170. /// The HTTP protocol used for this connection.
  171. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  172. return self.tlsConfiguration == nil ? .http : .https
  173. }
  174. /// Create a `Configuration` with some pre-defined defaults.
  175. ///
  176. /// - Parameter target: The target to connect to.
  177. /// - Parameter eventLoopGroup: The event loop group to run the connection on.
  178. /// - Parameter errorDelegate: The error delegate, defaulting to a delegate which will log only
  179. /// on debug builds.
  180. /// - Parameter tlsConfiguration: TLS configuration, defaulting to `nil`.
  181. public init(
  182. target: ConnectionTarget,
  183. eventLoopGroup: EventLoopGroup,
  184. errorDelegate: ClientErrorDelegate? = DebugOnlyLoggingClientErrorDelegate.shared,
  185. tlsConfiguration: TLSConfiguration? = nil
  186. ) {
  187. self.target = target
  188. self.eventLoopGroup = eventLoopGroup
  189. self.errorDelegate = errorDelegate
  190. self.tlsConfiguration = tlsConfiguration
  191. }
  192. }
  193. /// The TLS configuration for a connection.
  194. public struct TLSConfiguration {
  195. /// The SSL context to use.
  196. public var sslContext: NIOSSLContext
  197. /// Value to use for TLS SNI extension; this must not be an IP address.
  198. public var hostnameOverride: String?
  199. public init(sslContext: NIOSSLContext, hostnameOverride: String? = nil) {
  200. self.sslContext = sslContext
  201. self.hostnameOverride = hostnameOverride
  202. }
  203. }
  204. }
  205. // MARK: - Configuration helpers/extensions
  206. fileprivate extension ClientBootstrap {
  207. /// Connect to the given connection target.
  208. ///
  209. /// - Parameter target: The target to connect to.
  210. func connect(to target: ConnectionTarget) -> EventLoopFuture<Channel> {
  211. switch target {
  212. case .hostAndPort(let host, let port):
  213. return self.connect(host: host, port: port)
  214. case .unixDomainSocket(let path):
  215. return self.connect(unixDomainSocketPath: path)
  216. case .socketAddress(let address):
  217. return self.connect(to: address)
  218. }
  219. }
  220. }
  221. fileprivate extension Channel {
  222. /// Configure the channel with TLS.
  223. ///
  224. /// This function adds two handlers to the pipeline: the `NIOSSLClientHandler` to handle TLS, and
  225. /// the `GRPCTLSVerificationHandler` which verifies that a successful handshake was completed.
  226. ///
  227. /// - Parameter configuration: The configuration to configure the channel with.
  228. /// - Parameter errorDelegate: The error delegate to use for the TLS verification handler.
  229. func configureTLS(
  230. _ configuration: GRPCClientConnection.TLSConfiguration,
  231. errorDelegate: ClientErrorDelegate?
  232. ) -> EventLoopFuture<Void> {
  233. do {
  234. let sslClientHandler = try NIOSSLClientHandler(
  235. context: configuration.sslContext,
  236. serverHostname: configuration.hostnameOverride)
  237. let verificationHandler = GRPCTLSVerificationHandler(errorDelegate: errorDelegate)
  238. return self.pipeline.addHandlers(sslClientHandler, verificationHandler)
  239. } catch {
  240. return self.eventLoop.makeFailedFuture(error)
  241. }
  242. }
  243. }