HTTPProtocolSwitcher.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 preamble = initialData.split(separator: "\r\n",
  78. maxSplits: 1,
  79. omittingEmptySubsequences: true).first,
  80. let version = protocolVersion(String(preamble)) else {
  81. self.logger.error("unable to determine http version")
  82. context.fireErrorCaught(HTTPProtocolVersionError.invalidHTTPProtocolVersion)
  83. return
  84. }
  85. self.logger.info("determined http version", metadata: ["http_version": "\(version)"])
  86. // Once configured remove ourself from the pipeline, or handle the error.
  87. let pipelineConfigured: EventLoopPromise<Void> = context.eventLoop.makePromise()
  88. pipelineConfigured.futureResult.whenComplete { result in
  89. switch result {
  90. case .success:
  91. context.pipeline.removeHandler(context: context, promise: nil)
  92. case .failure(let error):
  93. self.state = .notConfigured
  94. self.errorCaught(context: context, error: error)
  95. }
  96. }
  97. // Depending on whether it is HTTP1 or HTTP2, create different processing pipelines.
  98. // Inbound handlers in handlersInitializer should expect HTTPServerRequestPart objects
  99. // and outbound handlers should return HTTPServerResponsePart objects.
  100. switch version {
  101. case .http1:
  102. // Upgrade connections are not handled since gRPC connections already arrive in HTTP2,
  103. // while gRPC-Web does not support HTTP2 at all, so there are no compelling use cases
  104. // to support this.
  105. context.pipeline.configureHTTPServerPipeline(withErrorHandling: true)
  106. .flatMap { context.pipeline.addHandler(WebCORSHandler()) }
  107. .flatMap { self.handlersInitializer(context.channel) }
  108. .cascade(to: pipelineConfigured)
  109. case .http2:
  110. context.channel.configureHTTP2Pipeline(mode: .server) { (streamChannel, streamID) in
  111. streamChannel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID))
  112. .flatMap { self.handlersInitializer(streamChannel) }
  113. }
  114. .map { _ in }
  115. .cascade(to: pipelineConfigured)
  116. }
  117. case .configuring:
  118. self.logger.info("buffering data \(data)")
  119. self.bufferedData.append(data)
  120. case .configured:
  121. self.logger.critical("unexpectedly received data; this handler should have been removed from the pipeline")
  122. assertionFailure("unexpectedly received data; this handler should have been removed from the pipeline")
  123. }
  124. }
  125. public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {
  126. self.logger.info("unbuffering data")
  127. self.bufferedData.forEach {
  128. context.fireChannelRead($0)
  129. }
  130. context.leavePipeline(removalToken: removalToken)
  131. self.state = .configured
  132. }
  133. public func errorCaught(context: ChannelHandlerContext, error: Error) {
  134. switch self.state {
  135. case .notConfigured, .configuring:
  136. errorDelegate?.observeLibraryError(error)
  137. context.close(mode: .all, promise: nil)
  138. case .configured:
  139. // If we're configured we will rely on a handler further down the pipeline.
  140. context.fireErrorCaught(error)
  141. }
  142. }
  143. /// Peek into the first line of the packet to check which HTTP version is being used.
  144. private func protocolVersion(_ preamble: String) -> HTTPProtocolVersion? {
  145. let range = NSRange(location: 0, length: preamble.utf16.count)
  146. let regex = try! NSRegularExpression(pattern: "^.*HTTP/(\\d)\\.\\d$")
  147. guard let result = regex.firstMatch(in: preamble, options: [], range: range) else {
  148. return nil
  149. }
  150. let versionRange = result.range(at: 1)
  151. let start = String.Index(utf16Offset: versionRange.location, in: preamble)
  152. let end = String.Index(utf16Offset: versionRange.location + versionRange.length, in: preamble)
  153. switch String(preamble.utf16[start..<end])! {
  154. case "1":
  155. return .http1
  156. case "2":
  157. return .http2
  158. default:
  159. return nil
  160. }
  161. }
  162. }