From 95b557d617810b0d1267cfed107d215e328dcaff Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 11 May 2018 10:04:32 +0100 Subject: [PATCH] Fail writes when stream closed by rststream --- Sources/NIOHTTP2/HTTP2Error.swift | 34 ++++++- Sources/NIOHTTP2/HTTP2Frame.swift | 2 +- Sources/NIOHTTP2/HTTP2PipelineHelpers.swift | 2 +- Sources/NIOHTTP2/NGHTTP2Session.swift | 26 ++++- .../SimpleClientServerTests.swift | 99 +++++++++++++++++++ Tests/NIOHTTP2Tests/TestUtilities.swift | 19 ++++ 6 files changed, 173 insertions(+), 9 deletions(-) diff --git a/Sources/NIOHTTP2/HTTP2Error.swift b/Sources/NIOHTTP2/HTTP2Error.swift index 6b94ff5..af49775 100644 --- a/Sources/NIOHTTP2/HTTP2Error.swift +++ b/Sources/NIOHTTP2/HTTP2Error.swift @@ -12,9 +12,39 @@ // //===----------------------------------------------------------------------===// +public protocol NIOHTTP2Error: Equatable, Error { } + /// Errors that NIO raises when handling HTTP/2 connections. -public enum NIOHTTP2Error: Error { +public enum NIOHTTP2Errors { /// NIO's upgrade handler encountered a successful upgrade to a protocol that it /// does not recognise. - case invalidALPNToken + public struct InvalidALPNToken: NIOHTTP2Error { + public init() { } + } + + /// An attempt was made to issue a write on a stream that does not exist. + public struct NoSuchStream: NIOHTTP2Error { + /// The stream ID that was used that does not exist. + public var streamID: HTTP2StreamID + + public init(streamID: HTTP2StreamID) { + self.streamID = streamID + } + } + + /// A stream was closed. + public struct StreamClosed: NIOHTTP2Error { + /// The stream ID that was closed. + public var streamID: HTTP2StreamID + + /// The error code associated with the closure. + public var errorCode: HTTP2ErrorCode + + public init(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode) { + self.streamID = streamID + self.errorCode = errorCode + } + } } + + diff --git a/Sources/NIOHTTP2/HTTP2Frame.swift b/Sources/NIOHTTP2/HTTP2Frame.swift index f2303df..a7c4dfb 100644 --- a/Sources/NIOHTTP2/HTTP2Frame.swift +++ b/Sources/NIOHTTP2/HTTP2Frame.swift @@ -108,7 +108,7 @@ public struct HTTP2Frame { case data(IOData) case headers(HTTPHeaders) case priority - case rstStream + case rstStream(HTTP2ErrorCode) case settings([HTTP2Setting]) case pushPromise case ping(HTTP2PingData) diff --git a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift index 4e04cd2..7abdeb9 100644 --- a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift +++ b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift @@ -69,7 +69,7 @@ public extension ChannelPipeline { case .negotiated: // We negotiated something that isn't HTTP/1.1. This is a bad scene, and is a good indication // of a user configuration error. We're going to close the connection directly. - return self.close().then { self.eventLoop.newFailedFuture(error: NIOHTTP2Error.invalidALPNToken) } + return self.close().then { self.eventLoop.newFailedFuture(error: NIOHTTP2Errors.InvalidALPNToken()) } } } diff --git a/Sources/NIOHTTP2/NGHTTP2Session.swift b/Sources/NIOHTTP2/NGHTTP2Session.swift index f1746b5..2b5254d 100644 --- a/Sources/NIOHTTP2/NGHTTP2Session.swift +++ b/Sources/NIOHTTP2/NGHTTP2Session.swift @@ -354,7 +354,7 @@ class NGHTTP2Session { case NGHTTP2_PRIORITY.rawValue: nioFramePayload = .priority case NGHTTP2_RST_STREAM.rawValue: - nioFramePayload = .rstStream + nioFramePayload = .rstStream(HTTP2ErrorCode(frame.rst_stream.error_code)) case NGHTTP2_SETTINGS.rawValue: var settings: [HTTP2Setting] = [] settings.reserveCapacity(frame.settings.niv) @@ -396,8 +396,12 @@ class NGHTTP2Session { fileprivate func onStreamCloseCallback(streamID: Int32, errorCode: UInt32) throws { // If we have a data provider, pull it out. if let provider = self.streamDataProviders.removeValue(forKey: streamID) { - // TODO(cory): we need to fail any pending writes here. + let error = NIOHTTP2Errors.StreamClosed(streamID: self.connectionManager.streamID(for: streamID), + errorCode: HTTP2ErrorCode(errorCode)) + provider.failAllWrites(error: error) } + + // TODO(cory): Fire the errro down the pipeline. } /// Called when the reception of a HEADERS or PUSH_PROMISE frame is started. Does not contain @@ -504,7 +508,7 @@ class NGHTTP2Session { case .priority: fatalError("not implemented") case .rstStream: - fatalError("not implemented") + self.sendRstStream(frame: frame) case .settings: self.sendSettings(frame: frame) case .pushPromise: @@ -614,8 +618,11 @@ class NGHTTP2Session { guard case .data(let data) = frame.payload else { preconditionFailure("Write data attempted on non-data frame \(frame)") } - // TODO(cory): Error handling here. - let dataProvider = self.streamDataProviders[frame.streamID.networkStreamID!]! + + guard let dataProvider = self.streamDataProviders[frame.streamID.networkStreamID!] else { + promise?.fail(error: NIOHTTP2Errors.NoSuchStream(streamID: frame.streamID)) + return + } dataProvider.bufferWrite(write: data, promise: promise) // TODO(cory): trailers support @@ -681,6 +688,15 @@ class NGHTTP2Session { precondition(rc == 0) } + private func sendRstStream(frame: HTTP2Frame) { + guard case .rstStream(let errorCode) = frame.payload else { + preconditionFailure("Send rstStream attempted on non-rst-stream frame \(frame)") + } + + let rc = nghttp2_submit_rst_stream(self.session, 0, frame.streamID.networkStreamID!, UInt32(http2ErrorCode: errorCode)) + precondition(rc == 0) + } + deinit { nghttp2_session_del(session) } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index da2c902..c02cf30 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -68,6 +68,20 @@ final class NoEmptyFlushesHandler: ChannelOutboundHandler { } } +/// A channel handler that forcibly resets all inbound frames it receives. +final class InstaResetHandler: ChannelInboundHandler { + typealias InboundIn = HTTP2Frame + typealias OutboundOut = HTTP2Frame + + func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + let frame = self.unwrapInboundIn(data) + if case .headers = frame.payload { + let kaboomFrame = HTTP2Frame(streamID: frame.streamID, payload: .rstStream(.refusedStream)) + ctx.writeAndFlush(self.wrapOutboundOut(kaboomFrame), promise: nil) + } + } +} + class SimpleClientServerTests: XCTestCase { var clientChannel: EmbeddedChannel! var serverChannel: EmbeddedChannel! @@ -693,4 +707,89 @@ class SimpleClientServerTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } + + func testFailingUnflushedWritesForResetStream() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // Let's set up a stream. + let clientStreamID = HTTP2StreamID() + let headers = HTTPHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(headers)) + let serverStreamId = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + + // Now we're going to queue up a DATA frame. + var requestBody = self.clientChannel.allocator.buffer(capacity: 128) + requestBody.write(bytes: Array(repeating: UInt8(0x04), count: 128)) + let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.byteBuffer(requestBody))) + + var writeError: Error? + self.clientChannel.write(reqBodyFrame).whenFailure { + writeError = $0 + } + XCTAssertNil(writeError) + + // From the server side, we're going to send and deliver a RST_STREAM frame. The client should receive this + // frame. The pending write will not be failed because it has not yet been flushed. + let frame = HTTP2Frame(streamID: serverStreamId, payload: .rstStream(.refusedStream)) + try self.assertFramesRoundTrip(frames: [frame], sender: self.serverChannel, receiver: self.clientChannel) + XCTAssertNil(writeError) + + // When we now flush the write, that write should fail immediately. + self.clientChannel.flush() + XCTAssertEqual(writeError as? NIOHTTP2Errors.NoSuchStream, NIOHTTP2Errors.NoSuchStream(streamID: clientStreamID)) + + // No other frames should be emitted. + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } + + func testFailingFlushedWritesForResetStream() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + + // Install a reset handler. + XCTAssertNoThrow(try self.serverChannel.pipeline.add(handler: InstaResetHandler()).wait()) + + // Let's set up a stream. + let clientStreamID = HTTP2StreamID() + let headers = HTTPHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(headers)) + var requestBody = self.clientChannel.allocator.buffer(capacity: 1024) + requestBody.write(bytes: Array(repeating: UInt8(0x04), count: 1024)) + let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.byteBuffer(requestBody))) + + // We'll send some frames: specifically, a headers and 80kB of DATA. + // We do this to ensure that the DATA does not all go out to the network in one go, such that there is still + // some sitting in the pipeline when the RST_STREAM frame arrives. The last write will have a promise attached. + var writeError: Error? + self.clientChannel.write(reqFrame, promise: nil) + for _ in 0..<79 { + self.clientChannel.write(reqBodyFrame, promise: nil) + } + + self.clientChannel.writeAndFlush(reqBodyFrame).whenFailure { + writeError = $0 + } + XCTAssertNil(writeError) + + // Let the channels dance. The RST_STREAM should come through. + self.interactInMemory(self.clientChannel, self.serverChannel) + try self.clientChannel.assertReceivedFrame().assertRstStreamFrame(streamID: clientStreamID.networkStreamID!, errorCode: .refusedStream) + + // The data frame write should have exploded. + XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: clientStreamID, errorCode: .refusedStream)) + + // There will also be two window update frames on the connection covering all sent data. + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32767) + + // No other frames should be emitted. + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } } diff --git a/Tests/NIOHTTP2Tests/TestUtilities.swift b/Tests/NIOHTTP2Tests/TestUtilities.swift index 37a56ba..e82d1a3 100644 --- a/Tests/NIOHTTP2Tests/TestUtilities.swift +++ b/Tests/NIOHTTP2Tests/TestUtilities.swift @@ -186,6 +186,8 @@ extension HTTP2Frame { self.assertPingFrameMatches(this: frame, file: file, line: line) case .settings: self.assertSettingsFrameMatches(this: frame, file: file, line: line) + case .rstStream: + self.assertRstStreamFrameMatches(this: frame, file: file, line: line) default: XCTFail("No frame matching method for \(frame.payload)", file: file, line: line) } @@ -311,6 +313,23 @@ extension HTTP2Frame { XCTAssertEqual(self.streamID.networkStreamID!, streamID, "Unexpected stream ID!", file: file, line: line) XCTAssertEqual(windowIncrement, actualWindowIncrement, "Unexpected window increment!", file: file, line: line) } + + func assertRstStreamFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { + guard case .rstStream(let errorCode) = frame.payload else { + preconditionFailure("RstStream frames can never match non-RstStream frames.") + } + self.assertRstStreamFrame(streamID: frame.streamID.networkStreamID!, errorCode: errorCode, file: file, line: line) + } + + func assertRstStreamFrame(streamID: Int32, errorCode: HTTP2ErrorCode, file: StaticString = #file, line: UInt = #line) { + guard case .rstStream(let actualErrorCode) = self.payload else { + XCTFail("Expected RST_STREAM frame, got \(self.payload) instead", file: file, line: line) + return + } + + XCTAssertEqual(self.streamID.networkStreamID!, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID.networkStreamID!)!", file: file, line: line) + XCTAssertEqual(actualErrorCode, errorCode, "Non-matching error-code: expected \(errorCode), got \(actualErrorCode)", file: file, line: line) + } } /// Runs the body with a temporary file, optionally containing some file content.