158 lines
5.8 KiB
Swift
158 lines
5.8 KiB
Swift
import Foundation
|
|
import NetworkExtension
|
|
|
|
@MainActor
|
|
final class VPNController: ObservableObject {
|
|
@Published private(set) var status: NEVPNStatus = .invalid
|
|
@Published private(set) var activeNodeSlug: String?
|
|
private var manager: NETunnelProviderManager?
|
|
private var observer: NSObjectProtocol?
|
|
|
|
init() {
|
|
observer = NotificationCenter.default.addObserver(
|
|
forName: .NEVPNStatusDidChange,
|
|
object: nil,
|
|
queue: .main
|
|
) { [weak self] note in
|
|
guard let connection = note.object as? NEVPNConnection else { return }
|
|
Task { @MainActor in self?.status = connection.status }
|
|
}
|
|
}
|
|
|
|
deinit {
|
|
if let observer { NotificationCenter.default.removeObserver(observer) }
|
|
}
|
|
|
|
func restore() async {
|
|
do {
|
|
manager = try await loadManager()
|
|
status = manager?.connection.status ?? .invalid
|
|
if isConnected,
|
|
let tunnelProtocol = manager?.protocolConfiguration as? NETunnelProviderProtocol,
|
|
let configuration = tunnelProtocol.providerConfiguration {
|
|
activeNodeSlug = configuration["nodeSlug"] as? String
|
|
}
|
|
} catch {
|
|
status = .invalid
|
|
activeNodeSlug = nil
|
|
}
|
|
}
|
|
|
|
func connect(configJSON: String, resolvedRemoteAddress: String, node: VPNNode, route: RouteMode) async throws {
|
|
guard route.id != "direct" else {
|
|
disconnect()
|
|
return
|
|
}
|
|
let selected = try await loadManager()
|
|
let tunnelProtocol = NETunnelProviderProtocol()
|
|
tunnelProtocol.providerBundleIdentifier = "cn.toplc.zonghengjia.PacketTunnel"
|
|
tunnelProtocol.serverAddress = node.name
|
|
tunnelProtocol.disconnectOnSleep = false
|
|
tunnelProtocol.includeAllNetworks = false
|
|
tunnelProtocol.providerConfiguration = [
|
|
"configJSON": configJSON,
|
|
"resolvedRemoteAddress": resolvedRemoteAddress,
|
|
"nodeSlug": node.slug,
|
|
"nodeName": node.name,
|
|
"routeMode": route.id,
|
|
]
|
|
|
|
selected.localizedDescription = "优创⁺纵横家"
|
|
selected.protocolConfiguration = tunnelProtocol
|
|
selected.isEnabled = true
|
|
try await save(selected)
|
|
try await reload(selected)
|
|
manager = selected
|
|
activeNodeSlug = node.slug
|
|
do {
|
|
try selected.connection.startVPNTunnel()
|
|
} catch {
|
|
activeNodeSlug = nil
|
|
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许优创⁺纵横家添加 VPN 配置。")
|
|
}
|
|
do {
|
|
try await waitUntilConnected(selected.connection)
|
|
} catch {
|
|
selected.connection.stopVPNTunnel()
|
|
activeNodeSlug = nil
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func disconnect() {
|
|
manager?.connection.stopVPNTunnel()
|
|
activeNodeSlug = nil
|
|
}
|
|
|
|
func disconnectAndWait(timeout: TimeInterval = 8) async {
|
|
disconnect()
|
|
let deadline = Date().addingTimeInterval(timeout)
|
|
while Date() < deadline {
|
|
let current = manager?.connection.status ?? .disconnected
|
|
status = current
|
|
if current == .disconnected || current == .invalid { return }
|
|
try? await Task.sleep(nanoseconds: 200_000_000)
|
|
}
|
|
}
|
|
|
|
var isConnected: Bool {
|
|
status == .connected || status == .connecting || status == .reasserting
|
|
}
|
|
|
|
private func waitUntilConnected(_ connection: NEVPNConnection, timeout: TimeInterval = 25) async throws {
|
|
let deadline = Date().addingTimeInterval(timeout)
|
|
var observedTransition = false
|
|
while Date() < deadline {
|
|
let current = connection.status
|
|
status = current
|
|
switch current {
|
|
case .connected:
|
|
return
|
|
case .connecting, .reasserting:
|
|
observedTransition = true
|
|
case .disconnected where observedTransition:
|
|
throw UCVLError.connection("Apple 系统 VPN 扩展启动后退出。")
|
|
case .invalid:
|
|
throw UCVLError.connection("Apple 系统 VPN 配置无效。")
|
|
default:
|
|
break
|
|
}
|
|
try await Task.sleep(nanoseconds: 250_000_000)
|
|
}
|
|
throw UCVLError.connection("Apple 系统 VPN 连接超时。")
|
|
}
|
|
|
|
private func loadManager() async throws -> NETunnelProviderManager {
|
|
let managers: [NETunnelProviderManager] = try await withCheckedThrowingContinuation { continuation in
|
|
NETunnelProviderManager.loadAllFromPreferences { managers, error in
|
|
if let error { continuation.resume(throwing: error) }
|
|
else { continuation.resume(returning: managers ?? []) }
|
|
}
|
|
}
|
|
if let existing = managers.first(where: {
|
|
($0.protocolConfiguration as? NETunnelProviderProtocol)?.providerBundleIdentifier == "cn.toplc.zonghengjia.PacketTunnel"
|
|
}) {
|
|
return existing
|
|
}
|
|
return NETunnelProviderManager()
|
|
}
|
|
|
|
private func save(_ manager: NETunnelProviderManager) async throws {
|
|
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
|
manager.saveToPreferences { error in
|
|
if let error { continuation.resume(throwing: error) }
|
|
else { continuation.resume(returning: ()) }
|
|
}
|
|
}
|
|
}
|
|
|
|
private func reload(_ manager: NETunnelProviderManager) async throws {
|
|
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
|
|
manager.loadFromPreferences { error in
|
|
if let error { continuation.resume(throwing: error) }
|
|
else { continuation.resume(returning: ()) }
|
|
}
|
|
}
|
|
}
|
|
}
|