Avoid crashing when connecting to empty host. (#103)

Motivation:

Network.framework will crash when we attempt to connect to the host
string "". That's not ideal, so we should detect that case and avoid it.

Modifications:

- Add code to detect the empty host string.

Result:

No crashes when accidentally connecting to "".
This commit is contained in:
Cory Benfield 2020-08-11 10:10:17 +01:00 committed by GitHub
parent 71dbab3f12
commit bb56586c4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 0 deletions

View File

@ -500,6 +500,16 @@ extension NIOTSConnectionChannel: StateManagedChannel {
internal func beginActivating0(to target: NWEndpoint, promise: EventLoopPromise<Void>?) { internal func beginActivating0(to target: NWEndpoint, promise: EventLoopPromise<Void>?) {
assert(self.nwConnection == nil) assert(self.nwConnection == nil)
assert(self.connectPromise == nil) assert(self.connectPromise == nil)
// Before we start, we validate that the target won't cause a crash: see
// https://github.com/apple/swift-nio/issues/1617.
if case .hostPort(host: let host, port: _) = target, host == "" {
// We don't pass the promise in here because we'll actually not complete it. We complete it manually ourselves.
self.close0(error: NIOTSErrors.InvalidHostname(), mode: .all, promise: nil)
promise?.fail(NIOTSErrors.InvalidHostname())
return
}
self.connectPromise = promise self.connectPromise = promise
let parameters = NWParameters(tls: self.tlsOptions, tcp: self.tcpOptions) let parameters = NWParameters(tls: self.tlsOptions, tcp: self.tcpOptions)

View File

@ -69,5 +69,10 @@ public enum NIOTSErrors {
self.timeout = timeout self.timeout = timeout
} }
} }
/// `InvalidHostname` is thrown when attempting to connect to an invalid host.
public struct InvalidHostname: NIOTSError {
public init() { }
}
} }
#endif #endif

View File

@ -778,5 +778,12 @@ class NIOTSConnectionChannelTests: XCTestCase {
// throw // throw
XCTAssertNoThrow(try eventPromise.futureResult.wait()) XCTAssertNoThrow(try eventPromise.futureResult.wait())
} }
func testConnectingToEmptyStringErrors() throws {
let connectBootstrap = NIOTSConnectionBootstrap(group: self.group)
XCTAssertThrowsError(try connectBootstrap.connect(host: "", port: 80).wait()) { error in
XCTAssertTrue(error is NIOTSErrors.InvalidHostname)
}
}
} }
#endif #endif