2018-06-22 06:23:39 +00:00
|
|
|
//
|
|
|
|
// PacketTunnelProvider.swift
|
|
|
|
// WireGuardNetworkExtension
|
|
|
|
//
|
|
|
|
// Created by Jeroen Leenarts on 19-06-18.
|
2018-06-22 20:50:16 +00:00
|
|
|
// Copyright © 2018 WireGuard. All rights reserved.
|
2018-06-22 06:23:39 +00:00
|
|
|
//
|
|
|
|
|
|
|
|
import NetworkExtension
|
2018-07-07 20:54:44 +00:00
|
|
|
import os.log
|
2018-06-22 06:23:39 +00:00
|
|
|
|
|
|
|
class PacketTunnelProvider: NEPacketTunnelProvider {
|
2018-07-07 20:54:44 +00:00
|
|
|
let wireGuardWrapper = WireGuardGoWrapper()
|
|
|
|
|
|
|
|
private let tunnelQueue = DispatchQueue(label: PacketTunnelProvider.description())
|
|
|
|
|
|
|
|
//TODO create a way to transfer config into extension
|
2018-06-22 06:23:39 +00:00
|
|
|
|
|
|
|
override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
|
2018-07-07 20:54:44 +00:00
|
|
|
os_log("Starting tunnel", log: Log.general, type: .info)
|
2018-06-22 06:23:39 +00:00
|
|
|
// Add code here to start the process of connecting the tunnel.
|
|
|
|
|
2018-07-07 20:54:44 +00:00
|
|
|
//TODO get a settings string in here.
|
|
|
|
tunnelQueue.sync {
|
|
|
|
wireGuardWrapper.turnOn(withInterfaceName: "TODO", settingsString: "TODO")
|
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
2018-07-07 20:54:44 +00:00
|
|
|
os_log("Stopping tunnel", log: Log.general, type: .info)
|
2018-06-22 06:23:39 +00:00
|
|
|
// Add code here to start the process of stopping the tunnel.
|
2018-07-07 20:54:44 +00:00
|
|
|
tunnelQueue.sync {
|
|
|
|
wireGuardWrapper.turnOff()
|
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
completionHandler()
|
|
|
|
}
|
|
|
|
|
|
|
|
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
|
|
|
|
// Add code here to handle the message.
|
|
|
|
if let handler = completionHandler {
|
|
|
|
handler(messageData)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-07 20:54:44 +00:00
|
|
|
private func loopReadPackets(_ handler: @escaping ([Data]?, Error?) -> Void) {
|
|
|
|
packetFlow.readPackets { [weak self] (_, _) in
|
|
|
|
// TODO write packets into the tunnel
|
|
|
|
self?.loopReadPackets(handler)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func writePacket(_ packet: Data, completionHandler: ((Error?) -> Void)?) {
|
|
|
|
packetFlow.writePackets([packet], withProtocols: [AF_INET] as [NSNumber])
|
|
|
|
completionHandler?(nil)
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
|
|
|
|
2018-07-07 20:54:44 +00:00
|
|
|
func writePackets(_ packets: [Data], completionHandler: ((Error?) -> Void)?) {
|
|
|
|
let protocols = [Int32](repeating: AF_INET, count: packets.count) as [NSNumber]
|
|
|
|
packetFlow.writePackets(packets, withProtocols: protocols)
|
|
|
|
completionHandler?(nil)
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
|
|
|
}
|