PIAWGTunnelProfile.swift 8.98 KB
Newer Older
Jose Blaya's avatar
wip  
Jose Blaya committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
//
//  PIAWGTunnelProfile.swift
//  PIALibrary
//  
//  Created by Jose Antonio Blaya Garcia on 06/02/2020.
//  Copyright © 2020 Private Internet Access, Inc.
//
//  This file is part of the Private Internet Access iOS Client.
//
//  The Private Internet Access iOS Client is free software: you can redistribute it and/or
//  modify it under the terms of the GNU General Public License as published by the Free
//  Software Foundation, either version 3 of the License, or (at your option) any later version.
//
//  The Private Internet Access iOS Client is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
//  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
//  details.
//
//  You should have received a copy of the GNU General Public License along with the Private
//  Internet Access iOS Client.  If not, see <https://www.gnu.org/licenses/>.
//

import Foundation
import PIAWireguard
import NetworkExtension

/// Implementation of `VPNProfile` providing OpenVPN connectivity.
public class PIAWGTunnelProfile: NetworkExtensionProfile {
    
    public func parsedCustomConfiguration(from map: [String : Any]) -> VPNCustomConfiguration? {
        return nil
    }
    
    
    public func requestLog(withCustomConfiguration customConfiguration: VPNCustomConfiguration?, _ callback: LibraryCallback<String>?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                callback?(nil, error)
                return
            }
            
