diff --git a/Sources/NIO/ByteBuffer-core.swift b/Sources/NIO/ByteBuffer-core.swift index 73a24d14d..4555aea69 100644 --- a/Sources/NIO/ByteBuffer-core.swift +++ b/Sources/NIO/ByteBuffer-core.swift @@ -242,7 +242,9 @@ public struct ByteBuffer { public func dumpBytes(slice: Slice, offset: Int, length: Int) -> String { var desc = "[" for i in Int(slice.lowerBound) + offset ..< Int(slice.lowerBound) + offset + length { - desc += String(format: " %02x", self.bytes.advanced(by: Int(i)).assumingMemoryBound(to: UInt8.self).pointee) + let byte = self.bytes.advanced(by: i).assumingMemoryBound(to: UInt8.self).pointee + let hexByte = String(byte, radix: 16) + desc += " \(hexByte.count == 1 ? " " : "")\(hexByte)" } desc += " ]" return desc diff --git a/Sources/NIOChatClient/main.swift b/Sources/NIOChatClient/main.swift index f15dec281..78da65d3e 100644 --- a/Sources/NIOChatClient/main.swift +++ b/Sources/NIOChatClient/main.swift @@ -12,7 +12,6 @@ // //===----------------------------------------------------------------------===// import NIO -import class Foundation.NSNull // dummy for strings private final class ChatHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index bdaefa01e..db87e98eb 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import NIO import Dispatch -import class Foundation.NSNull // dummy for strings let newLine = "\n".utf8.first! diff --git a/Sources/NIOEchoClient/main.swift b/Sources/NIOEchoClient/main.swift index 38447ea21..576a30d56 100644 --- a/Sources/NIOEchoClient/main.swift +++ b/Sources/NIOEchoClient/main.swift @@ -12,7 +12,6 @@ // //===----------------------------------------------------------------------===// import NIO -import class Foundation.NSNull // dummy for strings print("Please enter line to send to the server") let line = readLine(strippingNewline: true)! @@ -45,7 +44,7 @@ private final class EchoHandler: ChannelInboundHandler { print("Client connected to \(ctx.channel.remoteAddress!)") // We are connected its time to send the message to the server to initialize the ping-pong sequence. - var buffer = ctx.channel.allocator.buffer(capacity: line.lengthOfBytes(using: String.Encoding.utf8)) + var buffer = ctx.channel.allocator.buffer(capacity: line.utf8.count) buffer.write(string: line) self.numBytes = buffer.readableBytes ctx.writeAndFlush(self.wrapOutboundOut(buffer), promise: nil) diff --git a/Sources/NIOEchoServer/main.swift b/Sources/NIOEchoServer/main.swift index eac030602..be41975d5 100644 --- a/Sources/NIOEchoServer/main.swift +++ b/Sources/NIOEchoServer/main.swift @@ -12,7 +12,6 @@ // //===----------------------------------------------------------------------===// import NIO -import class Foundation.NSNull // dummy for strings private final class EchoHandler: ChannelInboundHandler { public typealias InboundIn = ByteBuffer diff --git a/Sources/NIO/ByteBuffer-foundation.swift b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift similarity index 80% rename from Sources/NIO/ByteBuffer-foundation.swift rename to Sources/NIOFoundationCompat/ByteBuffer-foundation.swift index 1e18f558e..63095696c 100644 --- a/Sources/NIO/ByteBuffer-foundation.swift +++ b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift @@ -12,8 +12,23 @@ // //===----------------------------------------------------------------------===// +import NIO import struct Foundation.Data +/* + * This is NIO's `NIOFoundationCompat` module which at the moment only adds `ByteBuffer` utility methods + * for Foundation's `Data` type. + * + * The reason that it's not in the `NIO` module is that we don't want to have any direct Foundation dependencies + * in `NIO` as Foundation is problematic for a few reasons: + * + * - its implementation is different on Linux and on macOS which means our macOS tests might be inaccurate + * - on macOS Foundation is mostly written in ObjC which means the autorelease pool might get populated + * - `swift-corelibs-foundation` (the OSS Foundation used on Linux) links the world which will prevent anyone from + * having static binaries. It can also cause problems in the choice of an SSL library as Foundation already brings + * the platforms OpenSSL in which might cause problems. + */ + extension Data: ContiguousCollection { public func withUnsafeBytes(_ fn: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try self.withUnsafeBytes { (ptr: UnsafePointer) -> R in diff --git a/Sources/NIOHTTP1/HTTPResponseCompressor.swift b/Sources/NIOHTTP1/HTTPResponseCompressor.swift index 19723af73..d470c3ac4 100644 --- a/Sources/NIOHTTP1/HTTPResponseCompressor.swift +++ b/Sources/NIOHTTP1/HTTPResponseCompressor.swift @@ -15,6 +15,19 @@ import CNIOZlib import NIO +internal extension String { + /// Test if this `Collection` starts with the unicode scalars of `needle`. + /// + /// - note: This will be faster than `String.startsWith` as no unicode normalisations are performed. + /// + /// - parameters: + /// - needle: The `Collection` of `Unicode.Scalar`s to match at the beginning of `self` + /// - returns: If `self` started with the elements contained in `needle`. + func startsWithSameUnicodeScalars(string needle: S) -> Bool { + return self.unicodeScalars.starts(with: needle.unicodeScalars) + } +} + /// Given a header value, extracts the q value if there is one present. If one is not present, /// returns the default q value, 1.0. @@ -154,11 +167,11 @@ public final class HTTPResponseCompressor: ChannelInboundHandler, ChannelOutboun var anyQValue: Float = -1 for acceptHeader in acceptHeaders { - if acceptHeader.hasPrefix("gzip") || acceptHeader.hasPrefix("x-gzip") { + if acceptHeader.startsWithSameUnicodeScalars(string: "gzip") || acceptHeader.startsWithSameUnicodeScalars(string: "x-gzip") { gzipQValue = qValueFromHeader(acceptHeader) - } else if acceptHeader.hasPrefix("deflate") { + } else if acceptHeader.startsWithSameUnicodeScalars(string: "deflate") { deflateQValue = qValueFromHeader(acceptHeader) - } else if acceptHeader.hasPrefix("*") { + } else if acceptHeader.startsWithSameUnicodeScalars(string: "*") { anyQValue = qValueFromHeader(acceptHeader) } } diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 8fab5618a..b1d9727f0 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -13,16 +13,24 @@ //===----------------------------------------------------------------------===// import NIO import NIOHTTP1 -import class Foundation.NSNull /* dummy just to get Foundation to link */ extension String { func chopPrefix(_ prefix: String) -> String? { - if self.hasPrefix(prefix) { + if self.unicodeScalars.starts(with: prefix.unicodeScalars) { return String(self[self.index(self.startIndex, offsetBy: prefix.count)...]) } else { return nil } } + + func containsDotDot() -> Bool { + for idx in self.indices { + if self[idx] == "." && idx < self.index(before: self.endIndex) && self[self.index(after: idx)] == "." { + return true + } + } + return false + } } private final class HTTPHandler: ChannelInboundHandler { @@ -203,7 +211,7 @@ private final class HTTPHandler: ChannelInboundHandler { switch request { case .head(let request): - guard !request.uri.contains("..") else { + guard !request.uri.containsDotDot() else { let response = HTTPResponseHead(version: request.version, status: .forbidden) ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) ctx.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) @@ -237,7 +245,7 @@ private final class HTTPHandler: ChannelInboundHandler { let response = HTTPResponseHead(version: request.version, status: .ok) ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) var buffer = ctx.channel.allocator.buffer(capacity: 100) - buffer.write(string: "fail: \(error.localizedDescription)") + buffer.write(string: "fail: \(error)") ctx.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) return ctx.writeAndFlush(self.wrapOutboundOut(.end(nil))) } else { @@ -274,7 +282,7 @@ private final class HTTPHandler: ChannelInboundHandler { return HTTPResponseHead(version: request.version, status: .internalServerError) } }() - body.write(string: error.localizedDescription) + body.write(string: "\(error)") body.write(staticString: "\r\n") ctx.write(self.wrapOutboundOut(.head(response)), promise: nil) ctx.write(self.wrapOutboundOut(.body(.byteBuffer(body))), promise: nil) @@ -299,7 +307,7 @@ private final class HTTPHandler: ChannelInboundHandler { case .head(let request): keepAlive = request.isKeepAlive - if request.uri.hasPrefix("/dynamic") { + if request.uri.unicodeScalars.starts(with: "/dynamic".unicodeScalars) { self.handler = self.dynamicHandler(request: request) self.handler!(ctx, reqPart) return diff --git a/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest+XCTest.swift b/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest+XCTest.swift index b4de73ded..9cc9c368b 100644 --- a/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest+XCTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest+XCTest.swift @@ -43,6 +43,12 @@ extension HTTPResponseCompressorTest { ("testOutOfRangeQValuePreventsChoice", testOutOfRangeQValuePreventsChoice), ("testRemovingHandlerFailsPendingWrites", testRemovingHandlerFailsPendingWrites), ("testDoesNotBufferWritesNoAlgorithm", testDoesNotBufferWritesNoAlgorithm), + ("testStartsWithSameUnicodeScalarsWorksOnEmptyStrings", testStartsWithSameUnicodeScalarsWorksOnEmptyStrings), + ("testStartsWithSameUnicodeScalarsWorksOnLongerNeedleFalse", testStartsWithSameUnicodeScalarsWorksOnLongerNeedleFalse), + ("testStartsWithSameUnicodeScalarsWorksOnSameStrings", testStartsWithSameUnicodeScalarsWorksOnSameStrings), + ("testStartsWithSameUnicodeScalarsWorksOnPrefix", testStartsWithSameUnicodeScalarsWorksOnPrefix), + ("testStartsWithSameUnicodeScalarsSaysNoForTheSameStringInDifferentNormalisations", testStartsWithSameUnicodeScalarsSaysNoForTheSameStringInDifferentNormalisations), + ("testStartsWithSaysYesForTheSameStringInDifferentNormalisations", testStartsWithSaysYesForTheSameStringInDifferentNormalisations), ] } } diff --git a/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift b/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift index 0ded4ce02..65663c9ee 100644 --- a/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPResponseCompressorTest.swift @@ -15,7 +15,7 @@ import XCTest import CNIOZlib @testable import NIO -import NIOHTTP1 +@testable import NIOHTTP1 private class PromiseOrderer { private var promiseArray: Array> @@ -533,4 +533,44 @@ class HTTPResponseCompressorTest: XCTestCase { channel.pipeline.removeHandlers() try writePromise.futureResult.wait() } + + func testStartsWithSameUnicodeScalarsWorksOnEmptyStrings() throws { + XCTAssertTrue("".startsWithSameUnicodeScalars(string: "")) + } + + func testStartsWithSameUnicodeScalarsWorksOnLongerNeedleFalse() throws { + XCTAssertFalse("_".startsWithSameUnicodeScalars(string: "__")) + } + + func testStartsWithSameUnicodeScalarsWorksOnSameStrings() throws { + XCTAssertTrue("beer".startsWithSameUnicodeScalars(string: "beer")) + } + + func testStartsWithSameUnicodeScalarsWorksOnPrefix() throws { + XCTAssertTrue("beer is good".startsWithSameUnicodeScalars(string: "beer")) + } + + func testStartsWithSameUnicodeScalarsSaysNoForTheSameStringInDifferentNormalisations() throws { + let nfcEncodedEAigu = "\u{e9}" + let nfdEncodedEAigu = "\u{65}\u{301}" + + XCTAssertEqual(nfcEncodedEAigu, nfdEncodedEAigu) + XCTAssertTrue(nfcEncodedEAigu.startsWithSameUnicodeScalars(string: nfcEncodedEAigu)) + XCTAssertTrue(nfdEncodedEAigu.startsWithSameUnicodeScalars(string: nfdEncodedEAigu)) + // the both do _not_ start like the other + XCTAssertFalse(nfcEncodedEAigu.startsWithSameUnicodeScalars(string: nfdEncodedEAigu)) + XCTAssertFalse(nfdEncodedEAigu.startsWithSameUnicodeScalars(string: nfcEncodedEAigu)) + } + + func testStartsWithSaysYesForTheSameStringInDifferentNormalisations() throws { + let nfcEncodedEAigu = "\u{e9}" + let nfdEncodedEAigu = "\u{65}\u{301}" + + XCTAssertEqual(nfcEncodedEAigu, nfdEncodedEAigu) + XCTAssertTrue(nfcEncodedEAigu.starts(with: nfcEncodedEAigu)) + XCTAssertTrue(nfdEncodedEAigu.starts(with: nfdEncodedEAigu)) + // the both do start like the other as we do unicode normalisation + XCTAssertTrue(nfcEncodedEAigu.starts(with: nfdEncodedEAigu)) + XCTAssertTrue(nfdEncodedEAigu.starts(with: nfcEncodedEAigu)) + } } diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index 0968b0b4f..3c3f52c73 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -13,8 +13,9 @@ //===----------------------------------------------------------------------===// import XCTest -import NIOConcurrencyHelpers import NIO +import NIOConcurrencyHelpers +import NIOFoundationCompat import Dispatch @testable import NIOHTTP1 diff --git a/Tests/NIOTLSTests/SNIHandlerTests.swift b/Tests/NIOTLSTests/SNIHandlerTests.swift index 6ba70b430..32bdb53e6 100644 --- a/Tests/NIOTLSTests/SNIHandlerTests.swift +++ b/Tests/NIOTLSTests/SNIHandlerTests.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest @testable import NIO +import NIOFoundationCompat import NIOTLS private let libressl227HelloNoSni = """ diff --git a/Tests/NIOTests/ByteBufferTest.swift b/Tests/NIOTests/ByteBufferTest.swift index 3ff9e2aa2..2ce7333dd 100644 --- a/Tests/NIOTests/ByteBufferTest.swift +++ b/Tests/NIOTests/ByteBufferTest.swift @@ -15,6 +15,7 @@ import struct Foundation.Data import XCTest @testable import NIO +import NIOFoundationCompat class ByteBufferTest: XCTestCase { private let allocator = ByteBufferAllocator() diff --git a/generate_docs.sh b/generate_docs.sh index 27dc97518..79991d219 100755 --- a/generate_docs.sh +++ b/generate_docs.sh @@ -6,7 +6,7 @@ my_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" swift_version=${swift_version:-4.0.2} version=$(git describe --abbrev=0 --tags) -modules=(SwiftNIO NIOHTTP1 NIOTLS) +modules=(SwiftNIO NIOHTTP1 NIOTLS NIOFoundationCompat) if [[ $CI == true ]]; then # CI setup, assume this is running in an ubuntu docker container: diff --git a/sh-tests/tests_03_linker_things/defines.sh b/sh-tests/tests_03_linker_things/defines.sh new file mode 100644 index 000000000..c0bda434d --- /dev/null +++ b/sh-tests/tests_03_linker_things/defines.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +swift build +bin_path=$(swift build --show-bin-path) diff --git a/sh-tests/tests_03_linker_things/test_01_check_we_do_not_link_Foundation.sh b/sh-tests/tests_03_linker_things/test_01_check_we_do_not_link_Foundation.sh new file mode 100644 index 000000000..0485d9601 --- /dev/null +++ b/sh-tests/tests_03_linker_things/test_01_check_we_do_not_link_Foundation.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +source defines.sh + +function check_does_not_link() { + library="$1" + binary="$1" + + case "$(uname -s)" in + Darwin) + assert_equal "" "$(otool -L "$binary" | grep "/$library")" + ;; + Linux) + assert_equal "" "$($ldd "$binary" | grep "lib$library")" + ;; + *) + fail "unsupported OS $(uname -s)" + ;; + esac +} + +for binary in NIOEchoServer NIOEchoClient NIOChatServer NIOChatClient NIOHTTP1Server; do + check_does_not_link Foundation "$bin_path/$binary" +done