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.

Make the folders a Put Back needs through descriptors, after the guard allows them

Țugui Dragoșf88939271a09
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 3d1bb603..257c1870 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -170,6 +170,8 @@ the Homebrew page's uninstall and cleanups are Homebrew's own.
real Trash, only to a place the guard allows, only when it is the item that went (`TrashedItem.identity`,
its inode and birth time, read in the Trash as it landed and asked again of the item Put Back holds open),
and, through the helper, only if the helper's own ledger says it moved that very item from that very place.
+ The folders gone on the way are made again through descriptors, never through a link, once the guard has
+ allowed the place, and are taken away again if the item then stays in the Trash.
An app that comes back gets its Dock icon back where it was, a launch job the move stopped starts again as the
file back in place declares it, and the apps put back are made known to Launch Services again only once every
item is back.
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index 5437ded7..c38b3d9b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -740,7 +740,6 @@ public struct TrashService: Sendable {
}
if fileManager.isWritableFile(atPath: ancestor) {
do {
- try fileManager.createDirectory(at: parent, withIntermediateDirectories: true)
try Self.putBack(item) { removalGuard.refusal(ofPuttingBack: item.trashedURL, at: $0) }
return nil
} catch is RefusedOnceHeld {
@@ -758,20 +757,54 @@ public struct TrashService: Sendable {
return .failed(failure)
}
- /// Moves `item` back from the Trash through a descriptor for its folder, which must already exist. The guard
- /// is asked again about the destination as the kernel names it, and the move never replaces an item there.
+ /// Moves `item` back from the Trash through a descriptor for its folder, making the folders gone on the way
+ /// through descriptors too, never through a link. The guard judges the place as the kernel names it before any
+ /// folder is made and again before the move, which never replaces an item there; a refused Put Back's go again.
static func putBack(_ item: TrashedItem, refusal: (URL) -> GuardRefusal?) throws {
let trashed = try OpenItem.at(item.trashedURL.path(percentEncoded: false)).get()
if let identity = item.identity, trashed.identity.map(TrashedItem.Identity.init) != identity {
throw NotTheItemThatMoved()
}
- let folder = try DirectoryHandle.at(item.originalURL.deletingLastPathComponent().path(percentEncoded: false))
- .get()
- guard let held = folder.currentPath else { throw POSIXError(.ENOENT) }
let name = item.originalURL.lastPathComponent
- let destination = URL(filePath: held, directoryHint: .isDirectory).appending(path: name)
- if let refused = refusal(destination) { throw RefusedOnceHeld(refusal: refused) }
- try TrashMover.rename(trashed, to: name, in: folder).get()
+ var nearest = item.originalURL.deletingLastPathComponent().path(percentEncoded: false)
+ var missing: [String] = []
+ while PrivilegedPathPolicy.resolvedPath(nearest) == nil {
+ guard nearest != "/", !nearest.isEmpty else { throw POSIXError(.ENOENT) }
+ missing.insert((nearest as NSString).lastPathComponent, at: 0)
+ nearest = (nearest as NSString).deletingLastPathComponent
+ }
+ guard !missing.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }) else { throw POSIXError(.EINVAL) }
+
+ var folder = try DirectoryHandle.at(nearest).get()
+ var made: [(parent: DirectoryHandle, name: String, identity: ItemIdentity)] = []
+ func takeBack() {
+ for folder in made.reversed() {
+ folder.parent.removeFolder(folder.name, if: folder.identity)
+ }
+ }
+ func refused(below rest: [String]) throws -> GuardRefusal? {
+ guard let held = folder.currentPath else { throw POSIXError(.ENOENT) }
+ var destination = URL(filePath: held, directoryHint: .isDirectory)
+ for part in rest {
+ destination.append(path: part, directoryHint: .isDirectory)
+ }
+ return refusal(destination.appending(path: name))
+ }
+ if !missing.isEmpty, let refusal = try refused(below: missing) { throw RefusedOnceHeld(refusal: refusal) }
+ do {
+ for part in missing {
+ let next = try folder.child(part, makingIfMissing: true).get()
+ if let identity = next.made {
+ made.append((folder, part, identity))
+ }
+ folder = next.folder
+ }
+ if let refusal = try refused(below: []) { throw RefusedOnceHeld(refusal: refusal) }
+ try TrashMover.rename(trashed, to: name, in: folder).get()
+ } catch {
+ takeBack()
+ throw error
+ }
}
/// Whether `url` sits directly in a Trash: `~/.Trash`, or `.Trashes/<uid>` at the root of its volume. The
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
index 4761261d..0e905c80 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
@@ -57,6 +57,39 @@ public final class DirectoryHandle: Sendable {
return DirectoryHandle(path: path == "/" ? "/" + name : path + "/" + name, descriptor: descriptor)
}
+ /// The folder `name` inside this one, made when nothing is there, and never a link or a file in its place. A
+ /// folder made here comes back with its identity, so the caller can take it away again.
+ public func child(
+ _ name: String,
+ makingIfMissing: Bool
+ ) -> Result<(folder: DirectoryHandle, made: ItemIdentity?), POSIXError> {
+ var made: ItemIdentity?
+ if makingIfMissing {
+ if name.withCString({ mkdirat(descriptor, $0, 0o755) }) == 0 {
+ var info = stat()
+ guard name.withCString({ fstatat(descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {
+ let failure = POSIXError.last
+ _ = name.withCString { unlinkat(descriptor, $0, AT_REMOVEDIR) }
+ return .failure(failure)
+ }
+ made = ItemIdentity(info)
+ } else {
+ let failure = POSIXError.last
+ guard failure.code == .EEXIST else { return .failure(failure) }
+ }
+ }
+ guard let folder = child(name) else { return .failure(.last) }
+ return .success((folder, made))
+ }
+
+ /// Takes away the folder `name` inside this one, only while it is still the empty folder `made` names.
+ public func removeFolder(_ name: String, if made: ItemIdentity) {
+ var info = stat()
+ guard name.withCString({ fstatat(descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0, ItemIdentity(info) == made
+ else { return }
+ _ = name.withCString { unlinkat(descriptor, $0, AT_REMOVEDIR) }
+ }
+
/// The owner of the directory itself, read through the descriptor.
public func ownerIdentifier() -> uid_t? {
var info = stat()
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
index 91423cec..06af5a3f 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
@@ -833,6 +833,67 @@ struct TrashServiceTests {
#expect(caches.appending(path: "Vendor.real/x.pdf").isThere)
}
+ @Test func makesNoFolderForAPutBackTheGuardRefusesOnceTheFoldersAreHeld() throws {
+ let directory = try TemporaryDirectory()
+ let caches = try directory.directory("home/Library/Caches")
+ let trashed = try directory.file("home/.Trash/x.pdf")
+ let record = TrashedItem(originalURL: caches.appending(path: "Vendor/Deep/x.pdf"), trashedURL: trashed, date: .now)
+ var asked: [URL] = []
+
+ #expect(throws: TrashService.RefusedOnceHeld.self) {
+ try TrashService.putBack(record) { held in
+ asked.append(held)
+ return .protectedLocation
+ }
+ }
+
+ #expect(asked.map { $0.path(percentEncoded: false) }.map { $0.hasSuffix("/home/Library/Caches/Vendor/Deep/x.pdf") } == [true])
+ #expect(!caches.appending(path: "Vendor").isThere)
+ #expect(trashed.isThere)
+ }
+
+ @Test func takesAwayTheFoldersItMadeForAPutBackThatIsThenRefused() throws {
+ let directory = try TemporaryDirectory()
+ let caches = try directory.directory("home/Library/Caches")
+ let trashed = try directory.file("home/.Trash/x.pdf")
+ let record = TrashedItem(originalURL: caches.appending(path: "Vendor/Deep/x.pdf"), trashedURL: trashed, date: .now)
+ var asked = 0
+
+ #expect(throws: TrashService.RefusedOnceHeld.self) {
+ try TrashService.putBack(record) { _ in
+ asked += 1
+ guard asked == 2 else { return nil }
+ #expect(caches.appending(path: "Vendor/Deep").isThere, "the folders were not made before the move")
+ return .protectedLocation
+ }
+ }
+
+ #expect(asked == 2)
+ #expect(!caches.appending(path: "Vendor").isThere)
+ #expect(trashed.isThere)
+ }
+
+ @Test func putsNothingBackThroughALinkPlantedWhereAFolderWasMissing() throws {
+ let directory = try TemporaryDirectory()
+ let caches = try directory.directory("home/Library/Caches")
+ let elsewhere = try directory.directory("home/Documents/Elsewhere")
+ let trashed = try directory.file("home/.Trash/x.pdf")
+ let record = TrashedItem(originalURL: caches.appending(path: "Vendor/Deep/x.pdf"), trashedURL: trashed, date: .now)
+
+ #expect(throws: POSIXError.self) {
+ try TrashService.putBack(record) { _ in
+ try? FileManager.default.createSymbolicLink(
+ atPath: caches.appending(path: "Vendor").path(percentEncoded: false),
+ withDestinationPath: elsewhere.path(percentEncoded: false)
+ )
+ return nil
+ }
+ }
+
+ #expect(!elsewhere.appending(path: "Deep").isThere, "a folder was made through the link")
+ #expect(trashed.isThere)
+ }
+
@Test func reallyMovesAFolderToTheTrashAndPutsItBack() async throws {
let directory = try TemporaryDirectory()
let item = try directory.file("home/Library/Caches/Example/note.txt")