GRPCServerPipelineConfigurator.swift 17 KB

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