HTTPProtocolSwitcher.swift 5.5 KB

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