HTTPProtocolSwitcher.swift 7.3 KB

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