This commit is contained in:
zeus
2025-01-22 16:22:33 +08:00
parent 09b9cec8ec
commit 738c373a77
2534 changed files with 0 additions and 486292 deletions
@@ -1,188 +0,0 @@
import Foundation
import Libbox
public class CommandClient: ObservableObject {
public enum ConnectionType {
case status
case groups
case log
case clashMode
}
private let connectionType: ConnectionType
private let logMaxLines: Int
private var commandClient: LibboxCommandClient?
private var connectTask: Task<Void, Error>?
@Published public var isConnected: Bool
@Published public var status: LibboxStatusMessage?
@Published public var groups: [LibboxOutboundGroup]?
@Published public var logList: [String]
@Published public var clashModeList: [String]
@Published public var clashMode: String
public init(_ connectionType: ConnectionType, logMaxLines: Int = 300) {
self.connectionType = connectionType
self.logMaxLines = logMaxLines
logList = []
clashModeList = []
clashMode = ""
isConnected = false
}
public func connect() {
if isConnected {
return
}
if let connectTask {
connectTask.cancel()
}
connectTask = Task {
await connect0()
}
}
public func disconnect() {
if let connectTask {
connectTask.cancel()
self.connectTask = nil
}
if let commandClient {
try? commandClient.disconnect()
self.commandClient = nil
}
}
private nonisolated func connect0() async {
print("connect0...")
let clientOptions = LibboxCommandClientOptions()
switch connectionType {
case .status:
print("connectionType = .status")
clientOptions.command = LibboxCommandStatus
case .groups:
print("connectionType = .groups")
clientOptions.command = LibboxCommandGroup
case .log:
print("connectionType = .log")
clientOptions.command = LibboxCommandLog
case .clashMode:
print("connectionType = .clashMode")
clientOptions.command = LibboxCommandClashMode
}
clientOptions.statusInterval = Int64(2 * NSEC_PER_SEC)
let client = LibboxNewCommandClient(clientHandler(self), clientOptions)!
do {
//
//
//
for i in 0 ..< 2 {
try await Task.sleep(nanoseconds: UInt64(Double(100 + (i * 50)) * Double(NSEC_PER_MSEC)))
try Task.checkCancellation()
do {
try client.connect()
await MainActor.run {
commandClient = client
}
return
} catch {}
try Task.checkCancellation()
}
} catch {
try? client.disconnect()
}
/*
do {
try client.connect()
await MainActor.run {
commandClient = client
}
return
} catch {
print("URLTesting... \(error)")
try? client.disconnect()
}
*/
}
private class clientHandler: NSObject, LibboxCommandClientHandlerProtocol {
private let commandClient: CommandClient
init(_ commandClient: CommandClient) {
self.commandClient = commandClient
}
func connected() {
DispatchQueue.main.async { [self] in
if commandClient.connectionType == .log {
commandClient.logList = []
}
commandClient.isConnected = true
}
}
func disconnected(_: String?) {
DispatchQueue.main.async { [self] in
commandClient.isConnected = false
}
}
func clearLog() {
DispatchQueue.main.async { [self] in
commandClient.logList.removeAll()
}
}
func writeLog(_ message: String?) {
// print("writeStatus \(String(describing: message))")
guard let message else {
return
}
DispatchQueue.main.async { [self] in
if commandClient.logList.count > commandClient.logMaxLines {
commandClient.logList.removeFirst()
}
commandClient.logList.append(message)
}
}
func writeStatus(_ message: LibboxStatusMessage?) {
// print("writeStatus \(String(describing: message?.description))")
DispatchQueue.main.async { [self] in
commandClient.status = message
}
}
func writeGroups(_ groups: LibboxOutboundGroupIteratorProtocol?) {
// print("writeGroups \(String(describing: groups?.next()))")
guard let groups else {
return
}
var newGroups: [LibboxOutboundGroup] = []
while groups.hasNext() {
newGroups.append(groups.next()!)
}
DispatchQueue.main.async { [self] in
commandClient.groups = newGroups
}
}
func initializeClashMode(_ modeList: LibboxStringIteratorProtocol?, currentMode: String?) {
DispatchQueue.main.async { [self] in
commandClient.clashModeList = modeList!.toArray()
commandClient.clashMode = currentMode!
}
}
func updateClashMode(_ newMode: String?) {
DispatchQueue.main.async { [self] in
commandClient.clashMode = newMode!
}
}
}
}
@@ -1,12 +0,0 @@
import Foundation
import Libbox
extension LibboxStringIteratorProtocol {
func toArray() -> [String] {
var array: [String] = []
while hasNext() {
array.append(next())
}
return array
}
}
@@ -1,36 +0,0 @@
import Foundation
import Libbox
import NetworkExtension
func runBlocking<T>(_ block: @escaping () async -> T) -> T {
let semaphore = DispatchSemaphore(value: 0)
let box = resultBox<T>()
Task.detached {
let value = await block()
box.result0 = value
semaphore.signal()
}
semaphore.wait()
return box.result0
}
func runBlocking<T>(_ tBlock: @escaping () async throws -> T) throws -> T {
let semaphore = DispatchSemaphore(value: 0)
let box = resultBox<T>()
Task.detached {
do {
let value = try await tBlock()
box.result = .success(value)
} catch {
box.result = .failure(error)
}
semaphore.signal()
}
semaphore.wait()
return try box.result.get()
}
private class resultBox<T> {
var result: Result<T, Error>!
var result0: T!
}
@@ -1,51 +0,0 @@
import Foundation
import SwiftUI
public class ExtensionEnvironments: ObservableObject {
@Published public var logClient = CommandClient(.log)
@Published public var extensionProfileLoading = true
@Published public var extensionProfile: ExtensionProfile?
@Published public var emptyProfiles = false
public let profileUpdate = ObjectWillChangePublisher()
public let selectedProfileUpdate = ObjectWillChangePublisher()
public let openSettings = ObjectWillChangePublisher()
public let openProfileGetSuccess = ObjectWillChangePublisher() //
public let opentixingSubnodes = ObjectWillChangePublisher() //
public let updateTixingdingyueEnabled = ObjectWillChangePublisher() //boolean
public init() {}
deinit {
logClient.disconnect()
}
public func postReload() {
Task {
await reload()
}
}
@MainActor
public func reload() async {
if let newProfile = try? await ExtensionProfile.load() {
if extensionProfile == nil || extensionProfile?.status == .invalid {
newProfile.register()
extensionProfile = newProfile
extensionProfileLoading = false
}
} else {
extensionProfile = nil
extensionProfileLoading = false
}
}
public func connectLog() {
guard let profile = extensionProfile else {
return
}
if profile.status.isConnected, !logClient.isConnected {
logClient.connect()
}
}
}
@@ -1,338 +0,0 @@
import Foundation
import Libbox
import NetworkExtension
#if canImport(CoreWLAN)
import CoreWLAN
#endif
public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtocol, LibboxCommandServerHandlerProtocol {
private let tunnel: ExtensionProvider
private var networkSettings: NEPacketTunnelNetworkSettings?
init(_ tunnel: ExtensionProvider) {
self.tunnel = tunnel
}
public func openTun(_ options: LibboxTunOptionsProtocol?, ret0_: UnsafeMutablePointer<Int32>?) throws {
try runBlocking { [self] in
try await openTun0(options, ret0_)
}
}
private func openTun0(_ options: LibboxTunOptionsProtocol?, _ ret0_: UnsafeMutablePointer<Int32>?) async throws {
guard let options else {
throw NSError(domain: "nil options", code: 0)
}
guard let ret0_ else {
throw NSError(domain: "nil return pointer", code: 0)
}
let autoRouteUseSubRangesByDefault = await SharedPreferences.autoRouteUseSubRangesByDefault.get()
let excludeAPNs = await SharedPreferences.excludeAPNsRoute.get()
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1")
if options.getAutoRoute() {
settings.mtu = NSNumber(value: options.getMTU())
var error: NSError?
let dnsServer = options.getDNSServerAddress(&error)
if let error {
throw error
}
settings.dnsSettings = NEDNSSettings(servers: [dnsServer])
var ipv4Address: [String] = []
var ipv4Mask: [String] = []
let ipv4AddressIterator = options.getInet4Address()!
while ipv4AddressIterator.hasNext() {
let ipv4Prefix = ipv4AddressIterator.next()!
ipv4Address.append(ipv4Prefix.address())
ipv4Mask.append(ipv4Prefix.mask())
}
let ipv4Settings = NEIPv4Settings(addresses: ipv4Address, subnetMasks: ipv4Mask)
var ipv4Routes: [NEIPv4Route] = []
var ipv4ExcludeRoutes: [NEIPv4Route] = []
let inet4RouteAddressIterator = options.getInet4RouteAddress()!
if inet4RouteAddressIterator.hasNext() {
while inet4RouteAddressIterator.hasNext() {
let ipv4RoutePrefix = inet4RouteAddressIterator.next()!
ipv4Routes.append(NEIPv4Route(destinationAddress: ipv4RoutePrefix.address(), subnetMask: ipv4RoutePrefix.mask()))
}
} else if autoRouteUseSubRangesByDefault {
ipv4Routes.append(NEIPv4Route(destinationAddress: "1.0.0.0", subnetMask: "255.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "2.0.0.0", subnetMask: "254.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "4.0.0.0", subnetMask: "252.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "8.0.0.0", subnetMask: "248.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "16.0.0.0", subnetMask: "240.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "32.0.0.0", subnetMask: "224.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "64.0.0.0", subnetMask: "192.0.0.0"))
ipv4Routes.append(NEIPv4Route(destinationAddress: "128.0.0.0", subnetMask: "128.0.0.0"))
} else {
ipv4Routes.append(NEIPv4Route.default())
}
let inet4RouteExcludeAddressIterator = options.getInet4RouteExcludeAddress()!
while inet4RouteExcludeAddressIterator.hasNext() {
let ipv4RoutePrefix = inet4RouteExcludeAddressIterator.next()!
ipv4ExcludeRoutes.append(NEIPv4Route(destinationAddress: ipv4RoutePrefix.address(), subnetMask: ipv4RoutePrefix.mask()))
}
if await SharedPreferences.excludeDefaultRoute.get(), !ipv4Routes.isEmpty {
if !ipv4ExcludeRoutes.contains(where: { it in
it.destinationAddress == "0.0.0.0" && it.destinationSubnetMask == "255.255.255.254"
}) {
ipv4ExcludeRoutes.append(NEIPv4Route(destinationAddress: "0.0.0.0", subnetMask: "255.255.255.254"))
}
}
if excludeAPNs, !ipv4Routes.isEmpty {
if !ipv4ExcludeRoutes.contains(where: { it in
it.destinationAddress == "17.0.0.0" && it.destinationSubnetMask == "255.0.0.0"
}) {
ipv4ExcludeRoutes.append(NEIPv4Route(destinationAddress: "17.0.0.0", subnetMask: "255.0.0.0"))
}
}
ipv4Settings.includedRoutes = ipv4Routes
ipv4Settings.excludedRoutes = ipv4ExcludeRoutes
settings.ipv4Settings = ipv4Settings
var ipv6Address: [String] = []
var ipv6Prefixes: [NSNumber] = []
let ipv6AddressIterator = options.getInet6Address()!
while ipv6AddressIterator.hasNext() {
let ipv6Prefix = ipv6AddressIterator.next()!
ipv6Address.append(ipv6Prefix.address())
ipv6Prefixes.append(NSNumber(value: ipv6Prefix.prefix()))
}
let ipv6Settings = NEIPv6Settings(addresses: ipv6Address, networkPrefixLengths: ipv6Prefixes)
var ipv6Routes: [NEIPv6Route] = []
var ipv6ExcludeRoutes: [NEIPv6Route] = []
let inet6RouteAddressIterator = options.getInet6RouteAddress()!
if inet6RouteAddressIterator.hasNext() {
while inet6RouteAddressIterator.hasNext() {
let ipv6RoutePrefix = inet6RouteAddressIterator.next()!
ipv6Routes.append(NEIPv6Route(destinationAddress: ipv6RoutePrefix.address(), networkPrefixLength: NSNumber(value: ipv6RoutePrefix.prefix())))
}
} else if autoRouteUseSubRangesByDefault {
ipv6Routes.append(NEIPv6Route(destinationAddress: "100::", networkPrefixLength: 8))
ipv6Routes.append(NEIPv6Route(destinationAddress: "200::", networkPrefixLength: 7))
ipv6Routes.append(NEIPv6Route(destinationAddress: "400::", networkPrefixLength: 6))
ipv6Routes.append(NEIPv6Route(destinationAddress: "800::", networkPrefixLength: 5))
ipv6Routes.append(NEIPv6Route(destinationAddress: "1000::", networkPrefixLength: 4))
ipv6Routes.append(NEIPv6Route(destinationAddress: "2000::", networkPrefixLength: 3))
ipv6Routes.append(NEIPv6Route(destinationAddress: "4000::", networkPrefixLength: 2))
ipv6Routes.append(NEIPv6Route(destinationAddress: "8000::", networkPrefixLength: 1))
} else {
ipv6Routes.append(NEIPv6Route.default())
}
let inet6RouteExcludeAddressIterator = options.getInet6RouteExcludeAddress()!
while inet6RouteExcludeAddressIterator.hasNext() {
let ipv6RoutePrefix = inet6RouteExcludeAddressIterator.next()!
ipv6ExcludeRoutes.append(NEIPv6Route(destinationAddress: ipv6RoutePrefix.address(), networkPrefixLength: NSNumber(value: ipv6RoutePrefix.prefix())))
}
ipv6Settings.includedRoutes = ipv6Routes
ipv6Settings.excludedRoutes = ipv6ExcludeRoutes
settings.ipv6Settings = ipv6Settings
}
if options.isHTTPProxyEnabled() {
let proxySettings = NEProxySettings()
let proxyServer = NEProxyServer(address: options.getHTTPProxyServer(), port: Int(options.getHTTPProxyServerPort()))
proxySettings.httpServer = proxyServer
proxySettings.httpsServer = proxyServer
if await SharedPreferences.systemProxyEnabled.get() {
proxySettings.httpEnabled = true
proxySettings.httpsEnabled = true
}
var bypassDomains: [String] = []
let bypassDomainIterator = options.getHTTPProxyBypassDomain()!
while bypassDomainIterator.hasNext() {
bypassDomains.append(bypassDomainIterator.next())
}
if excludeAPNs {
if !bypassDomains.contains(where: { it in
it == "push.apple.com"
}) {
bypassDomains.append("push.apple.com")
}
}
if !bypassDomains.isEmpty {
proxySettings.exceptionList = bypassDomains
}
var matchDomains: [String] = []
let matchDomainIterator = options.getHTTPProxyMatchDomain()!
while matchDomainIterator.hasNext() {
matchDomains.append(matchDomainIterator.next())
}
if !matchDomains.isEmpty {
proxySettings.matchDomains = matchDomains
}
settings.proxySettings = proxySettings
}
networkSettings = settings
try await tunnel.setTunnelNetworkSettings(settings)
if let tunFd = tunnel.packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32 {
ret0_.pointee = tunFd
return
}
let tunFdFromLoop = LibboxGetTunnelFileDescriptor()
if tunFdFromLoop != -1 {
ret0_.pointee = tunFdFromLoop
} else {
throw NSError(domain: "missing file descriptor", code: 0)
}
}
public func usePlatformAutoDetectControl() -> Bool {
true
}
public func autoDetectControl(_: Int32) throws {}
public func findConnectionOwner(_: Int32, sourceAddress _: String?, sourcePort _: Int32, destinationAddress _: String?, destinationPort _: Int32, ret0_ _: UnsafeMutablePointer<Int32>?) throws {
throw NSError(domain: "not implemented", code: 0)
}
public func packageName(byUid _: Int32, error _: NSErrorPointer) -> String {
""
}
public func uid(byPackageName _: String?, ret0_ _: UnsafeMutablePointer<Int32>?) throws {
throw NSError(domain: "not implemented", code: 0)
}
public func useProcFS() -> Bool {
false
}
public func writeLog(_ message: String?) {
guard let message else {
return
}
tunnel.writeMessage(message)
}
public func usePlatformDefaultInterfaceMonitor() -> Bool {
false
}
public func startDefaultInterfaceMonitor(_: LibboxInterfaceUpdateListenerProtocol?) throws {}
public func closeDefaultInterfaceMonitor(_: LibboxInterfaceUpdateListenerProtocol?) throws {}
public func useGetter() -> Bool {
false
}
public func getInterfaces() throws -> LibboxNetworkInterfaceIteratorProtocol {
throw NSError(domain: "not implemented", code: 0)
}
public func underNetworkExtension() -> Bool {
true
}
public func includeAllNetworks() -> Bool {
#if !os(tvOS)
return SharedPreferences.includeAllNetworks.getBlocking()
#else
return false
#endif
}
public func clearDNSCache() {
guard let networkSettings else {
return
}
tunnel.reasserting = true
tunnel.setTunnelNetworkSettings(nil) { _ in
}
tunnel.setTunnelNetworkSettings(networkSettings) { _ in
}
tunnel.reasserting = false
}
public func readWIFIState() -> LibboxWIFIState? {
#if os(iOS)
let network = runBlocking {
await NEHotspotNetwork.fetchCurrent()
}
guard let network else {
return nil
}
return LibboxWIFIState(network.ssid, wifiBSSID: network.bssid)!
#elseif os(macOS)
guard let interface = CWWiFiClient.shared().interface() else {
return nil
}
guard let ssid = interface.ssid() else {
return nil
}
guard let bssid = interface.bssid() else {
return nil
}
return LibboxWIFIState(ssid, wifiBSSID: bssid)!
#else
return nil
#endif
}
public func serviceReload() throws {
runBlocking { [self] in
await tunnel.reloadService()
}
}
public func postServiceClose() {
reset()
tunnel.postServiceClose()
}
public func getSystemProxyStatus() -> LibboxSystemProxyStatus? {
let status = LibboxSystemProxyStatus()
guard let networkSettings else {
return status
}
guard let proxySettings = networkSettings.proxySettings else {
return status
}
if proxySettings.httpServer == nil {
return status
}
status.available = true
status.enabled = proxySettings.httpEnabled
return status
}
public func setSystemProxyEnabled(_ isEnabled: Bool) throws {
guard let networkSettings else {
return
}
guard let proxySettings = networkSettings.proxySettings else {
return
}
if proxySettings.httpServer == nil {
return
}
if proxySettings.httpEnabled == isEnabled {
return
}
proxySettings.httpEnabled = isEnabled
proxySettings.httpsEnabled = isEnabled
networkSettings.proxySettings = proxySettings
try runBlocking {
try await self.tunnel.setTunnelNetworkSettings(networkSettings)
}
}
func reset() {
networkSettings = nil
}
}
@@ -1,124 +0,0 @@
import Foundation
import Libbox
import NetworkExtension
public class ExtensionProfile: ObservableObject {
private let manager: NEVPNManager
private var connection: NEVPNConnection
private var observer: Any?
@Published public var status: NEVPNStatus
public init(_ manager: NEVPNManager) {
self.manager = manager
connection = manager.connection
status = manager.connection.status
}
public func register() {
observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NEVPNStatusDidChange,
object: manager.connection,
queue: .main
) { [weak self] notification in
guard let self else {
return
}
self.connection = notification.object as! NEVPNConnection
self.status = self.connection.status
}
}
private func unregister() {
if let observer {
NotificationCenter.default.removeObserver(observer)
}
}
private func setOnDemandRules() {
let interfaceRule = NEOnDemandRuleConnect()
interfaceRule.interfaceTypeMatch = .any
let probeRule = NEOnDemandRuleConnect()
probeRule.probeURL = URL(string: "http://captive.apple.com")
manager.onDemandRules = [interfaceRule, probeRule]
}
public func updateAlwaysOn(_ newState: Bool) async throws {
manager.isOnDemandEnabled = newState
setOnDemandRules()
try await manager.saveToPreferences()
}
public func start() async throws {
await fetchProfile()
manager.isEnabled = true
if await SharedPreferences.alwaysOn.get() {
manager.isOnDemandEnabled = true
setOnDemandRules()
}
#if !os(tvOS)
if let protocolConfiguration = manager.protocolConfiguration {
let includeAllNetworks = await SharedPreferences.includeAllNetworks.get()
protocolConfiguration.includeAllNetworks = includeAllNetworks
if #available(iOS 16.4, macOS 13.3, *) {
protocolConfiguration.excludeCellularServices = !includeAllNetworks
}
}
#endif
try await manager.saveToPreferences()
#if os(macOS)
if Variant.useSystemExtension {
try manager.connection.startVPNTunnel(options: [
"username": NSString(string: NSUserName()),
])
return
}
#endif
try manager.connection.startVPNTunnel()
}
public func fetchProfile() async {
do {
if let profile = try await ProfileManager.get(Int64(SharedPreferences.selectedProfileID.get())) {
if profile.type == .icloud {
_ = try profile.read()
}
}
} catch {}
}
public func stop() async throws {
if manager.isOnDemandEnabled {
manager.isOnDemandEnabled = false
try await manager.saveToPreferences()
}
do {
try LibboxNewStandaloneCommandClient()!.serviceClose()
} catch {}
manager.connection.stopVPNTunnel()
}
public static func load() async throws -> ExtensionProfile? {
let managers = try await NETunnelProviderManager.loadAllFromPreferences()
if managers.isEmpty {
return nil
}
let profile = ExtensionProfile(managers[0])
return profile
}
public static func install() async throws {
let manager = NETunnelProviderManager()
manager.localizedDescription = Variant.applicationName
let tunnelProtocol = NETunnelProviderProtocol()
if Variant.useSystemExtension {
tunnelProtocol.providerBundleIdentifier = "\(FilePath.packageName).system"
} else {
tunnelProtocol.providerBundleIdentifier = "\(FilePath.packageName).extension"
}
tunnelProtocol.serverAddress = Variant.applicationName// "sing-box"
manager.protocolConfiguration = tunnelProtocol
manager.isEnabled = true
try await manager.saveToPreferences()
}
}
@@ -1,173 +0,0 @@
import Foundation
import Libbox
import NetworkExtension
open class ExtensionProvider: NEPacketTunnelProvider {
public var username: String? = nil
private var commandServer: LibboxCommandServer!
private var boxService: LibboxBoxService!
private var systemProxyAvailable = false
private var systemProxyEnabled = false
private var platformInterface: ExtensionPlatformInterface!
override open func startTunnel(options _: [String: NSObject]?) async throws {
LibboxClearServiceError()
if let username {
var error: NSError?
LibboxSetupWithUsername(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, username, &error)
if let error {
writeFatalError("(packet-tunnel) error: setup service: \(error.localizedDescription)")
return
}
} else {
var isTVOS = false
#if os(tvOS)
isTVOS = true
#endif
LibboxSetup(FilePath.sharedDirectory.relativePath, FilePath.workingDirectory.relativePath, FilePath.cacheDirectory.relativePath, isTVOS)
}
var error: NSError?
LibboxRedirectStderr(FilePath.cacheDirectory.appendingPathComponent("stderr.log").relativePath, &error)
if let error {
writeFatalError("(packet-tunnel) redirect stderr error: \(error.localizedDescription)")
}
await LibboxSetMemoryLimit(!SharedPreferences.ignoreMemoryLimit.get())
if platformInterface == nil {
platformInterface = ExtensionPlatformInterface(self)
}
commandServer = await LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines.get()))
do {
try commandServer.start()
} catch {
writeFatalError("(packet-tunnel): log server start error: \(error.localizedDescription)")
return
}
writeMessage("(packet-tunnel): Here I stand")
await startService()
}
func writeMessage(_ message: String) {
if let commandServer {
commandServer.writeMessage(message)
} else {
NSLog(message)
}
}
public func writeFatalError(_ message: String) {
#if DEBUG
NSLog(message)
#endif
writeMessage(message)
var error: NSError?
LibboxWriteServiceError(message, &error)
cancelTunnelWithError(NSError(domain: message, code: 0))
}
private func startService() async {
let profile: Profile?
do {
profile = try await ProfileManager.get(Int64(SharedPreferences.selectedProfileID.get()))
} catch {
writeFatalError("(packet-tunnel) error: read selected profile: \(error.localizedDescription)")
return
}
guard let profile else {
writeFatalError("(packet-tunnel) error: missing selected profile")
return
}
let configContent: String
do {
configContent = try profile.read()
} catch {
writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)")
return
}
var error: NSError?
let service = LibboxNewService(configContent, platformInterface, &error)
if let error {
writeFatalError("(packet-tunnel) error: create service: \(error.localizedDescription)")
return
}
guard let service else {
return
}
commandServer.setService(service)
do {
try service.start()
} catch {
commandServer.setService(nil)
writeFatalError("(packet-tunnel) error: start service: \(error.localizedDescription)")
return
}
boxService = service
#if os(macOS)
await SharedPreferences.startedByUser.set(true)
#endif
}
private func stopService() {
if let service = boxService {
do {
try service.close()
} catch {
writeMessage("(packet-tunnel) error: stop service: \(error.localizedDescription)")
}
boxService = nil
commandServer.setService(nil)
}
if let platformInterface {
platformInterface.reset()
}
}
func reloadService() async {
writeMessage("(packet-tunnel) reloading service")
reasserting = true
defer {
reasserting = false
}
stopService()
commandServer.resetLog()
await startService()
}
func postServiceClose() {
boxService = nil
}
override open func stopTunnel(with reason: NEProviderStopReason) async {
writeMessage("(packet-tunnel) stopping, reason: \(reason)")
stopService()
if let server = commandServer {
try? await Task.sleep(nanoseconds: 100 * NSEC_PER_MSEC)
try? server.close()
commandServer = nil
}
#if os(macOS)
if reason == .userInitiated {
await SharedPreferences.startedByUser.set(reason == .userInitiated)
}
#endif
}
override open func handleAppMessage(_ messageData: Data) async -> Data? {
messageData
}
override open func sleep() async {
if let boxService {
boxService.pause()
}
}
override open func wake() {
if let boxService {
boxService.wake()
}
}
}
@@ -1,40 +0,0 @@
import Foundation
import Libbox
public class HTTPClient {
private static var userAgent: String {
var userAgent = Variant.applicationName
userAgent += "/"
userAgent += Bundle.main.version
userAgent += " (Build "
userAgent += Bundle.main.versionNumber
userAgent += "; sing-box "
userAgent += LibboxVersion()
userAgent += ")"
return userAgent
}
private let client: any LibboxHTTPClientProtocol
public init() {
client = LibboxNewHTTPClient()!
client.modernTLS()
}
public func getString(_ url: String?) throws -> String {
let request = client.newRequest()!
request.setUserAgent(HTTPClient.userAgent)
try request.setURL(url)
let response = try request.execute()
var error: NSError?
let contentString = response.getContentString(&error)
if let error {
throw error
}
return contentString
}
deinit {
client.close()
}
}
@@ -1,40 +0,0 @@
import Foundation
import NetworkExtension
public extension NEVPNStatus {
var isEnabled: Bool {
switch self {
case .connected, .disconnected, .reasserting:
return true
default:
return false
}
}
var isSwitchable: Bool {
switch self {
case .connected, .disconnected:
return true
default:
return false
}
}
var isConnected: Bool {
switch self {
case .connecting, .connected, .disconnecting, .reasserting:
return true
default:
return false
}
}
var isConnectedStrict: Bool {
switch self {
case .connected, .reasserting:
return true
default:
return false
}
}
}
@@ -1,126 +0,0 @@
#if os(macOS)
import Foundation
import SystemExtensions
public class SystemExtension: NSObject, OSSystemExtensionRequestDelegate {
private let forceUpdate: Bool
private let inBackground: Bool
private let semaphore = DispatchSemaphore(value: 0)
private var result: OSSystemExtensionRequest.Result?
private var properties: [OSSystemExtensionProperties]?
private var error: Error?
private init(_ forceUpdate: Bool = false, _ inBackground: Bool = false) {
self.forceUpdate = forceUpdate
self.inBackground = inBackground
}
public func request(_: OSSystemExtensionRequest, actionForReplacingExtension existing: OSSystemExtensionProperties, withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction {
if forceUpdate {
return .replace
}
if existing.isAwaitingUserApproval, !inBackground {
return .replace
}
if existing.bundleIdentifier == ext.bundleIdentifier,
existing.bundleVersion == ext.bundleVersion,
existing.bundleShortVersion == ext.bundleShortVersion
{
NSLog("Skip update system extension")
return .cancel
} else {
NSLog("Update system extension")
return .replace
}
}
public func requestNeedsUserApproval(_: OSSystemExtensionRequest) {
semaphore.signal()
}
public func request(_: OSSystemExtensionRequest, didFinishWithResult result: OSSystemExtensionRequest.Result) {
self.result = result
semaphore.signal()
}
public func request(_: OSSystemExtensionRequest, didFailWithError error: Error) {
self.error = error
semaphore.signal()
}
public func request(_: OSSystemExtensionRequest, foundProperties properties: [OSSystemExtensionProperties]) {
self.properties = properties
semaphore.signal()
}
public func activation() throws -> OSSystemExtensionRequest.Result? {
let request = OSSystemExtensionRequest.activationRequest(forExtensionWithIdentifier: FilePath.packageName + ".system", queue: .main)
request.delegate = self
OSSystemExtensionManager.shared.submitRequest(request)
semaphore.wait()
if let error {
throw error
}
return result
}
public func deactivation() throws -> OSSystemExtensionRequest.Result? {
let request = OSSystemExtensionRequest.deactivationRequest(forExtensionWithIdentifier: FilePath.packageName + ".system", queue: .main)
request.delegate = self
OSSystemExtensionManager.shared.submitRequest(request)
semaphore.wait()
if let error {
throw error
}
return result
}
public func getProperties() throws -> [OSSystemExtensionProperties] {
let request = OSSystemExtensionRequest.propertiesRequest(forExtensionWithIdentifier: FilePath.packageName + ".system", queue: .main)
request.delegate = self
OSSystemExtensionManager.shared.submitRequest(request)
semaphore.wait()
if let error {
throw error
}
return properties!
}
public static func isInstalled() async -> Bool {
await (try? Task {
try await isInstalledBackground()
}.result.get()) == true
}
public nonisolated static func isInstalledBackground() async throws -> Bool {
for _ in 0 ..< 3 {
do {
let propList = try SystemExtension().getProperties()
if propList.isEmpty {
return false
}
for extensionProp in propList {
if !extensionProp.isAwaitingUserApproval, !extensionProp.isUninstalling {
return true
}
}
} catch {
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
}
}
return false
}
public nonisolated static func install(forceUpdate: Bool = false, inBackground: Bool = false) async throws -> OSSystemExtensionRequest.Result? {
try await Task.detached {
try SystemExtension(forceUpdate, inBackground).activation()
}.result.get()
}
public nonisolated static func uninstall() async throws -> OSSystemExtensionRequest.Result? {
try await Task.detached {
try SystemExtension().deactivation()
}.result.get()
}
}
#endif