            do {
                let session = vpn.connection as? NETunnelProviderSession
                if #available(iOSApplicationExtension 12.0, *) {
                    try session?.sendProviderMessage(WGPacketTunnelProvider.Message.requestLog.data) { (data) in
                        guard let data = data, !data.isEmpty else {
                            callback?(nil, nil)
                            return
                        }
                        let log = String(data: data, encoding: .utf8)
                        callback?(log, nil)
                    }
                } else {
                    // Fallback on earlier versions
                }
            } catch let e {
                callback?(nil, e)
            }
        }

    }
    
    public func requestDataUsage(withCustomConfiguration customConfiguration: VPNCustomConfiguration?, _ callback: LibraryCallback<Usage>?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                callback?(nil, error)
                return
            }
            
            do {
                let session = vpn.connection as? NETunnelProviderSession
                if #available(iOSApplicationExtension 12.0, *) {
                    try session?.sendProviderMessage(WGPacketTunnelProvider.Message.dataCount.data) { (data) in
                        guard let data = data, !data.isEmpty else {
                            callback?(nil, ClientError.vpnProfileUnavailable)
                            return
                        }
                        
                        let downloaded = data.getInt64(start: 0)
                        let uploaded = data.getInt64(start: 8)
                        let usage = Usage(uploaded: uploaded, downloaded: downloaded)
                        callback?(usage,
                                  nil)
                    }
                } else {
                    // Fallback on earlier versions
                }
            } catch let e {
                callback?(nil, e)
            }
        }

    }
    
    private let bundleIdentifier: String

    /**
     Default initializer.
     
     - Parameter bundleIdentifier: The bundle identifier of a Packet Tunnel Provider extension subclassing `PIATunnelProvider` from `PIATunnel`.
     */
    public init(bundleIdentifier: String) {
        self.bundleIdentifier = bundleIdentifier
    }
    
    // MARK: VPNProfile
    
    /// :nodoc:
    public static var vpnType: String {
        return "PIA Wireguard"
    }
    
    /// :nodoc:
    public static var isTunnel: Bool {
        return true
    }
    
    /// :nodoc:
    public var native: Any?
    
    /// :nodoc:
    public func prepare() {
        find(completionHandler: nil)
    }
    
    /// :nodoc:
    public func save(withConfiguration configuration: VPNConfiguration, force: Bool, _ callback: SuccessLibraryCallback?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                callback?(error)
                return
            }
            self.doSave(vpn, withConfiguration: configuration, force: force, callback)
        }
    }
    
    /// :nodoc:
    public func connect(withConfiguration configuration: VPNConfiguration, _ callback: SuccessLibraryCallback?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                callback?(error)
                return
            }
            self.doSave(vpn, withConfiguration: configuration, force: true) { (error) in
                if let _ = error {
                    callback?(error)
                    return
                }
                do {
                    let session = vpn.connection as? NETunnelProviderSession
                    try session?.startTunnel(options: nil)
                    callback?(nil)
                } catch let e {
                    callback?(e)
                }
            }
        }
    }
    
    /// :nodoc:
    public func disconnect(_ callback: SuccessLibraryCallback?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                callback?(error)
                return
            }
            
            // prevent reconnection
            vpn.isOnDemandEnabled = false

            vpn.saveToPreferences { (error) in
                if let error = error {
                    vpn.connection.stopVPNTunnel()
                    callback?(error)
                    return
                }
                vpn.connection.stopVPNTunnel()
                callback?(nil)
            }
        }
    }
    
    /// :nodoc:
    public func updatePreferences(_ callback: SuccessLibraryCallback?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                callback?(error)
                return
            }
            
            vpn.saveToPreferences { (error) in
                if let error = error {
                    callback?(error)
                    return
                }
                callback?(nil)
            }
        }
    }

    /// :nodoc:
    public func disable(_ callback: SuccessLibraryCallback?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                return
            }
            vpn.isEnabled = false
            vpn.isOnDemandEnabled = false
            vpn.saveToPreferences(completionHandler: callback)
        }
    }
    
    /// :nodoc:
    public func remove(_ callback: SuccessLibraryCallback?) {
        find { (vpn, error) in
            guard let vpn = vpn else {
                return
            }
            vpn.removeFromPreferences(completionHandler: callback)
        }
    }
        
    // MARK: NetworkExtensionProfile
    
    /// :nodoc:
    public func generatedProtocol(withConfiguration configuration: VPNConfiguration) -> NEVPNProtocol {
        
        if #available(iOSApplicationExtension 12.0, *) {

Jose Blaya's avatar
Jose Blaya committed
230 231 232 233 234 235
            let cfg = NETunnelProviderProtocol()
            cfg.providerBundleIdentifier = bundleIdentifier
            cfg.serverAddress = "https://blade1.tokyo-rack401.nodes.gen4.ninja"
            cfg.username = Client.providers.accountProvider.publicUsername
            
            cfg.providerConfiguration = ["token": Client.providers.accountProvider.token]
Jose Blaya's avatar
wip  
Jose Blaya committed
236

Jose Blaya's avatar
Jose Blaya committed
237
            return cfg
Jose Blaya's avatar
wip  
Jose Blaya committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
        } else {
            return NETunnelProviderProtocol()
        }
    }
    
    // MARK: Helpers
    
    private func find(completionHandler: LibraryCallback<NETunnelProviderManager>?) {
        PIAWGTunnelProfile.find(withBundleIdentifier: bundleIdentifier) { (vpn, error) in
            self.native = vpn
            completionHandler?(vpn, error)
        }
    }

    private static func find(withBundleIdentifier identifier: String?, completionHandler: LibraryCallback<NETunnelProviderManager>?) {
        NETunnelProviderManager.loadAllFromPreferences { (managers, error) in
            guard let managers = managers else {
                completionHandler?(nil, error)
                return
            }
            var foundVPN: NETunnelProviderManager?
            for m in managers {
                guard let tunnelProtocol = m.protocolConfiguration as? NETunnelProviderProtocol else {
                    continue
                }
                guard ((identifier == nil) || (tunnelProtocol.providerBundleIdentifier == identifier)) else {
                    continue
                }
                foundVPN = m
                break
            }
            let vpn = foundVPN ?? NETunnelProviderManager()
            completionHandler?(vpn, nil)
        }
    }

}