From 6346bad069be47f1d25c04af74ce0cd3b2c3457d Mon Sep 17 00:00:00 2001 From: Jeroen Leenarts Date: Wed, 3 Oct 2018 21:34:51 +0200 Subject: [PATCH] Better handling of CIDR values. Signed-off-by: Jason A. Donenfeld --- Shared/Validators.swift | 43 ++++++++++++++----- ...nnelConfigurationTableViewController.swift | 8 ++++ 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/Shared/Validators.swift b/Shared/Validators.swift index a73f329..cf20326 100644 --- a/Shared/Validators.swift +++ b/Shared/Validators.swift @@ -122,25 +122,42 @@ struct CIDRAddress { var addressType: AddressType init?(stringRepresentation: String) throws { - guard let range = stringRepresentation.range(of: "/", options: .backwards, range: nil, locale: nil) else { - throw CIDRAddressValidationError.noIpAndSubnet(stringRepresentation) + let subnetString: String.SubSequence + if let range = stringRepresentation.range(of: "/", options: .backwards, range: nil, locale: nil) { + let ipString = stringRepresentation[.. 128 ? 128 : subnet + case .IPv4: + self.subnet = subnet > 32 ? 32 : subnet + case .other: + self.subnet = subnet + } + } else { + switch addressType { + case .IPv4: + subnet = 32 + case .IPv6: + subnet = 128 + case .other: + throw CIDRAddressValidationError.invalidSubnet(String(subnetString)) + } + } } var subnetString: String { @@ -156,4 +173,8 @@ struct CIDRAddress { return "\(first).\(second).\(third).\(fourth)" } + + var stringRepresentation: String { + return "\(ipAddress)/\(subnet)" + } } diff --git a/WireGuard/ViewControllers/TunnelConfigurationTableViewController.swift b/WireGuard/ViewControllers/TunnelConfigurationTableViewController.swift index 0d2fe2f..65679c7 100644 --- a/WireGuard/ViewControllers/TunnelConfigurationTableViewController.swift +++ b/WireGuard/ViewControllers/TunnelConfigurationTableViewController.swift @@ -224,6 +224,14 @@ extension InterfaceTableViewCell: UITextFieldDelegate { } } } + + func textFieldDidEndEditing(_ textField: UITextField) { + if textField == addressesField { + if let addresses = model.addresses?.commaSeparatedToArray() { + textField.text = addresses.compactMap { try? CIDRAddress(stringRepresentation: $0 ) }.compactMap { $0?.stringRepresentation }.joined(separator: ", ") + } + } + } } protocol PeerTableViewCellDelegate: class {