Tolerate out-of-band ports. (#112)
Motivation: We shouldn't crash if the user gives us a bad port. Modifications: - Check the ports are in-band before we move on. Result: We won't crash.
This commit is contained in:
parent
9fc0d32e07
commit
5c90846c1b
|
|
@ -156,6 +156,11 @@ public final class NIOTSConnectionBootstrap {
|
|||
/// - port: The port to connect to.
|
||||
/// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected.
|
||||
public func connect(host: String, port: Int) -> EventLoopFuture<Channel> {
|
||||
let validPortRange = Int(UInt16.min)...Int(UInt16.max)
|
||||
guard validPortRange.contains(port) else {
|
||||
return self.group.next().makeFailedFuture(NIOTSErrors.InvalidPort(port: port))
|
||||
}
|
||||
|
||||
guard let actualPort = NWEndpoint.Port(rawValue: UInt16(port)) else {
|
||||
return self.group.next().makeFailedFuture(NIOTSErrors.InvalidPort(port: port))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -249,6 +249,11 @@ public final class NIOTSListenerBootstrap {
|
|||
/// - host: The host to bind on.
|
||||
/// - port: The port to bind on.
|
||||
public func bind(host: String, port: Int) -> EventLoopFuture<Channel> {
|
||||
let validPortRange = Int(UInt16.min)...Int(UInt16.max)
|
||||
guard validPortRange.contains(port) else {
|
||||
return self.group.next().makeFailedFuture(NIOTSErrors.InvalidPort(port: port))
|
||||
}
|
||||
|
||||
return self.bind0 { (channel, promise) in
|
||||
do {
|
||||
// NWListener does not actually resolve hostname-based NWEndpoints
|
||||
|
|
|
|||
|
|
@ -306,6 +306,33 @@ final class NIOTSBootstrapTests: XCTestCase {
|
|||
setValue: false,
|
||||
shortOption: .disableAutoRead)
|
||||
}
|
||||
|
||||
func testBootstrapsErrorGracefullyOnOutOfBandPorts() throws {
|
||||
let invalidPortNumbers = [-1, 65536]
|
||||
|
||||
let group = NIOTSEventLoopGroup()
|
||||
defer {
|
||||
try! group.syncShutdownGracefully()
|
||||
}
|
||||
|
||||
let listenerBootstrap = NIOTSListenerBootstrap(group: group)
|
||||
let connectionBootstrap = NIOTSConnectionBootstrap(group: group)
|
||||
|
||||
for invalidPort in invalidPortNumbers {
|
||||
var listenerChannel: Channel?
|
||||
var connectionChannel: Channel?
|
||||
|
||||
XCTAssertThrowsError(listenerChannel = try listenerBootstrap.bind(host: "localhost", port: invalidPort).wait()) { error in
|
||||
XCTAssertNotNil(error as? NIOTSErrors.InvalidPort)
|
||||
}
|
||||
XCTAssertThrowsError(connectionChannel = try connectionBootstrap.connect(host: "localhost", port: invalidPort).wait()) { error in
|
||||
XCTAssertNotNil(error as? NIOTSErrors.InvalidPort)
|
||||
}
|
||||
|
||||
try? listenerChannel?.close().wait()
|
||||
try? connectionChannel?.close().wait()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Channel {
|
||||
|
|
|
|||
Loading…
Reference in New Issue