From 537cbf224f94a1cfc76fd00fe4c26cfecc741063 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Wed, 28 Jun 2017 15:13:10 +0200 Subject: [PATCH] Initial version of HTTP server codec based on nodejs http_parser --- Sources/NIOHTTP/HTTP.swift | 57 +++ Sources/NIOHTTP/HTTPCParser.swift | 381 ++++++++++++++++ Sources/NIOHTTP/HTTPTypes.swift | 708 ++++++++++++++++++++++++++++++ Sources/NIOHTTPServer/main.swift | 89 ++++ 4 files changed, 1235 insertions(+) create mode 100644 Sources/NIOHTTP/HTTP.swift create mode 100644 Sources/NIOHTTP/HTTPCParser.swift create mode 100644 Sources/NIOHTTP/HTTPTypes.swift create mode 100644 Sources/NIOHTTPServer/main.swift diff --git a/Sources/NIOHTTP/HTTP.swift b/Sources/NIOHTTP/HTTP.swift new file mode 100644 index 000000000..d08ca8a8e --- /dev/null +++ b/Sources/NIOHTTP/HTTP.swift @@ -0,0 +1,57 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation +import NIO + +public final class HTTPResponseEncoder : ChannelOutboundHandler { + + public init() { } + + public func write(ctx: ChannelHandlerContext, data: IOData, promise: Promise?) { + if let response:HTTPResponse = data.tryAsOther() { + do { + // TODO: Is 256 really a good value here ? + var buffer = try ctx.channel!.allocator.buffer(capacity: 256) + response.version.write(buffer: &buffer) + response.status.write(buffer: &buffer) + response.headers.write(buffer: &buffer) + + ctx.write(data: .byteBuffer(buffer), promise: promise) + } catch let err { + promise?.fail(error: err) + } + } else if let content: HTTPContent = data.tryAsOther() { + // TODO: Implement chunked encoding + switch content { + case .more(let buffer): + ctx.write(data: .byteBuffer(buffer), promise: promise) + case .last(let buffer): + if let buf = buffer { + ctx.write(data: .byteBuffer(buf), promise: promise) + } else if promise != nil { + // We only need to pass the promise further if the user is even interested in the result. + do { + // Empty content so just write an empty buffer + ctx.write(data: .byteBuffer(try ctx.channel!.allocator.buffer(capacity: 0)), promise: promise) + } catch let err { + promise?.fail(error: err) + } + } + } + } else { + ctx.write(data: data, promise: promise) + } + } +} diff --git a/Sources/NIOHTTP/HTTPCParser.swift b/Sources/NIOHTTP/HTTPCParser.swift new file mode 100644 index 000000000..73ebe682a --- /dev/null +++ b/Sources/NIOHTTP/HTTPCParser.swift @@ -0,0 +1,381 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation +import NIO +import CHTTPParser + +public final class HTTPRequestDecoder : ChannelInboundHandler { + var parser: UnsafeMutablePointer? + var settings: UnsafeMutablePointer? + + private var state: HTTPParserState! + + private struct HTTPParserState { + var cumulationBuffer: ByteBuffer? + var currentHeaders: HTTPHeaders? + var currentUri: String? + var currentHeaderName: String? + var parserBuffer: ByteBuffer + + mutating func reset() { + self.currentHeaders = HTTPHeaders() + self.currentUri = nil + self.currentHeaderName = nil + self.parserBuffer.clear() + } + + mutating func addHeader() -> Bool { + guard let name = currentHeaderName else { + return true + } + guard let value = parserBuffer.readString() else { + // Header value could not be parsed + return false + } + parserBuffer.clear() + + currentHeaders!.add(name: name, value: value) + currentHeaderName = nil + return true + } + + mutating func finializeHTTPRequest(parser: UnsafeMutablePointer?) -> HTTPRequest? { + guard addHeader() else { + return nil + } + + guard let method = HTTPMethod.from(httpParserMethod: http_method(rawValue: parser!.pointee.method)) else { + return nil + } + let version = HTTPVersion(major: parser!.pointee.http_minor, minor: parser!.pointee.http_major) + + + let request = HTTPRequest(version: version, method: method, uri: currentUri!, headers: currentHeaders!) + currentHeaders = nil + return request + } + + init(allocator: ByteBufferAllocator) throws { + self.parserBuffer = try allocator.buffer(capacity: 64) + } + } + + public init() { } + + public func handlerAdded(ctx: ChannelHandlerContext) throws { + parser = UnsafeMutablePointer.allocate(capacity: 1) + http_parser_init(parser, HTTP_REQUEST) + parser!.pointee.data = Unmanaged.passUnretained(ctx).toOpaque() + + settings = UnsafeMutablePointer.allocate(capacity: 1) + http_parser_settings_init(settings) + + self.state = try HTTPParserState(allocator: ctx.channel!.allocator) + + settings!.pointee.on_message_begin = { parser in + let ctx = evacuateContext(parser) + let handler = (ctx.handler as! HTTPRequestDecoder) + handler.state.reset() + + return 0 + } + settings!.pointee.on_headers_complete = { parser in + let ctx = evacuateContext(parser) + let handler = (ctx.handler as! HTTPRequestDecoder) + + guard let request = handler.state.finializeHTTPRequest(parser: parser) else { + return -1 + } + ctx.fireChannelRead(data: .other(request)) + return 0 + } + + settings!.pointee.on_body = { parser, data, len in + let ctx = evacuateContext(parser) + do { + // TODO: We may be able to just slice out the bytes + var buffer = try ctx.channel!.allocator.buffer(capacity: len) + + // This will never return nil as we allocated the buffer with the correct size + buffer.write(int8Data: data!, len: len) + + ctx.fireChannelRead(data: .other(HTTPContent.more(buffer: buffer))) + } catch let err { + // propagate the error back to the handler + (ctx.handler as! HTTPRequestDecoder).errorCaught(ctx: ctx, error: err) + return -1 + } + + return 0 + } + + settings!.pointee.on_header_field = { parser, data, len in + let ctx = evacuateContext(parser) + let handler = (ctx.handler as! HTTPRequestDecoder) + + + if handler.state.currentUri == nil { + handler.state.currentUri = handler.state.parserBuffer.readString() + if handler.state.currentUri == nil { + // URI could not be parsed. + return -1 + } + handler.state.parserBuffer.clear() + } else { + // Add header if we already parsed one + guard handler.state.addHeader() else { + parser!.pointee.http_errno = HPE_INVALID_HEADER_TOKEN.rawValue + return -1 + } + } + + handler.state.parserBuffer.write(int8Data: data!, len: len) + + return 0 + } + + settings!.pointee.on_header_value = { parser, data, len in + let ctx = evacuateContext(parser) + let handler = (ctx.handler as! HTTPRequestDecoder) + + if handler.state.currentHeaderName == nil { + handler.state.currentHeaderName = handler.state.parserBuffer.readString() + if handler.state.currentHeaderName == nil { + // Header name could not be parser. + parser!.pointee.http_errno = HPE_INVALID_HEADER_TOKEN.rawValue + return -1 + } + handler.state.parserBuffer.clear() + } + + handler.state.parserBuffer.write(int8Data: data!, len: len) + + return 0 + } + + settings!.pointee.on_url = { parser, data, len in + let ctx = evacuateContext(parser) + let handler = (ctx.handler as! HTTPRequestDecoder) + + handler.state.parserBuffer.write(int8Data: data!, len: len) + + return 0 + } + + settings!.pointee.on_message_complete = { parser in + let ctx = evacuateContext(parser) + ctx.fireChannelRead(data: .other(HTTPContent.last(buffer: nil))) + return 0 + } + } + + public func handlerRemoved(ctx: ChannelHandlerContext) { + if let p = parser { + p.pointee.data = UnsafeMutableRawPointer(bitPattern: 0x0000deadbeef0000) + p.deallocate(capacity: 1) + settings!.deallocate(capacity: 1) + settings = nil + parser = nil + } + if let buffer = state.cumulationBuffer { + ctx.fireChannelRead(data: .byteBuffer(buffer)) + } + state = nil + } + + public func channelRead(ctx: ChannelHandlerContext, data: IOData) throws { + if var buffer = data.tryAsByteBuffer() { + if buffer.readableBytes > 0 { + if var cum = state.cumulationBuffer, cum.readableBytes > 0 { + var buf = try ctx.channel!.allocator.buffer(capacity: cum.readableBytes + buffer.readableBytes) + // This will never return nil as we sized the buffer when allocating it. + buf.write(buffer: &cum) + buf.write(buffer: &buffer) + state.cumulationBuffer = buf + } else { + state.cumulationBuffer = buffer + } + } + + let result = try state.cumulationBuffer!.withReadPointer(body: { (pointer: UnsafePointer, len: Int) -> size_t in + try pointer.withMemoryRebound(to: Int8.self, capacity: len, { (bytes: UnsafePointer) -> size_t in + let result = http_parser_execute(parser, settings, bytes, len) + let errno = parser!.pointee.http_errno + if errno != 0 { + throw HTTPParserError.httpError(fromCHTTPParserErrno: http_errno(rawValue: errno))! + } + return result + }) + }) + if result > 0 { + state.cumulationBuffer!.moveReaderIndex(forwardBy: result) + if state.cumulationBuffer!.readableBytes == 0 { + state.cumulationBuffer = nil + } + } + } + } + + public func errorCaught(ctx: ChannelHandlerContext, error: Error) { + ctx.fireErrorCaught(error: error) + if error is HTTPParserError { + _ = ctx.close() + } + } +} + + +private func evacuateContext(_ opaqueContext: UnsafeMutablePointer!) -> ChannelHandlerContext { + return Unmanaged.fromOpaque(opaqueContext.pointee.data).takeUnretainedValue() +} + +extension ByteBuffer { + + mutating func readString() -> String? { + return withReadPointer(body: { (pointer, length) -> String? in + return String(bytes: UnsafeBufferPointer(start: pointer, count: length), encoding: .utf8) + }) + } + + @discardableResult mutating func write(int8Data: UnsafePointer, len: Int) -> Int { + return self.set(bytes: UnsafeRawBufferPointer(start: int8Data, count: len), at: writerIndex) + } +} + +extension HTTPParserError { + static func httpError(fromCHTTPParserErrno: http_errno) -> HTTPParserError? { + switch fromCHTTPParserErrno { + case HPE_INVALID_EOF_STATE: + return .invalidEOFState + case HPE_HEADER_OVERFLOW: + return .headerOverflow + case HPE_CLOSED_CONNECTION: + return .closedConnection + case HPE_INVALID_VERSION: + return .invalidVersion + case HPE_INVALID_STATUS: + return .invalidStatus + case HPE_INVALID_METHOD: + return .invalidMethod + case HPE_INVALID_URL: + return .invalidURL + case HPE_INVALID_HOST: + return .invalidHost + case HPE_INVALID_PORT: + return .invalidPort + case HPE_INVALID_PATH: + return .invalidPath + case HPE_INVALID_QUERY_STRING: + return .invalidQueryString + case HPE_INVALID_FRAGMENT: + return .invalidFragment + case HPE_LF_EXPECTED: + return .lfExpected + case HPE_INVALID_HEADER_TOKEN: + return .invalidHeaderToken + case HPE_INVALID_CONTENT_LENGTH: + return .invalidContentLength + case HPE_UNEXPECTED_CONTENT_LENGTH: + return .unexpectedContentLength + case HPE_INVALID_CHUNK_SIZE: + return .invalidChunkSize + case HPE_INVALID_CONSTANT: + return .invalidConstant + case HPE_STRICT: + return .strictModeAssertion + case HPE_PAUSED: + return .paused + case HPE_UNKNOWN: + return .unknown + default: + return nil + } + } +} + +extension HTTPMethod { + static func from(httpParserMethod: http_method) -> HTTPMethod? { + switch httpParserMethod { + case HTTP_DELETE: + return .DELETE + case HTTP_GET: + return .GET + case HTTP_HEAD: + return .HEAD + case HTTP_POST: + return .POST + case HTTP_PUT: + return .PUT + case HTTP_CONNECT: + return .CONNECT + case HTTP_OPTIONS: + return .OPTIONS + case HTTP_TRACE: + return .TRACE + case HTTP_COPY: + return .COPY + case HTTP_LOCK: + return .LOCK + case HTTP_MKCOL: + return .MKCOL + case HTTP_MOVE: + return .MOVE + case HTTP_PROPFIND: + return .PROPFIND + case HTTP_PROPPATCH: + return .PROPPATCH + case HTTP_SEARCH: + return .SEARCH + case HTTP_UNLOCK: + return .UNLOCK + case HTTP_BIND: + return .BIND + case HTTP_REBIND: + return .REBIND + case HTTP_UNBIND: + return .UNBIND + case HTTP_ACL: + return .ACL + case HTTP_REPORT: + return .REPORT + case HTTP_MKACTIVITY: + return .MKACTIVITY + case HTTP_CHECKOUT: + return .CHECKOUT + case HTTP_MERGE: + return .MERGE + case HTTP_MSEARCH: + return .MSEARCH + case HTTP_NOTIFY: + return .NOTIFY + case HTTP_SUBSCRIBE: + return .SUBSCRIBE + case HTTP_UNSUBSCRIBE: + return .UNSUBSCRIBE + case HTTP_PATCH: + return .PATCH + case HTTP_PURGE: + return .PURGE + case HTTP_MKCALENDAR: + return .MKCALENDAR + case HTTP_LINK: + return .LINK + case HTTP_UNLINK: + return .UNLINK + default: + return nil + } + } +} diff --git a/Sources/NIOHTTP/HTTPTypes.swift b/Sources/NIOHTTP/HTTPTypes.swift new file mode 100644 index 000000000..6d03d2841 --- /dev/null +++ b/Sources/NIOHTTP/HTTPTypes.swift @@ -0,0 +1,708 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation +import NIO + + +let crlf = "\r\n".data(using: .ascii)! +let headerSeperator = ": ".data(using: .ascii)! +let http1_1 = "HTTP/1.1 ".data(using: .ascii)! +let status200 = "200 ok\r\n".data(using: .ascii)! + +public struct HTTPRequest { + public let method: HTTPMethod + public let uri: String + public let version: HTTPVersion + public var headers: HTTPHeaders + + public init(version: HTTPVersion, method: HTTPMethod, uri: String) { + self.version = version + self.method = method + self.uri = uri + self.headers = HTTPHeaders() + } + + init(version: HTTPVersion, method: HTTPMethod, uri: String, headers: HTTPHeaders) { + self.version = version + self.method = method + self.uri = uri + self.headers = headers + } +} + +public extension HTTPRequest { + var isKeepAlive: Bool { + guard let connection = headers["connection"].first?.lowercased() else { + // HTTP 1.1 use keep-alive by default if not otherwise told. + return version.major == 1 && version.minor == 1 + } + + if connection == "close" { + return false + } + return connection == "keep-alive" + } +} + +public struct HTTPResponse { + public let status: HTTPResponseStatus + public let version: HTTPVersion + public var headers: HTTPHeaders = HTTPHeaders() + + public init(version: HTTPVersion, status: HTTPResponseStatus) { + self.version = version + self.status = status + } +} + +public enum HTTPContent { + case last(buffer: ByteBuffer?) + case more(buffer: ByteBuffer) +} + +public struct HTTPHeaders : CustomStringConvertible { + private var storage: [String:[String]] = [String:[String]]() + public var description: String { return storage.description } + + public mutating func add(name: String, value: String) { + let keyLower = name.lowercased() + storage[keyLower] = (storage[keyLower] ?? []) + [value] + } + + public subscript(name: String) -> [String] { + return storage[name.lowercased()] ?? [] + } + + func write(buffer: inout ByteBuffer) { + for k in storage { + _ = buffer.write(string: k.key) + _ = buffer.write(data: headerSeperator) + + var writerIndex = buffer.writerIndex + for value in k.value { + _ = buffer.write(string: value) + writerIndex = buffer.writerIndex + _ = buffer.write(string: ",") + } + // Discard last , + buffer.moveWriterIndex(to: writerIndex) + _ = buffer.write(data: crlf) + } + _ = buffer.write(data: crlf) + } +} + +public enum HTTPMethod { + case GET + case PUT + case ACL + case HEAD + case POST + case COPY + case LOCK + case MOVE + case BIND + case LINK + case PATCH + case TRACE + case MKCOL + case MERGE + case PURGE + case NOTIFY + case SEARCH + case UNLOCK + case REBIND + case UNBIND + case REPORT + case DELETE + case UNLINK + case CONNECT + case MSEARCH + case OPTIONS + case PROPFIND + case CHECKOUT + case PROPPATCH + case SUBSCRIBE + case MKCALENDAR + case MKACTIVITY + case UNSUBSCRIBE + case RAW(value: String) +} + +public struct HTTPVersion { + let major: UInt16 + let minor: UInt16 +} + +extension HTTPVersion { + func write(buffer: inout ByteBuffer) { + if major == 1 && minor == 1 { + // Optimize for HTTP/1.1 + buffer.write(data: http1_1) + } else { + buffer.write(string: "HTTP/") + buffer.write(string: String(major)) + buffer.write(string: ".") + buffer.write(string: String(minor)) + buffer.write(string: " ") + } + } +} + +extension HTTPParserError: CustomDebugStringConvertible { + public var debugDescription: String { + switch self { + case .invalidCharactersUsed: + return "illegal characters used in URL/headers" + case .trailingGarbage: + return "trailing garbage bytes" + case .invalidEOFState: + return "stream ended at an unexpected time" + case .headerOverflow: + return "too many header bytes seen; overflow detected" + case .closedConnection: + return "data received after completed connection: close message" + case .invalidVersion: + return "invalid HTTP version" + case .invalidStatus: + return "invalid HTTP status code" + case .invalidMethod: + return "invalid HTTP method" + case .invalidURL: + return "invalid URL" + case .invalidHost: + return "invalid host" + case .invalidPort: + return "invalid port" + case .invalidPath: + return "invalid path" + case .invalidQueryString: + return "invalid query string" + case .invalidFragment: + return "invalid fragment" + case .lfExpected: + return "LF character expected" + case .invalidHeaderToken: + return "invalid character in header" + case .invalidContentLength: + return "invalid character in content-length header" + case .unexpectedContentLength: + return "unexpected content-length header" + case .invalidChunkSize: + return "invalid character in chunk size header" + case .invalidConstant: + return "invalid constant string" + case .invalidInternalState: + return "invalid internal state (swift-http-parser error)" + case .strictModeAssertion: + return "strict mode assertion" + case .paused: + return "paused (swift-http-parser error)" + case .unknown: + return "unknown (http_parser error)" + } + } +} + +public enum HTTPParserError: Error { + case invalidCharactersUsed + case trailingGarbage + /* from CHTTPParser */ + case invalidEOFState + case headerOverflow + case closedConnection + case invalidVersion + case invalidStatus + case invalidMethod + case invalidURL + case invalidHost + case invalidPort + case invalidPath + case invalidQueryString + case invalidFragment + case lfExpected + case invalidHeaderToken + case invalidContentLength + case unexpectedContentLength + case invalidChunkSize + case invalidConstant + case invalidInternalState + case strictModeAssertion + case paused + case unknown +} + +extension HTTPResponseStatus { + public var code: UInt { + get { + switch self { + case .continue: + return 100 + case .switchingProtocols: + return 101 + case .processing: + return 102 + case .ok: + return 200 + case .created: + return 201 + case .accepted: + return 202 + case .nonAuthoritativeInformation: + return 203 + case .noContent: + return 204 + case .resetContent: + return 205 + case .partialContent: + return 206 + case .multiStatus: + return 207 + case .alreadyReported: + return 208 + case .imUsed: + return 226 + case .multipleChoices: + return 300 + case .movedPermanently: + return 301 + case .found: + return 302 + case .seeOther: + return 303 + case .notModified: + return 304 + case .useProxy: + return 305 + case .temporaryRedirect: + return 307 + case .permanentRedirect: + return 308 + case .badRequest: + return 400 + case .unauthorized: + return 401 + case .paymentRequired: + return 402 + case .forbidden: + return 403 + case .notFound: + return 404 + case .methodNotAllowed: + return 405 + case .notAcceptable: + return 406 + case .proxyAuthenticationRequired: + return 407 + case .requestTimeout: + return 408 + case .conflict: + return 409 + case .gone: + return 410 + case .lengthRequired: + return 411 + case .preconditionFailed: + return 412 + case .payloadTooLarge: + return 413 + case .uriTooLong: + return 414 + case .unsupportedMediaType: + return 415 + case .rangeNotSatisfiable: + return 416 + case .expectationFailed: + return 417 + case .misdirectedRequest: + return 421 + case .unprocessableEntity: + return 422 + case .locked: + return 423 + case .failedDependency: + return 424 + case .upgradeRequired: + return 426 + case .preconditionRequired: + return 428 + case .tooManyRequests: + return 429 + case .requestHeaderFieldsTooLarge: + return 431 + case .unavailableForLegalReasons: + return 451 + case .internalServerError: + return 500 + case .notImplemented: + return 501 + case .badGateway: + return 502 + case .serviceUnavailable: + return 503 + case .gatewayTimeout: + return 504 + case .httpVersionNotSupported: + return 505 + case .variantAlsoNegotiates: + return 506 + case .insufficientStorage: + return 507 + case .loopDetected: + return 508 + case .notExtended: + return 510 + case .networkAuthenticationRequired: + return 511 + case .custom(code: let code, reasonPhrase: _): + return code + } + } + } + + public var reasonPhrase: String { + get { + switch self { + case .continue: + return "Continue" + case .switchingProtocols: + return "Switching Protocols" + case .processing: + return "Processing" + case .ok: + return "OK" + case .created: + return "Created" + case .accepted: + return "Accepted" + case .nonAuthoritativeInformation: + return "Non-Authoritative Information" + case .noContent: + return "No Content" + case .resetContent: + return "Reset Content" + case .partialContent: + return "Partial Content" + case .multiStatus: + return "Multi-Status" + case .alreadyReported: + return "Already Reported" + case .imUsed: + return "IM Used" + case .multipleChoices: + return "Multiple Choices" + case .movedPermanently: + return "Moved Permanently" + case .found: + return "Found" + case .seeOther: + return "See Other" + case .notModified: + return "Not Modified" + case .useProxy: + return "Use Proxy" + case .temporaryRedirect: + return "Temporary Redirect" + case .permanentRedirect: + return "Permanent Redirect" + case .badRequest: + return "Bad Request" + case .unauthorized: + return "Unauthorized" + case .paymentRequired: + return "Payment Required" + case .forbidden: + return "Forbidden" + case .notFound: + return "Not Found" + case .methodNotAllowed: + return "Method Not Allowed" + case .notAcceptable: + return "Not Acceptable" + case .proxyAuthenticationRequired: + return "Proxy Authentication Required" + case .requestTimeout: + return "Request Timeout" + case .conflict: + return "Conflict" + case .gone: + return "Gone" + case .lengthRequired: + return "Length Required" + case .preconditionFailed: + return "Precondition Failed" + case .payloadTooLarge: + return "Payload Too Large" + case .uriTooLong: + return "URI Too Long" + case .unsupportedMediaType: + return "Unsupported Media Type" + case .rangeNotSatisfiable: + return "Range Not Satisfiable" + case .expectationFailed: + return "Expectation Failed" + case .misdirectedRequest: + return "Misdirected Request" + case .unprocessableEntity: + return "Unprocessable Entity" + case .locked: + return "Locked" + case .failedDependency: + return "Failed Dependency" + case .upgradeRequired: + return "Upgrade Required" + case .preconditionRequired: + return "Precondition Required" + case .tooManyRequests: + return "Too Many Requests" + case .requestHeaderFieldsTooLarge: + return "Request Header Fields Too Large" + case .unavailableForLegalReasons: + return "Unavailable For Legal Reasons" + case .internalServerError: + return "Internal Server Error" + case .notImplemented: + return "Not Implemented" + case .badGateway: + return "Bad Gateway" + case .serviceUnavailable: + return "Service Unavailable" + case .gatewayTimeout: + return "Gateway Timeout" + case .httpVersionNotSupported: + return "HTTP Version Not Supported" + case .variantAlsoNegotiates: + return "Variant Also Negotiates" + case .insufficientStorage: + return "Insufficient Storage" + case .loopDetected: + return "Loop Detected" + case .notExtended: + return "Not Extended" + case .networkAuthenticationRequired: + return "Network Authentication Required" + case .custom(code: _, reasonPhrase: let phrase): + return phrase + } + } + } + + func write(buffer: inout ByteBuffer) { + switch self { + case .ok: + // Optimize for 200 ok, which should be the most likely code (...hopefully). + buffer.write(data: status200) + default: + buffer.write(string: String(code)) + buffer.write(string: " ") + buffer.write(string: reasonPhrase) + buffer.write(data: crlf) + } + } +} + +public enum HTTPResponseStatus: Equatable { + /* use custom if you want to use a non-standard response code or + have it available in a (UInt, String) pair from a higher-level web framework. */ + case custom(code: UInt, reasonPhrase: String) + + /* all the codes from http://www.iana.org/assignments/http-status-codes */ + case `continue` + case switchingProtocols + case processing + case ok + case created + case accepted + case nonAuthoritativeInformation + case noContent + case resetContent + case partialContent + case multiStatus + case alreadyReported + case imUsed + case multipleChoices + case movedPermanently + case found + case seeOther + case notModified + case useProxy + case temporaryRedirect + case permanentRedirect + case badRequest + case unauthorized + case paymentRequired + case forbidden + case notFound + case methodNotAllowed + case notAcceptable + case proxyAuthenticationRequired + case requestTimeout + case conflict + case gone + case lengthRequired + case preconditionFailed + case payloadTooLarge + case uriTooLong + case unsupportedMediaType + case rangeNotSatisfiable + case expectationFailed + case misdirectedRequest + case unprocessableEntity + case locked + case failedDependency + case upgradeRequired + case preconditionRequired + case tooManyRequests + case requestHeaderFieldsTooLarge + case unavailableForLegalReasons + case internalServerError + case notImplemented + case badGateway + case serviceUnavailable + case gatewayTimeout + case httpVersionNotSupported + case variantAlsoNegotiates + case insufficientStorage + case loopDetected + case notExtended + case networkAuthenticationRequired +} + +public func ==(lhs: HTTPResponseStatus, rhs: HTTPResponseStatus) -> Bool { + switch (lhs, rhs) { + case (.custom(let lcode, let lreason), .custom(let rcode, let rreason)): + return lcode == rcode && lreason == rreason + case (.continue, .continue): + return true + case (.switchingProtocols, .switchingProtocols): + return true + case (.processing, .processing): + return true + case (.ok, .ok): + return true + case (.created, .created): + return true + case (.accepted, .accepted): + return true + case (.nonAuthoritativeInformation, .nonAuthoritativeInformation): + return true + case (.noContent, .noContent): + return true + case (.resetContent, .resetContent): + return true + case (.partialContent, .partialContent): + return true + case (.multiStatus, .multiStatus): + return true + case (.alreadyReported, .alreadyReported): + return true + case (.imUsed, .imUsed): + return true + case (.multipleChoices, .multipleChoices): + return true + case (.movedPermanently, .movedPermanently): + return true + case (.found, .found): + return true + case (.seeOther, .seeOther): + return true + case (.notModified, .notModified): + return true + case (.useProxy, .useProxy): + return true + case (.temporaryRedirect, .temporaryRedirect): + return true + case (.permanentRedirect, .permanentRedirect): + return true + case (.badRequest, .badRequest): + return true + case (.unauthorized, .unauthorized): + return true + case (.paymentRequired, .paymentRequired): + return true + case (.forbidden, .forbidden): + return true + case (.notFound, .notFound): + return true + case (.methodNotAllowed, .methodNotAllowed): + return true + case (.notAcceptable, .notAcceptable): + return true + case (.proxyAuthenticationRequired, .proxyAuthenticationRequired): + return true + case (.requestTimeout, .requestTimeout): + return true + case (.conflict, .conflict): + return true + case (.gone, .gone): + return true + case (.lengthRequired, .lengthRequired): + return true + case (.preconditionFailed, .preconditionFailed): + return true + case (.payloadTooLarge, .payloadTooLarge): + return true + case (.uriTooLong, .uriTooLong): + return true + case (.unsupportedMediaType, .unsupportedMediaType): + return true + case (.rangeNotSatisfiable, .rangeNotSatisfiable): + return true + case (.expectationFailed, .expectationFailed): + return true + case (.misdirectedRequest, .misdirectedRequest): + return true + case (.unprocessableEntity, .unprocessableEntity): + return true + case (.locked, .locked): + return true + case (.failedDependency, .failedDependency): + return true + case (.upgradeRequired, .upgradeRequired): + return true + case (.preconditionRequired, .preconditionRequired): + return true + case (.tooManyRequests, .tooManyRequests): + return true + case (.requestHeaderFieldsTooLarge, .requestHeaderFieldsTooLarge): + return true + case (.unavailableForLegalReasons, .unavailableForLegalReasons): + return true + case (.internalServerError, .internalServerError): + return true + case (.notImplemented, .notImplemented): + return true + case (.badGateway, .badGateway): + return true + case (.serviceUnavailable, .serviceUnavailable): + return true + case (.gatewayTimeout, .gatewayTimeout): + return true + case (.httpVersionNotSupported, .httpVersionNotSupported): + return true + case (.variantAlsoNegotiates, .variantAlsoNegotiates): + return true + case (.insufficientStorage, .insufficientStorage): + return true + case (.loopDetected, .loopDetected): + return true + case (.notExtended, .notExtended): + return true + case (.networkAuthenticationRequired, .networkAuthenticationRequired): + return true + default: + return false + } +} diff --git a/Sources/NIOHTTPServer/main.swift b/Sources/NIOHTTPServer/main.swift new file mode 100644 index 000000000..cbfe5ed5b --- /dev/null +++ b/Sources/NIOHTTPServer/main.swift @@ -0,0 +1,89 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation +import NIO +import NIOHttp + + +private class HTTPHandler : ChannelInboundHandler { + + private var buffer: ByteBuffer? = nil + private var keepAlive = false + + func channelRead(ctx: ChannelHandlerContext, data: IOData) throws { + if let request: HTTPRequest = data.tryAsOther() { + keepAlive = request.isKeepAlive + + var response = HTTPResponse(version: request.version, status: HTTPResponseStatus.ok) + response.headers.add(name: "content-length", value: "12") + ctx.write(data: .other(response), promise: nil) + } else if let content:HTTPContent = data.tryAsOther() { + switch content { + case .more(_): + break + case .last: + let content = HTTPContent.last(buffer: buffer!.slice()) + if keepAlive { + ctx.write(data: .other(content), promise: nil) + } else { + ctx.write(data: .other(content)).whenComplete(callback: { _ in + ctx.close(promise: nil) + }) + } + } + } + } + + func channelReadComplete(ctx: ChannelHandlerContext) { + ctx.flush(promise: nil) + } + + func handlerAdded(ctx: ChannelHandlerContext) throws { + buffer = try ctx.channel!.allocator.buffer(capacity: 12) + buffer!.write(string: "Hello World!") + } +} + +let group = try MultiThreadedEventLoopGroup(numThreads: 1) +let bootstrap = ServerBootstrap(group: group) + // Specify backlog and enable SO_REUSEADDR for the server itself + .option(option: ChannelOptions.Backlog, value: 256) + .option(option: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + + // Set the handlers that are applied to the accepted Channels + .handler(childHandler: ChannelInitializer(initChannel: { channel in + return channel.pipeline.add(handler: HTTPResponseEncoder()).then(callback: { v2 in + return channel.pipeline.add(handler: HTTPRequestDecoder()).then(callback: { v2 in + return channel.pipeline.add(handler: HTTPHandler()) + }) + }) + })) + + // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels + .option(childOption: ChannelOptions.Socket(IPPROTO_TCP, TCP_NODELAY), childValue: 1) + .option(childOption: ChannelOptions.Socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), childValue: 1) + .option(childOption: ChannelOptions.MaxMessagesPerRead, childValue: 1) + +defer { + _ = try? group.close() +} + +let channel = try bootstrap.bind(host: "0.0.0.0", port: 8888).wait() + +print("Server started") + +// This will never unblock as we not close the ServerChannel +try channel.closeFuture.wait() + +print("Server closed")