Compare commits
No commits in common. "policy_mst" and "main" have entirely different histories.
policy_mst
...
main
1
.gitignore
vendored
1
.gitignore
vendored
@ -0,0 +1 @@
|
|||||||
|
punchnet.xcodeproj/*
|
||||||
@ -1,126 +0,0 @@
|
|||||||
//
|
|
||||||
// ArpResolver.swift
|
|
||||||
// sdlan
|
|
||||||
// 1. 通过ip地址查找mac地址
|
|
||||||
// 2. 要限制单位时间内,同一个ip的查询
|
|
||||||
// Created by 安礼成 on 2025/7/14.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import Darwin
|
|
||||||
|
|
||||||
actor ArpResolver {
|
|
||||||
// 增加缓存时间逻辑
|
|
||||||
struct ArpEntry {
|
|
||||||
var mac: Data
|
|
||||||
var expireTime: TimeInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
private var coolingDown: [UInt32: Date] = [:]
|
|
||||||
|
|
||||||
private var known_macs: [UInt32: ArpEntry] = [:]
|
|
||||||
private let arpTTL: TimeInterval
|
|
||||||
nonisolated private let snapshotPublisher: SnapshotPublisher<ArpSnapshot>
|
|
||||||
|
|
||||||
init(arpTTL: TimeInterval = 300) {
|
|
||||||
self.arpTTL = arpTTL
|
|
||||||
self.snapshotPublisher = SnapshotPublisher(initial: ArpSnapshot.empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
func runCleanup() async throws {
|
|
||||||
while !Task.isCancelled {
|
|
||||||
try await Task.sleep(for: .seconds(1))
|
|
||||||
try Task.checkCancellation()
|
|
||||||
self.cleanup()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func query(ip: UInt32) -> Data? {
|
|
||||||
guard let entry = known_macs[ip] else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if entry.expireTime < Date().timeIntervalSince1970 {
|
|
||||||
known_macs.removeValue(forKey: ip)
|
|
||||||
self.publishSnapshot()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return entry.mac
|
|
||||||
}
|
|
||||||
|
|
||||||
func append(ip: UInt32, mac: Data) {
|
|
||||||
let expireAt = Date().timeIntervalSince1970 + arpTTL
|
|
||||||
self.known_macs[ip] = ArpEntry(mac: mac, expireTime: expireAt)
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
|
|
||||||
func remove(ip: UInt32) {
|
|
||||||
self.known_macs.removeValue(forKey: ip)
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
|
|
||||||
func dropMacs(macs: [Data]) {
|
|
||||||
self.known_macs = self.known_macs.filter { !macs.contains($0.value.mac) }
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
|
|
||||||
func clear() {
|
|
||||||
self.known_macs = [:]
|
|
||||||
self.coolingDown = [:]
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
self.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeArpRequest(targetIp: UInt32) throws -> Data? {
|
|
||||||
guard self.coolingDown[targetIp] == nil else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
self.coolingDown[targetIp] = Date().addingTimeInterval(3)
|
|
||||||
|
|
||||||
var arpRequest = SDLArpRequest()
|
|
||||||
arpRequest.targetIp = targetIp
|
|
||||||
|
|
||||||
return try arpRequest.serializedData()
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleArpResponse(arpResponse: SDLArpResponse) {
|
|
||||||
let targetIp = arpResponse.targetIp
|
|
||||||
let targetMac = arpResponse.targetMac
|
|
||||||
if !targetMac.isEmpty {
|
|
||||||
let expireAt = Date().timeIntervalSince1970 + arpTTL
|
|
||||||
self.known_macs[targetIp] = ArpEntry(mac: targetMac, expireTime: expireAt)
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
nonisolated func snapshot() -> ArpSnapshot {
|
|
||||||
return self.snapshotPublisher.current()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func cleanup() {
|
|
||||||
let now = Date()
|
|
||||||
self.coolingDown = self.coolingDown.filter { $0.value > now }
|
|
||||||
let oldCount = self.known_macs.count
|
|
||||||
self.known_macs = self.known_macs.filter { $0.value.expireTime >= now.timeIntervalSince1970 }
|
|
||||||
if self.known_macs.count != oldCount {
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func publishSnapshot() {
|
|
||||||
self.snapshotPublisher.publish(self.compileSnapshot())
|
|
||||||
}
|
|
||||||
|
|
||||||
private func compileSnapshot() -> ArpSnapshot {
|
|
||||||
let now = Date().timeIntervalSince1970
|
|
||||||
let entries = self.known_macs.compactMapValues { entry in
|
|
||||||
entry.expireTime >= now ? entry.mac : nil
|
|
||||||
}
|
|
||||||
return ArpSnapshot(entries: entries)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
//
|
|
||||||
// ArpSnapshot.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/20.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class ArpSnapshot: Snapshot {
|
|
||||||
private let entries: [UInt32: Data]
|
|
||||||
|
|
||||||
init(entries: [UInt32: Data]) {
|
|
||||||
self.entries = entries
|
|
||||||
}
|
|
||||||
|
|
||||||
func lookup(_ ip: UInt32) -> Data? {
|
|
||||||
return self.entries[ip]
|
|
||||||
}
|
|
||||||
|
|
||||||
static func empty() -> ArpSnapshot {
|
|
||||||
return ArpSnapshot(entries: [:])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,27 +0,0 @@
|
|||||||
//
|
|
||||||
// CCAESChiper.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/3/17.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
struct CCAESChiper: CCDataCipher {
|
|
||||||
private let aesKey: Data
|
|
||||||
|
|
||||||
init(key: Data) {
|
|
||||||
self.aesKey = key
|
|
||||||
}
|
|
||||||
|
|
||||||
func decrypt(cipherText: Data) throws -> Data {
|
|
||||||
let ivData = Data(aesKey.prefix(16))
|
|
||||||
return try CC.crypt(.decrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: cipherText, key: aesKey, iv: ivData)
|
|
||||||
}
|
|
||||||
|
|
||||||
func encrypt(plainText: Data) throws -> Data {
|
|
||||||
let ivData = Data(aesKey.prefix(16))
|
|
||||||
|
|
||||||
return try CC.crypt(.encrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: plainText, key: aesKey, iv: ivData)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,77 +0,0 @@
|
|||||||
//
|
|
||||||
// NonceGenerator.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/3/17.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import CryptoKit
|
|
||||||
|
|
||||||
/// ChaCha20-Poly1305 加解密示例
|
|
||||||
struct CCChaCha20Cipher: CCDataCipher {
|
|
||||||
private let key: SymmetricKey
|
|
||||||
private let nonceGenerator: NonceGenerator
|
|
||||||
|
|
||||||
init(regionId: UInt32, keyData: Data) {
|
|
||||||
self.key = SymmetricKey(data: keyData)
|
|
||||||
self.nonceGenerator = NonceGenerator(regionId: regionId)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 加密
|
|
||||||
func encrypt(plainText: Data) throws -> Data {
|
|
||||||
let nonce = nonceGenerator.nextNonceData()
|
|
||||||
let sealedBox = try ChaChaPoly.seal(plainText, using: key, nonce: .init(data: nonce))
|
|
||||||
|
|
||||||
return sealedBox.combined
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 解密
|
|
||||||
func decrypt(cipherText: Data) throws -> Data {
|
|
||||||
let sealedBox = try ChaChaPoly.SealedBox(combined: cipherText)
|
|
||||||
return try ChaChaPoly.open(sealedBox, using: key)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension CCChaCha20Cipher {
|
|
||||||
|
|
||||||
/// Nonce生成器(基于ServerRange + 毫秒时间低位 + 本地自增counter)
|
|
||||||
final class NonceGenerator {
|
|
||||||
private let locker = NSLock()
|
|
||||||
|
|
||||||
private let regionId: UInt32 // 32-bit 全局前缀
|
|
||||||
private var counter: UInt64 = 0 // 自增counter
|
|
||||||
|
|
||||||
init(regionId: UInt32) {
|
|
||||||
self.regionId = regionId
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 生成64-bit Nonce
|
|
||||||
func nextNonceData() -> Data {
|
|
||||||
locker.lock()
|
|
||||||
defer {
|
|
||||||
locker.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
let nowMillis = UInt64(Date().timeIntervalSince1970 * 1000)
|
|
||||||
// 时间占用40个bit位, 自增id占用24位
|
|
||||||
let timeMask: UInt64 = (1 << 40) - 1
|
|
||||||
let timeLow = nowMillis & timeMask
|
|
||||||
|
|
||||||
// 生成 Nonce
|
|
||||||
let counterMask: UInt64 = (1 << 24) - 1
|
|
||||||
let nonce = (timeLow << 24) | (counter & counterMask)
|
|
||||||
// 自增counter
|
|
||||||
self.counter = (self.counter + 1) & counterMask // 超过最大值回到0
|
|
||||||
|
|
||||||
var data = Data()
|
|
||||||
// region: UInt32 -> 4字节大端
|
|
||||||
data.append(contentsOf: withUnsafeBytes(of: regionId.bigEndian, Array.init))
|
|
||||||
// nonce: UInt64 -> 8字节大端
|
|
||||||
data.append(contentsOf: withUnsafeBytes(of: nonce.bigEndian, Array.init))
|
|
||||||
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,13 +0,0 @@
|
|||||||
//
|
|
||||||
// AESCipher.swift
|
|
||||||
// sdlan
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2025/7/14.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
public protocol CCDataCipher {
|
|
||||||
func decrypt(cipherText: Data) throws -> Data
|
|
||||||
|
|
||||||
func encrypt(plainText: Data) throws -> Data
|
|
||||||
}
|
|
||||||
@ -1,41 +0,0 @@
|
|||||||
//
|
|
||||||
// CCRSACipher.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/3/17.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
struct CCRSACipher: RSACipher {
|
|
||||||
var pubKey: String
|
|
||||||
let privateKeyDER: Data
|
|
||||||
|
|
||||||
init(keySize: Int) throws {
|
|
||||||
let (privateKey, publicKey) = try Self.loadKeys(keySize: keySize)
|
|
||||||
let privKeyStr = SwKeyConvert.PrivateKey.derToPKCS1PEM(privateKey)
|
|
||||||
|
|
||||||
self.pubKey = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)
|
|
||||||
self.privateKeyDER = try SwKeyConvert.PrivateKey.pemToPKCS1DER(privKeyStr)
|
|
||||||
}
|
|
||||||
|
|
||||||
public func decode(data: Data) throws -> Data {
|
|
||||||
let tag = Data()
|
|
||||||
let (decryptedData, _) = try CC.RSA.decrypt(data, derKey: self.privateKeyDER, tag: tag, padding: .pkcs1, digest: .none)
|
|
||||||
|
|
||||||
return decryptedData
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func loadKeys(keySize: Int) throws -> (Data, Data) {
|
|
||||||
if let privateKey = UserDefaults.standard.data(forKey: "privateKey"),
|
|
||||||
let publicKey = UserDefaults.standard.data(forKey: "publicKey") {
|
|
||||||
|
|
||||||
return (privateKey, publicKey)
|
|
||||||
} else {
|
|
||||||
let (privateKey, publicKey) = try CC.RSA.generateKeyPair(keySize)
|
|
||||||
UserDefaults.standard.setValue(privateKey, forKey: "privateKey")
|
|
||||||
UserDefaults.standard.setValue(publicKey, forKey: "publicKey")
|
|
||||||
|
|
||||||
return (privateKey, publicKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,109 +0,0 @@
|
|||||||
//
|
|
||||||
// AsyncOneShot.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/4/28.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
enum AsyncOneShotError: Error {
|
|
||||||
case timeout
|
|
||||||
}
|
|
||||||
|
|
||||||
actor AsyncOneShot<Value: Sendable> {
|
|
||||||
private struct Waiter {
|
|
||||||
let continuation: CheckedContinuation<Value, Error>
|
|
||||||
let timeoutTask: Task<Void, Never>?
|
|
||||||
}
|
|
||||||
|
|
||||||
private var result: Result<Value, Error>?
|
|
||||||
private var waiters: [UUID: Waiter] = [:]
|
|
||||||
|
|
||||||
func wait() async throws -> Value {
|
|
||||||
try await self.waitInternal(timeout: nil, timeoutError: AsyncOneShotError.timeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
func wait(timeout: Duration, timeoutError: Error = AsyncOneShotError.timeout) async throws -> Value {
|
|
||||||
try await self.waitInternal(timeout: timeout, timeoutError: timeoutError)
|
|
||||||
}
|
|
||||||
|
|
||||||
func succeed(_ value: Value) {
|
|
||||||
self.complete(.success(value))
|
|
||||||
}
|
|
||||||
|
|
||||||
func fail(_ error: Error) {
|
|
||||||
self.complete(.failure(error))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func waitInternal(timeout: Duration?, timeoutError: Error) async throws -> Value {
|
|
||||||
let id = UUID()
|
|
||||||
|
|
||||||
return try await withTaskCancellationHandler {
|
|
||||||
try await withCheckedThrowingContinuation { continuation in
|
|
||||||
self.addWaiter(
|
|
||||||
id: id,
|
|
||||||
continuation: continuation,
|
|
||||||
timeout: timeout,
|
|
||||||
timeoutError: timeoutError
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
Task {
|
|
||||||
await self.cancelWaiter(id: id, throwing: CancellationError())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func addWaiter(
|
|
||||||
id: UUID,
|
|
||||||
continuation: CheckedContinuation<Value, Error>,
|
|
||||||
timeout: Duration?,
|
|
||||||
timeoutError: Error
|
|
||||||
) {
|
|
||||||
if let result {
|
|
||||||
continuation.resume(with: result)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let timeoutTask = timeout.map { timeout in
|
|
||||||
Task {
|
|
||||||
do {
|
|
||||||
try await Task.sleep(for: timeout)
|
|
||||||
if !Task.isCancelled {
|
|
||||||
self.cancelWaiter(id: id, throwing: timeoutError)
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.waiters[id] = Waiter(continuation: continuation, timeoutTask: timeoutTask)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func complete(_ result: Result<Value, Error>) {
|
|
||||||
guard self.result == nil else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.result = result
|
|
||||||
|
|
||||||
let waiters = self.waiters
|
|
||||||
self.waiters.removeAll()
|
|
||||||
|
|
||||||
for waiter in waiters.values {
|
|
||||||
waiter.timeoutTask?.cancel()
|
|
||||||
waiter.continuation.resume(with: result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func cancelWaiter(id: UUID, throwing error: Error) {
|
|
||||||
guard let waiter = self.waiters.removeValue(forKey: id) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
waiter.timeoutTask?.cancel()
|
|
||||||
waiter.continuation.resume(throwing: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,53 +0,0 @@
|
|||||||
//
|
|
||||||
// AsyncPromise.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/27.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
public actor AsyncPromise<Value: Sendable> {
|
|
||||||
private enum State {
|
|
||||||
case pending([CheckedContinuation<Value, Error>])
|
|
||||||
case completed(Result<Value, Error>)
|
|
||||||
}
|
|
||||||
|
|
||||||
private var state: State = .pending([])
|
|
||||||
|
|
||||||
public init() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public func value() async throws -> Value {
|
|
||||||
try await withCheckedThrowingContinuation { continuation in
|
|
||||||
switch state {
|
|
||||||
case .pending(var continuations):
|
|
||||||
continuations.append(continuation)
|
|
||||||
state = .pending(continuations)
|
|
||||||
|
|
||||||
case .completed(let result):
|
|
||||||
continuation.resume(with: result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public func succeed(_ value: Value) {
|
|
||||||
complete(.success(value))
|
|
||||||
}
|
|
||||||
|
|
||||||
public func fail(_ error: Error) {
|
|
||||||
complete(.failure(error))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func complete(_ result: Result<Value, Error>) {
|
|
||||||
guard case .pending(let continuations) = state else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
state = .completed(result)
|
|
||||||
|
|
||||||
for continuation in continuations {
|
|
||||||
continuation.resume(with: result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,56 +0,0 @@
|
|||||||
//
|
|
||||||
// OnceContinuation.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/7.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class OnceContinuation<Value, Failure: Error>: @unchecked Sendable {
|
|
||||||
private let lock = NSLock()
|
|
||||||
private var continuation: CheckedContinuation<Value, Failure>?
|
|
||||||
private var result: Result<Value, Failure>?
|
|
||||||
|
|
||||||
func set(_ continuation: CheckedContinuation<Value, Failure>) {
|
|
||||||
lock.lock()
|
|
||||||
if let result {
|
|
||||||
lock.unlock()
|
|
||||||
continuation.resume(with: result)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let hasPendingContinuation = self.continuation != nil
|
|
||||||
if !hasPendingContinuation {
|
|
||||||
self.continuation = continuation
|
|
||||||
}
|
|
||||||
lock.unlock()
|
|
||||||
|
|
||||||
if hasPendingContinuation {
|
|
||||||
preconditionFailure("OnceContinuation can only store one pending continuation")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func resume(returning value: Value) {
|
|
||||||
resume(with: .success(value))
|
|
||||||
}
|
|
||||||
|
|
||||||
func resume(throwing error: Failure) {
|
|
||||||
resume(with: .failure(error))
|
|
||||||
}
|
|
||||||
|
|
||||||
func resume(with result: Result<Value, Failure>) {
|
|
||||||
lock.lock()
|
|
||||||
guard self.result == nil else {
|
|
||||||
lock.unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.result = result
|
|
||||||
let continuation = self.continuation
|
|
||||||
self.continuation = nil
|
|
||||||
lock.unlock()
|
|
||||||
|
|
||||||
continuation?.resume(with: result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,251 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLConfiguration.swift
|
|
||||||
// sdlan
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2025/7/14.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
// 配置项目
|
|
||||||
public class SDLConfiguration {
|
|
||||||
|
|
||||||
// 网络地址信息
|
|
||||||
public struct NetworkAddress {
|
|
||||||
public let networkId: UInt32
|
|
||||||
public let ip: UInt32
|
|
||||||
public let maskLen: UInt8
|
|
||||||
public let mac: Data
|
|
||||||
public let networkDomain: String
|
|
||||||
|
|
||||||
// ip地址
|
|
||||||
var ipAddress: String {
|
|
||||||
return SDLUtil.int32ToIp(self.ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 掩码
|
|
||||||
var maskAddress: String {
|
|
||||||
let len0 = 32 - maskLen
|
|
||||||
let num: UInt32 = (0xFFFFFFFF >> len0) << len0
|
|
||||||
|
|
||||||
return SDLUtil.int32ToIp(num)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 网络地址
|
|
||||||
var netAddress: String {
|
|
||||||
let len0 = 32 - maskLen
|
|
||||||
let mask: UInt32 = (0xFFFFFFFF >> len0) << len0
|
|
||||||
|
|
||||||
return SDLUtil.int32ToIp(self.ip & mask)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 网络出口
|
|
||||||
public struct ExitNode {
|
|
||||||
let exitNodeIp: UInt32
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct ACL: Sendable {
|
|
||||||
let tcpPorts: Set<UInt16>
|
|
||||||
let udpPorts: Set<UInt16>
|
|
||||||
|
|
||||||
static let empty = ACL(tcpPorts: [], udpPorts: [])
|
|
||||||
}
|
|
||||||
|
|
||||||
// 解析的服务器地址信息
|
|
||||||
public struct ResolvedServerEndpoint: Sendable {
|
|
||||||
let host: String
|
|
||||||
let ip: String
|
|
||||||
}
|
|
||||||
|
|
||||||
// 当前的客户端版本
|
|
||||||
let version: Int
|
|
||||||
|
|
||||||
let serverEndpoint: ResolvedServerEndpoint
|
|
||||||
|
|
||||||
let stunSocketAddress: SocketAddress
|
|
||||||
|
|
||||||
// 网络探测地址信息
|
|
||||||
let stunProbeSocketAddressArray: [[SocketAddress]]
|
|
||||||
|
|
||||||
let clientId: String
|
|
||||||
let networkAddress: NetworkAddress
|
|
||||||
let hostname: String
|
|
||||||
let accessToken: String
|
|
||||||
let identityId: UInt32
|
|
||||||
let env: String
|
|
||||||
|
|
||||||
var acl: ACL
|
|
||||||
|
|
||||||
var exitNode: ExitNode?
|
|
||||||
|
|
||||||
public init(version: Int,
|
|
||||||
serverEndpoint: ResolvedServerEndpoint,
|
|
||||||
stunServers: [String],
|
|
||||||
clientId: String,
|
|
||||||
networkAddress: NetworkAddress,
|
|
||||||
hostname: String,
|
|
||||||
accessToken: String,
|
|
||||||
identityId: UInt32,
|
|
||||||
env: String,
|
|
||||||
acl: ACL,
|
|
||||||
exitNode: ExitNode?) {
|
|
||||||
self.version = version
|
|
||||||
self.serverEndpoint = serverEndpoint
|
|
||||||
let stunHosts = stunServers.isEmpty ? [serverEndpoint.ip] : stunServers
|
|
||||||
self.stunSocketAddress = Self.makeStunSocketAddress(host: stunHosts[0], port: 1365)
|
|
||||||
self.stunProbeSocketAddressArray = stunHosts.map { stunServer in
|
|
||||||
[
|
|
||||||
Self.makeStunSocketAddress(host: stunServer, port: 1365),
|
|
||||||
Self.makeStunSocketAddress(host: stunServer, port: 1366)
|
|
||||||
]
|
|
||||||
}
|
|
||||||
self.clientId = clientId
|
|
||||||
self.networkAddress = networkAddress
|
|
||||||
self.accessToken = accessToken
|
|
||||||
self.identityId = identityId
|
|
||||||
self.acl = acl
|
|
||||||
self.env = env
|
|
||||||
self.hostname = hostname
|
|
||||||
self.exitNode = exitNode
|
|
||||||
|
|
||||||
setenv("RUNTIME_ENV", env, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private extension SDLConfiguration {
|
|
||||||
|
|
||||||
static func resolveHostAddress(host: String, port: Int) -> String {
|
|
||||||
let address = try! SocketAddress.makeAddressResolvingHost(host, port: port)
|
|
||||||
return address.ipAddress!
|
|
||||||
}
|
|
||||||
|
|
||||||
static func makeStunSocketAddress(host: String, port: Int) -> SocketAddress {
|
|
||||||
return try! SocketAddress.makeAddressResolvingHost(host, port: port)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// 解析配置文件
|
|
||||||
extension SDLConfiguration {
|
|
||||||
|
|
||||||
static func parse(options: [String: NSObject]) -> SDLConfiguration? {
|
|
||||||
guard let version = options["version"] as? Int,
|
|
||||||
let serverHost = options["server_host"] as? String,
|
|
||||||
let stunAssistHost = options["stun_assist_host"] as? String,
|
|
||||||
let accessToken = options["access_token"] as? String,
|
|
||||||
let identityId = options["identity_id"] as? UInt32,
|
|
||||||
let clientId = options["client_id"] as? String,
|
|
||||||
let hostname = options["hostname"] as? String,
|
|
||||||
let env = options["env"] as? String,
|
|
||||||
let networkAddressDict = options["network_address"] as? [String: NSObject] else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let networkAddress = parseNetworkAddress(networkAddressDict) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
let acl = parseACL(options["exposed_service"])
|
|
||||||
|
|
||||||
// 网络出口配置是可选的
|
|
||||||
var exitNode: ExitNode? = nil
|
|
||||||
if let exitNodeIpStr = options["exit_node_ip"] as? String, let exitNodeIp = SDLUtil.ipv4StrToInt32(exitNodeIpStr) {
|
|
||||||
exitNode = .init(exitNodeIp: exitNodeIp)
|
|
||||||
}
|
|
||||||
|
|
||||||
let serverEndpoint = ResolvedServerEndpoint(
|
|
||||||
host: serverHost,
|
|
||||||
ip: Self.resolveHostAddress(host: serverHost, port: 1443)
|
|
||||||
)
|
|
||||||
|
|
||||||
return SDLConfiguration(version: version,
|
|
||||||
serverEndpoint: serverEndpoint,
|
|
||||||
stunServers: [serverHost, stunAssistHost],
|
|
||||||
clientId: clientId,
|
|
||||||
networkAddress: networkAddress,
|
|
||||||
hostname: hostname,
|
|
||||||
accessToken: accessToken,
|
|
||||||
identityId: identityId,
|
|
||||||
env: env,
|
|
||||||
acl: acl,
|
|
||||||
exitNode: exitNode)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parseNetworkAddress(_ config: [String: NSObject]) -> SDLConfiguration.NetworkAddress? {
|
|
||||||
guard let networkId = config["network_id"] as? UInt32,
|
|
||||||
let ipStr = config["ip"] as? String,
|
|
||||||
let ip = SDLUtil.ipv4StrToInt32(ipStr),
|
|
||||||
let maskLen = config["mask_len"] as? UInt8,
|
|
||||||
let mac = config["mac"] as? Data,
|
|
||||||
let networkDomain = config["network_domain"] as? String else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return .init(networkId: networkId, ip: ip, maskLen: maskLen, mac: mac, networkDomain: networkDomain)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parseACL(_ value: NSObject?) -> SDLConfiguration.ACL {
|
|
||||||
guard let dict = value as? [String: NSObject] else {
|
|
||||||
return .empty
|
|
||||||
}
|
|
||||||
|
|
||||||
return .init(
|
|
||||||
tcpPorts: parsePortSet(dict["tcp"]),
|
|
||||||
udpPorts: parsePortSet(dict["udp"])
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parsePortSet(_ value: NSObject?) -> Set<UInt16> {
|
|
||||||
let ports: [UInt32]
|
|
||||||
if let values = value as? [UInt32] {
|
|
||||||
ports = values
|
|
||||||
} else if let values = value as? [Int] {
|
|
||||||
ports = values.compactMap { $0 >= 0 ? UInt32($0) : nil }
|
|
||||||
} else if let values = value as? [NSNumber] {
|
|
||||||
ports = values.map(\.uint32Value)
|
|
||||||
} else if let values = value as? NSArray {
|
|
||||||
ports = values.compactMap { item in
|
|
||||||
if let value = item as? UInt32 {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
if let value = item as? Int, value >= 0 {
|
|
||||||
return UInt32(value)
|
|
||||||
}
|
|
||||||
if let value = item as? NSNumber {
|
|
||||||
return value.uint32Value
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ports = []
|
|
||||||
}
|
|
||||||
|
|
||||||
return Set(ports.compactMap { port in
|
|
||||||
guard port > 0, port <= UInt32(UInt16.max) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return UInt16(port)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SDLConfiguration.ACL {
|
|
||||||
|
|
||||||
init(response: SDLExposedServiceResponse) {
|
|
||||||
self.init(
|
|
||||||
tcpPorts: Self.parsePorts(response.tcpPorts),
|
|
||||||
udpPorts: Self.parsePorts(response.udpPorts)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parsePorts(_ ports: [UInt32]) -> Set<UInt16> {
|
|
||||||
return Set(ports.compactMap { port in
|
|
||||||
guard port > 0, port <= UInt32(UInt16.max) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return UInt16(port)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,634 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLContext.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2024/2/29.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NetworkExtension
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
// 上下文环境变量,全局共享
|
|
||||||
/*
|
|
||||||
1. 处理rsa的加解密逻辑
|
|
||||||
*/
|
|
||||||
actor SDLContextActor {
|
|
||||||
|
|
||||||
private var config: SDLConfiguration
|
|
||||||
// nat的网络类型
|
|
||||||
var natType: SDLNATProberActor.NatType = .blocked
|
|
||||||
|
|
||||||
// AES加密,授权通过后,对象才会被创建
|
|
||||||
private var dataCipher: CCDataCipher?
|
|
||||||
|
|
||||||
// rsa的相关配置, public_key是本地生成的
|
|
||||||
// 加密算法相关
|
|
||||||
nonisolated let rsaCipher: RSACipher
|
|
||||||
|
|
||||||
private let dnsCloudService: DNSCloudService
|
|
||||||
private let dnsLocalService: DNSLocalService
|
|
||||||
private let superService: SDLSuperService
|
|
||||||
private let superControlPlane: SDLSuperControlPlane
|
|
||||||
private let holeControlPlane: SDLHoleControlPlane
|
|
||||||
private let udpHoleService: SDLUDPHoleService
|
|
||||||
private let udpHoleV6Service: SDLUDPHoleV6Service
|
|
||||||
private let packetOutboundActor: PacketOutboundActor
|
|
||||||
private let packetInboundActor: PacketInboundActor
|
|
||||||
private let tunNetworkManager: SDLTunNetworkManager
|
|
||||||
|
|
||||||
private static let publicDnsServers = ["223.5.5.5", "119.29.29.29"]
|
|
||||||
|
|
||||||
nonisolated private let puncherActor: SDLPuncherActor
|
|
||||||
// 网络探测对象
|
|
||||||
nonisolated private let proberActor: SDLNATProberActor
|
|
||||||
|
|
||||||
// 本地ipv6地址信息探测
|
|
||||||
private var ipv6AssistClient: SDLIPV6AssistClient?
|
|
||||||
private let ipv6AssistEvents: AsyncStream<SDLV6Info?>
|
|
||||||
private let ipv6AssistContinuation: AsyncStream<SDLV6Info?>.Continuation
|
|
||||||
|
|
||||||
private let sessionManager: SessionManager
|
|
||||||
nonisolated private let arpResolver: ArpResolver
|
|
||||||
|
|
||||||
// 内部socket通讯
|
|
||||||
// 改为基于 App Group + Darwin Notification 的通知
|
|
||||||
|
|
||||||
// 流量统计
|
|
||||||
nonisolated private let flowTracer: SDLFlowTracer
|
|
||||||
|
|
||||||
nonisolated private let provider: NEPacketTunnelProvider
|
|
||||||
|
|
||||||
// 处理权限控制
|
|
||||||
private let policyService: PolicyService
|
|
||||||
private var rootTask: Task<Void, Error>?
|
|
||||||
private var rootTaskID: UUID?
|
|
||||||
private var terminalError: Error?
|
|
||||||
private let readySignal = AsyncOneShot<Void>()
|
|
||||||
|
|
||||||
public init(provider: NEPacketTunnelProvider, config: SDLConfiguration, rsaCipher: RSACipher) {
|
|
||||||
let puncherActor = SDLPuncherActor()
|
|
||||||
let proberActor = SDLNATProberActor(addressArray: config.stunProbeSocketAddressArray)
|
|
||||||
let sessionManager = SessionManager()
|
|
||||||
let arpResolver = ArpResolver()
|
|
||||||
let flowTracer = SDLFlowTracer()
|
|
||||||
let policyService = PolicyService(identityId: config.identityId, acl: config.acl)
|
|
||||||
let superService = SDLSuperService(serverEndpoint: config.serverEndpoint)
|
|
||||||
let udpHoleService = SDLUDPHoleService(proberActor: proberActor)
|
|
||||||
let udpHoleV6Service = SDLUDPHoleV6Service()
|
|
||||||
let dnsCloudService = DNSCloudService(serverIP: config.serverEndpoint.ip)
|
|
||||||
let dnsLocalService = DNSLocalService(publicDnsServers: Self.publicDnsServers)
|
|
||||||
let superControlPlane = SDLSuperControlPlane(config: config, rsaCipher: rsaCipher)
|
|
||||||
let holeControlPlane = SDLHoleControlPlane(networkAddress: config.networkAddress)
|
|
||||||
let tunNetworkManager = SDLTunNetworkManager(provider: provider)
|
|
||||||
let ipv6AssistPair = AsyncStream.makeStream(of: Optional<SDLV6Info>.self, bufferingPolicy: .bufferingNewest(1))
|
|
||||||
let packetOutboundActor = PacketOutboundActor(
|
|
||||||
provider: provider,
|
|
||||||
config: config,
|
|
||||||
dataCipher: nil,
|
|
||||||
sessionManager: sessionManager,
|
|
||||||
arpResolver: arpResolver,
|
|
||||||
puncherActor: puncherActor,
|
|
||||||
policyService: policyService,
|
|
||||||
superService: superService,
|
|
||||||
udpHoleService: udpHoleService,
|
|
||||||
udpHoleV6Service: udpHoleV6Service,
|
|
||||||
dnsCloudService: dnsCloudService,
|
|
||||||
dnsLocalService: dnsLocalService,
|
|
||||||
flowTracer: flowTracer
|
|
||||||
)
|
|
||||||
let packetInboundActor = PacketInboundActor(
|
|
||||||
provider: provider,
|
|
||||||
config: config,
|
|
||||||
dataCipher: nil,
|
|
||||||
policyService: policyService,
|
|
||||||
packetOutboundActor: packetOutboundActor,
|
|
||||||
arpResolver: arpResolver,
|
|
||||||
superService: superService,
|
|
||||||
flowTracer: flowTracer
|
|
||||||
)
|
|
||||||
|
|
||||||
self.provider = provider
|
|
||||||
self.config = config
|
|
||||||
self.rsaCipher = rsaCipher
|
|
||||||
|
|
||||||
self.puncherActor = puncherActor
|
|
||||||
self.proberActor = proberActor
|
|
||||||
|
|
||||||
self.sessionManager = sessionManager
|
|
||||||
self.arpResolver = arpResolver
|
|
||||||
self.flowTracer = flowTracer
|
|
||||||
|
|
||||||
// 权限控制
|
|
||||||
self.policyService = policyService
|
|
||||||
|
|
||||||
self.dnsCloudService = dnsCloudService
|
|
||||||
self.dnsLocalService = dnsLocalService
|
|
||||||
self.superService = superService
|
|
||||||
self.superControlPlane = superControlPlane
|
|
||||||
self.holeControlPlane = holeControlPlane
|
|
||||||
self.udpHoleService = udpHoleService
|
|
||||||
self.udpHoleV6Service = udpHoleV6Service
|
|
||||||
self.packetOutboundActor = packetOutboundActor
|
|
||||||
self.packetInboundActor = packetInboundActor
|
|
||||||
self.tunNetworkManager = tunNetworkManager
|
|
||||||
self.ipv6AssistEvents = ipv6AssistPair.stream
|
|
||||||
self.ipv6AssistContinuation = ipv6AssistPair.continuation
|
|
||||||
}
|
|
||||||
|
|
||||||
public func start() async throws {
|
|
||||||
guard self.rootTask == nil else {
|
|
||||||
try await self.readySignal.wait(timeout: .seconds(30))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let rootTaskID = UUID()
|
|
||||||
let rootTask = Task {
|
|
||||||
var result: Result<Void, Error> = .success(())
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await self.runRootBody()
|
|
||||||
} catch is CancellationError {
|
|
||||||
if let terminalError = self.consumeTerminalError() {
|
|
||||||
SDLLogger.fatal("[SDLContext] root task stopped by terminal error: \(terminalError)", category: .context)
|
|
||||||
result = .failure(terminalError)
|
|
||||||
} else {
|
|
||||||
SDLLogger.fatal("[SDLContext] root task cancelled", category: .context)
|
|
||||||
result = .failure(CancellationError())
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
SDLLogger.fatal("[SDLContext] root task failed: \(error)", category: .context)
|
|
||||||
await self.readySignal.fail(error)
|
|
||||||
result = .failure(error)
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.cleanupRoot()
|
|
||||||
self.finishRootTask(id: rootTaskID)
|
|
||||||
try result.get()
|
|
||||||
}
|
|
||||||
self.rootTaskID = rootTaskID
|
|
||||||
self.rootTask = rootTask
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await self.readySignal.wait(timeout: .seconds(30))
|
|
||||||
} catch {
|
|
||||||
SDLLogger.fatal("[SDLContext] start failed while waiting ready signal: \(error)", category: .context)
|
|
||||||
rootTask.cancel()
|
|
||||||
_ = try? await rootTask.value
|
|
||||||
self.rootTask = nil
|
|
||||||
self.rootTaskID = nil
|
|
||||||
self.terminalError = nil
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理context的停止问题
|
|
||||||
public func stop() async {
|
|
||||||
SDLLogger.fatal("[SDLContext] stop requested", category: .context)
|
|
||||||
let rootTask = self.rootTask
|
|
||||||
|
|
||||||
rootTask?.cancel()
|
|
||||||
await self.readySignal.fail(CancellationError())
|
|
||||||
_ = try? await rootTask?.value
|
|
||||||
|
|
||||||
self.rootTask = nil
|
|
||||||
self.rootTaskID = nil
|
|
||||||
self.terminalError = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
public func recoverAfterWake() async throws {
|
|
||||||
SDLLogger.log("[SDLContext] recoverAfterWake requested", category: .context)
|
|
||||||
|
|
||||||
guard self.rootTask != nil else {
|
|
||||||
throw TunnelError.invalidContext
|
|
||||||
}
|
|
||||||
|
|
||||||
try await self.readySignal.wait(timeout: .seconds(30))
|
|
||||||
|
|
||||||
guard let dataCipher = self.dataCipher else {
|
|
||||||
throw TunnelError.invalidContext
|
|
||||||
}
|
|
||||||
|
|
||||||
let clearedSessions = await self.sessionManager.clear()
|
|
||||||
self.natType = .blocked
|
|
||||||
await self.stopCurrentIPv6AssistClient()
|
|
||||||
await self.packetOutboundActor.updateRuntime(config: self.config, dataCipher: dataCipher)
|
|
||||||
await self.packetInboundActor.updateRuntime(config: self.config, dataCipher: dataCipher)
|
|
||||||
try await self.tunNetworkManager.apply(settings: .init(config: self.config), dnsServer: DNSHelper.dnsServer)
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContext] restart volatile resources after wake", category: .context)
|
|
||||||
|
|
||||||
await self.superService.recoverAfterWake()
|
|
||||||
await self.udpHoleService.recoverAfterWake()
|
|
||||||
await self.udpHoleV6Service.recoverAfterWake()
|
|
||||||
await self.dnsCloudService.recoverAfterWake()
|
|
||||||
await self.dnsLocalService.recoverAfterWake()
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContext] recoverAfterWake completed, clearedSessions: \(clearedSessions)", category: .context)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func runRootBody() async throws {
|
|
||||||
self.prepareTunnelNotifier()
|
|
||||||
|
|
||||||
await self.dnsCloudService.updateEventHandler { [weak self] event in
|
|
||||||
await self?.handleDNSEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.dnsLocalService.updateEventHandler { [weak self] event in
|
|
||||||
await self?.handleDNSEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.superControlPlane.updateDecisionHandler { [weak self] decision in
|
|
||||||
await self?.handleSuperDecision(decision)
|
|
||||||
}
|
|
||||||
|
|
||||||
let superControlPlane = self.superControlPlane
|
|
||||||
await self.superService.updateMessageHandler { message in
|
|
||||||
await superControlPlane.handle(message)
|
|
||||||
}
|
|
||||||
|
|
||||||
let packetInboundActor = self.packetInboundActor
|
|
||||||
await self.udpHoleService.updateHandlers(
|
|
||||||
onEvent: { [weak self] event in
|
|
||||||
await self?.handleUDPHoleControlEvent(event)
|
|
||||||
},
|
|
||||||
onData: { data in
|
|
||||||
await packetInboundActor.handleData(data)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
await self.udpHoleV6Service.updateHandlers(
|
|
||||||
onEvent: { [weak self] event in
|
|
||||||
await self?.handleUDPHoleControlEvent(event)
|
|
||||||
},
|
|
||||||
onData: { data in
|
|
||||||
await packetInboundActor.handleData(data)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
let superService = self.superService
|
|
||||||
let dnsCloudService = self.dnsCloudService
|
|
||||||
let dnsLocalService = self.dnsLocalService
|
|
||||||
let udpHoleService = self.udpHoleService
|
|
||||||
let udpHoleV6Service = self.udpHoleV6Service
|
|
||||||
let packetOutboundActor = self.packetOutboundActor
|
|
||||||
let policyService = self.policyService
|
|
||||||
let puncherActor = self.puncherActor
|
|
||||||
let arpResolver = self.arpResolver
|
|
||||||
let readySignal = self.readySignal
|
|
||||||
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await superService.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await udpHoleService.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await udpHoleV6Service.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await dnsCloudService.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await dnsLocalService.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await puncherActor.runCleanup()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await arpResolver.runCleanup()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await self.runIPv6AssistSupervisor()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask(priority: .high) {
|
|
||||||
_ = try await readySignal.wait()
|
|
||||||
try await packetOutboundActor.runPacketReader()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
_ = try await readySignal.wait()
|
|
||||||
try await Self.runPeriodic(name: "updatePolicyTask", interval: .seconds(10)) {
|
|
||||||
SDLLogger.log("[SDLContext] updatePolicyTask execute", category: .context)
|
|
||||||
await policyService.updatePolicy(superService: superService)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
_ = try await readySignal.wait()
|
|
||||||
try await Self.runPeriodic(name: "stunRequestTask", interval: .seconds(8)) {
|
|
||||||
try await self.runStunRequestOnce()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try await group.waitForAll()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func runIPv6AssistSupervisor() async throws {
|
|
||||||
do {
|
|
||||||
for await assistInfo in self.ipv6AssistEvents {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
await self.stopCurrentIPv6AssistClient()
|
|
||||||
|
|
||||||
guard let assistInfo else {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let client = SDLIPV6AssistClient(assistServerInfo: assistInfo) else {
|
|
||||||
SDLLogger.log("[SDLContext] invalid ipv6 assist config", category: .context)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
self.ipv6AssistClient = client
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await client.run()
|
|
||||||
} catch is CancellationError {
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
SDLLogger.log("[SDLContext] ipv6 assist client ended: \(error.localizedDescription)", category: .context)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.ipv6AssistClient === client {
|
|
||||||
self.ipv6AssistClient = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch is CancellationError {
|
|
||||||
await self.stopCurrentIPv6AssistClient()
|
|
||||||
throw CancellationError()
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.stopCurrentIPv6AssistClient()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func stopCurrentIPv6AssistClient() async {
|
|
||||||
let client = self.ipv6AssistClient
|
|
||||||
self.ipv6AssistClient = nil
|
|
||||||
await client?.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func cleanupRoot() async {
|
|
||||||
await self.puncherActor.stop()
|
|
||||||
await self.arpResolver.stop()
|
|
||||||
await self.sessionManager.clear()
|
|
||||||
|
|
||||||
await self.policyService.clear()
|
|
||||||
|
|
||||||
await self.udpHoleService.stop()
|
|
||||||
await self.udpHoleV6Service.stop()
|
|
||||||
|
|
||||||
await self.dnsCloudService.stop()
|
|
||||||
await self.dnsLocalService.stop()
|
|
||||||
|
|
||||||
await self.superService.stop()
|
|
||||||
await self.superControlPlane.reset()
|
|
||||||
|
|
||||||
self.dataCipher = nil
|
|
||||||
self.natType = .blocked
|
|
||||||
await self.packetOutboundActor.updateRuntime(config: self.config, dataCipher: nil)
|
|
||||||
await self.packetInboundActor.updateRuntime(config: self.config, dataCipher: nil)
|
|
||||||
|
|
||||||
self.ipv6AssistContinuation.yield(nil)
|
|
||||||
await self.stopCurrentIPv6AssistClient()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func requestRootShutdown(error: Error) async {
|
|
||||||
self.terminalError = error
|
|
||||||
await self.readySignal.fail(error)
|
|
||||||
self.rootTask?.cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func consumeTerminalError() -> Error? {
|
|
||||||
let error = self.terminalError
|
|
||||||
self.terminalError = nil
|
|
||||||
return error
|
|
||||||
}
|
|
||||||
|
|
||||||
private func finishRootTask(id: UUID) {
|
|
||||||
guard self.rootTaskID == id else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.rootTask = nil
|
|
||||||
self.rootTaskID = nil
|
|
||||||
self.terminalError = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[SDLContext] deinit", category: .context)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SDLContextActor {
|
|
||||||
|
|
||||||
// MARK: probe网络类型
|
|
||||||
|
|
||||||
private func setNatType(natType: SDLNATProberActor.NatType) {
|
|
||||||
self.natType = natType
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Notifier通知机制
|
|
||||||
|
|
||||||
private func prepareTunnelNotifier() {
|
|
||||||
// 启动noticeClient
|
|
||||||
// 旧的 UDP NoticeClient 已移除,改为初始化基于 App Group 的通知通道。
|
|
||||||
SDLTunnelAppNotifier.shared.clear()
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContext] tunnelAppNotifier ready", category: .context)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func publishTunnelEvent(code: Int? = nil, message: String) {
|
|
||||||
SDLTunnelAppNotifier.shared.publish(code: code, message: message)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: 数据发送
|
|
||||||
|
|
||||||
private func sendPacket(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) async {
|
|
||||||
switch remoteAddress {
|
|
||||||
case .v4:
|
|
||||||
await self.udpHoleService.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
case .v6:
|
|
||||||
await self.udpHoleV6Service.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
default:
|
|
||||||
SDLLogger.log("[SDLContext] unsupported socket family: \(remoteAddress)", category: .context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: 处理和Super之间的通讯
|
|
||||||
|
|
||||||
private func handleSuperDecision(_ decision: SuperDecision) async {
|
|
||||||
switch decision {
|
|
||||||
case .updateIPv6Assist(let assistInfo):
|
|
||||||
await self.stopCurrentIPv6AssistClient()
|
|
||||||
self.ipv6AssistContinuation.yield(assistInfo)
|
|
||||||
case .completeRegistration(let cipher):
|
|
||||||
await self.completeSuperRegistration(cipher: cipher)
|
|
||||||
case .failTunnel(let error):
|
|
||||||
await self.failTunnel(error)
|
|
||||||
case .publishTunnelEvent(let code, let message):
|
|
||||||
self.publishTunnelEvent(code: code, message: message)
|
|
||||||
case .sendSuper(let type, let data):
|
|
||||||
await self.superService.send(type: type, data: data)
|
|
||||||
case .sendPacket(let type, let data, let remoteAddress):
|
|
||||||
await self.sendPacket(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
case .resolvePeerInfo(let peerInfo):
|
|
||||||
let packets = await self.puncherActor.makeRegisterPackets(peerInfo: peerInfo)
|
|
||||||
for packet in packets {
|
|
||||||
await self.sendPacket(type: .register, data: packet.data, remoteAddress: packet.remoteAddress)
|
|
||||||
}
|
|
||||||
case .removeSession(let dstMac):
|
|
||||||
await self.sessionManager.removeSession(dstMac: dstMac)
|
|
||||||
case .requestExposedService:
|
|
||||||
await self.requestExposedService()
|
|
||||||
case .shutdown(let message):
|
|
||||||
SDLLogger.fatal("[SDLContext] Super shutdown received: \(message)", category: .context)
|
|
||||||
self.publishTunnelEvent(message: message)
|
|
||||||
let error = NSError(domain: "com.jihe.punchnet.tun", code: -2)
|
|
||||||
await self.failTunnel(error)
|
|
||||||
case .applyPolicyResponse(let policyResponse):
|
|
||||||
await self.policyService.applyPolicyResponse(policyResponse)
|
|
||||||
case .applyExposedServiceResponse(let response):
|
|
||||||
await self.applyExposedServiceResponse(response)
|
|
||||||
case .handleARPResponse(let arpResponse):
|
|
||||||
await self.arpResolver.handleArpResponse(arpResponse: arpResponse)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func completeSuperRegistration(cipher: CCDataCipher) async {
|
|
||||||
self.dataCipher = cipher
|
|
||||||
await self.packetOutboundActor.updateRuntime(config: self.config, dataCipher: cipher)
|
|
||||||
await self.packetInboundActor.updateRuntime(config: self.config, dataCipher: cipher)
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await self.tunNetworkManager.apply(settings: .init(config: self.config), dnsServer: DNSHelper.dnsServer)
|
|
||||||
SDLLogger.log("[SDLContext] setNetworkSettings successed", category: .context)
|
|
||||||
await self.readySignal.succeed(())
|
|
||||||
} catch {
|
|
||||||
SDLLogger.fatal("[SDLContext] apply tunnel network settings failed: \(error)", category: .context)
|
|
||||||
SDLLogger.log("[SDLContext] setTunnelNetworkSettings get error: \(error)", category: .context)
|
|
||||||
await self.failTunnel(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func failTunnel(_ error: Error) async {
|
|
||||||
SDLLogger.fatal("[SDLContext] failTunnel: \(error)", category: .context)
|
|
||||||
self.provider.cancelTunnelWithError(error)
|
|
||||||
await self.requestRootShutdown(error: error)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func requestExposedService() async {
|
|
||||||
guard let requestData = await self.policyService.makeExposedServiceRequest() else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.superService.send(type: .exposedServiceRequest, data: requestData)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func applyExposedServiceResponse(_ response: SDLExposedServiceResponse) async {
|
|
||||||
guard let acl = await self.policyService.applyExposedServiceResponse(response) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.config.acl = acl
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: DNS service events
|
|
||||||
|
|
||||||
private func handleDNSEvent(_ event: DNSEvent) async {
|
|
||||||
switch event {
|
|
||||||
case .packet(let packet):
|
|
||||||
let nePacket = NEPacket(data: packet, protocolFamily: 2)
|
|
||||||
self.provider.packetFlow.writePacketObjects([nePacket])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: 处理从Hole收到的数据
|
|
||||||
|
|
||||||
private func handleUDPHoleControlEvent(_ event: SDLUDPHoleService.Event) async {
|
|
||||||
let decisions = self.holeControlPlane.handle(event)
|
|
||||||
for decision in decisions {
|
|
||||||
await self.handleHoleDecision(decision)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleHoleDecision(_ decision: HoleDecision) async {
|
|
||||||
switch decision {
|
|
||||||
case .updateNatType(let natType):
|
|
||||||
self.setNatType(natType: natType)
|
|
||||||
case .sendPacket(let type, let data, let remoteAddress):
|
|
||||||
await self.sendPacket(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
case .addSession(let session):
|
|
||||||
await self.sessionManager.addSession(session: session)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: 和Stun相关的心跳机制
|
|
||||||
|
|
||||||
private func runStunRequestOnce() async throws {
|
|
||||||
let probeReply = try? await self.ipv6AssistClient?.probe(requestTimeout: .seconds(3))
|
|
||||||
|
|
||||||
if let v6Info = probeReply?.v6Info, let v6Address = SDLUtil.ipv6DataToString(v6Info.v6) {
|
|
||||||
SDLLogger.log("[SDLContext] probe ipv6 address: \(v6Address)", category: .context)
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLContext] probe ipv6 address: empty", category: .context)
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.superControlPlane.sendStunRequest(natType: self.natType, v6Info: probeReply?.v6Info)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: NEPacketTunnelProvider相关的逻辑
|
|
||||||
|
|
||||||
// 取消出口节点的时候,ip地址为: 0.0.0.0
|
|
||||||
public func updateExitNode(exitNodeIp: String) async throws {
|
|
||||||
if let ip = SDLUtil.ipv4StrToInt32(exitNodeIp), ip > 0 {
|
|
||||||
self.config.exitNode = .init(exitNodeIp: ip)
|
|
||||||
} else {
|
|
||||||
self.config.exitNode = nil
|
|
||||||
}
|
|
||||||
await self.packetOutboundActor.updateRuntime(config: self.config, dataCipher: self.dataCipher)
|
|
||||||
await self.packetInboundActor.updateRuntime(config: self.config, dataCipher: self.dataCipher)
|
|
||||||
|
|
||||||
try await self.tunNetworkManager.apply(settings: .init(config: self.config), dnsServer: DNSHelper.dnsServer)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SDLContextActor {
|
|
||||||
|
|
||||||
private static func runPeriodic(
|
|
||||||
name: String,
|
|
||||||
interval: Duration,
|
|
||||||
retryDelay: Duration = .seconds(5),
|
|
||||||
operation: @escaping @Sendable () async throws -> Void
|
|
||||||
) async throws {
|
|
||||||
while !Task.isCancelled {
|
|
||||||
do {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
try await operation()
|
|
||||||
try await Task.sleep(for: interval)
|
|
||||||
} catch is CancellationError {
|
|
||||||
SDLLogger.log("[SDLContext] worker \(name) cancelled", category: .context)
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
SDLLogger.log("[SDLContext] worker \(name) crashed: \(error.localizedDescription), will retry", category: .context)
|
|
||||||
try await Task.sleep(for: retryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,264 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLContextBootstrap.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/28.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class SDLContextBootstrap: @unchecked Sendable {
|
|
||||||
private typealias StartCompletion = (Error?) -> Void
|
|
||||||
private typealias StopCompletion = () -> Void
|
|
||||||
private typealias WakeCompletion = (Error?) -> Void
|
|
||||||
|
|
||||||
private enum BootstrapCommand {
|
|
||||||
case start(config: SDLConfiguration, rsaCipher: CCRSACipher, completion: StartCompletion)
|
|
||||||
case stop(clearRuntimeConfiguration: Bool, completion: StopCompletion)
|
|
||||||
case recoverAfterWake(completion: WakeCompletion)
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum RuntimeState {
|
|
||||||
case idle
|
|
||||||
case starting
|
|
||||||
case running
|
|
||||||
case stopping
|
|
||||||
}
|
|
||||||
|
|
||||||
private weak var provider: PacketTunnelProvider?
|
|
||||||
private let runtimeLock = NSLock()
|
|
||||||
private var runtimeState: RuntimeState = .idle
|
|
||||||
private var config: SDLConfiguration?
|
|
||||||
private var rsaCipher: CCRSACipher?
|
|
||||||
private var contextActor: SDLContextActor?
|
|
||||||
private var startCompletionHandler: ((Error?) -> Void)?
|
|
||||||
private let commandContinuation: AsyncStream<BootstrapCommand>.Continuation
|
|
||||||
private var commandWorker: Task<Void, Never>?
|
|
||||||
|
|
||||||
init(provider: PacketTunnelProvider) {
|
|
||||||
let commandPair = AsyncStream.makeStream(of: BootstrapCommand.self, bufferingPolicy: .unbounded)
|
|
||||||
|
|
||||||
self.provider = provider
|
|
||||||
self.commandContinuation = commandPair.continuation
|
|
||||||
let stream = commandPair.stream
|
|
||||||
|
|
||||||
self.commandWorker = Task { [weak self] in
|
|
||||||
await self?.runCommandLoop(stream)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
self.commandContinuation.finish()
|
|
||||||
self.commandWorker?.cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
func startCached(completionHandler: @escaping (Error?) -> Void) {
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
let config = self.config
|
|
||||||
let rsaCipher = self.rsaCipher
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
|
|
||||||
guard let config, let rsaCipher else {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] startCached failed: missing cached runtime configuration", category: .app)
|
|
||||||
completionHandler(TunnelError.invalidConfiguration)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.start(config: config, rsaCipher: rsaCipher, completionHandler: completionHandler)
|
|
||||||
}
|
|
||||||
|
|
||||||
func start(config: SDLConfiguration, rsaCipher: CCRSACipher, completionHandler: @escaping (Error?) -> Void) {
|
|
||||||
self.submit(.start(config: config, rsaCipher: rsaCipher, completion: completionHandler))
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop(clearRuntimeConfiguration: Bool, completionHandler: @escaping () -> Void) {
|
|
||||||
self.submit(.stop(clearRuntimeConfiguration: clearRuntimeConfiguration, completion: completionHandler))
|
|
||||||
}
|
|
||||||
|
|
||||||
func recoverAfterWake(completionHandler: @escaping (Error?) -> Void) {
|
|
||||||
self.submit(.recoverAfterWake(completion: completionHandler))
|
|
||||||
}
|
|
||||||
|
|
||||||
func currentContextActor() -> SDLContextActor? {
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
let contextActor = self.contextActor
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
return contextActor
|
|
||||||
}
|
|
||||||
|
|
||||||
private func submit(_ command: BootstrapCommand) {
|
|
||||||
self.commandContinuation.yield(command)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func runCommandLoop(_ stream: AsyncStream<BootstrapCommand>) async {
|
|
||||||
for await command in stream {
|
|
||||||
self.handle(command)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handle(_ command: BootstrapCommand) {
|
|
||||||
switch command {
|
|
||||||
case .start(let config, let rsaCipher, let completion):
|
|
||||||
self.handleStart(config: config, rsaCipher: rsaCipher, completionHandler: completion)
|
|
||||||
case .stop(let clearRuntimeConfiguration, let completion):
|
|
||||||
self.handleStop(clearRuntimeConfiguration: clearRuntimeConfiguration, completionHandler: completion)
|
|
||||||
case .recoverAfterWake(let completion):
|
|
||||||
self.handleRecoverAfterWake(completionHandler: completion)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleStart(config: SDLConfiguration, rsaCipher: CCRSACipher, completionHandler: @escaping (Error?) -> Void) {
|
|
||||||
guard let provider = self.provider else {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] start rejected: provider released", category: .app)
|
|
||||||
completionHandler(TunnelError.invalidContext)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
switch self.runtimeState {
|
|
||||||
case .idle:
|
|
||||||
SDLTunnelAppNotifier.shared.clear()
|
|
||||||
|
|
||||||
let contextActor = SDLContextActor(
|
|
||||||
provider: provider,
|
|
||||||
config: config,
|
|
||||||
rsaCipher: rsaCipher
|
|
||||||
)
|
|
||||||
|
|
||||||
self.config = config
|
|
||||||
self.rsaCipher = rsaCipher
|
|
||||||
self.contextActor = contextActor
|
|
||||||
self.startCompletionHandler = completionHandler
|
|
||||||
self.runtimeState = .starting
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
|
|
||||||
Task {
|
|
||||||
do {
|
|
||||||
try await contextActor.start()
|
|
||||||
self.finishContextStart(contextActor, error: nil)
|
|
||||||
} catch {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] context start failed: \(error)", category: .app)
|
|
||||||
self.finishContextStart(contextActor, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case .starting, .running, .stopping:
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] start rejected: invalid runtime state \(self.runtimeState)", category: .app)
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
completionHandler(TunnelError.invalidContext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleStop(clearRuntimeConfiguration: Bool, completionHandler: @escaping () -> Void) {
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
let contextActor = self.contextActor
|
|
||||||
let startCompletionHandler = self.startCompletionHandler
|
|
||||||
|
|
||||||
guard let contextActor else {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] stop requested while context is nil, clearRuntimeConfiguration: \(clearRuntimeConfiguration)", category: .app)
|
|
||||||
self.runtimeState = .idle
|
|
||||||
self.startCompletionHandler = nil
|
|
||||||
if clearRuntimeConfiguration {
|
|
||||||
self.config = nil
|
|
||||||
self.rsaCipher = nil
|
|
||||||
}
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
startCompletionHandler?(TunnelError.invalidContext)
|
|
||||||
completionHandler()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.contextActor = nil
|
|
||||||
self.startCompletionHandler = nil
|
|
||||||
self.runtimeState = .stopping
|
|
||||||
if clearRuntimeConfiguration {
|
|
||||||
self.config = nil
|
|
||||||
self.rsaCipher = nil
|
|
||||||
}
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] stop will stop current context, clearRuntimeConfiguration: \(clearRuntimeConfiguration)", category: .app)
|
|
||||||
startCompletionHandler?(TunnelError.invalidContext)
|
|
||||||
|
|
||||||
Task {
|
|
||||||
await contextActor.stop()
|
|
||||||
self.markContextStopped()
|
|
||||||
completionHandler()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleRecoverAfterWake(completionHandler: @escaping (Error?) -> Void) {
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
let runtimeState = self.runtimeState
|
|
||||||
let contextActor = self.contextActor
|
|
||||||
let config = self.config
|
|
||||||
let rsaCipher = self.rsaCipher
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
|
|
||||||
switch runtimeState {
|
|
||||||
case .running:
|
|
||||||
guard let contextActor else {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] recoverAfterWake failed: missing running context", category: .app)
|
|
||||||
completionHandler(TunnelError.invalidContext)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
Task {
|
|
||||||
do {
|
|
||||||
try await contextActor.recoverAfterWake()
|
|
||||||
completionHandler(nil)
|
|
||||||
} catch {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] recoverAfterWake failed: \(error)", category: .app)
|
|
||||||
completionHandler(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case .idle:
|
|
||||||
guard let config, let rsaCipher else {
|
|
||||||
SDLLogger.fatal("[SDLContextBootstrap] recoverAfterWake failed: missing cached runtime configuration", category: .app)
|
|
||||||
completionHandler(TunnelError.invalidConfiguration)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContextBootstrap] recoverAfterWake will start cached context", category: .app)
|
|
||||||
self.handleStart(config: config, rsaCipher: rsaCipher, completionHandler: completionHandler)
|
|
||||||
|
|
||||||
case .starting:
|
|
||||||
SDLLogger.log("[SDLContextBootstrap] recoverAfterWake ignored while context is starting", category: .app)
|
|
||||||
completionHandler(nil)
|
|
||||||
|
|
||||||
case .stopping:
|
|
||||||
SDLLogger.log("[SDLContextBootstrap] recoverAfterWake ignored while context is stopping", category: .app)
|
|
||||||
completionHandler(nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func finishContextStart(_ contextActor: SDLContextActor, error: Error?) {
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
guard self.contextActor === contextActor else {
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let startCompletionHandler = self.startCompletionHandler
|
|
||||||
self.startCompletionHandler = nil
|
|
||||||
|
|
||||||
if let error {
|
|
||||||
self.contextActor = nil
|
|
||||||
self.runtimeState = .idle
|
|
||||||
} else {
|
|
||||||
self.runtimeState = .running
|
|
||||||
}
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
|
|
||||||
startCompletionHandler?(error)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func markContextStopped() {
|
|
||||||
self.runtimeLock.lock()
|
|
||||||
if self.contextActor == nil {
|
|
||||||
self.runtimeState = .idle
|
|
||||||
}
|
|
||||||
self.runtimeLock.unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLContextError.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/27.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
enum SDLContextError: Error {
|
|
||||||
case udpHoleClosed
|
|
||||||
|
|
||||||
case dnsLocalClientClosed
|
|
||||||
case dnsLocalClientCancelled
|
|
||||||
|
|
||||||
case dnsClientClosed
|
|
||||||
case dnsClientCancelled
|
|
||||||
}
|
|
||||||
@ -1,113 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLHoleControlPlane.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/28.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
enum HoleDecision {
|
|
||||||
case updateNatType(SDLNATProberActor.NatType)
|
|
||||||
case sendPacket(type: SDLPacketType, data: Data, remoteAddress: SocketAddress)
|
|
||||||
case addSession(Session)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct SDLHoleControlPlane {
|
|
||||||
private let networkAddress: SDLConfiguration.NetworkAddress
|
|
||||||
|
|
||||||
init(networkAddress: SDLConfiguration.NetworkAddress) {
|
|
||||||
self.networkAddress = networkAddress
|
|
||||||
}
|
|
||||||
|
|
||||||
func handle(_ event: SDLUDPHoleService.Event) -> [HoleDecision] {
|
|
||||||
switch event {
|
|
||||||
case .ready(let localAddress):
|
|
||||||
SDLLogger.log("[SDLContext] udpHole ready: \(localAddress)", category: .udpHole)
|
|
||||||
return []
|
|
||||||
case .natType(let natType):
|
|
||||||
SDLLogger.log("[SDLContext] nat_type is: \(natType)", category: .udpHole)
|
|
||||||
return [
|
|
||||||
.updateNatType(natType)
|
|
||||||
]
|
|
||||||
case .packet(let remoteAddress, let message):
|
|
||||||
return self.handlePacket(remoteAddress: remoteAddress, message: message)
|
|
||||||
case .closed(let error):
|
|
||||||
SDLLogger.log("[SDLContext] udpHole closed: \(error)", category: .udpHole)
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handlePacket(remoteAddress: SocketAddress, message: SDLHoleControlMessage) -> [HoleDecision] {
|
|
||||||
switch message {
|
|
||||||
case .stunReply, .stunProbeReply:
|
|
||||||
SDLLogger.log("[SDLContext] get a stun reply", category: .udpHole)
|
|
||||||
return []
|
|
||||||
case .register(let register):
|
|
||||||
return self.handleRegister(remoteAddress: remoteAddress, register: register)
|
|
||||||
case .registerAck(let registerAck):
|
|
||||||
return self.handleRegisterAck(remoteAddress: remoteAddress, registerAck: registerAck)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleRegister(remoteAddress: SocketAddress, register: SDLRegister) -> [HoleDecision] {
|
|
||||||
SDLLogger.log("[SDLContext] register packet: \(register), network_address: \(self.networkAddress)", category: .udpHole)
|
|
||||||
var decisions: [HoleDecision] = []
|
|
||||||
|
|
||||||
guard register.dstMac == self.networkAddress.mac && register.networkID == self.networkAddress.networkId else {
|
|
||||||
SDLLogger.log("[SDLContext] didReadRegister get a invalid packet, because dst_ip not matched: \(register.dstMac)", category: .udpHole)
|
|
||||||
return decisions
|
|
||||||
}
|
|
||||||
|
|
||||||
var registerAck = SDLRegisterAck()
|
|
||||||
registerAck.networkID = self.networkAddress.networkId
|
|
||||||
registerAck.srcMac = self.networkAddress.mac
|
|
||||||
registerAck.dstMac = register.srcMac
|
|
||||||
|
|
||||||
if let data = try? registerAck.serializedData() {
|
|
||||||
decisions.append(.sendPacket(type: .registerAck, data: data, remoteAddress: remoteAddress))
|
|
||||||
}
|
|
||||||
|
|
||||||
if let session = self.makeSession(dstMac: register.srcMac, remoteAddress: remoteAddress) {
|
|
||||||
decisions.append(.addSession(session))
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLContext] didReadRegister get unsupported remoteAddress: \(remoteAddress)", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
return decisions
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleRegisterAck(remoteAddress: SocketAddress, registerAck: SDLRegisterAck) -> [HoleDecision] {
|
|
||||||
guard registerAck.dstMac == self.networkAddress.mac && registerAck.networkID == self.networkAddress.networkId else {
|
|
||||||
SDLLogger.log("[SDLContext] didReadRegisterAck get a invalid packet, because dst_mac not matched: \(registerAck.dstMac)", category: .udpHole)
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let session = self.makeSession(dstMac: registerAck.srcMac, remoteAddress: remoteAddress) else {
|
|
||||||
SDLLogger.log("[SDLContext] didReadRegisterAck get unsupported remoteAddress: \(remoteAddress)", category: .udpHole)
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
return [.addSession(session)]
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeSession(dstMac: Data, remoteAddress: SocketAddress) -> Session? {
|
|
||||||
guard let addressType = Self.addressType(from: remoteAddress) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return Session(dstMac: dstMac, natAddress: remoteAddress, addressType: addressType)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func addressType(from remoteAddress: SocketAddress) -> Session.AddressType? {
|
|
||||||
switch remoteAddress {
|
|
||||||
case .v4:
|
|
||||||
return .v4
|
|
||||||
case .v6:
|
|
||||||
return .v6
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,214 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperControlPlane.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/28.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
enum SuperDecision {
|
|
||||||
case updateIPv6Assist(SDLV6Info?)
|
|
||||||
case completeRegistration(cipher: CCDataCipher)
|
|
||||||
case failTunnel(Error)
|
|
||||||
case publishTunnelEvent(code: Int?, message: String)
|
|
||||||
case sendSuper(type: SDLPacketType, data: Data)
|
|
||||||
case sendPacket(type: SDLPacketType, data: Data, remoteAddress: SocketAddress)
|
|
||||||
case resolvePeerInfo(SDLPeerInfo)
|
|
||||||
case removeSession(dstMac: Data)
|
|
||||||
case requestExposedService
|
|
||||||
case shutdown(message: String)
|
|
||||||
case applyPolicyResponse(SDLPolicyResponse)
|
|
||||||
case applyExposedServiceResponse(SDLExposedServiceResponse)
|
|
||||||
case handleARPResponse(SDLArpResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
actor SDLSuperControlPlane {
|
|
||||||
typealias DecisionHandler = @Sendable (SuperDecision) async -> Void
|
|
||||||
|
|
||||||
private let config: SDLConfiguration
|
|
||||||
private let rsaCipher: RSACipher
|
|
||||||
private var sessionToken: Data?
|
|
||||||
private var onDecision: DecisionHandler = { _ in }
|
|
||||||
|
|
||||||
init(config: SDLConfiguration, rsaCipher: RSACipher) {
|
|
||||||
self.config = config
|
|
||||||
self.rsaCipher = rsaCipher
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateDecisionHandler(_ onDecision: @escaping DecisionHandler) {
|
|
||||||
self.onDecision = onDecision
|
|
||||||
}
|
|
||||||
|
|
||||||
func reset() {
|
|
||||||
self.sessionToken = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handle(_ message: SDLSuperMessage) async {
|
|
||||||
switch message {
|
|
||||||
case .welcome(let welcome):
|
|
||||||
await self.handleWelcome(welcome)
|
|
||||||
case .pong:
|
|
||||||
()
|
|
||||||
case .registerSuperAck(let registerSuperAck):
|
|
||||||
await self.handleRegisterSuperAck(registerSuperAck)
|
|
||||||
case .registerSuperNak(let registerSuperNak):
|
|
||||||
await self.handleRegisterSuperNak(registerSuperNak)
|
|
||||||
case .peerInfo(let peerInfo):
|
|
||||||
SDLLogger.log("[SDLContext] peer message: \(peerInfo)", category: .super)
|
|
||||||
await self.onDecision(.resolvePeerInfo(peerInfo))
|
|
||||||
case .event(let event):
|
|
||||||
await self.handleEvent(event)
|
|
||||||
case .policyReponse(let policyResponse):
|
|
||||||
await self.onDecision(.applyPolicyResponse(policyResponse))
|
|
||||||
case .exposedServiceResponse(let response):
|
|
||||||
await self.onDecision(.applyExposedServiceResponse(response))
|
|
||||||
case .arpResponse(let arpResponse):
|
|
||||||
SDLLogger.log("[SDLContext] get arp response: \(arpResponse)", category: .super)
|
|
||||||
await self.onDecision(.handleARPResponse(arpResponse))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendStunRequest(natType: SDLNATProberActor.NatType, v6Info: SDLV6Info?) async {
|
|
||||||
guard let sessionToken else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var stunRequest = SDLStunRequest()
|
|
||||||
stunRequest.clientID = self.config.clientId
|
|
||||||
stunRequest.networkID = self.config.networkAddress.networkId
|
|
||||||
stunRequest.ip = self.config.networkAddress.ip
|
|
||||||
stunRequest.mac = self.config.networkAddress.mac
|
|
||||||
stunRequest.natType = UInt32(natType.rawValue)
|
|
||||||
stunRequest.sessionToken = sessionToken
|
|
||||||
|
|
||||||
if let v6Info {
|
|
||||||
stunRequest.v6Info = v6Info
|
|
||||||
}
|
|
||||||
|
|
||||||
if let stunData = try? stunRequest.serializedData() {
|
|
||||||
await self.onDecision(.sendPacket(type: .stunRequest, data: stunData, remoteAddress: self.config.stunSocketAddress))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleWelcome(_ welcome: SDLWelcome) async {
|
|
||||||
SDLLogger.log("[SDLContext] quic welcome: \(welcome)", category: .super)
|
|
||||||
|
|
||||||
if welcome.hasIpv6Assist {
|
|
||||||
await self.onDecision(.updateIPv6Assist(welcome.ipv6Assist))
|
|
||||||
} else {
|
|
||||||
await self.onDecision(.updateIPv6Assist(nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.doRegisterSuper()
|
|
||||||
SDLLogger.log("[SDLContext] quic doRegisterSuper", category: .super)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleRegisterSuperAck(_ registerSuperAck: SDLRegisterSuperAck) async {
|
|
||||||
guard let key = try? self.rsaCipher.decode(data: Data(registerSuperAck.key)) else {
|
|
||||||
SDLLogger.fatal("[SDLSuperControlPlane] registerSuperAck invalid key, will fail tunnel", category: .super)
|
|
||||||
SDLLogger.log("[SDLContext] registerSuperAck invalid key", category: .super)
|
|
||||||
await self.onDecision(.failTunnel(SDLError.invalidKey))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let algorithm = registerSuperAck.algorithm.lowercased()
|
|
||||||
let regionId = registerSuperAck.regionID
|
|
||||||
self.sessionToken = registerSuperAck.sessionToken
|
|
||||||
|
|
||||||
let cipher: CCDataCipher
|
|
||||||
switch algorithm {
|
|
||||||
case "aes":
|
|
||||||
cipher = CCAESChiper(key: key)
|
|
||||||
case "chacha20":
|
|
||||||
cipher = CCChaCha20Cipher(regionId: regionId, keyData: key)
|
|
||||||
default:
|
|
||||||
SDLLogger.fatal("[SDLSuperControlPlane] unsupported cipher algorithm \(algorithm), will fail tunnel", category: .super)
|
|
||||||
SDLLogger.log("[SDLContext] registerSuperAck invalid algorithm \(algorithm)", category: .super)
|
|
||||||
await self.onDecision(.failTunnel(SDLError.unsupportedAlgorithm(algorithm: algorithm)))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContext] registerSuperAck, use algorithm \(algorithm), key len: \(key.count)", category: .super)
|
|
||||||
await self.onDecision(.completeRegistration(cipher: cipher))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleRegisterSuperNak(_ nakPacket: SDLRegisterSuperNak) async {
|
|
||||||
let errorMessage = nakPacket.errorMessage
|
|
||||||
guard let errorCode = SDLNAKErrorCode(rawValue: UInt8(nakPacket.errorCode)) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
switch errorCode {
|
|
||||||
case .invalidToken, .nodeDisabled:
|
|
||||||
SDLLogger.fatal("[SDLSuperControlPlane] SuperNak \(errorCode) will fail tunnel: \(errorMessage)", category: .super)
|
|
||||||
await self.onDecision(.publishTunnelEvent(code: Int(errorCode.rawValue), message: errorMessage))
|
|
||||||
await self.onDecision(.failTunnel(NSError(domain: "com.jihe.punchnet.tun", code: -1)))
|
|
||||||
case .noIpAddress, .networkFault, .internalFault:
|
|
||||||
await self.onDecision(.publishTunnelEvent(code: Int(errorCode.rawValue), message: errorMessage))
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContext] Get a SuperNak message exit", category: .super)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleEvent(_ event: SDLEvent) async {
|
|
||||||
switch event.event {
|
|
||||||
case .natChanged(let natChangedEvent):
|
|
||||||
let dstMac = natChangedEvent.mac
|
|
||||||
SDLLogger.log("[SDLContext] natChangedEvent, dstMac: \(dstMac)", category: .super)
|
|
||||||
await self.onDecision(.removeSession(dstMac: dstMac))
|
|
||||||
case .sendRegister(let sendRegisterEvent):
|
|
||||||
await self.handleSendRegisterEvent(sendRegisterEvent)
|
|
||||||
case .exposedServiceChanged:
|
|
||||||
SDLLogger.log("[SDLContext] exposedServiceChanged event", category: .super)
|
|
||||||
await self.onDecision(.requestExposedService)
|
|
||||||
case .shutdown(let shutdownEvent):
|
|
||||||
SDLLogger.fatal("[SDLSuperControlPlane] shutdown event received: \(shutdownEvent.message)", category: .super)
|
|
||||||
await self.onDecision(.shutdown(message: shutdownEvent.message))
|
|
||||||
case .none:
|
|
||||||
()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleSendRegisterEvent(_ event: SDLEvent.SendRegister) async {
|
|
||||||
var register = SDLRegister()
|
|
||||||
register.networkID = self.config.networkAddress.networkId
|
|
||||||
register.srcMac = self.config.networkAddress.mac
|
|
||||||
register.dstMac = event.dstMac
|
|
||||||
|
|
||||||
guard let registerData = try? register.serializedData() else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLContext] sendRegisterEvent, ip: \(event)", category: .super)
|
|
||||||
|
|
||||||
if event.natIp > 0 && event.natPort > 0 {
|
|
||||||
let address = SDLUtil.int32ToIp(event.natIp)
|
|
||||||
if let remoteAddress = try? SocketAddress(ipAddress: address, port: Int(event.natPort)) {
|
|
||||||
await self.onDecision(.sendPacket(type: .register, data: registerData, remoteAddress: remoteAddress))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if event.hasV6Info, let remoteAddress = try? await event.v6Info.socketAddress() {
|
|
||||||
await self.onDecision(.sendPacket(type: .register, data: registerData, remoteAddress: remoteAddress))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func doRegisterSuper() async {
|
|
||||||
var registerSuper = SDLRegisterSuper()
|
|
||||||
registerSuper.clientID = self.config.clientId
|
|
||||||
registerSuper.networkID = self.config.networkAddress.networkId
|
|
||||||
registerSuper.mac = self.config.networkAddress.mac
|
|
||||||
registerSuper.ip = self.config.networkAddress.ip
|
|
||||||
registerSuper.maskLen = UInt32(self.config.networkAddress.maskLen)
|
|
||||||
registerSuper.hostname = self.config.hostname
|
|
||||||
registerSuper.pubKey = self.rsaCipher.pubKey
|
|
||||||
registerSuper.accessToken = self.config.accessToken
|
|
||||||
|
|
||||||
if let registerSuperData = try? registerSuper.serializedData() {
|
|
||||||
SDLLogger.log("[SDLContext] will send register super", category: .super)
|
|
||||||
await self.onDecision(.sendSuper(type: .registerSuper, data: registerSuperData))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,181 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLDNSClient 2.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/9.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import Network
|
|
||||||
|
|
||||||
actor DNSCloudClient {
|
|
||||||
|
|
||||||
enum DNSCloudError: Error {
|
|
||||||
case failed(Error)
|
|
||||||
case cancelled
|
|
||||||
case sendFailed(Error)
|
|
||||||
case invalidData
|
|
||||||
}
|
|
||||||
|
|
||||||
private let queue = DispatchQueue(label: "com.sdl.DNSCloudClient.queue")
|
|
||||||
private let connection: NWConnection
|
|
||||||
|
|
||||||
// 用于对外输出收到的 DNS 响应包
|
|
||||||
nonisolated let packetFlow: AsyncThrowingStream<Data, Error>
|
|
||||||
private let packetContinuation: AsyncThrowingStream<Data, Error>.Continuation
|
|
||||||
|
|
||||||
private let readySignal = AsyncOneShot<Void>()
|
|
||||||
|
|
||||||
private var isStopped: Bool = false
|
|
||||||
private var isPacketContinuationFinished: Bool = false
|
|
||||||
|
|
||||||
/// - Parameter serverIP: 你的 sn-server IP 地址 (如 "8.8.8.8")
|
|
||||||
/// - Parameter port: 端口 (如 53)
|
|
||||||
init(serverIP: String, port: UInt16) {
|
|
||||||
let dnsServerAddress = NWEndpoint.hostPort(host: Self.makeEndpointHost(address: serverIP), port: NWEndpoint.Port(integerLiteral: port))
|
|
||||||
|
|
||||||
let packetPair = AsyncThrowingStream.makeStream(of: Data.self)
|
|
||||||
self.packetFlow = packetPair.stream
|
|
||||||
self.packetContinuation = packetPair.continuation
|
|
||||||
|
|
||||||
// 1. 配置参数:这是解决环路的关键
|
|
||||||
let parameters = NWParameters.udp
|
|
||||||
// 禁止此连接走 TUN 网卡(在 NE 中 TUN 通常被归类为 .other)
|
|
||||||
parameters.prohibitedInterfaceTypes = [.other]
|
|
||||||
// 2. 增强健壮性:启用多路径切换(替代 pathSelectionOptions 的意图)
|
|
||||||
parameters.multipathServiceType = .handover
|
|
||||||
|
|
||||||
// 2. 创建连接
|
|
||||||
self.connection = NWConnection(to: dnsServerAddress, using: parameters)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func makeEndpointHost(address ip: String) -> NWEndpoint.Host {
|
|
||||||
if let ipv4Address = IPv4Address(ip) {
|
|
||||||
return .ipv4(ipv4Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let ipv6Address = IPv6Address(ip) {
|
|
||||||
return .ipv6(ipv6Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
preconditionFailure("invalid DNS cloud server IP: \(ip)")
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
self.connection.stateUpdateHandler = { [weak self] state in
|
|
||||||
Task {
|
|
||||||
await self?.handleConnectionStateUpdate(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.connection.start(queue: self.queue)
|
|
||||||
|
|
||||||
try await withTaskCancellationHandler {
|
|
||||||
try await self.readySignal.wait()
|
|
||||||
|
|
||||||
while true {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
let data = try await self.readOnce()
|
|
||||||
self.packetContinuation.yield(data)
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
self.connection.cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 发送 DNS 查询包(由 TUN 拦截到的原始 IP 包数据)
|
|
||||||
func forward(ipPacketData: Data) async {
|
|
||||||
do {
|
|
||||||
try await self.readySignal.wait(timeout: .seconds(3))
|
|
||||||
} catch {
|
|
||||||
SDLLogger.log("[DNSCloudClient] drop query before ready: \(error)", category: .dns)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
guard !self.isStopped, connection.state == .ready else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
connection.send(content: ipPacketData, completion: .contentProcessed { [weak self] error in
|
|
||||||
if let error {
|
|
||||||
Task {
|
|
||||||
await self?.finishPacketContinuationIfNeed(throwing: .sendFailed(error))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
guard !self.isStopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
self.isStopped = true
|
|
||||||
|
|
||||||
self.connection.cancel()
|
|
||||||
await self.readySignal.fail(DNSCloudError.cancelled)
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: nil)
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLCloudClient] stopped", category: .dns)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleConnectionStateUpdate(_ state: NWConnection.State) async {
|
|
||||||
switch state {
|
|
||||||
case .ready:
|
|
||||||
guard !self.isStopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[DNSClient] Connection ready", category: .dns)
|
|
||||||
await self.readySignal.succeed(())
|
|
||||||
case .failed(let error):
|
|
||||||
await self.readySignal.fail(DNSCloudError.failed(error))
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: .failed(error))
|
|
||||||
case .cancelled:
|
|
||||||
await self.readySignal.fail(DNSCloudError.cancelled)
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: .cancelled)
|
|
||||||
default:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func finishPacketContinuationIfNeed(throwing error: DNSCloudError?) {
|
|
||||||
guard !self.isPacketContinuationFinished else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isPacketContinuationFinished = true
|
|
||||||
|
|
||||||
if let error {
|
|
||||||
self.packetContinuation.finish(throwing: error)
|
|
||||||
} else {
|
|
||||||
self.packetContinuation.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readOnce() async throws -> Data {
|
|
||||||
guard self.connection.state == .ready else {
|
|
||||||
throw DNSCloudError.cancelled
|
|
||||||
}
|
|
||||||
|
|
||||||
let readContinuation = OnceContinuation<Data, Error>()
|
|
||||||
return try await withTaskCancellationHandler {
|
|
||||||
try await withCheckedThrowingContinuation { cont in
|
|
||||||
readContinuation.set(cont)
|
|
||||||
self.connection.receiveMessage { content, _, _, error in
|
|
||||||
if let error {
|
|
||||||
readContinuation.resume(throwing: error)
|
|
||||||
} else if let data = content, !data.isEmpty {
|
|
||||||
readContinuation.resume(returning: data)
|
|
||||||
} else {
|
|
||||||
readContinuation.resume(throwing: DNSCloudError.invalidData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
readContinuation.resume(throwing: CancellationError())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[DNSCloudClient] deinit", category: .dns)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,133 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
actor DNSCloudService {
|
|
||||||
private let serverIP: String
|
|
||||||
private var onEvent: DNSEventHandler = { _ in }
|
|
||||||
|
|
||||||
private var currentClient: DNSCloudClient?
|
|
||||||
private var isRunning = false
|
|
||||||
private var isStopping = false
|
|
||||||
private var needsImmediateRestart = false
|
|
||||||
private let retryDelay: Duration
|
|
||||||
|
|
||||||
init(serverIP: String, retryDelay: Duration = .seconds(5)) {
|
|
||||||
self.serverIP = serverIP
|
|
||||||
self.retryDelay = retryDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateEventHandler(_ onEvent: @escaping DNSEventHandler) {
|
|
||||||
self.onEvent = onEvent
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard !self.isRunning else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isRunning = true
|
|
||||||
self.isStopping = false
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.isRunning = false
|
|
||||||
self.currentClient = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
while !Task.isCancelled, !self.isStopping {
|
|
||||||
let client = DNSCloudClient(serverIP: self.serverIP, port: 15353)
|
|
||||||
self.currentClient = client
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await self.run(client: client)
|
|
||||||
self.clearCurrent(client)
|
|
||||||
await client.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[DNSCloudService] dnsCloudClient ended, will restart", category: .dns)
|
|
||||||
} catch is CancellationError {
|
|
||||||
self.clearCurrent(client)
|
|
||||||
await client.stop()
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
self.clearCurrent(client)
|
|
||||||
await client.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[DNSCloudService] dnsCloudClient failed: \(error.localizedDescription), will restart", category: .dns)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.consumeImmediateRestartRequest() {
|
|
||||||
SDLLogger.log("[DNSCloudService] dnsCloudClient invalidated after wakeup, will restart immediately", category: .dns)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
try await Task.sleep(for: self.retryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
self.isStopping = true
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
await self.invalidateCurrentClient()
|
|
||||||
}
|
|
||||||
|
|
||||||
func recoverAfterWake() async {
|
|
||||||
guard !self.isStopping else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.needsImmediateRestart = self.currentClient != nil
|
|
||||||
await self.invalidateCurrentClient()
|
|
||||||
}
|
|
||||||
|
|
||||||
func forward(ipPacketData: Data) async {
|
|
||||||
await self.currentClient?.forward(ipPacketData: ipPacketData)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func clearCurrent(_ client: DNSCloudClient) {
|
|
||||||
if self.currentClient === client {
|
|
||||||
self.currentClient = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func invalidateCurrentClient() async {
|
|
||||||
let client = self.currentClient
|
|
||||||
self.currentClient = nil
|
|
||||||
|
|
||||||
await client?.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func consumeImmediateRestartRequest() -> Bool {
|
|
||||||
let needsImmediateRestart = self.needsImmediateRestart
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
return needsImmediateRestart
|
|
||||||
}
|
|
||||||
|
|
||||||
private func run(client: DNSCloudClient) async throws {
|
|
||||||
let onEvent = self.onEvent
|
|
||||||
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await client.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
for try await packet in client.packetFlow {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
await onEvent(.packet(packet))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = try await group.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
enum DNSEvent {
|
|
||||||
case packet(Data)
|
|
||||||
}
|
|
||||||
|
|
||||||
typealias DNSEventHandler = @Sendable (DNSEvent) async -> Void
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
//
|
|
||||||
// Helper.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/10.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
struct DNSHelper {
|
|
||||||
static let dnsServer: String = "100.100.100.100"
|
|
||||||
// dns请求包的目标地址
|
|
||||||
static let dnsDestIpAddr: UInt32 = 1684300900
|
|
||||||
|
|
||||||
// 判断是否是dns请求的数据包
|
|
||||||
static func isDnsRequestPacket(ipPacket: IPPacketView) -> Bool {
|
|
||||||
return ipPacket.header.destination == dnsDestIpAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,345 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import Network
|
|
||||||
|
|
||||||
actor DNSLocalClient {
|
|
||||||
|
|
||||||
struct DNSTracker {
|
|
||||||
let transactionID: UInt16
|
|
||||||
let clientIP: UInt32
|
|
||||||
let clientPort: UInt16
|
|
||||||
let createdAt: Date
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct PendingRequest {
|
|
||||||
let tracker: DNSTracker
|
|
||||||
}
|
|
||||||
|
|
||||||
enum DNSLocalError: Error {
|
|
||||||
case failed(Error)
|
|
||||||
case cancelled
|
|
||||||
case sendFailed(Error)
|
|
||||||
case invalidData
|
|
||||||
}
|
|
||||||
|
|
||||||
private let queue = DispatchQueue(label: "com.sdl.DNSCloudClient.queue")
|
|
||||||
private let connection: NWConnection
|
|
||||||
|
|
||||||
private let timeoutInterval: TimeInterval = 3.0
|
|
||||||
|
|
||||||
nonisolated let packetFlow: AsyncThrowingStream<Data, Error>
|
|
||||||
private let packetContinuation: AsyncThrowingStream<Data, Error>.Continuation
|
|
||||||
private var isPacketContinuationFinished: Bool = false
|
|
||||||
|
|
||||||
private var pendingRequests: [UInt16: PendingRequest] = [:]
|
|
||||||
private var nextTransactionID: UInt16 = 1
|
|
||||||
|
|
||||||
private let readySignal = AsyncOneShot<Void>()
|
|
||||||
private var isStopped: Bool = false
|
|
||||||
|
|
||||||
init(host: String) {
|
|
||||||
let dnsServerEndpoint = NWEndpoint.hostPort(host: Self.makeEndpointHost(ip: host), port: 53)
|
|
||||||
|
|
||||||
let (stream, continuation) = AsyncThrowingStream.makeStream(of: Data.self, bufferingPolicy: .bufferingNewest(256))
|
|
||||||
self.packetFlow = stream
|
|
||||||
self.packetContinuation = continuation
|
|
||||||
|
|
||||||
self.packetContinuation.onTermination = { termination in
|
|
||||||
SDLLogger.log("[DNSLocalClient] packetFlow terminated: \(termination)", category: .dns)
|
|
||||||
}
|
|
||||||
|
|
||||||
let parameters = NWParameters.udp
|
|
||||||
parameters.prohibitedInterfaceTypes = [.other]
|
|
||||||
// 2. 增强健壮性:启用多路径切换(替代 pathSelectionOptions 的意图)
|
|
||||||
parameters.multipathServiceType = .handover
|
|
||||||
|
|
||||||
self.connection = NWConnection(to: dnsServerEndpoint, using: parameters)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func makeEndpointHost(ip: String) -> NWEndpoint.Host {
|
|
||||||
if let ipv4Address = IPv4Address(ip) {
|
|
||||||
return .ipv4(ipv4Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let ipv6Address = IPv6Address(ip) {
|
|
||||||
return .ipv6(ipv6Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
preconditionFailure("invalid public DNS server IP: \(ip)")
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
self.connection.stateUpdateHandler = { [weak self] state in
|
|
||||||
Task {
|
|
||||||
await self?.handleConnectionStateUpdate(state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.connection.start(queue: self.queue)
|
|
||||||
|
|
||||||
try await withTaskCancellationHandler {
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await self.readySignal.wait()
|
|
||||||
while true {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
let data = try await self.readOnce()
|
|
||||||
await self.handleResponse(data: data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
while !Task.isCancelled {
|
|
||||||
try await Task.sleep(for: .seconds(3))
|
|
||||||
await self.performCleanup()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try await group.next()
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
self.connection.cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func query(tracker: DNSTracker, dnsPayload: Data) async {
|
|
||||||
guard dnsPayload.count >= 2 else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await self.readySignal.wait(timeout: .seconds(3))
|
|
||||||
} catch {
|
|
||||||
SDLLogger.log("[DNSLocalClient] drop query before ready: \(error)", category: .dns)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
guard !self.isStopped, connection.state == .ready else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let allocatedTransactionID = self.allocateTransactionID() else {
|
|
||||||
SDLLogger.log("[DNSLocalClient] no available transaction id", category: .dns)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let transactionID = allocatedTransactionID
|
|
||||||
self.pendingRequests[transactionID] = PendingRequest(tracker: tracker)
|
|
||||||
let rewrittenPayload = Self.rewriteTransactionID(in: dnsPayload, to: transactionID)
|
|
||||||
|
|
||||||
connection.send(content: rewrittenPayload, completion: .contentProcessed { [weak self] error in
|
|
||||||
if let error {
|
|
||||||
Task {
|
|
||||||
await self?.handleSendFailure(transactionID: transactionID, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
guard !self.isStopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
self.isStopped = true
|
|
||||||
|
|
||||||
self.connection.cancel()
|
|
||||||
|
|
||||||
self.pendingRequests.removeAll()
|
|
||||||
self.nextTransactionID = 1
|
|
||||||
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: nil)
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLLocalClient] stopped", category: .dns)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleConnectionStateUpdate(_ state: NWConnection.State) async {
|
|
||||||
switch state {
|
|
||||||
case .ready:
|
|
||||||
guard !self.isStopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.readySignal.succeed(())
|
|
||||||
case .failed(let error):
|
|
||||||
await self.readySignal.fail(DNSLocalError.failed(error))
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: .failed(error))
|
|
||||||
case .cancelled:
|
|
||||||
await self.readySignal.fail(DNSLocalError.cancelled)
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: .cancelled)
|
|
||||||
default:
|
|
||||||
()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func finishPacketContinuationIfNeed(throwing error: DNSLocalError?) {
|
|
||||||
guard !self.isPacketContinuationFinished else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isPacketContinuationFinished = true
|
|
||||||
|
|
||||||
if let error {
|
|
||||||
self.packetContinuation.finish(throwing: error)
|
|
||||||
} else {
|
|
||||||
self.packetContinuation.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleResponse(data: Data) {
|
|
||||||
guard let rewrittenTransactionID = Self.readTransactionID(from: data),
|
|
||||||
let pendingRequest = self.pendingRequests.removeValue(forKey: rewrittenTransactionID) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let restoredPayload = Self.rewriteTransactionID(in: data, to: pendingRequest.tracker.transactionID)
|
|
||||||
|
|
||||||
let packet = Self.createDNSResponse(
|
|
||||||
payload: restoredPayload,
|
|
||||||
srcIP: DNSHelper.dnsDestIpAddr,
|
|
||||||
srcPort: 53,
|
|
||||||
destIP: pendingRequest.tracker.clientIP,
|
|
||||||
destPort: pendingRequest.tracker.clientPort
|
|
||||||
)
|
|
||||||
self.packetContinuation.yield(packet)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleSendFailure(transactionID: UInt16, error: NWError) {
|
|
||||||
self.pendingRequests.removeValue(forKey: transactionID)
|
|
||||||
self.finishPacketContinuationIfNeed(throwing: .sendFailed(error))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func performCleanup() {
|
|
||||||
let now = Date()
|
|
||||||
self.pendingRequests = self.pendingRequests.filter { _, request in
|
|
||||||
now.timeIntervalSince(request.tracker.createdAt) < self.timeoutInterval
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func allocateTransactionID() -> UInt16? {
|
|
||||||
var candidate = self.nextTransactionID == 0 ? 1 : self.nextTransactionID
|
|
||||||
let start = candidate
|
|
||||||
|
|
||||||
repeat {
|
|
||||||
if self.pendingRequests[candidate] == nil {
|
|
||||||
self.nextTransactionID = Self.nextTransactionID(after: candidate)
|
|
||||||
return candidate
|
|
||||||
}
|
|
||||||
|
|
||||||
candidate = Self.nextTransactionID(after: candidate)
|
|
||||||
} while candidate != start
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func nextTransactionID(after id: UInt16) -> UInt16 {
|
|
||||||
return id == UInt16.max ? 1 : id &+ 1
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func readTransactionID(from payload: Data) -> UInt16? {
|
|
||||||
guard payload.count >= 2 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return UInt16(payload[0]) << 8 | UInt16(payload[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func rewriteTransactionID(in payload: Data, to transactionID: UInt16) -> Data {
|
|
||||||
guard payload.count >= 2 else {
|
|
||||||
return payload
|
|
||||||
}
|
|
||||||
|
|
||||||
var rewrittenPayload = payload
|
|
||||||
rewrittenPayload[0] = UInt8((transactionID >> 8) & 0xFF)
|
|
||||||
rewrittenPayload[1] = UInt8(transactionID & 0xFF)
|
|
||||||
return rewrittenPayload
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readOnce() async throws -> Data {
|
|
||||||
guard self.connection.state == .ready else {
|
|
||||||
throw DNSLocalError.cancelled
|
|
||||||
}
|
|
||||||
|
|
||||||
let readContinuation = OnceContinuation<Data, Error>()
|
|
||||||
return try await withTaskCancellationHandler {
|
|
||||||
try await withCheckedThrowingContinuation { cont in
|
|
||||||
readContinuation.set(cont)
|
|
||||||
self.connection.receiveMessage { content, _, _, error in
|
|
||||||
if let error {
|
|
||||||
readContinuation.resume(throwing: error)
|
|
||||||
} else if let data = content, !data.isEmpty {
|
|
||||||
readContinuation.resume(returning: data)
|
|
||||||
} else {
|
|
||||||
readContinuation.resume(throwing: DNSLocalError.invalidData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
readContinuation.resume(throwing: CancellationError())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[DNSLocalClient] deinit", category: .dns)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension DNSLocalClient {
|
|
||||||
static func createDNSResponse(payload: Data, srcIP: UInt32, srcPort: UInt16, destIP: UInt32, destPort: UInt16) -> Data {
|
|
||||||
let udpLen = 8 + payload.count
|
|
||||||
let ipLen = 20 + udpLen
|
|
||||||
|
|
||||||
var ipHeader = Data(count: 20)
|
|
||||||
ipHeader[0] = 0x45
|
|
||||||
ipHeader[2...3] = withUnsafeBytes(of: UInt16(ipLen).bigEndian) { Data($0) }
|
|
||||||
ipHeader[8] = 64
|
|
||||||
ipHeader[9] = 17
|
|
||||||
|
|
||||||
ipHeader[12...15] = withUnsafeBytes(of: srcIP.bigEndian) { Data($0) }
|
|
||||||
ipHeader[16...19] = withUnsafeBytes(of: destIP.bigEndian) { Data($0) }
|
|
||||||
|
|
||||||
let ipChecksum = calculateChecksum(data: ipHeader)
|
|
||||||
ipHeader[10...11] = withUnsafeBytes(of: ipChecksum.bigEndian) { Data($0) }
|
|
||||||
|
|
||||||
var udpHeader = Data(count: 8)
|
|
||||||
udpHeader[0...1] = withUnsafeBytes(of: srcPort.bigEndian) { Data($0) }
|
|
||||||
udpHeader[2...3] = withUnsafeBytes(of: destPort.bigEndian) { Data($0) }
|
|
||||||
udpHeader[4...5] = withUnsafeBytes(of: UInt16(udpLen).bigEndian) { Data($0) }
|
|
||||||
udpHeader[6...7] = Data([0, 0])
|
|
||||||
|
|
||||||
var packet = Data(capacity: ipLen)
|
|
||||||
packet.append(ipHeader)
|
|
||||||
packet.append(udpHeader)
|
|
||||||
packet.append(payload)
|
|
||||||
|
|
||||||
return packet
|
|
||||||
}
|
|
||||||
|
|
||||||
static func calculateChecksum(data: Data) -> UInt16 {
|
|
||||||
var sum: UInt32 = 0
|
|
||||||
let count = data.count
|
|
||||||
|
|
||||||
data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) in
|
|
||||||
guard let baseAddress = ptr.baseAddress else { return }
|
|
||||||
|
|
||||||
let wordCount = count / 2
|
|
||||||
let words = baseAddress.bindMemory(to: UInt16.self, capacity: wordCount)
|
|
||||||
|
|
||||||
for i in 0..<wordCount {
|
|
||||||
sum += UInt32(UInt16(bigEndian: words[i]))
|
|
||||||
}
|
|
||||||
|
|
||||||
if count % 2 != 0 {
|
|
||||||
let lastByte = ptr[count - 1]
|
|
||||||
sum += UInt32(lastByte) << 8
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
while (sum >> 16) != 0 {
|
|
||||||
sum = (sum & 0xffff) + (sum >> 16)
|
|
||||||
}
|
|
||||||
|
|
||||||
return UInt16(~sum & 0xffff)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,136 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
actor DNSLocalService {
|
|
||||||
private let publicDnsServers: [String]
|
|
||||||
private var onEvent: DNSEventHandler = { _ in }
|
|
||||||
|
|
||||||
private var currentClient: DNSLocalClient?
|
|
||||||
private var isRunning = false
|
|
||||||
private var isStopping = false
|
|
||||||
private var needsImmediateRestart = false
|
|
||||||
private let retryDelay: Duration
|
|
||||||
|
|
||||||
init(publicDnsServers: [String], retryDelay: Duration = .seconds(5)) {
|
|
||||||
self.publicDnsServers = publicDnsServers
|
|
||||||
self.retryDelay = retryDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateEventHandler(_ onEvent: @escaping DNSEventHandler) {
|
|
||||||
self.onEvent = onEvent
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard !self.isRunning else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isRunning = true
|
|
||||||
self.isStopping = false
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.isRunning = false
|
|
||||||
self.currentClient = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
while !Task.isCancelled, !self.isStopping {
|
|
||||||
let dnsServer = self.publicDnsServers.randomElement() ?? "223.5.5.5"
|
|
||||||
let client = DNSLocalClient(host: dnsServer)
|
|
||||||
self.currentClient = client
|
|
||||||
|
|
||||||
SDLLogger.log("[DNSLocalService] dnsLocalClient started", category: .dns)
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await self.run(client: client)
|
|
||||||
self.clearCurrent(client)
|
|
||||||
await client.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[DNSLocalService] dnsLocalClient ended, will restart", category: .dns)
|
|
||||||
} catch is CancellationError {
|
|
||||||
self.clearCurrent(client)
|
|
||||||
await client.stop()
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
self.clearCurrent(client)
|
|
||||||
await client.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[DNSLocalService] dnsLocalClient failed: \(error.localizedDescription), will restart", category: .dns)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.consumeImmediateRestartRequest() {
|
|
||||||
SDLLogger.log("[DNSLocalService] dnsLocalClient invalidated after wakeup, will restart immediately", category: .dns)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
try await Task.sleep(for: self.retryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
self.isStopping = true
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
await self.invalidateCurrentClient()
|
|
||||||
}
|
|
||||||
|
|
||||||
func recoverAfterWake() async {
|
|
||||||
guard !self.isStopping else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.needsImmediateRestart = self.currentClient != nil
|
|
||||||
await self.invalidateCurrentClient()
|
|
||||||
}
|
|
||||||
|
|
||||||
func query(tracker: DNSLocalClient.DNSTracker, dnsPayload: Data) async {
|
|
||||||
await self.currentClient?.query(tracker: tracker, dnsPayload: dnsPayload)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func run(client: DNSLocalClient) async throws {
|
|
||||||
let onEvent = self.onEvent
|
|
||||||
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await client.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
for try await packet in client.packetFlow {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
await onEvent(.packet(packet))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = try await group.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func clearCurrent(_ client: DNSLocalClient) {
|
|
||||||
if self.currentClient === client {
|
|
||||||
self.currentClient = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func invalidateCurrentClient() async {
|
|
||||||
let client = self.currentClient
|
|
||||||
self.currentClient = nil
|
|
||||||
|
|
||||||
await client?.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func consumeImmediateRestartRequest() -> Bool {
|
|
||||||
let needsImmediateRestart = self.needsImmediateRestart
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
return needsImmediateRestart
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,246 +0,0 @@
|
|||||||
//
|
|
||||||
// DNSQuestion.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/10.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import Network
|
|
||||||
|
|
||||||
// MARK: - DNS 協議模型
|
|
||||||
struct DNSQuestion {
|
|
||||||
let name: String
|
|
||||||
let type: UInt16
|
|
||||||
let qclass: UInt16
|
|
||||||
}
|
|
||||||
|
|
||||||
struct DNSResourceRecord {
|
|
||||||
let name: String
|
|
||||||
let type: UInt16
|
|
||||||
let rclass: UInt16
|
|
||||||
let ttl: UInt32
|
|
||||||
let rdLength: UInt16
|
|
||||||
let rdata: Data
|
|
||||||
}
|
|
||||||
|
|
||||||
struct DNSMessage {
|
|
||||||
var transactionID: UInt16
|
|
||||||
var flags: UInt16
|
|
||||||
var questions: [DNSQuestion] = []
|
|
||||||
var answers: [DNSResourceRecord] = []
|
|
||||||
|
|
||||||
var isResponse: Bool {
|
|
||||||
(flags & 0x8000) != 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct DNSQuerySummary {
|
|
||||||
let transactionID: UInt16
|
|
||||||
let name: String
|
|
||||||
let type: UInt16
|
|
||||||
let qclass: UInt16
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - DNS 完整解析器
|
|
||||||
final class DNSParser {
|
|
||||||
private let data: Data
|
|
||||||
private var offset: Int = 0
|
|
||||||
|
|
||||||
init(data: Data, offset: Int) {
|
|
||||||
self.data = data
|
|
||||||
self.offset = offset
|
|
||||||
}
|
|
||||||
|
|
||||||
func parse() -> DNSMessage? {
|
|
||||||
guard data.count >= 12 + self.offset else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let id = readUInt16()
|
|
||||||
let flags = readUInt16()
|
|
||||||
let qdCount = readUInt16()
|
|
||||||
let anCount = readUInt16()
|
|
||||||
let _ = readUInt16() // NSCount
|
|
||||||
let _ = readUInt16() // ARCount
|
|
||||||
|
|
||||||
var message = DNSMessage(transactionID: id, flags: flags)
|
|
||||||
|
|
||||||
for _ in 0..<qdCount {
|
|
||||||
if let q = parseQuestion() {
|
|
||||||
message.questions.append(q)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _ in 0..<anCount {
|
|
||||||
if let rr = parseRR() {
|
|
||||||
message.answers.append(rr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return message
|
|
||||||
}
|
|
||||||
|
|
||||||
private func parseName() -> String {
|
|
||||||
var parts: [String] = []
|
|
||||||
var jumped = false
|
|
||||||
var nextOffset = 0
|
|
||||||
var currentOffset = self.offset
|
|
||||||
|
|
||||||
while currentOffset < data.count {
|
|
||||||
let length = Int(data[currentOffset])
|
|
||||||
if length == 0 {
|
|
||||||
currentOffset += 1
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if (length & 0xC0) == 0xC0 {
|
|
||||||
let pointer = Int(UInt16(data[currentOffset] & 0x3F) << 8 | UInt16(data[currentOffset + 1]))
|
|
||||||
if !jumped {
|
|
||||||
nextOffset = currentOffset + 2
|
|
||||||
jumped = true
|
|
||||||
}
|
|
||||||
currentOffset = pointer
|
|
||||||
} else {
|
|
||||||
currentOffset += 1
|
|
||||||
if let label = String(data: data.subdata(in: currentOffset..<currentOffset+length), encoding: .ascii) {
|
|
||||||
parts.append(label)
|
|
||||||
}
|
|
||||||
currentOffset += length
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.offset = jumped ? nextOffset : currentOffset
|
|
||||||
return parts.joined(separator: ".")
|
|
||||||
}
|
|
||||||
|
|
||||||
private func parseQuestion() -> DNSQuestion? {
|
|
||||||
let name = parseName()
|
|
||||||
return DNSQuestion(name: name, type: readUInt16(), qclass: readUInt16())
|
|
||||||
}
|
|
||||||
|
|
||||||
private func parseRR() -> DNSResourceRecord? {
|
|
||||||
let name = parseName()
|
|
||||||
let type = readUInt16()
|
|
||||||
let rclass = readUInt16()
|
|
||||||
let ttl = readUInt32()
|
|
||||||
let rdLength = readUInt16()
|
|
||||||
guard offset + Int(rdLength) <= data.count else { return nil }
|
|
||||||
let rdata = data.subdata(in: offset..<offset + Int(rdLength))
|
|
||||||
offset += Int(rdLength)
|
|
||||||
return DNSResourceRecord(name: name, type: type, rclass: rclass, ttl: ttl, rdLength: rdLength, rdata: rdata)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readUInt16() -> UInt16 {
|
|
||||||
guard offset + 2 <= data.count else { return 0 }
|
|
||||||
let val = UInt16(data[offset]) << 8 | UInt16(data[offset + 1])
|
|
||||||
offset += 2
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readUInt32() -> UInt32 {
|
|
||||||
guard offset + 4 <= data.count else { return 0 }
|
|
||||||
let val = UInt32(data[offset]) << 24 | UInt32(data[offset+1]) << 16 | UInt32(data[offset+2]) << 8 | UInt32(data[offset+3])
|
|
||||||
offset += 4
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension DNSParser {
|
|
||||||
static func parseFirstQuestion(data: Data, offset: Int) -> DNSQuerySummary? {
|
|
||||||
guard offset >= 0, data.count >= offset + 12 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return data.withUnsafeBytes { rawBuffer -> DNSQuerySummary? in
|
|
||||||
let bytes = rawBuffer.bindMemory(to: UInt8.self)
|
|
||||||
guard let baseAddress = bytes.baseAddress else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readUInt16(at index: Int) -> UInt16 {
|
|
||||||
UInt16(baseAddress[index]) << 8 | UInt16(baseAddress[index + 1])
|
|
||||||
}
|
|
||||||
|
|
||||||
let transactionID = readUInt16(at: offset)
|
|
||||||
let questionCount = readUInt16(at: offset + 4)
|
|
||||||
guard questionCount > 0 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var cursor = offset + 12
|
|
||||||
guard let name = parseName(
|
|
||||||
baseAddress: baseAddress,
|
|
||||||
count: data.count,
|
|
||||||
messageStart: offset,
|
|
||||||
cursor: &cursor
|
|
||||||
), cursor + 4 <= data.count else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return DNSQuerySummary(
|
|
||||||
transactionID: transactionID,
|
|
||||||
name: name,
|
|
||||||
type: readUInt16(at: cursor),
|
|
||||||
qclass: readUInt16(at: cursor + 2)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parseName(
|
|
||||||
baseAddress: UnsafePointer<UInt8>,
|
|
||||||
count: Int,
|
|
||||||
messageStart: Int,
|
|
||||||
cursor: inout Int
|
|
||||||
) -> String? {
|
|
||||||
var currentOffset = cursor
|
|
||||||
var resumeOffset: Int?
|
|
||||||
var jumpCount = 0
|
|
||||||
var name = ""
|
|
||||||
|
|
||||||
while currentOffset < count {
|
|
||||||
let length = Int(baseAddress[currentOffset])
|
|
||||||
|
|
||||||
if length == 0 {
|
|
||||||
currentOffset += 1
|
|
||||||
cursor = resumeOffset ?? currentOffset
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
|
|
||||||
if (length & 0xC0) == 0xC0 {
|
|
||||||
guard currentOffset + 1 < count else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let pointer = Int(UInt16(baseAddress[currentOffset] & 0x3F) << 8 | UInt16(baseAddress[currentOffset + 1]))
|
|
||||||
let targetOffset = messageStart + pointer
|
|
||||||
guard targetOffset < count, jumpCount < 8 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if resumeOffset == nil {
|
|
||||||
resumeOffset = currentOffset + 2
|
|
||||||
}
|
|
||||||
currentOffset = targetOffset
|
|
||||||
jumpCount += 1
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
guard (length & 0xC0) == 0, length <= 63 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let labelStart = currentOffset + 1
|
|
||||||
guard labelStart + length <= count else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !name.isEmpty {
|
|
||||||
name.append(".")
|
|
||||||
}
|
|
||||||
|
|
||||||
let labelBuffer = UnsafeBufferPointer(start: baseAddress.advanced(by: labelStart), count: length)
|
|
||||||
name.append(String(decoding: labelBuffer, as: UTF8.self))
|
|
||||||
currentOffset = labelStart + length
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,70 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLLogger.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2024/3/13.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import os
|
|
||||||
|
|
||||||
public final class SDLLogger: @unchecked Sendable {
|
|
||||||
|
|
||||||
public enum Category: String, CaseIterable {
|
|
||||||
case app
|
|
||||||
case context
|
|
||||||
case dns
|
|
||||||
case network
|
|
||||||
case packet
|
|
||||||
case policy
|
|
||||||
case session
|
|
||||||
case `super`
|
|
||||||
case udpHole
|
|
||||||
}
|
|
||||||
|
|
||||||
private static let subsystem = "com.jihe.punchnet.tun"
|
|
||||||
private static let loggers: [Category: SDLLogger] = {
|
|
||||||
Dictionary(uniqueKeysWithValues: Category.allCases.map { ($0, SDLLogger(category: $0)) })
|
|
||||||
}()
|
|
||||||
|
|
||||||
private let logger: Logger
|
|
||||||
|
|
||||||
private init(category: Category) {
|
|
||||||
self.logger = Logger(subsystem: Self.subsystem, category: category.rawValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func log(_ message: String) {
|
|
||||||
self.logger.info("\(message, privacy: .public)")
|
|
||||||
}
|
|
||||||
|
|
||||||
private func trace(_ message: String) {
|
|
||||||
self.logger.debug("\(message, privacy: .public)")
|
|
||||||
}
|
|
||||||
|
|
||||||
private func fatal(_ message: String) {
|
|
||||||
self.logger.fault("\(message, privacy: .public)")
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func log(_ message: @autoclosure () -> String, category: Category = .context) {
|
|
||||||
guard let logger = loggers[category] else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.log(message())
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func trace(_ message: @autoclosure () -> String, category: Category) {
|
|
||||||
guard let logger = loggers[category] else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.trace(message())
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func fatal(_ message: @autoclosure () -> String, category: Category = .context) {
|
|
||||||
guard let logger = loggers[category] else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.fatal(message())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,113 +0,0 @@
|
|||||||
//
|
|
||||||
// Util.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2024/1/19.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import SystemConfiguration
|
|
||||||
import Darwin
|
|
||||||
|
|
||||||
struct SDLUtil {
|
|
||||||
|
|
||||||
public static func int32ToIp(_ num: UInt32) -> String {
|
|
||||||
let ip0 = (UInt8) (num >> 24 & 0xFF)
|
|
||||||
let ip1 = (UInt8) (num >> 16 & 0xFF)
|
|
||||||
let ip2 = (UInt8) (num >> 8 & 0xFF)
|
|
||||||
let ip3 = (UInt8) (num & 0xFF)
|
|
||||||
|
|
||||||
return "\(ip0).\(ip1).\(ip2).\(ip3)"
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func netMaskIp(maskLen: UInt8) -> String {
|
|
||||||
let len0 = 32 - maskLen
|
|
||||||
let num: UInt32 = (0xFFFFFFFF >> len0) << len0
|
|
||||||
|
|
||||||
let ip0 = (UInt8) (num >> 24 & 0xFF)
|
|
||||||
let ip1 = (UInt8) (num >> 16 & 0xFF)
|
|
||||||
let ip2 = (UInt8) (num >> 8 & 0xFF)
|
|
||||||
let ip3 = (UInt8) (num & 0xFF)
|
|
||||||
|
|
||||||
return "\(ip0).\(ip1).\(ip2).\(ip3)"
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func ipv4StrToInt32(_ ip: String) -> UInt32? {
|
|
||||||
let parts = ip.split(separator: ".")
|
|
||||||
guard parts.count == 4 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var result: UInt32 = 0
|
|
||||||
for part in parts {
|
|
||||||
guard let byte = UInt8(part) else { return nil }
|
|
||||||
result = (result << 8) | UInt32(byte)
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func ipv6DataToString(_ data: Data) -> String? {
|
|
||||||
guard data.count == 16 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return data.withUnsafeBytes { rawBuffer in
|
|
||||||
guard let baseAddress = rawBuffer.baseAddress else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var hostBuffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
|
|
||||||
guard inet_ntop(AF_INET6, baseAddress, &hostBuffer, socklen_t(INET6_ADDRSTRLEN)) != nil else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return String(cString: hostBuffer)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func ipv6StrToData(_ ip: String) -> Data? {
|
|
||||||
let normalizedIp = String(ip.split(separator: "%", maxSplits: 1, omittingEmptySubsequences: false).first ?? "")
|
|
||||||
guard !normalizedIp.isEmpty else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var address = in6_addr()
|
|
||||||
guard inet_pton(AF_INET6, normalizedIp, &address) == 1 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return withUnsafeBytes(of: &address) { Data($0) }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 判断ip地址是否在同一个网络
|
|
||||||
public static func inSameNetwork(ip: UInt32, compareIp: UInt32, maskLen: UInt8) -> Bool {
|
|
||||||
if ip == compareIp {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
let len0 = 32 - maskLen
|
|
||||||
// 掩码值
|
|
||||||
let mask: UInt32 = (0xFFFFFFFF >> len0) << len0
|
|
||||||
|
|
||||||
return ip & mask == compareIp & mask
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func formatMacAddress(mac: Data) -> String {
|
|
||||||
let bytes = [UInt8](mac)
|
|
||||||
|
|
||||||
return bytes.map { String(format: "%02X", $0) }.joined(separator: ":").lowercased()
|
|
||||||
}
|
|
||||||
|
|
||||||
public static func getMacOSSystemDnsServers() -> [String] {
|
|
||||||
var results = [String]()
|
|
||||||
|
|
||||||
// 获取全局 DNS 配置
|
|
||||||
if let dict = SCDynamicStoreCopyValue(nil, "State:/Network/Global/DNS" as CFString) as? [String: Any] {
|
|
||||||
if let servers = dict["ServerAddresses"] as? [String] {
|
|
||||||
results = servers
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return results
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,208 +0,0 @@
|
|||||||
//
|
|
||||||
// PacketInboundActor.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/20.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NetworkExtension
|
|
||||||
|
|
||||||
actor PacketInboundActor {
|
|
||||||
private struct PolicyPacketContext {
|
|
||||||
let srcIdentityID: UInt32
|
|
||||||
let proto: UInt8
|
|
||||||
let srcIP: UInt32
|
|
||||||
let dstIP: UInt32
|
|
||||||
let srcPort: UInt16?
|
|
||||||
let dstPort: UInt16?
|
|
||||||
|
|
||||||
var logDescription: String {
|
|
||||||
let srcPort = self.srcPort.map(String.init) ?? "-"
|
|
||||||
let dstPort = self.dstPort.map(String.init) ?? "-"
|
|
||||||
return "srcIdentityID: \(self.srcIdentityID), proto: \(self.proto), srcIP: \(SDLUtil.int32ToIp(self.srcIP)), dstIP: \(SDLUtil.int32ToIp(self.dstIP)), srcPort: \(srcPort), dstPort: \(dstPort)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum ProcessingAction {
|
|
||||||
case sendARPReply(dstMac: Data, data: Data)
|
|
||||||
case appendARP(ip: UInt32, mac: Data)
|
|
||||||
case writeToTun(packetData: Data, identityID: UInt32)
|
|
||||||
case requestPolicy(PolicyPacketContext)
|
|
||||||
case dropByPolicy(PolicyPacketContext)
|
|
||||||
case none
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct ProcessingPlan {
|
|
||||||
let inboundBytes: Int
|
|
||||||
let action: ProcessingAction
|
|
||||||
}
|
|
||||||
|
|
||||||
private let provider: NEPacketTunnelProvider
|
|
||||||
private let policyService: PolicyService
|
|
||||||
private let packetOutboundActor: PacketOutboundActor
|
|
||||||
private let arpResolver: ArpResolver
|
|
||||||
private let superService: SDLSuperService
|
|
||||||
private let flowTracer: SDLFlowTracer
|
|
||||||
|
|
||||||
private var networkAddress: SDLConfiguration.NetworkAddress
|
|
||||||
private var identityId: UInt32
|
|
||||||
private var dataCipher: CCDataCipher?
|
|
||||||
|
|
||||||
init(provider: NEPacketTunnelProvider,
|
|
||||||
config: SDLConfiguration,
|
|
||||||
dataCipher: CCDataCipher?,
|
|
||||||
policyService: PolicyService,
|
|
||||||
packetOutboundActor: PacketOutboundActor,
|
|
||||||
arpResolver: ArpResolver,
|
|
||||||
superService: SDLSuperService,
|
|
||||||
flowTracer: SDLFlowTracer) {
|
|
||||||
self.provider = provider
|
|
||||||
self.networkAddress = config.networkAddress
|
|
||||||
self.identityId = config.identityId
|
|
||||||
self.dataCipher = dataCipher
|
|
||||||
self.policyService = policyService
|
|
||||||
self.packetOutboundActor = packetOutboundActor
|
|
||||||
self.arpResolver = arpResolver
|
|
||||||
self.superService = superService
|
|
||||||
self.flowTracer = flowTracer
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateRuntime(config: SDLConfiguration, dataCipher: CCDataCipher?) {
|
|
||||||
self.networkAddress = config.networkAddress
|
|
||||||
self.identityId = config.identityId
|
|
||||||
self.dataCipher = dataCipher
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleData(_ data: SDLData) async {
|
|
||||||
let policyRuntime = self.policyService.policyRuntime()
|
|
||||||
guard let plan = try? self.makeProcessingPlan(data: data, policyRuntime: policyRuntime) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.flowTracer.inc(num: plan.inboundBytes, type: .inbound)
|
|
||||||
|
|
||||||
switch plan.action {
|
|
||||||
case .sendARPReply(let dstMac, let responseData):
|
|
||||||
SDLLogger.log("[PacketInboundActor] get arp request packet", category: .packet)
|
|
||||||
await self.packetOutboundActor.routeLayerPacket(dstMac: dstMac, type: .arp, data: responseData)
|
|
||||||
case .appendARP(let ip, let mac):
|
|
||||||
SDLLogger.log("[PacketInboundActor] get arp response packet", category: .packet)
|
|
||||||
await self.arpResolver.append(ip: ip, mac: mac)
|
|
||||||
case .writeToTun(let packetData, let identityID):
|
|
||||||
let packet = NEPacket(data: packetData, protocolFamily: 2)
|
|
||||||
self.provider.packetFlow.writePacketObjects([packet])
|
|
||||||
SDLLogger.trace("[PacketInboundActor] hole identity: \(identityID), allow, data count: \(packetData.count)", category: .packet)
|
|
||||||
case .requestPolicy(let context):
|
|
||||||
SDLLogger.log("[PacketInboundActor] policy miss, \(context.logDescription)", category: .packet)
|
|
||||||
if let queryData = await self.policyService.makePolicyRequest(srcIdentityID: context.srcIdentityID) {
|
|
||||||
await self.superService.send(type: .policyRequest, data: queryData)
|
|
||||||
}
|
|
||||||
case .dropByPolicy(let context):
|
|
||||||
SDLLogger.trace("[PacketInboundActor] policy denied, \(context.logDescription)", category: .packet)
|
|
||||||
case .none:
|
|
||||||
()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeProcessingPlan(data: SDLData, policyRuntime: PolicyRuntime) throws -> ProcessingPlan? {
|
|
||||||
guard let dataCipher = self.dataCipher else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let mac = LayerPacket.MacAddress(data: data.dstMac)
|
|
||||||
guard (data.dstMac == self.networkAddress.mac || mac.isBroadcast() || mac.isMulticast()) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let decryptedData = try dataCipher.decrypt(cipherText: data.data)
|
|
||||||
let layerPacket = try LayerPacketView(layerData: decryptedData)
|
|
||||||
let inboundBytes = decryptedData.count
|
|
||||||
|
|
||||||
switch layerPacket.type {
|
|
||||||
case .arp:
|
|
||||||
return self.makeARPPlan(layerData: layerPacket.data, inboundBytes: inboundBytes)
|
|
||||||
case .ipv4:
|
|
||||||
return self.makeIPv4Plan(
|
|
||||||
layerData: layerPacket.data,
|
|
||||||
identityID: data.identityID,
|
|
||||||
inboundBytes: inboundBytes,
|
|
||||||
policyRuntime: policyRuntime
|
|
||||||
)
|
|
||||||
default:
|
|
||||||
SDLLogger.log("[SDLContext] get invalid packet", category: .packet)
|
|
||||||
return .init(inboundBytes: inboundBytes, action: .none)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeARPPlan(layerData: Data, inboundBytes: Int) -> ProcessingPlan {
|
|
||||||
if let arpPacket = ARPPacket(data: layerData) {
|
|
||||||
if arpPacket.targetIP == self.networkAddress.ip {
|
|
||||||
switch arpPacket.opcode {
|
|
||||||
case .request:
|
|
||||||
let response = ARPPacket.arpResponse(for: arpPacket, mac: self.networkAddress.mac, ip: self.networkAddress.ip)
|
|
||||||
return .init(
|
|
||||||
inboundBytes: inboundBytes,
|
|
||||||
action: .sendARPReply(dstMac: arpPacket.senderMAC, data: response.marshal())
|
|
||||||
)
|
|
||||||
case .response:
|
|
||||||
return .init(
|
|
||||||
inboundBytes: inboundBytes,
|
|
||||||
action: .appendARP(ip: arpPacket.senderIP, mac: arpPacket.senderMAC)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLContext] get invalid arp packet: \(arpPacket), target_ip: \(SDLUtil.int32ToIp(arpPacket.targetIP)), net ip: \(SDLUtil.int32ToIp(self.networkAddress.ip))", category: .packet)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLContext] get invalid arp packet", category: .packet)
|
|
||||||
}
|
|
||||||
|
|
||||||
return .init(inboundBytes: inboundBytes, action: .none)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeIPv4Plan(layerData: Data, identityID: UInt32, inboundBytes: Int, policyRuntime: PolicyRuntime) -> ProcessingPlan {
|
|
||||||
guard let ipPacket = IPPacketView(layerData) else {
|
|
||||||
return .init(inboundBytes: inboundBytes, action: .none)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch policyRuntime.evaluateInbound(srcIdentityID: identityID, ipPacket: ipPacket) {
|
|
||||||
case .allow:
|
|
||||||
return .init(
|
|
||||||
inboundBytes: inboundBytes,
|
|
||||||
action: .writeToTun(packetData: ipPacket.data, identityID: identityID)
|
|
||||||
)
|
|
||||||
case .deny:
|
|
||||||
return .init(
|
|
||||||
inboundBytes: inboundBytes,
|
|
||||||
action: .dropByPolicy(self.makePolicyPacketContext(identityID: identityID, ipPacket: ipPacket))
|
|
||||||
)
|
|
||||||
case .missingPolicy:
|
|
||||||
return .init(
|
|
||||||
inboundBytes: inboundBytes,
|
|
||||||
action: .requestPolicy(self.makePolicyPacketContext(identityID: identityID, ipPacket: ipPacket))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makePolicyPacketContext(identityID: UInt32, ipPacket: IPPacketView) -> PolicyPacketContext {
|
|
||||||
let ports: (UInt16?, UInt16?)
|
|
||||||
switch ipPacket.transportPacket {
|
|
||||||
case .tcp(let srcPort, let dstPort, _):
|
|
||||||
ports = (srcPort, dstPort)
|
|
||||||
case .udp(let srcPort, let dstPort, _):
|
|
||||||
ports = (srcPort, dstPort)
|
|
||||||
default:
|
|
||||||
ports = (nil, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
return PolicyPacketContext(
|
|
||||||
srcIdentityID: identityID,
|
|
||||||
proto: ipPacket.header.proto,
|
|
||||||
srcIP: ipPacket.header.source,
|
|
||||||
dstIP: ipPacket.header.destination,
|
|
||||||
srcPort: ports.0,
|
|
||||||
dstPort: ports.1
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,228 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLDNSClient 2.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/9.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import Network
|
|
||||||
|
|
||||||
enum SDLIPV6AssistError: Error {
|
|
||||||
case lostConnection
|
|
||||||
case requestTimeout
|
|
||||||
}
|
|
||||||
|
|
||||||
actor SDLIPV6AssistClient {
|
|
||||||
private struct PendingRequest {
|
|
||||||
let continuation: CheckedContinuation<SDLV6AssistProbeReply, Error>
|
|
||||||
let timeoutTask: Task<Void, Never>
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum State {
|
|
||||||
case idle
|
|
||||||
case running
|
|
||||||
case stopped
|
|
||||||
}
|
|
||||||
|
|
||||||
private var state: State = .idle
|
|
||||||
private var connection: NWConnection?
|
|
||||||
private let assistServerAddress: NWEndpoint
|
|
||||||
|
|
||||||
private var packetId: UInt32 = 1
|
|
||||||
private var pendingRequests: [UInt32: PendingRequest] = [:]
|
|
||||||
|
|
||||||
init?(assistServerInfo: SDLV6Info) {
|
|
||||||
guard assistServerInfo.port <= UInt32(UInt16.max),
|
|
||||||
let host = SDLUtil.ipv6DataToString(assistServerInfo.v6),
|
|
||||||
let address = IPv6Address(host) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
self.assistServerAddress = .hostPort(host: .ipv6(address), port: NWEndpoint.Port(integerLiteral: UInt16(assistServerInfo.port)))
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard case .idle = self.state else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.state = .running
|
|
||||||
|
|
||||||
// 1. 配置参数:这是解决环路的关键
|
|
||||||
let parameters = NWParameters.udp
|
|
||||||
|
|
||||||
// 禁止此连接走 TUN 网卡(在 NE 中 TUN 通常被归类为 .other)
|
|
||||||
parameters.prohibitedInterfaceTypes = [.other]
|
|
||||||
// 2. 增强健壮性:启用多路径切换(替代 pathSelectionOptions 的意图)
|
|
||||||
parameters.multipathServiceType = .handover
|
|
||||||
|
|
||||||
// 只允许走 IPv6,避免在 assist 通道上退回到 IPv4 或双栈协商。
|
|
||||||
if let ipOptions = parameters.defaultProtocolStack.internetProtocol as? NWProtocolIP.Options {
|
|
||||||
ipOptions.version = .v6
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 创建连接
|
|
||||||
let connection = NWConnection(to: self.assistServerAddress, using: parameters)
|
|
||||||
self.connection = connection
|
|
||||||
|
|
||||||
connection.stateUpdateHandler = { [weak self] state in
|
|
||||||
Task {
|
|
||||||
await self?.handleConnectionStateUpdate(state, for: connection)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 启动连接队列
|
|
||||||
connection.start(queue: .global())
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
let stream = Self.makeReceiveStream(for: connection)
|
|
||||||
try await withTaskCancellationHandler {
|
|
||||||
for await data in stream {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
self.handleReceivedPacket(data)
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
connection.cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 接收数据的递归循环
|
|
||||||
private static func makeReceiveStream(for connection: NWConnection) -> AsyncStream<Data> {
|
|
||||||
return AsyncStream(bufferingPolicy: .bufferingNewest(256)) { continuation in
|
|
||||||
func receiveNext() {
|
|
||||||
connection.receiveMessage { content, _, _, error in
|
|
||||||
if let data = content, !data.isEmpty {
|
|
||||||
// 将收到的 DNS 响应写回 AsyncStream
|
|
||||||
continuation.yield(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
if error == nil && connection.state == .ready {
|
|
||||||
receiveNext() // 继续监听下一个包
|
|
||||||
} else {
|
|
||||||
continuation.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
receiveNext()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func probe(requestTimeout: Duration = .seconds(5)) async throws -> SDLV6AssistProbeReply {
|
|
||||||
guard case .running = self.state, let connection = self.connection, connection.state == .ready else {
|
|
||||||
throw SDLIPV6AssistError.lostConnection
|
|
||||||
}
|
|
||||||
|
|
||||||
let pktId = self.nextPacketId()
|
|
||||||
var assistProbe = SDLV6AssistProbe()
|
|
||||||
assistProbe.pktID = pktId
|
|
||||||
let data = try assistProbe.serializedData()
|
|
||||||
|
|
||||||
return try await withCheckedThrowingContinuation { cont in
|
|
||||||
let timeoutTask = Task { [weak self] in
|
|
||||||
try? await Task.sleep(for: requestTimeout)
|
|
||||||
await self?.handleRequestTimeout(packetId: pktId)
|
|
||||||
}
|
|
||||||
|
|
||||||
self.pendingRequests[pktId] = .init(continuation: cont, timeoutTask: timeoutTask)
|
|
||||||
connection.send(content: data, completion: .contentProcessed { error in
|
|
||||||
if let error {
|
|
||||||
Task {
|
|
||||||
await self.handleProcessError(packetId: pktId, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleProcessError(packetId: UInt32, error: NWError) {
|
|
||||||
if let request = self.takePendingRequest(packetId: packetId) {
|
|
||||||
request.continuation.resume(throwing: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleRequestTimeout(packetId: UInt32) {
|
|
||||||
if let request = self.takePendingRequest(packetId: packetId) {
|
|
||||||
request.continuation.resume(throwing: SDLIPV6AssistError.requestTimeout)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
self.stop(pendingError: SDLIPV6AssistError.lostConnection)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func stop(pendingError: any Error) {
|
|
||||||
guard self.state != .stopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.state = .stopped
|
|
||||||
self.connection?.cancel()
|
|
||||||
self.connection = nil
|
|
||||||
self.failAllPendingRequests(error: pendingError)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleConnectionStateUpdate(_ state: NWConnection.State, for connection: NWConnection) {
|
|
||||||
guard case .running = self.state else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
switch state {
|
|
||||||
case .ready:
|
|
||||||
SDLLogger.log("[SDLIPV6AssistClient] Connection ready", category: .network)
|
|
||||||
case .failed(let error):
|
|
||||||
SDLLogger.log("[SDLIPV6AssistClient] Connection failed: \(error)", category: .network)
|
|
||||||
self.stop(pendingError: error)
|
|
||||||
case .cancelled:
|
|
||||||
self.stop()
|
|
||||||
default:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleReceivedPacket(_ data: Data) {
|
|
||||||
do {
|
|
||||||
let packet = try SDLV6AssistProbeReply(serializedBytes: data)
|
|
||||||
let pktId = packet.pktID
|
|
||||||
if let request = self.takePendingRequest(packetId: pktId) {
|
|
||||||
request.continuation.resume(returning: packet)
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
SDLLogger.log("[SDLIPV6AssistClient] Receive error: \(error)", category: .network)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func nextPacketId() -> UInt32 {
|
|
||||||
let packetId = self.packetId
|
|
||||||
self.packetId &+= 1
|
|
||||||
|
|
||||||
return packetId
|
|
||||||
}
|
|
||||||
|
|
||||||
private func takePendingRequest(packetId: UInt32) -> PendingRequest? {
|
|
||||||
guard let request = self.pendingRequests.removeValue(forKey: packetId) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
request.timeoutTask.cancel()
|
|
||||||
return request
|
|
||||||
}
|
|
||||||
|
|
||||||
private func failAllPendingRequests(error: any Error) {
|
|
||||||
let pendingRequests = self.pendingRequests
|
|
||||||
self.pendingRequests.removeAll()
|
|
||||||
|
|
||||||
pendingRequests.values.forEach { request in
|
|
||||||
request.timeoutTask.cancel()
|
|
||||||
request.continuation.resume(throwing: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
self.connection?.cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -14,7 +14,6 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
import Network
|
|
||||||
|
|
||||||
public struct NetworkInterface {
|
public struct NetworkInterface {
|
||||||
public let name: String
|
public let name: String
|
||||||
@ -73,68 +72,4 @@ public struct NetworkInterfaceManager {
|
|||||||
return interfaces
|
return interfaces
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取本地网卡中的公网IPv6地址
|
|
||||||
public static func getPublicIPv6Address() -> String? {
|
|
||||||
return self.getPublicIPv6Interface()?.ip
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取本地网卡中的公网IPv6网卡
|
|
||||||
public static func getPublicIPv6Interface() -> NetworkInterface? {
|
|
||||||
let interfaces = self.getInterfaces()
|
|
||||||
|
|
||||||
return interfaces.first { interface in
|
|
||||||
!interface.name.hasPrefix("utun")
|
|
||||||
&& self.isPublicIPv6(interface.ip)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 判断一个 IPv6 字符串是否是公网 IPv6
|
|
||||||
public static func isPublicIPv6(_ ipString: String) -> Bool {
|
|
||||||
let normalizedIp = String(ipString.split(separator: "%", maxSplits: 1, omittingEmptySubsequences: false).first ?? "")
|
|
||||||
guard let ipv6 = IPv6Address(normalizedIp) else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return self.isPublicIPv6(ipv6.rawValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 判断 16 字节 IPv6 地址是否是公网 IPv6
|
|
||||||
public static func isPublicIPv6(_ raw: Data) -> Bool {
|
|
||||||
guard raw.count == 16 else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
let bytes = [UInt8](raw)
|
|
||||||
|
|
||||||
// 1. 排除 unspecified ::
|
|
||||||
if bytes.allSatisfy({ $0 == 0 }) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 排除 loopback ::1
|
|
||||||
if bytes.dropLast().allSatisfy({ $0 == 0 }) && bytes[15] == 1 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 排除 multicast ff00::/8
|
|
||||||
if bytes[0] == 0xFF {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. 排除 link-local fe80::/10
|
|
||||||
// 即首字节 0xFE,第二字节前两位是 10(二进制)
|
|
||||||
if bytes[0] == 0xFE && (bytes[1] & 0xC0) == 0x80 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. 排除 ULA fc00::/7
|
|
||||||
// 即首字节前 7 位是 1111110
|
|
||||||
if (bytes[0] & 0xFE) == 0xFC {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// 6. 判断是否属于 2000::/3
|
|
||||||
// 即首字节前 3 位是 001
|
|
||||||
return (bytes[0] & 0xE0) == 0x20
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -1,143 +0,0 @@
|
|||||||
//
|
|
||||||
// IPPacket.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2024/1/18.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
enum IPVersion: UInt8 {
|
|
||||||
case ipv4 = 4
|
|
||||||
case ipv6 = 6
|
|
||||||
}
|
|
||||||
|
|
||||||
enum TransportProtocol: UInt8 {
|
|
||||||
case icmp = 1
|
|
||||||
case tcp = 6
|
|
||||||
case udp = 17
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - IP Header
|
|
||||||
|
|
||||||
struct IPHeader {
|
|
||||||
let version: UInt8
|
|
||||||
let headerLength: UInt8
|
|
||||||
let typeOfService: UInt8
|
|
||||||
let totalLength: UInt16
|
|
||||||
let id: UInt16
|
|
||||||
let offset: UInt16
|
|
||||||
let ttl: UInt8
|
|
||||||
let proto: UInt8
|
|
||||||
let checksum: UInt16
|
|
||||||
let source: UInt32
|
|
||||||
let destination: UInt32
|
|
||||||
|
|
||||||
var headerBytes: Int {
|
|
||||||
Int(headerLength)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TCPFlags: OptionSet {
|
|
||||||
let rawValue: UInt16
|
|
||||||
|
|
||||||
static let fin = TCPFlags(rawValue: 1 << 0)
|
|
||||||
static let syn = TCPFlags(rawValue: 1 << 1)
|
|
||||||
static let rst = TCPFlags(rawValue: 1 << 2)
|
|
||||||
static let psh = TCPFlags(rawValue: 1 << 3)
|
|
||||||
static let ack = TCPFlags(rawValue: 1 << 4)
|
|
||||||
static let urg = TCPFlags(rawValue: 1 << 5)
|
|
||||||
static let ece = TCPFlags(rawValue: 1 << 6)
|
|
||||||
static let cwr = TCPFlags(rawValue: 1 << 7)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Lightweight IP Packet View
|
|
||||||
|
|
||||||
struct IPPacketView {
|
|
||||||
let header: IPHeader
|
|
||||||
let data: Data
|
|
||||||
let transportPacket: TransportPacket
|
|
||||||
|
|
||||||
enum TransportPacket {
|
|
||||||
case tcp(srcPort: UInt16, dstPort: UInt16, flags: TCPFlags)
|
|
||||||
case udp(srcPort: UInt16, dstPort: UInt16, payloadOffset: Int)
|
|
||||||
case icmp
|
|
||||||
case unsupported(UInt8)
|
|
||||||
case malformed
|
|
||||||
}
|
|
||||||
|
|
||||||
init?(_ data: Data) {
|
|
||||||
guard data.count >= 20 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let firstByte = Self.byte(at: 0, in: data)
|
|
||||||
let version = firstByte >> 4
|
|
||||||
let headerLen = (firstByte & 0x0F) * 4
|
|
||||||
|
|
||||||
guard headerLen >= 20, data.count >= headerLen else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let proto = Self.byte(at: 9, in: data)
|
|
||||||
self.header = IPHeader(
|
|
||||||
version: version,
|
|
||||||
headerLength: headerLen,
|
|
||||||
typeOfService: Self.byte(at: 1, in: data),
|
|
||||||
totalLength: UInt16(bytes: (Self.byte(at: 2, in: data), Self.byte(at: 3, in: data))),
|
|
||||||
id: UInt16(bytes: (Self.byte(at: 4, in: data), Self.byte(at: 5, in: data))),
|
|
||||||
offset: UInt16(bytes: (Self.byte(at: 6, in: data), Self.byte(at: 7, in: data))),
|
|
||||||
ttl: Self.byte(at: 8, in: data),
|
|
||||||
proto: proto,
|
|
||||||
checksum: UInt16(bytes: (Self.byte(at: 10, in: data), Self.byte(at: 11, in: data))),
|
|
||||||
source: UInt32(bytes: (Self.byte(at: 12, in: data), Self.byte(at: 13, in: data), Self.byte(at: 14, in: data), Self.byte(at: 15, in: data))),
|
|
||||||
destination: UInt32(bytes: (Self.byte(at: 16, in: data), Self.byte(at: 17, in: data), Self.byte(at: 18, in: data), Self.byte(at: 19, in: data)))
|
|
||||||
)
|
|
||||||
|
|
||||||
self.data = data
|
|
||||||
self.transportPacket = Self.parseTransportPacket(proto: proto, offset: Int(headerLen), data: data)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parseTransportPacket(proto: UInt8, offset: Int, data: Data) -> TransportPacket {
|
|
||||||
guard let proto = TransportProtocol(rawValue: proto) else {
|
|
||||||
return .unsupported(proto)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch proto {
|
|
||||||
case .tcp:
|
|
||||||
guard data.count >= offset + 20 else {
|
|
||||||
return .malformed
|
|
||||||
}
|
|
||||||
let offsetAndFlags = UInt16(bytes: (Self.byte(at: offset + 12, in: data), Self.byte(at: offset + 13, in: data)))
|
|
||||||
let dataOffset = Int(offsetAndFlags >> 12) * 4
|
|
||||||
guard dataOffset >= 20, data.count >= offset + dataOffset else {
|
|
||||||
return .malformed
|
|
||||||
}
|
|
||||||
return .tcp(
|
|
||||||
srcPort: UInt16(bytes: (Self.byte(at: offset, in: data), Self.byte(at: offset + 1, in: data))),
|
|
||||||
dstPort: UInt16(bytes: (Self.byte(at: offset + 2, in: data), Self.byte(at: offset + 3, in: data))),
|
|
||||||
flags: TCPFlags(rawValue: offsetAndFlags & 0x01FF)
|
|
||||||
)
|
|
||||||
|
|
||||||
case .udp:
|
|
||||||
guard data.count >= offset + 8 else {
|
|
||||||
return .malformed
|
|
||||||
}
|
|
||||||
return .udp(
|
|
||||||
srcPort: UInt16(bytes: (Self.byte(at: offset, in: data), Self.byte(at: offset + 1, in: data))),
|
|
||||||
dstPort: UInt16(bytes: (Self.byte(at: offset + 2, in: data), Self.byte(at: offset + 3, in: data))),
|
|
||||||
payloadOffset: offset + 8
|
|
||||||
)
|
|
||||||
|
|
||||||
case .icmp:
|
|
||||||
guard data.count >= offset + 4 else {
|
|
||||||
return .malformed
|
|
||||||
}
|
|
||||||
return .icmp
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func byte(at offset: Int, in data: Data) -> UInt8 {
|
|
||||||
data[data.index(data.startIndex, offsetBy: offset)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,51 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLTunnelAppNotifier.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/15.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class SDLTunnelAppNotifier {
|
|
||||||
static let shared = SDLTunnelAppNotifier()
|
|
||||||
|
|
||||||
private let suiteName: String
|
|
||||||
private let eventKey: String
|
|
||||||
|
|
||||||
init(suiteName: String = SDLNotificationCenter.Configuration.appGroupSuiteName,
|
|
||||||
eventKey: String = SDLNotificationCenter.Configuration.latestEventKey) {
|
|
||||||
self.suiteName = suiteName
|
|
||||||
self.eventKey = eventKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func publish(code: Int? = nil, message: String) {
|
|
||||||
var event = TunnelEvent()
|
|
||||||
event.id = UUID().uuidString
|
|
||||||
event.timestampMs = UInt64(Date().timeIntervalSince1970 * 1000)
|
|
||||||
event.code = Int32(clamping: code ?? 0)
|
|
||||||
event.message = message
|
|
||||||
self.publish(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
func publish(_ event: TunnelEvent) {
|
|
||||||
guard let shared = UserDefaults(suiteName: self.suiteName),
|
|
||||||
let data = try? event.serializedData() else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
shared.set(data, forKey: self.eventKey)
|
|
||||||
shared.synchronize()
|
|
||||||
SDLNotificationCenter.shared.post(.tunnelEventChanged)
|
|
||||||
}
|
|
||||||
|
|
||||||
func clear() {
|
|
||||||
guard let shared = UserDefaults(suiteName: self.suiteName) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
shared.removeObject(forKey: self.eventKey)
|
|
||||||
shared.synchronize()
|
|
||||||
SDLNotificationCenter.shared.post(.tunnelEventChanged)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,249 +0,0 @@
|
|||||||
//
|
|
||||||
// PacketOutboundActor.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/20.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NetworkExtension
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor PacketOutboundActor {
|
|
||||||
private typealias PacketReadResult = (packets: [Data], protocols: [NSNumber])?
|
|
||||||
|
|
||||||
private enum DeliveryPlan {
|
|
||||||
case superNode(payload: Data)
|
|
||||||
case peer(payload: Data, session: Session)
|
|
||||||
case superNodeAndPunch(payload: Data, request: SDLPuncherActor.RegisterRequest)
|
|
||||||
}
|
|
||||||
|
|
||||||
private let provider: NEPacketTunnelProvider
|
|
||||||
private let sessionManager: SessionManager
|
|
||||||
private let arpResolver: ArpResolver
|
|
||||||
private let puncherActor: SDLPuncherActor
|
|
||||||
private let policyService: PolicyService
|
|
||||||
private let superService: SDLSuperService
|
|
||||||
private let udpHoleService: SDLUDPHoleService
|
|
||||||
private let udpHoleV6Service: SDLUDPHoleV6Service
|
|
||||||
private let dnsCloudService: DNSCloudService
|
|
||||||
private let dnsLocalService: DNSLocalService
|
|
||||||
private let flowTracer: SDLFlowTracer
|
|
||||||
|
|
||||||
private var networkAddress: SDLConfiguration.NetworkAddress
|
|
||||||
private var identityId: UInt32
|
|
||||||
private var exitNode: SDLConfiguration.ExitNode?
|
|
||||||
private var stunSocketAddress: SocketAddress
|
|
||||||
private var dataCipher: CCDataCipher?
|
|
||||||
|
|
||||||
init(provider: NEPacketTunnelProvider,
|
|
||||||
config: SDLConfiguration,
|
|
||||||
dataCipher: CCDataCipher?,
|
|
||||||
sessionManager: SessionManager,
|
|
||||||
arpResolver: ArpResolver,
|
|
||||||
puncherActor: SDLPuncherActor,
|
|
||||||
policyService: PolicyService,
|
|
||||||
superService: SDLSuperService,
|
|
||||||
udpHoleService: SDLUDPHoleService,
|
|
||||||
udpHoleV6Service: SDLUDPHoleV6Service,
|
|
||||||
dnsCloudService: DNSCloudService,
|
|
||||||
dnsLocalService: DNSLocalService,
|
|
||||||
flowTracer: SDLFlowTracer) {
|
|
||||||
self.provider = provider
|
|
||||||
self.networkAddress = config.networkAddress
|
|
||||||
self.identityId = config.identityId
|
|
||||||
self.exitNode = config.exitNode
|
|
||||||
self.stunSocketAddress = config.stunSocketAddress
|
|
||||||
self.dataCipher = dataCipher
|
|
||||||
self.sessionManager = sessionManager
|
|
||||||
self.arpResolver = arpResolver
|
|
||||||
self.puncherActor = puncherActor
|
|
||||||
self.policyService = policyService
|
|
||||||
self.superService = superService
|
|
||||||
self.udpHoleService = udpHoleService
|
|
||||||
self.udpHoleV6Service = udpHoleV6Service
|
|
||||||
self.dnsCloudService = dnsCloudService
|
|
||||||
self.dnsLocalService = dnsLocalService
|
|
||||||
self.flowTracer = flowTracer
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateRuntime(config: SDLConfiguration, dataCipher: CCDataCipher?) {
|
|
||||||
self.networkAddress = config.networkAddress
|
|
||||||
self.identityId = config.identityId
|
|
||||||
self.exitNode = config.exitNode
|
|
||||||
self.stunSocketAddress = config.stunSocketAddress
|
|
||||||
self.dataCipher = dataCipher
|
|
||||||
}
|
|
||||||
|
|
||||||
func runPacketReader() async throws {
|
|
||||||
let provider = self.provider
|
|
||||||
|
|
||||||
while !Task.isCancelled {
|
|
||||||
guard let batch = await Self.readPackets(from: provider) else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
try Task.checkCancellation()
|
|
||||||
|
|
||||||
for (data, number) in zip(batch.packets, batch.protocols) where number.int32Value == 2 {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
|
|
||||||
if let packet = IPPacketView(data) {
|
|
||||||
await self.handleTunPacket(packet)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[PacketOutboundActor] packet reader task finished", category: .packet)
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleTunPacket(_ packet: IPPacketView) async {
|
|
||||||
let router = PacketOutboundRouter(networkAddress: self.networkAddress, exitNode: self.exitNode)
|
|
||||||
let decision = router.route(packet: packet)
|
|
||||||
|
|
||||||
switch decision {
|
|
||||||
case .loopback(let ipPacketData):
|
|
||||||
let nePacket = NEPacket(data: ipPacketData, protocolFamily: 2)
|
|
||||||
self.provider.packetFlow.writePacketObjects([nePacket])
|
|
||||||
case .cloudDNS(let name, let ipPacketData):
|
|
||||||
SDLLogger.log("[PacketOutboundActor] get cloud dns request: \(name)", category: .packet)
|
|
||||||
await self.dnsCloudService.forward(ipPacketData: ipPacketData)
|
|
||||||
case .localDNS(let name, let payload, let tracker):
|
|
||||||
SDLLogger.log("[PacketOutboundActor] get local dns request: \(name)", category: .packet)
|
|
||||||
await self.dnsLocalService.query(tracker: tracker, dnsPayload: payload)
|
|
||||||
case .forwardToNextHop(let ip, let type, let data, let kind):
|
|
||||||
await self.forwardPacketToNextHop(ip: ip, type: type, data: data, kind: kind, originalPacket: packet)
|
|
||||||
case .drop(let reason):
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] drop tun packet, reason: \(reason.rawValue)", category: .packet)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func forwardPacketToNextHop(ip: UInt32,
|
|
||||||
type: LayerPacket.PacketType,
|
|
||||||
data: Data,
|
|
||||||
kind: PacketOutboundRouter.ForwardKind,
|
|
||||||
originalPacket: IPPacketView) async {
|
|
||||||
switch kind {
|
|
||||||
case .sameNetwork:
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] dstIp: \(SDLUtil.int32ToIp(ip)) same network", category: .packet)
|
|
||||||
case .exitNode, .dnsExitNode:
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] use exit_node: \(SDLUtil.int32ToIp(ip))", category: .packet)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let dstMac = self.arpResolver.snapshot().lookup(ip) {
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] dstIp: \(SDLUtil.int32ToIp(ip)), dst_mac is: \(SDLUtil.formatMacAddress(mac: dstMac))", category: .packet)
|
|
||||||
let didSend = await self.routeLayerPacket(dstMac: dstMac, type: type, data: data)
|
|
||||||
if didSend {
|
|
||||||
self.policyService.recordOutboundFlow(ipPacket: originalPacket)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] dstIp: \(SDLUtil.int32ToIp(ip)) arp query not found, broadcast", category: .packet)
|
|
||||||
if let arpRequest = try? await self.arpResolver.makeArpRequest(targetIp: ip) {
|
|
||||||
await self.superService.send(type: .arpRequest, data: arpRequest)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@discardableResult
|
|
||||||
func routeLayerPacket(dstMac: Data, type: LayerPacket.PacketType, data: Data) async -> Bool {
|
|
||||||
guard let plan = try? self.makeDeliveryPlan(dstMac: dstMac, type: type, data: data) else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch plan {
|
|
||||||
case .superNode(let payload):
|
|
||||||
await self.sendSuperPacket(type: .data, data: payload)
|
|
||||||
case .peer(let payload, let session):
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] send packet by session: \(session)", category: .packet)
|
|
||||||
await self.sendPeerPacket(type: .data, data: payload, remoteAddress: session.natAddress)
|
|
||||||
self.flowTracer.inc(num: payload.count, type: .p2p)
|
|
||||||
case .superNodeAndPunch(let payload, let request):
|
|
||||||
await self.sendSuperPacket(type: .data, data: payload)
|
|
||||||
SDLLogger.trace("[PacketOutboundActor] send packet by super: \(self.stunSocketAddress)", category: .packet)
|
|
||||||
self.flowTracer.inc(num: payload.count, type: .forward)
|
|
||||||
|
|
||||||
if let queryData = await self.puncherActor.makeQueryInfoRequest(request: request) {
|
|
||||||
await self.superService.send(type: .queryInfo, data: queryData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func readPackets(from provider: NEPacketTunnelProvider) async -> PacketReadResult {
|
|
||||||
let readContinuation = OnceContinuation<PacketReadResult, Never>()
|
|
||||||
|
|
||||||
return await withTaskCancellationHandler {
|
|
||||||
await withCheckedContinuation { continuation in
|
|
||||||
readContinuation.set(continuation)
|
|
||||||
provider.packetFlow.readPackets { packets, protocols in
|
|
||||||
readContinuation.resume(returning: (packets: packets, protocols: protocols))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
readContinuation.resume(returning: nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeDeliveryPlan(dstMac: Data, type: LayerPacket.PacketType, data: Data) throws -> DeliveryPlan? {
|
|
||||||
guard let payload = try self.makeDataPayload(dstMac: dstMac, type: type, data: data) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if ARPPacket.isBroadcastMac(dstMac) {
|
|
||||||
return .superNode(payload: payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let session = self.sessionManager.snapshot().getSession(toAddress: dstMac) {
|
|
||||||
return .peer(payload: payload, session: session)
|
|
||||||
}
|
|
||||||
|
|
||||||
return .superNodeAndPunch(
|
|
||||||
payload: payload,
|
|
||||||
request: .init(
|
|
||||||
srcMac: self.networkAddress.mac,
|
|
||||||
dstMac: dstMac,
|
|
||||||
networkId: self.networkAddress.networkId
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeDataPayload(dstMac: Data, type: LayerPacket.PacketType, data: Data) throws -> Data? {
|
|
||||||
guard let dataCipher = self.dataCipher else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let layerPacket = LayerPacket(dstMac: dstMac, srcMac: self.networkAddress.mac, type: type, data: data)
|
|
||||||
let encodedPacket = try dataCipher.encrypt(plainText: layerPacket.marshal())
|
|
||||||
|
|
||||||
var dataPacket = SDLData()
|
|
||||||
dataPacket.networkID = self.networkAddress.networkId
|
|
||||||
dataPacket.srcMac = self.networkAddress.mac
|
|
||||||
dataPacket.dstMac = dstMac
|
|
||||||
dataPacket.ttl = 255
|
|
||||||
dataPacket.identityID = self.identityId
|
|
||||||
dataPacket.isP2P = true
|
|
||||||
dataPacket.data = encodedPacket
|
|
||||||
|
|
||||||
return try dataPacket.serializedData()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func sendSuperPacket(type: SDLPacketType, data: Data) async {
|
|
||||||
await self.sendPacket(type: type, data: data, remoteAddress: self.stunSocketAddress)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func sendPeerPacket(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) async {
|
|
||||||
await self.sendPacket(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func sendPacket(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) async {
|
|
||||||
switch remoteAddress {
|
|
||||||
case .v4:
|
|
||||||
await self.udpHoleService.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
case .v6:
|
|
||||||
await self.udpHoleV6Service.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
default:
|
|
||||||
SDLLogger.log("[PacketOutboundActor] unsupported socket family: \(remoteAddress)", category: .packet)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,93 +0,0 @@
|
|||||||
//
|
|
||||||
// PacketOutboundRouter.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/14.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
struct PacketOutboundRouter {
|
|
||||||
enum DropReason: String {
|
|
||||||
case invalidDNSRequest
|
|
||||||
case noRoute
|
|
||||||
}
|
|
||||||
|
|
||||||
enum ForwardKind {
|
|
||||||
case sameNetwork
|
|
||||||
case exitNode
|
|
||||||
case dnsExitNode
|
|
||||||
}
|
|
||||||
|
|
||||||
enum RouteDecision {
|
|
||||||
case loopback(ipPacketData: Data)
|
|
||||||
case cloudDNS(name: String, ipPacketData: Data)
|
|
||||||
case localDNS(name: String, payload: Data, tracker: DNSLocalClient.DNSTracker)
|
|
||||||
case forwardToNextHop(ip: UInt32, type: LayerPacket.PacketType, data: Data, kind: ForwardKind)
|
|
||||||
case drop(reason: DropReason)
|
|
||||||
}
|
|
||||||
|
|
||||||
let networkAddress: SDLConfiguration.NetworkAddress
|
|
||||||
let exitNode: SDLConfiguration.ExitNode?
|
|
||||||
|
|
||||||
func route(packet: IPPacketView, now: Date = Date()) -> RouteDecision {
|
|
||||||
let dstIp = packet.header.destination
|
|
||||||
|
|
||||||
// 本地通讯, 目标地址是本地服务器的ip地址
|
|
||||||
if dstIp == self.networkAddress.ip {
|
|
||||||
return .loopback(ipPacketData: packet.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理dns的解析
|
|
||||||
if let dnsDecision = self.routeDNS(packet: packet, now: now) {
|
|
||||||
return dnsDecision
|
|
||||||
}
|
|
||||||
|
|
||||||
// 判断目标地址是否和当前的网络地址是否在同一个网段
|
|
||||||
// 只有在同一个网段的ip数据才直接发送
|
|
||||||
if SDLUtil.inSameNetwork(ip: dstIp, compareIp: self.networkAddress.ip, maskLen: self.networkAddress.maskLen) {
|
|
||||||
return .forwardToNextHop(ip: dstIp, type: .ipv4, data: packet.data, kind: .sameNetwork)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 不在同一个网段的数据,看是否配置了网络出口, 如果配置了,转发数据个网络出口,否则丢弃
|
|
||||||
if let exitNode = self.exitNode {
|
|
||||||
return .forwardToNextHop(ip: exitNode.exitNodeIp, type: .ipv4, data: packet.data, kind: .exitNode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return .drop(reason: .noRoute)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func routeDNS(packet: IPPacketView, now: Date) -> RouteDecision? {
|
|
||||||
guard DNSHelper.isDnsRequestPacket(ipPacket: packet) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
guard case .udp(let srcPort, _, let payloadOffset) = packet.transportPacket else {
|
|
||||||
return .drop(reason: .invalidDNSRequest)
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let query = DNSParser.parseFirstQuestion(data: packet.data, offset: payloadOffset) else {
|
|
||||||
return .drop(reason: .invalidDNSRequest)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果是内部域名,则转发整个ip包的内容到云端服务器
|
|
||||||
if query.name.contains(self.networkAddress.networkDomain) {
|
|
||||||
return .cloudDNS(name: query.name, ipPacketData: packet.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果开启了出口节点,则转发给出口节点
|
|
||||||
if let exitNode = self.exitNode {
|
|
||||||
return .forwardToNextHop(ip: exitNode.exitNodeIp, type: .ipv4, data: packet.data, kind: .dnsExitNode)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 通过本地的dns解析,发送的是udp的payload部分
|
|
||||||
let dnsPayload = Data(packet.data[payloadOffset..<packet.data.count])
|
|
||||||
let tracker = DNSLocalClient.DNSTracker(
|
|
||||||
transactionID: query.transactionID,
|
|
||||||
clientIP: packet.header.source,
|
|
||||||
clientPort: srcPort,
|
|
||||||
createdAt: now
|
|
||||||
)
|
|
||||||
return .localDNS(name: query.name, payload: dnsPayload, tracker: tracker)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -5,100 +5,174 @@
|
|||||||
// Created by 安礼成 on 2025/8/3.
|
// Created by 安礼成 on 2025/8/3.
|
||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
//
|
||||||
|
// PacketTunnelProvider.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/1/17.
|
||||||
|
//
|
||||||
|
|
||||||
import NetworkExtension
|
import NetworkExtension
|
||||||
|
|
||||||
enum TunnelError: Error {
|
|
||||||
case invalidConfiguration
|
|
||||||
case invalidContext
|
|
||||||
}
|
|
||||||
|
|
||||||
class PacketTunnelProvider: NEPacketTunnelProvider {
|
class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||||
private lazy var contextBootstrap = SDLContextBootstrap(provider: self)
|
var context: SDLContext?
|
||||||
|
private var rootTask: Task<Void, Error>?
|
||||||
|
|
||||||
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
|
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
|
||||||
guard let options, let config = SDLConfiguration.parse(options: options) else {
|
// host: "192.168.0.101", port: 1265
|
||||||
SDLLogger.fatal("[PacketTunnelProvider] startTunnel failed: invalid configuration", category: .app)
|
guard let options else {
|
||||||
completionHandler(TunnelError.invalidConfiguration)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
// 如果当前在运行状态,不允许重复请求
|
||||||
let rsaCipher = try CCRSACipher(keySize: 1024)
|
guard self.context == nil else {
|
||||||
self.contextBootstrap.start(config: config, rsaCipher: rsaCipher, completionHandler: completionHandler)
|
return
|
||||||
} catch {
|
|
||||||
SDLLogger.fatal("[PacketTunnelProvider] startTunnel failed: rsa cipher initialization failed: \(error)", category: .app)
|
|
||||||
completionHandler(error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// let token = options["token"] as! String
|
||||||
|
let installed_channel = options["installed_channel"] as! String
|
||||||
|
let superIp = options["super_ip"] as! String
|
||||||
|
let superPort = options["super_port"] as! Int
|
||||||
|
let stunServersStr = options["stun_servers"] as! String
|
||||||
|
let noticePort = options["notice_port"] as! Int
|
||||||
|
let token = options["token"] as! String
|
||||||
|
let networkCode = options["network_code"] as! String
|
||||||
|
let clientId = options["client_id"] as! String
|
||||||
|
let remoteDnsServer = options["remote_dns_server"] as! String
|
||||||
|
let hostname = options["hostname"] as! String
|
||||||
|
|
||||||
|
let stunServers = stunServersStr.split(separator: ";").compactMap { server -> SDLConfiguration.StunServer? in
|
||||||
|
let parts = server.split(separator: ":", maxSplits: 2)
|
||||||
|
guard parts.count == 2 else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
let ports = parts[1].split(separator: ",", maxSplits: 2)
|
||||||
|
guard ports.count == 2, let port1 = Int(String(ports[0])), let port2 = Int(String(ports[1])) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return .init(host: String(parts[0]), ports: [port1, port2])
|
||||||
|
}
|
||||||
|
|
||||||
|
guard stunServers.count >= 2 else {
|
||||||
|
NSLog("stunServers配置错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
NSLog("[PacketTunnelProvider] client_id: \(clientId), token: \(token), network_code: \(networkCode)")
|
||||||
|
|
||||||
|
let config = SDLConfiguration(version: 1,
|
||||||
|
installedChannel: installed_channel,
|
||||||
|
superHost: superIp,
|
||||||
|
superPort: superPort,
|
||||||
|
stunServers: stunServers,
|
||||||
|
clientId: clientId,
|
||||||
|
noticePort: noticePort,
|
||||||
|
token: token,
|
||||||
|
networkCode: networkCode,
|
||||||
|
remoteDnsServer: remoteDnsServer,
|
||||||
|
hostname: hostname)
|
||||||
|
// 加密算法
|
||||||
|
let rsaCipher = try! CCRSACipher(keySize: 1024)
|
||||||
|
let aesChiper = CCAESChiper()
|
||||||
|
|
||||||
|
self.rootTask = Task {
|
||||||
|
do {
|
||||||
|
self.context = SDLContext(provider: self, config: config, rsaCipher: rsaCipher, aesCipher: aesChiper, logger: SDLLogger(level: .debug))
|
||||||
|
try await self.context?.start()
|
||||||
|
} catch let err {
|
||||||
|
NSLog("[PacketTunnelProvider] exit with error: \(err)")
|
||||||
|
exit(-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
completionHandler(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
||||||
SDLLogger.fatal("[PacketTunnelProvider] stopTunnel requested, reason: \(reason.rawValue)", category: .app)
|
// Add code here to start the process of stopping the tunnel.
|
||||||
self.contextBootstrap.stop(clearRuntimeConfiguration: true, completionHandler: completionHandler)
|
self.rootTask?.cancel()
|
||||||
|
Task {
|
||||||
|
await self.context?.stop()
|
||||||
|
}
|
||||||
|
self.context = nil
|
||||||
|
self.rootTask = nil
|
||||||
|
|
||||||
|
completionHandler()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
|
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
|
||||||
// Add code here to handle the message.
|
// Add code here to handle the message.
|
||||||
Task {
|
if let handler = completionHandler {
|
||||||
do {
|
handler(messageData)
|
||||||
let message = try AppRequest(serializedBytes: messageData)
|
|
||||||
let replyData = try await self.handleAppRequest(message: message)
|
|
||||||
completionHandler?(replyData)
|
|
||||||
} catch let err {
|
|
||||||
var reply = TunnelResponse()
|
|
||||||
reply.code = 1
|
|
||||||
reply.message = err.localizedDescription
|
|
||||||
|
|
||||||
let errorReplyData = try? reply.serializedData()
|
|
||||||
completionHandler?(errorReplyData)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override func sleep(completionHandler: @escaping () -> Void) {
|
override func sleep(completionHandler: @escaping () -> Void) {
|
||||||
SDLLogger.log("[PacketTunnelProvider] sleep requested", category: .app)
|
// Add code here to get ready to sleep.
|
||||||
completionHandler()
|
completionHandler()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func wake() {
|
override func wake() {
|
||||||
SDLLogger.log("[PacketTunnelProvider] wake up!!!!!!!", category: .app)
|
// Add code here to wake up.
|
||||||
self.contextBootstrap.recoverAfterWake { err in
|
}
|
||||||
if let err {
|
|
||||||
SDLLogger.fatal("[PacketTunnelProvider] wakeup recovery failed: \(err)", category: .app)
|
}
|
||||||
SDLLogger.log("[PacketTunnelProvider] wakeup recovery failed: \(err.localizedDescription)", category: .app)
|
|
||||||
|
// 获取物理网卡ip地址
|
||||||
|
extension PacketTunnelProvider {
|
||||||
|
|
||||||
|
public static var viaInterface: NetworkInterface? = {
|
||||||
|
let interfaces = NetworkInterfaceManager.getInterfaces()
|
||||||
|
|
||||||
|
return interfaces.first {$0.name == "en0"}
|
||||||
|
}()
|
||||||
|
|
||||||
|
struct CCRSACipher: RSACipher {
|
||||||
|
var pubKey: String
|
||||||
|
let privateKeyDER: Data
|
||||||
|
|
||||||
|
init(keySize: Int) throws {
|
||||||
|
let (privateKey, publicKey) = try Self.loadKeys(keySize: keySize)
|
||||||
|
let privKeyStr = SwKeyConvert.PrivateKey.derToPKCS1PEM(privateKey)
|
||||||
|
|
||||||
|
self.pubKey = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)
|
||||||
|
self.privateKeyDER = try SwKeyConvert.PrivateKey.pemToPKCS1DER(privKeyStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func decode(data: Data) throws -> Data {
|
||||||
|
let tag = Data()
|
||||||
|
let (decryptedData, _) = try CC.RSA.decrypt(data, derKey: self.privateKeyDER, tag: tag, padding: .pkcs1, digest: .none)
|
||||||
|
|
||||||
|
return decryptedData
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func loadKeys(keySize: Int) throws -> (Data, Data) {
|
||||||
|
if let privateKey = UserDefaults.standard.data(forKey: "privateKey"),
|
||||||
|
let publicKey = UserDefaults.standard.data(forKey: "publicKey") {
|
||||||
|
|
||||||
|
return (privateKey, publicKey)
|
||||||
} else {
|
} else {
|
||||||
SDLLogger.log("[PacketTunnelProvider] wakeup recovery completed", category: .app)
|
let (privateKey, publicKey) = try CC.RSA.generateKeyPair(keySize)
|
||||||
|
UserDefaults.standard.setValue(privateKey, forKey: "privateKey")
|
||||||
|
UserDefaults.standard.setValue(publicKey, forKey: "publicKey")
|
||||||
|
|
||||||
|
return (privateKey, publicKey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func handleAppRequest(message: AppRequest) async throws -> Data? {
|
struct CCAESChiper: AESCipher {
|
||||||
guard let contextActor = self.contextBootstrap.currentContextActor() else {
|
func decypt(aesKey: Data, data: Data) throws -> Data {
|
||||||
throw TunnelError.invalidContext
|
let ivData = Data(aesKey.prefix(16))
|
||||||
|
return try CC.crypt(.decrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: data, key: aesKey, iv: ivData)
|
||||||
}
|
}
|
||||||
|
|
||||||
switch message.command {
|
func encrypt(aesKey: Data, data: Data) throws -> Data {
|
||||||
case .changeExitNode(let changeExitNode):
|
let ivData = Data(aesKey.prefix(16))
|
||||||
let exitNodeIp = changeExitNode.ip
|
|
||||||
do {
|
|
||||||
try await contextActor.updateExitNode(exitNodeIp: exitNodeIp)
|
|
||||||
var reply = TunnelResponse()
|
|
||||||
reply.code = 0
|
|
||||||
reply.message = "操作成功"
|
|
||||||
return try reply.serializedData()
|
|
||||||
|
|
||||||
} catch let err {
|
return try CC.crypt(.encrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding, data: data, key: aesKey, iv: ivData)
|
||||||
var reply = TunnelResponse()
|
|
||||||
reply.code = 1
|
|
||||||
reply.message = err.localizedDescription
|
|
||||||
|
|
||||||
return try reply.serializedData()
|
|
||||||
}
|
|
||||||
case .none:
|
|
||||||
var reply = TunnelResponse()
|
|
||||||
reply.code = 1
|
|
||||||
reply.message = "无效请求"
|
|
||||||
return try reply.serializedData()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,223 +0,0 @@
|
|||||||
//
|
|
||||||
// FlowSessionTable.swift
|
|
||||||
// punchnet
|
|
||||||
// tcp/udp Flow流管理
|
|
||||||
// Created by 安礼成 on 2026/3/10.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
// MARK: - 五元组 key
|
|
||||||
struct FlowSession: Hashable {
|
|
||||||
let srcIP: UInt32
|
|
||||||
let dstIP: UInt32
|
|
||||||
let srcPort: UInt16
|
|
||||||
let dstPort: UInt16
|
|
||||||
let proto: UInt8
|
|
||||||
|
|
||||||
func hash(into hasher: inout Hasher) {
|
|
||||||
// 高效组合 hash
|
|
||||||
hasher.combine(srcIP)
|
|
||||||
hasher.combine(dstIP)
|
|
||||||
hasher.combine(UInt32(srcPort) << 16 | UInt32(dstPort))
|
|
||||||
hasher.combine(proto)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func ==(lhs: Self, rhs: Self) -> Bool {
|
|
||||||
return lhs.srcIP == rhs.srcIP &&
|
|
||||||
lhs.dstIP == rhs.dstIP &&
|
|
||||||
lhs.srcPort == rhs.srcPort &&
|
|
||||||
lhs.dstPort == rhs.dstPort &&
|
|
||||||
lhs.proto == rhs.proto
|
|
||||||
}
|
|
||||||
|
|
||||||
func reverse() -> FlowSession {
|
|
||||||
return FlowSession(
|
|
||||||
srcIP: dstIP,
|
|
||||||
dstIP: srcIP,
|
|
||||||
srcPort: dstPort,
|
|
||||||
dstPort: srcPort,
|
|
||||||
proto: proto
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - 会话表
|
|
||||||
final class FlowSessionTable: @unchecked Sendable {
|
|
||||||
|
|
||||||
private enum SessionState: Hashable {
|
|
||||||
case tcpPending
|
|
||||||
case tcpEstablished
|
|
||||||
case udp
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct SessionEntry {
|
|
||||||
let state: SessionState
|
|
||||||
let expiresAt: TimeInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
private var sessions: [FlowSession: SessionEntry] = [:]
|
|
||||||
private let lock = NSLock()
|
|
||||||
private let tcpPendingTimeout: TimeInterval
|
|
||||||
private let tcpEstablishedTimeout: TimeInterval
|
|
||||||
private let udpTimeout: TimeInterval
|
|
||||||
private let dnsTimeout: TimeInterval
|
|
||||||
|
|
||||||
init(tcpPendingTimeout: TimeInterval = 30,
|
|
||||||
tcpEstablishedTimeout: TimeInterval = 300,
|
|
||||||
udpTimeout: TimeInterval = 30,
|
|
||||||
dnsTimeout: TimeInterval = 10) {
|
|
||||||
self.tcpPendingTimeout = tcpPendingTimeout
|
|
||||||
self.tcpEstablishedTimeout = tcpEstablishedTimeout
|
|
||||||
self.udpTimeout = udpTimeout
|
|
||||||
self.dnsTimeout = dnsTimeout
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordOutboundTCP(_ key: FlowSession, flags: TCPFlags) {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
if flags.contains(.rst) || flags.contains(.fin) {
|
|
||||||
sessions.removeValue(forKey: key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if flags.contains(.syn) && !flags.contains(.ack) {
|
|
||||||
sessions[key] = SessionEntry(state: .tcpPending, expiresAt: Date().timeIntervalSince1970 + tcpPendingTimeout)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.touchIfValidLocked(key, allowedStates: [.tcpEstablished], timeout: tcpEstablishedTimeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
func recordOutboundUDP(_ key: FlowSession, isDNS: Bool) {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
sessions[key] = SessionEntry(state: .udp, expiresAt: Date().timeIntervalSince1970 + (isDNS ? dnsTimeout : udpTimeout))
|
|
||||||
}
|
|
||||||
|
|
||||||
func allowInboundTCP(_ key: FlowSession, flags: TCPFlags) -> Bool {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
if flags.contains(.rst) || flags.contains(.fin) {
|
|
||||||
let existed = self.hasValidLocked(key, allowedStates: [.tcpPending, .tcpEstablished])
|
|
||||||
sessions.removeValue(forKey: key)
|
|
||||||
return existed
|
|
||||||
}
|
|
||||||
|
|
||||||
if flags.contains(.syn) && flags.contains(.ack) {
|
|
||||||
return self.touchIfValidLocked(key, allowedStates: [.tcpPending, .tcpEstablished], timeout: tcpEstablishedTimeout, nextState: .tcpEstablished)
|
|
||||||
}
|
|
||||||
|
|
||||||
return self.touchIfValidLocked(key, allowedStates: [.tcpEstablished], timeout: tcpEstablishedTimeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
func allowInboundUDP(_ key: FlowSession, isDNS: Bool) -> Bool {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
return self.touchIfValidLocked(key, allowedStates: [.udp], timeout: isDNS ? dnsTimeout : udpTimeout)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 删除会话
|
|
||||||
func removeSession(_ key: FlowSession) {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
sessions.removeValue(forKey: key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func clear() {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
sessions.removeAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 清理过期会话
|
|
||||||
func cleanupExpiredSessions() {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
let now = Date().timeIntervalSince1970
|
|
||||||
self.sessions = self.sessions.filter { $0.value.expiresAt >= now }
|
|
||||||
}
|
|
||||||
|
|
||||||
// 返回当前会话数(调试/统计用)
|
|
||||||
var count: Int {
|
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
return sessions.count
|
|
||||||
}
|
|
||||||
|
|
||||||
private func hasValidLocked(_ key: FlowSession, allowedStates: Set<SessionState>) -> Bool {
|
|
||||||
guard let entry = sessions[key] else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
guard entry.expiresAt >= Date().timeIntervalSince1970 else {
|
|
||||||
sessions.removeValue(forKey: key)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return allowedStates.contains(entry.state)
|
|
||||||
}
|
|
||||||
|
|
||||||
@discardableResult
|
|
||||||
private func touchIfValidLocked(_ key: FlowSession,
|
|
||||||
allowedStates: Set<SessionState>,
|
|
||||||
timeout: TimeInterval,
|
|
||||||
nextState: SessionState? = nil) -> Bool {
|
|
||||||
guard let entry = sessions[key] else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
guard entry.expiresAt >= Date().timeIntervalSince1970 else {
|
|
||||||
sessions.removeValue(forKey: key)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
guard allowedStates.contains(entry.state) else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
sessions[key] = SessionEntry(
|
|
||||||
state: nextState ?? entry.state,
|
|
||||||
expiresAt: Date().timeIntervalSince1970 + timeout
|
|
||||||
)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
extension IPPacketView {
|
|
||||||
|
|
||||||
func flowSession() -> FlowSession? {
|
|
||||||
switch self.transportPacket {
|
|
||||||
case .tcp(let srcPort, let dstPort, _):
|
|
||||||
return FlowSession(srcIP: header.source, dstIP: header.destination, srcPort: srcPort, dstPort: dstPort, proto: header.proto)
|
|
||||||
case .udp(let srcPort, let dstPort, _):
|
|
||||||
return FlowSession(srcIP: header.source, dstIP: header.destination, srcPort: srcPort, dstPort: dstPort, proto: header.proto)
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,28 +0,0 @@
|
|||||||
//
|
|
||||||
// PolicyRuleMap.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/2/5.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
struct PolicyRuleMap {
|
|
||||||
let version: UInt32
|
|
||||||
// map[proto][port]
|
|
||||||
let ruleMap: [UInt8: [UInt16: Bool]]
|
|
||||||
|
|
||||||
init(version: UInt32, ruleMap: [UInt8: [UInt16: Bool]]) {
|
|
||||||
self.version = version
|
|
||||||
self.ruleMap = ruleMap
|
|
||||||
}
|
|
||||||
|
|
||||||
func isAllow(proto: UInt8, port: UInt16) -> Bool {
|
|
||||||
if let portMap = self.ruleMap[proto],
|
|
||||||
let allowed = portMap[port] {
|
|
||||||
return allowed
|
|
||||||
} else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
//
|
|
||||||
// PolicyRuleSnapshot.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/2/5.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class PolicyRuleSnapshot: Snapshot {
|
|
||||||
typealias IdentityID = UInt32
|
|
||||||
|
|
||||||
private let ruleMapByIdentity: [IdentityID: PolicyRuleMap]
|
|
||||||
|
|
||||||
init(ruleMapByIdentity: [IdentityID : PolicyRuleMap]) {
|
|
||||||
self.ruleMapByIdentity = ruleMapByIdentity
|
|
||||||
}
|
|
||||||
|
|
||||||
func lookup(_ id: IdentityID) -> PolicyRuleMap? {
|
|
||||||
return self.ruleMapByIdentity[id]
|
|
||||||
}
|
|
||||||
|
|
||||||
static func empty() -> PolicyRuleSnapshot {
|
|
||||||
return PolicyRuleSnapshot(ruleMapByIdentity: [:])
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,158 +0,0 @@
|
|||||||
//
|
|
||||||
// PolicyRuleStore.swift
|
|
||||||
// punchnet
|
|
||||||
// 1. 需要增加规则基于轮训更新的逻辑
|
|
||||||
// Created by 安礼成 on 2026/2/5.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIO
|
|
||||||
|
|
||||||
actor PolicyRuleStore {
|
|
||||||
|
|
||||||
private struct PolicyEntry {
|
|
||||||
let ruleMap: PolicyRuleMap
|
|
||||||
let expiresAt: TimeInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct PendingRequest {
|
|
||||||
let version: UInt32
|
|
||||||
let retryCount: Int
|
|
||||||
let nextRetryAt: TimeInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
private let policyTTL: TimeInterval = 120
|
|
||||||
private let refreshLeadTime: TimeInterval = 15
|
|
||||||
private let baseRetryDelay: TimeInterval = 2
|
|
||||||
private let maxRetryDelay: TimeInterval = 60
|
|
||||||
|
|
||||||
// 处理各个请求的版本问题, map[identityId] = version
|
|
||||||
private var versions: [UInt32: UInt32] = [:]
|
|
||||||
private var pendingByIdentity: [UInt32: PendingRequest] = [:]
|
|
||||||
|
|
||||||
nonisolated private let alloctor = ByteBufferAllocator()
|
|
||||||
|
|
||||||
private let publisher: SnapshotPublisher<PolicyRuleSnapshot>
|
|
||||||
private var policyByIdentity: [UInt32: PolicyEntry] = [:]
|
|
||||||
|
|
||||||
init(publisher: SnapshotPublisher<PolicyRuleSnapshot>) {
|
|
||||||
self.publisher = publisher
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeBatchPolicyRequests(dstIdentityID: UInt32) -> [Data] {
|
|
||||||
let now = Date().timeIntervalSince1970
|
|
||||||
let identities = Set(self.policyByIdentity.keys).union(self.pendingByIdentity.keys)
|
|
||||||
|
|
||||||
return identities.compactMap { identityId in
|
|
||||||
self.makePolicyRequestIfDue(srcIdentityId: identityId, dstIdentityId: dstIdentityID, now: now, forceMissing: false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func makePolicyRequest(srcIdentityId: UInt32, dstIdentityId: UInt32) -> Data? {
|
|
||||||
guard self.policyByIdentity[srcIdentityId] == nil else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return self.makePolicyRequestIfDue(
|
|
||||||
srcIdentityId: srcIdentityId,
|
|
||||||
dstIdentityId: dstIdentityId,
|
|
||||||
now: Date().timeIntervalSince1970,
|
|
||||||
forceMissing: true
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理权限的响应
|
|
||||||
func applyPolicyResponse(_ policyResponse: SDLPolicyResponse) {
|
|
||||||
let id = policyResponse.srcIdentityID
|
|
||||||
let version = policyResponse.version
|
|
||||||
|
|
||||||
if let pending = self.pendingByIdentity[id], pending.version <= version {
|
|
||||||
self.pendingByIdentity.removeValue(forKey: id)
|
|
||||||
}
|
|
||||||
|
|
||||||
guard self.policyByIdentity[id] == nil || ((self.policyByIdentity[id]?.ruleMap.version ?? 0) < version) else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 判断一下是否接受完成
|
|
||||||
var buffer = alloctor.buffer(bytes: policyResponse.rules)
|
|
||||||
var ruleMap: [UInt8: [UInt16: Bool]] = [:]
|
|
||||||
while true {
|
|
||||||
guard let proto = buffer.readInteger(endianness: .big, as: UInt8.self),
|
|
||||||
let port = buffer.readInteger(endianness: .big, as: UInt16.self) else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
ruleMap[proto, default: [:]][port] = true
|
|
||||||
}
|
|
||||||
let now = Date().timeIntervalSince1970
|
|
||||||
self.policyByIdentity[id] = PolicyEntry(
|
|
||||||
ruleMap: PolicyRuleMap(version: version, ruleMap: ruleMap),
|
|
||||||
expiresAt: now + self.policyTTL
|
|
||||||
)
|
|
||||||
SDLLogger.log("[PolicyRuleStore] apply policy response, srcIdentityID: \(id), version: \(version), rulesCount: \(ruleMap.reduce(0) { $0 + $1.value.count })", category: .policy)
|
|
||||||
|
|
||||||
// 发布新的快照信息
|
|
||||||
let snapshot = compileSnapshot()
|
|
||||||
publisher.publish(snapshot)
|
|
||||||
}
|
|
||||||
|
|
||||||
func clear() {
|
|
||||||
self.versions.removeAll()
|
|
||||||
self.pendingByIdentity.removeAll()
|
|
||||||
self.policyByIdentity.removeAll()
|
|
||||||
self.publisher.publish(PolicyRuleSnapshot.empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
private func compileSnapshot() -> PolicyRuleSnapshot {
|
|
||||||
return PolicyRuleSnapshot(ruleMapByIdentity: self.policyByIdentity.mapValues(\.ruleMap))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func nextVersion(identityId: UInt32) -> UInt32 {
|
|
||||||
let version = self.versions[identityId, default: 1]
|
|
||||||
// 更新请求的版本问题
|
|
||||||
self.versions[identityId] = version + 1
|
|
||||||
|
|
||||||
return version
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makePolicyRequestIfDue(srcIdentityId: UInt32, dstIdentityId: UInt32, now: TimeInterval, forceMissing: Bool) -> Data? {
|
|
||||||
if let pending = self.pendingByIdentity[srcIdentityId], pending.nextRetryAt > now {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !forceMissing,
|
|
||||||
let entry = self.policyByIdentity[srcIdentityId],
|
|
||||||
entry.expiresAt - self.refreshLeadTime > now {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let version = self.nextVersion(identityId: srcIdentityId)
|
|
||||||
guard let data = self.makePolicyRequestData(srcIdentityId: srcIdentityId, dstIdentityId: dstIdentityId, version: version) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let retryCount = self.pendingByIdentity[srcIdentityId].map { $0.retryCount + 1 } ?? 0
|
|
||||||
let retryDelay = self.retryDelay(for: retryCount, identityId: srcIdentityId)
|
|
||||||
self.pendingByIdentity[srcIdentityId] = PendingRequest(
|
|
||||||
version: version,
|
|
||||||
retryCount: retryCount,
|
|
||||||
nextRetryAt: now + retryDelay
|
|
||||||
)
|
|
||||||
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makePolicyRequestData(srcIdentityId: UInt32, dstIdentityId: UInt32, version: UInt32) -> Data? {
|
|
||||||
var policyRequest = SDLPolicyRequest()
|
|
||||||
policyRequest.srcIdentityID = srcIdentityId
|
|
||||||
policyRequest.dstIdentityID = dstIdentityId
|
|
||||||
policyRequest.version = version
|
|
||||||
return try? policyRequest.serializedData()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func retryDelay(for retryCount: Int, identityId: UInt32) -> TimeInterval {
|
|
||||||
let cappedRetryCount = min(retryCount, 5)
|
|
||||||
let multiplier = Double(1 << cappedRetryCount)
|
|
||||||
let jitter = Double(identityId % 1_000) / 1_000
|
|
||||||
return min(self.baseRetryDelay * multiplier + jitter, self.maxRetryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,107 +0,0 @@
|
|||||||
//
|
|
||||||
// PolicyRuntime.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/21.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
struct PolicyRuntime: @unchecked Sendable {
|
|
||||||
enum InboundDecision {
|
|
||||||
case allow
|
|
||||||
case deny
|
|
||||||
case missingPolicy
|
|
||||||
}
|
|
||||||
|
|
||||||
private let policyRuleSnapshot: PolicyRuleSnapshot
|
|
||||||
private let flowSessionTable: FlowSessionTable
|
|
||||||
private let acl: SDLConfiguration.ACL
|
|
||||||
|
|
||||||
init(policyRuleSnapshot: PolicyRuleSnapshot, flowSessionTable: FlowSessionTable, acl: SDLConfiguration.ACL) {
|
|
||||||
self.policyRuleSnapshot = policyRuleSnapshot
|
|
||||||
self.flowSessionTable = flowSessionTable
|
|
||||||
self.acl = acl
|
|
||||||
}
|
|
||||||
|
|
||||||
func evaluateInbound(srcIdentityID: UInt32, ipPacket: IPPacketView) -> InboundDecision {
|
|
||||||
if self.isExposedService(ipPacket: ipPacket) {
|
|
||||||
SDLLogger.log("[PolicyRuntime] acl hit, src_identify_id: \(srcIdentityID), check rule: \(debugInfo(ipPacket: ipPacket))", category: .policy)
|
|
||||||
return self.evaluateByRule(srcIdentityID: srcIdentityID, ipPacket: ipPacket)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.isAllowedBySession(ipPacket: ipPacket) {
|
|
||||||
SDLLogger.log("[PolicyRuntime] session hit, src_identify_id: \(srcIdentityID), allow: \(debugInfo(ipPacket: ipPacket))", category: .policy)
|
|
||||||
return .allow
|
|
||||||
}
|
|
||||||
|
|
||||||
if case .icmp = ipPacket.transportPacket {
|
|
||||||
SDLLogger.log("[PolicyRuntime] icmp hit, src_identify_id: \(srcIdentityID), allow: \(debugInfo(ipPacket: ipPacket))", category: .policy)
|
|
||||||
return .allow
|
|
||||||
}
|
|
||||||
|
|
||||||
return self.evaluateByRule(srcIdentityID: srcIdentityID, ipPacket: ipPacket)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func evaluateByRule(srcIdentityID: UInt32, ipPacket: IPPacketView) -> InboundDecision {
|
|
||||||
guard let ruleMap = self.policyRuleSnapshot.lookup(srcIdentityID) else {
|
|
||||||
return .missingPolicy
|
|
||||||
}
|
|
||||||
|
|
||||||
let isAllowed = self.isAllowedByRule(ruleMap: ruleMap, ipPacket: ipPacket)
|
|
||||||
SDLLogger.log("[PolicyRuntime] rule hit: \(isAllowed), src_identify_id: \(srcIdentityID), allow: \(debugInfo(ipPacket: ipPacket))", category: .policy)
|
|
||||||
|
|
||||||
return isAllowed ? .allow : .deny
|
|
||||||
}
|
|
||||||
|
|
||||||
private func isExposedService(ipPacket: IPPacketView) -> Bool {
|
|
||||||
switch ipPacket.transportPacket {
|
|
||||||
case .tcp(_, let dstPort, _):
|
|
||||||
return ipPacket.header.proto == TransportProtocol.tcp.rawValue && self.acl.tcpPorts.contains(dstPort)
|
|
||||||
case .udp(_, let dstPort, _):
|
|
||||||
return ipPacket.header.proto == TransportProtocol.udp.rawValue && self.acl.udpPorts.contains(dstPort)
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func isAllowedByRule(ruleMap: PolicyRuleMap, ipPacket: IPPacketView) -> Bool {
|
|
||||||
let proto = ipPacket.header.proto
|
|
||||||
|
|
||||||
switch ipPacket.transportPacket {
|
|
||||||
case .tcp(_, let dstPort, _):
|
|
||||||
return ruleMap.isAllow(proto: proto, port: dstPort)
|
|
||||||
case .udp(_, let dstPort, _):
|
|
||||||
return ruleMap.isAllow(proto: proto, port: dstPort)
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func isAllowedBySession(ipPacket: IPPacketView) -> Bool {
|
|
||||||
guard let reverseFlowSession = ipPacket.flowSession()?.reverse() else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch ipPacket.transportPacket {
|
|
||||||
case .tcp(_, _, let flags):
|
|
||||||
return self.flowSessionTable.allowInboundTCP(reverseFlowSession, flags: flags)
|
|
||||||
case .udp(let srcPort, _, _):
|
|
||||||
return self.flowSessionTable.allowInboundUDP(reverseFlowSession, isDNS: srcPort == 53)
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func debugInfo(ipPacket: IPPacketView) -> String {
|
|
||||||
switch ipPacket.transportPacket {
|
|
||||||
case .tcp(_, let dstPort, _):
|
|
||||||
return "tcp: \(dstPort)"
|
|
||||||
case .udp(_, let dstPort, _):
|
|
||||||
return "udp: \(dstPort)"
|
|
||||||
default:
|
|
||||||
return "unknown"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,114 +0,0 @@
|
|||||||
//
|
|
||||||
// PolicyService.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/19.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class ExposedServiceSnapshot: Snapshot {
|
|
||||||
let acl: SDLConfiguration.ACL
|
|
||||||
|
|
||||||
init(acl: SDLConfiguration.ACL) {
|
|
||||||
self.acl = acl
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
actor PolicyService {
|
|
||||||
// 处理权限控制
|
|
||||||
private let policyRuleStore: PolicyRuleStore
|
|
||||||
nonisolated private let snapshotPublisher: SnapshotPublisher<PolicyRuleSnapshot>
|
|
||||||
nonisolated private let aclPublisher: SnapshotPublisher<ExposedServiceSnapshot>
|
|
||||||
|
|
||||||
nonisolated private let flowSessionTable = FlowSessionTable()
|
|
||||||
|
|
||||||
// 当前节点的identityId值
|
|
||||||
let identityId: UInt32
|
|
||||||
private var latestExposedServiceRequestVersion: UInt32 = 0
|
|
||||||
|
|
||||||
init(identityId: UInt32, acl: SDLConfiguration.ACL) {
|
|
||||||
self.identityId = identityId
|
|
||||||
// 权限控制
|
|
||||||
let snapshotPublisher = SnapshotPublisher(initial: PolicyRuleSnapshot.empty())
|
|
||||||
self.policyRuleStore = PolicyRuleStore(publisher: snapshotPublisher)
|
|
||||||
self.snapshotPublisher = snapshotPublisher
|
|
||||||
self.aclPublisher = SnapshotPublisher(initial: ExposedServiceSnapshot(acl: acl))
|
|
||||||
}
|
|
||||||
|
|
||||||
nonisolated func policyRuntime() -> PolicyRuntime {
|
|
||||||
return PolicyRuntime(policyRuleSnapshot: self.snapshotPublisher.current(), flowSessionTable: self.flowSessionTable, acl: self.aclPublisher.current().acl)
|
|
||||||
}
|
|
||||||
|
|
||||||
nonisolated func recordOutboundFlow(ipPacket: IPPacketView) {
|
|
||||||
guard let flowSession = ipPacket.flowSession() else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
switch ipPacket.transportPacket {
|
|
||||||
case .tcp(_, _, let flags):
|
|
||||||
self.flowSessionTable.recordOutboundTCP(flowSession, flags: flags)
|
|
||||||
case .udp(_, let dstPort, _):
|
|
||||||
self.flowSessionTable.recordOutboundUDP(flowSession, isDNS: dstPort == 53)
|
|
||||||
default:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func makePolicyRequest(srcIdentityID: UInt32) async -> Data? {
|
|
||||||
return await self.policyRuleStore.makePolicyRequest(srcIdentityId: srcIdentityID, dstIdentityId: self.identityId)
|
|
||||||
}
|
|
||||||
|
|
||||||
func updatePolicy(superService: SDLSuperService) async {
|
|
||||||
let requests = await self.policyRuleStore.makeBatchPolicyRequests(dstIdentityID: self.identityId)
|
|
||||||
for request in requests {
|
|
||||||
await superService.send(type: .policyRequest, data: request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyPolicyResponse(_ policyResponse: SDLPolicyResponse) async {
|
|
||||||
guard policyResponse.dstIdentityID == self.identityId else {
|
|
||||||
SDLLogger.log("[PolicyService] ignore policy response, dstIdentityID mismatch: \(policyResponse.dstIdentityID), expected: \(self.identityId)", category: .policy)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.policyRuleStore.applyPolicyResponse(policyResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeExposedServiceRequest() -> Data? {
|
|
||||||
var request = SDLExposedServiceRequest()
|
|
||||||
self.latestExposedServiceRequestVersion = Self.nextVersion(after: self.latestExposedServiceRequestVersion)
|
|
||||||
request.version = self.latestExposedServiceRequestVersion
|
|
||||||
SDLLogger.log("[PolicyService] make exposed service request, version: \(request.version)", category: .policy)
|
|
||||||
return try? request.serializedData()
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyExposedServiceResponse(_ response: SDLExposedServiceResponse) -> SDLConfiguration.ACL? {
|
|
||||||
guard response.version == self.latestExposedServiceRequestVersion else {
|
|
||||||
SDLLogger.log("[PolicyService] ignore exposed service response, version: \(response.version), latest request version: \(self.latestExposedServiceRequestVersion)", category: .policy)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let acl = SDLConfiguration.ACL(response: response)
|
|
||||||
self.aclPublisher.publish(ExposedServiceSnapshot(acl: acl))
|
|
||||||
SDLLogger.log("[PolicyService] apply exposed service response, version: \(response.version), tcp: \(acl.tcpPorts.count), udp: \(acl.udpPorts.count)", category: .policy)
|
|
||||||
return acl
|
|
||||||
}
|
|
||||||
|
|
||||||
func clear() async {
|
|
||||||
self.flowSessionTable.clear()
|
|
||||||
await self.policyRuleStore.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[PolicyService] deinit", category: .policy)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func nextVersion(after version: UInt32) -> UInt32 {
|
|
||||||
if version == UInt32.max {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
return version + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,262 +0,0 @@
|
|||||||
// DO NOT EDIT.
|
|
||||||
// swift-format-ignore-file
|
|
||||||
// swiftlint:disable all
|
|
||||||
//
|
|
||||||
// Generated by the Swift generator plugin for the protocol buffer compiler.
|
|
||||||
// Source: tun.proto
|
|
||||||
//
|
|
||||||
// For information on using the generated types, please see the documentation:
|
|
||||||
// https://github.com/apple/swift-protobuf/
|
|
||||||
|
|
||||||
import SwiftProtobuf
|
|
||||||
|
|
||||||
// If the compiler emits an error on this type, it is because this file
|
|
||||||
// was generated by a version of the `protoc` Swift plug-in that is
|
|
||||||
// incompatible with the version of SwiftProtobuf to which you are linking.
|
|
||||||
// Please ensure that you are building against the same version of the API
|
|
||||||
// that was used to generate this file.
|
|
||||||
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
|
|
||||||
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
|
|
||||||
typealias Version = _2
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 定义App发送给NE的事件
|
|
||||||
struct AppRequest: Sendable {
|
|
||||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
|
||||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
|
||||||
// methods supported on all messages.
|
|
||||||
|
|
||||||
var command: AppRequest.OneOf_Command? = nil
|
|
||||||
|
|
||||||
var changeExitNode: AppRequest.ChangeExitNodeRequest {
|
|
||||||
get {
|
|
||||||
if case .changeExitNode(let v)? = command {return v}
|
|
||||||
return AppRequest.ChangeExitNodeRequest()
|
|
||||||
}
|
|
||||||
set {command = .changeExitNode(newValue)}
|
|
||||||
}
|
|
||||||
|
|
||||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
|
||||||
|
|
||||||
enum OneOf_Command: Equatable, Sendable {
|
|
||||||
case changeExitNode(AppRequest.ChangeExitNodeRequest)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ChangeExitNodeRequest: Sendable {
|
|
||||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
|
||||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
|
||||||
// methods supported on all messages.
|
|
||||||
|
|
||||||
/// 空字符串表示清除出口节点
|
|
||||||
var ip: String = String()
|
|
||||||
|
|
||||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
|
||||||
|
|
||||||
init() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
init() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TunnelResponse: Sendable {
|
|
||||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
|
||||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
|
||||||
// methods supported on all messages.
|
|
||||||
|
|
||||||
var code: Int32 = 0
|
|
||||||
|
|
||||||
var message: String = String()
|
|
||||||
|
|
||||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
|
||||||
|
|
||||||
init() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TunnelEvent: Sendable {
|
|
||||||
// SwiftProtobuf.Message conformance is added in an extension below. See the
|
|
||||||
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
|
|
||||||
// methods supported on all messages.
|
|
||||||
|
|
||||||
var id: String = String()
|
|
||||||
|
|
||||||
var timestampMs: UInt64 = 0
|
|
||||||
|
|
||||||
var code: Int32 = 0
|
|
||||||
|
|
||||||
var message: String = String()
|
|
||||||
|
|
||||||
var unknownFields = SwiftProtobuf.UnknownStorage()
|
|
||||||
|
|
||||||
init() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Code below here is support for the SwiftProtobuf runtime.
|
|
||||||
|
|
||||||
extension AppRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
|
||||||
static let protoMessageName: String = "AppRequest"
|
|
||||||
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
|
|
||||||
1: .standard(proto: "change_exit_node"),
|
|
||||||
]
|
|
||||||
|
|
||||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
|
||||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
|
||||||
// The use of inline closures is to circumvent an issue where the compiler
|
|
||||||
// allocates stack space for every case branch when no optimizations are
|
|
||||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
|
||||||
switch fieldNumber {
|
|
||||||
case 1: try {
|
|
||||||
var v: AppRequest.ChangeExitNodeRequest?
|
|
||||||
var hadOneofValue = false
|
|
||||||
if let current = self.command {
|
|
||||||
hadOneofValue = true
|
|
||||||
if case .changeExitNode(let m) = current {v = m}
|
|
||||||
}
|
|
||||||
try decoder.decodeSingularMessageField(value: &v)
|
|
||||||
if let v = v {
|
|
||||||
if hadOneofValue {try decoder.handleConflictingOneOf()}
|
|
||||||
self.command = .changeExitNode(v)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
default: break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
|
||||||
// The use of inline closures is to circumvent an issue where the compiler
|
|
||||||
// allocates stack space for every if/case branch local when no optimizations
|
|
||||||
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
|
|
||||||
// https://github.com/apple/swift-protobuf/issues/1182
|
|
||||||
try { if case .changeExitNode(let v)? = self.command {
|
|
||||||
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
|
|
||||||
} }()
|
|
||||||
try unknownFields.traverse(visitor: &visitor)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func ==(lhs: AppRequest, rhs: AppRequest) -> Bool {
|
|
||||||
if lhs.command != rhs.command {return false}
|
|
||||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension AppRequest.ChangeExitNodeRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
|
||||||
static let protoMessageName: String = AppRequest.protoMessageName + ".ChangeExitNodeRequest"
|
|
||||||
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
|
|
||||||
1: .same(proto: "ip"),
|
|
||||||
]
|
|
||||||
|
|
||||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
|
||||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
|
||||||
// The use of inline closures is to circumvent an issue where the compiler
|
|
||||||
// allocates stack space for every case branch when no optimizations are
|
|
||||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
|
||||||
switch fieldNumber {
|
|
||||||
case 1: try { try decoder.decodeSingularStringField(value: &self.ip) }()
|
|
||||||
default: break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
|
||||||
if !self.ip.isEmpty {
|
|
||||||
try visitor.visitSingularStringField(value: self.ip, fieldNumber: 1)
|
|
||||||
}
|
|
||||||
try unknownFields.traverse(visitor: &visitor)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func ==(lhs: AppRequest.ChangeExitNodeRequest, rhs: AppRequest.ChangeExitNodeRequest) -> Bool {
|
|
||||||
if lhs.ip != rhs.ip {return false}
|
|
||||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension TunnelResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
|
||||||
static let protoMessageName: String = "TunnelResponse"
|
|
||||||
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
|
|
||||||
1: .same(proto: "code"),
|
|
||||||
2: .same(proto: "message"),
|
|
||||||
]
|
|
||||||
|
|
||||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
|
||||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
|
||||||
// The use of inline closures is to circumvent an issue where the compiler
|
|
||||||
// allocates stack space for every case branch when no optimizations are
|
|
||||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
|
||||||
switch fieldNumber {
|
|
||||||
case 1: try { try decoder.decodeSingularInt32Field(value: &self.code) }()
|
|
||||||
case 2: try { try decoder.decodeSingularStringField(value: &self.message) }()
|
|
||||||
default: break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
|
||||||
if self.code != 0 {
|
|
||||||
try visitor.visitSingularInt32Field(value: self.code, fieldNumber: 1)
|
|
||||||
}
|
|
||||||
if !self.message.isEmpty {
|
|
||||||
try visitor.visitSingularStringField(value: self.message, fieldNumber: 2)
|
|
||||||
}
|
|
||||||
try unknownFields.traverse(visitor: &visitor)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func ==(lhs: TunnelResponse, rhs: TunnelResponse) -> Bool {
|
|
||||||
if lhs.code != rhs.code {return false}
|
|
||||||
if lhs.message != rhs.message {return false}
|
|
||||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension TunnelEvent: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
|
|
||||||
static let protoMessageName: String = "TunnelEvent"
|
|
||||||
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
|
|
||||||
1: .same(proto: "id"),
|
|
||||||
2: .standard(proto: "timestamp_ms"),
|
|
||||||
3: .same(proto: "code"),
|
|
||||||
4: .same(proto: "message"),
|
|
||||||
]
|
|
||||||
|
|
||||||
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
|
|
||||||
while let fieldNumber = try decoder.nextFieldNumber() {
|
|
||||||
// The use of inline closures is to circumvent an issue where the compiler
|
|
||||||
// allocates stack space for every case branch when no optimizations are
|
|
||||||
// enabled. https://github.com/apple/swift-protobuf/issues/1034
|
|
||||||
switch fieldNumber {
|
|
||||||
case 1: try { try decoder.decodeSingularStringField(value: &self.id) }()
|
|
||||||
case 2: try { try decoder.decodeSingularUInt64Field(value: &self.timestampMs) }()
|
|
||||||
case 3: try { try decoder.decodeSingularInt32Field(value: &self.code) }()
|
|
||||||
case 4: try { try decoder.decodeSingularStringField(value: &self.message) }()
|
|
||||||
default: break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
|
|
||||||
if !self.id.isEmpty {
|
|
||||||
try visitor.visitSingularStringField(value: self.id, fieldNumber: 1)
|
|
||||||
}
|
|
||||||
if self.timestampMs != 0 {
|
|
||||||
try visitor.visitSingularUInt64Field(value: self.timestampMs, fieldNumber: 2)
|
|
||||||
}
|
|
||||||
if self.code != 0 {
|
|
||||||
try visitor.visitSingularInt32Field(value: self.code, fieldNumber: 3)
|
|
||||||
}
|
|
||||||
if !self.message.isEmpty {
|
|
||||||
try visitor.visitSingularStringField(value: self.message, fieldNumber: 4)
|
|
||||||
}
|
|
||||||
try unknownFields.traverse(visitor: &visitor)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func ==(lhs: TunnelEvent, rhs: TunnelEvent) -> Bool {
|
|
||||||
if lhs.id != rhs.id {return false}
|
|
||||||
if lhs.timestampMs != rhs.timestampMs {return false}
|
|
||||||
if lhs.code != rhs.code {return false}
|
|
||||||
if lhs.message != rhs.message {return false}
|
|
||||||
if lhs.unknownFields != rhs.unknownFields {return false}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
13
Tun/Punchnet/AESCipher.swift
Normal file
13
Tun/Punchnet/AESCipher.swift
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
//
|
||||||
|
// AESCipher.swift
|
||||||
|
// sdlan
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2025/7/14.
|
||||||
|
//
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
public protocol AESCipher {
|
||||||
|
func decypt(aesKey: Data, data: Data) throws -> Data
|
||||||
|
|
||||||
|
func encrypt(aesKey: Data, data: Data) throws -> Data
|
||||||
|
}
|
||||||
117
Tun/Punchnet/Actors/SDLDNSClientActor.swift
Normal file
117
Tun/Punchnet/Actors/SDLDNSClientActor.swift
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
//
|
||||||
|
// DNSClient.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2025/12/10.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import NIOCore
|
||||||
|
import NIOPosix
|
||||||
|
|
||||||
|
// 处理和sn-server服务器之间的通讯
|
||||||
|
@available(macOS 14, *)
|
||||||
|
actor SDLDNSClientActor {
|
||||||
|
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||||
|
private let asyncChannel: NIOAsyncChannel<AddressedEnvelope<ByteBuffer>, AddressedEnvelope<ByteBuffer>>
|
||||||
|
private let (writeStream, writeContinuation) = AsyncStream.makeStream(of: Data.self, bufferingPolicy: .unbounded)
|
||||||
|
|
||||||
|
private let logger: SDLLogger
|
||||||
|
private let dnsServerAddress: SocketAddress
|
||||||
|
|
||||||
|
public let packetFlow: AsyncStream<Data>
|
||||||
|
private let packetContinuation: AsyncStream<Data>.Continuation
|
||||||
|
|
||||||
|
// 启动函数
|
||||||
|
init(dnsServerAddress: SocketAddress, logger: SDLLogger) async throws {
|
||||||
|
self.dnsServerAddress = dnsServerAddress
|
||||||
|
self.logger = logger
|
||||||
|
|
||||||
|
(self.packetFlow, self.packetContinuation) = AsyncStream.makeStream(of: Data.self, bufferingPolicy: .unbounded)
|
||||||
|
|
||||||
|
let bootstrap = DatagramBootstrap(group: group)
|
||||||
|
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||||
|
|
||||||
|
self.asyncChannel = try await bootstrap.bind(host: "0.0.0.0", port: 0)
|
||||||
|
.flatMapThrowing { channel in
|
||||||
|
return try NIOAsyncChannel(wrappingChannelSynchronously: channel, configuration: .init(
|
||||||
|
inboundType: AddressedEnvelope<ByteBuffer>.self,
|
||||||
|
outboundType: AddressedEnvelope<ByteBuffer>.self
|
||||||
|
))
|
||||||
|
}
|
||||||
|
.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
func start() async throws {
|
||||||
|
try await withTaskCancellationHandler {
|
||||||
|
try await self.asyncChannel.executeThenClose {inbound, outbound in
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[DNSClient] inbound closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
for try await envelope in inbound {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
var buffer = envelope.data
|
||||||
|
let remoteAddress = envelope.remoteAddress
|
||||||
|
self.logger.log("[DNSClient] read data: \(buffer), from: \(remoteAddress)", level: .debug)
|
||||||
|
|
||||||
|
let len = buffer.readableBytes
|
||||||
|
if let bytes = buffer.readBytes(length: len) {
|
||||||
|
self.packetContinuation.yield(Data(bytes))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[DNSClient] outbound closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
for await message in self.writeStream {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
|
let buffer = self.asyncChannel.channel.allocator.buffer(bytes: message)
|
||||||
|
let envelope = AddressedEnvelope<ByteBuffer>(remoteAddress: self.dnsServerAddress, data: buffer)
|
||||||
|
try await outbound.write(envelope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let _ = try await group.next() {
|
||||||
|
group.cancelAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} onCancel: {
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
self.packetContinuation.finish()
|
||||||
|
self.logger.log("[DNSClient] withTaskCancellationHandler cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func forward(ipPacket: IPPacket) {
|
||||||
|
self.writeContinuation.yield(ipPacket.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
try? self.group.syncShutdownGracefully()
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
extension SDLDNSClientActor {
|
||||||
|
|
||||||
|
struct Helper {
|
||||||
|
static let dnsServer: String = "100.100.100.100"
|
||||||
|
// dns请求包的目标地址
|
||||||
|
static let dnsDestIpAddr: UInt32 = 1684300900
|
||||||
|
|
||||||
|
// 判断是否是dns请求的数据包
|
||||||
|
static func isDnsRequestPacket(ipPacket: IPPacket) -> Bool {
|
||||||
|
return ipPacket.header.destination == dnsDestIpAddr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
89
Tun/Punchnet/Actors/SDLPuncherActor.swift
Normal file
89
Tun/Punchnet/Actors/SDLPuncherActor.swift
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
//
|
||||||
|
// SDLPuncherActor.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2026/1/7.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
actor SDLPuncherActor {
|
||||||
|
// dstMac
|
||||||
|
private var coolingDown: Set<Data> = []
|
||||||
|
private let cooldown: Duration = .seconds(5)
|
||||||
|
|
||||||
|
private var superClientActor: SDLSuperClientActor?
|
||||||
|
private var udpHoleActor: SDLUDPHoleActor?
|
||||||
|
|
||||||
|
// 处理holer
|
||||||
|
private var logger: SDLLogger
|
||||||
|
|
||||||
|
struct RegisterRequest {
|
||||||
|
let srcMac: Data
|
||||||
|
let dstMac: Data
|
||||||
|
let networkId: UInt32
|
||||||
|
}
|
||||||
|
|
||||||
|
init(logger: SDLLogger) {
|
||||||
|
self.logger = logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func setSuperClientActor(superClientActor: SDLSuperClientActor?) {
|
||||||
|
self.superClientActor = superClientActor
|
||||||
|
}
|
||||||
|
|
||||||
|
func setUDPHoleActor(udpHoleActor: SDLUDPHoleActor?) {
|
||||||
|
self.udpHoleActor = udpHoleActor
|
||||||
|
}
|
||||||
|
|
||||||
|
func submitRegisterRequest(request: RegisterRequest) {
|
||||||
|
let dstMac = request.dstMac
|
||||||
|
|
||||||
|
guard !coolingDown.contains(dstMac) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 触发一次打洞
|
||||||
|
coolingDown.insert(dstMac)
|
||||||
|
|
||||||
|
Task {
|
||||||
|
await self.tryHole(request: request)
|
||||||
|
// 启动冷却期
|
||||||
|
try? await Task.sleep(for: .seconds(5))
|
||||||
|
self.endCooldown(for: dstMac)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func endCooldown(for key: Data) {
|
||||||
|
self.coolingDown.remove(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func tryHole(request: RegisterRequest) async {
|
||||||
|
var queryInfo = SDLQueryInfo()
|
||||||
|
queryInfo.dstMac = request.dstMac
|
||||||
|
guard let message = try? await self.superClientActor?.request(type: .queryInfo, data: try queryInfo.serializedData()) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch message.packet {
|
||||||
|
case .empty:
|
||||||
|
self.logger.log("[SDLContext] hole query_info get empty: \(message)", level: .debug)
|
||||||
|
case .peerInfo(let peerInfo):
|
||||||
|
if let remoteAddress = peerInfo.v4Info.socketAddress() {
|
||||||
|
self.logger.log("[SDLContext] hole sock address: \(remoteAddress)", level: .debug)
|
||||||
|
// 发送register包
|
||||||
|
var register = SDLRegister()
|
||||||
|
register.networkID = request.networkId
|
||||||
|
register.srcMac = request.srcMac
|
||||||
|
register.dstMac = request.dstMac
|
||||||
|
|
||||||
|
await self.udpHoleActor?.send(type: .register, data: try! register.serializedData(), remoteAddress: remoteAddress)
|
||||||
|
} else {
|
||||||
|
self.logger.log("[SDLContext] hole sock address is invalid: \(peerInfo.v4Info)", level: .warning)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
self.logger.log("[SDLContext] hole query_info is packet: \(message)", level: .warning)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
312
Tun/Punchnet/Actors/SDLSuperClientActor.swift
Normal file
312
Tun/Punchnet/Actors/SDLSuperClientActor.swift
Normal file
@ -0,0 +1,312 @@
|
|||||||
|
//
|
||||||
|
// SDLWebsocketClient.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/3/28.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import NIOCore
|
||||||
|
import NIOPosix
|
||||||
|
|
||||||
|
// --MARK: 和SuperNode的客户端
|
||||||
|
actor SDLSuperClientActor {
|
||||||
|
// 发送的消息格式
|
||||||
|
private typealias TcpMessage = (packetId: UInt32, type: SDLPacketType, data: Data)
|
||||||
|
|
||||||
|
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||||
|
private let asyncChannel: NIOAsyncChannel<ByteBuffer,ByteBuffer>
|
||||||
|
private let (writeStream, writeContinuation) = AsyncStream.makeStream(of: TcpMessage.self, bufferingPolicy: .unbounded)
|
||||||
|
private var continuations: [UInt32:CheckedContinuation<SDLSuperInboundMessage, Error>] = [:]
|
||||||
|
|
||||||
|
public let eventFlow: AsyncStream<SuperEvent>
|
||||||
|
private let inboundContinuation: AsyncStream<SuperEvent>.Continuation
|
||||||
|
|
||||||
|
// id生成器
|
||||||
|
var idGenerator = SDLIdGenerator(seed: 1)
|
||||||
|
|
||||||
|
private let logger: SDLLogger
|
||||||
|
|
||||||
|
// 定义事件类型
|
||||||
|
enum SuperEvent {
|
||||||
|
case ready
|
||||||
|
case event(SDLEvent)
|
||||||
|
case command(UInt32, SDLCommand)
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SuperClientError: Error {
|
||||||
|
case timeout
|
||||||
|
case connectionClosed
|
||||||
|
case cancelled
|
||||||
|
}
|
||||||
|
|
||||||
|
init(host: String, port: Int, logger: SDLLogger) async throws {
|
||||||
|
self.logger = logger
|
||||||
|
|
||||||
|
(self.eventFlow, self.inboundContinuation) = AsyncStream.makeStream(of: SuperEvent.self, bufferingPolicy: .unbounded)
|
||||||
|
let bootstrap = ClientBootstrap(group: self.group)
|
||||||
|
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||||
|
.channelInitializer { channel in
|
||||||
|
return channel.pipeline.addHandlers([
|
||||||
|
ByteToMessageHandler(FixedHeaderDecoder()),
|
||||||
|
MessageToByteHandler(FixedHeaderEncoder())
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
self.asyncChannel = try await bootstrap.connect(host: host, port: port)
|
||||||
|
.flatMapThrowing { channel in
|
||||||
|
return try NIOAsyncChannel(wrappingChannelSynchronously: channel, configuration: .init(
|
||||||
|
inboundType: ByteBuffer.self,
|
||||||
|
outboundType: ByteBuffer.self
|
||||||
|
))
|
||||||
|
}
|
||||||
|
.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
func start() async throws {
|
||||||
|
try await withTaskCancellationHandler {
|
||||||
|
try await self.asyncChannel.executeThenClose { inbound, outbound in
|
||||||
|
self.inboundContinuation.yield(.ready)
|
||||||
|
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLSuperClient] inbound closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
for try await var packet in inbound {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
|
if let message = SDLSuperClientDecoder.decode(buffer: &packet) {
|
||||||
|
if !message.isPong() {
|
||||||
|
self.logger.log("[SDLSuperClient] read message: \(message)", level: .debug)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch message.packet {
|
||||||
|
case .event(let event):
|
||||||
|
self.inboundContinuation.yield(.event(event))
|
||||||
|
case .command(let command):
|
||||||
|
self.inboundContinuation.yield(.command(message.msgId, command))
|
||||||
|
default:
|
||||||
|
await self.fireCallback(message: message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLSuperClient] outbound closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
for await (packetId, type, data) in self.writeStream {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
|
var buffer = self.asyncChannel.channel.allocator.buffer(capacity: data.count + 5)
|
||||||
|
buffer.writeInteger(packetId, as: UInt32.self)
|
||||||
|
buffer.writeBytes([type.rawValue])
|
||||||
|
buffer.writeBytes(data)
|
||||||
|
try await outbound.write(buffer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --MARK: 心跳机制
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLSuperClient] ping task closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
while true {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
await self.ping()
|
||||||
|
try await Task.sleep(nanoseconds: 5 * 1_000_000_000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 迭代等待所有任务的退出, 第一个异常会被抛出
|
||||||
|
if let _ = try await group.next() {
|
||||||
|
group.cancelAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} onCancel: {
|
||||||
|
self.inboundContinuation.finish()
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
self.logger.log("[SDLSuperClient] withTaskCancellationHandler cancel")
|
||||||
|
Task {
|
||||||
|
await self.failAllContinuations(SuperClientError.cancelled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- MARK: apis
|
||||||
|
func unregister() throws {
|
||||||
|
self.send(type: .unregisterSuper, packetId: 0, data: Data())
|
||||||
|
}
|
||||||
|
|
||||||
|
private func ping() {
|
||||||
|
self.send(type: .ping, packetId: 0, data: Data())
|
||||||
|
}
|
||||||
|
|
||||||
|
func request(type: SDLPacketType, data: Data, timeout: Duration = .seconds(5)) async throws -> SDLSuperInboundMessage {
|
||||||
|
let packetId = idGenerator.nextId()
|
||||||
|
|
||||||
|
return try await withCheckedThrowingContinuation { cont in
|
||||||
|
self.continuations[packetId] = cont
|
||||||
|
self.writeContinuation.yield(TcpMessage(packetId: packetId, type: type, data: data))
|
||||||
|
Task {
|
||||||
|
try? await Task.sleep(for: timeout)
|
||||||
|
self.timeout(packetId: packetId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func send(type: SDLPacketType, packetId: UInt32, data: Data) {
|
||||||
|
self.writeContinuation.yield(TcpMessage(packetId: packetId, type: type, data: data))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理回调函数
|
||||||
|
private func fireCallback(message: SDLSuperInboundMessage) {
|
||||||
|
guard let cont = self.continuations.removeValue(forKey: message.msgId) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cont.resume(returning: message)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func failAllContinuations(_ error: Error) {
|
||||||
|
let all = continuations
|
||||||
|
continuations.removeAll()
|
||||||
|
|
||||||
|
for (_, cont) in all {
|
||||||
|
cont.resume(throwing: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func timeout(packetId: UInt32) {
|
||||||
|
guard let cont = self.continuations.removeValue(forKey: packetId) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cont.resume(throwing: SuperClientError.timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
try! group.syncShutdownGracefully()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// --MARK: 编解码器
|
||||||
|
private struct SDLSuperClientDecoder {
|
||||||
|
// 消息格式为: <<MsgId:32, Type:8, Body/binary>>
|
||||||
|
static func decode(buffer: inout ByteBuffer) -> SDLSuperInboundMessage? {
|
||||||
|
guard let msgId = buffer.readInteger(as: UInt32.self),
|
||||||
|
let type = buffer.readInteger(as: UInt8.self),
|
||||||
|
let messageType = SDLPacketType(rawValue: type) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch messageType {
|
||||||
|
case .empty:
|
||||||
|
return .init(msgId: msgId, packet: .empty)
|
||||||
|
case .registerSuperAck:
|
||||||
|
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
||||||
|
let registerSuperAck = try? SDLRegisterSuperAck(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return .init(msgId: msgId, packet: .registerSuperAck(registerSuperAck))
|
||||||
|
|
||||||
|
case .registerSuperNak:
|
||||||
|
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
||||||
|
let registerSuperNak = try? SDLRegisterSuperNak(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return .init(msgId: msgId, packet: .registerSuperNak(registerSuperNak))
|
||||||
|
|
||||||
|
case .peerInfo:
|
||||||
|
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
||||||
|
let peerInfo = try? SDLPeerInfo(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return .init(msgId: msgId, packet: .peerInfo(peerInfo))
|
||||||
|
case .pong:
|
||||||
|
return .init(msgId: msgId, packet: .pong)
|
||||||
|
|
||||||
|
case .command:
|
||||||
|
guard let commandVal = buffer.readInteger(as: UInt8.self),
|
||||||
|
let command = SDLCommandType(rawValue: commandVal),
|
||||||
|
let bytes = buffer.readBytes(length: buffer.readableBytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch command {
|
||||||
|
case .changeNetwork:
|
||||||
|
guard let changeNetworkCommand = try? SDLChangeNetworkCommand(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return .init(msgId: msgId, packet: .command(.changeNetwork(changeNetworkCommand)))
|
||||||
|
}
|
||||||
|
|
||||||
|
case .event:
|
||||||
|
guard let eventVal = buffer.readInteger(as: UInt8.self),
|
||||||
|
let event = SDLEventType(rawValue: eventVal),
|
||||||
|
let bytes = buffer.readBytes(length: buffer.readableBytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch event {
|
||||||
|
case .natChanged:
|
||||||
|
guard let natChangedEvent = try? SDLNatChangedEvent(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return .init(msgId: msgId, packet: .event(.natChanged(natChangedEvent)))
|
||||||
|
case .sendRegister:
|
||||||
|
guard let sendRegisterEvent = try? SDLSendRegisterEvent(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return .init(msgId: msgId, packet: .event(.sendRegister(sendRegisterEvent)))
|
||||||
|
case .networkShutdown:
|
||||||
|
guard let networkShutdownEvent = try? SDLNetworkShutdownEvent(serializedBytes: bytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return .init(msgId: msgId, packet: .event(.networkShutdown(networkShutdownEvent)))
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class FixedHeaderEncoder: MessageToByteEncoder, @unchecked Sendable {
|
||||||
|
typealias InboundIn = ByteBuffer
|
||||||
|
typealias InboundOut = ByteBuffer
|
||||||
|
|
||||||
|
func encode(data: ByteBuffer, out: inout ByteBuffer) throws {
|
||||||
|
let len = data.readableBytes
|
||||||
|
out.writeInteger(UInt16(len))
|
||||||
|
out.writeBytes(data.readableBytesView)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class FixedHeaderDecoder: ByteToMessageDecoder, @unchecked Sendable {
|
||||||
|
typealias InboundIn = ByteBuffer
|
||||||
|
typealias InboundOut = ByteBuffer
|
||||||
|
|
||||||
|
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
|
||||||
|
guard let len = buffer.getInteger(at: buffer.readerIndex, endianness: .big, as: UInt16.self) else {
|
||||||
|
return .needMoreData
|
||||||
|
}
|
||||||
|
|
||||||
|
if buffer.readableBytes >= len + 2 {
|
||||||
|
buffer.moveReaderIndex(forwardBy: 2)
|
||||||
|
if let bytes = buffer.readBytes(length: Int(len)) {
|
||||||
|
context.fireChannelRead(self.wrapInboundOut(ByteBuffer(bytes: bytes)))
|
||||||
|
}
|
||||||
|
return .continue
|
||||||
|
} else {
|
||||||
|
return .needMoreData
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
89
Tun/Punchnet/Actors/SDLTunnelProviderActor.swift
Normal file
89
Tun/Punchnet/Actors/SDLTunnelProviderActor.swift
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
//
|
||||||
|
// SDLContext.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/2/29.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import NetworkExtension
|
||||||
|
import NIOCore
|
||||||
|
import Combine
|
||||||
|
|
||||||
|
// 上下文环境变量,全局共享
|
||||||
|
/*
|
||||||
|
1. 处理rsa的加解密逻辑
|
||||||
|
*/
|
||||||
|
|
||||||
|
actor SDLTunnelProviderActor {
|
||||||
|
|
||||||
|
// 路由信息
|
||||||
|
struct Route {
|
||||||
|
let dstAddress: String
|
||||||
|
let subnetMask: String
|
||||||
|
|
||||||
|
var debugInfo: String {
|
||||||
|
return "\(dstAddress):\(subnetMask)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 数据包读取任务
|
||||||
|
private var readTask: Task<(), Never>?
|
||||||
|
|
||||||
|
let provider: NEPacketTunnelProvider
|
||||||
|
let logger: SDLLogger
|
||||||
|
|
||||||
|
public init(provider: NEPacketTunnelProvider, logger: SDLLogger) {
|
||||||
|
self.logger = logger
|
||||||
|
self.provider = provider
|
||||||
|
}
|
||||||
|
|
||||||
|
func writePackets(packets: [NEPacket]) {
|
||||||
|
//let packet = NEPacket(data: ipPacket.data, protocolFamily: 2)
|
||||||
|
self.provider.packetFlow.writePacketObjects(packets)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 网络改变时需要重新配置网络信息
|
||||||
|
func setNetworkSettings(devAddr: SDLDevAddr, dnsServer: String) async throws -> String {
|
||||||
|
let netAddress = SDLNetAddress(ip: devAddr.netAddr, maskLen: UInt8(devAddr.netBitLen))
|
||||||
|
let routes = [
|
||||||
|
Route(dstAddress: netAddress.networkAddress, subnetMask: netAddress.maskAddress),
|
||||||
|
Route(dstAddress: dnsServer, subnetMask: "255.255.255.255")
|
||||||
|
]
|
||||||
|
|
||||||
|
// Add code here to start the process of connecting the tunnel.
|
||||||
|
let networkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "8.8.8.8")
|
||||||
|
networkSettings.mtu = 1460
|
||||||
|
|
||||||
|
// 设置网卡的DNS解析
|
||||||
|
|
||||||
|
let networkDomain = devAddr.networkDomain
|
||||||
|
let dnsSettings = NEDNSSettings(servers: [dnsServer])
|
||||||
|
dnsSettings.searchDomains = [networkDomain]
|
||||||
|
dnsSettings.matchDomains = [networkDomain]
|
||||||
|
dnsSettings.matchDomainsNoSearch = false
|
||||||
|
networkSettings.dnsSettings = dnsSettings
|
||||||
|
self.logger.log("[SDLContext] Tun started at network ip: \(netAddress.ipAddress), mask: \(netAddress.maskAddress)", level: .info)
|
||||||
|
|
||||||
|
let ipv4Settings = NEIPv4Settings(addresses: [netAddress.ipAddress], subnetMasks: [netAddress.maskAddress])
|
||||||
|
// 设置路由表
|
||||||
|
//NEIPv4Route.default()
|
||||||
|
ipv4Settings.includedRoutes = routes.map { route in
|
||||||
|
NEIPv4Route(destinationAddress: route.dstAddress, subnetMask: route.subnetMask)
|
||||||
|
}
|
||||||
|
networkSettings.ipv4Settings = ipv4Settings
|
||||||
|
// 网卡配置设置必须成功
|
||||||
|
try await self.provider.setTunnelNetworkSettings(networkSettings)
|
||||||
|
|
||||||
|
return netAddress.ipAddress
|
||||||
|
}
|
||||||
|
|
||||||
|
// 开始读取数据, 用单独的线程处理packetFlow
|
||||||
|
func readPackets() async -> [Data] {
|
||||||
|
let (packets, numbers) = await self.provider.packetFlow.readPackets()
|
||||||
|
return zip(packets, numbers).compactMap { (data, number) in
|
||||||
|
return number == 2 ? data : nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
210
Tun/Punchnet/Actors/SDLUDPHoleActor.swift
Normal file
210
Tun/Punchnet/Actors/SDLUDPHoleActor.swift
Normal file
@ -0,0 +1,210 @@
|
|||||||
|
//
|
||||||
|
// SDLanServer.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/1/31.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import NIOCore
|
||||||
|
import NIOPosix
|
||||||
|
|
||||||
|
// 处理和sn-server服务器之间的通讯
|
||||||
|
actor SDLUDPHoleActor {
|
||||||
|
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||||
|
private let asyncChannel: NIOAsyncChannel<AddressedEnvelope<ByteBuffer>, AddressedEnvelope<ByteBuffer>>
|
||||||
|
private let (writeStream, writeContinuation) = AsyncStream.makeStream(of: UDPMessage.self, bufferingPolicy: .unbounded)
|
||||||
|
|
||||||
|
private var cookieGenerator = SDLIdGenerator(seed: 1)
|
||||||
|
private var promises: [UInt32:EventLoopPromise<SDLStunProbeReply>] = [:]
|
||||||
|
public var localAddress: SocketAddress?
|
||||||
|
|
||||||
|
public let eventFlow: AsyncStream<UDPEvent>
|
||||||
|
private let eventContinuation: AsyncStream<UDPEvent>.Continuation
|
||||||
|
|
||||||
|
private let logger: SDLLogger
|
||||||
|
|
||||||
|
// 依赖的外表能力
|
||||||
|
struct Capabilities {
|
||||||
|
let logger: @Sendable (String) async -> Void
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UDPMessage {
|
||||||
|
let remoteAddress: SocketAddress
|
||||||
|
let type: SDLPacketType
|
||||||
|
let data: Data
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义事件类型
|
||||||
|
enum UDPEvent {
|
||||||
|
case ready
|
||||||
|
case message(SocketAddress, SDLHoleInboundMessage)
|
||||||
|
case data(SDLData)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动函数
|
||||||
|
init(logger: SDLLogger) async throws {
|
||||||
|
self.logger = logger
|
||||||
|
|
||||||
|
(self.eventFlow, self.eventContinuation) = AsyncStream.makeStream(of: UDPEvent.self, bufferingPolicy: .unbounded)
|
||||||
|
|
||||||
|
let bootstrap = DatagramBootstrap(group: group)
|
||||||
|
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||||
|
|
||||||
|
self.asyncChannel = try await bootstrap.bind(host: "0.0.0.0", port: 0)
|
||||||
|
.flatMapThrowing { channel in
|
||||||
|
return try NIOAsyncChannel(wrappingChannelSynchronously: channel, configuration: .init(
|
||||||
|
inboundType: AddressedEnvelope<ByteBuffer>.self,
|
||||||
|
outboundType: AddressedEnvelope<ByteBuffer>.self
|
||||||
|
))
|
||||||
|
}
|
||||||
|
.get()
|
||||||
|
|
||||||
|
self.localAddress = self.asyncChannel.channel.localAddress
|
||||||
|
self.logger.log("[UDPHole] started and listening on: \(self.localAddress!)", level: .debug)
|
||||||
|
}
|
||||||
|
|
||||||
|
func start() async throws {
|
||||||
|
try await withTaskCancellationHandler {
|
||||||
|
try await self.asyncChannel.executeThenClose {inbound, outbound in
|
||||||
|
self.eventContinuation.yield(.ready)
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLUDPHole] inbound closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
for try await envelope in inbound {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
|
var buffer = envelope.data
|
||||||
|
let remoteAddress = envelope.remoteAddress
|
||||||
|
do {
|
||||||
|
if let message = try Self.decode(buffer: &buffer) {
|
||||||
|
switch message {
|
||||||
|
case .data(let data):
|
||||||
|
self.logger.log("[SDLUDPHole] read data: \(data.format()), from: \(remoteAddress)", level: .debug)
|
||||||
|
self.eventContinuation.yield(.data(data))
|
||||||
|
case .stunProbeReply(let probeReply):
|
||||||
|
// 执行并移除回调
|
||||||
|
await self.trigger(probeReply: probeReply)
|
||||||
|
default:
|
||||||
|
self.eventContinuation.yield(.message(remoteAddress, message))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.logger.log("[SDLUDPHole] decode message, get null", level: .warning)
|
||||||
|
}
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLUDPHole] decode message, get error: \(err)", level: .warning)
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLUDPHole] outbound closed", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
for await message in self.writeStream {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
|
var buffer = self.asyncChannel.channel.allocator.buffer(capacity: message.data.count + 1)
|
||||||
|
buffer.writeBytes([message.type.rawValue])
|
||||||
|
buffer.writeBytes(message.data)
|
||||||
|
|
||||||
|
let envelope = AddressedEnvelope<ByteBuffer>(remoteAddress: message.remoteAddress, data: buffer)
|
||||||
|
try await outbound.write(envelope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let _ = try await group.next() {
|
||||||
|
group.cancelAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} onCancel: {
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
self.eventContinuation.finish()
|
||||||
|
self.logger.log("[SDLUDPHole] withTaskCancellationHandler cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getCookieId() -> UInt32 {
|
||||||
|
return self.cookieGenerator.nextId()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 探测tun信息
|
||||||
|
func stunProbe(remoteAddress: SocketAddress, attr: SDLProbeAttr = .none, timeout: Int = 5) async throws -> SDLStunProbeReply {
|
||||||
|
return try await self._stunProbe(remoteAddress: remoteAddress, attr: attr, timeout: timeout).get()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func _stunProbe(remoteAddress: SocketAddress, attr: SDLProbeAttr = .none, timeout: Int) -> EventLoopFuture<SDLStunProbeReply> {
|
||||||
|
let cookie = self.cookieGenerator.nextId()
|
||||||
|
var stunProbe = SDLStunProbe()
|
||||||
|
stunProbe.cookie = cookie
|
||||||
|
stunProbe.attr = UInt32(attr.rawValue)
|
||||||
|
self.send( type: .stunProbe, data: try! stunProbe.serializedData(), remoteAddress: remoteAddress)
|
||||||
|
self.logger.log("[SDLUDPHole] stunProbe: \(remoteAddress)", level: .debug)
|
||||||
|
|
||||||
|
let promise = self.asyncChannel.channel.eventLoop.makePromise(of: SDLStunProbeReply.self)
|
||||||
|
self.promises[cookie] = promise
|
||||||
|
|
||||||
|
return promise.futureResult
|
||||||
|
}
|
||||||
|
|
||||||
|
private func trigger(probeReply: SDLStunProbeReply) {
|
||||||
|
let id = probeReply.cookie
|
||||||
|
// 执行并移除回调
|
||||||
|
if let promise = self.promises[id] {
|
||||||
|
self.asyncChannel.channel.eventLoop.execute {
|
||||||
|
promise.succeed(probeReply)
|
||||||
|
}
|
||||||
|
self.promises.removeValue(forKey: id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: client-client apis
|
||||||
|
// 处理写入逻辑
|
||||||
|
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) {
|
||||||
|
let message = UDPMessage(remoteAddress: remoteAddress, type: type, data: data)
|
||||||
|
self.writeContinuation.yield(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
//--MARK: 编解码器
|
||||||
|
private static func decode(buffer: inout ByteBuffer) throws -> SDLHoleInboundMessage? {
|
||||||
|
guard let type = buffer.readInteger(as: UInt8.self),
|
||||||
|
let packetType = SDLPacketType(rawValue: type),
|
||||||
|
let bytes = buffer.readBytes(length: buffer.readableBytes) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch packetType {
|
||||||
|
case .data:
|
||||||
|
let dataPacket = try SDLData(serializedBytes: bytes)
|
||||||
|
return .data(dataPacket)
|
||||||
|
case .register:
|
||||||
|
let registerPacket = try SDLRegister(serializedBytes: bytes)
|
||||||
|
return .register(registerPacket)
|
||||||
|
case .registerAck:
|
||||||
|
let registerAck = try SDLRegisterAck(serializedBytes: bytes)
|
||||||
|
return .registerAck(registerAck)
|
||||||
|
case .stunReply:
|
||||||
|
let stunReply = try SDLStunReply(serializedBytes: bytes)
|
||||||
|
return .stunReply(stunReply)
|
||||||
|
case .stunProbeReply:
|
||||||
|
let stunProbeReply = try SDLStunProbeReply(serializedBytes: bytes)
|
||||||
|
return .stunProbeReply(stunProbeReply)
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
try? self.group.syncShutdownGracefully()
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
self.eventContinuation.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
31
Tun/Punchnet/ArpServer.swift
Normal file
31
Tun/Punchnet/ArpServer.swift
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
//
|
||||||
|
// ArpServer.swift
|
||||||
|
// sdlan
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2025/7/14.
|
||||||
|
//
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
actor ArpServer {
|
||||||
|
private var known_macs: [UInt32:Data] = [:]
|
||||||
|
|
||||||
|
init(known_macs: [UInt32:Data]) {
|
||||||
|
self.known_macs = known_macs
|
||||||
|
}
|
||||||
|
|
||||||
|
func query(ip: UInt32) -> Data? {
|
||||||
|
return self.known_macs[ip]
|
||||||
|
}
|
||||||
|
|
||||||
|
func append(ip: UInt32, mac: Data) {
|
||||||
|
self.known_macs[ip] = mac
|
||||||
|
}
|
||||||
|
|
||||||
|
func remove(ip: UInt32) {
|
||||||
|
self.known_macs.removeValue(forKey: ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
func clear() {
|
||||||
|
self.known_macs = [:]
|
||||||
|
}
|
||||||
|
}
|
||||||
86
Tun/Punchnet/IPPacket.swift
Normal file
86
Tun/Punchnet/IPPacket.swift
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
//
|
||||||
|
// IPPacket.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/1/18.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct IPHeader {
|
||||||
|
let version: UInt8
|
||||||
|
let headerLength: UInt8
|
||||||
|
let typeOfService: UInt8
|
||||||
|
let totalLength: UInt16
|
||||||
|
let id: UInt16
|
||||||
|
let offset: UInt16
|
||||||
|
let timeToLive: UInt8
|
||||||
|
let proto:UInt8
|
||||||
|
let checksum: UInt16
|
||||||
|
let source: UInt32
|
||||||
|
let destination: UInt32
|
||||||
|
|
||||||
|
var source_ip: String {
|
||||||
|
return intToIp(source)
|
||||||
|
}
|
||||||
|
|
||||||
|
var destination_ip: String {
|
||||||
|
return intToIp(destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func intToIp(_ num: UInt32) -> String {
|
||||||
|
let ip0 = (UInt8) (num >> 24 & 0xFF)
|
||||||
|
let ip1 = (UInt8) (num >> 16 & 0xFF)
|
||||||
|
let ip2 = (UInt8) (num >> 8 & 0xFF)
|
||||||
|
let ip3 = (UInt8) (num & 0xFF)
|
||||||
|
|
||||||
|
return "\(ip0).\(ip1).\(ip2).\(ip3)"
|
||||||
|
}
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
"""
|
||||||
|
IPHeader version: \(version), header length: \(headerLength), type of service: \(typeOfService), total length: \(totalLength),
|
||||||
|
id: \(id), offset: \(offset), time ot live: \(timeToLive), proto: \(proto), checksum: \(checksum), source ip: \(source_ip), destination ip:\(destination_ip)
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum IPVersion: UInt8 {
|
||||||
|
case ipv4 = 4
|
||||||
|
case ipv6 = 6
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TransportProtocol: UInt8 {
|
||||||
|
case icmp = 1
|
||||||
|
case tcp = 6
|
||||||
|
case udp = 17
|
||||||
|
}
|
||||||
|
|
||||||
|
struct IPPacket {
|
||||||
|
let header: IPHeader
|
||||||
|
let data: Data
|
||||||
|
|
||||||
|
init?(_ data: Data) {
|
||||||
|
guard data.count >= 20 else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
self.header = IPHeader(version: data[0] >> 4,
|
||||||
|
headerLength: (data[0] & 0b1111) * 4,
|
||||||
|
typeOfService: data[1],
|
||||||
|
totalLength: UInt16(bytes: (data[2], data[3])),
|
||||||
|
id: UInt16(bytes: (data[4], data[5])),
|
||||||
|
offset: 1,
|
||||||
|
timeToLive: data[8],
|
||||||
|
proto: data[9],
|
||||||
|
checksum: UInt16(bytes: (data[10], data[11])),
|
||||||
|
source: UInt32(bytes: (data[12], data[13], data[14], data[15])),
|
||||||
|
destination: UInt32(bytes: (data[16], data[17], data[18], data[19])))
|
||||||
|
self.data = data
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取负载部分
|
||||||
|
func getPayload() -> Data {
|
||||||
|
return data.subdata(in: 20..<data.count)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -79,11 +79,10 @@ struct LayerPacket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func marshal() -> Data {
|
func marshal() -> Data {
|
||||||
var packet = Data(capacity: 14 + self.data.count)
|
var packet = Data()
|
||||||
packet.append(dstMac)
|
packet.append(dstMac)
|
||||||
packet.append(srcMac)
|
packet.append(srcMac)
|
||||||
packet.append(UInt8(self.type.rawValue >> 8))
|
packet.append(self.type.rawValue.data())
|
||||||
packet.append(UInt8(self.type.rawValue & 0x00FF))
|
|
||||||
packet.append(self.data)
|
packet.append(self.data)
|
||||||
|
|
||||||
return packet
|
return packet
|
||||||
@ -98,21 +97,3 @@ struct LayerPacket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct LayerPacketView {
|
|
||||||
let type: LayerPacket.PacketType
|
|
||||||
let data: Data
|
|
||||||
|
|
||||||
init(layerData payload: Data) throws {
|
|
||||||
guard payload.count >= 14 else {
|
|
||||||
throw LayerPacket.LayerPacketError.invalidLength
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let type = LayerPacket.PacketType(rawValue: UInt16(bytes: (payload[12], payload[13]))) else {
|
|
||||||
throw LayerPacket.LayerPacketError.invaldPacketType
|
|
||||||
}
|
|
||||||
|
|
||||||
self.type = type
|
|
||||||
self.data = payload.dropFirst(14)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
72
Tun/Punchnet/SDLConfiguration.swift
Normal file
72
Tun/Punchnet/SDLConfiguration.swift
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
//
|
||||||
|
// SDLConfiguration.swift
|
||||||
|
// sdlan
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2025/7/14.
|
||||||
|
//
|
||||||
|
import Foundation
|
||||||
|
import NIOCore
|
||||||
|
|
||||||
|
// 配置项目
|
||||||
|
public class SDLConfiguration {
|
||||||
|
|
||||||
|
public struct StunServer {
|
||||||
|
public let host: String
|
||||||
|
public let ports: [Int]
|
||||||
|
|
||||||
|
public init(host: String, ports: [Int]) {
|
||||||
|
self.host = host
|
||||||
|
self.ports = ports
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前的客户端版本
|
||||||
|
let version: UInt8
|
||||||
|
|
||||||
|
// 安装渠道
|
||||||
|
let installedChannel: String
|
||||||
|
|
||||||
|
let superHost: String
|
||||||
|
let superPort: Int
|
||||||
|
|
||||||
|
let stunServers: [StunServer]
|
||||||
|
|
||||||
|
let remoteDnsServer: String
|
||||||
|
let hostname: String
|
||||||
|
|
||||||
|
let noticePort: Int
|
||||||
|
|
||||||
|
lazy var stunSocketAddress: SocketAddress = {
|
||||||
|
let stunServer = stunServers[0]
|
||||||
|
return try! SocketAddress.makeAddressResolvingHost(stunServer.host, port: stunServer.ports[0])
|
||||||
|
}()
|
||||||
|
|
||||||
|
// 网络探测地址信息
|
||||||
|
lazy var stunProbeSocketAddressArray: [[SocketAddress]] = {
|
||||||
|
return stunServers.map { stunServer in
|
||||||
|
[
|
||||||
|
try! SocketAddress.makeAddressResolvingHost(stunServer.host, port: stunServer.ports[0]),
|
||||||
|
try! SocketAddress.makeAddressResolvingHost(stunServer.host, port: stunServer.ports[1])
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
let clientId: String
|
||||||
|
let token: String
|
||||||
|
let networkCode: String
|
||||||
|
|
||||||
|
public init(version: UInt8, installedChannel: String, superHost: String, superPort: Int, stunServers: [StunServer], clientId: String, noticePort: Int, token: String, networkCode: String, remoteDnsServer: String, hostname: String) {
|
||||||
|
self.version = version
|
||||||
|
self.installedChannel = installedChannel
|
||||||
|
self.superHost = superHost
|
||||||
|
self.superPort = superPort
|
||||||
|
self.stunServers = stunServers
|
||||||
|
self.clientId = clientId
|
||||||
|
self.noticePort = noticePort
|
||||||
|
self.token = token
|
||||||
|
self.networkCode = networkCode
|
||||||
|
self.remoteDnsServer = remoteDnsServer
|
||||||
|
self.hostname = hostname
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
715
Tun/Punchnet/SDLContext.swift
Normal file
715
Tun/Punchnet/SDLContext.swift
Normal file
@ -0,0 +1,715 @@
|
|||||||
|
//
|
||||||
|
// SDLContext.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/2/29.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import NetworkExtension
|
||||||
|
import NIOCore
|
||||||
|
import Combine
|
||||||
|
|
||||||
|
// 上下文环境变量,全局共享
|
||||||
|
/*
|
||||||
|
1. 处理rsa的加解密逻辑
|
||||||
|
*/
|
||||||
|
|
||||||
|
@available(macOS 14, *)
|
||||||
|
public class SDLContext {
|
||||||
|
|
||||||
|
// 路由信息
|
||||||
|
struct Route {
|
||||||
|
let dstAddress: String
|
||||||
|
let subnetMask: String
|
||||||
|
|
||||||
|
var debugInfo: String {
|
||||||
|
return "\(dstAddress):\(subnetMask)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let config: SDLConfiguration
|
||||||
|
|
||||||
|
// tun网络地址信息
|
||||||
|
var devAddr: SDLDevAddr
|
||||||
|
|
||||||
|
// nat映射的相关信息, 暂时没有用处
|
||||||
|
//var natAddress: SDLNatAddress?
|
||||||
|
// nat的网络类型
|
||||||
|
var natType: NatType = .blocked
|
||||||
|
|
||||||
|
// AES加密,授权通过后,对象才会被创建
|
||||||
|
var aesCipher: AESCipher
|
||||||
|
|
||||||
|
// aes
|
||||||
|
var aesKey: Data = Data()
|
||||||
|
|
||||||
|
// rsa的相关配置, public_key是本地生成的
|
||||||
|
let rsaCipher: RSACipher
|
||||||
|
|
||||||
|
// 依赖的变量
|
||||||
|
var udpHoleActor: SDLUDPHoleActor?
|
||||||
|
var superClientActor: SDLSuperClientActor?
|
||||||
|
var providerActor: SDLTunnelProviderActor
|
||||||
|
var puncherActor: SDLPuncherActor
|
||||||
|
// dns的client对象
|
||||||
|
var dnsClientActor: SDLDNSClientActor?
|
||||||
|
|
||||||
|
// 数据包读取任务
|
||||||
|
private var readTask: Task<(), Never>?
|
||||||
|
|
||||||
|
private var sessionManager: SessionManager
|
||||||
|
private var arpServer: ArpServer
|
||||||
|
|
||||||
|
// 记录最后发送的stunRequest的cookie
|
||||||
|
private var lastCookie: UInt32? = 0
|
||||||
|
|
||||||
|
// 网络状态变化的健康
|
||||||
|
private var monitor: SDLNetworkMonitor?
|
||||||
|
|
||||||
|
// 内部socket通讯
|
||||||
|
private var noticeClient: SDLNoticeClient?
|
||||||
|
|
||||||
|
// 流量统计
|
||||||
|
private var flowTracer = SDLFlowTracerActor()
|
||||||
|
private var flowTracerCancel: AnyCancellable?
|
||||||
|
|
||||||
|
private let logger: SDLLogger
|
||||||
|
private var rootTask: Task<Void, Error>?
|
||||||
|
|
||||||
|
public init(provider: NEPacketTunnelProvider, config: SDLConfiguration, rsaCipher: RSACipher, aesCipher: AESCipher, logger: SDLLogger) {
|
||||||
|
self.logger = logger
|
||||||
|
|
||||||
|
self.config = config
|
||||||
|
self.rsaCipher = rsaCipher
|
||||||
|
self.aesCipher = aesCipher
|
||||||
|
|
||||||
|
// 生成mac地址
|
||||||
|
var devAddr = SDLDevAddr()
|
||||||
|
devAddr.mac = Self.getMacAddress()
|
||||||
|
self.devAddr = devAddr
|
||||||
|
|
||||||
|
self.sessionManager = SessionManager()
|
||||||
|
self.arpServer = ArpServer(known_macs: [:])
|
||||||
|
self.providerActor = SDLTunnelProviderActor(provider: provider, logger: logger)
|
||||||
|
self.puncherActor = SDLPuncherActor(logger: logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func start() async throws {
|
||||||
|
self.rootTask = Task {
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
do {
|
||||||
|
try await self.startDnsClient()
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] UDPHole get err: \(err)", level: .warning)
|
||||||
|
try await Task.sleep(for: .seconds(2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
do {
|
||||||
|
try await self.startUDPHole()
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] UDPHole get err: \(err)", level: .warning)
|
||||||
|
try await Task.sleep(for: .seconds(2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
do {
|
||||||
|
try await self.startSuperClient()
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] SuperClient get error: \(err), will restart", level: .warning)
|
||||||
|
await self.arpServer.clear()
|
||||||
|
try await Task.sleep(for: .seconds(2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
await self.startMonitor()
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
do {
|
||||||
|
try await self.startNoticeClient()
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] noticeClient get err: \(err)", level: .warning)
|
||||||
|
try await Task.sleep(for: .seconds(2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try await group.waitForAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try await self.rootTask?.value
|
||||||
|
}
|
||||||
|
|
||||||
|
public func stop() async {
|
||||||
|
self.rootTask?.cancel()
|
||||||
|
self.superClientActor = nil
|
||||||
|
self.udpHoleActor = nil
|
||||||
|
self.noticeClient = nil
|
||||||
|
|
||||||
|
self.readTask?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startNoticeClient() async throws {
|
||||||
|
self.noticeClient = try await SDLNoticeClient(noticePort: self.config.noticePort, logger: self.logger)
|
||||||
|
try await self.noticeClient?.start()
|
||||||
|
self.logger.log("[SDLContext] notice_client task cancel", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startUDPHole() async throws {
|
||||||
|
self.udpHoleActor = try await SDLUDPHoleActor(logger: self.logger)
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
try await self.udpHoleActor?.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
try await Task.sleep(nanoseconds: 5 * 1_000_000_000)
|
||||||
|
try Task.checkCancellation()
|
||||||
|
|
||||||
|
if let udpHoleActor = self.udpHoleActor {
|
||||||
|
let cookie = await udpHoleActor.getCookieId()
|
||||||
|
var stunRequest = SDLStunRequest()
|
||||||
|
stunRequest.cookie = cookie
|
||||||
|
stunRequest.clientID = self.config.clientId
|
||||||
|
stunRequest.networkID = self.devAddr.networkID
|
||||||
|
stunRequest.ip = self.devAddr.netAddr
|
||||||
|
stunRequest.mac = self.devAddr.mac
|
||||||
|
stunRequest.natType = UInt32(self.natType.rawValue)
|
||||||
|
|
||||||
|
let remoteAddress = self.config.stunSocketAddress
|
||||||
|
await udpHoleActor.send(type: .stunRequest, data: try stunRequest.serializedData(), remoteAddress: remoteAddress)
|
||||||
|
self.lastCookie = cookie
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
if let eventFlow = self.udpHoleActor?.eventFlow {
|
||||||
|
for try await event in eventFlow {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
try await self.handleUDPEvent(event: event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let _ = try await group.next() {
|
||||||
|
group.cancelAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startSuperClient() async throws {
|
||||||
|
self.superClientActor = try await SDLSuperClientActor(host: self.config.superHost, port: self.config.superPort, logger: self.logger)
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLContext] super client task cancel", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
try await self.superClientActor?.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
if let eventFlow = self.superClientActor?.eventFlow {
|
||||||
|
for try await event in eventFlow {
|
||||||
|
try await self.handleSuperEvent(event: event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let _ = try await group.next() {
|
||||||
|
group.cancelAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startMonitor() async {
|
||||||
|
self.monitor = SDLNetworkMonitor()
|
||||||
|
for await event in self.monitor!.eventStream {
|
||||||
|
switch event {
|
||||||
|
case .changed:
|
||||||
|
// 需要重新探测网络的nat类型
|
||||||
|
self.natType = await self.getNatType()
|
||||||
|
self.logger.log("didNetworkPathChanged, nat type is: \(self.natType)", level: .info)
|
||||||
|
case .unreachable:
|
||||||
|
self.logger.log("didNetworkPathUnreachable", level: .warning)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startDnsClient() async throws {
|
||||||
|
let remoteDnsServer = config.remoteDnsServer
|
||||||
|
let dnsSocketAddress = try SocketAddress.makeAddressResolvingHost(remoteDnsServer, port: 15353)
|
||||||
|
self.dnsClientActor = try await SDLDNSClientActor(dnsServerAddress: dnsSocketAddress, logger: self.logger)
|
||||||
|
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
defer {
|
||||||
|
self.logger.log("[SDLContext] dns client task cancel", level: .warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
try await self.dnsClientActor?.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
if let packetFlow = self.dnsClientActor?.packetFlow {
|
||||||
|
for await packet in packetFlow {
|
||||||
|
let nePacket = NEPacket(data: packet, protocolFamily: 2)
|
||||||
|
await self.providerActor.writePackets(packets: [nePacket])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if let _ = try await group.next() {
|
||||||
|
group.cancelAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleSuperEvent(event: SDLSuperClientActor.SuperEvent) async throws {
|
||||||
|
switch event {
|
||||||
|
case .ready:
|
||||||
|
await self.puncherActor.setSuperClientActor(superClientActor: self.superClientActor)
|
||||||
|
|
||||||
|
self.logger.log("[SDLContext] get registerSuper, mac address: \(SDLUtil.formatMacAddress(mac: self.devAddr.mac))", level: .debug)
|
||||||
|
var registerSuper = SDLRegisterSuper()
|
||||||
|
registerSuper.version = UInt32(self.config.version)
|
||||||
|
registerSuper.clientID = self.config.clientId
|
||||||
|
registerSuper.devAddr = self.devAddr
|
||||||
|
registerSuper.pubKey = self.rsaCipher.pubKey
|
||||||
|
registerSuper.token = self.config.token
|
||||||
|
registerSuper.networkCode = self.config.networkCode
|
||||||
|
registerSuper.hostname = self.config.hostname
|
||||||
|
guard let message = try await self.superClientActor?.request(type: .registerSuper, data: try registerSuper.serializedData()) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch message.packet {
|
||||||
|
case .registerSuperAck(let registerSuperAck):
|
||||||
|
// 需要对数据通过rsa的私钥解码
|
||||||
|
let aesKey = try! self.rsaCipher.decode(data: Data(registerSuperAck.aesKey))
|
||||||
|
let upgradeType = SDLUpgradeType(rawValue: registerSuperAck.upgradeType)
|
||||||
|
|
||||||
|
self.logger.log("[SDLContext] get registerSuperAck, aes_key len: \(aesKey.count), network_id:\(registerSuperAck.devAddr.networkID)", level: .info)
|
||||||
|
self.devAddr = registerSuperAck.devAddr
|
||||||
|
|
||||||
|
if upgradeType == .force {
|
||||||
|
let forceUpgrade = NoticeMessage.upgrade(prompt: registerSuperAck.upgradePrompt, address: registerSuperAck.upgradeAddress)
|
||||||
|
await self.noticeClient?.send(data: forceUpgrade)
|
||||||
|
exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 服务器分配的tun网卡信息
|
||||||
|
do {
|
||||||
|
let ipAddress = try await self.providerActor.setNetworkSettings(devAddr: self.devAddr, dnsServer: SDLDNSClientActor.Helper.dnsServer)
|
||||||
|
await self.noticeClient?.send(data: NoticeMessage.ipAdress(ip: ipAddress))
|
||||||
|
|
||||||
|
self.startReader()
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] setTunnelNetworkSettings get error: \(err)", level: .error)
|
||||||
|
exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.aesKey = aesKey
|
||||||
|
if upgradeType == .normal {
|
||||||
|
let normalUpgrade = NoticeMessage.upgrade(prompt: registerSuperAck.upgradePrompt, address: registerSuperAck.upgradeAddress)
|
||||||
|
await self.noticeClient?.send(data: normalUpgrade)
|
||||||
|
}
|
||||||
|
|
||||||
|
case .registerSuperNak(let nakPacket):
|
||||||
|
let errorMessage = nakPacket.errorMessage
|
||||||
|
guard let errorCode = SDLNAKErrorCode(rawValue: UInt8(nakPacket.errorCode)) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch errorCode {
|
||||||
|
case .invalidToken, .nodeDisabled:
|
||||||
|
let alertNotice = NoticeMessage.alert(alert: errorMessage)
|
||||||
|
await self.noticeClient?.send(data: alertNotice)
|
||||||
|
exit(-1)
|
||||||
|
case .noIpAddress, .networkFault, .internalFault:
|
||||||
|
let alertNotice = NoticeMessage.alert(alert: errorMessage)
|
||||||
|
await self.noticeClient?.send(data: alertNotice)
|
||||||
|
}
|
||||||
|
self.logger.log("[SDLContext] Get a SuperNak message exit", level: .warning)
|
||||||
|
default:
|
||||||
|
()
|
||||||
|
}
|
||||||
|
|
||||||
|
case .event(let evt):
|
||||||
|
switch evt {
|
||||||
|
case .natChanged(let natChangedEvent):
|
||||||
|
let dstMac = natChangedEvent.mac
|
||||||
|
self.logger.log("[SDLContext] natChangedEvent, dstMac: \(dstMac)", level: .info)
|
||||||
|
await sessionManager.removeSession(dstMac: dstMac)
|
||||||
|
case .sendRegister(let sendRegisterEvent):
|
||||||
|
self.logger.log("[SDLContext] sendRegisterEvent, ip: \(sendRegisterEvent)", level: .debug)
|
||||||
|
let address = SDLUtil.int32ToIp(sendRegisterEvent.natIp)
|
||||||
|
if let remoteAddress = try? SocketAddress.makeAddressResolvingHost(address, port: Int(sendRegisterEvent.natPort)) {
|
||||||
|
// 发送register包
|
||||||
|
var register = SDLRegister()
|
||||||
|
register.networkID = self.devAddr.networkID
|
||||||
|
register.srcMac = self.devAddr.mac
|
||||||
|
register.dstMac = sendRegisterEvent.dstMac
|
||||||
|
await self.udpHoleActor?.send(type: .register, data: try register.serializedData(), remoteAddress: remoteAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
case .networkShutdown(let shutdownEvent):
|
||||||
|
let alertNotice = NoticeMessage.alert(alert: shutdownEvent.message)
|
||||||
|
await self.noticeClient?.send(data: alertNotice)
|
||||||
|
exit(-1)
|
||||||
|
}
|
||||||
|
case .command(let packetId, let command):
|
||||||
|
switch command {
|
||||||
|
case .changeNetwork(let changeNetworkCommand):
|
||||||
|
// 需要对数据通过rsa的私钥解码
|
||||||
|
let aesKey = try! self.rsaCipher.decode(data: Data(changeNetworkCommand.aesKey))
|
||||||
|
self.logger.log("[SDLContext] change network command get aes_key len: \(aesKey.count)", level: .info)
|
||||||
|
self.devAddr = changeNetworkCommand.devAddr
|
||||||
|
|
||||||
|
// 服务器分配的tun网卡信息
|
||||||
|
do {
|
||||||
|
let ipAddress = try await self.providerActor.setNetworkSettings(devAddr: self.devAddr, dnsServer: SDLDNSClientActor.Helper.dnsServer)
|
||||||
|
await self.noticeClient?.send(data: NoticeMessage.ipAdress(ip: ipAddress))
|
||||||
|
|
||||||
|
self.startReader()
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] setTunnelNetworkSettings get error: \(err)", level: .error)
|
||||||
|
exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
self.aesKey = aesKey
|
||||||
|
|
||||||
|
var commandAck = SDLCommandAck()
|
||||||
|
commandAck.status = true
|
||||||
|
await self.superClientActor?.send(type: .commandAck, packetId: packetId, data: try commandAck.serializedData())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleUDPEvent(event: SDLUDPHoleActor.UDPEvent) async throws {
|
||||||
|
switch event {
|
||||||
|
case .ready:
|
||||||
|
await self.puncherActor.setUDPHoleActor(udpHoleActor: self.udpHoleActor)
|
||||||
|
// 获取当前网络的类型
|
||||||
|
self.natType = await getNatType()
|
||||||
|
self.logger.log("[SDLContext] broadcast is: \(self.natType)", level: .debug)
|
||||||
|
|
||||||
|
case .message(let remoteAddress, let message):
|
||||||
|
switch message {
|
||||||
|
case .register(let register):
|
||||||
|
self.logger.log("register packet: \(register), dev_addr: \(self.devAddr)", level: .debug)
|
||||||
|
// 判断目标地址是否是tun的网卡地址, 并且是在同一个网络下
|
||||||
|
if register.dstMac == self.devAddr.mac && register.networkID == self.devAddr.networkID {
|
||||||
|
// 回复ack包
|
||||||
|
var registerAck = SDLRegisterAck()
|
||||||
|
registerAck.networkID = self.devAddr.networkID
|
||||||
|
registerAck.srcMac = self.devAddr.mac
|
||||||
|
registerAck.dstMac = register.srcMac
|
||||||
|
|
||||||
|
await self.udpHoleActor?.send(type: .registerAck, data: try registerAck.serializedData(), remoteAddress: remoteAddress)
|
||||||
|
// 这里需要建立到来源的会话, 在复杂网络下,通过super-node查询到的nat地址不一定靠谱,需要通过udp包的来源地址作为nat地址
|
||||||
|
let session = Session(dstMac: register.srcMac, natAddress: remoteAddress)
|
||||||
|
await self.sessionManager.addSession(session: session)
|
||||||
|
} else {
|
||||||
|
self.logger.log("SDLContext didReadRegister get a invalid packet, because dst_ip not matched: \(register.dstMac)", level: .warning)
|
||||||
|
}
|
||||||
|
case .registerAck(let registerAck):
|
||||||
|
// 判断目标地址是否是tun的网卡地址, 并且是在同一个网络下
|
||||||
|
if registerAck.dstMac == self.devAddr.mac && registerAck.networkID == self.devAddr.networkID {
|
||||||
|
let session = Session(dstMac: registerAck.srcMac, natAddress: remoteAddress)
|
||||||
|
await self.sessionManager.addSession(session: session)
|
||||||
|
} else {
|
||||||
|
self.logger.log("SDLContext didReadRegisterAck get a invalid packet, because dst_mac not matched: \(registerAck.dstMac)", level: .warning)
|
||||||
|
}
|
||||||
|
case .stunReply(let stunReply):
|
||||||
|
let cookie = stunReply.cookie
|
||||||
|
if cookie == self.lastCookie {
|
||||||
|
// 记录下当前在nat上的映射信息,暂时没有用;后续会用来判断网络类型
|
||||||
|
//self.natAddress = stunReply.natAddress
|
||||||
|
self.logger.log("[SDLContext] get a stunReply: \(try! stunReply.jsonString())", level: .debug)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
()
|
||||||
|
}
|
||||||
|
|
||||||
|
case .data(let data):
|
||||||
|
let mac = LayerPacket.MacAddress(data: data.dstMac)
|
||||||
|
guard (data.dstMac == self.devAddr.mac || mac.isBroadcast() || mac.isMulticast()) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let decyptedData = try? self.aesCipher.decypt(aesKey: self.aesKey, data: Data(data.data)) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
let layerPacket = try LayerPacket(layerData: decyptedData)
|
||||||
|
|
||||||
|
await self.flowTracer.inc(num: decyptedData.count, type: .inbound)
|
||||||
|
// 处理arp请求
|
||||||
|
switch layerPacket.type {
|
||||||
|
case .arp:
|
||||||
|
// 判断如果收到的是arp请求
|
||||||
|
if let arpPacket = ARPPacket(data: layerPacket.data) {
|
||||||
|
if arpPacket.targetIP == self.devAddr.netAddr {
|
||||||
|
switch arpPacket.opcode {
|
||||||
|
case .request:
|
||||||
|
self.logger.log("[SDLContext] get arp request packet", level: .debug)
|
||||||
|
let response = ARPPacket.arpResponse(for: arpPacket, mac: self.devAddr.mac, ip: self.devAddr.netAddr)
|
||||||
|
await self.routeLayerPacket(dstMac: arpPacket.senderMAC, type: .arp, data: response.marshal())
|
||||||
|
case .response:
|
||||||
|
self.logger.log("[SDLContext] get arp response packet", level: .debug)
|
||||||
|
await self.arpServer.append(ip: arpPacket.senderIP, mac: arpPacket.senderMAC)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.logger.log("[SDLContext] get invalid arp packet: \(arpPacket), target_ip: \(SDLUtil.int32ToIp(arpPacket.targetIP)), net ip: \(SDLUtil.int32ToIp(self.devAddr.netAddr))", level: .debug)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.logger.log("[SDLContext] get invalid arp packet", level: .debug)
|
||||||
|
}
|
||||||
|
case .ipv4:
|
||||||
|
guard let ipPacket = IPPacket(layerPacket.data), ipPacket.header.destination == self.devAddr.netAddr else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let packet = NEPacket(data: ipPacket.data, protocolFamily: 2)
|
||||||
|
await self.providerActor.writePackets(packets: [packet])
|
||||||
|
default:
|
||||||
|
self.logger.log("[SDLContext] get invalid packet", level: .debug)
|
||||||
|
}
|
||||||
|
} catch let err {
|
||||||
|
self.logger.log("[SDLContext] didReadData err: \(err)", level: .warning)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// 流量统计
|
||||||
|
// public func flowReportTask() {
|
||||||
|
// Task {
|
||||||
|
// // 每分钟汇报一次
|
||||||
|
// self.flowTracerCancel = Timer.publish(every: 60.0, on: .main, in: .common).autoconnect()
|
||||||
|
// .sink { _ in
|
||||||
|
// Task {
|
||||||
|
// let (forwardNum, p2pNum, inboundNum) = await self.flowTracer.reset()
|
||||||
|
// await self.superClient?.flowReport(forwardNum: forwardNum, p2pNum: p2pNum, inboundNum: inboundNum)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// 开始读取数据, 用单独的线程处理packetFlow
|
||||||
|
private func startReader() {
|
||||||
|
// 停止之前的任务
|
||||||
|
self.readTask?.cancel()
|
||||||
|
|
||||||
|
// 开启新的任务
|
||||||
|
self.readTask = Task(priority: .high) {
|
||||||
|
repeat {
|
||||||
|
let packets = await self.providerActor.readPackets()
|
||||||
|
for packet in packets {
|
||||||
|
await self.dealPacket(data: packet)
|
||||||
|
}
|
||||||
|
} while true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理读取的每个数据包
|
||||||
|
private func dealPacket(data: Data) async {
|
||||||
|
guard let packet = IPPacket(data) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if SDLDNSClientActor.Helper.isDnsRequestPacket(ipPacket: packet) {
|
||||||
|
let destIp = packet.header.destination_ip
|
||||||
|
self.logger.log("[DNSQuery] destIp: \(destIp), int: \(packet.header.destination.asIpAddress())", level: .debug)
|
||||||
|
await self.dnsClientActor?.forward(ipPacket: packet)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Task.detached {
|
||||||
|
let dstIp = packet.header.destination
|
||||||
|
// 本地通讯, 目标地址是本地服务器的ip地址
|
||||||
|
if dstIp == self.devAddr.netAddr {
|
||||||
|
let nePacket = NEPacket(data: packet.data, protocolFamily: 2)
|
||||||
|
await self.providerActor.writePackets(packets: [nePacket])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查找arp缓存中是否有目标mac地址
|
||||||
|
if let dstMac = await self.arpServer.query(ip: dstIp) {
|
||||||
|
await self.routeLayerPacket(dstMac: dstMac, type: .ipv4, data: packet.data)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
self.logger.log("[SDLContext] dstIp: \(dstIp.asIpAddress()) arp query not found, broadcast", level: .debug)
|
||||||
|
// 构造arp广播
|
||||||
|
let arpReqeust = ARPPacket.arpRequest(senderIP: self.devAddr.netAddr, senderMAC: self.devAddr.mac, targetIP: dstIp)
|
||||||
|
await self.routeLayerPacket(dstMac: ARPPacket.broadcastMac , type: .arp, data: arpReqeust.marshal())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func routeLayerPacket(dstMac: Data, type: LayerPacket.PacketType, data: Data) async {
|
||||||
|
// 将数据封装层2层的数据包
|
||||||
|
let layerPacket = LayerPacket(dstMac: dstMac, srcMac: self.devAddr.mac, type: type, data: data)
|
||||||
|
guard let encodedPacket = try? self.aesCipher.encrypt(aesKey: self.aesKey, data: layerPacket.marshal()) else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构造数据包
|
||||||
|
var dataPacket = SDLData()
|
||||||
|
dataPacket.networkID = self.devAddr.networkID
|
||||||
|
dataPacket.srcMac = self.devAddr.mac
|
||||||
|
dataPacket.dstMac = dstMac
|
||||||
|
dataPacket.ttl = 255
|
||||||
|
dataPacket.data = encodedPacket
|
||||||
|
|
||||||
|
let data = try! dataPacket.serializedData()
|
||||||
|
// 广播地址不要去尝试打洞
|
||||||
|
if ARPPacket.isBroadcastMac(dstMac) {
|
||||||
|
// 通过super_node进行转发
|
||||||
|
await self.udpHoleActor?.send(type: .data, data: data, remoteAddress: self.config.stunSocketAddress)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// 通过session发送到对端
|
||||||
|
if let session = await self.sessionManager.getSession(toAddress: dstMac) {
|
||||||
|
self.logger.log("[SDLContext] send packet by session: \(session)", level: .debug)
|
||||||
|
await self.udpHoleActor?.send(type: .data, data: data, remoteAddress: session.natAddress)
|
||||||
|
await self.flowTracer.inc(num: data.count, type: .p2p)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// 通过super_node进行转发
|
||||||
|
await self.udpHoleActor?.send(type: .data, data: data, remoteAddress: self.config.stunSocketAddress)
|
||||||
|
// 流量统计
|
||||||
|
await self.flowTracer.inc(num: data.count, type: .forward)
|
||||||
|
// 尝试打洞
|
||||||
|
await self.puncherActor.submitRegisterRequest(request: .init(srcMac: self.devAddr.mac, dstMac: dstMac, networkId: self.devAddr.networkID))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
self.rootTask?.cancel()
|
||||||
|
self.udpHoleActor = nil
|
||||||
|
self.superClientActor = nil
|
||||||
|
self.dnsClientActor = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取mac地址
|
||||||
|
public static func getMacAddress() -> Data {
|
||||||
|
let key = "gMacAddress2"
|
||||||
|
|
||||||
|
let userDefaults = UserDefaults.standard
|
||||||
|
if let mac = userDefaults.value(forKey: key) as? Data {
|
||||||
|
return mac
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
let mac = generateMacAddress()
|
||||||
|
userDefaults.setValue(mac, forKey: key)
|
||||||
|
|
||||||
|
return mac
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 随机生成mac地址
|
||||||
|
private static func generateMacAddress() -> Data {
|
||||||
|
var macAddress = [UInt8](repeating: 0, count: 6)
|
||||||
|
for i in 0..<6 {
|
||||||
|
macAddress[i] = UInt8.random(in: 0...255)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Data(macAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// 网络类型探测
|
||||||
|
extension SDLContext {
|
||||||
|
// 定义nat类型
|
||||||
|
enum NatType: UInt8, Encodable {
|
||||||
|
case blocked = 0
|
||||||
|
case noNat = 1
|
||||||
|
case fullCone = 2
|
||||||
|
case portRestricted = 3
|
||||||
|
case coneRestricted = 4
|
||||||
|
case symmetric = 5
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取当前所处的网络的nat类型
|
||||||
|
func getNatType() async -> NatType {
|
||||||
|
guard let udpHole = self.udpHoleActor else {
|
||||||
|
return .blocked
|
||||||
|
}
|
||||||
|
|
||||||
|
let addressArray = config.stunProbeSocketAddressArray
|
||||||
|
// step1: ip1:port1 <---- ip1:port1
|
||||||
|
guard let natAddress1 = await getNatAddress(udpHole, remoteAddress: addressArray[0][0], attr: .none) else {
|
||||||
|
return .blocked
|
||||||
|
}
|
||||||
|
|
||||||
|
// 网络没有在nat下
|
||||||
|
if await natAddress1 == udpHole.localAddress {
|
||||||
|
return .noNat
|
||||||
|
}
|
||||||
|
|
||||||
|
// step2: ip2:port2 <---- ip2:port2
|
||||||
|
guard let natAddress2 = await getNatAddress(udpHole, remoteAddress: addressArray[1][1], attr: .none) else {
|
||||||
|
return .blocked
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果natAddress2 的IP地址与上次回来的IP是不一样的,它就是对称型NAT; 这次的包也一定能发成功并收到
|
||||||
|
// 如果ip地址变了,这说明{dstIp, dstPort, srcIp, srcPort}, 其中有一个变了;则用新的ip地址
|
||||||
|
logger.log("[SDLNatProber] nat_address1: \(natAddress1), nat_address2: \(natAddress2)", level: .debug)
|
||||||
|
if let ipAddress1 = natAddress1.ipAddress, let ipAddress2 = natAddress2.ipAddress, ipAddress1 != ipAddress2 {
|
||||||
|
return .symmetric
|
||||||
|
}
|
||||||
|
|
||||||
|
// step3: ip1:port1 <---- ip2:port2 (ip地址和port都变的情况)
|
||||||
|
// 如果能收到的,说明是完全锥形 说明是IP地址限制锥型NAT,如果不能收到说明是端口限制锥型。
|
||||||
|
if let natAddress3 = await getNatAddress(udpHole, remoteAddress: addressArray[0][0], attr: .peer) {
|
||||||
|
logger.log("[SDLNatProber] nat_address1: \(natAddress1), nat_address2: \(natAddress2), nat_address3: \(natAddress3)", level: .debug)
|
||||||
|
return .fullCone
|
||||||
|
}
|
||||||
|
|
||||||
|
// step3: ip1:port1 <---- ip1:port2 (port改变情况)
|
||||||
|
// 如果能收到的说明是IP地址限制锥型NAT,如果不能收到说明是端口限制锥型。
|
||||||
|
if let natAddress4 = await getNatAddress(udpHole, remoteAddress: addressArray[0][0], attr: .port) {
|
||||||
|
logger.log("[SDLNatProber] nat_address1: \(natAddress1), nat_address2: \(natAddress2), nat_address4: \(natAddress4)", level: .debug)
|
||||||
|
return .coneRestricted
|
||||||
|
} else {
|
||||||
|
return .portRestricted
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func getNatAddress(_ udpHole: SDLUDPHoleActor, remoteAddress: SocketAddress, attr: SDLProbeAttr) async -> SocketAddress? {
|
||||||
|
let stunProbeReply = try? await udpHole.stunProbe(remoteAddress: remoteAddress, attr: attr, timeout: 5)
|
||||||
|
return stunProbeReply?.socketAddress()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private extension UInt32 {
|
||||||
|
// 转换成ip地址
|
||||||
|
func asIpAddress() -> String {
|
||||||
|
return SDLUtil.int32ToIp(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -8,7 +8,4 @@
|
|||||||
enum SDLError: Error {
|
enum SDLError: Error {
|
||||||
case socketClosed
|
case socketClosed
|
||||||
case socketError
|
case socketError
|
||||||
|
|
||||||
case invalidKey
|
|
||||||
case unsupportedAlgorithm(algorithm: String)
|
|
||||||
}
|
}
|
||||||
@ -6,10 +6,9 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
import Darwin
|
|
||||||
|
|
||||||
// 流量统计器
|
// 流量统计器
|
||||||
final class SDLFlowTracer {
|
actor SDLFlowTracerActor {
|
||||||
enum FlowType {
|
enum FlowType {
|
||||||
case forward
|
case forward
|
||||||
case p2p
|
case p2p
|
||||||
@ -20,14 +19,7 @@ final class SDLFlowTracer {
|
|||||||
private var p2pFlowBytes: UInt32 = 0
|
private var p2pFlowBytes: UInt32 = 0
|
||||||
private var inFlowBytes: UInt32 = 0
|
private var inFlowBytes: UInt32 = 0
|
||||||
|
|
||||||
private let lock = NSLock()
|
|
||||||
|
|
||||||
func inc(num: Int, type: FlowType) {
|
func inc(num: Int, type: FlowType) {
|
||||||
lock.lock()
|
|
||||||
defer {
|
|
||||||
lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch type {
|
switch type {
|
||||||
case .inbound:
|
case .inbound:
|
||||||
self.inFlowBytes += UInt32(num)
|
self.inFlowBytes += UInt32(num)
|
||||||
@ -39,14 +31,13 @@ final class SDLFlowTracer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func reset() -> (UInt32, UInt32, UInt32) {
|
func reset() -> (UInt32, UInt32, UInt32) {
|
||||||
lock.lock()
|
|
||||||
defer {
|
defer {
|
||||||
self.forwardFlowBytes = 0
|
self.forwardFlowBytes = 0
|
||||||
self.inFlowBytes = 0
|
self.inFlowBytes = 0
|
||||||
self.p2pFlowBytes = 0
|
self.p2pFlowBytes = 0
|
||||||
lock.unlock()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (forwardFlowBytes, p2pFlowBytes, inFlowBytes)
|
return (forwardFlowBytes, p2pFlowBytes, inFlowBytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
46
Tun/Punchnet/SDLLogger.swift
Normal file
46
Tun/Punchnet/SDLLogger.swift
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
//
|
||||||
|
// SDLLogger.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/3/13.
|
||||||
|
//
|
||||||
|
import Foundation
|
||||||
|
import os.log
|
||||||
|
|
||||||
|
public class SDLLogger: @unchecked Sendable {
|
||||||
|
public enum Level: Int8, CustomStringConvertible {
|
||||||
|
case debug = 0
|
||||||
|
case info = 1
|
||||||
|
case warning = 2
|
||||||
|
case error = 3
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
switch self {
|
||||||
|
case .debug:
|
||||||
|
return "Debug"
|
||||||
|
case .info:
|
||||||
|
return "Info"
|
||||||
|
case .warning:
|
||||||
|
return "Warning"
|
||||||
|
case .error:
|
||||||
|
return "Error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private let level: Level
|
||||||
|
private let log: OSLog
|
||||||
|
|
||||||
|
public init(level: Level) {
|
||||||
|
self.level = level
|
||||||
|
self.log = OSLog(subsystem: "com.jihe.punchnet", category: "punchnet")
|
||||||
|
}
|
||||||
|
|
||||||
|
public func log(_ message: String, level: Level = .debug) {
|
||||||
|
if self.level.rawValue <= level.rawValue {
|
||||||
|
//os_log("%{public}@: %{public}@", log: self.log, type: .debug, level.description, message)
|
||||||
|
NSLog("\(level.description): \(message)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@ -21,13 +21,19 @@ enum SDLPacketType: UInt8 {
|
|||||||
case queryInfo = 0x06
|
case queryInfo = 0x06
|
||||||
case peerInfo = 0x07
|
case peerInfo = 0x07
|
||||||
|
|
||||||
// 心跳机制
|
|
||||||
case ping = 0x08
|
case ping = 0x08
|
||||||
case pong = 0x09
|
case pong = 0x09
|
||||||
|
|
||||||
// 事件类型
|
// 事件类型
|
||||||
case event = 0x10
|
case event = 0x10
|
||||||
|
|
||||||
|
// 推送命令消息, 需要返回值
|
||||||
|
case command = 0x11
|
||||||
|
case commandAck = 0x12
|
||||||
|
|
||||||
|
// 流量统计
|
||||||
|
case flowTracer = 0x15
|
||||||
|
|
||||||
case register = 0x20
|
case register = 0x20
|
||||||
case registerAck = 0x21
|
case registerAck = 0x21
|
||||||
|
|
||||||
@ -37,23 +43,16 @@ enum SDLPacketType: UInt8 {
|
|||||||
case stunProbe = 0x32
|
case stunProbe = 0x32
|
||||||
case stunProbeReply = 0x33
|
case stunProbeReply = 0x33
|
||||||
|
|
||||||
// arp查询
|
|
||||||
case arpRequest = 0x50
|
|
||||||
case arpResponse = 0x51
|
|
||||||
|
|
||||||
// 权限控制
|
|
||||||
case policyRequest = 0xb0
|
|
||||||
case policyResponse = 0xb1
|
|
||||||
|
|
||||||
case exposedServiceRequest = 0xb2
|
|
||||||
case exposedServiceResponse = 0xb3
|
|
||||||
|
|
||||||
// 获取欢迎消息
|
|
||||||
case welcome = 0x4F
|
|
||||||
|
|
||||||
case data = 0xFF
|
case data = 0xFF
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 升级策略
|
||||||
|
enum SDLUpgradeType: UInt32 {
|
||||||
|
case none = 0
|
||||||
|
case normal = 1
|
||||||
|
case force = 2
|
||||||
|
}
|
||||||
|
|
||||||
// Id生成器
|
// Id生成器
|
||||||
struct SDLIdGenerator: Sendable {
|
struct SDLIdGenerator: Sendable {
|
||||||
// 消息体id
|
// 消息体id
|
||||||
@ -72,6 +71,29 @@ struct SDLIdGenerator: Sendable {
|
|||||||
|
|
||||||
// 定义事件类型
|
// 定义事件类型
|
||||||
|
|
||||||
|
// 命令类型
|
||||||
|
enum SDLEventType: UInt8 {
|
||||||
|
case natChanged = 0x03
|
||||||
|
case sendRegister = 0x04
|
||||||
|
case networkShutdown = 0xFF
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SDLEvent {
|
||||||
|
case natChanged(SDLNatChangedEvent)
|
||||||
|
case sendRegister(SDLSendRegisterEvent)
|
||||||
|
case networkShutdown(SDLNetworkShutdownEvent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --MARK: 定义命令类型
|
||||||
|
|
||||||
|
enum SDLCommandType: UInt8 {
|
||||||
|
case changeNetwork = 0x01
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SDLCommand {
|
||||||
|
case changeNetwork(SDLChangeNetworkCommand)
|
||||||
|
}
|
||||||
|
|
||||||
// --MARK: 网络类型探测
|
// --MARK: 网络类型探测
|
||||||
// 探测的Attr属性
|
// 探测的Attr属性
|
||||||
enum SDLProbeAttr: UInt8 {
|
enum SDLProbeAttr: UInt8 {
|
||||||
@ -90,47 +112,55 @@ enum SDLNAKErrorCode: UInt8 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extension SDLV4Info {
|
extension SDLV4Info {
|
||||||
func socketAddress() async throws -> SocketAddress? {
|
func socketAddress() -> SocketAddress? {
|
||||||
guard self.v4.count == 4 else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
let address = "\(v4[0]).\(v4[1]).\(v4[2]).\(v4[3])"
|
let address = "\(v4[0]).\(v4[1]).\(v4[2]).\(v4[3])"
|
||||||
return try SocketAddress(ipAddress: address, port: Int(port))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SDLV6Info {
|
return try? SocketAddress.makeAddressResolvingHost(address, port: Int(port))
|
||||||
func socketAddress() async throws -> SocketAddress? {
|
|
||||||
guard let address = SDLUtil.ipv6DataToString(self.v6) else {
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return try SocketAddress(ipAddress: address, port: Int(port))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SDLData {
|
|
||||||
|
|
||||||
func format() -> String {
|
|
||||||
return "network_id: \(self.networkID), src_mac: \(LayerPacket.MacAddress.description(data: self.srcMac)), dst_mac: \(LayerPacket.MacAddress.description(data: self.dstMac)), data: \([UInt8](self.data))"
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SDLStunProbeReply {
|
extension SDLStunProbeReply {
|
||||||
func socketAddress() async -> SocketAddress? {
|
func socketAddress() -> SocketAddress? {
|
||||||
let address = SDLUtil.int32ToIp(self.ip)
|
let address = SDLUtil.int32ToIp(self.ip)
|
||||||
|
|
||||||
return try? SocketAddress(ipAddress: address, port: Int(port))
|
return try? SocketAddress.makeAddressResolvingHost(address, port: Int(port))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --MARK: 进来的消息, 这里需要采用代数类型来表示
|
||||||
|
|
||||||
|
enum SDLHoleInboundMessage {
|
||||||
|
case stunReply(SDLStunReply)
|
||||||
|
case stunProbeReply(SDLStunProbeReply)
|
||||||
|
|
||||||
|
case data(SDLData)
|
||||||
|
case register(SDLRegister)
|
||||||
|
case registerAck(SDLRegisterAck)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --MARK: 定义消息类型
|
||||||
|
|
||||||
|
struct SDLSuperInboundMessage {
|
||||||
|
let msgId: UInt32
|
||||||
|
let packet: InboundPacket
|
||||||
|
|
||||||
|
enum InboundPacket {
|
||||||
|
case empty
|
||||||
|
case registerSuperAck(SDLRegisterSuperAck)
|
||||||
|
case registerSuperNak(SDLRegisterSuperNak)
|
||||||
|
case peerInfo(SDLPeerInfo)
|
||||||
|
case pong
|
||||||
|
case event(SDLEvent)
|
||||||
|
case command(SDLCommand)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPong() -> Bool {
|
||||||
|
switch self.packet {
|
||||||
|
case .pong:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 命令类型
|
|
||||||
enum SDLEventType: UInt8 {
|
|
||||||
case natChanged = 0x03
|
|
||||||
case sendRegister = 0x04
|
|
||||||
case networkShutdown = 0xFF
|
|
||||||
}
|
}
|
||||||
49
Tun/Punchnet/SDLNetAddress.swift
Normal file
49
Tun/Punchnet/SDLNetAddress.swift
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
//
|
||||||
|
// SDLIPAddress.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/3/4.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct SDLNetAddress {
|
||||||
|
let ip: UInt32
|
||||||
|
let maskLen: UInt8
|
||||||
|
|
||||||
|
// ip地址
|
||||||
|
var ipAddress: String {
|
||||||
|
return intToIpAddress(self.ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 掩码
|
||||||
|
var maskAddress: String {
|
||||||
|
let len0 = 32 - maskLen
|
||||||
|
let num: UInt32 = (0xFFFFFFFF >> len0) << len0
|
||||||
|
|
||||||
|
return intToIpAddress(num)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 网络地址
|
||||||
|
var networkAddress: String {
|
||||||
|
let len0 = 32 - maskLen
|
||||||
|
let mask: UInt32 = (0xFFFFFFFF >> len0) << len0
|
||||||
|
|
||||||
|
return intToIpAddress(self.ip & mask)
|
||||||
|
}
|
||||||
|
|
||||||
|
init(ip: UInt32, maskLen: UInt8) {
|
||||||
|
self.ip = ip
|
||||||
|
self.maskLen = maskLen
|
||||||
|
}
|
||||||
|
|
||||||
|
private func intToIpAddress(_ num: UInt32) -> String {
|
||||||
|
let ip0 = (UInt8) (num >> 24 & 0xFF)
|
||||||
|
let ip1 = (UInt8) (num >> 16 & 0xFF)
|
||||||
|
let ip2 = (UInt8) (num >> 8 & 0xFF)
|
||||||
|
let ip3 = (UInt8) (num & 0xFF)
|
||||||
|
|
||||||
|
return "\(ip0).\(ip1).\(ip2).\(ip3)"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
64
Tun/Punchnet/SDLNetworkMonitor.swift
Normal file
64
Tun/Punchnet/SDLNetworkMonitor.swift
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
//
|
||||||
|
// SDLNetworkMonitor.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/5/16.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import Network
|
||||||
|
import Combine
|
||||||
|
|
||||||
|
// 监控网络的变化
|
||||||
|
class SDLNetworkMonitor: @unchecked Sendable {
|
||||||
|
private var monitor: NWPathMonitor
|
||||||
|
private var interfaceType: NWInterface.InterfaceType?
|
||||||
|
private let publisher = PassthroughSubject<NWInterface.InterfaceType, Never>()
|
||||||
|
private var cancel: AnyCancellable?
|
||||||
|
|
||||||
|
public let eventStream: AsyncStream<MonitorEvent>
|
||||||
|
private let eventContinuation: AsyncStream<MonitorEvent>.Continuation
|
||||||
|
|
||||||
|
enum MonitorEvent {
|
||||||
|
case changed
|
||||||
|
case unreachable
|
||||||
|
}
|
||||||
|
|
||||||
|
init() {
|
||||||
|
self.monitor = NWPathMonitor()
|
||||||
|
(self.eventStream , self.eventContinuation) = AsyncStream.makeStream(of: MonitorEvent.self, bufferingPolicy: .unbounded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func start() {
|
||||||
|
self.monitor.pathUpdateHandler = {path in
|
||||||
|
if path.status == .satisfied {
|
||||||
|
if path.usesInterfaceType(.wifi) {
|
||||||
|
self.publisher.send(.wifi)
|
||||||
|
} else if path.usesInterfaceType(.cellular) {
|
||||||
|
self.publisher.send(.cellular)
|
||||||
|
} else if path.usesInterfaceType(.wiredEthernet) {
|
||||||
|
self.publisher.send(.wiredEthernet)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.eventContinuation.yield(.unreachable)
|
||||||
|
self.interfaceType = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.monitor.start(queue: DispatchQueue.global())
|
||||||
|
|
||||||
|
self.cancel = publisher.throttle(for: 5.0, scheduler: DispatchQueue.global(), latest: true)
|
||||||
|
.sink { type in
|
||||||
|
if self.interfaceType != nil && self.interfaceType != type {
|
||||||
|
self.eventContinuation.yield(.changed)
|
||||||
|
}
|
||||||
|
self.interfaceType = type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
self.monitor.cancel()
|
||||||
|
self.cancel?.cancel()
|
||||||
|
self.eventContinuation.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
88
Tun/Punchnet/SDLNoticeClient.swift
Normal file
88
Tun/Punchnet/SDLNoticeClient.swift
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
//
|
||||||
|
// SDLNoticeClient.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/5/20.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
//
|
||||||
|
// SDLanServer.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/1/31.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import NIOCore
|
||||||
|
import NIOPosix
|
||||||
|
|
||||||
|
// 处理和sn-server服务器之间的通讯
|
||||||
|
actor SDLNoticeClient {
|
||||||
|
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||||
|
private let asyncChannel: NIOAsyncChannel<AddressedEnvelope<ByteBuffer>, AddressedEnvelope<ByteBuffer>>
|
||||||
|
private let remoteAddress: SocketAddress
|
||||||
|
private let (writeStream, writeContinuation) = AsyncStream.makeStream(of: Data.self, bufferingPolicy: .unbounded)
|
||||||
|
|
||||||
|
private let logger: SDLLogger
|
||||||
|
|
||||||
|
// 启动函数
|
||||||
|
init(noticePort: Int, logger: SDLLogger) async throws {
|
||||||
|
self.logger = logger
|
||||||
|
|
||||||
|
self.remoteAddress = try! SocketAddress(ipAddress: "127.0.0.1", port: noticePort)
|
||||||
|
|
||||||
|
let bootstrap = DatagramBootstrap(group: self.group)
|
||||||
|
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||||
|
|
||||||
|
self.asyncChannel = try await bootstrap.bind(host: "0.0.0.0", port: 0)
|
||||||
|
.flatMapThrowing {channel in
|
||||||
|
return try NIOAsyncChannel(wrappingChannelSynchronously: channel, configuration: .init(
|
||||||
|
inboundType: AddressedEnvelope<ByteBuffer>.self,
|
||||||
|
outboundType: AddressedEnvelope<ByteBuffer>.self
|
||||||
|
))
|
||||||
|
}
|
||||||
|
.get()
|
||||||
|
|
||||||
|
self.logger.log("[SDLNoticeClient] started and listening on: \(self.asyncChannel.channel.localAddress!)", level: .debug)
|
||||||
|
}
|
||||||
|
|
||||||
|
func start() async throws {
|
||||||
|
try await self.asyncChannel.executeThenClose { inbound, outbound in
|
||||||
|
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
try await self.asyncChannel.channel.closeFuture.get()
|
||||||
|
throw SDLError.socketClosed
|
||||||
|
}
|
||||||
|
|
||||||
|
group.addTask {
|
||||||
|
defer {
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
for try await message in self.writeStream {
|
||||||
|
let buf = self.asyncChannel.channel.allocator.buffer(bytes: message)
|
||||||
|
let envelope = AddressedEnvelope<ByteBuffer>(remoteAddress: self.remoteAddress, data: buf)
|
||||||
|
|
||||||
|
try await outbound.write(envelope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for try await _ in group {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理写入逻辑
|
||||||
|
func send(data: Data) {
|
||||||
|
self.writeContinuation.yield(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
try? self.group.syncShutdownGracefully()
|
||||||
|
self.writeContinuation.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
16
Tun/Punchnet/SDLProtoMessageExtension.swift
Normal file
16
Tun/Punchnet/SDLProtoMessageExtension.swift
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
//
|
||||||
|
// SDLProtoMessageExtension.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/10/24.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
extension SDLData {
|
||||||
|
|
||||||
|
func format() -> String {
|
||||||
|
return "network_id: \(self.networkID), src_mac: \(LayerPacket.MacAddress.description(data: self.srcMac)), dst_mac: \(LayerPacket.MacAddress.description(data: self.dstMac)), data: \([UInt8](self.data))"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
37
Tun/Punchnet/SDLQPSCounter.swift
Normal file
37
Tun/Punchnet/SDLQPSCounter.swift
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
//
|
||||||
|
// SDLQPSCounter.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/4/16.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
// 计数器,用来统计qps
|
||||||
|
class SDLQPSCounter: @unchecked Sendable {
|
||||||
|
private var count = 0
|
||||||
|
private let timer: DispatchSourceTimer
|
||||||
|
private let label: String
|
||||||
|
private let queue = DispatchQueue(label: "com.punchnet.qps")
|
||||||
|
|
||||||
|
init(label: String) {
|
||||||
|
self.label = label
|
||||||
|
timer = DispatchSource.makeTimerSource(queue: queue)
|
||||||
|
timer.schedule(deadline: .now(), repeating: .seconds(1), leeway: .milliseconds(100))
|
||||||
|
timer.setEventHandler { [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
self.count = 0
|
||||||
|
}
|
||||||
|
timer.resume()
|
||||||
|
}
|
||||||
|
|
||||||
|
func increment(num: Int = 1) {
|
||||||
|
queue.async {
|
||||||
|
self.count += num
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
timer.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
45
Tun/Punchnet/SDLThrottler.swift
Normal file
45
Tun/Punchnet/SDLThrottler.swift
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
//
|
||||||
|
// SDLThrottler.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/6/3.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import Combine
|
||||||
|
|
||||||
|
// 限流器
|
||||||
|
actor SDLThrottler {
|
||||||
|
private var limit: Int
|
||||||
|
private var token: Int
|
||||||
|
private var cancel: AnyCancellable?
|
||||||
|
|
||||||
|
init(limit: Int) {
|
||||||
|
self.limit = limit
|
||||||
|
self.token = limit
|
||||||
|
}
|
||||||
|
|
||||||
|
func start() {
|
||||||
|
self.cancel?.cancel()
|
||||||
|
self.cancel = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()
|
||||||
|
.sink { _ in
|
||||||
|
Task {
|
||||||
|
self.token = self.limit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setRateLimit(limit: Int) {
|
||||||
|
self.limit = limit
|
||||||
|
}
|
||||||
|
|
||||||
|
func getToken(num: Int) -> Bool {
|
||||||
|
if token > 0 {
|
||||||
|
self.token = self.token - num
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
52
Tun/Punchnet/SDLUtil.swift
Normal file
52
Tun/Punchnet/SDLUtil.swift
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
//
|
||||||
|
// Util.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2024/1/19.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct SDLUtil {
|
||||||
|
|
||||||
|
public static func int32ToIp(_ num: UInt32) -> String {
|
||||||
|
let ip0 = (UInt8) (num >> 24 & 0xFF)
|
||||||
|
let ip1 = (UInt8) (num >> 16 & 0xFF)
|
||||||
|
let ip2 = (UInt8) (num >> 8 & 0xFF)
|
||||||
|
let ip3 = (UInt8) (num & 0xFF)
|
||||||
|
|
||||||
|
return "\(ip0).\(ip1).\(ip2).\(ip3)"
|
||||||
|
}
|
||||||
|
|
||||||
|
public static func netMaskIp(maskLen: UInt8) -> String {
|
||||||
|
let len0 = 32 - maskLen
|
||||||
|
let num: UInt32 = (0xFFFFFFFF >> len0) << len0
|
||||||
|
|
||||||
|
let ip0 = (UInt8) (num >> 24 & 0xFF)
|
||||||
|
let ip1 = (UInt8) (num >> 16 & 0xFF)
|
||||||
|
let ip2 = (UInt8) (num >> 8 & 0xFF)
|
||||||
|
let ip3 = (UInt8) (num & 0xFF)
|
||||||
|
|
||||||
|
return "\(ip0).\(ip1).\(ip2).\(ip3)"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 判断ip地址是否在同一个网络
|
||||||
|
public static func inSameNetwork(ip: UInt32, compareIp: UInt32, maskLen: UInt8) -> Bool {
|
||||||
|
if ip == compareIp {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
let len0 = 32 - maskLen
|
||||||
|
// 掩码值
|
||||||
|
let mask: UInt32 = (0xFFFFFFFF >> len0) << len0
|
||||||
|
|
||||||
|
return ip & mask == compareIp & mask
|
||||||
|
}
|
||||||
|
|
||||||
|
public static func formatMacAddress(mac: Data) -> String {
|
||||||
|
let bytes = [UInt8](mac)
|
||||||
|
|
||||||
|
return bytes.map { String(format: "%02X", $0) }.joined(separator: ":").lowercased()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
57
Tun/Punchnet/SessionManager.swift
Normal file
57
Tun/Punchnet/SessionManager.swift
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
//
|
||||||
|
// Session.swift
|
||||||
|
// sdlan
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2025/7/14.
|
||||||
|
//
|
||||||
|
import Foundation
|
||||||
|
import NIOCore
|
||||||
|
|
||||||
|
struct Session {
|
||||||
|
// 在内部的通讯的ip地址, 整数格式
|
||||||
|
let dstMac: Data
|
||||||
|
// 对端的主机在nat上映射的端口信息
|
||||||
|
let natAddress: SocketAddress
|
||||||
|
|
||||||
|
// 最后使用时间
|
||||||
|
var lastTimestamp: Int32
|
||||||
|
|
||||||
|
init(dstMac: Data, natAddress: SocketAddress) {
|
||||||
|
self.dstMac = dstMac
|
||||||
|
self.natAddress = natAddress
|
||||||
|
self.lastTimestamp = Int32(Date().timeIntervalSince1970)
|
||||||
|
}
|
||||||
|
|
||||||
|
mutating func updateLastTimestamp(_ lastTimestamp: Int32) {
|
||||||
|
self.lastTimestamp = lastTimestamp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
actor SessionManager {
|
||||||
|
private var sessions: [Data:Session] = [:]
|
||||||
|
|
||||||
|
// session的有效时间
|
||||||
|
private let ttl: Int32 = 10
|
||||||
|
|
||||||
|
func getSession(toAddress: Data) -> Session? {
|
||||||
|
let timestamp = Int32(Date().timeIntervalSince1970)
|
||||||
|
if let session = self.sessions[toAddress] {
|
||||||
|
if session.lastTimestamp >= timestamp + ttl {
|
||||||
|
self.sessions[toAddress]?.updateLastTimestamp(timestamp)
|
||||||
|
return session
|
||||||
|
} else {
|
||||||
|
self.sessions.removeValue(forKey: toAddress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func addSession(session: Session) {
|
||||||
|
self.sessions[session.dstMac] = session
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeSession(dstMac: Data) {
|
||||||
|
self.sessions.removeValue(forKey: dstMac)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
38
Tun/Punchnet/UDPPacket.swift
Normal file
38
Tun/Punchnet/UDPPacket.swift
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
//
|
||||||
|
// UDPPacket.swift
|
||||||
|
// Tun
|
||||||
|
//
|
||||||
|
// Created by 安礼成 on 2025/12/13.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct UDPHeader {
|
||||||
|
let sourcePort: UInt16
|
||||||
|
let destinationPort: UInt16
|
||||||
|
let length: UInt16
|
||||||
|
let checksum: UInt16
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UDPPacket {
|
||||||
|
let header: UDPHeader
|
||||||
|
let payload: Data
|
||||||
|
|
||||||
|
init?(_ data: Data) {
|
||||||
|
// UDP header 至少 8 字节
|
||||||
|
guard data.count >= 8 else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
let header = UDPHeader(sourcePort: UInt16(bytes: (data[0], data[1])),
|
||||||
|
destinationPort: UInt16(bytes: (data[2], data[3])),
|
||||||
|
length: UInt16(bytes: (data[4], data[5])),
|
||||||
|
checksum: UInt16(bytes: (data[6], data[7]))
|
||||||
|
)
|
||||||
|
// UDP payload = length - 8
|
||||||
|
let payloadLength = Int(header.length) - 8
|
||||||
|
|
||||||
|
self.header = header
|
||||||
|
self.payload = data.subdata(in: 8..<(8 + payloadLength))
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,128 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLPuncherActor.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/1/7.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor SDLPuncherActor {
|
|
||||||
// 10秒内只需要提交一次查询
|
|
||||||
nonisolated private let cooldownInterval: TimeInterval = 10
|
|
||||||
// 等待peerInfo返回的超时时间
|
|
||||||
nonisolated private let peerInfoTimeout: TimeInterval = 3
|
|
||||||
|
|
||||||
struct RegisterRequest {
|
|
||||||
let srcMac: Data
|
|
||||||
let dstMac: Data
|
|
||||||
let networkId: UInt32
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum RequestPhase {
|
|
||||||
case waitingPeerInfo(deadline: Date)
|
|
||||||
case coolingDown
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct RequestEntry {
|
|
||||||
let request: RegisterRequest
|
|
||||||
let cooldownUntil: Date
|
|
||||||
var phase: RequestPhase
|
|
||||||
|
|
||||||
func canSubmit(at now: Date) -> Bool {
|
|
||||||
return cooldownUntil <= now
|
|
||||||
}
|
|
||||||
|
|
||||||
func isWaitingPeerInfo(at now: Date) -> Bool {
|
|
||||||
guard case .waitingPeerInfo(let deadline) = self.phase else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return deadline > now
|
|
||||||
}
|
|
||||||
|
|
||||||
mutating func markCoolingDown() {
|
|
||||||
self.phase = .coolingDown
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// dstMac
|
|
||||||
private var requestEntries: [Data: RequestEntry] = [:]
|
|
||||||
|
|
||||||
func runCleanup() async throws {
|
|
||||||
while !Task.isCancelled {
|
|
||||||
try await Task.sleep(for: .seconds(1))
|
|
||||||
try Task.checkCancellation()
|
|
||||||
self.cleanupExpiredEntries()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeQueryInfoRequest(request: RegisterRequest) async -> Data? {
|
|
||||||
let now = Date()
|
|
||||||
self.cleanupExpiredEntries(now: now)
|
|
||||||
|
|
||||||
if let entry = self.requestEntries[request.dstMac], !entry.canSubmit(at: now) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var queryInfo = SDLQueryInfo()
|
|
||||||
queryInfo.dstMac = request.dstMac
|
|
||||||
|
|
||||||
guard let queryData = try? queryInfo.serializedData() else {
|
|
||||||
SDLLogger.log("[SDLPuncherActor] failed to encode queryInfo", category: .session)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
self.requestEntries[request.dstMac] = RequestEntry(
|
|
||||||
request: request,
|
|
||||||
cooldownUntil: now.addingTimeInterval(self.cooldownInterval),
|
|
||||||
phase: .waitingPeerInfo(deadline: now.addingTimeInterval(self.peerInfoTimeout))
|
|
||||||
)
|
|
||||||
|
|
||||||
return queryData
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeRegisterPackets(peerInfo: SDLPeerInfo) async -> [(data: Data, remoteAddress: SocketAddress)] {
|
|
||||||
let now = Date()
|
|
||||||
self.cleanupExpiredEntries(now: now)
|
|
||||||
|
|
||||||
guard var entry = self.requestEntries[peerInfo.dstMac], entry.isWaitingPeerInfo(at: now) else {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
entry.markCoolingDown()
|
|
||||||
self.requestEntries[peerInfo.dstMac] = entry
|
|
||||||
|
|
||||||
var register = SDLRegister()
|
|
||||||
register.networkID = entry.request.networkId
|
|
||||||
register.srcMac = entry.request.srcMac
|
|
||||||
register.dstMac = entry.request.dstMac
|
|
||||||
|
|
||||||
guard let registerData = try? register.serializedData() else {
|
|
||||||
SDLLogger.log("[SDLPuncherActor] failed to encode register", category: .session)
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
var packets: [(data: Data, remoteAddress: SocketAddress)] = []
|
|
||||||
if peerInfo.hasV4Info, let remoteAddress = try? await peerInfo.v4Info.socketAddress() {
|
|
||||||
packets.append((data: registerData, remoteAddress: remoteAddress))
|
|
||||||
}
|
|
||||||
if peerInfo.hasV6Info, let remoteAddress = try? await peerInfo.v6Info.socketAddress() {
|
|
||||||
packets.append((data: registerData, remoteAddress: remoteAddress))
|
|
||||||
}
|
|
||||||
|
|
||||||
return packets
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
self.requestEntries.removeAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func cleanupExpiredEntries(now: Date = Date()) {
|
|
||||||
self.requestEntries = self.requestEntries.filter { _, entry in
|
|
||||||
!entry.canSubmit(at: now)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,36 +0,0 @@
|
|||||||
//
|
|
||||||
// Session.swift
|
|
||||||
// sdlan
|
|
||||||
// Session是增加了有效时间的
|
|
||||||
// Created by 安礼成 on 2025/7/14.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
struct Session {
|
|
||||||
enum AddressType: String, Hashable {
|
|
||||||
case v4
|
|
||||||
case v6
|
|
||||||
}
|
|
||||||
|
|
||||||
// 在内部的通讯的ip地址, 整数格式
|
|
||||||
let dstMac: Data
|
|
||||||
// 对端的主机在nat上映射的端口信息
|
|
||||||
let natAddress: SocketAddress
|
|
||||||
// 当前会话对应的外层地址族
|
|
||||||
let addressType: AddressType
|
|
||||||
|
|
||||||
// 最后使用时间
|
|
||||||
var lastTimestamp: Int32
|
|
||||||
|
|
||||||
init?(dstMac: Data, natAddress: SocketAddress, addressType: AddressType) {
|
|
||||||
self.dstMac = dstMac
|
|
||||||
self.natAddress = natAddress
|
|
||||||
self.addressType = addressType
|
|
||||||
self.lastTimestamp = Int32(Date().timeIntervalSince1970)
|
|
||||||
}
|
|
||||||
|
|
||||||
mutating func updateLastTimestamp(_ lastTimestamp: Int32) {
|
|
||||||
self.lastTimestamp = lastTimestamp
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,27 +0,0 @@
|
|||||||
//
|
|
||||||
// SessionSnapshot.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/21.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class SessionSnapshot: Snapshot {
|
|
||||||
private let sessions: [Data: [Session.AddressType: Session]]
|
|
||||||
|
|
||||||
init(sessions: [Data: [Session.AddressType: Session]]) {
|
|
||||||
self.sessions = sessions
|
|
||||||
}
|
|
||||||
|
|
||||||
func getSession(toAddress: Data) -> Session? {
|
|
||||||
guard let peerSessions = self.sessions[toAddress] else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return peerSessions.values.max(by: { $0.lastTimestamp < $1.lastTimestamp })
|
|
||||||
}
|
|
||||||
|
|
||||||
static func empty() -> SessionSnapshot {
|
|
||||||
return SessionSnapshot(sessions: [:])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,115 +0,0 @@
|
|||||||
//
|
|
||||||
// SessionTable.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/21.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
actor SessionManager {
|
|
||||||
private var sessions: [Data: [Session.AddressType: Session]] = [:]
|
|
||||||
|
|
||||||
// session的有效时间
|
|
||||||
private let ttl: Int32
|
|
||||||
nonisolated private let snapshotPublisher: SnapshotPublisher<SessionSnapshot>
|
|
||||||
|
|
||||||
init() {
|
|
||||||
let ttl: Int32 = 10
|
|
||||||
self.ttl = ttl
|
|
||||||
self.snapshotPublisher = SnapshotPublisher(initial: SessionSnapshot.empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
func getSession(toAddress: Data) -> Session? {
|
|
||||||
let timestamp = Int32(Date().timeIntervalSince1970)
|
|
||||||
|
|
||||||
guard var peerSessions = self.sessions[toAddress] else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
peerSessions = peerSessions.filter { $0.value.lastTimestamp + ttl >= timestamp }
|
|
||||||
guard !peerSessions.isEmpty else {
|
|
||||||
self.sessions.removeValue(forKey: toAddress)
|
|
||||||
self.publishSnapshot()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
guard var session = self.selectSession(in: peerSessions) else {
|
|
||||||
self.sessions[toAddress] = peerSessions
|
|
||||||
self.publishSnapshot()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
session.updateLastTimestamp(timestamp)
|
|
||||||
peerSessions[session.addressType] = session
|
|
||||||
|
|
||||||
self.sessions[toAddress] = peerSessions
|
|
||||||
self.publishSnapshot()
|
|
||||||
|
|
||||||
return session
|
|
||||||
}
|
|
||||||
|
|
||||||
func addSession(session: Session) {
|
|
||||||
let timestamp = Int32(Date().timeIntervalSince1970)
|
|
||||||
|
|
||||||
var sessions = self.sessions[session.dstMac, default: [:]]
|
|
||||||
sessions = sessions.filter {
|
|
||||||
$0.value.lastTimestamp + ttl >= timestamp && $0.key != session.addressType
|
|
||||||
}
|
|
||||||
sessions[session.addressType] = session
|
|
||||||
|
|
||||||
self.sessions[session.dstMac] = sessions
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
|
|
||||||
func removeSession(dstMac: Data) {
|
|
||||||
self.sessions.removeValue(forKey: dstMac)
|
|
||||||
self.publishSnapshot()
|
|
||||||
}
|
|
||||||
|
|
||||||
@discardableResult
|
|
||||||
func clear() -> Int {
|
|
||||||
let oldCount = self.sessionCount()
|
|
||||||
self.sessions.removeAll()
|
|
||||||
self.publishSnapshot()
|
|
||||||
return oldCount
|
|
||||||
}
|
|
||||||
|
|
||||||
@discardableResult
|
|
||||||
func pruneExpiredSessions() -> Int {
|
|
||||||
let oldCount = self.sessionCount()
|
|
||||||
self.sessions = self.validSessions()
|
|
||||||
let newCount = self.sessionCount()
|
|
||||||
self.publishSnapshot()
|
|
||||||
return oldCount - newCount
|
|
||||||
}
|
|
||||||
|
|
||||||
nonisolated func snapshot() -> SessionSnapshot {
|
|
||||||
return self.snapshotPublisher.current()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func selectSession(in sessions: [Session.AddressType: Session]) -> Session? {
|
|
||||||
return sessions.values.max(by: { $0.lastTimestamp < $1.lastTimestamp })
|
|
||||||
}
|
|
||||||
|
|
||||||
private func publishSnapshot() {
|
|
||||||
self.snapshotPublisher.publish(self.compileSnapshot())
|
|
||||||
}
|
|
||||||
|
|
||||||
private func validSessions() -> [Data: [Session.AddressType: Session]] {
|
|
||||||
let timestamp = Int32(Date().timeIntervalSince1970)
|
|
||||||
return self.sessions.compactMapValues { peerSessions in
|
|
||||||
let validSessions = peerSessions.filter { $0.value.lastTimestamp + self.ttl >= timestamp }
|
|
||||||
return validSessions.isEmpty ? nil : validSessions
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func sessionCount() -> Int {
|
|
||||||
return self.sessions.values.reduce(0) { count, peerSessions in
|
|
||||||
count + peerSessions.count
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func compileSnapshot() -> SessionSnapshot {
|
|
||||||
return SessionSnapshot(sessions: self.validSessions())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,10 +0,0 @@
|
|||||||
//
|
|
||||||
// Snapshot.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/20.
|
|
||||||
//
|
|
||||||
|
|
||||||
protocol Snapshot: AnyObject {
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
//
|
|
||||||
// SnapshotPublisher.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/2/5.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class SnapshotPublisher<S: Snapshot>: @unchecked Sendable {
|
|
||||||
private let lock = NSLock()
|
|
||||||
private var snapshot: S
|
|
||||||
|
|
||||||
init(initial snapshot: S) {
|
|
||||||
self.snapshot = snapshot
|
|
||||||
}
|
|
||||||
|
|
||||||
func publish(_ snapshot: S) {
|
|
||||||
self.lock.lock()
|
|
||||||
self.snapshot = snapshot
|
|
||||||
self.lock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
@inline(__always)
|
|
||||||
func current() -> S {
|
|
||||||
self.lock.lock()
|
|
||||||
let snapshot = self.snapshot
|
|
||||||
self.lock.unlock()
|
|
||||||
return snapshot
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,258 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperClient.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/2/13.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import Network
|
|
||||||
|
|
||||||
final class SDLSuperClient: @unchecked Sendable {
|
|
||||||
private let queue = DispatchQueue(label: "com.sdl.SuperClient.queue") // 专用队列保证线程安全
|
|
||||||
public let messageStream: AsyncThrowingStream<SDLSuperMessage, Error>
|
|
||||||
private let messageContinuation: AsyncThrowingStream<SDLSuperMessage, Error>.Continuation
|
|
||||||
|
|
||||||
private let readySignal = AsyncOneShot<Void>()
|
|
||||||
private let stateLock = NSLock()
|
|
||||||
private var isStarted = false
|
|
||||||
private var isStopped = false
|
|
||||||
private var isMessageContinuationFinished = false
|
|
||||||
|
|
||||||
private let connection: NWConnection
|
|
||||||
private let maxBufferSize: Int
|
|
||||||
|
|
||||||
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16, maxBufferSize: Int = 2 * 1024 * 1024) {
|
|
||||||
self.maxBufferSize = maxBufferSize
|
|
||||||
|
|
||||||
let pairs = AsyncThrowingStream.makeStream(of: SDLSuperMessage.self, bufferingPolicy: .bufferingNewest(1024))
|
|
||||||
self.messageStream = pairs.stream
|
|
||||||
self.messageContinuation = pairs.continuation
|
|
||||||
|
|
||||||
let options = NWProtocolTLS.Options()
|
|
||||||
serverEndpoint.host.withCString {
|
|
||||||
sec_protocol_options_set_tls_server_name(options.securityProtocolOptions, $0)
|
|
||||||
}
|
|
||||||
sec_protocol_options_add_tls_application_protocol(
|
|
||||||
options.securityProtocolOptions,
|
|
||||||
"punchnet/1.0"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 这里设置证书的校验逻辑
|
|
||||||
sec_protocol_options_set_verify_block(
|
|
||||||
options.securityProtocolOptions,
|
|
||||||
{ _, trust, complete in
|
|
||||||
// 执行公钥校验
|
|
||||||
complete(SDLSuperTLSVerifier.verify(trust: trust, host: serverEndpoint.host))
|
|
||||||
},
|
|
||||||
queue
|
|
||||||
)
|
|
||||||
|
|
||||||
let params = NWParameters(tls: options)
|
|
||||||
// 关键:让 Network.framework 忽略系统代理
|
|
||||||
params.preferNoProxies = true
|
|
||||||
|
|
||||||
self.connection = NWConnection(host: Self.makeEndpointHost(address: serverEndpoint.ip), port: .init(rawValue: port)!, using: params)
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLSuperClient] start with tls protocol", category: .super)
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard self.markStarted() else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await withTaskCancellationHandler {
|
|
||||||
self.connection.stateUpdateHandler = { [weak self] state in
|
|
||||||
self?.handleConnectionStateUpdate(state)
|
|
||||||
}
|
|
||||||
self.connection.start(queue: self.queue)
|
|
||||||
try await self.readySignal.wait()
|
|
||||||
try await self.readLoop()
|
|
||||||
self.finishMessageStream()
|
|
||||||
} onCancel: {
|
|
||||||
self.connection.stateUpdateHandler = nil
|
|
||||||
self.connection.cancel()
|
|
||||||
}
|
|
||||||
} catch is CancellationError {
|
|
||||||
self.finishMessageStream()
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
self.finishMessageStream(throwing: error)
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func makeEndpointHost(address ip: String) -> NWEndpoint.Host {
|
|
||||||
if let ipv4Address = IPv4Address(ip) {
|
|
||||||
return .ipv4(ipv4Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
if let ipv6Address = IPv6Address(ip) {
|
|
||||||
return .ipv6(ipv6Address)
|
|
||||||
}
|
|
||||||
|
|
||||||
preconditionFailure("invalid super server IP: \(ip)")
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleConnectionStateUpdate(_ state: NWConnection.State) {
|
|
||||||
SDLLogger.log("[SDLSuperClient] new state: \(state)", category: .super)
|
|
||||||
switch state {
|
|
||||||
case .ready:
|
|
||||||
Task {
|
|
||||||
await self.readySignal.succeed(())
|
|
||||||
}
|
|
||||||
case .failed(let error):
|
|
||||||
let wrappedError = SDLSuperError.connectionFailed(error)
|
|
||||||
Task {
|
|
||||||
await self.readySignal.fail(wrappedError)
|
|
||||||
}
|
|
||||||
self.finishMessageStream(throwing: wrappedError)
|
|
||||||
case .cancelled:
|
|
||||||
let error = SDLSuperError.connectionCancelled
|
|
||||||
Task {
|
|
||||||
await self.readySignal.fail(error)
|
|
||||||
}
|
|
||||||
self.finishMessageStream(throwing: error)
|
|
||||||
default:
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readLoop() async throws {
|
|
||||||
let frameParser = SDLSuperFrameParser(maxBufferSize: self.maxBufferSize)
|
|
||||||
while true {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
let data = try await Self.readOnce(connection: self.connection)
|
|
||||||
let frames = try frameParser.parseFrames(data: data)
|
|
||||||
for frame in frames {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
if let message = SDLSuperCodec.decode(frame: frame) {
|
|
||||||
self.messageContinuation.yield(message)
|
|
||||||
} else {
|
|
||||||
throw SDLSuperError.decodeError("invalid message")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data) {
|
|
||||||
guard connection.state == .ready else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var len = UInt16(data.count + 1).bigEndian
|
|
||||||
var packet = Data(Data(bytes: &len, count: 2))
|
|
||||||
packet.append(type.rawValue)
|
|
||||||
packet.append(data)
|
|
||||||
|
|
||||||
connection.send(content: packet, completion: .contentProcessed { [weak self] error in
|
|
||||||
if let error {
|
|
||||||
SDLLogger.log("[SDLSuperClient] send data get error: \(error)", category: .super)
|
|
||||||
self?.finishMessageStream(throwing: SDLSuperError.writeFailed(error))
|
|
||||||
self?.connection.cancel()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func readOnce(connection: NWConnection) async throws -> Data {
|
|
||||||
guard connection.state == .ready else {
|
|
||||||
throw SDLSuperError.connectionCancelled
|
|
||||||
}
|
|
||||||
|
|
||||||
let readContinuation = OnceContinuation<Data, Error>()
|
|
||||||
|
|
||||||
return try await withTaskCancellationHandler {
|
|
||||||
try await withCheckedThrowingContinuation { cont in
|
|
||||||
readContinuation.set(cont)
|
|
||||||
connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in
|
|
||||||
if let error {
|
|
||||||
readContinuation.resume(throwing: error)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if isComplete {
|
|
||||||
readContinuation.resume(throwing: SDLSuperError.dataStreamClosed)
|
|
||||||
} else {
|
|
||||||
readContinuation.resume(returning: data ?? Data())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} onCancel: {
|
|
||||||
readContinuation.resume(throwing: CancellationError())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
guard self.markStopped() else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let connection = self.connection
|
|
||||||
connection.stateUpdateHandler = nil
|
|
||||||
connection.cancel()
|
|
||||||
Task {
|
|
||||||
await self.readySignal.fail(SDLSuperError.connectionCancelled)
|
|
||||||
}
|
|
||||||
self.finishMessageStream()
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLSuperClient] stopped", category: .super)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func markStarted() -> Bool {
|
|
||||||
self.stateLock.lock()
|
|
||||||
defer {
|
|
||||||
self.stateLock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
guard !self.isStarted, !self.isStopped else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isStarted = true
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private func markStopped() -> Bool {
|
|
||||||
self.stateLock.lock()
|
|
||||||
defer {
|
|
||||||
self.stateLock.unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
guard !self.isStopped else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isStopped = true
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
private func finishMessageStream(throwing error: Error? = nil) {
|
|
||||||
self.stateLock.lock()
|
|
||||||
let shouldFinish = !self.isMessageContinuationFinished
|
|
||||||
if shouldFinish {
|
|
||||||
self.isMessageContinuationFinished = true
|
|
||||||
}
|
|
||||||
self.stateLock.unlock()
|
|
||||||
|
|
||||||
guard shouldFinish else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if let error {
|
|
||||||
self.messageContinuation.finish(throwing: error)
|
|
||||||
} else {
|
|
||||||
self.messageContinuation.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[SDLSuperClient] deinit", category: .super)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,77 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperCodec.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/22.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
enum SDLSuperCodec {
|
|
||||||
public static func decode(frame: ByteBuffer) -> SDLSuperMessage? {
|
|
||||||
var buffer = frame
|
|
||||||
guard let type = buffer.readInteger(as: UInt8.self),
|
|
||||||
let packetType = SDLPacketType(rawValue: type) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
switch packetType {
|
|
||||||
case .welcome:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let welcome = try? SDLWelcome(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .welcome(welcome)
|
|
||||||
|
|
||||||
case .registerSuperAck:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let registerSuperAck = try? SDLRegisterSuperAck(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .registerSuperAck(registerSuperAck)
|
|
||||||
case .registerSuperNak:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let registerSuperNak = try? SDLRegisterSuperNak(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .registerSuperNak(registerSuperNak)
|
|
||||||
case .peerInfo:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let peerInfo = try? SDLPeerInfo(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .peerInfo(peerInfo)
|
|
||||||
case .policyResponse:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let policyResponse = try? SDLPolicyResponse(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .policyReponse(policyResponse)
|
|
||||||
case .exposedServiceResponse:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let response = try? SDLExposedServiceResponse(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .exposedServiceResponse(response)
|
|
||||||
case .arpResponse:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let arpResponse = try? SDLArpResponse(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .arpResponse(arpResponse)
|
|
||||||
case .event:
|
|
||||||
guard let bytes = buffer.readBytes(length: buffer.readableBytes),
|
|
||||||
let event = try? SDLEvent(serializedBytes: bytes) else {
|
|
||||||
SDLLogger.log("SDLSuperClient decode Event Error", category: .super)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .event(event)
|
|
||||||
case .pong:
|
|
||||||
return .pong
|
|
||||||
default:
|
|
||||||
SDLLogger.log("SDLSuperClient decode miss type: \(type)", category: .super)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,20 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperError.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/22.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
// 定义错误类型,便于上层处理
|
|
||||||
enum SDLSuperError: Error {
|
|
||||||
case connectionFailed(Error)
|
|
||||||
case connectionCancelled
|
|
||||||
case writeFailed(Error)
|
|
||||||
|
|
||||||
case internalError(Error)
|
|
||||||
case packetTooLarge
|
|
||||||
|
|
||||||
case decodeError(String)
|
|
||||||
case dataStreamClosed
|
|
||||||
}
|
|
||||||
@ -1,58 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperFrameParser.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/22.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
final class SDLSuperFrameParser {
|
|
||||||
private let allocator = ByteBufferAllocator()
|
|
||||||
// 最大缓冲区区为2M
|
|
||||||
private let maxPacketSize: Int = 64 * 1024
|
|
||||||
private let maxBufferSize: Int
|
|
||||||
private var buffer: ByteBuffer
|
|
||||||
|
|
||||||
init(maxBufferSize: Int) {
|
|
||||||
self.buffer = allocator.buffer(capacity: maxBufferSize)
|
|
||||||
self.maxBufferSize = maxBufferSize
|
|
||||||
}
|
|
||||||
|
|
||||||
// 尝试解析数据
|
|
||||||
public func parseFrames(data: Data) throws -> [ByteBuffer] {
|
|
||||||
self.buffer.writeBytes(data)
|
|
||||||
|
|
||||||
guard buffer.readableBytes >= 2 else {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
|
|
||||||
var frames: [ByteBuffer] = []
|
|
||||||
while true {
|
|
||||||
guard let len = buffer.getInteger(at: buffer.readerIndex, endianness: .big, as: UInt16.self) else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if len > self.maxPacketSize {
|
|
||||||
throw SDLSuperError.packetTooLarge
|
|
||||||
}
|
|
||||||
|
|
||||||
guard buffer.readableBytes >= len + 2 else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
buffer.moveReaderIndex(forwardBy: 2)
|
|
||||||
if let buf = buffer.readSlice(length: Int(len)) {
|
|
||||||
frames.append(buf)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let threshold = maxBufferSize / 10 * 6
|
|
||||||
if buffer.readerIndex > threshold {
|
|
||||||
buffer.discardReadBytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
return frames
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLQUICInboundMessage.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/27.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
enum SDLSuperMessage {
|
|
||||||
// 欢迎消息
|
|
||||||
case welcome(SDLWelcome)
|
|
||||||
|
|
||||||
case pong
|
|
||||||
|
|
||||||
// 注册相关
|
|
||||||
case registerSuperAck(SDLRegisterSuperAck)
|
|
||||||
case registerSuperNak(SDLRegisterSuperNak)
|
|
||||||
|
|
||||||
case peerInfo(SDLPeerInfo)
|
|
||||||
case event(SDLEvent)
|
|
||||||
case policyReponse(SDLPolicyResponse)
|
|
||||||
case exposedServiceResponse(SDLExposedServiceResponse)
|
|
||||||
|
|
||||||
case arpResponse(SDLArpResponse)
|
|
||||||
}
|
|
||||||
@ -1,142 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
actor SDLSuperService {
|
|
||||||
typealias MessageHandler = @Sendable (SDLSuperMessage) async -> Void
|
|
||||||
|
|
||||||
private let serverEndpoint: SDLConfiguration.ResolvedServerEndpoint
|
|
||||||
private let port: UInt16
|
|
||||||
|
|
||||||
private var onMessage: MessageHandler = { _ in }
|
|
||||||
private var currentSession: SDLSuperSession?
|
|
||||||
private var generation: UInt64 = 0
|
|
||||||
private var isRunning = false
|
|
||||||
private var isStopping = false
|
|
||||||
private var needsImmediateRestart = false
|
|
||||||
private let retryDelay: Duration
|
|
||||||
|
|
||||||
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16 = 1443, retryDelay: Duration = .seconds(5)) {
|
|
||||||
self.serverEndpoint = serverEndpoint
|
|
||||||
self.port = port
|
|
||||||
self.retryDelay = retryDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateMessageHandler(_ onMessage: @escaping MessageHandler) {
|
|
||||||
self.onMessage = onMessage
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard !self.isRunning else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isRunning = true
|
|
||||||
self.isStopping = false
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.isRunning = false
|
|
||||||
self.currentSession = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
while !Task.isCancelled, !self.isStopping {
|
|
||||||
let generation = self.nextGeneration()
|
|
||||||
let session = SDLSuperSession(
|
|
||||||
serverEndpoint: self.serverEndpoint,
|
|
||||||
port: self.port,
|
|
||||||
onMessage: { [weak self] message in
|
|
||||||
await self?.handleMessage(message, generation: generation)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
self.currentSession = session
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await session.run()
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLSuperService] session ended, will restart", category: .super)
|
|
||||||
} catch is CancellationError {
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLSuperService] session failed: \(error.localizedDescription), will restart", category: .super)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.consumeImmediateRestartRequest() {
|
|
||||||
SDLLogger.log("[SDLSuperService] session invalidated after wakeup, will restart immediately", category: .super)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
try await Task.sleep(for: self.retryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
self.isStopping = true
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
await self.invalidateCurrentSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
func recoverAfterWake() async {
|
|
||||||
guard !self.isStopping else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.needsImmediateRestart = self.currentSession != nil
|
|
||||||
await self.invalidateCurrentSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data) async {
|
|
||||||
await self.currentSession?.send(type: type, data: data)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func nextGeneration() -> UInt64 {
|
|
||||||
self.generation &+= 1
|
|
||||||
return self.generation
|
|
||||||
}
|
|
||||||
|
|
||||||
private func invalidateCurrentSession() async {
|
|
||||||
self.generation &+= 1
|
|
||||||
|
|
||||||
let session = self.currentSession
|
|
||||||
self.currentSession = nil
|
|
||||||
|
|
||||||
await session?.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func consumeImmediateRestartRequest() -> Bool {
|
|
||||||
let needsImmediateRestart = self.needsImmediateRestart
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
return needsImmediateRestart
|
|
||||||
}
|
|
||||||
|
|
||||||
private func clearCurrent(_ session: SDLSuperSession, generation: UInt64) {
|
|
||||||
guard self.generation == generation else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.currentSession === session {
|
|
||||||
self.currentSession = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleMessage(_ message: SDLSuperMessage, generation: UInt64) async {
|
|
||||||
guard self.generation == generation else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.onMessage(message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,70 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperSession.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/27.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
final class SDLSuperSession: @unchecked Sendable {
|
|
||||||
typealias MessageHandler = @Sendable (SDLSuperMessage) async -> Void
|
|
||||||
|
|
||||||
private let serverEndpoint: SDLConfiguration.ResolvedServerEndpoint
|
|
||||||
private let port: UInt16
|
|
||||||
private let onMessage: MessageHandler
|
|
||||||
private let client: SDLSuperClient
|
|
||||||
|
|
||||||
init(serverEndpoint: SDLConfiguration.ResolvedServerEndpoint, port: UInt16, onMessage: @escaping MessageHandler) {
|
|
||||||
self.serverEndpoint = serverEndpoint
|
|
||||||
self.port = port
|
|
||||||
self.onMessage = onMessage
|
|
||||||
self.client = SDLSuperClient(serverEndpoint: serverEndpoint, port: port)
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
SDLLogger.log("[SDLSuperSession] start super client: \(self.serverEndpoint.ip)", category: .super)
|
|
||||||
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await self.client.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await self.readLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await self.pingLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = try await group.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
self.client.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data) async {
|
|
||||||
self.client.send(type: type, data: data)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readLoop() async throws {
|
|
||||||
for try await message in self.client.messageStream {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
await self.onMessage(message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func pingLoop() async throws {
|
|
||||||
while true {
|
|
||||||
try await Task.sleep(for: .seconds(5))
|
|
||||||
try Task.checkCancellation()
|
|
||||||
self.client.send(type: .ping, data: Data())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,67 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLSuperTLSVerifier.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/22.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import CryptoKit
|
|
||||||
import Security
|
|
||||||
|
|
||||||
enum SDLSuperTLSVerifier {
|
|
||||||
// 你的 Base64 公钥指纹
|
|
||||||
static let pinnedPublicKeyHashes = [
|
|
||||||
// 正式服务器的
|
|
||||||
"Q41r6hbMWEVyxo6heNAH4Wx/TH5NNOWlNif9bewcJ3E=".lowercased(),
|
|
||||||
|
|
||||||
// 测试服务器
|
|
||||||
"oeU0bWqLWMdn79s4ZHz6IRwXmFX4p70u/Qt9VrsDIb4=".lowercased()
|
|
||||||
]
|
|
||||||
|
|
||||||
static func verify(trust: sec_trust_t, host: String) -> Bool {
|
|
||||||
let secTrust = sec_trust_copy_ref(trust).takeRetainedValue()
|
|
||||||
|
|
||||||
// --- Step 1: 系统验证 ---
|
|
||||||
var error: CFError?
|
|
||||||
guard SecTrustEvaluateWithError(secTrust, &error) else {
|
|
||||||
SDLLogger.log("❌ 系统证书验证失败: \(error?.localizedDescription ?? "未知错误")", category: .super)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Step 2: 主机名验证 ---
|
|
||||||
let policy = SecPolicyCreateSSL(true, host as CFString)
|
|
||||||
SecTrustSetPolicies(secTrust, policy)
|
|
||||||
|
|
||||||
guard SecTrustEvaluateWithError(secTrust, &error) else {
|
|
||||||
SDLLogger.log("❌ 主机名校验失败: \(error?.localizedDescription ?? "未知错误")", category: .super)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Step 3: 获取叶子证书 ---
|
|
||||||
guard let chain = SecTrustCopyCertificateChain(secTrust) as? [SecCertificate],
|
|
||||||
let leafCertificate = chain.first else {
|
|
||||||
SDLLogger.log("❌ 无法获取证书链或叶子证书", category: .super)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Step 4: 提取公钥 ---
|
|
||||||
guard let publicKey = SecCertificateCopyKey(leafCertificate),
|
|
||||||
let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, nil) as Data? else {
|
|
||||||
SDLLogger.log("❌ 无法提取公钥", category: .super)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Step 5: SHA256 校验 ---
|
|
||||||
let hash = SHA256.hash(data: publicKeyData)
|
|
||||||
let hashBase64 = Data(hash).base64EncodedString().lowercased()
|
|
||||||
|
|
||||||
if pinnedPublicKeyHashes.contains(hashBase64) {
|
|
||||||
SDLLogger.log("✅ 公钥校验通过", category: .super)
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("⚠️ 公钥不匹配! 收到: \(hashBase64), config hashes: \(pinnedPublicKeyHashes)", category: .super)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -10,7 +10,7 @@
|
|||||||
<true/>
|
<true/>
|
||||||
<key>com.apple.security.application-groups</key>
|
<key>com.apple.security.application-groups</key>
|
||||||
<array>
|
<array>
|
||||||
<string>group.com.jihe.punchnetmac</string>
|
<string>$(TeamIdentifierPrefix)</string>
|
||||||
</array>
|
</array>
|
||||||
<key>com.apple.security.network.client</key>
|
<key>com.apple.security.network.client</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
|||||||
@ -1,20 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>com.apple.developer.networking.networkextension</key>
|
|
||||||
<array>
|
|
||||||
<string>packet-tunnel-provider</string>
|
|
||||||
</array>
|
|
||||||
<key>com.apple.security.app-sandbox</key>
|
|
||||||
<true/>
|
|
||||||
<key>com.apple.security.application-groups</key>
|
|
||||||
<array>
|
|
||||||
<string>group.com.jihe.punchnetmac</string>
|
|
||||||
</array>
|
|
||||||
<key>com.apple.security.network.client</key>
|
|
||||||
<true/>
|
|
||||||
<key>com.apple.security.network.server</key>
|
|
||||||
<true/>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
||||||
@ -1,96 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLTunNetworkManager.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by Codex on 2026/5/20.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NetworkExtension
|
|
||||||
|
|
||||||
final class SDLTunNetworkManager: @unchecked Sendable {
|
|
||||||
struct Settings: Sendable {
|
|
||||||
let ipAddress: String
|
|
||||||
let maskAddress: String
|
|
||||||
let netAddress: String
|
|
||||||
let networkDomain: String
|
|
||||||
let shouldRouteDefault: Bool
|
|
||||||
|
|
||||||
init(config: SDLConfiguration) {
|
|
||||||
let networkAddress = config.networkAddress
|
|
||||||
self.ipAddress = networkAddress.ipAddress
|
|
||||||
self.maskAddress = networkAddress.maskAddress
|
|
||||||
self.netAddress = networkAddress.netAddress
|
|
||||||
self.networkDomain = networkAddress.networkDomain
|
|
||||||
self.shouldRouteDefault = config.exitNode != nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private let provider: NEPacketTunnelProvider
|
|
||||||
|
|
||||||
init(provider: NEPacketTunnelProvider) {
|
|
||||||
self.provider = provider
|
|
||||||
}
|
|
||||||
|
|
||||||
func apply(settings: Settings, dnsServer: String) async throws {
|
|
||||||
let networkSettings = self.makeNetworkSettings(settings: settings, dnsServer: dnsServer)
|
|
||||||
try await self.provider.setTunnelNetworkSettings(networkSettings)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeNetworkSettings(settings: Settings, dnsServer: String) -> NEPacketTunnelNetworkSettings {
|
|
||||||
let networkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "8.8.8.8")
|
|
||||||
networkSettings.mtu = 1250
|
|
||||||
networkSettings.dnsSettings = self.makeDNSSettings(settings: settings, dnsServer: dnsServer)
|
|
||||||
networkSettings.ipv4Settings = self.makeIPv4Settings(settings: settings, dnsServer: dnsServer)
|
|
||||||
return networkSettings
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeDNSSettings(settings: Settings, dnsServer: String) -> NEDNSSettings {
|
|
||||||
let dnsSettings = NEDNSSettings(servers: [dnsServer])
|
|
||||||
dnsSettings.searchDomains = [settings.networkDomain]
|
|
||||||
dnsSettings.matchDomains = [settings.networkDomain, ""]
|
|
||||||
// 设置为 false 允许系统在补全 Search Domain 时也能匹配到此设置
|
|
||||||
dnsSettings.matchDomainsNoSearch = false
|
|
||||||
return dnsSettings
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeIPv4Settings(settings: Settings, dnsServer: String) -> NEIPv4Settings {
|
|
||||||
let ipv4Settings = NEIPv4Settings(addresses: [settings.ipAddress], subnetMasks: [settings.maskAddress])
|
|
||||||
ipv4Settings.includedRoutes = self.makeIPv4IncludedRoutes(settings: settings, dnsServer: dnsServer)
|
|
||||||
ipv4Settings.excludedRoutes = self.makeIPv4ExcludedRoutes()
|
|
||||||
return ipv4Settings
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeIPv4IncludedRoutes(settings: Settings, dnsServer: String) -> [NEIPv4Route] {
|
|
||||||
var routes: [NEIPv4Route] = [
|
|
||||||
NEIPv4Route(destinationAddress: settings.netAddress, subnetMask: settings.maskAddress),
|
|
||||||
NEIPv4Route(destinationAddress: dnsServer, subnetMask: "255.255.255.255"),
|
|
||||||
]
|
|
||||||
|
|
||||||
if settings.shouldRouteDefault {
|
|
||||||
routes.append(.default())
|
|
||||||
}
|
|
||||||
|
|
||||||
return routes
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeIPv4ExcludedRoutes() -> [NEIPv4Route] {
|
|
||||||
let dnsServers = SDLUtil.getMacOSSystemDnsServers()
|
|
||||||
var ipv4DnsServers = dnsServers.filter { !$0.contains(":") }
|
|
||||||
let commonDnsServers = [
|
|
||||||
"8.8.8.8",
|
|
||||||
"8.8.4.4",
|
|
||||||
"223.5.5.5",
|
|
||||||
"223.6.6.6",
|
|
||||||
"114.114.114.114"
|
|
||||||
]
|
|
||||||
|
|
||||||
for ip in commonDnsServers where !ipv4DnsServers.contains(ip) {
|
|
||||||
ipv4DnsServers.append(ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ipv4DnsServers.map {
|
|
||||||
NEIPv4Route(destinationAddress: $0, subnetMask: "255.255.255.255")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,202 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLNATProberActor.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/1/28.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor SDLNATProberActor {
|
|
||||||
|
|
||||||
// MARK: - NAT Type
|
|
||||||
|
|
||||||
enum NatType: UInt8, Encodable {
|
|
||||||
case blocked = 0
|
|
||||||
case noNat = 1
|
|
||||||
case fullCone = 2
|
|
||||||
case portRestricted = 3
|
|
||||||
case coneRestricted = 4
|
|
||||||
case symmetric = 5
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Internal State
|
|
||||||
|
|
||||||
class ProbeSession {
|
|
||||||
var cookieId: UInt32
|
|
||||||
// 建立step -> SDLStunProbeReply的映射关系
|
|
||||||
var replies: [UInt32: SDLStunProbeReply]
|
|
||||||
var timeoutTask: Task<Void, Never>?
|
|
||||||
var sendTask: Task<Void, Never>?
|
|
||||||
var continuation: CheckedContinuation<NatType, Never>
|
|
||||||
|
|
||||||
private var isFinished: Bool = false
|
|
||||||
|
|
||||||
init(cookieId: UInt32, timeoutTask: Task<Void, Never>? = nil, continuation: CheckedContinuation<NatType, Never>) {
|
|
||||||
self.cookieId = cookieId
|
|
||||||
self.replies = [:]
|
|
||||||
self.timeoutTask = timeoutTask
|
|
||||||
self.continuation = continuation
|
|
||||||
}
|
|
||||||
|
|
||||||
func finished(with type: NatType) {
|
|
||||||
guard !isFinished else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.continuation.resume(returning: type)
|
|
||||||
// 取消定时器
|
|
||||||
self.timeoutTask?.cancel()
|
|
||||||
self.sendTask?.cancel()
|
|
||||||
self.isFinished = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Dependencies
|
|
||||||
|
|
||||||
nonisolated private let addressArray: [[SocketAddress]]
|
|
||||||
|
|
||||||
// MARK: - Completion
|
|
||||||
private var cookieId: UInt32 = 1
|
|
||||||
|
|
||||||
private var sessions: [UInt32: ProbeSession] = [:]
|
|
||||||
|
|
||||||
// MARK: - Init
|
|
||||||
|
|
||||||
init(addressArray: [[SocketAddress]]) {
|
|
||||||
self.addressArray = addressArray
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Public API
|
|
||||||
|
|
||||||
func probeNatType(using udpHole: SDLUDPHole) async -> NatType {
|
|
||||||
if Task.isCancelled {
|
|
||||||
return .blocked
|
|
||||||
}
|
|
||||||
|
|
||||||
let cookieId = self.cookieId
|
|
||||||
self.cookieId &+= 1
|
|
||||||
|
|
||||||
return await withCheckedContinuation { continuation in
|
|
||||||
let timeoutTask = Task {
|
|
||||||
try? await Task.sleep(nanoseconds: 5_000_000_000)
|
|
||||||
await self.handleTimeout(cookie: cookieId)
|
|
||||||
}
|
|
||||||
|
|
||||||
let session = ProbeSession(
|
|
||||||
cookieId: cookieId,
|
|
||||||
timeoutTask: timeoutTask,
|
|
||||||
continuation: continuation
|
|
||||||
)
|
|
||||||
self.sessions[cookieId] = session
|
|
||||||
session.sendTask = Task {
|
|
||||||
await self.sendProbe(using: udpHole, cookie: cookieId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// UDP 层收到 STUN 响应后调用
|
|
||||||
func handleProbeReply(localAddress: SocketAddress?, reply: SDLStunProbeReply) async {
|
|
||||||
guard let session = self.sessions[reply.cookie] else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
session.replies[reply.step] = reply
|
|
||||||
|
|
||||||
// 提前退出的情况,没有nat映射
|
|
||||||
if session.replies[1] != nil {
|
|
||||||
if await reply.socketAddress() == localAddress {
|
|
||||||
finish(cookie: session.cookieId, .noNat)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let step1 = session.replies[1], let step2 = session.replies[2] {
|
|
||||||
// 如果natAddress2 的IP地址与上次回来的IP是不一样的,它就是对称型NAT; 这次的包也一定能发成功并收到
|
|
||||||
// 如果ip地址变了,这说明{dstIp, dstPort, srcIp, srcPort}, 其中有一个变了;则用新的ip地址
|
|
||||||
if let addr1 = await step1.socketAddress(), let addr2 = await step2.socketAddress(), addr1 != addr2 {
|
|
||||||
finish(cookie: session.cookieId, .symmetric)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 收到了所有的响应, 优先判断
|
|
||||||
if session.replies[1] != nil && session.replies[2] != nil && session.replies[3] != nil && session.replies[4] != nil {
|
|
||||||
// step3: ip2:port2 <---- ip1:port1 (ip地址和port都变的情况)
|
|
||||||
// 如果能收到的,说明是完全锥形 说明是IP地址限制锥型NAT,如果不能收到说明是端口限制锥型。
|
|
||||||
if session.replies[3] != nil {
|
|
||||||
finish(cookie: session.cookieId, .fullCone)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// step3: ip1:port1 <---- ip1:port2 (port改变情况)
|
|
||||||
// 如果能收到的说明是IP地址限制锥型NAT,如果不能收到说明是端口限制锥型。
|
|
||||||
if session.replies[4] != nil {
|
|
||||||
finish(cookie: session.cookieId, .coneRestricted)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func cancelAll() {
|
|
||||||
let sessions = self.sessions
|
|
||||||
self.sessions.removeAll()
|
|
||||||
sessions.values.forEach { session in
|
|
||||||
session.finished(with: .blocked)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 超时事件(由外部 Timer / Task 驱动)
|
|
||||||
private func handleTimeout(cookie: UInt32) async {
|
|
||||||
guard let session = self.sessions[cookie] else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if session.replies[1] == nil {
|
|
||||||
finish(cookie: cookie, .blocked)
|
|
||||||
} else if session.replies[3] != nil {
|
|
||||||
finish(cookie: cookie, .fullCone)
|
|
||||||
} else if session.replies[4] != nil {
|
|
||||||
finish(cookie: cookie, .coneRestricted)
|
|
||||||
} else {
|
|
||||||
finish(cookie: cookie, .portRestricted)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func finish(cookie: UInt32, _ type: NatType) {
|
|
||||||
if let session = self.sessions.removeValue(forKey: cookie) {
|
|
||||||
session.finished(with: type)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Internal helpers
|
|
||||||
|
|
||||||
private func sendProbe(using udpHole: SDLUDPHole, cookie: UInt32) async {
|
|
||||||
guard !Task.isCancelled else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
udpHole.send(type: .stunProbe, data: makeProbePacket(cookieId: cookie, step: 1, attr: .none), remoteAddress: addressArray[0][0])
|
|
||||||
guard !Task.isCancelled else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
udpHole.send(type: .stunProbe, data: makeProbePacket(cookieId: cookie, step: 2, attr: .none), remoteAddress: addressArray[1][1])
|
|
||||||
guard !Task.isCancelled else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
udpHole.send(type: .stunProbe, data: makeProbePacket(cookieId: cookie, step: 3, attr: .peer), remoteAddress: addressArray[0][0])
|
|
||||||
guard !Task.isCancelled else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
udpHole.send(type: .stunProbe, data: makeProbePacket(cookieId: cookie, step: 4, attr: .port), remoteAddress: addressArray[0][0])
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeProbePacket(cookieId: UInt32, step: UInt32, attr: SDLProbeAttr) -> Data {
|
|
||||||
var stunProbe = SDLStunProbe()
|
|
||||||
stunProbe.cookie = cookieId
|
|
||||||
stunProbe.step = step
|
|
||||||
stunProbe.attr = UInt32(attr.rawValue)
|
|
||||||
|
|
||||||
return try! stunProbe.serializedData()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,135 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLanServer.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2024/1/31.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
import NIOPosix
|
|
||||||
|
|
||||||
// 处理和sn-server服务器之间的通讯
|
|
||||||
final class SDLUDPHole: ChannelInboundHandler {
|
|
||||||
typealias InboundIn = AddressedEnvelope<ByteBuffer>
|
|
||||||
|
|
||||||
struct SDLHoleDatagram {
|
|
||||||
let remoteAddress: SocketAddress
|
|
||||||
let message: SDLHoleMessage
|
|
||||||
}
|
|
||||||
|
|
||||||
enum State {
|
|
||||||
case idle
|
|
||||||
case running
|
|
||||||
case stopped
|
|
||||||
}
|
|
||||||
|
|
||||||
private var state: State = .idle
|
|
||||||
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
|
||||||
private var channel: Channel?
|
|
||||||
|
|
||||||
let messageStream: AsyncThrowingStream<SDLHoleDatagram, Error>
|
|
||||||
private let messageContinuation: AsyncThrowingStream<SDLHoleDatagram, Error>.Continuation
|
|
||||||
|
|
||||||
init() throws {
|
|
||||||
let (stream, continuation) = AsyncThrowingStream.makeStream(of: SDLHoleDatagram.self, bufferingPolicy: .bufferingNewest(2048))
|
|
||||||
self.messageStream = stream
|
|
||||||
self.messageContinuation = continuation
|
|
||||||
}
|
|
||||||
|
|
||||||
func start() throws -> SocketAddress {
|
|
||||||
guard self.state == .idle else {
|
|
||||||
guard let localAddress = self.channel?.localAddress else {
|
|
||||||
throw SDLUDPHoleError.invalidLocalAddress
|
|
||||||
}
|
|
||||||
|
|
||||||
return localAddress
|
|
||||||
}
|
|
||||||
|
|
||||||
let bootstrap = DatagramBootstrap(group: group)
|
|
||||||
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
|
||||||
.channelInitializer { channel in
|
|
||||||
channel.pipeline.addHandler(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 绑定到IPv4通配地址,只处理IPv4流量
|
|
||||||
let channel = try bootstrap.bind(host: "0.0.0.0", port: 0).wait()
|
|
||||||
guard let localAddress = channel.localAddress else {
|
|
||||||
throw SDLUDPHoleError.invalidLocalAddress
|
|
||||||
}
|
|
||||||
|
|
||||||
self.channel = channel
|
|
||||||
self.state = .running
|
|
||||||
|
|
||||||
return localAddress
|
|
||||||
}
|
|
||||||
|
|
||||||
// --MARK: ChannelInboundHandler delegate
|
|
||||||
|
|
||||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
|
||||||
let envelope = unwrapInboundIn(data)
|
|
||||||
var buffer = envelope.data
|
|
||||||
let remoteAddress = envelope.remoteAddress
|
|
||||||
|
|
||||||
do {
|
|
||||||
if let message = try SDLHoleMessage.decode(buffer: &buffer) {
|
|
||||||
self.messageContinuation.yield(SDLHoleDatagram(remoteAddress: remoteAddress, message: message))
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLUDPHole] decode message, get null", category: .udpHole)
|
|
||||||
}
|
|
||||||
} catch let err {
|
|
||||||
SDLLogger.log("[SDLUDPHole] decode message, get error: \(err)", category: .udpHole)
|
|
||||||
self.messageContinuation.finish(throwing: err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func channelInactive(context: ChannelHandlerContext) {
|
|
||||||
self.messageContinuation.finish(throwing: SDLUDPHoleError.closed)
|
|
||||||
}
|
|
||||||
|
|
||||||
func errorCaught(context: ChannelHandlerContext, error: any Error) {
|
|
||||||
context.close(promise: nil)
|
|
||||||
self.messageContinuation.finish(throwing: SDLUDPHoleError.errorCaught)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: 处理写入逻辑
|
|
||||||
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) {
|
|
||||||
guard self.state == .running, let channel = self.channel else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var buffer = channel.allocator.buffer(capacity: data.count + 1)
|
|
||||||
buffer.writeBytes([type.rawValue])
|
|
||||||
buffer.writeBytes(data)
|
|
||||||
|
|
||||||
let envelope = AddressedEnvelope<ByteBuffer>(remoteAddress: remoteAddress, data: buffer)
|
|
||||||
let promise = channel.eventLoop.makePromise(of: Void.self)
|
|
||||||
|
|
||||||
channel.eventLoop.execute {
|
|
||||||
channel.writeAndFlush(envelope, promise: promise)
|
|
||||||
}
|
|
||||||
|
|
||||||
promise.futureResult.whenFailure { [weak self] err in
|
|
||||||
self?.messageContinuation.finish(throwing: SDLUDPHoleError.sendFaied(err))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
guard self.state != .stopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.state = .stopped
|
|
||||||
self.messageContinuation.finish()
|
|
||||||
|
|
||||||
let channel = self.channel
|
|
||||||
self.channel = nil
|
|
||||||
try? channel?.close().wait()
|
|
||||||
try? self.group.syncShutdownGracefully()
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLUDPHole] stopped", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[SDLUDPHole] deinit", category: .udpHole)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,152 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor SDLUDPHoleService {
|
|
||||||
enum Event {
|
|
||||||
case ready(SocketAddress)
|
|
||||||
case natType(SDLNATProberActor.NatType)
|
|
||||||
case packet(SocketAddress, SDLHoleControlMessage)
|
|
||||||
case closed(Error)
|
|
||||||
}
|
|
||||||
|
|
||||||
typealias EventHandler = @Sendable (Event) async -> Void
|
|
||||||
typealias DataHandler = @Sendable (SDLData) async -> Void
|
|
||||||
|
|
||||||
private let proberActor: SDLNATProberActor
|
|
||||||
|
|
||||||
private var onEvent: EventHandler = { _ in }
|
|
||||||
private var onData: DataHandler = { _ in }
|
|
||||||
private var currentSession: SDLUDPHoleSession?
|
|
||||||
private var generation: UInt64 = 0
|
|
||||||
private var isRunning = false
|
|
||||||
private var isStopping = false
|
|
||||||
private var needsImmediateRestart = false
|
|
||||||
private let retryDelay: Duration
|
|
||||||
|
|
||||||
init(proberActor: SDLNATProberActor, retryDelay: Duration = .seconds(5)) {
|
|
||||||
self.proberActor = proberActor
|
|
||||||
self.retryDelay = retryDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateHandlers(onEvent: @escaping EventHandler, onData: @escaping DataHandler) {
|
|
||||||
self.onEvent = onEvent
|
|
||||||
self.onData = onData
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard !self.isRunning else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isRunning = true
|
|
||||||
self.isStopping = false
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.isRunning = false
|
|
||||||
self.currentSession = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
while !Task.isCancelled, !self.isStopping {
|
|
||||||
let generation = self.nextGeneration()
|
|
||||||
let session = SDLUDPHoleSession(
|
|
||||||
proberActor: self.proberActor,
|
|
||||||
onEvent: { [weak self] event in
|
|
||||||
await self?.handleEvent(event, generation: generation)
|
|
||||||
},
|
|
||||||
onData: self.onData
|
|
||||||
)
|
|
||||||
|
|
||||||
self.currentSession = session
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await session.run()
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLUDPHoleService] session ended, will restart", category: .udpHole)
|
|
||||||
} catch is CancellationError {
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLUDPHoleService] session failed: \(error.localizedDescription), will restart", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.consumeImmediateRestartRequest() {
|
|
||||||
SDLLogger.log("[SDLUDPHoleService] session invalidated after wakeup, will restart immediately", category: .udpHole)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
try await Task.sleep(for: self.retryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
self.isStopping = true
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
await self.invalidateCurrentSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
func recoverAfterWake() async {
|
|
||||||
guard !self.isStopping else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.needsImmediateRestart = self.currentSession != nil
|
|
||||||
await self.invalidateCurrentSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) async {
|
|
||||||
await self.currentSession?.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func nextGeneration() -> UInt64 {
|
|
||||||
self.generation &+= 1
|
|
||||||
return self.generation
|
|
||||||
}
|
|
||||||
|
|
||||||
private func invalidateCurrentSession() async {
|
|
||||||
self.generation &+= 1
|
|
||||||
|
|
||||||
let session = self.currentSession
|
|
||||||
self.currentSession = nil
|
|
||||||
|
|
||||||
await session?.stop()
|
|
||||||
await self.proberActor.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func consumeImmediateRestartRequest() -> Bool {
|
|
||||||
let needsImmediateRestart = self.needsImmediateRestart
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
return needsImmediateRestart
|
|
||||||
}
|
|
||||||
|
|
||||||
private func clearCurrent(_ session: SDLUDPHoleSession, generation: UInt64) {
|
|
||||||
guard self.generation == generation else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.currentSession === session {
|
|
||||||
self.currentSession = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleEvent(_ event: Event, generation: UInt64) async {
|
|
||||||
guard self.generation == generation else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.onEvent(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,110 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLUDPHoleSession.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/27.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor SDLUDPHoleSession {
|
|
||||||
private let proberActor: SDLNATProberActor
|
|
||||||
private let onEvent: SDLUDPHoleService.EventHandler
|
|
||||||
private let onData: SDLUDPHoleService.DataHandler
|
|
||||||
|
|
||||||
private var udpHole: SDLUDPHole?
|
|
||||||
private var localAddress: SocketAddress?
|
|
||||||
|
|
||||||
init(
|
|
||||||
proberActor: SDLNATProberActor,
|
|
||||||
onEvent: @escaping SDLUDPHoleService.EventHandler,
|
|
||||||
onData: @escaping SDLUDPHoleService.DataHandler
|
|
||||||
) {
|
|
||||||
self.proberActor = proberActor
|
|
||||||
self.onEvent = onEvent
|
|
||||||
self.onData = onData
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
let udpHole = try SDLUDPHole()
|
|
||||||
let localAddress = try udpHole.start()
|
|
||||||
self.udpHole = udpHole
|
|
||||||
self.localAddress = localAddress
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLUDPHoleSession] udpHole started, on address: \(localAddress)", category: .udpHole)
|
|
||||||
await self.onEvent(.ready(localAddress))
|
|
||||||
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
try await self.readLoop(udpHole: udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
await self.probeNatType(udpHole: udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
try await group.waitForAll()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
let udpHole = self.udpHole
|
|
||||||
self.udpHole = nil
|
|
||||||
self.localAddress = nil
|
|
||||||
udpHole?.stop()
|
|
||||||
|
|
||||||
await self.proberActor.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) async {
|
|
||||||
guard case .v4 = remoteAddress else {
|
|
||||||
SDLLogger.log("[SDLUDPHoleSession] unsupported socket family: \(remoteAddress)", category: .udpHole)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let udpHole else {
|
|
||||||
SDLLogger.log("[SDLUDPHoleSession] udpHole is nil for remoteAddress: \(remoteAddress)", category: .udpHole)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
udpHole.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func readLoop(udpHole: SDLUDPHole) async throws {
|
|
||||||
for try await datagram in udpHole.messageStream {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
try await self.handleMessage(remoteAddress: datagram.remoteAddress, message: datagram.message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func probeNatType(udpHole: SDLUDPHole) async {
|
|
||||||
if Task.isCancelled {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
let natType = await self.proberActor.probeNatType(using: udpHole)
|
|
||||||
if Task.isCancelled {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.onEvent(.natType(natType))
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleMessage(remoteAddress: SocketAddress, message: SDLHoleMessage) async throws {
|
|
||||||
switch message {
|
|
||||||
case .control(let control):
|
|
||||||
switch control {
|
|
||||||
case .stunProbeReply(let probeReply):
|
|
||||||
await self.proberActor.handleProbeReply(localAddress: self.localAddress, reply: probeReply)
|
|
||||||
default:
|
|
||||||
await self.onEvent(.packet(remoteAddress, control))
|
|
||||||
}
|
|
||||||
case .data(let data):
|
|
||||||
await self.onData(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,72 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLHoleMessageDecoder.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/15.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
import NIOFoundationCompat
|
|
||||||
import NIOPosix
|
|
||||||
import SwiftProtobuf
|
|
||||||
|
|
||||||
// --MARK: 进来的消息, 这里需要采用代数类型来表示
|
|
||||||
enum SDLHoleMessage {
|
|
||||||
case data(SDLData)
|
|
||||||
case control(SDLHoleControlMessage)
|
|
||||||
}
|
|
||||||
|
|
||||||
enum SDLHoleControlMessage {
|
|
||||||
case register(SDLRegister)
|
|
||||||
case registerAck(SDLRegisterAck)
|
|
||||||
case stunProbeReply(SDLStunProbeReply)
|
|
||||||
case stunReply(SDLStunReply)
|
|
||||||
}
|
|
||||||
|
|
||||||
extension SDLHoleMessage {
|
|
||||||
|
|
||||||
static func decode(buffer: inout ByteBuffer) throws -> SDLHoleMessage? {
|
|
||||||
guard let type = buffer.readInteger(as: UInt8.self),
|
|
||||||
let packetType = SDLPacketType(rawValue: type) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
switch packetType {
|
|
||||||
case .data:
|
|
||||||
guard let bytes = buffer.readData(length: buffer.readableBytes, byteTransferStrategy: .copy),
|
|
||||||
let dataPacket = try? SDLData(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .data(dataPacket)
|
|
||||||
case .register:
|
|
||||||
guard let bytes = buffer.readData(length: buffer.readableBytes, byteTransferStrategy: .copy),
|
|
||||||
let registerPacket = try? SDLRegister(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .control(.register(registerPacket))
|
|
||||||
case .registerAck:
|
|
||||||
guard let bytes = buffer.readData(length: buffer.readableBytes, byteTransferStrategy: .copy),
|
|
||||||
let registerAck = try? SDLRegisterAck(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .control(.registerAck(registerAck))
|
|
||||||
case .stunProbeReply:
|
|
||||||
guard let bytes = buffer.readData(length: buffer.readableBytes, byteTransferStrategy: .copy),
|
|
||||||
let stunProbeReply = try? SDLStunProbeReply(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .control(.stunProbeReply(stunProbeReply))
|
|
||||||
case .stunReply:
|
|
||||||
guard let bytes = buffer.readData(length: buffer.readableBytes, byteTransferStrategy: .copy),
|
|
||||||
let stunReply = try? SDLStunReply(serializedBytes: bytes) else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return .control(.stunReply(stunReply))
|
|
||||||
default:
|
|
||||||
SDLLogger.log("[SDLUDPHole] decode miss type: \(type)", category: .udpHole)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLUDPHoleError.swift
|
|
||||||
// punchnet
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/5/22.
|
|
||||||
//
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
enum SDLUDPHoleError: Error {
|
|
||||||
case invalidLocalAddress
|
|
||||||
case closed
|
|
||||||
case errorCaught
|
|
||||||
case sendFaied(Error)
|
|
||||||
}
|
|
||||||
@ -1,133 +0,0 @@
|
|||||||
//
|
|
||||||
// SDLUDPHoleV6.swift
|
|
||||||
// Tun
|
|
||||||
//
|
|
||||||
// Created by 安礼成 on 2026/4/15.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
import NIOPosix
|
|
||||||
import SwiftProtobuf
|
|
||||||
|
|
||||||
// 处理和sn-server服务器之间的通讯
|
|
||||||
final class SDLUDPHoleV6: ChannelInboundHandler {
|
|
||||||
typealias InboundIn = AddressedEnvelope<ByteBuffer>
|
|
||||||
|
|
||||||
// 事件
|
|
||||||
enum HoleEvent {
|
|
||||||
case ready
|
|
||||||
case closed
|
|
||||||
case errorCaught
|
|
||||||
}
|
|
||||||
|
|
||||||
private var isStopped: Bool = false
|
|
||||||
|
|
||||||
private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
|
||||||
private var channel: Channel?
|
|
||||||
|
|
||||||
public let messageStream: AsyncStream<(SocketAddress, SDLHoleMessage)>
|
|
||||||
private let messageContinuation: AsyncStream<(SocketAddress, SDLHoleMessage)>.Continuation
|
|
||||||
|
|
||||||
// 事件相关逻辑
|
|
||||||
public let eventStream: AsyncStream<HoleEvent>
|
|
||||||
private let eventContinuation: AsyncStream<HoleEvent>.Continuation
|
|
||||||
|
|
||||||
// 启动函数
|
|
||||||
init() throws {
|
|
||||||
let (stream, continuation) = AsyncStream.makeStream(of: (SocketAddress, SDLHoleMessage).self, bufferingPolicy: .bufferingNewest(2048))
|
|
||||||
self.messageStream = stream
|
|
||||||
self.messageContinuation = continuation
|
|
||||||
|
|
||||||
let eventPair = AsyncStream.makeStream(of: HoleEvent.self)
|
|
||||||
self.eventStream = eventPair.stream
|
|
||||||
self.eventContinuation = eventPair.continuation
|
|
||||||
}
|
|
||||||
|
|
||||||
func start() throws -> SocketAddress? {
|
|
||||||
let bootstrap = DatagramBootstrap(group: group)
|
|
||||||
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
|
||||||
.channelInitializer { channel in
|
|
||||||
channel.pipeline.addHandler(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 绑定到IPv6通配地址,只处理IPv6流量
|
|
||||||
let channel = try bootstrap.bind(host: "::", port: 0).wait()
|
|
||||||
self.channel = channel
|
|
||||||
|
|
||||||
return channel.localAddress
|
|
||||||
}
|
|
||||||
|
|
||||||
// --MARK: ChannelInboundHandler delegate
|
|
||||||
|
|
||||||
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
|
||||||
let envelope = unwrapInboundIn(data)
|
|
||||||
|
|
||||||
var buffer = envelope.data
|
|
||||||
let remoteAddress = envelope.remoteAddress
|
|
||||||
|
|
||||||
if let rawBytes = buffer.getBytes(at: buffer.readerIndex, length: buffer.readableBytes) {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] get raw bytes: \(rawBytes.count), from: \(remoteAddress)", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
if let message = try SDLHoleMessage.decode(buffer: &buffer) {
|
|
||||||
self.messageContinuation.yield((remoteAddress, message))
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] decode message, get null", category: .udpHole)
|
|
||||||
}
|
|
||||||
} catch let err {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] decode message, get error: \(err)", category: .udpHole)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func channelInactive(context: ChannelHandlerContext) {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] channelInactive", category: .udpHole)
|
|
||||||
self.eventContinuation.yield(.closed)
|
|
||||||
}
|
|
||||||
|
|
||||||
func errorCaught(context: ChannelHandlerContext, error: any Error) {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] channel error: \(error)", category: .udpHole)
|
|
||||||
context.close(promise: nil)
|
|
||||||
self.eventContinuation.yield(.errorCaught)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: 处理写入逻辑
|
|
||||||
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) {
|
|
||||||
guard let channel = self.channel else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var buffer = channel.allocator.buffer(capacity: data.count + 1)
|
|
||||||
buffer.writeBytes([type.rawValue])
|
|
||||||
buffer.writeBytes(data)
|
|
||||||
|
|
||||||
let envelope = AddressedEnvelope<ByteBuffer>(remoteAddress: remoteAddress, data: buffer)
|
|
||||||
_ = channel.eventLoop.submit {
|
|
||||||
channel.writeAndFlush(envelope, promise: nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() {
|
|
||||||
guard !self.isStopped else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isStopped = true
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] stop", category: .udpHole)
|
|
||||||
|
|
||||||
self.messageContinuation.finish()
|
|
||||||
self.eventContinuation.finish()
|
|
||||||
|
|
||||||
let channel = self.channel
|
|
||||||
self.channel = nil
|
|
||||||
try? channel?.close().wait()
|
|
||||||
|
|
||||||
try? self.group.syncShutdownGracefully()
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6] deinit", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,140 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor SDLUDPHoleV6Service {
|
|
||||||
typealias EventHandler = SDLUDPHoleService.EventHandler
|
|
||||||
typealias DataHandler = SDLUDPHoleService.DataHandler
|
|
||||||
|
|
||||||
private var onEvent: EventHandler = { _ in }
|
|
||||||
private var onData: DataHandler = { _ in }
|
|
||||||
private var currentSession: SDLUDPHoleV6Session?
|
|
||||||
private var generation: UInt64 = 0
|
|
||||||
private var isRunning = false
|
|
||||||
private var isStopping = false
|
|
||||||
private var needsImmediateRestart = false
|
|
||||||
private let retryDelay: Duration
|
|
||||||
|
|
||||||
init(retryDelay: Duration = .seconds(5)) {
|
|
||||||
self.retryDelay = retryDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateHandlers(onEvent: @escaping EventHandler, onData: @escaping DataHandler) {
|
|
||||||
self.onEvent = onEvent
|
|
||||||
self.onData = onData
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
guard !self.isRunning else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.isRunning = true
|
|
||||||
self.isStopping = false
|
|
||||||
|
|
||||||
defer {
|
|
||||||
self.isRunning = false
|
|
||||||
self.currentSession = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
while !Task.isCancelled, !self.isStopping {
|
|
||||||
let generation = self.nextGeneration()
|
|
||||||
let session = SDLUDPHoleV6Session(
|
|
||||||
onEvent: { [weak self] event in
|
|
||||||
await self?.handleEvent(event, generation: generation)
|
|
||||||
},
|
|
||||||
onData: self.onData
|
|
||||||
)
|
|
||||||
|
|
||||||
self.currentSession = session
|
|
||||||
|
|
||||||
do {
|
|
||||||
try await session.run()
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Service] session ended, will restart", category: .udpHole)
|
|
||||||
} catch is CancellationError {
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
throw CancellationError()
|
|
||||||
} catch {
|
|
||||||
self.clearCurrent(session, generation: generation)
|
|
||||||
await session.stop()
|
|
||||||
|
|
||||||
guard !self.isStopping else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Service] session failed: \(error.localizedDescription), will restart", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.consumeImmediateRestartRequest() {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Service] session invalidated after wakeup, will restart immediately", category: .udpHole)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
try await Task.sleep(for: self.retryDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
self.isStopping = true
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
await self.invalidateCurrentSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
func recoverAfterWake() async {
|
|
||||||
guard !self.isStopping else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
self.needsImmediateRestart = self.currentSession != nil
|
|
||||||
await self.invalidateCurrentSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) async {
|
|
||||||
await self.currentSession?.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func nextGeneration() -> UInt64 {
|
|
||||||
self.generation &+= 1
|
|
||||||
return self.generation
|
|
||||||
}
|
|
||||||
|
|
||||||
private func invalidateCurrentSession() async {
|
|
||||||
self.generation &+= 1
|
|
||||||
|
|
||||||
let session = self.currentSession
|
|
||||||
self.currentSession = nil
|
|
||||||
|
|
||||||
await session?.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
private func consumeImmediateRestartRequest() -> Bool {
|
|
||||||
let needsImmediateRestart = self.needsImmediateRestart
|
|
||||||
self.needsImmediateRestart = false
|
|
||||||
return needsImmediateRestart
|
|
||||||
}
|
|
||||||
|
|
||||||
private func clearCurrent(_ session: SDLUDPHoleV6Session, generation: UInt64) {
|
|
||||||
guard self.generation == generation else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.currentSession === session {
|
|
||||||
self.currentSession = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func handleEvent(_ event: SDLUDPHoleService.Event, generation: UInt64) async {
|
|
||||||
guard self.generation == generation else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await self.onEvent(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,84 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import NIOCore
|
|
||||||
|
|
||||||
actor SDLUDPHoleV6Session {
|
|
||||||
private let onEvent: SDLUDPHoleService.EventHandler
|
|
||||||
private let onData: SDLUDPHoleService.DataHandler
|
|
||||||
|
|
||||||
private var udpHoleV6: SDLUDPHoleV6?
|
|
||||||
|
|
||||||
init(
|
|
||||||
onEvent: @escaping SDLUDPHoleService.EventHandler,
|
|
||||||
onData: @escaping SDLUDPHoleService.DataHandler
|
|
||||||
) {
|
|
||||||
self.onEvent = onEvent
|
|
||||||
self.onData = onData
|
|
||||||
}
|
|
||||||
|
|
||||||
func run() async throws {
|
|
||||||
let udpHoleV6 = try SDLUDPHoleV6()
|
|
||||||
let localAddress = try udpHoleV6.start()
|
|
||||||
self.udpHoleV6 = udpHoleV6
|
|
||||||
|
|
||||||
if let localAddress {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Session] udpHoleV6 started, on address: \(localAddress)", category: .udpHole)
|
|
||||||
} else {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Session] udpHoleV6 started, no local address", category: .udpHole)
|
|
||||||
}
|
|
||||||
|
|
||||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
|
||||||
defer {
|
|
||||||
group.cancelAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
let onEvent = self.onEvent
|
|
||||||
let onData = self.onData
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
for await (remoteAddress, message) in udpHoleV6.messageStream {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
switch message {
|
|
||||||
case .control(let control):
|
|
||||||
await onEvent(.packet(remoteAddress, control))
|
|
||||||
case .data(let data):
|
|
||||||
await onData(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
group.addTask {
|
|
||||||
for await event in udpHoleV6.eventStream {
|
|
||||||
try Task.checkCancellation()
|
|
||||||
switch event {
|
|
||||||
case .ready:
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Session] udpHoleV6 ready", category: .udpHole)
|
|
||||||
case .closed, .errorCaught:
|
|
||||||
throw SDLContextError.udpHoleClosed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = try await group.next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stop() async {
|
|
||||||
let udpHoleV6 = self.udpHoleV6
|
|
||||||
self.udpHoleV6 = nil
|
|
||||||
udpHoleV6?.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) {
|
|
||||||
guard case .v6 = remoteAddress else {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Session] unsupported socket family: \(remoteAddress)", category: .udpHole)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
guard let udpHoleV6 else {
|
|
||||||
SDLLogger.log("[SDLUDPHoleV6Session] udpHoleV6 is nil for remoteAddress: \(remoteAddress)", category: .udpHole)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
udpHoleV6.send(type: type, data: data, remoteAddress: remoteAddress)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
2
dmg.sh
2
dmg.sh
@ -1,3 +1,3 @@
|
|||||||
#! /bin/sh
|
#! /bin/sh
|
||||||
|
|
||||||
create-dmg --volname "punchnet" --window-pos 200 120 --window-size 800 400 --icon "punchnet.app" 200 190 --hide-extension "punchnet.app" --app-drop-link 600 185 ~/Desktop/punchnet.dmg /Users/anlicheng/Desktop/punchnet-release-v1.0
|
create-dmg --volname "punchnet" --window-pos 200 120 --window-size 800 400 --icon "punchnet.app" 200 190 --hide-extension "punchnet.app" --app-drop-link 600 185 ~/Desktop/punchnet.dmg /Users/anlicheng/Desktop/punchnet_macos_v1
|
||||||
|
|||||||
@ -1,914 +0,0 @@
|
|||||||
// !$*UTF8*$!
|
|
||||||
{
|
|
||||||
archiveVersion = 1;
|
|
||||||
classes = {
|
|
||||||
};
|
|
||||||
objectVersion = 77;
|
|
||||||
objects = {
|
|
||||||
|
|
||||||
/* Begin PBXBuildFile section */
|
|
||||||
C89D410D2F874CC5001A17CF /* SwiftProtobuf in Frameworks */ = {isa = PBXBuildFile; productRef = C89D410C2F874CC5001A17CF /* SwiftProtobuf */; };
|
|
||||||
C8A77F2A2DD1E77B00195617 /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C8A77F292DD1E77B00195617 /* NetworkExtension.framework */; };
|
|
||||||
C8A77F322DD1E77B00195617 /* Tun.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = C8A77F272DD1E77B00195617 /* Tun.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
|
||||||
C8A77F792DD1E93900195617 /* NIO in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F782DD1E93900195617 /* NIO */; };
|
|
||||||
C8A77F7B2DD1E93900195617 /* NIOConcurrencyHelpers in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F7A2DD1E93900195617 /* NIOConcurrencyHelpers */; };
|
|
||||||
C8A77F7D2DD1E93900195617 /* NIOCore in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F7C2DD1E93900195617 /* NIOCore */; };
|
|
||||||
C8A77F7F2DD1E93900195617 /* NIOEmbedded in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F7E2DD1E93900195617 /* NIOEmbedded */; };
|
|
||||||
C8A77F812DD1E93900195617 /* NIOFoundationCompat in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F802DD1E93900195617 /* NIOFoundationCompat */; };
|
|
||||||
C8A77F882DD1EA0200195617 /* SwiftProtobuf in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F872DD1EA0200195617 /* SwiftProtobuf */; };
|
|
||||||
C8A77F8A2DD1EA0200195617 /* SwiftProtobufPluginLibrary in Frameworks */ = {isa = PBXBuildFile; productRef = C8A77F892DD1EA0200195617 /* SwiftProtobufPluginLibrary */; };
|
|
||||||
C8AA72BB2E5C49E000E4C4E9 /* SwiftProtobuf in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72BA2E5C49E000E4C4E9 /* SwiftProtobuf */; };
|
|
||||||
C8AA72BD2E5C49E000E4C4E9 /* SwiftProtobufPluginLibrary in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72BC2E5C49E000E4C4E9 /* SwiftProtobufPluginLibrary */; };
|
|
||||||
C8AA72C02E5C4A3100E4C4E9 /* NIO in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72BF2E5C4A3100E4C4E9 /* NIO */; };
|
|
||||||
C8AA72C22E5C4A3100E4C4E9 /* NIOConcurrencyHelpers in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72C12E5C4A3100E4C4E9 /* NIOConcurrencyHelpers */; };
|
|
||||||
C8AA72C42E5C4A3100E4C4E9 /* NIOCore in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72C32E5C4A3100E4C4E9 /* NIOCore */; };
|
|
||||||
C8AA72C62E5C4A3100E4C4E9 /* NIOEmbedded in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72C52E5C4A3100E4C4E9 /* NIOEmbedded */; };
|
|
||||||
C8AA72C82E5C4A3100E4C4E9 /* NIOFoundationCompat in Frameworks */ = {isa = PBXBuildFile; productRef = C8AA72C72E5C4A3100E4C4E9 /* NIOFoundationCompat */; };
|
|
||||||
/* End PBXBuildFile section */
|
|
||||||
|
|
||||||
/* Begin PBXContainerItemProxy section */
|
|
||||||
C8A77F072DD1E6D100195617 /* PBXContainerItemProxy */ = {
|
|
||||||
isa = PBXContainerItemProxy;
|
|
||||||
containerPortal = C8A77EEB2DD1E6D000195617 /* Project object */;
|
|
||||||
proxyType = 1;
|
|
||||||
remoteGlobalIDString = C8A77EF22DD1E6D000195617;
|
|
||||||
remoteInfo = punchnet;
|
|
||||||
};
|
|
||||||
C8A77F112DD1E6D100195617 /* PBXContainerItemProxy */ = {
|
|
||||||
isa = PBXContainerItemProxy;
|
|
||||||
containerPortal = C8A77EEB2DD1E6D000195617 /* Project object */;
|
|
||||||
proxyType = 1;
|
|
||||||
remoteGlobalIDString = C8A77EF22DD1E6D000195617;
|
|
||||||
remoteInfo = punchnet;
|
|
||||||
};
|
|
||||||
C8A77F302DD1E77B00195617 /* PBXContainerItemProxy */ = {
|
|
||||||
isa = PBXContainerItemProxy;
|
|
||||||
containerPortal = C8A77EEB2DD1E6D000195617 /* Project object */;
|
|
||||||
proxyType = 1;
|
|
||||||
remoteGlobalIDString = C8A77F262DD1E77B00195617;
|
|
||||||
remoteInfo = Tun;
|
|
||||||
};
|
|
||||||
/* End PBXContainerItemProxy section */
|
|
||||||
|
|
||||||
/* Begin PBXCopyFilesBuildPhase section */
|
|
||||||
C8A77F372DD1E77B00195617 /* Embed Foundation Extensions */ = {
|
|
||||||
isa = PBXCopyFilesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
dstPath = "";
|
|
||||||
dstSubfolderSpec = 13;
|
|
||||||
files = (
|
|
||||||
C8A77F322DD1E77B00195617 /* Tun.appex in Embed Foundation Extensions */,
|
|
||||||
);
|
|
||||||
name = "Embed Foundation Extensions";
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXCopyFilesBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
|
||||||
C8A77EF32DD1E6D000195617 /* punchnet.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = punchnet.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
C8A77F062DD1E6D100195617 /* punchnetTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = punchnetTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
C8A77F102DD1E6D100195617 /* punchnetUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = punchnetUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
C8A77F272DD1E77B00195617 /* Tun.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = Tun.appex; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
C8A77F292DD1E77B00195617 /* NetworkExtension.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = NetworkExtension.framework; path = System/Library/Frameworks/NetworkExtension.framework; sourceTree = SDKROOT; };
|
|
||||||
/* End PBXFileReference section */
|
|
||||||
|
|
||||||
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
|
|
||||||
C89D42E62F8F39B7001A17CF /* Exceptions for "Tun" folder in "punchnet" target */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
|
||||||
membershipExceptions = (
|
|
||||||
Protobuf/TunMessage.pb.swift,
|
|
||||||
);
|
|
||||||
target = C8A77EF22DD1E6D000195617 /* punchnet */;
|
|
||||||
};
|
|
||||||
C8A77F332DD1E77B00195617 /* Exceptions for "Tun" folder in "Tun" target */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
|
||||||
membershipExceptions = (
|
|
||||||
Info.plist,
|
|
||||||
);
|
|
||||||
target = C8A77F262DD1E77B00195617 /* Tun */;
|
|
||||||
};
|
|
||||||
C8A77F8C2DD1EA7900195617 /* Exceptions for "punchnet" folder in "Tun" target */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
|
|
||||||
membershipExceptions = (
|
|
||||||
AppEventCenter/SDLNotificationCenter.swift,
|
|
||||||
);
|
|
||||||
target = C8A77F262DD1E77B00195617 /* Tun */;
|
|
||||||
};
|
|
||||||
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
|
|
||||||
|
|
||||||
/* Begin PBXFileSystemSynchronizedRootGroup section */
|
|
||||||
C8A77EF52DD1E6D000195617 /* punchnet */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
exceptions = (
|
|
||||||
C8A77F8C2DD1EA7900195617 /* Exceptions for "punchnet" folder in "Tun" target */,
|
|
||||||
);
|
|
||||||
path = punchnet;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
C8A77F092DD1E6D100195617 /* punchnetTests */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
path = punchnetTests;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
C8A77F132DD1E6D100195617 /* punchnetUITests */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
path = punchnetUITests;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
C8A77F2B2DD1E77B00195617 /* Tun */ = {
|
|
||||||
isa = PBXFileSystemSynchronizedRootGroup;
|
|
||||||
exceptions = (
|
|
||||||
C89D42E62F8F39B7001A17CF /* Exceptions for "Tun" folder in "punchnet" target */,
|
|
||||||
C8A77F332DD1E77B00195617 /* Exceptions for "Tun" folder in "Tun" target */,
|
|
||||||
);
|
|
||||||
path = Tun;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
/* End PBXFileSystemSynchronizedRootGroup section */
|
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
|
||||||
C8A77EF02DD1E6D000195617 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
C8A77F7D2DD1E93900195617 /* NIOCore in Frameworks */,
|
|
||||||
C8A77F812DD1E93900195617 /* NIOFoundationCompat in Frameworks */,
|
|
||||||
C8A77F792DD1E93900195617 /* NIO in Frameworks */,
|
|
||||||
C8A77F7B2DD1E93900195617 /* NIOConcurrencyHelpers in Frameworks */,
|
|
||||||
C8A77F7F2DD1E93900195617 /* NIOEmbedded in Frameworks */,
|
|
||||||
C89D410D2F874CC5001A17CF /* SwiftProtobuf in Frameworks */,
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F032DD1E6D100195617 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F0D2DD1E6D100195617 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F242DD1E77B00195617 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
C8A77F2A2DD1E77B00195617 /* NetworkExtension.framework in Frameworks */,
|
|
||||||
C8A77F8A2DD1EA0200195617 /* SwiftProtobufPluginLibrary in Frameworks */,
|
|
||||||
C8AA72BD2E5C49E000E4C4E9 /* SwiftProtobufPluginLibrary in Frameworks */,
|
|
||||||
C8AA72C62E5C4A3100E4C4E9 /* NIOEmbedded in Frameworks */,
|
|
||||||
C8AA72C02E5C4A3100E4C4E9 /* NIO in Frameworks */,
|
|
||||||
C8AA72C22E5C4A3100E4C4E9 /* NIOConcurrencyHelpers in Frameworks */,
|
|
||||||
C8AA72C82E5C4A3100E4C4E9 /* NIOFoundationCompat in Frameworks */,
|
|
||||||
C8A77F882DD1EA0200195617 /* SwiftProtobuf in Frameworks */,
|
|
||||||
C8AA72C42E5C4A3100E4C4E9 /* NIOCore in Frameworks */,
|
|
||||||
C8AA72BB2E5C49E000E4C4E9 /* SwiftProtobuf in Frameworks */,
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXFrameworksBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXGroup section */
|
|
||||||
C8A77EEA2DD1E6D000195617 = {
|
|
||||||
isa = PBXGroup;
|
|
||||||
children = (
|
|
||||||
C8A77EF52DD1E6D000195617 /* punchnet */,
|
|
||||||
C8A77F092DD1E6D100195617 /* punchnetTests */,
|
|
||||||
C8A77F132DD1E6D100195617 /* punchnetUITests */,
|
|
||||||
C8A77F2B2DD1E77B00195617 /* Tun */,
|
|
||||||
C8A77F282DD1E77B00195617 /* Frameworks */,
|
|
||||||
C8A77EF42DD1E6D000195617 /* Products */,
|
|
||||||
);
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
C8A77EF42DD1E6D000195617 /* Products */ = {
|
|
||||||
isa = PBXGroup;
|
|
||||||
children = (
|
|
||||||
C8A77EF32DD1E6D000195617 /* punchnet.app */,
|
|
||||||
C8A77F062DD1E6D100195617 /* punchnetTests.xctest */,
|
|
||||||
C8A77F102DD1E6D100195617 /* punchnetUITests.xctest */,
|
|
||||||
C8A77F272DD1E77B00195617 /* Tun.appex */,
|
|
||||||
);
|
|
||||||
name = Products;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
C8A77F282DD1E77B00195617 /* Frameworks */ = {
|
|
||||||
isa = PBXGroup;
|
|
||||||
children = (
|
|
||||||
C8A77F292DD1E77B00195617 /* NetworkExtension.framework */,
|
|
||||||
);
|
|
||||||
name = Frameworks;
|
|
||||||
sourceTree = "<group>";
|
|
||||||
};
|
|
||||||
/* End PBXGroup section */
|
|
||||||
|
|
||||||
/* Begin PBXNativeTarget section */
|
|
||||||
C8A77EF22DD1E6D000195617 /* punchnet */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = C8A77F1A2DD1E6D100195617 /* Build configuration list for PBXNativeTarget "punchnet" */;
|
|
||||||
buildPhases = (
|
|
||||||
C8A77EEF2DD1E6D000195617 /* Sources */,
|
|
||||||
C8A77EF02DD1E6D000195617 /* Frameworks */,
|
|
||||||
C8A77EF12DD1E6D000195617 /* Resources */,
|
|
||||||
C8A77F372DD1E77B00195617 /* Embed Foundation Extensions */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
C8A77F312DD1E77B00195617 /* PBXTargetDependency */,
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
C8A77EF52DD1E6D000195617 /* punchnet */,
|
|
||||||
);
|
|
||||||
name = punchnet;
|
|
||||||
packageProductDependencies = (
|
|
||||||
C8A77F782DD1E93900195617 /* NIO */,
|
|
||||||
C8A77F7A2DD1E93900195617 /* NIOConcurrencyHelpers */,
|
|
||||||
C8A77F7C2DD1E93900195617 /* NIOCore */,
|
|
||||||
C8A77F7E2DD1E93900195617 /* NIOEmbedded */,
|
|
||||||
C8A77F802DD1E93900195617 /* NIOFoundationCompat */,
|
|
||||||
C89D410C2F874CC5001A17CF /* SwiftProtobuf */,
|
|
||||||
);
|
|
||||||
productName = punchnet;
|
|
||||||
productReference = C8A77EF32DD1E6D000195617 /* punchnet.app */;
|
|
||||||
productType = "com.apple.product-type.application";
|
|
||||||
};
|
|
||||||
C8A77F052DD1E6D100195617 /* punchnetTests */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = C8A77F1D2DD1E6D100195617 /* Build configuration list for PBXNativeTarget "punchnetTests" */;
|
|
||||||
buildPhases = (
|
|
||||||
C8A77F022DD1E6D100195617 /* Sources */,
|
|
||||||
C8A77F032DD1E6D100195617 /* Frameworks */,
|
|
||||||
C8A77F042DD1E6D100195617 /* Resources */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
C8A77F082DD1E6D100195617 /* PBXTargetDependency */,
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
C8A77F092DD1E6D100195617 /* punchnetTests */,
|
|
||||||
);
|
|
||||||
name = punchnetTests;
|
|
||||||
packageProductDependencies = (
|
|
||||||
);
|
|
||||||
productName = punchnetTests;
|
|
||||||
productReference = C8A77F062DD1E6D100195617 /* punchnetTests.xctest */;
|
|
||||||
productType = "com.apple.product-type.bundle.unit-test";
|
|
||||||
};
|
|
||||||
C8A77F0F2DD1E6D100195617 /* punchnetUITests */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = C8A77F202DD1E6D100195617 /* Build configuration list for PBXNativeTarget "punchnetUITests" */;
|
|
||||||
buildPhases = (
|
|
||||||
C8A77F0C2DD1E6D100195617 /* Sources */,
|
|
||||||
C8A77F0D2DD1E6D100195617 /* Frameworks */,
|
|
||||||
C8A77F0E2DD1E6D100195617 /* Resources */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
C8A77F122DD1E6D100195617 /* PBXTargetDependency */,
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
C8A77F132DD1E6D100195617 /* punchnetUITests */,
|
|
||||||
);
|
|
||||||
name = punchnetUITests;
|
|
||||||
packageProductDependencies = (
|
|
||||||
);
|
|
||||||
productName = punchnetUITests;
|
|
||||||
productReference = C8A77F102DD1E6D100195617 /* punchnetUITests.xctest */;
|
|
||||||
productType = "com.apple.product-type.bundle.ui-testing";
|
|
||||||
};
|
|
||||||
C8A77F262DD1E77B00195617 /* Tun */ = {
|
|
||||||
isa = PBXNativeTarget;
|
|
||||||
buildConfigurationList = C8A77F342DD1E77B00195617 /* Build configuration list for PBXNativeTarget "Tun" */;
|
|
||||||
buildPhases = (
|
|
||||||
C8A77F232DD1E77B00195617 /* Sources */,
|
|
||||||
C8A77F242DD1E77B00195617 /* Frameworks */,
|
|
||||||
C8A77F252DD1E77B00195617 /* Resources */,
|
|
||||||
);
|
|
||||||
buildRules = (
|
|
||||||
);
|
|
||||||
dependencies = (
|
|
||||||
);
|
|
||||||
fileSystemSynchronizedGroups = (
|
|
||||||
C8A77F2B2DD1E77B00195617 /* Tun */,
|
|
||||||
);
|
|
||||||
name = Tun;
|
|
||||||
packageProductDependencies = (
|
|
||||||
C8A77F872DD1EA0200195617 /* SwiftProtobuf */,
|
|
||||||
C8A77F892DD1EA0200195617 /* SwiftProtobufPluginLibrary */,
|
|
||||||
C8AA72BA2E5C49E000E4C4E9 /* SwiftProtobuf */,
|
|
||||||
C8AA72BC2E5C49E000E4C4E9 /* SwiftProtobufPluginLibrary */,
|
|
||||||
C8AA72BF2E5C4A3100E4C4E9 /* NIO */,
|
|
||||||
C8AA72C12E5C4A3100E4C4E9 /* NIOConcurrencyHelpers */,
|
|
||||||
C8AA72C32E5C4A3100E4C4E9 /* NIOCore */,
|
|
||||||
C8AA72C52E5C4A3100E4C4E9 /* NIOEmbedded */,
|
|
||||||
C8AA72C72E5C4A3100E4C4E9 /* NIOFoundationCompat */,
|
|
||||||
);
|
|
||||||
productName = Tun;
|
|
||||||
productReference = C8A77F272DD1E77B00195617 /* Tun.appex */;
|
|
||||||
productType = "com.apple.product-type.app-extension";
|
|
||||||
};
|
|
||||||
/* End PBXNativeTarget section */
|
|
||||||
|
|
||||||
/* Begin PBXProject section */
|
|
||||||
C8A77EEB2DD1E6D000195617 /* Project object */ = {
|
|
||||||
isa = PBXProject;
|
|
||||||
attributes = {
|
|
||||||
BuildIndependentTargetsInParallel = 1;
|
|
||||||
LastSwiftUpdateCheck = 1620;
|
|
||||||
LastUpgradeCheck = 1620;
|
|
||||||
TargetAttributes = {
|
|
||||||
C8A77EF22DD1E6D000195617 = {
|
|
||||||
CreatedOnToolsVersion = 16.2;
|
|
||||||
};
|
|
||||||
C8A77F052DD1E6D100195617 = {
|
|
||||||
CreatedOnToolsVersion = 16.2;
|
|
||||||
TestTargetID = C8A77EF22DD1E6D000195617;
|
|
||||||
};
|
|
||||||
C8A77F0F2DD1E6D100195617 = {
|
|
||||||
CreatedOnToolsVersion = 16.2;
|
|
||||||
TestTargetID = C8A77EF22DD1E6D000195617;
|
|
||||||
};
|
|
||||||
C8A77F262DD1E77B00195617 = {
|
|
||||||
CreatedOnToolsVersion = 16.2;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
buildConfigurationList = C8A77EEE2DD1E6D000195617 /* Build configuration list for PBXProject "punchnet" */;
|
|
||||||
developmentRegion = en;
|
|
||||||
hasScannedForEncodings = 0;
|
|
||||||
knownRegions = (
|
|
||||||
en,
|
|
||||||
Base,
|
|
||||||
);
|
|
||||||
mainGroup = C8A77EEA2DD1E6D000195617;
|
|
||||||
minimizedProjectReferenceProxies = 1;
|
|
||||||
packageReferences = (
|
|
||||||
C8AA72B92E5C49E000E4C4E9 /* XCRemoteSwiftPackageReference "swift-protobuf" */,
|
|
||||||
C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */,
|
|
||||||
);
|
|
||||||
preferredProjectObjectVersion = 77;
|
|
||||||
productRefGroup = C8A77EF42DD1E6D000195617 /* Products */;
|
|
||||||
projectDirPath = "";
|
|
||||||
projectRoot = "";
|
|
||||||
targets = (
|
|
||||||
C8A77EF22DD1E6D000195617 /* punchnet */,
|
|
||||||
C8A77F052DD1E6D100195617 /* punchnetTests */,
|
|
||||||
C8A77F0F2DD1E6D100195617 /* punchnetUITests */,
|
|
||||||
C8A77F262DD1E77B00195617 /* Tun */,
|
|
||||||
);
|
|
||||||
};
|
|
||||||
/* End PBXProject section */
|
|
||||||
|
|
||||||
/* Begin PBXResourcesBuildPhase section */
|
|
||||||
C8A77EF12DD1E6D000195617 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F042DD1E6D100195617 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F0E2DD1E6D100195617 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F252DD1E77B00195617 /* Resources */ = {
|
|
||||||
isa = PBXResourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXResourcesBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXSourcesBuildPhase section */
|
|
||||||
C8A77EEF2DD1E6D000195617 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F022DD1E6D100195617 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F0C2DD1E6D100195617 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
C8A77F232DD1E77B00195617 /* Sources */ = {
|
|
||||||
isa = PBXSourcesBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXSourcesBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXTargetDependency section */
|
|
||||||
C8A77F082DD1E6D100195617 /* PBXTargetDependency */ = {
|
|
||||||
isa = PBXTargetDependency;
|
|
||||||
target = C8A77EF22DD1E6D000195617 /* punchnet */;
|
|
||||||
targetProxy = C8A77F072DD1E6D100195617 /* PBXContainerItemProxy */;
|
|
||||||
};
|
|
||||||
C8A77F122DD1E6D100195617 /* PBXTargetDependency */ = {
|
|
||||||
isa = PBXTargetDependency;
|
|
||||||
target = C8A77EF22DD1E6D000195617 /* punchnet */;
|
|
||||||
targetProxy = C8A77F112DD1E6D100195617 /* PBXContainerItemProxy */;
|
|
||||||
};
|
|
||||||
C8A77F312DD1E77B00195617 /* PBXTargetDependency */ = {
|
|
||||||
isa = PBXTargetDependency;
|
|
||||||
target = C8A77F262DD1E77B00195617 /* Tun */;
|
|
||||||
targetProxy = C8A77F302DD1E77B00195617 /* PBXContainerItemProxy */;
|
|
||||||
};
|
|
||||||
/* End PBXTargetDependency section */
|
|
||||||
|
|
||||||
/* Begin XCBuildConfiguration section */
|
|
||||||
C8A77F182DD1E6D100195617 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
|
||||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
|
||||||
CLANG_ENABLE_MODULES = YES;
|
|
||||||
CLANG_ENABLE_OBJC_ARC = YES;
|
|
||||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
|
||||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
|
||||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_COMMA = YES;
|
|
||||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
|
||||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
|
||||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
|
||||||
CLANG_WARN_EMPTY_BODY = YES;
|
|
||||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
|
||||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
|
||||||
CLANG_WARN_INT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
|
||||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
|
||||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
|
||||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
|
||||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
|
||||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
|
||||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
|
||||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
|
||||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
|
||||||
COPY_PHASE_STRIP = NO;
|
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
|
||||||
ENABLE_TESTABILITY = YES;
|
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
|
||||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
|
||||||
GCC_DYNAMIC_NO_PIC = NO;
|
|
||||||
GCC_NO_COMMON_BLOCKS = YES;
|
|
||||||
GCC_OPTIMIZATION_LEVEL = 0;
|
|
||||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
|
||||||
"DEBUG=1",
|
|
||||||
"$(inherited)",
|
|
||||||
);
|
|
||||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
|
||||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
|
||||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
|
||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
|
||||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
|
||||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
|
||||||
MTL_FAST_MATH = YES;
|
|
||||||
ONLY_ACTIVE_ARCH = YES;
|
|
||||||
SDKROOT = macosx;
|
|
||||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
|
||||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
C8A77F192DD1E6D100195617 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
|
||||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
|
||||||
CLANG_ENABLE_MODULES = YES;
|
|
||||||
CLANG_ENABLE_OBJC_ARC = YES;
|
|
||||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
|
||||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
|
||||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_COMMA = YES;
|
|
||||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
|
||||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
|
||||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
|
||||||
CLANG_WARN_EMPTY_BODY = YES;
|
|
||||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
|
||||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
|
||||||
CLANG_WARN_INT_CONVERSION = YES;
|
|
||||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
|
||||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
|
||||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
|
||||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
|
||||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
|
||||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
|
||||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
|
||||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
|
||||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
|
||||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
|
||||||
COPY_PHASE_STRIP = NO;
|
|
||||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
|
||||||
ENABLE_NS_ASSERTIONS = NO;
|
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
|
||||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
|
||||||
GCC_NO_COMMON_BLOCKS = YES;
|
|
||||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
|
||||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
|
||||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
|
||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
|
||||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
|
||||||
MTL_FAST_MATH = YES;
|
|
||||||
SDKROOT = macosx;
|
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
C8A77F1B2DD1E6D100195617 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
|
||||||
CODE_SIGN_ENTITLEMENTS = punchnet/punchnetDebug.entitlements;
|
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
|
||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Mac Developer";
|
|
||||||
CODE_SIGN_STYLE = Manual;
|
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_ASSET_PATHS = "\"punchnet/Preview Content\"";
|
|
||||||
DEVELOPMENT_TEAM = "";
|
|
||||||
"DEVELOPMENT_TEAM[sdk=macosx*]" = PF3QG837XS;
|
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
|
||||||
ENABLE_PREVIEWS = YES;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
INFOPLIST_KEY_LSUIElement = YES;
|
|
||||||
INFOPLIST_KEY_NSHumanReadableCopyright = "";
|
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
|
||||||
"$(inherited)",
|
|
||||||
"@executable_path/../Frameworks",
|
|
||||||
);
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetmac;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
|
||||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = MacPunchnetTest;
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
C8A77F1C2DD1E6D100195617 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
|
||||||
CODE_SIGN_ENTITLEMENTS = punchnet/punchnet.entitlements;
|
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
|
||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Mac Developer";
|
|
||||||
CODE_SIGN_STYLE = Manual;
|
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_ASSET_PATHS = "\"punchnet/Preview Content\"";
|
|
||||||
DEVELOPMENT_TEAM = "";
|
|
||||||
"DEVELOPMENT_TEAM[sdk=macosx*]" = PF3QG837XS;
|
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
|
||||||
ENABLE_PREVIEWS = YES;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
INFOPLIST_KEY_LSUIElement = YES;
|
|
||||||
INFOPLIST_KEY_NSHumanReadableCopyright = "";
|
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
|
||||||
"$(inherited)",
|
|
||||||
"@executable_path/../Frameworks",
|
|
||||||
);
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetmac;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
|
||||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = MacPunchnetTest;
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
C8A77F1E2DD1E6D100195617 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = 4CAML48Y7B;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetTests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/punchnet.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/punchnet";
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
C8A77F1F2DD1E6D100195617 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = 4CAML48Y7B;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetTests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/punchnet.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/punchnet";
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
C8A77F212DD1E6D100195617 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = 4CAML48Y7B;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetUITests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TEST_TARGET_NAME = punchnet;
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
C8A77F222DD1E6D100195617 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
|
||||||
CODE_SIGN_STYLE = Automatic;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = 4CAML48Y7B;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetUITests;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
TEST_TARGET_NAME = punchnet;
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
C8A77F352DD1E77B00195617 /* Debug */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
CODE_SIGN_ENTITLEMENTS = Tun/TunDebug.entitlements;
|
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
|
||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Mac Developer";
|
|
||||||
CODE_SIGN_STYLE = Manual;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = "";
|
|
||||||
"DEVELOPMENT_TEAM[sdk=macosx*]" = PF3QG837XS;
|
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
INFOPLIST_FILE = Tun/Info.plist;
|
|
||||||
INFOPLIST_KEY_CFBundleDisplayName = Tun;
|
|
||||||
INFOPLIST_KEY_NSHumanReadableCopyright = "";
|
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
|
||||||
"$(inherited)",
|
|
||||||
"@executable_path/../Frameworks",
|
|
||||||
"@executable_path/../../../../Frameworks",
|
|
||||||
);
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetmac.tun;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
|
||||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = MacPunchnetTunTest;
|
|
||||||
SKIP_INSTALL = YES;
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
};
|
|
||||||
name = Debug;
|
|
||||||
};
|
|
||||||
C8A77F362DD1E77B00195617 /* Release */ = {
|
|
||||||
isa = XCBuildConfiguration;
|
|
||||||
buildSettings = {
|
|
||||||
CODE_SIGN_ENTITLEMENTS = Tun/Tun.entitlements;
|
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
|
||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Mac Developer";
|
|
||||||
CODE_SIGN_STYLE = Manual;
|
|
||||||
CURRENT_PROJECT_VERSION = 1;
|
|
||||||
DEVELOPMENT_TEAM = "";
|
|
||||||
"DEVELOPMENT_TEAM[sdk=macosx*]" = PF3QG837XS;
|
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
|
||||||
INFOPLIST_FILE = Tun/Info.plist;
|
|
||||||
INFOPLIST_KEY_CFBundleDisplayName = Tun;
|
|
||||||
INFOPLIST_KEY_NSHumanReadableCopyright = "";
|
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
|
||||||
"$(inherited)",
|
|
||||||
"@executable_path/../Frameworks",
|
|
||||||
"@executable_path/../../../../Frameworks",
|
|
||||||
);
|
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.6;
|
|
||||||
MARKETING_VERSION = 1.0;
|
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.jihe.punchnetmac.tun;
|
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
|
||||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
|
||||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = MacPunchnetTunTest;
|
|
||||||
SKIP_INSTALL = YES;
|
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
|
||||||
SWIFT_VERSION = 5.0;
|
|
||||||
};
|
|
||||||
name = Release;
|
|
||||||
};
|
|
||||||
/* End XCBuildConfiguration section */
|
|
||||||
|
|
||||||
/* Begin XCConfigurationList section */
|
|
||||||
C8A77EEE2DD1E6D000195617 /* Build configuration list for PBXProject "punchnet" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
C8A77F182DD1E6D100195617 /* Debug */,
|
|
||||||
C8A77F192DD1E6D100195617 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
C8A77F1A2DD1E6D100195617 /* Build configuration list for PBXNativeTarget "punchnet" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
C8A77F1B2DD1E6D100195617 /* Debug */,
|
|
||||||
C8A77F1C2DD1E6D100195617 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
C8A77F1D2DD1E6D100195617 /* Build configuration list for PBXNativeTarget "punchnetTests" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
C8A77F1E2DD1E6D100195617 /* Debug */,
|
|
||||||
C8A77F1F2DD1E6D100195617 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
C8A77F202DD1E6D100195617 /* Build configuration list for PBXNativeTarget "punchnetUITests" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
C8A77F212DD1E6D100195617 /* Debug */,
|
|
||||||
C8A77F222DD1E6D100195617 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
C8A77F342DD1E77B00195617 /* Build configuration list for PBXNativeTarget "Tun" */ = {
|
|
||||||
isa = XCConfigurationList;
|
|
||||||
buildConfigurations = (
|
|
||||||
C8A77F352DD1E77B00195617 /* Debug */,
|
|
||||||
C8A77F362DD1E77B00195617 /* Release */,
|
|
||||||
);
|
|
||||||
defaultConfigurationIsVisible = 0;
|
|
||||||
defaultConfigurationName = Release;
|
|
||||||
};
|
|
||||||
/* End XCConfigurationList section */
|
|
||||||
|
|
||||||
/* Begin XCRemoteSwiftPackageReference section */
|
|
||||||
C8AA72B92E5C49E000E4C4E9 /* XCRemoteSwiftPackageReference "swift-protobuf" */ = {
|
|
||||||
isa = XCRemoteSwiftPackageReference;
|
|
||||||
repositoryURL = "https://github.com/apple/swift-protobuf.git";
|
|
||||||
requirement = {
|
|
||||||
kind = exactVersion;
|
|
||||||
version = 1.30.0;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */ = {
|
|
||||||
isa = XCRemoteSwiftPackageReference;
|
|
||||||
repositoryURL = "https://github.com/apple/swift-nio.git";
|
|
||||||
requirement = {
|
|
||||||
kind = exactVersion;
|
|
||||||
version = 2.85.0;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
/* End XCRemoteSwiftPackageReference section */
|
|
||||||
|
|
||||||
/* Begin XCSwiftPackageProductDependency section */
|
|
||||||
C89D410C2F874CC5001A17CF /* SwiftProtobuf */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72B92E5C49E000E4C4E9 /* XCRemoteSwiftPackageReference "swift-protobuf" */;
|
|
||||||
productName = SwiftProtobuf;
|
|
||||||
};
|
|
||||||
C8A77F782DD1E93900195617 /* NIO */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = NIO;
|
|
||||||
};
|
|
||||||
C8A77F7A2DD1E93900195617 /* NIOConcurrencyHelpers */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = NIOConcurrencyHelpers;
|
|
||||||
};
|
|
||||||
C8A77F7C2DD1E93900195617 /* NIOCore */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = NIOCore;
|
|
||||||
};
|
|
||||||
C8A77F7E2DD1E93900195617 /* NIOEmbedded */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = NIOEmbedded;
|
|
||||||
};
|
|
||||||
C8A77F802DD1E93900195617 /* NIOFoundationCompat */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = NIOFoundationCompat;
|
|
||||||
};
|
|
||||||
C8A77F872DD1EA0200195617 /* SwiftProtobuf */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = SwiftProtobuf;
|
|
||||||
};
|
|
||||||
C8A77F892DD1EA0200195617 /* SwiftProtobufPluginLibrary */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
productName = SwiftProtobufPluginLibrary;
|
|
||||||
};
|
|
||||||
C8AA72BA2E5C49E000E4C4E9 /* SwiftProtobuf */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72B92E5C49E000E4C4E9 /* XCRemoteSwiftPackageReference "swift-protobuf" */;
|
|
||||||
productName = SwiftProtobuf;
|
|
||||||
};
|
|
||||||
C8AA72BC2E5C49E000E4C4E9 /* SwiftProtobufPluginLibrary */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72B92E5C49E000E4C4E9 /* XCRemoteSwiftPackageReference "swift-protobuf" */;
|
|
||||||
productName = SwiftProtobufPluginLibrary;
|
|
||||||
};
|
|
||||||
C8AA72BF2E5C4A3100E4C4E9 /* NIO */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */;
|
|
||||||
productName = NIO;
|
|
||||||
};
|
|
||||||
C8AA72C12E5C4A3100E4C4E9 /* NIOConcurrencyHelpers */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */;
|
|
||||||
productName = NIOConcurrencyHelpers;
|
|
||||||
};
|
|
||||||
C8AA72C32E5C4A3100E4C4E9 /* NIOCore */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */;
|
|
||||||
productName = NIOCore;
|
|
||||||
};
|
|
||||||
C8AA72C52E5C4A3100E4C4E9 /* NIOEmbedded */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */;
|
|
||||||
productName = NIOEmbedded;
|
|
||||||
};
|
|
||||||
C8AA72C72E5C4A3100E4C4E9 /* NIOFoundationCompat */ = {
|
|
||||||
isa = XCSwiftPackageProductDependency;
|
|
||||||
package = C8AA72BE2E5C4A3100E4C4E9 /* XCRemoteSwiftPackageReference "swift-nio" */;
|
|
||||||
productName = NIOFoundationCompat;
|
|
||||||
};
|
|
||||||
/* End XCSwiftPackageProductDependency section */
|
|
||||||
};
|
|
||||||
rootObject = C8A77EEB2DD1E6D000195617 /* Project object */;
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Workspace
|
|
||||||
version = "1.0">
|
|
||||||
<FileRef
|
|
||||||
location = "self:">
|
|
||||||
</FileRef>
|
|
||||||
</Workspace>
|
|
||||||
@ -1,51 +0,0 @@
|
|||||||
{
|
|
||||||
"originHash" : "03bf3695750ad5eb9d4372b7d6478fa6d8494d0400ef6f58755e25a26a9f4d8d",
|
|
||||||
"pins" : [
|
|
||||||
{
|
|
||||||
"identity" : "swift-atomics",
|
|
||||||
"kind" : "remoteSourceControl",
|
|
||||||
"location" : "https://github.com/apple/swift-atomics.git",
|
|
||||||
"state" : {
|
|
||||||
"revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7",
|
|
||||||
"version" : "1.3.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"identity" : "swift-collections",
|
|
||||||
"kind" : "remoteSourceControl",
|
|
||||||
"location" : "https://github.com/apple/swift-collections.git",
|
|
||||||
"state" : {
|
|
||||||
"revision" : "8c0c0a8b49e080e54e5e328cc552821ff07cd341",
|
|
||||||
"version" : "1.2.1"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"identity" : "swift-nio",
|
|
||||||
"kind" : "remoteSourceControl",
|
|
||||||
"location" : "https://github.com/apple/swift-nio.git",
|
|
||||||
"state" : {
|
|
||||||
"revision" : "a5fea865badcb1c993c85b0f0e8d05a4bd2270fb",
|
|
||||||
"version" : "2.85.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"identity" : "swift-protobuf",
|
|
||||||
"kind" : "remoteSourceControl",
|
|
||||||
"location" : "https://github.com/apple/swift-protobuf.git",
|
|
||||||
"state" : {
|
|
||||||
"revision" : "102a647b573f60f73afdce5613a51d71349fe507",
|
|
||||||
"version" : "1.30.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"identity" : "swift-system",
|
|
||||||
"kind" : "remoteSourceControl",
|
|
||||||
"location" : "https://github.com/apple/swift-system.git",
|
|
||||||
"state" : {
|
|
||||||
"revision" : "b63d24d465e237966c3f59f47dcac6c70fb0bca3",
|
|
||||||
"version" : "1.6.1"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"version" : 3
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user