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.

Ask launchd about a background agent in the domain it runs in

Țugui Dragoș1dbee8a61393
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
index 9bb640e7..508e6ff5 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
@@ -37,18 +37,21 @@ public enum BackgroundItems {
async let userList = Launchctl.run(["list"])
async let systemPrint = Launchctl.run(["print", "system"])
async let userDisabledOutput = Launchctl.run(["print-disabled", userDomain])
+ // `launchctl list` names the jobs of the user's own domain too, which launchd keeps apart from the GUI one.
+ async let userDomainPrint = Launchctl.run(["print", "user/\(getuid())"])
let systemOutput = await systemPrint.output
let loaded = Loaded(
user: Launchctl.parseList(await userList.output),
system: Launchctl.parseSystemServices(systemOutput),
userDisabled: Launchctl.parseDisabled(await userDisabledOutput.output),
- systemDisabled: Launchctl.parseDisabled(systemOutput)
+ systemDisabled: Launchctl.parseDisabled(systemOutput),
+ inTheUserDomain: Launchctl.parseSystemServices(await userDomainPrint.output).map { Set($0.keys) }
)
var items = declared(in: environment, ownership: ownership, exclusions: exclusions, loaded: loaded)
- let submitted = undeclared(in: loaded, declared: items, userDomain: userDomain)
+ let submitted = undeclared(in: loaded, declared: items, uid: getuid())
let found = await withTaskGroup(of: Undeclared.self) { group in
var pending = submitted.makeIterator()
@@ -103,12 +106,14 @@ public enum BackgroundItems {
static func undeclared(
in loaded: Loaded,
declared items: [BackgroundItem],
- userDomain: String
+ uid: uid_t
) -> [(label: String, kind: BackgroundItem.Kind, target: String)] {
// By kind and label: an item's `id` also holds its file's path, which a loaded job does not report.
let known = Set(items.map { "\($0.kind.rawValue)/\($0.label)" })
let candidates: [(label: String, kind: BackgroundItem.Kind, target: String)] =
- (loaded.user ?? [:]).keys.map { ($0, .agent, "\(userDomain)/\($0)") }
+ (loaded.user ?? [:]).keys.map { label in
+ (label, .agent, "\(loaded.isInTheUserDomain(label) ? "user" : "gui")/\(uid)/\(label)")
+ }
+ (loaded.system ?? [:]).keys.map { ($0, .daemon, "system/\($0)") }
return candidates.filter { label, kind, _ in
!label.hasPrefix("com.apple.") && !label.hasPrefix("application.") && !known.contains("\(kind.rawValue)/\(label)")
@@ -162,6 +167,12 @@ public enum BackgroundItems {
var system: [String: Int32?]? = [:]
var userDisabled: [String: Bool]? = [:]
var systemDisabled: [String: Bool]? = [:]
+ /// The agents launchd keeps in the user's own domain rather than the GUI one, which are asked about there.
+ var inTheUserDomain: Set<String>? = []
+
+ func isInTheUserDomain(_ label: String) -> Bool {
+ inTheUserDomain?.contains(label) == true
+ }
/// The state of the job `label` of `kind`, known only when what `launchctl` said about both the jobs and
/// the overrides of its domain could be read.
@@ -183,7 +194,7 @@ public enum BackgroundItems {
/// known only from them, may be missing.
var unanswered: Set<BackgroundItem.Kind> {
var kinds: Set<BackgroundItem.Kind> = []
- if user == nil || userDisabled == nil { kinds.insert(.agent) }
+ if user == nil || userDisabled == nil || inTheUserDomain == nil { kinds.insert(.agent) }
if system == nil || systemDisabled == nil { kinds.insert(.daemon) }
return kinds
}
@@ -340,6 +351,7 @@ public enum BackgroundItems {
item.isSystemExtension = program.map { PathComponents.isPath($0, inside: "/Library/SystemExtensions") } == true
item.isManagedByServiceManagement = details.managedBy == serviceManagement
item.isFileGone = !isAnApps && path?.isMissing == true
+ item.loadsInTheBackgroundSession = candidate.kind == .agent && loaded.isInTheUserDomain(candidate.label)
if isAnApps, item.canBeControlled, !item.isManagedByServiceManagement {
item.staysListedWhenDisabled =
ownership.owner(label: candidate.label, associated: [], program: nil)?.isInstalled == true
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
index 81215d7b..5cd45095 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/Launchctl.swift
@@ -35,8 +35,8 @@ enum Launchctl {
return jobs
}
- /// Parses the "services = { … }" block of `launchctl print system`: "pid exit-status label". Nil when there is
- /// no such block.
+ /// Parses the "services = { … }" block `launchctl print` gives for a domain, the system's or a user's: "pid
+ /// exit-status label". Nil when there is no such block.
static func parseSystemServices(_ output: String) -> [String: Int32?]? {
var jobs: [String: Int32?]?
for line in output.split(whereSeparator: \.isNewline) {
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
index 2e4df496..74256a03 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
@@ -7,6 +7,9 @@ enum LaunchdCleanup {
let isDaemon: Bool
/// The file that declares it.
let plist: URL
+ var loadsInTheBackgroundSession = false
+
+ var domain: String { LaunchdCleanup.domain(isDaemon: isDaemon, background: loadsInTheBackgroundSession) }
}
/// A job launchd runs now whose program sits inside an app: one of the app's own background programs. `plist` is
@@ -16,8 +19,24 @@ enum LaunchdCleanup {
let isDaemon: Bool
let pid: pid_t
let plist: URL?
+ var loadsInTheBackgroundSession = false
+
+ var domain: String { LaunchdCleanup.domain(isDaemon: isDaemon, background: loadsInTheBackgroundSession) }
- var job: Job? { plist.map { Job(label: label, isDaemon: isDaemon, plist: $0) } }
+ var job: Job? {
+ plist.map {
+ Job(
+ label: label, isDaemon: isDaemon, plist: $0,
+ loadsInTheBackgroundSession: loadsInTheBackgroundSession
+ )
+ }
+ }
+ }
+
+ /// A daemon's domain is the system's; an agent's is the GUI one, or the user's own for one that loads only in the
+ /// Background session (`man launchctl`: the two "still have discrete sets of services").
+ static func domain(isDaemon: Bool, background: Bool) -> String {
+ isDaemon ? "system" : background ? "user/\(getuid())" : "gui/\(getuid())"
}
/// Stops jobs whose configuration has gone, so launchd doesn't keep them running or restart them, and answers
@@ -25,19 +44,21 @@ enum LaunchdCleanup {
@concurrent
static func stop(_ jobs: [Job], canUseHelper: Bool) async -> [Job] {
var stopped: [Job] = []
- for job in jobs where await bootout(job.label, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {
+ for job in jobs
+ where await bootout(job.label, in: job.domain, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {
stopped.append(job)
}
return stopped
}
- /// The jobs running now, in this user's domain and the system's, whose program sits inside `app`. An app Launch
+ /// The jobs running now, in this user's domains and the system's, whose program sits inside `app`. An app Launch
/// Services opened is a job too (`application.`), which is quit as an app and never stopped as a job.
@concurrent
static func running(inside app: URL, environment: SearchEnvironment = .current) async -> [Running] {
let bundle = PathPattern.comparablePath(of: PathPattern.canonical(app))
var found: [Running] = []
- for (domain, isDaemon) in [("gui/\(getuid())", false), ("system", true)] {
+ for (isDaemon, background) in [(false, false), (false, true), (true, false)] {
+ let domain = domain(isDaemon: isDaemon, background: background)
let services = Launchctl.parseSystemServices(await Launchctl.run(["print", domain]).output) ?? [:]
for case let (label, pid?) in services where isAppsOwn(label) {
guard let program = RunningProgram.path(of: pid),
@@ -45,7 +66,9 @@ enum LaunchdCleanup {
else { continue }
let path = Launchctl.parseDetails(await Launchctl.run(["print", "\(domain)/\(label)"]).output)?.path
let plist = path.flatMap { jobs(for: [URL(filePath: $0)], environment: environment).first?.plist }
- found.append(Running(label: label, isDaemon: isDaemon, pid: pid, plist: plist))
+ found.append(Running(
+ label: label, isDaemon: isDaemon, pid: pid, plist: plist, loadsInTheBackgroundSession: background
+ ))
}
}
return found
@@ -56,7 +79,8 @@ enum LaunchdCleanup {
static func stop(_ jobs: [Running], canUseHelper: Bool, patience: Duration = .seconds(10)) async -> [Running] {
let ends = ProcessEnds.of(jobs.map(\.pid))
var stopped: [Running] = []
- for job in jobs where await bootout(job.label, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {
+ for job in jobs
+ where await bootout(job.label, in: job.domain, isDaemon: job.isDaemon, canUseHelper: canUseHelper) {
stopped.append(job)
}
await withTaskGroup(of: Void.self) { group in
@@ -73,12 +97,12 @@ enum LaunchdCleanup {
&& !SystemDaemons.shipped.contains(label) && !SystemAgents.shipped.contains(label)
}
- private static func bootout(_ label: String, isDaemon: Bool, canUseHelper: Bool) async -> Bool {
+ private static func bootout(_ label: String, in domain: String, isDaemon: Bool, canUseHelper: Bool) async -> Bool {
if isDaemon {
guard canUseHelper, PrivilegedHelper.status == .enabled else { return false }
return await PrivilegedHelper.runDaemonCommand(.bootout, label: label) == nil
}
- return await Launchctl.run(["bootout", "gui/\(getuid())/\(label)"]).status == 0
+ return await Launchctl.run(["bootout", "\(domain)/\(label)"]).status == 0
}
@concurrent
@@ -87,7 +111,7 @@ enum LaunchdCleanup {
guard canUseHelper, PrivilegedHelper.status == .enabled else { return }
_ = await PrivilegedHelper.runDaemonCommand(.bootstrap, label: job.label)
} else {
- _ = await Launchctl.run(["bootstrap", "gui/\(getuid())", job.plist.path(percentEncoded: false)])
+ _ = await Launchctl.run(["bootstrap", job.domain, job.plist.path(percentEncoded: false)])
}
}
@@ -106,10 +130,14 @@ enum LaunchdCleanup {
guard all.contains(parent) else { return nil }
// A label macOS itself uses would reach macOS's own job, whatever file declared it.
guard
- let label = BoundedRead.propertyList(at: url)?["Label"] as? String, PrivilegedPathPolicy.isValidLabel(label),
+ let plist = BoundedRead.propertyList(at: url),
+ let label = plist["Label"] as? String, PrivilegedPathPolicy.isValidLabel(label),
!SystemDaemons.shipped.contains(label), !SystemAgents.shipped.contains(label)
else { return nil }
- return Job(label: label, isDaemon: daemons.contains(parent), plist: url)
+ return Job(
+ label: label, isDaemon: daemons.contains(parent), plist: url,
+ loadsInTheBackgroundSession: JobDefinition(plist)?.loadsOnlyInTheBackground == true
+ )
}
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
index 0c33787d..b0699602 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BackgroundItemActionsTests.swift
@@ -146,6 +146,29 @@ struct BackgroundItemActionsTests {
#expect(disabled.first { $0.label == "org.example.tide.other" }.map { $0.runsAtLoad == nil && $0.keepsAlive == nil } == true)
}
+ @Test func aJobInTheUserDomainIsAskedAboutThere() throws {
+ let directory = try TemporaryDirectory()
+ let job = try PropertyListSerialization.data(
+ fromPropertyList: ["Label": "org.example.background", "Program": "/bin/cat"], format: .xml, options: 0
+ )
+ let file = try directory.file("Elsewhere/org.example.background.plist", contents: job)
+ let loaded = BackgroundItems.Loaded(
+ user: ["org.example.background": 42, "org.example.window": nil], inTheUserDomain: ["org.example.background"]
+ )
+
+ let undeclared = BackgroundItems.undeclared(in: loaded, declared: [], uid: 501)
+ let found = BackgroundItems.undeclaredItem(
+ try #require(undeclared.first),
+ answer: .details(Launchctl.JobDetails(path: file.path(percentEncoded: false), program: "/bin/cat")),
+ ownership: BackgroundItemOwnership(installedApps: []), loaded: loaded, exclusions: .none
+ )
+
+ #expect(undeclared.map(\.target) == ["user/501/org.example.background", "gui/501/org.example.window"])
+ guard case .item(let item) = found else { throw CocoaError(.featureUnsupported) }
+ #expect(item.loadsInTheBackgroundSession)
+ #expect(BackgroundItems.Loaded(user: [:], inTheUserDomain: nil).unanswered == [.agent])
+ }
+
@Test func aJobWhoseFileIsGoneSaysSo() throws {
let directory = try TemporaryDirectory()
let job = try PropertyListSerialization.data(
@@ -753,7 +776,7 @@ struct DeclaredBackgroundItemsTests {
#expect(items.first { $0.label == "com.example.agent" }?.state == .unknown)
#expect(items.first { $0.label == "com.example.daemon" }?.state == .unknown)
- #expect(BackgroundItems.undeclared(in: loaded, declared: items, userDomain: "gui/501").isEmpty)
+ #expect(BackgroundItems.undeclared(in: loaded, declared: items, uid: 501).isEmpty)
}
/// A loaded job is asked about as one an app submitted only when no file in the three folders declares it, so
@@ -768,7 +791,7 @@ struct DeclaredBackgroundItemsTests {
loaded: loaded
)
- let undeclared = BackgroundItems.undeclared(in: loaded, declared: items, userDomain: "gui/501")
+ let undeclared = BackgroundItems.undeclared(in: loaded, declared: items, uid: 501)
#expect(undeclared.map(\.label) == ["com.example.submitted"])
#expect(undeclared.first?.target == "gui/501/com.example.submitted")
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
index 06be278a..688d3111 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/RemovalHygieneTests.swift
@@ -61,6 +61,26 @@ struct RemovalHygieneTests {
])
}
+ @Test func stopsAndStartsABackgroundAgentInTheUserDomain() throws {
+ let directory = try TemporaryDirectory()
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home"),
+ rootDirectory: directory.url.appending(path: "root")
+ )
+ let contents = try PropertyListSerialization.data(
+ fromPropertyList: ["Label": "org.example.background", "LimitLoadToSessionType": "Background"],
+ format: .xml, options: 0
+ )
+ let background = try directory.file("home/Library/LaunchAgents/org.example.background.plist", contents: contents)
+ let window = try launchdPlist(
+ "home/Library/LaunchAgents/org.example.window.plist", label: "org.example.window", in: directory
+ )
+
+ let jobs = LaunchdCleanup.jobs(for: [background, window], environment: environment)
+
+ #expect(jobs.map(\.domain) == ["user/\(getuid())", "gui/\(getuid())"])
+ }
+
@Test func findsThePreferenceDomainsToForget() {
let urls = [
URL(filePath: "/Users/x/Library/Preferences/com.example.app.plist"),