HTTPProtocolSwitcher.swift 6.1 KB

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