feat(client/macos): P1 原生隧道——PacketTunnel 系统扩展可加载 + libbox 运行
经长链路排查(同机对照可工作的 Tailscale),修复 macOS 系统扩展 realize 失败(OSSystemExtensionErrorDomain code=4)与 libbox 运行时崩溃,使内嵌 sing-box 的系统扩展能在 macOS 15 上激活并启动隧道。 系统扩展 realize(三个叠加根因): - 扩展自包含:PacketTunnel 加 OTHER_LDFLAGS="" 切断对项目级 CocoaPods 链接 标志的继承(原会把 flutter_secure_storage 链进扩展);Libbox.xcframework 改纯 Link(静态),从 Embed Frameworks 移除冗余内嵌 - bundle 名 = 标识符:PRODUCT_NAME 设为 com.pangolin.pangolin.PacketTunnel - 扩展 Info.plist 补 NSSystemExtensionUsageDescription(网络扩展类别强制要求) - App Group 改 macOS 原生格式 BYL4KQHMTN.com.pangolin.pangolin;NEMachServiceName 以其为前缀;扩展补 network.client/server;get-task-allow=false + 签名加 --timestamp - CFBundleVersion 随构建递增(否则 sysextd 视为同版本不更新) libbox 运行时: - startOrReloadService(options:) 传 nil 致空指针 SIGSEGV → 传 LibboxOverrideOptions() - 默认接口监控阻塞到首个 path 更新再返回,修 "no available network interface" 配套: - scripts/local_test.sh:build/sign/notarize/copy/run 一条龙(Developer ID + 公证) - client/macos/sign_libbox.sh:构建期以 Developer ID 重签内嵌 Libbox - VpnChannel:401 自动刷新 token、详尽 os_log;auth/api 统一走 kApiBaseUrl - docs/macos-sysext-realize-troubleshooting.html:完整踩坑复盘 WIP / 临时(后续清理): - 隧道运行时仍在排查:剥离远程 rule-set 后 sing-box 启动卡点未定位 - 含临时诊断代码:main.swift stderr 重定向、box.log 输出、rule-set 剥离、debug 日志 - api_config 仍指向联调节点,发版前还原 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JEHzjEcFzvGwgbxT6Wbt6c
This commit is contained in:
@@ -2,12 +2,21 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- 网络扩展类别强制要求:扩展自己的 Info.plist 必须有此键,否则
|
||||
sysextd category 校验失败并卸载("require the presence of the
|
||||
'NSSystemExtensionUsageDescription' property")。主 app 的同名键不顶用。 -->
|
||||
<key>NSSystemExtensionUsageDescription</key>
|
||||
<string>Pangolin 需要安装网络扩展以提供安全的网络连接。</string>
|
||||
<!-- 自定义键:声明 NEPacketTunnelProvider。其余标准 CFBundle* 键由
|
||||
GENERATE_INFOPLIST_FILE=YES 自动生成并合并,此处不重复写以免冲突。 -->
|
||||
<key>NetworkExtension</key>
|
||||
<dict>
|
||||
<!-- NEMachServiceName 必须以扩展所属的某个 App Group 为前缀(Apple 规则)。
|
||||
App Group 用 macOS 原生格式 BYL4KQHMTN.com.pangolin.pangolin,mach 名 = 该 group
|
||||
+ .PacketTunnel。参照可工作的 Tailscale:group=<Team>.io.tailscale.ipn.macsys、
|
||||
mach=该 group + .network-extension。 -->
|
||||
<key>NEMachServiceName</key>
|
||||
<string>$(TeamIdentifierPrefix)group.com.pangolin.pangolin</string>
|
||||
<string>BYL4KQHMTN.com.pangolin.pangolin.PacketTunnel</string>
|
||||
<key>NEProviderClasses</key>
|
||||
<dict>
|
||||
<key>com.apple.networkextension.packet-tunnel</key>
|
||||
|
||||
@@ -2,20 +2,26 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- 开发期:App Extension 变体,Apple Development 自动签名即可编/签/本机调试。
|
||||
⚠️ 上线(站外 Developer ID 分发)时改为 System Extension:
|
||||
- 把本值换成 packet-tunnel-provider-systemextension
|
||||
- target 产物类型转 System Extension(.systemextension)
|
||||
- 用 Developer ID 手动签名 + 公证;首启 systemextensionsctl developer on
|
||||
Swift 代码两形态一致,仅打包/签名不同。详见 docs/p1-macos-system-extension.md。 -->
|
||||
<!-- Developer ID 分发 + 公证:禁止调试附加。 -->
|
||||
<key>com.apple.security.get-task-allow</key>
|
||||
<false/>
|
||||
<!-- 沙箱内的 packet tunnel 需显式网络权限才能对外建连/收发(对照可工作的 Tailscale)。 -->
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.server</key>
|
||||
<true/>
|
||||
<!-- System Extension 形态(站外 Developer ID 分发):用 -systemextension 变体,
|
||||
与 Developer ID profile(Pangolin PacketTunnel DevID)授权一致。
|
||||
详见 docs/p1-macos-system-extension.md。 -->
|
||||
<key>com.apple.developer.networking.networkextension</key>
|
||||
<array>
|
||||
<string>packet-tunnel-provider</string>
|
||||
<string>packet-tunnel-provider-systemextension</string>
|
||||
</array>
|
||||
<!-- 与主 app 共享配置/状态(同一 App Group) -->
|
||||
<!-- 与主 app 共享配置/状态(同一 App Group)。macOS 原生格式 <TeamID>.<name>,
|
||||
非 iOS 的 group. 前缀——sysextd realize 前校验请求方/扩展时要求此格式。 -->
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.com.pangolin.pangolin</string>
|
||||
<string>BYL4KQHMTN.com.pangolin.pangolin</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -15,7 +15,9 @@ import NetworkExtension
|
||||
import os
|
||||
|
||||
private let log = Logger(subsystem: "com.pangolin.pangolin.PacketTunnel", category: "provider")
|
||||
private let appGroup = "group.com.pangolin.pangolin"
|
||||
// macOS 原生 App Group 格式 <TeamID>.<name>(非 iOS 的 group. 前缀)。
|
||||
// sysextd 校验请求方 app 时要求此格式;用 group. 式会在 realize 暂存前被拒。
|
||||
private let appGroup = "BYL4KQHMTN.com.pangolin.pangolin"
|
||||
|
||||
final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
private var commandServer: LibboxCommandServer?
|
||||
@@ -25,7 +27,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
completionHandler: @escaping (Error?) -> Void) {
|
||||
log.info("startTunnel")
|
||||
do {
|
||||
let configContent = try resolveConfig(options)
|
||||
let rawConfig = try resolveConfig(options)
|
||||
|
||||
guard let base = FileManager.default
|
||||
.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
|
||||
@@ -34,6 +36,10 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
let work = base.appendingPathComponent("work", isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
|
||||
|
||||
// 【临时】剥掉远程 rule-set(#5);并把 sing-box 日志直写容器 box.log(debug)以定位启动卡点。
|
||||
let configContent = Self.stripRemoteRuleSets(
|
||||
rawConfig, logOutput: base.appendingPathComponent("box.log").path)
|
||||
|
||||
let setup = LibboxSetupOptions()
|
||||
setup.basePath = base.path
|
||||
setup.workingPath = work.path
|
||||
@@ -50,13 +56,17 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
throw newErr ?? simpleError("LibboxNewCommandServer returned nil")
|
||||
}
|
||||
try server.start()
|
||||
try server.startOrReloadService(configContent, options: nil)
|
||||
// 必须传非空 options:此版本 libbox 的 StartOrReloadService 会解引用 options,
|
||||
// 传 nil 会在 command_server.go:175 触发 SIGSEGV(空指针),扩展进程崩溃。
|
||||
try server.startOrReloadService(configContent, options: LibboxOverrideOptions())
|
||||
self.commandServer = server
|
||||
|
||||
log.info("startTunnel: service started")
|
||||
completionHandler(nil)
|
||||
} catch {
|
||||
log.error("startTunnel failed: \(error.localizedDescription)")
|
||||
// 【临时诊断】完整错误写进 stderr.log;并设 public 避免 os_log 脱敏成 <private>。
|
||||
FileHandle.standardError.write("startTunnel failed: \(error)\n".data(using: .utf8)!)
|
||||
log.error("startTunnel failed: \(error.localizedDescription, privacy: .public)")
|
||||
completionHandler(error)
|
||||
}
|
||||
}
|
||||
@@ -90,13 +100,33 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
guard !content.isEmpty else { throw simpleError("empty sing-box config") }
|
||||
return content
|
||||
}
|
||||
|
||||
// 【临时】移除配置里的远程 rule-set 定义,以及 route.rules 中引用了 rule_set 的规则。
|
||||
// 解析失败则原样返回。正式分流方案应改用本地 .srs(客户端预取)。
|
||||
static func stripRemoteRuleSets(_ json: String, logOutput: String) -> String {
|
||||
guard let data = json.data(using: .utf8),
|
||||
var root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
var route = root["route"] as? [String: Any] else {
|
||||
return json
|
||||
}
|
||||
if route["rule_set"] != nil { route.removeValue(forKey: "rule_set") }
|
||||
if let rules = route["rules"] as? [[String: Any]] {
|
||||
route["rules"] = rules.filter { $0["rule_set"] == nil }
|
||||
}
|
||||
root["route"] = route
|
||||
// 【临时诊断】sing-box 日志直写容器 box.log(debug),定位启动卡点。
|
||||
root["log"] = ["level": "debug", "timestamp": true, "output": logOutput]
|
||||
guard let out = try? JSONSerialization.data(withJSONObject: root),
|
||||
let s = String(data: out, encoding: .utf8) else { return json }
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
// ── LibboxCommandServerHandler:服务端事件回调 ──────────────────────────────
|
||||
extension PacketTunnelProvider: LibboxCommandServerHandlerProtocol {
|
||||
func serviceReload() throws {
|
||||
if let cfg = try? resolveConfig(nil) {
|
||||
try commandServer?.startOrReloadService(cfg, options: nil)
|
||||
try commandServer?.startOrReloadService(cfg, options: LibboxOverrideOptions())
|
||||
}
|
||||
}
|
||||
func serviceStop() throws { cancelTunnelWithError(nil) }
|
||||
@@ -106,7 +136,15 @@ extension PacketTunnelProvider: LibboxCommandServerHandlerProtocol {
|
||||
}
|
||||
func setSystemProxyEnabled(_ enabled: Bool) throws {}
|
||||
func writeStatus(_ message: LibboxStatusMessage?) {}
|
||||
func writeLogs(_ messageList: (any LibboxLogIteratorProtocol)?) {}
|
||||
func writeLogs(_ messageList: (any LibboxLogIteratorProtocol)?) {
|
||||
// 【临时诊断】把 sing-box 日志写进 stderr.log,定位启动卡点。
|
||||
guard let it = messageList else { return }
|
||||
while it.hasNext() {
|
||||
guard let entry = it.next() else { continue }
|
||||
let line = "[box] \(entry.message)\n"
|
||||
FileHandle.standardError.write(line.data(using: .utf8) ?? Data())
|
||||
}
|
||||
}
|
||||
func writeConnectionEvents(_ events: LibboxConnectionEvents?) {}
|
||||
func writeGroups(_ message: (any LibboxOutboundGroupIteratorProtocol)?) {}
|
||||
func writeDebugMessage(_ message: String?) {}
|
||||
@@ -170,6 +208,11 @@ final class PangolinPlatformInterface: NSObject, LibboxPlatformInterfaceProtocol
|
||||
func startDefaultInterfaceMonitor(_ listener: (any LibboxInterfaceUpdateListenerProtocol)?) throws {
|
||||
let m = NWPathMonitor()
|
||||
monitor = m
|
||||
// 必须阻塞到首个 path 更新再返回:否则 sing-box 紧接着下载远程 rule-set 时
|
||||
// defaultInterfaceIndex 仍为 -1,autoDetectControl 跳过绑接口 → "no available
|
||||
// network interface"。对齐 sing-box-for-apple 的实现。
|
||||
let firstUpdate = DispatchSemaphore(value: 0)
|
||||
var signaled = false
|
||||
m.pathUpdateHandler = { [weak self] path in
|
||||
guard let self else { return }
|
||||
let iface = path.availableInterfaces.first { path.usesInterfaceType($0.type) }
|
||||
@@ -180,8 +223,10 @@ final class PangolinPlatformInterface: NSObject, LibboxPlatformInterfaceProtocol
|
||||
listener?.updateDefaultInterface(name, interfaceIndex: index,
|
||||
isExpensive: path.isExpensive,
|
||||
isConstrained: path.isConstrained)
|
||||
if !signaled { signaled = true; firstUpdate.signal() }
|
||||
}
|
||||
m.start(queue: monitorQueue)
|
||||
_ = firstUpdate.wait(timeout: .now() + 5)
|
||||
}
|
||||
func closeDefaultInterfaceMonitor(_ listener: (any LibboxInterfaceUpdateListenerProtocol)?) throws {
|
||||
stopMonitor()
|
||||
|
||||
@@ -7,6 +7,17 @@
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
|
||||
// 【临时诊断】把 stderr/stdout 重定向到 App Group 容器文件,捕获 libbox(Go)的
|
||||
// fatal error / panic——系统扩展默认不把 stderr 收进统一日志。诊断完移除。
|
||||
if let c = FileManager.default.containerURL(
|
||||
forSecurityApplicationGroupIdentifier: "BYL4KQHMTN.com.pangolin.pangolin") {
|
||||
let p = c.appendingPathComponent("stderr.log").path
|
||||
freopen(p, "a", stderr)
|
||||
freopen(p, "a", stdout)
|
||||
setvbuf(stderr, nil, _IONBF, 0)
|
||||
FileHandle.standardError.write("=== boot \(Date()) ===\n".data(using: .utf8)!)
|
||||
}
|
||||
|
||||
autoreleasepool {
|
||||
NEProvider.startSystemExtensionMode()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user