2
0

HTTPProtocolSwitcher.swift 7.0 KB

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