HTTP2ServerTransport+Posix.swift 11 KB

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