From 2acaef60c820b7c1704369a81ef2c91ab4d224b6 Mon Sep 17 00:00:00 2001 From: Qiu Yuzhou Date: Sat, 26 Sep 2026 23:32:42 +0800 Subject: [PATCH] fix(agent): register LaunchAgent via launchctl bootstrap with absolute path SMAppService does not resolve relative ProgramArguments paths reliably when the app runs from DerivedData or other non-/Applications locations (launchd reports inferred program + partial import and rejects spawn with EX_CONFIG). The same binary and plist format work correctly when registered via launchctl bootstrap with an absolute path. Write the plist to ~/Library/LaunchAgents/ with the wrapper's absolute path and register via launchctl bootstrap. Keep SMAppService only for reading BTM approval status. --- ShadowsocksX-NG2/App/LaunchAgentService.swift | 102 +++++++++++------- ...com.qiuyuzhou.ShadowsocksX-NG2.agent.plist | 2 +- ShadowsocksX-NG2/project.yml | 6 +- 3 files changed, 68 insertions(+), 42 deletions(-) diff --git a/ShadowsocksX-NG2/App/LaunchAgentService.swift b/ShadowsocksX-NG2/App/LaunchAgentService.swift index fc66050f..3a4b84ed 100644 --- a/ShadowsocksX-NG2/App/LaunchAgentService.swift +++ b/ShadowsocksX-NG2/App/LaunchAgentService.swift @@ -2,68 +2,94 @@ import Foundation import ServiceManagement /// LaunchAgent 管理缝(spec #21 D2):控制器经此协议启停 agent,单元测试以 -/// fake 替换(真实 SMAppService 注册会改动用户登录项,不进单测)。 +/// fake 替换(真实注册会改动用户登录项,不进单测)。 protocol LaunchAgentControlling { var status: LaunchAgentStatus { get } func register() throws func unregister() throws } -/// 生产实现:注册时从 bundle 内模板 plist 生成带绝对 ProgramArguments 的 -/// 临时 plist,写入 `Contents/Library/LaunchAgents/` 后交给 SMAppService。 -/// SMAppService 对相对路径的 `ProgramArguments` 解析不可靠(launchd 显示 -/// `inferred program` + `partial import` 并以 EX_CONFIG 拒绝 spawn), -/// 因此注册前把 wrapper 可执行文件的绝对路径写入 plist。 +/// 生产实现。用 `launchctl bootstrap` 注册 `~/Library/LaunchAgents/` 下带 +/// 绝对路径的 plist(SMAppService 对相对 ProgramArguments 的解析在 +/// DerivedData 等非 /Applications 路径下不可靠,launchd 报 `inferred +/// program` + `partial import` 并以 EX_CONFIG 拒绝 spawn)。SMAppService +/// 仅用于读取 BTM 批准状态;批准流仍走系统设置 → 登录项。 struct SMAppLaunchAgentService: LaunchAgentControlling { - static let plistName = "com.qiuyuzhou.ShadowsocksX-NG2.agent.plist" + static let label = "com.qiuyuzhou.ShadowsocksX-NG2.agent" - private let service = SMAppService.agent(plistName: Self.plistName) + private let service = SMAppService.agent( + plistName: "com.qiuyuzhou.ShadowsocksX-NG2.agent.plist") var status: LaunchAgentStatus { + if isLoadedInLaunchd { return .registered } switch service.status { - case .notRegistered: - return .notRegistered - case .enabled: - return .registered case .requiresApproval: return .requiresApproval - case .notFound: - return .notFound - @unknown default: - return .notFound + case .enabled: + return .registered + default: + return .notRegistered } } func register() throws { - try rewritePlistWithAbsoluteProgramPath() - try service.register() + try writeUserPlist() + try runLaunchctl(["bootstrap", "gui/\(getuid())", userPlistURL.path]) } func unregister() throws { - try service.unregister() + _ = try? runLaunchctl(["bootout", "gui/\(getuid())/\(Self.label)"]) + try? FileManager.default.removeItem(at: userPlistURL) } - /// 把 bundle 内 plist 的 ProgramArguments[0] 重写为 wrapper 的绝对路径。 - /// 只在注册前调用;卸载不要求还原。 - private func rewritePlistWithAbsoluteProgramPath() throws { - let bundle = Bundle.main.bundleURL - let plistURL = bundle.appendingPathComponent( - "Contents/Library/LaunchAgents/\(Self.plistName)") - let agentURL = bundle.appendingPathComponent("Contents/MacOS/ShadowsocksX-NG2Agent") - guard - let data = try? Data(contentsOf: plistURL), - var plist = try? PropertyListSerialization.propertyList(from: data, format: nil) - as? [String: Any] - else { - throw LaunchAgentPlistError.unreadable - } - plist["ProgramArguments"] = [agentURL.path] - let updated = try PropertyListSerialization.data( + // MARK: - Implementation + + private var userPlistURL: URL { + FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/LaunchAgents/\(Self.label).plist") + } + + private var agentBinaryURL: URL { + Bundle.main.bundleURL.appendingPathComponent("Contents/MacOS/ShadowsocksX-NG2Agent") + } + + private var isLoadedInLaunchd: Bool { + (try? runLaunchctl(["print", "gui/\(getuid())/\(Self.label)"])) != nil + } + + private func writeUserPlist() throws { + let plist: [String: Any] = [ + "Label": Self.label, + "ProgramArguments": [agentBinaryURL.path], + "KeepAlive": ["SuccessfulExit": false], + "ThrottleInterval": 2, + ] + let data = try PropertyListSerialization.data( fromPropertyList: plist, format: .xml, options: 0) - try updated.write(to: plistURL, options: .atomic) + try FileManager.default.createDirectory( + at: userPlistURL.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: userPlistURL, options: .atomic) + } + + @discardableResult + private func runLaunchctl(_ arguments: [String]) throws -> String { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/launchctl") + process.arguments = arguments + let stderr = Pipe() + process.standardError = stderr + try process.run() + process.waitUntilExit() + let errorOutput = + String( + data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" + guard process.terminationStatus == 0 else { + throw LaunchAgentRegistrationError.launchctlFailed(errorOutput) + } + return errorOutput } } -enum LaunchAgentPlistError: Error, Equatable { - case unreadable +enum LaunchAgentRegistrationError: Error, Equatable { + case launchctlFailed(String) } diff --git a/ShadowsocksX-NG2/LaunchAgent/com.qiuyuzhou.ShadowsocksX-NG2.agent.plist b/ShadowsocksX-NG2/LaunchAgent/com.qiuyuzhou.ShadowsocksX-NG2.agent.plist index 8c54a042..746b222b 100644 --- a/ShadowsocksX-NG2/LaunchAgent/com.qiuyuzhou.ShadowsocksX-NG2.agent.plist +++ b/ShadowsocksX-NG2/LaunchAgent/com.qiuyuzhou.ShadowsocksX-NG2.agent.plist @@ -11,7 +11,7 @@ com.qiuyuzhou.ShadowsocksX-NG2.agent ProgramArguments - MacOS/ShadowsocksX-NG2Agent + Contents/MacOS/ShadowsocksX-NG2Agent ThrottleInterval 2 diff --git a/ShadowsocksX-NG2/project.yml b/ShadowsocksX-NG2/project.yml index 60a5d4d0..2bab6ac2 100644 --- a/ShadowsocksX-NG2/project.yml +++ b/ShadowsocksX-NG2/project.yml @@ -24,8 +24,8 @@ targets: # 领域核心:配置目录树、凭据引用与持久化(spec #21 D3/D5) - path: Domain # LaunchAgent 注册清单:SMAppService.agent(plistName:) 从 bundle 内 - # Contents/Library/LaunchAgents/ 读取;ProgramArguments 用 Contents/ - # 相对路径(launchd 按注册 app 的 Contents/ 解析,spec #21 D2,issue #27)。 + # Contents/Library/LaunchAgents/ 读取;ProgramArguments 用 bundle 相对路径 + # (spec #21 D2,issue #27)。 - path: LaunchAgent/com.qiuyuzhou.ShadowsocksX-NG2.agent.plist buildPhase: copyFiles: @@ -97,7 +97,7 @@ targets: - ShadowsocksX-NG2Tests dependencies: # 代理运行时 wrapper(BundleProgram,spec #21 D2):以独立可执行文件装入 - # Contents/MacOS,由 LaunchAgent plist 以 Contents/ 相对路径引用。 + # Contents/MacOS,由 LaunchAgent plist 以 bundle 相对路径引用。 - target: ShadowsocksX-NG2Agent copy: destination: wrapper