HTTP2ServerTransport+Posix.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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: @escaping @Sendable (
  201. _ stream: RPCStream<Inbound, Outbound>,
  202. _ context: ServerContext
  203. ) async -> Void
  204. ) async throws {
  205. try await self.underlyingTransport.listen(streamHandler: streamHandler)
  206. }
  207. public func beginGracefulShutdown() {
  208. self.underlyingTransport.beginGracefulShutdown()
  209. }
  210. }
  211. }
  212. @available(gRPCSwiftNIOTransport 2.0, *)
  213. extension HTTP2ServerTransport.Posix {
  214. /// Context for Posix TransportSpecific
  215. public struct Context: ServerContext.TransportSpecific {
  216. /// The peer certificate (if any) from the mTLS handshake
  217. public var peerCertificate: Certificate?
  218. /// The validated peer certificate chain from the mTLS handshake. This is only available when using a custom verification callback.
  219. @available(gRPCSwiftNIOTransport 2.2, *)
  220. public var peerCertificateChain: X509.ValidatedCertificateChain?
  221. public init() {
  222. }
  223. }
  224. /// Config for the `Posix` transport.
  225. public struct Config: Sendable {
  226. /// Compression configuration.
  227. public var compression: HTTP2ServerTransport.Config.Compression
  228. /// Connection configuration.
  229. public var connection: HTTP2ServerTransport.Config.Connection
  230. /// HTTP2 configuration.
  231. public var http2: HTTP2ServerTransport.Config.HTTP2
  232. /// RPC configuration.
  233. public var rpc: HTTP2ServerTransport.Config.RPC
  234. /// Channel callbacks for debugging.
  235. public var channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  236. /// Construct a new `Config`.
  237. ///
  238. /// - Parameters:
  239. /// - http2: HTTP2 configuration.
  240. /// - rpc: RPC configuration.
  241. /// - connection: Connection configuration.
  242. /// - compression: Compression configuration.
  243. /// - channelDebuggingCallbacks: Channel callbacks for debugging.
  244. ///
  245. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  246. public init(
  247. http2: HTTP2ServerTransport.Config.HTTP2,
  248. rpc: HTTP2ServerTransport.Config.RPC,
  249. connection: HTTP2ServerTransport.Config.Connection,
  250. compression: HTTP2ServerTransport.Config.Compression,
  251. channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  252. ) {
  253. self.compression = compression
  254. self.connection = connection
  255. self.http2 = http2
  256. self.rpc = rpc
  257. self.channelDebuggingCallbacks = channelDebuggingCallbacks
  258. }
  259. /// Default configuration.
  260. public static var defaults: Self {
  261. Self.defaults()
  262. }
  263. /// Default values for the different configurations.
  264. ///
  265. /// - Parameters:
  266. /// - configure: A closure which allows you to modify the defaults before returning them.
  267. public static func defaults(
  268. configure: (_ config: inout Self) -> Void = { _ in }
  269. ) -> Self {
  270. var config = Self(
  271. http2: .defaults,
  272. rpc: .defaults,
  273. connection: .defaults,
  274. compression: .defaults,
  275. channelDebuggingCallbacks: .defaults
  276. )
  277. configure(&config)
  278. return config
  279. }
  280. }
  281. }
  282. @available(gRPCSwiftNIOTransport 2.0, *)
  283. extension ServerBootstrap {
  284. fileprivate func bind<Output: Sendable>(
  285. to address: GRPCNIOTransportCore.SocketAddress,
  286. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  287. ) async throws -> NIOAsyncChannel<Output, Never> {
  288. if let virtualSocket = address.virtualSocket {
  289. return try await self.bind(
  290. to: VsockAddress(virtualSocket),
  291. childChannelInitializer: childChannelInitializer
  292. )
  293. } else if let uds = address.unixDomainSocket {
  294. return try await self.bind(
  295. unixDomainSocketPath: uds.path,
  296. cleanupExistingSocketFile: true,
  297. childChannelInitializer: childChannelInitializer
  298. )
  299. } else {
  300. return try await self.bind(
  301. to: NIOCore.SocketAddress(address),
  302. childChannelInitializer: childChannelInitializer
  303. )
  304. }
  305. }
  306. }
  307. @available(gRPCSwiftNIOTransport 2.0, *)
  308. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  309. /// Create a new `Posix` based HTTP/2 server transport.
  310. ///
  311. /// - Parameters:
  312. /// - address: The address to which the server should be bound.
  313. /// - transportSecurity: The configuration for securing network traffic.
  314. /// - config: The transport configuration.
  315. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  316. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  317. /// a `MultiThreadedEventLoopGroup`.
  318. public static func http2NIOPosix(
  319. address: GRPCNIOTransportCore.SocketAddress,
  320. transportSecurity: HTTP2ServerTransport.Posix.TransportSecurity,
  321. config: HTTP2ServerTransport.Posix.Config = .defaults,
  322. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  323. ) -> Self {
  324. return HTTP2ServerTransport.Posix(
  325. address: address,
  326. transportSecurity: transportSecurity,
  327. config: config,
  328. eventLoopGroup: eventLoopGroup
  329. )
  330. }
  331. }