HTTPProtocolSwitcher.swift 6.7 KB

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