HTTPProtocolSwitcher.swift 6.3 KB

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