Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Let an old helper leave as soon as an update replaced it

Țugui Dragoș266a9c684fdd
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 07975278..ea4c9921 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -172,8 +172,13 @@ macOS asks the user to approve it once. It talks to the app over XPC.
- It keeps a ledger of what it moved, in a folder only root can write (`/private/var/db/com.tuguidragos.Peel.Helper`),
and puts back only what that ledger knows. While the ledger can't be read it moves nothing, and one it can't make
sense of is kept under another name (`DamagedFile`), never written over.
-- Any change to the helper means bumping `HelperIdentity.protocolVersion`, which asks users to install the
- helper again.
+- An update needs nothing from the person. 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's identifier, 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`). That holds while the helper's identifier and its launchd property list stay the same: a
+ version that changes either has to register the helper again (`SMAppService.h`).
+- Any change to the helper means bumping `HelperIdentity.protocolVersion`, so Peel never works with a helper of
+ another version.
## The app
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 7e5927e7..22e5c5b1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -226,8 +226,9 @@ disk that somebody may have replaced.
- It never uses a path again after checking it. It opens the folder, checks the item there as the kernel names
the folder (`F_GETPATH`), works only through that descriptor, and moves the item only while its identity is the
one it checked, so a folder or an item swapped after the check leads nowhere.
-- A new operation needs `PrivilegedPathPolicyTests`, and any change to the helper a protocol version bump,
- which asks every user to install the helper again. That cost is deliberate.
+- A new operation needs `PrivilegedPathPolicyTests`, and any change to the helper a protocol version bump, so
+ Peel never works with a helper of another version. An update asks nothing of the person while the helper's
+ identifier and its launchd property list stay the same; a change to either means registering the helper again.
If you are unsure whether something belongs in the helper, it doesn't. The helper should stay small enough to
read in one sitting.
diff --git a/GUIDE.md b/GUIDE.md
index 3f04ab74..9296f890 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -230,7 +230,7 @@ and takes you straight to the right place in System Settings.
|---|---|
| Full Disk Access | Look inside the Trash and the private folders where apps keep their data. Without it, Peel can't find everything an app leaves behind. |
| App Management | Move another developer's app to the Trash. Without it, Peel can still clear an app's files, but macOS may refuse to move the app itself. |
-| Helper | Move the leftovers that sit in folders only an administrator can change, and put them back, and start, stop, enable, or disable other developers' background items that run as root. It answers administrators only. macOS asks you to approve it in Login Items & Extensions, and an update of Peel that changes the helper asks you to install it again. |
+| Helper | Move the leftovers that sit in folders only an administrator can change, and put them back, and start, stop, enable, or disable other developers' background items that run as root. It answers administrators only. macOS asks you to approve it once in Login Items & Extensions, and an update of Peel brings its new helper with it. |
| Notifications (optional) | Tell you when your apps have updates, when Homebrew finishes an upgrade or runs into a problem, when your disk is almost full if you turn that warning on, and, with Watch the Trash on, when you move an app to the Trash yourself. |
| Folders macOS asks about | Without Full Disk Access, macOS asks the first time Peel looks in Desktop, Documents, or Downloads for installers, duplicates, and what builds left, inside another app's data for what it would leave behind, or at your cloud folders to measure them. |
| Finder extension (optional) | Add Uninstall with Peel to the menu you get when you Control-click an app in Finder. |
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift
index 440bd300..5806f15f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift
@@ -66,7 +66,7 @@ struct OpenFiles {
/// The program a process runs, unless it is an app extension: macOS starts and ends those on their app's behalf,
/// so the person could not quit one to let its app go.
private static func program(of pid: pid_t) -> String? {
- guard let path = path(of: pid) else { return nil }
+ guard let path = RunningProgram.path(of: pid) else { return nil }
return PathComponents.of(path).contains { $0.hasSuffix(".appex") } ? nil : path
}
@@ -74,14 +74,8 @@ struct OpenFiles {
static func name(of pid: pid_t) -> String {
var buffer = [CChar](repeating: 0, count: 2 * Int(MAXCOMLEN) + 1)
guard proc_name(pid, &buffer, UInt32(buffer.count)) > 0 else {
- return path(of: pid).map { URL(filePath: $0).lastPathComponent } ?? "process \(pid)"
+ return RunningProgram.path(of: pid).map { URL(filePath: $0).lastPathComponent } ?? "process \(pid)"
}
return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)
}
-
- private static func path(of pid: pid_t) -> String? {
- var buffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
- guard proc_pidpath(pid, &buffer, UInt32(buffer.count)) > 0 else { return nil }
- return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)
- }
}
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
index 91af2904..568df368 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
@@ -5,9 +5,9 @@ public enum HelperIdentity {
public static let helperIdentifier = "com.tuguidragos.Peel.Helper"
public static let machServiceName = "com.tuguidragos.Peel.Helper"
public static let launchdPlistName = "com.tuguidragos.Peel.Helper.plist"
- /// Raise it whenever the helper changes, so Peel asks for the helper to be installed again rather than work with
- /// an older one. The helper refuses requests that carry any other version.
- public static let protocolVersion = 13
+ /// Raise it whenever the helper changes, so Peel never works with a helper of another version. The helper
+ /// refuses requests that carry any other version.
+ public static let protocolVersion = 14
}
/// The complete set of privileged operations. The helper validates every argument itself.
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift
index e8a6b34d..c8b5ff0a 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift
@@ -5,6 +5,9 @@ import Synchronization
/// launchd starts it again on the next request.
public final class HelperLifetime: Sendable {
private let idleTimeout: TimeInterval
+ /// Where the helper's program was when it started, and the file that was there. An update puts another file
+ /// there, which launchd starts at the next request, so a helper whose file was replaced leaves once it is idle.
+ private let program: (path: String, identity: ItemIdentity)?
private let schedule: @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void
private let exit: @Sendable () -> Void
private let state = Mutex((activeConnections: 0, requestsInFlight: 0, generation: 0))
@@ -15,6 +18,7 @@ public final class HelperLifetime: Sendable {
public convenience init() {
self.init(
idleTimeout: Self.standardIdleTimeout,
+ program: RunningProgram.path(of: getpid()),
schedule: { delay, work in DispatchQueue.global().asyncAfter(deadline: .now() + delay, execute: work) },
// `_exit`, not `exit`: `exit` would first run `atexit` handlers, while the helper's other threads keep
// running.
@@ -24,10 +28,12 @@ public final class HelperLifetime: Sendable {
init(
idleTimeout: TimeInterval,
+ program: String?,
schedule: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void,
exit: @escaping @Sendable () -> Void
) {
self.idleTimeout = idleTimeout
+ self.program = program.flatMap { path in ItemIdentity(ofItemAt: path).map { (path, $0) } }
self.schedule = schedule
self.exit = exit
}
@@ -82,7 +88,8 @@ public final class HelperLifetime: Sendable {
/// has changed since `generation`. The check and the exit happen under one lock, so no connection can open
/// between them and have its work cut off.
private func scheduleExitIfIdle(generation: Int) {
- schedule(idleTimeout) { [self] in
+ let isReplaced = program.map { ItemIdentity(ofItemAt: $0.path) != $0.identity } ?? false
+ schedule(isReplaced ? 0 : idleTimeout) { [self] in
state.withLock { state in
if state.activeConnections == 0, state.requestsInFlight == 0, state.generation == generation {
exit()
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/RunningProgram.swift b/Packages/PeelCore/Sources/PeelPrivileged/RunningProgram.swift
new file mode 100644
index 00000000..dc2cd8ef
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelPrivileged/RunningProgram.swift
@@ -0,0 +1,9 @@
+public import Darwin
+
+public enum RunningProgram {
+ public static func path(of pid: pid_t) -> String? {
+ var buffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
+ guard proc_pidpath(pid, &buffer, UInt32(buffer.count)) > 0 else { return nil }
+ return String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift
index aeb72533..a7cb04a4 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift
@@ -7,12 +7,17 @@ struct HelperLifetimeTests {
/// Holds each scheduled idle check until the test runs it, so the order is the test's and never the clock's.
private final class Clock: Sendable {
private let pending = Mutex<[@Sendable () -> Void]>([])
+ let delays = Mutex<[TimeInterval]>([])
let exits = Mutex(0)
- func lifetime() -> HelperLifetime {
+ func lifetime(program: String? = nil) -> HelperLifetime {
HelperLifetime(
idleTimeout: 30,
- schedule: { [self] _, work in pending.withLock { $0.append(work) } },
+ program: program,
+ schedule: { [self] delay, work in
+ delays.withLock { $0.append(delay) }
+ pending.withLock { $0.append(work) }
+ },
exit: { [self] in exits.withLock { $0 += 1 } }
)
}
@@ -33,6 +38,7 @@ struct HelperLifetimeTests {
clock.lifetime().start()
clock.runChecks()
#expect(clock.exitCount == 1)
+ #expect(clock.delays.withLock { $0 } == [30])
}
@Test func staysWhileARequestRunsAndExitsAfterIt() {
@@ -80,4 +86,48 @@ struct HelperLifetimeTests {
clock.runChecks()
#expect(clock.exitCount == 1, "a refused connection kept the helper running")
}
+
+ @Test func leavesAsSoonAsItIsIdleOnceAnUpdateReplacedItsProgram() throws {
+ let folder = try TemporaryDirectory()
+ let program = try folder.file("Peel.app/Contents/MacOS/PeelHelper")
+ let update = try folder.file("Update/PeelHelper")
+ let clock = Clock()
+ let lifetime = clock.lifetime(program: program.path)
+ lifetime.start()
+ #expect(lifetime.accept { true })
+ #expect(rename(update.path, program.path) == 0)
+
+ lifetime.connectionClosed()
+
+ #expect(clock.delays.withLock { $0 } == [30, 0])
+ clock.runChecks()
+ #expect(clock.exitCount == 1)
+ }
+
+ @Test func leavesAsSoonAsItIsIdleOnceItsProgramIsGone() throws {
+ let folder = try TemporaryDirectory()
+ let program = try folder.file("Peel.app/Contents/MacOS/PeelHelper")
+ let clock = Clock()
+ let lifetime = clock.lifetime(program: program.path)
+ lifetime.start()
+ #expect(lifetime.accept { true })
+ try FileManager.default.removeItem(at: folder.url.appending(path: "Peel.app"))
+
+ lifetime.connectionClosed()
+
+ #expect(clock.delays.withLock { $0 } == [30, 0])
+ }
+
+ @Test func waitsWhileItsProgramStaysInPlace() throws {
+ let folder = try TemporaryDirectory()
+ let program = try folder.file("Peel.app/Contents/MacOS/PeelHelper")
+ let clock = Clock()
+ let lifetime = clock.lifetime(program: program.path)
+ lifetime.start()
+ #expect(lifetime.accept { true })
+
+ lifetime.connectionClosed()
+
+ #expect(clock.delays.withLock { $0 } == [30, 30])
+ }
}
diff --git a/PeelHelper/HelperService.swift b/PeelHelper/HelperService.swift
index b2641c04..92d31888 100644
--- a/PeelHelper/HelperService.swift
+++ b/PeelHelper/HelperService.swift
@@ -24,12 +24,8 @@ final class HelperService: NSObject, PeelHelperProtocol {
}
/// The `peel` tool of the app the helper runs from, found from the program the kernel says it runs.
- private static let ownTool: String? = {
- var buffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
- guard proc_pidpath(getpid(), &buffer, UInt32(buffer.count)) > 0 else { return nil }
- let path = String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)
- return PrivilegedPathPolicy.peelTool(besideHelperAt: path)
- }()
+ private static let ownTool = RunningProgram.path(of: getpid())
+ .flatMap(PrivilegedPathPolicy.peelTool(besideHelperAt:))
private func tracked(_ finish: @escaping @Sendable (String?) -> Void) -> @Sendable (String?) -> Void {
{ [lifetime] answer in
diff --git a/SAFETY.md b/SAFETY.md
index a5d4b020..af7bddba 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -401,8 +401,8 @@ and it fails closed.
PrivilegedHelperTools, and StartupItems) and the 22 that hold plug-ins; the installer receipts in
`/private/var/db/receipts`; the links in `/usr/local/bin`, `/usr/local/sbin`, and the four folders of
`/usr/local` that shell completions are linked into; and the Library of the administrator who asks.
-- It takes at most 100 items in one request, and quits 30 seconds after its last request ends, so it isn't
- left running.
+- It takes at most 100 items in one request, and quits 30 seconds after its last request ends, or as soon as
+ it is idle once an update has replaced it, so it isn't left running.
- A path with a control character in it is refused. The rules read the whole name and the system stops at
the first zero byte, so such a name would be checked as one thing and moved as another.
- It starts, stops, enables, and disables launch daemons only for other vendors. What macOS ships is