HTTP2ServerTransport+Posix.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /*
  2. * Copyright 2024, 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. public import GRPCCore
  17. public import GRPCNIOTransportCore // should be @usableFromInline
  18. internal import NIOCore
  19. internal import NIOExtras
  20. internal import NIOHTTP2
  21. public import NIOPosix // has to be public because of default argument value in init
  22. private import NIOSSL
  23. private import SwiftASN1
  24. private import Synchronization
  25. public import X509
  26. @available(gRPCSwiftNIOTransport 2.0, *)
  27. extension HTTP2ServerTransport {
  28. /// A `ServerTransport` using HTTP/2 built on top of `NIOPosix`.
  29. ///
  30. /// This transport builds on top of SwiftNIO's Posix networking layer and is suitable for use
  31. /// on Linux and Darwin based platform (macOS, iOS, etc.) However, it's *strongly* recommended
  32. /// that if you are targeting Darwin platforms then you should use the `NIOTS` variant of
  33. /// the `HTTP2ServerTransport`.
  34. ///
  35. /// You can control various aspects of connection creation, management, security and RPC behavior via
  36. /// the ``Config``.
  37. ///
  38. /// Beyond creating the transport you don't need to interact with it directly, instead, pass it
  39. /// to a `GRPCServer`:
  40. ///
  41. /// ```swift
  42. /// try await withThrowingDiscardingTaskGroup { group in
  43. /// let transport = HTTP2ServerTransport.Posix(
  44. /// address: .ipv4(host: "127.0.0.1", port: 0),
  45. /// transportSecurity: .plaintext
  46. /// )
  47. /// let server = GRPCServer(transport: transport, services: someServices)
  48. /// group.addTask {
  49. /// try await server.serve()
  50. /// }
  51. ///
  52. /// // ...
  53. /// }
  54. /// ```
  55. public struct Posix: ServerTransport, ListeningServerTransport {
  56. public typealias Bytes = GRPCNIOTransportBytes
  57. private struct ListenerFactory: HTTP2ListenerFactory {
  58. let config: Config
  59. let transportSecurity: TransportSecurity
  60. func makeListeningChannel(
  61. eventLoopGroup: any EventLoopGroup,
  62. address: GRPCNIOTransportCore.SocketAddress,
  63. serverQuiescingHelper: ServerQuiescingHelper
  64. ) async throws -> NIOAsyncChannel<AcceptedChannel, Never> {
  65. let sslContext: NIOSSLContext?
  66. let customVerificationCallback:
  67. (
  68. @Sendable (
  69. [NIOSSLCertificate], EventLoopPromise<NIOSSLVerificationResultWithMetadata>
  70. ) -> Void
  71. )?
  72. switch self.transportSecurity.wrapped {
  73. case .plaintext:
  74. sslContext = nil
  75. customVerificationCallback = nil
  76. case .tls(let tlsConfig):
  77. do {
  78. sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  79. } catch {
  80. throw RuntimeError(
  81. code: .transportError,
  82. message: "Couldn't create SSL context, check your TLS configuration.",
  83. cause: error
  84. )
  85. }
  86. customVerificationCallback = tlsConfig.customVerificationCallback
  87. }
  88. let serverChannel = try await ServerBootstrap(group: eventLoopGroup)
  89. .serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
  90. .serverChannelInitializer { channel in
  91. return channel.eventLoop.makeCompletedFuture {
  92. let quiescingHandler = serverQuiescingHelper.makeServerChannelHandler(
  93. channel: channel
  94. )
  95. try channel.pipeline.syncOperations.addHandler(quiescingHandler)
  96. }.runInitializerIfSet(
  97. self.config.channelDebuggingCallbacks.onBindTCPListener,
  98. on: channel
  99. )
  100. }
  101. .bind(to: address) { channel in
  102. channel.eventLoop.makeCompletedFuture {
  103. if let sslContext {
  104. if let callback = customVerificationCallback {
  105. try channel.pipeline.syncOperations.addHandler(
  106. NIOSSLServerHandler(
  107. context: sslContext,
  108. customVerificationCallbackWithMetadata: callback
  109. )
  110. )
  111. } else {
  112. try channel.pipeline.syncOperations.addHandler(
  113. NIOSSLServerHandler(context: sslContext)
  114. )
  115. }
  116. }
  117. let requireALPN: Bool
  118. let scheme: Scheme
  119. switch self.transportSecurity.wrapped {
  120. case .plaintext:
  121. requireALPN = false
  122. scheme = .http
  123. case .tls(let tlsConfig):
  124. requireALPN = tlsConfig.requireALPN
  125. scheme = .https
  126. }
  127. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  128. channel: channel,
  129. compressionConfig: self.config.compression,
  130. connectionConfig: self.config.connection,
  131. http2Config: self.config.http2,
  132. rpcConfig: self.config.rpc,
  133. debugConfig: self.config.channelDebuggingCallbacks,
  134. requireALPN: requireALPN,
  135. scheme: scheme
  136. )
  137. }.runInitializerIfSet(
  138. self.config.channelDebuggingCallbacks.onAcceptTCPConnection,
  139. on: channel
  140. )
  141. }
  142. return serverChannel
  143. }
  144. }
  145. private let underlyingTransport: CommonHTTP2ServerTransport<ListenerFactory>
  146. /// The listening address for this server transport.
  147. ///
  148. /// It is an `async` property because it will only return once the address has been successfully bound.
  149. ///
  150. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  151. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  152. /// invalid address.
  153. public var listeningAddress: GRPCNIOTransportCore.SocketAddress {
  154. get async throws {
  155. try await self.underlyingTransport.listeningAddress
  156. }
  157. }
  158. /// Create a new `Posix` transport.
  159. ///
  160. /// - Parameters:
  161. /// - address: The address to which the server should be bound.
  162. /// - transportSecurity: The configuration for securing network traffic.
  163. /// - config: The transport configuration.
  164. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  165. public init(
  166. address: GRPCNIOTransportCore.SocketAddress,
  167. transportSecurity: TransportSecurity,
  168. config: Config = .defaults,
  169. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  170. ) {
  171. let factory = ListenerFactory(config: config, transportSecurity: transportSecurity)
  172. let helper = ServerQuiescingHelper(group: eventLoopGroup)
  173. self.underlyingTransport = CommonHTTP2ServerTransport(
  174. address: address,
  175. eventLoopGroup: eventLoopGroup,
  176. quiescingHelper: helper,
  177. listenerFactory: factory
  178. ) { channel in
  179. var context = HTTP2ServerTransport.Posix.Context()
  180. do {
  181. // The validadted certificate chain is only available when using a custom verification callback, while the
  182. // peer certificate is only available when using the BoringSSL backend. But if we can get the certificate
  183. // chain, we can set the peer certificate (the leaf of the chain) as well.
  184. if let peerCertificateChain =
  185. try await channel.nioSSL_peerValidatedCertificateChain().get(),
  186. let peerCertificateChain = try? X509.ValidatedCertificateChain(peerCertificateChain)
  187. {
  188. context.peerCertificate = peerCertificateChain.leaf
  189. context.peerCertificateChain = peerCertificateChain
  190. } else if let peerCert = try await channel.nioSSL_peerCertificate().get() {
  191. let serialized = try peerCert.toDERBytes()
  192. let swiftCert = try Certificate(derEncoded: serialized)
  193. context.peerCertificate = swiftCert
  194. }
  195. } catch {}
  196. return context
  197. }
  198. }
  199. public func listen(
  200. streamHandler:
  201. @escaping @Sendable (
  202. _ stream: RPCStream<Inbound, Outbound>,
  203. _ context: ServerContext
  204. ) async -> Void
  205. ) async throws {
  206. try await self.underlyingTransport.listen(streamHandler: streamHandler)
  207. }
  208. public func beginGracefulShutdown() {
  209. self.underlyingTransport.beginGracefulShutdown()
  210. }
  211. }
  212. }
  213. @available(gRPCSwiftNIOTransport 2.0, *)
  214. extension HTTP2ServerTransport.Posix {
  215. /// Context for Posix TransportSpecific
  216. public struct Context: ServerContext.TransportSpecific {
  217. /// The peer certificate (if any) from the mTLS handshake
  218. public var peerCertificate: Certificate?
  219. /// The validated peer certificate chain from the mTLS handshake. This is only available when using a custom verification callback.
  220. @available(gRPCSwiftNIOTransport 2.2, *)
  221. public var peerCertificateChain: X509.ValidatedCertificateChain?
  222. public init() {
  223. }
  224. }
  225. /// Config for the `Posix` transport.
  226. public struct Config: Sendable {
  227. /// Compression configuration.
  228. public var compression: HTTP2ServerTransport.Config.Compression
  229. /// Connection configuration.
  230. public var connection: HTTP2ServerTransport.Config.Connection
  231. /// HTTP2 configuration.
  232. public var http2: HTTP2ServerTransport.Config.HTTP2
  233. /// RPC configuration.
  234. public var rpc: HTTP2ServerTransport.Config.RPC
  235. /// Channel callbacks for debugging.
  236. public var channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  237. /// Construct a new `Config`.
  238. ///
  239. /// - Parameters:
  240. /// - http2: HTTP2 configuration.
  241. /// - rpc: RPC configuration.
  242. /// - connection: Connection configuration.
  243. /// - compression: Compression configuration.
  244. /// - channelDebuggingCallbacks: Channel callbacks for debugging.
  245. ///
  246. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  247. public init(
  248. http2: HTTP2ServerTransport.Config.HTTP2,
  249. rpc: HTTP2ServerTransport.Config.RPC,
  250. connection: HTTP2ServerTransport.Config.Connection,
  251. compression: HTTP2ServerTransport.Config.Compression,
  252. channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  253. ) {
  254. self.compression = compression
  255. self.connection = connection
  256. self.http2 = http2
  257. self.rpc = rpc
  258. self.channelDebuggingCallbacks = channelDebuggingCallbacks
  259. }
  260. /// Default configuration.
  261. public static var defaults: Self {
  262. Self.defaults()
  263. }
  264. /// Default values for the different configurations.
  265. ///
  266. /// - Parameters:
  267. /// - configure: A closure which allows you to modify the defaults before returning them.
  268. public static func defaults(
  269. configure: (_ config: inout Self) -> Void = { _ in }
  270. ) -> Self {
  271. var config = Self(
  272. http2: .defaults,
  273. rpc: .defaults,
  274. connection: .defaults,
  275. compression: .defaults,
  276. channelDebuggingCallbacks: .defaults
  277. )
  278. configure(&config)
  279. return config
  280. }
  281. }
  282. }
  283. @available(gRPCSwiftNIOTransport 2.0, *)
  284. extension ServerBootstrap {
  285. fileprivate func bind<Output: Sendable>(
  286. to address: GRPCNIOTransportCore.SocketAddress,
  287. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  288. ) async throws -> NIOAsyncChannel<Output, Never> {
  289. if let virtualSocket = address.virtualSocket {
  290. return try await self.bind(
  291. to: VsockAddress(virtualSocket),
  292. childChannelInitializer: childChannelInitializer
  293. )
  294. } else if let uds = address.unixDomainSocket {
  295. return try await self.bind(
  296. unixDomainSocketPath: uds.path,
  297. cleanupExistingSocketFile: true,
  298. childChannelInitializer: childChannelInitializer
  299. )
  300. } else {
  301. return try await self.bind(
  302. to: NIOCore.SocketAddress(address),
  303. childChannelInitializer: childChannelInitializer
  304. )
  305. }
  306. }
  307. }
  308. @available(gRPCSwiftNIOTransport 2.0, *)
  309. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  310. /// Create a new `Posix` based HTTP/2 server transport.
  311. ///
  312. /// - Parameters:
  313. /// - address: The address to which the server should be bound.
  314. /// - transportSecurity: The configuration for securing network traffic.
  315. /// - config: The transport configuration.
  316. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  317. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  318. /// a `MultiThreadedEventLoopGroup`.
  319. public static func http2NIOPosix(
  320. address: GRPCNIOTransportCore.SocketAddress,
  321. transportSecurity: HTTP2ServerTransport.Posix.TransportSecurity,
  322. config: HTTP2ServerTransport.Posix.Config = .defaults,
  323. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  324. ) -> Self {
  325. return HTTP2ServerTransport.Posix(
  326. address: address,
  327. transportSecurity: transportSecurity,
  328. config: config,
  329. eventLoopGroup: eventLoopGroup
  330. )
  331. }
  332. }