Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

fix(keeper): wait for Steam's update to settle before re-applying (#2061)

Raystormsefed7b7d8e99
diff --git a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
index 95a7de1..a2cfadb 100644
--- a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
@@ -102,6 +102,7 @@ enum SteamInstaller {
_ = try RunnerPatcher.install(build: build, root: root, bridge: bridge)
},
stopClient: ClientStopper = stopTheClient,
+ steamClosed: () -> Bool = steamStaysClosed,
register: BundleRegistrar = { SteamBundle.register($0) },
resetInputAccess: () -> [String] = resetInputAccess,
onInputReset: ([String]) -> Void = { _ in },
@@ -211,16 +212,16 @@ enum SteamInstaller {
report(.signing)
try LocalSigning.unlocked(signingIdentity()) { identity in
- try sign(dylib, identity: identity)
- try sign(app.appending(path: "Contents/MacOS/steam_osx"), identity: identity)
- try sign(app, identity: identity)
+ try sign(dylib, identity: identity, steamClosed: steamClosed)
+ try sign(app.appending(path: "Contents/MacOS/steam_osx"), identity: identity, steamClosed: steamClosed)
+ try sign(app, identity: identity, steamClosed: steamClosed)
}
} catch {
do {
- try revertPlist(priorPlist, at: plist, app: app)
+ try revertPlist(priorPlist, at: plist, app: app, steamClosed: steamClosed)
} catch let revertFailure {
AppLog.note("install: putting the plist back failed: \(revertFailure.localizedDescription)")
- throw StepFailure(step: step, detail: error.localizedDescription + " " + String(localized: "Putting Steam back as it was also failed, so Steam may not start: \(revertFailure.localizedDescription) Use Repair Steam to restore it."))
+ throw revertFailed(error, revertFailure)
}
throw error
}
@@ -354,8 +355,18 @@ enum SteamInstaller {
&& SteamBundle.currentControllerBlock(at: plist) == SteamBundle.controllerBlockValue
let file = DeploymentContent.File(source: shipping, destination: dylib, name: "notproton.dylib", allowsResigning: true)
if deployed, try file.matches() {
- AppLog.note("install: Steam already carries this dylib, installing for this account only")
- return false
+ if sealIsIntact(app) {
+ AppLog.note("install: Steam already carries this dylib, installing for this account only")
+ return false
+ }
+ // Signing failed and the plist could not be put back (#1931): sign it again.
+ do {
+ try assertBundleIsWritable(app)
+ } catch let refusal as WriteRefused {
+ guard let detail = brokenSealDetail(refusal.remedy) else { throw refusal }
+ throw StepFailure(step: step, detail: detail)
+ }
+ return true
}
do {
@@ -367,6 +378,26 @@ enum SteamInstaller {
return true
}
+ // A codesign that can't run says nothing about the seal, so it counts as intact.
+ static func sealIsIntact(_ app: URL) -> Bool {
+ guard let result = try? Shell.run("/usr/bin/codesign", ["--verify", app.path(percentEncoded: false)])
+ else { return true }
+ if !result.succeeded {
+ AppLog.note("install: Steam's signature no longer matches: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))")
+ }
+ return result.succeeded
+ }
+
+ // What to say when Steam's seal is broken and this account can't sign it again.
+ static func brokenSealDetail(_ remedy: Remedy) -> String? {
+ let lead = String(localized: "Steam's signature no longer matches its files, so Steam may not start, and this account cannot sign it again.")
+ return switch remedy {
+ case .otherAccount: lead + " " + String(localized: "Install Bridgeplay again from the account that owns Steam.")
+ case .rootOwned: lead + " " + remedy.advice
+ case .appManagement, .ownership: nil
+ }
+ }
+
// What to say when Steam.app can't be written for a reason this account can't fix.
static func refusalDetail(_ remedy: Remedy, deployed: Bool) -> String? {
switch remedy {
@@ -428,12 +459,55 @@ enum SteamInstaller {
return true
}
+ // The signing failure already names this step, so it is not said twice. Retryable as
+ // the signing failure was: a later install puts the plist and signature right.
+ static func revertFailed(_ error: Error, _ revertFailure: Error) -> StepFailure {
+ let own = error as? StepFailure
+ let cause = own.flatMap { $0.step == step ? $0.detail : nil } ?? error.localizedDescription
+ return StepFailure(
+ step: step,
+ detail: cause + " " + String(localized: "Putting Steam back as it was also failed, so Steam may not start: \(revertFailure.localizedDescription) Use Repair Steam to restore it."),
+ retryable: own?.retryable == true)
+ }
+
// Throws when either half fails: a plist that still declares the insert, or a bundle
- // whose seal no longer matches it, is a Steam that does not start.
- static func revertPlist(_ bytes: Data?, at plist: URL, app: URL) throws {
+ // whose seal no longer matches it, is a Steam that does not start. Tried again after a
+ // pause first, since what made signing fail (Steam's updater still writing, #1931) can
+ // refuse this write for a moment too.
+ static func revertPlist(
+ _ bytes: Data?, at plist: URL, app: URL,
+ attempts: Int = 3,
+ pause: (TimeInterval) -> Void = { Thread.sleep(forTimeInterval: $0) },
+ steamClosed: () -> Bool = steamStaysClosed,
+ resign: (URL) throws -> Void = { try adHocSign($0) }
+ ) throws {
guard let bytes else { return }
- try WriteRefused.catching(plist) { try bytes.write(to: plist) }
- try adHocSign(app)
+ // Signing may have stopped because Steam opened; re-signing a running Steam can get
+ // it killed, so it is left as it is and reported.
+ guard steamClosed() else { throw ClientStarted() }
+ for attempt in 1... {
+ do {
+ // Atomic like the write being undone: a read-only plist can be replaced but
+ // not opened, so a plain write fails every time.
+ try WriteRefused.catching(plist) { try bytes.write(to: plist, options: .atomic) }
+ try resign(app)
+ return
+ } catch where attempt < attempts {
+ AppLog.note("install: putting the plist back failed (try \(attempt)): \(error.localizedDescription)")
+ pause(retryPause * Double(attempt))
+ guard steamClosed() else { throw error }
+ }
+ }
+ }
+
+ static let retryPause: TimeInterval = 2
+
+ // A retry waits a moment, and Steam may have opened since; its bundle is then left alone.
+ // Checked again before putting the plist back.
+ static func steamStaysClosed() -> Bool {
+ guard SteamBundle.isRunning else { return true }
+ AppLog.note("install: Steam opened, not trying again")
+ return false
}
static func setInsert(at plist: URL, to dylib: URL) throws {
@@ -451,8 +525,8 @@ enum SteamInstaller {
try SteamBundle.writeInfoPlist(dict, at: plist)
}
- static func adHocSign(_ url: URL, step: String = step) throws {
- try sign(url, identity: "-", step: step)
+ static func adHocSign(_ url: URL, step: String = step, steamClosed: () -> Bool = steamStaysClosed) throws {
+ try sign(url, identity: "-", step: step, steamClosed: steamClosed)
}
// A self-signed code signing identity, in Bridgeplay's own keychain (or the login keychain
@@ -466,28 +540,58 @@ enum SteamInstaller {
LocalSigning.existing()
}
- static func sign(_ url: URL, identity: LocalSigning.Identity?, step: String = step) throws {
- try sign(url, identity: identity?.hash ?? "-", keychain: identity?.keychain, step: step)
+ static func sign(_ url: URL, identity: LocalSigning.Identity?, step: String = step,
+ steamClosed: () -> Bool = steamStaysClosed) throws {
+ try sign(url, identity: identity?.hash ?? "-", keychain: identity?.keychain, step: step, steamClosed: steamClosed)
}
- static func sign(_ url: URL, identity: String, keychain: URL? = nil, step: String = step) throws {
+ typealias Codesign = ([String]) throws -> CommandResult
+
+ // codesign says this when a file in the bundle changes under it, as when Steam's updater
+ // is still writing into Steam.app (#1931). Another try a moment later usually works.
+ static let transientSigningErrors = ["internal error in Code Signing subsystem"]
+ static let signingRetries = 2
+
+ static func isTransientSigningError(_ stderr: String) -> Bool {
+ transientSigningErrors.contains { stderr.contains($0) }
+ }
+
+ static func sign(
+ _ url: URL, identity: String, keychain: URL? = nil, step: String = step,
+ codesign: Codesign = { try Shell.run("/usr/bin/codesign", $0) },
+ pause: (TimeInterval) -> Void = { Thread.sleep(forTimeInterval: $0) },
+ steamClosed: () -> Bool = steamStaysClosed
+ ) throws {
let path = url.path(percentEncoded: false)
let lookup = keychain.map { ["--keychain", $0.path(percentEncoded: false)] } ?? []
- var result = try Shell.run("/usr/bin/codesign", ["-f", "-s", identity] + lookup + [path])
- // Fixes codesign refusing a Steam.app that carries Finder info or a resource fork.
- if !result.succeeded, result.stderr.contains("detritus not allowed") {
- clearFinderData(in: enclosingBundle(of: url))
- result = try Shell.run("/usr/bin/codesign", ["-f", "-s", identity] + lookup + [path])
+ func attempt() throws -> CommandResult {
+ var result = try codesign(["-f", "-s", identity] + lookup + [path])
+ // Fixes codesign refusing a Steam.app that carries Finder info or a resource fork.
+ if !result.succeeded, result.stderr.contains("detritus not allowed") {
+ clearFinderData(in: enclosingBundle(of: url))
+ result = try codesign(["-f", "-s", identity] + lookup + [path])
+ }
+ // A keychain that refuses the identity must not leave Steam unsigned.
+ if !result.succeeded, identity != "-" {
+ result = try codesign(["-f", "-s", "-", path])
+ }
+ return result
}
- // A keychain that refuses the identity must not leave Steam unsigned.
- if !result.succeeded, identity != "-" {
- result = try Shell.run("/usr/bin/codesign", ["-f", "-s", "-", path])
+ var result = try attempt()
+ var retries = 0
+ while !result.succeeded, isTransientSigningError(result.stderr), retries < signingRetries {
+ retries += 1
+ AppLog.note("install: codesign hit a transient error on \(url.lastPathComponent), trying again (\(retries))")
+ pause(retryPause * Double(retries))
+ guard steamClosed() else { break }
+ result = try attempt()
}
guard result.succeeded else {
throw StepFailure(
step: step,
detail: String(localized: "\(path) could not be signed. ")
- + result.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ + result.stderr.trimmingCharacters(in: .whitespacesAndNewlines),
+ retryable: isTransientSigningError(result.stderr)
)
}
}
diff --git a/app/Sources/BridgeplayApp/Model/SteamPatchKeeper.swift b/app/Sources/BridgeplayApp/Model/SteamPatchKeeper.swift
index a56762e..dc45e98 100644
--- a/app/Sources/BridgeplayApp/Model/SteamPatchKeeper.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamPatchKeeper.swift
@@ -3,7 +3,8 @@ import Foundation
// Notices when Steam no longer carries Bridgeplay (a Steam client update rewrites
// Steam.app) or carries an older build (Bridgeplay itself updated), and decides whether to
// put it back silently or to ask. It never touches Steam while Steam or a game runs, so it
-// cannot fight Steam's own updater, and it tries on its own at most once per cooldown.
+// cannot fight Steam's own updater, and it tries on its own at most once per cooldown
+// (a try that hits a Steam still settling gets a couple of retries, see reapply).
enum SteamPatchKeeper {
// Set by Repair Steam, cleared by any install: a Steam the user restored on purpose
@@ -80,6 +81,79 @@ enum SteamPatchKeeper {
gameRunning)
}
+ // MARK: Waiting for Steam's update to finish
+
+ // Steam's updater rewrites Steam.app in place. Going in while it still writes made both
+ // codesign and the plist write fail (#1931), so the keeper waits until nothing in the
+ // bundle has changed for `settleQuiet`, and gives up after `settleTimeout`.
+ static let settleQuiet: TimeInterval = 15
+ static let settleTimeout: TimeInterval = 120
+ static let settlePoll: Duration = .seconds(3)
+ // Tries per re-apply; a failure that may pass is held back until the last one.
+ static let maxAttempts = 3
+
+ // True once settled, false on timeout. A bundle it can't read counts as settled and is
+ // left to the install to report.
+ @MainActor
+ static func waitForSteamToSettle(
+ lastChange: () async -> Date?,
+ quiet: TimeInterval = settleQuiet,
+ timeout: TimeInterval = settleTimeout,
+ poll: Duration = settlePoll,
+ now: () -> Date = Date.init,
+ sleep: (Duration) async -> Void = { try? await Task.sleep(for: $0) }
+ ) async -> Bool {
+ let start = now()
+ while true {
+ guard let changed = await lastChange() else { return true }
+ let current = now()
+ if current.timeIntervalSince(changed) >= quiet { return true }
+ if current.timeIntervalSince(start) >= timeout { return false }
+ await sleep(poll)
+ }
+ }
+
+ // The newest status change of anything in the bundle, folders included, so a file
+ // added, replaced or removed counts too. ctime, because an updater can set mtimes back.
+ static func lastChange(in app: URL) -> Date? {
+ let root = app.path(percentEncoded: false)
+ func changed(_ path: String) -> Date? {
+ var info = stat()
+ guard lstat(path, &info) == 0 else { return nil }
+ let time = info.st_ctimespec
+ return Date(timeIntervalSince1970: TimeInterval(time.tv_sec) + TimeInterval(time.tv_nsec) / 1e9)
+ }
+ guard var newest = changed(root) else { return nil }
+ let walk = FileManager.default.enumerator(atPath: root)
+ while let relative = walk?.nextObject() as? String {
+ if let date = changed(root + "/" + relative), date > newest { newest = date }
+ }
+ return newest
+ }
+
+ static func isRetryable(_ error: Error?) -> Bool {
+ (error as? StepFailure)?.retryable == true
+ }
+
+ // Runs up to `maxAttempts` tries. Each try after a removedBySteam, and every retry, first
+ // waits for Steam.app to settle (told whether it is a retry); `settle` returning false
+ // stops. `attempt` is told whether a later try remains and returns true when it held a
+ // failure back for one.
+ @MainActor
+ static func reapply(
+ _ kind: Kind,
+ maxAttempts: Int = maxAttempts,
+ settle: (_ retrying: Bool) async -> Bool,
+ attempt: (_ number: Int, _ mayRetry: Bool) async -> Bool
+ ) async {
+ for number in 1...maxAttempts {
+ if kind == .removedBySteam || number > 1 {
+ guard await settle(number > 1) else { return }
+ }
+ guard await attempt(number, number < maxAttempts) else { return }
+ }
+ }
+
struct Banner: Equatable, Sendable {
let kind: Kind
let blocker: Blocker
diff --git a/app/Sources/BridgeplayApp/Model/Uninstall.swift b/app/Sources/BridgeplayApp/Model/Uninstall.swift
index 3782297..958a910 100644
--- a/app/Sources/BridgeplayApp/Model/Uninstall.swift
+++ b/app/Sources/BridgeplayApp/Model/Uninstall.swift
@@ -214,7 +214,8 @@ enum Uninstall {
)
}
- static func detach(from app: URL, innerPlist: URL, updateBlocks: [URL]) throws -> Bool {
+ static func detach(from app: URL, innerPlist: URL, updateBlocks: [URL],
+ steamClosed: () -> Bool = SteamInstaller.steamStaysClosed) throws -> Bool {
let files = FileManager.default
let plist = app.appending(path: "Contents/Info.plist")
let dylib = app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)")
@@ -233,12 +234,15 @@ enum Uninstall {
guard cleared || droppedDylib else { return false }
- try SteamInstaller.adHocSign(executable, step: step)
- try SteamInstaller.adHocSign(app, step: step)
+ try SteamInstaller.adHocSign(executable, step: step, steamClosed: steamClosed)
+ try SteamInstaller.adHocSign(app, step: step, steamClosed: steamClosed)
} catch {
+ // Signing a Steam that opened meanwhile can get it killed, so it is left alone;
+ // checked before each, since the first can pause for a retry.
if cleared || droppedDylib {
- try? SteamInstaller.adHocSign(executable, step: step)
- try? SteamInstaller.adHocSign(app, step: step)
+ for target in [executable, app] where steamClosed() {
+ try? SteamInstaller.adHocSign(target, step: step, steamClosed: steamClosed)
+ }
}
throw error
}
diff --git a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
index 92df199..324931a 100644
--- a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
+++ b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings
@@ -5650,6 +5650,22 @@
}
}
},
+ "Install Bridgeplay again from the account that owns Steam." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Installa di nuovo Bridgeplay dall'account a cui appartiene Steam."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "请使用安装 Steam 的账户重新安装 Bridgeplay。"
+ }
+ }
+ }
+ },
"Install Bridgeplay into Steam below, or run the Setup Assistant." : {
"localizations" : {
"it" : {
@@ -10277,6 +10293,22 @@
}
}
},
+ "Steam's signature no longer matches its files, so Steam may not start, and this account cannot sign it again." : {
+ "localizations" : {
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "La firma di Steam non corrisponde più ai suoi file, quindi Steam potrebbe non avviarsi, e questo account non può firmarlo di nuovo."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Steam 的签名已与其文件不符,Steam 可能无法启动,且当前账户无法重新签名。"
+ }
+ }
+ }
+ },
"Steam's update removed Bridgeplay, so Windows games won't start." : {
"localizations" : {
"it" : {
diff --git a/app/Sources/BridgeplayApp/Support/StepFailure.swift b/app/Sources/BridgeplayApp/Support/StepFailure.swift
index 38b971c..c30b3c6 100644
--- a/app/Sources/BridgeplayApp/Support/StepFailure.swift
+++ b/app/Sources/BridgeplayApp/Support/StepFailure.swift
@@ -3,6 +3,9 @@ import Foundation
struct StepFailure: LocalizedError {
let step: String
let detail: String
+ // A failure that another try a little later may not hit, such as Steam's updater still
+ // writing into Steam.app.
+ var retryable = false
var errorDescription: String? { "\(step): \(detail)" }
}
diff --git a/app/Sources/BridgeplayApp/SystemStatus.swift b/app/Sources/BridgeplayApp/SystemStatus.swift
index ad9718f..1675f51 100644
--- a/app/Sources/BridgeplayApp/SystemStatus.swift
+++ b/app/Sources/BridgeplayApp/SystemStatus.swift
@@ -454,8 +454,11 @@ final class SystemStatus {
return String(localized: "Compatibility tool ready. \(Self.toolsRestartHint)")
}
+ // `holdBack` keeps a failure out of the Status page (it is still logged and kept in
+ // lastRunError) when the caller is about to try again.
func perform(
from first: String,
+ holdBack: (Error) -> Bool = { _ in false },
_ body: (_ progress: @escaping @Sendable (String) -> Void) async throws -> String?
) async {
guard !runInFlight else {
@@ -475,6 +478,9 @@ final class SystemStatus {
outcome = try await body { label in
Task { @MainActor in self.report(run, label) }
}
+ } catch where holdBack(error) {
+ lastRunError = error
+ AppLog.note("run failed, trying again: \(error.localizedDescription)")
} catch {
record(error)
}
@@ -623,13 +629,13 @@ final class SystemStatus {
// unattended: nobody pressed anything, so a Steam that opened since the decision to
// install is left running and the install stops instead.
- func installIntoSteam(unattended: Bool = false) async {
+ func installIntoSteam(unattended: Bool = false, holdBack: (Error) -> Bool = { _ in false }) async {
if let refusal = MigrationLaunch.shared.refusal {
setFailure(refusal)
AppLog.note("run refused: install waits for the 3.0 folder move")
return
}
- await perform(from: InstallPhase.checkingPayload.label) { progress in
+ await perform(from: InstallPhase.checkingPayload.label, holdBack: holdBack) { progress in
let lock = try DeploymentContent.acquireInstallationLock()
defer { lock.release() }
let stopClient = unattended ? SteamInstaller.leaveTheClient : SteamInstaller.stopTheClient
@@ -733,6 +739,7 @@ final class SystemStatus {
@ObservationIgnored private var lastPatchCheck: Date?
@ObservationIgnored private var lastAutoReapply: Date?
@ObservationIgnored private var autoReapplyFailed = false
+ @ObservationIgnored private var autoReapplying = false
// Called at launch, when the app comes to the front and every few minutes. Re-applies
// Bridgeplay on its own only while Steam and every game are closed; otherwise it shows
@@ -764,19 +771,87 @@ final class SystemStatus {
if banner != patchBanner { AppLog.note("patch keeper (\(trigger)): \(kind) waits, \(blocker)") }
patchBanner = banner
case .reapply(let kind):
- guard isIdle else { return }
- AppLog.note("patch keeper (\(trigger)): re-applying on its own, \(kind)")
- lastAutoReapply = now
- await installIntoSteam(unattended: true)
- if lastRunError is SteamInstaller.ClientStarted {
- // Not a failure: Steam opened in the meantime, so ask as if it had been open.
- AppLog.note("patch keeper (\(trigger)): Steam opened before re-applying, asking instead")
- clearFailure()
- patchBanner = SteamPatchKeeper.Banner(kind: kind, blocker: .steamRunning)
- return
+ guard isIdle, !autoReapplying else { return }
+ autoReapplying = true
+ defer { autoReapplying = false }
+ // A failure kept back for a retry that never ran is reported after all: it can
+ // leave a Steam that still declares Bridgeplay but whose seal is broken.
+ var heldBack: Error?
+ var heldBackRun = generation
+ await SteamPatchKeeper.reapply(kind) { retrying in
+ await waitForSteamToSettle(trigger: trigger, retryingAfter: retrying ? heldBackRun : nil)
+ } attempt: { number, mayRetry in
+ // The wait gave the user time to start something of their own.
+ guard isIdle else { return false }
+ AppLog.note("patch keeper (\(trigger)): re-applying on its own, \(kind)\(number > 1 ? ", try \(number)" : "")")
+ lastAutoReapply = Date()
+ await installIntoSteam(unattended: true) { mayRetry && SteamPatchKeeper.isRetryable($0) }
+ if lastRunError is SteamInstaller.ClientStarted {
+ // Not a failure: Steam opened in the meantime, so ask as if it had been open.
+ AppLog.note("patch keeper (\(trigger)): Steam opened before re-applying, asking instead")
+ clearFailure()
+ patchBanner = SteamPatchKeeper.Banner(kind: kind, blocker: .steamRunning)
+ // This try changed nothing, so an earlier held-back failure still stands.
+ heldBackRun = generation
+ return false
+ }
+ if failure == nil, let error = lastRunError {
+ AppLog.note("patch keeper (\(trigger)): Steam was still changing, trying again")
+ heldBack = error
+ heldBackRun = generation
+ return true
+ }
+ heldBack = nil
+ settleReapply(kind)
+ return false
}
- settleReapply(kind)
+ // A run since then, or one still going (Repair Steam, an install, Remove
+ // Everything), has its own outcome on show. A refresh is not a run.
+ if let heldBack {
+ if heldBackRun == generation, !runInFlight {
+ AppLog.note("patch keeper (\(trigger)): no later try ran, reporting the held-back failure")
+ record(heldBack)
+ settleReapply(kind)
+ } else {
+ AppLog.note("patch keeper (\(trigger)): another run followed, dropping the held-back failure")
+ }
+ }
+ }
+ }
+
+ // False when Steam.app is still changing after the wait, or no longer needs Bridgeplay
+ // put back (Steam or a game started, or the user installed it meanwhile). A retry goes
+ // ahead even when the plist still declares Bridgeplay, since a failed try can leave it
+ // there with the signature broken, but only if no run (Repair Steam, Remove Everything)
+ // has happened since the try that failed.
+ private func waitForSteamToSettle(trigger: String, retryingAfter failedRun: Int?) async -> Bool {
+ let app = SupportPaths.Steam.app
+ let settled = await SteamPatchKeeper.waitForSteamToSettle {
+ await Task.detached(priority: .utility) { SteamPatchKeeper.lastChange(in: app) }.value
}
+ guard settled else {
+ AppLog.note("patch keeper (\(trigger)): Steam.app is still changing, trying again later")
+ return false
+ }
+ let version = AppVersion.bundled
+ let seen = await Task.detached(priority: .utility) { SteamPatchKeeper.capture(bundledVersion: version) }.value
+ // Repair Steam may have paused the keeper while it waited.
+ let paused = UserDefaults.standard.bool(forKey: SteamPatchKeeper.pausedKey)
+ let installBlocked = snapshot?.installContent.blocksInstallation == true
+ let decision = SteamPatchKeeper.decide(SteamPatchKeeper.Inputs(
+ deployment: seen.deployment,
+ previouslyDeployed: seen.previouslyDeployed,
+ steamRunning: seen.steamRunning,
+ gameRunning: seen.gameRunning,
+ paused: paused,
+ installBlocked: installBlocked))
+ if case .reapply = decision { return true }
+ if let failedRun, failedRun == generation, !runInFlight, seen.previouslyDeployed,
+ !paused, !installBlocked, !seen.steamRunning, !seen.gameRunning {
+ return true
+ }
+ AppLog.note("patch keeper (\(trigger)): nothing to re-apply after waiting for Steam, \(decision)")
+ return false
}
func reapplyFromBanner() async {
diff --git a/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift b/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift
index 3bca69a..0860fe7 100644
--- a/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift
+++ b/app/Tests/BridgeplayAppTests/SteamInstallerTests.swift
@@ -142,6 +142,8 @@ struct SteamInstallerTests {
if stopped { onStopping() }
return stopped
},
+ // The scratch bundle is not the Steam that may be open on this Mac.
+ steamClosed: { true },
register: register ?? { calls.register($0) },
resetInputAccess: { calls.resetInputAccess(); return refusedResets },
onInputReset: onInputReset
@@ -419,13 +421,143 @@ struct SteamInstallerTests {
let missing = work.appending(path: "gone/Steam.app")
#expect(throws: (any Error).self) {
- try SteamInstaller.revertPlist(Data("plist".utf8), at: missing.appending(path: "Contents/Info.plist"), app: missing)
+ try SteamInstaller.revertPlist(Data("plist".utf8), at: missing.appending(path: "Contents/Info.plist"), app: missing,
+ pause: { _ in }, steamClosed: { true })
}
#expect(throws: Never.self) {
try SteamInstaller.revertPlist(nil, at: missing.appending(path: "Contents/Info.plist"), app: missing)
}
}
+ @Test("Putting the plist back is tried again before it is reported")
+ func revertRetries() throws {
+ let work = try scratchDirectory("install")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let app = work.appending(path: "Steam.app")
+ let plist = app.appending(path: "Contents/Info.plist")
+ var pauses: [TimeInterval] = []
+ var signed = 0
+
+ // The folder is back by the second try, as when Steam's updater finished writing.
+ try SteamInstaller.revertPlist(Data("plist".utf8), at: plist, app: app, pause: {
+ pauses.append($0)
+ try? FileManager.default.createDirectory(at: plist.deletingLastPathComponent(), withIntermediateDirectories: true)
+ }, steamClosed: { true }, resign: { _ in signed += 1 })
+ #expect(try Data(contentsOf: plist) == Data("plist".utf8))
+ #expect(pauses.count == 1)
+ #expect(signed == 1)
+
+ // A write that keeps failing is reported after the last try, not retried forever.
+ var tries = 0
+ #expect(throws: (any Error).self) {
+ try SteamInstaller.revertPlist(Data("plist".utf8), at: plist, app: app, pause: { _ in }, steamClosed: { true },
+ resign: { _ in tries += 1; throw StepFailure(step: "s", detail: "d") })
+ }
+ #expect(tries == 3)
+
+ // Steam opened (signing stopped for it): its bundle is left as it is.
+ tries = 0
+ #expect(throws: SteamInstaller.ClientStarted.self) {
+ try SteamInstaller.revertPlist(Data("plist".utf8), at: plist, app: app, pause: { _ in }, steamClosed: { false },
+ resign: { _ in tries += 1; throw StepFailure(step: "s", detail: "d") })
+ }
+ #expect(tries == 0)
+ }
+
+ @Test("A read-only plist can still be put back")
+ func revertReplacesReadOnlyPlist() throws {
+ let work = try scratchDirectory("install")
+ defer { try? FileManager.default.removeItem(at: work) }
+ let app = work.appending(path: "Steam.app")
+ let plist = app.appending(path: "Contents/Info.plist")
+ try FileManager.default.createDirectory(at: plist.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("changed".utf8).write(to: plist)
+ try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: plist.path(percentEncoded: false))
+
+ try SteamInstaller.revertPlist(Data("plist".utf8), at: plist, app: app, pause: { _ in }, steamClosed: { true }, resign: { _ in })
+ #expect(try Data(contentsOf: plist) == Data("plist".utf8))
+ }
+
+ @Test("A revert that also failed names the install step once")
+ func revertFailureSaysTheStepOnce() {
+ let signing = StepFailure(step: SteamInstaller.step, detail: "x could not be signed.", retryable: true)
+ let failure = SteamInstaller.revertFailed(signing, WriteRefused(path: "/x", remedy: .ownership))
+ let message = failure.localizedDescription
+ #expect(message.hasPrefix("\(SteamInstaller.step): x could not be signed."))
+ #expect(!message.contains("\(SteamInstaller.step): \(SteamInstaller.step)"))
+ #expect(failure.retryable)
+
+ // A failure from another step keeps its own name.
+ let other = SteamInstaller.revertFailed(StepFailure(step: "Keychain", detail: "locked"), WriteRefused(path: "/x", remedy: .ownership))
+ #expect(other.detail.hasPrefix("Keychain: locked"))
+ #expect(!other.retryable)
+ }
+
+ @Test("A broken seal this account can't sign again is reported, not taken as installed")
+ func brokenSealElsewhereIsReported() throws {
+ let other = try #require(SteamInstaller.brokenSealDetail(.otherAccount))
+ #expect(other.contains("may not start"))
+ #expect(other.contains("account that owns Steam"))
+ #expect(SteamInstaller.brokenSealDetail(.rootOwned(handOver: nil))?.contains("may not start") == true)
+ // These keep the write refusal, whose remedy says what to change on this Mac.
+ #expect(SteamInstaller.brokenSealDetail(.appManagement) == nil)
+ #expect(SteamInstaller.brokenSealDetail(.ownership) == nil)
+ }
+
+ private static func codesignResult(_ stderr: String) -> CommandResult {
+ CommandResult(status: stderr.isEmpty ? 0 : 1, stdout: "", stderr: stderr)
+ }
+
+ @Test("codesign's internal error is retried after a pause, and a later success counts")
+ func signingRetriesTransientError() throws {
+ var results = [Self.codesignResult("x: internal error in Code Signing subsystem"), Self.codesignResult("")]
+ var pauses = 0
+ try SteamInstaller.sign(URL(filePath: "/tmp/x.dylib"), identity: "-",
+ codesign: { _ in results.removeFirst() }, pause: { _ in pauses += 1 }, steamClosed: { true })
+ #expect(results.isEmpty)
+ #expect(pauses == 1)
+ }
+
+ @Test("A codesign that keeps hitting its internal error gives up, and says it may pass later")
+ func signingRetriesAreBounded() throws {
+ var calls = 0
+ let failure = try #require(throws: StepFailure.self) {
+ try SteamInstaller.sign(URL(filePath: "/tmp/x.dylib"), identity: "-", codesign: { _ in
+ calls += 1
+ return Self.codesignResult("x: internal error in Code Signing subsystem")
+ }, pause: { _ in }, steamClosed: { true })
+ }
+ #expect(calls == 1 + SteamInstaller.signingRetries)
+ #expect(failure.retryable)
+ }
+
+ @Test("A Steam that opened during the pause is not signed again")
+ func signingStopsWhenSteamOpens() throws {
+ var calls = 0
+ let failure = try #require(throws: StepFailure.self) {
+ try SteamInstaller.sign(URL(filePath: "/tmp/x.dylib"), identity: "-", codesign: { _ in
+ calls += 1
+ return Self.codesignResult("x: internal error in Code Signing subsystem")
+ }, pause: { _ in }, steamClosed: { false })
+ }
+ #expect(calls == 1)
+ #expect(failure.retryable)
+ }
+
+ @Test("A real codesign failure is reported at once and not marked as passing")
+ func signingDoesNotRetryRealFailures() throws {
+ var calls = 0
+ let failure = try #require(throws: StepFailure.self) {
+ try SteamInstaller.sign(URL(filePath: "/tmp/x.dylib"), identity: "-", codesign: { _ in
+ calls += 1
+ return Self.codesignResult("x: No such file or directory")
+ }, pause: { _ in Issue.record("paused for a failure that does not pass") }, steamClosed: { true })
+ }
+ #expect(calls == 1)
+ #expect(!failure.retryable)
+ #expect(failure.detail.contains("could not be signed"))
+ }
+
@Test("The plist backup records the state before the first install only")
func backsUpOriginalPlistOnce() async throws {
let work = try scratchDirectory("install")
@@ -581,6 +713,21 @@ struct SteamInstallerTests {
)
)
+ // Signing failed and the plist could not be put back: the insert is there but the
+ // seal no longer matches, so the next install signs Steam again.
+ var dict = try #require(SteamBundle.readInfoPlist(at: fixture.plist))
+ dict["BridgeplayTestKey"] = "changed"
+ try SteamBundle.writeInfoPlist(dict, at: fixture.plist)
+ #expect(!SteamInstaller.sealIsIntact(fixture.app))
+ #expect(
+ try SteamInstaller.needsPatching(
+ plist: fixture.plist,
+ dylib: fixture.deployedDylib,
+ shipping: fixture.payload.dylib,
+ app: fixture.app
+ )
+ )
+
try Data("a different build".utf8).write(to: fixture.deployedDylib)
#expect(
diff --git a/app/Tests/BridgeplayAppTests/SteamPatchKeeperTests.swift b/app/Tests/BridgeplayAppTests/SteamPatchKeeperTests.swift
index af35e35..1f0a508 100644
--- a/app/Tests/BridgeplayAppTests/SteamPatchKeeperTests.swift
+++ b/app/Tests/BridgeplayAppTests/SteamPatchKeeperTests.swift
@@ -74,6 +74,120 @@ struct SteamPatchKeeperTests {
#expect(banner.button == "Re-apply Bridgeplay")
}
+ // A clock the settle wait reads and its sleep moves forward, so no test really waits.
+ private final class Clock: @unchecked Sendable {
+ var now = Date(timeIntervalSince1970: 1_000_000)
+ var sleeps = 0
+ func sleep(_ duration: Duration) async {
+ sleeps += 1
+ now += TimeInterval(duration.components.seconds)
+ }
+ }
+
+ @Test("A Steam.app that settled a while ago is re-applied without waiting")
+ @MainActor
+ func settledBundleGoesStraightIn() async {
+ let clock = Clock()
+ let changed = clock.now.addingTimeInterval(-SteamPatchKeeper.settleQuiet - 1)
+ let settled = await SteamPatchKeeper.waitForSteamToSettle(
+ lastChange: { changed }, now: { clock.now }, sleep: clock.sleep)
+ #expect(settled)
+ #expect(clock.sleeps == 0)
+ }
+
+ @Test("A Steam.app still being written is waited on until it has been quiet")
+ @MainActor
+ func waitsWhileSteamWrites() async {
+ let clock = Clock()
+ let start = clock.now
+ // The updater keeps writing for 20 seconds, then stops.
+ let settled = await SteamPatchKeeper.waitForSteamToSettle(
+ lastChange: { min(clock.now, start.addingTimeInterval(20)) },
+ now: { clock.now }, sleep: clock.sleep)
+ #expect(settled)
+ #expect(clock.now.timeIntervalSince(start) >= 20 + SteamPatchKeeper.settleQuiet)
+ #expect(clock.now.timeIntervalSince(start) < SteamPatchKeeper.settleTimeout)
+ }
+
+ @Test("A Steam.app that never settles is given up on, not waited on forever")
+ @MainActor
+ func settleWaitIsBounded() async {
+ let clock = Clock()
+ let start = clock.now
+ let settled = await SteamPatchKeeper.waitForSteamToSettle(
+ lastChange: { clock.now }, now: { clock.now }, sleep: clock.sleep)
+ #expect(!settled)
+ #expect(clock.now.timeIntervalSince(start) >= SteamPatchKeeper.settleTimeout)
+ #expect(clock.now.timeIntervalSince(start) < SteamPatchKeeper.settleTimeout + 10)
+ }
+
+ @Test("A bundle that can't be read is left to the install to report")
+ @MainActor
+ func unreadableBundleCountsAsSettled() async {
+ #expect(await SteamPatchKeeper.waitForSteamToSettle(lastChange: { nil }))
+ }
+
+ @Test("The bundle's last change includes files deep inside it")
+ func lastChangeSeesNestedWrites() throws {
+ let app = try scratchDirectory("keeper").appending(path: "Steam.app")
+ defer { try? FileManager.default.removeItem(at: app.deletingLastPathComponent()) }
+ let macOS = app.appending(path: "Contents/MacOS")
+ try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true)
+ let before = try #require(SteamPatchKeeper.lastChange(in: app))
+ Thread.sleep(forTimeInterval: 0.05)
+ try Data("new".utf8).write(to: macOS.appending(path: "steam_osx"))
+ let after = try #require(SteamPatchKeeper.lastChange(in: app))
+ #expect(after > before)
+ #expect(SteamPatchKeeper.lastChange(in: app.appending(path: "missing")) == nil)
+ }
+
+ @Test("After Steam's update the keeper waits for Steam.app before every try")
+ @MainActor
+ func removedBySteamWaitsFirst() async {
+ var events: [String] = []
+ await SteamPatchKeeper.reapply(.removedBySteam) { retrying in
+ events.append("settle \(retrying)")
+ return true
+ } attempt: { number, mayRetry in
+ events.append("try \(number) \(mayRetry)")
+ return number < 2
+ }
+ #expect(events == ["settle false", "try 1 true", "settle true", "try 2 true"])
+ }
+
+ @Test("An outdated patch goes in at once, and retries stop after the last try")
+ @MainActor
+ func retriesAreBounded() async {
+ var events: [String] = []
+ await SteamPatchKeeper.reapply(.outdated) { retrying in
+ events.append("settle \(retrying)")
+ return true
+ } attempt: { number, mayRetry in
+ events.append("try \(number) \(mayRetry)")
+ return true
+ }
+ #expect(events == ["try 1 true", "settle true", "try 2 true", "settle true", "try 3 false"])
+ }
+
+ @Test("A Steam.app that never settles is not tried at all")
+ @MainActor
+ func unsettledSteamIsNotTouched() async {
+ var tries = 0
+ await SteamPatchKeeper.reapply(.removedBySteam) { _ in false } attempt: { _, _ in
+ tries += 1
+ return true
+ }
+ #expect(tries == 0)
+ }
+
+ @Test("Only a failure marked as passing is retried")
+ func retryableFailures() {
+ #expect(SteamPatchKeeper.isRetryable(StepFailure(step: "s", detail: "d", retryable: true)))
+ #expect(!SteamPatchKeeper.isRetryable(StepFailure(step: "s", detail: "d")))
+ #expect(!SteamPatchKeeper.isRetryable(WriteRefused(path: "/x", remedy: .ownership)))
+ #expect(!SteamPatchKeeper.isRetryable(nil))
+ }
+
@Test("The Input Monitoring link opens the ListenEvent list")
@MainActor
func inputMonitoringLink() {
diff --git a/app/Tests/BridgeplayAppTests/UninstallTests.swift b/app/Tests/BridgeplayAppTests/UninstallTests.swift
index e9d83a8..d7cfc30 100644
--- a/app/Tests/BridgeplayAppTests/UninstallTests.swift
+++ b/app/Tests/BridgeplayAppTests/UninstallTests.swift
@@ -210,15 +210,59 @@ struct UninstallTests {
try Shell.check("/usr/bin/chflags", ["uchg", dylib])
defer { _ = try? Shell.check("/usr/bin/chflags", ["nouchg", dylib]) }
+ // The scratch bundle is not the Steam that may be open on this Mac.
#expect(throws: (any Error).self) {
try Uninstall.detach(
- from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock])
+ from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
+ steamClosed: { true })
}
#expect(SteamBundle.currentInsert(at: layout.outerPlist) == nil)
#expect(try verifies(layout.app))
}
+ @Test("A removal whose signing stopped because Steam opened leaves that Steam alone")
+ func failureWithSteamOpenLeavesItAlone() throws {
+ let layout = try layout(signable: true)
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let dylib = layout.dylib.path(percentEncoded: false)
+ try Shell.check("/usr/bin/chflags", ["uchg", dylib])
+ defer { _ = try? Shell.check("/usr/bin/chflags", ["nouchg", dylib]) }
+ let before = try Data(contentsOf: layout.app.appending(path: "Contents/MacOS/steam_osx"))
+
+ #expect(throws: (any Error).self) {
+ try Uninstall.detach(
+ from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
+ steamClosed: { false })
+ }
+
+ #expect(try Data(contentsOf: layout.app.appending(path: "Contents/MacOS/steam_osx")) == before)
+ }
+
+ @Test("Steam opening between the two recovery signatures stops the second")
+ func steamOpeningMidRecoveryStopsIt() throws {
+ let layout = try layout(signable: true)
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let dylib = layout.dylib.path(percentEncoded: false)
+ try Shell.check("/usr/bin/chflags", ["uchg", dylib])
+ defer { _ = try? Shell.check("/usr/bin/chflags", ["nouchg", dylib]) }
+ let executable = layout.app.appending(path: "Contents/MacOS/steam_osx")
+ let seal = layout.app.appending(path: "Contents/_CodeSignature/CodeResources")
+ let executableBefore = try Data(contentsOf: executable)
+ let sealBefore = try Data(contentsOf: seal)
+
+ // Closed for the executable's signature, open by the time the app's would start.
+ var checks = 0
+ #expect(throws: (any Error).self) {
+ try Uninstall.detach(
+ from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock],
+ steamClosed: { checks += 1; return checks == 1 })
+ }
+
+ #expect(try Data(contentsOf: executable) != executableBefore)
+ #expect(try Data(contentsOf: seal) == sealBefore)
+ }
+
@Test("A restore that fails does not cancel the removal")
func removesEverythingWhenSteamCannotBeRestored() async throws {
let layout = try layout()