GRPCServerPipelineConfigurator.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. // TODO: use sync options when NIO HTTP/2 support for them is released
  80. // https://github.com/apple/swift-nio-http2/pull/283
  81. stream.getOption(HTTP2StreamChannelOptions.streamID).map { streamID -> Logger in
  82. logger[metadataKey: MetadataKey.h2StreamID] = "\(streamID)"
  83. return logger
  84. }.recover { _ in
  85. logger[metadataKey: MetadataKey.h2StreamID] = "<unknown>"
  86. return logger
  87. }.flatMap { logger in
  88. // TODO: provide user configuration for header normalization.
  89. let handler = self.makeHTTP2ToRawGRPCHandler(normalizeHeaders: true, logger: logger)
  90. return stream.pipeline.addHandler(handler)
  91. }
  92. }
  93. }
  94. /// Makes an HTTP/2 to raw gRPC server handler.
  95. private func makeHTTP2ToRawGRPCHandler(
  96. normalizeHeaders: Bool,
  97. logger: Logger
  98. ) -> HTTP2ToRawGRPCServerCodec {
  99. return HTTP2ToRawGRPCServerCodec(
  100. servicesByName: self.configuration.serviceProvidersByName,
  101. encoding: self.configuration.messageEncoding,
  102. errorDelegate: self.configuration.errorDelegate,
  103. normalizeHeaders: normalizeHeaders,
  104. logger: logger
  105. )
  106. }
  107. /// The pipeline finished configuring.
  108. private func configurationCompleted(result: Result<Void, Error>, context: ChannelHandlerContext) {
  109. switch result {
  110. case .success:
  111. context.pipeline.removeHandler(context: context, promise: nil)
  112. case let .failure(error):
  113. self.errorCaught(context: context, error: error)
  114. }
  115. }
  116. /// Configures the pipeline to handle gRPC requests on an HTTP/2 connection.
  117. private func configureHTTP2(context: ChannelHandlerContext) {
  118. // We're now configuring the pipeline.
  119. self.state = .configuring
  120. // We could use 'Channel.configureHTTP2Pipeline', but then we'd have to find the right handlers
  121. // to then insert our keepalive and idle handlers between. We can just add everything together.
  122. let result: Result<Void, Error>
  123. do {
  124. // This is only ever called as a result of reading a user inbound event or reading inbound so
  125. // we'll be on the right event loop and sync operations are fine.
  126. let sync = context.pipeline.syncOperations
  127. try sync.addHandler(self.makeHTTP2Handler())
  128. try sync.addHandler(self.makeIdleHandler())
  129. try sync.addHandler(self.makeHTTP2Multiplexer(for: context.channel))
  130. result = .success(())
  131. } catch {
  132. result = .failure(error)
  133. }
  134. self.configurationCompleted(result: result, context: context)
  135. }
  136. /// Configures the pipeline to handle gRPC-Web requests on an HTTP/1 connection.
  137. private func configureHTTP1(context: ChannelHandlerContext) {
  138. // We're now configuring the pipeline.
  139. self.state = .configuring
  140. let result: Result<Void, Error>
  141. do {
  142. // This is only ever called as a result of reading a user inbound event or reading inbound so
  143. // we'll be on the right event loop and sync operations are fine.
  144. let sync = context.pipeline.syncOperations
  145. try sync.configureHTTPServerPipeline(withErrorHandling: true)
  146. try sync.addHandler(WebCORSHandler())
  147. let scheme = self.configuration.tls == nil ? "http" : "https"
  148. try sync.addHandler(GRPCWebToHTTP2ServerCodec(scheme: scheme))
  149. // There's no need to normalize headers for HTTP/1.
  150. try sync.addHandler(
  151. self.makeHTTP2ToRawGRPCHandler(normalizeHeaders: false, logger: self.configuration.logger)
  152. )
  153. result = .success(())
  154. } catch {
  155. result = .failure(error)
  156. }
  157. self.configurationCompleted(result: result, context: context)
  158. }
  159. /// Attempts to determine the HTTP version from the buffer and then configure the pipeline
  160. /// appropriately. Closes the connection if the HTTP version could not be determined.
  161. private func determineHTTPVersionAndConfigurePipeline(
  162. buffer: ByteBuffer,
  163. context: ChannelHandlerContext
  164. ) {
  165. if HTTPVersionParser.prefixedWithHTTP2ConnectionPreface(buffer) {
  166. self.configureHTTP2(context: context)
  167. } else if HTTPVersionParser.prefixedWithHTTP1RequestLine(buffer) {
  168. self.configureHTTP1(context: context)
  169. } else {
  170. self.configuration.logger.error("Unable to determine http version, closing")
  171. context.close(mode: .all, promise: nil)
  172. }
  173. }
  174. /// Handles a 'TLSUserEvent.handshakeCompleted' event and configures the pipeline to handle gRPC
  175. /// requests.
  176. private func handleHandshakeCompletedEvent(
  177. _ event: TLSUserEvent,
  178. alpnIsRequired: Bool,
  179. context: ChannelHandlerContext
  180. ) {
  181. switch event {
  182. case let .handshakeCompleted(negotiatedProtocol):
  183. self.configuration.logger.debug("TLS handshake completed", metadata: [
  184. "alpn": "\(negotiatedProtocol ?? "nil")",
  185. ])
  186. switch negotiatedProtocol {
  187. case let .some(negotiated):
  188. if GRPCApplicationProtocolIdentifier.isHTTP2Like(negotiated) {
  189. self.configureHTTP2(context: context)
  190. } else if GRPCApplicationProtocolIdentifier.isHTTP1(negotiated) {
  191. self.configureHTTP1(context: context)
  192. } else {
  193. self.configuration.logger.warning("Unsupported ALPN identifier '\(negotiated)', closing")
  194. context.close(mode: .all, promise: nil)
  195. }
  196. case .none:
  197. if alpnIsRequired {
  198. self.configuration.logger.warning("No ALPN protocol negotiated, closing'")
  199. context.close(mode: .all, promise: nil)
  200. } else {
  201. self.configuration.logger.warning("No ALPN protocol negotiated'")
  202. // We're now falling back to parsing bytes.
  203. self.state = .notConfigured(alpn: .expectedButFallingBack)
  204. self.tryParsingBufferedData(context: context)
  205. }
  206. }
  207. case .shutdownCompleted:
  208. // We don't care about this here.
  209. ()
  210. }
  211. }
  212. /// Try to parse the buffered data to determine whether or not HTTP/2 or HTTP/1 should be used.
  213. private func tryParsingBufferedData(context: ChannelHandlerContext) {
  214. guard let first = self.bufferedReads.first else {
  215. // No data buffered yet. We'll try when we read.
  216. return
  217. }
  218. let buffer = self.unwrapInboundIn(first)
  219. self.determineHTTPVersionAndConfigurePipeline(buffer: buffer, context: context)
  220. }
  221. // MARK: - Channel Handler
  222. internal func errorCaught(context: ChannelHandlerContext, error: Error) {
  223. if let delegate = self.configuration.errorDelegate {
  224. let baseError: Error
  225. if let errorWithContext = error as? GRPCError.WithContext {
  226. baseError = errorWithContext.error
  227. } else {
  228. baseError = error
  229. }
  230. delegate.observeLibraryError(baseError)
  231. }
  232. context.close(mode: .all, promise: nil)
  233. }
  234. internal func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  235. switch self.state {
  236. case let .notConfigured(alpn: .expected(required)):
  237. if let event = event as? TLSUserEvent {
  238. self.handleHandshakeCompletedEvent(event, alpnIsRequired: required, context: context)
  239. }
  240. case .notConfigured(alpn: .expectedButFallingBack),
  241. .notConfigured(alpn: .notExpected),
  242. .configuring:
  243. ()
  244. }
  245. context.fireUserInboundEventTriggered(event)
  246. }
  247. internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  248. self.bufferedReads.append(data)
  249. switch self.state {
  250. case .notConfigured(alpn: .notExpected),
  251. .notConfigured(alpn: .expectedButFallingBack):
  252. // If ALPN isn't expected, or we didn't negotiate via ALPN and we don't require it then we
  253. // can try parsing the data we just buffered.
  254. self.tryParsingBufferedData(context: context)
  255. case .notConfigured(alpn: .expected),
  256. .configuring:
  257. // We expect ALPN or we're being configured, just buffer the data, we'll forward it later.
  258. ()
  259. }
  260. // Don't forward the reads: we'll do so when we have configured the pipeline.
  261. }
  262. internal func removeHandler(
  263. context: ChannelHandlerContext,
  264. removalToken: ChannelHandlerContext.RemovalToken
  265. ) {
  266. // Forward any buffered reads.
  267. while let read = self.bufferedReads.popFirst() {
  268. context.fireChannelRead(read)
  269. }
  270. context.leavePipeline(removalToken: removalToken)
  271. }
  272. }
  273. // MARK: - HTTP Version Parser
  274. struct HTTPVersionParser {
  275. /// HTTP/2 connection preface bytes. See RFC 7540 § 5.3.
  276. private static let http2ClientMagic = [
  277. UInt8(ascii: "P"),
  278. UInt8(ascii: "R"),
  279. UInt8(ascii: "I"),
  280. UInt8(ascii: " "),
  281. UInt8(ascii: "*"),
  282. UInt8(ascii: " "),
  283. UInt8(ascii: "H"),
  284. UInt8(ascii: "T"),
  285. UInt8(ascii: "T"),
  286. UInt8(ascii: "P"),
  287. UInt8(ascii: "/"),
  288. UInt8(ascii: "2"),
  289. UInt8(ascii: "."),
  290. UInt8(ascii: "0"),
  291. UInt8(ascii: "\r"),
  292. UInt8(ascii: "\n"),
  293. UInt8(ascii: "\r"),
  294. UInt8(ascii: "\n"),
  295. UInt8(ascii: "S"),
  296. UInt8(ascii: "M"),
  297. UInt8(ascii: "\r"),
  298. UInt8(ascii: "\n"),
  299. UInt8(ascii: "\r"),
  300. UInt8(ascii: "\n"),
  301. ]
  302. /// Determines whether the bytes in the `ByteBuffer` are prefixed with the HTTP/2 client
  303. /// connection preface.
  304. static func prefixedWithHTTP2ConnectionPreface(_ buffer: ByteBuffer) -> Bool {
  305. let view = buffer.readableBytesView
  306. guard view.count >= HTTPVersionParser.http2ClientMagic.count else {
  307. // Not enough bytes.
  308. return false
  309. }
  310. let slice = view[view.startIndex ..< view.startIndex.advanced(by: self.http2ClientMagic.count)]
  311. return slice.elementsEqual(HTTPVersionParser.http2ClientMagic)
  312. }
  313. private static let http1_1 = [
  314. UInt8(ascii: "H"),
  315. UInt8(ascii: "T"),
  316. UInt8(ascii: "T"),
  317. UInt8(ascii: "P"),
  318. UInt8(ascii: "/"),
  319. UInt8(ascii: "1"),
  320. UInt8(ascii: "."),
  321. UInt8(ascii: "1"),
  322. ]
  323. /// Determines whether the bytes in the `ByteBuffer` are prefixed with an HTTP/1.1 request line.
  324. static func prefixedWithHTTP1RequestLine(_ buffer: ByteBuffer) -> Bool {
  325. var readableBytesView = buffer.readableBytesView
  326. // From RFC 2616 § 5.1:
  327. // Request-Line = Method SP Request-URI SP HTTP-Version CRLF
  328. // Read off the Method and Request-URI (and spaces).
  329. guard readableBytesView.trimPrefix(to: UInt8(ascii: " ")) != nil,
  330. readableBytesView.trimPrefix(to: UInt8(ascii: " ")) != nil else {
  331. return false
  332. }
  333. // Read off the HTTP-Version and CR.
  334. guard let versionView = readableBytesView.trimPrefix(to: UInt8(ascii: "\r")) else {
  335. return false
  336. }
  337. // Check that the LF followed the CR.
  338. guard readableBytesView.first == UInt8(ascii: "\n") else {
  339. return false
  340. }
  341. // Now check the HTTP version.
  342. return versionView.elementsEqual(HTTPVersionParser.http1_1)
  343. }
  344. }