GRPCClientConnection.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. /// Underlying channel and HTTP/2 stream multiplexer.
  21. ///
  22. /// Different service clients implementing `GRPCClient` may share an instance of this class.
  23. open class GRPCClientConnection {
  24. /// Starts a connection to the given host and port.
  25. ///
  26. /// - Parameters:
  27. /// - host: Host to connect to.
  28. /// - port: Port on the host to connect to.
  29. /// - eventLoopGroup: Event loop group to run the connection on.
  30. /// - tlsMode: How TLS should be configured for this connection.
  31. /// - hostOverride: Value to use for TLS SNI extension; this must not be an IP address. Ignored
  32. /// if `tlsMode` is `.none`.
  33. /// - Returns: A future which will be fulfilled with a connection to the remote peer.
  34. public static func start(
  35. host: String,
  36. port: Int,
  37. eventLoopGroup: EventLoopGroup,
  38. tls tlsMode: TLSMode = .none,
  39. hostOverride: String? = nil
  40. ) throws -> EventLoopFuture<GRPCClientConnection> {
  41. // We need to capture the multiplexer from the channel initializer to store it after connection.
  42. let multiplexerPromise: EventLoopPromise<HTTP2StreamMultiplexer> = eventLoopGroup.next().makePromise()
  43. let bootstrap = ClientBootstrap(group: eventLoopGroup)
  44. // Enable SO_REUSEADDR.
  45. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  46. .channelInitializer { channel in
  47. let multiplexer = configureTLS(mode: tlsMode, channel: channel, host: hostOverride ?? host).flatMap {
  48. channel.configureHTTP2Pipeline(mode: .client)
  49. }
  50. multiplexer.cascade(to: multiplexerPromise)
  51. return multiplexer.map { _ in }
  52. }
  53. return bootstrap.connect(host: host, port: port)
  54. .and(multiplexerPromise.futureResult)
  55. .map { channel, multiplexer in GRPCClientConnection(channel: channel, multiplexer: multiplexer, host: host, httpProtocol: tlsMode.httpProtocol) }
  56. }
  57. /// Configure an SSL handler on the channel, if one is required.
  58. ///
  59. /// - Parameters:
  60. /// - mode: TLS mode to use when creating the new handler.
  61. /// - channel: The channel on which to add the SSL handler.
  62. /// - host: The hostname of the server we're connecting to.
  63. /// - Returns: A future which will be succeeded when the pipeline has been configured.
  64. private static func configureTLS(mode tls: TLSMode, channel: Channel, host: String) -> EventLoopFuture<Void> {
  65. let handlerAddedPromise: EventLoopPromise<Void> = channel.eventLoop.makePromise()
  66. do {
  67. guard let sslContext = try tls.makeSSLContext() else {
  68. handlerAddedPromise.succeed(())
  69. return handlerAddedPromise.futureResult
  70. }
  71. channel.pipeline.addHandler(try NIOSSLClientHandler(context: sslContext, serverHostname: host)).cascade(to: handlerAddedPromise)
  72. } catch {
  73. handlerAddedPromise.fail(error)
  74. }
  75. return handlerAddedPromise.futureResult
  76. }
  77. public let channel: Channel
  78. public let multiplexer: HTTP2StreamMultiplexer
  79. public let host: String
  80. public let httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol
  81. init(channel: Channel, multiplexer: HTTP2StreamMultiplexer, host: String, httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol) {
  82. self.channel = channel
  83. self.multiplexer = multiplexer
  84. self.host = host
  85. self.httpProtocol = httpProtocol
  86. }
  87. /// Fired when the client shuts down.
  88. public var onClose: EventLoopFuture<Void> {
  89. return channel.closeFuture
  90. }
  91. public func close() -> EventLoopFuture<Void> {
  92. return channel.close(mode: .all)
  93. }
  94. }
  95. extension GRPCClientConnection {
  96. public enum TLSMode {
  97. case none
  98. case anonymous
  99. case custom(NIOSSLContext)
  100. /// Returns an SSL context for the TLS mode.
  101. ///
  102. /// - Returns: An SSL context for the TLS mode, or `nil` if TLS is not being used.
  103. public func makeSSLContext() throws -> NIOSSLContext? {
  104. switch self {
  105. case .none:
  106. return nil
  107. case .anonymous:
  108. return try NIOSSLContext(configuration: .forClient())
  109. case .custom(let context):
  110. return context
  111. }
  112. }
  113. /// Rethrns the HTTP protocol for the TLS mode.
  114. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  115. switch self {
  116. case .none:
  117. return .http
  118. case .anonymous, .custom:
  119. return .https
  120. }
  121. }
  122. }
  123. }