Extend validators to work for DNS entries as well.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jeroen Leenarts 2018-08-16 22:41:45 +02:00
parent bf3510765a
commit 5a7e67b53c
2 changed files with 19 additions and 13 deletions

View File

@ -31,20 +31,28 @@ public enum EndpointValidationError: Error {
struct Endpoint { struct Endpoint {
var ipAddress: String var ipAddress: String
var port: Int32 var port: Int32?
var addressType: AddressType var addressType: AddressType
init?(endpointString: String) throws { init?(endpointString: String, needsPort: Bool = true) throws {
var ipString: String
if needsPort {
guard let range = endpointString.range(of: ":", options: .backwards, range: nil, locale: nil) else { guard let range = endpointString.range(of: ":", options: .backwards, range: nil, locale: nil) else {
throw EndpointValidationError.noIpAndPort(endpointString) throw EndpointValidationError.noIpAndPort(endpointString)
} }
ipString = String(endpointString[..<range.lowerBound])
let ipString = endpointString[..<range.lowerBound].replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "")
let portString = endpointString[range.upperBound...] let portString = endpointString[range.upperBound...]
guard let port = Int32(portString), port > 0 else { guard let port = Int32(portString), port > 0 else {
throw EndpointValidationError.invalidPort(String(portString/*parts[1]*/)) throw EndpointValidationError.invalidPort(String(portString/*parts[1]*/))
} }
self.port = port
} else {
ipString = endpointString
}
ipString = ipString.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "")
ipAddress = String(ipString) ipAddress = String(ipString)
let addressType = validateIpAddress(ipToValidate: ipAddress) let addressType = validateIpAddress(ipToValidate: ipAddress)
@ -52,8 +60,6 @@ struct Endpoint {
throw EndpointValidationError.invalidIP(ipAddress) throw EndpointValidationError.invalidIP(ipAddress)
} }
self.addressType = addressType self.addressType = addressType
self.port = port
} }
} }

View File

@ -29,7 +29,7 @@ extension Interface {
try dns?.commaSeparatedToArray().forEach { address in try dns?.commaSeparatedToArray().forEach { address in
do { do {
try _ = Endpoint(endpointString: address) try _ = Endpoint(endpointString: address, needsPort: false)
} catch { } catch {
throw InterfaceValidationError.invalidDNSServer(cause: error) throw InterfaceValidationError.invalidDNSServer(cause: error)
} }