Files
ShadowsocksX-NG/ShadowsocksX-NG2/App/SystemProxyHelperService.swift
T
Qiu Yuzhou c1aba5a882 fix(system-proxy): make helper XPC connection reachable and crash-free
GUI 侧 XPC 回调闭包(invalidationHandler 与 remoteObjectProxy 错误回调)在
@MainActor 方法里形成、传给非 @Sendable 的 Foundation 参数被推断为主 actor
隔离,Foundation 在 XPC 内部队列上调起时触发动态隔离断言直接崩溃;显式标注
@Sendable(nonisolated),闭包只捕获 Sendable 应答闸门。

连接系统域 LaunchDaemon 的 MachService 必须带 options: .privileged(否则只
在 per-user launchd 域查找,永远失败走错误回调);并把 resume() 提到首次远
程调用之前,超时兜底任务在应答到达后取消。

收敛/清除失败补 RuntimeLog systemProxyWriteFailed(detail:)(诊断报告白名单
按既有承诺脱敏收录),XPC/ helper 层失败原因不再只能靠崩溃报告逆向。

listener delegate 与客户端校验移入 Domain 共享编译单元(与引擎同模式),
main.swift 改为显式注入引擎;新增真实 XPC 装配层 round-trip 测试:匿名监听
器挂真实 delegate(注入假特权写入器)+ listenerEndpoint 连接,覆盖接口签
名、客户端签名校验、Data 传输与 XPC 队列应答路径,无需 launchd。
2026-09-30 13:40:16 +08:00

