HTTP2ServerTransport+Posix.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 1.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. switch self.transportSecurity.wrapped {
  67. case .plaintext:
  68. sslContext = nil
  69. case .tls(let tlsConfig):
  70. do {
  71. sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  72. } catch {
  73. throw RuntimeError(
  74. code: .transportError,
  75. message: "Couldn't create SSL context, check your TLS configuration.",
  76. cause: error
  77. )
  78. }
  79. }
  80. let serverChannel = try await ServerBootstrap(group: eventLoopGroup)
  81. .serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
  82. .serverChannelInitializer { channel in
  83. return channel.eventLoop.makeCompletedFuture {
  84. let quiescingHandler = serverQuiescingHelper.makeServerChannelHandler(
  85. channel: channel
  86. )
  87. try channel.pipeline.syncOperations.addHandler(quiescingHandler)
  88. }.runInitializerIfSet(
  89. self.config.channelDebuggingCallbacks.onBindTCPListener,
  90. on: channel
  91. )
  92. }
  93. .bind(to: address) { channel in
  94. channel.eventLoop.makeCompletedFuture {
  95. if let sslContext {
  96. try channel.pipeline.syncOperations.addHandler(
  97. NIOSSLServerHandler(context: sslContext)
  98. )
  99. }
  100. let requireALPN: Bool
  101. let scheme: Scheme
  102. switch self.transportSecurity.wrapped {
  103. case .plaintext:
  104. requireALPN = false
  105. scheme = .http
  106. case .tls(let tlsConfig):
  107. requireALPN = tlsConfig.requireALPN
  108. scheme = .https
  109. }
  110. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  111. channel: channel,
  112. compressionConfig: self.config.compression,
  113. connectionConfig: self.config.connection,
  114. http2Config: self.config.http2,
  115. rpcConfig: self.config.rpc,
  116. debugConfig: self.config.channelDebuggingCallbacks,
  117. requireALPN: requireALPN,
  118. scheme: scheme
  119. )
  120. }.runInitializerIfSet(
  121. self.config.channelDebuggingCallbacks.onAcceptTCPConnection,
  122. on: channel
  123. )
  124. }
  125. return serverChannel
  126. }
  127. }
  128. private let underlyingTransport: CommonHTTP2ServerTransport<ListenerFactory>
  129. /// The listening address for this server transport.
  130. ///
  131. /// It is an `async` property because it will only return once the address has been successfully bound.
  132. ///
  133. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  134. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  135. /// invalid address.
  136. public var listeningAddress: GRPCNIOTransportCore.SocketAddress {
  137. get async throws {
  138. try await self.underlyingTransport.listeningAddress
  139. }
  140. }
  141. /// Create a new `Posix` transport.
  142. ///
  143. /// - Parameters:
  144. /// - address: The address to which the server should be bound.
  145. /// - transportSecurity: The configuration for securing network traffic.
  146. /// - config: The transport configuration.
  147. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  148. public init(
  149. address: GRPCNIOTransportCore.SocketAddress,
  150. transportSecurity: TransportSecurity,
  151. config: Config = .defaults,
  152. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  153. ) {
  154. let factory = ListenerFactory(config: config, transportSecurity: transportSecurity)
  155. let helper = ServerQuiescingHelper(group: eventLoopGroup)
  156. self.underlyingTransport = CommonHTTP2ServerTransport(
  157. address: address,
  158. eventLoopGroup: eventLoopGroup,
  159. quiescingHelper: helper,
  160. listenerFactory: factory
  161. ) { channel in
  162. var context = HTTP2ServerTransport.Posix.Context()
  163. do {
  164. if let peerCert = try await channel.nioSSL_peerCertificate().get() {
  165. let serialized = try peerCert.toDERBytes()
  166. let swiftCert = try Certificate(derEncoded: serialized)
  167. context.peerCertificate = swiftCert
  168. }
  169. } catch {}
  170. return context
  171. }
  172. }
  173. public func listen(
  174. streamHandler: @escaping @Sendable (
  175. _ stream: RPCStream<Inbound, Outbound>,
  176. _ context: ServerContext
  177. ) async -> Void
  178. ) async throws {
  179. try await self.underlyingTransport.listen(streamHandler: streamHandler)
  180. }
  181. public func beginGracefulShutdown() {
  182. self.underlyingTransport.beginGracefulShutdown()
  183. }
  184. }
  185. }
  186. @available(gRPCSwiftNIOTransport 1.0, *)
  187. extension HTTP2ServerTransport.Posix {
  188. /// Context for Posix TransportSpecific
  189. @available(gRPCSwiftNIOTransport 1.1, *)
  190. public struct Context: ServerContext.TransportSpecific {
  191. /// The peer certificate (if any) from the mTLS handshake
  192. public var peerCertificate: Certificate?
  193. public init() {
  194. }
  195. }
  196. /// Config for the `Posix` transport.
  197. public struct Config: Sendable {
  198. /// Compression configuration.
  199. public var compression: HTTP2ServerTransport.Config.Compression
  200. /// Connection configuration.
  201. public var connection: HTTP2ServerTransport.Config.Connection
  202. /// HTTP2 configuration.
  203. public var http2: HTTP2ServerTransport.Config.HTTP2
  204. /// RPC configuration.
  205. public var rpc: HTTP2ServerTransport.Config.RPC
  206. /// Channel callbacks for debugging.
  207. public var channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  208. /// Construct a new `Config`.
  209. ///
  210. /// - Parameters:
  211. /// - http2: HTTP2 configuration.
  212. /// - rpc: RPC configuration.
  213. /// - connection: Connection configuration.
  214. /// - compression: Compression configuration.
  215. /// - channelDebuggingCallbacks: Channel callbacks for debugging.
  216. ///
  217. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  218. public init(
  219. http2: HTTP2ServerTransport.Config.HTTP2,
  220. rpc: HTTP2ServerTransport.Config.RPC,
  221. connection: HTTP2ServerTransport.Config.Connection,
  222. compression: HTTP2ServerTransport.Config.Compression,
  223. channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  224. ) {
  225. self.compression = compression
  226. self.connection = connection
  227. self.http2 = http2
  228. self.rpc = rpc
  229. self.channelDebuggingCallbacks = channelDebuggingCallbacks
  230. }
  231. /// Default configuration.
  232. public static var defaults: Self {
  233. Self.defaults()
  234. }
  235. /// Default values for the different configurations.
  236. ///
  237. /// - Parameters:
  238. /// - configure: A closure which allows you to modify the defaults before returning them.
  239. public static func defaults(
  240. configure: (_ config: inout Self) -> Void = { _ in }
  241. ) -> Self {
  242. var config = Self(
  243. http2: .defaults,
  244. rpc: .defaults,
  245. connection: .defaults,
  246. compression: .defaults,
  247. channelDebuggingCallbacks: .defaults
  248. )
  249. configure(&config)
  250. return config
  251. }
  252. }
  253. }
  254. @available(gRPCSwiftNIOTransport 1.0, *)
  255. extension ServerBootstrap {
  256. fileprivate func bind<Output: Sendable>(
  257. to address: GRPCNIOTransportCore.SocketAddress,
  258. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  259. ) async throws -> NIOAsyncChannel<Output, Never> {
  260. if let virtualSocket = address.virtualSocket {
  261. return try await self.bind(
  262. to: VsockAddress(virtualSocket),
  263. childChannelInitializer: childChannelInitializer
  264. )
  265. } else if let uds = address.unixDomainSocket {
  266. return try await self.bind(
  267. unixDomainSocketPath: uds.path,
  268. cleanupExistingSocketFile: true,
  269. childChannelInitializer: childChannelInitializer
  270. )
  271. } else {
  272. return try await self.bind(
  273. to: NIOCore.SocketAddress(address),
  274. childChannelInitializer: childChannelInitializer
  275. )
  276. }
  277. }
  278. }
  279. @available(gRPCSwiftNIOTransport 1.0, *)
  280. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  281. /// Create a new `Posix` based HTTP/2 server transport.
  282. ///
  283. /// - Parameters:
  284. /// - address: The address to which the server should be bound.
  285. /// - transportSecurity: The configuration for securing network traffic.
  286. /// - config: The transport configuration.
  287. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  288. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  289. /// a `MultiThreadedEventLoopGroup`.
  290. public static func http2NIOPosix(
  291. address: GRPCNIOTransportCore.SocketAddress,
  292. transportSecurity: HTTP2ServerTransport.Posix.TransportSecurity,
  293. config: HTTP2ServerTransport.Posix.Config = .defaults,
  294. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  295. ) -> Self {
  296. return HTTP2ServerTransport.Posix(
  297. address: address,
  298. transportSecurity: transportSecurity,
  299. config: config,
  300. eventLoopGroup: eventLoopGroup
  301. )
  302. }
  303. }