Server.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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 Logging
  18. import NIOCore
  19. import NIOExtras
  20. import NIOHTTP1
  21. import NIOHTTP2
  22. import NIOPosix
  23. import NIOTransportServices
  24. #if canImport(NIOSSL)
  25. import NIOSSL
  26. #endif
  27. #if canImport(Network)
  28. import Network
  29. #endif
  30. /// Wrapper object to manage the lifecycle of a gRPC server.
  31. ///
  32. /// The pipeline is configured in three stages detailed below. Note: handlers marked with
  33. /// a '*' are responsible for handling errors.
  34. ///
  35. /// 1. Initial stage, prior to pipeline configuration.
  36. ///
  37. /// ┌─────────────────────────────────┐
  38. /// │ GRPCServerPipelineConfigurator* │
  39. /// └────▲───────────────────────┬────┘
  40. /// ByteBuffer│ │ByteBuffer
  41. /// ┌─┴───────────────────────▼─┐
  42. /// │ NIOSSLHandler │
  43. /// └─▲───────────────────────┬─┘
  44. /// ByteBuffer│ │ByteBuffer
  45. /// │ ▼
  46. ///
  47. /// The `NIOSSLHandler` is optional and depends on how the framework user has configured
  48. /// their server. The `GRPCServerPipelineConfigurator` detects which HTTP version is being used
  49. /// (via ALPN if TLS is used or by parsing the first bytes on the connection otherwise) and
  50. /// configures the pipeline accordingly.
  51. ///
  52. /// 2. HTTP version detected. "HTTP Handlers" depends on the HTTP version determined by
  53. /// `GRPCServerPipelineConfigurator`. In the case of HTTP/2:
  54. ///
  55. /// ┌─────────────────────────────────┐
  56. /// │ HTTP2StreamMultiplexer │
  57. /// └─▲─────────────────────────────┬─┘
  58. /// HTTP2Frame│ │HTTP2Frame
  59. /// ┌─┴─────────────────────────────▼─┐
  60. /// │ HTTP2Handler │
  61. /// └─▲─────────────────────────────┬─┘
  62. /// ByteBuffer│ │ByteBuffer
  63. /// ┌─┴─────────────────────────────▼─┐
  64. /// │ NIOSSLHandler │
  65. /// └─▲─────────────────────────────┬─┘
  66. /// ByteBuffer│ │ByteBuffer
  67. /// │ ▼
  68. ///
  69. /// The `HTTP2StreamMultiplexer` provides one `Channel` for each HTTP/2 stream (and thus each
  70. /// RPC).
  71. ///
  72. /// 3. The frames for each stream channel are routed by the `HTTP2ToRawGRPCServerCodec` handler to
  73. /// a handler containing the user-implemented logic provided by a `CallHandlerProvider`:
  74. ///
  75. /// ┌─────────────────────────────────┐
  76. /// │ BaseCallHandler* │
  77. /// └─▲─────────────────────────────┬─┘
  78. /// GRPCServerRequestPart│ │GRPCServerResponsePart
  79. /// ┌─┴─────────────────────────────▼─┐
  80. /// │ HTTP2ToRawGRPCServerCodec │
  81. /// └─▲─────────────────────────────┬─┘
  82. /// HTTP2Frame.FramePayload│ │HTTP2Frame.FramePayload
  83. /// │ ▼
  84. ///
  85. /// - Note: This class is thread safe. It's marked as `@unchecked Sendable` because the non-Sendable
  86. /// `errorDelegate` property is mutated, but it's done thread-safely, as it only happens inside the `EventLoop`.
  87. public final class Server: @unchecked Sendable {
  88. /// Makes and configures a `ServerBootstrap` using the provided configuration.
  89. public class func makeBootstrap(configuration: Configuration) -> ServerBootstrapProtocol {
  90. let bootstrap = PlatformSupport.makeServerBootstrap(group: configuration.eventLoopGroup)
  91. // Backlog is only available on `ServerBootstrap`.
  92. if bootstrap is ServerBootstrap {
  93. // Specify a backlog to avoid overloading the server.
  94. _ = bootstrap.serverChannelOption(ChannelOptions.backlog, value: 256)
  95. }
  96. #if canImport(NIOSSL)
  97. // Making a `NIOSSLContext` is expensive, we should only do it once per TLS configuration so
  98. // we'll do it now, before accepting connections. Unfortunately our API isn't throwing so we'll
  99. // only surface any error when initializing a child channel.
  100. //
  101. // 'nil' means we're not using TLS, or we're using the Network.framework TLS backend. If we're
  102. // using the Network.framework TLS backend we'll apply the settings just below.
  103. let sslContext: Result<NIOSSLContext, Error>?
  104. if let tlsConfiguration = configuration.tlsConfiguration {
  105. do {
  106. sslContext = try tlsConfiguration.makeNIOSSLContext().map { .success($0) }
  107. } catch {
  108. sslContext = .failure(error)
  109. }
  110. } else {
  111. // No TLS configuration, no SSL context.
  112. sslContext = nil
  113. }
  114. #endif // canImport(NIOSSL)
  115. #if canImport(Network)
  116. if let tlsConfiguration = configuration.tlsConfiguration {
  117. if #available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  118. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  119. {
  120. _ = transportServicesBootstrap.tlsOptions(from: tlsConfiguration)
  121. }
  122. }
  123. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
  124. let configurator = configuration.listenerNWParametersConfigurator,
  125. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  126. {
  127. _ = transportServicesBootstrap.configureNWParameters(configurator)
  128. }
  129. if #available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *),
  130. let configurator = configuration.childChannelNWParametersConfigurator,
  131. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap
  132. {
  133. _ = transportServicesBootstrap.configureChildNWParameters(configurator)
  134. }
  135. #endif // canImport(Network)
  136. return
  137. bootstrap
  138. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  139. .serverChannelOption(
  140. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  141. value: 1
  142. )
  143. // Set the handlers that are applied to the accepted Channels
  144. .childChannelInitializer { channel in
  145. var configuration = configuration
  146. configuration.logger[metadataKey: MetadataKey.connectionID] = "\(UUID().uuidString)"
  147. configuration.logger.addIPAddressMetadata(
  148. local: channel.localAddress,
  149. remote: channel.remoteAddress
  150. )
  151. do {
  152. let sync = channel.pipeline.syncOperations
  153. #if canImport(NIOSSL)
  154. if let sslContext = try sslContext?.get() {
  155. let sslHandler: NIOSSLServerHandler
  156. if let verify = configuration.tlsConfiguration?.nioSSLCustomVerificationCallback {
  157. sslHandler = NIOSSLServerHandler(
  158. context: sslContext,
  159. customVerificationCallback: verify
  160. )
  161. } else {
  162. sslHandler = NIOSSLServerHandler(context: sslContext)
  163. }
  164. try sync.addHandler(sslHandler)
  165. }
  166. #endif // canImport(NIOSSL)
  167. // Configures the pipeline based on whether the connection uses TLS or not.
  168. try sync.addHandler(GRPCServerPipelineConfigurator(configuration: configuration))
  169. // Work around the zero length write issue, if needed.
  170. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  171. group: configuration.eventLoopGroup,
  172. hasTLS: configuration.tlsConfiguration != nil
  173. )
  174. if requiresZeroLengthWorkaround,
  175. #available(macOS 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  176. {
  177. try sync.addHandler(NIOFilterEmptyWritesHandler())
  178. }
  179. } catch {
  180. return channel.eventLoop.makeFailedFuture(error)
  181. }
  182. // Run the debug initializer, if there is one.
  183. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  184. return debugAcceptedChannelInitializer(channel)
  185. } else {
  186. return channel.eventLoop.makeSucceededVoidFuture()
  187. }
  188. }
  189. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  190. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  191. .childChannelOption(
  192. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  193. value: 1
  194. )
  195. }
  196. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  197. /// available to configure the server.
  198. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  199. let quiescingHelper = ServerQuiescingHelper(group: configuration.eventLoopGroup)
  200. return self.makeBootstrap(configuration: configuration)
  201. .serverChannelInitializer { channel in
  202. channel.pipeline.addHandler(quiescingHelper.makeServerChannelHandler(channel: channel))
  203. }
  204. .bind(to: configuration.target)
  205. .map { channel in
  206. Server(
  207. channel: channel,
  208. quiescingHelper: quiescingHelper,
  209. errorDelegate: configuration.errorDelegate
  210. )
  211. }
  212. }
  213. public let channel: Channel
  214. private let quiescingHelper: ServerQuiescingHelper
  215. private var errorDelegate: ServerErrorDelegate?
  216. private init(
  217. channel: Channel,
  218. quiescingHelper: ServerQuiescingHelper,
  219. errorDelegate: ServerErrorDelegate?
  220. ) {
  221. self.channel = channel
  222. self.quiescingHelper = quiescingHelper
  223. // Maintain a strong reference to ensure it lives as long as the server.
  224. self.errorDelegate = errorDelegate
  225. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  226. // be added.
  227. if let errorDelegate = errorDelegate {
  228. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  229. }
  230. // nil out errorDelegate to avoid retain cycles.
  231. self.onClose.whenComplete { _ in
  232. self.errorDelegate = nil
  233. }
  234. }
  235. /// Fired when the server shuts down.
  236. public var onClose: EventLoopFuture<Void> {
  237. return self.channel.closeFuture
  238. }
  239. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  240. /// connections will be rejected.
  241. public func initiateGracefulShutdown(promise: EventLoopPromise<Void>?) {
  242. self.quiescingHelper.initiateShutdown(promise: promise)
  243. }
  244. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  245. /// connections will be rejected.
  246. public func initiateGracefulShutdown() -> EventLoopFuture<Void> {
  247. let promise = self.channel.eventLoop.makePromise(of: Void.self)
  248. self.initiateGracefulShutdown(promise: promise)
  249. return promise.futureResult
  250. }
  251. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  252. public func close(promise: EventLoopPromise<Void>?) {
  253. self.channel.close(mode: .all, promise: promise)
  254. }
  255. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  256. public func close() -> EventLoopFuture<Void> {
  257. return self.channel.close(mode: .all)
  258. }
  259. }
  260. public typealias BindTarget = ConnectionTarget
  261. extension Server {
  262. /// The configuration for a server.
  263. public struct Configuration {
  264. /// The target to bind to.
  265. public var target: BindTarget
  266. /// The event loop group to run the connection on.
  267. public var eventLoopGroup: EventLoopGroup
  268. /// Providers the server should use to handle gRPC requests.
  269. public var serviceProviders: [CallHandlerProvider] {
  270. get {
  271. return Array(self.serviceProvidersByName.values)
  272. }
  273. set {
  274. self
  275. .serviceProvidersByName = Dictionary(
  276. uniqueKeysWithValues:
  277. newValue
  278. .map { ($0.serviceName, $0) }
  279. )
  280. }
  281. }
  282. /// An error delegate which is called when errors are caught. Provided delegates **must not
  283. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  284. public var errorDelegate: ServerErrorDelegate?
  285. #if canImport(NIOSSL)
  286. /// TLS configuration for this connection. `nil` if TLS is not desired.
  287. @available(*, deprecated, renamed: "tlsConfiguration")
  288. public var tls: TLS? {
  289. get {
  290. return self.tlsConfiguration?.asDeprecatedServerConfiguration
  291. }
  292. set {
  293. self.tlsConfiguration = newValue.map { GRPCTLSConfiguration(transforming: $0) }
  294. }
  295. }
  296. #endif // canImport(NIOSSL)
  297. public var tlsConfiguration: GRPCTLSConfiguration?
  298. /// The connection keepalive configuration.
  299. public var connectionKeepalive = ServerConnectionKeepalive()
  300. /// The amount of time to wait before closing connections. The idle timeout will start only
  301. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  302. public var connectionIdleTimeout: TimeAmount = .nanoseconds(.max)
  303. /// The compression configuration for requests and responses.
  304. ///
  305. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  306. /// setting `compressionEnabled` to `false` on the context of the call.
  307. ///
  308. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  309. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  310. /// in `sendResponse(_:compression)`.
  311. ///
  312. /// Defaults to ``ServerMessageEncoding/disabled``.
  313. public var messageEncoding: ServerMessageEncoding = .disabled
  314. /// The maximum size in bytes of a message which may be received from a client. Defaults to 4MB.
  315. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  316. willSet {
  317. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  318. }
  319. }
  320. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  321. /// 1 and 2^31-1 inclusive.
  322. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  323. didSet {
  324. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  325. }
  326. }
  327. /// The HTTP/2 max number of concurrent streams. Defaults to 100. Must be non-negative.
  328. public var httpMaxConcurrentStreams: Int = 100 {
  329. willSet {
  330. precondition(newValue >= 0, "httpMaxConcurrentStreams must be non-negative")
  331. }
  332. }
  333. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  334. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  335. public var httpMaxFrameSize: Int = 16384 {
  336. didSet {
  337. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  338. }
  339. }
  340. /// The HTTP/2 max number of reset streams. Defaults to 32. Must be non-negative.
  341. public var httpMaxResetStreams: Int = 32 {
  342. willSet {
  343. precondition(newValue >= 0, "httpMaxResetStreams must be non-negative")
  344. }
  345. }
  346. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  347. /// each connection will use a logger branched from the connections logger. This logger is made
  348. /// available to service providers via `context`. Defaults to a no-op logger.
  349. public var logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  350. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  351. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  352. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  353. ///
  354. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  355. /// be invoked at most once per accepted connection.
  356. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  357. /// A calculated private cache of the service providers by name.
  358. ///
  359. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  360. /// the need to recalculate this dictionary each time we receive an rpc.
  361. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  362. #if canImport(Network)
  363. /// A closure allowing to customise the listener's `NWParameters` used when establishing a connection using `NIOTransportServices`.
  364. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  365. public var listenerNWParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  366. get {
  367. self._listenerNWParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  368. }
  369. set {
  370. self._listenerNWParametersConfigurator = newValue
  371. }
  372. }
  373. private var _listenerNWParametersConfigurator: (any Sendable)?
  374. /// A closure allowing to customise the child channels' `NWParameters` used when establishing connections using `NIOTransportServices`.
  375. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  376. public var childChannelNWParametersConfigurator: (@Sendable (NWParameters) -> Void)? {
  377. get {
  378. self._childChannelNWParametersConfigurator as! (@Sendable (NWParameters) -> Void)?
  379. }
  380. set {
  381. self._childChannelNWParametersConfigurator = newValue
  382. }
  383. }
  384. private var _childChannelNWParametersConfigurator: (any Sendable)?
  385. #endif
  386. /// CORS configuration for gRPC-Web support.
  387. public var webCORS = Configuration.CORS()
  388. #if canImport(NIOSSL)
  389. /// Create a `Configuration` with some pre-defined defaults.
  390. ///
  391. /// - Parameters:
  392. /// - target: The target to bind to.
  393. /// - eventLoopGroup: The event loop group to run the server on.
  394. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  395. /// to handle requests.
  396. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  397. /// - tls: TLS configuration, defaulting to `nil`.
  398. /// - connectionKeepalive: The keepalive configuration to use.
  399. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  400. /// indefinite by default.
  401. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  402. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  403. /// - logger: A logger. Defaults to a no-op logger.
  404. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  405. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  406. @available(*, deprecated, renamed: "default(target:eventLoopGroup:serviceProviders:)")
  407. public init(
  408. target: BindTarget,
  409. eventLoopGroup: EventLoopGroup,
  410. serviceProviders: [CallHandlerProvider],
  411. errorDelegate: ServerErrorDelegate? = nil,
  412. tls: TLS? = nil,
  413. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  414. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  415. messageEncoding: ServerMessageEncoding = .disabled,
  416. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  417. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  418. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  419. ) {
  420. self.target = target
  421. self.eventLoopGroup = eventLoopGroup
  422. self.serviceProvidersByName = Dictionary(
  423. uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }
  424. )
  425. self.errorDelegate = errorDelegate
  426. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  427. self.connectionKeepalive = connectionKeepalive
  428. self.connectionIdleTimeout = connectionIdleTimeout
  429. self.messageEncoding = messageEncoding
  430. self.httpTargetWindowSize = httpTargetWindowSize
  431. self.logger = logger
  432. self.debugChannelInitializer = debugChannelInitializer
  433. }
  434. #endif // canImport(NIOSSL)
  435. private init(
  436. eventLoopGroup: EventLoopGroup,
  437. target: BindTarget,
  438. serviceProviders: [CallHandlerProvider]
  439. ) {
  440. self.eventLoopGroup = eventLoopGroup
  441. self.target = target
  442. self.serviceProvidersByName = Dictionary(
  443. uniqueKeysWithValues: serviceProviders.map {
  444. ($0.serviceName, $0)
  445. }
  446. )
  447. }
  448. /// Make a new configuration using default values.
  449. ///
  450. /// - Parameters:
  451. /// - target: The target to bind to.
  452. /// - eventLoopGroup: The `EventLoopGroup` the server should run on.
  453. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  454. /// to handle requests.
  455. /// - Returns: A configuration with default values set.
  456. public static func `default`(
  457. target: BindTarget,
  458. eventLoopGroup: EventLoopGroup,
  459. serviceProviders: [CallHandlerProvider]
  460. ) -> Configuration {
  461. return .init(
  462. eventLoopGroup: eventLoopGroup,
  463. target: target,
  464. serviceProviders: serviceProviders
  465. )
  466. }
  467. }
  468. }
  469. extension Server.Configuration {
  470. public struct CORS: Hashable, Sendable {
  471. /// Determines which 'origin' header field values are permitted in a CORS request.
  472. public var allowedOrigins: AllowedOrigins
  473. /// Sets the headers which are permitted in a response to a CORS request.
  474. public var allowedHeaders: [String]
  475. /// Enabling this value allows sets the "access-control-allow-credentials" header field
  476. /// to "true" in respones to CORS requests. This must be enabled if the client intends to send
  477. /// credentials.
  478. public var allowCredentialedRequests: Bool
  479. /// The maximum age in seconds which pre-flight CORS requests may be cached for.
  480. public var preflightCacheExpiration: Int
  481. public init(
  482. allowedOrigins: AllowedOrigins = .all,
  483. allowedHeaders: [String] = ["content-type", "x-grpc-web", "x-user-agent"],
  484. allowCredentialedRequests: Bool = false,
  485. preflightCacheExpiration: Int = 86400
  486. ) {
  487. self.allowedOrigins = allowedOrigins
  488. self.allowedHeaders = allowedHeaders
  489. self.allowCredentialedRequests = allowCredentialedRequests
  490. self.preflightCacheExpiration = preflightCacheExpiration
  491. }
  492. }
  493. }
  494. extension Server.Configuration.CORS {
  495. public struct AllowedOrigins: Hashable, Sendable {
  496. enum Wrapped: Hashable, Sendable {
  497. case all
  498. case originBased
  499. case only([String])
  500. case custom(AnyCustomCORSAllowedOrigin)
  501. }
  502. private(set) var wrapped: Wrapped
  503. private init(_ wrapped: Wrapped) {
  504. self.wrapped = wrapped
  505. }
  506. /// Allow all origin values.
  507. public static let all = Self(.all)
  508. /// Allow all origin values; similar to `all` but returns the value of the origin header field
  509. /// in the 'access-control-allow-origin' response header (rather than "*").
  510. public static let originBased = Self(.originBased)
  511. /// Allow only the given origin values.
  512. public static func only(_ allowed: [String]) -> Self {
  513. return Self(.only(allowed))
  514. }
  515. /// Provide a custom CORS origin check.
  516. ///
  517. /// - Parameter checkOrigin: A closure which is called with the value of the 'origin' header
  518. /// and returns the value to use in the 'access-control-allow-origin' response header,
  519. /// or `nil` if the origin is not allowed.
  520. public static func custom<C: GRPCCustomCORSAllowedOrigin>(_ custom: C) -> Self {
  521. return Self(.custom(AnyCustomCORSAllowedOrigin(custom)))
  522. }
  523. }
  524. }
  525. extension ServerBootstrapProtocol {
  526. fileprivate func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  527. switch target.wrapped {
  528. case let .hostAndPort(host, port):
  529. return self.bind(host: host, port: port)
  530. case let .unixDomainSocket(path):
  531. return self.bind(unixDomainSocketPath: path)
  532. case let .socketAddress(address):
  533. return self.bind(to: address)
  534. case let .connectedSocket(socket):
  535. return self.withBoundSocket(socket)
  536. case let .vsockAddress(address):
  537. return self.bind(to: address)
  538. }
  539. }
  540. }
  541. extension Comparable {
  542. internal func clamped(to range: ClosedRange<Self>) -> Self {
  543. return min(max(self, range.lowerBound), range.upperBound)
  544. }
  545. }
  546. public protocol GRPCCustomCORSAllowedOrigin: Sendable, Hashable {
  547. /// Returns the value to use for the 'access-control-allow-origin' response header for the given
  548. /// value of the 'origin' request header.
  549. ///
  550. /// - Parameter origin: The value of the 'origin' request header field.
  551. /// - Returns: The value to use for the 'access-control-allow-origin' header field or `nil` if no
  552. /// CORS related headers should be returned.
  553. func check(origin: String) -> String?
  554. }
  555. extension Server.Configuration.CORS.AllowedOrigins {
  556. struct AnyCustomCORSAllowedOrigin: GRPCCustomCORSAllowedOrigin {
  557. private var checkOrigin: @Sendable (String) -> String?
  558. private let hashInto: @Sendable (inout Hasher) -> Void
  559. private let isEqualTo: @Sendable (any GRPCCustomCORSAllowedOrigin) -> Bool
  560. init<W: GRPCCustomCORSAllowedOrigin>(_ wrap: W) {
  561. self.checkOrigin = { wrap.check(origin: $0) }
  562. self.hashInto = { wrap.hash(into: &$0) }
  563. self.isEqualTo = { wrap == ($0 as? W) }
  564. }
  565. func check(origin: String) -> String? {
  566. return self.checkOrigin(origin)
  567. }
  568. func hash(into hasher: inout Hasher) {
  569. self.hashInto(&hasher)
  570. }
  571. static func == (
  572. lhs: Server.Configuration.CORS.AllowedOrigins.AnyCustomCORSAllowedOrigin,
  573. rhs: Server.Configuration.CORS.AllowedOrigins.AnyCustomCORSAllowedOrigin
  574. ) -> Bool {
  575. return lhs.isEqualTo(rhs)
  576. }
  577. }
  578. }