Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Ask again when XPC turns away an update's old helper
Țugui Dragoș79d5fe912ff6
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 35ce411b..f70abd32 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -257,8 +257,10 @@ macOS asks the user to approve it once. It talks to the app over XPC.program or property list to register it again, or it may not launch. launchd starts `Contents/MacOS/PeelHelper`from the app as it is at that moment, under a spawn constraint that names only the team and the helper'sidentifier, so the next request runs the new helper, and a helper still running when an update replaced its- program quits as soon as it is idle (`HelperLifetime`). Until then it answers with its own version, so a helper- of another version is waited for until its process ends, and asked once more (`PrivilegedHelper.isResponding`).+ program quits as soon as it is idle (`HelperLifetime`). Until then it answers with its own version, or, once the+ update has deleted its program as Sparkle does, with an answer XPC turns away under the helper's code+ requirement, so Peel waits for that process to end, named by XPC or else by launchd, and asks once more+ (`PrivilegedHelper.isResponding`).That holds only while the helper's identifier and its launchd property list stay the same: a version thatchanges either has to register the helper again.- Any change to the helper means bumping `HelperIdentity.protocolVersion`, so Peel never works with a helper ofdiff --git a/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swift b/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swiftindex 2ca509b4..322a1ccf 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/ProcessEnds.swift@@ -12,6 +12,17 @@ public enum ProcessEnds {return proc_pidinfo(identifier, PROC_PIDTBSDINFO, 0, &info, size) == size}+ /// When the process started, as the kernel says, or nil when no such process runs. `sysctl` tells it of any+ /// process, root's included, while `proc_pidinfo` answers only about this account's.+ static func startTime(of identifier: pid_t) -> Date? {+ var info = kinfo_proc()+ var size = MemoryLayout<kinfo_proc>.size+ var name = [CTL_KERN, KERN_PROC, KERN_PROC_PID, identifier]+ guard sysctl(&name, u_int(name.count), &info, &size, nil, 0) == 0, size > 0 else { return nil }+ let start = info.kp_proc.p_un.__p_starttime+ return Date(timeIntervalSince1970: TimeInterval(start.tv_sec) + TimeInterval(start.tv_usec) / 1_000_000)+ }+/// Whether the process ends within `limit` seconds, true at once for one that has ended already. Any process may/// watch another one end, root's included (`kevent(2)`, EVFILT_PROC).public static func ends(_ identifier: pid_t, within limit: TimeInterval) async -> Bool {diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swiftindex 88add967..81215d7b 100644--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift@@ -7,6 +7,7 @@ enum Launchctl {var program: String?var managedBy: String?var parentBundleIdentifier: String?+ var pid: pid_t?}/// Runs `launchctl` and returns its exit status and its output, error text included. `bootout` waits for@@ -108,6 +109,7 @@ enum Launchctl {case "program": details.program = valuecase "managed_by": details.managedBy = valuecase "parent bundle identifier": details.parentBundleIdentifier = value+ case "pid": details.pid = pid_t(value)default: break}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swiftindex d460a32c..2ed1a797 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift@@ -164,23 +164,52 @@ public enum PrivilegedHelper {static func isResponding(connecting connect: @escaping @Sendable () -> NSXPCConnection?,waitingAtMost wait: TimeInterval = answerWait,+ runningHelper: @escaping @Sendable (Date, TimeInterval) async -> pid_t? = {+ await runningHelper(startedBefore: $0, within: $1)+ },untilEnded: @escaping @Sendable (pid_t, TimeInterval) async -> Bool = { await ProcessEnds.ends($0, within: $1) }) async -> Bool {let deadline = ContinuousClock.now.advanced(by: .seconds(wait))let left = { ContinuousClock.now.duration(to: deadline) / .seconds(1) }+ let asked = Date.nowlet first = await askVersion(connecting: connect, waitingAtMost: wait)- guard let version = first.value else { return false }- if version == HelperIdentity.protocolVersion { return true }- // A helper of another version is one an update left running: it leaves as soon as no connection is open- // (`HelperLifetime`), and launchd then starts the one this copy carries. Another copy's helper answers again.- guard let process = first.process, await untilEnded(process, left()) else { return false }+ if first.value == HelperIdentity.protocolVersion { return true }+ guard first.value != nil || first.wasRejected else { return false }+ // A helper of another version, or one XPC turns away because an update deleted its program, is one the update+ // left running: it leaves as soon as no connection is open (`HelperLifetime`), and launchd then starts the one+ // this copy carries. Another copy's helper keeps running.+ var process = first.process+ if process == nil { process = await runningHelper(asked, left()) }+ if let process {+ guard await untilEnded(process, left()) else { return false }+ }return await askVersion(connecting: connect, waitingAtMost: left()).value == HelperIdentity.protocolVersion}+ /// The process launchd runs the helper in, if it already ran when Peel asked at `date`: XPC names no process whose+ /// answer it turned away, launchd tells any account about a job of the system domain, and a process started later+ /// can't have answered, being the helper this copy carries, started for another question.+ @concurrent+ static func runningHelper(startedBefore date: Date, within limit: TimeInterval) async -> pid_t? {+ guard limit > 0, case .success(let output) = await Subprocess.run(+ "/bin/launchctl", ["print", "system/\(HelperIdentity.helperIdentifier)"], timeout: limit+ ) else { return nil }+ return process(in: Launchctl.answer(status: output.status, output: output.text), startedBefore: date)+ }++ static func process(+ in answer: Launchctl.Answer, startedBefore date: Date, startTime: (pid_t) -> Date? = ProcessEnds.startTime+ ) -> pid_t? {+ guard case .details(let details) = answer, let process = details.pid, let started = startTime(process),+ started < date+ else { return nil }+ return process+ }+private static func askVersion(connecting connect: @escaping @Sendable () -> NSXPCConnection?,waitingAtMost wait: TimeInterval- ) async -> (value: Int?, process: pid_t?) {+ ) async -> Reply<Int?> {await answer(connecting: connect, waitingAtMost: wait, fallback: nil) { helper, finish inhelper.protocolVersion { finish($0) }}@@ -357,42 +386,52 @@ public enum PrivilegedHelper {await answer(connecting: connect, waitingAtMost: wait, fallback: fallback, body).value}- /// `ask`, with the process that replied, which XPC knows once a message has come from it.+ private struct Reply<Value: Sendable>: Sendable {+ let value: Value+ /// The process that answered, which XPC names once it has accepted a message from it.+ let process: pid_t?+ /// Whether XPC turned the answer away, its sender not meeting this copy's requirement for the helper.+ let wasRejected: Bool+ }+private static func answer<T: Sendable>(connecting connect: @escaping @Sendable () -> NSXPCConnection?,waitingAtMost wait: TimeInterval,fallback: T,_ body: @escaping @Sendable (any PeelHelperProtocol, @escaping @Sendable (T) -> Void) -> Void- ) async -> (value: T, process: pid_t?) {+ ) async -> Reply<T> {// XPC delivers a reply at the quality its message went out with, and never while Peel keeps every thread at// that quality busy, so the message goes out at the timer's quality, whatever the task that asks.await Task.detached(priority: .userInitiated) {- guard let connection = connect() else { return (fallback, nil) }+ guard let connection = connect() else { return Reply(value: fallback, process: nil, wasRejected: false) }connection.remoteObjectInterface = remoteInterface()connection.resume()defer { connection.invalidate() }- let value = await withCheckedContinuation { continuation in+ let (value, wasRejected) = await withCheckedContinuation { continuation inlet once = ResumeOnce()- let finish: @Sendable (T) -> Void = { value in+ let finish: @Sendable (T, Bool) -> Void = { value, wasRejected inif once.claim() {- continuation.resume(returning: value)+ continuation.resume(returning: (value, wasRejected))}}// A helper that is running but never answers keeps the connection valid, and so does one launchd// keeps and cannot start, so only this timer ends the wait.- timers.asyncAfter(deadline: .now() + wait) { finish(fallback) }+ timers.asyncAfter(deadline: .now() + wait) { finish(fallback, false) }guard- let helper = connection.remoteObjectProxyWithErrorHandler({ _ in finish(fallback) })- as? any PeelHelperProtocol+ let helper = connection.remoteObjectProxyWithErrorHandler({ error in+ let error = error as NSError+ finish(fallback, error.domain == NSCocoaErrorDomain+ && error.code == NSXPCConnectionCodeSigningRequirementFailure)+ }) as? any PeelHelperProtocolelse {- finish(fallback)+ finish(fallback, false)return}- body(helper, finish)+ body(helper) { finish($0, false) }}let process = connection.processIdentifier- return (value, process > 0 ? process : nil)+ return Reply(value: value, process: process > 0 ? process : nil, wasRejected: wasRejected)}.value}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperAnswerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperAnswerTests.swiftindex 2db4e95b..74e10d19 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperAnswerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperAnswerTests.swift@@ -16,21 +16,35 @@ private final class StandInHelper: NSObject, VersionQuestion, NSXPCListenerDelegprivate let listener = NSXPCListener.anonymous()let handledAt = Mutex<UInt32?>(nil)let questions = Mutex(0)+ private let rejections: Record<Int>- convenience init(answering version: Int?) {- self.init(answering: [version])+ convenience init(answering version: Int?, rejectingFirst rejected: Int = 0) {+ self.init(answering: [version], rejectingFirst: rejected)}- init(answering versions: [Int?]) {+ init(answering versions: [Int?], rejectingFirst rejected: Int = 0) {self.versions = Mutex(versions)+ rejections = Record(rejected)super.init()listener.delegate = selflistener.resume()}+ /// Its first `rejected` connections require code no process has, so XPC turns their answers away, as it turns+ /// away an update's old helper once its program is gone.var connecting: @Sendable () -> NSXPCConnection? {let endpoint = listener.endpoint- return { NSXPCConnection(listenerEndpoint: endpoint) }+ let rejections = rejections+ return {+ let connection = NSXPCConnection(listenerEndpoint: endpoint)+ if rejections.value.withLock({ left in+ defer { left = max(0, left - 1) }+ return left > 0+ }) {+ connection.setCodeSigningRequirement("identifier \"org.example.nobody\"")+ }+ return connection+ }}func stop() {@@ -90,16 +104,82 @@ struct HelperAnswerTests {let helper = StandInHelper(answering: [HelperIdentity.protocolVersion - 1, HelperIdentity.protocolVersion])defer { helper.stop() }let watched = Record<[pid_t]>([])+ let lookedUp = Record(0)let answering = await PrivilegedHelper.isResponding(- connecting: helper.connecting, waitingAtMost: Self.anyWait- ) { process, _ in- watched.value.withLock { $0.append(process) }- return true- }+ connecting: helper.connecting, waitingAtMost: Self.anyWait,+ runningHelper: { _, _ in+ lookedUp.value.withLock { $0 += 1 }+ return nil+ },+ untilEnded: { process, _ in+ watched.value.withLock { $0.append(process) }+ return true+ }+ )++ #expect(answering)+ #expect(watched.value.withLock { $0 } == [getpid()])+ #expect(lookedUp.value.withLock { $0 } == 0)+ }++ @Test func aHelperWhoseAnswerIsTurnedAwayGivesWayToTheOneOfThisVersion() async {+ let helper = StandInHelper(answering: HelperIdentity.protocolVersion, rejectingFirst: 1)+ defer { helper.stop() }+ let before = Date.now+ let askedAt = Record<[Date]>([])+ let watched = Record<[pid_t]>([])++ let answering = await PrivilegedHelper.isResponding(+ connecting: helper.connecting, waitingAtMost: Self.anyWait,+ runningHelper: { asked, _ in+ askedAt.value.withLock { $0.append(asked) }+ return getpid()+ },+ untilEnded: { process, _ in+ watched.value.withLock { $0.append(process) }+ return true+ }+ )#expect(answering)+ #expect(helper.questions.withLock { $0 } == 2)#expect(watched.value.withLock { $0 } == [getpid()])+ #expect(askedAt.value.withLock { $0 }.allSatisfy { $0 >= before && $0 <= .now })+ #expect(askedAt.value.withLock { $0.count } == 1)+ }++ @Test func aHelperTurnedAwayIsAskedAgainAtOnceWhenNoProcessRunsIt() async {+ let helper = StandInHelper(answering: HelperIdentity.protocolVersion, rejectingFirst: 1)+ defer { helper.stop() }+ let watched = Record<[pid_t]>([])++ let answering = await PrivilegedHelper.isResponding(+ connecting: helper.connecting, waitingAtMost: Self.anyWait,+ runningHelper: { _, _ in nil },+ untilEnded: { process, _ in+ watched.value.withLock { $0.append(process) }+ return true+ }+ )++ #expect(answering)+ #expect(helper.questions.withLock { $0 } == 2)+ #expect(watched.value.withLock { $0 }.isEmpty)+ }++ @Test func aHelperTurnedAwayWhoseProcessKeepsRunningIsNotAnswering() async {+ let helper = StandInHelper(answering: HelperIdentity.protocolVersion, rejectingFirst: 1)+ defer { helper.stop() }++ let answering = await PrivilegedHelper.isResponding(+ connecting: helper.connecting, waitingAtMost: Self.anyWait,+ runningHelper: { _, _ in getpid() },+ untilEnded: { _, _ in false }+ )++ #expect(!answering)+ #expect(helper.questions.withLock { $0 } == 1)}@Test func aHelperOfAnotherVersionIsAskedOnceMoreOnceItsProcessEnds() async {@@ -107,8 +187,8 @@ struct HelperAnswerTests {defer { helper.stop() }let answering = await PrivilegedHelper.isResponding(- connecting: helper.connecting, waitingAtMost: Self.anyWait- ) { _, _ in true }+ connecting: helper.connecting, waitingAtMost: Self.anyWait, untilEnded: { _, _ in true }+ )#expect(!answering)#expect(helper.questions.withLock { $0 } == 2)@@ -119,13 +199,26 @@ struct HelperAnswerTests {defer { helper.stop() }let answering = await PrivilegedHelper.isResponding(- connecting: helper.connecting, waitingAtMost: Self.anyWait- ) { _, _ in false }+ connecting: helper.connecting, waitingAtMost: Self.anyWait, untilEnded: { _, _ in false }+ )#expect(!answering)#expect(helper.questions.withLock { $0 } == 1)}+ @Test func onlyTheProcessThatRanTheHelperBeforePeelAskedCanHaveAnswered() {+ let asked = Date(timeIntervalSince1970: 1_000_000)+ let running = Launchctl.Answer.details(Launchctl.JobDetails(path: "(submitted by smd.92)", pid: 5236))+ let stopped = Launchctl.Answer.details(Launchctl.JobDetails(path: "(submitted by smd.92)"))++ #expect(PrivilegedHelper.process(in: running, startedBefore: asked) { _ in asked - 60 } == 5236)+ #expect(PrivilegedHelper.process(in: running, startedBefore: asked) { _ in asked + 1 } == nil)+ #expect(PrivilegedHelper.process(in: running, startedBefore: asked) { _ in nil } == nil)+ #expect(PrivilegedHelper.process(in: stopped, startedBefore: asked) { _ in asked - 60 } == nil)+ #expect(PrivilegedHelper.process(in: .gone, startedBefore: asked) { _ in asked - 60 } == nil)+ #expect(PrivilegedHelper.process(in: .unreadable, startedBefore: asked) { _ in asked - 60 } == nil)+ }+@Test func withNoConnectionThereIsNoAnswer() async {#expect(await !PrivilegedHelper.isResponding(connecting: { nil }))}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swiftindex 45278901..73aa7e5f 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LaunchctlTests.swift@@ -89,6 +89,32 @@ struct LaunchctlTests {#expect(details.path == "(submitted by smd.524)")}+ @Test func readsTheProcessOfAJobThatRuns() throws {+ let printed = """+ system/org.example.helper = {+ \tactive count = 1+ \tpath = (submitted by smd.92)+ \ttype = Submitted+ \tmanaged_by = com.apple.xpc.ServiceManagement+ \tstate = running+ \tprogram identifier = Contents/MacOS/Helper (mode: 2)+ \tparent bundle identifier = org.example.app+ \tdomain = system+ \truns = 7+ \tpid = 5236+ \tlast exit code = 0+ \tendpoints = {+ \t\t"org.example.helper" = {+ \t\t\tport = 0x3d03+ \t\t\tactive = 1+ \t\t}+ \t}+ }+ """++ #expect(try #require(Launchctl.parseDetails(printed)).pid == 5236)+ }+@Test func tellsAJobThatLeftFromAnAnswerItCannotRead() {let printed = """gui/501/org.example.updater = {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swiftindex e17599ab..fd8eb322 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/ProcessEndsTests.swift@@ -132,6 +132,33 @@ struct ProcessEndsTests {#expect(await !ProcessEnds.ends(program.processIdentifier, within: 0.1))}+ @Test func knowsWhenAProgramStarted() throws {+ let before = Date.now+ let directory = try TemporaryDirectory()+ let program = try directory.runningProgram("Example.app/Contents/MacOS/example")+ defer { program.terminate() }++ let started = try #require(ProcessEnds.startTime(of: program.processIdentifier))++ #expect(started >= before && started <= .now)+ }++ @Test func knowsWhenAProcessOfAnotherAccountStarted() throws {+ // launchd, root's, is process 1 on every Mac.+ let started = try #require(ProcessEnds.startTime(of: 1))++ #expect(started < .now)+ }++ @Test func knowsNoStartOfAProgramThatHasEnded() throws {+ let directory = try TemporaryDirectory()+ let program = try directory.runningProgram("Example.app/Contents/MacOS/example")+ program.terminate()+ program.waitUntilExit()++ #expect(ProcessEnds.startTime(of: program.processIdentifier) == nil)+ }+@Test func finishesAtOnceWithNoProgramToWatch() async {#expect(await collect(ProcessEnds.of([0, -1]), within: 1) == [])}