Update usages of libbox

This commit is contained in:
世界
2025-11-26 22:25:47 +08:00
parent 532c140f05
commit f4b284acd8
6 changed files with 64 additions and 79 deletions
@@ -4,7 +4,7 @@ import SwiftUI
public struct SettingView: View { public struct SettingView: View {
private enum Tabs: Int, CaseIterable, Identifiable { private enum Tabs: Int, CaseIterable, Identifiable {
public var id: Self { var id: Self {
self self
} }
@@ -61,12 +61,12 @@ extension SharedPreferences {
} }
private class Item: Record, Identifiable { private class Item: Record, Identifiable {
public var id: String { var id: String {
name name
} }
public var name: String var name: String
public var data: Data var data: Data
init(name: String, data: Data) { init(name: String, data: Data) {
self.name = name self.name = name
@@ -74,7 +74,7 @@ private class Item: Record, Identifiable {
super.init() super.init()
} }
override public class var databaseTableName: String { override class var databaseTableName: String {
"preferences" "preferences"
} }
@@ -88,7 +88,7 @@ private class Item: Record, Identifiable {
try super.init(row: row) try super.init(row: row)
} }
override public func encode(to container: inout PersistenceContainer) throws { override func encode(to container: inout PersistenceContainer) throws {
container[Columns.name] = name container[Columns.name] = name
container[Columns.data] = data container[Columns.data] = data
} }
+12 -2
View File
@@ -18,6 +18,7 @@ public class CommandClient: ObservableObject {
@Published public var status: LibboxStatusMessage? @Published public var status: LibboxStatusMessage?
@Published public var groups: [LibboxOutboundGroup]? @Published public var groups: [LibboxOutboundGroup]?
@Published public var logList: [String] @Published public var logList: [String]
@Published public var defaultLogLevel: Int32 = 0
@Published public var clashModeList: [String] @Published public var clashModeList: [String]
@Published public var clashMode: String @Published public var clashMode: String
@@ -160,20 +161,29 @@ public class CommandClient: ObservableObject {
} }
} }
func setDefaultLogLevel(_ level: Int32) {
DispatchQueue.main.async { [self] in
commandClient.defaultLogLevel = level
}
}
func clearLogs() { func clearLogs() {
DispatchQueue.main.async { [self] in DispatchQueue.main.async { [self] in
commandClient.logList.removeAll() commandClient.logList.removeAll()
} }
} }
func writeLogs(_ messageList: (any LibboxStringIteratorProtocol)?) { func writeLogs(_ messageList: (any LibboxLogIteratorProtocol)?) {
guard let messageList else { guard let messageList else {
return return
} }
DispatchQueue.main.async { [self] in DispatchQueue.main.async { [self] in
var newLogList = commandClient.logList var newLogList = commandClient.logList
while messageList.hasNext() { while messageList.hasNext() {
newLogList.append(messageList.next()) let logEntry = messageList.next()!
if logEntry.level <= commandClient.defaultLogLevel {
newLogList.append(logEntry.message)
}
} }
if newLogList.count >= commandClient.logMaxLines { if newLogList.count >= commandClient.logMaxLines {
newLogList.removeSubrange(0 ... newLogList.count - commandClient.logMaxLines) newLogList.removeSubrange(0 ... newLogList.count - commandClient.logMaxLines)
@@ -356,18 +356,17 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
#endif #endif
} }
public func serviceStop() throws {
reset()
}
public func serviceReload() throws { public func serviceReload() throws {
runBlocking { [self] in runBlocking { [self] in
await tunnel.reloadService() await tunnel.reloadService()
} }
} }
public func postServiceClose() { public func getSystemProxyStatus() throws -> LibboxSystemProxyStatus {
reset()
tunnel.postServiceClose()
}
public func getSystemProxyStatus() -> LibboxSystemProxyStatus? {
let status = LibboxSystemProxyStatus() let status = LibboxSystemProxyStatus()
guard let networkSettings else { guard let networkSettings else {
return status return status
@@ -404,6 +403,13 @@ public class ExtensionPlatformInterface: NSObject, LibboxPlatformInterfaceProtoc
} }
} }
public func writeDebugMessage(_ message: String?) {
guard let message else {
return
}
tunnel.writeMessage(message)
}
func reset() { func reset() {
networkSettings = nil networkSettings = nil
} }
+31 -61
View File
@@ -11,9 +11,6 @@ import NetworkExtension
open class ExtensionProvider: NEPacketTunnelProvider { open class ExtensionProvider: NEPacketTunnelProvider {
public var username: String? public var username: String?
private var commandServer: LibboxCommandServer! private var commandServer: LibboxCommandServer!
private var boxService: LibboxBoxService!
private var systemProxyAvailable = false
private var systemProxyEnabled = false
private var platformInterface: ExtensionPlatformInterface! private var platformInterface: ExtensionPlatformInterface!
override open func startTunnel(options _: [String: NSObject]?) async throws { override open func startTunnel(options _: [String: NSObject]?) async throws {
@@ -23,22 +20,17 @@ open class ExtensionProvider: NEPacketTunnelProvider {
options.basePath = FilePath.sharedDirectory.relativePath options.basePath = FilePath.sharedDirectory.relativePath
options.workingPath = FilePath.workingDirectory.relativePath options.workingPath = FilePath.workingDirectory.relativePath
options.tempPath = FilePath.cacheDirectory.relativePath options.tempPath = FilePath.cacheDirectory.relativePath
var error: NSError? var setupError: NSError?
#if os(tvOS) LibboxSetup(options, &setupError)
options.isTVOS = true if let setupError {
#endif writeFatalError("(packet-tunnel) error: setup service: \(setupError.localizedDescription)")
if let username {
options.username = username
}
LibboxSetup(options, &error)
if let error {
writeFatalError("(packet-tunnel) error: setup service: \(error.localizedDescription)")
return return
} }
LibboxRedirectStderr(FilePath.cacheDirectory.appendingPathComponent("stderr.log").relativePath, &error) var stderrError: NSError?
if let error { LibboxRedirectStderr(FilePath.cacheDirectory.appendingPathComponent("stderr.log").relativePath, &stderrError)
writeFatalError("(packet-tunnel) redirect stderr error: \(error.localizedDescription)") if let stderrError {
writeFatalError("(packet-tunnel) redirect stderr error: \(stderrError.localizedDescription)")
return return
} }
@@ -47,11 +39,16 @@ open class ExtensionProvider: NEPacketTunnelProvider {
if platformInterface == nil { if platformInterface == nil {
platformInterface = ExtensionPlatformInterface(self) platformInterface = ExtensionPlatformInterface(self)
} }
commandServer = await LibboxNewCommandServer(platformInterface, Int32(SharedPreferences.maxLogLines.get())) var error: NSError?
commandServer = LibboxNewCommandServer(platformInterface, platformInterface, &error)
if let error {
writeFatalError("(packet-tunnel): create command server error: \(error.localizedDescription)")
return
}
do { do {
try commandServer.start() try commandServer.start()
} catch { } catch {
writeFatalError("(packet-tunnel): log server start error: \(error.localizedDescription)") writeFatalError("(packet-tunnel): start command server error: \(error.localizedDescription)")
return return
} }
writeMessage("(packet-tunnel): Here I stand") writeMessage("(packet-tunnel): Here I stand")
@@ -65,7 +62,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
func writeMessage(_ message: String) { func writeMessage(_ message: String) {
if let commandServer { if let commandServer {
commandServer.writeMessage(message) commandServer.writeMessage(2, message: message)
} }
} }
@@ -73,9 +70,9 @@ open class ExtensionProvider: NEPacketTunnelProvider {
#if DEBUG #if DEBUG
NSLog(message) NSLog(message)
#endif #endif
writeMessage(message) if let commandServer {
var error: NSError? commandServer.setError(message)
LibboxWriteServiceError(message, &error) }
cancelTunnelWithError(nil) cancelTunnelWithError(nil)
} }
@@ -98,33 +95,23 @@ open class ExtensionProvider: NEPacketTunnelProvider {
writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)") writeFatalError("(packet-tunnel) error: read config file \(profile.path): \(error.localizedDescription)")
return return
} }
var error: NSError? let options = LibboxOverrideOptions()
let service = LibboxNewService(configContent, platformInterface, &error)
if let error {
writeFatalError("(packet-tunnel) error: create service: \(error.localizedDescription)")
return
}
guard let service else {
return
}
do { do {
try service.start() try commandServer.startOrReloadService(configContent, options: options)
} catch { } catch {
writeFatalError("(packet-tunnel) error: start service: \(error.localizedDescription)") writeFatalError("(packet-tunnel) error: start service: \(error.localizedDescription)")
return return
} }
commandServer.setService(service)
boxService = service
#if os(macOS) #if os(macOS)
await SharedPreferences.startedByUser.set(true) await SharedPreferences.startedByUser.set(true)
if service.needWIFIState() { if commandServer.needWIFIState() {
if !Variant.useSystemExtension { if !Variant.useSystemExtension {
locationManager = CLLocationManager() locationManager = CLLocationManager()
locationDelegate = stubLocationDelegate(boxService) locationDelegate = stubLocationDelegate()
locationManager?.delegate = locationDelegate locationManager?.delegate = locationDelegate
locationManager?.requestLocation() locationManager?.requestLocation()
} else { } else {
commandServer.writeMessage("(packet-tunnel) WIFI SSID and BSSID information is not currently available in the standalone version of SFM. We are working on resolving this issue.") writeMessage("(packet-tunnel) WIFI SSID and BSSID information is not currently available in the standalone version of SFM. We are working on resolving this issue.")
} }
} }
#endif #endif
@@ -136,14 +123,7 @@ open class ExtensionProvider: NEPacketTunnelProvider {
private var locationDelegate: stubLocationDelegate? private var locationDelegate: stubLocationDelegate?
class stubLocationDelegate: NSObject, CLLocationManagerDelegate { class stubLocationDelegate: NSObject, CLLocationManagerDelegate {
private unowned let boxService: LibboxBoxService func locationManagerDidChangeAuthorization(_: CLLocationManager) {}
init(_ boxService: LibboxBoxService) {
self.boxService = boxService
}
func locationManagerDidChangeAuthorization(_: CLLocationManager) {
boxService.updateWIFIState()
}
func locationManager(_: CLLocationManager, didUpdateLocations _: [CLLocation]) {} func locationManager(_: CLLocationManager, didUpdateLocations _: [CLLocation]) {}
@@ -153,15 +133,11 @@ open class ExtensionProvider: NEPacketTunnelProvider {
#endif #endif
private func stopService() { private func stopService() {
if let service = boxService {
do { do {
try service.close() try commandServer.closeService()
} catch { } catch {
writeMessage("(packet-tunnel) error: stop service: \(error.localizedDescription)") writeMessage("(packet-tunnel) error: stop service: \(error.localizedDescription)")
} }
boxService = nil
commandServer.setService(nil)
}
if let platformInterface { if let platformInterface {
platformInterface.reset() platformInterface.reset()
} }
@@ -173,21 +149,15 @@ open class ExtensionProvider: NEPacketTunnelProvider {
defer { defer {
reasserting = false reasserting = false
} }
stopService()
commandServer.resetLog()
await startService() await startService()
} }
func postServiceClose() {
boxService = nil
}
override open func stopTunnel(with reason: NEProviderStopReason) async { override open func stopTunnel(with reason: NEProviderStopReason) async {
writeMessage("(packet-tunnel) stopping, reason: \(reason)") writeMessage("(packet-tunnel) stopping, reason: \(reason)")
stopService() stopService()
if let server = commandServer { if let server = commandServer {
try? await Task.sleep(nanoseconds: 100 * NSEC_PER_MSEC) try? await Task.sleep(nanoseconds: 100 * NSEC_PER_MSEC)
try? server.close() server.close()
commandServer = nil commandServer = nil
} }
#if os(macOS) #if os(macOS)
@@ -207,14 +177,14 @@ open class ExtensionProvider: NEPacketTunnelProvider {
} }
override open func sleep() async { override open func sleep() async {
if let boxService { if let commandServer {
boxService.pause() commandServer.pause()
} }
} }
override open func wake() { override open func wake() {
if let boxService { if let commandServer {
boxService.wake() commandServer.wake()
} }
} }
} }
-1
View File
@@ -11,7 +11,6 @@ class ApplicationDelegate: NSObject, UIApplicationDelegate {
options.basePath = FilePath.sharedDirectory.relativePath options.basePath = FilePath.sharedDirectory.relativePath
options.workingPath = FilePath.workingDirectory.relativePath options.workingPath = FilePath.workingDirectory.relativePath
options.tempPath = FilePath.cacheDirectory.relativePath options.tempPath = FilePath.cacheDirectory.relativePath
options.isTVOS = true
var error: NSError? var error: NSError?
LibboxSetup(options, &error) LibboxSetup(options, &error)
LibboxSetLocale(Locale.current.identifier) LibboxSetLocale(Locale.current.identifier)