Publish reviewed history-free open-source snapshot (2026-10-12)

This commit is contained in:
Zonghengjia Open Source
2026-10-11 23:23:20 +00:00
commit 901f27baf5
301 changed files with 32378 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
<?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/></plist>
@@ -0,0 +1,10 @@
<?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>
</dict>
</plist>
+171
View File
@@ -0,0 +1,171 @@
import Darwin
import Foundation
import NetworkExtension
final class PacketTunnelProvider: NEPacketTunnelProvider {
private let coreQueue = DispatchQueue(label: "cn.toplc.zonghengjia.xray-core", qos: .userInitiated)
override func startTunnel(
options: [String: NSObject]? = nil,
completionHandler: @escaping (Error?) -> Void
) {
guard let tunnelProtocol = protocolConfiguration as? NETunnelProviderProtocol,
let providerConfiguration = tunnelProtocol.providerConfiguration,
let rawJSON = providerConfiguration["configJSON"] as? String
else {
completionHandler(UCVLError.invalidConfiguration("没有收到线路配置,请返回应用重新连接。"))
return
}
guard let remoteHost = TunnelConfigurationBuilder.remoteAddress(from: rawJSON) else {
completionHandler(UCVLError.invalidConfiguration("线路配置缺少节点地址。"))
return
}
let providedRemoteAddress = providerConfiguration["resolvedRemoteAddress"] as? String
coreQueue.async { [weak self] in
guard let self else { return }
do {
let resolvedRemoteAddress: String
if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
resolvedRemoteAddress = providedRemoteAddress
} else {
resolvedRemoteAddress = try Self.resolveIPv4Address(remoteHost)
}
let settings = self.makeNetworkSettings(remoteAddress: resolvedRemoteAddress)
self.setTunnelNetworkSettings(settings) { [weak self] error in
guard let self else { return }
if let error {
completionHandler(error)
return
}
self.coreQueue.async {
do {
guard let tunnelFD = Self.findTunnelFileDescriptor() else {
throw UCVLError.invalidConfiguration("无法取得 Apple utun 虚拟网卡。")
}
guard let geoIP = Bundle.main.url(forResource: "geoip", withExtension: "dat"),
Bundle.main.url(forResource: "geosite", withExtension: "dat") != nil
else {
throw UCVLError.invalidConfiguration("路由规则资源缺失。")
}
let config = try TunnelConfigurationBuilder.makeConfiguration(
rawJSON: rawJSON,
tunnelFileDescriptor: tunnelFD,
assetDirectory: geoIP.deletingLastPathComponent().path,
resolvedRemoteAddress: resolvedRemoteAddress
)
XrayBridge.stop()
try XrayBridge.start(configJSON: config)
completionHandler(nil)
} catch {
XrayBridge.stop()
completionHandler(error)
}
}
}
} catch {
completionHandler(error)
}
}
}
override func stopTunnel(
with reason: NEProviderStopReason,
completionHandler: @escaping () -> Void
) {
coreQueue.async {
XrayBridge.stop()
completionHandler()
}
}
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
let response = ["running": XrayBridge.isRunning()]
completionHandler?(try? JSONSerialization.data(withJSONObject: response))
}
override func sleep(completionHandler: @escaping () -> Void) {
completionHandler()
}
override func wake() {}
private func makeNetworkSettings(remoteAddress: String) -> NEPacketTunnelNetworkSettings {
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress)
let ipv4 = NEIPv4Settings(addresses: ["198.18.0.1"], subnetMasks: ["255.255.0.0"])
ipv4.includedRoutes = [NEIPv4Route.default()]
if Self.isIPv4Address(remoteAddress) {
ipv4.excludedRoutes = [NEIPv4Route(destinationAddress: remoteAddress, subnetMask: "255.255.255.255")]
}
settings.ipv4Settings = ipv4
let ipv6 = NEIPv6Settings(addresses: ["fd00:7563:766c::1"], networkPrefixLengths: [64])
ipv6.includedRoutes = [NEIPv6Route.default()]
settings.ipv6Settings = ipv6
let dns = NEDNSSettings(servers: ["1.1.1.1", "8.8.8.8"])
dns.matchDomains = [""]
settings.dnsSettings = dns
settings.mtu = 1500
return settings
}
private static func findTunnelFileDescriptor() -> Int32? {
for fileDescriptor in Int32(0)...Int32(1024) {
var interfaceName = [CChar](repeating: 0, count: Int(IFNAMSIZ))
var length = socklen_t(interfaceName.count)
let result = interfaceName.withUnsafeMutableBytes { pointer in
getsockopt(
fileDescriptor,
SYSPROTO_CONTROL,
2,
pointer.baseAddress,
&length
)
}
if result == 0, String(cString: interfaceName).hasPrefix("utun") {
return fileDescriptor
}
}
return nil
}
private static func isIPv4Address(_ value: String) -> Bool {
var address = in_addr()
return value.withCString { inet_pton(AF_INET, $0, &address) } == 1
}
private static func resolveIPv4Address(_ host: String) throws -> String {
if NetworkAddress.isPublicIPv4(host) { return host }
var hints = addrinfo()
hints.ai_flags = AI_ADDRCONFIG
hints.ai_family = AF_INET
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
hints.ai_protocol = IPPROTO_TCP
var results: UnsafeMutablePointer<addrinfo>?
let status = host.withCString { getaddrinfo($0, nil, &hints, &results) }
guard status == 0, let first = results else {
let reason = status == 0 ? "没有 IPv4 地址" : String(cString: gai_strerror(status))
throw UCVLError.invalidConfiguration("无法解析节点域名 \(host):\(reason)。")
}
defer { freeaddrinfo(first) }
var cursor: UnsafeMutablePointer<addrinfo>? = first
while let current = cursor {
cursor = current.pointee.ai_next
guard current.pointee.ai_family == AF_INET,
let socketAddress = current.pointee.ai_addr
else { continue }
var address = socketAddress.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
$0.pointee.sin_addr
}
var text = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
guard inet_ntop(AF_INET, &address, &text, socklen_t(INET_ADDRSTRLEN)) != nil else { continue }
let value = String(cString: text)
if NetworkAddress.isPublicIPv4(value) { return value }
}
throw UCVLError.invalidConfiguration("节点域名 \(host) 没有可用的 IPv4 地址。")
}
}
+46
View File
@@ -0,0 +1,46 @@
import Darwin
import Foundation
import LibXray
enum XrayBridge {
static func start(configJSON: String) throws {
_ = try invoke(method: "runXrayFromJson", payload: ["configJSON": configJSON])
}
static func stop() {
_ = try? invoke(method: "stopXray", payload: nil)
}
static func isRunning() -> Bool {
guard let data = try? invoke(method: "getXrayState", payload: nil) else { return false }
return data["running"] as? Bool ?? false
}
@discardableResult
private static func invoke(method: String, payload: [String: Any]?) throws -> [String: Any] {
var request: [String: Any] = ["apiVersion": 1, "method": method]
if let payload { request["payload"] = payload }
let requestData = try JSONSerialization.data(withJSONObject: request, options: [])
let requestText = String(decoding: requestData, as: UTF8.self)
guard let requestPointer = requestText.withCString({ strdup($0) }) else {
throw UCVLError.invalidConfiguration("无法调用 Xray 核心。")
}
defer { free(requestPointer) }
guard let responsePointer = CGoInvoke(requestPointer) else {
throw UCVLError.invalidConfiguration("Xray 核心没有返回结果。")
}
defer { CGoFree(responsePointer) }
let responseText = String(cString: responsePointer)
guard let responseData = responseText.data(using: .utf8),
let response = try JSONSerialization.jsonObject(with: responseData) as? [String: Any]
else {
throw UCVLError.invalidConfiguration("Xray 核心返回格式错误。")
}
guard response["success"] as? Bool == true else {
let error = response["error"] as? String ?? "Xray 核心启动失败。"
throw UCVLError.invalidConfiguration(error)
}
return response["data"] as? [String: Any] ?? [:]
}
}