passepartout-apple/PassepartoutLibrary/Sources/PassepartoutVPNImpl/Strategies/TunnelKitVPNManagerStrategy...

389 lines
12 KiB
Swift
Raw Normal View History

2022-06-23 21:31:01 +00:00
//
// TunnelKitVPNManagerStrategy.swift
// Passepartout
//
// Created by Davide De Rosa on 3/4/22.
2023-03-17 15:56:19 +00:00
// Copyright (c) 2023 Davide De Rosa. All rights reserved.
2022-06-23 21:31:01 +00:00
//
// https://github.com/passepartoutvpn
//
// This file is part of Passepartout.
//
// Passepartout 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.
//
// Passepartout 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 Passepartout. If not, see <http://www.gnu.org/licenses/>.
//
import Combine
import Foundation
2022-06-23 21:31:01 +00:00
import NetworkExtension
import PassepartoutCore
2023-05-24 16:19:47 +00:00
import PassepartoutProviders
import PassepartoutVPN
2022-06-23 21:31:01 +00:00
import TunnelKitCore
import TunnelKitManager
import TunnelKitOpenVPNCore
typealias TunnelKitVPNConfiguration = (neConfiguration: NetworkExtensionConfiguration, neExtra: NetworkExtensionExtra)
2023-05-24 16:19:47 +00:00
protocol TunnelKitConfigurationProviding {
func tunnelKitConfiguration(_ appGroup: String, parameters: VPNConfigurationParameters) throws -> TunnelKitVPNConfiguration
2023-05-24 16:19:47 +00:00
}
public final class TunnelKitVPNManagerStrategy<VPNType: VPN>: VPNManagerStrategy where VPNType.Configuration == NetworkExtensionConfiguration, VPNType.Extra == NetworkExtensionExtra {
2022-06-23 21:31:01 +00:00
private struct AtomicState: Equatable {
let isEnabled: Bool
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
let vpnStatus: VPNStatus
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
init(isEnabled: Bool = false, vpnStatus: VPNStatus = .disconnected) {
self.isEnabled = isEnabled
self.vpnStatus = vpnStatus
}
}
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
private let appGroup: String
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
private let tunnelBundleIdentifier: (VPNProtocolType) -> String
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
private let defaults: UserDefaults
private let vpn: VPNType
2023-03-17 20:55:47 +00:00
private let reconnectionInterval: TimeInterval
2022-06-23 21:31:01 +00:00
private let dataCountInterval: TimeInterval
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
// MARK: State
2023-03-17 20:55:47 +00:00
2023-05-24 16:19:47 +00:00
private var currentState: MutableObservableVPNState?
2022-06-23 21:31:01 +00:00
private let vpnState = CurrentValueSubject<AtomicState, Never>(.init())
private var dataCountTimer: AnyCancellable?
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
private var cancellables: Set<AnyCancellable> = []
// MARK: Protocol specific
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
private var currentBundleIdentifier: String?
public init(
appGroup: String,
tunnelBundleIdentifier: @escaping (VPNProtocolType) -> String,
vpn: VPNType,
reconnectionInterval: TimeInterval = 2.0,
dataCountInterval: TimeInterval = 3.0
) {
2022-06-23 21:31:01 +00:00
self.appGroup = appGroup
self.tunnelBundleIdentifier = tunnelBundleIdentifier
guard let defaults = UserDefaults(suiteName: appGroup) else {
fatalError("No entitlements for group '\(appGroup)'")
}
self.defaults = defaults
self.vpn = vpn
self.reconnectionInterval = reconnectionInterval
2022-06-23 21:31:01 +00:00
self.dataCountInterval = dataCountInterval
registerNotification(withName: VPNNotification.didReinstall) {
self.onVPNReinstall($0)
}
registerNotification(withName: VPNNotification.didChangeStatus) {
self.onVPNStatus($0)
}
registerNotification(withName: VPNNotification.didFail) {
self.onVPNFail($0)
}
Task {
await vpn.prepare()
}
}
private func registerNotification(withName name: Notification.Name, perform: @escaping (Notification) -> Void) {
NotificationCenter.default.publisher(for: name, object: nil)
.receive(on: DispatchQueue.main)
.sink(receiveValue: perform)
.store(in: &cancellables)
}
2023-05-24 16:19:47 +00:00
}
2023-03-17 20:55:47 +00:00
2023-05-24 16:19:47 +00:00
// MARK: Actions
2023-03-17 20:55:47 +00:00
2023-05-24 16:19:47 +00:00
extension TunnelKitVPNManagerStrategy {
2023-07-02 10:51:50 +00:00
public func observe(into state: MutableObservableVPNState) {
2022-06-23 21:31:01 +00:00
currentState = state
// use this to drop redundant NE notifications
vpnState
.removeDuplicates()
.receive(on: DispatchQueue.main)
2023-09-08 14:20:01 +00:00
.sink { [weak self] in
self?.currentState?.isEnabled = $0.isEnabled
self?.currentState?.vpnStatus = $0.vpnStatus
2022-06-23 21:31:01 +00:00
}.store(in: &cancellables)
}
2023-03-17 20:55:47 +00:00
public func reinstate(_ parameters: VPNConfigurationParameters) async throws {
let configuration = try vpnConfiguration(withParameters: parameters)
2022-06-23 21:31:01 +00:00
guard let vpnType = configuration.neConfiguration as? VPNProtocolProviding else {
fatalError("Configuration must implement VPNProtocolProviding")
}
let bundleIdentifier = tunnelBundleIdentifier(vpnType.vpnProtocol)
currentBundleIdentifier = bundleIdentifier
pp_log.verbose("Configuration: \(configuration)")
pp_log.info("Reinstating VPN...")
do {
try await vpn.install(
bundleIdentifier,
configuration: configuration.neConfiguration,
extra: configuration.neExtra
)
} catch {
pp_log.error("Unable to install: \(error)")
}
}
2023-03-17 20:55:47 +00:00
public func connect(_ parameters: VPNConfigurationParameters) async throws {
let configuration = try vpnConfiguration(withParameters: parameters)
2022-06-23 21:31:01 +00:00
guard let vpnType = configuration.neConfiguration as? VPNProtocolProviding else {
fatalError("Configuration must implement VPNProtocolProviding")
}
let bundleIdentifier = tunnelBundleIdentifier(vpnType.vpnProtocol)
currentBundleIdentifier = bundleIdentifier
pp_log.verbose("Configuration: \(configuration)")
pp_log.info("Reconnecting VPN...")
do {
try await vpn.reconnect(
bundleIdentifier,
configuration: configuration.neConfiguration,
extra: configuration.neExtra,
after: reconnectionInterval.dispatchTimeInterval
2022-06-23 21:31:01 +00:00
)
} catch {
pp_log.error("Unable to connect: \(error)")
}
}
2023-03-17 20:55:47 +00:00
public func reconnect() async {
try? await vpn.reconnect(
after: reconnectionInterval.dispatchTimeInterval
)
}
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
public func disconnect() async {
await vpn.disconnect()
}
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
public func removeConfigurations() async {
await vpn.uninstall()
// XXX: force isEnabled to false as it's not properly notified by NetworkExtension
vpnState.send(AtomicState(
isEnabled: false,
vpnStatus: vpnState.value.vpnStatus
))
}
2023-05-24 16:19:47 +00:00
}
2023-03-17 20:55:47 +00:00
2023-05-24 16:19:47 +00:00
// MARK: Notifications
2022-06-23 21:31:01 +00:00
private extension TunnelKitVPNManagerStrategy {
func onVPNReinstall(_ notification: Notification) {
2022-06-23 21:31:01 +00:00
guard isRelevantNotification(notification) else {
return
}
vpnState.send(AtomicState(
isEnabled: notification.vpnIsEnabled,
vpnStatus: vpnState.value.vpnStatus
))
}
func onVPNStatus(_ notification: Notification) {
2022-06-23 21:31:01 +00:00
// assume first notified identifier to be the relevant one
// in order to restore VPN status on app launch
if currentBundleIdentifier == nil {
currentBundleIdentifier = notification.vpnBundleIdentifier
}
guard isRelevantNotification(notification) else {
return
}
var error: Error?
switch notification.vpnStatus {
case .connected:
startCountingData()
case .disconnecting:
error = lastError(withBundleIdentifier: notification.vpnBundleIdentifier)
case .disconnected:
error = lastError(withBundleIdentifier: notification.vpnBundleIdentifier)
stopCountingData()
default:
break
}
vpnState.send(AtomicState(
isEnabled: notification.vpnIsEnabled,
vpnStatus: notification.vpnStatus
))
currentState?.lastError = error
}
2023-03-17 20:55:47 +00:00
func onVPNFail(_ notification: Notification) {
2022-06-23 21:31:01 +00:00
vpnState.send(AtomicState(
isEnabled: notification.vpnIsEnabled,
vpnStatus: vpnState.value.vpnStatus
))
currentState?.lastError = notification.vpnError
}
func isRelevantNotification(_ notification: Notification) -> Bool {
2022-06-23 21:31:01 +00:00
guard let notificationTunnelIdentifier = notification.vpnBundleIdentifier else {
return false
}
guard notificationTunnelIdentifier == currentBundleIdentifier else {
pp_log.debug("Skipping not relevant notification from \(notificationTunnelIdentifier)")
return false
}
return true
}
// MARK: Data count
func onDataCount(_: Date) {
2022-06-23 21:31:01 +00:00
switch vpnState.value.vpnStatus {
case .connected:
guard let currentDataCount = currentDataCount else {
return
}
currentState?.dataCount = currentDataCount
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
default:
currentState?.dataCount = nil
}
}
2023-03-17 20:55:47 +00:00
func startCountingData() {
2022-06-23 21:31:01 +00:00
guard dataCountTimer == nil else {
return
}
dataCountTimer = Timer.TimerPublisher(interval: dataCountInterval, runLoop: .main, mode: .common)
.autoconnect()
2023-09-08 14:20:01 +00:00
.sink { [weak self] in
self?.onDataCount($0)
2022-06-23 21:31:01 +00:00
}
}
func stopCountingData() {
2022-06-23 21:31:01 +00:00
dataCountTimer?.cancel()
dataCountTimer = nil
currentState?.dataCount = nil
}
2023-05-24 16:19:47 +00:00
}
2022-06-23 21:31:01 +00:00
// MARK: Configuration
private extension TunnelKitVPNManagerStrategy {
func vpnConfiguration(withParameters parameters: VPNConfigurationParameters) throws -> TunnelKitVPNConfiguration {
let profile = parameters.profile
do {
switch profile.currentVPNProtocol {
case .openVPN:
let settings: Profile.OpenVPNSettings
if profile.isProvider {
settings = try profile.providerOpenVPNSettings(withManager: parameters.providerManager)
} else {
guard let hostSettings = profile.hostOpenVPNSettings else {
fatalError("Profile currentVPNProtocol is OpenVPN, but host has no OpenVPN settings")
}
settings = hostSettings
}
2023-07-02 10:51:50 +00:00
return settings.tunnelKitConfiguration(appGroup, parameters: parameters)
case .wireGuard:
let settings: Profile.WireGuardSettings
if profile.isProvider {
settings = try profile.providerWireGuardSettings(withManager: parameters.providerManager)
} else {
guard let hostSettings = profile.hostWireGuardSettings else {
fatalError("Profile currentVPNProtocol is WireGuard, but host has no WireGuard settings")
}
settings = hostSettings
}
2023-07-02 10:51:50 +00:00
return settings.tunnelKitConfiguration(appGroup, parameters: parameters)
}
} catch {
pp_log.error("Unable to build TunnelKitVPNConfiguration: \(error)")
throw error
}
}
}
2023-05-24 16:19:47 +00:00
// MARK: Pulled
2023-03-17 20:55:47 +00:00
2023-05-24 16:19:47 +00:00
extension TunnelKitVPNManagerStrategy {
2022-06-23 21:31:01 +00:00
public func serverConfiguration(forProtocol vpnProtocol: VPNProtocolType) -> Any? {
switch vpnProtocol {
case .openVPN:
return defaults.openVPNServerConfiguration
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
default:
return nil
}
}
public func debugLogURL(forProtocol vpnProtocol: VPNProtocolType) -> URL? {
switch vpnProtocol {
case .openVPN:
return defaults.openVPNURLForDebugLog(appGroup: appGroup)
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
default:
return defaults.wireGuardURLForDebugLog(appGroup: appGroup)
}
}
}
2022-06-23 21:31:01 +00:00
// MARK: Callbacks
2022-06-23 21:31:01 +00:00
private extension TunnelKitVPNManagerStrategy {
func lastError(withBundleIdentifier bundleIdentifier: String?) -> Error? {
2022-06-23 21:31:01 +00:00
switch bundleIdentifier {
case tunnelBundleIdentifier(.openVPN):
return defaults.openVPNLastError
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
case tunnelBundleIdentifier(.wireGuard):
return defaults.wireGuardLastError
2023-03-17 20:55:47 +00:00
2022-06-23 21:31:01 +00:00
default:
return nil
}
}
var currentDataCount: DataCount? {
2022-06-23 21:31:01 +00:00
switch currentBundleIdentifier {
case tunnelBundleIdentifier(.openVPN):
return defaults.openVPNDataCount
default:
return nil
}
}
}