HTTPProtocolSwitcher.swift 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 NIO
  19. import NIOHTTP1
  20. import NIOHTTP2
  21. /// Channel handler that creates different processing pipelines depending on whether
  22. /// the incoming request is HTTP 1 or 2.
  23. internal class HTTPProtocolSwitcher {
  24. private let handlersInitializer: (Channel, Logger) -> EventLoopFuture<Void>
  25. private let errorDelegate: ServerErrorDelegate?
  26. private let logger: Logger
  27. private let httpTargetWindowSize: Int
  28. private let keepAlive: ServerConnectionKeepalive
  29. private let idleTimeout: TimeAmount
  30. // We could receive additional data after the initial data and before configuring
  31. // the pipeline; buffer it and fire it down the pipeline once it is configured.
  32. private enum State {
  33. case notConfigured
  34. case configuring
  35. case configured
  36. }
  37. private var state: State = .notConfigured
  38. private var bufferedData: [NIOAny] = []
  39. init(
  40. errorDelegate: ServerErrorDelegate?,
  41. httpTargetWindowSize: Int = 65535,
  42. keepAlive: ServerConnectionKeepalive,
  43. idleTimeout: TimeAmount,
  44. logger: Logger,
  45. handlersInitializer: @escaping (Channel, Logger) -> EventLoopFuture<Void>
  46. ) {
  47. self.errorDelegate = errorDelegate
  48. self.httpTargetWindowSize = httpTargetWindowSize
  49. self.keepAlive = keepAlive
  50. self.idleTimeout = idleTimeout
  51. self.logger = logger
  52. self.handlersInitializer = handlersInitializer
  53. }
  54. }
  55. extension HTTPProtocolSwitcher: ChannelInboundHandler, RemovableChannelHandler {
  56. typealias InboundIn = ByteBuffer
  57. typealias InboundOut = ByteBuffer
  58. enum HTTPProtocolVersionError: Error {
  59. /// Raised when it wasn't possible to detect HTTP Protocol version.
  60. case invalidHTTPProtocolVersion
  61. var localizedDescription: String {
  62. switch self {
  63. case .invalidHTTPProtocolVersion:
  64. return "Could not identify HTTP Protocol Version"
  65. }
  66. }
  67. }
  68. /// HTTP Protocol Version type
  69. enum HTTPProtocolVersion {
  70. case http1
  71. case http2
  72. }
  73. func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  74. switch self.state {
  75. case .notConfigured:
  76. self.logger.debug("determining http protocol version")
  77. self.state = .configuring
  78. self.logger.debug("buffering data", metadata: ["data": "\(data)"])
  79. self.bufferedData.append(data)
  80. // Detect the HTTP protocol version for the incoming request, or error out if it
  81. // couldn't be detected.
  82. var inBuffer = self.unwrapInboundIn(data)
  83. guard let initialData = inBuffer.readString(length: inBuffer.readableBytes),
  84. let firstLine = initialData.split(
  85. separator: "\r\n",
  86. maxSplits: 1,
  87. omittingEmptySubsequences: true
  88. ).first else {
  89. self.logger.error("unable to determine http version")
  90. context.fireErrorCaught(HTTPProtocolVersionError.invalidHTTPProtocolVersion)
  91. return
  92. }
  93. let version: HTTPProtocolVersion
  94. if firstLine.contains("HTTP/2") {
  95. version = .http2
  96. } else if firstLine.contains("HTTP/1") {
  97. version = .http1
  98. } else {
  99. self.logger.error("unable to determine http version")
  100. context.fireErrorCaught(HTTPProtocolVersionError.invalidHTTPProtocolVersion)
  101. return
  102. }
  103. self.logger.debug("determined http version", metadata: ["http_version": "\(version)"])
  104. // Once configured remove ourself from the pipeline, or handle the error.
  105. let pipelineConfigured: EventLoopPromise<Void> = context.eventLoop.makePromise()
  106. pipelineConfigured.futureResult.whenComplete { result in
  107. switch result {
  108. case .success:
  109. context.pipeline.removeHandler(context: context, promise: nil)
  110. case let .failure(error):
  111. self.state = .notConfigured
  112. self.errorCaught(context: context, error: error)
  113. }
  114. }
  115. // Depending on whether it is HTTP1 or HTTP2, create different processing pipelines.
  116. // Inbound handlers in handlersInitializer should expect HTTPServerRequestPart objects
  117. // and outbound handlers should return HTTPServerResponsePart objects.
  118. switch version {
  119. case .http1:
  120. // Upgrade connections are not handled since gRPC connections already arrive in HTTP2,
  121. // while gRPC-Web does not support HTTP2 at all, so there are no compelling use cases
  122. // to support this.
  123. context.pipeline.configureHTTPServerPipeline(withErrorHandling: true)
  124. .flatMap { context.pipeline.addHandler(WebCORSHandler()) }
  125. .flatMap { self.handlersInitializer(context.channel, self.logger) }
  126. .cascade(to: pipelineConfigured)
  127. case .http2:
  128. context.channel.configureHTTP2Pipeline(
  129. mode: .server,
  130. targetWindowSize: self.httpTargetWindowSize
  131. ) { streamChannel in
  132. var logger = self.logger
  133. // Grab the streamID from the channel.
  134. return streamChannel.getOption(HTTP2StreamChannelOptions.streamID).map { streamID in
  135. logger[metadataKey: MetadataKey.h2StreamID] = "\(streamID)"
  136. return logger
  137. }.recover { _ in
  138. logger[metadataKey: MetadataKey.h2StreamID] = "<unknown>"
  139. return logger
  140. }.flatMap { logger in
  141. streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap {
  142. self.handlersInitializer(streamChannel, logger)
  143. }
  144. }
  145. }.flatMap { multiplexer -> EventLoopFuture<Void> in
  146. // Add a keepalive and idle handlers between the two HTTP2 handlers.
  147. let keepaliveHandler = GRPCServerKeepaliveHandler(configuration: self.keepAlive)
  148. let idleHandler = GRPCIdleHandler(
  149. mode: .server,
  150. logger: self.logger,
  151. idleTimeout: self.idleTimeout
  152. )
  153. return context.channel.pipeline.addHandlers(
  154. [keepaliveHandler, idleHandler],
  155. position: .before(multiplexer)
  156. )
  157. }
  158. .cascade(to: pipelineConfigured)
  159. }
  160. case .configuring:
  161. self.logger.debug("buffering data", metadata: ["data": "\(data)"])
  162. self.bufferedData.append(data)
  163. case .configured:
  164. self.logger
  165. .critical(
  166. "unexpectedly received data; this handler should have been removed from the pipeline"
  167. )
  168. assertionFailure(
  169. "unexpectedly received data; this handler should have been removed from the pipeline"
  170. )
  171. }
  172. }
  173. func removeHandler(
  174. context: ChannelHandlerContext,
  175. removalToken: ChannelHandlerContext.RemovalToken
  176. ) {
  177. self.logger.debug("unbuffering data")
  178. self.bufferedData.forEach {
  179. context.fireChannelRead($0)
  180. }
  181. context.leavePipeline(removalToken: removalToken)
  182. self.state = .configured
  183. }
  184. func errorCaught(context: ChannelHandlerContext, error: Error) {
  185. switch self.state {
  186. case .notConfigured, .configuring:
  187. let baseError: Error
  188. if let errorWithContext = error as? GRPCError.WithContext {
  189. baseError = errorWithContext.error
  190. } else {
  191. baseError = error
  192. }
  193. self.errorDelegate?.observeLibraryError(baseError)
  194. context.close(mode: .all, promise: nil)
  195. case .configured:
  196. // If we're configured we will rely on a handler further down the pipeline.
  197. context.fireErrorCaught(error)
  198. }
  199. }
  200. }