Files

190 lines
8.6 KiB
Swift
Raw Permalink Normal View History

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
let runtimeJSON: String
if let endpointData = providerConfiguration["internalEndpointJSON"] as? Data {
let endpoint = try JSONDecoder().decode(ProxyTransportEndpoint.self, from: endpointData)
guard endpoint.address == providedRemoteAddress,
ProxyTransportPolicy.authorizedInternalEndpoint(
endpoint: endpoint,
nodeSlug: providerConfiguration["nodeSlug"] as? String ?? "",
configContract: providerConfiguration["configContract"] as? Int,
connectionScope: providerConfiguration["connectionScope"] as? String,
routeMode: providerConfiguration["routeMode"] as? String ?? "",
configJSON: rawJSON
) != nil else {
throw UCVLError.invalidConfiguration("内部代理入口与授权配置不一致。")
}
resolvedRemoteAddress = endpoint.address
runtimeJSON = try ProxyTransportPolicy.internalConfigJSON(rawJSON: rawJSON, endpoint: endpoint)
} else if let providedRemoteAddress, NetworkAddress.isPublicIPv4(providedRemoteAddress) {
resolvedRemoteAddress = providedRemoteAddress
runtimeJSON = rawJSON
} else {
resolvedRemoteAddress = try Self.resolveIPv4Address(remoteHost)
runtimeJSON = rawJSON
}
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: runtimeJSON,
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 = SOCK_STREAM
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 地址。")
}
}