diff --git a/palium/ContentView.swift b/palium/ContentView.swift index 2a29e79..232e461 100644 --- a/palium/ContentView.swift +++ b/palium/ContentView.swift @@ -234,9 +234,15 @@ struct ContentView: View { Text("Update Available") .font(.headline) - Text("v\(appState.localGameVersion) → v\(appState.gameVersion)") - .font(.subheadline) - .foregroundStyle(.secondary) + Group { + if appState.localGameVersion == appState.gameVersion { + Text("New content available for v\(appState.gameVersion)") + } else { + Text("v\(appState.localGameVersion) → v\(appState.gameVersion)") + } + } + .font(.subheadline) + .foregroundStyle(.secondary) if let manifest = appState.manifest { Text("\(manifest.files.count) files — only changed files will be downloaded") @@ -415,9 +421,14 @@ struct ContentView: View { // Install VC++ runtime if not already present in prefix if !WineManager.isVCRuntimeInstalled(info: info) { appState.statusMessage = "Installing VC++ runtime..." + appState.showDebugLog = true appState.log("VC++ runtime not found in prefix, installing...") do { - try await WineManager.installVCRuntime(info: info) + try await WineManager.installVCRuntime(info: info) { [appState] message, level in + Task { @MainActor in + appState.log(message, level: level) + } + } appState.log("VC++ runtime installed", level: .success) } catch { appState.log("VC++ runtime install failed: \(error.localizedDescription) — game may still work", level: .warning) @@ -473,19 +484,34 @@ struct ContentView: View { appState.log("Game found at \(info.gameInstallPath.path)", level: .success) let localVersion = LaunchSettings.shared.installedVersion + let localHash = LaunchSettings.shared.installedManifestHash + let cdnHash = appState.manifest?.contentsHash + if let localVersion { appState.localGameVersion = localVersion appState.log("Installed version: \(localVersion)", level: .info) - if localVersion != appState.gameVersion { - appState.log("Update available: \(localVersion) → \(appState.gameVersion)", level: .warning) + let versionChanged = localVersion != appState.gameVersion + // A stale hash always signals a real content change; a missing hash just + // means this build predates hash tracking — backfill it, don't force an update. + let contentChanged = localHash != nil && localHash != cdnHash + + if versionChanged || contentChanged { + let reason = versionChanged + ? "\(localVersion) → \(appState.gameVersion)" + : "content update for v\(appState.gameVersion)" + appState.log("Update available: \(reason)", level: .warning) appState.phase = .needsUpdate } else { + if localHash == nil { + LaunchSettings.shared.installedManifestHash = cdnHash + } appState.phase = .ready } } else { appState.log("No stored version found — assuming up to date", level: .warning) LaunchSettings.shared.installedVersion = appState.gameVersion + LaunchSettings.shared.installedManifestHash = cdnHash appState.phase = .ready } } else { @@ -519,6 +545,7 @@ struct ContentView: View { installDirectory: info.gameInstallPath ) LaunchSettings.shared.installedVersion = appState.gameVersion + LaunchSettings.shared.installedManifestHash = manifest.contentsHash appState.phase = .ready } catch is CancellationError { appState.log("Download cancelled", level: .warning) @@ -550,21 +577,16 @@ struct ContentView: View { ) appState.log("Launching game (DX11, Metal HUD: \(options.metalHUD ? "ON" : "OFF"))...") do { - let process = try GameLauncher.launch(info: info, options: options) - appState.gameProcess = process - appState.phase = .launching - appState.log("Game process started (PID: \(process.processIdentifier))", level: .success) - - // Monitor process in background - Task.detached { - process.waitUntilExit() - let status = process.terminationStatus - await MainActor.run { + let process = try GameLauncher.launch(info: info, options: options) { [appState] status in + Task { @MainActor in appState.log("Game exited with status \(status)", level: status == 0 ? .info : .warning) appState.gameProcess = nil appState.phase = .ready } } + appState.gameProcess = process + appState.phase = .launching + appState.log("Game process started (PID: \(process.processIdentifier))", level: .success) } catch let error as PaliumError { appState.log("Launch failed: \(error.localizedDescription)", level: .error) appState.phase = .error(error) @@ -596,6 +618,8 @@ struct ContentView: View { if corruptFiles.isEmpty { appState.statusMessage = "All files verified successfully" + LaunchSettings.shared.installedVersion = appState.gameVersion + LaunchSettings.shared.installedManifestHash = manifest.contentsHash appState.phase = .ready return } @@ -613,6 +637,8 @@ struct ContentView: View { version: appState.gameVersion, installDirectory: info.gameInstallPath ) + LaunchSettings.shared.installedVersion = appState.gameVersion + LaunchSettings.shared.installedManifestHash = manifest.contentsHash appState.phase = .ready } catch let error as PaliumError { appState.log("Repair failed: \(error.localizedDescription)", level: .error) diff --git a/palium/Models/AppState.swift b/palium/Models/AppState.swift index 11cf30b..3f3acf9 100644 --- a/palium/Models/AppState.swift +++ b/palium/Models/AppState.swift @@ -64,10 +64,12 @@ class AppState { } private static let maxLogEntries = 1000 + // Trim in batches so the O(n) removeFirst runs once per batch, not per append. + private static let logTrimBatch = 100 func log(_ message: String, level: LogEntry.Level = .info) { logEntries.append(LogEntry(level: level, message: message)) - if logEntries.count > Self.maxLogEntries { + if logEntries.count >= Self.maxLogEntries + Self.logTrimBatch { logEntries.removeFirst(logEntries.count - Self.maxLogEntries) } } diff --git a/palium/Models/LaunchSettings.swift b/palium/Models/LaunchSettings.swift index b70820a..e306a71 100644 --- a/palium/Models/LaunchSettings.swift +++ b/palium/Models/LaunchSettings.swift @@ -24,10 +24,26 @@ class LaunchSettings { // Installed game version (persisted to detect updates) var installedVersion: String? { didSet { save() } } + // SHA-256 of the manifest's "contents" node at install time — catches + // content updates the CDN ships without bumping the channel version. + var installedManifestHash: Data? { didSet { save() } } + private static let storageKey = "launchSettings_v2" + /// Suppresses the didSet-triggered save() while restoring persisted values — + /// property observers fire for assignments made during load. + @ObservationIgnored private var isLoaded = false + private init() { - load() + if let data = UserDefaults.standard.data(forKey: Self.storageKey), + let stored = try? JSONDecoder().decode(StoredSettings.self, from: data) { + wineSource = stored.wineSource + metalHUD = stored.metalHUD + useAllCores = stored.useAllCores + installedVersion = stored.installedVersion + installedManifestHash = stored.installedManifestHash + } + isLoaded = true } private struct StoredSettings: Codable { @@ -35,25 +51,17 @@ class LaunchSettings { var metalHUD: Bool = false var useAllCores: Bool = true var installedVersion: String? - } - - private func load() { - guard let data = UserDefaults.standard.data(forKey: Self.storageKey), - let stored = try? JSONDecoder().decode(StoredSettings.self, from: data) else { - return - } - wineSource = stored.wineSource - metalHUD = stored.metalHUD - useAllCores = stored.useAllCores - installedVersion = stored.installedVersion + var installedManifestHash: Data? } private func save() { + guard isLoaded else { return } let stored = StoredSettings( wineSource: wineSource, metalHUD: metalHUD, useAllCores: useAllCores, - installedVersion: installedVersion + installedVersion: installedVersion, + installedManifestHash: installedManifestHash ) if let data = try? JSONEncoder().encode(stored) { UserDefaults.standard.set(data, forKey: Self.storageKey) diff --git a/palium/Models/ManifestModels.swift b/palium/Models/ManifestModels.swift index ae96284..3f8fe42 100644 --- a/palium/Models/ManifestModels.swift +++ b/palium/Models/ManifestModels.swift @@ -1,17 +1,10 @@ import Foundation -struct ManifestChunk: Sendable { - let offset: UInt64 - let size: UInt64 - let hash: Data -} - struct ManifestFile: Sendable, Identifiable { var id: String { path } let path: String let size: UInt64 let hash: Data - let chunks: [ManifestChunk] } struct UpdateManifest: Sendable { @@ -20,4 +13,8 @@ struct UpdateManifest: Sendable { let platform: String let files: [ManifestFile] let totalSize: UInt64 + /// SHA-256 digest over every file's (path, size, hash), computed locally from `files` + /// rather than trusted from the manifest's own "contents.hash" field. Lets us detect + /// content changes the CDN ships without bumping the channel version. + let contentsHash: Data } diff --git a/palium/Services/CDNClient.swift b/palium/Services/CDNClient.swift index e0c1760..9cbc902 100644 --- a/palium/Services/CDNClient.swift +++ b/palium/Services/CDNClient.swift @@ -1,4 +1,5 @@ import Foundation +import CryptoKit nonisolated enum CDNClient { @@ -62,17 +63,19 @@ nonisolated enum CDNClient { // MARK: - Manifest Parsing static func parseManifest(_ data: Data) throws -> UpdateManifest { - let root = try FlexBuffersParser.decode(data) + // Walk the manifest lazily: only the fields we keep are ever decoded, + // which avoids materializing the (large) per-chunk metadata. + let root = try FlexBuffersParser.root(data) - guard let rootMap = root.mapValue else { + guard root.isMap else { throw PaliumError.manifestParseFailed("Root is not a map") } - let bundleName = rootMap["bundle"]?.stringValue ?? "" - let version = rootMap["version"]?.stringValue ?? "" - let platformName = rootMap["platform"]?.stringValue ?? "" + let bundleName = root["bundle"]?.stringValue ?? "" + let version = root["version"]?.stringValue ?? "" + let platformName = root["platform"]?.stringValue ?? "" - guard let contents = rootMap["contents"]?.mapValue else { + guard let contents = root["contents"], contents.isMap else { throw PaliumError.manifestParseFailed("No 'contents' in manifest") } @@ -85,37 +88,44 @@ nonisolated enum CDNClient { version: version, platform: platformName, files: files, - totalSize: totalSize + totalSize: totalSize, + contentsHash: filesDigest(files) ) } - private static func collectFiles(from node: [String: FlexValue], into files: inout [ManifestFile]) { - guard let children = node["files"]?.vectorValue else { return } - - for child in children { - guard let childMap = child.mapValue else { continue } - let path = childMap["path"]?.stringValue ?? "" - let size = childMap["size"]?.uintValue ?? 0 - let hash = childMap["hash"]?.blobValue ?? Data() - - if let chunksVec = childMap["chunks"]?.vectorValue, !chunksVec.isEmpty { - // Leaf file with chunks - let chunks = chunksVec.compactMap { chunkVal -> ManifestChunk? in - guard let arr = chunkVal.vectorValue, arr.count >= 3 else { return nil } - return ManifestChunk( - offset: arr[0].uintValue ?? 0, - size: arr[1].uintValue ?? 0, - hash: arr[2].blobValue ?? Data() - ) - } - files.append(ManifestFile(path: path, size: size, hash: hash, chunks: chunks)) - } else if childMap["files"] != nil { + /// Digest over (path, size, hash) of every file, computed locally rather than trusting + /// the CDN's own "contents.hash" field, which can be absent/empty on a malformed manifest. + /// Sorted by path first since manifest tree-walk order isn't a guaranteed stable key. + private static func filesDigest(_ files: [ManifestFile]) -> Data { + var hasher = SHA256() + for file in files.sorted(by: { $0.path < $1.path }) { + hasher.update(data: Data(file.path.utf8)) + var size = file.size + withUnsafeBytes(of: &size) { hasher.update(bufferPointer: $0) } + hasher.update(data: file.hash) + } + return Data(hasher.finalize()) + } + + private static func collectFiles(from node: FlexRef, into files: inout [ManifestFile]) { + guard let children = node["files"], children.isVector else { return } + + for i in 0.. String { +nonisolated func formatSize(_ bytes: UInt64) -> String { if bytes >= 1024 * 1024 * 1024 { return String(format: "%.2f GB", Double(bytes) / (1024 * 1024 * 1024)) } else if bytes >= 1024 * 1024 { @@ -27,32 +27,42 @@ func formatSize(_ bytes: UInt64) -> String { return "\(bytes) B" } -// MARK: - URLSession Download Delegate (reports per-chunk progress) +// MARK: - URLSession Delegate (one session, routes callbacks per task) -private final class FileDownloadDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { - private let onBytesWritten: @Sendable (Int64) -> Void - private let onComplete: @Sendable (Result<(URL, URLResponse), Error>) -> Void - private let lock = OSAllocatedUnfairLock(initialState: State()) - weak var session: URLSession? +private final class DownloadSessionDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { + + struct Handler { + let onBytesWritten: @Sendable (Int64) -> Void + let onComplete: @Sendable (Result<(URL, URLResponse), Error>) -> Void + } private struct State { - var didResume = false - var lastReportedBytes: Int64 = 0 + var handlers: [Int: Handler] = [:] + var lastReportedBytes: [Int: Int64] = [:] + /// Results for tasks that completed before register() ran — possible + /// when a task is cancelled immediately after creation. + var orphanResults: [Int: Result<(URL, URLResponse), Error>] = [:] } - init( - onBytesWritten: @escaping @Sendable (Int64) -> Void, - onComplete: @escaping @Sendable (Result<(URL, URLResponse), Error>) -> Void - ) { - self.onBytesWritten = onBytesWritten - self.onComplete = onComplete + private let state = OSAllocatedUnfairLock(initialState: State()) + + func register(_ task: URLSessionTask, handler: Handler) { + let orphan = state.withLock { s -> Result<(URL, URLResponse), Error>? in + if let result = s.orphanResults.removeValue(forKey: task.taskIdentifier) { + return result + } + s.handlers[task.taskIdentifier] = handler + return nil + } + if let orphan { + handler.onComplete(orphan) + } } - private func tryResume() -> Bool { - lock.withLock { state in - if state.didResume { return false } - state.didResume = true - return true + private func takeHandler(for task: URLSessionTask) -> Handler? { + state.withLock { s in + s.lastReportedBytes[task.taskIdentifier] = nil + return s.handlers.removeValue(forKey: task.taskIdentifier) } } @@ -63,15 +73,14 @@ private final class FileDownloadDelegate: NSObject, URLSessionDownloadDelegate, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64 ) { - // Throttle: report every 256 KB to avoid flooding the actor - let shouldReport = lock.withLock { state -> Bool in - guard totalBytesWritten - state.lastReportedBytes >= 262_144 else { return false } - state.lastReportedBytes = totalBytesWritten - return true - } - if shouldReport { - onBytesWritten(totalBytesWritten) + // Throttle: report every 256 KB per task to avoid flooding the actor + let handler = state.withLock { s -> Handler? in + let id = downloadTask.taskIdentifier + guard totalBytesWritten - (s.lastReportedBytes[id] ?? 0) >= 262_144 else { return nil } + s.lastReportedBytes[id] = totalBytesWritten + return s.handlers[id] } + handler?.onBytesWritten(totalBytesWritten) } func urlSession( @@ -79,25 +88,26 @@ private final class FileDownloadDelegate: NSObject, URLSessionDownloadDelegate, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL ) { - // Copy file before the system deletes it when this method returns + // Move the file before the system deletes it when this method returns let tempFile = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString) + let result: Result<(URL, URLResponse), Error> do { - try FileManager.default.copyItem(at: location, to: tempFile) - guard tryResume() else { return } - let response = downloadTask.response ?? URLResponse() - onComplete(.success((tempFile, response))) + try FileManager.default.moveItem(at: location, to: tempFile) + result = .success((tempFile, downloadTask.response ?? URLResponse())) } catch { - guard tryResume() else { return } - onComplete(.failure(error)) + result = .failure(error) } + takeHandler(for: downloadTask)?.onComplete(result) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - self.session?.finishTasksAndInvalidate() - if let error = error { - guard tryResume() else { return } - onComplete(.failure(error)) + // Success is delivered in didFinishDownloadingTo; only errors arrive here. + guard let error else { return } + if let handler = takeHandler(for: task) { + handler.onComplete(.failure(error)) + } else { + state.withLock { $0.orphanResults[task.taskIdentifier] = .failure(error) } } } } @@ -116,9 +126,16 @@ actor DownloadManager { private let onProgress: @Sendable (DownloadProgress) -> Void private let onLog: @Sendable (String, LogEntry.Level) -> Void - private static let maxHashVerifySize: UInt64 = 2 * 1024 * 1024 * 1024 // 2 GB private static let maxConcurrent = 4 + private static let sessionDelegate = DownloadSessionDelegate() + private static let session: URLSession = { + let config = URLSessionConfiguration.default + config.timeoutIntervalForRequest = 300 // 5 min per request + config.timeoutIntervalForResource = 43200 // 12 hour total per file + return URLSession(configuration: config, delegate: sessionDelegate, delegateQueue: nil) + }() + init( onProgress: @escaping @Sendable (DownloadProgress) -> Void, onLog: @escaping @Sendable (String, LogEntry.Level) -> Void = { _, _ in } @@ -143,6 +160,36 @@ actor DownloadManager { onLog("Starting download: \(files.count) files, \(formatSize(manifest.totalSize))", .info) onLog("Install directory: \(installDirectory.path)", .info) + try await downloadThrottled(files: files, version: version, installDirectory: installDirectory) + + onLog("All downloads complete", .success) + } + + func repairFiles( + files: [ManifestFile], + version: String, + installDirectory: URL + ) async throws { + totalBytes = files.reduce(0) { $0 + Int64($1.size) } + downloadedBytes = 0 + inFlightBytes = [:] + filesTotal = files.count + filesCompleted = 0 + + onLog("Repairing \(files.count) files (\(formatSize(UInt64(totalBytes))))", .info) + sendProgress() + + try await downloadThrottled(files: files, version: version, installDirectory: installDirectory) + + onLog("Repair complete", .success) + } + + /// Download files with at most `maxConcurrent` in flight at a time. + private func downloadThrottled( + files: [ManifestFile], + version: String, + installDirectory: URL + ) async throws { // Sort files smallest first so small files complete quickly let sortedFiles = files.sorted { $0.size < $1.size } @@ -169,8 +216,6 @@ actor DownloadManager { } } } - - onLog("All downloads complete", .success) } private func downloadFile( @@ -180,18 +225,29 @@ actor DownloadManager { ) async throws { let destURL = installDirectory.appendingPathComponent(file.path) let fm = FileManager.default + defer { inFlightBytes.removeValue(forKey: file.path) } - // Check if file already exists with correct size (skip re-download) + // Skip re-download only if both size and content hash match — a changed + // file of identical size (e.g. an in-place patch) must be re-fetched. if fm.fileExists(atPath: destURL.path), let attrs = try? fm.attributesOfItem(atPath: destURL.path), let existingSize = attrs[.size] as? UInt64, existingSize == file.size { - onLog("SKIP (exists): \(file.path) (\(formatSize(file.size)))", .info) - downloadedBytes += Int64(file.size) - filesCompleted += 1 - currentFile = file.path - sendProgress() - return + let hashMatches: Bool + if file.hash.isEmpty { + hashMatches = true + } else { + hashMatches = (try? await Self.computeHash(at: destURL)) == file.hash + } + if hashMatches { + onLog("SKIP (up to date): \(file.path) (\(formatSize(file.size)))", .info) + downloadedBytes += Int64(file.size) + filesCompleted += 1 + currentFile = file.path + sendProgress() + return + } + onLog("STALE (hash changed): \(file.path) — re-downloading", .warning) } // Create parent directories @@ -206,13 +262,15 @@ actor DownloadManager { // Download with real-time progress tracking let filePath = file.path - let (tempURL, response) = try await Self.downloadWithProgress(from: url) { totalBytesWritten in - Task { await self.updateInFlightBytes(fileName: filePath, bytes: totalBytesWritten) } + let (tempURL, response): (URL, URLResponse) + do { + (tempURL, response) = try await Self.downloadWithProgress(from: url) { totalBytesWritten in + Task { await self.updateInFlightBytes(fileName: filePath, bytes: totalBytesWritten) } + } + } catch let error as URLError where error.code == .cancelled { + throw CancellationError() } - // Clear in-flight tracking for this file - inFlightBytes.removeValue(forKey: file.path) - if let httpResponse = response as? HTTPURLResponse, !(200..<300).contains(httpResponse.statusCode) { try? fm.removeItem(at: tempURL) onLog("HTTP ERROR \(httpResponse.statusCode): \(file.path)", .error) @@ -238,9 +296,9 @@ actor DownloadManager { } } - // Verify hash for files under the size threshold - if file.size <= Self.maxHashVerifySize && !file.hash.isEmpty { - let actualHash = try Self.hashFile(at: destURL) + // Verify hash + if !file.hash.isEmpty { + let actualHash = try await Self.computeHash(at: destURL) if actualHash != file.hash { onLog("HASH MISMATCH: \(file.path)", .error) try? fm.removeItem(at: destURL) @@ -260,11 +318,27 @@ actor DownloadManager { sendProgress() } - /// Hash a file using memory-mapped I/O. + // MARK: - Hashing + + /// Hash a file in fixed-size chunks so large files never need to be + /// resident in memory all at once. private static nonisolated func hashFile(at url: URL) throws -> Data { - let mapped = try Data(contentsOf: url, options: .mappedIfSafe) - let digest = SHA256.hash(data: mapped) - return Data(digest) + let handle = try FileHandle(forReadingFrom: url) + defer { try? handle.close() } + var hasher = SHA256() + while true { + let chunk = try autoreleasepool { try handle.read(upToCount: 1_048_576) } + guard let chunk, !chunk.isEmpty else { break } + hasher.update(data: chunk) + } + return Data(hasher.finalize()) + } + + /// Hash off the actor so progress callbacks stay responsive. + private static nonisolated func computeHash(at url: URL) async throws -> Data { + try await Task.detached(priority: .utility) { + try hashFile(at: url) + }.value } // MARK: - Download with Progress @@ -273,23 +347,17 @@ actor DownloadManager { from url: URL, onBytesWritten: @escaping @Sendable (Int64) -> Void ) async throws -> (URL, URLResponse) { - try await withCheckedThrowingContinuation { continuation in - let delegate = FileDownloadDelegate( - onBytesWritten: onBytesWritten, - onComplete: { result in - continuation.resume(with: result) - } - ) - let config = URLSessionConfiguration.default - config.timeoutIntervalForRequest = 300 // 5 min per request - config.timeoutIntervalForResource = 43200 // 12 hour total per file - let session = URLSession( - configuration: config, - delegate: delegate, - delegateQueue: nil - ) - delegate.session = session - session.downloadTask(with: url).resume() + let task = session.downloadTask(with: url) + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + sessionDelegate.register(task, handler: .init( + onBytesWritten: onBytesWritten, + onComplete: { continuation.resume(with: $0) } + )) + task.resume() + } + } onCancel: { + task.cancel() } } @@ -306,7 +374,16 @@ actor DownloadManager { case ok(ManifestFile, UInt64) case missing(ManifestFile) case sizeMismatch(ManifestFile, local: UInt64) + case hashMismatch(ManifestFile) case unreadable(ManifestFile) + + var file: ManifestFile { + switch self { + case .ok(let f, _), .missing(let f), .sizeMismatch(let f, _), + .hashMismatch(let f), .unreadable(let f): + return f + } + } } func verifyFiles( @@ -332,7 +409,7 @@ actor DownloadManager { let file = files[index] index += 1 group.addTask { - Self.verifyOneFile(file: file, installDirectory: installDirectory) + await Self.verifyOneFile(file: file, installDirectory: installDirectory) } } @@ -345,7 +422,7 @@ actor DownloadManager { let file = files[index] index += 1 group.addTask { - Self.verifyOneFile(file: file, installDirectory: installDirectory) + await Self.verifyOneFile(file: file, installDirectory: installDirectory) } } } @@ -353,14 +430,7 @@ actor DownloadManager { } var corruptFiles: [ManifestFile] = [] - let sorted = results.sorted { lhs, rhs in - func path(_ r: VerifyResult) -> String { - switch r { - case .ok(let f, _), .missing(let f), .sizeMismatch(let f, _), .unreadable(let f): return f.path - } - } - return path(lhs) < path(rhs) - } + let sorted = results.sorted { $0.file.path < $1.file.path } for result in sorted { switch result { @@ -372,8 +442,11 @@ actor DownloadManager { case .sizeMismatch(let file, let localSize): onLog("SIZE MISMATCH: \(file.path) — local: \(formatSize(localSize)), expected: \(formatSize(file.size)) (diff: \(Self.formatSizeDiff(local: localSize, expected: file.size)))", .warning) corruptFiles.append(file) + case .hashMismatch(let file): + onLog("HASH MISMATCH: \(file.path) — content differs from manifest", .warning) + corruptFiles.append(file) case .unreadable(let file): - onLog("UNREADABLE: \(file.path) — cannot read file attributes", .error) + onLog("UNREADABLE: \(file.path) — cannot read file", .error) corruptFiles.append(file) } } @@ -388,7 +461,8 @@ actor DownloadManager { return corruptFiles } - private static nonisolated func verifyOneFile(file: ManifestFile, installDirectory: URL) -> VerifyResult { + // Nonisolated async so hashing runs on the global executor, off the actor. + private static nonisolated func verifyOneFile(file: ManifestFile, installDirectory: URL) async -> VerifyResult { let destURL = installDirectory.appendingPathComponent(file.path) let fm = FileManager.default @@ -405,18 +479,24 @@ actor DownloadManager { return .sizeMismatch(file, local: fileSize) } + if !file.hash.isEmpty { + guard let actualHash = try? hashFile(at: destURL) else { + return .unreadable(file) + } + if actualHash != file.hash { + return .hashMismatch(file) + } + } + return .ok(file, fileSize) } private func incrementVerifyProgress(result: VerifyResult) { filesCompleted += 1 - switch result { - case .ok(let file, let size): + if case .ok(_, let size) = result { downloadedBytes += Int64(size) - currentFile = file.path - case .missing(let file), .sizeMismatch(let file, _), .unreadable(let file): - currentFile = file.path } + currentFile = result.file.path sendProgress() } @@ -428,47 +508,6 @@ actor DownloadManager { } } - func repairFiles( - files: [ManifestFile], - version: String, - installDirectory: URL - ) async throws { - totalBytes = files.reduce(0) { $0 + Int64($1.size) } - downloadedBytes = 0 - inFlightBytes = [:] - filesTotal = files.count - filesCompleted = 0 - - onLog("Repairing \(files.count) files (\(formatSize(UInt64(totalBytes))))", .info) - sendProgress() - - let sortedFiles = files.sorted { $0.size < $1.size } - - try await withThrowingTaskGroup(of: Void.self) { group in - var index = 0 - - for _ in 0.. FlexValue { + try root(data).materialized() + } + + /// Entry point for lazy traversal: returns a reference to the root value. + static func root(_ data: Data) throws -> FlexRef { guard data.count >= 3 else { throw ParseError(message: "Buffer too small for FlexBuffers") } - let rootByteWidth = Int(data[data.count - 1]) - let rootPackedType = data[data.count - 2] - let rootOffset = data.count - 2 - rootByteWidth - return decodeValue(data, offset: rootOffset, parentByteWidth: rootByteWidth, packedType: rootPackedType) + let bytes = [UInt8](data) + let rootByteWidth = Int(bytes[bytes.count - 1]) + let rootPackedType = bytes[bytes.count - 2] + let rootOffset = bytes.count - 2 - rootByteWidth + guard rootByteWidth >= 1, rootOffset >= 0 else { + throw ParseError(message: "Invalid FlexBuffers root byte width") + } + return FlexRef(bytes: bytes, offset: rootOffset, slotWidth: rootByteWidth, packedType: rootPackedType) } +} - // MARK: - Primitive Reads - - private static func readUInt(_ data: Data, offset: Int, byteWidth: Int) -> UInt64 { - switch byteWidth { - case 1: return UInt64(data[offset]) - case 2: - return data.withUnsafeBytes { ptr in - UInt64(ptr.load(fromByteOffset: offset, as: UInt16.self).littleEndian) - } - case 4: - return data.withUnsafeBytes { ptr in - UInt64(ptr.load(fromByteOffset: offset, as: UInt32.self).littleEndian) - } - case 8: - return data.withUnsafeBytes { ptr in - ptr.load(fromByteOffset: offset, as: UInt64.self).littleEndian +// MARK: - FlexRef + +/// A lazy, bounds-checked reference into a FlexBuffers document. +/// Accessors return nil instead of crashing on malformed or truncated input, +/// and children are decoded on demand rather than materializing the full tree. +nonisolated struct FlexRef: Sendable { + + // FlexBuffers type ids + private static let tNull: UInt8 = 0 + private static let tInt: UInt8 = 1 + private static let tUInt: UInt8 = 2 + private static let tFloat: UInt8 = 3 + private static let tKey: UInt8 = 4 + private static let tString: UInt8 = 5 + private static let tIndirectInt: UInt8 = 6 + private static let tIndirectUInt: UInt8 = 7 + private static let tIndirectFloat: UInt8 = 8 + private static let tMap: UInt8 = 9 + private static let tVector: UInt8 = 10 + private static let tVectorInt: UInt8 = 11 + private static let tVectorUInt: UInt8 = 12 + private static let tVectorFloat: UInt8 = 13 + private static let tVectorKey: UInt8 = 14 + private static let tVectorString: UInt8 = 15 + private static let tVectorInt2: UInt8 = 16 + private static let tVectorFloat4: UInt8 = 24 + private static let tBlob: UInt8 = 25 + private static let tBool: UInt8 = 26 + + fileprivate let bytes: [UInt8] + /// Position of this value's slot within `bytes`. + fileprivate let offset: Int + /// Byte width of the slot (the enclosing container's element width). + fileprivate let slotWidth: Int + fileprivate let packedType: UInt8 + + private var typeId: UInt8 { packedType >> 2 } + private var childWidth: Int { 1 << Int(packedType & 0x03) } + + // MARK: Bounds-checked primitive reads + + private func readUInt(at offset: Int, width: Int) -> UInt64? { + guard offset >= 0, width >= 1, offset <= bytes.count - width else { return nil } + return bytes.withUnsafeBytes { ptr in + switch width { + case 1: return UInt64(ptr.loadUnaligned(fromByteOffset: offset, as: UInt8.self)) + case 2: return UInt64(UInt16(littleEndian: ptr.loadUnaligned(fromByteOffset: offset, as: UInt16.self))) + case 4: return UInt64(UInt32(littleEndian: ptr.loadUnaligned(fromByteOffset: offset, as: UInt32.self))) + case 8: return UInt64(littleEndian: ptr.loadUnaligned(fromByteOffset: offset, as: UInt64.self)) + default: return nil } - default: return 0 } } - private static func readInt(_ data: Data, offset: Int, byteWidth: Int) -> Int64 { - switch byteWidth { - case 1: return Int64(Int8(bitPattern: data[offset])) - case 2: - return data.withUnsafeBytes { ptr in - Int64(Int16(bitPattern: ptr.load(fromByteOffset: offset, as: UInt16.self).littleEndian)) - } - case 4: - return data.withUnsafeBytes { ptr in - Int64(Int32(bitPattern: ptr.load(fromByteOffset: offset, as: UInt32.self).littleEndian)) - } - case 8: - return data.withUnsafeBytes { ptr in - Int64(bitPattern: ptr.load(fromByteOffset: offset, as: UInt64.self).littleEndian) - } - default: return 0 + private func readInt(at offset: Int, width: Int) -> Int64? { + guard let raw = readUInt(at: offset, width: width) else { return nil } + switch width { + case 1: return Int64(Int8(bitPattern: UInt8(truncatingIfNeeded: raw))) + case 2: return Int64(Int16(bitPattern: UInt16(truncatingIfNeeded: raw))) + case 4: return Int64(Int32(bitPattern: UInt32(truncatingIfNeeded: raw))) + case 8: return Int64(bitPattern: raw) + default: return nil } } - private static func readFloat(_ data: Data, offset: Int, byteWidth: Int) -> Double { - switch byteWidth { - case 4: - return data.withUnsafeBytes { ptr in - Double(ptr.load(fromByteOffset: offset, as: Float.self)) - } - case 8: - return data.withUnsafeBytes { ptr in - ptr.load(fromByteOffset: offset, as: Double.self) - } - default: return 0 + private func readFloat(at offset: Int, width: Int) -> Double? { + guard let raw = readUInt(at: offset, width: width) else { return nil } + switch width { + case 4: return Double(Float(bitPattern: UInt32(truncatingIfNeeded: raw))) + case 8: return Double(bitPattern: raw) + default: return nil } } - private static func readString(_ data: Data, offset: Int) -> String { + private func readCString(at offset: Int) -> String? { + guard offset >= 0, offset < bytes.count else { return nil } var end = offset - while end < data.count && data[end] != 0 { + while end < bytes.count && bytes[end] != 0 { end += 1 } - return String(data: data[offset.. FlexValue { - let bitWidth = Int(packedType & 0x03) - let typeId = packedType >> 2 - let childByteWidth = 1 << bitWidth - return decodeTypedValue(data, offset: offset, parentByteWidth: parentByteWidth, - childByteWidth: childByteWidth, typeId: typeId) + /// Resolve the slot's relative offset to the position it points at. + private var indirectTarget: Int? { + guard let rel = readUInt(at: offset, width: slotWidth), rel <= UInt64(offset) else { return nil } + return offset - Int(rel) } - private static func decodeTypedValue(_ data: Data, offset: Int, parentByteWidth: Int, - childByteWidth: Int, typeId: UInt8) -> FlexValue { - switch typeId { - case FBT_NULL: - return .null - - case FBT_BOOL: - return .bool(readUInt(data, offset: offset, byteWidth: parentByteWidth) != 0) - - case FBT_INT: - return .int(readInt(data, offset: offset, byteWidth: parentByteWidth)) + // MARK: Scalar accessors - case FBT_UINT: - return .uint(readUInt(data, offset: offset, byteWidth: parentByteWidth)) + var boolValue: Bool? { + guard typeId == Self.tBool else { return nil } + return readUInt(at: offset, width: slotWidth).map { $0 != 0 } + } - case FBT_FLOAT: - return .float(readFloat(data, offset: offset, byteWidth: parentByteWidth)) + var intValue: Int64? { + switch typeId { + case Self.tInt: return readInt(at: offset, width: slotWidth) + case Self.tIndirectInt: return indirectTarget.flatMap { readInt(at: $0, width: childWidth) } + case Self.tUInt, Self.tIndirectUInt: + return uintValue.flatMap { $0 <= UInt64(Int64.max) ? Int64($0) : nil } + default: return nil + } + } - case FBT_STRING: - let strOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - return .string(readString(data, offset: strOffset)) + var uintValue: UInt64? { + switch typeId { + case Self.tUInt: return readUInt(at: offset, width: slotWidth) + case Self.tIndirectUInt: return indirectTarget.flatMap { readUInt(at: $0, width: childWidth) } + case Self.tInt, Self.tIndirectInt: + return intValue.flatMap { $0 >= 0 ? UInt64($0) : nil } + default: return nil + } + } - case FBT_KEY: - let keyOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - return .string(readString(data, offset: keyOffset)) + var floatValue: Double? { + switch typeId { + case Self.tFloat: return readFloat(at: offset, width: slotWidth) + case Self.tIndirectFloat: return indirectTarget.flatMap { readFloat(at: $0, width: childWidth) } + default: return nil + } + } - case FBT_BLOB: - let blobOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - let size = Int(readUInt(data, offset: blobOffset - childByteWidth, byteWidth: childByteWidth)) - return .blob(data[blobOffset..<(blobOffset + size)]) + var stringValue: String? { + guard typeId == Self.tString || typeId == Self.tKey else { return nil } + return indirectTarget.flatMap { readCString(at: $0) } + } - case FBT_INDIRECT_INT: - let indirectOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - return .int(readInt(data, offset: indirectOffset, byteWidth: childByteWidth)) + /// Blob contents, copied out so the result does not pin the whole document. + var blobValue: Data? { + guard typeId == Self.tBlob, + let target = indirectTarget, + let size64 = readUInt(at: target - childWidth, width: childWidth), + let size = Int(exactly: size64), + size >= 0, target <= bytes.count - size else { return nil } + return Data(bytes[target..<(target + size)]) + } - case FBT_INDIRECT_UINT: - let indirectOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - return .uint(readUInt(data, offset: indirectOffset, byteWidth: childByteWidth)) + // MARK: Composite accessors - case FBT_INDIRECT_FLOAT: - let indirectOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - return .float(readFloat(data, offset: indirectOffset, byteWidth: childByteWidth)) + var isNull: Bool { typeId == Self.tNull } + var isMap: Bool { typeId == Self.tMap } - case FBT_MAP: - return decodeMap(data, offset: offset, parentByteWidth: parentByteWidth, byteWidth: childByteWidth) + var isVector: Bool { + typeId == Self.tVector || isTypedVector || isFixedTypedVector + } - case FBT_VECTOR: - return decodeVector(data, offset: offset, parentByteWidth: parentByteWidth, byteWidth: childByteWidth) + private var isTypedVector: Bool { + typeId >= Self.tVectorInt && typeId <= Self.tVectorString + } - case FBT_VECTOR_INT, FBT_VECTOR_UINT, FBT_VECTOR_FLOAT, - FBT_VECTOR_KEY, FBT_VECTOR_STRING, FBT_BOOL: - return decodeTypedVector(data, offset: offset, parentByteWidth: parentByteWidth, - byteWidth: childByteWidth, typeId: typeId) + private var isFixedTypedVector: Bool { + typeId >= Self.tVectorInt2 && typeId <= Self.tVectorFloat4 + } - case FBT_VECTOR_INT2, FBT_VECTOR_UINT2, FBT_VECTOR_FLOAT2, - FBT_VECTOR_INT3, FBT_VECTOR_UINT3, FBT_VECTOR_FLOAT3, - FBT_VECTOR_INT4, FBT_VECTOR_UINT4, FBT_VECTOR_FLOAT4: - return decodeFixedTypedVector(data, offset: offset, parentByteWidth: parentByteWidth, - byteWidth: childByteWidth, typeId: typeId) + /// Element count for vectors, key/value pair count for maps. + var count: Int { + if typeId == Self.tMap || typeId == Self.tVector || isTypedVector { + guard let base = indirectTarget, + let n = readUInt(at: base - childWidth, width: childWidth), + let c = Int(exactly: n), + c >= 0, c <= (bytes.count - base) / childWidth else { return 0 } + return c + } + if isFixedTypedVector { + // Fixed vectors encode the length in the type: INT2/UINT2/FLOAT2, INT3/..., INT4/... + return 2 + Int(typeId - Self.tVectorInt2) / 3 + } + return 0 + } + private var typedElementType: UInt8 { + switch typeId { + case Self.tVectorUInt: return Self.tUInt + case Self.tVectorFloat: return Self.tFloat + case Self.tVectorKey: return Self.tKey + case Self.tVectorString: return Self.tString + case Self.tVectorInt: return Self.tInt default: - return .null + // Fixed typed vectors cycle INT, UINT, FLOAT + switch Int(typeId - Self.tVectorInt2) % 3 { + case 0: return Self.tInt + case 1: return Self.tUInt + default: return Self.tFloat + } } } - // MARK: - Composite Decoding - - private static func decodeVector(_ data: Data, offset: Int, parentByteWidth: Int, byteWidth: Int) -> FlexValue { - let vecOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - let size = Int(readUInt(data, offset: vecOffset - byteWidth, byteWidth: byteWidth)) - let typeVecOffset = vecOffset + size * byteWidth + subscript(index: Int) -> FlexRef? { + let n = count + guard index >= 0, index < n, let base = indirectTarget else { return nil } + let elemOffset = base + index * childWidth - var result: [FlexValue] = [] - result.reserveCapacity(size) - for i in 0.. FlexValue { - let vecOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - let size = Int(readUInt(data, offset: vecOffset - byteWidth, byteWidth: byteWidth)) - - let elemTypeMap: [UInt8: UInt8] = [ - FBT_VECTOR_INT: FBT_INT, - FBT_VECTOR_UINT: FBT_UINT, - FBT_VECTOR_FLOAT: FBT_FLOAT, - FBT_VECTOR_KEY: FBT_KEY, - FBT_VECTOR_STRING: FBT_STRING, - FBT_BOOL: FBT_BOOL, - ] - let elemType = elemTypeMap[typeId] ?? FBT_NULL - - var result: [FlexValue] = [] - result.reserveCapacity(size) - for i in 0.. FlexValue { - let vecOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) + func key(at index: Int) -> String? { + guard typeId == Self.tMap, index >= 0, index < count, let base = indirectTarget else { return nil } + let w = childWidth + // The keys vector descriptor (offset + byte width) sits before the size field. + let keysOffsetPos = base - w * 3 + guard let rel = readUInt(at: keysOffsetPos, width: w), + rel <= UInt64(keysOffsetPos), + let keysWidth64 = readUInt(at: keysOffsetPos + w, width: w), + let keysWidth = Int(exactly: keysWidth64), + keysWidth >= 1 else { return nil } + let keySlot = (keysOffsetPos - Int(rel)) + index * keysWidth + guard let keyRel = readUInt(at: keySlot, width: keysWidth), keyRel <= UInt64(keySlot) else { return nil } + return readCString(at: keySlot - Int(keyRel)) + } - let count: Int - switch typeId { - case FBT_VECTOR_INT2, FBT_VECTOR_UINT2, FBT_VECTOR_FLOAT2: count = 2 - case FBT_VECTOR_INT3, FBT_VECTOR_UINT3, FBT_VECTOR_FLOAT3: count = 3 - default: count = 4 + subscript(key: String) -> FlexRef? { + guard typeId == Self.tMap else { return nil } + for i in 0.. FlexValue { - let vecOffset = offset - Int(readUInt(data, offset: offset, byteWidth: parentByteWidth)) - let size = Int(readUInt(data, offset: vecOffset - byteWidth, byteWidth: byteWidth)) - - // Keys metadata is stored before the size field - let keysOffsetPos = vecOffset - byteWidth * 3 - let keysOffsetVal = Int(readUInt(data, offset: keysOffsetPos, byteWidth: byteWidth)) - let keysByteWidth = Int(readUInt(data, offset: keysOffsetPos + byteWidth, byteWidth: byteWidth)) - let keysVecOffset = keysOffsetPos - keysOffsetVal - - let typeVecOffset = vecOffset + size * byteWidth - - var result: [String: FlexValue] = [:] - result.reserveCapacity(size) - for i in 0.. FlexValue { + switch typeId { + case Self.tNull: + return .null + case Self.tBool: + return boolValue.map(FlexValue.bool) ?? .null + case Self.tInt, Self.tIndirectInt: + return intValue.map(FlexValue.int) ?? .null + case Self.tUInt, Self.tIndirectUInt: + return uintValue.map(FlexValue.uint) ?? .null + case Self.tFloat, Self.tIndirectFloat: + return floatValue.map(FlexValue.float) ?? .null + case Self.tString, Self.tKey: + return stringValue.map(FlexValue.string) ?? .null + case Self.tBlob: + return blobValue.map(FlexValue.blob) ?? .null + case Self.tMap: + let n = count + var result: [String: FlexValue] = [:] + result.reserveCapacity(n) + for i in 0.. Process { + /// Launch the game. `onExit` is installed before the process starts, so it + /// fires even if the game exits immediately. + static func launch( + info: WineInfo, + options: LaunchOptions, + onExit: @escaping @Sendable (Int32) -> Void = { _ in } + ) throws -> Process { let wineUser = info.wineUsername // Launch the actual game binary directly, NOT PaliaClient.exe (which is a @@ -35,6 +41,7 @@ nonisolated enum GameLauncher { process.arguments = arguments process.environment = WineManager.makeWineEnvironment(info: info, metalHUD: options.metalHUD) process.currentDirectoryURL = info.gameInstallPath + process.terminationHandler = { onExit($0.terminationStatus) } try process.run() return process diff --git a/palium/Services/WineManager.swift b/palium/Services/WineManager.swift index b3c676a..980b129 100644 --- a/palium/Services/WineManager.swift +++ b/palium/Services/WineManager.swift @@ -36,12 +36,12 @@ nonisolated enum WineManager { guard let wineBinary = findWineBinary() else { throw PaliumError.wineNotFound } - let gptkPrefix = gptkPrefixPath() - try await initializePrefix(wineBinary: wineBinary, at: gptkPrefix) - let username = try findWineUsername(in: gptkPrefix) + let prefix = gptkPrefix + try await initializePrefix(wineBinary: wineBinary, at: prefix) + let username = try findWineUsername(in: prefix) return WineInfo( wineBinaryURL: wineBinary, - prefixPath: gptkPrefix, + prefixPath: prefix, wineUsername: username, source: .gptk ) @@ -52,20 +52,20 @@ nonisolated enum WineManager { guard let wineBinary = findGPTKBinary() else { throw PaliumError.wineNotFound } - let gptkPrefix = gptkPrefixPath() - if isPrefixValid(gptkPrefix), let username = try? findWineUsername(in: gptkPrefix) { + let prefix = gptkPrefix + if isPrefixValid(prefix), let username = try? findWineUsername(in: prefix) { return WineInfo( wineBinaryURL: wineBinary, - prefixPath: gptkPrefix, + prefixPath: prefix, wineUsername: username, source: .gptk ) } - try await initializePrefix(wineBinary: wineBinary, at: gptkPrefix) - let username = try findWineUsername(in: gptkPrefix) + try await initializePrefix(wineBinary: wineBinary, at: prefix) + let username = try findWineUsername(in: prefix) return WineInfo( wineBinaryURL: wineBinary, - prefixPath: gptkPrefix, + prefixPath: prefix, wineUsername: username, source: .gptk ) @@ -121,7 +121,9 @@ nonisolated enum WineManager { // MARK: - Prefix Management - private static func gptkPrefixPath() -> URL { + /// The prefix Palium manages itself (GPTK mode). Exposed so UI code + /// (e.g. Troubleshooting's "Delete Wine Prefix") uses the same path. + static var gptkPrefix: URL { FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(gptkPrefixRelativePath) } @@ -168,7 +170,57 @@ nonisolated enum WineManager { // MARK: - Username Detection + /// The Wine user the game will actually run as. + /// + /// Wine stamps the running user's identity into `[Volatile Environment]` on every + /// wineboot, and that is what `%LOCALAPPDATA%` resolves to inside the prefix — so + /// it is authoritative in a way that listing `drive_c/users` is not. A prefix can + /// accumulate several user directories (GPTK is CrossOver-derived and runs as + /// `crossover`; other Wine builds use the macOS username), and `contentsOfDirectory` + /// returns them unordered — so scanning could pick a different user between runs and + /// silently split the game install from the save data the game writes. static func findWineUsername(in prefix: URL) throws -> String { + if let username = registryUsername(in: prefix) { + return username + } + return try scannedUsername(in: prefix) + } + + /// Read `HKCU\Volatile Environment\USERNAME` out of the prefix's `user.reg`. + private static func registryUsername(in prefix: URL) -> String? { + let userReg = prefix.appendingPathComponent("user.reg") + guard let contents = try? String(contentsOf: userReg, encoding: .utf8) else { + return nil + } + + let key = "\"USERNAME\"=\"" + var inVolatileEnvironment = false + + for rawLine in contents.split(separator: "\n", omittingEmptySubsequences: false) { + let line = rawLine.trimmingCharacters(in: .whitespacesAndNewlines) + + // Section headers look like `[Volatile Environment] 1782835665`. + if line.hasPrefix("[") { + inVolatileEnvironment = line.hasPrefix("[Volatile Environment]") + continue + } + + guard inVolatileEnvironment, line.hasPrefix(key), line.hasSuffix("\"") else { + continue + } + + let username = line.dropFirst(key.count).dropLast() + .replacingOccurrences(of: "\\\\", with: "\\") + .replacingOccurrences(of: "\\\"", with: "\"") + return username.isEmpty ? nil : username + } + + return nil + } + + /// Fallback for prefixes with no usable `user.reg`: scan `drive_c/users`, preferring a + /// user that already holds a game install, then sorting so the result is at least stable. + private static func scannedUsername(in prefix: URL) throws -> String { let fm = FileManager.default let usersDir = prefix.appendingPathComponent("drive_c/users") @@ -176,10 +228,25 @@ nonisolated enum WineManager { throw PaliumError.noBottleFound } - let users = try fm.contentsOfDirectory(atPath: usersDir.path) - let filtered = users.filter { $0 != "Public" && !$0.hasPrefix(".") && !$0.contains("Default") } + let candidates = try fm.contentsOfDirectory(atPath: usersDir.path) + .filter { $0 != "Public" && !$0.hasPrefix(".") && !$0.contains("Default") } + .filter { name in + var isDir: ObjCBool = false + let exists = fm.fileExists( + atPath: usersDir.appendingPathComponent(name).path, + isDirectory: &isDir + ) + return exists && isDir.boolValue + } + .sorted() + + let withInstall = candidates.first { name in + let exe = usersDir + .appendingPathComponent("\(name)/AppData/Local/Palia/Client/PaliaClient.exe") + return fm.fileExists(atPath: exe.path) + } - guard let username = filtered.first else { + guard let username = withInstall ?? candidates.first else { throw PaliumError.noBottleFound } return username @@ -231,7 +298,23 @@ nonisolated enum WineManager { let didResume = OSAllocatedUnfairLock(initialState: false) + // Weak capture: don't keep the (finished) process alive until the + // timeout deadline; cancelled in the termination handler. + let timeoutWork = DispatchWorkItem { [weak process] in + let shouldResume = didResume.withLock { flag -> Bool in + if flag { return false } + flag = true + return true + } + guard shouldResume else { return } + if let process, process.isRunning { process.terminate() } + continuation.resume(throwing: PaliumError.launchFailed( + "Wine process timed out after \(Int(timeout))s" + )) + } + process.terminationHandler = { proc in + timeoutWork.cancel() let shouldResume = didResume.withLock { flag -> Bool in if flag { return false } flag = true @@ -247,18 +330,7 @@ nonisolated enum WineManager { } } - DispatchQueue.global().asyncAfter(deadline: .now() + timeout) { - let shouldResume = didResume.withLock { flag -> Bool in - if flag { return false } - flag = true - return true - } - guard shouldResume else { return } - if process.isRunning { process.terminate() } - continuation.resume(throwing: PaliumError.launchFailed( - "Wine process timed out after \(Int(timeout))s" - )) - } + DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: timeoutWork) do { try process.run() @@ -276,7 +348,8 @@ nonisolated enum WineManager { // MARK: - Diagnostics - struct DiagnosticResult: Sendable { + struct DiagnosticResult: Sendable, Identifiable { + var id: String { name } let name: String let passed: Bool let detail: String diff --git a/palium/Views/TroubleshootingTab.swift b/palium/Views/TroubleshootingTab.swift index c73467a..c7a666f 100644 --- a/palium/Views/TroubleshootingTab.swift +++ b/palium/Views/TroubleshootingTab.swift @@ -78,7 +78,7 @@ struct TroubleshootingTab: View { ScrollViewReader { proxy in ScrollView { LazyVStack(alignment: .leading, spacing: 0) { - ForEach(Array(results.enumerated()), id: \.offset) { _, result in + ForEach(results) { result in diagnosticRow(result) Divider().padding(.leading, 28) } @@ -242,24 +242,24 @@ struct TroubleshootingTab: View { } private func deletePrefix() { - // Use the same prefix path as WineManager (gptkPrefixRelativePath) - let home = FileManager.default.homeDirectoryForCurrentUser - let prefix = home.appendingPathComponent("Library/Application Support/com.palium/prefix") - try? FileManager.default.removeItem(at: prefix) - // Also kill wineserver so it doesn't hold stale state - let binDir = (WineManager.findGPTKBinary() ?? WineManager.findWhiskyBinary())?.deletingLastPathComponent() - if let wineserver = binDir?.appendingPathComponent("wineserver") { - let p = Process() - p.executableURL = wineserver - p.arguments = ["-k"] - p.standardOutput = FileHandle.nullDevice - p.standardError = FileHandle.nullDevice - try? p.run() - p.waitUntilExit() - } - results = [] logEntries = [] hasRun = false + + // File removal and wineserver shutdown run off the main thread. + Task.detached(priority: .utility) { + try? FileManager.default.removeItem(at: WineManager.gptkPrefix) + // Also kill wineserver so it doesn't hold stale state + let binDir = (WineManager.findGPTKBinary() ?? WineManager.findWhiskyBinary())?.deletingLastPathComponent() + if let wineserver = binDir?.appendingPathComponent("wineserver") { + let p = Process() + p.executableURL = wineserver + p.arguments = ["-k"] + p.standardOutput = FileHandle.nullDevice + p.standardError = FileHandle.nullDevice + try? p.run() + p.waitUntilExit() + } + } } } diff --git a/paliumTests/paliumTests.swift b/paliumTests/paliumTests.swift index c4f549a..b2ecbd3 100644 --- a/paliumTests/paliumTests.swift +++ b/paliumTests/paliumTests.swift @@ -74,6 +74,49 @@ struct FlexBuffersParserTests { #expect(result.uintValue == 1000) } + @Test func decodeMap() throws { + // {"a": 42} encoded by hand (all byte widths 1): + // key cstring, keys vector (len + offset), keys descriptor (offset + width), + // values vector (len + value), element types, root offset, type, width. + let data = Data([0x61, 0x00, 0x01, 0x03, 0x01, 0x01, 0x01, 42, 8, 0x02, 0x24, 0x01]) + let result = try FlexBuffersParser.decode(data) + #expect(result["a"]?.uintValue == 42) + + let root = try FlexBuffersParser.root(data) + #expect(root.isMap) + #expect(root.count == 1) + #expect(root.key(at: 0) == "a") + #expect(root["a"]?.uintValue == 42) + #expect(root["missing"] == nil) + } + + @Test func decodeVector() throws { + // [1, 2] encoded by hand: len, values, element types, root offset, type, width + let data = Data([2, 1, 2, 8, 8, 4, 0x28, 1]) + let result = try FlexBuffersParser.decode(data) + #expect(result[0]?.uintValue == 1) + #expect(result[1]?.uintValue == 2) + #expect(result[2] == nil) + + let root = try FlexBuffersParser.root(data) + #expect(root.isVector) + #expect(root.count == 2) + #expect(root[1]?.uintValue == 2) + } + + @Test func decodeMalformedBufferDoesNotCrash() throws { + // Garbage offsets and truncated buffers must degrade gracefully, not crash. + let buffers: [Data] = [ + Data([0xFF, 0xFE, 0x24, 0x08]), // map with nonsense offsets + Data([0xFF, 0xFF, 0xFF, 0x28, 0x08]), // vector with absurd width + Data([0x00, 0x64, 0x01]), // blob pointing out of bounds + Data((0..<64).map { _ in UInt8.random(in: 0...255) } + [0x24, 0x01]), + ] + for data in buffers { + _ = try? FlexBuffersParser.decode(data) + } + } + @Test func decodeString() throws { // FlexBuffers string: length-prefixed, null-terminated // "hi" = [2(len), 'h', 'i', 0, packed_type, byte_width] @@ -200,27 +243,21 @@ struct CDNClientTests { struct ManifestModelTests { @Test func manifestFileIdentity() { - let file = ManifestFile(path: "test/file.exe", size: 1024, hash: Data(), chunks: []) + let file = ManifestFile(path: "test/file.exe", size: 1024, hash: Data()) #expect(file.id == "test/file.exe") } - @Test func manifestChunkProperties() { - let chunk = ManifestChunk(offset: 0, size: 512, hash: Data([0xAB, 0xCD])) - #expect(chunk.offset == 0) - #expect(chunk.size == 512) - #expect(chunk.hash.count == 2) - } - @Test func updateManifestTotalSize() { let manifest = UpdateManifest( bundle: "Palia", version: "1.0", platform: "windows", files: [ - ManifestFile(path: "a.exe", size: 100, hash: Data(), chunks: []), - ManifestFile(path: "b.pak", size: 200, hash: Data(), chunks: []), + ManifestFile(path: "a.exe", size: 100, hash: Data()), + ManifestFile(path: "b.pak", size: 200, hash: Data()), ], - totalSize: 300 + totalSize: 300, + contentsHash: Data() ) #expect(manifest.files.count == 2) #expect(manifest.totalSize == 300) @@ -431,6 +468,140 @@ struct WineManagerTests { ) #expect(WineManager.isGameInstalled(info: info) == false) } + + // MARK: - Wine Username Detection + + /// Build a throwaway prefix. `users` become directories under `drive_c/users`; + /// `registryUser`, when set, is written into `user.reg` as Wine's wineboot does. + private func makePrefix( + users: [String], + registryUser: String? = nil, + installedFor: String? = nil + ) throws -> URL { + let fm = FileManager.default + let prefix = fm.temporaryDirectory.appendingPathComponent("prefix_\(UUID())") + let usersDir = prefix.appendingPathComponent("drive_c/users") + for user in users { + try fm.createDirectory( + at: usersDir.appendingPathComponent(user), + withIntermediateDirectories: true + ) + } + if let installedFor { + let clientDir = usersDir + .appendingPathComponent("\(installedFor)/AppData/Local/Palia/Client") + try fm.createDirectory(at: clientDir, withIntermediateDirectories: true) + try Data().write(to: clientDir.appendingPathComponent("PaliaClient.exe")) + } + if let registryUser { + let userReg = """ + WINE REGISTRY Version 2 + + [Software\\\\Wine] 1782835665 + "SomeKey"="SomeValue" + + [Volatile Environment] 1782835665 + #time=1dd08aa966aefd2 + "HOMEPATH"="\\\\users\\\\\(registryUser)" + "USERNAME"="\(registryUser)" + "USERPROFILE"="C:\\\\users\\\\\(registryUser)" + + """ + try userReg.write( + to: prefix.appendingPathComponent("user.reg"), + atomically: true, + encoding: .utf8 + ) + } + return prefix + } + + @Test func usernameComesFromRegistryNotDirectoryOrder() throws { + // GPTK runs the game as `crossover` regardless of which user directories + // happen to exist, and `user.reg` is what says so. + let prefix = try makePrefix( + users: ["alice", "crossover", "zoe"], + registryUser: "crossover" + ) + defer { try? FileManager.default.removeItem(at: prefix) } + + #expect(try WineManager.findWineUsername(in: prefix) == "crossover") + } + + @Test func registryUsernameWinsOverUserWithInstall() throws { + // The install may sit under a stale user; the game still reads and writes + // under whoever Wine actually runs as. + let prefix = try makePrefix( + users: ["crossover", "stale"], + registryUser: "crossover", + installedFor: "stale" + ) + defer { try? FileManager.default.removeItem(at: prefix) } + + #expect(try WineManager.findWineUsername(in: prefix) == "crossover") + } + + @Test func usernameIgnoresUnrelatedRegistrySections() throws { + // A `USERNAME` value outside [Volatile Environment] must not be picked up. + let prefix = try makePrefix(users: ["crossover"]) + defer { try? FileManager.default.removeItem(at: prefix) } + let userReg = """ + WINE REGISTRY Version 2 + + [Software\\\\Decoy] 1782835665 + "USERNAME"="wrong" + + """ + try userReg.write( + to: prefix.appendingPathComponent("user.reg"), + atomically: true, + encoding: .utf8 + ) + + // Falls through to the directory scan rather than trusting the decoy. + #expect(try WineManager.findWineUsername(in: prefix) == "crossover") + } + + @Test func fallbackPrefersUserHoldingTheInstall() throws { + // No user.reg: the user that already has the game beats alphabetical order. + let prefix = try makePrefix( + users: ["aaa", "crossover"], + installedFor: "crossover" + ) + defer { try? FileManager.default.removeItem(at: prefix) } + + #expect(try WineManager.findWineUsername(in: prefix) == "crossover") + } + + @Test func fallbackIsStableWhenNothingIsInstalled() throws { + // Deterministic across runs even though contentsOfDirectory is unordered. + let prefix = try makePrefix(users: ["zoe", "alice", "crossover"]) + defer { try? FileManager.default.removeItem(at: prefix) } + + let results = try (0..<5).map { _ in try WineManager.findWineUsername(in: prefix) } + #expect(results.allSatisfy { $0 == "alice" }) + } + + @Test func fallbackSkipsPublicAndDefaultAndFiles() throws { + let fm = FileManager.default + let prefix = try makePrefix(users: ["Public", "Default User", "crossover"]) + defer { try? fm.removeItem(at: prefix) } + // A stray file must not be mistaken for a user directory. + try Data().write( + to: prefix.appendingPathComponent("drive_c/users/.DS_Store") + ) + + #expect(try WineManager.findWineUsername(in: prefix) == "crossover") + } + + @Test func throwsWhenPrefixHasNoUsers() throws { + let prefix = try makePrefix(users: []) + defer { try? FileManager.default.removeItem(at: prefix) } + + #expect(throws: PaliumError.self) { + _ = try WineManager.findWineUsername(in: prefix) + } + } } // MARK: - AppState Tests