diff --git a/Sources/NIOHTTP1/HTTP.swift b/Sources/NIOHTTP1/HTTP.swift index e6217bdad..fec804488 100644 --- a/Sources/NIOHTTP1/HTTP.swift +++ b/Sources/NIOHTTP1/HTTP.swift @@ -62,10 +62,8 @@ public final class HTTPResponseEncoder : ChannelOutboundHandler { public func write(ctx: ChannelHandlerContext, data: IOData, promise: Promise?) { switch self.tryUnwrapOutboundIn(data) { case .some(.head(var response)): - self.isChunked = response.headers["Content-Length"].count == 0 - if self.isChunked { - response.headers.replaceOrAdd(name: "Transfer-Encoding", value: "chunked") - } + sanitizeTransportHeaders(status: response.status, headers: &response.headers) + self.isChunked = response.headers["transfer-encoding"].contains("chunked") self.scratchBuffer.clear() response.version.write(buffer: &self.scratchBuffer) @@ -100,4 +98,19 @@ public final class HTTPResponseEncoder : ChannelOutboundHandler { ctx.write(data: data, promise: promise) } } + + /// Adjusts the response headers to ensure that the response will be well-framed. + /// + /// This method strips Content-Length and Transfer-Encoding headers from responses that must + /// not have a body. It also adds Transfer-Encoding headers to responses that do have bodies + /// but do not have any other transport headers. This ensures that we can always safely + /// reuse a connection. + private func sanitizeTransportHeaders(status: HTTPResponseStatus, headers: inout HTTPHeaders) { + if !status.mayHaveResponseBody { + headers.remove(name: "content-length") + headers.remove(name: "transfer-encoding") + } else if headers["content-length"].count == 0 { + headers.replaceOrAdd(name: "transfer-encoding", value: "chunked") + } + } } diff --git a/Sources/NIOHTTP1/HTTPTypes.swift b/Sources/NIOHTTP1/HTTPTypes.swift index fcde0ad17..b2f23e8e3 100644 --- a/Sources/NIOHTTP1/HTTPTypes.swift +++ b/Sources/NIOHTTP1/HTTPTypes.swift @@ -776,6 +776,19 @@ public enum HTTPResponseStatus: Equatable { case loopDetected case notExtended case networkAuthenticationRequired + + public var mayHaveResponseBody: Bool { + switch self { + case .`continue`, + .switchingProtocols, + .processing, + .noContent, + .custom where (code < 200) && (code >= 100): + return false + default: + return true + } + } } public func ==(lhs: HTTPResponseStatus, rhs: HTTPResponseStatus) -> Bool { diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 17ce06685..ee75c3544 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -46,5 +46,6 @@ import XCTest testCase(HTTPServerClientTest.allTests), testCase(HTTPHeadersTest.allTests), testCase(HTTPTest.allTests), + testCase(HTTPEncoderTests.allTests), ]) #endif \ No newline at end of file diff --git a/Tests/NIOHTTP1Tests/HTTPEncoderTest+XCTest.swift b/Tests/NIOHTTP1Tests/HTTPEncoderTest+XCTest.swift new file mode 100644 index 000000000..d5b037cd5 --- /dev/null +++ b/Tests/NIOHTTP1Tests/HTTPEncoderTest+XCTest.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +/// +/// HTTPEncoderTest+XCTest.swift +/// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension HTTPEncoderTests { + + static var allTests : [(String, (HTTPEncoderTests) -> () throws -> Void)] { + return [ + ("testNoAutoHeadersFor101", testNoAutoHeadersFor101), + ("testNoAutoHeadersForCustom1XX", testNoAutoHeadersForCustom1XX), + ("testNoAutoHeadersFor204", testNoAutoHeadersFor204), + ("testNoContentLengthHeadersFor101", testNoContentLengthHeadersFor101), + ("testNoContentLengthHeadersForCustom1XX", testNoContentLengthHeadersForCustom1XX), + ("testNoContentLengthHeadersFor204", testNoContentLengthHeadersFor204), + ("testNoTransferEncodingHeadersFor101", testNoTransferEncodingHeadersFor101), + ("testNoTransferEncodingHeadersForCustom1XX", testNoTransferEncodingHeadersForCustom1XX), + ("testNoTransferEncodingHeadersFor204", testNoTransferEncodingHeadersFor204), + ] + } +} + diff --git a/Tests/NIOHTTP1Tests/HTTPEncoderTest.swift b/Tests/NIOHTTP1Tests/HTTPEncoderTest.swift new file mode 100644 index 000000000..1bdd14e18 --- /dev/null +++ b/Tests/NIOHTTP1Tests/HTTPEncoderTest.swift @@ -0,0 +1,90 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest +@testable import NIO +@testable import NIOHTTP1 + +private extension ByteBuffer { + func assertContainsOnly(_ string: String) { + let innerData = self.string(at: self.readerIndex, length: self.readableBytes)! + XCTAssertEqual(innerData, string) + } +} + +class HTTPEncoderTests: XCTestCase { + private func sendResponse(withStatus status: HTTPResponseStatus, andHeaders headers: HTTPHeaders) -> ByteBuffer { + let channel = EmbeddedChannel() + defer { + XCTAssertFalse(try! channel.finish()) + } + + try! channel.pipeline.add(handler: HTTPResponseEncoder(allocator: channel.allocator)).wait() + var switchingResponse = HTTPResponseHead(version: HTTPVersion(major: 1, minor:1), status: status) + switchingResponse.headers = headers + try! channel.writeOutbound(data: HTTPResponsePart.head(switchingResponse)) + return channel.readOutbound()! + } + + func testNoAutoHeadersFor101() throws { + let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: HTTPHeaders()) + writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\n\r\n") + } + + func testNoAutoHeadersForCustom1XX() throws { + let headers = HTTPHeaders([("Link", "; rel=preload; as=style")]) + let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nlink: ; rel=preload; as=style\r\n\r\n") + } + + func testNoAutoHeadersFor204() throws { + let writtenData = sendResponse(withStatus: .noContent, andHeaders: HTTPHeaders()) + writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\n\r\n") + } + + func testNoContentLengthHeadersFor101() throws { + let headers = HTTPHeaders([("content-length", "0")]) + let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\n\r\n") + } + + func testNoContentLengthHeadersForCustom1XX() throws { + let headers = HTTPHeaders([("Link", "; rel=preload; as=style"), ("content-length", "0")]) + let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nlink: ; rel=preload; as=style\r\n\r\n") + } + + func testNoContentLengthHeadersFor204() throws { + let headers = HTTPHeaders([("content-length", "0")]) + let writtenData = sendResponse(withStatus: .noContent, andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\n\r\n") + } + + func testNoTransferEncodingHeadersFor101() throws { + let headers = HTTPHeaders([("transfer-encoding", "chunked")]) + let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\n\r\n") + } + + func testNoTransferEncodingHeadersForCustom1XX() throws { + let headers = HTTPHeaders([("Link", "; rel=preload; as=style"), ("transfer-encoding", "chunked")]) + let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nlink: ; rel=preload; as=style\r\n\r\n") + } + + func testNoTransferEncodingHeadersFor204() throws { + let headers = HTTPHeaders([("transfer-encoding", "chunked")]) + let writtenData = sendResponse(withStatus: .noContent, andHeaders: headers) + writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\n\r\n") + } +}