mirror of
https://github.com/shadowsocks/ShadowsocksX-NG.git
synced 2026-11-23 14:24:12 +00:00
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.
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<string>com.qiuyuzhou.ShadowsocksX-NG2.agent</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>MacOS/ShadowsocksX-NG2Agent</string>
|
||||
<string>Contents/MacOS/ShadowsocksX-NG2Agent</string>
|
||||
</array>
|
||||
<key>ThrottleInterval</key>
|
||||
<integer>2</integer>
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user