ios vpn app
This commit is contained in:
1 parent
96f16399d7
commit
1b506b9ee7
48 files changed
+4934
-45
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import Foundation
|
||||
import Network
|
||||
|
||||
enum PingResult {
|
||||
case ok(Int)
|
||||
case timeout
|
||||
}
|
||||
|
||||
private final class PingOnce: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var done = false
|
||||
private let connection: NWConnection
|
||||
private let continuation: CheckedContinuation<PingResult, Never>
|
||||
|
||||
init(_ connection: NWConnection, _ continuation: CheckedContinuation<PingResult, Never>) {
|
||||
self.connection = connection
|
||||
self.continuation = continuation
|
||||
}
|
||||
|
||||
func finish(_ result: PingResult) {
|
||||
lock.lock()
|
||||
if done {
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
done = true
|
||||
lock.unlock()
|
||||
connection.cancel()
|
||||
continuation.resume(returning: result)
|
||||
}
|
||||
}
|
||||
|
||||
enum Ping {
|
||||
static let host = "ya.ru"
|
||||
static let port: UInt16 = 443
|
||||
static let timeoutSeconds = 5.0
|
||||
|
||||
static func run() async -> PingResult {
|
||||
await withCheckedContinuation { continuation in
|
||||
let connection = NWConnection(host: NWEndpoint.Host(host), port: NWEndpoint.Port(rawValue: port)!, using: .tls)
|
||||
let queue = DispatchQueue(label: "ping.connection")
|
||||
let start = DispatchTime.now()
|
||||
let once = PingOnce(connection, continuation)
|
||||
|
||||
connection.stateUpdateHandler = { state in
|
||||
switch state {
|
||||
case .ready:
|
||||
let elapsedNs = DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds
|
||||
once.finish(.ok(Int(Double(elapsedNs) / 1_000_000)))
|
||||
case .failed, .cancelled:
|
||||
once.finish(.timeout)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
queue.asyncAfter(deadline: .now() + timeoutSeconds) { once.finish(.timeout) }
|
||||
connection.start(queue: queue)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import SwiftUI
|
||||
import UIKit
|
||||
|
||||
extension UIColor {
|
||||
convenience init(hex: UInt32) {
|
||||
let a = CGFloat((hex >> 24) & 0xFF) / 255.0
|
||||
let r = CGFloat((hex >> 16) & 0xFF) / 255.0
|
||||
let g = CGFloat((hex >> 8) & 0xFF) / 255.0
|
||||
let b = CGFloat(hex & 0xFF) / 255.0
|
||||
self.init(red: r, green: g, blue: b, alpha: a)
|
||||
}
|
||||
|
||||
static func dynamic(light: UInt32, dark: UInt32) -> UIColor {
|
||||
UIColor { traits in
|
||||
traits.userInterfaceStyle == .dark ? UIColor(hex: dark) : UIColor(hex: light)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Palette {
|
||||
static let accent = Color(UIColor.dynamic(light: 0xFF7B1C2A, dark: 0xFFD04C5E))
|
||||
static let accentSoft = Color(UIColor.dynamic(light: 0x1F7B1C2A, dark: 0x2ED04C5E))
|
||||
static let warn = Color(UIColor.dynamic(light: 0xFFB07A1D, dark: 0xFFE5B260))
|
||||
static let error = Color(UIColor.dynamic(light: 0xFFD32F2F, dark: 0xFFEF7A52))
|
||||
static let ink = Color(UIColor.dynamic(light: 0xFF0D0D0C, dark: 0xFFECECE8))
|
||||
static let ink2 = Color(UIColor.dynamic(light: 0xFF4A4946, dark: 0xFFA8A8A2))
|
||||
static let ink3 = Color(UIColor.dynamic(light: 0xFF8A8782, dark: 0xFF6A6A65))
|
||||
static let hair = Color(UIColor.dynamic(light: 0x140D0D0C, dark: 0x14ECECE8))
|
||||
static let hairStrong = Color(UIColor.dynamic(light: 0x290D0D0C, dark: 0x2EECECE8))
|
||||
static let panel = Color(UIColor.dynamic(light: 0xFFFFFFFF, dark: 0xFF131517))
|
||||
static let panel2 = Color(UIColor.dynamic(light: 0xFFF9F8F4, dark: 0xFF181B1E))
|
||||
static let surface = Color(UIColor.dynamic(light: 0xFFFFFFFF, dark: 0xFF0A0B0C))
|
||||
}
|
||||
|
||||
enum Mono {
|
||||
static func label(_ size: CGFloat) -> Font {
|
||||
.system(size: size, weight: .regular, design: .monospaced)
|
||||
}
|
||||
static func bold(_ size: CGFloat) -> Font {
|
||||
.system(size: size, weight: .bold, design: .monospaced)
|
||||
}
|
||||
}
|
||||
|
||||
struct StatCardBackground: ViewModifier {
|
||||
var radius: CGFloat = 18
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: radius, style: .continuous)
|
||||
.fill(Palette.panel2)
|
||||
)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: radius, style: .continuous)
|
||||
.stroke(Palette.hair, lineWidth: 1)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension View {
|
||||
func statCard(radius: CGFloat = 18) -> some View {
|
||||
modifier(StatCardBackground(radius: radius))
|
||||
}
|
||||
}
|
||||
|
||||
enum ThemeMode: String, CaseIterable, Identifiable {
|
||||
case system = "SYSTEM"
|
||||
case light = "LIGHT"
|
||||
case dark = "DARK"
|
||||
|
||||
var id: String { rawValue }
|
||||
|
||||
var label: String {
|
||||
switch self {
|
||||
case .system: return NSLocalizedString("theme_system", comment: "")
|
||||
case .light: return NSLocalizedString("theme_light", comment: "")
|
||||
case .dark: return NSLocalizedString("theme_dark", comment: "")
|
||||
}
|
||||
}
|
||||
|
||||
var colorScheme: ColorScheme? {
|
||||
switch self {
|
||||
case .system: return nil
|
||||
case .light: return .light
|
||||
case .dark: return .dark
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
import Combine
|
||||
|
||||
enum ConnectionPhase {
|
||||
case disconnected
|
||||
case connecting
|
||||
case connected
|
||||
case failed
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class VPNController: ObservableObject {
|
||||
@Published var phase: ConnectionPhase = .disconnected
|
||||
@Published var statusDetail: String = ""
|
||||
@Published var uptimeText: String = "00:00:00"
|
||||
@Published var logs: [String] = []
|
||||
@Published var lastError: String?
|
||||
@Published var captchaURL: String?
|
||||
|
||||
var appState: AppState?
|
||||
|
||||
private var manager: NETunnelProviderManager?
|
||||
private var statusObserver: NSObjectProtocol?
|
||||
private var pollTimer: Timer?
|
||||
private var connectedSince: Date?
|
||||
private var relayUp = false
|
||||
private var lastRevision = -1
|
||||
private var lastStatus = ""
|
||||
|
||||
init() {
|
||||
statusObserver = NotificationCenter.default.addObserver(
|
||||
forName: .NEVPNStatusDidChange, object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
Task { @MainActor in self?.refreshStatus() }
|
||||
}
|
||||
Task { await loadManager() }
|
||||
startPolling()
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let observer = statusObserver {
|
||||
NotificationCenter.default.removeObserver(observer)
|
||||
}
|
||||
pollTimer?.invalidate()
|
||||
}
|
||||
|
||||
func connect() async {
|
||||
guard let appState else { return }
|
||||
guard let config = appState.tunnelConfig() else {
|
||||
Log.app.error("connect aborted: no active call")
|
||||
return
|
||||
}
|
||||
|
||||
Log.app.log("connect requested: platform=\(config.platform.rawValue, privacy: .public) room=\(config.roomId, privacy: .public)")
|
||||
lastError = nil
|
||||
captchaURL = nil
|
||||
relayUp = false
|
||||
connectedSince = nil
|
||||
logs = []
|
||||
lastRevision = -1
|
||||
lastStatus = ""
|
||||
|
||||
let mgr = manager ?? NETunnelProviderManager()
|
||||
let proto = NETunnelProviderProtocol()
|
||||
proto.providerBundleIdentifier = AppIdentifiers.tunnelBundleId
|
||||
proto.serverAddress = AppIdentifiers.vpnLocalizedDescription
|
||||
proto.providerConfiguration = config.dictionary
|
||||
mgr.protocolConfiguration = proto
|
||||
mgr.localizedDescription = AppIdentifiers.vpnLocalizedDescription
|
||||
mgr.isEnabled = true
|
||||
|
||||
do {
|
||||
try await mgr.saveToPreferences()
|
||||
try await mgr.loadFromPreferences()
|
||||
manager = mgr
|
||||
try mgr.connection.startVPNTunnel()
|
||||
} catch {
|
||||
phase = .failed
|
||||
lastError = error.localizedDescription
|
||||
Log.app.error("start error: \(error.localizedDescription, privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
func disconnect() {
|
||||
Log.app.log("disconnect requested")
|
||||
manager?.connection.stopVPNTunnel()
|
||||
}
|
||||
|
||||
func startPolling() {
|
||||
pollTimer?.invalidate()
|
||||
pollTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in self?.tick() }
|
||||
}
|
||||
}
|
||||
|
||||
func stopPolling() {
|
||||
pollTimer?.invalidate()
|
||||
pollTimer = nil
|
||||
}
|
||||
|
||||
private func loadManager() async {
|
||||
let managers = (try? await NETunnelProviderManager.loadAllFromPreferences()) ?? []
|
||||
manager = managers.first ?? NETunnelProviderManager()
|
||||
refreshStatus()
|
||||
if phase == .disconnected || phase == .failed {
|
||||
captchaURL = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshStatus() {
|
||||
guard let connection = manager?.connection else {
|
||||
phase = .disconnected
|
||||
return
|
||||
}
|
||||
switch connection.status {
|
||||
case .connected:
|
||||
phase = relayUp ? .connected : .connecting
|
||||
case .connecting, .reasserting:
|
||||
phase = .connecting
|
||||
case .disconnecting:
|
||||
phase = .connecting
|
||||
case .disconnected, .invalid:
|
||||
relayUp = false
|
||||
connectedSince = nil
|
||||
uptimeText = "00:00:00"
|
||||
phase = lastStatus.hasPrefix(GoStatus.error) ? .failed : .disconnected
|
||||
@unknown default:
|
||||
phase = .disconnected
|
||||
}
|
||||
}
|
||||
|
||||
private func tick() {
|
||||
if phase == .connected, let since = connectedSince {
|
||||
uptimeText = formatUptime(Date().timeIntervalSince(since))
|
||||
}
|
||||
pollExtension()
|
||||
}
|
||||
|
||||
private func pollExtension() {
|
||||
guard let session = manager?.connection as? NETunnelProviderSession else { return }
|
||||
switch session.status {
|
||||
case .connected, .connecting, .reasserting, .disconnecting: break
|
||||
default: return
|
||||
}
|
||||
try? session.sendProviderMessage(Data()) { [weak self] data in
|
||||
guard let data, let snapshot = try? JSONDecoder().decode(LogSnapshot.self, from: data) else { return }
|
||||
Task { @MainActor in self?.applySnapshot(snapshot) }
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(_ snapshot: LogSnapshot) {
|
||||
if snapshot.revision != lastRevision {
|
||||
let previousCount = logs.count
|
||||
let start = snapshot.lines.count >= previousCount ? previousCount : 0
|
||||
if snapshot.lines.count > start {
|
||||
for line in snapshot.lines[start..<snapshot.lines.count] { print("[GO] \(line)") }
|
||||
}
|
||||
logs = snapshot.lines
|
||||
lastRevision = snapshot.revision
|
||||
}
|
||||
if snapshot.status != lastStatus {
|
||||
lastStatus = snapshot.status
|
||||
Log.app.log("go status -> \(snapshot.status, privacy: .public)")
|
||||
}
|
||||
applyGoStatus(snapshot.status)
|
||||
}
|
||||
|
||||
private func applyGoStatus(_ status: String) {
|
||||
if status.hasPrefix(GoStatus.error) {
|
||||
let msg = String(status.dropFirst(GoStatus.error.count).drop(while: { $0 == ":" }))
|
||||
statusDetail = msg.isEmpty ? NSLocalizedString("status_error", comment: "") : msg
|
||||
lastError = statusDetail
|
||||
captchaURL = nil
|
||||
relayUp = false
|
||||
return
|
||||
}
|
||||
if status.hasPrefix("CAPTCHA:") {
|
||||
if phase == .connecting || phase == .connected {
|
||||
captchaURL = String(status.dropFirst("CAPTCHA:".count))
|
||||
statusDetail = NSLocalizedString("status_solve_captcha", comment: "")
|
||||
} else {
|
||||
captchaURL = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
if captchaURL != nil, status != "CAPTCHA" {
|
||||
captchaURL = nil
|
||||
}
|
||||
switch status {
|
||||
case GoStatus.tunnelConnected:
|
||||
if !relayUp {
|
||||
relayUp = true
|
||||
connectedSince = Date()
|
||||
}
|
||||
refreshStatus()
|
||||
statusDetail = NSLocalizedString("status_tunnel_active", comment: "")
|
||||
case GoStatus.connecting, GoStatus.reconnecting, GoStatus.tunnelLost:
|
||||
relayUp = false
|
||||
refreshStatus()
|
||||
switch status {
|
||||
case GoStatus.connecting: statusDetail = NSLocalizedString("status_connecting_ellipsis", comment: "")
|
||||
case GoStatus.reconnecting: statusDetail = NSLocalizedString("status_reconnecting", comment: "")
|
||||
default: statusDetail = NSLocalizedString("status_tunnel_lost", comment: "")
|
||||
}
|
||||
case GoStatus.ready:
|
||||
statusDetail = NSLocalizedString("status_ready", comment: "")
|
||||
default:
|
||||
statusDetail = phase == .connected ? NSLocalizedString("status_tunnel_active", comment: "") : ""
|
||||
}
|
||||
}
|
||||
|
||||
private func formatUptime(_ interval: TimeInterval) -> String {
|
||||
let total = Int(interval)
|
||||
return String(format: "%02d:%02d:%02d", total / 3600, (total % 3600) / 60, total % 60)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user