GRPCServerPipelineConfigurator.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * Copyright 2020, 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 Logging
  17. import NIO
  18. import NIOHTTP1
  19. import NIOHTTP2
  20. import NIOTLS
  21. /// Configures a server pipeline for gRPC with the appropriate handlers depending on the HTTP
  22. /// version used for transport.
  23. ///
  24. /// If TLS is enabled then the handler listens for an 'TLSUserEvent.handshakeCompleted' event and
  25. /// configures the pipeline appropriately for the protocol negotiated via ALPN. If TLS is not
  26. /// configured then the HTTP version is determined by parsing the inbound byte stream.
  27. final class GRPCServerPipelineConfigurator: ChannelInboundHandler, RemovableChannelHandler {
  28. internal typealias InboundIn = ByteBuffer
  29. internal typealias InboundOut = ByteBuffer
  30. /// The server configuration.
  31. private let configuration: Server.Configuration
  32. /// Reads which we're holding on to before the pipeline is configured.
  33. private var bufferedReads = CircularBuffer<NIOAny>()
  34. /// The current state.
  35. private var state: State
  36. private enum ALPN {
  37. /// ALPN is expected. It may or may not be required, however.
  38. case expected(required: Bool)
  39. /// ALPN was expected but not required and no protocol was negotiated in the handshake. We may
  40. /// now fall back to parsing bytes on the connection.
  41. case expectedButFallingBack
  42. /// ALPN is not expected; this is a cleartext connection.
  43. case notExpected
  44. }
  45. private enum State {
  46. /// The pipeline isn't configured yet.
  47. case notConfigured(alpn: ALPN)
  48. /// We're configuring the pipeline.
  49. case configuring
  50. }
  51. init(configuration: Server.Configuration) {
  52. if let tls = configuration.tls {
  53. self.state = .notConfigured(alpn: .expected(required: tls.requireALPN))
  54. } else {
  55. self.state = .notConfigured(alpn: .notExpected)
  56. }
  57. self.configuration = configuration
  58. }
  59. /// Makes a gRPC idle handler for the server..
  60. private func makeIdleHandler() -> GRPCIdleHandler {
  61. return .init(
  62. idleTimeout: self.configuration.connectionIdleTimeout,
  63. keepalive: self.configuration.connectionKeepalive,
  64. logger: self.configuration.logger
  65. )
  66. }
  67. /// Makes an HTTP/2 handler.
  68. private func makeHTTP2Handler() -> NIOHTTP2Handler {
  69. return .init(mode: .server)
  70. }
  71. /// Makes an HTTP/2 multiplexer suitable handling gRPC requests.
  72. private func makeHTTP2Multiplexer(for channel: Channel) -> HTTP2StreamMultiplexer {
  73. var logger = self.configuration.logger
  74. return .init(
  75. mode: .server,
  76. channel: channel,
  77. targetWindowSize: self.configuration.httpTargetWindowSize
  78. ) { stream in
  79. stream.getOption(HTTP2StreamChannelOptions.streamID).map { streamID -> Logger in
  80. logger[metadataKey: MetadataKey.h2StreamID] = "\(streamID)"
  81. return logger
  82. }.recover { _ in
  83. logger[metadataKey: MetadataKey.h2StreamID] = "<unknown>"
  84. return logger
  85. }.flatMap { logger in
  86. // TODO: provide user configuration for header normalization.
  87. let handler = self.makeHTTP2ToRawGRPCHandler(normalizeHeaders: true, logger: logger)
  88. return stream.pipeline.addHandler(handler)
  89. }
  90. }
  91. }
  92. /// Makes an HTTP/2 to raw gRPC server handler.
  93. private func makeHTTP2ToRawGRPCHandler(
  94. normalizeHeaders: Bool,
  95. logger: Logger
  96. ) -> HTTP2ToRawGRPCServerCodec {
  97. return HTTP2ToRawGRPCServerCodec(
  98. servicesByName: self.configuration.serviceProvidersByName,
  99. encoding: self.configuration.messageEncoding,
  100. errorDelegate: self.configuration.errorDelegate,
  101. normalizeHeaders: normalizeHeaders,
  102. logger: logger
  103. )
  104. }
  105. /// The pipeline finished configuring.
  106. private func configurationCompleted(result: Result<Void, Error>, context: ChannelHandlerContext) {
  107. switch result {
  108. case .success:
  109. context.pipeline.removeHandler(context: context, promise: nil)
  110. case let .failure(error):
  111. self.errorCaught(context: context, error: error)
  112. }
  113. }
  114. /// Configures the pipeline to handle gRPC requests on an HTTP/2 connection.
  115. private func configureHTTP2(context: ChannelHandlerContext) {
  116. // We're now configuring the pipeline.
  117. self.state = .configuring
  118. // We could use 'Channel.configureHTTP2Pipeline', but then we'd have to find the right handlers
  119. // to then insert our keepalive and idle handlers between. We can just add everything together.
  120. var handlers: [ChannelHandler] = []
  121. handlers.reserveCapacity(3)
  122. handlers.append(self.makeHTTP2Handler())
  123. handlers.append(self.makeIdleHandler())
  124. handlers.append(self.makeHTTP2Multiplexer(for: context.channel))
  125. // Now configure the pipeline with the handlers.
  126. context.channel.pipeline.addHandlers(handlers).whenComplete { result in
  127. self.configurationCompleted(result: result, context: context)
  128. }
  129. }
  130. /// Configures the pipeline to handle gRPC-Web requests on an HTTP/1 connection.
  131. private func configureHTTP1(context: ChannelHandlerContext) {
  132. // We're now configuring the pipeline.
  133. self.state = .configuring
  134. context.pipeline.configureHTTPServerPipeline(withErrorHandling: true).flatMap {
  135. context.pipeline.addHandlers([
  136. WebCORSHandler(),
  137. GRPCWebToHTTP2ServerCodec(scheme: self.configuration.tls == nil ? "http" : "https"),
  138. // There's no need to normalize headers for HTTP/1.
  139. self.makeHTTP2ToRawGRPCHandler(normalizeHeaders: false, logger: self.configuration.logger),
  140. ])
  141. }.whenComplete { result in
  142. self.configurationCompleted(result: result, context: context)
  143. }
  144. }
  145. /// Attempts to determine the HTTP version from the buffer and then configure the pipeline
  146. /// appropriately. Closes the connection if the HTTP version could not be determined.
  147. private func determineHTTPVersionAndConfigurePipeline(
  148. buffer: ByteBuffer,
  149. context: ChannelHandlerContext
  150. ) {
  151. if HTTPVersionParser.prefixedWithHTTP2ConnectionPreface(buffer) {
  152. self.configureHTTP2(context: context)
  153. } else if HTTPVersionParser.prefixedWithHTTP1RequestLine(buffer) {
  154. self.configureHTTP1(context: context)
  155. } else {
  156. self.configuration.logger.error("Unable to determine http version, closing")
  157. context.close(mode: .all, promise: nil)
  158. }
  159. }
  160. /// Handles a 'TLSUserEvent.handshakeCompleted' event and configures the pipeline to handle gRPC
  161. /// requests.
  162. private func handleHandshakeCompletedEvent(
  163. _ event: TLSUserEvent,
  164. alpnIsRequired: Bool,
  165. context: ChannelHandlerContext
  166. ) {
  167. switch event {
  168. case let .handshakeCompleted(negotiatedProtocol):
  169. self.configuration.logger.debug("TLS handshake completed", metadata: [
  170. "alpn": "\(negotiatedProtocol ?? "nil")",
  171. ])
  172. switch negotiatedProtocol {
  173. case let .some(negotiated):
  174. if GRPCApplicationProtocolIdentifier.isHTTP2Like(negotiated) {
  175. self.configureHTTP2(context: context)
  176. } else if GRPCApplicationProtocolIdentifier.isHTTP1(negotiated) {
  177. self.configureHTTP1(context: context)
  178. } else {
  179. self.configuration.logger.warning("Unsupported ALPN identifier '\(negotiated)', closing")
  180. context.close(mode: .all, promise: nil)
  181. }
  182. case .none:
  183. if alpnIsRequired {
  184. self.configuration.logger.warning("No ALPN protocol negotiated, closing'")
  185. context.close(mode: .all, promise: nil)
  186. } else {
  187. self.configuration.logger.warning("No ALPN protocol negotiated'")
  188. // We're now falling back to parsing bytes.
  189. self.state = .notConfigured(alpn: .expectedButFallingBack)
  190. self.tryParsingBufferedData(context: context)
  191. }
  192. }
  193. case .shutdownCompleted:
  194. // We don't care about this here.
  195. ()
  196. }
  197. }
  198. /// Try to parse the buffered data to determine whether or not HTTP/2 or HTTP/1 should be used.
  199. private func tryParsingBufferedData(context: ChannelHandlerContext) {
  200. guard let first = self.bufferedReads.first else {
  201. // No data buffered yet. We'll try when we read.
  202. return
  203. }
  204. let buffer = self.unwrapInboundIn(first)
  205. self.determineHTTPVersionAndConfigurePipeline(buffer: buffer, context: context)
  206. }
  207. // MARK: - Channel Handler
  208. internal func errorCaught(context: ChannelHandlerContext, error: Error) {
  209. if let delegate = self.configuration.errorDelegate {
  210. let baseError: Error
  211. if let errorWithContext = error as? GRPCError.WithContext {
  212. baseError = errorWithContext.error
  213. } else {
  214. baseError = error
  215. }
  216. delegate.observeLibraryError(baseError)
  217. }
  218. context.close(mode: .all, promise: nil)
  219. }
  220. internal func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  221. switch self.state {
  222. case let .notConfigured(alpn: .expected(required)):
  223. if let event = event as? TLSUserEvent {
  224. self.handleHandshakeCompletedEvent(event, alpnIsRequired: required, context: context)
  225. }
  226. case .notConfigured(alpn: .expectedButFallingBack),
  227. .notConfigured(alpn: .notExpected),
  228. .configuring:
  229. ()
  230. }
  231. context.fireUserInboundEventTriggered(event)
  232. }
  233. internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  234. self.bufferedReads.append(data)
  235. switch self.state {
  236. case .notConfigured(alpn: .notExpected),
  237. .notConfigured(alpn: .expectedButFallingBack):
  238. // If ALPN isn't expected, or we didn't negotiate via ALPN and we don't require it then we
  239. // can try parsing the data we just buffered.
  240. self.tryParsingBufferedData(context: context)
  241. case .notConfigured(alpn: .expected),
  242. .configuring:
  243. // We expect ALPN or we're being configured, just buffer the data, we'll forward it later.
  244. ()
  245. }
  246. // Don't forward the reads: we'll do so when we have configured the pipeline.
  247. }
  248. internal func removeHandler(
  249. context: ChannelHandlerContext,
  250. removalToken: ChannelHandlerContext.RemovalToken
  251. ) {
  252. // Forward any buffered reads.
  253. while let read = self.bufferedReads.popFirst() {
  254. context.fireChannelRead(read)
  255. }
  256. context.leavePipeline(removalToken: removalToken)
  257. }
  258. }
  259. // MARK: - HTTP Version Parser
  260. struct HTTPVersionParser {
  261. /// HTTP/2 connection preface bytes. See RFC 7540 § 5.3.
  262. private static let http2ClientMagic = [
  263. UInt8(ascii: "P"),
  264. UInt8(ascii: "R"),
  265. UInt8(ascii: "I"),
  266. UInt8(ascii: " "),
  267. UInt8(ascii: "*"),
  268. UInt8(ascii: " "),
  269. UInt8(ascii: "H"),
  270. UInt8(ascii: "T"),
  271. UInt8(ascii: "T"),
  272. UInt8(ascii: "P"),
  273. UInt8(ascii: "/"),
  274. UInt8(ascii: "2"),
  275. UInt8(ascii: "."),
  276. UInt8(ascii: "0"),
  277. UInt8(ascii: "\r"),
  278. UInt8(ascii: "\n"),
  279. UInt8(ascii: "\r"),
  280. UInt8(ascii: "\n"),
  281. UInt8(ascii: "S"),
  282. UInt8(ascii: "M"),
  283. UInt8(ascii: "\r"),
  284. UInt8(ascii: "\n"),
  285. UInt8(ascii: "\r"),
  286. UInt8(ascii: "\n"),
  287. ]
  288. /// Determines whether the bytes in the `ByteBuffer` are prefixed with the HTTP/2 client
  289. /// connection preface.
  290. static func prefixedWithHTTP2ConnectionPreface(_ buffer: ByteBuffer) -> Bool {
  291. let view = buffer.readableBytesView
  292. guard view.count >= HTTPVersionParser.http2ClientMagic.count else {
  293. // Not enough bytes.
  294. return false
  295. }
  296. let slice = view[view.startIndex ..< view.startIndex.advanced(by: self.http2ClientMagic.count)]
  297. return slice.elementsEqual(HTTPVersionParser.http2ClientMagic)
  298. }
  299. private static let http1_1 = [
  300. UInt8(ascii: "H"),
  301. UInt8(ascii: "T"),
  302. UInt8(ascii: "T"),
  303. UInt8(ascii: "P"),
  304. UInt8(ascii: "/"),
  305. UInt8(ascii: "1"),
  306. UInt8(ascii: "."),
  307. UInt8(ascii: "1"),
  308. ]
  309. /// Determines whether the bytes in the `ByteBuffer` are prefixed with an HTTP/1.1 request line.
  310. static func prefixedWithHTTP1RequestLine(_ buffer: ByteBuffer) -> Bool {
  311. var readableBytesView = buffer.readableBytesView
  312. // From RFC 2616 § 5.1:
  313. // Request-Line = Method SP Request-URI SP HTTP-Version CRLF
  314. // Read off the Method and Request-URI (and spaces).
  315. guard readableBytesView.trimPrefix(to: UInt8(ascii: " ")) != nil,
  316. readableBytesView.trimPrefix(to: UInt8(ascii: " ")) != nil else {
  317. return false
  318. }
  319. // Read off the HTTP-Version and CR.
  320. guard let versionView = readableBytesView.trimPrefix(to: UInt8(ascii: "\r")) else {
  321. return false
  322. }
  323. // Check that the LF followed the CR.
  324. guard readableBytesView.first == UInt8(ascii: "\n") else {
  325. return false
  326. }
  327. // Now check the HTTP version.
  328. return versionView.elementsEqual(HTTPVersionParser.http1_1)
  329. }
  330. }