GRPCServerPipelineConfigurator.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 NIOCore
  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. /// A buffer containing the buffered bytes.
  34. private var buffer: ByteBuffer?
  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(
  70. for channel: Channel,
  71. streamDelegate: NIOHTTP2StreamDelegate?
  72. ) -> NIOHTTP2Handler {
  73. var connectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration()
  74. connectionConfiguration.initialSettings = [
  75. HTTP2Setting(
  76. parameter: .maxConcurrentStreams,
  77. value: self.configuration.httpMaxConcurrentStreams
  78. ),
  79. HTTP2Setting(
  80. parameter: .maxHeaderListSize,
  81. value: HPACKDecoder.defaultMaxHeaderListSize
  82. ),
  83. HTTP2Setting(
  84. parameter: .maxFrameSize,
  85. value: self.configuration.httpMaxFrameSize
  86. ),
  87. HTTP2Setting(
  88. parameter: .initialWindowSize,
  89. value: self.configuration.httpTargetWindowSize
  90. ),
  91. ]
  92. var streamConfiguration = NIOHTTP2Handler.StreamConfiguration()
  93. streamConfiguration.targetWindowSize = self.configuration.httpTargetWindowSize
  94. return .init(
  95. mode: .server,
  96. eventLoop: channel.eventLoop,
  97. connectionConfiguration: connectionConfiguration,
  98. streamConfiguration: streamConfiguration,
  99. streamDelegate: streamDelegate
  100. ) { stream in
  101. // Sync options were added to the HTTP/2 stream channel in 1.17.0 (we require at least this)
  102. // so this shouldn't be `nil`, but it's not a problem if it is.
  103. let http2StreamID = try? stream.syncOptions?.getOption(HTTP2StreamChannelOptions.streamID)
  104. let streamID = http2StreamID.map { streamID in
  105. return String(Int(streamID))
  106. } ?? "<unknown>"
  107. var logger = self.configuration.logger
  108. logger[metadataKey: MetadataKey.h2StreamID] = "\(streamID)"
  109. do {
  110. // TODO: provide user configuration for header normalization.
  111. let handler = self.makeHTTP2ToRawGRPCHandler(normalizeHeaders: true, logger: logger)
  112. try stream.pipeline.syncOperations.addHandler(handler)
  113. return stream.eventLoop.makeSucceededVoidFuture()
  114. } catch {
  115. return stream.eventLoop.makeFailedFuture(error)
  116. }
  117. }
  118. }
  119. /// Makes an HTTP/2 to raw gRPC server handler.
  120. private func makeHTTP2ToRawGRPCHandler(
  121. normalizeHeaders: Bool,
  122. logger: Logger
  123. ) -> HTTP2ToRawGRPCServerCodec {
  124. return HTTP2ToRawGRPCServerCodec(
  125. servicesByName: self.configuration.serviceProvidersByName,
  126. encoding: self.configuration.messageEncoding,
  127. errorDelegate: self.configuration.errorDelegate,
  128. normalizeHeaders: normalizeHeaders,
  129. maximumReceiveMessageLength: self.configuration.maximumReceiveMessageLength,
  130. logger: logger
  131. )
  132. }
  133. /// The pipeline finished configuring.
  134. private func configurationCompleted(result: Result<Void, Error>, context: ChannelHandlerContext) {
  135. switch result {
  136. case .success:
  137. context.pipeline.removeHandler(context: context, promise: nil)
  138. case let .failure(error):
  139. self.errorCaught(context: context, error: error)
  140. }
  141. }
  142. /// Configures the pipeline to handle gRPC requests on an HTTP/2 connection.
  143. private func configureHTTP2(context: ChannelHandlerContext) {
  144. // We're now configuring the pipeline.
  145. self.state = .configuring
  146. // We could use 'Channel.configureHTTP2Pipeline', but then we'd have to find the right handlers
  147. // to then insert our keepalive and idle handlers between. We can just add everything together.
  148. let result: Result<Void, Error>
  149. let idleHandler = self.makeIdleHandler()
  150. do {
  151. // This is only ever called as a result of reading a user inbound event or reading inbound so
  152. // we'll be on the right event loop and sync operations are fine.
  153. let sync = context.pipeline.syncOperations
  154. try sync.addHandler(self.makeHTTP2Handler(for: context.channel, streamDelegate: idleHandler))
  155. // Here we intentionally don't associate the multiplexer with the idleHandler in the server case
  156. try sync.addHandler(idleHandler)
  157. result = .success(())
  158. } catch {
  159. result = .failure(error)
  160. }
  161. self.configurationCompleted(result: result, context: context)
  162. }
  163. /// Configures the pipeline to handle gRPC-Web requests on an HTTP/1 connection.
  164. private func configureHTTP1(context: ChannelHandlerContext) {
  165. // We're now configuring the pipeline.
  166. self.state = .configuring
  167. let result: Result<Void, Error>
  168. do {
  169. // This is only ever called as a result of reading a user inbound event or reading inbound so
  170. // we'll be on the right event loop and sync operations are fine.
  171. let sync = context.pipeline.syncOperations
  172. try sync.configureHTTPServerPipeline(withErrorHandling: true)
  173. try sync.addHandler(WebCORSHandler(configuration: self.configuration.webCORS))
  174. let scheme = self.configuration.tlsConfiguration == nil ? "http" : "https"
  175. try sync.addHandler(GRPCWebToHTTP2ServerCodec(scheme: scheme))
  176. // There's no need to normalize headers for HTTP/1.
  177. try sync.addHandler(
  178. self.makeHTTP2ToRawGRPCHandler(normalizeHeaders: false, logger: self.configuration.logger)
  179. )
  180. result = .success(())
  181. } catch {
  182. result = .failure(error)
  183. }
  184. self.configurationCompleted(result: result, context: context)
  185. }
  186. /// Attempts to determine the HTTP version from the buffer and then configure the pipeline
  187. /// appropriately. Closes the connection if the HTTP version could not be determined.
  188. private func determineHTTPVersionAndConfigurePipeline(
  189. buffer: ByteBuffer,
  190. context: ChannelHandlerContext
  191. ) {
  192. switch HTTPVersionParser.determineHTTPVersion(buffer) {
  193. case .http2:
  194. self.configureHTTP2(context: context)
  195. case .http1:
  196. self.configureHTTP1(context: context)
  197. case .unknown:
  198. // Neither H2 nor H1 or the length limit has been exceeded.
  199. self.configuration.logger.error("Unable to determine http version, closing")
  200. context.close(mode: .all, promise: nil)
  201. case .notEnoughBytes:
  202. () // Try again with more bytes.
  203. }
  204. }
  205. /// Handles a 'TLSUserEvent.handshakeCompleted' event and configures the pipeline to handle gRPC
  206. /// requests.
  207. private func handleHandshakeCompletedEvent(
  208. _ event: TLSUserEvent,
  209. alpnIsRequired: Bool,
  210. context: ChannelHandlerContext
  211. ) {
  212. switch event {
  213. case let .handshakeCompleted(negotiatedProtocol):
  214. let tlsVersion = try? context.channel.getTLSVersionSync()
  215. self.configuration.logger.debug("TLS handshake completed", metadata: [
  216. "alpn": "\(negotiatedProtocol ?? "nil")",
  217. "tls_version": "\(tlsVersion.map(String.init(describing:)) ?? "nil")",
  218. ])
  219. switch negotiatedProtocol {
  220. case let .some(negotiated):
  221. if GRPCApplicationProtocolIdentifier.isHTTP2Like(negotiated) {
  222. self.configureHTTP2(context: context)
  223. } else if GRPCApplicationProtocolIdentifier.isHTTP1(negotiated) {
  224. self.configureHTTP1(context: context)
  225. } else {
  226. self.configuration.logger.warning("Unsupported ALPN identifier '\(negotiated)', closing")
  227. context.close(mode: .all, promise: nil)
  228. }
  229. case .none:
  230. if alpnIsRequired {
  231. self.configuration.logger.warning("No ALPN protocol negotiated, closing'")
  232. context.close(mode: .all, promise: nil)
  233. } else {
  234. self.configuration.logger.warning("No ALPN protocol negotiated'")
  235. // We're now falling back to parsing bytes.
  236. self.state = .notConfigured(alpn: .expectedButFallingBack)
  237. self.tryParsingBufferedData(context: context)
  238. }
  239. }
  240. case .shutdownCompleted:
  241. // We don't care about this here.
  242. ()
  243. }
  244. }
  245. /// Try to parse the buffered data to determine whether or not HTTP/2 or HTTP/1 should be used.
  246. private func tryParsingBufferedData(context: ChannelHandlerContext) {
  247. if let buffer = self.buffer {
  248. self.determineHTTPVersionAndConfigurePipeline(buffer: buffer, context: context)
  249. }
  250. }
  251. // MARK: - Channel Handler
  252. internal func errorCaught(context: ChannelHandlerContext, error: Error) {
  253. if let delegate = self.configuration.errorDelegate {
  254. let baseError: Error
  255. if let errorWithContext = error as? GRPCError.WithContext {
  256. baseError = errorWithContext.error
  257. } else {
  258. baseError = error
  259. }
  260. delegate.observeLibraryError(baseError)
  261. }
  262. context.close(mode: .all, promise: nil)
  263. }
  264. internal func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
  265. switch self.state {
  266. case let .notConfigured(alpn: .expected(required)):
  267. if let event = event as? TLSUserEvent {
  268. self.handleHandshakeCompletedEvent(event, alpnIsRequired: required, context: context)
  269. }
  270. case .notConfigured(alpn: .expectedButFallingBack),
  271. .notConfigured(alpn: .notExpected),
  272. .configuring:
  273. ()
  274. }
  275. context.fireUserInboundEventTriggered(event)
  276. }
  277. internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
  278. var buffer = self.unwrapInboundIn(data)
  279. self.buffer.setOrWriteBuffer(&buffer)
  280. switch self.state {
  281. case .notConfigured(alpn: .notExpected),
  282. .notConfigured(alpn: .expectedButFallingBack):
  283. // If ALPN isn't expected, or we didn't negotiate via ALPN and we don't require it then we
  284. // can try parsing the data we just buffered.
  285. self.tryParsingBufferedData(context: context)
  286. case .notConfigured(alpn: .expected),
  287. .configuring:
  288. // We expect ALPN or we're being configured, just buffer the data, we'll forward it later.
  289. ()
  290. }
  291. // Don't forward the reads: we'll do so when we have configured the pipeline.
  292. }
  293. internal func removeHandler(
  294. context: ChannelHandlerContext,
  295. removalToken: ChannelHandlerContext.RemovalToken
  296. ) {
  297. // Forward any buffered reads.
  298. if let buffer = self.buffer {
  299. self.buffer = nil
  300. context.fireChannelRead(self.wrapInboundOut(buffer))
  301. }
  302. context.leavePipeline(removalToken: removalToken)
  303. }
  304. }
  305. // MARK: - HTTP Version Parser
  306. struct HTTPVersionParser {
  307. /// HTTP/2 connection preface bytes. See RFC 7540 § 5.3.
  308. private static let http2ClientMagic = [
  309. UInt8(ascii: "P"),
  310. UInt8(ascii: "R"),
  311. UInt8(ascii: "I"),
  312. UInt8(ascii: " "),
  313. UInt8(ascii: "*"),
  314. UInt8(ascii: " "),
  315. UInt8(ascii: "H"),
  316. UInt8(ascii: "T"),
  317. UInt8(ascii: "T"),
  318. UInt8(ascii: "P"),
  319. UInt8(ascii: "/"),
  320. UInt8(ascii: "2"),
  321. UInt8(ascii: "."),
  322. UInt8(ascii: "0"),
  323. UInt8(ascii: "\r"),
  324. UInt8(ascii: "\n"),
  325. UInt8(ascii: "\r"),
  326. UInt8(ascii: "\n"),
  327. UInt8(ascii: "S"),
  328. UInt8(ascii: "M"),
  329. UInt8(ascii: "\r"),
  330. UInt8(ascii: "\n"),
  331. UInt8(ascii: "\r"),
  332. UInt8(ascii: "\n"),
  333. ]
  334. /// Determines whether the bytes in the `ByteBuffer` are prefixed with the HTTP/2 client
  335. /// connection preface.
  336. static func prefixedWithHTTP2ConnectionPreface(_ buffer: ByteBuffer) -> SubParseResult {
  337. let view = buffer.readableBytesView
  338. guard view.count >= HTTPVersionParser.http2ClientMagic.count else {
  339. // Not enough bytes.
  340. return .notEnoughBytes
  341. }
  342. let slice = view[view.startIndex ..< view.startIndex.advanced(by: self.http2ClientMagic.count)]
  343. return slice.elementsEqual(HTTPVersionParser.http2ClientMagic) ? .accepted : .rejected
  344. }
  345. enum ParseResult: Hashable {
  346. case http1
  347. case http2
  348. case unknown
  349. case notEnoughBytes
  350. }
  351. enum SubParseResult: Hashable {
  352. case accepted
  353. case rejected
  354. case notEnoughBytes
  355. }
  356. private static let maxLengthToCheck = 1024
  357. static func determineHTTPVersion(_ buffer: ByteBuffer) -> ParseResult {
  358. switch Self.prefixedWithHTTP2ConnectionPreface(buffer) {
  359. case .accepted:
  360. return .http2
  361. case .notEnoughBytes:
  362. switch Self.prefixedWithHTTP1RequestLine(buffer) {
  363. case .accepted:
  364. // Not enough bytes to check H2, but enough to confirm H1.
  365. return .http1
  366. case .notEnoughBytes:
  367. // Not enough bytes to check H2 or H1.
  368. return .notEnoughBytes
  369. case .rejected:
  370. // Not enough bytes to check H2 and definitely not H1.
  371. return .notEnoughBytes
  372. }
  373. case .rejected:
  374. switch Self.prefixedWithHTTP1RequestLine(buffer) {
  375. case .accepted:
  376. // Not H2, but H1 is confirmed.
  377. return .http1
  378. case .notEnoughBytes:
  379. // Not H2, but not enough bytes to reject H1 yet.
  380. return .notEnoughBytes
  381. case .rejected:
  382. // Not H2 or H1.
  383. return .unknown
  384. }
  385. }
  386. }
  387. private static let http1_1 = [
  388. UInt8(ascii: "H"),
  389. UInt8(ascii: "T"),
  390. UInt8(ascii: "T"),
  391. UInt8(ascii: "P"),
  392. UInt8(ascii: "/"),
  393. UInt8(ascii: "1"),
  394. UInt8(ascii: "."),
  395. UInt8(ascii: "1"),
  396. ]
  397. /// Determines whether the bytes in the `ByteBuffer` are prefixed with an HTTP/1.1 request line.
  398. static func prefixedWithHTTP1RequestLine(_ buffer: ByteBuffer) -> SubParseResult {
  399. var readableBytesView = buffer.readableBytesView
  400. // We don't need to validate the request line, only determine whether we think it's an HTTP1
  401. // request line. Another handler will parse it properly.
  402. // From RFC 2616 § 5.1:
  403. // Request-Line = Method SP Request-URI SP HTTP-Version CRLF
  404. // Get through the first space.
  405. guard readableBytesView.dropPrefix(through: UInt8(ascii: " ")) != nil else {
  406. let tooLong = buffer.readableBytes > Self.maxLengthToCheck
  407. return tooLong ? .rejected : .notEnoughBytes
  408. }
  409. // Get through the second space.
  410. guard readableBytesView.dropPrefix(through: UInt8(ascii: " ")) != nil else {
  411. let tooLong = buffer.readableBytes > Self.maxLengthToCheck
  412. return tooLong ? .rejected : .notEnoughBytes
  413. }
  414. // +2 for \r\n
  415. guard readableBytesView.count >= (Self.http1_1.count + 2) else {
  416. return .notEnoughBytes
  417. }
  418. guard let version = readableBytesView.dropPrefix(through: UInt8(ascii: "\r")),
  419. readableBytesView.first == UInt8(ascii: "\n") else {
  420. // If we didn't drop the prefix OR we did and the next byte wasn't '\n', then we had enough
  421. // bytes but the '\r\n' wasn't present: reject this as being HTTP1.
  422. return .rejected
  423. }
  424. return version.elementsEqual(Self.http1_1) ? .accepted : .rejected
  425. }
  426. }
  427. extension Collection where Self == Self.SubSequence, Self.Element: Equatable {
  428. /// Drops the prefix off the collection up to and including the first `separator`
  429. /// only if that separator appears in the collection.
  430. ///
  431. /// Returns the prefix up to but not including the separator if it was found, nil otherwise.
  432. mutating func dropPrefix(through separator: Element) -> SubSequence? {
  433. if self.isEmpty {
  434. return nil
  435. }
  436. guard let separatorIndex = self.firstIndex(of: separator) else {
  437. return nil
  438. }
  439. let prefix = self[..<separatorIndex]
  440. self = self[self.index(after: separatorIndex)...]
  441. return prefix
  442. }
  443. }