GRPCServerPipelineConfigurator.swift 14 KB

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