181 lines
6.3 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
import ServiceManagement
/// 系统代理写入缝(issue #71):异步 typed apply 与无条件 clear 的边界,
/// 形状为 XPC 就绪。GUI 域决策(意图、门禁、值、清理时机)全部在调用方;
/// 本缝只执行。生产实现经特权 helper,测试注入 fake。
@MainActor
protocol SystemProxyControlling {
@discardableResult
func apply(_ configuration: SystemProxyConfiguration) async throws -> SystemProxyWriteOutcome
func clear() async throws
}
/// helper 注册/审批状态缝(issue #71):注册走 SMAppService.daemon;审批缺失
/// 时 GUI 据此呈现登录项批准路径,不提供直接授权回退。单测以 fake 替换
/// (真实注册会改动系统登录项状态)。
@MainActor
protocol SystemProxyHelperServicing {
var status: SystemProxyHelperStatus { get }
func register() throws
func openApprovalPath()
}
enum SystemProxyHelperStatus: Equatable, Sendable {
case notRegistered
case requiresApproval
case approved
}
/// 生产实现:SMAppService.daemon 注册 bundle 内
/// Contents/Library/LaunchDaemons/ 下的 LaunchDaemon 清单。
struct SMAppServiceSystemProxyHelper: SystemProxyHelperServicing {
private let service = SMAppService.daemon(plistName: SystemProxyHelperIdentity.plistName)
var status: SystemProxyHelperStatus {
switch service.status {
case .requiresApproval:
return .requiresApproval
case .enabled:
return .approved
case .notRegistered, .notFound:
return .notRegistered
@unknown default:
return .notRegistered
}
}
func register() throws {
try service.register()
}
func openApprovalPath() {
SMAppService.openSystemSettingsLoginItems()
}
}
/// 经特权 helper 的系统代理写入器(issue #71):每个请求一条按需连接,
/// MachService 连接触发 launchd 激活已注册的 LaunchDaemon。应答在
/// helper 不可达、连接失效、报错或超时时以 typed 错误呈现。
@MainActor
final class XPCSystemProxyController: SystemProxyControlling {
private let requestTimeoutNanoseconds: UInt64
init(requestTimeoutNanoseconds: UInt64 = 10_000_000_000) {
self.requestTimeoutNanoseconds = requestTimeoutNanoseconds
}
func apply(_ configuration: SystemProxyConfiguration) async throws -> SystemProxyWriteOutcome {
let payload = try SystemProxyHelperWire.encodeConfiguration(configuration)
let response = try await send { proxy, reply in proxy.apply(payload, withReply: reply) }
switch response {
case .applied(let outcome):
return outcome
case .failure(let error):
throw error
case .cleared:
throw SystemProxyError.helperUnavailable("apply 收到 clear 应答")
}
}
func clear() async throws {
let response = try await send { proxy, reply in proxy.clear(withReply: reply) }
switch response {
case .cleared:
return
case .failure(let error):
throw error
case .applied:
throw SystemProxyError.helperUnavailable("clear 收到 apply 应答")
}
}
// MARK: - XPC 请求
private func send(
_ call:
@escaping @Sendable (
_ proxy: SystemProxyHelperControlling, _ reply: @escaping @Sendable (Data) -> Void
) -> Void
) async throws -> SystemProxyHelperResponse {
let gate = SystemProxyReplyGate()
// 系统域 LaunchDaemon 的 MachService 注册在系统 launchd 命名空间;不带
// .privileged 的连接只在 per-user 域查找,永远失败。
let connection = NSXPCConnection(
machServiceName: SystemProxyHelperIdentity.machServiceName, options: .privileged)
defer { connection.invalidate() }
connection.remoteObjectInterface = NSXPCInterface(with: SystemProxyHelperControlling.self)
// 回调闭包必须显式 @Sendable(nonisolated):它们在 @MainActor 方法里形成,
// 传给非 @Sendable 的 Foundation 参数会被推断为主 actor 隔离,而 Foundation
// 在 XPC 内部队列上调起它们,Swift 6 动态隔离检查会让跨线程调用直接 trap。
// 闭包只捕获 Sendable 闸门,无需回主 actor。
connection.invalidationHandler = { @Sendable in
gate.finish(.failure(SystemProxyError.helperUnavailable("XPC 连接已失效")))
}
guard
let proxy = connection.remoteObjectProxyWithErrorHandler({ @Sendable (error: Error) in
gate.finish(.failure(SystemProxyError.helperUnavailable(String(describing: error))))
}) as? SystemProxyHelperControlling
else {
gate.finish(.failure(SystemProxyError.helperUnavailable("无法创建远程对象代理")))
return try await gate.wait()
}
connection.resume()
call(proxy) { payload in
gate.finish(Result { try SystemProxyHelperWire.decode(payload) })
}
// 超时兜底:已批准但卡死的 helper 不应让 UI 命令永久挂起;应答先到时取消。
let timeout = requestTimeoutNanoseconds
let timeoutTask = Task.detached(priority: .utility) {
do {
try await Task.sleep(nanoseconds: timeout)
} catch {
return
}
gate.finish(.failure(SystemProxyError.helperUnavailable("helper 应答超时")))
}
defer { timeoutTask.cancel() }
return try await gate.wait()
}
}
/// 一次性应答闸门:XPC 回调与超时兜底来自任意队列,只有第一个 finish 生效;
/// finish 先于 wait 到达时由闸门暂存结果。
private final class SystemProxyReplyGate: @unchecked Sendable {
private let lock = NSLock()
private var continuation: CheckedContinuation<SystemProxyHelperResponse, Error>?
private var result: Result<SystemProxyHelperResponse, Error>?
func finish(_ result: Result<SystemProxyHelperResponse, Error>) {
lock.lock()
if let continuation {
self.continuation = nil
lock.unlock()
continuation.resume(with: result)
return
}
if self.result == nil {
self.result = result
}
lock.unlock()
}
func wait() async throws -> SystemProxyHelperResponse {
try await withCheckedThrowingContinuation { continuation in
lock.lock()
if let result {
lock.unlock()
continuation.resume(with: result)
return
}
if self.continuation == nil {
self.continuation = continuation
lock.unlock()
return
}
lock.unlock()
continuation.resume(throwing: SystemProxyError.helperUnavailable("重复等待应答"))
}
}
}