Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

Bottles: fix three ways the new delete could destroy the wrong thing (#38)

Gauthier Piarrette9fed3894ddfd
diff --git a/Sources/HighballKit/BottleStore.swift b/Sources/HighballKit/BottleStore.swift
index 631c305..abaf5f0 100644
--- a/Sources/HighballKit/BottleStore.swift
+++ b/Sources/HighballKit/BottleStore.swift
@@ -168,10 +168,10 @@ public struct BottleStore: Sendable {
/// name is free either way; leftovers wait in `.trash` for `sweepTrash()` to retry.
@discardableResult
public func delete(_ name: String) throws -> [PurgeFailure] {
- let url = paths.bottle(name)
// Resolve by folder, not by bottle.json. The folder is the bottle's identity — the same
// rule list() reconciles names to — and a bottle whose settings file is unreadable is
// precisely the one that most needs deleting.
+ let url = try Self.bottleURL(name, in: paths)
var st = stat()
guard lstat(url.path, &st) == 0 else { throw HighballError.missing("bottle '\(name)'") }
return try discard(url, name: name)
@@ -182,6 +182,13 @@ public struct BottleStore: Sendable {
/// moment the call returns, the name is reusable.
@discardableResult
func discard(_ url: URL, name: String) throws -> [PurgeFailure] {
+ Purge.tree(at: try moveToTrash(url, name: name))
+ }
+
+ /// The atomic half, split out so the rename can be tested on its own: once the purge has run
+ /// there is nothing left to compare, and a copy-then-delete implementation would look
+ /// identical from the outside.
+ func moveToTrash(_ url: URL, name: String) throws -> URL {
try FileManager.default.createDirectory(at: paths.trash, withIntermediateDirectories: true)
// rename(2) needs write on the two parent directories and nothing else, so it succeeds
// over trees removeItem cannot touch (0555 and 0000 directories, uchg flags, deny-delete
@@ -204,7 +211,29 @@ public struct BottleStore: Sendable {
(\(why)). Nothing was removed and the bottle still works.
""")
}
- return Purge.tree(at: target)
+ return target
+ }
+
+ /// Resolves a bottle name to its directory, refusing anything that is not a single component
+ /// inside `bottles/`.
+ ///
+ /// This guard is load-bearing for a destructive call. delete() used to be protected by
+ /// accident: its old bottle.json check meant a traversing name found no settings file and was
+ /// rejected. Removing that check for #38 removed the protection with it, and
+ /// `highball bottle delete ../../Something` then resolved outside the bottles folder and
+ /// purged it — found in review, reproduced against the built CLI.
+ static func bottleURL(_ name: String, in paths: HighballPaths) throws -> URL {
+ guard !name.isEmpty, name != ".", name != "..",
+ !name.contains("/"), !name.unicodeScalars.contains("\0") else {
+ throw HighballError.invalid("'\(name)' isn't a bottle name")
+ }
+ let url = paths.bottle(name)
+ // Belt and braces: whatever the name did, the result must sit directly in bottles/.
+ guard url.deletingLastPathComponent().standardizedFileURL.path
+ == paths.bottles.standardizedFileURL.path else {
+ throw HighballError.invalid("'\(name)' isn't a bottle name")
+ }
+ return url
}
/// Bottle names are user-supplied, so keep them from steering the trash path anywhere.
diff --git a/Sources/HighballKit/Purge.swift b/Sources/HighballKit/Purge.swift
index 2a3f496..5cbd064 100644
--- a/Sources/HighballKit/Purge.swift
+++ b/Sources/HighballKit/Purge.swift
@@ -23,8 +23,8 @@ public struct PurgeFailure: Sendable, Hashable, CustomStringConvertible {
/// The errno text, e.g. "Permission denied".
public var reason: String { String(cString: strerror(code)) }
- /// Mode, flags and uid go in the message on purpose: they are the only evidence that can
- /// tell us what makes a directory unremovable inside a real prefix, which #38 left open.
+ /// Mode, flags and uid are recorded as observed BEFORE any repair, because they are the only
+ /// evidence of what made an entry unremovable — the open question left by issue #38.
public var description: String {
"\(path): \(reason) (mode \(String(mode & 0o7777, radix: 8)) flags \(flags) uid \(uid))"
}
@@ -32,18 +32,28 @@ public struct PurgeFailure: Sendable, Hashable, CustomStringConvertible {
/// Removes a directory tree, doing everything a user could do without privilege escalation.
///
-/// `FileManager.removeItem` gives up on far less than the filesystem actually allows: it stops
-/// at the first unwritable directory, immutable flag or deny ACL, and cannot delete a path over
-/// `PATH_MAX` at all. Since a Wine prefix is written by arbitrary Windows installers, any of
-/// those can appear in one.
+/// `FileManager.removeItem` gives up on far less than the filesystem allows: it stops at the
+/// first unwritable directory, immutable flag or deny ACL, and cannot delete a path over
+/// `PATH_MAX` at all. A Wine prefix is written by arbitrary Windows installers, so any of those
+/// can appear in one.
+///
+/// The walk is **fd-relative** — `openat`/`fstatat`/`unlinkat` against a directory descriptor,
+/// with `O_NOFOLLOW`, never a re-resolved path string. That is not a micro-optimisation, it is
+/// the safety property: every bottle contains symlinks pointing out of itself
+/// (`drive_c/users/<user>/{Documents,Desktop,Downloads}` at the real home folders, `dosdevices/z:`
+/// at `/`), and Wine's mountmgr writes into a live prefix. A path-based walk re-resolves each
+/// component after checking it, so a directory that becomes a symlink between the check and the
+/// unlink redirects the delete outside the tree — verified: a path-based version deleted every
+/// file in a directory outside the bottle, 6 runs out of 6. Holding descriptors makes that
+/// unrepresentable, and it removes the PATH_MAX ceiling for free, since each name is relative.
public enum Purge {
- /// Best effort. Returns what is still on disk afterwards, deepest entry first, so the
- /// caller can name the real cause rather than an ENOTEMPTY cascade above it.
+ /// Best effort. Returns what is still on disk afterwards. An empty result means the tree is
+ /// genuinely gone: the caller is told so only after a positive check, never by assumption.
@discardableResult
public static func tree(at url: URL) -> [PurgeFailure] {
- // This deletes recursively and eventually shells out to `rm -rf`, so refuse the shallow
- // paths a bug upstream could produce: "/", "/Users", "/Users/someone", a volume root.
- // Everything Highball actually purges is at least <home>/.trash/<entry>, far deeper.
+ // This deletes recursively, so refuse the shallow paths a bug upstream could produce:
+ // "/", "/Users", "/Users/someone", a volume root. Everything Highball purges is at least
+ // <home>/.trash/<entry>, far deeper.
guard url.isFileURL, url.pathComponents.count >= 4 else {
return [PurgeFailure(path: url.path, code: EINVAL)]
}
@@ -51,73 +61,158 @@ public enum Purge {
if (try? FileManager.default.removeItem(at: url)) != nil { return [] }
var failures: [PurgeFailure] = []
- force(url.path, &failures)
- if !exists(url.path) { return [] }
-
- // Two things the walk above cannot clear: stripping an ACL needs acl(3), and unlink()
- // on a path over PATH_MAX fails with ENAMETOOLONG whatever the permissions. Both fall
- // to the system tools — chmod uses acl_set_file, and rm walks with fts, which chdirs
- // so a long path is never formed. Ordering matters: modes are already repaired here,
- // so chmod can descend.
- _ = run("/bin/chmod", ["-R", "-N", url.path])
- _ = run("/bin/rm", ["-rf", url.path])
- if !exists(url.path) { return [] }
-
- failures.removeAll()
- collect(url.path, &failures)
+ let parentPath = url.deletingLastPathComponent().path
+ let name = url.lastPathComponent
+ let parent = open(parentPath, O_RDONLY | O_DIRECTORY | O_CLOEXEC)
+ if parent < 0 {
+ return [PurgeFailure(path: parentPath, code: errno)]
+ }
+ remove(in: parent, named: name, at: url.path, &failures)
+ close(parent)
+
+ // Never report an all-clear we have not verified. A silently stranded prefix is how the
+ // original bug hid: the caller believed the delete had finished.
+ var st = stat()
+ if lstat(url.path, &st) == 0, failures.isEmpty {
+ failures.append(PurgeFailure(path: url.path, code: ENOTEMPTY,
+ mode: st.st_mode, flags: st.st_flags, uid: st.st_uid))
+ }
return failures
}
- /// Depth-first, repairing each node on the way down.
- private static func force(_ path: String, _ failures: inout [PurgeFailure]) {
+ /// Removes one entry by name, relative to an open descriptor for its parent directory.
+ ///
+ /// Iterative, with an explicit stack, deliberately. The recursive version overflowed the
+ /// 512 KB stack of a Swift cooperative-pool thread at around 450 levels and wedged the
+ /// process in an uninterruptible wait — a prefix deep enough to hit that is exactly the kind
+ /// a runaway Windows installer produces, and it would have hung the app with no error.
+ private static func remove(in parent: Int32, named name: String, at path: String,
+ _ failures: inout [PurgeFailure]) {
var st = stat()
- guard lstat(path, &st) == 0 else {
- if errno != ENOENT { failures.append(PurgeFailure(path: path, code: errno)) }
+ guard fstatat(parent, name, &st, AT_SYMLINK_NOFOLLOW) == 0 else {
+ let e = errno
+ if e != ENOENT { failures.append(PurgeFailure(path: path, code: e)) }
return
}
- // uchg/uappnd block unlink and rmdir. lchflags, never chflags: every bottle links
- // drive_c/users/<user>/{Documents,Desktop,Downloads} at the real home folders and
- // dosdevices/z: at /, and chflags follows symlinks straight out of the tree.
- if st.st_flags != 0 { _ = lchflags(path, 0) }
-
- // Likewise lstat, never fileExists(atPath:isDirectory:) — that call follows symlinks
- // and calls a link to ~/Documents a directory, so a recursion built on it would
- // descend into and delete the user's home folders.
- guard (st.st_mode & S_IFMT) == S_IFDIR else {
- if unlink(path) != 0, errno != ENOENT { failures.append(fail(path, st)) }
+ if (st.st_mode & S_IFMT) != S_IFDIR {
+ removeLeaf(in: parent, named: name, at: path, observed: st, &failures)
return
}
- // A directory's contents cannot be listed or unlinked without owner rwx on it.
- if (st.st_mode & 0o700) != 0o700 { _ = chmod(path, st.st_mode | 0o700) }
- for entry in (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? [] {
- force(path + "/" + entry, &failures)
+
+ /// One open directory on the way down, with the children still to process.
+ struct Level {
+ let fd: Int32, parent: Int32
+ let name: String, path: String
+ let observed: stat
+ var kids: [String]
+ var next: Int
}
- if rmdir(path) != 0, errno != ENOENT { failures.append(fail(path, st)) }
- }
+ var stack: [Level] = []
- /// Reports what survived. Directories that are merely non-empty are skipped, so the list
- /// holds the entries that actually refused to go rather than every parent above them.
- private static func collect(_ path: String, _ failures: inout [PurgeFailure]) {
- var st = stat()
- guard lstat(path, &st) == 0 else { return }
- guard (st.st_mode & S_IFMT) == S_IFDIR else {
- if unlink(path) != 0 { failures.append(fail(path, st)) }
+ func push(parent: Int32, name: String, path: String, observed: stat) -> Bool {
+ var fd = openat(parent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ if fd < 0, errno == EACCES || errno == EPERM {
+ // A directory's contents cannot be listed, or even opened, without owner rwx on
+ // it — a 0000 directory fails openat outright, so the mode has to be repaired
+ // before the descriptor exists. fchmodat is name-relative and does not follow a
+ // symlink, so this cannot reach outside the tree.
+ _ = fchmodat(parent, name, observed.st_mode | 0o700, AT_SYMLINK_NOFOLLOW)
+ fd = openat(parent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ }
+ guard fd >= 0 else { return false }
+ if observed.st_flags != 0 { _ = fchflags(fd, 0) }
+ if (observed.st_mode & 0o700) != 0o700 { _ = fchmod(fd, observed.st_mode | 0o700) }
+ stack.append(Level(fd: fd, parent: parent, name: name, path: path,
+ observed: observed, kids: entries(of: fd), next: 0))
+ return true
+ }
+
+ if !push(parent: parent, name: name, path: path, observed: st) {
+ // Unreadable even to open: still try to unlink it, it may be empty.
+ unlink(in: parent, named: name, at: path, flag: AT_REMOVEDIR, observed: st, &failures)
return
}
- let entries = (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? []
- for entry in entries { collect(path + "/" + entry, &failures) }
- if (try? FileManager.default.contentsOfDirectory(atPath: path))?.isEmpty ?? false {
- if rmdir(path) != 0 { failures.append(fail(path, st)) }
+
+ while var level = stack.last {
+ if level.next < level.kids.count {
+ let kid = level.kids[level.next]
+ level.next += 1
+ stack[stack.count - 1] = level
+ let kidPath = level.path + "/" + kid
+ var kst = stat()
+ guard fstatat(level.fd, kid, &kst, AT_SYMLINK_NOFOLLOW) == 0 else {
+ let e = errno
+ if e != ENOENT { failures.append(PurgeFailure(path: kidPath, code: e)) }
+ continue
+ }
+ if (kst.st_mode & S_IFMT) == S_IFDIR {
+ if !push(parent: level.fd, name: kid, path: kidPath, observed: kst) {
+ unlink(in: level.fd, named: kid, at: kidPath, flag: AT_REMOVEDIR,
+ observed: kst, &failures)
+ }
+ } else {
+ removeLeaf(in: level.fd, named: kid, at: kidPath, observed: kst, &failures)
+ }
+ } else {
+ // Children done: close this directory and unlink it from its own parent.
+ stack.removeLast()
+ close(level.fd)
+ unlink(in: level.parent, named: level.name, at: level.path,
+ flag: AT_REMOVEDIR, observed: level.observed, &failures)
+ }
}
}
- private static func fail(_ path: String, _ st: stat) -> PurgeFailure {
- PurgeFailure(path: path, code: errno, mode: st.st_mode, flags: st.st_flags, uid: st.st_uid)
+ /// A non-directory: clear any flag that blocks unlink, then unlink it.
+ private static func removeLeaf(in parent: Int32, named name: String, at path: String,
+ observed: stat, _ failures: inout [PurgeFailure]) {
+ // uchg/uappnd block unlink. O_SYMLINK opens a symlink itself rather than its target,
+ // so clearing flags can never reach through one.
+ if observed.st_flags != 0 {
+ let fd = openat(parent, name, O_SYMLINK | O_CLOEXEC)
+ if fd >= 0 { _ = fchflags(fd, 0); close(fd) }
+ }
+ unlink(in: parent, named: name, at: path, flag: 0, observed: observed, &failures)
}
- private static func exists(_ path: String) -> Bool {
- var st = stat()
- return lstat(path, &st) == 0
+ /// unlinkat, and on a permission failure one retry after stripping the entry's ACL.
+ /// `chmod -h -N` takes a single path and never recurses, so unlike `chmod -R` it cannot
+ /// follow a symlink out of the tree — a real defect found in review, where `chmod -R -N`
+ /// stripped the ACL off the user's actual home folder through a bottle's Documents link.
+ private static func unlink(in parent: Int32, named name: String, at path: String,
+ flag: Int32, observed: stat, _ failures: inout [PurgeFailure]) {
+ if unlinkat(parent, name, flag) == 0 { return }
+ var e = errno
+ if e == ENOENT { return }
+ if e == EACCES || e == EPERM {
+ _ = run("/bin/chmod", ["-h", "-N", path])
+ if unlinkat(parent, name, flag) == 0 { return }
+ e = errno
+ if e == ENOENT { return }
+ }
+ failures.append(PurgeFailure(path: path, code: e, mode: observed.st_mode,
+ flags: observed.st_flags, uid: observed.st_uid))
+ }
+
+ /// Child names of an open directory, excluding "." and "..". Collected before recursing so
+ /// the directory stream is closed while its entries are being removed.
+ private static func entries(of fd: Int32) -> [String] {
+ let copy = dup(fd)
+ guard copy >= 0, let dir = fdopendir(copy) else {
+ if copy >= 0 { close(copy) }
+ return []
+ }
+ defer { closedir(dir) }
+ var names: [String] = []
+ while let entry = readdir(dir) {
+ var e = entry.pointee
+ let name = withUnsafePointer(to: &e.d_name) {
+ $0.withMemoryRebound(to: CChar.self, capacity: Int(e.d_namlen) + 1) { String(cString: $0) }
+ }
+ if name == "." || name == ".." { continue }
+ names.append(name)
+ }
+ return names
}
private static func run(_ tool: String, _ args: [String]) -> Int32 {
diff --git a/Tests/HighballKitTests/BottleDeleteTests.swift b/Tests/HighballKitTests/BottleDeleteTests.swift
index 46b66a1..92e6b1f 100644
--- a/Tests/HighballKitTests/BottleDeleteTests.swift
+++ b/Tests/HighballKitTests/BottleDeleteTests.swift
@@ -4,6 +4,11 @@ import XCTest
/// Issue #38: deleting a bottle reported "you don't have permission to access it" and left the
/// bottle half-destroyed — invisible to `list()`, refused by `delete()` and blocked by
/// `create()`'s name check, with its files still on disk.
+///
+/// Every test here asserts `assertFullyGone`, not just that `bottles/<name>` disappeared. The
+/// first version of this suite checked only the latter, which `rename(2)` alone guarantees — so
+/// a purge that deleted nothing at all kept 12 of 13 tests green. Checking `.trash` is what makes
+/// these tests able to fail.
final class BottleDeleteTests: XCTestCase {
private var home: URL!
private var paths: HighballPaths!
@@ -17,13 +22,30 @@ final class BottleDeleteTests: XCTestCase {
}
override func tearDownWithError() throws {
- if let home { Purge.tree(at: home) }
+ guard let home else { return }
+ // Deliberately not Purge.tree: cleaning up with the code under test would let a broken
+ // purge tidy away its own evidence.
+ _ = try? Process.run(URL(fileURLWithPath: "/bin/chmod"), arguments: ["-R", "-N", home.path]).waitUntilExit()
+ _ = try? Process.run(URL(fileURLWithPath: "/usr/bin/chflags"), arguments: ["-R", "nouchg", home.path]).waitUntilExit()
+ _ = try? Process.run(URL(fileURLWithPath: "/bin/chmod"), arguments: ["-R", "u+rwX", home.path]).waitUntilExit()
+ _ = try? Process.run(URL(fileURLWithPath: "/bin/rm"), arguments: ["-rf", home.path]).waitUntilExit()
+ }
+
+ // MARK: Helpers
+
+ /// The assertion that matters: the bottle is gone from `bottles/` AND the purge finished, so
+ /// nothing is parked in `.trash` and no leftovers were reported.
+ private func assertFullyGone(_ name: String, _ leftovers: [PurgeFailure],
+ file: StaticString = #filePath, line: UInt = #line) throws {
+ XCTAssertFalse(FileManager.default.fileExists(atPath: paths.bottle(name).path),
+ "bottles/\(name) still exists", file: file, line: line)
+ XCTAssertEqual(leftovers.map(\.description), [], "delete reported leftovers", file: file, line: line)
+ let trash = (try? FileManager.default.contentsOfDirectory(atPath: paths.trash.path)) ?? []
+ XCTAssertEqual(trash, [], "the purge left the tree in .trash", file: file, line: line)
}
- /// A bottle shaped like a real one: the same top-level entries, in a tree deep enough that
- /// a blocker is reached only after the metadata.
@discardableResult
- private func makeBottle(_ name: String, files: Int = 40) throws -> URL {
+ private func makeBottle(_ name: String, files: Int = 30) throws -> URL {
let url = paths.bottle(name)
let system32 = url.appending(path: "drive_c/windows/system32")
try FileManager.default.createDirectory(at: system32, withIntermediateDirectories: true)
@@ -38,7 +60,7 @@ final class BottleDeleteTests: XCTestCase {
return url
}
- /// Plants the thing that broke #38: a directory macOS will not let us empty.
+ /// A directory macOS will not let us empty — what broke #38.
private func lock(_ url: URL) throws {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
try "locked".write(to: url.appending(path: "inside.dat"), atomically: true, encoding: .utf8)
@@ -49,12 +71,13 @@ final class BottleDeleteTests: XCTestCase {
func testDeleteSucceedsWithAnUnwritableSubdirectory() throws {
let url = try makeBottle("play")
- try lock(url.appending(path: "drive_c/Program Files/Game/data"))
+ let locked = url.appending(path: "drive_c/Program Files/Game/data")
+ try lock(locked)
+ // Naming the file proves the purge descended, not merely that the bottle was renamed.
+ let inside = locked.appending(path: "inside.dat").path
- XCTAssertNoThrow(try store.delete("play"))
- XCTAssertFalse(FileManager.default.fileExists(atPath: url.path), "bottles/play must be gone")
- XCTAssertTrue(try store.list().isEmpty)
- XCTAssertTrue(try store.damaged().isEmpty, "nothing may be left behind in bottles/")
+ try assertFullyGone("play", try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: inside), "the unwritable directory's contents survived")
}
func testDeleteSucceedsWithImmutableAndUnreadableEntries() throws {
@@ -64,66 +87,51 @@ final class BottleDeleteTests: XCTestCase {
let immutable = dir.appending(path: "locked.dat")
try "x".write(to: immutable, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.immutable: true], ofItemAtPath: immutable.path)
- try FileManager.default.createDirectory(at: dir.appending(path: "unreadable"), withIntermediateDirectories: true)
- try FileManager.default.setAttributes([.posixPermissions: 0o000],
- ofItemAtPath: dir.appending(path: "unreadable").path)
-
- XCTAssertNoThrow(try store.delete("play"))
- XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
- }
-
- /// The name must be reusable the instant delete returns. #38's reporter could not recreate
- /// his bottle: `create()` refused because the gutted directory was still there.
- func testDeleteFreesTheNameEvenWhenFilesCannotBeRemoved() throws {
- let url = try makeBottle("play")
- try lock(url.appending(path: "drive_c/Program Files/Game/data"))
-
- try store.delete("play")
- XCTAssertFalse(FileManager.default.fileExists(atPath: paths.bottle("play").path),
- "the name must be free for create() to reuse")
+ let unreadable = dir.appending(path: "unreadable")
+ try FileManager.default.createDirectory(at: unreadable, withIntermediateDirectories: true)
+ try "x".write(to: unreadable.appending(path: "f"), atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: unreadable.path)
+
+ try assertFullyGone("play", try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: immutable.path), "the immutable file survived")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: unreadable.path), "the unreadable directory survived")
}
- // MARK: Atomicity
-
- func testDeleteMovesTheBottleOutOfBottlesBeforePurging() throws {
+ func testDeleteSucceedsWithADenyDeleteACL() throws {
let url = try makeBottle("play")
- // An unpurgeable entry: a 0555 directory whose parent is also 0555, so even the forced
- // walk leaves something behind and we can observe where the tree went.
- try lock(url.appending(path: "drive_c/keep/inner"))
- try FileManager.default.setAttributes([.posixPermissions: 0o555],
- ofItemAtPath: url.appending(path: "drive_c/keep").path)
-
- _ = try store.delete("play")
- XCTAssertFalse(FileManager.default.fileExists(atPath: url.path),
- "bottles/ must be clean whatever the purge managed")
+ let dir = url.appending(path: "drive_c/Program Files/Game")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let guarded = dir.appending(path: "guarded.dat")
+ try "x".write(to: guarded, atomically: true, encoding: .utf8)
+ let chmod = Process()
+ chmod.executableURL = URL(fileURLWithPath: "/bin/chmod")
+ chmod.arguments = ["+a", "everyone deny delete", guarded.path]
+ try chmod.run(); chmod.waitUntilExit()
+
+ try assertFullyGone("play", try store.delete("play"))
+ XCTAssertFalse(FileManager.default.fileExists(atPath: guarded.path), "the ACL-protected file survived")
}
- /// Guards against someone "simplifying" rename(2) back into FileManager.moveItem, which
- /// across volumes copies and then deletes — reproducing #38 with a full duplicate on the side.
- func testDeleteIsARenameNotACopy() throws {
+ /// The name must be reusable the instant delete returns; #38's reporter could not recreate his.
+ func testDeleteFreesTheNameForReuse() throws {
let url = try makeBottle("play")
try lock(url.appending(path: "drive_c/Program Files/Game/data"))
- let before = try FileManager.default.attributesOfItem(atPath: url.path)[.systemFileNumber] as? Int
-
_ = try store.delete("play")
- let moved = (try? FileManager.default.contentsOfDirectory(at: paths.trash, includingPropertiesForKeys: nil)) ?? []
- let after = moved.first.flatMap {
- try? FileManager.default.attributesOfItem(atPath: $0.path)[.systemFileNumber] as? Int
- }
- XCTAssertNotNil(before)
- XCTAssertEqual(before, after ?? before, "the tree must keep its inode: rename, not copy")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: paths.bottle("play").path))
+ XCTAssertNoThrow(try makeBottle("play"), "the name must be reusable")
}
// MARK: Safety
- /// The one mistake that would be catastrophic. Every bottle links
+ /// The mistake that would be catastrophic. Every bottle links
/// drive_c/users/<user>/{Documents,Desktop,Downloads} at the real home folders and
- /// dosdevices/z: at /, so a purge that followed symlinks would delete the user's data.
+ /// dosdevices/z: at /, so a purge that resolved paths instead of holding descriptors would
+ /// delete the user's data — a path-based version did exactly that under a concurrent swap.
func testPurgeNeverFollowsSymlinksOutOfTheTree() throws {
let url = try makeBottle("play")
let outside = home.appending(path: "precious")
- try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
- let canary = outside.appending(path: "canary.txt")
+ try FileManager.default.createDirectory(at: outside.appending(path: "sub"), withIntermediateDirectories: true)
+ let canary = outside.appending(path: "sub/canary.txt")
try "do not delete".write(to: canary, atomically: true, encoding: .utf8)
let users = url.appending(path: "drive_c/users/tester")
@@ -131,77 +139,147 @@ final class BottleDeleteTests: XCTestCase {
try FileManager.default.createSymbolicLink(at: users.appending(path: "Documents"), withDestinationURL: outside)
try FileManager.default.createSymbolicLink(at: url.appending(path: "dosdevices/z:"),
withDestinationURL: URL(fileURLWithPath: "/"))
- // Force the slow path, so the hand-written recursion is what gets exercised.
+ // Force the slow path so the hand-written walk is what runs.
try lock(url.appending(path: "drive_c/Program Files/Game/data"))
- _ = try store.delete("play")
- XCTAssertTrue(FileManager.default.fileExists(atPath: canary.path),
- "the purge followed a symlink out of the bottle")
+ try assertFullyGone("play", try store.delete("play"))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: canary.path), "the purge followed a symlink out of the bottle")
XCTAssertEqual(try String(contentsOf: canary, encoding: .utf8), "do not delete")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: "/usr"), "/ must be untouched")
+ }
+
+ /// `chmod -R -N` follows symlinks (and macOS refuses `-R -h` together), so the ACL-clearing
+ /// step used to reach through a bottle's Documents link and strip the ACL off the real folder.
+ func testPurgeLeavesACLsOnSymlinkTargetsOutsideTheTree() throws {
+ let url = try makeBottle("play")
+ let outside = home.appending(path: "outside")
+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
+ let chmod = Process()
+ chmod.executableURL = URL(fileURLWithPath: "/bin/chmod")
+ chmod.arguments = ["+a", "everyone deny delete", outside.path]
+ try chmod.run(); chmod.waitUntilExit()
+
+ let users = url.appending(path: "drive_c/users/tester")
+ try FileManager.default.createDirectory(at: users, withIntermediateDirectories: true)
+ try FileManager.default.createSymbolicLink(at: users.appending(path: "Documents"), withDestinationURL: outside)
+ try lock(url.appending(path: "drive_c/Program Files/Game/data"))
+
+ try assertFullyGone("play", try store.delete("play"))
+ let ls = Process(), pipe = Pipe()
+ ls.executableURL = URL(fileURLWithPath: "/bin/ls")
+ ls.arguments = ["-lde", outside.path]
+ ls.standardOutput = pipe
+ try ls.run(); ls.waitUntilExit()
+ let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ XCTAssertTrue(out.contains("deny delete"), "the purge stripped an ACL outside the bottle:\n\(out)")
+ }
+
+ /// A destructive call must not take a name that resolves anywhere but inside bottles/.
+ /// Dropping the old bottle.json guard removed this protection by accident, and
+ /// `bottle delete ../../Something` then purged that directory.
+ func testDeleteRefusesNamesThatEscapeTheBottlesFolder() throws {
+ let outside = home.appending(path: "outside")
+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
+ let canary = outside.appending(path: "canary.txt")
+ try "keep".write(to: canary, atomically: true, encoding: .utf8)
+
+ for bad in ["..", ".", "", "../outside", "../../etc", "a/b", "bottles/../../outside"] {
+ XCTAssertThrowsError(try store.delete(bad), "'\(bad)' must be refused")
+ }
+ XCTAssertTrue(FileManager.default.fileExists(atPath: canary.path), "an escaping name reached outside bottles/")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: outside.path))
+ }
+
+ /// A prefix deeper than a thread's stack must not wedge the app. A recursive walk overflowed
+ /// the 512 KB stack of a cooperative-pool thread at ~450 levels and hung in an uninterruptible
+ /// wait; the iterative walk has no depth ceiling.
+ func testDeleteHandlesATreeDeeperThanTheStack() throws {
+ let url = try makeBottle("play")
+ let fm = FileManager.default
+ let start = fm.currentDirectoryPath
+ defer { fm.changeCurrentDirectoryPath(start) }
+ let deep = url.appending(path: "drive_c/deep")
+ try fm.createDirectory(at: deep, withIntermediateDirectories: true)
+ // chdir-relative, because an absolute path over PATH_MAX cannot even be created.
+ XCTAssertTrue(fm.changeCurrentDirectoryPath(deep.path))
+ let segment = String(repeating: "d", count: 31)
+ for _ in 0..<700 {
+ guard (try? fm.createDirectory(atPath: segment, withIntermediateDirectories: false)) != nil,
+ fm.changeCurrentDirectoryPath(segment) else { break }
+ }
+ fm.createFile(atPath: "leaf.txt", contents: Data("x".utf8))
+ fm.changeCurrentDirectoryPath(start)
+
+ try assertFullyGone("play", try store.delete("play"))
+ }
+
+ func testPurgeRefusesShallowPaths() {
+ for dangerous in ["/", "/Users", "/Users/someone", "/Volumes"] {
+ let failures = Purge.tree(at: URL(fileURLWithPath: dangerous))
+ XCTAssertEqual(failures.first?.code, EINVAL, "\(dangerous) must be refused")
+ }
+ XCTAssertTrue(FileManager.default.fileExists(atPath: "/Users"))
+ }
+
+ /// Guards against someone replacing rename(2) with a copy-then-delete implementation, which
+ /// across volumes is exactly what reintroduces #38. Tests the move on its own, because after
+ /// the purge there is nothing left to compare and a copy would look identical from outside.
+ func testDeleteMovesTheTreeWithoutCopyingIt() throws {
+ let url = try makeBottle("play")
+ let before = try XCTUnwrap(FileManager.default.attributesOfItem(atPath: url.path)[.systemFileNumber] as? Int)
+
+ let moved = try store.moveToTrash(url, name: "play")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: url.path), "the source must be gone at once")
+ let after = try XCTUnwrap(FileManager.default.attributesOfItem(atPath: moved.path)[.systemFileNumber] as? Int)
+ XCTAssertEqual(before, after, "the tree was copied, not renamed")
+ // A copy would also duplicate the contents; the rename moves the whole subtree intact.
+ XCTAssertTrue(FileManager.default.fileExists(atPath: moved.appending(path: "drive_c/windows/system32/lib0.dll").path))
}
// MARK: Recovery
- /// The state #38's reporter is stuck in: a directory with no readable settings file. It was
- /// invisible to `list()` and `delete()` refused it, so there was no way out from the app.
func testADamagedBottleIsListedAndDeletable() throws {
let url = try makeBottle("play")
try FileManager.default.removeItem(at: url.appending(path: "bottle.json"))
- XCTAssertTrue(try store.list().isEmpty, "list() still only shows loadable bottles")
+ XCTAssertTrue(try store.list().isEmpty)
XCTAssertEqual(try store.damaged().map(\.name), ["play"])
- XCTAssertNoThrow(try store.delete("play"))
- XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
+ try assertFullyGone("play", try store.delete("play"))
}
- /// A Gin-era bottle keeps its settings in gin.json. `Bottle.load` accepts it, so `list()`
- /// showed it while the old bottle.json guard made it permanently undeletable.
func testALegacyGinBottleIsDeletable() throws {
let url = try makeBottle("play")
try FileManager.default.moveItem(at: url.appending(path: "bottle.json"),
to: url.appending(path: "gin.json"))
-
XCTAssertEqual(try store.list().map(\.name), ["play"])
- XCTAssertNoThrow(try store.delete("play"))
- XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
+ XCTAssertTrue(try store.damaged().isEmpty, "a loadable bottle must never also be damaged")
+ try assertFullyGone("play", try store.delete("play"))
}
- func testDeletingAnAbsentBottleStillReportsItMissing() throws {
+ func testDeletingAnAbsentBottleReportsItMissing() {
XCTAssertThrowsError(try store.delete("nope"))
}
- func testDamagedIgnoresDotFilesAndLooseFiles() throws {
+ func testDamagedIgnoresDotFilesLooseFilesAndSymlinks() throws {
try "x".write(to: paths.bottles.appending(path: ".DS_Store"), atomically: true, encoding: .utf8)
+ try "x".write(to: paths.bottles.appending(path: "loose.txt"), atomically: true, encoding: .utf8)
+ try FileManager.default.createSymbolicLink(at: paths.bottles.appending(path: "alink"),
+ withDestinationURL: home)
try makeBottle("play")
- XCTAssertTrue(try store.damaged().isEmpty)
+ XCTAssertTrue(try store.damaged().isEmpty, "damaged() must list only real bottle directories")
+ XCTAssertEqual(try store.list().map(\.name), ["play"])
}
- // MARK: Leftovers
-
- func testLeftoversAreReportedAndSweptLater() throws {
- let url = try makeBottle("play")
- let stubborn = url.appending(path: "drive_c/mnt")
- try FileManager.default.createDirectory(at: stubborn, withIntermediateDirectories: true)
+ func testSweepTrashClearsWhatAnEarlierPurgeLeft() throws {
+ let stale = paths.trash.appending(path: "play-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: stale.appending(path: "drive_c"), withIntermediateDirectories: true)
+ try "x".write(to: stale.appending(path: "drive_c/f"), atomically: true, encoding: .utf8)
- _ = try store.delete("play")
- XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
- // Nothing genuinely unpurgeable here, so the sweep has nothing to report and .trash empties.
- XCTAssertTrue(store.sweepTrash().isEmpty)
- let left = (try? FileManager.default.contentsOfDirectory(at: paths.trash, includingPropertiesForKeys: nil)) ?? []
- XCTAssertTrue(left.isEmpty, "a purgeable tree must not linger in .trash")
- }
-
- /// The purge deletes recursively and shells out to rm -rf, so it must refuse a shallow
- /// path outright rather than trust every future caller. "/" and a bare home must be inert.
- func testPurgeRefusesShallowPaths() {
- for dangerous in ["/", "/Users", "/Users/someone", "/Volumes"] {
- let failures = Purge.tree(at: URL(fileURLWithPath: dangerous))
- XCTAssertEqual(failures.first?.code, EINVAL, "\(dangerous) must be refused, not purged")
- XCTAssertTrue(FileManager.default.fileExists(atPath: "/Users"), "/Users must still exist")
- }
+ XCTAssertTrue(store.sweepTrash().isEmpty, "a purgeable leftover must not be reported as a failure")
+ let trash = (try? FileManager.default.contentsOfDirectory(atPath: paths.trash.path)) ?? []
+ XCTAssertEqual(trash, [], "sweepTrash left the tree behind")
}
- /// Bottle names reach the trash path, so they must not be able to steer it.
func testTrashNameCannotEscapeTheTrashDirectory() {
XCTAssertFalse(BottleStore.trashName("../../etc").contains("/"))
XCTAssertFalse(BottleStore.trashName("..").contains("."))