fix(client/macos): 实时统计改走 sendProviderMessage,根治容器路径死局
上一版试图让 root 扩展把 command.sock 建到用户容器,反而让 startTunnel 抛错、隧道连不上
(root 在用户 home 建 socket、属主/路径与无 root 的 app 对不上,且方向本就错)。回退该路子。
正解:用 NetworkExtension 官方跨进程通道,绕开「root 扩展容器 vs 用户 app 容器」死局——
- 扩展内新增 StatsCollector:连本进程自己的 command.sock(同容器、root 可达),订阅
status/group 缓存最新上下行 + urltest;handleAppMessage 收到 "stats" 即回最新 JSON。
- 主 app StatsClient 改为每秒 NETunnelProviderSession.sendProviderMessage("stats") 拉取、
解析后推 onStats(不再直连 socket);VpnChannel 三处启动点改传 session。
- 扩展代码变更 → CURRENT_PROJECT_VERSION 44→45,让 sysextd 重装。
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,105 +1,49 @@
|
||||
// StatsClient.swift — 主 app 侧实时统计生产者(macOS)
|
||||
// StatsClient.swift — 主 app 侧实时统计消费者(macOS)
|
||||
//
|
||||
// 隧道跑在 PacketTunnel System Extension 进程里,扩展已 LibboxSetup 到 App Group 容器
|
||||
// 并起了 LibboxCommandServer。主 app 用 LibboxCommandClient 连接「同一 group 容器路径」
|
||||
// 下的 CommandServer socket,订阅 status/group 命令拿实时上/下行 + 延迟——对齐 iOS
|
||||
// StatsClient 与 sing-box-for-apple 模型,替代旧的「每秒推占位 0」骨架。
|
||||
// 隧道跑在 PacketTunnel System Extension 进程里(root)。扩展和主 app 的 App Group 容器
|
||||
// 不是同一路径(root 的 /var/root/... vs 用户的 /Users/<user>/...),主 app 无法直接连
|
||||
// 扩展的 libbox command.sock。改走 NetworkExtension 官方的跨进程通道:
|
||||
// 主 app → NETunnelProviderSession.sendProviderMessage("stats")
|
||||
// 扩展 → handleAppMessage 回最新统计 JSON(由扩展进程内的 StatsCollector 缓存)
|
||||
//
|
||||
// 字段映射到 pangolin/vpn/stats 契约(见 lib/bridge/vpn_bridge.dart),经 onStats 回调
|
||||
// 交给 VpnChannel 推到 Dart 侧。生命周期由 VpnChannel 的 NEVPNStatus 观察驱动。
|
||||
// 这绕开了 root/用户容器与 socket 属主的死局。字段映射到 pangolin/vpn/stats 契约
|
||||
// (见 lib/bridge/vpn_bridge.dart),经 onStats 交给 VpnChannel 推到 Dart 侧。
|
||||
|
||||
import Foundation
|
||||
import Libbox
|
||||
import NetworkExtension
|
||||
|
||||
final class StatsClient: NSObject {
|
||||
|
||||
// macOS 原生 App Group 格式 <TeamID>.<name>(与扩展一致,非 iOS 的 group. 前缀)。
|
||||
private let appGroup = "BYL4KQHMTN.com.pangolin.pangolin"
|
||||
|
||||
/// 把契约字典交还 VpnChannel(由其推给当前 statsSink)。主队列回调。
|
||||
var onStats: (([String: Any]) -> Void)?
|
||||
|
||||
private let queue = DispatchQueue(label: "pangolin.stats.client")
|
||||
private var client: LibboxCommandClient?
|
||||
private var started = false
|
||||
private static var didSetup = false
|
||||
|
||||
private var latestUrltest: [(tag: String, delayMs: Int)] = []
|
||||
|
||||
/// writeGroups 捕获的出口组 tag,用于主动触发延迟探测。
|
||||
private var groupTags: [String] = []
|
||||
/// 周期主动 urltest:补偿 sing-box urltest 惰性探测,让延迟稳定及时。
|
||||
private var urlTestTimer: DispatchSourceTimer?
|
||||
private weak var session: NETunnelProviderSession?
|
||||
private var timer: DispatchSourceTimer?
|
||||
|
||||
// ── 生命周期 ────────────────────────────────────────────────
|
||||
|
||||
func start() {
|
||||
/// 隧道 connected 时调用,传入当前会话。每秒向扩展拉一次统计。
|
||||
func start(session: NETunnelProviderSession) {
|
||||
queue.async { [weak self] in
|
||||
guard let self, !self.started else { return }
|
||||
guard self.ensureSetup() else { return }
|
||||
|
||||
let options = LibboxCommandClientOptions()
|
||||
options.statusInterval = 1_000_000_000 // 1s(纳秒)
|
||||
options.addCommand(LibboxCommandStatus)
|
||||
options.addCommand(LibboxCommandGroup)
|
||||
|
||||
guard let c = LibboxNewCommandClient(self, options) else {
|
||||
NSLog("[pangolin/stats] LibboxNewCommandClient returned nil")
|
||||
return
|
||||
}
|
||||
// 打点:command.sock 由 sysext 的 LibboxCommandServer 在 group 容器内创建。
|
||||
// 若此处 sock 不存在 → 跑的是没起 CommandServer 的旧 sysext(版本没换上)。
|
||||
if let base = FileManager.default
|
||||
.containerURL(forSecurityApplicationGroupIdentifier: self.appGroup) {
|
||||
let sock = base.appendingPathComponent("command.sock").path
|
||||
let exists = FileManager.default.fileExists(atPath: sock)
|
||||
NSLog("[pangolin/stats] command.sock=%@ exists=%@", sock, exists ? "YES" : "NO(sysext 未起 CommandServer/旧版)")
|
||||
}
|
||||
for attempt in 0..<10 {
|
||||
do {
|
||||
try c.connect()
|
||||
self.client = c
|
||||
self.started = true
|
||||
NSLog("[pangolin/stats] connected (attempt %d)", attempt + 1)
|
||||
self.startUrlTestTimer()
|
||||
return
|
||||
} catch {
|
||||
NSLog("[pangolin/stats] connect failed (attempt %d): %@", attempt + 1,
|
||||
error.localizedDescription)
|
||||
Thread.sleep(forTimeInterval: 0.5)
|
||||
}
|
||||
}
|
||||
NSLog("[pangolin/stats] gave up connecting after retries")
|
||||
guard let self else { return }
|
||||
self.session = session
|
||||
self.timer?.cancel()
|
||||
let t = DispatchSource.makeTimerSource(queue: self.queue)
|
||||
t.schedule(deadline: .now() + 0.2, repeating: 1.0)
|
||||
t.setEventHandler { [weak self] in self?.poll() }
|
||||
t.resume()
|
||||
self.timer = t
|
||||
NSLog("[pangolin/stats] polling via sendProviderMessage started")
|
||||
}
|
||||
}
|
||||
|
||||
/// 周期主动触发 urltest 探测(在 queue 上)。
|
||||
private func startUrlTestTimer() {
|
||||
urlTestTimer?.cancel()
|
||||
let timer = DispatchSource.makeTimerSource(queue: queue)
|
||||
timer.schedule(deadline: .now() + 2, repeating: 12)
|
||||
timer.setEventHandler { [weak self] in
|
||||
guard let self, let c = self.client else { return }
|
||||
for tag in self.groupTags {
|
||||
try? c.urlTest(tag)
|
||||
}
|
||||
}
|
||||
timer.resume()
|
||||
urlTestTimer = timer
|
||||
}
|
||||
|
||||
func stop() {
|
||||
queue.async { [weak self] in
|
||||
guard let self else { return }
|
||||
self.urlTestTimer?.cancel()
|
||||
self.urlTestTimer = nil
|
||||
if let c = self.client {
|
||||
try? c.disconnect()
|
||||
}
|
||||
self.client = nil
|
||||
self.started = false
|
||||
self.latestUrltest = []
|
||||
self.groupTags = []
|
||||
self.timer?.cancel()
|
||||
self.timer = nil
|
||||
self.session = nil
|
||||
self.emit([
|
||||
"uploadBytes": 0, "downloadBytes": 0,
|
||||
"uploadSpeed": 0.0, "downloadSpeed": 0.0,
|
||||
@@ -108,71 +52,23 @@ final class StatsClient: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func poll() {
|
||||
guard let session else { return }
|
||||
do {
|
||||
try session.sendProviderMessage(Data("stats".utf8)) { [weak self] resp in
|
||||
guard let self, let resp, !resp.isEmpty else { return }
|
||||
guard let obj = (try? JSONSerialization.jsonObject(with: resp)) as? [String: Any] else {
|
||||
NSLog("[pangolin/stats] bad stats payload (%d bytes)", resp.count)
|
||||
return
|
||||
}
|
||||
self.emit(obj)
|
||||
}
|
||||
} catch {
|
||||
NSLog("[pangolin/stats] sendProviderMessage failed: %@", error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
private func emit(_ stats: [String: Any]) {
|
||||
DispatchQueue.main.async { [weak self] in self?.onStats?(stats) }
|
||||
}
|
||||
|
||||
// ── libbox 全局 setup(与扩展同一 group 容器路径)─────────────
|
||||
|
||||
private func ensureSetup() -> Bool {
|
||||
if Self.didSetup { return true }
|
||||
guard let base = FileManager.default
|
||||
.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
|
||||
NSLog("[pangolin/stats] no app group container")
|
||||
return false
|
||||
}
|
||||
let work = base.appendingPathComponent("work", isDirectory: true)
|
||||
let setup = LibboxSetupOptions()
|
||||
setup.basePath = base.path
|
||||
setup.workingPath = work.path
|
||||
setup.tempPath = NSTemporaryDirectory()
|
||||
var err: NSError?
|
||||
LibboxSetup(setup, &err)
|
||||
if let err {
|
||||
NSLog("[pangolin/stats] LibboxSetup failed: %@", err.localizedDescription)
|
||||
return false
|
||||
}
|
||||
Self.didSetup = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// ── LibboxCommandClientHandler:实时回调 ─────────────────────────────
|
||||
extension StatsClient: LibboxCommandClientHandlerProtocol {
|
||||
func connected() { NSLog("[pangolin/stats] server connected") }
|
||||
func disconnected(_ message: String?) { NSLog("[pangolin/stats] server disconnected: %@", message ?? "") }
|
||||
func clearLogs() {}
|
||||
func writeLogs(_ messageList: (any LibboxLogIteratorProtocol)?) {}
|
||||
func setDefaultLogLevel(_ level: Int32) {}
|
||||
func initializeClashMode(_ modeList: (any LibboxStringIteratorProtocol)?, currentMode: String?) {}
|
||||
func updateClashMode(_ newMode: String?) {}
|
||||
func write(_ events: LibboxConnectionEvents?) {}
|
||||
|
||||
func writeStatus(_ message: LibboxStatusMessage?) {
|
||||
guard let m = message else { return }
|
||||
emit([
|
||||
"uploadBytes": m.uplinkTotal,
|
||||
"downloadBytes": m.downlinkTotal,
|
||||
"uploadSpeed": Double(m.uplink),
|
||||
"downloadSpeed": Double(m.downlink),
|
||||
"urltestResults": latestUrltest.map { ["tag": $0.tag, "delayMs": $0.delayMs] },
|
||||
])
|
||||
}
|
||||
|
||||
func writeGroups(_ message: (any LibboxOutboundGroupIteratorProtocol)?) {
|
||||
guard let groups = message else { return }
|
||||
var urltest: [(tag: String, delayMs: Int)] = []
|
||||
var tags: [String] = []
|
||||
while groups.hasNext() {
|
||||
guard let group = groups.next() else { break }
|
||||
tags.append(group.tag)
|
||||
guard let items = group.getItems() else { continue }
|
||||
while items.hasNext() {
|
||||
guard let item = items.next() else { break }
|
||||
urltest.append((tag: item.tag, delayMs: Int(item.urlTestDelay)))
|
||||
}
|
||||
}
|
||||
latestUrltest = urltest
|
||||
queue.async { [weak self] in self?.groupTags = tags }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user