2
0

HTTPProtocolSwitcher.swift 6.2 KB

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