diff --git a/Sources/NIOHTTP2/HTTP2ErrorCode.swift b/Sources/NIOHTTP2/HTTP2ErrorCode.swift new file mode 100644 index 0000000..247dc0a --- /dev/null +++ b/Sources/NIOHTTP2/HTTP2ErrorCode.swift @@ -0,0 +1,174 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO + +/// HTTP/2 error codes that may be found in frames at the HTTP/2 level. +public enum HTTP2ErrorCode { + /// The associated condition is not a result of an error. For example, + /// a GOAWAY might include this code to indicate graceful shutdown of + /// a connection. + case noError + + /// The endpoint detected an unspecific protocol error. This error is + /// for use when a more specific error code is not available. + case protocolError + + /// The endpoint encountered an unexpected internal error. + case internalError + + /// The endpoint detected that its peer violated the flow-control + /// protocol. + case flowControlError + + /// The endpoint sent a SETTINGS frame but did not receive a + /// response in a timely manner. + case settingsTimeout + + /// The endpoint received a frame after a stream was half-closed. + case streamClosed + + /// The endpoint received a frame with an invalid size. + case frameSizeError + + /// The endpoint refused the stream prior to performing any + /// application processing. + case refusedStream + + /// Used by the endpoint to indicate that the stream is no + /// longer needed. + case cancel + + /// The endpoint is unable to maintain the header compression + /// context for the connection. + case compressionError + + /// The connection established in response to a CONNECT request + /// was reset or abnormally closed. + case connectError + + /// The endpoint detected that its peer is exhibiting a behavior + /// that might be generating excessive load. + case enhanceYourCalm + + /// The underlying transport has properties that do not meet + /// minimum security requirements. + case inadequateSecurity + + /// The endpoint requires that HTTP/1.1 be used instead of HTTP/2. + case http11Required + + /// The error code is not known to NIO. + case unknown(UInt32) +} + +public extension HTTP2ErrorCode { + /// Create a `HTTP2ErrorCode` from the 32-bit integer it corresponds to. + public init(_ networkInteger: UInt32) { + switch networkInteger { + case 0x0: + self = .noError + case 0x1: + self = .protocolError + case 0x2: + self = .internalError + case 0x3: + self = .flowControlError + case 0x4: + self = .settingsTimeout + case 0x5: + self = .streamClosed + case 0x6: + self = .frameSizeError + case 0x7: + self = .refusedStream + case 0x8: + self = .cancel + case 0x9: + self = .compressionError + case 0xa: + self = .connectError + case 0xb: + self = .enhanceYourCalm + case 0xc: + self = .inadequateSecurity + case 0xd: + self = .http11Required + default: + self = .unknown(networkInteger) + } + } + + /// Create a `HTTP2ErrorCode` from the integer it corresponds to. + public init(_ userInteger: Int) { + self.init(UInt32(userInteger)) + } +} + +public extension UInt32 { + /// Create a 32-bit integer corresponding to the given `HTTP2ErrorCode`. + public init(http2ErrorCode code: HTTP2ErrorCode) { + switch code { + case .noError: + self = 0x0 + case .protocolError: + self = 0x1 + case .internalError: + self = 0x2 + case .flowControlError: + self = 0x3 + case .settingsTimeout: + self = 0x4 + case .streamClosed: + self = 0x5 + case .frameSizeError: + self = 0x6 + case .refusedStream: + self = 0x7 + case .cancel: + self = 0x8 + case .compressionError: + self = 0x9 + case .connectError: + self = 0xa + case .enhanceYourCalm: + self = 0xb + case .inadequateSecurity: + self = 0xc + case .http11Required: + self = 0xd + case .unknown(let val): + self = val + } + } +} + +public extension Int { + /// Create an integer corresponding to the given `HTTP2ErrorCode`. + public init(http2ErrorCode code: HTTP2ErrorCode) { + self = Int(UInt32(http2ErrorCode: code)) + } +} + +public extension ByteBuffer { + /// Serializes a `HTTP2ErrorCode` into a `ByteBuffer` in the appropriate endianness + /// for use in HTTP/2. + /// + /// - parameters: + /// - code: The `HTTP2ErrorCode` to serialize. + /// - returns: The number of bytes written. + public mutating func write(http2ErrorCode code: HTTP2ErrorCode) -> Int { + return self.write(integer: UInt32(http2ErrorCode: code)) + } +} diff --git a/Sources/NIOHTTP2/HTTP2Frame.swift b/Sources/NIOHTTP2/HTTP2Frame.swift index 45847e9..7987cc3 100644 --- a/Sources/NIOHTTP2/HTTP2Frame.swift +++ b/Sources/NIOHTTP2/HTTP2Frame.swift @@ -132,7 +132,7 @@ public struct HTTP2Frame { case settings([(Int32, UInt32)]) case pushPromise case ping - case goAway + case goAway(lastStreamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, opaqueData: ByteBuffer?) case windowUpdate(windowSizeIncrement: Int) case continuation case alternativeService diff --git a/Sources/NIOHTTP2/HTTP2StreamID.swift b/Sources/NIOHTTP2/HTTP2StreamID.swift index cdc7eef..d188287 100644 --- a/Sources/NIOHTTP2/HTTP2StreamID.swift +++ b/Sources/NIOHTTP2/HTTP2StreamID.swift @@ -49,6 +49,12 @@ public class HTTP2StreamID { /// This can safely be used across all connections to identify stream 0. public static let rootStream: HTTP2StreamID = HTTP2StreamID(knownID: 0) + /// The largest possible stream ID on a HTTP/2 connection. + /// + /// This should not usually be used to manage a specific stream. Instead, it's a sentinel + /// that can be used to "quiesce" a HTTP/2 connection on a GOAWAY frame. + public static let maxID: HTTP2StreamID = HTTP2StreamID(knownID: Int32.max) + /// Create an abstract stream ID. /// /// An abstract stream ID represents a handle to a stream ID that may or may not yet @@ -97,8 +103,8 @@ extension HTTP2StreamID: Hashable { /// The only use-case for this today is to manage stream IDs for connections. public class HTTP2ConnectionManager { /// The map of concrete stream numbers to internal stream ID references. This is always initialized - /// with stream 0 as the root stream ID. - private var abstractConnectionMap: [Int32: HTTP2StreamID] = [0: .rootStream] + /// with stream 0 as the root stream ID, and the max stream ID. + private var abstractConnectionMap: [Int32: HTTP2StreamID] = [0: .rootStream, Int32.max: .maxID] public init() { } diff --git a/Sources/NIOHTTP2/NGHTTP2Session.swift b/Sources/NIOHTTP2/NGHTTP2Session.swift index 51c712a..b4d0f4e 100644 --- a/Sources/NIOHTTP2/NGHTTP2Session.swift +++ b/Sources/NIOHTTP2/NGHTTP2Session.swift @@ -267,6 +267,9 @@ class NGHTTP2Session { /// An internal buffer used to accumulate the body of DATA frames. private var dataAccumulation: ByteBuffer + /// Access to an allocator for use during frame callbacks. + private let allocator: ByteBufferAllocator + /// A small byte-buffer used to write DATA frame headers into. /// /// In many cases this will trigger a CoW (as most flushes will write more than one DATA @@ -307,6 +310,7 @@ class NGHTTP2Session { self.sendFunction = sendFunction self.flushFunction = flushFunction self.connectionManager = connectionManager + self.allocator = allocator // TODO(cory): We should make MAX_FRAME_SIZE configurable and use that, rather than hardcode // that value here. @@ -378,7 +382,11 @@ class NGHTTP2Session { case NGHTTP2_PING.rawValue: nioFramePayload = .ping case NGHTTP2_GOAWAY.rawValue: - nioFramePayload = .goAway + let frameData = frame.goaway + let opaqueData = frameData.opaque_data_len > 0 ? self.allocator.buffer(containingCopyOf: UnsafeBufferPointer(start: frameData.opaque_data, count: frameData.opaque_data_len)) : nil + let lastStreamID = self.connectionManager.streamID(for: frameData.last_stream_id) + let errorCode = HTTP2ErrorCode(frameData.error_code) + nioFramePayload = .goAway(lastStreamID: lastStreamID, errorCode: errorCode, opaqueData: opaqueData) case NGHTTP2_WINDOW_UPDATE.rawValue: nioFramePayload = .windowUpdate(windowSizeIncrement: Int(frame.window_update.window_size_increment)) case NGHTTP2_CONTINUATION.rawValue: @@ -518,7 +526,7 @@ class NGHTTP2Session { case .ping: fatalError("not implemented") case .goAway: - fatalError("not implemented") + self.sendGoAway(frame: frame) case .windowUpdate(let windowSizeIncrement): fatalError("not implemented") case .continuation: @@ -629,7 +637,47 @@ class NGHTTP2Session { } } + private func sendGoAway(frame: HTTP2Frame) { + guard case .goAway(let lastStreamID, let errorCode, let opaqueData) = frame.payload else { + preconditionFailure("Send goaway attempted on non-goaway frame \(frame)") + } + + precondition(frame.streamID == .rootStream, "GOAWAY must be sent on the root stream") + + func submitGoAway(opaqueData: UnsafeRawBufferPointer?) -> CInt { + return nghttp2_submit_goaway(self.session, + 0, + lastStreamID.networkStreamID!, + UInt32(http2ErrorCode: errorCode), + opaqueData?.baseAddress?.assumingMemoryBound(to: UInt8.self), + opaqueData?.count ?? 0) + } + + let rc: CInt + if let data = opaqueData { + rc = data.withUnsafeReadableBytes { submitGoAway(opaqueData: $0) } + } else { + rc = submitGoAway(opaqueData: nil) + } + + // TODO(cory): Error handling! + precondition(rc == 0) + } + deinit { nghttp2_session_del(session) } } + +private extension ByteBufferAllocator { + /// Allocate a buffer containing a copy of the bytes in `pointer`. + /// + /// - parameters: + /// - pointer: The pointer to the bytes to copy. + /// - returns: A `ByteBuffer` containing a copy of the bytes. + func buffer(containingCopyOf pointer: UnsafeBufferPointer) -> ByteBuffer { + var buffer = self.buffer(capacity: pointer.count) + buffer.write(bytes: pointer) + return buffer + } +} diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index 8a232d0..c7aca70 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -107,7 +107,31 @@ class SimpleClientServerTests: XCTestCase { // There should be no frames here. self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() - + + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } + + func testNothingButGoaway() throws { + // A simple connection with a goaway should be no big deal. + try self.basicHTTP2Connection() + let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .noError, opaqueData: nil)) + self.clientChannel.writeAndFlush(goAwayFrame, promise: nil) + self.interactInMemory(self.clientChannel, self.serverChannel) + + // The server should have received a GOAWAY. Nothing else should have happened. + let receivedGoawayFrame = try self.serverChannel.assertReceivedFrame() + receivedGoawayFrame.assertFrameMatches(this: goAwayFrame) + + // Send the GOAWAY back to the client. Should be safe. + self.serverChannel.writeAndFlush(goAwayFrame, promise: nil) + self.interactInMemory(self.clientChannel, self.serverChannel) + + // The client should not receive this GOAWAY frame, as it has shut down. + self.clientChannel.assertNoFramesReceived() + + // All should be good. + 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 1915b5e..d866ecb 100644 --- a/Tests/NIOHTTP2Tests/TestUtilities.swift +++ b/Tests/NIOHTTP2Tests/TestUtilities.swift @@ -145,6 +145,8 @@ extension HTTP2Frame { self.assertHeadersFrameMatches(this: frame, file: file, line: line) case .data: self.assertDataFrameMatches(this: frame, file: file, line: line) + case .goAway: + self.assertGoAwayFrameMatches(this: frame, file: file, line: line) default: XCTFail("No frame matching method for \(frame.payload)", file: file, line: line) } @@ -208,4 +210,33 @@ extension HTTP2Frame { "Unexpected body: expected \(payload), got \(actualPayload)", file: file, line: line) } + + func assertGoAwayFrameMatches(this frame: HTTP2Frame, file: StaticString = #file, line: UInt = #line) { + guard case .goAway(let lastStreamID, let errorCode, let opaqueData) = frame.payload else { + preconditionFailure("Goaway frames can never match non-Goaway frames.") + } + self.assertGoAwayFrame(lastStreamID: lastStreamID.networkStreamID!, + errorCode: UInt32(http2ErrorCode: errorCode), + opaqueData: opaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }, + file: file, + line: line) + } + + func assertGoAwayFrame(lastStreamID: Int32, errorCode: UInt32, opaqueData: [UInt8]?, file: StaticString = #file, line: UInt = #line) { + guard case .goAway(let actualLastStreamID, let actualErrorCode, let actualOpaqueData) = self.payload else { + XCTFail("Expected GOAWAY frame, got \(self.payload) instead", file: file, line: line) + return + } + + let integerErrorCode = UInt32(http2ErrorCode: actualErrorCode) + let byteArrayOpaqueData = actualOpaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) } + + XCTAssertEqual(self.streamID, .rootStream, "Goaway frame must be on the root stream!", file: file, line: line) + XCTAssertEqual(lastStreamID, actualLastStreamID.networkStreamID!, + "Unexpected last stream ID: expected \(lastStreamID), got \(actualLastStreamID)", file: file, line: line) + XCTAssertEqual(integerErrorCode, errorCode, + "Unexpected error code: expected \(errorCode), got \(integerErrorCode)", file: file, line: line) + XCTAssertEqual(byteArrayOpaqueData, opaqueData, + "Unexpected opaque data: expected \(String(describing: opaqueData)), got \(String(describing: byteArrayOpaqueData))", file: file, line: line) + } }