wireguard-apple/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift

146 lines
6.2 KiB
Swift
Raw Normal View History

2018-11-06 18:04:53 +00:00
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.
2018-11-29 10:16:21 +00:00
import Foundation
import Network
import NetworkExtension
import os.log
2018-08-03 20:24:41 +00:00
enum PacketTunnelProviderError: Error {
case savedProtocolConfigurationIsInvalid
case dnsResolutionFailure
case couldNotStartWireGuard
case coultNotSetNetworkSettings
2018-08-03 20:24:41 +00:00
}
class PacketTunnelProvider: NEPacketTunnelProvider {
2018-12-21 22:34:56 +00:00
2018-09-26 09:22:54 +00:00
private var wgHandle: Int32?
private var networkMonitor: NWPathMonitor?
2018-12-21 14:56:03 +00:00
private var lastFirstInterface: NWInterface?
private var packetTunnelSettingsGenerator: PacketTunnelSettingsGenerator?
2018-09-26 09:22:54 +00:00
deinit {
networkMonitor?.cancel()
}
override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
let activationAttemptId = options?["activationAttemptId"] as? String
let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId, tunnelProvider: self)
guard let tunnelProviderProtocol = protocolConfiguration as? NETunnelProviderProtocol,
2018-12-21 23:28:18 +00:00
let tunnelConfiguration = tunnelProviderProtocol.asTunnelConfiguration() else {
errorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
startTunnelCompletionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
return
2018-08-27 20:32:47 +00:00
}
2018-08-16 19:26:24 +00:00
2018-11-29 10:16:21 +00:00
configureLogger()
wg_log(.info, message: "Starting tunnel from the " + (activationAttemptId == nil ? "OS directly, rather than the app" : "app"))
let endpoints = tunnelConfiguration.peers.map { $0.endpoint }
2018-12-21 13:53:16 +00:00
guard let resolvedEndpoints = DNSResolver.resolveSync(endpoints: endpoints) else {
errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure)
startTunnelCompletionHandler(PacketTunnelProviderError.dnsResolutionFailure)
return
}
assert(endpoints.count == resolvedEndpoints.count)
2018-12-21 14:56:03 +00:00
packetTunnelSettingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration, resolvedEndpoints: resolvedEndpoints)
let fileDescriptor = packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32 //swiftlint:disable:this force_cast
if fileDescriptor < 0 {
wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor")
errorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
return
}
2018-12-21 14:56:03 +00:00
let wireguardSettings = packetTunnelSettingsGenerator!.uapiConfiguration()
networkMonitor = NWPathMonitor()
2018-12-21 14:56:03 +00:00
lastFirstInterface = networkMonitor!.currentPath.availableInterfaces.first
networkMonitor!.pathUpdateHandler = pathUpdate
networkMonitor!.start(queue: DispatchQueue(label: "NetworkMonitor"))
let handle = wireguardSettings.withGoString { return wgTurnOn($0, fileDescriptor) }
2018-08-27 20:32:47 +00:00
if handle < 0 {
2018-12-22 01:21:07 +00:00
wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(handle)")
errorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
2018-08-27 20:32:47 +00:00
return
}
wgHandle = handle
2018-08-15 20:57:40 +00:00
2018-12-21 14:56:03 +00:00
let networkSettings: NEPacketTunnelNetworkSettings = packetTunnelSettingsGenerator!.generateNetworkSettings()
setTunnelNetworkSettings(networkSettings) { error in
2018-08-27 20:32:47 +00:00
if let error = error {
2018-12-22 01:21:07 +00:00
wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
errorNotifier.notify(PacketTunnelProviderError.coultNotSetNetworkSettings)
startTunnelCompletionHandler(PacketTunnelProviderError.coultNotSetNetworkSettings)
2018-08-27 20:32:47 +00:00
} else {
startTunnelCompletionHandler(nil)
2018-08-27 20:32:47 +00:00
}
}
}
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
networkMonitor?.cancel()
networkMonitor = nil
ErrorNotifier.removeLastErrorFile()
wg_log(.info, staticMessage: "Stopping tunnel")
2018-08-27 20:32:47 +00:00
if let handle = wgHandle {
wgTurnOff(handle)
}
completionHandler()
}
private func configureLogger() {
Logger.configureGlobal(withFilePath: FileManager.networkExtensionLogFileURL?.path)
wgSetLogger { level, msgC in
guard let msgC = msgC else { return }
let logType: OSLogType
switch level {
case 0:
logType = .debug
case 1:
logType = .info
case 2:
logType = .error
default:
logType = .default
}
wg_log(logType, message: String(cString: msgC))
}
}
2018-12-21 14:56:03 +00:00
private func pathUpdate(path: Network.NWPath) {
guard let handle = wgHandle, let packetTunnelSettingsGenerator = packetTunnelSettingsGenerator else { return }
var listenPort: UInt16?
if path.availableInterfaces.isEmpty || lastFirstInterface != path.availableInterfaces.first {
listenPort = wgGetListenPort(handle)
lastFirstInterface = path.availableInterfaces.first
}
guard path.status == .satisfied else { return }
wg_log(.debug, message: "Network change detected, re-establishing sockets and IPs: \(path.availableInterfaces)")
let endpointString = packetTunnelSettingsGenerator.endpointUapiConfiguration(currentListenPort: listenPort)
let err = endpointString.withGoString { return wgSetConfig(handle, $0) }
2018-12-21 14:56:03 +00:00
if err == -EADDRINUSE && listenPort != nil {
let endpointString = packetTunnelSettingsGenerator.endpointUapiConfiguration(currentListenPort: 0)
_ = endpointString.withGoString { return wgSetConfig(handle, $0) }
2018-12-21 14:56:03 +00:00
}
}
}
2018-08-27 20:32:47 +00:00
extension String {
func withGoString<R>(_ call: (gostring_t) -> R) -> R {
func helper(_ pointer: UnsafePointer<Int8>?, _ call: (gostring_t) -> R) -> R {
return call(gostring_t(p: pointer, n: utf8.count))
}
return helper(self, call)
2018-08-27 20:32:47 +00:00
}
}