iOS 1.0.3 source candidate only; no Apple build or installation acceptance

This commit is contained in:
2026-10-27 02:46:08 +00:00
parent 1cf54a46e4
commit 295799b1ab
29 changed files with 1499 additions and 213 deletions
+83 -31
View File
@@ -65,9 +65,11 @@ final class AppState: ObservableObject {
busy = true
defer { busy = false }
if vpn.isConnected {
await vpn.disconnectAndWait()
currentNode = nil
message = "正在断开,系统将自动恢复原网络"
do {
try await vpn.disconnectAndWait()
currentNode = nil
message = "已断开,系统已撤销本应用的 VPN 连接"
} catch { errorMessage = friendly(error) }
return
}
guard let profile,
@@ -77,7 +79,8 @@ final class AppState: ObservableObject {
return
}
if route.id == "direct" {
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch { errorMessage = friendly(error); return }
currentNode = nil
message = "当前为本地直连,不经过 VPN 节点"
return
@@ -91,44 +94,29 @@ final class AppState: ObservableObject {
var excludedNodes: [String] = []
var lastError: Error = UCVLError.connection("没有可用节点。")
let maximumAttempts = max(1, min(profile.nodes.count, 3))
// One explicit connect owns this state across all assigned nodes.
// No timers or system restore path may promote a public connection.
var transport = ProxyTransportSession()
for attempt in 1...maximumAttempts {
var attemptedNode: VPNNode?
do {
let response = try await api.config(token: token, route: route.id, excluding: excludedNodes)
attemptedNode = response.node
let configJSON = try response.configJSONString()
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
}
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
let pinnedGatewayIPv4 = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
let remoteAddress: String
if let pinnedGatewayIPv4, NetworkAddress.isPublicIPv4(pinnedGatewayIPv4) {
remoteAddress = pinnedGatewayIPv4
} else {
let hostToResolve = (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
remoteAddress = try await api.resolvePublicIPv4(host: hostToResolve)
}
currentNode = response.node
message = "正在连接 \(response.node.displayName)(第 \(attempt) 次验证)…"
try await vpn.connect(
configJSON: configJSON,
resolvedRemoteAddress: remoteAddress,
node: response.node,
route: route
)
try await api.verifyProxyEgress()
guard vpn.status == .connected else {
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在切换备用节点。")
}
message = "已连接 \(response.node.displayName),出口验证通过"
try await connectAssigned(response, route: route, transport: &transport)
return
} catch {
lastError = error
let decision = ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: attemptedNode != nil)
currentNode = nil
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch {
errorMessage = friendly(error)
message = "系统尚未完成断开,已停止切换线路"
return
}
if decision == .revokeAuthorization {
logoutLocal()
errorMessage = friendly(error)
@@ -149,11 +137,74 @@ final class AppState: ObservableObject {
message = "所有可用节点均未通过验证,已恢复本地网络"
}
private func connectAssigned(
_ response: ClientConfigResponse, route: RouteMode, transport: inout ProxyTransportSession
) async throws {
let configJSON = try response.configJSONString()
if !transport.domainOnly,
let endpoint = ProxyTransportPolicy.authorizedInternalEndpoint(response: response) {
let reachable = await InternalIPProbe.isReachable(endpoint.address)
try Task.checkCancellation()
if reachable {
message = "正在通过内部 IP 连接 \(response.node.displayName)…"
do {
try await vpn.connect(
configJSON: configJSON, resolvedRemoteAddress: endpoint.address,
node: response.node, route: route, internalEndpoint: endpoint,
configContract: response.configContract, connectionScope: response.connectionScope
)
try await verifyActiveEgress()
message = "已连接 \(response.node.displayName) · 内部 IP,出口验证通过"
return
} catch {
guard ConnectionAttemptPolicy.decide(error: error, hasAssignedNode: true) == .retryNode else {
throw error
}
try await vpn.disconnectAndWait()
}
}
}
transport.commitPublicFallback()
try Task.checkCancellation()
// Resolve only when public transport is actually needed. DNS failure
// must not prevent an otherwise usable authorized internal endpoint.
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: configJSON) else {
throw UCVLError.invalidConfiguration("后台线路配置缺少节点域名。")
}
let gatewayHost = response.gateway?.host.trimmingCharacters(in: .whitespacesAndNewlines)
let pinnedAddress = response.gateway?.ipv4?.trimmingCharacters(in: .whitespacesAndNewlines)
let publicAddress: String
if let pinnedAddress, NetworkAddress.isPublicIPv4(pinnedAddress) {
publicAddress = pinnedAddress
} else {
publicAddress = try await api.resolvePublicIPv4(
host: (gatewayHost?.isEmpty == false ? gatewayHost : nil) ?? remoteHost
)
}
message = "正在通过域名入口连接 \(response.node.displayName)…"
try await vpn.connect(
configJSON: configJSON, resolvedRemoteAddress: publicAddress, node: response.node, route: route
)
try await verifyActiveEgress()
message = "已连接 \(response.node.displayName) · 域名入口,本次连接保持不切换"
}
private func verifyActiveEgress() async throws {
try Task.checkCancellation()
try await api.verifyProxyEgress()
try Task.checkCancellation()
guard vpn.status == .connected else {
throw UCVLError.connection("出口验证返回时 VPN 已断开,正在尝试备用入口。")
}
}
func logout() async {
guard !busy else { return }
busy = true
defer { busy = false }
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch { errorMessage = friendly(error); return }
if let token = SecureStore.token() {
await api.logout(token: token)
}
@@ -182,7 +233,8 @@ final class AppState: ObservableObject {
apply(try await api.profile(token: token))
message = "账号和线路已同步"
} catch UCVLError.api(let status, let message) where status == 401 || status == 403 {
await vpn.disconnectAndWait()
do { try await vpn.disconnectAndWait() }
catch { errorMessage = friendly(error) }
SecureStore.clearToken()
profile = nil
errorMessage = message
+261 -94
View File
@@ -5,7 +5,8 @@ struct ContentView: View {
var body: some View {
ZStack {
UCVLColors.background.ignoresSafeArea()
LandscapeArtwork()
.ignoresSafeArea()
if let profile = state.profile {
DashboardView(profile: profile)
} else {
@@ -13,6 +14,8 @@ struct ContentView: View {
}
}
.tint(UCVLColors.royal)
.foregroundColor(UCVLColors.navy)
.preferredColorScheme(.light)
.alert("提示", isPresented: Binding(
get: { !state.errorMessage.isEmpty },
set: { if !$0 { state.errorMessage = "" } }
@@ -24,23 +27,81 @@ struct ContentView: View {
}
}
// Both placements draw the same original asset with a native aspect-fill crop.
// Artwork remains separate from the real controls and never changes VPN state.
private struct LandscapeArtwork: View {
var body: some View {
GeometryReader { geometry in
Image("MountainLandscape")
.resizable()
.scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
.background(UCVLColors.surface)
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
private struct ScenicPage<Content: View>: View {
let maxWidth: CGFloat
let content: Content
init(maxWidth: CGFloat, @ViewBuilder content: () -> Content) {
self.maxWidth = maxWidth
self.content = content()
}
var body: some View {
ScrollView {
content
.frame(maxWidth: maxWidth)
.padding(.horizontal, 18)
.padding(.vertical, 24)
.frame(maxWidth: .infinity)
}
}
}
private struct BrandHeader: View {
var compact = false
var body: some View {
VStack(spacing: compact ? 8 : 16) {
VStack(spacing: compact ? 8 : 12) {
Image("UCVLLogo")
.resizable()
.scaledToFit()
.frame(width: compact ? 84 : 132, height: compact ? 84 : 132)
.accessibilityLabel("优创未来 Logo")
Text("优创⁺纵横家")
.frame(width: compact ? 60 : 88, height: compact ? 60 : 88)
.accessibilityHidden(true)
Text("纵横家")
.font(compact ? .title2.bold() : .largeTitle.bold())
.foregroundStyle(.white)
Text("优创未来安全网络")
.font(.subheadline)
.foregroundStyle(UCVLColors.sky)
.foregroundStyle(UCVLColors.navy)
.fixedSize(horizontal: false, vertical: true)
Text(AppVersion.label)
.font(.caption)
.foregroundStyle(UCVLColors.muted)
.fixedSize(horizontal: false, vertical: true)
}
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.padding(.horizontal, 16)
.padding(.vertical, compact ? 16 : 24)
.background {
LandscapeArtwork()
.overlay(Color.white.opacity(0.18))
.mask(LinearGradient(colors: [.black, .black, .clear], startPoint: .top, endPoint: .bottom))
}
}
}
private enum AppVersion {
static var label: String {
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
guard let version, !version.isEmpty else { return "版本信息不可用" }
guard let build, !build.isEmpty else { return "版本 \(version)" }
return "版本 \(version) (\(build))"
}
}
@@ -48,36 +109,39 @@ private struct LoginView: View {
@EnvironmentObject private var state: AppState
@State private var identifier = SecureStore.lastLogin
@State private var password = ""
@FocusState private var focusedField: Field?
private enum Field: Hashable { case identifier, password }
var body: some View {
ScrollView {
VStack(spacing: 28) {
ScenicPage(maxWidth: 540) {
VStack(spacing: 20) {
BrandHeader()
.padding(.top, 34)
VStack(alignment: .leading, spacing: 18) {
Text("公司统一账号登录")
.font(.title2.bold())
.foregroundStyle(UCVLColors.navy)
TextField("用户名或邮箱", text: $identifier)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.disableAutocorrection(true)
.keyboardType(.emailAddress)
.textContentType(.username)
.submitLabel(.next)
.focused($focusedField, equals: .identifier)
.ucvlField()
.onSubmit { focusedField = .password }
SecureField("密码", text: $password)
.textContentType(.password)
.submitLabel(.go)
.focused($focusedField, equals: .password)
.ucvlField()
.onSubmit { Task { await state.login(identifier: identifier, password: password) } }
Button {
Task {
await state.login(identifier: identifier, password: password)
if state.profile != nil { password = "" }
}
} label: {
.onSubmit { signIn() }
Button(action: signIn) {
HStack {
if state.busy { ProgressView().tint(.white) }
Text(state.busy ? "正在登录…" : "安全登录").fontWeight(.semibold)
}
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding(.vertical, 14)
}
@@ -85,65 +149,113 @@ private struct LoginView: View {
.disabled(state.busy)
Text("账号停用后,设备授权与线路将自动失效。")
.font(.footnote)
.foregroundStyle(.secondary)
HStack {
Text("还没有账号?")
.font(.footnote)
.foregroundStyle(.secondary)
Link("注册新用户", destination: URL(string: "https://vpn.toplc.cn/register/")!)
.font(.footnote.weight(.semibold))
}
.foregroundStyle(UCVLColors.muted)
.fixedSize(horizontal: false, vertical: true)
RegistrationPrompt()
}
.padding(24)
.background(.white, in: RoundedRectangle(cornerRadius: 24, style: .continuous))
.shadow(color: .black.opacity(0.14), radius: 24, y: 12)
.frame(maxWidth: 540)
Text("vpn.toplc.cn · © 2026 UCVL")
.font(.footnote)
.foregroundStyle(UCVLColors.sky)
.padding(.bottom, 30)
.padding(20)
.scenicCard(cornerRadius: 24)
}
.padding(.horizontal, 20)
}
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("完成") { focusedField = nil }
}
}
}
private func signIn() {
focusedField = nil
Task {
await state.login(identifier: identifier, password: password)
if state.profile != nil { password = "" }
}
}
}
private struct RegistrationPrompt: View {
private var message: AttributedString {
var prompt = AttributedString("还没有账号?")
prompt.foregroundColor = UCVLColors.muted
var link = AttributedString("注册新用户")
link.link = URL(string: "https://vpn.example.invalid/register/")
link.foregroundColor = UCVLColors.royal
link.font = .footnote.weight(.semibold)
prompt.append(link)
return prompt
}
var body: some View {
// A single inline run shares a baseline and wraps naturally at large sizes.
Text(message)
.font(.footnote)
.lineSpacing(4)
.fixedSize(horizontal: false, vertical: true)
}
}
private struct DashboardHeader: View {
@Environment(\.horizontalSizeClass) private var sizeClass
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
let profile: ClientProfile
private var account: some View {
VStack(alignment: .leading, spacing: 6) {
Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)")
.font(.headline)
Text(profile.email)
.font(.subheadline)
.foregroundStyle(UCVLColors.muted)
Text(profile.identityType == "employee" ? "内部员工" : "外部联系人")
.font(.caption)
.foregroundStyle(UCVLColors.muted)
}
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
var body: some View {
Group {
if sizeClass == .regular && !dynamicTypeSize.isAccessibilitySize {
HStack(spacing: 24) {
BrandHeader(compact: true)
account
}
} else {
VStack(spacing: 16) {
BrandHeader(compact: true)
account
}
}
}
.padding(18)
.scenicCard()
}
}
private struct DashboardView: View {
@EnvironmentObject private var state: AppState
@Environment(\.horizontalSizeClass) private var sizeClass
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
let profile: ClientProfile
var body: some View {
ScrollView {
ScenicPage(maxWidth: 760) {
VStack(spacing: 18) {
HStack(spacing: 16) {
BrandHeader(compact: true)
Spacer()
VStack(alignment: .trailing, spacing: 4) {
Text("你好,\(profile.displayName.isEmpty ? profile.username : profile.displayName)")
.font(.headline)
.foregroundStyle(.white)
Text("\(profile.email) · \(profile.identityType == "employee" ? "内部员工" : "外部联系人")")
.font(.caption)
.foregroundStyle(UCVLColors.sky)
}
}
.padding(.vertical, 8)
DashboardHeader(profile: profile)
StatusCard()
UCVLCard(title: "工作节点与代理模式", systemImage: "point.3.connected.trianglepath.dotted") {
VStack(spacing: 14) {
HStack {
Text("当前工作节点")
Spacer()
AdaptiveDetailRow(title: "当前工作节点") {
Text(state.currentNode?.displayName ?? "由 vpn-ai 自动选择")
.foregroundStyle(state.currentNode == nil ? .secondary : UCVLColors.royal)
.multilineTextAlignment(.trailing)
.foregroundStyle(state.currentNode == nil ? UCVLColors.muted : UCVLColors.royal)
.fixedSize(horizontal: false, vertical: true)
}
Divider()
HStack {
Text("代理模式")
Spacer()
AdaptiveDetailRow(title: "代理模式") {
Picker("代理模式", selection: $state.selectedRouteID) {
ForEach(profile.routeModes) { route in Text(route.name).tag(route.id) }
}
@@ -158,6 +270,7 @@ private struct DashboardView: View {
Image(systemName: state.vpn.isConnected ? "stop.fill" : "bolt.shield.fill")
Text(state.vpn.isConnected ? "断开连接" : "连接")
}
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
}
@@ -169,25 +282,66 @@ private struct DashboardView: View {
UsageCard(subscription: profile.subscription)
HStack(spacing: 12) {
Button { Task { await state.refresh() } } label: {
Label("刷新", systemImage: "arrow.clockwise")
.frame(maxWidth: .infinity)
Group {
if sizeClass == .regular && !dynamicTypeSize.isAccessibilitySize {
HStack(spacing: 12) { accountActions }
} else {
VStack(spacing: 12) { accountActions }
}
.buttonStyle(.bordered)
.disabled(state.busy)
Button(role: .destructive) { Task { await state.logout() } } label: {
Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right")
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.disabled(state.busy)
}
.padding(16)
.scenicCard()
}
}
}
@ViewBuilder private var accountActions: some View {
Button { Task { await state.refresh() } } label: {
Label("刷新", systemImage: "arrow.clockwise")
.frame(maxWidth: .infinity)
.padding(.vertical, 6)
}
.buttonStyle(.bordered)
.disabled(state.busy)
Button(role: .destructive) { Task { await state.logout() } } label: {
Label("退出账号", systemImage: "rectangle.portrait.and.arrow.right")
.frame(maxWidth: .infinity)
.padding(.vertical, 6)
}
.buttonStyle(.bordered)
.disabled(state.busy)
}
}
private struct AdaptiveDetailRow<Content: View>: View {
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
let title: String
let content: Content
init(title: String, @ViewBuilder content: () -> Content) {
self.title = title
self.content = content()
}
var body: some View {
Group {
if dynamicTypeSize.isAccessibilitySize {
VStack(alignment: .leading, spacing: 8) {
Text(title)
content
.frame(maxWidth: .infinity, alignment: .leading)
}
} else {
HStack(alignment: .firstTextBaseline, spacing: 12) {
Text(title)
.fixedSize(horizontal: true, vertical: false)
content
.multilineTextAlignment(.trailing)
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
.frame(maxWidth: 760)
.padding(.horizontal, 18)
.padding(.vertical, 18)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
@@ -196,17 +350,19 @@ private struct StatusCard: View {
var body: some View {
UCVLCard(title: "连接状态", systemImage: "network.badge.shield.half.filled") {
HStack(spacing: 14) {
HStack(alignment: .top, spacing: 14) {
Circle()
.fill(state.statusIsActive ? Color.green : Color.gray)
.fill(state.statusIsActive ? UCVLColors.success : UCVLColors.muted)
.frame(width: 13, height: 13)
.padding(.top, 6)
VStack(alignment: .leading, spacing: 4) {
Text(state.statusTitle).font(.title3.bold())
Text(state.message.isEmpty ? "点击连接,vpn-ai 将自动选择并验证工作节点" : state.message)
.font(.subheadline)
.foregroundStyle(.secondary)
.foregroundStyle(UCVLColors.muted)
}
Spacer()
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
@@ -223,17 +379,21 @@ private struct UsageCard: View {
var body: some View {
UCVLCard(title: "本期流量", systemImage: "chart.bar.fill") {
VStack(alignment: .leading, spacing: 12) {
HStack {
AdaptiveDetailRow(title: "已用流量") {
Text(format(subscription.usedBytes))
Spacer()
.fixedSize(horizontal: false, vertical: true)
}
AdaptiveDetailRow(title: "套餐流量") {
Text(subscription.trafficLimitBytes > 0 ? format(subscription.trafficLimitBytes) : "不限流量")
.foregroundStyle(UCVLColors.royal)
.fixedSize(horizontal: false, vertical: true)
}
ProgressView(value: fraction)
.tint(UCVLColors.royal)
Text("套餐:\(subscription.plan) · 设备上限 \(subscription.deviceLimit) 台\(expiryText)")
.font(.footnote)
.foregroundStyle(.secondary)
.foregroundStyle(UCVLColors.muted)
.fixedSize(horizontal: false, vertical: true)
}
}
}
@@ -264,31 +424,38 @@ private struct UCVLCard<Content: View>: View {
Label(title, systemImage: systemImage)
.font(.headline)
.foregroundStyle(UCVLColors.navy)
.fixedSize(horizontal: false, vertical: true)
content
}
.padding(20)
.background(.white, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.shadow(color: .black.opacity(0.08), radius: 14, y: 7)
.frame(maxWidth: .infinity, alignment: .leading)
.scenicCard()
}
}
private enum UCVLColors {
static let navy = Color(red: 0.02, green: 0.10, blue: 0.26)
static let royal = Color(red: 0.02, green: 0.39, blue: 0.86)
static let sky = Color(red: 0.17, green: 0.73, blue: 0.98)
static let background = LinearGradient(
colors: [navy, Color(red: 0.03, green: 0.25, blue: 0.48)],
startPoint: .topLeading,
endPoint: .bottomTrailing
)
static let navy = Color(red: 10 / 255, green: 34 / 255, blue: 91 / 255)
static let royal = Color(red: 0, green: 80 / 255, blue: 221 / 255)
static let muted = Color(red: 52 / 255, green: 79 / 255, blue: 116 / 255)
static let surface = Color(red: 237 / 255, green: 248 / 255, blue: 1)
static let success = Color(red: 0, green: 113 / 255, blue: 110 / 255)
}
private extension View {
func scenicCard(cornerRadius: CGFloat = 22) -> some View {
self
.background(Color.white.opacity(0.50), in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous).stroke(Color.white.opacity(0.55)))
.shadow(color: UCVLColors.navy.opacity(0.08), radius: 14, y: 7)
}
func ucvlField() -> some View {
self
.foregroundColor(UCVLColors.navy)
.padding(.horizontal, 14)
.frame(height: 52)
.background(Color.gray.opacity(0.08), in: RoundedRectangle(cornerRadius: 13))
.overlay(RoundedRectangle(cornerRadius: 13).stroke(Color.gray.opacity(0.2)))
.padding(.vertical, 14)
.frame(minHeight: 52)
.background(Color.white.opacity(0.72), in: RoundedRectangle(cornerRadius: 13))
.overlay(RoundedRectangle(cornerRadius: 13).stroke(UCVLColors.navy.opacity(0.16)))
}
}
+94
View File
@@ -0,0 +1,94 @@
import Darwin
import Foundation
enum InternalIPProbe {
static func isReachable(_ address: String) async -> Bool {
guard NetworkAddress.isAuthorizedInternalIPv4(address), !Task.isCancelled else { return false }
let attempt = PingAttempt()
return await withTaskCancellationHandler(operation: {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .utility).async {
continuation.resume(returning: attempt.run(address))
}
}
}, onCancel: { attempt.cancel() })
}
}
private final class PingAttempt: @unchecked Sendable {
private let lock = NSLock()
private var cancelled = false
func cancel() {
lock.lock()
cancelled = true
lock.unlock()
}
private var isCancelled: Bool {
lock.lock()
defer { lock.unlock() }
return cancelled
}
func run(_ address: String) -> Bool {
let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000
guard !isCancelled else { return false }
// Darwin datagram ICMP is unprivileged. Never run a shell, query a VPN
// service or replace ICMP with a TCP/HTTP test.
let descriptor = Darwin.socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
guard descriptor >= 0 else { return false }
defer { Darwin.close(descriptor) }
let flags = fcntl(descriptor, F_GETFL, 0)
guard flags >= 0, fcntl(descriptor, F_SETFL, flags | O_NONBLOCK) == 0 else { return false }
var destination = sockaddr_in()
destination.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
destination.sin_family = sa_family_t(AF_INET)
guard address.withCString({ inet_pton(AF_INET, $0, &destination.sin_addr) }) == 1 else { return false }
let connected = withUnsafePointer(to: &destination) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
}
}
guard connected == 0, !isCancelled else { return false }
let payload = Array(UUID().uuidString.utf8)
let packet = ICMPEchoPacket.request(identifier: UInt16.random(in: 1...UInt16.max), payload: payload)
let sent = packet.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) }
guard sent == packet.count else { return false }
var descriptorState = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0)
while !isCancelled {
let now = DispatchTime.now().uptimeNanoseconds
guard now < deadline else { return false }
let waitMS = Int32(min(50, max(1, (deadline - now) / 1_000_000)))
let ready = Darwin.poll(&descriptorState, 1, waitMS)
if ready < 0 {
if errno == EINTR { continue }
return false
}
guard ready > 0 else { continue }
guard descriptorState.revents & Int16(POLLIN) != 0 else { return false }
var buffer = [UInt8](repeating: 0, count: 4096)
var sender = sockaddr_in()
var senderSize = socklen_t(MemoryLayout<sockaddr_in>.size)
let received = withUnsafeMutablePointer(to: &sender) { senderPointer in
senderPointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in
buffer.withUnsafeMutableBytes {
Darwin.recvfrom(descriptor, $0.baseAddress, $0.count, 0, socketPointer, &senderSize)
}
}
}
guard received > 0 else {
if errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR { continue }
return false
}
if sender.sin_family == sa_family_t(AF_INET),
sender.sin_addr.s_addr == destination.sin_addr.s_addr,
ICMPEchoPacket.isReply(Array(buffer.prefix(received)), payload: payload) {
return !isCancelled && DispatchTime.now().uptimeNanoseconds < deadline
}
}
return false
}
}
+5 -5
View File
@@ -4,7 +4,7 @@ import UIKit
actor PlatformAPI {
static let shared = PlatformAPI()
private let baseURL = URL(string: "https://vpn.toplc.cn/")!
private let baseURL = URL(string: "https://vpn.example.invalid/")!
private let session: URLSession
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
@@ -16,7 +16,7 @@ actor PlatformAPI {
configuration.waitsForConnectivity = true
configuration.httpAdditionalHeaders = [
"Accept": "application/json",
"User-Agent": "UCVL-Zonghengjia/1.0.2 iOS",
"User-Agent": "UCVL-Zonghengjia/1.0.3 iOS",
]
session = URLSession(configuration: configuration)
}
@@ -27,7 +27,7 @@ actor PlatformAPI {
"password": password,
"device_id": SecureStore.deviceID(),
"device_name": await MainActor.run { UIDevice.current.name },
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.2",
"app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.3",
"platform": "ios",
]
return try await send(
@@ -98,7 +98,7 @@ actor PlatformAPI {
if NetworkAddress.isPublicIPv4(host) { return host }
// 001/002 是后台节点名称。NPM TCP Stream 依靠 11081/11082 等端口
// 分流,不要求每个节点子域名都单独发布 A 记录;解析不到时使用统一入口。
let candidateHosts = host == "vpn.toplc.cn" ? [host] : [host, "vpn.toplc.cn"]
let candidateHosts = host == "vpn.example.invalid" ? [host] : [host, "vpn.example.invalid"]
let resolvers = [
"https://dns.alidns.com/resolve",
"https://doh.pub/resolve",
@@ -131,7 +131,7 @@ actor PlatformAPI {
}
}
}
throw UCVLError.connection("无法取得 NPM 入口 vpn.toplc.cn 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
throw UCVLError.connection("无法取得 NPM 入口 vpn.example.invalid 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。")
}
func logout(token: String) async {
+39 -10
View File
@@ -15,7 +15,10 @@ final class VPNController: ObservableObject {
queue: .main
) { [weak self] note in
guard let connection = note.object as? NEVPNConnection else { return }
Task { @MainActor in self?.status = connection.status }
Task { @MainActor in
guard let self, connection === self.manager?.connection else { return }
self.status = connection.status
}
}
}
@@ -38,26 +41,51 @@ final class VPNController: ObservableObject {
}
}
func connect(configJSON: String, resolvedRemoteAddress: String, node: VPNNode, route: RouteMode) async throws {
func connect(
configJSON: String,
resolvedRemoteAddress: String,
node: VPNNode,
route: RouteMode,
internalEndpoint: ProxyTransportEndpoint? = nil,
configContract: Int? = nil,
connectionScope: String? = nil
) async throws {
guard route.id != "direct" else {
disconnect()
try await disconnectAndWait()
return
}
if let internalEndpoint {
guard internalEndpoint.address == resolvedRemoteAddress,
ProxyTransportPolicy.authorizedInternalEndpoint(
endpoint: internalEndpoint, nodeSlug: node.slug, configContract: configContract,
connectionScope: connectionScope, routeMode: route.id, configJSON: configJSON
) != nil else {
throw UCVLError.invalidConfiguration("内部入口与后台授权节点不一致。")
}
} else if !NetworkAddress.isPublicIPv4(resolvedRemoteAddress) {
throw UCVLError.invalidConfiguration("公网入口地址不可用。")
}
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 = [
var configuration: [String: Any] = [
"configJSON": configJSON,
"resolvedRemoteAddress": resolvedRemoteAddress,
"nodeSlug": node.slug,
"nodeName": node.name,
"routeMode": route.id,
]
if let internalEndpoint {
configuration["internalEndpointJSON"] = try JSONEncoder().encode(internalEndpoint)
configuration["configContract"] = configContract
configuration["connectionScope"] = connectionScope ?? ""
}
tunnelProtocol.providerConfiguration = configuration
selected.localizedDescription = "优创⁺纵横家"
selected.localizedDescription = "纵横家"
selected.protocolConfiguration = tunnelProtocol
selected.isEnabled = true
try await save(selected)
@@ -68,7 +96,7 @@ final class VPNController: ObservableObject {
try selected.connection.startVPNTunnel()
} catch {
activeNodeSlug = nil
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许优创⁺纵横家添加 VPN 配置。")
throw UCVLError.vpnPermission("系统 VPN 启动失败,请在“设置”中允许纵横家添加 VPN 配置。")
}
do {
try await waitUntilConnected(selected.connection)
@@ -84,15 +112,16 @@ final class VPNController: ObservableObject {
activeNodeSlug = nil
}
func disconnectAndWait(timeout: TimeInterval = 8) async {
func disconnectAndWait(timeout: TimeInterval = 8) async throws {
disconnect()
let deadline = Date().addingTimeInterval(timeout)
while Date() < deadline {
let deadline = ProcessInfo.processInfo.systemUptime + timeout
while ProcessInfo.processInfo.systemUptime < deadline {
let current = manager?.connection.status ?? .disconnected
status = current
if current == .disconnected || current == .invalid { return }
try? await Task.sleep(nanoseconds: 200_000_000)
try await Task.sleep(nanoseconds: 200_000_000)
}
throw UCVLError.invalidConfiguration("系统 VPN 尚未完成断开,已停止切换线路,请稍后重试。")
}
var isConnected: Bool {