wireguard-apple/WireGuard/Shared/Model/NETunnelProviderProtocol+Ex...

70 lines
2.7 KiB
Swift
Raw Normal View History

// SPDX-License-Identifier: MIT
2019-01-02 00:56:33 +00:00
// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved.
import NetworkExtension
enum PacketTunnelProviderError: String, Error {
case savedProtocolConfigurationIsInvalid
case dnsResolutionFailure
case couldNotStartBackend
case couldNotDetermineFileDescriptor
case couldNotSetNetworkSettings
}
extension NETunnelProviderProtocol {
convenience init?(tunnelConfiguration: TunnelConfiguration, previouslyFrom old: NEVPNProtocol? = nil) {
self.init()
2018-12-21 22:34:56 +00:00
guard let name = tunnelConfiguration.name else { return nil }
guard let appId = Bundle.main.bundleIdentifier else { return nil }
providerBundleIdentifier = "\(appId).network-extension"
passwordReference = Keychain.makeReference(containing: tunnelConfiguration.asWgQuickConfig(), called: name, previouslyReferencedBy: old?.passwordReference)
if passwordReference == nil {
return nil
}
2018-12-21 22:34:56 +00:00
2018-12-21 04:52:45 +00:00
let endpoints = tunnelConfiguration.peers.compactMap { $0.endpoint }
if endpoints.count == 1 {
2018-12-21 04:52:45 +00:00
serverAddress = endpoints[0].stringRepresentation
} else if endpoints.isEmpty {
serverAddress = "Unspecified"
} else {
serverAddress = "Multiple endpoints"
}
}
2018-12-21 22:34:56 +00:00
2018-12-21 23:28:18 +00:00
func asTunnelConfiguration(called name: String? = nil) -> TunnelConfiguration? {
if let passwordReference = passwordReference,
let config = Keychain.openReference(called: passwordReference) {
return try? TunnelConfiguration(fromWgQuickConfig: config, called: name)
}
if let oldConfig = providerConfiguration?["WgQuickConfig"] as? String {
return try? TunnelConfiguration(fromWgQuickConfig: oldConfig, called: name)
}
return nil
}
2018-12-21 22:34:56 +00:00
func destroyConfigurationReference() {
guard let ref = passwordReference else { return }
Keychain.deleteReference(called: ref)
}
func verifyConfigurationReference() -> Data? {
guard let ref = passwordReference else { return nil }
return Keychain.verifyReference(called: ref) ? ref : nil
}
@discardableResult
func migrateConfigurationIfNeeded(called name: String) -> Bool {
/* This is how we did things before we switched to putting items
* in the keychain. But it's still useful to keep the migration
* around so that .mobileconfig files are easier.
*/
guard let oldConfig = providerConfiguration?["WgQuickConfig"] as? String else { return false }
providerConfiguration = nil
guard passwordReference == nil else { return true }
passwordReference = Keychain.makeReference(containing: oldConfig, called: name)
return true
}
}