wireguard-apple/WireGuardNetworkExtension/PacketTunnelProvider.swift

79 lines
2.7 KiB
Swift
Raw Normal View History

//
// PacketTunnelProvider.swift
// WireGuardNetworkExtension
//
// Created by Jeroen Leenarts on 19-06-18.
2018-07-15 09:55:41 +00:00
// Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All rights reserved.
//
import NetworkExtension
import os.log
2018-08-03 20:24:41 +00:00
enum PacketTunnelProviderError: Error {
case tunnelSetupFailed
}
/// A packet tunnel provider object.
class PacketTunnelProvider: NEPacketTunnelProvider {
2018-08-03 20:24:41 +00:00
// MARK: Properties
/// A reference to the WireGuard wrapper object.
let wireGuardWrapper = WireGuardGoWrapper()
2018-08-03 20:24:41 +00:00
// MARK: NEPacketTunnelProvider
2018-08-03 20:24:41 +00:00
/// Begin the process of establishing the tunnel.
override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
os_log("Starting tunnel", log: Log.general, type: .info)
2018-08-03 20:24:41 +00:00
//TODO tunnel settings
if wireGuardWrapper.turnOn(withInterfaceName: "test", settingsString: "") {
// Success
// completionHandler(nil)
//TODO obtain network config from WireGuard config or remote.
// route all traffic to VPN
let defaultRoute = NEIPv4Route.default()
// defaultRoute.gatewayAddress = gateway
let ipv4Settings = NEIPv4Settings(addresses: ["149.248.160.60"], subnetMasks: ["255.255.255.255"])
ipv4Settings.includedRoutes = [defaultRoute]
ipv4Settings.excludedRoutes = []
// let dnsSettings = NEDNSSettings(servers: dnsServers)
let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "149.248.160.60")
newSettings.ipv4Settings = ipv4Settings
// newSettings.dnsSettings = dnsSettings
// newSettings.mtu = cfg.mtu
setTunnelNetworkSettings(newSettings, completionHandler: completionHandler)
2018-08-03 20:24:41 +00:00
} else {
completionHandler(PacketTunnelProviderError.tunnelSetupFailed)
}
}
2018-08-03 20:24:41 +00:00
/// Begin the process of stopping the tunnel.
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
os_log("Stopping tunnel", log: Log.general, type: .info)
2018-08-03 20:24:41 +00:00
wireGuardWrapper.turnOff()
completionHandler()
}
2018-08-03 20:24:41 +00:00
/// Handle IPC messages from the app.
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
2018-08-03 20:24:41 +00:00
guard let messageString = NSString(data: messageData, encoding: String.Encoding.utf8.rawValue) else {
completionHandler?(nil)
return
}
2018-08-03 20:24:41 +00:00
os_log("Got a message from the app: %s", log: Log.general, type: .info, messageString)
2018-08-03 20:24:41 +00:00
let responseData = "Hello app".data(using: String.Encoding.utf8)
completionHandler?(responseData)
}
}