From 1fe92c978a71a4e2d346a048969cb2a94aab0bd5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:00:45 -0500 Subject: [PATCH] feat(library): Steam games install from the Library like the other stores (#3272) Owned Steam games are listed in the Library's Steam tab like the other stores' games. Any of them installs from its page into the Steam library the user picks, with a Rust engine running in the app. - Sign-in reuses the Linux Steam client's saved login; there is no second login. - The engine picks the same depots and manifests the client would (licensed depots only) and checks every chunk's SHA-1 before writing it. - It registers the game the way the client does (app manifest, libraryfolders, shared redistributables), so the client neither re-verifies nor re-downloads it. Updates stay with the client. - A paused or interrupted download shows in the arm64 or x86-64 client as a resumable install. Taking over a client's stopped download keeps the files the client already staged. - Uninstall matches the client's and updates the client whose library holds the game. - Steam gets no Stores tab. Tested on an AYN Thor with both client architectures. The engine is The412Banner's feat/steam-store work, derived from WinNative's wn-steam-client (GPL-3.0); see src/steam/NOTICE.md. --- .../main/java/com/droiddeck/launcher/App.kt | 3 +- .../droiddeck/launcher/FrontEndActivity.kt | 17 +- .../com/droiddeck/launcher/SessionActivity.kt | 10 + .../droiddeck/launcher/stores/CloudSaves.kt | 6 +- .../droiddeck/launcher/stores/LoginFlows.kt | 2 +- .../com/droiddeck/launcher/stores/Store.kt | 9 +- .../launcher/stores/StoreAccounts.kt | 2 +- .../launcher/stores/StoreInstallRoot.kt | 4 +- .../droiddeck/launcher/stores/StoreSizes.kt | 3 +- .../droiddeck/launcher/stores/StoreTabs.kt | 4 +- .../droiddeck/launcher/stores/StoresState.kt | 3 + .../launcher/stores/download/DownloadQueue.kt | 1 + .../launcher/stores/steam/SteamClient.kt | 130 ++ .../launcher/stores/steam/SteamEngine.kt | 102 ++ .../launcher/stores/steam/SteamInstallJob.kt | 144 ++ .../stores/steam/SteamLibraryFolders.kt | 170 +++ .../launcher/stores/steam/SteamNative.kt | 12 + .../launcher/stores/steam/SteamStore.kt | 399 ++++++ .../droiddeck/launcher/ui/FrontEndScreen.kt | 1 + .../com/droiddeck/launcher/ui/GameDetail.kt | 3 +- .../droiddeck/launcher/ui/LibraryHidden.kt | 13 +- .../com/droiddeck/launcher/ui/LibraryPage.kt | 8 +- .../com/droiddeck/launcher/ui/ManageStores.kt | 2 +- .../com/droiddeck/launcher/ui/StoreChips.kt | 4 +- .../launcher/ui/StoresInstallDialog.kt | 59 + .../com/droiddeck/launcher/ui/StoresPage.kt | 3 +- app/src/main/res/values-ar/strings.xml | 3 + app/src/main/res/values-b+es+419/strings.xml | 3 + app/src/main/res/values-bg/strings.xml | 3 + app/src/main/res/values-cs/strings.xml | 3 + app/src/main/res/values-da/strings.xml | 3 + app/src/main/res/values-de/strings.xml | 3 + app/src/main/res/values-el/strings.xml | 3 + app/src/main/res/values-es/strings.xml | 3 + app/src/main/res/values-fi/strings.xml | 3 + app/src/main/res/values-fr/strings.xml | 3 + app/src/main/res/values-hi/strings.xml | 3 + app/src/main/res/values-hu/strings.xml | 3 + app/src/main/res/values-in/strings.xml | 3 + app/src/main/res/values-it/strings.xml | 3 + app/src/main/res/values-ja/strings.xml | 3 + app/src/main/res/values-ko/strings.xml | 3 + app/src/main/res/values-ms/strings.xml | 3 + app/src/main/res/values-nb/strings.xml | 3 + app/src/main/res/values-nl/strings.xml | 3 + app/src/main/res/values-pl/strings.xml | 3 + app/src/main/res/values-pt-rPT/strings.xml | 3 + app/src/main/res/values-pt/strings.xml | 3 + app/src/main/res/values-ro/strings.xml | 3 + app/src/main/res/values-ru/strings.xml | 3 + app/src/main/res/values-sv/strings.xml | 3 + app/src/main/res/values-th/strings.xml | 3 + app/src/main/res/values-tr/strings.xml | 3 + app/src/main/res/values-uk/strings.xml | 3 + app/src/main/res/values-vi/strings.xml | 3 + app/src/main/res/values-zh-rCN/strings.xml | 3 + app/src/main/res/values-zh-rHK/strings.xml | 3 + app/src/main/res/values-zh-rTW/strings.xml | 3 + app/src/main/res/values/strings.xml | 3 + app/src/main/rust/stores/Cargo.lock | 318 ++++- app/src/main/rust/stores/Cargo.toml | 10 +- app/src/main/rust/stores/JNI.md | 208 ++- app/src/main/rust/stores/src/lib.rs | 3 +- app/src/main/rust/stores/src/steam/NOTICE.md | 50 + app/src/main/rust/stores/src/steam/base64.rs | 97 ++ app/src/main/rust/stores/src/steam/cdn.rs | 468 ++++++ .../main/rust/stores/src/steam/cm_client.rs | 873 ++++++++++++ .../main/rust/stores/src/steam/cm_runtime.rs | 594 ++++++++ .../main/rust/stores/src/steam/cm_server.rs | 93 ++ .../rust/stores/src/steam/cm_server_list.rs | 205 +++ .../stores/src/steam/cmsg_protobuf_header.rs | 168 +++ .../rust/stores/src/steam/content_manifest.rs | 353 +++++ app/src/main/rust/stores/src/steam/crypto.rs | 150 ++ .../main/rust/stores/src/steam/depot_chunk.rs | 258 ++++ .../rust/stores/src/steam/depot_config.rs | 191 +++ .../rust/stores/src/steam/depot_downloader.rs | 162 +++ .../rust/stores/src/steam/depot_writer.rs | 958 +++++++++++++ app/src/main/rust/stores/src/steam/emsg.rs | 102 ++ .../stores/src/steam/encrypted_channel.rs | 472 +++++++ .../stores/src/steam/handshake_messages.rs | 192 +++ .../main/rust/stores/src/steam/heartbeat.rs | 128 ++ app/src/main/rust/stores/src/steam/http.rs | 79 ++ app/src/main/rust/stores/src/steam/install.rs | 467 ++++++ app/src/main/rust/stores/src/steam/jni.rs | 446 ++++++ .../main/rust/stores/src/steam/job_manager.rs | 267 ++++ .../rust/stores/src/steam/key_dictionary.rs | 91 ++ app/src/main/rust/stores/src/steam/kv.rs | 177 +++ app/src/main/rust/stores/src/steam/library.rs | 277 ++++ app/src/main/rust/stores/src/steam/mod.rs | 69 + .../src/steam/pb/ccontentserverdirectory.rs | 217 +++ .../cmsg_client_get_depot_decryption_key.rs | 79 ++ .../src/steam/pb/cmsg_client_license_list.rs | 143 ++ .../stores/src/steam/pb/cmsg_client_pics.rs | 432 ++++++ .../pb/cmsg_client_request_free_license.rs | 188 +++ .../src/steam/pb/cmsg_clientserver_login.rs | 286 ++++ app/src/main/rust/stores/src/steam/pb/mod.rs | 8 + app/src/main/rust/stores/src/steam/plan.rs | 685 +++++++++ .../rust/stores/src/steam/proto_envelope.rs | 87 ++ .../main/rust/stores/src/steam/proto_wire.rs | 459 ++++++ .../main/rust/stores/src/steam/register.rs | 1253 +++++++++++++++++ app/src/main/rust/stores/src/steam/session.rs | 556 ++++++++ app/src/main/rust/stores/src/steam/signin.rs | 519 +++++++ .../rust/stores/src/steam/steam_directory.rs | 238 ++++ .../main/rust/stores/src/steam/transport.rs | 36 + app/src/main/rust/stores/src/steam/vdf.rs | 523 +++++++ .../main/rust/stores/src/steam/wire_format.rs | 154 ++ .../rust/stores/src/steam/ws_connection.rs | 536 +++++++ .../launcher/session/StoresTabOrderTest.kt | 2 +- .../stores/steam/SteamLibraryFoldersTest.kt | 278 ++++ .../launcher/ui/LibraryEntriesTest.kt | 11 + 110 files changed, 15788 insertions(+), 41 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/steam/SteamClient.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/steam/SteamEngine.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/steam/SteamInstallJob.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/steam/SteamLibraryFolders.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/steam/SteamNative.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt create mode 100644 app/src/main/rust/stores/src/steam/NOTICE.md create mode 100644 app/src/main/rust/stores/src/steam/base64.rs create mode 100644 app/src/main/rust/stores/src/steam/cdn.rs create mode 100644 app/src/main/rust/stores/src/steam/cm_client.rs create mode 100644 app/src/main/rust/stores/src/steam/cm_runtime.rs create mode 100644 app/src/main/rust/stores/src/steam/cm_server.rs create mode 100644 app/src/main/rust/stores/src/steam/cm_server_list.rs create mode 100644 app/src/main/rust/stores/src/steam/cmsg_protobuf_header.rs create mode 100644 app/src/main/rust/stores/src/steam/content_manifest.rs create mode 100644 app/src/main/rust/stores/src/steam/crypto.rs create mode 100644 app/src/main/rust/stores/src/steam/depot_chunk.rs create mode 100644 app/src/main/rust/stores/src/steam/depot_config.rs create mode 100644 app/src/main/rust/stores/src/steam/depot_downloader.rs create mode 100644 app/src/main/rust/stores/src/steam/depot_writer.rs create mode 100644 app/src/main/rust/stores/src/steam/emsg.rs create mode 100644 app/src/main/rust/stores/src/steam/encrypted_channel.rs create mode 100644 app/src/main/rust/stores/src/steam/handshake_messages.rs create mode 100644 app/src/main/rust/stores/src/steam/heartbeat.rs create mode 100644 app/src/main/rust/stores/src/steam/http.rs create mode 100644 app/src/main/rust/stores/src/steam/install.rs create mode 100644 app/src/main/rust/stores/src/steam/jni.rs create mode 100644 app/src/main/rust/stores/src/steam/job_manager.rs create mode 100644 app/src/main/rust/stores/src/steam/key_dictionary.rs create mode 100644 app/src/main/rust/stores/src/steam/kv.rs create mode 100644 app/src/main/rust/stores/src/steam/library.rs create mode 100644 app/src/main/rust/stores/src/steam/mod.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/ccontentserverdirectory.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/cmsg_client_get_depot_decryption_key.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/cmsg_client_license_list.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/cmsg_client_pics.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/cmsg_client_request_free_license.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/cmsg_clientserver_login.rs create mode 100644 app/src/main/rust/stores/src/steam/pb/mod.rs create mode 100644 app/src/main/rust/stores/src/steam/plan.rs create mode 100644 app/src/main/rust/stores/src/steam/proto_envelope.rs create mode 100644 app/src/main/rust/stores/src/steam/proto_wire.rs create mode 100644 app/src/main/rust/stores/src/steam/register.rs create mode 100644 app/src/main/rust/stores/src/steam/session.rs create mode 100644 app/src/main/rust/stores/src/steam/signin.rs create mode 100644 app/src/main/rust/stores/src/steam/steam_directory.rs create mode 100644 app/src/main/rust/stores/src/steam/transport.rs create mode 100644 app/src/main/rust/stores/src/steam/vdf.rs create mode 100644 app/src/main/rust/stores/src/steam/wire_format.rs create mode 100644 app/src/main/rust/stores/src/steam/ws_connection.rs create mode 100644 app/src/test/java/com/droiddeck/launcher/stores/steam/SteamLibraryFoldersTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 58e7e12b2c..53a0c89298 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -55,7 +55,7 @@ class App : Application() { com.droiddeck.launcher.session.QuestExperimental.initialize(this) com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this) com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) - com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id }) + com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.tabbed.map { it.id }) com.droiddeck.launcher.update.AppUpdates.init(this) com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null)) com.droiddeck.launcher.core.DownloadSource.init(this) @@ -80,6 +80,7 @@ class App : Application() { com.droiddeck.launcher.stores.ea.EaBackend.app = this com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend) + com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.steam.SteamBackend) } private fun prefetchAddonPacks() { diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 56cb921e0f..6080477ef3 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -1259,6 +1259,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private fun startAfterSession(next: Intent) { + if (com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(next)) { + android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show() + return + } SessionService.stop(this) awaitSessionEnd(next, android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS) } @@ -3096,6 +3100,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return } val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return + if (Library.fromSteamClient(g)) { + com.droiddeck.launcher.stores.steam.SteamStore.uninstall(this, g.appId, target.manifest, fallback = { com.droiddeck.launcher.frontend.GameRemoval.delete(target) }) { refreshAddedGames(); refresh() } + return + } Thread({ com.droiddeck.launcher.frontend.GameRemoval.delete(target) ui.post { refreshAddedGames(); refresh() } @@ -3471,6 +3479,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show() return false } + if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) { + android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show() + return false + } refreshPhantomStatus() if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis()) @@ -3533,9 +3545,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet retryMs = GATE_LAUNCH_RETRY_MS, ) - /** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, or a storage cleanup. */ + /** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, a storage cleanup, or a Steam store download. */ private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() || - (SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning + (SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning || + (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.downloading()) private fun refreshPhantomStatus() { phantomProcessStatus = PhantomProcessLimit.read(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index f7468607dd..4be3ce0aec 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -842,6 +842,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde finish() return } + if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) { + runtimeRemovalBlocked = true + android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show() + finish() + return + } + if (savedInstanceState == null && !SessionState.running && !com.droiddeck.launcher.stores.steam.SteamStore.downloading()) { + // The Steam client signs in itself; the store's own sign-in must not overlap it. + Thread({ com.droiddeck.launcher.stores.steam.SteamEngine.forget() }, "steam-store-signout").start() + } if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) { val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty() diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index 5923cd6e44..ef3c2d3482 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -113,7 +113,7 @@ object CloudSaves { } Store.UBISOFT -> UBISOFT_TEMPLATE Store.EA -> eaRules(context, id) ?: return null - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> "" + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR, Store.STEAM -> "" } ?: return null p.edit() .putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE }) @@ -181,7 +181,7 @@ object CloudSaves { Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id) Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) } - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR, Store.STEAM -> null } return dir to (if (dir == null) "unresolved" else "ok") } @@ -221,7 +221,7 @@ object CloudSaves { if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first) } - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR, Store.STEAM -> null } private fun signedIn(context: Context, store: Store): Boolean = when (store) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt index a1b54088eb..99870f032c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt @@ -16,7 +16,7 @@ internal object LoginFlows { Store.UBISOFT -> ubisoftFlow(browserUserAgent) Store.EA -> eaFlow(browserUserAgent) Store.ROCKSTAR -> rockstarFlow(browserUserAgent) - Store.ITCH, Store.XBOX, Store.BATTLENET -> null + Store.ITCH, Store.XBOX, Store.BATTLENET, Store.STEAM -> null } @Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt index 67b439943d..765ae7a5ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt @@ -10,11 +10,18 @@ enum class Store(val id: String, val label: String, val shortLabel: String) { UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"), AMAZON("amazon", "Amazon Games", "Amazon"), BATTLENET("battlenet", "Battle.net", "Battle.net"), - GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"); + GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"), + STEAM("steamstore", "Steam", "Steam"); val folder: String get() = if (this == ITCH) "itch" else shortLabel + /** The Library tab its games list under: Steam's are the Steam client's own tab. */ + val librarySource: String get() = if (this == STEAM) com.droiddeck.launcher.frontend.Library.SOURCE_STEAM else id + companion object { fun byId(id: String?): Store? = entries.firstOrNull { it.id == id } + + /** The stores with a tab of their own; Steam's games list in the Library's Steam tab. */ + val tabbed: List get() = entries - STEAM } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt index 5e30fb7a5d..5bf88fb1b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt @@ -90,7 +90,7 @@ object StoreAccounts { fun signedInAs(context: Context, store: Store): String? { val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() } - if (store == Store.BATTLENET) return json.optString("display_name").takeIf { it.isNotBlank() } + if (store == Store.BATTLENET || store == Store.STEAM) return json.optString("display_name").takeIf { it.isNotBlank() } if (json.optString("access_token", "").isEmpty()) return null return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt index 040969b840..e9e4f9f631 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt @@ -247,7 +247,7 @@ object StoreInstallRoot { fun storeDir(root: File, store: Store): File = File(root, store.folder) fun gameFolders(context: Context): List = roots(context).flatMap { root -> - Store.entries.flatMap { store -> + Store.entries.filter { it != Store.STEAM }.flatMap { store -> storeDir(root, store).listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList() } } @@ -267,7 +267,7 @@ object StoreInstallRoot { fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true fun unfinished(context: Context): List = roots(context).flatMap { root -> - Store.entries.filter { it != Store.BATTLENET }.flatMap { store -> + Store.entries.filter { it != Store.BATTLENET && it != Store.STEAM }.flatMap { store -> storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder -> val sidecar = StoreGameSidecar.read(folder) when { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt index 8a47c06806..af8e09bc57 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt @@ -63,7 +63,7 @@ object StoreSizes { Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply() Store.ITCH, Store.GAMEJOLT -> {} Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply() - Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> {} + Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR, Store.STEAM -> {} } } }, pool).exceptionally { error -> @@ -142,5 +142,6 @@ object StoreSizes { Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 0L Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item) Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item) + Store.STEAM -> com.droiddeck.launcher.stores.steam.SteamStore.plannedBytes(context, item) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt index 975626168d..e73d1e6801 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt @@ -3,7 +3,7 @@ package com.droiddeck.launcher.stores data class StoreTab(val store: Store, val shown: Boolean) fun arrangeStoreTabs(order: List, hidden: Set): List { - val known = Store.entries.associateBy { it.id } + val known = Store.tabbed.associateBy { it.id } val listed = order.mapNotNull { known[it] }.distinct() - return (listed + Store.entries.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) } + return (listed + Store.tabbed.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 8cd6ea13a2..b5a0a89e42 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -85,6 +85,7 @@ object StoresState { do { seen = refreshRequests.get() runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) } + runCatching { com.droiddeck.launcher.stores.steam.SteamStore.syncAccount(app) } val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } } val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder -> StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) } @@ -260,6 +261,7 @@ object StoresState { fun requestInstall(context: Context, item: CatalogItem) { askForNotifications(context) + if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.requestInstall(context, item); return } if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return } if (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return } if (isUnfinished(item)) { install(context, item); return } @@ -278,6 +280,7 @@ object StoresState { fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) { val app = context.applicationContext + if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.restore(app, item); return } val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app) if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) { backends[item.store]?.install(app, item, targetRoot) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt index 4ceb4278bf..112ddeb3d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt @@ -159,6 +159,7 @@ object DownloadQueue { } fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) } + fun dropHeld(key: String) = synchronized(lock) { heldPaused.remove(key) } private var running = 0 fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamClient.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamClient.kt new file mode 100644 index 0000000000..6574a31380 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamClient.kt @@ -0,0 +1,130 @@ +package com.droiddeck.launcher.stores.steam + +import android.content.Context +import android.os.Environment +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.AddedGames +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.session.SecondaryLibrary +import com.droiddeck.launcher.session.SessionPhase +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.session.SteamLibraries +import com.droiddeck.launcher.stores.StoreInstallRoot +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +/** The active Steam client's folders as the app sees them. Reads storage; call off the main thread. */ +internal object SteamClient { + const val X86_64 = "x86_64" + + class Target( + val library: SteamLibraryFolders.Library, val engineHost: File, val label: String, + val freeBytes: Long, val removable: Boolean, val folder: Boolean, + ) + + fun activeArch(context: Context): String = SessionPrefs.activeSteamClientArch(context) + + private fun guestHome(arch: String) = if (arch == X86_64) "/root/.droiddeck-x64" else "/root" + + fun guestRoot(arch: String) = "${guestHome(arch)}/.local/share/Steam" + + private fun aliases(arch: String) = listOf(guestRoot(arch), "${guestHome(arch)}/.steam/steam", "${guestHome(arch)}/.steam/root") + + /** [guest] names [library]; the main library also answers to the client's other spellings of its root. */ + fun sameLibrary(context: Context, library: SteamLibraryFolders.Library, guest: String): Boolean { + if (library.guest == guest) return true + if (!library.main) return false + val arch = activeArch(context) + val wanted = SteamLibraryFolders.normalize(guest) ?: return false + return (aliases(arch) + guestRoot(arch)).mapNotNull(SteamLibraryFolders::normalize).contains(wanted) + } + + fun root(context: Context, arch: String = activeArch(context)): File = SessionPrefs.steamRoot(context, arch) + + fun registry(context: Context, arch: String = activeArch(context)): File = + File(LinuxRuntime.rootDir(context), guestHome(arch).removePrefix("/") + "/.steam/registry.vdf") + + fun loginUsers(context: Context, arch: String = activeArch(context)): File = File(root(context, arch), "config/loginusers.vdf") + + fun language(context: Context): String = + runCatching { SteamLibraryFolders.language(registry(context).readText()) }.getOrNull() ?: "english" + + fun mounts(context: Context): List { + val out = ArrayList() + GameStorage.effective(context)?.let { card -> SecondaryLibrary.CARD_GUESTS.forEach { out += SteamLibraryFolders.Mount(it, File(card.path)) } } + SteamLibraries.list(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) } + AddedGames.roots(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) } + StoreInstallRoot.externalRoots(context).forEach { (host, guest) -> out += SteamLibraryFolders.Mount(guest, host) } + out += SteamLibraryFolders.Mount("/root/Storage", Environment.getExternalStorageDirectory()) + return out + } + + /** Every library the client lists in libraryfolders.vdf that maps to a folder of the app. */ + fun libraries(context: Context, arch: String = activeArch(context)): List { + val root = root(context, arch) + val text = runCatching { File(root, "steamapps/libraryfolders.vdf").readText() }.getOrNull().orEmpty() + return SteamLibraryFolders.resolve( + SteamLibraryFolders.parse(text), guestRoot(arch), aliases(arch), root, mounts(context), LinuxRuntime.rootDir(context), + ) + } + + private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath) + + /** The card and added libraries are written through the raw card view when Android allows it, as the session binds them. */ + private fun engineView(context: Context): (File) -> File { + val bases = listOfNotNull(GameStorage.effective(context)?.let { File(it.path) }) + SteamLibraries.list(context).map { it.host } + val seen = HashMap() + return { host -> + val path = host.absolutePath + val base = bases.filter { path == it.absolutePath || path.startsWith(it.absolutePath + "/") }.maxByOrNull { it.absolutePath.length } + if (base == null) host else { + val content = seen.getOrPut(base.absolutePath) { SecondaryLibrary.contentPath(base) } + if (content.absolutePath == base.absolutePath) host + else path.removePrefix(base.absolutePath).trimStart('/').let { if (it.isEmpty()) content else File(content, it) } + } + } + } + + class EngineLibraries(val libraries: List>) { + val json: String get() = JSONArray().apply { + for ((library, host) in libraries) put(JSONObject().put("host", host.absolutePath).put("guest", library.guest)) + }.toString() + + fun hostOf(library: SteamLibraryFolders.Library): File = + libraries.firstOrNull { it.first.guest == library.guest }?.second ?: library.host + } + + fun engineLibraries(context: Context, arch: String = activeArch(context)): EngineLibraries { + val view = engineView(context) + return EngineLibraries(libraries(context, arch).filter { it.host.isDirectory }.map { it to view(it.host) }) + } + + fun targets(context: Context): List { + val arch = activeArch(context) + val card = GameStorage.effective(context)?.let { canonical(File(it.path)) } + val known = Library.steamLibraries(context, arch).associate { (host, label) -> + canonical(host) to if (label == "internal") context.getString(R.string.games_internal) else label + } + val engine = engineLibraries(context) + return engine.libraries.mapNotNull { (library, host) -> + if (!library.host.isDirectory || !library.host.canWrite()) return@mapNotNull null + val path = canonical(library.host) + val onCard = card != null && (path == card || path.startsWith("$card/")) + val label = library.label.ifBlank { + if (library.main) context.getString(R.string.stores_target_internal) else known[path] ?: File(library.guest).name + } + Target(library, host, label, StoreInstallRoot.availableBytes(host), removable = onCard, folder = !library.main && !onCard) + } + } + + /** True while a session that can run the Steam client is up or starting. */ + fun clientMayRun(): Boolean { + val up = SessionState.running || (SessionState.phase != SessionPhase.IDLE && SessionState.phase != SessionPhase.FAILED) + return up && SessionState.mode != SessionService.MODE_RUN + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamEngine.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamEngine.kt new file mode 100644 index 0000000000..826d7ab0c5 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamEngine.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.stores.steam + +import android.content.Context +import android.os.SystemClock +import android.util.Log +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.stores.StoresNative +import org.json.JSONArray +import org.json.JSONObject + +/** Blocking calls into the Rust engine; they reach the network, so never on the main thread. */ +internal object SteamEngine { + private const val TAG = "SteamEngine" + const val MISSING = "engine_missing" + const val MISSING_TEXT = "Steam: the store engine is not available" + + private const val RETRY_MS = 60_000L + /** After Steam refuses sign-ins for coming too often, wait well past its limit. */ + private const val THROTTLED_MS = 30 * 60_000L + + private val lock = Any() + @Volatile private var signedIn = false + /** The saved login the last sign-in attempt read, so a refusal rejects that login and not one saved since. */ + @Volatile var attempted: String? = null + private set + private var failed: JSONObject? = null + private var failedAt = 0L + + fun failure(error: String): JSONObject = JSONObject().put("ok", false).put("error", error) + + private fun call(op: String, block: () -> String): JSONObject { + if (!StoresNative.ensureLoaded()) return failure(MISSING) + val text = try { + block() + } catch (e: UnsatisfiedLinkError) { + Log.w(TAG, "$op: not in this engine build") + return failure(MISSING) + } catch (t: Throwable) { + Log.w(TAG, "$op: ${t.javaClass.simpleName}") + return failure(t.javaClass.simpleName) + } + return runCatching { JSONObject(text) }.getOrElse { failure("$op: unreadable answer") } + } + + fun signIn(context: Context): JSONObject { + synchronized(lock) { + if (signedIn) return JSONObject().put("ok", true) + failed?.takeIf { SystemClock.elapsedRealtime() - failedAt < waitAfter(it) }?.let { return it } + val roots = JSONArray() + .put(SessionPrefs.steamRoot(context, "arm64").absolutePath) + .put(SessionPrefs.steamRoot(context, SteamClient.X86_64).absolutePath) + val registry = SteamClient.registry(context).absolutePath + attempted = SteamStore.fingerprint(context) + val answer = call("signIn") { SteamNative.nativeSignIn(roots.toString(), registry, "") } + signedIn = answer.optBoolean("ok") + failed = if (signedIn) null else answer + failedAt = SystemClock.elapsedRealtime() + if (!signedIn) Log.w(TAG, "sign-in: ${answer.optString("error")}") + return answer + } + } + + private fun waitAfter(failure: JSONObject): Long { + val error = failure.optString("error") + return if ("RateLimitExceeded" in error || "Throttle" in error) THROTTLED_MS else RETRY_MS + } + + fun forget() { + synchronized(lock) { + failed = null + if (!signedIn) return + signedIn = false + try { + SteamNative.nativeSignOut() + } catch (t: Throwable) { + Log.w(TAG, "sign-out: ${t.javaClass.simpleName}") + } + } + } + + private fun signedCall(context: Context, op: String, block: () -> String): JSONObject { + synchronized(lock) { + val signIn = signIn(context) + if (!signIn.optBoolean("ok")) return signIn + val answer = call(op, block) + val error = answer.optString("error").lowercase() + if (!answer.optBoolean("ok") && listOf("logon", "sign", "session", "connect").any { it in error }) signedIn = false + return answer + } + } + + fun library(context: Context): JSONObject = signedCall(context, "library") { SteamNative.nativeLibrary() } + + fun plan(context: Context, appId: Int, language: String): JSONObject = + signedCall(context, "plan") { SteamNative.nativePlan(appId, language) } + + fun uninstall(appId: Int, steamRoot: String, host: String, guest: String, roots: String): JSONObject { + synchronized(lock) { + return call("uninstall") { SteamNative.nativeUninstall(appId, steamRoot, host, guest, roots) } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamInstallJob.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamInstallJob.kt new file mode 100644 index 0000000000..dac4beb222 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamInstallJob.kt @@ -0,0 +1,144 @@ +package com.droiddeck.launcher.stores.steam + +import android.content.Context +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.download.DownloadQueue +import com.droiddeck.launcher.stores.download.DownloadStage +import com.droiddeck.launcher.stores.download.StoreDownloadTier +import org.json.JSONObject +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +/** Called by the engine on its own threads. */ +interface SteamInstallListener { + fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?) + fun onComplete(ok: Boolean, result: String?) +} + +internal class SteamInstallJob( + private val app: Context, + private val appId: Int, + private val libraryGuest: String, +) : DownloadQueue.DownloadJob { + private val cancelled = AtomicBoolean(false) + private val started = AtomicBoolean(false) + @Volatile private var discard = false + @Volatile private var installDir: String? = null + @Volatile private var createdDir = false + + override fun run(handle: DownloadQueue.JobHandle): String? { + started.set(true) + try { + return install(handle) + } finally { + if (discard) SteamStore.discardPartial(app, appId, libraryGuest, installDir, createdDir) + } + } + + private fun install(handle: DownloadQueue.JobHandle): String? { + handle.stage(DownloadStage.MANIFEST) + if (SteamClient.clientMayRun()) throw IllegalStateException(app.getString(R.string.steam_store_close_steam)) + val engine = SteamClient.engineLibraries(app) + val target = engine.libraries.firstOrNull { SteamClient.sameLibrary(app, it.first, libraryGuest) } + ?: throw IllegalStateException(app.getString(R.string.game_sync_err_steam_library)) + val signIn = SteamEngine.signIn(app) + if (!signIn.optBoolean("ok")) { + SteamStore.signInFailed(app, signIn.optString("error")) + throw IllegalStateException(SteamStore.errorText(app, signIn)) + } + val language = SteamClient.language(app) + val (plan, planned) = SteamStore.plan(app, appId, language) + if (plan == null) throw IllegalStateException(SteamStore.errorText(app, planned)) + installDir = plan.installDir + createdDir = SteamStore.claimFolder(app, appId, libraryGuest, File(target.second, "steamapps/common/${plan.installDir}")) + if (plan.installBytes > 0) handle.diskSize(plan.installBytes) + if (cancelled.get()) return null + + val tier = StoreDownloadTier.current(app) + val journal = File(app.filesDir, "${SteamStore.JOURNAL}/$appId").apply { mkdirs() } + handle.log("steam: $appId tier=${tier.id} window=${tier.networkWindow} process_workers=${tier.processWorkers}") + val done = CountDownLatch(1) + val succeeded = AtomicBoolean(false) + val answer = AtomicReference("") + val listener = object : SteamInstallListener { + private var stage: DownloadStage? = null + private var shown = -1L + + override fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?) { + synchronized(this) { + val now = SteamLibraryFolders.stageOf(phase.orEmpty()) + if (now != stage) { + stage = now + shown = -1L + } + if (doneBytes < shown) return + shown = doneBytes + if (now == DownloadStage.DOWNLOAD) handle.progress(doneBytes, totalBytes) + else { + handle.stage(now) + if (totalBytes > 0) handle.stageProgress(doneBytes, totalBytes, bytes = true) + } + } + } + + override fun onComplete(ok: Boolean, result: String?) { + answer.set(result.orEmpty()) + succeeded.set(ok) + done.countDown() + } + } + val native = try { + SteamNative.nativeStart( + appId, language, SteamClient.root(app).absolutePath, target.second.absolutePath, target.first.guest, engine.json, + journal.absolutePath, "", tier.networkWindow.coerceIn(1, 128), tier.processWorkers, listener, + ) + } catch (e: UnsatisfiedLinkError) { + throw IllegalStateException(SteamEngine.MISSING_TEXT) + } + if (native == 0L && done.count > 0L) throw IllegalStateException(SteamStore.errorText(app, parse(answer.get()))) + if (native != 0L) { + try { + var forwarded = false + while (true) { + val finished = try { + done.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS) + } catch (e: InterruptedException) { + cancelled.set(true) + false + } + if (finished) break + if (!forwarded && cancelled.get()) { + runCatching { SteamNative.nativeCancel(native) } + forwarded = true + } + } + } finally { + runCatching { SteamNative.nativeRelease(native) } + } + } + val result = parse(answer.get()) + if (succeeded.get() && result.optBoolean("ok", true)) { + SteamStore.forgetJournal(app, appId, libraryGuest, target.first.guest) + return File(target.first.host, "steamapps/common/${plan.installDir}").path + } + if (cancelled.get() || result.optString("error") == "cancelled") return null + throw IllegalStateException(SteamStore.errorText(app, result)) + } + + private fun parse(text: String): JSONObject = + runCatching { JSONObject(text) }.getOrElse { SteamEngine.failure(text.ifBlank { "install failed" }) } + + override fun cancel(deleteFiles: Boolean) { + cancelled.set(true) + if (!deleteFiles) return + discard = true + if (!started.get()) SteamStore.discardPartial(app, appId, libraryGuest, null, SteamStore.createdFolder(app, appId, libraryGuest)) + } + + private companion object { + const val CANCEL_POLL_MS = 250L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamLibraryFolders.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamLibraryFolders.kt new file mode 100644 index 0000000000..c22f365acc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamLibraryFolders.kt @@ -0,0 +1,170 @@ +package com.droiddeck.launcher.stores.steam + +import com.droiddeck.launcher.storage.SteamStorage +import com.droiddeck.launcher.stores.download.DownloadStage +import java.io.File + +internal object SteamLibraryFolders { + data class Folder(val path: String, val label: String) + + class Mount(guest: String, val host: File) { + val guest: String = guest.trimEnd('/') + } + + data class Library(val guest: String, val host: File, val label: String, val main: Boolean) + + data class Installed(val appId: Int, val name: String, val installDir: String?, val library: Library, val sizeOnDisk: Long) + + /** Guest folders that exist only as binds of the session; without their bind they are empty mount points in the rootfs. */ + val BIND_ONLY = listOf("/mnt", "/media", "/storage", "/sdcard", "/root/Storage", "/root/ROMs", "/root/Games") + + private val TOKEN = Regex("\"((?:\\\\.|[^\"\\\\])*)\"|[{}]|//[^\n]*") + private val ACF = Regex("appmanifest_\\d+\\.acf") + private val SIZE_ON_DISK = Regex("^\\s*\"SizeOnDisk\"\\s*\"(\\d+)\"", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE)) + + private fun walk(text: String, pair: (blocks: List, key: String, value: String) -> Unit, closed: (blocks: List) -> Unit = {}) { + val blocks = ArrayList() + var key: String? = null + for (m in TOKEN.findAll(text)) { + val token = m.value + when { + token.startsWith("//") -> {} + token == "{" -> { blocks.add(key.orEmpty()); key = null } + token == "}" -> { if (blocks.isNotEmpty()) { closed(blocks); blocks.removeAt(blocks.lastIndex) }; key = null } + key == null -> key = unescape(m.groupValues[1]) + else -> { pair(blocks, key, unescape(m.groupValues[1])); key = null } + } + } + } + + private fun unescape(s: String): String { + if ('\\' !in s) return s + val out = StringBuilder(s.length) + var i = 0 + while (i < s.length) { + if (s[i] == '\\' && i + 1 < s.length) { out.append(s[i + 1]); i += 2 } else { out.append(s[i]); i++ } + } + return out.toString() + } + + private fun inRoot(blocks: List) = blocks.firstOrNull()?.equals("libraryfolders", ignoreCase = true) == true + + fun parse(text: String): List { + val out = ArrayList() + var path: String? = null + var label = "" + walk(text, pair = { blocks, key, value -> + if (!inRoot(blocks)) return@walk + if (blocks.size == 1 && key.isNotEmpty() && key.all(Char::isDigit)) out += Folder(value, "") + if (blocks.size == 2) when (key.lowercase()) { + "path" -> path = value + "label" -> label = value + } + }, closed = { blocks -> + if (blocks.size == 2 && inRoot(blocks)) path?.let { out += Folder(it, label) } + if (blocks.size == 2) { path = null; label = "" } + }) + return out + } + + fun normalize(path: String): String? { + val p = path.trim().replace(Regex("/+"), "/").trimEnd('/') + if (!p.startsWith("/") || p.split('/').any { it == ".." || it == "." }) return null + return p + } + + private fun under(path: String, prefix: String) = path == prefix || path.startsWith("$prefix/") + + fun hostFor(guest: String, mounts: List, rootfs: File): File? { + val path = normalize(guest) ?: return null + mounts.filter { it.guest.isNotEmpty() && under(path, it.guest) }.maxByOrNull { it.guest.length }?.let { m -> + val rest = path.removePrefix(m.guest).trimStart('/') + return if (rest.isEmpty()) m.host else File(m.host, rest) + } + if (BIND_ONLY.any { under(path, it) } || !under(path, "/root")) return null + return File(rootfs, path.removePrefix("/")) + } + + fun resolve(folders: List, mainGuest: String, aliases: Collection, mainHost: File, mounts: List, rootfs: File): List { + val mains = (aliases + mainGuest).mapNotNull(::normalize).toSet() + val listed = if (folders.any { normalize(it.path) in mains }) folders else listOf(Folder(mainGuest, "")) + folders + val out = ArrayList() + // The main library first, so an entry reaching the same folder under another path cannot take its place. + for (f in listed.sortedByDescending { normalize(it.path) in mains }) { + val guest = normalize(f.path) ?: continue + val main = guest in mains + val host = if (main) mainHost else hostFor(guest, mounts, rootfs) ?: continue + if (out.any { it.host.path == host.path || (main && it.main) }) continue + out += Library(guest, host, f.label.trim(), main) + } + return out.sortedByDescending { it.main } + } + + fun installed(libraries: List, read: (File) -> String? = { runCatching { it.readText() }.getOrNull() }): Map { + val out = LinkedHashMap() + for (library in libraries) { + val apps = File(library.host, "steamapps") + val names = apps.list() ?: continue + for (name in names.sorted()) { + if (!ACF.matches(name)) continue + val file = File(apps, name) + val text = read(file) ?: continue + val manifest = SteamStorage.parseManifest(file, text) ?: continue + if (!manifest.installed || SteamStorage.isTool(manifest) || manifest.appId in out) continue + val size = SIZE_ON_DISK.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L + out[manifest.appId] = Installed(manifest.appId, manifest.name, manifest.installDir, library, size) + } + } + return out + } + + data class SavedAccount(val id: String, val name: String) + + fun savedAccount(loginUsers: String): String? = savedLogin(loginUsers)?.name + + /** + * The account the client signs in with by itself, chosen as the engine does: `AutoLoginUser`, else the most recent, else the newest; + * none when that account opted out of Remember me. [SavedAccount.id] is its SteamID64. + */ + fun savedLogin(loginUsers: String, registry: String = ""): SavedAccount? { + val users = LinkedHashMap>() + walk(loginUsers, pair = { blocks, key, value -> + if (blocks.size == 2 && blocks[0].equals("users", ignoreCase = true)) users.getOrPut(blocks[1]) { HashMap() }[key.lowercase()] = value + }) + val accounts = users.entries.filter { it.key.all(Char::isDigit) && !it.value["accountname"].isNullOrBlank() } + val auto = autoLoginUser(registry) + val (id, user) = auto?.let { name -> accounts.firstOrNull { it.value["accountname"].equals(name, ignoreCase = true) } } + ?: accounts.firstOrNull { it.value["mostrecent"] == "1" } + ?: accounts.maxByOrNull { it.value["timestamp"]?.toLongOrNull() ?: 0L } + ?: return null + if (user["rememberpassword"] == "0") return null + val name = user["personaname"]?.takeIf { it.isNotBlank() } ?: user["accountname"]?.takeIf { it.isNotBlank() } ?: return null + return SavedAccount(id, name) + } + + fun autoLoginUser(registry: String): String? { + var found: String? = null + walk(registry, pair = { blocks, key, value -> + if (found == null && key.equals("AutoLoginUser", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value + }) + return found + } + + fun language(registry: String): String? { + var found: String? = null + walk(registry, pair = { blocks, key, value -> + if (found == null && key.equals("language", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value + }) + return found + } + + fun stageOf(phase: String): DownloadStage { + val p = phase.lowercase() + return when { + "verif" in p || "validat" in p -> DownloadStage.VERIFY + listOf("install", "regist", "final", "commit", "acf", "apply").any { it in p } -> DownloadStage.INSTALL + listOf("manifest", "plan", "prepar", "check", "scan", "clean", "alloc", "connect", "logon", "login", "sign").any { it in p } -> DownloadStage.MANIFEST + else -> DownloadStage.DOWNLOAD + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamNative.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamNative.kt new file mode 100644 index 0000000000..bce35d4500 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamNative.kt @@ -0,0 +1,12 @@ +package com.droiddeck.launcher.stores.steam + +object SteamNative { + @JvmStatic external fun nativeSignIn(steamRootsJson: String, registryVdfPath: String, caBundlePath: String): String + @JvmStatic external fun nativeSignOut() + @JvmStatic external fun nativeLibrary(): String + @JvmStatic external fun nativePlan(appId: Int, language: String): String + @JvmStatic external fun nativeStart(appId: Int, language: String, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String, journalDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Any): Long + @JvmStatic external fun nativeCancel(handle: Long) + @JvmStatic external fun nativeRelease(handle: Long) + @JvmStatic external fun nativeUninstall(appId: Int, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String): String +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt new file mode 100644 index 0000000000..ced05629ff --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt @@ -0,0 +1,399 @@ +package com.droiddeck.launcher.stores.steam + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.util.Log +import android.widget.Toast +import androidx.annotation.StringRes +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.storage.SteamStorage +import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreAccounts +import com.droiddeck.launcher.stores.StoreBackend +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.StoreInstalls +import com.droiddeck.launcher.stores.StoreSizes +import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.download.DownloadEntry +import com.droiddeck.launcher.stores.download.DownloadQueue +import com.droiddeck.launcher.stores.download.DownloadState +import com.droiddeck.launcher.stores.download.SavedQueue +import com.droiddeck.launcher.stores.formatBytes +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Executors + +/** Games land in the active client's own libraries, registered as the client does, and only while no session can run the client. */ +internal object SteamStore { + private const val TAG = "SteamStore" + private const val PREFS = "steam-store" + internal const val JOURNAL = "steam-store/journal" + private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/" + private const val LIBRARY = "library" + private const val LIBRARY_LABEL = "libraryLabel" + private val SIGNED_OUT = setOf("no_saved_login", "remember_me_off", "decrypt_failed") + private val REFUSED = Regex("logon_failed: eresult=(-?\\d+).*") + /** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */ + private val REFUSALS = setOf(5, 15, 18, 26, 27, 63) + + var picking by mutableStateOf(null) + + class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) { + companion object { + fun of(json: JSONObject): Plan? { + if (!json.optBoolean("ok")) return null + val dir = json.optString("installDir").takeIf { SteamStore.validDir(it) } ?: return null + return Plan(dir, json.optLong("downloadBytes"), json.optLong("installBytes"), json.optString("buildId"), json.optBoolean("linuxBuild")) + } + } + } + + internal const val LINUX_BUILD = "linux_build" + + /** Each plan with the language it was made for. */ + private val plans = ConcurrentHashMap>() + private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "steam-store") } + @Volatile private var rejectedThisRun: String? = null + + fun key(appId: Int): String = "${Store.STEAM.id}:$appId" + + private fun validDir(dir: String) = dir.isNotBlank() && dir != "." && dir != ".." && '/' !in dir && '\\' !in dir + + private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + + private fun toast(context: Context, @StringRes text: Int) { + val app = context.applicationContext + StoresState.post { Toast.makeText(app, text, Toast.LENGTH_LONG).show() } + } + + /** Steam refusing the saved login; a connection failure or a throttled logon leaves the account as it is. */ + internal fun isSignInError(error: String) = + error in SIGNED_OUT || REFUSED.matchEntire(error)?.groupValues?.get(1)?.toIntOrNull() in REFUSALS + + internal fun errorText(context: Context, answer: JSONObject): String { + val error = answer.optString("error") + return when { + error == SteamEngine.MISSING -> SteamEngine.MISSING_TEXT + error == LINUX_BUILD -> context.getString(R.string.steam_store_linux_build) + isSignInError(error) -> context.getString(R.string.stores_login_title, Store.STEAM.label) + error.isBlank() -> "Steam: install failed" + else -> error + } + } + + internal fun fingerprint(context: Context): String { + val users = SteamClient.loginUsers(context) + val registry = SteamClient.registry(context) + return "${SteamClient.activeArch(context)}:${users.lastModified()}:${users.length()}:${registry.lastModified()}:${registry.length()}" + } + + private fun savedAccount(context: Context): SteamLibraryFolders.SavedAccount? { + val print = fingerprint(context) + if (print == rejectedThisRun || print == prefs(context).getString("rejected", null)) return null + val registry = runCatching { SteamClient.registry(context).readText() }.getOrDefault("") + return runCatching { SteamLibraryFolders.savedLogin(SteamClient.loginUsers(context).readText(), registry) }.getOrNull() + } + + /** Mirrors the client's saved sign-in into the store account; reads storage. A new name for the same account only relabels it. */ + fun syncAccount(context: Context): Boolean { + val saved = savedAccount(context) + val stored = StoreAccounts.read(context, Store.STEAM) + val storedId = stored?.optString("steam_id").orEmpty() + if (saved != null && saved.id == storedId) { + if (saved.name != stored?.optString("display_name")) { + StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", saved.name).put("steam_id", saved.id)) + } + return false + } + if (saved == null && stored == null) return false + if (saved == null) StoreAccounts.clear(context, Store.STEAM) + else StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", saved.name).put("steam_id", saved.id)) + plans.clear() + SteamEngine.forget() + StoresState.post { + StoresState.library.remove(Store.STEAM) + StoresState.problems.remove(Store.STEAM) + } + Log.i(TAG, if (saved == null) "no saved Steam sign-in" else "Steam sign-in found") + return true + } + + internal fun signInFailed(context: Context, error: String) { + if (!isSignInError(error)) return + val print = fingerprint(context) + if (SteamEngine.attempted?.let { it != print } == true) return + rejectedThisRun = print + if (error in SIGNED_OUT) prefs(context).edit().putString("rejected", print).apply() + StoreAccounts.clear(context, Store.STEAM) + StoresState.logLine("Steam: the saved sign-in was not accepted ($error)") + StoresState.post { + StoresState.accounts.remove(Store.STEAM) + StoresState.library.remove(Store.STEAM) + } + } + + fun downloading(): Boolean = StoresState.latestDownloads.any { + it.store == Store.STEAM && (it.state == DownloadState.RUNNING || it.state == DownloadState.QUEUED) + } + + /** A Steam store download holds every session that could start the Steam client. */ + fun blocksSession(intent: Intent?): Boolean { + val mode = intent?.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM + return mode != SessionService.MODE_RUN && (downloading() || StoresState.uninstalling.keys.any { it.startsWith("${Store.STEAM.id}:") }) + } + + internal fun syncLibrary(context: Context, force: Boolean) { + val app = context.applicationContext + if (force) plans.clear() + work.execute { + val answer = SteamEngine.library(app) + if (!answer.optBoolean("ok")) { + val error = answer.optString("error") + if (isSignInError(error)) signInFailed(app, error) + else StoresState.post { + StoresState.problems[Store.STEAM] = errorText(app, answer) + StoresState.library[Store.STEAM] = emptyList() + } + return@execute + } + val art = runCatching { Library.steamLibraryArt(app).toMap() }.getOrDefault(emptyMap()) + val items = items(answer.optJSONArray("games"), art) + StoresState.logLine("Steam: library has ${items.size} games") + StoresState.post { + StoresState.problems.remove(Store.STEAM) + StoresState.library[Store.STEAM] = items + } + } + } + + private fun items(games: JSONArray?, art: Map): List { + val out = ArrayList() + for (i in 0 until (games?.length() ?: 0)) { + val game = games?.optJSONObject(i) ?: continue + val id = game.optInt("appId").takeIf { it > 0 } ?: continue + val type = game.optString("type").lowercase() + if (type.isNotEmpty() && type != "game") continue + val name = game.optString("name").takeIf { it.isNotBlank() } ?: continue + out += CatalogItem( + Store.STEAM, id.toString(), name, + imageUrl = "$CDN$id/header.jpg", + tallImageUrl = art[id]?.let { Uri.fromFile(it).toString() } ?: "$CDN$id/library_600x900.jpg", + isFree = game.optBoolean("free"), + storeUrl = "https://store.steampowered.com/app/$id/", + owned = true, + ) + } + return out.distinctBy { it.id }.sortedBy { it.title.lowercase() } + } + + /** Reaches the network; call off the main thread. */ + internal fun plan(context: Context, appId: Int, language: String = SteamClient.language(context)): Pair { + val plan = plans[appId]?.takeIf { it.first == language }?.second ?: run { + val answer = SteamEngine.plan(context, appId, language) + val error = answer.optString("error") + if (isSignInError(error)) signInFailed(context, error) + Plan.of(answer)?.also { plans[appId] = language to it } ?: return null to answer + } + if (plan.linuxBuild && !protonMapped(context, appId)) return null to SteamEngine.failure(LINUX_BUILD) + return plan to JSONObject().put("ok", true) + } + + /** The engine installs the Windows depots; a game with a Linux build gets those from the client only when it is mapped to a Proton. */ + private fun protonMapped(context: Context, appId: Int): Boolean { + val config = runCatching { File(SteamClient.root(context), "config/config.vdf").readText() }.getOrNull() ?: return false + return SteamStorage.compatMappings(config)[appId.toString()]?.contains("proton", ignoreCase = true) == true + } + + internal fun plannedBytes(context: Context, item: CatalogItem): Long = + item.id.toIntOrNull()?.let { plan(context, it).first?.installBytes } ?: 0L + + fun requestInstall(context: Context, item: CatalogItem) { + if (SteamClient.clientMayRun()) { + toast(context, R.string.steam_store_close_steam) + return + } + picking = item + } + + fun install(context: Context, item: CatalogItem, target: SteamClient.Target) { + val app = context.applicationContext + val appId = item.id.toIntOrNull() ?: return + if (SteamClient.clientMayRun()) { + toast(app, R.string.steam_store_close_steam) + return + } + val plan = plans[appId]?.second + val needed = plan?.installBytes ?: 0L + val tagged = item.copy(extra = item.extra + mapOf(LIBRARY to target.library.guest, LIBRARY_LABEL to target.label)) + val entry = DownloadEntry( + Store.STEAM, item.id, item.title, cover = item.imageUrl, + bytesTotal = plan?.downloadBytes ?: 0L, location = target.label, + ) + SavedQueue.remember(app, tagged, target.library.host) + if (StoreInstallRoot.insufficientSpace(needed, target.freeBytes)) { + val error = app.getString(R.string.stores_storage_insufficient, formatBytes(needed), formatBytes(target.freeBytes)) + DownloadQueue.recordFailed(app, entry, error) { requestInstall(app, item) } + return + } + DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, target.library.guest) } + } + + internal fun restore(context: Context, item: CatalogItem) { + val app = context.applicationContext + val appId = item.id.toIntOrNull() ?: return + val guest = item.extra[LIBRARY] ?: return + work.execute { + // Either client may have finished the install from where this download was paused. + if (installedByAClient(app, appId)) { + DownloadQueue.dropHeld(key(appId)) + StoresState.logLine("Steam: \"${item.title}\" was finished by Steam; its saved download is dropped") + return@execute + } + StoresState.post { + SavedQueue.remember(app, item, null) + val entry = DownloadEntry(Store.STEAM, item.id, item.title, cover = item.imageUrl, location = item.extra[LIBRARY_LABEL].orEmpty()) + DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, guest) } + } + } + } + + private fun installedByAClient(context: Context, appId: Int): Boolean = listOf("arm64", SteamClient.X86_64).any { arch -> + runCatching { appId in SteamLibraryFolders.installed(SteamClient.libraries(context, arch)) }.getOrDefault(false) + } + + /** Removes a game like the client does; [fallback] deletes it when the engine cannot (no engine, or a library it does not map). */ + fun uninstall(context: Context, appId: Int, manifest: File?, fallback: () -> Boolean, onDone: () -> Unit = {}) { + val app = context.applicationContext + if (SteamClient.clientMayRun()) { + toast(app, R.string.steam_store_close_steam) + return + } + val key = key(appId) + if (key in StoresState.uninstalling) return + StoresState.uninstalling[key] = 0f + Thread({ + if (!DownloadQueue.holdForRemovalWhenFree(key)) { + StoresState.logLine("Steam: kept $appId, its download is still running") + StoresState.post { StoresState.uninstalling.remove(key); onDone() } + return@Thread + } + val answer = try { runCatching { + val apps = manifest?.parentFile?.let(::canonical) + // The game may sit in the other client's library; that client's files are the ones to update. + val active = SteamClient.activeArch(app) + val found = listOf(active, if (active == SteamClient.X86_64) "arm64" else SteamClient.X86_64).firstNotNullOfOrNull { arch -> + val libraries = SteamClient.libraries(app, arch) + val chosen = if (apps == null) libraries else libraries.filter { canonical(File(it.host, "steamapps")) == apps } + SteamLibraryFolders.installed(chosen)[appId]?.let { arch to it } + } + val answer = if (found == null) SteamEngine.failure(SteamEngine.MISSING) else { + val (arch, game) = found + val engine = SteamClient.engineLibraries(app, arch) + SteamEngine.uninstall(appId, SteamClient.root(app, arch).absolutePath, engine.hostOf(game.library).absolutePath, game.library.guest, engine.json) + } + when { + answer.optString("error") != SteamEngine.MISSING -> answer + fallback() -> JSONObject().put("ok", true) + else -> SteamEngine.failure("remove_failed") + } + }.getOrElse { SteamEngine.failure(it.javaClass.simpleName) } } finally { DownloadQueue.releaseRemoval(key) } + val ok = answer.optBoolean("ok") + StoresState.logLine(if (ok) "Steam: uninstalled $appId" else "Steam: uninstall of $appId failed: ${answer.optString("error")}") + StoresState.post { + StoresState.uninstalling.remove(key) + if (ok) StoreSizes.onDisk.remove(key) + else Toast.makeText(app, errorText(app, answer), Toast.LENGTH_LONG).show() + onDone() + } + }, "steam-uninstall").start() + } + + private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath) + + /** The engine keys an app's resume journal by library as `///`. */ + private fun libraryKey(guest: String): String = + "%08x".format(java.util.zip.CRC32().apply { update(guest.trimEnd('/').toByteArray()) }.value) + + private fun createdMarker(context: Context, appId: Int, guest: String) = + File(context.filesDir, "$JOURNAL/$appId/created-${libraryKey(guest)}") + + /** Drops the resume state of one app in one library; other libraries' downloads of the app keep theirs. */ + internal fun forgetJournal(context: Context, appId: Int, guest: String, engineGuest: String? = null) { + val app = File(context.filesDir, "$JOURNAL/$appId") + val spelled = engineGuest ?: runCatching { + SteamClient.engineLibraries(context).libraries.firstOrNull { SteamClient.sameLibrary(context, it.first, guest) }?.first?.guest + }.getOrNull() ?: guest + File(app, "$appId/${libraryKey(spelled)}").deleteRecursively() + createdMarker(context, appId, guest).delete() + File(app, "$appId").delete() + app.delete() + } + + /** Whether this install made the game folder in that library: decided by its first attempt and kept for every resume. */ + internal fun claimFolder(context: Context, appId: Int, guest: String, folder: File): Boolean { + val marker = createdMarker(context, appId, guest) + if (marker.isFile) return true + if (folder.exists()) return false + marker.parentFile?.mkdirs() + return runCatching { marker.writeText(folder.name); true }.getOrDefault(false) + } + + internal fun createdFolder(context: Context, appId: Int, guest: String): Boolean = createdMarker(context, appId, guest).isFile + + /** + * Removes what a cancelled download left; a finished install stays. The game folder goes only when this download made it + * ([createdDir]) and no other installed game uses it. + */ + internal fun discardPartial(context: Context, appId: Int, guest: String, installDir: String?, createdDir: Boolean) { + // An unmounted library keeps its journal and ownership record, so a later cancel can still clean it up. + val library = runCatching { + SteamClient.engineLibraries(context).libraries.firstOrNull { SteamClient.sameLibrary(context, it.first, guest) }?.second + }.getOrNull() ?: return + val apps = File(library, "steamapps") + val acf = File(apps, "appmanifest_$appId.acf") + val manifest = acf.takeIf { it.isFile }?.let { f -> runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull() } + if (manifest?.installed == true) { forgetJournal(context, appId, guest); return } + val claimed = runCatching { createdMarker(context, appId, guest).readText() }.getOrNull()?.ifEmpty { null } + val dir = (installDir ?: claimed ?: manifest?.installDir ?: plans[appId]?.second?.installDir)?.takeIf { validDir(it) } + val shared = dir != null && apps.listFiles { f -> f.name.startsWith("appmanifest_") && f.name != acf.name }.orEmpty().any { f -> + runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull()?.installDir == dir + } + if (dir != null && createdDir && !shared) StoreInstalls.deleteTree(File(apps, "common/$dir")) + StoreInstalls.deleteTree(File(apps, "downloading/$appId")) + File(apps, "downloading").listFiles { f -> f.name.startsWith("state_${appId}_") && f.name.endsWith(".patch") }?.forEach { it.delete() } + if (manifest != null) acf.delete() + forgetJournal(context, appId, guest) + StoresState.logLine("Steam: removed the unfinished download of $appId") + } +} + +internal object SteamBackend : StoreBackend { + override val store: Store = Store.STEAM + + override fun signIn(context: Context) { + StoresState.logLine("Steam: sign in from the Steam client") + } + + override fun signOut(context: Context) = SteamEngine.forget() + + override fun syncLibrary(context: Context, force: Boolean) = SteamStore.syncLibrary(context, force) + + override fun loadShelves(context: Context, force: Boolean) {} + + override fun search(context: Context, query: String): List = + StoresState.library[store].orEmpty().filter { it.title.contains(query, ignoreCase = true) } + + override fun install(context: Context, item: CatalogItem, root: File) = SteamStore.restore(context, item) + + override fun uninstall(context: Context, game: InstalledStoreGame) {} +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 6fdea19e64..4fea952f34 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -842,6 +842,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } } com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } } com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } } + com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } } StepsLayer(screenAt) UiZooSheet() SessionDrawerPreview(s.secondScreenDisplays) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index bb4cc867cf..9a0b43e1d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -139,6 +139,7 @@ import androidx.compose.foundation.layout.offset internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) { fun game(games: List): Library.SteamGame? = when { appId != null -> games.firstOrNull { it.appId == appId } + store == Store.STEAM && storeId != null -> games.firstOrNull { Library.fromSteamClient(it) && it.appId.toString() == storeId } store != null && storeId != null -> games.firstOrNull { it.source == store.id && it.storeId == storeId } else -> null } @@ -182,7 +183,7 @@ internal fun GameDetail( if (nothing) return val source = game?.source ?: store?.id ?: Library.SOURCE_STEAM val title = game?.name ?: item?.title ?: installed?.sidecar?.title ?: id.orEmpty() - val favoriteKey = if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key + val favoriteKey = if (store == Store.STEAM && id != null) "app:$id" else if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key val scores = if (source != Library.ADDED) rememberGameScores(title.takeIf { it.isNotBlank() && it != id }) else null val achievements = remember(store, id, item?.accessible, installed) { when { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt index c50a6c8978..584fee1072 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt @@ -15,6 +15,7 @@ import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.frontend.SteamHidden import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.stores.Store internal const val LIBRARY_HIDDEN = "hidden" internal val HIDDEN_DOT = androidx.compose.ui.graphics.Color(0xFF9AA0A6) @@ -46,14 +47,18 @@ internal object LibraryHidden { } } - fun steamId(game: Library.SteamGame?): Long? = game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong() + /** The Steam client's own id for a game it lists, or for an owned Steam game it has not installed ([key] `steamstore:`). */ + fun steamId(game: Library.SteamGame?, key: String = ""): Long? = + game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong() + ?: key.takeIf { game == null && it.startsWith("${Store.STEAM.id}:") }?.substringAfter(':')?.toLongOrNull() - fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game)?.let { it in steam } == true + fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game, key)?.let { it in steam } == true - fun isHidden(entry: LibraryEntry): Boolean = isHidden(entry.favoriteKey, entry.game) + fun isHidden(entry: LibraryEntry): Boolean = + isHidden(entry.favoriteKey, entry.game) || entry.item?.takeIf { it.store == Store.STEAM }?.let { it.key in keys || it.id.toLongOrNull()?.let { id -> id in steam } == true } == true fun set(context: Context, key: String, game: Library.SteamGame?, hidden: Boolean): Boolean { - val id = steamId(game) + val id = steamId(game, key) val root = SessionPrefs.activeSteamRoot(context) val written = id?.let { SteamHidden.write(root, it, hidden) } if (id != null) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index e940e7b47f..ed5d2f9cf6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -139,7 +139,8 @@ internal class LibraryEntry( val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean, ) { val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" } - val favoriteKey: String get() = storeKey ?: key + /** A Steam game keeps the key it has once the Steam client lists it, so favoriting it before the install carries over. */ + val favoriteKey: String get() = if (item?.store == Store.STEAM) "app:${item.id}" else storeKey ?: key } internal fun libraryEntries( @@ -149,6 +150,7 @@ internal fun libraryEntries( val out = ArrayList() for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) { if (g.library == Library.EPIC_LAUNCHER) continue + if (Library.fromSteamClient(g)) claimed.add("${Store.STEAM.id}:${g.appId}") val storeKey = g.storeId?.let { "${g.source}:$it" } val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } } if (storeKey != null) { @@ -160,7 +162,7 @@ internal fun libraryEntries( } for (store in Store.entries) for (item in owned[store].orEmpty()) { if (!claimed.add(item.key)) continue - out += LibraryEntry(GameRef.key(item), store.id, item.title, null, item, installed = item.key in installedStore) + out += LibraryEntry(GameRef.key(item), store.librarySource, item.title, null, item, installed = item.key in installedStore) } return out.distinctBy { it.key } } @@ -297,7 +299,7 @@ internal object LibraryView { fun showOwned(context: android.content.Context, store: Store) { SessionPrefs.setLibraryShowUninstalled(context, true) ownedRequest++ - source = store.id + source = store.librarySource query = "" focusFirst = true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt index 2b3a4a5413..add703ce09 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -79,7 +79,7 @@ internal object StoreTabsState { private set fun load(context: android.content.Context) { - SessionPrefs.settleStoresTabOrder(context, Store.entries.map { it.id }) + SessionPrefs.settleStoresTabOrder(context, Store.tabbed.map { it.id }) tabs = arrangeStoreTabs(SessionPrefs.storesTabOrder(context), SessionPrefs.storesTabHidden(context)) libraryPlaces = SessionPrefs.libraryTabPlaces(context) ?: DEFAULT_LIBRARY_PLACES libraryHidden = SessionPrefs.libraryTabsHidden(context) + listOfNotNull(LIBRARY_HIDDEN.takeUnless { SessionPrefs.libraryShowHidden(context) }) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt index a822548739..806975b3ee 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt @@ -39,7 +39,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) { Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF)) Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747)) Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17)) - Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF)) + Library.SOURCE_STEAM, Store.STEAM.id -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF)) Library.SOURCE_COLLECTION -> SourceColours(Color(0xFF2B1A3D), Color(0xFFD2A8FF), Color(0xFFA25BFF)) FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal) else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF)) @@ -47,7 +47,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) { @Composable internal fun sourceLabel(source: String): String = when (source) { - Library.SOURCE_STEAM -> stringResource(R.string.source_steam) + Library.SOURCE_STEAM, Store.STEAM.id -> stringResource(R.string.source_steam) Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections) Store.GOG.id -> Store.GOG.label Store.EPIC.id -> Store.EPIC.label diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt index c5dd008edb..ea7483e531 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt @@ -27,6 +27,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -46,7 +47,10 @@ import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoreLanguage +import com.droiddeck.launcher.stores.StoreSizes import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.steam.SteamClient +import com.droiddeck.launcher.stores.steam.SteamStore import com.droiddeck.launcher.stores.formatBytes import com.droiddeck.launcher.stores.gog.GogDownloadManager import kotlinx.coroutines.Dispatchers @@ -133,6 +137,61 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) { } } +@Composable +internal fun SteamInstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + val targets by produceState?>(null, item.key) { + value = withContext(Dispatchers.IO) { runCatching { SteamClient.targets(ctx) }.getOrDefault(emptyList()) } + } + val needed by produceState(StoreSizes.size(item), item.key) { + val bytes = withContext(Dispatchers.IO) { runCatching { SteamStore.plannedBytes(ctx, item) }.getOrDefault(0L) } + if (bytes > 0L) value = bytes + } + val list = targets + val focus = remember(list?.size) { List(list?.size ?: 0) { FocusRequester() } } + LaunchedEffect(focus) { if (focus.isNotEmpty()) focusWithinFrames({ false }) { focus[0] } } + AppDialog(shown, close, "steamInstallWhere", wide = false, maxWidth = 440.dp) { + Rise(0) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + Text( + stringResource(R.string.stores_install_title, item.title), fontSize = 15.sp, color = colors.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), + ) + Text( + stringResource(R.string.common_cancel), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, + modifier = Modifier.clip(Shape12).focusGlide().clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp), + ) + } + } + Rise(1) { + when { + list == null -> androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp)) + list.isEmpty() -> Note(stringResource(R.string.game_sync_err_steam_library)) + else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + list.forEachIndexed { i, t -> + val isLow = StoreInstallRoot.insufficientSpace(needed, t.freeBytes) + val freeText = when { + t.freeBytes < 0L -> stringResource(R.string.stores_target_free_unknown) + isLow -> stringResource(R.string.stores_storage_low, formatBytes(t.freeBytes), formatBytes(needed)) + else -> stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)) + } + TargetRow( + label = t.label, free = freeText, removable = t.removable, folder = t.folder, focus = focus[i], + modifier = Modifier.fillMaxWidth(), warning = isLow, + ) { + SteamStore.install(ctx, item, t) + close() + } + } + } + } + } + } +} + @Composable private fun TargetRow(label: String, free: String, removable: Boolean, folder: Boolean, focus: FocusRequester, modifier: Modifier, warning: Boolean = false, onPick: () -> Unit) { val colors = MaterialTheme.colorScheme diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 30caa5fca7..963c2f9c99 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -1031,6 +1031,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette { Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6) Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030) Store.ROCKSTAR -> Color(0xFFFCAF17) to Color(0xFFD98E00) + Store.STEAM -> Color(0xFF1A9FFF) to Color(0xFF0F6FC0) null -> return base } val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White @@ -1323,6 +1324,6 @@ internal fun openUrl(ctx: android.content.Context, url: String) { } internal fun launchStoreGame(store: Store, id: String, s: FrontEndState, a: FrontEndActions) { - val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id } + val game = GameRef(null, store, id).game(s.steamGames) if (game != null) a.onSteamGame(game) else a.onStoreGame(store, id) } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 922fecc6d6..6d7c3f2a99 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -4241,4 +4241,7 @@ خطأ عرض HUD أثناء اللعب فقط إخفاء HUD عند عدم اكتشاف إطارات اللعبة. + أغلق Steam أولاً + أوقف تنزيل Steam مؤقتًا أولاً + تثبّت هذه اللعبة إصدار Linux الخاص بها. ثبّتها من Steam. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index dc55741139..a2979d48c0 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -4121,4 +4121,7 @@ Error Mostrar el HUD solo durante una partida Ocultar el HUD cuando no se detecten fotogramas del juego. + Cierra Steam primero + Pausa primero la descarga de Steam + Este juego instala su versión para Linux. Instálalo desde Steam. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 1875c2fedf..e675862a3e 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -4081,4 +4081,7 @@ Грешка Показвай HUD само по време на игра Скривай HUD, когато не се засичат кадри от играта. + Първо затворете Steam + Първо поставете на пауза изтеглянето от Steam + Тази игра инсталира версията си за Linux. Инсталирайте я от Steam. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 9e89a11dab..7cf992764c 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -4161,4 +4161,7 @@ Chyba Zobrazovat HUD pouze během hry Skrýt HUD, když nejsou detekovány snímky hry. + Nejprve zavřete Steam + Nejprve pozastavte stahování ze Steamu + Tato hra instaluje svou verzi pro Linux. Nainstalujte ji ze Steamu. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index cb76db4888..143ab1b9ea 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -4081,4 +4081,7 @@ Fejl Vis kun HUD under spil Skjul HUD, når der ikke registreres spilbilleder. + Luk Steam først + Sæt Steam-downloaden på pause først + Dette spil installerer sin Linux-version. Installer det fra Steam. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 37269e423f..914bb74ad7 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -4081,4 +4081,7 @@ Fehler HUD nur während eines Spiels anzeigen HUD ausblenden, wenn keine Spielframes erkannt werden. + Schließe zuerst Steam + Pausiere zuerst den Steam-Download + Dieses Spiel installiert seine Linux-Version. Installiere es über Steam. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index dd2110463c..7fdf796097 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -4081,4 +4081,7 @@ Σφάλμα Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού. + Κλείστε πρώτα το Steam + Θέστε πρώτα σε παύση τη λήψη του Steam + Αυτό το παιχνίδι εγκαθιστά την έκδοσή του για Linux. Εγκαταστήστε το από το Steam. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 7c3023606f..053b93e421 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -4121,4 +4121,7 @@ Error Mostrar el HUD solo durante una partida Ocultar el HUD cuando no se detecten fotogramas del juego. + Cierra Steam primero + Pausa primero la descarga de Steam + Este juego instala su versión para Linux. Instálalo desde Steam. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index b901ff521f..6e55423d70 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -4081,4 +4081,7 @@ Virhe Näytä HUD vain pelin aikana Piilota HUD, kun pelin ruutuja ei havaita. + Sulje Steam ensin + Keskeytä Steam-lataus ensin + Tämä peli asentaa Linux-versionsa. Asenna se Steamista. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0688318753..6d4ded65c8 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -4120,4 +4120,7 @@ Erreur Afficher le HUD uniquement pendant une partie Masquer le HUD lorsqu’aucune image du jeu n’est détectée. + Fermez d\'abord Steam + Mettez d\'abord en pause le téléchargement Steam + Ce jeu installe sa version Linux. Installez-le depuis Steam. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index d0bb555bc9..6de5dc38b1 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -4081,4 +4081,7 @@ त्रुटि HUD केवल गेम के दौरान दिखाएँ गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ। + पहले Steam बंद करें + पहले Steam डाउनलोड रोकें + यह गेम अपना Linux संस्करण इंस्टॉल करता है। इसे Steam से इंस्टॉल करें। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index ec6fcc1046..d74049f467 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -4081,4 +4081,7 @@ Hiba HUD megjelenítése csak játék közben HUD elrejtése, ha nem észlelhetők játék képkockái. + Előbb zárd be a Steamet + Előbb szüneteltesd a Steam-letöltést + Ez a játék a Linux-verzióját telepíti. Telepítsd a Steamből. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 7a71814cde..236f232f4b 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -4051,4 +4051,7 @@ Kesalahan Tampilkan HUD hanya saat bermain Sembunyikan HUD saat tidak ada frame game yang terdeteksi. + Tutup Steam terlebih dahulu + Jeda unduhan Steam terlebih dahulu + Game ini memasang versi Linux-nya. Pasang dari Steam. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f5a493b0ec..43e9306d8e 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -4120,4 +4120,7 @@ Errore Mostra l’HUD solo durante il gioco Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco. + Chiudi prima Steam + Metti prima in pausa il download di Steam + Questo gioco installa la sua versione Linux. Installalo da Steam. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 474b14df32..67b18ea334 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -4051,4 +4051,7 @@ エラー ゲーム中のみHUDを表示 ゲームのフレームが検出されないときはHUDを非表示にする。 + 先に Steam を閉じてください + 先に Steam のダウンロードを一時停止してください + このゲームは Linux 版をインストールします。Steam からインストールしてください。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 629e4c7783..dc029a5291 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -4051,4 +4051,7 @@ 오류 게임 중에만 HUD 표시 게임 프레임이 감지되지 않으면 HUD 숨기기. + 먼저 Steam을 닫으세요 + 먼저 Steam 다운로드를 일시 중지하세요 + 이 게임은 Linux 버전을 설치합니다. Steam에서 설치하세요. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 49c45bdb40..91782ade1b 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -4051,4 +4051,7 @@ Ralat Paparkan HUD hanya semasa bermain Sembunyikan HUD apabila bingkai permainan tidak dikesan. + Tutup Steam dahulu + Jeda muat turun Steam dahulu + Permainan ini memasang versi Linuxnya. Pasang daripada Steam. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 39b4ce3cba..d6467031f5 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -4081,4 +4081,7 @@ Feil Vis HUD bare mens du spiller Skjul HUD når ingen spillbilder registreres. + Lukk Steam først + Sett Steam-nedlastingen på pause først + Dette spillet installerer Linux-versjonen sin. Installer det fra Steam. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 40136f0ea3..46d00397d5 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -4081,4 +4081,7 @@ Fout HUD alleen tijdens een game weergeven Verberg de HUD wanneer er geen gameframes worden gedetecteerd. + Sluit eerst Steam + Pauzeer eerst de Steam-download + Deze game installeert zijn Linux-versie. Installeer hem via Steam. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 9ebd06008b..13474fe501 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -4161,4 +4161,7 @@ Błąd Pokazuj HUD tylko podczas gry Ukryj HUD, gdy nie wykryto klatek gry. + Najpierw zamknij Steam + Najpierw wstrzymaj pobieranie ze Steam + Ta gra instaluje swoją wersję dla Linuksa. Zainstaluj ją ze Steama. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 57c6b9b645..c617438301 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -4120,4 +4120,7 @@ Suavização de serrilhado Mostrar o HUD apenas durante um jogo Ocultar o HUD quando não forem detetados fotogramas do jogo. + Feche primeiro o Steam + Coloque primeiro em pausa a transferência do Steam + Este jogo instala a sua versão para Linux. Instale-o a partir do Steam. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index c6db0023bb..8442d03cf3 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -4128,4 +4128,7 @@ Suavização de serrilhado Mostrar o HUD somente durante o jogo Ocultar o HUD quando nenhum quadro do jogo for detectado. + Feche o Steam primeiro + Pause o download do Steam primeiro + Este jogo instala sua versão para Linux. Instale-o pelo Steam. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 6101dd8761..94fd9b54e1 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -4121,4 +4121,7 @@ Eroare Afișează HUD-ul doar în timpul jocului Ascunde HUD-ul când nu sunt detectate cadre ale jocului. + Închide mai întâi Steam + Pune mai întâi pe pauză descărcarea Steam + Acest joc își instalează versiunea pentru Linux. Instalează-l din Steam. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 042b6cc500..7dbba39402 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -4162,4 +4162,7 @@ Ошибка Показывать HUD только во время игры Скрывать HUD, когда кадры игры не обнаруживаются. + Сначала закройте Steam + Сначала приостановите загрузку Steam + Эта игра устанавливает свою версию для Linux. Установите её из Steam. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index ea63d20fb9..ff194690b3 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -4081,4 +4081,7 @@ Fel Visa HUD endast under spel Dölj HUD när inga spelbildrutor upptäcks. + Stäng Steam först + Pausa Steam-nedladdningen först + Det här spelet installerar sin Linux-version. Installera det från Steam. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 50a282f966..42b58d08fb 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -4051,4 +4051,7 @@ ข้อผิดพลาด แสดง HUD เฉพาะขณะเล่นเกม ซ่อน HUD เมื่อไม่พบเฟรมของเกม + ปิด Steam ก่อน + หยุดการดาวน์โหลด Steam ชั่วคราวก่อน + เกมนี้ติดตั้งเวอร์ชัน Linux ของตัวเอง ให้ติดตั้งจาก Steam diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 8b3df10ac8..f3969661f0 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -4081,4 +4081,7 @@ Hata HUD\'yi yalnızca oyun sırasında göster Oyun kareleri algılanmadığında HUD\'yi gizle. + Önce Steam\'i kapatın + Önce Steam indirmesini duraklatın + Bu oyun Linux sürümünü yükler. Steam\'den yükleyin. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index d492865848..a151e22574 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -4161,4 +4161,7 @@ Помилка Показувати HUD лише під час гри Приховувати HUD, коли кадри гри не виявляються. + Спочатку закрийте Steam + Спочатку призупиніть завантаження Steam + Ця гра встановлює свою версію для Linux. Установіть її зі Steam. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 3a46f7b7f9..20b73786eb 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -4051,4 +4051,7 @@ Lỗi Chỉ hiển thị HUD khi đang chơi Ẩn HUD khi không phát hiện khung hình trò chơi. + Hãy đóng Steam trước + Hãy tạm dừng tải xuống Steam trước + Trò chơi này cài bản dành cho Linux. Hãy cài từ Steam. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index be252ebe48..2ba2dbb67c 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -4051,4 +4051,7 @@ 错误 仅在游戏期间显示 HUD 未检测到游戏帧时隐藏 HUD。 + 请先关闭 Steam + 请先暂停 Steam 下载 + 此游戏会安装其 Linux 版本。请通过 Steam 安装。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 101adaef46..7c9ed0161c 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -4051,4 +4051,7 @@ 錯誤 只在遊戲期間顯示 HUD 未偵測到遊戲畫面時隱藏 HUD。 + 請先關閉 Steam + 請先暫停 Steam 下載 + 此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index f9d96cf955..4776feb776 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -4051,4 +4051,7 @@ 錯誤 僅在遊戲期間顯示 HUD 未偵測到遊戲畫面時隱藏 HUD。 + 請先關閉 Steam + 請先暫停 Steam 下載 + 此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 700d06d37a..cc7f0aca34 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4390,4 +4390,7 @@ Hide the HUD when no game frames are detected. Getting ready · %1$d%% Finish setup · %1$d%% + Close Steam first + Pause the Steam download first + This game installs its Linux build. Install it from Steam. diff --git a/app/src/main/rust/stores/Cargo.lock b/app/src/main/rust/stores/Cargo.lock index 6a470b3bea..962c867e74 100644 --- a/app/src/main/rust/stores/Cargo.lock +++ b/app/src/main/rust/stores/Cargo.lock @@ -8,6 +8,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + [[package]] name = "async-compression" version = "0.4.42" @@ -26,12 +37,24 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.11.1" @@ -47,6 +70,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -65,6 +97,15 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.62" @@ -93,6 +134,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "combine" version = "4.6.7" @@ -120,6 +171,12 @@ version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -163,6 +220,23 @@ dependencies = [ "typenum", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -170,7 +244,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", + "subtle", ] [[package]] @@ -188,20 +264,28 @@ dependencies = [ name = "droiddeckstores" version = "0.1.0" dependencies = [ + "aes", + "cbc", "cc", + "crc32fast", "flate2", "futures-util", + "hmac", "jni", "libc", "lzma-rs", + "rand 0.8.8", "reqwest", + "rsa", "ruzstd", "serde_json", "sha1", "sha2", "tokio", "tokio-rustls", - "webpki-roots", + "tungstenite", + "webpki-roots 1.0.7", + "zeroize", ] [[package]] @@ -317,6 +401,15 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.4.1" @@ -389,7 +482,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots", + "webpki-roots 1.0.7", ] [[package]] @@ -528,6 +621,16 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -596,12 +699,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "litemap" version = "0.8.2" @@ -657,12 +775,66 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -675,6 +847,27 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -731,7 +924,7 @@ dependencies = [ "bytes", "getrandom 0.3.4", "lru-slab", - "rand", + "rand 0.9.4", "ring", "rustc-hash", "rustls", @@ -772,14 +965,35 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" dependencies = [ - "rand_chacha", - "rand_core", + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", ] [[package]] @@ -789,7 +1003,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", ] [[package]] @@ -836,7 +1059,7 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots", + "webpki-roots 1.0.7", ] [[package]] @@ -853,6 +1076,26 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-hash" version = "2.1.2" @@ -1007,6 +1250,16 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.9" @@ -1035,6 +1288,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1255,6 +1524,26 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.4", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 2.0.18", + "utf-8", + "webpki-roots 0.26.11", +] + [[package]] name = "twox-hash" version = "2.1.5" @@ -1291,6 +1580,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -1412,6 +1707,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.7", +] + [[package]] name = "webpki-roots" version = "1.0.7" diff --git a/app/src/main/rust/stores/Cargo.toml b/app/src/main/rust/stores/Cargo.toml index 97a27659a1..c8caf6f1b3 100644 --- a/app/src/main/rust/stores/Cargo.toml +++ b/app/src/main/rust/stores/Cargo.toml @@ -10,11 +10,17 @@ name = "droiddeckstores" crate-type = ["cdylib"] [dependencies] +aes = "0.8" +cbc = { version = "0.1", features = ["alloc", "block-padding"] } +crc32fast = "1" +hmac = "0.12" jni = "0.21" libc = "0.2" -lzma-rs = { version = "0.3", default-features = false } +lzma-rs = { version = "0.3", default-features = false, features = ["raw_decoder"] } flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +rand = "0.8" reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "gzip"] } +rsa = "0.9" tokio = { version = "1", default-features = false, features = ["rt", "net", "time", "sync", "io-util"] } futures-util = { version = "0.3", default-features = false, features = ["std"] } serde_json = { version = "1", features = ["preserve_order"] } @@ -23,6 +29,8 @@ sha2 = "0.10" tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } webpki-roots = "1" ruzstd = "0.8" +tungstenite = { version = "0.26", default-features = false, features = ["handshake", "rustls-tls-webpki-roots"] } +zeroize = "1" [build-dependencies] cc = "1" diff --git a/app/src/main/rust/stores/JNI.md b/app/src/main/rust/stores/JNI.md index b87390ac8f..80f84aee2c 100644 --- a/app/src/main/rust/stores/JNI.md +++ b/app/src/main/rust/stores/JNI.md @@ -2,19 +2,19 @@ The Kotlin side of the store download engines mirrors this file exactly. Every symbol the library exports is listed here with the class it binds to, the JNI signature, when it is called and on -which thread. The GOG engine and the shared fetch core came from Bannerlator's -`bl-steam-client` crate (method names and signatures match Bannerlator's `BlGogDownload`, only the -package and class names changed). The Epic module (`src/epic/`) and the Amazon module +which thread. The GOG engine, the shared fetch core and the Steam module (`src/steam/`, see its +`NOTICE.md`) are derived from WinNative's `wn-steam-client` crate (GPL-3.0-or-later, +https://github.com/WinNative-Emu/WinNative). The Epic module (`src/epic/`) and the Amazon module (`src/amazon/`) are DroidDeck's own, each written from a functional spec (see `docs/development/epic-cleanroom.md` and `docs/development/amazon-cleanroom.md`); their JNI -surfaces below are new. +surfaces below are new, as is the Steam one. Load it once with `System.loadLibrary("droiddeckstores")`. The library is built by Gradle (`buildRustStores`, see `app/build.gradle`) and is absent from a `-PskipRust=true` build, so every call site must be ready for `UnsatisfiedLinkError` on `loadLibrary` or on the first `external` call and degrade to "store unavailable". -## Conventions that hold for all three engines +## Conventions that hold for all engines - The `external` functions are declared `@JvmStatic` in a Kotlin `object` (a `JClass` arrives as the second JNI argument). Declaring them in a plain `object` without `@JvmStatic` also binds — @@ -290,9 +290,207 @@ absent or that of empty input are created without a request. `.amazon_download_i created when a run starts and removed when it succeeds, which also creates `.amazon_download_complete`; nothing reads either marker. +## `com.droiddeck.launcher.stores.steam.SteamNative` + +Steam store engine (`src/steam/`): signs in with the Linux Steam client's saved login, lists the +account's games, plans and downloads a game straight into the Steam library folder the client +uses, then writes what the client writes on completion, so the client sees the game as installed +and does not update or verify it. Kotlin runs downloads and uninstalls only while the Steam client +is closed. + +```kotlin +package com.droiddeck.launcher.stores.steam + +object SteamNative { + @JvmStatic external fun nativeSignIn(steamRootsJson: String, registryVdfPath: String, caBundlePath: String): String + @JvmStatic external fun nativeSignOut() + @JvmStatic external fun nativeLibrary(): String + @JvmStatic external fun nativePlan(appId: Int, language: String): String + @JvmStatic external fun nativeStart(appId: Int, language: String, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String, journalDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Any): Long + @JvmStatic external fun nativeCancel(handle: Long) + @JvmStatic external fun nativeRelease(handle: Long) + @JvmStatic external fun nativeUninstall(appId: Int, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String): String +} +``` + +| Method | JNI signature | Symbol suffix | +|---|---|---| +| `nativeSignIn(steamRootsJson, registryVdfPath, caBundlePath): String` | `(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;` | `nativeSignIn` | +| `nativeSignOut()` | `()V` | `nativeSignOut` | +| `nativeLibrary(): String` | `()Ljava/lang/String;` | `nativeLibrary` | +| `nativePlan(appId, language): String` | `(ILjava/lang/String;)Ljava/lang/String;` | `nativePlan` | +| `nativeStart(...)`: Long | `(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IILjava/lang/Object;)J` | `nativeStart` | +| `nativeCancel(handle: Long)` | `(J)V` | `nativeCancel` | +| `nativeRelease(handle: Long)` | `(J)V` | `nativeRelease` | +| `nativeUninstall(appId, steamRoot, gameLibraryHost, gameLibraryGuest, libraryRootsJson): String` | `(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;` | `nativeUninstall` | + +Full symbols are `Java_com_droiddeck_launcher_stores_steam_SteamNative_`. Every `String` +answer is a UTF-8 JSON object with `"ok": true|false`; a failure carries `"error": ""`. `nativeSignIn`, `nativeLibrary`, `nativePlan` and `nativeUninstall` block on the +network or the disk: call them off the main thread. A Rust panic is caught at the boundary and +answers `{"ok":false,"error":"internal_error"}`. + +Paths: "host" paths are Android paths the app can open; "guest" paths are what the Steam client +sees inside proot (what `libraryfolders.vdf` holds). `libraryRootsJson` is a JSON array of +`{"host": "...", "guest": "..."}`, one per library of the active client; it is used to find shared +app folders and `libraryfolders.vdf` entries, and the game library is added to it when missing. + +### `nativeSignIn` + +`steamRootsJson`: JSON array of host paths of Steam roots (arm64 and x86-64 clients), searched in +order. `registryVdfPath`: host path of `~/.steam/registry.vdf` (`""` = none). `caBundlePath`: see +conventions (used for the CM directory request). + +Reads, never writes: `/config/loginusers.vdf` (accounts), `/local.vdf` +(`MachineUserConfigStore/Software/Valve/Steam/ConnectCache`, keys matched case-insensitively; the +entry whose key starts with the 8-hex-digit CRC32 of the lowercased account name), and +`registry.vdf` (`Registry/HKCU/Software/Valve/Steam/AutoLoginUser`). The account is +`AutoLoginUser` when it names a known account, else the one with `MostRecent` `"1"`, else the +newest `Timestamp`. The token is decrypted in memory (key = SHA-256 of the lowercased account +name; AES-256-ECB-wrapped IV, AES-256-CBC + PKCS#7), checked to be a Steam JWT for that +SteamID64, sent once in the CM logon and zeroized. It is never logged, written, renewed or +replaced. + +Answers `{"ok":true,"account":"","steamId":""}` or +`{"ok":false,"error":…}` with `no_saved_login` (no account in any `loginusers.vdf`), +`remember_me_off` (`RememberPassword` `"0"`, or no ConnectCache entry: signed out), +`decrypt_failed` (the entry does not decrypt to this account's token), or `logon_failed: …` +(`logon_failed: eresult= ` when Steam refused the logon, e.g. `eresult=5 +InvalidPassword` for an expired token; otherwise a connection reason). One process-wide session: +a second call while it is logged on answers at once with the same account. After logon the +session sends no persona, friends or presence messages. + +`nativeSignOut()` logs off and drops the session; it never touches the client's files. + +### `nativeLibrary` + +`{"ok":true,"games":[{"appId":291550,"name":"Brawlhalla","installDir":"Brawlhalla","type":"game","free":true}…]}`: +every app the account's licenses grant (package 0, the basic Steam license, is skipped) whose +PICS `common.type` is `game`, sorted by name. `free` = appinfo marks it free to play +(`common.freetogame` or `extended.isfreeapp` `"1"`). Loaded once per session (the first call +fetches PICS for every owned app and can take a while). `not_signed_in` without a session. + +### `nativePlan` + +What `nativeStart` would install for `appId` with `language` (Steam's language names, e.g. +`english`): + +```json +{"ok":true,"appId":291550,"name":"Brawlhalla","installDir":"Brawlhalla","buildId":26465982, + "language":"english","linuxBuild":false,"downloadBytes":…,"installBytes":1594368732, + "depots":[{"depotId":291551,"manifestId":"4224536525702420323","size":1565156559,"dlcAppId":0}], + "shared":[{"depotId":228988,"fromAppId":228980,"manifestId":"6645201662696499616","size":29212173}]} +``` + +Selection (what the client picks for a Windows game run through Proton): `config.oslist` empty or +containing `windows`; `config.osarch` empty or `64` (`32` only when no `64` depot exists); +`config.language` empty or the language (english when the game has no depot for the requested +language but has english ones; the answer's `language` is the one used); no `lowviolence` +depots; for an owned app, only depots one of the account's packages grants (`depotids`), as +the client installs no other; DLC depots (`dlcappid`) only when the DLC is owned; `depotfromapp`/`sharedinstall` +depots are listed under `shared` with the owning app (e.g. 228980 Steamworks Common +Redistributables), whose public manifest they use. Manifest gids are the public branch's, sizes +come from PICS, `buildId` is the public branch's. `installBytes`/`downloadBytes` include the +shared depots (they are not checked against what is already installed here). Errors: +`not_signed_in`, `not_owned`, `appinfo unavailable`, `appinfo unavailable for shared app `, +`no installable Windows depot`, `linux_build` (no Windows depot, and the game has a Linux build). A free app +the account does not own yet is planned without asking for its license. `linuxBuild` is true +when `common.oslist` lists `linux`: the client then installs the Linux build unless the game is +mapped to a Proton, so the caller checks that mapping before installing. + +### `nativeStart` + +Parameters: `appId`, `language`, `steamRoot` (host path of the active client's Steam root; its +`steamapps/` and `config/` hold the two `libraryfolders.vdf` copies, `depotcache/` its cached +manifests), `gameLibraryHost`/`gameLibraryGuest` (the library to install into), `libraryRootsJson`, +`journalDir` (app-private directory for resume journals), `caBundlePath`, `maxWorkers` (request +window ceiling; `0` = 16), `processWorkers` (decrypt/decompress/write threads; `0` = half the +cores, 2 to 6; on SD cards the card writes, not the network, tend to be the limit), `listener`. + +Returns `0` without any callback when the listener is null, `appId <= 0`, the JavaVM or a global +ref cannot be obtained, `steamRoot`/`gameLibraryHost`/`gameLibraryGuest`/`journalDir` is empty, +or the worker thread cannot be spawned. Otherwise the run is on a thread named `steam-dl` +(background priority) and `onComplete` fires exactly once, last. `nativeCancel` is idempotent and +safe until `nativeRelease`; call `nativeRelease` exactly once per non-zero handle, after +`onComplete`. + +| Listener method | JNI signature | When | +|---|---|---| +| `onProgress(doneBytes: Long, totalBytes: Long, phase: String)` | `(JJLjava/lang/String;)V` | `phase` is `preparing` (sign-in check, plan, takeover, keys, manifests; `0`/`0`), `downloading` (the game's depots), `shared` (shared depots) or `registering`. `doneBytes`/`totalBytes` count the depot files (decompressed) of everything this run installs, shared depots included; chunks already correct on disk count as done. At most every 250 ms, plus at every phase change and depot end. | +| `onComplete(ok: Boolean, result: String)` | `(ZLjava/lang/String;)V` | `{"ok":true,"alreadyInstalled":false}` after a download, `{"ok":true,"alreadyInstalled":true}` when the game was already fully installed at the current build (nothing downloaded or written), or `{"ok":false,"error":"…"}`: `cancelled`, `not_signed_in`, `already_running` (a run for the same app is active), `not_owned`, `free_license_refused`, `library_not_in_libraryfolders` (no `libraryfolders.vdf` entry has the guest path), `not_enough_space: need … MiB, have … MiB`, `access_denied: depot `, or a short message for network and disk failures. | + +What a run does, in order: + +1. Plans as `nativePlan`; a free app the account does not own is first added to the account with + `CMsgClientRequestFreeLicense`. +2. Takeover check on `/steamapps/appmanifest_.acf`: absent → fresh + install; `StateFlags` has 4 and none of the update/download/validate bits and `buildid` is the + current build → `alreadyInstalled`; a build on disk at another build (the fully-installed bit + set, even with an update pending) → `update_in_steam`, left to the Steam client; otherwise (a + half-finished client download) `steamapps/downloading/` and `steamapps/temp/` + are deleted and the journal is discarded, while the manifest is kept so registration merges + its settings. +3. Downloads the game's depots in place into `/steamapps/common/`: + no temp files, no space reservation, each file trimmed to its exact size when its last chunk + lands. A chunk used several times is fetched once. Files already on disk are read back chunk by + chunk and only wrong or missing chunks are fetched (resume, update, taking over a client's + partial files). +4. Shared depots go into the library that holds `appmanifest_.acf` (else the Steam + root's own library), folder `steamapps/common/`; a shared depot already + installed at the planned manifest is skipped. +5. Registers: writes `appmanifest_.acf` (keys in the client's order: `appid`, `Universe`, + `name`, `StateFlags` 4, `installdir`, `LastUpdated`, `LastPlayed`, `SizeOnDisk` (the game's + depots), `StagingSize`, `buildid`, `LastOwner` (SteamID64), `DownloadType` 1, `UpdateResult`, + `BytesToDownload`/`BytesDownloaded` (compressed size of every installed depot, shared + included), `BytesToStage`/`BytesStaged` (installed size of the game's depots plus the shared + depots installed in this run), `TargetBuildID`, `AutoUpdateBehavior`, + `AllowOtherDownloadsWhileRunning`, `ScheduledAutoUpdate`, `InstalledDepots` + (`manifest`, `size`, plus `dlcappid` for DLC depots), `InstallScripts` when a game depot has + one, `SharedDepots`, `UserConfig`/`MountedConfig` `language`), merging into an existing file + (unknown keys, `LastPlayed` and the auto-update settings are kept). Updates the shared app's + manifest (`SizeOnDisk`, `InstalledDepots`, `InstallScripts` entry such as + `"228988" "_CommonRedist\\vcredist\\2019\\installscript.vdf"`; created when missing). + Adds `"" "0"` under `apps` of the matching entry in both + `/steamapps/libraryfolders.vdf` and `/config/libraryfolders.vdf` (the + client fills in the size later); nothing else there changes. All files are written through a + temp file + rename. + +Never written: `config.vdf`, `localconfig.vdf`, `registry.vdf` (the client regenerates them) and +`depotcache/` (the client keeps manifests there with decrypted file names, not in the CDN form +this engine caches; it fetches them when it needs them). + +On-disk protocol of the journal: `///depot.config` (JSON: +`buildId`, the finished manifest per depot or an in-progress sentinel) and +`_.manifest` (raw CDN manifests) beside it. `` is the CRC32, as 8 +lowercase hex digits, of `gameLibraryGuest` with trailing `/` removed, so a resume in one library +never trusts depots finished in another. A cancelled or failed run keeps it, and the next `nativeStart` for the same app +resumes (finished depots are skipped, the rest is checked on disk); a journal written for another +build is dropped. It is deleted after a successful registration. Nothing extra is ever left in +the game folder. + +### `nativeUninstall` + +Matches the client's own uninstall: deletes `/steamapps/common/` and +the game's `appmanifest_.acf`, `/depotcache/_.manifest` for +the game's `InstalledDepots` and `/steamapps/shadercache/`; keeps +`steamapps/compatdata/` (the Proton prefix, i.e. saves). For each of the game's +`SharedDepots` that no other installed game in any library lists, deletes that depot's files from +the shared app's folder (empty folders stay, as with the client) and removes its +`InstalledDepots` and `InstallScripts` entries and its size from the shared app's manifest. The +file list comes from the client's `depotcache` copy of that manifest, else from the CDN through +the live session; without either the shared depot is left installed and listed in `keptShared`. +Removes the app from `apps` in both `libraryfolders.vdf` copies. + +Answers `{"ok":true,"removedShared":[228988],"keptShared":[]}`, or `{"ok":false,"error":…}`: +`not_installed` (no app manifest), `bad installdir in app manifest`, `bad arguments`, or a disk +error. + ## Log tags Lines go to logcat under `GogNative` and `EpicNative` (the Amazon module logs only through `onLog`). Bannerlator used `BL_GOG_DL` for the GOG engine; the fetch core's line grammar (`fetch-start`, `fetch-window`, `throughput`, `fetch-end`, `summary`) is unchanged, so its tuning notes still read against a DroidDeck log. + +The Steam module logs under `DroidDeckSteam` and never logs a token; its chunk downloads go +through the fetch core with the label `steam depot=`. diff --git a/app/src/main/rust/stores/src/lib.rs b/app/src/main/rust/stores/src/lib.rs index 12a351138f..b8e3cd3935 100644 --- a/app/src/main/rust/stores/src/lib.rs +++ b/app/src/main/rust/stores/src/lib.rs @@ -1,4 +1,4 @@ -//! Ported from Bannerlator's bl-steam-client crate (GPL-3.0-or-later), itself derived from WinNative's wn-steam-client. +//! DroidDeck's store download engines. The Steam client and the shared fetch core are derived from WinNative's wn-steam-client (GPL-3.0-or-later, https://github.com/WinNative-Emu/WinNative). #![allow(clippy::missing_safety_doc, clippy::result_large_err)] @@ -11,4 +11,5 @@ pub mod fetch_tuning; pub mod gog; pub mod md5_small; pub mod priority; +pub mod steam; pub mod stores_jni; diff --git a/app/src/main/rust/stores/src/steam/NOTICE.md b/app/src/main/rust/stores/src/steam/NOTICE.md new file mode 100644 index 0000000000..49256ab3e1 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/NOTICE.md @@ -0,0 +1,50 @@ +# Steam store engine: provenance and license notice + +The Steam module of `libdroiddeckstores.so` (`app/src/main/rust/stores/src/steam/`) is a +**derivative work of the `wn-steam-client` crate from the WinNative project**, +, directory +`app/src/main/cpp/wn-steam-client/rust`, taken at upstream commit `a2020b7` (2026-09-01). +The upstream crate is published under **GPL-3.0-or-later**; this derivative is distributed under +the same license as part of DroidDeck. Copyright in the original code remains with the WinNative +authors and contributors, including maxjivi05. + +The shared fetch core (`src/fetch_core.rs`, `src/fetch_tuning.rs`) and `src/md5_small.rs`, which +this module uses, come from the same upstream crate. + +## Modifications made in DroidDeck (GPL-3.0 §5(a) statement of changes) + +Date of modification: 2026-11-07. + +- Ported into the `droiddeckstores` crate as the module `steam`; identifiers, log tag + (`DroidDeckSteam`) and thread name (`steam-dl`) follow DroidDeck naming. +- Kept, with import paths adapted: WebSocket transport (`ws_connection`, `transport`), channel + encryption and handshake (`encrypted_channel`, `handshake_messages`, `crypto`, `key_dictionary`), + CM server discovery (`cm_server`, `cm_server_list`, `steam_directory`), wire formats + (`emsg`, `cmsg_protobuf_header`, `proto_envelope`, `proto_wire`, `wire_format`, `base64`, `vdf`), + `heartbeat`, `job_manager`, `content_manifest`, `depot_chunk`, and the protobuf messages for + logon, licenses, PICS, depot keys, manifest request codes, CDN servers and free licenses. +- `cm_client` reduced to logon with a refresh token, heartbeat, log-off and the download-store + requests; the logon sends `machine_id` `DroidDeck-Steam`; logon and log-off EResults are kept + for error reporting. +- `cm_runtime`: no persona or friends traffic after logon, the C-ABI bridge (`cm_bridge`) is + removed, and outbound messages are cleared from memory once sent. +- Blocking HTTP replaced by a one-shot request helper (`http`); `cdn_client` reduced to `cdn` + (URLs, manifest and HTTP-delivered appinfo fetches); CDN servers are de-duplicated by host, + capped at 10 and filtered by `allowed_app_ids`. +- `depot_writer` rewritten on DroidDeck's shared fetch core: files are written in place without + `fallocate` or zero-fill and trimmed with `set_len`; the number of decode/write workers is a + parameter; a chunk used in several places is fetched once; on resume, chunks on disk are read + back and checked before anything is fetched. +- `depot_config` / `depot_downloader`: the resume journal moved out of the game folder into a + caller-given directory, keyed by app and build; the progress sidecar and clean-pause markers are + dropped. +- New: `signin` (reuse of the Linux Steam client's saved login), `session` (one process-wide CM + session), `library`, `plan` (depot selection), `register` (app manifests, shared depots, + `libraryfolders.vdf`, takeover of half-finished client downloads, uninstall), `kv` (Valve + KeyValues writer), `install` (download orchestration) and a new JNI layer (`jni`). +- `library` records the depots the account's packages grant, and `plan` installs only those + (the client skips the rest, e.g. edition-only depots); `plan` flags apps with a Linux build. +- Not ported: QR and password sign-in, auth sessions, friends, chat and chat images, persona, + lobbies, cloud, user stats, achievements, inventory, published files and workshop, app and + ownership tickets, playing-session control, the Wine bridge, the other stores' downloaders, + the version module and the original JNI layer. diff --git a/app/src/main/rust/stores/src/steam/base64.rs b/app/src/main/rust/stores/src/steam/base64.rs new file mode 100644 index 0000000000..b8854f1ce6 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/base64.rs @@ -0,0 +1,97 @@ +const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +pub fn encode(bytes: &[u8]) -> String { + if bytes.is_empty() { + return String::new(); + } + + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + let (chunks, remainder) = bytes.as_chunks::<3>(); + for chunk in chunks { + let v = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32; + out.push(ALPHABET[((v >> 18) & 0x3f) as usize] as char); + out.push(ALPHABET[((v >> 12) & 0x3f) as usize] as char); + out.push(ALPHABET[((v >> 6) & 0x3f) as usize] as char); + out.push(ALPHABET[(v & 0x3f) as usize] as char); + } + + match remainder { + [a] => { + let v = (*a as u32) << 16; + out.push(ALPHABET[((v >> 18) & 0x3f) as usize] as char); + out.push(ALPHABET[((v >> 12) & 0x3f) as usize] as char); + out.push('='); + out.push('='); + } + [a, b] => { + let v = ((*a as u32) << 16) | ((*b as u32) << 8); + out.push(ALPHABET[((v >> 18) & 0x3f) as usize] as char); + out.push(ALPHABET[((v >> 12) & 0x3f) as usize] as char); + out.push(ALPHABET[((v >> 6) & 0x3f) as usize] as char); + out.push('='); + } + [] => {} + _ => unreachable!(), + } + + out +} + +pub fn decode(s: &str) -> Option> { + let mut out = Vec::with_capacity((s.len() / 4) * 3 + 3); + let mut acc = 0u32; + let mut bits = 0u32; + + for b in s.bytes() { + let v = value_of(b)?; + let Some(v) = v else { + continue; + }; + acc = (acc << 6) | v as u32; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push(((acc >> bits) & 0xff) as u8); + } + } + + Some(out) +} + +fn value_of(b: u8) -> Option> { + match b { + b'A'..=b'Z' => Some(Some(b - b'A')), + b'a'..=b'z' => Some(Some(b - b'a' + 26)), + b'0'..=b'9' => Some(Some(b - b'0' + 52)), + b'+' | b'-' => Some(Some(62)), + b'/' | b'_' => Some(Some(63)), + b'=' | b' ' | b'\t' | b'\n' | b'\r' => Some(None), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encodes_rfc4648_padding() { + assert_eq!(encode(b""), ""); + assert_eq!(encode(b"f"), "Zg=="); + assert_eq!(encode(b"fo"), "Zm8="); + assert_eq!(encode(b"foo"), "Zm9v"); + assert_eq!(encode(b"foobar"), "Zm9vYmFy"); + } + + #[test] + fn decodes_standard_urlsafe_and_whitespace() { + assert_eq!(decode("Zm9v YmFy"), Some(b"foobar".to_vec())); + assert_eq!(decode("SGVsbG8td29ybGQ_"), Some(b"Hello-world?".to_vec())); + assert_eq!(decode("Zg=="), Some(b"f".to_vec())); + } + + #[test] + fn invalid_character_fails() { + assert_eq!(decode("Zm9v*"), None); + } +} diff --git a/app/src/main/rust/stores/src/steam/cdn.rs b/app/src/main/rust/stores/src/steam/cdn.rs new file mode 100644 index 0000000000..0fd92e0075 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/cdn.rs @@ -0,0 +1,468 @@ +//! SteamPipe CDN: URL formation, manifest + HTTP-delivered appinfo fetches, and the zip/gzip +//! helpers they need. Chunk bodies are fetched by the shared fetch core (`crate::fetch_core`). + +use crate::steam::pb::ccontentserverdirectory::CContentServerDirectoryServerInfo; +use flate2::read::{DeflateDecoder, GzDecoder}; +use std::io::Read; +use std::time::Duration; + +/// Distinct CDN hosts a depot run spreads over. Each chunk carries one URL per host, so this also +/// bounds the per-chunk URL memory. +pub const MAX_CDN_HOSTS: usize = 10; + +pub const MAX_MANIFEST_FETCH_ATTEMPTS: usize = 5; + +/// Largest decompressed manifest accepted; real ones are at most tens of MiB. +pub const MAX_MANIFEST_BYTES: usize = 512 * 1024 * 1024; +/// Largest decompressed HTTP-delivered appinfo accepted. +pub const MAX_APPINFO_BYTES: usize = 64 * 1024 * 1024; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CdnManifestResult { + pub raw_manifest: Vec, + pub error: String, + pub http_status: i32, +} + +impl CdnManifestResult { + pub fn ok(&self) -> bool { + self.error.is_empty() && !self.raw_manifest.is_empty() + } +} + +pub fn default_timeout() -> Duration { + Duration::from_secs(30) +} + +pub fn build_manifest_url( + server: &CContentServerDirectoryServerInfo, + depot_id: u32, + manifest_id: u64, + request_code: u64, +) -> Result { + let host = preferred_host(server).ok_or_else(|| "cdn server has no host".to_string())?; + let mut url = format!( + "{}://{}:{}/depot/{}/manifest/{}/5", + if server.use_https() { "https" } else { "http" }, + host, + server.port(), + depot_id, + manifest_id + ); + if request_code != 0 { + url.push('/'); + url.push_str(&request_code.to_string()); + } + Ok(url) +} + +pub fn build_chunk_url( + server: &CContentServerDirectoryServerInfo, + depot_id: u32, + chunk_sha: &[u8], +) -> Result { + if chunk_sha.is_empty() { + return Err("empty chunk sha".to_string()); + } + let host = preferred_host(server).ok_or_else(|| "cdn server has no host".to_string())?; + Ok(format!( + "{}://{}:{}/depot/{}/chunk/{}", + if server.use_https() { "https" } else { "http" }, + host, + server.port(), + depot_id, + hex_encode(chunk_sha) + )) +} + +/// The per-host key the fetch core caps concurrency on (vhost when present, as the URL uses it). +pub fn host_key(server: &CContentServerDirectoryServerInfo) -> String { + preferred_host(server).unwrap_or_default().to_string() +} + +/// Usable servers (not China-only, with a host), de-duplicated by host key, in directory order, +/// at most [`MAX_CDN_HOSTS`]. +pub fn usable_servers( + servers: &[CContentServerDirectoryServerInfo], +) -> Vec { + let mut out: Vec = Vec::new(); + for server in servers { + if server.steam_china_only || server.host.is_empty() { + continue; + } + let key = host_key(server); + if out.iter().any(|s| host_key(s) == key) { + continue; + } + out.push(server.clone()); + if out.len() >= MAX_CDN_HOSTS { + break; + } + } + out +} + +pub fn fetch_manifest( + server: &CContentServerDirectoryServerInfo, + depot_id: u32, + manifest_id: u64, + request_code: u64, + ca_bundle_path: &str, + timeout: Duration, +) -> CdnManifestResult { + let url = match build_manifest_url(server, depot_id, manifest_id, request_code) { + Ok(url) => url, + Err(error) => { + return CdnManifestResult { + error, + ..Default::default() + } + } + }; + match crate::steam::http::get(&url, timeout, ca_bundle_path) { + Ok(response) => validate_manifest_response( + response.status as i32, + response.body, + response.content_length, + ), + Err(error) => CdnManifestResult { + error, + ..Default::default() + }, + } +} + +/// Tries the servers in order (wrapping) with the shared back-off, up to +/// [`MAX_MANIFEST_FETCH_ATTEMPTS`] attempts. +pub fn fetch_manifest_with_retry( + servers: &[CContentServerDirectoryServerInfo], + depot_id: u32, + manifest_id: u64, + request_code: u64, + ca_bundle_path: &str, + cancel: &std::sync::atomic::AtomicBool, +) -> CdnManifestResult { + if servers.is_empty() { + return CdnManifestResult { + error: "no CDN servers available".to_string(), + ..Default::default() + }; + } + let mut last = CdnManifestResult::default(); + for attempt in 0..MAX_MANIFEST_FETCH_ATTEMPTS { + if attempt > 0 { + std::thread::sleep(Duration::from_millis( + crate::fetch_tuning::retry_backoff_millis(attempt as u32), + )); + } + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + return CdnManifestResult { + error: "cancelled".to_string(), + ..Default::default() + }; + } + let server = &servers[attempt % servers.len()]; + last = fetch_manifest( + server, + depot_id, + manifest_id, + request_code, + ca_bundle_path, + default_timeout(), + ); + if last.ok() { + return last; + } + } + last +} + +/// HTTP-delivered PICS appinfo URL (large appinfo the CM did not inline). +pub fn build_appinfo_url(http_host: &str, app_id: u32, sha: &[u8]) -> String { + format!( + "http://{}/appinfo/{}/sha/{}.txt.gz", + http_host, + app_id, + hex_encode(sha) + ) +} + +/// Fetch + gunzip an HTTP-delivered appinfo blob (same VDF as an inline `buffer`). +pub fn fetch_appinfo( + http_host: &str, + app_id: u32, + sha: &[u8], + ca_bundle_path: &str, + timeout: Duration, +) -> Option> { + if http_host.is_empty() || sha.is_empty() { + return None; + } + let url = build_appinfo_url(http_host, app_id, sha); + let response = crate::steam::http::get(&url, timeout, ca_bundle_path).ok()?; + if response.status != 200 || response.body.is_empty() { + return None; + } + maybe_gunzip(response.body, MAX_APPINFO_BYTES) +} + +pub fn validate_manifest_response( + http_status: i32, + body: Vec, + content_length: Option, +) -> CdnManifestResult { + if http_status != 200 { + return CdnManifestResult { + http_status, + error: format!("HTTP status {http_status}"), + ..Default::default() + }; + } + if let Some(expected) = content_length { + if body.len() as u64 != expected { + return CdnManifestResult { + http_status, + error: "manifest body truncated (length mismatch)".to_string(), + ..Default::default() + }; + } + } + let Some(raw_manifest) = unzip_first_entry(&body, MAX_MANIFEST_BYTES) else { + return CdnManifestResult { + http_status, + error: "manifest unzip failed".to_string(), + ..Default::default() + }; + }; + CdnManifestResult { + raw_manifest, + error: String::new(), + http_status, + } +} + +/// The first entry of a zip, refused when it declares or decodes to more than `limit` bytes, or +/// to a size other than the one its header declares. +pub fn unzip_first_entry(zip: &[u8], limit: usize) -> Option> { + if zip.len() < 30 || read_u32(zip, 0)? != 0x0403_4b50 { + return None; + } + let flags = read_u16(zip, 6)?; + let method = read_u16(zip, 8)?; + let comp_size = read_u32(zip, 18)? as usize; + let uncomp_size = read_u32(zip, 22)? as usize; + let name_len = read_u16(zip, 26)? as usize; + let extra_len = read_u16(zip, 28)? as usize; + + if (flags & 0x08) != 0 { + return None; + } + + let data_off = 30usize.checked_add(name_len)?.checked_add(extra_len)?; + if data_off.checked_add(comp_size)? > zip.len() { + return None; + } + if uncomp_size > limit { + return None; + } + let data = &zip[data_off..data_off + comp_size]; + + let out = match method { + 0 => data.to_vec(), + 8 => { + let mut out = Vec::with_capacity(uncomp_size); + DeflateDecoder::new(data) + .take(uncomp_size as u64 + 1) + .read_to_end(&mut out) + .ok()?; + out + } + _ => return None, + }; + (out.len() == uncomp_size).then_some(out) +} + +/// Gunzip; pass through already-inflated bytes (edge caches may decompress). Gzip data that does +/// not decode, or decodes to more than `limit` bytes, is refused. +pub fn maybe_gunzip(body: Vec, limit: usize) -> Option> { + if body.len() < 2 || body[0] != 0x1f || body[1] != 0x8b { + return (body.len() <= limit).then_some(body); + } + let mut out = Vec::new(); + GzDecoder::new(&body[..]) + .take(limit as u64 + 1) + .read_to_end(&mut out) + .ok()?; + (!out.is_empty() && out.len() <= limit).then_some(out) +} + +pub fn hex_encode(bytes: &[u8]) -> String { + crate::gog::to_hex(bytes) +} + +fn preferred_host(server: &CContentServerDirectoryServerInfo) -> Option<&str> { + if !server.vhost.is_empty() { + Some(&server.vhost) + } else if !server.host.is_empty() { + Some(&server.host) + } else { + None + } +} + +fn read_u16(buf: &[u8], off: usize) -> Option { + Some(u16::from_le_bytes(buf.get(off..off + 2)?.try_into().ok()?)) +} + +fn read_u32(buf: &[u8], off: usize) -> Option { + Some(u32::from_le_bytes(buf.get(off..off + 4)?.try_into().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use flate2::{write::DeflateEncoder, Compression}; + use std::io::Write; + + #[test] + fn extracts_stored_zip_entry() { + let zip = zip_with_entry(0, b"manifest bytes"); + assert_eq!(unzip_first_entry(&zip, 64), Some(b"manifest bytes".to_vec())); + } + + #[test] + fn extracts_deflated_zip_entry() { + let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(b"manifest bytes").unwrap(); + let deflated = encoder.finish().unwrap(); + let zip = zip_with_compressed_entry(8, &deflated, b"manifest bytes".len() as u32); + assert_eq!(unzip_first_entry(&zip, 64), Some(b"manifest bytes".to_vec())); + } + + #[test] + fn rejects_data_descriptor_zip_entry() { + let mut zip = zip_with_entry(0, b"x"); + zip[6] = 0x08; + assert_eq!(unzip_first_entry(&zip, 64), None); + } + + #[test] + fn hex_encodes_lowercase() { + assert_eq!(hex_encode(&[0, 1, 0xab, 0xff]), "0001abff"); + } + + #[test] + fn builds_http_appinfo_url() { + assert_eq!( + build_appinfo_url("cache1.steamcontent.com", 601150, &[0xab, 0xcd, 0x01]), + "http://cache1.steamcontent.com/appinfo/601150/sha/abcd01.txt.gz" + ); + } + + #[test] + fn gunzips_gzip_and_passes_through_plain_vdf() { + use flate2::write::GzEncoder; + let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(b"\"appinfo\"{}").unwrap(); + let gz = encoder.finish().unwrap(); + assert_eq!(maybe_gunzip(gz.clone(), 64).unwrap(), b"\"appinfo\"{}"); + assert_eq!(maybe_gunzip(b"\"appinfo\"{}".to_vec(), 64).unwrap(), b"\"appinfo\"{}"); + assert_eq!(maybe_gunzip(gz, 4), None); + assert_eq!(maybe_gunzip(vec![0x1f, 0x8b, 0, 0], 64), None); + } + + #[test] + fn refuses_zip_entries_over_the_limit_or_their_declared_size() { + let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(&[7u8; 4096]).unwrap(); + let deflated = encoder.finish().unwrap(); + assert!(unzip_first_entry(&zip_with_compressed_entry(8, &deflated, 4096), 4096).is_some()); + assert_eq!(unzip_first_entry(&zip_with_compressed_entry(8, &deflated, 4096), 4095), None); + assert_eq!(unzip_first_entry(&zip_with_compressed_entry(8, &deflated, 16), 4096), None); + } + + #[test] + fn builds_manifest_and_chunk_urls() { + let server = CContentServerDirectoryServerInfo { + host: "edge.steamcontent.com".into(), + vhost: "cdn.example".into(), + https_support: "mandatory".into(), + ..Default::default() + }; + assert_eq!( + build_manifest_url(&server, 100, 200, 300).unwrap(), + "https://cdn.example:443/depot/100/manifest/200/5/300" + ); + assert_eq!( + build_chunk_url(&server, 100, &[0xab, 0xcd]).unwrap(), + "https://cdn.example:443/depot/100/chunk/abcd" + ); + let plain = CContentServerDirectoryServerInfo { + host: "cache1.example".into(), + ..Default::default() + }; + assert_eq!( + build_manifest_url(&plain, 1, 2, 0).unwrap(), + "http://cache1.example:80/depot/1/manifest/2/5" + ); + } + + #[test] + fn usable_servers_drop_china_empty_and_duplicate_hosts() { + let server = |host: &str, vhost: &str, china: bool| CContentServerDirectoryServerInfo { + host: host.into(), + vhost: vhost.into(), + steam_china_only: china, + ..Default::default() + }; + let list = usable_servers(&[ + server("a", "", false), + server("b", "", true), + server("", "", false), + server("c", "a", false), + server("d", "", false), + ]); + let hosts: Vec<_> = list.iter().map(host_key).collect(); + assert_eq!(hosts, vec!["a", "d"]); + let many: Vec<_> = (0..20) + .map(|i| server(&format!("h{i}"), "", false)) + .collect(); + assert_eq!(usable_servers(&many).len(), MAX_CDN_HOSTS); + } + + #[test] + fn validates_http_status_lengths_and_manifest_zip() { + let zip = zip_with_entry(0, b"manifest bytes"); + let ok = validate_manifest_response(200, zip.clone(), Some(zip.len() as u64)); + assert!(ok.ok()); + assert_eq!(ok.raw_manifest, b"manifest bytes"); + let short = validate_manifest_response(200, zip, Some(999)); + assert_eq!(short.error, "manifest body truncated (length mismatch)"); + assert_eq!( + validate_manifest_response(404, vec![], None).error, + "HTTP status 404" + ); + } + + fn zip_with_entry(method: u16, data: &[u8]) -> Vec { + zip_with_compressed_entry(method, data, data.len() as u32) + } + + fn zip_with_compressed_entry(method: u16, data: &[u8], uncomp_size: u32) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + out.extend_from_slice(&20u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&method.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(&uncomp_size.to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(b"x"); + out.extend_from_slice(data); + out + } +} diff --git a/app/src/main/rust/stores/src/steam/cm_client.rs b/app/src/main/rust/stores/src/steam/cm_client.rs new file mode 100644 index 0000000000..e49c6f2833 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/cm_client.rs @@ -0,0 +1,873 @@ +//! CM session state and message builders: logon with a refresh token, heartbeat, log-off, and the +//! requests a download store needs (PICS, depot keys, manifest request codes, CDN server list, +//! free licenses). Social, stats, cloud, lobby and ticket messages are not part of this port. + +use crate::steam::cmsg_protobuf_header::{CMsgProtoBufHeader, INVALID_JOB_ID}; +use crate::steam::crypto::generate_session_key; +use crate::steam::emsg::EMsg; +use crate::steam::job_manager::JobResult; +use crate::steam::pb::ccontentserverdirectory::{ + CContentServerDirectoryGetManifestRequestCodeRequest, + CContentServerDirectoryGetServersForSteamPipeRequest, +}; +use crate::steam::pb::cmsg_client_get_depot_decryption_key::CMsgClientGetDepotDecryptionKey; +use crate::steam::pb::cmsg_client_license_list::{CMsgClientLicenseList, License}; +use crate::steam::pb::cmsg_client_pics::{ + CMsgClientPICSAccessTokenRequest, CMsgClientPICSProductInfoRequest, PicsAppInfoReq, + PicsPackageInfoReq, +}; +use crate::steam::pb::cmsg_client_request_free_license::CMsgClientRequestFreeLicense; +use crate::steam::pb::cmsg_clientserver_login::{ + CMsgClientHeartBeat, CMsgClientHello, CMsgClientLogOff, CMsgClientLogon, + CMsgClientLogonResponse, +}; +use crate::steam::proto_envelope::encode_proto_envelope; +use flate2::read::{GzDecoder, ZlibDecoder}; +use std::io::Read; +use std::sync::atomic::{AtomicI32, AtomicU32, AtomicU64, AtomicU8, Ordering}; +use std::sync::Mutex; + +/// Sent as `machine_id` in the logon. +pub const MACHINE_ID: &[u8] = b"DroidDeck-Steam"; +const LOGON_PROTOCOL_VERSION: u32 = 65580; +const LOGON_CLIENT_OS_TYPE: u32 = 16; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum ClientState { + Disconnected, + Connecting, + Connected, + LoggedOn, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum InboundAction { + DeliverJob(JobResult), + Multi, + PicsProductInfo, + LogonOk, + LoggedOff, + LicenseList(usize), + ClientMessage, + Ignored, + ParseFailed(&'static str), +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CMsgMultiBody { + pub size_unzipped: u32, + pub message_body: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct OutboundProtoMessage { + pub emsg: EMsg, + pub routing_appid: u32, + pub body: Vec, + pub wire: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct OutboundServiceCall { + pub method_name: String, + pub authed: bool, + pub job_id: u64, + pub request_body: Vec, + pub wire: Vec, +} + +pub struct CMClientCore { + state: AtomicU8, + steam_id: AtomicU64, + session_id: AtomicI32, + cell_id: AtomicU32, + /// EResult of the last logon response or log-off (0 = none yet). + last_logon_eresult: AtomicI32, + license_list: Mutex>>, + outbound_wires: Mutex>>, +} + +impl Default for CMClientCore { + fn default() -> Self { + Self { + state: AtomicU8::new(ClientState::Disconnected as u8), + steam_id: AtomicU64::new(0), + session_id: AtomicI32::new(0), + cell_id: AtomicU32::new(0), + last_logon_eresult: AtomicI32::new(0), + license_list: Mutex::new(None), + outbound_wires: Mutex::new(Vec::new()), + } + } +} + +impl CMClientCore { + pub fn state(&self) -> ClientState { + match self.state.load(Ordering::Relaxed) { + 1 => ClientState::Connecting, + 2 => ClientState::Connected, + 3 => ClientState::LoggedOn, + _ => ClientState::Disconnected, + } + } + + pub fn set_state(&self, state: ClientState) { + self.state.store(state as u8, Ordering::Relaxed); + } + + pub fn reset_session_identity(&self) { + self.steam_id.store(0, Ordering::Relaxed); + self.session_id.store(0, Ordering::Relaxed); + // Unsent wires can hold the logon token. + let mut queue = self.outbound_wires.lock().expect("outbound queue poisoned"); + for wire in queue.iter_mut() { + zeroize::Zeroize::zeroize(wire); + } + queue.clear(); + } + + pub fn steam_id(&self) -> u64 { + self.steam_id.load(Ordering::Relaxed) + } + + pub fn session_id(&self) -> i32 { + self.session_id.load(Ordering::Relaxed) + } + + pub fn cell_id(&self) -> u32 { + self.cell_id.load(Ordering::Relaxed) + } + + pub fn last_logon_eresult(&self) -> i32 { + self.last_logon_eresult.load(Ordering::Acquire) + } + + pub fn clear_last_logon_eresult(&self) { + self.last_logon_eresult.store(0, Ordering::Relaxed); + } + + /// The license list Steam pushed after logon; `None` until it arrived. + pub fn license_list(&self) -> Option> { + self.license_list + .lock() + .expect("license list poisoned") + .clone() + } + + pub fn enqueue_proto_message(&self, message: Option) -> bool { + let Some(message) = message else { + return false; + }; + self.enqueue_wire(message.wire) + } + + pub fn enqueue_wire(&self, wire: Vec) -> bool { + if wire.is_empty() { + return false; + } + self.outbound_wires + .lock() + .expect("outbound queue poisoned") + .push(wire); + true + } + + pub fn restore_outbound_wires_front(&self, mut wires: Vec>) { + if wires.is_empty() { + return; + } + let mut queue = self.outbound_wires.lock().expect("outbound queue poisoned"); + if queue.is_empty() { + *queue = wires; + return; + } + let mut restored = Vec::with_capacity(wires.len() + queue.len()); + restored.append(&mut wires); + restored.append(&mut queue); + *queue = restored; + } + + pub fn take_outbound_wires(&self) -> Vec> { + std::mem::take(&mut *self.outbound_wires.lock().expect("outbound queue poisoned")) + } + + pub fn build_proto_message(&self, emsg: EMsg, body: &[u8], routing_appid: u32) -> Vec { + let mut header = CMsgProtoBufHeader { + steamid: self.steam_id(), + client_sessionid: self.session_id(), + routing_appid, + ..Default::default() + }; + if emsg == EMsg::CLIENT_LOGON && header.steamid == 0 { + header.steamid = 0x0110_0001_0000_0000; + } + encode_proto_envelope(emsg, &header, body) + } + + pub fn build_client_hello(&self) -> OutboundProtoMessage { + let body = CMsgClientHello::default().serialize(); + let wire = self.build_proto_message(EMsg::CLIENT_HELLO, &body, 0); + OutboundProtoMessage { + emsg: EMsg::CLIENT_HELLO, + routing_appid: 0, + body, + wire, + } + } + + pub fn build_heartbeat(&self) -> OutboundProtoMessage { + let body = CMsgClientHeartBeat::default().serialize(); + let wire = self.build_proto_message(EMsg::CLIENT_HEART_BEAT, &body, 0); + OutboundProtoMessage { + emsg: EMsg::CLIENT_HEART_BEAT, + routing_appid: 0, + body, + wire, + } + } + + pub fn build_logoff(&self) -> Option { + if self.state() != ClientState::LoggedOn { + return None; + } + self.build_outbound_proto_message(EMsg::CLIENT_LOG_OFF, CMsgClientLogOff.serialize(), 0) + } + + /// `ClientLogon` carrying the saved refresh token as `access_token`. The returned wire holds + /// the token; drop it as soon as it is queued. + pub fn build_logon_with_refresh_token( + &self, + refresh_token: &str, + account_name: &str, + client_supplied_steam_id: u64, + ) -> Option { + if self.state() != ClientState::Connected || refresh_token.is_empty() { + return None; + } + let mut msg = CMsgClientLogon { + access_token: refresh_token.to_string(), + account_name: account_name.to_string(), + client_supplied_steam_id, + machine_id: MACHINE_ID.to_vec(), + protocol_version: LOGON_PROTOCOL_VERSION, + client_os_type: LOGON_CLIENT_OS_TYPE, + supports_rate_limit_response: true, + ..Default::default() + }; + if let Some(key) = generate_session_key() { + let mut client_instance_id = 0u64; + for (idx, byte) in key.bytes.iter().take(8).enumerate() { + client_instance_id |= (*byte as u64) << (idx * 8); + } + msg.client_instance_id = client_instance_id.max(1); + let mut login_id = 0u32; + for (idx, byte) in key.bytes.iter().skip(8).take(4).enumerate() { + login_id |= (*byte as u32) << (idx * 8); + } + msg.obfuscated_private_ip = login_id.max(1); + } + let body = msg.serialize(); + zeroize::Zeroize::zeroize(&mut msg.access_token); + let wire = self.build_proto_message(EMsg::CLIENT_LOGON, &body, 0); + let mut body = body; + zeroize::Zeroize::zeroize(&mut body); + Some(OutboundProtoMessage { + emsg: EMsg::CLIENT_LOGON, + routing_appid: 0, + body: Vec::new(), + wire, + }) + } + + pub fn build_service_method_call( + &self, + method_name: &str, + authed: bool, + job_id: u64, + request_body: &[u8], + ) -> Vec { + let header = CMsgProtoBufHeader { + steamid: self.steam_id(), + client_sessionid: self.session_id(), + jobid_source: job_id, + jobid_target: INVALID_JOB_ID, + target_job_name: method_name.to_string(), + ..Default::default() + }; + let emsg = if authed { + EMsg::SERVICE_METHOD_CALL_FROM_CLIENT + } else { + EMsg::SERVICE_METHOD_CALL_FROM_CLIENT_NON_AUTHED + }; + encode_proto_envelope(emsg, &header, request_body) + } + + pub fn build_outbound_proto_message( + &self, + emsg: EMsg, + body: Vec, + routing_appid: u32, + ) -> Option { + if self.state() != ClientState::LoggedOn { + return None; + } + let wire = self.build_proto_message(emsg, &body, routing_appid); + Some(OutboundProtoMessage { + emsg, + routing_appid, + body, + wire, + }) + } + + pub fn build_job_proto_message( + &self, + emsg: EMsg, + job_id: u64, + body: Vec, + routing_appid: u32, + ) -> Option { + if self.state() != ClientState::LoggedOn { + return None; + } + let header = CMsgProtoBufHeader { + steamid: self.steam_id(), + client_sessionid: self.session_id(), + routing_appid, + jobid_source: job_id, + jobid_target: INVALID_JOB_ID, + ..Default::default() + }; + let wire = encode_proto_envelope(emsg, &header, &body); + Some(OutboundProtoMessage { + emsg, + routing_appid, + body, + wire, + }) + } + + pub fn build_authed_service_call( + &self, + method_name: &str, + job_id: u64, + request_body: Vec, + ) -> Option { + if self.state() != ClientState::LoggedOn { + return None; + } + let wire = self.build_service_method_call(method_name, true, job_id, &request_body); + Some(OutboundServiceCall { + method_name: method_name.to_string(), + authed: true, + job_id, + request_body, + wire, + }) + } + + pub fn build_get_depot_decryption_key( + &self, + depot_id: u32, + app_id: u32, + job_id: u64, + ) -> Option { + if depot_id == 0 || app_id == 0 { + return None; + } + self.build_job_proto_message( + EMsg::CLIENT_GET_DEPOT_DECRYPTION_KEY, + job_id, + CMsgClientGetDepotDecryptionKey { depot_id, app_id }.serialize(), + 0, + ) + } + + pub fn build_manifest_request_code_call( + &self, + app_id: u32, + depot_id: u32, + manifest_id: u64, + branch: &str, + job_id: u64, + ) -> Option { + if app_id == 0 || depot_id == 0 || manifest_id == 0 { + return None; + } + let lower = branch.to_ascii_lowercase(); + let app_branch = if lower.is_empty() || lower == "public" { + String::new() + } else { + branch.to_string() + }; + self.build_authed_service_call( + "ContentServerDirectory.GetManifestRequestCode#1", + job_id, + CContentServerDirectoryGetManifestRequestCodeRequest { + app_id, + depot_id, + manifest_id, + app_branch, + branch_password_hash: String::new(), + } + .serialize(), + ) + } + + pub fn build_get_cdn_servers_call( + &self, + cell_id: u32, + job_id: u64, + ) -> Option { + self.build_authed_service_call( + "ContentServerDirectory.GetServersForSteamPipe#1", + job_id, + CContentServerDirectoryGetServersForSteamPipeRequest { + cell_id, + ..Default::default() + } + .serialize(), + ) + } + + pub fn build_pics_access_tokens( + &self, + packageids: Vec, + appids: Vec, + job_id: u64, + ) -> Option { + self.build_job_proto_message( + EMsg::CLIENT_PICS_ACCESS_TOKEN_REQUEST, + job_id, + CMsgClientPICSAccessTokenRequest { packageids, appids }.serialize(), + 0, + ) + } + + pub fn build_pics_product_info( + &self, + packages: Vec, + apps: Vec, + meta_data_only: bool, + job_id: u64, + ) -> Option { + self.build_job_proto_message( + EMsg::CLIENT_PICS_PRODUCT_INFO_REQUEST, + job_id, + CMsgClientPICSProductInfoRequest { + packages, + apps, + meta_data_only, + single_response: false, + ..Default::default() + } + .serialize(), + 0, + ) + } + + /// Succeeds only for apps Steam gives away; a paid unowned app comes back with a non-OK + /// EResult in the response body. + pub fn build_request_free_license( + &self, + app_ids: &[u32], + job_id: u64, + ) -> Option { + if app_ids.is_empty() { + return None; + } + self.build_job_proto_message( + EMsg::CLIENT_REQUEST_FREE_LICENSE, + job_id, + CMsgClientRequestFreeLicense { + appids: app_ids.to_vec(), + } + .serialize(), + 0, + ) + } + + pub fn route_inbound( + &self, + emsg: EMsg, + header: &CMsgProtoBufHeader, + body: &[u8], + ) -> InboundAction { + match emsg { + EMsg::SERVICE_METHOD_RESPONSE + | EMsg::CLIENT_PICS_ACCESS_TOKEN_RESPONSE + | EMsg::CLIENT_GET_DEPOT_DECRYPTION_KEY_RESPONSE + // 5573 carries its own EResult in the body; the job only reports transport health. + | EMsg::CLIENT_REQUEST_FREE_LICENSE_RESPONSE => { + if header.jobid_target == INVALID_JOB_ID { + InboundAction::Ignored + } else { + let eresult = if header.eresult == -1 { + 1 + } else { + header.eresult + }; + InboundAction::DeliverJob(JobResult { + eresult, + error_message: header.error_message.clone(), + body: body.to_vec(), + synthetic_failure: false, + }) + } + } + EMsg::CLIENT_PICS_PRODUCT_INFO_RESPONSE => InboundAction::PicsProductInfo, + EMsg::MULTI => InboundAction::Multi, + EMsg::CLIENT_LOGON_RESPONSE => { + let Some(resp) = CMsgClientLogonResponse::deserialize(body) else { + return InboundAction::ParseFailed("ClientLogonResponse"); + }; + // The eresult is published last (Release) so a waiter that sees it also sees the + // state and ids that go with it. + let action = if resp.eresult == 1 { + self.state + .store(ClientState::LoggedOn as u8, Ordering::Relaxed); + self.steam_id + .store(resp.client_supplied_steamid, Ordering::Relaxed); + self.session_id + .store(header.client_sessionid, Ordering::Relaxed); + self.cell_id.store(resp.cell_id, Ordering::Relaxed); + InboundAction::LogonOk + } else { + InboundAction::LoggedOff + }; + self.last_logon_eresult + .store(resp.eresult, Ordering::Release); + action + } + EMsg::CLIENT_LOGGED_OFF | EMsg::CLIENT_SERVER_UNAVAILABLE => { + if self.state() == ClientState::LoggedOn { + self.state + .store(ClientState::Connected as u8, Ordering::Relaxed); + } + if emsg == EMsg::CLIENT_LOGGED_OFF { + let eresult = crate::steam::pb::cmsg_clientserver_login::CMsgClientLoggedOff::deserialize(body) + .map(|m| m.eresult) + .unwrap_or(2); + self.last_logon_eresult.store(eresult, Ordering::Relaxed); + } + self.steam_id.store(0, Ordering::Relaxed); + self.session_id.store(0, Ordering::Relaxed); + InboundAction::LoggedOff + } + EMsg::CLIENT_LICENSE_LIST => { + let Some(msg) = CMsgClientLicenseList::deserialize(body) else { + return InboundAction::ParseFailed("ClientLicenseList"); + }; + let count = msg.licenses.len(); + // A refused list keeps the last good snapshot (or none, so the load reports it). + if msg.eresult != 1 && msg.licenses.is_empty() { + return InboundAction::ParseFailed("ClientLicenseList refused"); + } + *self.license_list.lock().expect("license list poisoned") = Some(msg.licenses); + InboundAction::LicenseList(count) + } + _ => InboundAction::ClientMessage, + } + } +} + +pub fn parse_cmsg_multi(body: &[u8]) -> Option { + let mut reader = crate::steam::proto_wire::Reader::new(body); + let mut multi = CMsgMultiBody::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(multi); + }; + match tag.field_number { + 1 => multi.size_unzipped = reader.u32()?, + 2 => multi.message_body = reader.bytes()?.to_vec(), + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(multi) +} + +pub fn decode_multi_records(body: &[u8]) -> Option>> { + let multi = parse_cmsg_multi(body)?; + let records = if multi.size_unzipped > 0 { + gunzip_or_zlib(&multi.message_body, multi.size_unzipped as usize)? + } else { + multi.message_body + }; + + let mut out = Vec::new(); + let mut offset = 0usize; + while offset + 4 <= records.len() { + let inner_len = crate::steam::wire_format::read_u32_le(&records[offset..]) as usize; + offset += 4; + if inner_len == 0 || offset + inner_len > records.len() { + return None; + } + out.push(records[offset..offset + inner_len].to_vec()); + offset += inner_len; + } + (offset == records.len()).then_some(out) +} + +/// Largest MULTI batch accepted once decompressed. +const MAX_MULTI_UNZIPPED: usize = 64 << 20; + +fn gunzip_or_zlib(compressed: &[u8], expected_size: usize) -> Option> { + if expected_size == 0 || expected_size > MAX_MULTI_UNZIPPED { + return None; + } + let limit = expected_size as u64 + 1; + let mut out = Vec::with_capacity(expected_size); + if GzDecoder::new(compressed).take(limit).read_to_end(&mut out).is_ok() && out.len() == expected_size { + return Some(out); + } + out.clear(); + if ZlibDecoder::new(compressed).take(limit).read_to_end(&mut out).is_ok() && out.len() == expected_size { + return Some(out); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::proto_envelope::decode_proto_envelope; + use crate::steam::proto_wire::{WireType, Writer}; + use flate2::write::GzEncoder; + use flate2::Compression; + use std::io::Write; + + #[test] + fn service_method_call_sets_authed_and_non_authed_emsgs() { + let core = CMClientCore::default(); + core.steam_id.store(123, Ordering::Relaxed); + core.session_id.store(7, Ordering::Relaxed); + let authed = decode_proto_envelope(&core.build_service_method_call( + "ContentServerDirectory.GetServersForSteamPipe#1", + true, + 55, + b"req", + )) + .unwrap(); + assert_eq!(authed.emsg, EMsg::SERVICE_METHOD_CALL_FROM_CLIENT); + assert_eq!(authed.header.steamid, 123); + assert_eq!(authed.header.client_sessionid, 7); + assert_eq!(authed.header.jobid_source, 55); + assert_eq!(authed.body, b"req"); + let non = decode_proto_envelope(&core.build_service_method_call("X.Y#1", false, 56, b"")) + .unwrap(); + assert_eq!(non.emsg, EMsg::SERVICE_METHOD_CALL_FROM_CLIENT_NON_AUTHED); + } + + #[test] + fn cmsg_multi_decodes_plain_and_gzip_records() { + let first = encode_proto_envelope(EMsg::CLIENT_HELLO, &CMsgProtoBufHeader::default(), b"a"); + let second = encode_proto_envelope( + EMsg::CLIENT_LICENSE_LIST, + &CMsgProtoBufHeader::default(), + b"b", + ); + let mut records = Vec::new(); + records.extend_from_slice(&(first.len() as u32).to_le_bytes()); + records.extend_from_slice(&first); + records.extend_from_slice(&(second.len() as u32).to_le_bytes()); + records.extend_from_slice(&second); + + let mut body = Vec::new(); + Writer::new(&mut body).bytes_field(2, &records); + assert_eq!( + decode_multi_records(&body).unwrap(), + vec![first.clone(), second.clone()] + ); + + let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(&records).unwrap(); + let zipped = encoder.finish().unwrap(); + let mut zipped_body = Vec::new(); + { + let mut writer = Writer::new(&mut zipped_body); + writer.uint32_field(1, records.len() as u32); + writer.bytes_field(2, &zipped); + } + assert_eq!( + decode_multi_records(&zipped_body).unwrap(), + vec![first, second] + ); + } + + #[test] + fn logon_needs_connected_state_and_carries_token_and_machine_id() { + let core = CMClientCore::default(); + assert!(core + .build_logon_with_refresh_token("refresh", "ada", 0) + .is_none()); + core.set_state(ClientState::Connected); + let logon = core + .build_logon_with_refresh_token("refresh", "ada", 123) + .unwrap(); + assert_eq!(logon.emsg, EMsg::CLIENT_LOGON); + let decoded = decode_proto_envelope(&logon.wire).unwrap(); + assert_eq!(decoded.header.steamid, 0x0110_0001_0000_0000); + assert!(decoded.body.windows(7).any(|w| w == b"refresh")); + assert!(decoded + .body + .windows(MACHINE_ID.len()) + .any(|w| w == MACHINE_ID)); + assert!(logon.body.is_empty()); + assert!(core.build_logon_with_refresh_token("", "ada", 1).is_none()); + + assert!(core.build_logoff().is_none()); + core.set_state(ClientState::LoggedOn); + assert_eq!(core.build_logoff().unwrap().emsg, EMsg::CLIENT_LOG_OFF); + } + + #[test] + fn logon_response_updates_session_identity_and_eresult() { + let core = CMClientCore::default(); + let mut body = Vec::new(); + { + let mut w = Writer::new(&mut body); + w.int32_field(1, 1); + w.tag(20, WireType::Fixed64); + w.raw_bytes(&765u64.to_le_bytes()); + } + let header = CMsgProtoBufHeader { + client_sessionid: 42, + ..Default::default() + }; + assert_eq!( + core.route_inbound(EMsg::CLIENT_LOGON_RESPONSE, &header, &body), + InboundAction::LogonOk + ); + assert_eq!(core.state(), ClientState::LoggedOn); + assert_eq!(core.steam_id(), 765); + assert_eq!(core.session_id(), 42); + assert_eq!(core.last_logon_eresult(), 1); + + assert_eq!( + core.route_inbound(EMsg::CLIENT_LOGGED_OFF, &CMsgProtoBufHeader::default(), &[]), + InboundAction::LoggedOff + ); + assert_eq!(core.state(), ClientState::Connected); + assert_eq!(core.steam_id(), 0); + + let mut refused = Vec::new(); + Writer::new(&mut refused).int32_field(1, 5); + let fresh = CMClientCore::default(); + assert_eq!( + fresh.route_inbound(EMsg::CLIENT_LOGON_RESPONSE, &header, &refused), + InboundAction::LoggedOff + ); + assert_eq!(fresh.last_logon_eresult(), 5); + assert_eq!(fresh.state(), ClientState::Disconnected); + } + + #[test] + fn license_list_push_is_stored() { + let core = CMClientCore::default(); + assert!(core.license_list().is_none()); + let mut refused = Vec::new(); + Writer::new(&mut refused).int32_field(1, 2); + assert!(matches!( + core.route_inbound(EMsg::CLIENT_LICENSE_LIST, &CMsgProtoBufHeader::default(), &refused), + InboundAction::ParseFailed(_) + )); + assert!(core.license_list().is_none()); + let mut ok = Vec::new(); + Writer::new(&mut ok).int32_field(1, 1); + assert_eq!( + core.route_inbound(EMsg::CLIENT_LICENSE_LIST, &CMsgProtoBufHeader::default(), &ok), + InboundAction::LicenseList(0) + ); + assert_eq!(core.license_list(), Some(Vec::new())); + } + + #[test] + fn downloader_builders_use_the_expected_messages() { + let core = logged_on_core(); + let depot_key = core.build_get_depot_decryption_key(11, 22, 33).unwrap(); + let decoded = decode_proto_envelope(&depot_key.wire).unwrap(); + assert_eq!(decoded.emsg, EMsg::CLIENT_GET_DEPOT_DECRYPTION_KEY); + assert_eq!(decoded.header.jobid_source, 33); + + let public = core + .build_manifest_request_code_call(480, 100, 555, "public", 44) + .unwrap(); + assert_eq!( + public.method_name, + "ContentServerDirectory.GetManifestRequestCode#1" + ); + assert!(!public.request_body.windows(6).any(|w| w == b"public")); + let beta = core + .build_manifest_request_code_call(480, 100, 555, "Beta", 45) + .unwrap(); + assert!(beta.request_body.windows(4).any(|w| w == b"Beta")); + + let servers = core.build_get_cdn_servers_call(7, 46).unwrap(); + assert_eq!( + servers.method_name, + "ContentServerDirectory.GetServersForSteamPipe#1" + ); + + let product = core + .build_pics_product_info( + vec![PicsPackageInfoReq { + packageid: 100, + access_token: 7, + }], + vec![PicsAppInfoReq { + appid: 480, + access_token: 8, + only_public_obsolete: false, + }], + true, + 3, + ) + .unwrap(); + assert_eq!(product.emsg, EMsg::CLIENT_PICS_PRODUCT_INFO_REQUEST); + assert!(product.body.windows(2).any(|w| w == [0x18, 1])); + + let free = core.build_request_free_license(&[440], 50).unwrap(); + assert_eq!(free.emsg, EMsg::CLIENT_REQUEST_FREE_LICENSE); + assert_eq!(free.body, [0x10, 0xb8, 0x03]); + assert!(core.build_request_free_license(&[], 51).is_none()); + } + + #[test] + fn job_responses_are_delivered_and_builders_need_logon() { + let core = logged_on_core(); + let header = CMsgProtoBufHeader { + jobid_target: 50, + ..Default::default() + }; + assert!(matches!( + core.route_inbound(EMsg::CLIENT_REQUEST_FREE_LICENSE_RESPONSE, &header, &[]), + InboundAction::DeliverJob(_) + )); + assert_eq!( + core.route_inbound( + EMsg::SERVICE_METHOD_RESPONSE, + &CMsgProtoBufHeader::default(), + &[] + ), + InboundAction::Ignored + ); + let offline = CMClientCore::default(); + assert!(offline.build_get_depot_decryption_key(1, 2, 3).is_none()); + assert!(offline.build_get_cdn_servers_call(0, 1).is_none()); + } + + fn logged_on_core() -> CMClientCore { + let core = CMClientCore::default(); + core.state + .store(ClientState::LoggedOn as u8, Ordering::Relaxed); + core.steam_id.store(7656119, Ordering::Relaxed); + core.session_id.store(42, Ordering::Relaxed); + core + } +} diff --git a/app/src/main/rust/stores/src/steam/cm_runtime.rs b/app/src/main/rust/stores/src/steam/cm_runtime.rs new file mode 100644 index 0000000000..cfe8663f72 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/cm_runtime.rs @@ -0,0 +1,594 @@ +use crate::steam::cm_client::{decode_multi_records, CMClientCore, ClientState, InboundAction}; +use crate::steam::cmsg_protobuf_header::{CMsgProtoBufHeader, INVALID_JOB_ID}; +use crate::steam::emsg::{has_proto_flag, strip_proto_flag, EMsg}; +use crate::steam::encrypted_channel::{ChannelDisconnectReason, ChannelState, EncryptedChannel}; +use crate::steam::heartbeat::Heartbeat; +use crate::steam::job_manager::{JobManager, JobResult}; +use crate::steam::pb::cmsg_client_pics::CMsgClientPICSProductInfoResponse; +use crate::steam::pb::cmsg_clientserver_login::CMsgClientLogonResponse; +use crate::steam::proto_envelope::decode_proto_envelope; +use crate::steam::transport::Transport; +use crate::steam::wire_format::read_u32_le; +use std::collections::HashMap; +use std::panic::{self, AssertUnwindSafe}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use zeroize::Zeroize; + +type StateCallback = Box; +type ClientMessageCallback = Box; + +/// MULTI batches nest at most this deep (Steam sends one level). +const MAX_MULTI_DEPTH: u32 = 2; + +pub struct CMClientRuntime { + flush: Mutex<()>, + core: Arc, + channel: EncryptedChannel, + jobs: JobManager, + heartbeat: Mutex, + pics_product_info: Mutex>, + on_state: Mutex>, + on_client_message: Mutex>, +} + +impl CMClientRuntime { + pub fn new(core: Arc, transport: Box) -> Arc { + let runtime = Arc::new(Self { + flush: Mutex::new(()), + core, + channel: EncryptedChannel::new(transport), + jobs: JobManager::default(), + heartbeat: Mutex::new(Heartbeat::default()), + pics_product_info: Mutex::new(HashMap::new()), + on_state: Mutex::new(None), + on_client_message: Mutex::new(None), + }); + + let weak = Arc::downgrade(&runtime); + runtime.channel.set_on_connected(move || { + if let Some(runtime) = weak.upgrade() { + runtime.on_channel_connected(); + } + }); + + let weak = Arc::downgrade(&runtime); + runtime.channel.set_on_disconnected(move |reason, detail| { + if let Some(runtime) = weak.upgrade() { + runtime.on_channel_disconnected(reason, detail); + } + }); + + let weak = Arc::downgrade(&runtime); + runtime.channel.set_on_message(move |bytes| { + if let Some(runtime) = weak.upgrade() { + runtime.handle_channel_message(bytes); + } + }); + + runtime + } + + pub fn core(&self) -> &Arc { + &self.core + } + + pub fn connect(&self, url: &str) -> bool { + self.core.set_state(ClientState::Connecting); + self.notify_state(ClientState::Connecting); + if self.channel.connect(url) { + true + } else { + self.core.set_state(ClientState::Disconnected); + self.notify_state(ClientState::Disconnected); + false + } + } + + pub fn disconnect(&self) { + self.heartbeat.lock().expect("heartbeat poisoned").stop(); + self.channel.disconnect(); + self.jobs.fail_all("CMClient disconnected"); + self.core.reset_session_identity(); + self.core.set_state(ClientState::Disconnected); + self.notify_state(ClientState::Disconnected); + } + + pub fn set_ca_bundle_path(&self, path: &str) { + self.channel.set_ca_bundle_path(path); + } + + pub fn set_on_state(&self, callback: F) + where + F: Fn(ClientState) + Send + Sync + 'static, + { + *self.on_state.lock().expect("runtime callback poisoned") = Some(Box::new(callback)); + } + + pub fn set_on_client_message(&self, callback: F) + where + F: Fn(EMsg, &CMsgProtoBufHeader, &[u8]) + Send + Sync + 'static, + { + *self + .on_client_message + .lock() + .expect("runtime callback poisoned") = Some(Box::new(callback)); + } + + pub fn next_job_id(&self) -> u64 { + self.jobs.next_job_id() + } + + pub fn track_job(&self, job_id: u64, callback: F, timeout: Option) + where + F: FnOnce(JobResult) + Send + 'static, + { + self.jobs.track(job_id, callback, timeout); + } + + pub fn flush_outbound(&self) -> usize { + if self.channel.state() != ChannelState::Encrypted { + return 0; + } + // One flush at a time, so two flushers cannot send queued wires out of order. + let _flushing = self.flush.lock().expect("flush poisoned"); + let mut wires = self.core.take_outbound_wires(); + let mut sent = 0usize; + for idx in 0..wires.len() { + if self.channel.send(&wires[idx]) { + // Outbound wires can hold the logon token; clear each one once it is sent. + wires[idx].zeroize(); + sent += 1; + continue; + } + self.core.restore_outbound_wires_front(wires.split_off(idx)); + break; + } + sent + } + + pub fn handle_channel_message(self: &Arc, bytes: &[u8]) -> InboundAction { + self.handle_message_at(bytes, 0) + } + + fn handle_message_at(self: &Arc, bytes: &[u8], depth: u32) -> InboundAction { + let Some(envelope) = decode_proto_envelope(bytes) else { + return self.handle_non_proto_message(bytes); + }; + self.process_envelope(envelope.emsg, &envelope.header, &envelope.body, depth) + } + + fn process_envelope( + self: &Arc, + emsg: EMsg, + header: &CMsgProtoBufHeader, + body: &[u8], + depth: u32, + ) -> InboundAction { + let action = self.core.route_inbound(emsg, header, body); + match &action { + InboundAction::Multi => { + if depth >= MAX_MULTI_DEPTH { + return InboundAction::ParseFailed("MULTI nested too deep"); + } + if let Some(records) = decode_multi_records(body) { + for record in records { + self.handle_message_at(&record, depth + 1); + } + } + } + InboundAction::DeliverJob(result) => { + self.jobs.deliver( + header.jobid_target, + result.eresult, + result.error_message.clone(), + &result.body, + ); + } + InboundAction::LogonOk => { + // No persona or friends traffic: this session exists only to download. + self.start_heartbeat_from_logon(body); + self.notify_state(ClientState::LoggedOn); + self.notify_client_message(emsg, header, body); + } + InboundAction::LoggedOff => { + self.heartbeat.lock().expect("heartbeat poisoned").stop(); + self.notify_state(self.core.state()); + self.notify_client_message(emsg, header, body); + } + InboundAction::Ignored | InboundAction::ParseFailed(_) => {} + InboundAction::PicsProductInfo => self.handle_pics_product_info(header, body), + InboundAction::LicenseList(_) | InboundAction::ClientMessage => { + self.notify_client_message(emsg, header, body); + } + } + action + } + + fn on_channel_connected(self: &Arc) { + // Always send ClientHello first; pre-existing queued wires (e.g. a + // logon enqueued before the channel finished negotiating) must come + // after the Hello or Steam rejects the conversation as malformed. + // If a Hello was already prequeued, do not duplicate it. + let queued = self.core.take_outbound_wires(); + let head_is_hello = queued + .first() + .and_then(|wire| decode_proto_envelope(wire)) + .is_some_and(|env| env.emsg == EMsg::CLIENT_HELLO); + let combined = if head_is_hello { + queued + } else { + let hello = self.core.build_client_hello().wire; + let mut combined = Vec::with_capacity(queued.len() + 1); + combined.push(hello); + combined.extend(queued); + combined + }; + self.core.restore_outbound_wires_front(combined); + // Connected is published only once Hello heads the queue, so a logon queued by a waiter + // that wakes on it cannot get ahead of the Hello. + self.core.set_state(ClientState::Connected); + self.notify_state(ClientState::Connected); + self.flush_outbound(); + } + + fn on_channel_disconnected(self: &Arc, _reason: ChannelDisconnectReason, detail: &str) { + self.heartbeat.lock().expect("heartbeat poisoned").stop(); + self.jobs + .fail_all(&format!("channel disconnected: {detail}")); + self.pics_product_info + .lock() + .expect("pics product info poisoned") + .clear(); + self.core.reset_session_identity(); + self.core.set_state(ClientState::Disconnected); + self.notify_state(ClientState::Disconnected); + } + + fn handle_pics_product_info(&self, header: &CMsgProtoBufHeader, body: &[u8]) { + if header.jobid_target == INVALID_JOB_ID { + return; + } + let mut pending = self + .pics_product_info + .lock() + .expect("pics product info poisoned"); + // Fragments of jobs that timed out or failed are dropped, and a late one starts nothing. + pending.retain(|job, _| self.jobs.is_tracked(*job)); + let Some(response) = CMsgClientPICSProductInfoResponse::deserialize(body) else { + pending.remove(&header.jobid_target); + drop(pending); + // 0 (Invalid) is a failure to every caller; -1 would be delivered as success. + self.jobs.deliver( + header.jobid_target, + 0, + "PICS product-info parse failed".to_string(), + &[], + ); + return; + }; + if !self.jobs.is_tracked(header.jobid_target) { + return; + } + if response.response_pending { + let acc = pending.entry(header.jobid_target).or_default(); + merge_pics_product_info(acc, response); + return; + } + let mut merged = pending.remove(&header.jobid_target).unwrap_or_default(); + merge_pics_product_info(&mut merged, response); + let body = merged.serialize(); + self.jobs + .deliver(header.jobid_target, 1, String::new(), &body); + } + + fn start_heartbeat_from_logon(self: &Arc, body: &[u8]) { + let Some(resp) = CMsgClientLogonResponse::deserialize(body) else { + return; + }; + if resp.heartbeat_seconds <= 0 { + return; + } + let weak = Arc::downgrade(self); + let interval = Duration::from_secs(resp.heartbeat_seconds as u64); + self.heartbeat + .lock() + .expect("heartbeat poisoned") + .start(interval, move || { + if let Some(runtime) = weak.upgrade() { + runtime + .core + .enqueue_wire(runtime.core.build_heartbeat().wire); + runtime.flush_outbound(); + } + }); + } + + fn handle_non_proto_message(&self, bytes: &[u8]) -> InboundAction { + if bytes.len() >= 4 { + let raw = read_u32_le(bytes); + if !has_proto_flag(raw) { + let legacy = strip_proto_flag(raw); + if legacy == EMsg::CHANNEL_ENCRYPT_REQUEST + || legacy == EMsg::CHANNEL_ENCRYPT_RESPONSE + || legacy == EMsg::CHANNEL_ENCRYPT_RESULT + { + return InboundAction::Ignored; + } + } + } + InboundAction::ParseFailed("ProtoEnvelope") + } + + fn notify_state(&self, state: ClientState) { + if let Some(callback) = self + .on_state + .lock() + .expect("runtime callback poisoned") + .as_ref() + { + let _ = panic::catch_unwind(AssertUnwindSafe(|| callback(state))); + } + } + + fn notify_client_message(&self, emsg: EMsg, header: &CMsgProtoBufHeader, body: &[u8]) { + if let Some(callback) = self + .on_client_message + .lock() + .expect("runtime callback poisoned") + .as_ref() + { + let _ = panic::catch_unwind(AssertUnwindSafe(|| callback(emsg, header, body))); + } + } +} + +fn merge_pics_product_info( + acc: &mut CMsgClientPICSProductInfoResponse, + mut next: CMsgClientPICSProductInfoResponse, +) { + acc.apps.append(&mut next.apps); + acc.packages.append(&mut next.packages); + acc.unknown_appids.append(&mut next.unknown_appids); + acc.unknown_packageids.append(&mut next.unknown_packageids); + if next.http_min_size > 0 { + acc.http_min_size = next.http_min_size; + } + if !next.http_host.is_empty() { + acc.http_host = next.http_host; + } + acc.meta_data_only = next.meta_data_only; + acc.response_pending = false; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::proto_envelope::encode_proto_envelope; + use crate::steam::proto_wire::Writer as ProtoWriter; + use crate::steam::transport::{ConnectedCallback, DisconnectedCallback, MessageCallback}; + use crate::steam::transport::{TransportDisconnectReason, TransportState}; + use crate::steam::wire_format::Writer as WireWriter; + use std::sync::mpsc; + + #[test] + fn connected_channel_sends_client_hello_and_reports_state() { + let shared = Arc::new(MockTransportState::default()); + let runtime = runtime_with_shared_transport(Arc::clone(&shared)); + let states = Arc::new(Mutex::new(Vec::new())); + let states_cb = Arc::clone(&states); + runtime.set_on_state(move |state| states_cb.lock().unwrap().push(state)); + + assert!(runtime.connect("wss://cm.example.com:443/cmsocket/")); + shared.fire_connected(); + + assert_eq!( + states.lock().unwrap().as_slice(), + &[ClientState::Connecting, ClientState::Connected] + ); + let sent = shared.take_sent(); + assert_eq!( + decode_proto_envelope(&sent[0]).unwrap().emsg, + EMsg::CLIENT_HELLO + ); + } + + #[test] + fn connected_channel_flushes_prequeued_hello_without_duplicate() { + let shared = Arc::new(MockTransportState::default()); + let runtime = runtime_with_shared_transport(Arc::clone(&shared)); + runtime + .core + .enqueue_wire(runtime.core.build_client_hello().wire); + + assert!(runtime.connect("wss://cm.example.com:443/cmsocket/")); + shared.fire_connected(); + + let sent = shared.take_sent(); + assert_eq!(sent.len(), 1); + assert_eq!( + decode_proto_envelope(&sent[0]).unwrap().emsg, + EMsg::CLIENT_HELLO + ); + } + + #[test] + fn flush_outbound_preserves_core_queue_order() { + let shared = Arc::new(MockTransportState::default()); + let runtime = runtime_with_shared_transport(Arc::clone(&shared)); + assert!(runtime.connect("wss://cm.example.com:443/cmsocket/")); + shared.fire_connected(); + shared.take_sent(); + + runtime.core.enqueue_wire(vec![1, 2, 3]); + runtime.core.enqueue_wire(vec![4, 5, 6]); + assert_eq!(runtime.flush_outbound(), 2); + assert_eq!(shared.take_sent(), vec![vec![1, 2, 3], vec![4, 5, 6]]); + } + + #[test] + fn inbound_job_response_is_delivered() { + let shared = Arc::new(MockTransportState::default()); + let runtime = runtime_with_shared_transport(shared); + let job_id = runtime.next_job_id(); + let (tx, rx) = mpsc::channel(); + runtime.track_job(job_id, move |result| tx.send(result).unwrap(), None); + + let header = CMsgProtoBufHeader { + jobid_target: job_id, + eresult: 1, + ..Default::default() + }; + let wire = encode_proto_envelope(EMsg::SERVICE_METHOD_RESPONSE, &header, b"reply"); + assert_eq!( + runtime.handle_channel_message(&wire), + InboundAction::DeliverJob(JobResult { + eresult: 1, + error_message: String::new(), + body: b"reply".to_vec(), + synthetic_failure: false, + }) + ); + assert_eq!(rx.recv().unwrap().body, b"reply"); + } + + #[test] + fn multi_records_are_redispatched() { + let shared = Arc::new(MockTransportState::default()); + let runtime = runtime_with_shared_transport(shared); + let (tx, rx) = mpsc::channel(); + runtime.set_on_client_message(move |emsg, _, body| { + tx.send((emsg, body.to_vec())).unwrap(); + }); + + let inner = encode_proto_envelope( + EMsg::CLIENT_SESSION_TOKEN, + &CMsgProtoBufHeader::default(), + &account_info_body("Ada"), + ); + let mut records = Vec::new(); + WireWriter::new(&mut records).u32(inner.len() as u32); + records.extend_from_slice(&inner); + let mut multi_body = Vec::new(); + ProtoWriter::new(&mut multi_body).bytes_field(2, &records); + let multi = encode_proto_envelope(EMsg::MULTI, &CMsgProtoBufHeader::default(), &multi_body); + + assert_eq!(runtime.handle_channel_message(&multi), InboundAction::Multi); + assert_eq!( + rx.recv().unwrap(), + (EMsg::CLIENT_SESSION_TOKEN, account_info_body("Ada")) + ); + } + + #[test] + fn legacy_channel_encrypt_frames_are_ignored() { + let shared = Arc::new(MockTransportState::default()); + let runtime = runtime_with_shared_transport(shared); + let mut legacy = Vec::new(); + WireWriter::new(&mut legacy).u32(EMsg::CHANNEL_ENCRYPT_REQUEST.0); + assert_eq!( + runtime.handle_channel_message(&legacy), + InboundAction::Ignored + ); + } + + fn runtime_with_shared_transport(shared: Arc) -> Arc { + CMClientRuntime::new( + Arc::new(CMClientCore::default()), + Box::new(MockTransport { shared }), + ) + } + + fn account_info_body(name: &str) -> Vec { + let mut body = Vec::new(); + ProtoWriter::new(&mut body).string_field(1, name); + body + } + + struct MockTransportState { + state: Mutex, + connected: Mutex>, + disconnected: Mutex>, + message: Mutex>, + sent: Mutex>>, + } + + impl Default for MockTransportState { + fn default() -> Self { + Self { + state: Mutex::new(TransportState::Disconnected), + connected: Mutex::new(None), + disconnected: Mutex::new(None), + message: Mutex::new(None), + sent: Mutex::new(Vec::new()), + } + } + } + + impl MockTransportState { + fn fire_connected(&self) { + *self.state.lock().unwrap() = TransportState::Connected; + if let Some(callback) = self.connected.lock().unwrap().as_ref() { + callback(); + } + } + + #[allow(dead_code)] + fn fire_disconnected(&self, reason: TransportDisconnectReason, detail: &str) { + *self.state.lock().unwrap() = TransportState::Disconnected; + if let Some(callback) = self.disconnected.lock().unwrap().as_ref() { + callback(reason, detail); + } + } + + #[allow(dead_code)] + fn fire_message(&self, bytes: &[u8]) { + if let Some(callback) = self.message.lock().unwrap().as_ref() { + callback(bytes); + } + } + + fn take_sent(&self) -> Vec> { + std::mem::take(&mut *self.sent.lock().unwrap()) + } + } + + struct MockTransport { + shared: Arc, + } + + impl Transport for MockTransport { + fn connect(&mut self, _url: &str) -> bool { + *self.shared.state.lock().unwrap() = TransportState::Connecting; + true + } + + fn send(&mut self, data: &[u8]) -> bool { + if self.state() != TransportState::Connected { + return false; + } + self.shared.sent.lock().unwrap().push(data.to_vec()); + true + } + + fn disconnect(&mut self) { + *self.shared.state.lock().unwrap() = TransportState::Disconnected; + } + + fn state(&self) -> TransportState { + *self.shared.state.lock().unwrap() + } + + fn set_on_message(&mut self, cb: MessageCallback) { + *self.shared.message.lock().unwrap() = Some(cb); + } + + fn set_on_connected(&mut self, cb: ConnectedCallback) { + *self.shared.connected.lock().unwrap() = Some(cb); + } + + fn set_on_disconnected(&mut self, cb: DisconnectedCallback) { + *self.shared.disconnected.lock().unwrap() = Some(cb); + } + } +} diff --git a/app/src/main/rust/stores/src/steam/cm_server.rs b/app/src/main/rust/stores/src/steam/cm_server.rs new file mode 100644 index 0000000000..1449a5a988 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/cm_server.rs @@ -0,0 +1,93 @@ +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[repr(u8)] +pub enum CmTransport { + #[default] + Unknown = 0, + WebSocket = 1, + Tcp = 2, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CmServer { + pub endpoint: String, + pub host: String, + pub port: u16, + pub transport: CmTransport, + pub realm: String, + pub datacenter: String, + pub load: i32, + pub weighted_load: f32, +} + +impl CmServer { + pub fn websocket_url(&self) -> String { + if self.transport != CmTransport::WebSocket || self.host.is_empty() || self.port == 0 { + return String::new(); + } + if self.host.contains(':') && !self.host.starts_with('[') { + format!("wss://[{}]:{}/cmsocket/", self.host, self.port) + } else { + format!("wss://{}:{}/cmsocket/", self.host, self.port) + } + } +} + +pub fn parse_endpoint(endpoint: &str) -> Option<(String, u16)> { + let colon = endpoint.rfind(':')?; + if colon == 0 || colon + 1 == endpoint.len() { + return None; + } + let mut host = &endpoint[..colon]; + if host.len() >= 2 && host.starts_with('[') && host.ends_with(']') { + host = &host[1..host.len() - 1]; + } + let port_text = &endpoint[colon + 1..]; + if !port_text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let port = port_text.parse::().ok()?; + if port == 0 || port > u16::MAX as u32 { + return None; + } + Some((host.to_string(), port as u16)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_host_port_and_ipv6_brackets() { + assert_eq!( + parse_endpoint("cm.example.com:443"), + Some(("cm.example.com".to_string(), 443)) + ); + assert_eq!( + parse_endpoint("[2001:db8::1]:27017"), + Some(("2001:db8::1".to_string(), 27017)) + ); + assert_eq!(parse_endpoint("missing-port"), None); + assert_eq!(parse_endpoint("host:0"), None); + assert_eq!(parse_endpoint("host:+443"), None); + assert_eq!(parse_endpoint("host:70000"), None); + } + + #[test] + fn websocket_url_requires_websocket_transport() { + let server = CmServer { + host: "cm.example.com".to_string(), + port: 443, + transport: CmTransport::WebSocket, + ..Default::default() + }; + assert_eq!(server.websocket_url(), "wss://cm.example.com:443/cmsocket/"); + let (host, port) = parse_endpoint("[2001:db8::1]:27017").unwrap(); + let v6 = CmServer { + host, + port, + transport: CmTransport::WebSocket, + ..Default::default() + }; + assert_eq!(v6.websocket_url(), "wss://[2001:db8::1]:27017/cmsocket/"); + } +} diff --git a/app/src/main/rust/stores/src/steam/cm_server_list.rs b/app/src/main/rust/stores/src/steam/cm_server_list.rs new file mode 100644 index 0000000000..069b036186 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/cm_server_list.rs @@ -0,0 +1,205 @@ +use crate::steam::cm_server::{CmServer, CmTransport}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ServerQuality { + Good, + Bad, +} + +pub const DEFAULT_BAD_MEMORY: Duration = Duration::from_secs(5 * 60); + +pub struct CmServerList { + inner: Mutex, + bad_memory: Duration, +} + +#[derive(Default)] +struct Inner { + entries: Vec, + next_index: usize, +} + +struct Entry { + server: CmServer, + quality: ServerQuality, + marked_bad_at: Option, +} + +impl Default for CmServerList { + fn default() -> Self { + Self::new(DEFAULT_BAD_MEMORY) + } +} + +impl CmServerList { + pub fn new(bad_memory: Duration) -> Self { + Self { + inner: Mutex::new(Inner::default()), + bad_memory, + } + } + + pub fn replace_all(&self, servers: &[CmServer]) { + let mut inner = self.inner.lock().unwrap(); + inner.entries = servers + .iter() + .cloned() + .map(|server| Entry { + server, + quality: ServerQuality::Good, + marked_bad_at: None, + }) + .collect(); + inner.next_index = 0; + } + + pub fn add(&self, server: CmServer) { + self.inner.lock().unwrap().entries.push(Entry { + server, + quality: ServerQuality::Good, + marked_bad_at: None, + }); + } + + pub fn size(&self) -> usize { + self.inner.lock().unwrap().entries.len() + } + + pub fn next_good(&self) -> Option { + let mut inner = self.inner.lock().unwrap(); + if inner.entries.is_empty() { + return None; + } + promote_expired(&mut inner.entries, self.bad_memory); + let n = inner.entries.len(); + for i in 0..n { + let idx = (inner.next_index + i) % n; + if inner.entries[idx].quality == ServerQuality::Good { + inner.next_index = (idx + 1) % n; + return Some(inner.entries[idx].server.clone()); + } + } + None + } + + pub fn mark_bad(&self, endpoint: &str) { + let mut inner = self.inner.lock().unwrap(); + if let Some(entry) = inner + .entries + .iter_mut() + .find(|e| e.server.endpoint == endpoint) + { + entry.quality = ServerQuality::Bad; + entry.marked_bad_at = Some(Instant::now()); + } + } + + pub fn mark_good(&self, endpoint: &str) { + let mut inner = self.inner.lock().unwrap(); + if let Some(entry) = inner + .entries + .iter_mut() + .find(|e| e.server.endpoint == endpoint) + { + entry.quality = ServerQuality::Good; + entry.marked_bad_at = None; + } + } + + pub fn reset_quality(&self) { + let mut inner = self.inner.lock().unwrap(); + for entry in &mut inner.entries { + entry.quality = ServerQuality::Good; + entry.marked_bad_at = None; + } + } +} + +fn promote_expired(entries: &mut [Entry], bad_memory: Duration) { + let now = Instant::now(); + for entry in entries { + if entry.quality == ServerQuality::Bad + && entry + .marked_bad_at + .is_some_and(|t| now.duration_since(t) >= bad_memory) + { + entry.quality = ServerQuality::Good; + entry.marked_bad_at = None; + } + } +} + +pub fn hardcoded_fallback_servers() -> Vec { + const FALLBACK: &[(&str, &str)] = &[ + ("ext1-sea1.steamserver.net", "sea1"), + ("ext2-sea1.steamserver.net", "sea1"), + ("ext1-iad1.steamserver.net", "iad1"), + ("ext2-iad1.steamserver.net", "iad1"), + ("ext1-fra1.steamserver.net", "fra1"), + ("ext2-fra1.steamserver.net", "fra1"), + ("ext1-lax1.steamserver.net", "lax1"), + ("ext1-sgp1.steamserver.net", "sgp1"), + ]; + FALLBACK + .iter() + .map(|(host, dc)| CmServer { + endpoint: format!("{host}:443"), + host: (*host).to_string(), + port: 443, + transport: CmTransport::WebSocket, + realm: "steamglobal".to_string(), + datacenter: (*dc).to_string(), + load: 0, + weighted_load: 0.0, + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn next_good_round_robins_and_skips_bad() { + let list = CmServerList::default(); + let a = server("a:443"); + let b = server("b:443"); + list.replace_all(&[a.clone(), b.clone()]); + assert_eq!(list.next_good().unwrap().endpoint, a.endpoint); + list.mark_bad(&b.endpoint); + assert_eq!(list.next_good().unwrap().endpoint, a.endpoint); + list.mark_good(&b.endpoint); + assert_eq!(list.next_good().unwrap().endpoint, b.endpoint); + } + + #[test] + fn bad_servers_promote_after_memory_interval() { + let list = CmServerList::new(Duration::ZERO); + let a = server("a:443"); + list.replace_all(std::slice::from_ref(&a)); + list.mark_bad(&a.endpoint); + assert_eq!(list.next_good().unwrap().endpoint, a.endpoint); + } + + #[test] + fn fallback_servers_are_websocket_urls() { + let servers = hardcoded_fallback_servers(); + assert!(!servers.is_empty()); + assert!(servers + .iter() + .all(|s| s.websocket_url().starts_with("wss://"))); + } + + fn server(endpoint: &str) -> CmServer { + let (host, port) = crate::steam::cm_server::parse_endpoint(endpoint).unwrap(); + CmServer { + endpoint: endpoint.to_string(), + host, + port, + transport: CmTransport::WebSocket, + ..Default::default() + } + } +} diff --git a/app/src/main/rust/stores/src/steam/cmsg_protobuf_header.rs b/app/src/main/rust/stores/src/steam/cmsg_protobuf_header.rs new file mode 100644 index 0000000000..23dd670ce8 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/cmsg_protobuf_header.rs @@ -0,0 +1,168 @@ +use crate::steam::proto_wire::{Reader, WireType, Writer}; + +pub const INVALID_JOB_ID: u64 = u64::MAX; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgProtoBufHeader { + pub steamid: u64, + pub client_sessionid: i32, + pub routing_appid: u32, + pub jobid_source: u64, + pub jobid_target: u64, + pub target_job_name: String, + pub eresult: i32, + pub error_message: String, + pub realm: u32, + pub messageid: u64, + pub token_id: u64, +} + +impl Default for CMsgProtoBufHeader { + fn default() -> Self { + Self { + steamid: 0, + client_sessionid: 0, + routing_appid: 0, + jobid_source: INVALID_JOB_ID, + jobid_target: INVALID_JOB_ID, + target_job_name: String::new(), + eresult: -1, + error_message: String::new(), + realm: 0, + messageid: 0, + token_id: 0, + } + } +} + +impl CMsgProtoBufHeader { + pub fn serialize(&self, out: &mut Vec) { + let mut writer = Writer::new(out); + + if self.steamid != 0 { + writer.tag(1, WireType::Fixed64); + writer.fixed64_field_force_body(self.steamid); + } + writer.int32_field(2, self.client_sessionid); + writer.uint32_field(3, self.routing_appid); + if self.jobid_source != INVALID_JOB_ID { + writer.tag(10, WireType::Fixed64); + writer.fixed64_field_force_body(self.jobid_source); + } + if self.jobid_target != INVALID_JOB_ID { + writer.tag(11, WireType::Fixed64); + writer.fixed64_field_force_body(self.jobid_target); + } + writer.string_field(12, &self.target_job_name); + if self.eresult >= 0 { + writer.tag(13, WireType::Varint); + writer.varint(self.eresult as i64 as u64); + } + writer.string_field(14, &self.error_message); + writer.uint64_field(18, self.messageid); + writer.uint32_field(32, self.realm); + writer.uint64_field(36, self.token_id); + } + + pub fn deserialize(bytes: &[u8]) -> Option { + let mut reader = Reader::new(bytes); + let mut header = Self::default(); + + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(header); + }; + match tag.field_number { + 1 => { + if tag.wire_type != WireType::Fixed64 { + return None; + } + header.steamid = reader.fixed64()?; + } + 2 => header.client_sessionid = reader.i32()?, + 3 => header.routing_appid = reader.u32()?, + 10 => { + if tag.wire_type != WireType::Fixed64 { + return None; + } + header.jobid_source = reader.fixed64()?; + } + 11 => { + if tag.wire_type != WireType::Fixed64 { + return None; + } + header.jobid_target = reader.fixed64()?; + } + 12 => header.target_job_name = reader.string()?, + 13 => header.eresult = reader.i32()?, + 14 => header.error_message = reader.string()?, + 18 => header.messageid = reader.u64()?, + 32 => header.realm = reader.u32()?, + 36 => header.token_id = reader.u64()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + + Some(header) + } +} + +trait WriterFixedBodies { + fn fixed64_field_force_body(&mut self, v: u64); +} + +impl WriterFixedBodies for Writer<'_> { + fn fixed64_field_force_body(&mut self, v: u64) { + self.raw_bytes(&v.to_le_bytes()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serializes_only_set_job_ids() { + let h = CMsgProtoBufHeader { + steamid: 0x1122_3344_5566_7788, + client_sessionid: 17, + routing_appid: 480, + target_job_name: "Authentication.BeginAuthSessionViaCredentials#1".to_string(), + ..Default::default() + }; + let mut bytes = Vec::new(); + h.serialize(&mut bytes); + let parsed = CMsgProtoBufHeader::deserialize(&bytes).unwrap(); + assert_eq!(parsed, h); + assert!(!bytes + .windows(2) + .any(|w| w == [0x51, 0xff] || w == [0x59, 0xff])); + } + + #[test] + fn reads_steam_field_numbers() { + // steammessages_base.proto: eresult = 13, error_message = 14, messageid = 18, realm = 32, token_id = 36. + let bytes = [ + 0x68, 0x05, 0x72, 0x02, b'n', b'o', 0x90, 0x01, 0x07, 0x80, 0x02, 0x01, 0xa0, 0x02, 0x09, + ]; + let h = CMsgProtoBufHeader::deserialize(&bytes).unwrap(); + assert_eq!(h.eresult, 5); + assert_eq!(h.error_message, "no"); + assert_eq!(h.messageid, 7); + assert_eq!(h.realm, 1); + assert_eq!(h.token_id, 9); + let mut out = Vec::new(); + h.serialize(&mut out); + assert_eq!(out, bytes); + } + + #[test] + fn rejects_wrong_fixed_wire_type() { + let bytes = [0x08, 0x01]; + assert_eq!(CMsgProtoBufHeader::deserialize(&bytes), None); + } +} diff --git a/app/src/main/rust/stores/src/steam/content_manifest.rs b/app/src/main/rust/stores/src/steam/content_manifest.rs new file mode 100644 index 0000000000..450b151e7e --- /dev/null +++ b/app/src/main/rust/stores/src/steam/content_manifest.rs @@ -0,0 +1,353 @@ +use crate::steam::base64; +use crate::steam::crypto::{ + aes256_cbc_decrypt, aes256_ecb_decrypt_block, AesBlock, SessionKey, AES_BLOCK_BYTES, + SESSION_KEY_LENGTH, +}; +use crate::steam::proto_wire::{Reader, WireType}; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ChunkData { + pub sha: Vec, + pub crc: u32, + pub offset: u64, + pub cb_original: u32, + pub cb_compressed: u32, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct FileMapping { + pub filename: String, + pub size: u64, + pub flags: u32, + pub sha_filename: Vec, + pub sha_content: Vec, + pub chunks: Vec, + pub linktarget: String, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Metadata { + pub depot_id: u32, + pub gid_manifest: u64, + pub creation_time: u32, + pub filenames_encrypted: bool, + pub cb_disk_original: u64, + pub cb_disk_compressed: u64, + pub unique_chunks: u32, + pub crc_encrypted: u32, + pub crc_clear: u32, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ContentManifest { + pub metadata: Metadata, + pub files: Vec, + pub signature: Vec, +} + +pub const PAYLOAD_MAGIC: u32 = 0x71f6_17d0; +pub const METADATA_MAGIC: u32 = 0x1f48_12be; +pub const SIGNATURE_MAGIC: u32 = 0x1b81_b817; +pub const END_OF_MANIFEST_MAGIC: u32 = 0x32c4_15ab; + +impl ContentManifest { + pub fn parse(raw: &[u8]) -> Option { + let mut manifest = Self::default(); + let mut have_payload = false; + let mut have_metadata = false; + let mut pos = 0usize; + + loop { + let magic = read_u32_le(raw, &mut pos)?; + if magic == END_OF_MANIFEST_MAGIC { + break; + } + let len = read_u32_le(raw, &mut pos)? as usize; + if pos + len > raw.len() { + return None; + } + let section = &raw[pos..pos + len]; + pos += len; + + match magic { + PAYLOAD_MAGIC => { + parse_payload(section, &mut manifest.files)?; + have_payload = true; + } + METADATA_MAGIC => { + manifest.metadata = parse_metadata(section)?; + have_metadata = true; + } + SIGNATURE_MAGIC => { + manifest.signature = parse_signature(section)?; + } + _ => return None, + } + } + + (have_payload && have_metadata).then_some(manifest) + } + + pub fn decrypt_filenames(&mut self, depot_key: &[u8]) -> bool { + if self.metadata.filenames_encrypted { + if depot_key.len() != SESSION_KEY_LENGTH { + return false; + } + let mut key = [0u8; SESSION_KEY_LENGTH]; + key.copy_from_slice(depot_key); + + for file in &mut self.files { + let Some(clear) = decrypt_name(&key, &file.filename) else { + return false; + }; + file.filename = clear; + if !file.linktarget.is_empty() { + let Some(clear) = decrypt_name(&key, &file.linktarget) else { + return false; + }; + file.linktarget = clear; + } + } + self.metadata.filenames_encrypted = false; + } + + for file in &mut self.files { + file.filename = file.filename.replace('\\', "/"); + file.linktarget = file.linktarget.replace('\\', "/"); + } + + self.files.sort_by(|a, b| { + a.filename + .bytes() + .map(|c| c.to_ascii_lowercase()) + .cmp(b.filename.bytes().map(|c| c.to_ascii_lowercase())) + }); + true + } +} + +fn decrypt_name(key: &SessionKey, enc: &str) -> Option { + let blob = base64::decode(enc)?; + if blob.len() < AES_BLOCK_BYTES * 2 { + return None; + } + let mut wrapped = [0u8; AES_BLOCK_BYTES]; + wrapped.copy_from_slice(&blob[..AES_BLOCK_BYTES]); + let iv: AesBlock = aes256_ecb_decrypt_block(key, &wrapped)?; + let plain = aes256_cbc_decrypt(key, &iv, &blob[AES_BLOCK_BYTES..])?; + let mut out = String::from_utf8_lossy(&plain).into_owned(); + if out.ends_with('\0') { + out.pop(); + } + Some(out) +} + +fn read_u32_le(buf: &[u8], pos: &mut usize) -> Option { + if *pos + 4 > buf.len() { + return None; + } + let v = u32::from_le_bytes(buf[*pos..*pos + 4].try_into().ok()?); + *pos += 4; + Some(v) +} + +fn parse_chunk(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut chunk = ChunkData::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(chunk); + }; + match tag.field_number { + 1 => chunk.sha = reader.bytes()?.to_vec(), + 2 => { + if tag.wire_type != WireType::Fixed32 { + return None; + } + chunk.crc = reader.fixed32()?; + } + 3 => chunk.offset = reader.u64()?, + 4 => chunk.cb_original = reader.u32()?, + 5 => chunk.cb_compressed = reader.u32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(chunk) +} + +fn parse_file_mapping(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut file = FileMapping::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(file); + }; + match tag.field_number { + 1 => file.filename = reader.string()?, + 2 => file.size = reader.u64()?, + 3 => file.flags = reader.u32()?, + 4 => file.sha_filename = reader.bytes()?.to_vec(), + 5 => file.sha_content = reader.bytes()?.to_vec(), + 6 => file.chunks.push(parse_chunk(reader.bytes()?)?), + 7 => file.linktarget = reader.string()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(file) +} + +fn parse_payload(body: &[u8], out: &mut Vec) -> Option<()> { + let mut reader = Reader::new(body); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(()); + }; + if tag.field_number == 1 { + out.push(parse_file_mapping(reader.bytes()?)?); + } else if !reader.skip(tag.wire_type) { + return None; + } + } + Some(()) +} + +fn parse_metadata(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut metadata = Metadata::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(metadata); + }; + match tag.field_number { + 1 => metadata.depot_id = reader.u32()?, + 2 => metadata.gid_manifest = reader.u64()?, + 3 => metadata.creation_time = reader.u32()?, + 4 => metadata.filenames_encrypted = reader.boolean()?, + 5 => metadata.cb_disk_original = reader.u64()?, + 6 => metadata.cb_disk_compressed = reader.u64()?, + 7 => metadata.unique_chunks = reader.u32()?, + 8 => metadata.crc_encrypted = reader.u32()?, + 9 => metadata.crc_clear = reader.u32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(metadata) +} + +fn parse_signature(body: &[u8]) -> Option> { + let mut reader = Reader::new(body); + let mut signature = Vec::new(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(signature); + }; + if tag.field_number == 1 { + signature = reader.bytes()?.to_vec(); + } else if !reader.skip(tag.wire_type) { + return None; + } + } + Some(signature) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::crypto::{aes256_cbc_encrypt, aes256_ecb_encrypt_block}; + use crate::steam::proto_wire::Writer; + + #[test] + fn parses_manifest_sections() { + let mut chunk_body = Vec::new(); + { + let mut w = Writer::new(&mut chunk_body); + w.bytes_field(1, &[1; 20]); + w.tag(2, WireType::Fixed32); + w.raw_bytes(&0x1234_5678u32.to_le_bytes()); + w.uint64_field(3, 99); + w.uint32_field(4, 11); + w.uint32_field(5, 22); + } + + let mut file_body = Vec::new(); + { + let mut w = Writer::new(&mut file_body); + w.string_field(1, "bin\\game.exe"); + w.uint64_field(2, 11); + w.uint32_field(3, 1); + w.submessage_field(6, &chunk_body); + } + + let mut payload = Vec::new(); + Writer::new(&mut payload).submessage_field(1, &file_body); + + let mut metadata = Vec::new(); + { + let mut w = Writer::new(&mut metadata); + w.uint32_field(1, 123); + w.uint64_field(2, 456); + w.uint32_field(3, 789); + w.bool_field_force(4, false); + } + + let mut raw = Vec::new(); + push_section(&mut raw, PAYLOAD_MAGIC, &payload); + push_section(&mut raw, METADATA_MAGIC, &metadata); + raw.extend_from_slice(&END_OF_MANIFEST_MAGIC.to_le_bytes()); + + let mut manifest = ContentManifest::parse(&raw).unwrap(); + assert_eq!(manifest.metadata.depot_id, 123); + assert_eq!(manifest.files[0].filename, "bin\\game.exe"); + assert!(manifest.decrypt_filenames(&[])); + assert_eq!(manifest.files[0].filename, "bin/game.exe"); + assert_eq!(manifest.files[0].chunks[0].crc, 0x1234_5678); + } + + #[test] + fn decrypts_encrypted_filenames() { + let key = [9u8; SESSION_KEY_LENGTH]; + let name = encrypt_name(&key, "dir\\file.txt\0"); + let mut manifest = ContentManifest { + metadata: Metadata { + filenames_encrypted: true, + ..Default::default() + }, + files: vec![FileMapping { + filename: name, + ..Default::default() + }], + signature: Vec::new(), + }; + + assert!(manifest.decrypt_filenames(&key)); + assert_eq!(manifest.files[0].filename, "dir/file.txt"); + assert!(!manifest.metadata.filenames_encrypted); + } + + fn push_section(out: &mut Vec, magic: u32, body: &[u8]) { + out.extend_from_slice(&magic.to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(body); + } + + fn encrypt_name(key: &SessionKey, name: &str) -> String { + let iv = [5u8; AES_BLOCK_BYTES]; + let wrapped = aes256_ecb_encrypt_block(key, &iv).unwrap(); + let body = aes256_cbc_encrypt(key, &iv, name.as_bytes()).unwrap(); + let mut blob = wrapped.to_vec(); + blob.extend_from_slice(&body); + base64::encode(&blob) + } +} diff --git a/app/src/main/rust/stores/src/steam/crypto.rs b/app/src/main/rust/stores/src/steam/crypto.rs new file mode 100644 index 0000000000..103608bebe --- /dev/null +++ b/app/src/main/rust/stores/src/steam/crypto.rs @@ -0,0 +1,150 @@ +use aes::cipher::{ + block_padding::Pkcs7, BlockDecrypt, BlockDecryptMut, BlockEncrypt, BlockEncryptMut, KeyInit, + KeyIvInit, +}; +use aes::Aes256; +use hmac::{Hmac, Mac}; +use rand::{rngs::OsRng, RngCore}; +use rsa::pkcs8::DecodePublicKey; +use rsa::traits::PublicKeyParts; +use rsa::{Oaep, RsaPublicKey}; +use sha1::{Digest as Sha1DigestTrait, Sha1}; +use sha2::Sha256; +use zeroize::Zeroize; + +pub const SESSION_KEY_LENGTH: usize = 32; +pub const AES_BLOCK_BYTES: usize = 16; +pub const SHA1_BYTES: usize = 20; +pub const SHA256_BYTES: usize = 32; +pub const HMAC_KEY_LENGTH: usize = 16; + +pub type SessionKey = [u8; SESSION_KEY_LENGTH]; +pub type Sha1Digest = [u8; SHA1_BYTES]; +pub type Sha256Digest = [u8; SHA256_BYTES]; +pub type AesBlock = [u8; AES_BLOCK_BYTES]; + +#[derive(Clone)] +pub struct SecureSessionKey { + pub bytes: SessionKey, +} + +impl SecureSessionKey { + pub fn new(bytes: SessionKey) -> Self { + Self { bytes } + } +} + +impl Drop for SecureSessionKey { + fn drop(&mut self) { + self.bytes.zeroize(); + } +} + +pub fn secure_random_bytes(out: &mut [u8]) -> bool { + OsRng.try_fill_bytes(out).is_ok() +} + +pub fn generate_session_key() -> Option { + let mut bytes = [0u8; SESSION_KEY_LENGTH]; + secure_random_bytes(&mut bytes).then_some(SecureSessionKey::new(bytes)) +} + +pub fn sha1(data: &[u8]) -> Sha1Digest { + Sha1::digest(data).into() +} + +pub fn sha256(data: &[u8]) -> Sha256Digest { + Sha256::digest(data).into() +} + +pub fn crc32(data: &[u8]) -> u32 { + crc32fast::hash(data) +} + +pub fn hmac_sha1(key: &[u8], data: &[u8]) -> Option { + let mut mac = as Mac>::new_from_slice(key).ok()?; + mac.update(data); + Some(mac.finalize().into_bytes().into()) +} + +pub fn aes256_ecb_encrypt_block(key: &SessionKey, input: &AesBlock) -> Option { + let cipher = Aes256::new_from_slice(key).ok()?; + let mut block = (*input).into(); + cipher.encrypt_block(&mut block); + Some(block.into()) +} + +pub fn aes256_ecb_decrypt_block(key: &SessionKey, input: &AesBlock) -> Option { + let cipher = Aes256::new_from_slice(key).ok()?; + let mut block = (*input).into(); + cipher.decrypt_block(&mut block); + Some(block.into()) +} + +pub fn aes256_cbc_encrypt(key: &SessionKey, iv: &AesBlock, plaintext: &[u8]) -> Option> { + Some( + cbc::Encryptor::::new(key.into(), iv.into()) + .encrypt_padded_vec_mut::(plaintext), + ) +} + +pub fn aes256_cbc_decrypt(key: &SessionKey, iv: &AesBlock, ciphertext: &[u8]) -> Option> { + if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(AES_BLOCK_BYTES) { + return None; + } + cbc::Decryptor::::new(key.into(), iv.into()) + .decrypt_padded_vec_mut::(ciphertext) + .ok() +} + +pub fn rsa_oaep_sha1_encrypt(spki_der: &[u8], plaintext: &[u8]) -> Option> { + let public_key = RsaPublicKey::from_public_key_der(spki_der).ok()?; + let modulus = public_key.size(); + if modulus < 2 + 2 * SHA1_BYTES || plaintext.len() > modulus - 2 - 2 * SHA1_BYTES { + return None; + } + public_key + .encrypt(&mut OsRng, Oaep::new::(), plaintext) + .ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hashes_match_known_values() { + assert_eq!( + hex(&sha1(b"abc")), + "a9993e364706816aba3e25717850c26c9cd0d89d" + ); + assert_eq!( + hex(&sha256(b"abc")), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + } + + #[test] + fn aes_cbc_roundtrips_with_pkcs7() { + let key = [7u8; SESSION_KEY_LENGTH]; + let iv = [3u8; AES_BLOCK_BYTES]; + let plaintext = b"steam manifest filename"; + let encrypted = aes256_cbc_encrypt(&key, &iv, plaintext).unwrap(); + assert_ne!(encrypted, plaintext); + let decrypted = aes256_cbc_decrypt(&key, &iv, &encrypted).unwrap(); + assert_eq!(decrypted, plaintext); + } + + #[test] + fn hmac_sha1_known_value() { + assert_eq!( + hex(&hmac_sha1(b"key", b"The quick brown fox jumps over the lazy dog").unwrap()), + "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9" + ); + } + + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() + } +} diff --git a/app/src/main/rust/stores/src/steam/depot_chunk.rs b/app/src/main/rust/stores/src/steam/depot_chunk.rs new file mode 100644 index 0000000000..728a34e0dc --- /dev/null +++ b/app/src/main/rust/stores/src/steam/depot_chunk.rs @@ -0,0 +1,258 @@ +use crate::steam::cdn; +use crate::steam::crypto::{ + aes256_cbc_decrypt, aes256_ecb_decrypt_block, AesBlock, SessionKey, AES_BLOCK_BYTES, + SESSION_KEY_LENGTH, +}; +use lzma_rs::decompress::raw::{LzmaDecoder, LzmaParams, LzmaProperties}; +use std::io::{Cursor, Read}; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct DepotChunkResult { + pub data: Vec, + pub error: String, +} + +impl DepotChunkResult { + pub fn ok(&self) -> bool { + self.error.is_empty() + } +} + +pub fn process_depot_chunk( + raw: &[u8], + depot_key: &[u8], + expected_crc: u32, + expected_size: u32, +) -> DepotChunkResult { + if depot_key.len() != SESSION_KEY_LENGTH { + return fail("chunk: bad depot key length"); + } + if raw.is_empty() { + return fail("chunk: empty"); + } + let mut key = [0u8; SESSION_KEY_LENGTH]; + key.copy_from_slice(depot_key); + + let Some(dec) = steam_symmetric_decrypt(&key, raw) else { + return fail("chunk: AES decrypt failed"); + }; + if dec.is_empty() { + return fail("chunk: AES decrypt failed"); + } + + let result = if dec.starts_with(b"VSZa") { + decompress_vzstd(&dec, expected_size) + } else if dec.starts_with(b"VZa") { + decompress_vzip(&dec, expected_size) + } else if dec.starts_with(b"PK\x03\x04") { + match cdn::unzip_first_entry(&dec, expected_size as usize) { + Some(data) => DepotChunkResult { + data, + error: String::new(), + }, + None => fail("chunk: PKZip decompress failed"), + } + } else { + fail("chunk: unrecognised compression header") + }; + if !result.ok() { + return result; + } + if result.data.len() != expected_size as usize { + return fail(format!( + "chunk: size mismatch ({} != {expected_size})", + result.data.len() + )); + } + if steam_adler_hash(&result.data) != expected_crc { + return fail("chunk: Adler32 mismatch"); + } + result +} + +pub fn steam_symmetric_decrypt(key: &SessionKey, enc: &[u8]) -> Option> { + if enc.len() < AES_BLOCK_BYTES * 2 { + return None; + } + let mut wrapped = [0u8; AES_BLOCK_BYTES]; + wrapped.copy_from_slice(&enc[..AES_BLOCK_BYTES]); + let iv: AesBlock = aes256_ecb_decrypt_block(key, &wrapped)?; + aes256_cbc_decrypt(key, &iv, &enc[AES_BLOCK_BYTES..]) +} + +fn decompress_vzstd(dec: &[u8], expected_size: u32) -> DepotChunkResult { + if dec.len() <= 8 { + return fail("vzstd: chunk too small"); + } + let payload = &dec[8..]; + let reader = match ruzstd::decoding::StreamingDecoder::new(Cursor::new(payload)) { + Ok(reader) => reader, + Err(_) => return fail("vzstd: bad zstd frame"), + }; + let mut data = Vec::with_capacity(expected_size as usize); + // One byte past the expected size is enough for the size check to reject an oversized frame. + if reader + .take(expected_size as u64 + 1) + .read_to_end(&mut data) + .is_err() + { + return fail("vzstd: decode failed"); + } + DepotChunkResult { + data, + error: String::new(), + } +} + +fn decompress_vzip(dec: &[u8], expected_size: u32) -> DepotChunkResult { + const HEADER: usize = 3 + 4; + const PROPS: usize = 5; + const FOOTER: usize = 10; + if dec.len() < HEADER + PROPS + FOOTER { + return fail("vzip: chunk too small"); + } + if dec[dec.len() - 2] != b'z' || dec[dec.len() - 1] != b'v' { + return fail("vzip: bad footer"); + } + let props = &dec[HEADER..HEADER + PROPS]; + let comp = &dec[HEADER + PROPS..dec.len() - FOOTER]; + let Some(params) = lzma_params_from_steam_props(props, expected_size as u64) else { + return fail("vzip: bad LZMA properties"); + }; + let mut decoder = match LzmaDecoder::new(params, None) { + Ok(decoder) => decoder, + Err(_) => return fail("vzip: raw decoder init failed"), + }; + let mut output = Vec::with_capacity(expected_size as usize); + match decoder.decompress(&mut Cursor::new(comp), &mut output) { + Ok(()) => DepotChunkResult { + data: output, + error: String::new(), + }, + Err(_) => fail("vzip: LZMA decode failed"), + } +} + +fn lzma_params_from_steam_props(props: &[u8], expected_size: u64) -> Option { + if props.len() != 5 { + return None; + } + let mut packed = props[0] as u32; + if packed >= 225 { + return None; + } + let lc = packed % 9; + packed /= 9; + let lp = packed % 5; + let pb = packed / 5; + if lc > 8 || lp > 4 || pb > 4 { + return None; + } + let dict_size = u32::from_le_bytes(props[1..5].try_into().ok()?); + Some(LzmaParams::new( + LzmaProperties { lc, lp, pb }, + dict_size, + Some(expected_size), + )) +} + +pub fn steam_adler_hash(data: &[u8]) -> u32 { + let mut a = 0u32; + let mut b = 0u32; + for byte in data { + a = (a + *byte as u32) % 65_521; + b = (b + a) % 65_521; + } + a | (b << 16) +} + +fn fail(msg: impl Into) -> DepotChunkResult { + DepotChunkResult { + data: Vec::new(), + error: msg.into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::crypto::{aes256_cbc_encrypt, aes256_ecb_encrypt_block}; + + #[test] + fn steam_adler_hash_uses_zero_seed() { + assert_eq!(steam_adler_hash(b""), 0); + assert_eq!(steam_adler_hash(b"abc"), 0x024a_0126); + } + + #[test] + fn decrypts_and_processes_pkzip_chunk() { + let key = [4u8; SESSION_KEY_LENGTH]; + let payload = b"chunk bytes"; + let mut zip = Vec::new(); + zip.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + zip.extend_from_slice(&20u16.to_le_bytes()); + zip.extend_from_slice(&0u16.to_le_bytes()); + zip.extend_from_slice(&0u16.to_le_bytes()); + zip.extend_from_slice(&0u16.to_le_bytes()); + zip.extend_from_slice(&0u16.to_le_bytes()); + zip.extend_from_slice(&0u32.to_le_bytes()); + zip.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + zip.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + zip.extend_from_slice(&1u16.to_le_bytes()); + zip.extend_from_slice(&0u16.to_le_bytes()); + zip.extend_from_slice(b"x"); + zip.extend_from_slice(payload); + + let raw = encrypt_steam_symmetric(&key, &zip); + let result = + process_depot_chunk(&raw, &key, steam_adler_hash(payload), payload.len() as u32); + assert_eq!(result.data, payload); + assert!(result.ok()); + } + + #[test] + fn decrypts_and_processes_vzip_raw_lzma_chunk() { + let key = [8u8; SESSION_KEY_LENGTH]; + let payload = b"legacy lzma chunk bytes"; + let mut lzma_alone = Vec::new(); + lzma_rs::lzma_compress(&mut Cursor::new(payload), &mut lzma_alone).unwrap(); + assert!(lzma_alone.len() > 13); + + let mut vzip = Vec::new(); + vzip.extend_from_slice(b"VZa"); + vzip.extend_from_slice(&0u32.to_le_bytes()); + vzip.extend_from_slice(&lzma_alone[..5]); + vzip.extend_from_slice(&lzma_alone[13..]); + vzip.extend_from_slice(&0u32.to_le_bytes()); + vzip.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + vzip.extend_from_slice(b"zv"); + + let raw = encrypt_steam_symmetric(&key, &vzip); + let result = + process_depot_chunk(&raw, &key, steam_adler_hash(payload), payload.len() as u32); + assert_eq!(result.data, payload); + assert!(result.ok()); + } + + #[test] + fn vzip_rejects_bad_properties_before_raw_decode() { + let mut dec = Vec::new(); + dec.extend_from_slice(b"VZa"); + dec.extend_from_slice(&0u32.to_le_bytes()); + dec.extend_from_slice(&[225, 0, 0, 0, 0]); + dec.extend_from_slice(b"payload"); + dec.extend_from_slice(&0u32.to_le_bytes()); + dec.extend_from_slice(&0u32.to_le_bytes()); + dec.extend_from_slice(b"zv"); + assert_eq!(decompress_vzip(&dec, 1).error, "vzip: bad LZMA properties"); + } + + fn encrypt_steam_symmetric(key: &SessionKey, plaintext: &[u8]) -> Vec { + let iv = [6u8; AES_BLOCK_BYTES]; + let wrapped = aes256_ecb_encrypt_block(key, &iv).unwrap(); + let body = aes256_cbc_encrypt(key, &iv, plaintext).unwrap(); + let mut out = wrapped.to_vec(); + out.extend_from_slice(&body); + out + } +} diff --git a/app/src/main/rust/stores/src/steam/depot_config.rs b/app/src/main/rust/stores/src/steam/depot_config.rs new file mode 100644 index 0000000000..91a8b2c62a --- /dev/null +++ b/app/src/main/rust/stores/src/steam/depot_config.rs @@ -0,0 +1,191 @@ +//! Resume journal for one app's download, kept in a caller-given app-private directory (never in +//! the game folder, which must end up exactly like one the Steam client made). +//! +//! Layout of `//`: `depot.config` (JSON: the build the journal belongs to and +//! the finished manifest per depot, or the in-progress sentinel while a depot is being written) +//! and `_.manifest` (the raw CDN manifest, so a resumed run does not refetch it). + +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub const INVALID_MANIFEST_ID: u64 = 0x7fff_ffff_ffff_ffff; + +pub fn app_journal_dir(journal_root: impl AsRef, app_id: u32) -> PathBuf { + journal_root.as_ref().join(app_id.to_string()) +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DepotConfigStore { + dir: PathBuf, + build_id: u64, + installed: BTreeMap, +} + +impl DepotConfigStore { + /// Loads the journal; a journal written for another build is dropped (its depot records and + /// cached manifests no longer describe what this run installs). + pub fn load(dir: impl Into, build_id: u64) -> Self { + let dir = dir.into(); + let mut store = Self { + dir, + build_id, + installed: BTreeMap::new(), + }; + let Ok(text) = fs::read_to_string(store.config_path()) else { + return store; + }; + let Ok(value) = serde_json::from_str::(&text) else { + return store; + }; + let journal_build = value.get("buildId").and_then(Value::as_u64).unwrap_or(0); + if journal_build != build_id { + store.discard(); + return store; + } + if let Some(obj) = value.get("installedManifestIDs").and_then(Value::as_object) { + for (key, value) in obj { + if let (Ok(depot_id), Some(manifest_id)) = (key.parse::(), value.as_u64()) { + store.installed.insert(depot_id, manifest_id); + } + } + } + store + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn manifest_cache_path(&self, depot_id: u32, manifest_id: u64) -> PathBuf { + self.dir.join(format!("{depot_id}_{manifest_id}.manifest")) + } + + pub fn is_installed(&self, depot_id: u32, manifest_id: u64) -> bool { + self.installed + .get(&depot_id) + .is_some_and(|installed| *installed == manifest_id && *installed != INVALID_MANIFEST_ID) + } + + pub fn begin_depot(&mut self, depot_id: u32) -> bool { + self.installed.insert(depot_id, INVALID_MANIFEST_ID); + self.save() + } + + pub fn finish_depot(&mut self, depot_id: u32, manifest_id: u64) -> bool { + self.installed.insert(depot_id, manifest_id); + self.save() + } + + pub fn read_cached_manifest(&self, depot_id: u32, manifest_id: u64) -> Option> { + let bytes = fs::read(self.manifest_cache_path(depot_id, manifest_id)).ok()?; + (!bytes.is_empty()).then_some(bytes) + } + + pub fn write_cached_manifest(&self, depot_id: u32, manifest_id: u64, raw: &[u8]) -> bool { + atomic_write_synced(&self.manifest_cache_path(depot_id, manifest_id), raw) + } + + /// Drops a cached manifest that turned out unusable, so the next attempt fetches it again. + pub fn remove_cached_manifest(&self, depot_id: u32, manifest_id: u64) { + let _ = fs::remove_file(self.manifest_cache_path(depot_id, manifest_id)); + } + + /// Removes the whole journal directory (after a successful install, or when it is stale). + pub fn discard(&mut self) { + self.installed.clear(); + let _ = fs::remove_dir_all(&self.dir); + } + + fn config_path(&self) -> PathBuf { + self.dir.join("depot.config") + } + + fn save(&self) -> bool { + let ids: serde_json::Map = self + .installed + .iter() + .map(|(depot, manifest)| (depot.to_string(), json!(manifest))) + .collect(); + let Ok(bytes) = serde_json::to_string_pretty(&json!({ + "buildId": self.build_id, + "installedManifestIDs": ids, + })) else { + return false; + }; + atomic_write_synced(&self.config_path(), bytes.as_bytes()) + } +} + +pub fn atomic_write_synced(final_path: &Path, bytes: &[u8]) -> bool { + let Some(parent) = final_path.parent() else { + return false; + }; + if fs::create_dir_all(parent).is_err() { + return false; + } + let mut tmp_name = final_path + .file_name() + .map(|n| n.to_os_string()) + .unwrap_or_default(); + tmp_name.push(".tmp"); + let tmp_path = final_path.with_file_name(tmp_name); + let mut file = match File::create(&tmp_path) { + Ok(file) => file, + Err(_) => return false, + }; + if file.write_all(bytes).is_err() || file.sync_all().is_err() { + let _ = fs::remove_file(&tmp_path); + return false; + } + drop(file); + if fs::rename(&tmp_path, final_path).is_err() { + let _ = fs::remove_file(&tmp_path); + return false; + } + if let Ok(dir) = File::open(parent) { + let _ = dir.sync_all(); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn journal_roundtrips_marks_in_progress_and_drops_other_builds() { + let root = temp_dir("journal"); + let dir = app_journal_dir(&root, 291550); + let mut store = DepotConfigStore::load(&dir, 26465982); + assert!(!store.is_installed(291551, 1)); + assert!(store.begin_depot(291551)); + assert!(!DepotConfigStore::load(&dir, 26465982).is_installed(291551, INVALID_MANIFEST_ID)); + assert!(store.finish_depot(291551, 4224536525702420323)); + assert!(store.write_cached_manifest(291551, 4224536525702420323, b"raw")); + let loaded = DepotConfigStore::load(&dir, 26465982); + assert!(loaded.is_installed(291551, 4224536525702420323)); + assert_eq!( + loaded.read_cached_manifest(291551, 4224536525702420323), + Some(b"raw".to_vec()) + ); + loaded.remove_cached_manifest(291551, 4224536525702420323); + assert_eq!(loaded.read_cached_manifest(291551, 4224536525702420323), None); + let other_build = DepotConfigStore::load(&dir, 1); + assert!(!other_build.is_installed(291551, 4224536525702420323)); + assert!(!dir.exists()); + let _ = fs::remove_dir_all(&root); + } + + fn temp_dir(name: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "droiddeck_steam_{name}_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )) + } +} diff --git a/app/src/main/rust/stores/src/steam/depot_downloader.rs b/app/src/main/rust/stores/src/steam/depot_downloader.rs new file mode 100644 index 0000000000..34faa16731 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/depot_downloader.rs @@ -0,0 +1,162 @@ +//! One depot from key to files: depot decryption key, manifest request code, the manifest (from +//! the journal when a cancelled run already fetched it), filename decryption, then the writer. + +use crate::steam::cdn; +use crate::steam::content_manifest::ContentManifest; +use crate::steam::depot_config::DepotConfigStore; +use crate::steam::depot_writer::{write_depot, DepotWriteOutcome, DepotWriteRequest}; +use crate::steam::pb::ccontentserverdirectory::CContentServerDirectoryServerInfo; +use crate::steam::session::{CodeResolution, KeyResolution, Session}; +use std::path::Path; +use std::sync::atomic::AtomicBool; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum DepotError { + Cancelled, + AccessDenied(u32), + Failed(String), +} + +impl DepotError { + pub fn message(&self) -> String { + match self { + DepotError::Cancelled => "cancelled".to_string(), + DepotError::AccessDenied(depot) => format!("access_denied: depot {depot}"), + DepotError::Failed(msg) => msg.clone(), + } + } +} + +pub struct PreparedDepot { + pub depot_id: u32, + pub manifest_id: u64, + pub key: Vec, + pub manifest: ContentManifest, +} + +impl Drop for PreparedDepot { + fn drop(&mut self) { + zeroize::Zeroize::zeroize(&mut self.key); + } +} + +/// Resolves the key and the manifest of `depot_id` (owned by `app_id`, the app the key and +/// request code are asked for). +#[allow(clippy::too_many_arguments)] +pub fn prepare_depot( + session: &Session, + servers: &[CContentServerDirectoryServerInfo], + journal: Option<&DepotConfigStore>, + ca_bundle_path: &str, + app_id: u32, + depot_id: u32, + manifest_id: u64, + cancel: &AtomicBool, +) -> Result { + let key = match session.depot_key(app_id, depot_id, cancel) { + KeyResolution::Granted(key) => key, + KeyResolution::AccessDenied => return Err(DepotError::AccessDenied(depot_id)), + KeyResolution::Cancelled => return Err(DepotError::Cancelled), + KeyResolution::Unavailable => { + return Err(DepotError::Failed(format!( + "depot key unavailable for depot {depot_id}" + ))) + } + }; + let raw = match journal.and_then(|j| j.read_cached_manifest(depot_id, manifest_id)) { + Some(raw) => raw, + None => { + let servers = cdn::usable_servers(servers); + let code = match session.manifest_code(app_id, depot_id, manifest_id, cancel) { + CodeResolution::Code(code) => code, + CodeResolution::AccessDenied => return Err(DepotError::AccessDenied(depot_id)), + CodeResolution::Cancelled => return Err(DepotError::Cancelled), + CodeResolution::Unavailable => { + return Err(DepotError::Failed(format!( + "manifest request code unavailable for depot {depot_id}" + ))) + } + }; + let ca = ca_bundle_path; + let mut fetched = + cdn::fetch_manifest_with_retry(&servers, depot_id, manifest_id, code, ca, cancel); + if !fetched.ok() && fetched.error != "cancelled" { + // Request codes rotate every few minutes: one more pass with a fresh one. + match session.manifest_code(app_id, depot_id, manifest_id, cancel) { + CodeResolution::Code(fresh) if fresh != code => { + fetched = cdn::fetch_manifest_with_retry( + &servers, + depot_id, + manifest_id, + fresh, + ca, + cancel, + ); + } + CodeResolution::Cancelled => return Err(DepotError::Cancelled), + _ => {} + } + } + if fetched.error == "cancelled" { + return Err(DepotError::Cancelled); + } + if !fetched.ok() { + return Err(DepotError::Failed(format!( + "manifest fetch failed for depot {depot_id}: {}", + fetched.error + ))); + } + if let Some(journal) = journal { + let _ = journal.write_cached_manifest(depot_id, manifest_id, &fetched.raw_manifest); + } + fetched.raw_manifest + } + }; + let forget = || { + if let Some(journal) = journal { + journal.remove_cached_manifest(depot_id, manifest_id); + } + }; + let Some(mut manifest) = ContentManifest::parse(&raw) else { + forget(); + return Err(DepotError::Failed(format!( + "manifest parse failed for depot {depot_id}" + ))); + }; + if !manifest.decrypt_filenames(&key) { + forget(); + return Err(DepotError::Failed(format!( + "filename decryption failed for depot {depot_id}" + ))); + } + Ok(PreparedDepot { + depot_id, + manifest_id, + key, + manifest, + }) +} + +#[allow(clippy::too_many_arguments)] +pub fn download_prepared( + prepared: &PreparedDepot, + servers: &[CContentServerDirectoryServerInfo], + target_dir: &Path, + ca_bundle_path: &str, + max_workers: usize, + process_workers: usize, + cancel: &AtomicBool, + progress: &(dyn Fn(u64) + Sync), + log: &(dyn Fn(&str) + Sync), +) -> DepotWriteOutcome { + let request = DepotWriteRequest { + manifest: &prepared.manifest, + depot_key: &prepared.key, + servers, + target_dir, + ca_bundle_path, + max_workers, + process_workers, + }; + write_depot(&request, cancel, progress, log) +} diff --git a/app/src/main/rust/stores/src/steam/depot_writer.rs b/app/src/main/rust/stores/src/steam/depot_writer.rs new file mode 100644 index 0000000000..f43a3a63c5 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/depot_writer.rs @@ -0,0 +1,958 @@ +//! Writes one depot's files in place under the target folder, the way the Steam client lays them +//! out: no temp files, no space reservation (`fallocate`/zero-fill are slow on Android's FUSE +//! storage), each file trimmed to its exact size with `set_len` once its last chunk lands. +//! +//! Chunk bodies come from the shared fetch core (`crate::fetch_core`), which owns the adaptive +//! request window, host rotation and retries; this module is the sink (decrypt, decompress, +//! Adler-32 check, positioned write). A chunk that appears several times in the manifest is +//! fetched once and written to every place it belongs. On resume, chunks already on disk are +//! read back and checked before anything is fetched. + +use crate::fetch_core::{run_fetch, FetchItem, FetchOptions, FetchSink, SinkError}; +use crate::steam::cdn; +use crate::steam::content_manifest::{ChunkData, ContentManifest}; +use crate::steam::depot_chunk::{process_depot_chunk, steam_adler_hash}; +use crate::steam::pb::ccontentserverdirectory::CContentServerDirectoryServerInfo; +use sha1::{Digest, Sha1}; +use std::collections::HashMap; +use std::fs::{self, File, OpenOptions}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +pub const DEPOT_FILE_FLAG_EXECUTABLE: u32 = 32; +pub const DEPOT_FILE_FLAG_DIRECTORY: u32 = 64; +/// Chunks per fetch-core run. Every chunk carries one URL per CDN host, so batches bound memory on +/// very large depots. +pub const FETCH_BATCH_ITEMS: usize = 8192; +/// Above this many open files a written file's handle is closed and reopened on its next chunk. +pub const MAX_OPEN_FILES: usize = 256; +pub const CHUNK_TIMEOUT: Duration = Duration::from_secs(60); +const FREE_SPACE_MARGIN_BYTES: u64 = 64 * 1024 * 1024; + +pub struct DepotWriteRequest<'a> { + /// Filenames already decrypted (see `ContentManifest::decrypt_filenames`). + pub manifest: &'a ContentManifest, + pub depot_key: &'a [u8], + pub servers: &'a [CContentServerDirectoryServerInfo], + pub target_dir: &'a Path, + pub ca_bundle_path: &'a str, + pub max_workers: usize, + pub process_workers: usize, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DepotWriteOutcome { + /// Bytes of the depot that are complete on disk (verified + written). + pub bytes_done: u64, + /// Of those, bytes that were already correct on disk. + pub bytes_verified: u64, + pub error: Option, + pub cancelled: bool, +} + +impl DepotWriteOutcome { + pub fn ok(&self) -> bool { + self.error.is_none() && !self.cancelled + } + + fn fail(error: impl Into) -> Self { + Self { + error: Some(error.into()), + ..Default::default() + } + } +} + +pub fn path_is_safe(rel: &str) -> bool { + if rel.is_empty() || rel.starts_with('/') || rel.starts_with('\\') { + return false; + } + let path = Path::new(rel); + !path.is_absolute() + && path + .components() + .all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) +} + +pub fn depot_total_bytes(manifest: &ContentManifest) -> u64 { + manifest + .files + .iter() + .filter(|f| is_regular(f.flags, &f.linktarget)) + .map(|f| f.size) + .sum() +} + +fn is_regular(flags: u32, linktarget: &str) -> bool { + linktarget.is_empty() && (flags & DEPOT_FILE_FLAG_DIRECTORY) == 0 +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct Target { + file_idx: u32, + offset: u64, +} + +#[derive(Clone, Debug)] +struct UniqueChunk { + sha: Vec, + crc: u32, + cb_original: u32, + cb_compressed: u32, + targets: Vec, +} + +struct FileSlot { + handle: Mutex>>, + remaining: AtomicUsize, + size: u64, + path: PathBuf, + mode: u32, +} + +struct DepotFiles { + slots: Vec, + open_count: AtomicUsize, + /// The canonical target folder; every write must resolve beneath it. + root: PathBuf, +} + +impl DepotFiles { + fn acquire(&self, file_idx: usize) -> Result, String> { + let slot = &self.slots[file_idx]; + let mut handle = slot.handle.lock().expect("file slot poisoned"); + if let Some(file) = handle.as_ref() { + return Ok(Arc::clone(file)); + } + make_parent_dirs(&self.root, &slot.path)?; + check_file_target(&self.root, &slot.path)?; + let file = OpenOptions::new() + .create(true) + .write(true) + .read(true) + .truncate(false) + .open(&slot.path) + .map_err(|err| format!("open '{}': {err}", slot.path.display()))?; + set_file_mode(&file, &slot.path, slot.mode)?; + let file = Arc::new(file); + *handle = Some(Arc::clone(&file)); + self.open_count.fetch_add(1, Ordering::Relaxed); + Ok(file) + } + + fn release(&self, file_idx: usize) { + let slot = &self.slots[file_idx]; + if slot + .handle + .lock() + .expect("file slot poisoned") + .take() + .is_some() + { + self.open_count.fetch_sub(1, Ordering::Relaxed); + } + } + + fn write(&self, file_idx: usize, offset: u64, data: &[u8]) -> Result<(), String> { + let file = self.acquire(file_idx)?; + pwrite_all_at(&file, offset, data).map_err(|err| { + format!( + "write '{}' at {offset}: {err}", + self.slots[file_idx].path.display() + ) + })?; + let slot = &self.slots[file_idx]; + if slot.remaining.fetch_sub(1, Ordering::AcqRel) == 1 { + finalize(&file, slot)?; + drop(file); + self.release(file_idx); + } else if self.open_count.load(Ordering::Relaxed) > MAX_OPEN_FILES { + drop(file); + self.release(file_idx); + } + Ok(()) + } + + /// Files with nothing left to fetch (zero chunks, or every chunk already correct on disk). + fn finalize_untouched(&self, idx: usize) -> Result<(), String> { + let slot = &self.slots[idx]; + make_parent_dirs(&self.root, &slot.path)?; + check_file_target(&self.root, &slot.path)?; + let file = OpenOptions::new() + .create(true) + .write(true) + .truncate(false) + .open(&slot.path) + .map_err(|err| format!("open '{}': {err}", slot.path.display()))?; + set_file_mode(&file, &slot.path, slot.mode)?; + let current = file.metadata().map(|m| m.len()).unwrap_or(u64::MAX); + if current != slot.size { + file.set_len(slot.size) + .map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?; + } + Ok(()) + } +} + +fn finalize(file: &File, slot: &FileSlot) -> Result<(), String> { + file.set_len(slot.size) + .map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?; + file.sync_all() + .map_err(|err| format!("sync '{}': {err}", slot.path.display())) +} + +struct ChunkSink<'a> { + chunks: &'a [UniqueChunk], + files: &'a DepotFiles, + depot_key: &'a [u8], +} + +impl FetchSink for ChunkSink<'_> { + fn process(&self, item: &FetchItem, body: Vec) -> Result { + let Some(chunk) = self.chunks.get(item.id as usize) else { + return Err(SinkError::Fatal("bad chunk index".to_string())); + }; + let processed = process_depot_chunk(&body, self.depot_key, chunk.crc, chunk.cb_original); + if !processed.ok() { + return Err(SinkError::Retry(processed.error)); + } + // A chunk's id is the SHA-1 of its decompressed bytes. + if Sha1::digest(&processed.data).as_slice() != chunk.sha.as_slice() { + return Err(SinkError::Retry("chunk: SHA-1 mismatch".to_string())); + } + let mut credited = 0u64; + for target in &chunk.targets { + self.files + .write(target.file_idx as usize, target.offset, &processed.data) + .map_err(SinkError::Fatal)?; + credited += processed.data.len() as u64; + } + Ok(credited) + } +} + +struct Prepared { + files: DepotFiles, + chunks: Vec, + bytes_verified: u64, + total: u64, +} + +/// Layout, free-space check, resume verify pass, and the de-duplicated chunk list still to fetch. +fn prepare( + request: &DepotWriteRequest<'_>, + cancel: &AtomicBool, +) -> Result { + let manifest = request.manifest; + if manifest.metadata.filenames_encrypted { + return Err(DepotWriteOutcome::fail( + "manifest filenames are still encrypted", + )); + } + if request.depot_key.len() != 32 { + return Err(DepotWriteOutcome::fail("bad depot key length")); + } + if let Some(bad) = manifest.files.iter().find(|f| !path_is_safe(&f.filename)) { + return Err(DepotWriteOutcome::fail(format!( + "unsafe path '{}'", + bad.filename + ))); + } + if let Err(err) = fs::create_dir_all(request.target_dir) { + return Err(DepotWriteOutcome::fail(format!( + "mkdir '{}': {err}", + request.target_dir.display() + ))); + } + let root = match fs::canonicalize(request.target_dir) { + Ok(root) => root, + Err(err) => { + return Err(DepotWriteOutcome::fail(format!( + "resolve '{}': {err}", + request.target_dir.display() + ))) + } + }; + + let mut slots = Vec::with_capacity(manifest.files.len()); + let mut existing = Vec::with_capacity(manifest.files.len()); + for file in &manifest.files { + let path = request.target_dir.join(&file.filename); + let regular = is_regular(file.flags, &file.linktarget); + let len = if regular { + fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + } else { + 0 + }; + existing.push(len); + slots.push(FileSlot { + handle: Mutex::new(None), + remaining: AtomicUsize::new(0), + size: file.size, + path, + mode: if (file.flags & DEPOT_FILE_FLAG_EXECUTABLE) != 0 { + 0o755 + } else { + 0o644 + }, + }); + } + + let total = depot_total_bytes(manifest); + let present: u64 = manifest + .files + .iter() + .zip(&existing) + .map(|(f, len)| (*len).min(f.size)) + .sum(); + let needed = total.saturating_sub(present); + if let Some(available) = available_space_bytes(request.target_dir) { + if available > 0 && available.saturating_add(FREE_SPACE_MARGIN_BYTES) < needed { + return Err(DepotWriteOutcome::fail(format!( + "not_enough_space: need {} MiB, have {} MiB", + needed / (1024 * 1024), + available / (1024 * 1024) + ))); + } + } + + for file in &manifest.files { + let path = request.target_dir.join(&file.filename); + let result = if !file.linktarget.is_empty() { + create_symlink(&root, &path, &file.linktarget) + } else if (file.flags & DEPOT_FILE_FLAG_DIRECTORY) != 0 { + make_dirs(&root, &path) + } else { + Ok(()) + }; + if let Err(err) = result { + return Err(DepotWriteOutcome::fail(err)); + } + } + + let verified = verify_existing( + manifest, + &slots, + &existing, + &root, + request.process_workers, + cancel, + ); + if cancel.load(Ordering::Relaxed) { + return Err(DepotWriteOutcome { + cancelled: true, + ..Default::default() + }); + } + let mut bytes_verified = 0u64; + let mut chunks: Vec = Vec::new(); + let mut by_sha: HashMap, usize> = HashMap::new(); + for (file_idx, file) in manifest.files.iter().enumerate() { + if !is_regular(file.flags, &file.linktarget) { + continue; + } + let mut remaining = 0usize; + for (chunk_idx, chunk) in file.chunks.iter().enumerate() { + if verified[file_idx].get(chunk_idx).copied().unwrap_or(false) { + bytes_verified += chunk.cb_original as u64; + continue; + } + remaining += 1; + let target = Target { + file_idx: file_idx as u32, + offset: chunk.offset, + }; + match by_sha.get(&chunk.sha) { + Some(&idx) => chunks[idx].targets.push(target), + None => { + by_sha.insert(chunk.sha.clone(), chunks.len()); + chunks.push(UniqueChunk { + sha: chunk.sha.clone(), + crc: chunk.crc, + cb_original: chunk.cb_original, + cb_compressed: chunk.cb_compressed, + targets: vec![target], + }); + } + } + } + slots[file_idx] + .remaining + .store(remaining, Ordering::Relaxed); + } + drop(by_sha); + + let files = DepotFiles { + slots, + open_count: AtomicUsize::new(0), + root, + }; + for (idx, file) in manifest.files.iter().enumerate() { + if is_regular(file.flags, &file.linktarget) + && files.slots[idx].remaining.load(Ordering::Relaxed) == 0 + { + if let Err(err) = files.finalize_untouched(idx) { + return Err(DepotWriteOutcome::fail(err)); + } + } + } + Ok(Prepared { + files, + chunks, + bytes_verified, + total, + }) +} + +/// Writes (or resumes) one depot. `progress` gets the depot's completed bytes; `log` gets the +/// fetch core's lines. +pub fn write_depot( + request: &DepotWriteRequest<'_>, + cancel: &AtomicBool, + progress: &(dyn Fn(u64) + Sync), + log: &(dyn Fn(&str) + Sync), +) -> DepotWriteOutcome { + let manifest = request.manifest; + let servers = cdn::usable_servers(request.servers); + let Prepared { + files, + chunks, + bytes_verified, + total, + } = match prepare(request, cancel) { + Ok(prepared) => prepared, + Err(outcome) => return outcome, + }; + if servers.is_empty() && !chunks.is_empty() { + return DepotWriteOutcome::fail("no usable CDN server"); + } + progress(bytes_verified); + log(&format!( + "depot={} files={} unique_chunks={} verified_bytes={bytes_verified} total_bytes={total}", + manifest.metadata.depot_id, + manifest.files.len(), + chunks.len() + )); + + let hosts: Vec = servers.iter().map(cdn::host_key).collect(); + let opts = FetchOptions { + max_workers: request.max_workers.max(1), + timeout: CHUNK_TIMEOUT, + ca_bundle_path: request.ca_bundle_path.to_string(), + process_workers: request.process_workers.max(1), + label: format!("steam depot={}", manifest.metadata.depot_id), + ..Default::default() + }; + let sink = ChunkSink { + chunks: &chunks, + files: &files, + depot_key: request.depot_key, + }; + let depot_id = manifest.metadata.depot_id; + let done_before = AtomicU64::new(bytes_verified); + let mut start = 0usize; + while start < chunks.len() { + if cancel.load(Ordering::Relaxed) { + return DepotWriteOutcome { + bytes_done: done_before.load(Ordering::Relaxed), + bytes_verified, + cancelled: true, + error: None, + }; + } + let end = (start + FETCH_BATCH_ITEMS).min(chunks.len()); + let mut items = Vec::with_capacity(end - start); + for (idx, chunk) in chunks.iter().enumerate().take(end).skip(start) { + let mut urls = Vec::with_capacity(servers.len()); + for server in &servers { + match cdn::build_chunk_url(server, depot_id, &chunk.sha) { + Ok(url) => urls.push(url), + Err(err) => return DepotWriteOutcome::fail(err), + } + } + items.push(FetchItem { + id: idx as u64, + urls, + reserve: chunk.cb_compressed as u64, + range: None, + }); + } + let base = done_before.load(Ordering::Relaxed); + let batch_progress = |credited: u64, _items: u64| progress(base + credited); + let outcome = run_fetch(items, &hosts, &opts, &sink, cancel, &batch_progress, log); + done_before.fetch_add(outcome.bytes_credited, Ordering::Relaxed); + if outcome.cancelled { + return DepotWriteOutcome { + bytes_done: done_before.load(Ordering::Relaxed), + bytes_verified, + cancelled: true, + error: None, + }; + } + if let Some(error) = outcome.error { + return DepotWriteOutcome { + bytes_done: done_before.load(Ordering::Relaxed), + bytes_verified, + cancelled: false, + error: Some(error), + }; + } + start = end; + } + + if let Some((idx, _)) = files + .slots + .iter() + .enumerate() + .find(|(_, s)| s.remaining.load(Ordering::Relaxed) != 0) + { + return DepotWriteOutcome::fail(format!( + "file '{}' incomplete after fetch", + manifest.files[idx].filename + )); + } + DepotWriteOutcome { + bytes_done: done_before.load(Ordering::Relaxed), + bytes_verified, + error: None, + cancelled: false, + } +} + +/// Per file, per chunk: is the chunk already correct on disk? Only files that already have bytes +/// are read; a fresh install skips this entirely. +fn verify_existing( + manifest: &ContentManifest, + slots: &[FileSlot], + existing: &[u64], + root: &Path, + workers: usize, + cancel: &AtomicBool, +) -> Vec> { + let mut out: Vec> = manifest + .files + .iter() + .map(|f| vec![false; f.chunks.len()]) + .collect(); + let todo: Vec = (0..manifest.files.len()) + .filter(|&i| existing[i] > 0 && !manifest.files[i].chunks.is_empty()) + .collect(); + if todo.is_empty() { + return out; + } + let queue = Mutex::new(todo.into_iter()); + let results: Mutex)>> = Mutex::new(Vec::new()); + std::thread::scope(|scope| { + for _ in 0..workers.clamp(1, 8) { + scope.spawn(|| { + crate::priority::background(); + loop { + if cancel.load(Ordering::Relaxed) { + return; + } + let next = queue.lock().expect("verify queue poisoned").next(); + let Some(idx) = next else { + return; + }; + if check_file_target(root, &slots[idx].path).is_err() { + continue; + } + let Ok(file) = File::open(&slots[idx].path) else { + continue; + }; + let chunks = &manifest.files[idx].chunks; + let mut flags = vec![false; chunks.len()]; + for (flag, chunk) in flags.iter_mut().zip(chunks) { + if cancel.load(Ordering::Relaxed) { + break; + } + *flag = existing_chunk_matches(&file, existing[idx], chunk); + } + results + .lock() + .expect("verify results poisoned") + .push((idx, flags)); + } + }); + } + }); + for (idx, flags) in results.into_inner().expect("verify results poisoned") { + out[idx] = flags; + } + out +} + +pub fn existing_chunk_matches(file: &File, file_len: u64, chunk: &ChunkData) -> bool { + if chunk.cb_original == 0 { + return false; + } + let end = chunk.offset.saturating_add(chunk.cb_original as u64); + if file_len < end { + return false; + } + let mut buf = vec![0u8; chunk.cb_original as usize]; + if pread_exact_at(file, chunk.offset, &mut buf).is_err() { + return false; + } + steam_adler_hash(&buf) == chunk.crc +} + +/// Fails unless `path` (which must exist) resolves beneath `root`, so a symlink in the game folder +/// cannot carry a write outside it. +fn check_inside(root: &Path, path: &Path) -> Result<(), String> { + match fs::canonicalize(path) { + Ok(real) if real.starts_with(root) => Ok(()), + Ok(real) => Err(format!( + "'{}' resolves outside the install folder ({})", + path.display(), + real.display() + )), + Err(err) => Err(format!("resolve '{}': {err}", path.display())), + } +} + +/// Creates `dir` and its missing parents, refusing when an existing ancestor or the result +/// resolves outside `root`. +fn make_dirs(root: &Path, dir: &Path) -> Result<(), String> { + let mut existing = dir; + while fs::symlink_metadata(existing).is_err() { + match existing.parent() { + Some(parent) if !parent.as_os_str().is_empty() => existing = parent, + _ => break, + } + } + check_inside(root, existing)?; + fs::create_dir_all(dir).map_err(|err| format!("mkdir '{}': {err}", dir.display()))?; + check_inside(root, dir) +} + +fn make_parent_dirs(root: &Path, path: &Path) -> Result<(), String> { + match path.parent() { + Some(parent) if !parent.as_os_str().is_empty() => make_dirs(root, parent), + _ => Ok(()), + } +} + +/// A file about to be opened: its folder must be inside `root`, and if the path itself is a symlink +/// it must resolve inside `root` too (a dangling one would create its target wherever it points). +fn check_file_target(root: &Path, path: &Path) -> Result<(), String> { + if let Some(parent) = path.parent() { + check_inside(root, parent)?; + } + match fs::symlink_metadata(path) { + Ok(meta) if meta.file_type().is_symlink() => check_inside(root, path), + _ => Ok(()), + } +} + +fn create_symlink(root: &Path, path: &Path, target: &str) -> Result<(), String> { + make_parent_dirs(root, path)?; + if fs::symlink_metadata(path).is_ok() { + fs::remove_file(path).map_err(|err| format!("unlink '{}': {err}", path.display()))?; + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, path) + .map_err(|err| format!("symlink '{}': {err}", path.display())) + } + #[cfg(not(unix))] + { + let _ = target; + Err(format!("symlink '{}': unsupported", path.display())) + } +} + +#[cfg(unix)] +fn set_file_mode(file: &File, path: &Path, mode: u32) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(fs::Permissions::from_mode(mode)) + .map_err(|err| format!("chmod '{}': {err}", path.display())) +} + +#[cfg(not(unix))] +fn set_file_mode(_file: &File, _path: &Path, _mode: u32) -> Result<(), String> { + Ok(()) +} + +#[cfg(unix)] +fn pwrite_all_at(file: &File, offset: u64, data: &[u8]) -> std::io::Result<()> { + use std::os::unix::fs::FileExt; + file.write_all_at(data, offset) +} + +#[cfg(unix)] +fn pread_exact_at(file: &File, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + use std::os::unix::fs::FileExt; + file.read_exact_at(buf, offset) +} + +#[cfg(any(target_os = "linux", target_os = "android"))] +pub fn available_space_bytes(path: &Path) -> Option { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + let c_path = CString::new(path.as_os_str().as_bytes()).ok()?; + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(c_path.as_ptr(), &mut st) } != 0 { + return None; + } + Some((st.f_bavail as u64).saturating_mul(st.f_frsize as u64)) +} + +#[cfg(not(any(target_os = "linux", target_os = "android")))] +pub fn available_space_bytes(_path: &Path) -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::content_manifest::FileMapping; + + #[test] + fn rejects_unsafe_paths() { + assert!(path_is_safe("bin/game.exe")); + assert!(path_is_safe("./a")); + assert!(!path_is_safe("")); + assert!(!path_is_safe("/etc/passwd")); + assert!(!path_is_safe("../x")); + assert!(!path_is_safe("a/../../x")); + assert!(!path_is_safe("\\x")); + } + + #[test] + fn existing_chunk_check_reads_back_and_compares_adler() { + let dir = std::env::temp_dir().join(format!( + "droiddeck_steam_verify_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + let path = dir.join("f.bin"); + fs::write(&path, b"helloworld").unwrap(); + let file = File::open(&path).unwrap(); + let good = ChunkData { + crc: steam_adler_hash(b"world"), + offset: 5, + cb_original: 5, + ..Default::default() + }; + let bad = ChunkData { + crc: steam_adler_hash(b"xxxxx"), + ..good.clone() + }; + let past_end = ChunkData { + offset: 8, + ..good.clone() + }; + assert!(existing_chunk_matches(&file, 10, &good)); + assert!(!existing_chunk_matches(&file, 10, &bad)); + assert!(!existing_chunk_matches(&file, 10, &past_end)); + let manifest = ContentManifest { + files: vec![FileMapping { + filename: "f.bin".into(), + size: 10, + chunks: vec![good.clone(), bad.clone()], + ..Default::default() + }], + ..Default::default() + }; + let slots = vec![FileSlot { + handle: Mutex::new(None), + remaining: AtomicUsize::new(0), + size: 10, + path: path.clone(), + mode: 0o644, + }]; + let root = fs::canonicalize(&dir).unwrap(); + let flags = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(false)); + assert_eq!(flags, vec![vec![true, false]]); + let cancelled = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(true)); + assert_eq!(cancelled, vec![vec![false, false]]); + let _ = fs::remove_dir_all(&dir); + } + + fn zip_stored(payload: &[u8]) -> Vec { + let mut zip = Vec::new(); + zip.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + zip.extend_from_slice(&20u16.to_le_bytes()); + zip.extend_from_slice(&[0u8; 8]); + zip.extend_from_slice(&0u32.to_le_bytes()); + zip.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + zip.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + zip.extend_from_slice(&1u16.to_le_bytes()); + zip.extend_from_slice(&0u16.to_le_bytes()); + zip.push(b'x'); + zip.extend_from_slice(payload); + zip + } + + fn encrypted_chunk(key: &[u8; 32], payload: &[u8]) -> Vec { + use crate::steam::crypto::{aes256_cbc_encrypt, aes256_ecb_encrypt_block}; + let iv = [9u8; 16]; + let mut out = aes256_ecb_encrypt_block(key, &iv).unwrap().to_vec(); + out.extend(aes256_cbc_encrypt(key, &iv, &zip_stored(payload)).unwrap()); + out + } + + fn chunk(data: &[u8], offset: u64) -> ChunkData { + ChunkData { + sha: Sha1::digest(data).to_vec(), + crc: steam_adler_hash(data), + offset, + cb_original: data.len() as u32, + cb_compressed: data.len() as u32 + 64, + } + } + + #[test] + fn writes_in_place_dedupes_chunks_and_resumes_from_disk() { + let dir = std::env::temp_dir().join(format!( + "droiddeck_steam_write_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let key = [3u8; 32]; + let manifest = ContentManifest { + files: vec![ + FileMapping { + filename: "bin".into(), + flags: DEPOT_FILE_FLAG_DIRECTORY, + ..Default::default() + }, + FileMapping { + filename: "bin/game.exe".into(), + size: 10, + flags: DEPOT_FILE_FLAG_EXECUTABLE, + chunks: vec![chunk(b"hello", 0), chunk(b"world", 5)], + ..Default::default() + }, + FileMapping { + filename: "data/copy.bin".into(), + size: 5, + chunks: vec![chunk(b"world", 0)], + ..Default::default() + }, + FileMapping { + filename: "empty.txt".into(), + ..Default::default() + }, + ], + ..Default::default() + }; + let request = DepotWriteRequest { + manifest: &manifest, + depot_key: &key, + servers: &[], + target_dir: &dir, + ca_bundle_path: "", + max_workers: 4, + process_workers: 2, + }; + let cancel = AtomicBool::new(false); + let prepared = prepare(&request, &cancel).unwrap(); + assert_eq!(prepared.total, 15); + assert_eq!(prepared.bytes_verified, 0); + assert_eq!(prepared.chunks.len(), 2); + assert_eq!(prepared.chunks[1].targets.len(), 2); + assert!(dir.join("bin").is_dir()); + assert_eq!(fs::metadata(dir.join("empty.txt")).unwrap().len(), 0); + + let sink = ChunkSink { + chunks: &prepared.chunks, + files: &prepared.files, + depot_key: &key, + }; + let item = |id: u64| FetchItem { + id, + urls: vec!["x".into()], + reserve: 0, + range: None, + }; + assert!(matches!( + sink.process(&item(0), b"garbage-garbage-garbage-garbage!".to_vec()), + Err(SinkError::Retry(_)) + )); + // Same size and Adler-32 as "hello" would need a collision; a different body of the right + // size is enough to show the SHA-1 is checked after the Adler-32 one passes. + let mut wrong = prepared.chunks.clone(); + wrong[0].crc = steam_adler_hash(b"HELLO"); + let wrong_sink = ChunkSink { + chunks: &wrong, + files: &prepared.files, + depot_key: &key, + }; + assert!(matches!( + wrong_sink.process(&item(0), encrypted_chunk(&key, b"HELLO")), + Err(SinkError::Retry(e)) if e.contains("SHA-1") + )); + assert_eq!( + sink.process(&item(1), encrypted_chunk(&key, b"world")) + .unwrap(), + 10 + ); + assert_eq!(fs::read(dir.join("data/copy.bin")).unwrap(), b"world"); + assert_eq!( + sink.process(&item(0), encrypted_chunk(&key, b"hello")) + .unwrap(), + 5 + ); + assert_eq!(fs::read(dir.join("bin/game.exe")).unwrap(), b"helloworld"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(dir.join("bin/game.exe")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o755); + } + drop(prepared); + + // A resumed run reads back what is on disk and fetches only what is wrong or missing. + fs::write(dir.join("bin/game.exe"), b"helloWORLD").unwrap(); + let again = prepare(&request, &cancel).unwrap(); + assert_eq!(again.bytes_verified, 10); + assert_eq!(again.chunks.len(), 1); + assert_eq!( + again.chunks[0].targets, + vec![Target { + file_idx: 1, + offset: 5 + }] + ); + let _ = fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn refuses_writes_through_a_symlink_out_of_the_install_folder() { + let base = std::env::temp_dir().join(format!( + "droiddeck_steam_escape_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let dir = base.join("game"); + let outside = base.join("outside"); + fs::create_dir_all(&dir).unwrap(); + fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("link")).unwrap(); + std::os::unix::fs::symlink("../game", dir.join("inner")).unwrap(); + let root = fs::canonicalize(&dir).unwrap(); + assert!(make_parent_dirs(&root, &dir.join("link/sub/f.bin")).is_err()); + assert!(!outside.join("sub").exists()); + assert!(check_file_target(&root, &dir.join("link/f.bin")).is_err()); + assert!(make_parent_dirs(&root, &dir.join("inner/sub/f.bin")).is_ok()); + assert!(check_file_target(&root, &dir.join("inner/sub/f.bin")).is_ok()); + std::os::unix::fs::symlink(outside.join("x"), dir.join("dangling")).unwrap(); + assert!(check_file_target(&root, &dir.join("dangling")).is_err()); + let _ = fs::remove_dir_all(&base); + } +} diff --git a/app/src/main/rust/stores/src/steam/emsg.rs b/app/src/main/rust/stores/src/steam/emsg.rs new file mode 100644 index 0000000000..7c7feb4975 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/emsg.rs @@ -0,0 +1,102 @@ +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +#[repr(transparent)] +pub struct EMsg(pub u32); + +impl EMsg { + pub const INVALID: Self = Self(0); + pub const MULTI: Self = Self(1); + pub const CHANNEL_ENCRYPT_REQUEST: Self = Self(1303); + pub const CHANNEL_ENCRYPT_RESPONSE: Self = Self(1304); + pub const CHANNEL_ENCRYPT_RESULT: Self = Self(1305); + pub const CLIENT_HELLO: Self = Self(9805); + pub const CLIENT_LOGON: Self = Self(5514); + pub const CLIENT_LOGON_RESPONSE: Self = Self(751); + pub const CLIENT_LOG_OFF: Self = Self(706); + pub const CLIENT_LOGGED_OFF: Self = Self(757); + pub const CLIENT_HEART_BEAT: Self = Self(703); + pub const CLIENT_SESSION_TOKEN: Self = Self(850); + pub const CLIENT_SERVER_UNAVAILABLE: Self = Self(5500); + pub const CLIENT_LICENSE_LIST: Self = Self(780); + /// Free/F2P/demo license grant (verified against JavaSteam `EMsg.java`). + pub const CLIENT_REQUEST_FREE_LICENSE: Self = Self(5572); + pub const CLIENT_REQUEST_FREE_LICENSE_RESPONSE: Self = Self(5573); + pub const CLIENT_PICS_PRODUCT_INFO_REQUEST: Self = Self(8903); + pub const CLIENT_PICS_PRODUCT_INFO_RESPONSE: Self = Self(8904); + pub const CLIENT_PICS_ACCESS_TOKEN_REQUEST: Self = Self(8905); + pub const CLIENT_PICS_ACCESS_TOKEN_RESPONSE: Self = Self(8906); + pub const CLIENT_GET_DEPOT_DECRYPTION_KEY: Self = Self(5438); + pub const CLIENT_GET_DEPOT_DECRYPTION_KEY_RESPONSE: Self = Self(5439); + pub const SERVICE_METHOD: Self = Self(146); + pub const SERVICE_METHOD_CALL_FROM_CLIENT: Self = Self(151); + pub const SERVICE_METHOD_RESPONSE: Self = Self(147); + pub const SERVICE_METHOD_SEND_TO_CLIENT: Self = Self(152); + pub const SERVICE_METHOD_CALL_FROM_CLIENT_NON_AUTHED: Self = Self(9804); +} + +pub const EMSG_PROTO_FLAG: u32 = 0x8000_0000; +pub const EMSG_MASK: u32 = 0x7fff_ffff; + +pub const fn has_proto_flag(raw: u32) -> bool { + (raw & EMSG_PROTO_FLAG) != 0 +} + +pub const fn strip_proto_flag(raw: u32) -> EMsg { + EMsg(raw & EMSG_MASK) +} + +pub const fn with_proto_flag(msg: EMsg) -> u32 { + msg.0 | EMSG_PROTO_FLAG +} + +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +#[repr(u32)] +pub enum EUniverse { + #[default] + Invalid = 0, + Public = 1, + Beta = 2, + Internal = 3, + Dev = 4, + Max = 5, +} + +impl EUniverse { + pub fn from_u32(v: u32) -> Option { + match v { + 1 => Some(Self::Public), + 2 => Some(Self::Beta), + 3 => Some(Self::Internal), + 4 => Some(Self::Dev), + 5 => Some(Self::Max), + _ => None, + } + } + + pub fn is_valid_universe(self) -> bool { + matches!(self, Self::Public | Self::Beta | Self::Internal | Self::Dev) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn universe_values_match_steam_enum() { + assert_eq!(EUniverse::Invalid as u32, 0); + assert_eq!(EUniverse::Public as u32, 1); + assert_eq!(EUniverse::Beta as u32, 2); + assert_eq!(EUniverse::Internal as u32, 3); + assert_eq!(EUniverse::Dev as u32, 4); + assert_eq!(EUniverse::Max as u32, 5); + assert!(!EUniverse::Max.is_valid_universe()); + assert!(EUniverse::Public.is_valid_universe()); + } + + #[test] + fn free_license_emsgs_match_steamkit() { + // JavaSteam EMsg.java: ClientRequestFreeLicense(5572) / ...Response(5573). + assert_eq!(EMsg::CLIENT_REQUEST_FREE_LICENSE.0, 5572); + assert_eq!(EMsg::CLIENT_REQUEST_FREE_LICENSE_RESPONSE.0, 5573); + } +} diff --git a/app/src/main/rust/stores/src/steam/encrypted_channel.rs b/app/src/main/rust/stores/src/steam/encrypted_channel.rs new file mode 100644 index 0000000000..c88f676379 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/encrypted_channel.rs @@ -0,0 +1,472 @@ +use crate::steam::crypto::{ + aes256_cbc_decrypt, aes256_cbc_encrypt, aes256_ecb_decrypt_block, aes256_ecb_encrypt_block, + hmac_sha1, secure_random_bytes, AesBlock, SecureSessionKey, SessionKey, AES_BLOCK_BYTES, + HMAC_KEY_LENGTH, +}; +use crate::steam::transport::{Transport, TransportDisconnectReason}; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Mutex}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum ChannelState { + Disconnected, + Connected, + Challenged, + Encrypted, + Closing, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum ChannelDisconnectReason { + UserInitiated, + TransportError, + HandshakeProtocolError, + HandshakeFailed, + EnvelopeDecryptFailed, + HmacMismatch, +} + +type MessageCallback = Arc; +type ConnectedCallback = Arc; +type DisconnectedCallback = Arc; + +pub struct EncryptedChannel { + inner: Arc, + transport: Mutex>, +} + +struct EncryptedChannelInner { + state: AtomicU8, + on_message: Mutex>, + on_connected: Mutex>, + on_disconnected: Mutex>, +} + +impl Default for EncryptedChannelInner { + fn default() -> Self { + Self { + state: AtomicU8::new(ChannelState::Disconnected as u8), + on_message: Mutex::new(None), + on_connected: Mutex::new(None), + on_disconnected: Mutex::new(None), + } + } +} + +impl EncryptedChannel { + pub fn new(mut transport: Box) -> Self { + let inner = Arc::new(EncryptedChannelInner::default()); + + let weak = Arc::downgrade(&inner); + transport.set_on_connected(Box::new(move || { + if let Some(inner) = weak.upgrade() { + inner + .state + .store(ChannelState::Encrypted as u8, Ordering::Release); + let callback = inner + .on_connected + .lock() + .expect("encrypted channel callback poisoned") + .clone(); + if let Some(callback) = callback { + callback(); + } + } + })); + + let weak = Arc::downgrade(&inner); + transport.set_on_disconnected(Box::new(move |reason, detail| { + if let Some(inner) = weak.upgrade() { + inner + .state + .store(ChannelState::Disconnected as u8, Ordering::Release); + let reason = match reason { + TransportDisconnectReason::UserInitiated => { + ChannelDisconnectReason::UserInitiated + } + _ => ChannelDisconnectReason::TransportError, + }; + let callback = inner + .on_disconnected + .lock() + .expect("encrypted channel callback poisoned") + .clone(); + if let Some(callback) = callback { + callback(reason, detail); + } + } + })); + + let weak = Arc::downgrade(&inner); + transport.set_on_message(Box::new(move |bytes| { + if let Some(inner) = weak.upgrade() { + if inner.state() != ChannelState::Encrypted { + return; + } + let callback = inner + .on_message + .lock() + .expect("encrypted channel callback poisoned") + .clone(); + if let Some(callback) = callback { + callback(bytes); + } + } + })); + + Self { + inner, + transport: Mutex::new(transport), + } + } + + pub fn connect(&self, url: &str) -> bool { + if self + .inner + .state + .compare_exchange( + ChannelState::Disconnected as u8, + ChannelState::Connected as u8, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_err() + { + return false; + } + if !self + .transport + .lock() + .expect("encrypted channel transport poisoned") + .connect(url) + { + self.inner + .state + .store(ChannelState::Disconnected as u8, Ordering::Release); + return false; + } + true + } + + pub fn send(&self, plaintext: &[u8]) -> bool { + if self.state() != ChannelState::Encrypted { + return false; + } + self.transport + .lock() + .expect("encrypted channel transport poisoned") + .send(plaintext) + } + + pub fn disconnect(&self) { + if self.state() == ChannelState::Disconnected { + return; + } + self.inner + .state + .store(ChannelState::Closing as u8, Ordering::Release); + self.transport + .lock() + .expect("encrypted channel transport poisoned") + .disconnect(); + } + + pub fn state(&self) -> ChannelState { + self.inner.state() + } + + pub fn set_ca_bundle_path(&self, path: &str) { + self.transport + .lock() + .expect("encrypted channel transport poisoned") + .set_ca_bundle_path(path); + } + + pub fn set_on_message(&self, callback: F) + where + F: Fn(&[u8]) + Send + Sync + 'static, + { + *self + .inner + .on_message + .lock() + .expect("encrypted channel callback poisoned") = Some(Arc::new(callback)); + } + + pub fn set_on_connected(&self, callback: F) + where + F: Fn() + Send + Sync + 'static, + { + *self + .inner + .on_connected + .lock() + .expect("encrypted channel callback poisoned") = Some(Arc::new(callback)); + } + + pub fn set_on_disconnected(&self, callback: F) + where + F: Fn(ChannelDisconnectReason, &str) + Send + Sync + 'static, + { + *self + .inner + .on_disconnected + .lock() + .expect("encrypted channel callback poisoned") = Some(Arc::new(callback)); + } +} + +impl Drop for EncryptedChannel { + fn drop(&mut self) { + self.disconnect(); + } +} + +impl EncryptedChannelInner { + fn state(&self) -> ChannelState { + match self.state.load(Ordering::Acquire) { + 1 => ChannelState::Connected, + 2 => ChannelState::Challenged, + 3 => ChannelState::Encrypted, + 4 => ChannelState::Closing, + _ => ChannelState::Disconnected, + } + } +} + +#[derive(Clone)] +pub struct EncryptedEnvelope { + session_key: SecureSessionKey, + hmac_key: [u8; HMAC_KEY_LENGTH], +} + +impl EncryptedEnvelope { + pub fn new(session_key: SessionKey) -> Self { + let mut hmac_key = [0u8; HMAC_KEY_LENGTH]; + hmac_key.copy_from_slice(&session_key[..HMAC_KEY_LENGTH]); + Self { + session_key: SecureSessionKey::new(session_key), + hmac_key, + } + } + + pub fn encrypt(&self, plaintext: &[u8]) -> Option> { + let mut random_iv = [0u8; AES_BLOCK_BYTES - 4]; + if !secure_random_bytes(&mut random_iv) { + return None; + } + self.encrypt_with_random_iv(plaintext, random_iv) + } + + fn encrypt_with_random_iv( + &self, + plaintext: &[u8], + random_iv: [u8; AES_BLOCK_BYTES - 4], + ) -> Option> { + let mut hmac_input = Vec::with_capacity(random_iv.len() + plaintext.len()); + hmac_input.extend_from_slice(&random_iv); + hmac_input.extend_from_slice(plaintext); + let hmac = hmac_sha1(&self.hmac_key, &hmac_input)?; + + let mut iv_plaintext = [0u8; AES_BLOCK_BYTES]; + iv_plaintext[..4].copy_from_slice(&hmac[..4]); + iv_plaintext[4..].copy_from_slice(&random_iv); + + let iv_ciphertext = aes256_ecb_encrypt_block(&self.session_key.bytes, &iv_plaintext)?; + let body = aes256_cbc_encrypt(&self.session_key.bytes, &iv_plaintext, plaintext)?; + + let mut out = Vec::with_capacity(AES_BLOCK_BYTES + body.len()); + out.extend_from_slice(&iv_ciphertext); + out.extend_from_slice(&body); + Some(out) + } + + pub fn decrypt(&self, wire: &[u8]) -> Option> { + if wire.len() < AES_BLOCK_BYTES * 2 { + return None; + } + let iv_ciphertext: AesBlock = wire[..AES_BLOCK_BYTES].try_into().ok()?; + let iv_plaintext = aes256_ecb_decrypt_block(&self.session_key.bytes, &iv_ciphertext)?; + let plaintext = aes256_cbc_decrypt( + &self.session_key.bytes, + &iv_plaintext, + &wire[AES_BLOCK_BYTES..], + )?; + + let mut hmac_input = Vec::with_capacity((AES_BLOCK_BYTES - 4) + plaintext.len()); + hmac_input.extend_from_slice(&iv_plaintext[4..]); + hmac_input.extend_from_slice(&plaintext); + let expected = hmac_sha1(&self.hmac_key, &hmac_input)?; + ct_equal(&iv_plaintext[..4], &expected[..4]).then_some(plaintext) + } +} + +fn ct_equal(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (x, y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::transport::TransportState; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::mpsc; + + #[test] + fn envelope_roundtrips_with_fixed_iv() { + let key = [7u8; 32]; + let env = EncryptedEnvelope::new(key); + let encrypted = env + .encrypt_with_random_iv(b"hello steam", [3u8; AES_BLOCK_BYTES - 4]) + .unwrap(); + assert_ne!(encrypted, b"hello steam"); + assert_eq!(env.decrypt(&encrypted).unwrap(), b"hello steam"); + } + + #[test] + fn envelope_rejects_hmac_mismatch() { + let key = [7u8; 32]; + let env = EncryptedEnvelope::new(key); + let mut encrypted = env + .encrypt_with_random_iv(b"hello steam", [3u8; AES_BLOCK_BYTES - 4]) + .unwrap(); + // Change the HMAC prefix carried in the IV and re-encrypt it: the CBC padding stays valid, + // so only the HMAC check can refuse it. + let iv_ciphertext: AesBlock = encrypted[..AES_BLOCK_BYTES].try_into().unwrap(); + let mut iv = aes256_ecb_decrypt_block(&key, &iv_ciphertext).unwrap(); + iv[0] ^= 0x55; + assert!(aes256_cbc_decrypt(&key, &iv, &encrypted[AES_BLOCK_BYTES..]).is_some()); + encrypted[..AES_BLOCK_BYTES].copy_from_slice(&aes256_ecb_encrypt_block(&key, &iv).unwrap()); + assert!(env.decrypt(&encrypted).is_none()); + } + + #[test] + fn websocket_channel_skips_app_layer_handshake() { + let shared = Arc::new(MockTransportState::default()); + let channel = EncryptedChannel::new(Box::new(MockTransport { + shared: Arc::clone(&shared), + })); + let connected = Arc::new(AtomicBool::new(false)); + let connected_cb = Arc::clone(&connected); + let (tx, rx) = mpsc::channel(); + channel.set_on_connected(move || { + connected_cb.store(true, Ordering::SeqCst); + }); + channel.set_on_message(move |bytes| { + tx.send(bytes.to_vec()).unwrap(); + }); + + assert!(channel.connect("wss://cm.example.com:443/cmsocket/")); + assert_eq!(channel.state(), ChannelState::Connected); + shared.fire_connected(); + assert_eq!(channel.state(), ChannelState::Encrypted); + assert!(connected.load(Ordering::SeqCst)); + + assert!(channel.send(b"client hello")); + assert_eq!(shared.sent.lock().unwrap()[0], b"client hello"); + + shared.fire_message(b"server frame"); + assert_eq!(rx.recv().unwrap(), b"server frame"); + } + + #[test] + fn channel_maps_transport_disconnect_reasons() { + let shared = Arc::new(MockTransportState::default()); + let channel = EncryptedChannel::new(Box::new(MockTransport { + shared: Arc::clone(&shared), + })); + let (tx, rx) = mpsc::channel(); + channel.set_on_disconnected(move |reason, detail| { + tx.send((reason, detail.to_string())).unwrap(); + }); + assert!(channel.connect("wss://cm.example.com:443/cmsocket/")); + shared.fire_connected(); + shared.fire_disconnected(TransportDisconnectReason::NetworkError, "net down"); + assert_eq!( + rx.recv().unwrap(), + ( + ChannelDisconnectReason::TransportError, + "net down".to_string() + ) + ); + assert_eq!(channel.state(), ChannelState::Disconnected); + } + + #[derive(Default)] + struct MockTransportState { + connected: Mutex>, + disconnected: Mutex>, + message: Mutex>, + sent: Mutex>>, + ca_bundle_path: Mutex, + } + + impl MockTransportState { + fn fire_connected(&self) { + if let Some(callback) = self.connected.lock().unwrap().as_ref() { + callback(); + } + } + + fn fire_disconnected(&self, reason: TransportDisconnectReason, detail: &str) { + if let Some(callback) = self.disconnected.lock().unwrap().as_ref() { + callback(reason, detail); + } + } + + fn fire_message(&self, bytes: &[u8]) { + if let Some(callback) = self.message.lock().unwrap().as_ref() { + callback(bytes); + } + } + } + + struct MockTransport { + shared: Arc, + } + + impl Transport for MockTransport { + fn connect(&mut self, _url: &str) -> bool { + true + } + + fn send(&mut self, data: &[u8]) -> bool { + self.shared.sent.lock().unwrap().push(data.to_vec()); + true + } + + fn disconnect(&mut self) {} + + fn state(&self) -> TransportState { + TransportState::Connected + } + + fn set_on_message(&mut self, cb: Box) { + *self.shared.message.lock().unwrap() = Some(cb); + } + + fn set_on_connected(&mut self, cb: Box) { + *self.shared.connected.lock().unwrap() = Some(cb); + } + + fn set_on_disconnected( + &mut self, + cb: Box, + ) { + *self.shared.disconnected.lock().unwrap() = Some(cb); + } + + fn set_ca_bundle_path(&mut self, path: &str) { + *self.shared.ca_bundle_path.lock().unwrap() = path.to_string(); + } + } +} diff --git a/app/src/main/rust/stores/src/steam/handshake_messages.rs b/app/src/main/rust/stores/src/steam/handshake_messages.rs new file mode 100644 index 0000000000..14e59a556c --- /dev/null +++ b/app/src/main/rust/stores/src/steam/handshake_messages.rs @@ -0,0 +1,192 @@ +use crate::steam::emsg::{has_proto_flag, strip_proto_flag, EMsg, EUniverse}; +use crate::steam::wire_format; + +pub const INVALID_JOB_ID: u64 = u64::MAX; +pub const MSG_HDR_BYTES: usize = 20; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct MsgHdr { + pub msg: EMsg, + pub target_job_id: u64, + pub source_job_id: u64, +} + +impl Default for MsgHdr { + fn default() -> Self { + Self { + msg: EMsg::INVALID, + target_job_id: INVALID_JOB_ID, + source_job_id: INVALID_JOB_ID, + } + } +} + +impl MsgHdr { + pub fn serialize(&self, out: &mut Vec) { + let mut writer = wire_format::Writer::new(out); + writer.u32(self.msg.0); + writer.u64(self.target_job_id); + writer.u64(self.source_job_id); + } + + pub fn deserialize(input: &[u8]) -> Option<(Self, usize)> { + if input.len() < MSG_HDR_BYTES { + return None; + } + let mut reader = wire_format::Reader::new(&input[..MSG_HDR_BYTES]); + let raw_msg = reader.u32(); + if has_proto_flag(raw_msg) { + return None; + } + let hdr = Self { + msg: strip_proto_flag(raw_msg), + target_job_id: reader.u64(), + source_job_id: reader.u64(), + }; + reader.ok().then_some((hdr, MSG_HDR_BYTES)) + } +} + +pub const CHANNEL_ENCRYPT_PROTOCOL_VERSION: u32 = 1; +pub const CHANNEL_ENCRYPT_REQUEST_FIXED_BODY: usize = 8; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct MsgChannelEncryptRequest { + pub protocol_version: u32, + pub universe: EUniverse, + pub challenge: Vec, +} + +impl Default for MsgChannelEncryptRequest { + fn default() -> Self { + Self { + protocol_version: CHANNEL_ENCRYPT_PROTOCOL_VERSION, + universe: EUniverse::Invalid, + challenge: Vec::new(), + } + } +} + +impl MsgChannelEncryptRequest { + pub fn deserialize_body(body: &[u8]) -> Option { + if body.len() < CHANNEL_ENCRYPT_REQUEST_FIXED_BODY { + return None; + } + let mut reader = wire_format::Reader::new(body); + let protocol_version = reader.u32(); + let universe = EUniverse::from_u32(reader.u32())?; + if !reader.ok() { + return None; + } + let challenge = body[CHANNEL_ENCRYPT_REQUEST_FIXED_BODY..].to_vec(); + Some(Self { + protocol_version, + universe, + challenge, + }) + } +} + +pub const RSA_1024_CIPHER_BYTES: usize = 128; +pub const CHANNEL_ENCRYPT_RESPONSE_BODY_BYTES: usize = 144; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct MsgChannelEncryptResponse { + pub protocol_version: u32, + pub key_size: u32, + pub encrypted_handshake_blob: [u8; RSA_1024_CIPHER_BYTES], + pub key_crc: u32, + pub unknown_zero: u32, +} + +impl Default for MsgChannelEncryptResponse { + fn default() -> Self { + Self { + protocol_version: CHANNEL_ENCRYPT_PROTOCOL_VERSION, + key_size: RSA_1024_CIPHER_BYTES as u32, + encrypted_handshake_blob: [0; RSA_1024_CIPHER_BYTES], + key_crc: 0, + unknown_zero: 0, + } + } +} + +impl MsgChannelEncryptResponse { + pub fn serialize_body(&self, out: &mut Vec) { + let mut writer = wire_format::Writer::new(out); + writer.u32(self.protocol_version); + writer.u32(self.key_size); + writer.bytes(&self.encrypted_handshake_blob); + writer.u32(self.key_crc); + writer.u32(self.unknown_zero); + } +} + +pub const CHANNEL_ENCRYPT_RESULT_BODY_BYTES: usize = 4; + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct MsgChannelEncryptResult { + pub result: u32, +} + +impl MsgChannelEncryptResult { + pub fn deserialize_body(body: &[u8]) -> Option { + if body.len() < CHANNEL_ENCRYPT_RESULT_BODY_BYTES { + return None; + } + let mut reader = wire_format::Reader::new(body); + let result = reader.u32(); + reader.ok().then_some(Self { result }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::emsg::with_proto_flag; + + #[test] + fn msg_hdr_roundtrips_and_rejects_proto_flag() { + let hdr = MsgHdr { + msg: EMsg::CHANNEL_ENCRYPT_REQUEST, + target_job_id: 7, + source_job_id: 9, + }; + let mut bytes = Vec::new(); + hdr.serialize(&mut bytes); + assert_eq!(bytes.len(), MSG_HDR_BYTES); + assert_eq!(MsgHdr::deserialize(&bytes), Some((hdr, MSG_HDR_BYTES))); + + bytes[..4].copy_from_slice(&with_proto_flag(EMsg::CHANNEL_ENCRYPT_REQUEST).to_le_bytes()); + assert_eq!(MsgHdr::deserialize(&bytes), None); + } + + #[test] + fn channel_encrypt_request_parses_challenge() { + let mut body = Vec::new(); + let mut writer = wire_format::Writer::new(&mut body); + writer.u32(1); + writer.u32(EUniverse::Public as u32); + writer.bytes(&[0xaa; 16]); + let msg = MsgChannelEncryptRequest::deserialize_body(&body).unwrap(); + assert_eq!(msg.protocol_version, 1); + assert_eq!(msg.universe, EUniverse::Public); + assert_eq!(msg.challenge, vec![0xaa; 16]); + } + + #[test] + fn channel_encrypt_response_is_144_bytes() { + let msg = MsgChannelEncryptResponse { + key_crc: 0xfeed_beef, + ..Default::default() + }; + let mut body = Vec::new(); + msg.serialize_body(&mut body); + assert_eq!(body.len(), CHANNEL_ENCRYPT_RESPONSE_BODY_BYTES); + assert_eq!(&body[0..4], &1u32.to_le_bytes()); + assert_eq!( + &body[8 + RSA_1024_CIPHER_BYTES..12 + RSA_1024_CIPHER_BYTES], + &0xfeed_beefu32.to_le_bytes() + ); + } +} diff --git a/app/src/main/rust/stores/src/steam/heartbeat.rs b/app/src/main/rust/stores/src/steam/heartbeat.rs new file mode 100644 index 0000000000..58e3c4769a --- /dev/null +++ b/app/src/main/rust/stores/src/steam/heartbeat.rs @@ -0,0 +1,128 @@ +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; +use std::{panic, panic::AssertUnwindSafe}; + +#[derive(Default)] +pub struct Heartbeat { + running: Arc, + stop: Arc<(Mutex, Condvar)>, + worker: Option>, +} + +impl Heartbeat { + pub fn start(&mut self, interval: Duration, cb: F) -> bool + where + F: Fn() + Send + 'static, + { + if interval.is_zero() { + return false; + } + self.stop(); + self.running.store(true, Ordering::Relaxed); + { + let (mu, _) = &*self.stop; + *mu.lock().expect("heartbeat poisoned") = false; + } + let running = Arc::clone(&self.running); + let stop = Arc::clone(&self.stop); + self.worker = Some(thread::spawn(move || run_loop(interval, cb, running, stop))); + true + } + + pub fn stop(&mut self) { + if !self.running.load(Ordering::Relaxed) { + return; + } + let (mu, cv) = &*self.stop; + *mu.lock().expect("heartbeat poisoned") = true; + cv.notify_all(); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + self.running.store(false, Ordering::Relaxed); + } + + pub fn running(&self) -> bool { + self.running.load(Ordering::Relaxed) + } +} + +impl Drop for Heartbeat { + fn drop(&mut self) { + self.stop(); + } +} + +fn run_loop( + interval: Duration, + cb: F, + running: Arc, + stop: Arc<(Mutex, Condvar)>, +) where + F: Fn() + Send + 'static, +{ + let (mu, cv) = &*stop; + loop { + let guard = mu.lock().expect("heartbeat poisoned"); + let (guard, _) = cv + .wait_timeout_while(guard, interval, |stop_requested| !*stop_requested) + .expect("heartbeat poisoned"); + if *guard { + return; + } + drop(guard); + let _ = panic::catch_unwind(AssertUnwindSafe(&cb)); + if !running.load(Ordering::Relaxed) { + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[test] + fn rejects_zero_interval() { + let mut hb = Heartbeat::default(); + assert!(!hb.start(Duration::ZERO, || {})); + assert!(!hb.running()); + } + + #[test] + fn ticks_and_stops() { + let ticks = Arc::new(AtomicUsize::new(0)); + let tick_copy = Arc::clone(&ticks); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let mut hb = Heartbeat::default(); + assert!(hb.start(Duration::from_millis(10), move || { + tick_copy.fetch_add(1, Ordering::Relaxed); + let _ = tx.try_send(()); + })); + rx.recv_timeout(Duration::from_secs(5)).unwrap(); + hb.stop(); + assert!(ticks.load(Ordering::Relaxed) > 0); + assert!(!hb.running()); + } + + #[test] + fn callback_panic_does_not_stop_worker() { + let ticks = Arc::new(AtomicUsize::new(0)); + let tick_copy = Arc::clone(&ticks); + let (tx, rx) = std::sync::mpsc::channel(); + let mut hb = Heartbeat::default(); + assert!(hb.start(Duration::from_millis(10), move || { + let n = tick_copy.fetch_add(1, Ordering::Relaxed); + if n == 0 { + panic!("first heartbeat panic"); + } + tx.send(()).unwrap(); + })); + rx.recv_timeout(Duration::from_secs(1)).unwrap(); + hb.stop(); + assert!(ticks.load(Ordering::Relaxed) > 1); + } +} diff --git a/app/src/main/rust/stores/src/steam/http.rs b/app/src/main/rust/stores/src/steam/http.rs new file mode 100644 index 0000000000..722eb4e3ab --- /dev/null +++ b/app/src/main/rust/stores/src/steam/http.rs @@ -0,0 +1,79 @@ +//! One-shot HTTPS GET for the few non-chunk requests (CM directory, manifests, HTTP-delivered +//! appinfo). Chunk downloads go through the shared fetch core instead. + +use std::fs; +use std::time::Duration; + +pub const USER_AGENT: &str = crate::fetch_tuning::USER_AGENT; +/// Largest body kept from a successful response (the biggest depot manifests are tens of MB). +pub const MAX_BODY_BYTES: usize = 256 << 20; +/// Largest body kept from any other status; callers only use it for diagnostics. +const MAX_ERROR_BODY_BYTES: usize = 64 << 10; + +pub struct Response { + pub status: u16, + pub content_length: Option, + pub body: Vec, +} + +pub fn get(url: &str, timeout: Duration, ca_bundle_path: &str) -> Result { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|err| format!("runtime: {err}"))?; + runtime.block_on(get_async(url, timeout, ca_bundle_path)) +} + +async fn get_async(url: &str, timeout: Duration, ca_bundle_path: &str) -> Result { + let mut builder = reqwest::Client::builder() + .user_agent(USER_AGENT) + .connect_timeout(crate::fetch_tuning::connect_timeout()) + .timeout(timeout); + if !ca_bundle_path.is_empty() { + let pem = fs::read(ca_bundle_path).map_err(|err| format!("read CA bundle: {err}"))?; + let certs = reqwest::Certificate::from_pem_bundle(&pem) + .map_err(|err| format!("parse CA bundle: {err}"))?; + for cert in certs { + builder = builder.add_root_certificate(cert); + } + } + let client = builder + .build() + .map_err(|err| format!("http client: {err}"))?; + let response = client + .get(url) + .send() + .await + .map_err(|err| format!("http get: {}", err.without_url()))?; + let status = response.status().as_u16(); + let content_length = response.content_length(); + let limit = if status == 200 { + MAX_BODY_BYTES + } else { + MAX_ERROR_BODY_BYTES + }; + if status == 200 && content_length.is_some_and(|len| len > limit as u64) { + return Err(format!("http body: larger than {limit} bytes")); + } + let mut response = response; + let mut body = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|err| format!("http body: {}", err.without_url()))? + { + if body.len() + chunk.len() > limit { + if status == 200 { + return Err(format!("http body: larger than {limit} bytes")); + } + body.extend_from_slice(&chunk[..limit - body.len()]); + break; + } + body.extend_from_slice(&chunk); + } + Ok(Response { + status, + content_length, + body, + }) +} diff --git a/app/src/main/rust/stores/src/steam/install.rs b/app/src/main/rust/stores/src/steam/install.rs new file mode 100644 index 0000000000..5088ca591c --- /dev/null +++ b/app/src/main/rust/stores/src/steam/install.rs @@ -0,0 +1,467 @@ +//! One `nativeStart` run: plan, take over a half-finished client download, download the game's +//! depots into its library folder, install missing shared depots into their app's folder, then +//! register everything the way the Steam client does. The resume journal lives in the +//! caller-given journal directory and is removed once the game is registered. + +use crate::steam::depot_config::{app_journal_dir, DepotConfigStore}; +use crate::steam::depot_downloader::{download_prepared, prepare_depot, DepotError, PreparedDepot}; +use crate::steam::pb::ccontentserverdirectory::CContentServerDirectoryServerInfo; +use crate::steam::plan::AppPlan; +use crate::steam::register::{self, InstalledDepot, LibraryRoot, SharedInstall, Takeover}; +use crate::steam::session::Session; +use serde_json::{json, Value}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +pub const PHASE_PREPARING: &str = "preparing"; +pub const PHASE_DOWNLOADING: &str = "downloading"; +pub const PHASE_SHARED: &str = "shared"; +pub const PHASE_REGISTERING: &str = "registering"; +pub const DEFAULT_MAX_WORKERS: usize = 16; +const PROGRESS_INTERVAL: Duration = Duration::from_millis(250); + +pub struct StartRequest { + pub app_id: u32, + pub language: String, + pub steam_root: PathBuf, + pub game_library: LibraryRoot, + pub libraries: Vec, + pub journal_dir: PathBuf, + pub ca_bundle_path: String, + pub max_workers: usize, + pub process_workers: usize, +} + +/// Decode/write threads when the caller passes 0: half the cores, between 2 and 6. +pub fn default_process_workers() -> usize { + std::thread::available_parallelism() + .map(|n| n.get() / 2) + .unwrap_or(2) + .clamp(2, 6) +} + +pub trait Events: Sync { + fn progress(&self, done: u64, total: u64, phase: &str); +} + +/// The resume journal of one app in one library: depots finished in another library are not on this one. +fn journal_for(root: &std::path::Path, app_id: u32, library_guest: &str) -> PathBuf { + app_journal_dir(root, app_id).join(format!("{:08x}", crc32fast::hash(library_guest.trim_end_matches('/').as_bytes()))) +} + +fn fail(error: impl Into) -> Value { + json!({"ok": false, "error": error.into()}) +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// The app's plan with shared depots resolved. An app the account does not own is refused, +/// except a free one: `request_free_license` asks Steam for its license first (an install), else +/// it is planned as is (sizes for the UI). +pub fn build_plan( + session: &Session, + app_id: u32, + language: &str, + request_free_license: bool, +) -> Result { + let appinfo = session + .app_info(app_id) + .ok_or_else(|| "appinfo unavailable".to_string())?; + let mut library = session.library()?; + if !library.owns(app_id) { + if !crate::steam::plan::is_free(&appinfo) { + return Err("not_owned".to_string()); + } + if request_free_license { + if !session.request_free_license(app_id) { + return Err("free_license_refused".to_string()); + } + library = session.library()?; + if !library.owns(app_id) { + return Err("not_owned".to_string()); + } + } + } + // An app planned without its license (a free one, for sizes) has no granted depots to go by. + let owned_depots = library.owns(app_id).then_some(&library.owned_depots); + let mut plan = crate::steam::plan::plan_app( + app_id, + &appinfo, + &library.owned_apps, + owned_depots, + language, + )?; + crate::steam::plan::resolve_shared(&mut plan, &|from| session.app_info(from))?; + Ok(plan) +} + +struct Progress<'a> { + events: &'a dyn Events, + total: AtomicU64, + base: AtomicU64, + phase: Mutex<&'static str>, + last: Mutex, +} + +impl<'a> Progress<'a> { + fn new(events: &'a dyn Events) -> Self { + Self { + events, + total: AtomicU64::new(0), + base: AtomicU64::new(0), + phase: Mutex::new(PHASE_PREPARING), + last: Mutex::new(Instant::now() - PROGRESS_INTERVAL), + } + } + + fn phase(&self, phase: &'static str) { + *self.phase.lock().expect("phase poisoned") = phase; + self.emit(self.base.load(Ordering::Relaxed), true); + } + + fn emit(&self, done: u64, force: bool) { + { + let mut last = self.last.lock().expect("progress poisoned"); + if !force && last.elapsed() < PROGRESS_INTERVAL { + return; + } + *last = Instant::now(); + } + let phase = *self.phase.lock().expect("phase poisoned"); + let total = self.total.load(Ordering::Relaxed); + self.events.progress(done, total, phase); + } + + /// Progress inside one depot: `done` bytes of it on top of what earlier depots finished. + fn depot(&self, done: u64) { + self.emit(self.base.load(Ordering::Relaxed) + done, false); + } + + fn finish_depot(&self, bytes: u64) { + self.base.fetch_add(bytes, Ordering::Relaxed); + self.emit(self.base.load(Ordering::Relaxed), true); + } +} + +fn servers_for( + servers: &[CContentServerDirectoryServerInfo], + app_id: u32, +) -> Vec { + servers + .iter() + .filter(|s| s.allowed_app_ids.is_empty() || s.allowed_app_ids.contains(&app_id)) + .cloned() + .collect() +} + +pub fn run( + session: &Session, + req: &StartRequest, + cancel: &AtomicBool, + events: &dyn Events, +) -> Value { + let progress = Progress::new(events); + progress.phase(PHASE_PREPARING); + let log = |line: &str| crate::steam::log(line); + let cancelled = || cancel.load(Ordering::Relaxed); + + let plan = match build_plan(session, req.app_id, &req.language, true) { + Ok(plan) => plan, + Err(err) => return fail(err), + }; + if cancelled() { + return fail("cancelled"); + } + // Checked before takeover, which removes a half-finished client download's staging. + if !register::library_registered(&req.steam_root, &req.game_library.guest) { + return fail("library_not_in_libraryfolders"); + } + let adopted = register::adopt_staged(&req.game_library, req.app_id, &plan.install_dir); + if adopted > 0 { + log(&format!("adopted {adopted} file(s) the client had staged")); + } + let takeover = match register::takeover(&req.game_library, req.app_id, plan.build_id) { + Ok(t) => t, + Err(err) => return fail(format!("takeover: {err}")), + }; + log(&format!( + "start app={} build={} depots={} shared={} takeover={takeover:?}", + req.app_id, + plan.build_id, + plan.depots.len(), + plan.shared.len() + )); + let mut journal = + DepotConfigStore::load(journal_for(&req.journal_dir, req.app_id, &req.game_library.guest), plan.build_id); + if takeover == Takeover::AlreadyInstalled { + // A run that wrote the app manifest may have stopped before the library index: finish it. + match register::update_libraryfolders( + &req.steam_root, + &req.game_library.guest, + req.app_id, + true, + ) { + Ok(0) => return fail("library_not_in_libraryfolders"), + Ok(_) => {} + Err(err) => return fail(format!("libraryfolders: {err}")), + } + journal.discard(); + return json!({"ok": true, "alreadyInstalled": true}); + } + if takeover == Takeover::Update { + // Updates stay with the Steam client: it removes files a new build dropped. + return fail("update_in_steam"); + } + if takeover == Takeover::TookOver { + journal.discard(); + } + + let Some(all_servers) = session.cdn_servers() else { + return fail("CDN server request failed"); + }; + let game_servers = servers_for(&all_servers, req.app_id); + + let mut game_depots: Vec<(PreparedDepot, u32)> = Vec::new(); + for depot in &plan.depots { + match prepare_depot( + session, + &game_servers, + Some(&journal), + &req.ca_bundle_path, + req.app_id, + depot.depot_id, + depot.manifest_id, + cancel, + ) { + Ok(prepared) => game_depots.push((prepared, depot.dlc_app_id)), + Err(DepotError::AccessDenied(id)) if depot.dlc_app_id != 0 => { + log(&format!("skipping DLC depot {id}: access denied")); + } + Err(err) => return fail(err.message()), + } + } + + let mut shared_jobs: Vec<(PreparedDepot, SharedInstall)> = Vec::new(); + let mut shared_present: Vec<(u32, u32)> = Vec::new(); + let mut shared_present_libraries: Vec<(u32, register::LibraryRoot)> = Vec::new(); + for shared in &plan.shared { + let library = + register::shared_app_library(shared.from_app_id, &req.steam_root, &req.libraries); + let installed = crate::steam::kv::parse_file(&library.acf_path(shared.from_app_id)) + .and_then(|acf| register::installed_manifest(&acf, shared.depot_id)); + if installed == Some(shared.manifest_id) { + shared_present.push((shared.depot_id, shared.from_app_id)); + shared_present_libraries.push((shared.from_app_id, library)); + continue; + } + let servers = servers_for(&all_servers, shared.from_app_id); + let prepared = match prepare_depot( + session, + &servers, + Some(&journal), + &req.ca_bundle_path, + shared.from_app_id, + shared.depot_id, + shared.manifest_id, + cancel, + ) { + Ok(p) => p, + Err(DepotError::AccessDenied(id)) => { + log(&format!("skipping shared depot {id}: access denied")); + continue; + } + Err(err) => return fail(err.message()), + }; + let install = SharedInstall { + depot_id: shared.depot_id, + from_app_id: shared.from_app_id, + from_name: shared.from_name.clone(), + from_install_dir: shared.from_install_dir.clone(), + from_build_id: shared.from_build_id, + manifest_id: shared.manifest_id, + size: prepared.manifest.metadata.cb_disk_original.max(shared.size), + install_script: register::install_script_path(&prepared.manifest), + library, + }; + shared_jobs.push((prepared, install)); + } + + let depot_bytes = + |p: &PreparedDepot| crate::steam::depot_writer::depot_total_bytes(&p.manifest); + let total: u64 = game_depots.iter().map(|(p, _)| depot_bytes(p)).sum::() + + shared_jobs.iter().map(|(p, _)| depot_bytes(p)).sum::(); + progress.total.store(total, Ordering::Relaxed); + + let max_workers = if req.max_workers == 0 { + DEFAULT_MAX_WORKERS + } else { + req.max_workers + }; + let process_workers = if req.process_workers == 0 { + default_process_workers() + } else { + req.process_workers + }; + let ca = req.ca_bundle_path.as_str(); + + if let Err(err) = + register::write_started_acf(&req.game_library, &plan, session.steam_id, now_unix()) + { + return fail(format!("app manifest: {err}")); + } + progress.phase(PHASE_DOWNLOADING); + let game_dir = req.game_library.common_dir(&plan.install_dir); + for (prepared, _) in &game_depots { + if journal.is_installed(prepared.depot_id, prepared.manifest_id) { + progress.finish_depot(depot_bytes(prepared)); + continue; + } + if cancelled() { + return fail("cancelled"); + } + journal.begin_depot(prepared.depot_id); + let outcome = download_prepared( + prepared, + &game_servers, + &game_dir, + ca, + max_workers, + process_workers, + cancel, + &|done| progress.depot(done), + &log, + ); + if outcome.cancelled { + return fail("cancelled"); + } + if let Some(err) = outcome.error { + return fail(format!("depot {}: {err}", prepared.depot_id)); + } + journal.finish_depot(prepared.depot_id, prepared.manifest_id); + progress.finish_depot(depot_bytes(prepared)); + } + + progress.phase(PHASE_SHARED); + for (prepared, install) in &shared_jobs { + if cancelled() { + return fail("cancelled"); + } + let servers = servers_for(&all_servers, install.from_app_id); + let target = install.library.common_dir(&install.from_install_dir); + // The journal belongs to the game's library; a shared depot written to another library is + // checked on disk instead (only missing or wrong chunks are fetched). + let recorded = install.library.guest.trim_end_matches('/') + == req.game_library.guest.trim_end_matches('/') + && journal.is_installed(prepared.depot_id, prepared.manifest_id); + if !recorded { + journal.begin_depot(prepared.depot_id); + let outcome = download_prepared( + prepared, + &servers, + &target, + ca, + max_workers, + process_workers, + cancel, + &|done| progress.depot(done), + &log, + ); + if outcome.cancelled { + return fail("cancelled"); + } + if let Some(err) = outcome.error { + return fail(format!("shared depot {}: {err}", prepared.depot_id)); + } + journal.finish_depot(prepared.depot_id, prepared.manifest_id); + } + progress.finish_depot(depot_bytes(prepared)); + } + + progress.phase(PHASE_REGISTERING); + let now = now_unix(); + let owner = session.steam_id; + for (_, install) in &shared_jobs { + if let Err(err) = register::register_shared_depot(install, owner, now) { + return fail(format!("register shared depot: {err}")); + } + if let Err(err) = register::update_libraryfolders( + &req.steam_root, + &install.library.guest, + install.from_app_id, + true, + ) { + return fail(format!("libraryfolders: {err}")); + } + } + // A shared app already installed may still be missing from its library's index (an earlier + // run stopped between its manifest and the index); the update is idempotent. + for (from_app_id, library) in &shared_present_libraries { + if let Err(err) = + register::update_libraryfolders(&req.steam_root, &library.guest, *from_app_id, true) + { + return fail(format!("libraryfolders: {err}")); + } + } + let installed: Vec = game_depots + .iter() + .map(|(p, dlc)| InstalledDepot { + depot_id: p.depot_id, + manifest_id: p.manifest_id, + size: p.manifest.metadata.cb_disk_original, + dlc_app_id: *dlc, + }) + .collect(); + let scripts: Vec<(u32, String)> = game_depots + .iter() + .filter_map(|(p, _)| register::install_script_path(&p.manifest).map(|s| (p.depot_id, s))) + .collect(); + let mut shared_list: Vec<(u32, u32)> = shared_jobs + .iter() + .map(|(_, s)| (s.depot_id, s.from_app_id)) + .collect(); + shared_list.extend(shared_present); + shared_list.sort_unstable(); + let downloaded = game_depots + .iter() + .map(|(p, _)| p.manifest.metadata.cb_disk_compressed) + .sum::() + + shared_jobs + .iter() + .map(|(p, _)| p.manifest.metadata.cb_disk_compressed) + .sum::(); + let staged = installed.iter().map(|d| d.size).sum::() + + shared_jobs.iter().map(|(_, s)| s.size).sum::(); + let registration = register::GameRegistration { + plan: &plan, + owner_steam_id: owner, + depots: &installed, + shared: &shared_list, + install_scripts: &scripts, + bytes_downloaded: downloaded, + bytes_staged: staged, + now, + }; + if let Err(err) = register::write_game_acf(&req.game_library, ®istration) { + return fail(format!("app manifest: {err}")); + } + match register::update_libraryfolders(&req.steam_root, &req.game_library.guest, req.app_id, true) + { + Ok(0) => return fail("library_not_in_libraryfolders"), + Ok(_) => {} + Err(err) => return fail(format!("libraryfolders: {err}")), + } + journal.discard(); + progress.emit(total, true); + log(&format!( + "installed app={} build={} bytes={total} downloaded={downloaded}", + req.app_id, plan.build_id + )); + json!({"ok": true, "alreadyInstalled": false}) +} diff --git a/app/src/main/rust/stores/src/steam/jni.rs b/app/src/main/rust/stores/src/steam/jni.rs new file mode 100644 index 0000000000..0eeafb60f5 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/jni.rs @@ -0,0 +1,446 @@ +//! JNI surface of the Steam store: `com.droiddeck.launcher.stores.steam.SteamNative` +//! (see `JNI.md`). Every answer is a JSON object with `"ok"`; failures carry `"error"`. + +use crate::steam::install::{self, Events, StartRequest}; +use crate::steam::register::{self, LibraryRoot}; +use crate::steam::session; +use crate::steam::signin; +use jni::objects::{GlobalRef, JClass, JObject, JString, JValue}; +use jni::sys::{jint, jlong, jstring, JNI_FALSE, JNI_TRUE}; +use jni::{JNIEnv, JavaVM}; +use serde_json::{json, Value}; +use std::collections::HashSet; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; + +static RUNNING: Mutex>> = Mutex::new(None); + +fn jstring_to_string(env: &mut JNIEnv, value: &JString) -> String { + if value.is_null() { + return String::new(); + } + env.get_string(value) + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn answer(env: &mut JNIEnv, value: Value) -> jstring { + env.new_string(value.to_string()) + .map(|s| s.into_raw()) + .unwrap_or(std::ptr::null_mut()) +} + +fn error(message: impl Into) -> Value { + json!({"ok": false, "error": message.into()}) +} + +/// Runs `f`, turning a panic into an `internal_error` answer. +fn guarded(f: impl FnOnce() -> Value) -> Value { + catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|_| error("internal_error")) +} + +fn parse_string_array(text: &str) -> Vec { + serde_json::from_str::(text) + .ok() + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(PathBuf::from) + .collect() +} + +pub fn parse_library_roots(text: &str) -> Vec { + serde_json::from_str::(text) + .ok() + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|v| { + let host = v.get("host")?.as_str()?; + let guest = v.get("guest")?.as_str()?; + (!host.is_empty()).then(|| LibraryRoot { + host: PathBuf::from(host), + guest: guest.to_string(), + }) + }) + .collect() +} + +/// All libraries, with the game library first when the list misses it. +fn libraries_with(game: &LibraryRoot, mut libraries: Vec) -> Vec { + if !libraries.iter().any(|l| l.host == game.host) { + libraries.insert(0, game.clone()); + } + libraries +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeSignIn( + mut env: JNIEnv, + _class: JClass, + steam_roots_json: JString, + registry_vdf_path: JString, + ca_bundle_path: JString, +) -> jstring { + let roots = parse_string_array(&jstring_to_string(&mut env, &steam_roots_json)); + let registry = jstring_to_string(&mut env, ®istry_vdf_path); + let ca = jstring_to_string(&mut env, &ca_bundle_path); + let value = guarded(|| { + if let Some(live) = session::current() { + return json!({"ok": true, "account": live.account, "steamId": live.steam_id.to_string()}); + } + let registry = (!registry.is_empty()).then(|| Path::new(®istry)); + let login = match signin::load_saved_login(&roots, registry) { + Ok(login) => login, + Err(err) => { + crate::steam::log(&format!("sign-in: {}", err.code())); + return error(err.code()); + } + }; + match session::sign_in(&login, &ca) { + Ok(live) => { + json!({"ok": true, "account": live.account, "steamId": live.steam_id.to_string()}) + } + Err(err) => error(err), + } + }); + answer(&mut env, value) +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeSignOut( + _env: JNIEnv, + _class: JClass, +) { + let _ = catch_unwind(session::sign_out); +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeLibrary( + mut env: JNIEnv, + _class: JClass, +) -> jstring { + let value = guarded(|| { + let Some(live) = session::current() else { + return error("not_signed_in"); + }; + match live.games() { + Ok(games) => crate::steam::library::games_json(&games), + Err(err) => error(err), + } + }); + answer(&mut env, value) +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativePlan( + mut env: JNIEnv, + _class: JClass, + app_id: jint, + language: JString, +) -> jstring { + let language = jstring_to_string(&mut env, &language); + let value = guarded(|| { + let Some(live) = session::current() else { + return error("not_signed_in"); + }; + if app_id <= 0 { + return error("bad app id"); + } + match install::build_plan(&live, app_id as u32, &language, false) { + Ok(plan) => plan.to_json(), + Err(err) => error(err), + } + }); + answer(&mut env, value) +} + +pub struct SteamRunHandle { + pub cancel: Arc, +} + +struct JniEvents { + vm: JavaVM, + listener: GlobalRef, +} + +impl JniEvents { + fn with_env(&self, f: impl FnOnce(&mut JNIEnv)) { + let Ok(mut env) = self.vm.attach_current_thread_as_daemon() else { + return; + }; + f(&mut env); + if env.exception_check().unwrap_or(false) { + let _ = env.exception_clear(); + } + } + + fn complete(&self, result: &Value) { + let ok = result.get("ok").and_then(Value::as_bool).unwrap_or(false); + let text = result.to_string(); + self.with_env(|env| { + let Ok(text) = env.new_string(&text) else { + return; + }; + let text = JObject::from(text); + let _ = env.call_method( + self.listener.as_obj(), + "onComplete", + "(ZLjava/lang/String;)V", + &[ + JValue::Bool(if ok { JNI_TRUE } else { JNI_FALSE }), + JValue::Object(&text), + ], + ); + let _ = env.delete_local_ref(text); + }); + } +} + +impl Events for JniEvents { + fn progress(&self, done: u64, total: u64, phase: &str) { + self.with_env(|env| { + let Ok(phase) = env.new_string(phase) else { + return; + }; + let phase = JObject::from(phase); + let _ = env.call_method( + self.listener.as_obj(), + "onProgress", + "(JJLjava/lang/String;)V", + &[ + JValue::Long(done as jlong), + JValue::Long(total as jlong), + JValue::Object(&phase), + ], + ); + let _ = env.delete_local_ref(phase); + }); + } +} + +fn claim(app_id: u32) -> bool { + let mut guard = RUNNING.lock().expect("running poisoned"); + guard.get_or_insert_with(HashSet::new).insert(app_id) +} + +fn release_claim(app_id: u32) { + if let Some(set) = RUNNING.lock().expect("running poisoned").as_mut() { + set.remove(&app_id); + } +} + +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeStart( + mut env: JNIEnv, + _class: JClass, + app_id: jint, + language: JString, + steam_root: JString, + game_library_host: JString, + game_library_guest: JString, + library_roots_json: JString, + journal_dir: JString, + ca_bundle_path: JString, + max_workers: jint, + process_workers: jint, + listener: JObject, +) -> jlong { + if listener.is_null() || app_id <= 0 { + crate::steam::log("nativeStart: null listener or bad app id"); + return 0; + } + let Ok(vm) = env.get_java_vm() else { + return 0; + }; + let Ok(listener) = env.new_global_ref(&listener) else { + return 0; + }; + let game_library = LibraryRoot { + host: PathBuf::from(jstring_to_string(&mut env, &game_library_host)), + guest: jstring_to_string(&mut env, &game_library_guest), + }; + let libraries = parse_library_roots(&jstring_to_string(&mut env, &library_roots_json)); + let request = StartRequest { + app_id: app_id as u32, + language: jstring_to_string(&mut env, &language), + steam_root: PathBuf::from(jstring_to_string(&mut env, &steam_root)), + libraries: libraries_with(&game_library, libraries), + game_library, + journal_dir: PathBuf::from(jstring_to_string(&mut env, &journal_dir)), + ca_bundle_path: jstring_to_string(&mut env, &ca_bundle_path), + max_workers: max_workers.max(0) as usize, + process_workers: process_workers.max(0) as usize, + }; + if request.steam_root.as_os_str().is_empty() + || request.game_library.host.as_os_str().is_empty() + || request.game_library.guest.is_empty() + || request.journal_dir.as_os_str().is_empty() + { + crate::steam::log("nativeStart: empty path argument"); + return 0; + } + let cancel = Arc::new(AtomicBool::new(false)); + let handle = SteamRunHandle { + cancel: Arc::clone(&cancel), + }; + let spawned = thread::Builder::new() + .name("steam-dl".to_string()) + .spawn(move || { + crate::priority::background(); + let events = JniEvents { vm, listener }; + let result = if !claim(request.app_id) { + error("already_running") + } else { + let result = guarded(|| match session::current() { + Some(live) => install::run(&live, &request, &cancel, &events), + None => error("not_signed_in"), + }); + release_claim(request.app_id); + result + }; + crate::steam::log(&format!("run app={} result={result}", request.app_id)); + events.complete(&result); + }); + if spawned.is_err() { + crate::steam::log("nativeStart: worker thread spawn failed"); + return 0; + } + Box::into_raw(Box::new(handle)) as jlong +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeCancel( + _env: JNIEnv, + _class: JClass, + handle: jlong, +) { + let ptr = handle as *const SteamRunHandle; + if let Some(run) = unsafe { ptr.as_ref() } { + run.cancel.store(true, Ordering::Relaxed); + } +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeRelease( + _env: JNIEnv, + _class: JClass, + handle: jlong, +) { + let ptr = handle as *mut SteamRunHandle; + if !ptr.is_null() { + unsafe { drop(Box::from_raw(ptr)) }; + } +} + +/// The file list of a shared depot for uninstall: the client's `depotcache` copy of the manifest +/// (it stores decrypted file names), else the manifest from the CDN through the live session. +fn shared_depot_files( + steam_root: &Path, + from_app: u32, + depot_id: u32, + manifest_id: u64, +) -> Option> { + let cached = steam_root + .join("depotcache") + .join(format!("{depot_id}_{manifest_id}.manifest")); + if let Some(mut manifest) = std::fs::read(&cached) + .ok() + .and_then(|raw| crate::steam::content_manifest::ContentManifest::parse(&raw)) + { + if !manifest.metadata.filenames_encrypted && manifest.decrypt_filenames(&[]) { + return Some(register::manifest_file_list(&manifest)); + } + } + let live = session::current()?; + let servers = live.cdn_servers()?; + let ca = live.ca_bundle_path.clone(); + let prepared = crate::steam::depot_downloader::prepare_depot( + &live, + &servers, + None, + &ca, + from_app, + depot_id, + manifest_id, + &AtomicBool::new(false), + ) + .ok()?; + Some(register::manifest_file_list(&prepared.manifest)) +} + +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_steam_SteamNative_nativeUninstall( + mut env: JNIEnv, + _class: JClass, + app_id: jint, + steam_root: JString, + game_library_host: JString, + game_library_guest: JString, + library_roots_json: JString, +) -> jstring { + let steam_root = PathBuf::from(jstring_to_string(&mut env, &steam_root)); + let game_library = LibraryRoot { + host: PathBuf::from(jstring_to_string(&mut env, &game_library_host)), + guest: jstring_to_string(&mut env, &game_library_guest), + }; + let libraries = libraries_with( + &game_library, + parse_library_roots(&jstring_to_string(&mut env, &library_roots_json)), + ); + let value = guarded(|| { + if app_id <= 0 || steam_root.as_os_str().is_empty() { + return error("bad arguments"); + } + let root = steam_root.clone(); + let files = move |from_app: u32, depot: u32, manifest: u64| { + shared_depot_files(&root, from_app, depot, manifest) + }; + match register::uninstall( + app_id as u32, + &steam_root, + &game_library, + &libraries, + &files, + ) { + Ok(report) => json!({ + "ok": true, + "removedShared": report.removed_shared, + "keptShared": report.kept_shared, + }), + Err(err) => error(err), + } + }); + answer(&mut env, value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_library_roots_and_keeps_the_game_library() { + let libs = parse_library_roots( + r#"[{"host":"/data/Steam","guest":"/root/.local/share/Steam"},{"host":"","guest":"x"},{"guest":"y"}]"#, + ); + assert_eq!(libs.len(), 1); + let game = LibraryRoot { + host: "/sd/steam".into(), + guest: "/mnt/droiddeck-sd".into(), + }; + let all = libraries_with(&game, libs); + assert_eq!(all[0], game); + assert_eq!(all.len(), 2); + assert_eq!( + parse_string_array(r#"["/a", "", 3, "/b"]"#), + vec![PathBuf::from("/a"), PathBuf::from("/b")] + ); + assert!(parse_library_roots("not json").is_empty()); + } +} diff --git a/app/src/main/rust/stores/src/steam/job_manager.rs b/app/src/main/rust/stores/src/steam/job_manager.rs new file mode 100644 index 0000000000..8d6b4975fe --- /dev/null +++ b/app/src/main/rust/stores/src/steam/job_manager.rs @@ -0,0 +1,267 @@ +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use std::{panic, panic::AssertUnwindSafe}; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct JobResult { + pub eresult: i32, + pub error_message: String, + pub body: Vec, + pub synthetic_failure: bool, +} + +impl Default for JobResult { + fn default() -> Self { + Self { + eresult: 2, + error_message: String::new(), + body: Vec::new(), + synthetic_failure: false, + } + } +} + +type JobContinuation = Box; + +struct Entry { + cb: JobContinuation, + deadline: Instant, +} + +#[derive(Default)] +struct Pending { + jobs: HashMap, +} + +pub struct JobManager { + next_counter: AtomicU64, + process_epoch: u64, + default_timeout: Duration, + pending: Arc<(Mutex, Condvar)>, + stop: Arc, + timeout_thread: Option>, +} + +impl JobManager { + pub fn new(default_timeout: Duration) -> Self { + let pending = Arc::new((Mutex::new(Pending::default()), Condvar::new())); + let stop = Arc::new(AtomicBool::new(false)); + let thread_pending = Arc::clone(&pending); + let thread_stop = Arc::clone(&stop); + let timeout_thread = thread::spawn(move || timeout_loop(thread_pending, thread_stop)); + Self { + next_counter: AtomicU64::new(1), + process_epoch: make_process_epoch(), + default_timeout, + pending, + stop, + timeout_thread: Some(timeout_thread), + } + } + + pub fn next_job_id(&self) -> u64 { + let lo = self.next_counter.fetch_add(1, Ordering::Relaxed); + ((self.process_epoch & 0xFF_FFFF) << 40) | (lo & 0xFF_FFFF_FFFF) + } + + pub fn track(&self, job_id: u64, cb: F, timeout: Option) + where + F: FnOnce(JobResult) + Send + 'static, + { + let timeout = timeout.unwrap_or(self.default_timeout); + let (mu, cv) = &*self.pending; + let mut pending = mu.lock().expect("job manager poisoned"); + pending.jobs.insert( + job_id, + Entry { + cb: Box::new(cb), + deadline: Instant::now() + timeout, + }, + ); + cv.notify_all(); + } + + pub fn is_tracked(&self, job_id: u64) -> bool { + let (mu, _) = &*self.pending; + mu.lock() + .expect("job manager poisoned") + .jobs + .contains_key(&job_id) + } + + pub fn deliver( + &self, + job_id_target: u64, + mut eresult: i32, + error_message: String, + body: &[u8], + ) { + let cb = { + let (mu, _) = &*self.pending; + let mut pending = mu.lock().expect("job manager poisoned"); + pending.jobs.remove(&job_id_target).map(|entry| entry.cb) + }; + if let Some(cb) = cb { + if eresult == -1 { + eresult = 1; + } + invoke_continuation( + cb, + JobResult { + eresult, + error_message, + body: body.to_vec(), + synthetic_failure: false, + }, + ); + } + } + + pub fn fail_all(&self, reason: &str) { + let drained = { + let (mu, _) = &*self.pending; + let mut pending = mu.lock().expect("job manager poisoned"); + std::mem::take(&mut pending.jobs) + }; + for (_, entry) in drained { + invoke_continuation( + entry.cb, + JobResult { + eresult: -1, + error_message: reason.to_string(), + body: Vec::new(), + synthetic_failure: true, + }, + ); + } + } +} + +impl Default for JobManager { + fn default() -> Self { + Self::new(Duration::from_secs(30)) + } +} + +impl Drop for JobManager { + fn drop(&mut self) { + { + // Under the lock, so the worker cannot start waiting between the store and the notify. + let _guard = self.pending.0.lock().expect("job manager poisoned"); + self.stop.store(true, Ordering::Relaxed); + self.pending.1.notify_all(); + } + if let Some(handle) = self.timeout_thread.take() { + let _ = handle.join(); + } + self.fail_all("JobManager shutting down"); + } +} + +fn timeout_loop(pending: Arc<(Mutex, Condvar)>, stop: Arc) { + let (mu, cv) = &*pending; + loop { + let mut guard = mu.lock().expect("job manager poisoned"); + while guard.jobs.is_empty() && !stop.load(Ordering::Relaxed) { + guard = cv.wait(guard).expect("job manager poisoned"); + } + if stop.load(Ordering::Relaxed) { + return; + } + let earliest = guard + .jobs + .values() + .map(|entry| entry.deadline) + .min() + .unwrap_or_else(Instant::now); + let now = Instant::now(); + if earliest > now { + let (g, _) = cv + .wait_timeout(guard, earliest - now) + .expect("job manager poisoned"); + guard = g; + } + if stop.load(Ordering::Relaxed) { + return; + } + let now = Instant::now(); + let expired_ids: Vec = guard + .jobs + .iter() + .filter_map(|(id, entry)| (entry.deadline <= now).then_some(*id)) + .collect(); + let expired: Vec = expired_ids + .into_iter() + .filter_map(|id| guard.jobs.remove(&id)) + .collect(); + drop(guard); + for entry in expired { + invoke_continuation( + entry.cb, + JobResult { + eresult: -1, + error_message: "job timeout".to_string(), + body: Vec::new(), + synthetic_failure: true, + }, + ); + } + } +} + +fn invoke_continuation(cb: JobContinuation, result: JobResult) { + let _ = panic::catch_unwind(AssertUnwindSafe(|| cb(result))); +} + +fn make_process_epoch() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + #[test] + fn deliver_maps_missing_eresult_to_ok() { + let jm = JobManager::new(Duration::from_secs(30)); + let id = jm.next_job_id(); + let (tx, rx) = mpsc::channel(); + jm.track(id, move |result| tx.send(result).unwrap(), None); + jm.deliver(id, -1, String::new(), b"body"); + let result = rx.recv_timeout(Duration::from_secs(1)).unwrap(); + assert_eq!(result.eresult, 1); + assert_eq!(result.body, b"body"); + } + + #[test] + fn timeout_fails_jobs_synthetically() { + let jm = JobManager::new(Duration::from_millis(20)); + let id = jm.next_job_id(); + let (tx, rx) = mpsc::channel(); + jm.track(id, move |result| tx.send(result).unwrap(), None); + let result = rx.recv_timeout(Duration::from_secs(2)).unwrap(); + assert!(result.synthetic_failure); + assert_eq!(result.error_message, "job timeout"); + } + + #[test] + fn continuation_panic_is_caught() { + let jm = JobManager::new(Duration::from_secs(30)); + let id = jm.next_job_id(); + jm.track( + id, + |_| { + panic!("continuation panic"); + }, + None, + ); + jm.deliver(id, 1, String::new(), b"body"); + } +} diff --git a/app/src/main/rust/stores/src/steam/key_dictionary.rs b/app/src/main/rust/stores/src/steam/key_dictionary.rs new file mode 100644 index 0000000000..87fb030aab --- /dev/null +++ b/app/src/main/rust/stores/src/steam/key_dictionary.rs @@ -0,0 +1,91 @@ +use crate::steam::emsg::EUniverse; + +pub const PUBLIC_UNIVERSE_KEY: [u8; 160] = [ + 0x30, 0x81, 0x9D, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x03, 0x81, 0x8B, 0x00, 0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0xDF, 0xEC, 0x1A, + 0xD6, 0x2C, 0x10, 0x66, 0x2C, 0x17, 0x35, 0x3A, 0x14, 0xB0, 0x7C, 0x59, 0x11, 0x7F, 0x9D, 0xD3, + 0xD8, 0x2B, 0x7A, 0xE3, 0xE0, 0x15, 0xCD, 0x19, 0x1E, 0x46, 0xE8, 0x7B, 0x87, 0x74, 0xA2, 0x18, + 0x46, 0x31, 0xA9, 0x03, 0x14, 0x79, 0x82, 0x8E, 0xE9, 0x45, 0xA2, 0x49, 0x12, 0xA9, 0x23, 0x68, + 0x73, 0x89, 0xCF, 0x69, 0xA1, 0xB1, 0x61, 0x46, 0xBD, 0xC1, 0xBE, 0xBF, 0xD6, 0x01, 0x1B, 0xD8, + 0x81, 0xD4, 0xDC, 0x90, 0xFB, 0xFE, 0x4F, 0x52, 0x73, 0x66, 0xCB, 0x95, 0x70, 0xD7, 0xC5, 0x8E, + 0xBA, 0x1C, 0x7A, 0x33, 0x75, 0xA1, 0x62, 0x34, 0x46, 0xBB, 0x60, 0xB7, 0x80, 0x68, 0xFA, 0x13, + 0xA7, 0x7A, 0x8A, 0x37, 0x4B, 0x9E, 0xC6, 0xF4, 0x5D, 0x5F, 0x3A, 0x99, 0xF9, 0x9E, 0xC4, 0x3A, + 0xE9, 0x63, 0xA2, 0xBB, 0x88, 0x19, 0x28, 0xE0, 0xE7, 0x14, 0xC0, 0x42, 0x89, 0x02, 0x01, 0x11, +]; + +pub const BETA_UNIVERSE_KEY: [u8; 160] = [ + 0x30, 0x81, 0x9D, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x03, 0x81, 0x8B, 0x00, 0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0xAE, 0xD1, 0x4B, + 0xC0, 0xA3, 0x36, 0x8B, 0xA0, 0x39, 0x0B, 0x43, 0xDC, 0xED, 0x6A, 0xC8, 0xF2, 0xA3, 0xE4, 0x7E, + 0x09, 0x8C, 0x55, 0x2E, 0xE7, 0xE9, 0x3C, 0xBB, 0xE5, 0x5E, 0x0F, 0x18, 0x74, 0x54, 0x8F, 0xF3, + 0xBD, 0x56, 0x69, 0x5B, 0x13, 0x09, 0xAF, 0xC8, 0xBE, 0xB3, 0xA1, 0x48, 0x69, 0xE9, 0x83, 0x49, + 0x65, 0x8D, 0xD2, 0x93, 0x21, 0x2F, 0xB9, 0x1E, 0xFA, 0x74, 0x3B, 0x55, 0x22, 0x79, 0xBF, 0x85, + 0x18, 0xCB, 0x6D, 0x52, 0x44, 0x4E, 0x05, 0x92, 0x89, 0x6A, 0xA8, 0x99, 0xED, 0x44, 0xAE, 0xE2, + 0x66, 0x46, 0x42, 0x0C, 0xFB, 0x6E, 0x4C, 0x30, 0xC6, 0x6C, 0x5C, 0x16, 0xFF, 0xBA, 0x9C, 0xB9, + 0x78, 0x3F, 0x17, 0x4B, 0xCB, 0xC9, 0x01, 0x5D, 0x3E, 0x37, 0x70, 0xEC, 0x67, 0x5A, 0x33, 0x48, + 0xF7, 0x46, 0xCE, 0x58, 0xAA, 0xEC, 0xD9, 0xFF, 0x4A, 0x78, 0x6C, 0x83, 0x4B, 0x02, 0x01, 0x11, +]; + +pub const INTERNAL_UNIVERSE_KEY: [u8; 160] = [ + 0x30, 0x81, 0x9D, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x03, 0x81, 0x8B, 0x00, 0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0xA8, 0xFE, 0x01, + 0x3B, 0xB6, 0xD7, 0x21, 0x4B, 0x53, 0x23, 0x6F, 0xA1, 0xAB, 0x4E, 0xF1, 0x07, 0x30, 0xA7, 0xC6, + 0x7E, 0x6A, 0x2C, 0xC2, 0x5D, 0x3A, 0xB8, 0x40, 0xCA, 0x59, 0x4D, 0x16, 0x2D, 0x74, 0xEB, 0x0E, + 0x72, 0x46, 0x29, 0xF9, 0xDE, 0x9B, 0xCE, 0x4B, 0x8C, 0xD0, 0xCA, 0xF4, 0x08, 0x94, 0x46, 0xA5, + 0x11, 0xAF, 0x3A, 0xCB, 0xB8, 0x4E, 0xDE, 0xC6, 0xD8, 0x85, 0x0A, 0x7D, 0xAA, 0x96, 0x0A, 0xEA, + 0x7B, 0x51, 0xD6, 0x22, 0x62, 0x5C, 0x1E, 0x58, 0xD7, 0x46, 0x1E, 0x09, 0xAE, 0x43, 0xA7, 0xC4, + 0x34, 0x69, 0xA2, 0xA5, 0xE8, 0x44, 0x76, 0x18, 0xE2, 0x3D, 0xB7, 0xC5, 0xA8, 0x96, 0xFD, 0xE5, + 0xB4, 0x4B, 0xF8, 0x40, 0x12, 0xA6, 0x17, 0x4E, 0xC4, 0xC1, 0x60, 0x0E, 0xB0, 0xC2, 0xB8, 0x40, + 0x4D, 0x9E, 0x76, 0x4C, 0x44, 0xF4, 0xFC, 0x6F, 0x14, 0x89, 0x73, 0xB4, 0x13, 0x02, 0x01, 0x11, +]; + +pub const DEV_UNIVERSE_KEY: [u8; 160] = [ + 0x30, 0x81, 0x9D, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x03, 0x81, 0x8B, 0x00, 0x30, 0x81, 0x87, 0x02, 0x81, 0x81, 0x00, 0xD0, 0x05, 0x2C, + 0xE9, 0x80, 0x95, 0xCD, 0x30, 0x83, 0xA8, 0xE9, 0x25, 0x96, 0x63, 0xCE, 0xCC, 0x48, 0x5D, 0x5C, + 0x52, 0x00, 0xDB, 0x1E, 0x78, 0xD7, 0x6A, 0x4C, 0x2C, 0xC8, 0x41, 0x8C, 0xCC, 0x87, 0x46, 0xFB, + 0x1B, 0xC9, 0xE8, 0x6E, 0x4F, 0x7A, 0x6B, 0xC3, 0xE7, 0x0F, 0xD5, 0xA9, 0x5D, 0x6C, 0xD4, 0xEE, + 0xA2, 0xCC, 0x80, 0x5A, 0xD3, 0xCE, 0x53, 0x59, 0xE6, 0x80, 0x91, 0xC4, 0xC0, 0xD5, 0xF0, 0x63, + 0x23, 0x91, 0x69, 0x70, 0xC5, 0xBB, 0xBD, 0x05, 0xE2, 0x4F, 0x7D, 0x90, 0x12, 0xED, 0xAC, 0x4F, + 0x86, 0x96, 0x3C, 0x89, 0xCC, 0x92, 0x15, 0x63, 0xCB, 0x57, 0x70, 0xB9, 0xC3, 0xAE, 0x08, 0x4F, + 0xC8, 0x56, 0x16, 0xB0, 0x0C, 0xC6, 0xC8, 0x8A, 0x80, 0xD2, 0x37, 0xF7, 0x7F, 0xAB, 0x93, 0xBB, + 0xE6, 0xDE, 0x95, 0x78, 0xB8, 0x11, 0xC9, 0xE5, 0x62, 0xAD, 0xBC, 0x0C, 0x87, 0x02, 0x01, 0x11, +]; + +pub fn get_universe_public_key(universe: EUniverse) -> &'static [u8] { + match universe { + EUniverse::Public => &PUBLIC_UNIVERSE_KEY, + EUniverse::Beta => &BETA_UNIVERSE_KEY, + EUniverse::Internal => &INTERNAL_UNIVERSE_KEY, + EUniverse::Dev => &DEV_UNIVERSE_KEY, + EUniverse::Invalid | EUniverse::Max => &[], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn returns_keys_for_known_universes_only() { + assert_eq!(get_universe_public_key(EUniverse::Public).len(), 160); + assert_eq!(get_universe_public_key(EUniverse::Beta).len(), 160); + assert_eq!(get_universe_public_key(EUniverse::Internal).len(), 160); + assert_eq!(get_universe_public_key(EUniverse::Dev).len(), 160); + assert!(get_universe_public_key(EUniverse::Invalid).is_empty()); + } + + #[test] + fn keys_are_spki_rsa_with_exponent_17() { + for universe in [ + EUniverse::Public, + EUniverse::Beta, + EUniverse::Internal, + EUniverse::Dev, + ] { + let key = get_universe_public_key(universe); + assert_eq!(&key[..8], &[0x30, 0x81, 0x9D, 0x30, 0x0D, 0x06, 0x09, 0x2A]); + assert_eq!(&key[157..], &[0x02, 0x01, 0x11]); + } + } +} diff --git a/app/src/main/rust/stores/src/steam/kv.rs b/app/src/main/rust/stores/src/steam/kv.rs new file mode 100644 index 0000000000..22e313c75a --- /dev/null +++ b/app/src/main/rust/stores/src/steam/kv.rs @@ -0,0 +1,177 @@ +//! Valve KeyValues text files (`.acf`, `libraryfolders.vdf`) as the Steam client writes them: +//! `"key"\t\t"value"`, tab indentation, `{`/`}` on their own lines, LF line endings, `\` and `"` +//! escaped. Parsing reuses `vdf::parse_text`, which keeps the file's key order, so a rewrite only +//! changes the keys that were set. + +use crate::steam::vdf::{KVNode, KVValue}; +use std::fs; +use std::path::Path; + +pub fn parse_file(path: &Path) -> Option { + let bytes = fs::read(path).ok()?; + crate::steam::vdf::parse_text(&bytes) +} + +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + other => out.push(other), + } + } + out +} + +pub fn serialize(root: &KVNode) -> String { + let mut out = String::new(); + write_node(&mut out, root, 0); + out +} + +fn write_node(out: &mut String, node: &KVNode, depth: usize) { + let indent = "\t".repeat(depth); + if node.is_object() { + out.push_str(&format!("{indent}\"{}\"\n{indent}{{\n", escape(&node.name))); + for child in &node.children { + write_node(out, child, depth + 1); + } + out.push_str(&format!("{indent}}}\n")); + } else { + out.push_str(&format!( + "{indent}\"{}\"\t\t\"{}\"\n", + escape(&node.name), + escape(&node.as_string("")) + )); + } +} + +/// Writes `root` to `path` through a temp file in the same folder + rename. +pub fn write_file(path: &Path, root: &KVNode) -> Result<(), String> { + let text = serialize(root); + if crate::steam::depot_config::atomic_write_synced(path, text.as_bytes()) { + Ok(()) + } else { + Err(format!("write '{}' failed", path.display())) + } +} + +pub fn object(name: &str) -> KVNode { + KVNode::new(name) +} + +pub fn string(name: &str, value: impl Into) -> KVNode { + KVNode { + name: name.to_string(), + value: KVValue::String(value.into()), + children: Vec::new(), + } +} + +pub fn get<'a>(node: &'a KVNode, key: &str) -> Option<&'a KVNode> { + node.child(key) +} + +pub fn get_str(node: &KVNode, key: &str) -> Option { + node.child(key) + .filter(|c| !c.is_object()) + .map(|c| c.as_string("")) +} + +pub fn get_u64(node: &KVNode, key: &str) -> u64 { + get_str(node, key) + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0) +} + +pub fn get_mut<'a>(node: &'a mut KVNode, key: &str) -> Option<&'a mut KVNode> { + node.children + .iter_mut() + .find(|c| c.name.eq_ignore_ascii_case(key)) +} + +/// Sets `key` to a string value, in place when present (keeping its position and spelling), +/// appended otherwise. +pub fn set(node: &mut KVNode, key: &str, value: impl Into) { + let value = value.into(); + match get_mut(node, key) { + Some(child) => { + child.value = KVValue::String(value); + child.children.clear(); + } + None => node.children.push(string(key, value)), + } +} + +/// The object child `key`, created (appended) when missing. +pub fn object_mut<'a>(node: &'a mut KVNode, key: &str) -> &'a mut KVNode { + let idx = match node + .children + .iter() + .position(|c| c.name.eq_ignore_ascii_case(key)) + { + Some(idx) => { + if !node.children[idx].is_object() { + node.children[idx] = object(key); + } + idx + } + None => { + node.children.push(object(key)); + node.children.len() - 1 + } + }; + &mut node.children[idx] +} + +pub fn remove(node: &mut KVNode, key: &str) -> bool { + let before = node.children.len(); + node.children.retain(|c| !c.name.eq_ignore_ascii_case(key)); + before != node.children.len() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn writes_steam_layout_and_round_trips_escapes() { + let mut root = object("AppState"); + set(&mut root, "appid", "228980"); + let scripts = object_mut(&mut root, "InstallScripts"); + set( + scripts, + "228988", + "_CommonRedist\\vcredist\\2019\\installscript.vdf", + ); + object_mut(&mut root, "UserConfig"); + let text = serialize(&root); + assert_eq!( + text, + "\"AppState\"\n{\n\t\"appid\"\t\t\"228980\"\n\t\"InstallScripts\"\n\t{\n\t\t\"228988\"\t\t\"_CommonRedist\\\\vcredist\\\\2019\\\\installscript.vdf\"\n\t}\n\t\"UserConfig\"\n\t{\n\t}\n}\n" + ); + let parsed = crate::steam::vdf::parse_text(text.as_bytes()).unwrap(); + assert_eq!(parsed, root); + } + + #[test] + fn set_keeps_position_and_spelling_and_appends_new_keys() { + let mut root = crate::steam::vdf::parse_text( + b"\"AppState\"\n{\n\t\"Name\"\t\t\"a\"\n\t\"x\"\t\t\"1\"\n}\n", + ) + .unwrap(); + set(&mut root, "name", "b"); + set(&mut root, "y", "2"); + assert_eq!( + serialize(&root), + "\"AppState\"\n{\n\t\"Name\"\t\t\"b\"\n\t\"x\"\t\t\"1\"\n\t\"y\"\t\t\"2\"\n}\n" + ); + assert!(remove(&mut root, "X")); + assert!(!remove(&mut root, "x")); + assert_eq!(get_u64(&root, "y"), 2); + } +} diff --git a/app/src/main/rust/stores/src/steam/library.rs b/app/src/main/rust/stores/src/steam/library.rs new file mode 100644 index 0000000000..903c366c3b --- /dev/null +++ b/app/src/main/rust/stores/src/steam/library.rs @@ -0,0 +1,277 @@ +//! The signed-in account's library: licenses → packages (PICS) → apps (PICS, with access +//! tokens). Only apps of type `game` are listed. + +use crate::steam::pb::cmsg_client_pics::{PicsAppInfoReq, PicsPackageInfoReq}; +use crate::steam::session::Session; +use crate::steam::vdf::{self, KVNode}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; + +const PACKAGE_BATCH: usize = 200; +const APP_BATCH: usize = 100; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Game { + pub app_id: u32, + pub name: String, + pub install_dir: String, + pub app_type: String, + pub free: bool, +} + +#[derive(Clone, Debug, Default)] +pub struct Library { + /// Every app id the account's licenses grant (games, DLC, tools …). + pub owned_apps: HashSet, + /// Every depot id the account's licenses grant; the client installs no other depot of an app. + pub owned_depots: HashSet, + games: Option>, +} + +fn package_ids(buffer: &[u8], key: &str) -> Vec { + let Some((_id, root)) = vdf::parse_binary_package(buffer) else { + return Vec::new(); + }; + root.child(key) + .map(|node| { + node.children + .iter() + .map(|c| c.as_uint(0) as u32) + .filter(|id| *id != 0) + .collect() + }) + .unwrap_or_default() +} + +pub fn package_app_ids(buffer: &[u8]) -> Vec { + package_ids(buffer, "appids") +} + +pub fn package_depot_ids(buffer: &[u8]) -> Vec { + package_ids(buffer, "depotids") +} + +/// A library entry for an app, or `None` when it is not a game. +pub fn game_from_appinfo(app_id: u32, appinfo: &KVNode) -> Option { + let info = crate::steam::plan::appinfo_root(appinfo); + let app_type = crate::steam::plan::app_type(info); + if !app_type.eq_ignore_ascii_case("game") { + return None; + } + let name = crate::steam::plan::app_name(info); + if name.is_empty() { + return None; + } + Some(Game { + app_id, + name, + install_dir: crate::steam::plan::app_install_dir(info), + app_type: app_type.to_ascii_lowercase(), + free: crate::steam::plan::is_free(info), + }) +} + +pub fn sort_games(games: &mut [Game]) { + games.sort_by(|a, b| { + a.name + .to_lowercase() + .cmp(&b.name.to_lowercase()) + .then(a.app_id.cmp(&b.app_id)) + }); +} + +pub fn games_json(games: &[Game]) -> Value { + json!({ + "ok": true, + "games": games.iter().map(|g| json!({ + "appId": g.app_id, + "name": g.name, + "installDir": g.install_dir, + "type": g.app_type, + "free": g.free, + })).collect::>(), + }) +} + +impl Library { + /// Licenses → package PICS → owned app ids. Package 0 (the basic Steam license every account + /// has) is skipped. + pub fn load(session: &Session) -> Result { + let licenses = session + .core() + .license_list() + .ok_or_else(|| "no license list from Steam".to_string())?; + let mut tokens: HashMap = HashMap::new(); + for license in &licenses { + if license.package_id == 0 { + continue; + } + let entry = tokens.entry(license.package_id).or_insert(0); + if license.access_token != 0 { + *entry = license.access_token; + } + } + let mut package_ids: Vec = tokens.keys().copied().collect(); + package_ids.sort_unstable(); + let mut owned_apps = HashSet::new(); + let mut owned_depots = HashSet::new(); + // A package the CM left out of its answer (neither info nor unknown) is asked once more; + // ownership is not published while one is still unanswered. + let mut pending = package_ids.clone(); + for attempt in 0..2 { + let mut unanswered = Vec::new(); + for batch in pending.chunks(PACKAGE_BATCH) { + let request = batch + .iter() + .map(|id| PicsPackageInfoReq { + packageid: *id, + access_token: tokens.get(id).copied().unwrap_or(0), + }) + .collect(); + let response = session + .pics_product_info(request, Vec::new()) + .ok_or_else(|| "package info request failed".to_string())?; + let answered: HashSet = response + .packages + .iter() + .map(|p| p.packageid) + .chain(response.unknown_packageids.iter().copied()) + .collect(); + for package in &response.packages { + owned_apps.extend(package_app_ids(&package.buffer)); + owned_depots.extend(package_depot_ids(&package.buffer)); + } + unanswered.extend(batch.iter().copied().filter(|id| !answered.contains(id))); + } + pending = unanswered; + if pending.is_empty() { + break; + } + if attempt == 1 { + return Err(format!("package info incomplete ({} unanswered)", pending.len())); + } + } + crate::steam::log(&format!( + "library: licenses={} packages={} apps={}", + licenses.len(), + package_ids.len(), + owned_apps.len() + )); + Ok(Library { + owned_apps, + owned_depots, + games: None, + }) + } + + pub fn cached_games(&self) -> Option> { + self.games.clone() + } + + pub fn owns(&self, app_id: u32) -> bool { + self.owned_apps.contains(&app_id) + } + + /// App PICS for every owned app (access tokens first), filtered to games, sorted by name. + pub fn load_games(&self, session: &Session) -> Result, String> { + if let Some(games) = &self.games { + return Ok(games.clone()); + } + let mut app_ids: Vec = self.owned_apps.iter().copied().collect(); + app_ids.sort_unstable(); + let mut tokens: HashMap = HashMap::new(); + // A failed token batch is asked once more, then fails the load: without its tokens the + // apps would come back `missing_token` and be cached as non-games. + for batch in app_ids.chunks(APP_BATCH * 5) { + let response = session + .pics_access_tokens(Vec::new(), batch.to_vec()) + .or_else(|| session.pics_access_tokens(Vec::new(), batch.to_vec())) + .ok_or_else(|| "access token request failed".to_string())?; + for token in response.app_access_tokens { + tokens.insert(token.appid, token.access_token); + } + } + let mut games = Vec::new(); + // An app whose appinfo did not arrive (left out, or its HTTP delivery failed) is asked + // once more; it is not taken for a non-game while its metadata is missing. + let mut pending = app_ids; + for attempt in 0..2 { + let mut unresolved = Vec::new(); + for batch in pending.chunks(APP_BATCH) { + let request = batch + .iter() + .map(|id| PicsAppInfoReq { + appid: *id, + access_token: tokens.get(id).copied().unwrap_or(0), + only_public_obsolete: false, + }) + .collect(); + let response = session + .pics_product_info(Vec::new(), request) + .ok_or_else(|| "app info request failed".to_string())?; + let mut settled: HashSet = response.unknown_appids.iter().copied().collect(); + for app in &response.apps { + if app.buffer.is_empty() { + if app.missing_token { + settled.insert(app.appid); + } + continue; + } + settled.insert(app.appid); + let Some(root) = vdf::parse_auto(&app.buffer) else { + continue; + }; + if let Some(game) = game_from_appinfo(app.appid, &root) { + games.push(game); + } + } + unresolved.extend(batch.iter().copied().filter(|id| !settled.contains(id))); + } + pending = unresolved; + if pending.is_empty() { + break; + } + if attempt == 1 { + return Err(format!("app info incomplete ({} unresolved)", pending.len())); + } + } + sort_games(&mut games); + Ok(games) + } + + pub fn with_games(&self, games: Vec) -> Library { + Library { + owned_apps: self.owned_apps.clone(), + owned_depots: self.owned_depots.clone(), + games: Some(games), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_games_only_and_sorts_by_name() { + let parse = |t: &str| vdf::parse_text(t.as_bytes()).unwrap(); + let game = parse( + r#""appinfo" { "common" { "name" "brawlhalla" "type" "Game" "freetogame" "1" } "config" { "installdir" "Brawlhalla" } }"#, + ); + let tool = parse(r#""appinfo" { "common" { "name" "Proton" "type" "Tool" } }"#); + let other = parse(r#""appinfo" { "common" { "name" "Alpha" "type" "game" } }"#); + assert!(game_from_appinfo(5, &tool).is_none()); + let mut games = vec![ + game_from_appinfo(291550, &game).unwrap(), + game_from_appinfo(10, &other).unwrap(), + ]; + sort_games(&mut games); + assert_eq!(games[0].name, "Alpha"); + assert_eq!(games[1].install_dir, "Brawlhalla"); + assert!(games[1].free); + let json = games_json(&games); + assert_eq!(json["games"][1]["appId"], 291550); + assert_eq!(json["games"][1]["type"], "game"); + assert_eq!(json["games"][0]["free"], false); + } +} diff --git a/app/src/main/rust/stores/src/steam/mod.rs b/app/src/main/rust/stores/src/steam/mod.rs new file mode 100644 index 0000000000..d2701e078a --- /dev/null +++ b/app/src/main/rust/stores/src/steam/mod.rs @@ -0,0 +1,69 @@ +//! Steam store: signs in with the Linux Steam client's saved login, downloads a game straight into +//! the client's library folder and registers it the way the client does. Derived from WinNative's +//! wn-steam-client (GPL-3.0-or-later); see `NOTICE.md` in this directory. + +pub mod base64; +pub mod cdn; +pub mod cm_client; +pub mod cm_runtime; +pub mod cm_server; +pub mod cm_server_list; +pub mod cmsg_protobuf_header; +pub mod content_manifest; +pub mod crypto; +pub mod depot_chunk; +pub mod depot_config; +pub mod depot_downloader; +pub mod depot_writer; +pub mod emsg; +pub mod encrypted_channel; +pub mod handshake_messages; +pub mod heartbeat; +pub mod http; +pub mod install; +pub mod jni; +pub mod job_manager; +pub mod key_dictionary; +pub mod kv; +pub mod library; +pub mod pb; +pub mod plan; +pub mod proto_envelope; +pub mod proto_wire; +pub mod register; +pub mod session; +pub mod signin; +pub mod steam_directory; +pub mod transport; +pub mod vdf; +pub mod wire_format; +pub mod ws_connection; + +pub const LOG_TAG: &str = "DroidDeckSteam"; + +#[cfg(target_os = "android")] +#[link(name = "log")] +unsafe extern "C" { + fn __android_log_write(prio: i32, tag: *const i8, text: *const i8) -> i32; +} + +/// One line to logcat under [`LOG_TAG`]. Never pass a token or any other secret. +pub fn log(message: &str) { + #[cfg(target_os = "android")] + { + use std::ffi::CString; + let Ok(tag) = CString::new(LOG_TAG) else { + return; + }; + let Ok(text) = CString::new(message.replace('\0', " ")) else { + return; + }; + unsafe { + let _ = __android_log_write(4, tag.as_ptr().cast(), text.as_ptr().cast()); + } + } + #[cfg(not(target_os = "android"))] + { + let _ = message; + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/ccontentserverdirectory.rs b/app/src/main/rust/stores/src/steam/pb/ccontentserverdirectory.rs new file mode 100644 index 0000000000..68e99e80c0 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/ccontentserverdirectory.rs @@ -0,0 +1,217 @@ +use crate::steam::proto_wire::{Reader, WireType, Writer}; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CContentServerDirectoryGetManifestRequestCodeRequest { + pub app_id: u32, + pub depot_id: u32, + pub manifest_id: u64, + pub app_branch: String, + pub branch_password_hash: String, +} + +impl CContentServerDirectoryGetManifestRequestCodeRequest { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + w.uint32_field(1, self.app_id); + w.uint32_field(2, self.depot_id); + w.uint64_field(3, self.manifest_id); + w.string_field(4, &self.app_branch); + w.string_field(5, &self.branch_password_hash); + out + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct CContentServerDirectoryGetManifestRequestCodeResponse { + pub manifest_request_code: u64, +} + +impl CContentServerDirectoryGetManifestRequestCodeResponse { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.manifest_request_code = reader.u64()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CContentServerDirectoryServerInfo { + pub server_type: String, + pub source_id: i32, + pub cell_id: i32, + pub load: i32, + pub weighted_load: f32, + pub num_entries_in_client_list: i32, + pub steam_china_only: bool, + pub host: String, + pub vhost: String, + pub use_as_proxy: bool, + pub proxy_request_path_template: String, + pub https_support: String, + pub allowed_app_ids: Vec, + pub priority_class: u32, +} + +impl CContentServerDirectoryServerInfo { + pub fn use_https(&self) -> bool { + self.https_support.eq_ignore_ascii_case("mandatory") + } + + pub fn port(&self) -> u16 { + if self.use_https() { + 443 + } else { + 80 + } + } + + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.server_type = reader.string()?, + 2 => msg.source_id = reader.i32()?, + 3 => msg.cell_id = reader.i32()?, + 4 => msg.load = reader.i32()?, + 5 => msg.weighted_load = f32::from_bits(reader.fixed32()?), + 6 => msg.num_entries_in_client_list = reader.i32()?, + 7 => msg.steam_china_only = reader.boolean()?, + 8 => msg.host = reader.string()?, + 9 => msg.vhost = reader.string()?, + 10 => msg.use_as_proxy = reader.boolean()?, + 11 => msg.proxy_request_path_template = reader.string()?, + 12 => msg.https_support = reader.string()?, + 13 => match tag.wire_type { + WireType::LengthDelimited => { + let mut packed = Reader::new(reader.bytes()?); + while !packed.eof() { + msg.allowed_app_ids.push(packed.varint()? as u32); + } + } + WireType::Varint => msg.allowed_app_ids.push(reader.u32()?), + other => { + if !reader.skip(other) { + return None; + } + } + }, + 15 => msg.priority_class = reader.u32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct CContentServerDirectoryGetServersForSteamPipeRequest { + pub cell_id: u32, + pub max_servers: u32, +} + +impl Default for CContentServerDirectoryGetServersForSteamPipeRequest { + fn default() -> Self { + Self { + cell_id: 0, + max_servers: 20, + } + } +} + +impl CContentServerDirectoryGetServersForSteamPipeRequest { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + w.uint32_field(1, self.cell_id); + w.uint32_field_force(2, self.max_servers); + out + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CContentServerDirectoryGetServersForSteamPipeResponse { + pub servers: Vec, + pub no_change: bool, +} + +impl CContentServerDirectoryGetServersForSteamPipeResponse { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg + .servers + .push(CContentServerDirectoryServerInfo::deserialize( + reader.bytes()?, + )?), + 2 => msg.no_change = reader.boolean()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_server_info_with_packed_and_unpacked_app_ids() { + let mut server = Vec::new(); + { + let mut w = Writer::new(&mut server); + w.string_field(1, "SteamCache"); + w.int32_field(2, 5); + w.int32_field(3, 6); + w.int32_field(4, 7); + w.tag(5, WireType::Fixed32); + w.raw_bytes(&1.25f32.to_bits().to_le_bytes()); + w.bool_field(7, true); + w.string_field(8, "cache.example"); + w.string_field(12, "MANDATORY"); + w.uint32_field(13, 480); + let mut packed = Vec::new(); + Writer::new(&mut packed).varint(730); + w.bytes_field(13, &packed); + w.uint32_field(15, 2); + } + + let parsed = CContentServerDirectoryServerInfo::deserialize(&server).unwrap(); + assert_eq!(parsed.server_type, "SteamCache"); + assert_eq!(parsed.weighted_load, 1.25); + assert_eq!(parsed.allowed_app_ids, [480, 730]); + assert!(parsed.use_https()); + assert_eq!(parsed.port(), 443); + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/cmsg_client_get_depot_decryption_key.rs b/app/src/main/rust/stores/src/steam/pb/cmsg_client_get_depot_decryption_key.rs new file mode 100644 index 0000000000..4e16666a70 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/cmsg_client_get_depot_decryption_key.rs @@ -0,0 +1,79 @@ +use crate::steam::proto_wire::{Reader, WireType, Writer}; + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientGetDepotDecryptionKey { + pub depot_id: u32, + pub app_id: u32, +} + +impl CMsgClientGetDepotDecryptionKey { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + w.uint32_field(1, self.depot_id); + w.uint32_field(2, self.app_id); + out + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgClientGetDepotDecryptionKeyResponse { + pub eresult: i32, + pub depot_id: u32, + pub depot_encryption_key: Vec, +} + +impl Default for CMsgClientGetDepotDecryptionKeyResponse { + fn default() -> Self { + Self { + eresult: 2, + depot_id: 0, + depot_encryption_key: Vec::new(), + } + } +} + +impl CMsgClientGetDepotDecryptionKeyResponse { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match (tag.field_number, tag.wire_type) { + (1, WireType::Varint) => msg.eresult = reader.i32()?, + (2, WireType::Varint) => msg.depot_id = reader.u32()?, + (3, WireType::LengthDelimited) => { + msg.depot_encryption_key = reader.bytes()?.to_vec() + } + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_fields_only_with_their_wire_type() { + let mut ok = Vec::new(); + let mut w = Writer::new(&mut ok); + w.int32_field(1, 1); + w.uint32_field(2, 7); + w.bytes_field(3, &[9u8; 32]); + let r = CMsgClientGetDepotDecryptionKeyResponse::deserialize(&ok).unwrap(); + assert_eq!((r.eresult, r.depot_id, r.depot_encryption_key.len()), (1, 7, 32)); + // Field 1 as a length-delimited value is skipped, not read as the eresult. + let mismatched = [0x0a, 0x01, 0x01]; + let r = CMsgClientGetDepotDecryptionKeyResponse::deserialize(&mismatched).unwrap(); + assert_eq!(r.eresult, 2); + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/cmsg_client_license_list.rs b/app/src/main/rust/stores/src/steam/pb/cmsg_client_license_list.rs new file mode 100644 index 0000000000..616de9a117 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/cmsg_client_license_list.rs @@ -0,0 +1,143 @@ +use crate::steam::proto_wire::{Reader, WireType}; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct License { + pub package_id: u32, + pub time_created: u32, + pub time_next_process: u32, + pub minute_limit: i32, + pub minutes_used: i32, + pub payment_method: u32, + pub flags: u32, + pub purchase_country_code: String, + pub license_type: u32, + pub territory_code: i32, + pub change_number: i32, + pub owner_id: u32, + pub initial_period: u32, + pub initial_time_unit: u32, + pub renewal_period: u32, + pub renewal_time_unit: u32, + pub access_token: u64, + pub master_package_id: u32, +} + +impl License { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.package_id = reader.u32()?, + 2 => { + if tag.wire_type != WireType::Fixed32 { + return None; + } + msg.time_created = reader.fixed32()?; + } + 3 => { + if tag.wire_type != WireType::Fixed32 { + return None; + } + msg.time_next_process = reader.fixed32()?; + } + 4 => msg.minute_limit = reader.i32()?, + 5 => msg.minutes_used = reader.i32()?, + 6 => msg.payment_method = reader.u32()?, + 7 => msg.flags = reader.u32()?, + 8 => msg.purchase_country_code = reader.string()?, + 9 => msg.license_type = reader.u32()?, + 10 => msg.territory_code = reader.i32()?, + 11 => msg.change_number = reader.i32()?, + 12 => msg.owner_id = reader.u32()?, + 13 => msg.initial_period = reader.u32()?, + 14 => msg.initial_time_unit = reader.u32()?, + 15 => msg.renewal_period = reader.u32()?, + 16 => msg.renewal_time_unit = reader.u32()?, + 17 => msg.access_token = reader.u64()?, + 18 => msg.master_package_id = reader.u32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgClientLicenseList { + pub eresult: i32, + pub licenses: Vec, +} + +impl Default for CMsgClientLicenseList { + fn default() -> Self { + Self { + eresult: 2, + licenses: Vec::new(), + } + } +} + +impl CMsgClientLicenseList { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.eresult = reader.i32()?, + 2 => msg.licenses.push(License::deserialize(reader.bytes()?)?), + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::proto_wire::Writer; + + #[test] + fn parses_license_with_fixed_times_and_two_byte_tags() { + let mut lic = Vec::new(); + { + let mut w = Writer::new(&mut lic); + w.uint32_field(1, 123); + w.tag(2, WireType::Fixed32); + w.raw_bytes(&1000u32.to_le_bytes()); + w.tag(3, WireType::Fixed32); + w.raw_bytes(&2000u32.to_le_bytes()); + w.string_field(8, "US"); + w.uint32_field(16, 7); + w.uint64_field(17, 0x1234); + w.uint32_field(18, 456); + } + let mut body = Vec::new(); + { + let mut w = Writer::new(&mut body); + w.int32_field(1, 1); + w.submessage_field(2, &lic); + } + let parsed = CMsgClientLicenseList::deserialize(&body).unwrap(); + assert_eq!(parsed.eresult, 1); + assert_eq!(parsed.licenses[0].package_id, 123); + assert_eq!(parsed.licenses[0].time_created, 1000); + assert_eq!(parsed.licenses[0].renewal_time_unit, 7); + assert_eq!(parsed.licenses[0].master_package_id, 456); + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/cmsg_client_pics.rs b/app/src/main/rust/stores/src/steam/pb/cmsg_client_pics.rs new file mode 100644 index 0000000000..c0069fabc0 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/cmsg_client_pics.rs @@ -0,0 +1,432 @@ +use crate::steam::proto_wire::{Reader, WireType, Writer}; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientPICSAccessTokenRequest { + pub packageids: Vec, + pub appids: Vec, +} + +impl CMsgClientPICSAccessTokenRequest { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + for id in &self.packageids { + w.tag(1, WireType::Varint); + w.varint(*id as u64); + } + for id in &self.appids { + w.tag(2, WireType::Varint); + w.varint(*id as u64); + } + out + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PicsPackageToken { + pub packageid: u32, + pub access_token: u64, +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PicsAppToken { + pub appid: u32, + pub access_token: u64, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientPICSAccessTokenResponse { + pub package_access_tokens: Vec, + pub package_denied_tokens: Vec, + pub app_access_tokens: Vec, + pub app_denied_tokens: Vec, +} + +impl CMsgClientPICSAccessTokenResponse { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg + .package_access_tokens + .push(parse_package_token(reader.bytes()?)?), + 2 => read_repeated_uint32( + &mut reader, + tag.wire_type, + &mut msg.package_denied_tokens, + )?, + 3 => msg + .app_access_tokens + .push(parse_app_token(reader.bytes()?)?), + 4 => read_repeated_uint32(&mut reader, tag.wire_type, &mut msg.app_denied_tokens)?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PicsAppInfoReq { + pub appid: u32, + pub access_token: u64, + pub only_public_obsolete: bool, +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PicsPackageInfoReq { + pub packageid: u32, + pub access_token: u64, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientPICSProductInfoRequest { + pub packages: Vec, + pub apps: Vec, + pub meta_data_only: bool, + pub num_prev_failed: u32, + pub sequence_number: u32, + pub single_response: bool, +} + +impl CMsgClientPICSProductInfoRequest { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + for package in &self.packages { + let mut sub = Vec::new(); + let mut sw = Writer::new(&mut sub); + sw.uint32_field(1, package.packageid); + sw.uint64_field(2, package.access_token); + w.submessage_field(1, &sub); + } + for app in &self.apps { + let mut sub = Vec::new(); + let mut sw = Writer::new(&mut sub); + sw.uint32_field(1, app.appid); + sw.uint64_field(2, app.access_token); + sw.bool_field(3, app.only_public_obsolete); + w.submessage_field(2, &sub); + } + w.bool_field(3, self.meta_data_only); + w.uint32_field(4, self.num_prev_failed); + w.uint32_field(6, self.sequence_number); + w.bool_field(7, self.single_response); + out + } +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct PicsAppInfoResp { + pub appid: u32, + pub change_number: u32, + pub missing_token: bool, + pub sha: Vec, + pub buffer: Vec, + pub only_public: bool, + pub size: u32, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct PicsPackageInfoResp { + pub packageid: u32, + pub change_number: u32, + pub missing_token: bool, + pub sha: Vec, + pub buffer: Vec, + pub size: u32, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientPICSProductInfoResponse { + pub apps: Vec, + pub unknown_appids: Vec, + pub packages: Vec, + pub unknown_packageids: Vec, + pub meta_data_only: bool, + pub response_pending: bool, + pub http_min_size: u32, + pub http_host: String, +} + +impl CMsgClientPICSProductInfoResponse { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.apps.push(parse_app_info_resp(reader.bytes()?)?), + 2 => read_repeated_uint32(&mut reader, tag.wire_type, &mut msg.unknown_appids)?, + 3 => msg.packages.push(parse_package_info_resp(reader.bytes()?)?), + 4 => read_repeated_uint32(&mut reader, tag.wire_type, &mut msg.unknown_packageids)?, + 5 => msg.meta_data_only = reader.boolean()?, + 6 => msg.response_pending = reader.boolean()?, + 7 => msg.http_min_size = reader.u32()?, + 8 => msg.http_host = reader.string()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } + + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + for app in &self.apps { + w.submessage_field(1, &app.serialize()); + } + for appid in &self.unknown_appids { + w.uint32_field(2, *appid); + } + for package in &self.packages { + w.submessage_field(3, &package.serialize()); + } + for packageid in &self.unknown_packageids { + w.uint32_field(4, *packageid); + } + w.bool_field(5, self.meta_data_only); + w.bool_field(6, self.response_pending); + w.uint32_field(7, self.http_min_size); + w.string_field(8, &self.http_host); + out + } +} + +fn parse_package_token(body: &[u8]) -> Option { + let raw = parse_token(body)?; + Some(PicsPackageToken { + packageid: raw.id, + access_token: raw.access_token, + }) +} + +fn parse_app_token(body: &[u8]) -> Option { + let raw = parse_token(body)?; + Some(PicsAppToken { + appid: raw.id, + access_token: raw.access_token, + }) +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct TokenRaw { + id: u32, + access_token: u64, +} + +fn parse_token(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = TokenRaw::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.id = reader.u32()?, + 2 => msg.access_token = reader.u64()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) +} + +fn parse_app_info_resp(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = PicsAppInfoResp::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.appid = reader.u32()?, + 2 => msg.change_number = reader.u32()?, + 3 => msg.missing_token = reader.boolean()?, + 4 => msg.sha = reader.bytes()?.to_vec(), + 5 => msg.buffer = reader.bytes()?.to_vec(), + 6 => msg.only_public = reader.boolean()?, + 7 => msg.size = reader.u32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) +} + +impl PicsAppInfoResp { + fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + w.uint32_field(1, self.appid); + w.uint32_field(2, self.change_number); + w.bool_field(3, self.missing_token); + w.bytes_field(4, &self.sha); + w.bytes_field(5, &self.buffer); + w.bool_field(6, self.only_public); + w.uint32_field(7, self.size); + out + } +} + +fn parse_package_info_resp(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = PicsPackageInfoResp::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.packageid = reader.u32()?, + 2 => msg.change_number = reader.u32()?, + 3 => msg.missing_token = reader.boolean()?, + 4 => msg.sha = reader.bytes()?.to_vec(), + 5 => msg.buffer = reader.bytes()?.to_vec(), + 6 => msg.size = reader.u32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) +} + +impl PicsPackageInfoResp { + fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + w.uint32_field(1, self.packageid); + w.uint32_field(2, self.change_number); + w.bool_field(3, self.missing_token); + w.bytes_field(4, &self.sha); + w.bytes_field(5, &self.buffer); + w.uint32_field(6, self.size); + out + } +} + +fn read_repeated_uint32( + reader: &mut Reader<'_>, + wire_type: WireType, + out: &mut Vec, +) -> Option<()> { + match wire_type { + WireType::Varint => out.push(reader.u32()?), + WireType::LengthDelimited => { + let mut packed = Reader::new(reader.bytes()?); + while !packed.eof() { + out.push(packed.varint()? as u32); + } + } + _ => return None, + } + Some(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn token_body(id: u32, token: u64) -> Vec { + let mut body = Vec::new(); + let mut w = Writer::new(&mut body); + w.uint32_field(1, id); + w.uint64_field(2, token); + body + } + + #[test] + fn parses_access_tokens_and_packed_denied_lists() { + let mut packed = Vec::new(); + { + let mut w = Writer::new(&mut packed); + w.varint(10); + w.varint(11); + } + + let mut body = Vec::new(); + { + let mut w = Writer::new(&mut body); + w.submessage_field(1, &token_body(100, 555)); + w.uint32_field(2, 9); + w.bytes_field(2, &packed); + w.submessage_field(3, &token_body(480, 777)); + w.uint32_field(4, 12); + } + + let parsed = CMsgClientPICSAccessTokenResponse::deserialize(&body).unwrap(); + assert_eq!(parsed.package_access_tokens[0].packageid, 100); + assert_eq!(parsed.package_denied_tokens, [9, 10, 11]); + assert_eq!(parsed.app_access_tokens[0].appid, 480); + assert_eq!(parsed.app_denied_tokens, [12]); + } + + #[test] + fn parses_product_info_response_without_stripping_package_prefix() { + let mut app = Vec::new(); + { + let mut w = Writer::new(&mut app); + w.uint32_field(1, 480); + w.uint32_field(2, 22); + w.bool_field(3, true); + w.bytes_field(4, &[1; 20]); + w.bytes_field(5, b"appvdf"); + w.bool_field(6, true); + w.uint32_field(7, 6); + } + + let mut package = Vec::new(); + { + let mut w = Writer::new(&mut package); + w.uint32_field(1, 100); + w.uint32_field(2, 33); + w.bytes_field(5, &[100, 0, 0, 0, b'v', b'd', b'f']); + w.uint32_field(6, 7); + } + + let mut packed_unknown = Vec::new(); + Writer::new(&mut packed_unknown).varint(888); + + let mut body = Vec::new(); + { + let mut w = Writer::new(&mut body); + w.submessage_field(1, &app); + w.uint32_field(2, 404); + w.submessage_field(3, &package); + w.bytes_field(4, &packed_unknown); + w.bool_field(6, true); + w.uint32_field(7, 1024); + w.string_field(8, "cdn.example"); + } + + let parsed = CMsgClientPICSProductInfoResponse::deserialize(&body).unwrap(); + assert_eq!(parsed.apps[0].appid, 480); + assert_eq!(parsed.unknown_appids, [404]); + assert_eq!(parsed.unknown_packageids, [888]); + assert_eq!(parsed.packages[0].buffer, [100, 0, 0, 0, b'v', b'd', b'f']); + assert!(parsed.response_pending); + assert_eq!(parsed.http_host, "cdn.example"); + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/cmsg_client_request_free_license.rs b/app/src/main/rust/stores/src/steam/pb/cmsg_client_request_free_license.rs new file mode 100644 index 0000000000..413e6ab28a --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/cmsg_client_request_free_license.rs @@ -0,0 +1,188 @@ +//! `CMsgClientRequestFreeLicense` / `...Response` (SteamKit +//! `steammessages_clientserver_2.proto`, EMsg 5572 / 5573) — the legitimate "add a free/F2P/demo +//! title to my library" grant. +//! +//! Field numbers and the EMsg pair are verified against the JavaSteam protobufs bundled with the +//! app (`SteammessagesClientserver2.java`, `EMsg.java`), and corroborated by the field-name +//! strings (`granted_packageids` / `granted_appids`) in the reference Rust Steam engine. +//! +//! Two details that a guess would have got wrong, both taken from the real definition: +//! * the request's `appids` is field **2**, not 1; +//! * the response's `eresult` carries an explicit proto2 `[default = 2]` (EResult.Fail), so an +//! absent field must read as *failure*, never as 0/Invalid and never as success. + +use crate::steam::proto_wire::{Reader, WireType, Writer}; + +/// Proto2 `[default = 2]` on `CMsgClientRequestFreeLicenseResponse.eresult` — EResult.Fail. +/// An omitted field means the grant did NOT happen. +pub const FREE_LICENSE_DEFAULT_ERESULT: i32 = 2; + +/// `CMsgClientRequestFreeLicense` (EMsg 5572): `repeated uint32 appids = 2;` +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientRequestFreeLicense { + pub appids: Vec, +} + +impl CMsgClientRequestFreeLicense { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + for appid in &self.appids { + // Field 2 (not 1). Force-emit so an appid of 0 still occupies a slot rather than + // silently shortening the request. + w.uint32_field_force(2, *appid); + } + out + } +} + +/// `CMsgClientRequestFreeLicenseResponse` (EMsg 5573): +/// `eresult = 1 [default = 2]`, `granted_packageids = 2`, `granted_appids = 3`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgClientRequestFreeLicenseResponse { + pub eresult: i32, + pub granted_packageids: Vec, + pub granted_appids: Vec, +} + +impl Default for CMsgClientRequestFreeLicenseResponse { + fn default() -> Self { + Self { + eresult: FREE_LICENSE_DEFAULT_ERESULT, + granted_packageids: Vec::new(), + granted_appids: Vec::new(), + } + } +} + +impl CMsgClientRequestFreeLicenseResponse { + /// True only when Steam reported EResult.OK *and* actually handed something over. + pub fn is_granted(&self) -> bool { + self.eresult == 1 && !(self.granted_packageids.is_empty() && self.granted_appids.is_empty()) + } + + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match (tag.field_number, tag.wire_type) { + (1, WireType::Varint) => msg.eresult = reader.i32()?, + // Repeated uint32 is unpacked in proto2, but accept a packed block too so a + // server-side encoding change cannot silently empty the grant list. + (2, WireType::Varint) => msg.granted_packageids.push(reader.u32()?), + (2, WireType::LengthDelimited) => { + read_packed_u32(reader.bytes()?, &mut msg.granted_packageids)? + } + (3, WireType::Varint) => msg.granted_appids.push(reader.u32()?), + (3, WireType::LengthDelimited) => { + read_packed_u32(reader.bytes()?, &mut msg.granted_appids)? + } + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +/// Drain a packed repeated-varint block into `out`. +fn read_packed_u32(block: &[u8], out: &mut Vec) -> Option<()> { + let mut reader = Reader::new(block); + while !reader.eof() { + out.push(reader.u32()?); + } + Some(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn request_puts_appids_on_field_two() { + let body = CMsgClientRequestFreeLicense { + appids: vec![440, 570], + } + .serialize(); + // tag = (2 << 3) | 0 = 0x10. Field 1 (0x08) would be the wrong-by-one guess. + assert_eq!(body[0], 0x10); + let mut expected = Vec::new(); + { + let mut w = Writer::new(&mut expected); + w.uint32_field_force(2, 440); + w.uint32_field_force(2, 570); + } + assert_eq!(body, expected); + } + + #[test] + fn absent_eresult_defaults_to_fail_not_success() { + // Proto2 [default = 2]: an empty body must NEVER read as granted. + let parsed = CMsgClientRequestFreeLicenseResponse::deserialize(&[]).unwrap(); + assert_eq!(parsed.eresult, FREE_LICENSE_DEFAULT_ERESULT); + assert_eq!(parsed.eresult, 2); + assert!(!parsed.is_granted()); + } + + #[test] + fn parses_unpacked_grant_response() { + let mut body = Vec::new(); + { + let mut w = Writer::new(&mut body); + w.int32_field(1, 1); + w.uint32_field_force(2, 303_386); + w.uint32_field_force(3, 440); + } + let parsed = CMsgClientRequestFreeLicenseResponse::deserialize(&body).unwrap(); + assert_eq!(parsed.eresult, 1); + assert_eq!(parsed.granted_packageids, vec![303_386]); + assert_eq!(parsed.granted_appids, vec![440]); + assert!(parsed.is_granted()); + } + + #[test] + fn parses_packed_grant_response() { + let mut packed_packages = Vec::new(); + { + let mut w = Writer::new(&mut packed_packages); + w.varint(100); + w.varint(300); + } + let mut body = Vec::new(); + { + let mut w = Writer::new(&mut body); + w.int32_field(1, 1); + w.submessage_field(2, &packed_packages); + } + let parsed = CMsgClientRequestFreeLicenseResponse::deserialize(&body).unwrap(); + assert_eq!(parsed.granted_packageids, vec![100, 300]); + } + + #[test] + fn ok_with_no_grant_is_not_a_grant() { + // eresult OK but nothing handed over: must not be reported as success. + let mut body = Vec::new(); + Writer::new(&mut body).int32_field(1, 1); + let parsed = CMsgClientRequestFreeLicenseResponse::deserialize(&body).unwrap(); + assert_eq!(parsed.eresult, 1); + assert!(!parsed.is_granted()); + } + + #[test] + fn failure_eresult_is_preserved_verbatim() { + // A paid/unowned title comes back with a non-OK EResult; surface it, don't flatten it. + for eresult in [2, 8, 15, 16] { + let mut body = Vec::new(); + Writer::new(&mut body).int32_field(1, eresult); + let parsed = CMsgClientRequestFreeLicenseResponse::deserialize(&body).unwrap(); + assert_eq!(parsed.eresult, eresult); + assert!(!parsed.is_granted()); + } + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/cmsg_clientserver_login.rs b/app/src/main/rust/stores/src/steam/pb/cmsg_clientserver_login.rs new file mode 100644 index 0000000000..ae1db1cf91 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/cmsg_clientserver_login.rs @@ -0,0 +1,286 @@ +use crate::steam::proto_wire::{Reader, WireType, Writer}; + +pub const MSG_CLIENT_CURRENT_PROTOCOL: u32 = 65_581; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgClientHello { + pub protocol_version: u32, +} + +impl Default for CMsgClientHello { + fn default() -> Self { + Self { + protocol_version: MSG_CLIENT_CURRENT_PROTOCOL, + } + } +} + +impl CMsgClientHello { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + Writer::new(&mut out).uint32_field(1, self.protocol_version); + out + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientHeartBeat { + pub send_reply: bool, +} + +impl CMsgClientHeartBeat { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + Writer::new(&mut out).bool_field(1, self.send_reply); + out + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct CMsgClientLogOff; + +impl CMsgClientLogOff { + pub fn serialize(&self) -> Vec { + Vec::new() + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct CMsgClientLoggedOff { + pub eresult: i32, +} + +impl Default for CMsgClientLoggedOff { + fn default() -> Self { + Self { eresult: 2 } + } +} + +impl CMsgClientLoggedOff { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.eresult = reader.i32()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgClientLogon { + pub protocol_version: u32, + pub cell_id: u32, + pub client_package_version: u32, + pub client_language: String, + pub client_os_type: u32, + pub should_remember_password: bool, + pub qos_level: u32, + pub client_supplied_steam_id: u64, + pub machine_id: Vec, + pub ui_mode: u32, + pub chat_mode: u32, + pub account_name: String, + pub machine_name: String, + pub client_instance_id: u64, + pub supports_rate_limit_response: bool, + pub access_token: String, + pub obfuscated_private_ip: u32, +} + +impl Default for CMsgClientLogon { + fn default() -> Self { + Self { + protocol_version: MSG_CLIENT_CURRENT_PROTOCOL, + cell_id: 0, + client_package_version: 1771, + client_language: "english".to_string(), + client_os_type: 16, + should_remember_password: true, + qos_level: 2, + client_supplied_steam_id: 0, + machine_id: Vec::new(), + ui_mode: 7, + chat_mode: 2, + account_name: String::new(), + machine_name: "DroidDeck".to_string(), + client_instance_id: 0, + supports_rate_limit_response: true, + access_token: String::new(), + obfuscated_private_ip: 0, + } + } +} + +impl CMsgClientLogon { + pub fn serialize(&self) -> Vec { + let mut out = Vec::new(); + let mut w = Writer::new(&mut out); + w.uint32_field(1, self.protocol_version); + w.uint32_field(3, self.cell_id); + w.uint32_field(5, self.client_package_version); + w.string_field(6, &self.client_language); + w.uint32_field(7, self.client_os_type); + w.bool_field(8, self.should_remember_password); + w.uint32_field(21, self.qos_level); + if self.client_supplied_steam_id != 0 { + w.tag(22, WireType::Fixed64); + w.raw_bytes(&self.client_supplied_steam_id.to_le_bytes()); + } + w.bytes_field(30, &self.machine_id); + if self.obfuscated_private_ip != 0 { + // The LoginID: deprecated_obfustucated_private_ip = 2 and + // obfuscated_private_ip = 11 (CMsgIPAddress { fixed32 v4 = 1 }). + w.uint32_field(2, self.obfuscated_private_ip); + let mut ip_msg = Vec::new(); + let mut ip = Writer::new(&mut ip_msg); + ip.tag(1, WireType::Fixed32); + ip.raw_bytes(&self.obfuscated_private_ip.to_le_bytes()); + w.bytes_field(11, &ip_msg); + } + w.uint32_field(32, self.ui_mode); + w.uint32_field(33, self.chat_mode); + w.string_field(50, &self.account_name); + w.string_field(96, &self.machine_name); + w.uint64_field(100, self.client_instance_id); + w.bool_field(102, self.supports_rate_limit_response); + w.string_field(108, &self.access_token); + out + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CMsgClientLogonResponse { + pub eresult: i32, + pub heartbeat_seconds: i32, + pub rtime32_server_time: u32, + pub cell_id: u32, + pub eresult_extended: i32, + pub vanity_url: String, + pub client_supplied_steamid: u64, + pub client_instance_id: u64, + pub force_client_update_check: bool, + pub agreement_session_url: String, + pub token_id: u64, + pub family_group_id: u64, +} + +impl Default for CMsgClientLogonResponse { + fn default() -> Self { + Self { + eresult: 2, + heartbeat_seconds: 0, + rtime32_server_time: 0, + cell_id: 0, + eresult_extended: 0, + vanity_url: String::new(), + client_supplied_steamid: 0, + client_instance_id: 0, + force_client_update_check: false, + agreement_session_url: String::new(), + token_id: 0, + family_group_id: 0, + } + } +} + +impl CMsgClientLogonResponse { + pub fn deserialize(body: &[u8]) -> Option { + let mut reader = Reader::new(body); + let mut msg = Self::default(); + while !reader.eof() { + let Some(tag) = reader.next_tag() else { + return reader.ok().then_some(msg); + }; + match tag.field_number { + 1 => msg.eresult = reader.i32()?, + 3 => msg.heartbeat_seconds = reader.i32()?, + 5 => { + if tag.wire_type != WireType::Fixed32 { + return None; + } + msg.rtime32_server_time = reader.fixed32()?; + } + 7 => msg.cell_id = reader.u32()?, + 10 => msg.eresult_extended = reader.i32()?, + 14 => msg.vanity_url = reader.string()?, + 20 => { + if tag.wire_type != WireType::Fixed64 { + return None; + } + msg.client_supplied_steamid = reader.fixed64()?; + } + 27 => msg.client_instance_id = reader.u64()?, + 28 => msg.force_client_update_check = reader.boolean()?, + 29 => msg.agreement_session_url = reader.string()?, + 30 => msg.token_id = reader.u64()?, + 31 => msg.family_group_id = reader.u64()?, + _ => { + if !reader.skip(tag.wire_type) { + return None; + } + } + } + } + Some(msg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn logon_serializes_canonical_fields() { + let msg = CMsgClientLogon { + account_name: "user".to_string(), + access_token: "refresh.jwt".to_string(), + client_instance_id: 99, + obfuscated_private_ip: 0x0102_0304, + ..Default::default() + }; + let bytes = msg.serialize(); + let mut reader = Reader::new(&bytes); + let mut fields = Vec::new(); + let mut ip_message = Vec::new(); + while let Some(tag) = reader.next_tag() { + fields.push((tag.field_number, tag.wire_type)); + if tag.field_number == 11 { + ip_message = reader.bytes().unwrap().to_vec(); + } else { + reader.skip(tag.wire_type); + } + } + assert!(fields.contains(&(2, WireType::Varint))); + assert!(fields.contains(&(11, WireType::LengthDelimited))); + assert_eq!(ip_message, [0x0d, 0x04, 0x03, 0x02, 0x01]); + assert!(fields.contains(&(50, WireType::LengthDelimited))); + assert!(fields.contains(&(108, WireType::LengthDelimited))); + assert!(!fields.iter().any(|(f, _)| *f == 31 || *f == 95 || *f == 10)); + } + + #[test] + fn logon_response_reads_token_id_as_varint() { + let mut bytes = Vec::new(); + let mut w = Writer::new(&mut bytes); + w.int32_field(1, 1); + w.int32_field(3, 10); + w.tag(5, WireType::Fixed32); + w.raw_bytes(&123u32.to_le_bytes()); + w.uint64_field(30, 987); + let msg = CMsgClientLogonResponse::deserialize(&bytes).unwrap(); + assert_eq!(msg.eresult, 1); + assert_eq!(msg.rtime32_server_time, 123); + assert_eq!(msg.token_id, 987); + } +} diff --git a/app/src/main/rust/stores/src/steam/pb/mod.rs b/app/src/main/rust/stores/src/steam/pb/mod.rs new file mode 100644 index 0000000000..e514428e7a --- /dev/null +++ b/app/src/main/rust/stores/src/steam/pb/mod.rs @@ -0,0 +1,8 @@ +//! Hand-written protobuf messages for the CM requests the download store sends. + +pub mod ccontentserverdirectory; +pub mod cmsg_client_get_depot_decryption_key; +pub mod cmsg_client_license_list; +pub mod cmsg_client_pics; +pub mod cmsg_client_request_free_license; +pub mod cmsg_clientserver_login; diff --git a/app/src/main/rust/stores/src/steam/plan.rs b/app/src/main/rust/stores/src/steam/plan.rs new file mode 100644 index 0000000000..03628acecf --- /dev/null +++ b/app/src/main/rust/stores/src/steam/plan.rs @@ -0,0 +1,685 @@ +//! Which depots to install: what the Steam client picks for a Windows game run through Proton +//! (DroidDeck maps Proton globally), from the app's PICS appinfo. +//! +//! - `config.oslist` empty or containing `windows`; +//! - `config.osarch` empty or `64`; depots marked `32` only when the set has no `64` depot; +//! - `config.language` empty or the client language (english when the game has no depot for the +//! requested language but has english ones); +//! - `config.lowviolence` depots skipped; +//! - DLC depots (`dlcappid`) only when that DLC is owned; +//! - `depotfromapp` / `sharedinstall` depots are shared depots of another app (e.g. 228980 +//! Steamworks Common Redistributables) and go into that app's folder; +//! - the public branch's manifest gid, and the app's public `buildid`. + +use crate::steam::vdf::KVNode; +use serde_json::{json, Value}; +use std::collections::HashSet; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct PlannedDepot { + pub depot_id: u32, + pub manifest_id: u64, + pub size: u64, + pub download: u64, + pub dlc_app_id: u32, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct SharedRef { + pub depot_id: u32, + pub from_app_id: u32, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct SharedDepot { + pub depot_id: u32, + pub from_app_id: u32, + pub manifest_id: u64, + pub size: u64, + pub download: u64, + pub from_name: String, + pub from_install_dir: String, + pub from_build_id: u64, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct AppPlan { + pub app_id: u32, + pub name: String, + pub install_dir: String, + pub build_id: u64, + /// The language written to the app manifest (the requested one, or english, see above). + pub language: String, + /// The app ships a Linux build (`common.oslist`). The client installs it, not these Windows + /// depots, unless the game is mapped to a Proton; the caller checks that mapping. + pub linux_build: bool, + pub depots: Vec, + pub shared_refs: Vec, + pub shared: Vec, +} + +impl AppPlan { + pub fn install_bytes(&self) -> u64 { + self.depots.iter().map(|d| d.size).sum::() + + self.shared.iter().map(|d| d.size).sum::() + } + + pub fn download_bytes(&self) -> u64 { + self.depots.iter().map(|d| d.download).sum::() + + self.shared.iter().map(|d| d.download).sum::() + } + + pub fn to_json(&self) -> Value { + json!({ + "ok": true, + "appId": self.app_id, + "name": self.name, + "installDir": self.install_dir, + "buildId": self.build_id, + "language": self.language, + "linuxBuild": self.linux_build, + "downloadBytes": self.download_bytes(), + "installBytes": self.install_bytes(), + "depots": self.depots.iter().map(|d| json!({ + "depotId": d.depot_id, + "manifestId": d.manifest_id.to_string(), + "size": d.size, + "dlcAppId": d.dlc_app_id, + })).collect::>(), + "shared": self.shared.iter().map(|d| json!({ + "depotId": d.depot_id, + "fromAppId": d.from_app_id, + "manifestId": d.manifest_id.to_string(), + "size": d.size, + })).collect::>(), + }) + } +} + +/// `appinfo` as PICS delivers it: either the `appinfo` node itself or a root holding it. +pub fn appinfo_root(root: &KVNode) -> &KVNode { + if root.name.eq_ignore_ascii_case("appinfo") { + root + } else { + root.child("appinfo").unwrap_or(root) + } +} + +fn str_at(node: &KVNode, path: &[&str]) -> String { + let mut cur = node; + for key in path { + match cur.child(key) { + Some(next) => cur = next, + None => return String::new(), + } + } + if cur.is_object() { + String::new() + } else { + cur.as_string("") + } +} + +fn uint_at(node: &KVNode, path: &[&str]) -> u64 { + str_at(node, path).trim().parse().unwrap_or(0) +} + +pub fn app_name(appinfo: &KVNode) -> String { + str_at(appinfo, &["common", "name"]) +} + +pub fn app_type(appinfo: &KVNode) -> String { + str_at(appinfo, &["common", "type"]) +} + +pub fn app_install_dir(appinfo: &KVNode) -> String { + str_at(appinfo, &["config", "installdir"]) +} + +pub fn public_build_id(appinfo: &KVNode) -> u64 { + uint_at(appinfo, &["depots", "branches", "public", "buildid"]) +} + +/// Free to play / free app, as appinfo marks it. +pub fn is_free(appinfo: &KVNode) -> bool { + str_at(appinfo, &["common", "freetogame"]) == "1" + || str_at(appinfo, &["extended", "isfreeapp"]) == "1" +} + +/// Public manifest gid, size and download size of one depot entry (new layout +/// `manifests.public { gid size download }`, or the old `manifests.public ""` + `maxsize`). +pub fn public_manifest(depot: &KVNode) -> Option<(u64, u64, u64)> { + let public = depot.child("manifests")?.child("public")?; + if public.is_object() { + let gid = uint_at(public, &["gid"]); + if gid == 0 { + return None; + } + let size = uint_at(public, &["size"]); + let download = uint_at(public, &["download"]); + Some((gid, size, download)) + } else { + let gid = public.as_uint(0); + if gid == 0 { + return None; + } + Some((gid, uint_at(depot, &["maxsize"]), 0)) + } +} + +fn os_ok(config: Option<&KVNode>) -> bool { + let oslist = config.map(|c| str_at(c, &["oslist"])).unwrap_or_default(); + oslist.trim().is_empty() + || oslist + .split(',') + .any(|os| os.trim().eq_ignore_ascii_case("windows")) +} + +fn arch_of(config: Option<&KVNode>) -> String { + config + .map(|c| str_at(c, &["osarch"]).trim().to_string()) + .unwrap_or_default() +} + +fn language_of(config: Option<&KVNode>) -> String { + config + .map(|c| str_at(c, &["language"]).trim().to_ascii_lowercase()) + .unwrap_or_default() +} + +fn low_violence(config: Option<&KVNode>) -> bool { + config.is_some_and(|c| str_at(c, &["lowviolence"]) == "1") +} + +struct Candidate<'a> { + depot_id: u32, + node: &'a KVNode, + arch: String, + language: String, +} + +/// Applies the osarch preference and the language choice to a candidate set. +fn narrow<'a>(mut set: Vec>, language: &str) -> Vec> { + if set.iter().any(|c| c.arch == "64") { + set.retain(|c| c.arch != "32"); + } + set.retain(|c| c.arch.is_empty() || c.arch == "64" || c.arch == "32"); + set.retain(|c| c.language.is_empty() || c.language == language); + set +} + +/// The language to install: the requested one when the game has a depot for it (or has no +/// language-tagged depots at all), else english when the game has english depots. +pub fn effective_language(appinfo: &KVNode, requested: &str) -> String { + let requested = requested.trim().to_ascii_lowercase(); + let requested = if requested.is_empty() { + "english".to_string() + } else { + requested + }; + let Some(depots) = appinfo.child("depots") else { + return requested; + }; + let tags: HashSet = depots + .children + .iter() + .filter(|d| d.name.parse::().is_ok()) + .map(|d| language_of(d.child("config"))) + .filter(|l| !l.is_empty()) + .collect(); + language_from(&tags, requested) +} + +fn language_from(tags: &HashSet, requested: String) -> String { + if tags.is_empty() || tags.contains(&requested) || !tags.contains("english") { + requested + } else { + "english".to_string() + } +} + +/// Plans the app's own depots and lists the shared depots it references (resolved later with +/// [`resolve_shared`] from the owning apps' appinfo). +pub fn plan_app( + app_id: u32, + appinfo: &KVNode, + owned_apps: &HashSet, + owned_depots: Option<&HashSet>, + language: &str, +) -> Result { + let appinfo = appinfo_root(appinfo); + let mut plan = AppPlan { + app_id, + name: app_name(appinfo), + install_dir: app_install_dir(appinfo), + build_id: public_build_id(appinfo), + linux_build: str_at(appinfo, &["common", "oslist"]) + .split(',') + .any(|os| os.trim().eq_ignore_ascii_case("linux")), + ..Default::default() + }; + if plan.install_dir.is_empty() { + return Err("appinfo has no installdir".to_string()); + } + if !crate::steam::register::is_plain_name(&plan.install_dir) { + return Err("appinfo installdir is not a plain folder name".to_string()); + } + let Some(depots) = appinfo.child("depots") else { + return Err("appinfo has no depots".to_string()); + }; + + let mut own: Vec = Vec::new(); + let mut shared: Vec = Vec::new(); + for depot in &depots.children { + let Ok(depot_id) = depot.name.parse::() else { + continue; + }; + if !depot.is_object() { + continue; + } + let config = depot.child("config"); + if !os_ok(config) || low_violence(config) { + continue; + } + let dlc = uint_at(depot, &["dlcappid"]) as u32; + if dlc != 0 && !owned_apps.contains(&dlc) { + continue; + } + let from_app = uint_at(depot, &["depotfromapp"]) as u32; + let shared_install = str_at(depot, &["sharedinstall"]) == "1"; + let is_shared = from_app != 0 || shared_install; + if !is_shared && owned_depots.is_some_and(|owned| !owned.contains(&depot_id)) { + continue; + } + let candidate = Candidate { + depot_id, + node: depot, + arch: arch_of(config), + language: language_of(config), + }; + if is_shared { + shared.push(candidate); + } else if public_manifest(depot).is_some() { + // Only a depot with a public manifest can be installed, so only those take part in + // the language and architecture choice. + own.push(candidate); + } + } + + let requested = language.trim().to_ascii_lowercase(); + let requested = if requested.is_empty() { + "english".to_string() + } else { + requested + }; + let tags: HashSet = own + .iter() + .map(|c| c.language.clone()) + .filter(|l| !l.is_empty()) + .collect(); + let language = language_from(&tags, requested); + plan.language = language.clone(); + + for candidate in narrow(own, &language) { + let Some((manifest_id, size, download)) = public_manifest(candidate.node) else { + continue; + }; + plan.depots.push(PlannedDepot { + depot_id: candidate.depot_id, + manifest_id, + size, + download, + dlc_app_id: uint_at(candidate.node, &["dlcappid"]) as u32, + }); + } + for candidate in narrow(shared, &language) { + let from_app = uint_at(candidate.node, &["depotfromapp"]) as u32; + if from_app == 0 || from_app == app_id { + continue; + } + plan.shared_refs.push(SharedRef { + depot_id: candidate.depot_id, + from_app_id: from_app, + }); + } + if plan.depots.is_empty() { + // The client installs the Linux build of a game that has no Windows depot. + return Err(if plan.linux_build { + "linux_build".to_string() + } else { + "no installable Windows depot".to_string() + }); + } + Ok(plan) +} + +/// Fills [`AppPlan::shared`] from the owning apps' appinfo (`lookup(from_app_id)`); a shared +/// depot without a public manifest there is left out. Fails when an owning app's appinfo could +/// not be fetched, so a plan never goes ahead without a shared depot it may need. +pub fn resolve_shared( + plan: &mut AppPlan, + lookup: &dyn Fn(u32) -> Option, +) -> Result<(), String> { + plan.shared.clear(); + let mut cache: Vec<(u32, Option)> = Vec::new(); + for shared_ref in plan.shared_refs.clone() { + let pos = match cache + .iter() + .position(|(id, _)| *id == shared_ref.from_app_id) + { + Some(pos) => pos, + None => { + cache.push((shared_ref.from_app_id, lookup(shared_ref.from_app_id))); + cache.len() - 1 + } + }; + let Some(info) = cache[pos].1.as_ref() else { + return Err(format!( + "appinfo unavailable for shared app {}", + shared_ref.from_app_id + )); + }; + let info = appinfo_root(info); + let Some(depot) = info + .child("depots") + .and_then(|d| d.child(&shared_ref.depot_id.to_string())) + else { + continue; + }; + let Some((manifest_id, size, download)) = public_manifest(depot) else { + continue; + }; + let install_dir = app_install_dir(info); + if !crate::steam::register::is_plain_name(&install_dir) { + continue; + } + plan.shared.push(SharedDepot { + depot_id: shared_ref.depot_id, + from_app_id: shared_ref.from_app_id, + manifest_id, + size, + download, + from_name: app_name(info), + from_install_dir: install_dir, + from_build_id: public_build_id(info), + }); + } + Ok(()) +} + +#[cfg(test)] +pub mod tests { + use super::*; + + /// Shaped like Brawlhalla's (291550) appinfo. Depot 291551/228988 gids and sizes and the + /// build ids are the captured install's; `download` values and depots 291552-291556 are made + /// up for the selection rules. + pub const BRAWLHALLA: &str = r#""appinfo" +{ + "appid" "291550" + "common" + { + "name" "Brawlhalla" + "type" "Game" + "freetogame" "1" + } + "config" + { + "installdir" "Brawlhalla" + } + "depots" + { + "228988" + { + "config" + { + "oslist" "windows" + } + "depotfromapp" "228980" + "sharedinstall" "1" + } + "291551" + { + "config" + { + "oslist" "windows" + } + "manifests" + { + "public" + { + "gid" "4224536525702420323" + "size" "1565156559" + "download" "1521899507" + } + } + } + "291552" + { + "config" + { + "oslist" "macos" + } + "manifests" + { + "public" + { + "gid" "11" + "size" "5" + } + } + } + "291553" + { + "config" + { + "oslist" "windows" + "osarch" "32" + } + "manifests" + { + "public" + { + "gid" "12" + "size" "5" + } + } + } + "291554" + { + "config" + { + "oslist" "windows" + "osarch" "64" + "language" "german" + } + "manifests" + { + "public" + { + "gid" "13" + "size" "7" + } + } + } + "291555" + { + "config" + { + "lowviolence" "1" + } + "manifests" + { + "public" "14" + } + "maxsize" "9" + } + "291556" + { + "dlcappid" "291560" + "manifests" + { + "public" + { + "gid" "15" + "size" "3" + } + } + } + "branches" + { + "public" + { + "buildid" "26465982" + } + } + } +} +"#; + + pub const REDIST: &str = r#""appinfo" +{ + "appid" "228980" + "common" + { + "name" "Steamworks Common Redistributables" + "type" "Config" + } + "config" + { + "installdir" "Steamworks Shared" + } + "depots" + { + "228988" + { + "config" + { + "oslist" "windows" + } + "manifests" + { + "public" + { + "gid" "6645201662696499616" + "size" "29212173" + "download" "29212496" + } + } + } + "branches" + { + "public" + { + "buildid" "24098430" + } + } + } +} +"#; + + pub fn parse(text: &str) -> KVNode { + crate::steam::vdf::parse_text(text.as_bytes()).unwrap() + } + + #[test] + fn picks_windows_64bit_language_and_shared_depots_like_the_client() { + let info = parse(BRAWLHALLA); + let mut plan = plan_app(291550, &info, &HashSet::new(), None, "english").unwrap(); + assert_eq!(plan.name, "Brawlhalla"); + assert_eq!(plan.install_dir, "Brawlhalla"); + assert_eq!(plan.build_id, 26465982); + assert_eq!(plan.language, "english"); + let ids: Vec = plan.depots.iter().map(|d| d.depot_id).collect(); + // 291552 macOS, 291553 32-bit (a 64-bit depot exists), 291554 german, 291555 low + // violence and 291556 unowned DLC are all left out. + assert_eq!(ids, vec![291551]); + assert_eq!(plan.depots[0].manifest_id, 4224536525702420323); + assert_eq!(plan.depots[0].size, 1565156559); + assert_eq!( + plan.shared_refs, + vec![SharedRef { + depot_id: 228988, + from_app_id: 228980 + }] + ); + resolve_shared(&mut plan, &|app| (app == 228980).then(|| parse(REDIST))).unwrap(); + assert_eq!(plan.shared.len(), 1); + let shared = &plan.shared[0]; + assert_eq!(shared.manifest_id, 6645201662696499616); + assert_eq!(shared.size, 29212173); + assert_eq!(shared.from_install_dir, "Steamworks Shared"); + assert_eq!(shared.from_build_id, 24098430); + // BytesToStage of the captured install = game depot + shared depot. + assert_eq!(plan.install_bytes(), 1594368732); + let json = plan.to_json(); + assert_eq!(json["depots"][0]["manifestId"], "4224536525702420323"); + assert_eq!(json["shared"][0]["fromAppId"], 228980); + } + + #[test] + fn owned_dlc_german_and_32bit_fallback() { + let info = parse(BRAWLHALLA); + let owned: HashSet = [291560].into_iter().collect(); + let plan = plan_app(291550, &info, &owned, None, "german").unwrap(); + let ids: Vec = plan.depots.iter().map(|d| d.depot_id).collect(); + assert_eq!(ids, vec![291551, 291554, 291556]); + assert_eq!(plan.depots[2].dlc_app_id, 291560); + + let only32 = parse( + r#""appinfo" { "config" { "installdir" "X" } "depots" { "1" { "config" { "osarch" "32" } "manifests" { "public" "5" } "maxsize" "10" } } }"#, + ); + let plan = plan_app(1, &only32, &HashSet::new(), None, "english").unwrap(); + assert_eq!(plan.depots[0].depot_id, 1); + assert_eq!(plan.depots[0].manifest_id, 5); + assert_eq!(plan.depots[0].size, 10); + } + + #[test] + fn unsupported_language_falls_back_to_english_depots() { + let info = parse( + r#""appinfo" { "config" { "installdir" "X" } "depots" { + "1" { "manifests" { "public" { "gid" "1" "size" "1" } } } + "2" { "config" { "language" "english" } "manifests" { "public" { "gid" "2" "size" "1" } } } + "3" { "config" { "language" "german" } "manifests" { "public" { "gid" "3" "size" "1" } } } } }"#, + ); + let plan = plan_app(9, &info, &HashSet::new(), None, "koreana").unwrap(); + assert_eq!(plan.language, "english"); + let ids: Vec = plan.depots.iter().map(|d| d.depot_id).collect(); + assert_eq!(ids, vec![1, 2]); + assert!(plan_app( + 9, + &parse(r#""appinfo" { "depots" { } }"#), + &HashSet::new(), + None, + "english" + ) + .is_err()); + } + + #[test] + fn skips_depots_the_licenses_do_not_grant() { + let info = parse( + r#""appinfo" { "config" { "installdir" "X" } "depots" { + "11" { "config" { "oslist" "windows" } "manifests" { "public" { "gid" "1" "size" "1" } } } + "12" { "config" { "oslist" "windows" } "manifests" { "public" { "gid" "2" "size" "1" } } } + "13" { "config" { "oslist" "windows" } "depotfromapp" "228980" "sharedinstall" "1" } } }"#, + ); + let owned: HashSet = [11].into_iter().collect(); + let plan = plan_app(10, &info, &HashSet::new(), Some(&owned), "english").unwrap(); + let ids: Vec = plan.depots.iter().map(|d| d.depot_id).collect(); + assert_eq!(ids, vec![11]); + assert_eq!(plan.shared_refs.len(), 1); + let all = plan_app(10, &info, &HashSet::new(), None, "english").unwrap(); + assert_eq!(all.depots.len(), 2); + } + + #[test] + fn flags_a_linux_build() { + let info = parse( + r#""appinfo" { "common" { "oslist" "windows,linux" } "config" { "installdir" "X" } "depots" { + "1" { "config" { "oslist" "windows" } "manifests" { "public" { "gid" "1" "size" "1" } } } } }"#, + ); + assert!(plan_app(1, &info, &HashSet::new(), None, "english").unwrap().linux_build); + } +} diff --git a/app/src/main/rust/stores/src/steam/proto_envelope.rs b/app/src/main/rust/stores/src/steam/proto_envelope.rs new file mode 100644 index 0000000000..903a0821a7 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/proto_envelope.rs @@ -0,0 +1,87 @@ +use crate::steam::cmsg_protobuf_header::CMsgProtoBufHeader; +use crate::steam::emsg::{has_proto_flag, strip_proto_flag, with_proto_flag, EMsg}; +use crate::steam::wire_format; + +pub const PROTO_ENVELOPE_PREFIX_BYTES: usize = 8; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ProtoEnvelope { + pub emsg: EMsg, + pub header: CMsgProtoBufHeader, + pub body: Vec, +} + +impl Default for ProtoEnvelope { + fn default() -> Self { + Self { + emsg: EMsg::INVALID, + header: CMsgProtoBufHeader::default(), + body: Vec::new(), + } + } +} + +pub fn encode_proto_envelope(emsg: EMsg, header: &CMsgProtoBufHeader, body: &[u8]) -> Vec { + let mut hdr_bytes = Vec::with_capacity(64); + header.serialize(&mut hdr_bytes); + + let mut out = Vec::with_capacity(PROTO_ENVELOPE_PREFIX_BYTES + hdr_bytes.len() + body.len()); + let mut writer = wire_format::Writer::new(&mut out); + writer.u32(with_proto_flag(emsg)); + writer.u32(hdr_bytes.len() as u32); + writer.bytes(&hdr_bytes); + writer.bytes(body); + out +} + +pub fn decode_proto_envelope(wire: &[u8]) -> Option { + if wire.len() < PROTO_ENVELOPE_PREFIX_BYTES { + return None; + } + let mut reader = wire_format::Reader::new(wire); + let raw_emsg = reader.u32(); + let hdr_len = reader.u32() as usize; + if !reader.ok() || !has_proto_flag(raw_emsg) || reader.remaining() < hdr_len { + return None; + } + let header = CMsgProtoBufHeader::deserialize(reader.bytes(hdr_len))?; + if !reader.ok() { + return None; + } + let body_off = reader.position(); + Some(ProtoEnvelope { + emsg: strip_proto_flag(raw_emsg), + header, + body: wire[body_off..].to_vec(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn proto_envelope_roundtrips() { + let header = CMsgProtoBufHeader { + steamid: 76561197960287930, + jobid_source: 42, + target_job_name: "Player.GetOwnedGames#1".to_string(), + ..Default::default() + }; + let body = [1, 2, 3, 4, 5]; + let bytes = encode_proto_envelope(EMsg::SERVICE_METHOD_CALL_FROM_CLIENT, &header, &body); + let decoded = decode_proto_envelope(&bytes).unwrap(); + assert_eq!(decoded.emsg, EMsg::SERVICE_METHOD_CALL_FROM_CLIENT); + assert_eq!(decoded.header, header); + assert_eq!(decoded.body, body); + } + + #[test] + fn decode_rejects_non_proto_messages() { + let mut bytes = Vec::new(); + let mut writer = wire_format::Writer::new(&mut bytes); + writer.u32(EMsg::MULTI.0); + writer.u32(0); + assert_eq!(decode_proto_envelope(&bytes), None); + } +} diff --git a/app/src/main/rust/stores/src/steam/proto_wire.rs b/app/src/main/rust/stores/src/steam/proto_wire.rs new file mode 100644 index 0000000000..bdb10f5a4c --- /dev/null +++ b/app/src/main/rust/stores/src/steam/proto_wire.rs @@ -0,0 +1,459 @@ +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum WireType { + Varint = 0, + Fixed64 = 1, + LengthDelimited = 2, + StartGroup = 3, + EndGroup = 4, + Fixed32 = 5, +} + +impl TryFrom for WireType { + type Error = (); + + fn try_from(value: u8) -> Result { + match value { + 0 => Ok(Self::Varint), + 1 => Ok(Self::Fixed64), + 2 => Ok(Self::LengthDelimited), + 3 => Ok(Self::StartGroup), + 4 => Ok(Self::EndGroup), + 5 => Ok(Self::Fixed32), + _ => Err(()), + } + } +} + +pub const MAX_VARINT_BYTES: usize = 10; + +pub const fn zigzag_encode_i64(v: i64) -> u64 { + ((v as u64) << 1) ^ ((v >> 63) as u64) +} + +pub const fn zigzag_decode_i64(v: u64) -> i64 { + ((v >> 1) as i64) ^ -((v & 1) as i64) +} + +pub const fn zigzag_encode_i32(v: i32) -> u32 { + ((v as u32) << 1) ^ ((v >> 31) as u32) +} + +pub const fn zigzag_decode_i32(v: u32) -> i32 { + ((v >> 1) as i32) ^ -((v & 1) as i32) +} + +pub const fn make_tag(field_number: i32, wire_type: WireType) -> u32 { + ((field_number as u32) << 3) | wire_type as u32 +} + +pub struct Writer<'a> { + out: &'a mut Vec, +} + +impl<'a> Writer<'a> { + pub fn new(out: &'a mut Vec) -> Self { + Self { out } + } + + pub fn varint(&mut self, mut v: u64) { + while v >= 0x80 { + self.out.push((v as u8) | 0x80); + v >>= 7; + } + self.out.push(v as u8); + } + + pub fn tag(&mut self, field_number: i32, wire_type: WireType) { + self.varint(make_tag(field_number, wire_type) as u64); + } + + pub fn uint32_field(&mut self, field_number: i32, v: u32) { + if v == 0 { + return; + } + self.tag(field_number, WireType::Varint); + self.varint(v as u64); + } + + pub fn uint64_field(&mut self, field_number: i32, v: u64) { + if v == 0 { + return; + } + self.tag(field_number, WireType::Varint); + self.varint(v); + } + + pub fn int32_field(&mut self, field_number: i32, v: i32) { + if v == 0 { + return; + } + self.tag(field_number, WireType::Varint); + self.varint(v as i64 as u64); + } + + pub fn int64_field(&mut self, field_number: i32, v: i64) { + if v == 0 { + return; + } + self.tag(field_number, WireType::Varint); + self.varint(v as u64); + } + + pub fn bool_field(&mut self, field_number: i32, v: bool) { + if !v { + return; + } + self.tag(field_number, WireType::Varint); + self.varint(1); + } + + pub fn fixed32_field(&mut self, field_number: i32, v: u32) { + if v == 0 { + return; + } + self.tag(field_number, WireType::Fixed32); + self.out.extend_from_slice(&v.to_le_bytes()); + } + + pub fn fixed64_field(&mut self, field_number: i32, v: u64) { + if v == 0 { + return; + } + self.tag(field_number, WireType::Fixed64); + self.out.extend_from_slice(&v.to_le_bytes()); + } + + pub fn string_field(&mut self, field_number: i32, s: &str) { + if s.is_empty() { + return; + } + self.tag(field_number, WireType::LengthDelimited); + self.varint(s.len() as u64); + self.out.extend_from_slice(s.as_bytes()); + } + + pub fn bytes_field(&mut self, field_number: i32, bytes: &[u8]) { + if bytes.is_empty() { + return; + } + self.tag(field_number, WireType::LengthDelimited); + self.varint(bytes.len() as u64); + self.out.extend_from_slice(bytes); + } + + pub fn submessage_field(&mut self, field_number: i32, body: &[u8]) { + self.tag(field_number, WireType::LengthDelimited); + self.varint(body.len() as u64); + self.out.extend_from_slice(body); + } + + pub fn raw_bytes(&mut self, bytes: &[u8]) { + self.out.extend_from_slice(bytes); + } + + pub fn uint32_field_force(&mut self, field_number: i32, v: u32) { + self.tag(field_number, WireType::Varint); + self.varint(v as u64); + } + + pub fn bool_field_force(&mut self, field_number: i32, v: bool) { + self.tag(field_number, WireType::Varint); + self.varint(u64::from(v)); + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Tag { + pub field_number: i32, + pub wire_type: WireType, +} + +pub struct Reader<'a> { + buf: &'a [u8], + pos: usize, + ok: bool, +} + +impl<'a> Reader<'a> { + pub fn new(buf: &'a [u8]) -> Self { + Self { + buf, + pos: 0, + ok: true, + } + } + + pub fn ok(&self) -> bool { + self.ok + } + + pub fn eof(&self) -> bool { + self.pos >= self.buf.len() + } + + pub fn position(&self) -> usize { + self.pos + } + + pub fn next_tag(&mut self) -> Option { + if self.eof() { + return None; + } + let raw = self.varint()? as u32; + let wire_type = match WireType::try_from((raw & 0x07) as u8) { + Ok(wire_type) => wire_type, + Err(_) => { + self.ok = false; + return None; + } + }; + let field_number = (raw >> 3) as i32; + if matches!(wire_type, WireType::StartGroup | WireType::EndGroup) || field_number <= 0 { + self.ok = false; + return None; + } + Some(Tag { + field_number, + wire_type, + }) + } + + pub fn varint(&mut self) -> Option { + let mut result = 0u64; + for i in 0..MAX_VARINT_BYTES { + if self.pos >= self.buf.len() { + self.ok = false; + return None; + } + let b = self.buf[self.pos]; + self.pos += 1; + result |= ((b & 0x7f) as u64) << (i * 7); + if (b & 0x80) == 0 { + return Some(result); + } + } + self.ok = false; + None + } + + pub fn skip(&mut self, wire_type: WireType) -> bool { + match wire_type { + WireType::Varint => self.varint().is_some(), + WireType::Fixed64 => self.advance(8), + WireType::LengthDelimited => { + let Some(len) = self.varint() else { + return false; + }; + if len > usize::MAX as u64 { + self.ok = false; + return false; + } + self.advance(len as usize) + } + WireType::Fixed32 => self.advance(4), + WireType::StartGroup | WireType::EndGroup => { + self.ok = false; + false + } + } + } + + pub fn u32(&mut self) -> Option { + self.varint().map(|v| v as u32) + } + + pub fn u64(&mut self) -> Option { + self.varint() + } + + pub fn i32(&mut self) -> Option { + self.varint().map(|v| v as i32) + } + + pub fn i64(&mut self) -> Option { + self.varint().map(|v| v as i64) + } + + pub fn boolean(&mut self) -> Option { + self.varint().map(|v| v != 0) + } + + pub fn fixed32(&mut self) -> Option { + let Some(end) = self.pos.checked_add(4) else { + self.ok = false; + return None; + }; + if end > self.buf.len() { + self.ok = false; + return None; + } + let bytes: [u8; 4] = self.buf[self.pos..end].try_into().ok()?; + self.pos = end; + Some(u32::from_le_bytes(bytes)) + } + + pub fn fixed64(&mut self) -> Option { + let Some(end) = self.pos.checked_add(8) else { + self.ok = false; + return None; + }; + if end > self.buf.len() { + self.ok = false; + return None; + } + let bytes: [u8; 8] = self.buf[self.pos..end].try_into().ok()?; + self.pos = end; + Some(u64::from_le_bytes(bytes)) + } + + pub fn bytes(&mut self) -> Option<&'a [u8]> { + let len = self.varint()?; + if len > usize::MAX as u64 { + self.ok = false; + return None; + } + let len = len as usize; + let Some(end) = self.pos.checked_add(len) else { + self.ok = false; + return None; + }; + if end > self.buf.len() { + self.ok = false; + return None; + } + let out = &self.buf[self.pos..end]; + self.pos = end; + Some(out) + } + + pub fn string(&mut self) -> Option { + Some(String::from_utf8_lossy(self.bytes()?).into_owned()) + } + + fn advance(&mut self, amount: usize) -> bool { + let Some(end) = self.pos.checked_add(amount) else { + self.ok = false; + return false; + }; + if end > self.buf.len() { + self.ok = false; + return false; + } + self.pos = end; + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn varint_roundtrips_common_edges() { + let cases = [0, 1, 127, 128, 300, u32::MAX as u64, u64::MAX]; + for case in cases { + let mut buf = Vec::new(); + Writer::new(&mut buf).varint(case); + let mut reader = Reader::new(&buf); + assert_eq!(reader.varint(), Some(case)); + assert!(reader.ok()); + assert!(reader.eof()); + } + } + + #[test] + fn writes_and_reads_typed_fields() { + let mut buf = Vec::new(); + let mut writer = Writer::new(&mut buf); + writer.uint32_field(1, 42); + writer.fixed32_field(2, 0x1234_5678); + writer.string_field(3, "steam"); + writer.bool_field_force(4, false); + + let mut reader = Reader::new(&buf); + assert_eq!( + reader.next_tag(), + Some(Tag { + field_number: 1, + wire_type: WireType::Varint + }) + ); + assert_eq!(reader.u32(), Some(42)); + assert_eq!( + reader.next_tag(), + Some(Tag { + field_number: 2, + wire_type: WireType::Fixed32 + }) + ); + assert_eq!(reader.fixed32(), Some(0x1234_5678)); + assert_eq!( + reader.next_tag(), + Some(Tag { + field_number: 3, + wire_type: WireType::LengthDelimited + }) + ); + assert_eq!(reader.string(), Some("steam".to_string())); + assert_eq!( + reader.next_tag(), + Some(Tag { + field_number: 4, + wire_type: WireType::Varint + }) + ); + assert_eq!(reader.boolean(), Some(false)); + assert!(reader.eof()); + } + + #[test] + fn rejects_deprecated_groups_and_truncated_data() { + let mut group = Vec::new(); + Writer::new(&mut group).tag(1, WireType::StartGroup); + let mut reader = Reader::new(&group); + assert_eq!(reader.next_tag(), None); + assert!(!reader.ok()); + + let mut truncated = Reader::new(&[0x0a, 0x05, b'a']); + assert_eq!( + truncated.next_tag(), + Some(Tag { + field_number: 1, + wire_type: WireType::LengthDelimited + }) + ); + assert_eq!(truncated.bytes(), None); + assert!(!truncated.ok()); + } + + #[test] + fn rejects_invalid_wire_type_and_oversized_length() { + let mut invalid = Reader::new(&[0x0e]); + assert_eq!(invalid.next_tag(), None); + assert!(!invalid.ok()); + + let mut oversized = Vec::new(); + Writer::new(&mut oversized).varint(make_tag(1, WireType::LengthDelimited) as u64); + Writer::new(&mut oversized).varint(u64::MAX); + let mut reader = Reader::new(&oversized); + assert_eq!( + reader.next_tag(), + Some(Tag { + field_number: 1, + wire_type: WireType::LengthDelimited + }) + ); + assert_eq!(reader.bytes(), None); + assert!(!reader.ok()); + } + + #[test] + fn zigzag_matches_known_values() { + assert_eq!(zigzag_encode_i32(0), 0); + assert_eq!(zigzag_encode_i32(-1), 1); + assert_eq!(zigzag_encode_i32(1), 2); + assert_eq!(zigzag_decode_i32(1), -1); + assert_eq!(zigzag_decode_i64(3), -2); + } +} diff --git a/app/src/main/rust/stores/src/steam/register.rs b/app/src/main/rust/stores/src/steam/register.rs new file mode 100644 index 0000000000..ca5d58938c --- /dev/null +++ b/app/src/main/rust/stores/src/steam/register.rs @@ -0,0 +1,1253 @@ +//! What the Steam client writes around an install, so it sees a game we downloaded as installed +//! (and does not update or verify it), and what it removes on uninstall. Modelled on a captured +//! client install and uninstall of Brawlhalla (291550) to an SD-card library: +//! +//! - `/steamapps/appmanifest_.acf` (key order as the client writes it); +//! - shared depots (e.g. 228988 VC++ 2019 of 228980) in the library holding that app's manifest, +//! under `steamapps/common/`, recorded in its `InstalledDepots` and +//! `InstallScripts`, with its `SizeOnDisk` adjusted; +//! - `"" "0"` under the library's `apps` in both `libraryfolders.vdf` copies (the client +//! fills in the size later). +//! +//! `config.vdf`, `localconfig.vdf` and `registry.vdf` are never written; the client regenerates +//! them. `depotcache/` is not written either: the client keeps manifests there with decrypted +//! file names, not in the CDN form this engine caches. + +use crate::steam::content_manifest::ContentManifest; +use crate::steam::kv; +use crate::steam::plan::AppPlan; +use crate::steam::vdf::KVNode; +use std::collections::HashSet; +use std::fs; +use std::path::{Path, PathBuf}; + +pub const STATE_UPDATE_REQUIRED: u64 = 2; +pub const STATE_FULLY_INSTALLED: u64 = 4; +/// StateFlags bits that mean "not a finished install": update required, files missing or +/// corrupt, update running/paused/started, uninstalling, reconfiguring, validating, adding files, +/// preallocating, downloading, staging, committing, update stopping. +pub const STATE_UNFINISHED_MASK: u64 = 2 + | 32 + | 128 + | 256 + | 512 + | 1024 + | 2048 + | 65536 + | 131072 + | 262144 + | 524288 + | 1048576 + | 2097152 + | 4194304 + | 8388608; +/// `EDepotFileFlag::InstallScript`. +pub const DEPOT_FILE_FLAG_INSTALL_SCRIPT: u32 = 256; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct LibraryRoot { + pub host: PathBuf, + /// The path as the Steam client sees it inside proot (what `libraryfolders.vdf` holds). + pub guest: String, +} + +impl LibraryRoot { + pub fn steamapps(&self) -> PathBuf { + self.host.join("steamapps") + } + + pub fn acf_path(&self, app_id: u32) -> PathBuf { + self.steamapps().join(format!("appmanifest_{app_id}.acf")) + } + + pub fn common_dir(&self, install_dir: &str) -> PathBuf { + self.steamapps().join("common").join(install_dir) + } +} + +/// Orders a block's entries by numeric key (depot ids), the way the client lists them. +fn sort_by_numeric_key(node: &mut crate::steam::vdf::KVNode) { + node.children + .sort_by_key(|c| c.name.parse::().unwrap_or(u64::MAX)); +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Takeover { + /// No app manifest, or an unfinished one with no client staging left (an earlier run of + /// ours): installed as fresh, merging into that manifest. + Fresh, + /// Fully installed at the build being installed: nothing to do. + AlreadyInstalled, + /// Fully installed at another build: left to the Steam client, which updates it. + Update, + /// A half-finished client download was taken over: its `downloading/` and + /// `temp/` staging went; its manifest stays so its user settings carry into the one + /// written when the install finishes. + TookOver, +} + +pub fn state_is_finished(flags: u64) -> bool { + flags & STATE_FULLY_INSTALLED != 0 && flags & STATE_UNFINISHED_MASK == 0 +} + +pub fn takeover( + game_library: &LibraryRoot, + app_id: u32, + build_id: u64, +) -> Result { + let acf_path = game_library.acf_path(app_id); + if !acf_path.exists() { + return Ok(Takeover::Fresh); + } + let acf = kv::parse_file(&acf_path); + if let Some(acf) = acf.as_ref() { + let flags = kv::get_u64(acf, "StateFlags"); + if state_is_finished(flags) && kv::get_u64(acf, "buildid") == build_id { + return Ok(Takeover::AlreadyInstalled); + } + // A build is on disk (e.g. 6: installed, update required): updating it is the client's. + if flags & STATE_FULLY_INSTALLED != 0 { + return Ok(Takeover::Update); + } + } + let steamapps = game_library.steamapps(); + let mut took_over = false; + for dir in [ + steamapps.join("downloading").join(app_id.to_string()), + steamapps.join("temp").join(app_id.to_string()), + ] { + if dir.exists() { + fs::remove_dir_all(&dir).map_err(|err| format!("remove '{}': {err}", dir.display()))?; + took_over = true; + } + } + let prefix = format!("state_{app_id}_"); + if let Ok(entries) = fs::read_dir(steamapps.join("downloading")) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with(&prefix) && name.ends_with(".patch") { + let _ = fs::remove_file(entry.path()); + } + } + } + Ok(if took_over { + Takeover::TookOver + } else { + Takeover::Fresh + }) +} + +/// Moves the files a stopped client download staged in `downloading/` (full-size files at +/// their final offsets) into the install folder where that file is not there yet, so resuming +/// verifies their chunks instead of fetching them again. What stays behind goes with the takeover. +/// Returns how many files were moved. +pub fn adopt_staged(library: &LibraryRoot, app_id: u32, install_dir: &str) -> usize { + if !is_plain_name(install_dir) { + return 0; + } + let installed = kv::parse_file(&library.acf_path(app_id)) + .is_some_and(|acf| kv::get_u64(&acf, "StateFlags") & STATE_FULLY_INSTALLED != 0); + if installed { + return 0; + } + let staging = library.steamapps().join("downloading").join(app_id.to_string()); + let target = library.common_dir(install_dir); + let mut moved = 0; + let mut pending = vec![staging.clone()]; + while let Some(dir) = pending.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(meta) = fs::symlink_metadata(&path) else { + continue; + }; + if meta.is_dir() { + pending.push(path); + continue; + } + if !meta.is_file() { + continue; + } + let Ok(rel) = path.strip_prefix(&staging) else { + continue; + }; + let dest = target.join(rel); + if fs::symlink_metadata(&dest).is_ok() { + continue; + } + let Some(parent) = dest.parent() else { + continue; + }; + if fs::create_dir_all(parent).is_ok() && fs::rename(&path, &dest).is_ok() { + moved += 1; + } + } + } + moved +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct InstalledDepot { + pub depot_id: u32, + pub manifest_id: u64, + pub size: u64, + pub dlc_app_id: u32, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SharedInstall { + pub depot_id: u32, + pub from_app_id: u32, + pub from_name: String, + pub from_install_dir: String, + pub from_build_id: u64, + pub manifest_id: u64, + pub size: u64, + /// Windows-style path of the depot's install script, if it has one. + pub install_script: Option, + pub library: LibraryRoot, +} + +/// The install script of a depot (`InstallScript` file flag; `installscript.vdf` by name as a +/// fallback), as the Windows-style relative path the client records. +pub fn install_script_path(manifest: &ContentManifest) -> Option { + let flagged = manifest + .files + .iter() + .find(|f| f.flags & DEPOT_FILE_FLAG_INSTALL_SCRIPT != 0 && f.linktarget.is_empty()); + let named = || { + manifest.files.iter().find(|f| { + f.filename + .rsplit('/') + .next() + .is_some_and(|n| n.eq_ignore_ascii_case("installscript.vdf")) + }) + }; + flagged + .or_else(named) + .map(|f| f.filename.replace('/', "\\")) +} + +/// Where a shared app lives: the library that already holds its manifest, else the Steam root's +/// own library (its guest path taken from `libraryfolders.vdf` entry `0` when the caller did not +/// list it). +pub fn shared_app_library( + from_app_id: u32, + steam_root: &Path, + libraries: &[LibraryRoot], +) -> LibraryRoot { + if let Some(lib) = libraries.iter().find(|l| l.acf_path(from_app_id).exists()) { + return lib.clone(); + } + if let Some(lib) = libraries.iter().find(|l| same_path(&l.host, steam_root)) { + return lib.clone(); + } + let guest = libraryfolders_paths(steam_root) + .iter() + .find_map(|path| { + let root = kv::parse_file(path)?; + kv::get_str(root.child("0")?, "path") + }) + .unwrap_or_default(); + LibraryRoot { + host: steam_root.to_path_buf(), + guest, + } +} + +fn same_path(a: &Path, b: &Path) -> bool { + let norm = |p: &Path| p.to_string_lossy().trim_end_matches('/').to_string(); + norm(a) == norm(b) +} + +/// The manifest's InstalledDepots entry for `depot_id` (manifest gid), if any. +pub fn installed_manifest(acf: &KVNode, depot_id: u32) -> Option { + let entry = acf.child("InstalledDepots")?.child(&depot_id.to_string())?; + kv::get_str(entry, "manifest")?.parse().ok() +} + +pub struct GameRegistration<'a> { + pub plan: &'a AppPlan, + pub owner_steam_id: u64, + pub depots: &'a [InstalledDepot], + /// Every shared depot the game uses (installed now or already present). + pub shared: &'a [(u32, u32)], + pub install_scripts: &'a [(u32, String)], + pub bytes_downloaded: u64, + pub bytes_staged: u64, + pub now: u64, +} + +/// Writes (or merges into) `appmanifest_.acf` in the client's key order. +pub fn write_game_acf(library: &LibraryRoot, reg: &GameRegistration<'_>) -> Result<(), String> { + let path = library.acf_path(reg.plan.app_id); + let mut root = kv::parse_file(&path) + .filter(|r| r.name.eq_ignore_ascii_case("AppState")) + .unwrap_or_else(|| kv::object("AppState")); + let size_on_disk: u64 = reg.depots.iter().map(|d| d.size).sum(); + let build = reg.plan.build_id.to_string(); + kv::set(&mut root, "appid", reg.plan.app_id.to_string()); + kv::set(&mut root, "Universe", "1"); + kv::set(&mut root, "name", reg.plan.name.as_str()); + kv::set(&mut root, "StateFlags", "4"); + kv::set(&mut root, "installdir", reg.plan.install_dir.as_str()); + kv::set(&mut root, "LastUpdated", reg.now.to_string()); + set_default(&mut root, "LastPlayed", "0"); + kv::set(&mut root, "SizeOnDisk", size_on_disk.to_string()); + kv::set(&mut root, "StagingSize", "0"); + kv::set(&mut root, "buildid", build.as_str()); + kv::set(&mut root, "LastOwner", reg.owner_steam_id.to_string()); + kv::set(&mut root, "DownloadType", "1"); + kv::set(&mut root, "UpdateResult", "0"); + kv::set( + &mut root, + "BytesToDownload", + reg.bytes_downloaded.to_string(), + ); + kv::set( + &mut root, + "BytesDownloaded", + reg.bytes_downloaded.to_string(), + ); + kv::set(&mut root, "BytesToStage", reg.bytes_staged.to_string()); + kv::set(&mut root, "BytesStaged", reg.bytes_staged.to_string()); + kv::set(&mut root, "TargetBuildID", build.as_str()); + set_default(&mut root, "AutoUpdateBehavior", "0"); + set_default(&mut root, "AllowOtherDownloadsWhileRunning", "0"); + set_default(&mut root, "ScheduledAutoUpdate", "0"); + kv::remove(&mut root, "FullValidateAfterNextUpdate"); + + let installed = kv::object_mut(&mut root, "InstalledDepots"); + installed.children.clear(); + for depot in reg.depots { + let mut entry = kv::object(&depot.depot_id.to_string()); + kv::set(&mut entry, "manifest", depot.manifest_id.to_string()); + kv::set(&mut entry, "size", depot.size.to_string()); + if depot.dlc_app_id != 0 { + kv::set(&mut entry, "dlcappid", depot.dlc_app_id.to_string()); + } + installed.children.push(entry); + } + if reg.install_scripts.is_empty() { + kv::remove(&mut root, "InstallScripts"); + } else { + let scripts = kv::object_mut(&mut root, "InstallScripts"); + scripts.children.clear(); + for (depot, path) in reg.install_scripts { + kv::set(scripts, &depot.to_string(), path.as_str()); + } + } + if reg.shared.is_empty() { + kv::remove(&mut root, "SharedDepots"); + } else { + let shared = kv::object_mut(&mut root, "SharedDepots"); + shared.children.clear(); + for (depot, from) in reg.shared { + kv::set(shared, &depot.to_string(), from.to_string()); + } + } + kv::set( + kv::object_mut(&mut root, "UserConfig"), + "language", + reg.plan.language.as_str(), + ); + kv::set( + kv::object_mut(&mut root, "MountedConfig"), + "language", + reg.plan.language.as_str(), + ); + fs::create_dir_all(library.steamapps()).map_err(|err| format!("mkdir steamapps: {err}"))?; + kv::write_file(&path, &root) +} + +/// Before any file lands, records the install the way the client does when it starts one +/// (`StateFlags` 1026: update required and started, nothing installed yet), so a paused or +/// interrupted download shows in the client as a resumable install. Leaves an existing manifest. +pub fn write_started_acf( + library: &LibraryRoot, + plan: &AppPlan, + owner_steam_id: u64, + now: u64, +) -> Result<(), String> { + let path = library.acf_path(plan.app_id); + if path.exists() { + return Ok(()); + } + let mut root = kv::object("AppState"); + let build = plan.build_id.to_string(); + kv::set(&mut root, "appid", plan.app_id.to_string()); + kv::set(&mut root, "Universe", "1"); + kv::set(&mut root, "name", plan.name.as_str()); + kv::set(&mut root, "StateFlags", "1026"); + kv::set(&mut root, "installdir", plan.install_dir.as_str()); + kv::set(&mut root, "LastUpdated", now.to_string()); + kv::set(&mut root, "LastPlayed", "0"); + kv::set(&mut root, "SizeOnDisk", "0"); + kv::set(&mut root, "StagingSize", "0"); + kv::set(&mut root, "buildid", "0"); + kv::set(&mut root, "LastOwner", owner_steam_id.to_string()); + kv::set(&mut root, "DownloadType", "1"); + kv::set(&mut root, "UpdateResult", "0"); + kv::set(&mut root, "BytesToDownload", plan.download_bytes().to_string()); + kv::set(&mut root, "BytesDownloaded", "0"); + kv::set(&mut root, "BytesToStage", plan.install_bytes().to_string()); + kv::set(&mut root, "BytesStaged", "0"); + kv::set(&mut root, "TargetBuildID", build.as_str()); + kv::set(&mut root, "AutoUpdateBehavior", "0"); + kv::set(&mut root, "AllowOtherDownloadsWhileRunning", "0"); + kv::set(&mut root, "ScheduledAutoUpdate", "0"); + kv::object_mut(&mut root, "InstalledDepots"); + kv::set(kv::object_mut(&mut root, "UserConfig"), "language", plan.language.as_str()); + kv::set(kv::object_mut(&mut root, "MountedConfig"), "language", plan.language.as_str()); + fs::create_dir_all(library.steamapps()).map_err(|err| format!("mkdir steamapps: {err}"))?; + kv::write_file(&path, &root) +} + +fn set_default(node: &mut KVNode, key: &str, value: &str) { + if node.child(key).is_none() { + kv::set(node, key, value); + } +} + +/// Records a shared depot in its app's manifest (creating the manifest when the app has none +/// yet), as the client does: `InstalledDepots`, `InstallScripts`, `SizeOnDisk`. +/// Serializes read-modify-write of a shared app's manifest between installs and uninstalls. +static SHARED_ACF_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +pub fn register_shared_depot( + shared: &SharedInstall, + owner_steam_id: u64, + now: u64, +) -> Result { + let _guard = SHARED_ACF_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let path = shared.library.acf_path(shared.from_app_id); + let existing = kv::parse_file(&path).filter(|r| r.name.eq_ignore_ascii_case("AppState")); + let created = existing.is_none(); + let mut root = match existing { + Some(root) => root, + None => { + let mut root = kv::object("AppState"); + let build = shared.from_build_id.to_string(); + for (key, value) in [ + ("appid", shared.from_app_id.to_string()), + ("Universe", "1".to_string()), + ("name", shared.from_name.clone()), + ("StateFlags", "4".to_string()), + ("installdir", shared.from_install_dir.clone()), + ("LastUpdated", now.to_string()), + ("LastPlayed", "0".to_string()), + ("SizeOnDisk", "0".to_string()), + ("StagingSize", "0".to_string()), + ("buildid", build.clone()), + ("LastOwner", owner_steam_id.to_string()), + ("DownloadType", "1".to_string()), + ("UpdateResult", "0".to_string()), + ("BytesToDownload", "0".to_string()), + ("BytesDownloaded", "0".to_string()), + ("BytesToStage", "0".to_string()), + ("BytesStaged", "0".to_string()), + ("TargetBuildID", build), + ("AutoUpdateBehavior", "0".to_string()), + ("AllowOtherDownloadsWhileRunning", "0".to_string()), + ("ScheduledAutoUpdate", "0".to_string()), + ] { + kv::set(&mut root, key, value); + } + kv::object_mut(&mut root, "InstalledDepots"); + root + } + }; + let depot_key = shared.depot_id.to_string(); + let old_size = root + .child("InstalledDepots") + .and_then(|d| d.child(&depot_key)) + .map(|e| kv::get_u64(e, "size")) + .unwrap_or(0); + let size_on_disk = kv::get_u64(&root, "SizeOnDisk") + .saturating_sub(old_size) + .saturating_add(shared.size); + kv::set(&mut root, "SizeOnDisk", size_on_disk.to_string()); + { + let installed = kv::object_mut(&mut root, "InstalledDepots"); + kv::remove(installed, &depot_key); + let mut entry = kv::object(&depot_key); + kv::set(&mut entry, "manifest", shared.manifest_id.to_string()); + kv::set(&mut entry, "size", shared.size.to_string()); + installed.children.push(entry); + sort_by_numeric_key(installed); + } + if let Some(script) = &shared.install_script { + let scripts = insert_after(&mut root, "InstallScripts", "InstalledDepots"); + kv::set(scripts, &depot_key, script.as_str()); + sort_by_numeric_key(scripts); + } else if let Some(scripts) = kv::get_mut(&mut root, "InstallScripts") { + kv::remove(scripts, &depot_key); + } + if root.child("UserConfig").is_none() { + kv::object_mut(&mut root, "UserConfig"); + } + if root.child("MountedConfig").is_none() { + kv::object_mut(&mut root, "MountedConfig"); + } + fs::create_dir_all(shared.library.steamapps()) + .map_err(|err| format!("mkdir steamapps: {err}"))?; + kv::write_file(&path, &root)?; + Ok(created) +} + +/// The object `key`, created right after `after` when missing (the client's section order). +fn insert_after<'a>(root: &'a mut KVNode, key: &str, after: &str) -> &'a mut KVNode { + if root.child(key).is_none() { + let pos = root + .children + .iter() + .position(|c| c.name.eq_ignore_ascii_case(after)) + .map(|p| p + 1) + .unwrap_or(root.children.len()); + root.children.insert(pos, kv::object(key)); + } + kv::object_mut(root, key) +} + +pub fn libraryfolders_paths(steam_root: &Path) -> [PathBuf; 2] { + [ + steam_root.join("steamapps").join("libraryfolders.vdf"), + steam_root.join("config").join("libraryfolders.vdf"), + ] +} + +fn normalize_guest(path: &str) -> String { + let trimmed = path.trim_end_matches('/'); + if trimmed.is_empty() { + "/".to_string() + } else { + trimmed.to_string() + } +} + +/// Does either `libraryfolders.vdf` copy have an entry whose `path` is `guest_path`? +pub fn library_registered(steam_root: &Path, guest_path: &str) -> bool { + let want = normalize_guest(guest_path); + libraryfolders_paths(steam_root).iter().any(|path| { + kv::parse_file(path).is_some_and(|root| { + root.children.iter().any(|entry| { + entry.is_object() + && kv::get_str(entry, "path").is_some_and(|p| normalize_guest(&p) == want) + }) + }) + }) +} + +/// Adds (`add = true`) or removes `""` in the `apps` block of the entry whose `path` is +/// `guest_path`, in both copies. Returns how many copies had that entry. +/// Serializes the read-modify-write of `libraryfolders.vdf` between installs and uninstalls. +static LIBRARYFOLDERS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +pub fn update_libraryfolders( + steam_root: &Path, + guest_path: &str, + app_id: u32, + add: bool, +) -> Result { + let _guard = LIBRARYFOLDERS_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let want = normalize_guest(guest_path); + let mut matched = 0usize; + for path in libraryfolders_paths(steam_root) { + let Some(mut root) = kv::parse_file(&path) else { + continue; + }; + let app_key = app_id.to_string(); + let mut changed = false; + let mut found = false; + for entry in root.children.iter_mut().filter(|c| c.is_object()) { + let matches = kv::get_str(entry, "path") + .map(|p| normalize_guest(&p) == want) + .unwrap_or(false); + if add { + if !matches { + continue; + } + found = true; + let apps = kv::object_mut(entry, "apps"); + if apps.child(&app_key).is_none() { + apps.children.push(kv::string(&app_key, "0")); + changed = true; + } + } else if let Some(apps) = kv::get_mut(entry, "apps") { + if matches { + found = true; + } + if kv::remove(apps, &app_key) { + changed = true; + } + } + } + if found { + matched += 1; + } + if changed { + kv::write_file(&path, &root)?; + } + } + Ok(matched) +} + +pub(crate) fn is_plain_name(name: &str) -> bool { + !name.is_empty() && name != "." && name != ".." && !name.contains('/') && !name.contains('\\') +} + +/// Every app manifest in the libraries, except `skip` (path), parsed, and whether every library +/// and manifest could be read (a library without `steamapps` counts as read). +fn all_app_manifests(libraries: &[LibraryRoot], skip: &[PathBuf]) -> (Vec, bool) { + let mut out = Vec::new(); + let mut complete = true; + let mut seen: HashSet = HashSet::new(); + for lib in libraries { + let entries = match fs::read_dir(lib.steamapps()) { + Ok(entries) => entries, + Err(err) => { + if err.kind() != std::io::ErrorKind::NotFound { + complete = false; + } + continue; + } + }; + for entry in entries { + let Ok(entry) = entry else { + complete = false; + continue; + }; + let path = entry.path(); + let name = entry.file_name().to_string_lossy().to_string(); + if !name.starts_with("appmanifest_") || !name.ends_with(".acf") { + continue; + } + if skip.contains(&path) || !seen.insert(path.clone()) { + continue; + } + match kv::parse_file(&path) { + Some(acf) => out.push(acf), + None => complete = false, + } + } + } + (out, complete) +} + +/// Is `depot_id` listed in the `SharedDepots` of any of these manifests? +pub fn shared_depot_in_use(manifests: &[KVNode], depot_id: u32) -> bool { + let key = depot_id.to_string(); + manifests.iter().any(|acf| { + acf.child("SharedDepots") + .and_then(|s| s.child(&key)) + .is_some() + }) +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UninstallReport { + pub removed_shared: Vec, + /// Shared depots no other game uses whose file list was not available; left installed. + pub kept_shared: Vec, +} + +/// Uninstalls like the client: game folder, app manifest, `depotcache` manifests of the game's +/// depots and `steamapps/shadercache/` under the Steam root go; `compatdata/` +/// (the Proton prefix, i.e. saves) stays. A shared depot no other installed game lists loses its +/// files (from the depot's file list, `shared_files(app, depot, manifest)`; empty folders stay) +/// and +/// its entries in the shared app's manifest. The app leaves `apps` in both `libraryfolders.vdf`. +pub fn uninstall( + app_id: u32, + steam_root: &Path, + game_library: &LibraryRoot, + libraries: &[LibraryRoot], + shared_files: &dyn Fn(u32, u32, u64) -> Option>, +) -> Result { + let acf_path = game_library.acf_path(app_id); + let acf = kv::parse_file(&acf_path).ok_or_else(|| "not_installed".to_string())?; + let install_dir = kv::get_str(&acf, "installdir").unwrap_or_default(); + if !is_plain_name(&install_dir) { + return Err("bad installdir in app manifest".to_string()); + } + let game_dir = game_library.common_dir(&install_dir); + if game_dir.exists() { + fs::remove_dir_all(&game_dir) + .map_err(|err| format!("remove '{}': {err}", game_dir.display()))?; + } + if let Some(depots) = acf.child("InstalledDepots") { + for depot in &depots.children { + let manifest = kv::get_str(depot, "manifest").unwrap_or_default(); + if depot.name.parse::().is_err() || manifest.parse::().is_err() { + continue; + } + let cached = steam_root + .join("depotcache") + .join(format!("{}_{manifest}.manifest", depot.name)); + let _ = fs::remove_file(cached); + } + } + let shader = steam_root + .join("steamapps") + .join("shadercache") + .join(app_id.to_string()); + if shader.exists() { + let _ = fs::remove_dir_all(shader); + } + + let mut report = UninstallReport::default(); + let (others, complete) = all_app_manifests(libraries, std::slice::from_ref(&acf_path)); + if let Some(shared) = acf.child("SharedDepots") { + for entry in &shared.children { + let (Ok(depot_id), Ok(from_app)) = ( + entry.name.parse::(), + entry.as_string("").parse::(), + ) else { + continue; + }; + if shared_depot_in_use(&others, depot_id) { + continue; + } + // A library or manifest that could not be read may hold another game using it. + if !complete { + report.kept_shared.push(depot_id); + continue; + } + if remove_shared_depot(depot_id, from_app, libraries, shared_files)? { + report.removed_shared.push(depot_id); + } else { + report.kept_shared.push(depot_id); + } + } + } + + update_libraryfolders(steam_root, &game_library.guest, app_id, false)?; + // The manifest goes last, so a run that stopped early is retried rather than "not_installed". + match fs::remove_file(&acf_path) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(format!("remove '{}': {err}", acf_path.display())), + } + Ok(report) +} + +/// Removes one shared depot's files and its entries in the owning app's manifest. `false` when +/// the depot is not recorded there or its file list is unknown (nothing changed). +fn remove_shared_depot( + depot_id: u32, + from_app: u32, + libraries: &[LibraryRoot], + shared_files: &dyn Fn(u32, u32, u64) -> Option>, +) -> Result { + let _guard = SHARED_ACF_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(lib) = libraries.iter().find(|l| l.acf_path(from_app).exists()) else { + return Ok(false); + }; + let path = lib.acf_path(from_app); + let Some(mut root) = kv::parse_file(&path) else { + return Ok(false); + }; + let Some(manifest_id) = installed_manifest(&root, depot_id) else { + return Ok(false); + }; + let install_dir = kv::get_str(&root, "installdir").unwrap_or_default(); + if !is_plain_name(&install_dir) { + return Ok(false); + } + let Some(files) = shared_files(from_app, depot_id, manifest_id) else { + return Ok(false); + }; + let base = lib.common_dir(&install_dir); + let Ok(real_base) = fs::canonicalize(&base) else { + return Ok(false); + }; + let mut removed_any = false; + for rel in files { + if !crate::steam::depot_writer::path_is_safe(&rel) { + continue; + } + let target = base.join(&rel); + // The final component is unlinked without following it; its folder must resolve inside + // the shared app's folder, so a linked ancestor cannot send the removal elsewhere. + let inside = target + .parent() + .and_then(|parent| fs::canonicalize(parent).ok()) + .is_some_and(|parent| parent.starts_with(&real_base)); + if !inside { + continue; + } + if fs::symlink_metadata(&target).is_ok_and(|m| !m.is_dir()) { + match fs::remove_file(&target) { + Ok(()) => removed_any = true, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + // Untouched, the depot stays recorded so a later uninstall can retry. Once files + // are gone it must not read as installed at its manifest, or an install would skip + // it; manifest 0 makes the client and the engine download it again. + Err(_) => { + if removed_any { + if let Some(entry) = kv::get_mut(&mut root, "InstalledDepots") + .and_then(|d| kv::get_mut(d, &depot_id.to_string())) + { + kv::set(entry, "manifest", "0"); + kv::write_file(&path, &root)?; + } + } + return Ok(false); + } + } + } + } + let key = depot_id.to_string(); + let size = root + .child("InstalledDepots") + .and_then(|d| d.child(&key)) + .map(|e| kv::get_u64(e, "size")) + .unwrap_or(0); + let size_on_disk = kv::get_u64(&root, "SizeOnDisk").saturating_sub(size); + kv::set(&mut root, "SizeOnDisk", size_on_disk.to_string()); + if let Some(installed) = kv::get_mut(&mut root, "InstalledDepots") { + kv::remove(installed, &key); + } + if let Some(scripts) = kv::get_mut(&mut root, "InstallScripts") { + kv::remove(scripts, &key); + } + kv::write_file(&path, &root)?; + Ok(true) +} + +/// Regular files and links of a manifest (relative, `/`-separated), for shared-depot removal. +pub fn manifest_file_list(manifest: &ContentManifest) -> Vec { + manifest + .files + .iter() + .filter(|f| f.flags & crate::steam::depot_writer::DEPOT_FILE_FLAG_DIRECTORY == 0) + .map(|f| f.filename.clone()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::content_manifest::FileMapping; + + const OWNER: u64 = 76561198000000001; + + fn temp_root(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "droiddeck_steam_register_{name}_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + const LIBRARYFOLDERS: &str = "\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"/root/.local/share/Steam\"\n\t\t\"label\"\t\t\"Internal Storage\"\n\t\t\"contentid\"\t\t\"4468340155036637738\"\n\t\t\"totalsize\"\t\t\"0\"\n\t\t\"update_clean_bytes_tally\"\t\t\"2147547047\"\n\t\t\"time_last_update_verified\"\t\t\"1792656438\"\n\t\t\"apps\"\n\t\t{\n\t\t\t\"228980\"\t\t\"172268093\"\n\t\t}\n\t}\n\t\"1\"\n\t{\n\t\t\"path\"\t\t\"/mnt/droiddeck-sd\"\n\t\t\"label\"\t\t\"SD card\"\n\t\t\"contentid\"\t\t\"-5681848553336386775\"\n\t\t\"totalsize\"\t\t\"989672112128\"\n\t\t\"update_clean_bytes_tally\"\t\t\"0\"\n\t\t\"time_last_update_verified\"\t\t\"0\"\n\t\t\"apps\"\n\t\t{\n\t\t}\n\t}\n\t\"2\"\n\t{\n\t\t\"path\"\t\t\"/root/.droiddeck-x64/shared/x86-64\"\n\t\t\"label\"\t\t\"x86-64 client games\"\n\t\t\"apps\"\n\t\t{\n\t\t\t\"550\"\t\t\"15100020676\"\n\t\t}\n\t}\n}\n"; + + const REDIST_ACF: &str = "\"AppState\"\n{\n\t\"appid\"\t\t\"228980\"\n\t\"Universe\"\t\t\"1\"\n\t\"name\"\t\t\"Steamworks Common Redistributables\"\n\t\"StateFlags\"\t\t\"4\"\n\t\"installdir\"\t\t\"Steamworks Shared\"\n\t\"LastUpdated\"\t\t\"1792892508\"\n\t\"LastPlayed\"\t\t\"0\"\n\t\"SizeOnDisk\"\t\t\"143055920\"\n\t\"StagingSize\"\t\t\"0\"\n\t\"buildid\"\t\t\"24098430\"\n\t\"LastOwner\"\t\t\"76561198000000001\"\n\t\"DownloadType\"\t\t\"1\"\n\t\"UpdateResult\"\t\t\"0\"\n\t\"BytesToDownload\"\t\t\"0\"\n\t\"BytesDownloaded\"\t\t\"0\"\n\t\"BytesToStage\"\t\t\"0\"\n\t\"BytesStaged\"\t\t\"0\"\n\t\"TargetBuildID\"\t\t\"24098430\"\n\t\"AutoUpdateBehavior\"\t\t\"0\"\n\t\"AllowOtherDownloadsWhileRunning\"\t\t\"0\"\n\t\"ScheduledAutoUpdate\"\t\t\"0\"\n\t\"InstalledDepots\"\n\t{\n\t\t\"228989\"\n\t\t{\n\t\t\t\"manifest\"\t\t\"5753583882400741046\"\n\t\t\t\"size\"\t\t\"25674515\"\n\t\t}\n\t\t\"229007\"\n\t\t{\n\t\t\t\"manifest\"\t\t\"4477590687906973371\"\n\t\t\t\"size\"\t\t\"117381405\"\n\t\t}\n\t}\n\t\"InstallScripts\"\n\t{\n\t\t\"228989\"\t\t\"_CommonRedist\\\\vcredist\\\\2022\\\\installscript.vdf\"\n\t\t\"229007\"\t\t\"_CommonRedist\\\\DotNet\\\\4.8\\\\installscript.vdf\"\n\t}\n\t\"UserConfig\"\n\t{\n\t}\n\t\"MountedConfig\"\n\t{\n\t}\n}\n"; + + /// The captured client acf for Brawlhalla (LastOwner replaced). + const BRAWLHALLA_ACF: &str = "\"AppState\"\n{\n\t\"appid\"\t\t\"291550\"\n\t\"Universe\"\t\t\"1\"\n\t\"name\"\t\t\"Brawlhalla\"\n\t\"StateFlags\"\t\t\"4\"\n\t\"installdir\"\t\t\"Brawlhalla\"\n\t\"LastUpdated\"\t\t\"1794027736\"\n\t\"LastPlayed\"\t\t\"0\"\n\t\"SizeOnDisk\"\t\t\"1565156559\"\n\t\"StagingSize\"\t\t\"0\"\n\t\"buildid\"\t\t\"26465982\"\n\t\"LastOwner\"\t\t\"76561198000000001\"\n\t\"DownloadType\"\t\t\"1\"\n\t\"UpdateResult\"\t\t\"0\"\n\t\"BytesToDownload\"\t\t\"1551111680\"\n\t\"BytesDownloaded\"\t\t\"1551111680\"\n\t\"BytesToStage\"\t\t\"1594368732\"\n\t\"BytesStaged\"\t\t\"1594368732\"\n\t\"TargetBuildID\"\t\t\"26465982\"\n\t\"AutoUpdateBehavior\"\t\t\"0\"\n\t\"AllowOtherDownloadsWhileRunning\"\t\t\"0\"\n\t\"ScheduledAutoUpdate\"\t\t\"0\"\n\t\"InstalledDepots\"\n\t{\n\t\t\"291551\"\n\t\t{\n\t\t\t\"manifest\"\t\t\"4224536525702420323\"\n\t\t\t\"size\"\t\t\"1565156559\"\n\t\t}\n\t}\n\t\"SharedDepots\"\n\t{\n\t\t\"228988\"\t\t\"228980\"\n\t}\n\t\"UserConfig\"\n\t{\n\t\t\"language\"\t\t\"english\"\n\t}\n\t\"MountedConfig\"\n\t{\n\t\t\"language\"\t\t\"english\"\n\t}\n}\n"; + + struct Fixture { + base: PathBuf, + steam_root: PathBuf, + internal: LibraryRoot, + sd: LibraryRoot, + } + + impl Fixture { + fn new(name: &str) -> Self { + let base = temp_root(name); + let steam_root = base.join("Steam"); + let sd_host = base.join("sd").join("steam"); + fs::create_dir_all(steam_root.join("steamapps")).unwrap(); + fs::create_dir_all(steam_root.join("config")).unwrap(); + fs::create_dir_all(steam_root.join("depotcache")).unwrap(); + fs::create_dir_all(sd_host.join("steamapps")).unwrap(); + for path in libraryfolders_paths(&steam_root) { + fs::write(path, LIBRARYFOLDERS).unwrap(); + } + fs::write( + steam_root.join("steamapps").join("appmanifest_228980.acf"), + REDIST_ACF, + ) + .unwrap(); + Fixture { + internal: LibraryRoot { + host: steam_root.clone(), + guest: "/root/.local/share/Steam".into(), + }, + sd: LibraryRoot { + host: sd_host, + guest: "/mnt/droiddeck-sd".into(), + }, + steam_root, + base, + } + } + + fn libraries(&self) -> Vec { + vec![self.internal.clone(), self.sd.clone()] + } + } + + fn brawlhalla_plan() -> AppPlan { + AppPlan { + app_id: 291550, + name: "Brawlhalla".into(), + install_dir: "Brawlhalla".into(), + build_id: 26465982, + language: "english".into(), + ..Default::default() + } + } + + fn vc2019_manifest() -> ContentManifest { + let file = |name: &str, flags: u32| FileMapping { + filename: name.into(), + flags, + ..Default::default() + }; + ContentManifest { + files: vec![ + file("_CommonRedist/vcredist/2019", 64), + file("_CommonRedist/vcredist/2019/VC_redist.x64.exe", 0), + file("_CommonRedist/vcredist/2019/VC_redist.x86.exe", 0), + file("_CommonRedist/vcredist/2019/installscript.vdf", 256), + ], + ..Default::default() + } + } + + fn register_brawlhalla(fx: &Fixture) { + let plan = brawlhalla_plan(); + let depots = [InstalledDepot { + depot_id: 291551, + manifest_id: 4224536525702420323, + size: 1565156559, + dlc_app_id: 0, + }]; + let shared = SharedInstall { + depot_id: 228988, + from_app_id: 228980, + from_name: "Steamworks Common Redistributables".into(), + from_install_dir: "Steamworks Shared".into(), + from_build_id: 24098430, + manifest_id: 6645201662696499616, + size: 29212173, + install_script: install_script_path(&vc2019_manifest()), + library: shared_app_library(228980, &fx.steam_root, &fx.libraries()), + }; + assert_eq!(shared.library, fx.internal); + assert!(!register_shared_depot(&shared, OWNER, 1794027736).unwrap()); + write_game_acf( + &fx.sd, + &GameRegistration { + plan: &plan, + owner_steam_id: OWNER, + depots: &depots, + shared: &[(228988, 228980)], + install_scripts: &[], + bytes_downloaded: 1551111680, + bytes_staged: 1594368732, + now: 1794027736, + }, + ) + .unwrap(); + assert!(library_registered(&fx.steam_root, "/mnt/droiddeck-sd/")); + assert!(!library_registered(&fx.steam_root, "/mnt/elsewhere")); + assert_eq!( + update_libraryfolders(&fx.steam_root, &fx.sd.guest, 291550, true).unwrap(), + 2 + ); + } + + #[test] + fn registration_reproduces_the_captured_client_install() { + let fx = Fixture::new("install"); + register_brawlhalla(&fx); + + let acf = fs::read_to_string(fx.sd.acf_path(291550)).unwrap(); + assert_eq!(acf, BRAWLHALLA_ACF); + + let redist = kv::parse_file(&fx.internal.acf_path(228980)).unwrap(); + assert_eq!(kv::get_u64(&redist, "SizeOnDisk"), 143055920 + 29212173); + assert_eq!( + installed_manifest(&redist, 228988), + Some(6645201662696499616) + ); + let text = fs::read_to_string(fx.internal.acf_path(228980)).unwrap(); + assert!(text.contains( + "\t\t\"228988\"\t\t\"_CommonRedist\\\\vcredist\\\\2019\\\\installscript.vdf\"\n" + )); + assert!(text.contains("\t\t\"228988\"\n\t\t{\n\t\t\t\"manifest\"\t\t\"6645201662696499616\"\n\t\t\t\"size\"\t\t\"29212173\"\n\t\t}\n")); + // Depot entries are listed by id, as the client lists them. + let pos = |s: &str| text.find(s).unwrap(); + assert!(pos("\t\t\"228988\"\n") < pos("\t\t\"228989\"\n")); + assert!( + pos("\t\t\"228988\"\t\t\"_CommonRedist") < pos("\t\t\"228989\"\t\t\"_CommonRedist") + ); + // Unknown keys and order of the shared manifest are kept. + assert!(text.starts_with("\"AppState\"\n{\n\t\"appid\"\t\t\"228980\"\n")); + + for path in libraryfolders_paths(&fx.steam_root) { + let text = fs::read_to_string(path).unwrap(); + assert!(text.contains("\t\t\"path\"\t\t\"/mnt/droiddeck-sd\"\n\t\t\"label\"\t\t\"SD card\"\n\t\t\"contentid\"\t\t\"-5681848553336386775\"\n\t\t\"totalsize\"\t\t\"989672112128\"\n\t\t\"update_clean_bytes_tally\"\t\t\"0\"\n\t\t\"time_last_update_verified\"\t\t\"0\"\n\t\t\"apps\"\n\t\t{\n\t\t\t\"291550\"\t\t\"0\"\n\t\t}\n")); + assert!(text.contains("\t\t\t\"228980\"\t\t\"172268093\"\n")); + } + // Registering twice changes nothing. + register_brawlhalla(&fx); + assert_eq!( + fs::read_to_string(fx.sd.acf_path(291550)).unwrap(), + BRAWLHALLA_ACF + ); + let redist = kv::parse_file(&fx.internal.acf_path(228980)).unwrap(); + assert_eq!(kv::get_u64(&redist, "SizeOnDisk"), 143055920 + 29212173); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn merge_keeps_unknown_keys_and_user_settings() { + let fx = Fixture::new("merge"); + let path = fx.sd.acf_path(291550); + fs::write( + &path, + "\"AppState\"\n{\n\t\"appid\"\t\t\"291550\"\n\t\"LastPlayed\"\t\t\"1700000000\"\n\t\"AutoUpdateBehavior\"\t\t\"1\"\n\t\"UserConfig\"\n\t{\n\t\t\"BetaKey\"\t\t\"\"\n\t}\n\t\"SomethingNew\"\t\t\"x\"\n}\n", + ) + .unwrap(); + register_brawlhalla(&fx); + let acf = kv::parse_file(&path).unwrap(); + assert_eq!(kv::get_str(&acf, "LastPlayed").unwrap(), "1700000000"); + assert_eq!(kv::get_str(&acf, "AutoUpdateBehavior").unwrap(), "1"); + assert_eq!(kv::get_str(&acf, "SomethingNew").unwrap(), "x"); + let user = acf.child("UserConfig").unwrap(); + assert!(user.child("BetaKey").is_some()); + assert_eq!(kv::get_str(user, "language").unwrap(), "english"); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn takeover_removes_a_half_finished_client_download() { + let fx = Fixture::new("takeover"); + assert_eq!(takeover(&fx.sd, 291550, 26465982).unwrap(), Takeover::Fresh); + let steamapps = fx.sd.steamapps(); + fs::create_dir_all(steamapps.join("downloading/291550/x")).unwrap(); + fs::create_dir_all(steamapps.join("temp/291550")).unwrap(); + fs::write( + fx.sd.acf_path(291550), + "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"1026\"\n\t\"buildid\"\t\t\"0\"\n}\n", + ) + .unwrap(); + assert_eq!( + takeover(&fx.sd, 291550, 26465982).unwrap(), + Takeover::TookOver + ); + assert!(fx.sd.acf_path(291550).exists()); // its settings merge into the final one + assert!(!steamapps.join("downloading/291550").exists()); + assert!(!steamapps.join("temp/291550").exists()); + assert_eq!(takeover(&fx.sd, 291550, 26465982).unwrap(), Takeover::Fresh); // a retry + fs::write( + fx.sd.acf_path(291550), + "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"6\"\n\t\"buildid\"\t\t\"1\"\n}\n", + ) + .unwrap(); + fs::create_dir_all(steamapps.join("downloading/291550")).unwrap(); + assert_eq!(takeover(&fx.sd, 291550, 26465982).unwrap(), Takeover::Update); + assert!(steamapps.join("downloading/291550").exists()); // the client's update staging stays + fs::write(fx.sd.acf_path(291550), BRAWLHALLA_ACF).unwrap(); + assert_eq!( + takeover(&fx.sd, 291550, 26465982).unwrap(), + Takeover::AlreadyInstalled + ); + assert_eq!(takeover(&fx.sd, 291550, 1).unwrap(), Takeover::Update); // left to the client + assert!(state_is_finished(4)); + assert!(!state_is_finished(6)); + assert!(!state_is_finished(1)); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn uninstall_matches_the_captured_client_uninstall() { + let fx = Fixture::new("uninstall"); + register_brawlhalla(&fx); + let game_dir = fx.sd.common_dir("Brawlhalla"); + fs::create_dir_all(game_dir.join("bin")).unwrap(); + fs::write(game_dir.join("bin/Brawlhalla.exe"), b"x").unwrap(); + let shared_dir = fx + .internal + .common_dir("Steamworks Shared") + .join("_CommonRedist/vcredist/2019"); + fs::create_dir_all(&shared_dir).unwrap(); + for name in [ + "VC_redist.x64.exe", + "VC_redist.x86.exe", + "installscript.vdf", + ] { + fs::write(shared_dir.join(name), b"x").unwrap(); + } + let compat = fx.sd.steamapps().join("compatdata/291550/pfx"); + fs::create_dir_all(&compat).unwrap(); + let shader = fx.steam_root.join("steamapps/shadercache/291550"); + fs::create_dir_all(&shader).unwrap(); + let cached = fx + .steam_root + .join("depotcache/291551_4224536525702420323.manifest"); + fs::write(&cached, b"m").unwrap(); + let shared_cached = fx + .steam_root + .join("depotcache/228988_6645201662696499616.manifest"); + fs::write(&shared_cached, b"m").unwrap(); + + let files = |app: u32, depot: u32, manifest: u64| { + (app == 228980 && depot == 228988 && manifest == 6645201662696499616) + .then(|| manifest_file_list(&vc2019_manifest())) + }; + let report = uninstall(291550, &fx.steam_root, &fx.sd, &fx.libraries(), &files).unwrap(); + assert_eq!(report.removed_shared, vec![228988]); + assert!(!game_dir.exists()); + assert!(!fx.sd.acf_path(291550).exists()); + assert!(!cached.exists()); + assert!(shared_cached.exists()); + assert!(!shader.exists()); + assert!(compat.exists()); + assert!(shared_dir.exists()); + assert_eq!(fs::read_dir(&shared_dir).unwrap().count(), 0); + assert_eq!( + fs::read_to_string(fx.internal.acf_path(228980)).unwrap(), + REDIST_ACF + ); + for path in libraryfolders_paths(&fx.steam_root) { + assert_eq!(fs::read_to_string(path).unwrap(), LIBRARYFOLDERS); + } + assert_eq!( + uninstall(291550, &fx.steam_root, &fx.sd, &fx.libraries(), &files).unwrap_err(), + "not_installed" + ); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn shared_depot_used_by_another_game_is_kept() { + let fx = Fixture::new("shared_in_use"); + register_brawlhalla(&fx); + let other = BRAWLHALLA_ACF + .replace("291550", "993090") + .replace("\"Brawlhalla\"", "\"Lossless Scaling\""); + fs::write(fx.internal.acf_path(993090), other).unwrap(); + let report = uninstall( + 291550, + &fx.steam_root, + &fx.sd, + &fx.libraries(), + &|_, _, _| Some(vec!["_CommonRedist/vcredist/2019/VC_redist.x64.exe".into()]), + ) + .unwrap(); + assert!(report.removed_shared.is_empty()); + assert!(report.kept_shared.is_empty()); + let redist = kv::parse_file(&fx.internal.acf_path(228980)).unwrap(); + assert_eq!( + installed_manifest(&redist, 228988), + Some(6645201662696499616) + ); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn shared_library_defaults_to_the_steam_root() { + let fx = Fixture::new("shared_default"); + let only_sd = vec![fx.sd.clone()]; + assert_eq!( + shared_app_library(228980, &fx.steam_root, &only_sd), + fx.internal + ); + assert_eq!( + shared_app_library(1, &fx.steam_root, &fx.libraries()), + fx.internal + ); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn new_shared_app_manifest_is_created_when_missing() { + let fx = Fixture::new("new_shared"); + fs::remove_file(fx.internal.acf_path(228980)).unwrap(); + let shared = SharedInstall { + depot_id: 228988, + from_app_id: 228980, + from_name: "Steamworks Common Redistributables".into(), + from_install_dir: "Steamworks Shared".into(), + from_build_id: 24098430, + manifest_id: 6645201662696499616, + size: 29212173, + install_script: Some("_CommonRedist\\vcredist\\2019\\installscript.vdf".into()), + library: fx.internal.clone(), + }; + assert!(register_shared_depot(&shared, OWNER, 5).unwrap()); + let text = fs::read_to_string(fx.internal.acf_path(228980)).unwrap(); + let acf = kv::parse_file(&fx.internal.acf_path(228980)).unwrap(); + assert_eq!(kv::get_u64(&acf, "SizeOnDisk"), 29212173); + let names: Vec<&str> = acf.children.iter().map(|c| c.name.as_str()).collect(); + let pos = |n: &str| names.iter().position(|x| *x == n).unwrap(); + assert!(pos("InstalledDepots") + 1 == pos("InstallScripts")); + assert!(pos("InstallScripts") < pos("UserConfig")); + assert!(text.ends_with("\t\"UserConfig\"\n\t{\n\t}\n\t\"MountedConfig\"\n\t{\n\t}\n}\n")); + let _ = fs::remove_dir_all(&fx.base); + } + + #[test] + fn a_started_install_reads_as_unfinished_and_leaves_a_manifest_alone() { + let dir = std::env::temp_dir().join(format!("dd-started-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let library = LibraryRoot { host: dir.clone(), guest: "/lib".to_string() }; + let plan = AppPlan { + app_id: 42, + name: "Game".to_string(), + install_dir: "Game".to_string(), + build_id: 7, + language: "english".to_string(), + ..Default::default() + }; + write_started_acf(&library, &plan, 1, 2).unwrap(); + let acf = kv::parse_file(&library.acf_path(42)).unwrap(); + assert_eq!(kv::get_u64(&acf, "StateFlags"), 1026); + assert_eq!(kv::get_u64(&acf, "TargetBuildID"), 7); + assert_eq!(takeover(&library, 42, 7).unwrap(), Takeover::Fresh); + fs::write(library.acf_path(42), "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"4\"\n}\n").unwrap(); + write_started_acf(&library, &plan, 1, 2).unwrap(); + assert_eq!(kv::get_u64(&kv::parse_file(&library.acf_path(42)).unwrap(), "StateFlags"), 4); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn staged_client_files_move_into_the_install_folder_without_replacing_files_there() { + let dir = std::env::temp_dir().join(format!("dd-adopt-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let library = LibraryRoot { host: dir.clone(), guest: "/lib".to_string() }; + let staging = library.steamapps().join("downloading/42"); + fs::create_dir_all(staging.join("sub")).unwrap(); + fs::write(staging.join("a.bin"), b"client").unwrap(); + fs::write(staging.join("sub/b.bin"), b"client").unwrap(); + let common = library.common_dir("Game"); + fs::create_dir_all(&common).unwrap(); + fs::write(common.join("a.bin"), b"ours").unwrap(); + assert_eq!(adopt_staged(&library, 42, "Game"), 1); + assert_eq!(fs::read(common.join("a.bin")).unwrap(), b"ours"); + assert_eq!(fs::read(common.join("sub/b.bin")).unwrap(), b"client"); + assert_eq!(adopt_staged(&library, 42, ".."), 0); + fs::write(staging.join("c.bin"), b"client").unwrap(); + fs::write(library.acf_path(42), "\"AppState\"\n{\n\t\"StateFlags\"\t\t\"6\"\n}\n").unwrap(); + assert_eq!(adopt_staged(&library, 42, "Game"), 0); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/app/src/main/rust/stores/src/steam/session.rs b/app/src/main/rust/stores/src/steam/session.rs new file mode 100644 index 0000000000..14fe32b448 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/session.rs @@ -0,0 +1,556 @@ +//! The one process-wide Steam session: connect to a CM over WebSocket, log on with the saved +//! refresh token, then answer the store's requests (PICS, depot keys, manifest request codes, +//! CDN servers, free licenses) as blocking calls with timeouts. + +use crate::steam::cm_client::{ + CMClientCore, ClientState, OutboundProtoMessage, OutboundServiceCall, +}; +use crate::steam::cm_runtime::CMClientRuntime; +use crate::steam::library::Library; +use crate::steam::pb::ccontentserverdirectory::{ + CContentServerDirectoryGetManifestRequestCodeResponse, + CContentServerDirectoryGetServersForSteamPipeResponse, CContentServerDirectoryServerInfo, +}; +use crate::steam::pb::cmsg_client_get_depot_decryption_key::CMsgClientGetDepotDecryptionKeyResponse; +use crate::steam::pb::cmsg_client_pics::{ + CMsgClientPICSAccessTokenResponse, CMsgClientPICSProductInfoResponse, PicsAppInfoReq, + PicsPackageInfoReq, +}; +use crate::steam::pb::cmsg_client_request_free_license::CMsgClientRequestFreeLicenseResponse; +use crate::steam::signin::SavedLogin; +use crate::steam::vdf::KVNode; +use crate::steam::ws_connection::WsConnection; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); +const LOGON_TIMEOUT: Duration = Duration::from_secs(20); +const LICENSE_LIST_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_CM_ATTEMPTS: usize = 4; +const MAX_RESOLVE_ATTEMPTS: u32 = 4; +const ERESULT_OK: i32 = 1; +/// EResults after which another CM is worth a try (the token itself was not refused). +const RETRY_ON_ANOTHER_CM: [i32; 3] = [20, 48, 3]; + +pub struct Session { + runtime: Arc, + pub account: String, + pub steam_id: u64, + pub ca_bundle_path: String, + library: Mutex>>, + /// Bumped by [`Session::forget_library`]; a load started before it is not published. + library_generation: std::sync::atomic::AtomicU64, +} + +static SESSION: Mutex>> = Mutex::new(None); + +pub fn eresult_name(eresult: i32) -> &'static str { + match eresult { + 1 => "OK", + 2 => "Fail", + 3 => "NoConnection", + 5 => "InvalidPassword", + 6 => "LoggedInElsewhere", + 15 => "AccessDenied", + 18 => "AccountNotFound", + 20 => "ServiceUnavailable", + 26 => "Revoked", + 27 => "Expired", + 48 => "TryAnotherCM", + 63 => "AccountLogonDenied", + 84 => "RateLimitExceeded", + 87 => "AccountLoginDeniedThrottle", + _ => "", + } +} + +/// The live session, if one is logged on. +pub fn current() -> Option> { + let guard = SESSION.lock().expect("session poisoned"); + guard.as_ref().filter(|s| s.is_logged_on()).cloned() +} + +/// Logs on with `login` unless a live session exists; returns the live session. +pub fn sign_in(login: &SavedLogin, ca_bundle_path: &str) -> Result, String> { + if let Some(live) = current() { + return Ok(live); + } + sign_out(); + let runtime = connect_and_logon(login, ca_bundle_path)?; + let steam_id = runtime.core().steam_id(); + let session = Arc::new(Session { + runtime, + account: login.account.clone(), + steam_id: if steam_id != 0 { + steam_id + } else { + login.steam_id + }, + ca_bundle_path: ca_bundle_path.to_string(), + library: Mutex::new(None), + library_generation: std::sync::atomic::AtomicU64::new(0), + }); + *SESSION.lock().expect("session poisoned") = Some(Arc::clone(&session)); + Ok(session) +} + +/// Logs off and drops the session. Never touches the Steam client's files. +pub fn sign_out() { + let previous = SESSION.lock().expect("session poisoned").take(); + if let Some(session) = previous { + session.log_off(); + } +} + +fn cm_urls(ca_bundle_path: &str) -> Vec { + let directory = crate::steam::steam_directory::SteamDirectoryClient::new(ca_bundle_path); + let result = directory.fetch(0, crate::steam::steam_directory::DEFAULT_TIMEOUT); + let mut urls: Vec = Vec::new(); + let servers = if result.ok() { + result.servers + } else { + crate::steam::log(&format!("cm directory failed: {}", result.error)); + Vec::new() + }; + for server in servers + .into_iter() + .chain(crate::steam::cm_server_list::hardcoded_fallback_servers()) + { + let url = server.websocket_url(); + if !url.is_empty() && !urls.contains(&url) { + urls.push(url); + } + } + urls +} + +fn wait_until(timeout: Duration, mut done: impl FnMut() -> bool) -> bool { + let deadline = Instant::now() + timeout; + loop { + if done() { + return true; + } + if Instant::now() >= deadline { + return false; + } + thread::sleep(Duration::from_millis(50)); + } +} + +fn connect_and_logon( + login: &SavedLogin, + ca_bundle_path: &str, +) -> Result, String> { + let urls = cm_urls(ca_bundle_path); + let mut last_error = "logon_failed: no CM server".to_string(); + for url in urls.iter().take(MAX_CM_ATTEMPTS) { + let core = Arc::new(CMClientCore::default()); + let runtime = CMClientRuntime::new(Arc::clone(&core), Box::new(WsConnection::new())); + if !ca_bundle_path.is_empty() { + runtime.set_ca_bundle_path(ca_bundle_path); + } + if !runtime.connect(url) { + last_error = "logon_failed: connect".to_string(); + continue; + } + if !wait_until(CONNECT_TIMEOUT, || core.state() == ClientState::Connected) { + runtime.disconnect(); + last_error = "logon_failed: CM did not answer".to_string(); + continue; + } + let message = + core.build_logon_with_refresh_token(&login.token, &login.account, login.steam_id); + if !core.enqueue_proto_message(message) { + runtime.disconnect(); + last_error = "logon_failed: connection dropped".to_string(); + continue; + } + runtime.flush_outbound(); + let settled = wait_until(LOGON_TIMEOUT, || { + core.state() == ClientState::LoggedOn + || core.last_logon_eresult() != 0 + || core.state() == ClientState::Disconnected + }); + if core.state() == ClientState::LoggedOn { + crate::steam::log(&format!( + "logged on steam_id={} cell={}", + core.steam_id(), + core.cell_id() + )); + wait_until(LICENSE_LIST_TIMEOUT, || core.license_list().is_some()); + return Ok(runtime); + } + let eresult = core.last_logon_eresult(); + runtime.disconnect(); + if !settled { + last_error = "logon_failed: no logon response".to_string(); + continue; + } + if eresult == 0 { + last_error = "logon_failed: connection dropped".to_string(); + continue; + } + last_error = format!("logon_failed: eresult={eresult} {}", eresult_name(eresult)) + .trim_end() + .to_string(); + crate::steam::log(&last_error); + if !RETRY_ON_ANOTHER_CM.contains(&eresult) { + break; + } + } + Err(last_error) +} + +pub enum KeyResolution { + Granted(Vec), + AccessDenied, + Cancelled, + Unavailable, +} + +pub enum CodeResolution { + Code(u64), + AccessDenied, + Cancelled, + Unavailable, +} + +impl Session { + pub fn is_logged_on(&self) -> bool { + self.runtime.core().state() == ClientState::LoggedOn + } + + fn log_off(&self) { + let core = self.runtime.core(); + if core.enqueue_proto_message(core.build_logoff()) { + self.runtime.flush_outbound(); + thread::sleep(Duration::from_millis(500)); + } + self.runtime.disconnect(); + } + + pub fn core(&self) -> &Arc { + self.runtime.core() + } + + fn proto_response(&self, timeout: Duration, build: F) -> Option<(i32, Vec)> + where + F: FnOnce(&CMClientCore, u64) -> Option, + { + if !self.is_logged_on() { + return None; + } + let job_id = self.runtime.next_job_id(); + let message = build(self.runtime.core(), job_id)?; + let (tx, rx) = mpsc::channel(); + self.runtime.track_job( + job_id, + move |job| { + let _ = tx.send((!job.synthetic_failure).then_some((job.eresult, job.body))); + }, + Some(timeout), + ); + if !self.runtime.core().enqueue_wire(message.wire) { + return None; + } + self.runtime.flush_outbound(); + rx.recv_timeout(timeout + Duration::from_secs(1)) + .ok() + .flatten() + } + + fn service_response(&self, timeout: Duration, build: F) -> Option<(i32, Vec)> + where + F: FnOnce(&CMClientCore, u64) -> Option, + { + if !self.is_logged_on() { + return None; + } + let job_id = self.runtime.next_job_id(); + let call = build(self.runtime.core(), job_id)?; + let (tx, rx) = mpsc::channel(); + self.runtime.track_job( + job_id, + move |job| { + let _ = tx.send((!job.synthetic_failure).then_some((job.eresult, job.body))); + }, + Some(timeout), + ); + if !self.runtime.core().enqueue_wire(call.wire) { + return None; + } + self.runtime.flush_outbound(); + rx.recv_timeout(timeout + Duration::from_secs(1)) + .ok() + .flatten() + } + + pub fn pics_access_tokens( + &self, + packages: Vec, + apps: Vec, + ) -> Option { + let (eresult, body) = self.proto_response(REQUEST_TIMEOUT, |core, job| { + core.build_pics_access_tokens(packages, apps, job) + })?; + if eresult <= 0 { + return None; + } + CMsgClientPICSAccessTokenResponse::deserialize(&body) + } + + /// PICS product info; large appinfo the CM delivers over HTTP is fetched here. + pub fn pics_product_info( + &self, + packages: Vec, + apps: Vec, + ) -> Option { + let (eresult, body) = self.proto_response(Duration::from_secs(60), |core, job| { + core.build_pics_product_info(packages, apps, false, job) + })?; + if eresult <= 0 { + return None; + } + let mut response = CMsgClientPICSProductInfoResponse::deserialize(&body)?; + self.hydrate_http_appinfo(&mut response); + Some(response) + } + + fn hydrate_http_appinfo(&self, response: &mut CMsgClientPICSProductInfoResponse) { + if response.http_host.is_empty() { + return; + } + let host = response.http_host.clone(); + let targets: Vec = response + .apps + .iter() + .enumerate() + .filter(|(_, app)| !app.missing_token && app.buffer.is_empty() && !app.sha.is_empty()) + .map(|(idx, _)| idx) + .collect(); + if targets.is_empty() { + return; + } + let queue = Mutex::new(targets.into_iter()); + let results: Mutex)>> = Mutex::new(Vec::new()); + let apps = &response.apps; + let workers = queue.lock().expect("queue poisoned").len().clamp(1, 8); + thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| loop { + let next = queue.lock().expect("queue poisoned").next(); + let Some(idx) = next else { + return; + }; + let app = &apps[idx]; + if let Some(buffer) = crate::steam::cdn::fetch_appinfo( + &host, + app.appid, + &app.sha, + &self.ca_bundle_path, + REQUEST_TIMEOUT, + ) { + results + .lock() + .expect("results poisoned") + .push((idx, buffer)); + } + }); + } + }); + for (idx, buffer) in results.into_inner().expect("results poisoned") { + response.apps[idx].buffer = buffer; + } + } + + /// The app's appinfo (`appinfo` node), with its PICS access token. + pub fn app_info(&self, app_id: u32) -> Option { + let token = self + .pics_access_tokens(Vec::new(), vec![app_id]) + .and_then(|r| { + r.app_access_tokens + .iter() + .find(|t| t.appid == app_id) + .map(|t| t.access_token) + }) + .unwrap_or(0); + let response = self.pics_product_info( + Vec::new(), + vec![PicsAppInfoReq { + appid: app_id, + access_token: token, + only_public_obsolete: false, + }], + )?; + let app = response + .apps + .into_iter() + .find(|a| a.appid == app_id && !a.buffer.is_empty())?; + let root = crate::steam::vdf::parse_auto(&app.buffer)?; + Some(crate::steam::plan::appinfo_root(&root).clone()) + } + + pub fn library(&self) -> Result, String> { + if let Some(lib) = self.library.lock().expect("library poisoned").as_ref() { + return Ok(Arc::clone(lib)); + } + let generation = self.library_generation.load(Ordering::Acquire); + let lib = Arc::new(Library::load(self)?); + self.publish_library(generation, &lib); + Ok(lib) + } + + /// The owned games, loaded once per session. + pub fn games(&self) -> Result, String> { + let generation = self.library_generation.load(Ordering::Acquire); + let lib = self.library()?; + if let Some(games) = lib.cached_games() { + return Ok(games); + } + let games = lib.load_games(self)?; + self.publish_library(generation, &Arc::new(lib.with_games(games.clone()))); + Ok(games) + } + + fn publish_library(&self, generation: u64, lib: &Arc) { + let mut slot = self.library.lock().expect("library poisoned"); + if self.library_generation.load(Ordering::Acquire) == generation { + *slot = Some(Arc::clone(lib)); + } + } + + pub fn forget_library(&self) { + let mut slot = self.library.lock().expect("library poisoned"); + self.library_generation.fetch_add(1, Ordering::AcqRel); + *slot = None; + } + + /// `CMsgClientRequestFreeLicense` for one app; true when Steam granted it and the license + /// list shows the new package. + pub fn request_free_license(&self, app_id: u32) -> bool { + let Some((_header, body)) = self.proto_response(Duration::from_secs(20), |core, job| { + core.build_request_free_license(&[app_id], job) + }) else { + return false; + }; + let Some(response) = CMsgClientRequestFreeLicenseResponse::deserialize(&body) else { + return false; + }; + let granted = response.is_granted(); + crate::steam::log(&format!( + "free license app={app_id} eresult={} packages={:?}", + response.eresult, response.granted_packageids + )); + if !granted { + return false; + } + let packages = response.granted_packageids.clone(); + let core = self.runtime.core(); + let visible = wait_until(Duration::from_secs(8), || { + core.license_list().is_some_and(|list| { + packages + .iter() + .all(|p| list.iter().any(|l| l.package_id == *p)) + }) + }); + self.forget_library(); + visible || packages.is_empty() + } + + pub fn cdn_servers(&self) -> Option> { + let (eresult, body) = self.service_response(REQUEST_TIMEOUT, |core, job| { + core.build_get_cdn_servers_call(0, job) + })?; + if eresult != ERESULT_OK { + return None; + } + let servers = + CContentServerDirectoryGetServersForSteamPipeResponse::deserialize(&body)?.servers; + let preview = servers + .iter() + .take(4) + .map(|s| s.host.as_str()) + .collect::>() + .join(","); + crate::steam::log(&format!( + "cdn pool: {} server(s) first=[{preview}]", + servers.len() + )); + Some(servers) + } + + pub fn depot_key(&self, app_id: u32, depot_id: u32, cancel: &AtomicBool) -> KeyResolution { + for attempt in 0..MAX_RESOLVE_ATTEMPTS { + if cancel.load(Ordering::Relaxed) { + return KeyResolution::Cancelled; + } + if attempt > 0 { + thread::sleep(Duration::from_millis( + crate::fetch_tuning::retry_backoff_millis(attempt), + )); + if cancel.load(Ordering::Relaxed) { + return KeyResolution::Cancelled; + } + } + let Some((header, body)) = self.proto_response(REQUEST_TIMEOUT, |core, job| { + core.build_get_depot_decryption_key(depot_id, app_id, job) + }) else { + continue; + }; + // An undecodable reply is retried like a missing one. + let Some(r) = CMsgClientGetDepotDecryptionKeyResponse::deserialize(&body) else { + continue; + }; + if r.eresult == ERESULT_OK && r.depot_encryption_key.len() == 32 { + return KeyResolution::Granted(r.depot_encryption_key); + } + crate::steam::log(&format!( + "depot key refused depot={depot_id} header_eresult={header} body_eresult={}", + r.eresult + )); + return KeyResolution::AccessDenied; + } + KeyResolution::Unavailable + } + + pub fn manifest_code( + &self, + app_id: u32, + depot_id: u32, + manifest_id: u64, + cancel: &AtomicBool, + ) -> CodeResolution { + for attempt in 0..MAX_RESOLVE_ATTEMPTS { + if cancel.load(Ordering::Relaxed) { + return CodeResolution::Cancelled; + } + if attempt > 0 { + thread::sleep(Duration::from_millis( + crate::fetch_tuning::retry_backoff_millis(attempt), + )); + if cancel.load(Ordering::Relaxed) { + return CodeResolution::Cancelled; + } + } + let Some((eresult, body)) = self.service_response(REQUEST_TIMEOUT, |core, job| { + core.build_manifest_request_code_call(app_id, depot_id, manifest_id, "public", job) + }) else { + continue; + }; + if eresult == ERESULT_OK { + match CContentServerDirectoryGetManifestRequestCodeResponse::deserialize(&body) { + Some(r) => return CodeResolution::Code(r.manifest_request_code), + None => continue, + } + } + crate::steam::log(&format!( + "manifest code refused depot={depot_id} eresult={eresult}" + )); + return CodeResolution::AccessDenied; + } + CodeResolution::Unavailable + } +} diff --git a/app/src/main/rust/stores/src/steam/signin.rs b/app/src/main/rust/stores/src/steam/signin.rs new file mode 100644 index 0000000000..2248f3c154 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/signin.rs @@ -0,0 +1,519 @@ +//! Reuses the sign-in the Linux Steam client saved ("Remember me"), so the user never signs in +//! twice. Read-only: nothing here writes to the client's files, and the token is never renewed, +//! refreshed or replaced (that would sign the client out). +//! +//! Where it lives, per Steam root: +//! - `config/loginusers.vdf`: the accounts (` { AccountName, RememberPassword, +//! MostRecent, Timestamp … }`). +//! - `local.vdf`: `MachineUserConfigStore/Software/Valve/Steam/ConnectCache`, one entry per +//! remembered account whose key starts with the 8-hex-digit CRC32 of the lowercased account +//! name (e.g. `9a410a9b` + `1`) and whose value is a hex blob. +//! - `~/.steam/registry.vdf`: `Registry/HKCU/Software/Valve/Steam/AutoLoginUser`. +//! +//! The blob: key = SHA-256(lowercased account name); the first 16 bytes are the IV encrypted with +//! AES-256-ECB; the rest is AES-256-CBC with PKCS#7 padding; the plaintext is the refresh-token +//! JWT. Method as documented by deadlock-api-ingest, `src/gc/auth.rs` (MIT, +//! https://github.com/deadlock-api/deadlock-api-ingest). Keys are matched case-insensitively +//! because clients mix casings. +//! +//! The token stays in memory only, is never logged or written anywhere, and is zeroized on drop. + +use crate::steam::crypto::{aes256_cbc_decrypt, aes256_ecb_decrypt_block, sha256}; +use crate::steam::vdf::{self, KVNode}; +use std::fs; +use std::path::{Path, PathBuf}; +use zeroize::{Zeroize, Zeroizing}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SigninError { + /// No Steam root has an account in `loginusers.vdf`. + NoSavedLogin, + /// The account exists but the client kept no token for it (Remember me off, or signed out). + RememberMeOff, + /// A token blob exists but does not decrypt to this account's Steam JWT. + DecryptFailed, +} + +impl SigninError { + pub fn code(self) -> &'static str { + match self { + SigninError::NoSavedLogin => "no_saved_login", + SigninError::RememberMeOff => "remember_me_off", + SigninError::DecryptFailed => "decrypt_failed", + } + } +} + +/// The saved login of one account. `Debug` keeps the token out of any output. +pub struct SavedLogin { + pub account: String, + pub steam_id: u64, + pub steam_root: PathBuf, + pub token: Zeroizing, +} + +impl std::fmt::Debug for SavedLogin { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SavedLogin") + .field("account", &self.account) + .field("steam_id", &self.steam_id) + .field("steam_root", &self.steam_root) + .field("token", &"") + .finish() + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Account { + pub steam_id: u64, + pub account_name: String, + pub remember_password: Option, + pub most_recent: bool, + pub timestamp: u64, + pub root_index: usize, +} + +pub fn child_ci<'a>(node: &'a KVNode, key: &str) -> Option<&'a KVNode> { + node.child(key) +} + +/// Follows `path` from `root` (whose own name is `path[0]`), matching every key case-insensitively. +pub fn find_path<'a>(root: &'a KVNode, path: &[&str]) -> Option<&'a KVNode> { + let (first, rest) = path.split_first()?; + if !root.name.eq_ignore_ascii_case(first) { + return None; + } + rest.iter().try_fold(root, |node, key| child_ci(node, key)) +} + +fn read_vdf(path: &Path) -> Option { + let bytes = fs::read(path).ok()?; + vdf::parse_text(&bytes) +} + +pub fn parse_login_users(root: &KVNode, root_index: usize) -> Vec { + if !root.name.eq_ignore_ascii_case("users") { + return Vec::new(); + } + let mut out = Vec::new(); + for user in &root.children { + let Ok(steam_id) = user.name.parse::() else { + continue; + }; + let Some(name) = child_ci(user, "AccountName").map(|n| n.as_string("")) else { + continue; + }; + if name.is_empty() { + continue; + } + let flag = |key: &str| child_ci(user, key).map(|n| n.as_string("") == "1"); + out.push(Account { + steam_id, + account_name: name, + remember_password: flag("RememberPassword"), + most_recent: flag("MostRecent").unwrap_or(false), + timestamp: child_ci(user, "Timestamp") + .map(|n| n.as_uint(0)) + .unwrap_or(0), + root_index, + }); + } + out +} + +pub fn auto_login_user(registry: &KVNode) -> Option { + let user = find_path( + registry, + &[ + "Registry", + "HKCU", + "Software", + "Valve", + "Steam", + "AutoLoginUser", + ], + )? + .as_string(""); + (!user.is_empty()).then_some(user) +} + +/// `AutoLoginUser` when it names a known account, else the `MostRecent` one, else the newest +/// `Timestamp` (Linux clients may omit `MostRecent`). +pub fn choose_account<'a>( + accounts: &'a [Account], + auto_login: Option<&str>, +) -> Option<&'a Account> { + if let Some(user) = auto_login { + if let Some(found) = accounts + .iter() + .find(|a| a.account_name.eq_ignore_ascii_case(user)) + { + return Some(found); + } + } + if let Some(found) = accounts.iter().find(|a| a.most_recent) { + return Some(found); + } + accounts.iter().max_by_key(|a| a.timestamp) +} + +pub fn connect_cache_key_prefix(account_name: &str) -> String { + format!( + "{:08x}", + crc32fast::hash(account_name.to_lowercase().as_bytes()) + ) +} + +/// The hex blob for `account_name` in a parsed `local.vdf`. +pub fn connect_cache_blob(local: &KVNode, account_name: &str) -> Option { + let cache = find_path( + local, + &[ + "MachineUserConfigStore", + "Software", + "Valve", + "Steam", + "ConnectCache", + ], + )?; + let prefix = connect_cache_key_prefix(account_name); + cache + .children + .iter() + .find(|entry| { + entry + .name + .get(..prefix.len()) + .is_some_and(|p| p.eq_ignore_ascii_case(&prefix)) + }) + .map(|entry| entry.as_string("")) + .filter(|value| !value.is_empty()) +} + +fn decode_hex(text: &str) -> Option> { + let text = text.trim(); + if !text.len().is_multiple_of(2) { + return None; + } + let digit = |c: u8| -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } + }; + text.as_bytes() + .chunks(2) + .map(|pair| Some((digit(pair[0])? << 4) | digit(pair[1])?)) + .collect() +} + +/// Decrypts a ConnectCache blob (hex) into the refresh-token JWT. +pub fn decrypt_connect_cache(hex_blob: &str, account_name: &str) -> Option> { + let blob = Zeroizing::new(decode_hex(hex_blob)?); + if blob.len() < 32 { + return None; + } + let mut key = sha256(account_name.to_lowercase().as_bytes()); + let mut wrapped = [0u8; 16]; + wrapped.copy_from_slice(&blob[..16]); + let iv = aes256_ecb_decrypt_block(&key, &wrapped); + let plain = iv.and_then(|iv| aes256_cbc_decrypt(&key, &iv, &blob[16..])); + key.zeroize(); + let mut plain = plain?; + let text = match String::from_utf8(std::mem::take(&mut plain)) { + Ok(text) => Zeroizing::new(text), + Err(err) => { + let mut bytes = err.into_bytes(); + bytes.zeroize(); + return None; + } + }; + Some(text) +} + +fn base64url_decode(text: &str) -> Option> { + let mut s: String = text + .chars() + .map(|c| match c { + '-' => '+', + '_' => '/', + other => other, + }) + .collect(); + while !s.len().is_multiple_of(4) { + s.push('='); + } + crate::steam::base64::decode(&s) +} + +/// The SteamID64 a Steam JWT was issued for (`sub`), if it is a Steam JWT. +pub fn jwt_steam_id(jwt: &str) -> Option { + let mut parts = jwt.split('.'); + let (_header, payload, _sig) = (parts.next()?, parts.next()?, parts.next()?); + if parts.next().is_some() { + return None; + } + let bytes = base64url_decode(payload)?; + let json: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + if json.get("iss").and_then(|v| v.as_str()) != Some("steam") { + return None; + } + json.get("sub")?.as_str()?.parse().ok() +} + +/// Loads the saved login. `steam_roots` are host paths of Steam roots, searched in order; +/// `registry_vdf` is `~/.steam/registry.vdf` (may be missing). +pub fn load_saved_login( + steam_roots: &[PathBuf], + registry_vdf: Option<&Path>, +) -> Result { + let mut accounts = Vec::new(); + for (idx, root) in steam_roots.iter().enumerate() { + if let Some(users) = read_vdf(&root.join("config").join("loginusers.vdf")) { + accounts.extend(parse_login_users(&users, idx)); + } + } + let auto_login = registry_vdf + .and_then(read_vdf) + .and_then(|reg| auto_login_user(®)); + let mut account = choose_account(&accounts, auto_login.as_deref()) + .ok_or(SigninError::NoSavedLogin)? + .clone(); + if account.remember_password == Some(false) { + // The same account may be remembered by the other client's root. + account = accounts + .iter() + .find(|a| a.steam_id == account.steam_id && a.remember_password != Some(false)) + .ok_or(SigninError::RememberMeOff)? + .clone(); + } + + let mut order: Vec = vec![account.root_index]; + order.extend((0..steam_roots.len()).filter(|&i| i != account.root_index)); + let mut found_blob = false; + for idx in order { + let Some(local) = read_vdf(&steam_roots[idx].join("local.vdf")) else { + continue; + }; + let Some(mut blob) = connect_cache_blob(&local, &account.account_name) else { + continue; + }; + found_blob = true; + let token = decrypt_connect_cache(&blob, &account.account_name); + blob.zeroize(); + let Some(token) = token else { + continue; + }; + if jwt_steam_id(&token) != Some(account.steam_id) { + continue; + } + return Ok(SavedLogin { + account: account.account_name.clone(), + steam_id: account.steam_id, + steam_root: steam_roots[idx].clone(), + token, + }); + } + Err(if found_blob { + SigninError::DecryptFailed + } else { + SigninError::RememberMeOff + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::steam::crypto::{aes256_cbc_encrypt, aes256_ecb_encrypt_block}; + + const ID: u64 = 76561198000000001; + + fn jwt_for(steam_id: u64) -> String { + let payload = format!(r#"{{"iss":"steam","sub":"{steam_id}","aud":["client","web"]}}"#); + let b64 = crate::steam::base64::encode(payload.as_bytes()) + .trim_end_matches('=') + .replace('+', "-") + .replace('/', "_"); + format!("eyJhbGciOiJFZERTQSJ9.{b64}.c2ln") + } + + /// Same scheme the client uses: IV wrapped with AES-256-ECB, body AES-256-CBC + PKCS#7. + fn encrypt_blob(token: &str, account: &str) -> String { + let key = sha256(account.to_lowercase().as_bytes()); + let iv = [0x5au8; 16]; + let mut out = aes256_ecb_encrypt_block(&key, &iv).unwrap().to_vec(); + out.extend(aes256_cbc_encrypt(&key, &iv, token.as_bytes()).unwrap()); + out.iter().map(|b| format!("{b:02x}")).collect() + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "droiddeck_steam_signin_{name}_{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(dir.join("config")).unwrap(); + dir + } + + fn write_root(root: &Path, users: &str, cache_entries: &str) { + fs::write(root.join("config").join("loginusers.vdf"), users).unwrap(); + fs::write( + root.join("local.vdf"), + format!( + "\"MachineUserConfigStore\"\n{{\n\t\"Software\"\n\t{{\n\t\t\"valve\"\n\t\t{{\n\t\t\t\"steam\"\n\t\t\t{{\n\t\t\t\t\"ConnectCache\"\n\t\t\t\t{{\n{cache_entries}\t\t\t\t}}\n\t\t\t}}\n\t\t}}\n\t}}\n}}\n" + ), + ) + .unwrap(); + } + + fn user_block(id: u64, name: &str, extra: &str) -> String { + format!("\t\"{id}\"\n\t{{\n\t\t\"AccountName\"\t\t\"{name}\"\n{extra}\t}}\n") + } + + #[test] + fn crc_prefix_is_zero_padded_lowercase_hex_of_lowercased_name() { + assert_eq!( + connect_cache_key_prefix("Ada"), + format!("{:08x}", crc32fast::hash(b"ada")) + ); + assert_eq!(connect_cache_key_prefix("x").len(), 8); + } + + #[test] + fn encrypts_a_known_token_and_decrypts_it_back() { + let token = jwt_for(ID); + let blob = encrypt_blob(&token, "AdaLovelace"); + let clear = decrypt_connect_cache(&blob, "adalovelace").unwrap(); + assert_eq!(clear.as_str(), token); + assert_eq!(jwt_steam_id(&clear), Some(ID)); + assert!(decrypt_connect_cache(&blob, "someone_else").is_none()); + assert!(decrypt_connect_cache("zz", "adalovelace").is_none()); + assert!(decrypt_connect_cache("00ff", "adalovelace").is_none()); + } + + #[test] + fn loads_saved_login_with_mixed_case_keys_and_auto_login_user() { + let root = temp_dir("load"); + let token = jwt_for(ID); + let other = ID + 1; + let users = format!( + "\"users\"\n{{\n{}{}}}\n", + user_block(other, "second", "\t\t\"MostRecent\"\t\t\"1\"\n"), + user_block(ID, "AdaLovelace", "\t\t\"RememberPassword\"\t\t\"1\"\n"), + ); + let entry = format!( + "\t\t\t\t\t\"{}1\"\t\t\"{}\"\n", + connect_cache_key_prefix("AdaLovelace").to_uppercase(), + encrypt_blob(&token, "AdaLovelace") + ); + write_root(&root, &users, &entry); + let registry = root.join("registry.vdf"); + fs::write( + ®istry, + "\"Registry\"\n{\n\t\"HKCU\"\n\t{\n\t\t\"Software\"\n\t\t{\n\t\t\t\"Valve\"\n\t\t\t{\n\t\t\t\t\"Steam\"\n\t\t\t\t{\n\t\t\t\t\t\"AutoLoginUser\"\t\t\"adalovelace\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n", + ) + .unwrap(); + + let login = load_saved_login(std::slice::from_ref(&root), Some(®istry)).unwrap(); + assert_eq!(login.account, "AdaLovelace"); + assert_eq!(login.steam_id, ID); + assert_eq!(login.token.as_str(), token); + assert!(!format!("{login:?}").contains(&token)); + + // Without AutoLoginUser the MostRecent account wins; it has no token saved. + assert_eq!( + load_saved_login(std::slice::from_ref(&root), None).unwrap_err(), + SigninError::RememberMeOff + ); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn reports_no_login_remember_me_off_and_decrypt_failures() { + let empty = temp_dir("empty"); + assert_eq!( + load_saved_login(std::slice::from_ref(&empty), None).unwrap_err(), + SigninError::NoSavedLogin + ); + + let off = temp_dir("off"); + write_root( + &off, + &format!( + "\"users\"\n{{\n{}}}\n", + user_block(ID, "ada", "\t\t\"RememberPassword\"\t\t\"0\"\n") + ), + "", + ); + assert_eq!( + load_saved_login(std::slice::from_ref(&off), None).unwrap_err(), + SigninError::RememberMeOff + ); + + let wrong = temp_dir("wrong"); + let entry = format!( + "\t\t\t\t\t\"{}1\"\t\t\"{}\"\n", + connect_cache_key_prefix("ada"), + encrypt_blob(&jwt_for(ID + 5), "ada") + ); + write_root( + &wrong, + &format!("\"users\"\n{{\n{}}}\n", user_block(ID, "ada", "")), + &entry, + ); + assert_eq!( + load_saved_login(std::slice::from_ref(&wrong), None).unwrap_err(), + SigninError::DecryptFailed + ); + let remembered = temp_dir("remembered"); + let good = format!( + "\t\t\t\t\t\"{}1\"\t\t\"{}\"\n", + connect_cache_key_prefix("ada"), + encrypt_blob(&jwt_for(ID), "ada") + ); + write_root( + &remembered, + &format!("\"users\"\n{{\n{}}}\n", user_block(ID, "ada", "")), + &good, + ); + let login = load_saved_login(&[off.clone(), remembered.clone()], None).unwrap(); + assert_eq!(login.steam_root, remembered); + for dir in [empty, off, wrong, remembered] { + let _ = fs::remove_dir_all(dir); + } + } + + #[test] + fn newest_timestamp_wins_when_most_recent_is_absent() { + let accounts = vec![ + Account { + steam_id: 1, + account_name: "old".into(), + remember_password: None, + most_recent: false, + timestamp: 10, + root_index: 0, + }, + Account { + steam_id: 2, + account_name: "new".into(), + remember_password: None, + most_recent: false, + timestamp: 20, + root_index: 0, + }, + ]; + assert_eq!(choose_account(&accounts, None).unwrap().steam_id, 2); + assert_eq!(choose_account(&accounts, Some("OLD")).unwrap().steam_id, 1); + assert_eq!( + choose_account(&accounts, Some("nobody")).unwrap().steam_id, + 2 + ); + assert!(choose_account(&[], None).is_none()); + } +} diff --git a/app/src/main/rust/stores/src/steam/steam_directory.rs b/app/src/main/rust/stores/src/steam/steam_directory.rs new file mode 100644 index 0000000000..cc9780a787 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/steam_directory.rs @@ -0,0 +1,238 @@ +use crate::steam::cm_server::{parse_endpoint, CmServer, CmTransport}; +use serde_json::Value; +use std::time::Duration; + +pub const DEFAULT_USER_AGENT: &str = "Valve/Steam HTTP Client 1.0"; +pub const DIRECTORY_ENDPOINT: &str = + "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/"; +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SteamDirectoryResult { + pub servers: Vec, + pub error: String, + pub http_status: i32, +} + +impl SteamDirectoryResult { + pub fn ok(&self) -> bool { + self.error.is_empty() && !self.servers.is_empty() + } +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct SteamDirectoryClient { + ca_bundle_path: String, +} + +impl SteamDirectoryClient { + pub fn new(ca_bundle_path: impl Into) -> Self { + Self { + ca_bundle_path: ca_bundle_path.into(), + } + } + + pub fn ca_bundle_path(&self) -> &str { + &self.ca_bundle_path + } + + pub fn build_url(cell_id: u32) -> String { + format!( + "{DIRECTORY_ENDPOINT}?cellid={cell_id}&cmtype=websockets&maxcount=20&realm=steamglobal" + ) + } + + pub fn fetch(&self, cell_id: u32, timeout: Duration) -> SteamDirectoryResult { + self.fetch_with_user_agent(cell_id, timeout, DEFAULT_USER_AGENT) + } + + pub fn fetch_with_user_agent( + &self, + cell_id: u32, + timeout: Duration, + user_agent: &str, + ) -> SteamDirectoryResult { + let url = SteamDirectoryClient::build_url(cell_id); + match self.http_get_text(&url, timeout, user_agent) { + Ok(response) => { + SteamDirectoryClient::validate_response(response.http_status, &response.body) + } + Err(error) => SteamDirectoryResult { + error, + ..Default::default() + }, + } + } + + pub fn validate_response(http_status: i32, body: &str) -> SteamDirectoryResult { + if http_status != 200 { + return SteamDirectoryResult { + error: "non-200 HTTP status".to_string(), + http_status, + ..Default::default() + }; + } + let mut result = parse_directory_response(body); + result.http_status = http_status; + result + } + + pub fn default_timeout() -> Duration { + DEFAULT_TIMEOUT + } + + fn http_get_text( + &self, + url: &str, + timeout: Duration, + _user_agent: &str, + ) -> Result { + let response = crate::steam::http::get(url, timeout, &self.ca_bundle_path)?; + Ok(HttpTextResponse { + http_status: response.status as i32, + body: String::from_utf8_lossy(&response.body).into_owned(), + }) + } +} + +struct HttpTextResponse { + http_status: i32, + body: String, +} + +pub fn parse_directory_response(body: &str) -> SteamDirectoryResult { + let mut result = SteamDirectoryResult::default(); + let root: Value = match serde_json::from_str(body) { + Ok(v) => v, + Err(e) => { + result.error = format!("json parse error: {e}"); + return result; + } + }; + let Some(response) = root.get("response") else { + result.error = "directory response: missing response".to_string(); + return result; + }; + let ok = response + .get("success") + .map(|s| { + s.as_bool() + .unwrap_or_else(|| s.as_i64().is_some_and(|n| n == 1)) + }) + .unwrap_or(false); + if !ok { + result.error = "directory response: success=false".to_string(); + return result; + } + let Some(list) = response.get("serverlist").and_then(|v| v.as_array()) else { + result.error = "directory response: missing serverlist".to_string(); + return result; + }; + + for entry in list { + let Some(endpoint) = entry.get("endpoint").and_then(|v| v.as_str()) else { + continue; + }; + let Some((host, port)) = parse_endpoint(endpoint) else { + continue; + }; + let transport = entry + .get("type") + .and_then(|v| v.as_str()) + .map(parse_transport) + .unwrap_or(CmTransport::Unknown); + if transport != CmTransport::WebSocket { + continue; + } + result.servers.push(CmServer { + endpoint: endpoint.to_string(), + host, + port, + transport, + realm: entry + .get("realm") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + datacenter: entry + .get("dc") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + load: entry.get("load").and_then(|v| v.as_i64()).unwrap_or(0) as i32, + weighted_load: entry + .get("wtd_load") + .and_then(|v| v.as_f64()) + .unwrap_or(0.0) as f32, + }); + } + result +} + +pub fn parse_transport(s: &str) -> CmTransport { + match s { + "websockets" | "websocket" => CmTransport::WebSocket, + "netfilter" => CmTransport::Tcp, + _ => CmTransport::Unknown, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_websocket_entries_and_filters_tcp() { + let json = r#"{ + "response": { + "success": 1, + "serverlist": [ + {"endpoint":"ext1-sea1.steamserver.net:443","type":"websockets","realm":"steamglobal","dc":"sea1","load":1,"wtd_load":2.5}, + {"endpoint":"tcp.example.com:27017","type":"netfilter"}, + {"endpoint":"bad","type":"websockets"} + ] + } + }"#; + let result = parse_directory_response(json); + assert!(result.error.is_empty()); + assert_eq!(result.servers.len(), 1); + assert_eq!(result.servers[0].host, "ext1-sea1.steamserver.net"); + assert_eq!(result.servers[0].weighted_load, 2.5); + } + + #[test] + fn accepts_boolean_success() { + let json = r#"{"response":{"success":true,"serverlist":[]}}"#; + let result = parse_directory_response(json); + assert!(result.error.is_empty()); + assert!(result.servers.is_empty()); + } + + #[test] + fn builds_directory_url_and_tracks_ca_bundle() { + let client = SteamDirectoryClient::new("/cacert.pem"); + assert_eq!(client.ca_bundle_path(), "/cacert.pem"); + assert_eq!( + SteamDirectoryClient::default_timeout(), + Duration::from_secs(10) + ); + assert_eq!( + SteamDirectoryClient::build_url(123), + "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/?cellid=123&cmtype=websockets&maxcount=20&realm=steamglobal" + ); + } + + #[test] + fn validates_http_status_before_json() { + let result = SteamDirectoryClient::validate_response(503, "{}"); + assert_eq!(result.http_status, 503); + assert_eq!(result.error, "non-200 HTTP status"); + + let ok = SteamDirectoryClient::validate_response( + 200, + r#"{"response":{"success":1,"serverlist":[{"endpoint":"ext1-sea1.steamserver.net:443","type":"websockets"}]}}"#, + ); + assert_eq!(ok.http_status, 200); + assert!(ok.ok()); + } +} diff --git a/app/src/main/rust/stores/src/steam/transport.rs b/app/src/main/rust/stores/src/steam/transport.rs new file mode 100644 index 0000000000..12456d4bcb --- /dev/null +++ b/app/src/main/rust/stores/src/steam/transport.rs @@ -0,0 +1,36 @@ +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum TransportState { + Disconnected, + Connecting, + Connected, + Disconnecting, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum TransportDisconnectReason { + UserInitiated, + RemoteClose, + TlsHandshakeFailed, + NetworkError, + HandshakeTimeout, + Unknown, +} + +pub type MessageCallback = Box; +pub type ConnectedCallback = Box; +pub type DisconnectedCallback = Box; + +pub trait Transport: Send { + fn connect(&mut self, url: &str) -> bool; + fn send(&mut self, data: &[u8]) -> bool; + fn disconnect(&mut self); + fn state(&self) -> TransportState; + + fn set_on_message(&mut self, cb: MessageCallback); + fn set_on_connected(&mut self, cb: ConnectedCallback); + fn set_on_disconnected(&mut self, cb: DisconnectedCallback); + + fn set_ca_bundle_path(&mut self, _path: &str) {} +} diff --git a/app/src/main/rust/stores/src/steam/vdf.rs b/app/src/main/rust/stores/src/steam/vdf.rs new file mode 100644 index 0000000000..b4d9f625df --- /dev/null +++ b/app/src/main/rust/stores/src/steam/vdf.rs @@ -0,0 +1,523 @@ +#[derive(Clone, Debug, PartialEq)] +pub enum KVValue { + Object, + String(String), + Int32(i32), + Float32(f32), + UInt32(u32), + WideString(Vec), + UInt64(u64), + Int64(i64), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct KVNode { + pub name: String, + pub value: KVValue, + pub children: Vec, +} + +impl KVNode { + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + value: KVValue::Object, + children: Vec::new(), + } + } + + pub fn is_object(&self) -> bool { + matches!(self.value, KVValue::Object) + } + + pub fn child(&self, key: &str) -> Option<&KVNode> { + self.children + .iter() + .find(|c| c.name.eq_ignore_ascii_case(key)) + } + + pub fn as_string(&self, fallback: &str) -> String { + match &self.value { + KVValue::String(v) => v.clone(), + KVValue::Int32(v) => v.to_string(), + KVValue::Float32(v) => v.to_string(), + KVValue::UInt32(v) => v.to_string(), + KVValue::UInt64(v) => v.to_string(), + KVValue::Int64(v) => v.to_string(), + _ => fallback.to_string(), + } + } + + pub fn as_int(&self, fallback: i64) -> i64 { + match &self.value { + KVValue::Int32(v) => *v as i64, + KVValue::Int64(v) => *v, + KVValue::UInt32(v) => *v as i64, + KVValue::UInt64(v) => *v as i64, + KVValue::String(v) => v.parse().unwrap_or(fallback), + _ => fallback, + } + } + + pub fn as_uint(&self, fallback: u64) -> u64 { + match &self.value { + KVValue::UInt32(v) => *v as u64, + KVValue::UInt64(v) => *v, + KVValue::Int32(v) => *v as u64, + KVValue::Int64(v) => *v as u64, + KVValue::String(v) => v.parse().unwrap_or(fallback), + _ => fallback, + } + } + + pub fn as_bool(&self, fallback: bool) -> bool { + match &self.value { + KVValue::Int32(v) => *v != 0, + KVValue::Int64(v) => *v != 0, + KVValue::UInt32(v) => *v != 0, + KVValue::UInt64(v) => *v != 0, + KVValue::String(v) + if v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes") => + { + true + } + KVValue::String(v) + if v == "0" || v.eq_ignore_ascii_case("false") || v.eq_ignore_ascii_case("no") => + { + false + } + _ => fallback, + } + } +} + +const TYPE_NONE: u8 = 0x00; +const TYPE_STRING: u8 = 0x01; +const TYPE_INT32: u8 = 0x02; +const TYPE_FLOAT32: u8 = 0x03; +const TYPE_POINTER: u8 = 0x04; +const TYPE_WIDE_STRING: u8 = 0x05; +const TYPE_COLOR: u8 = 0x06; +const TYPE_UINT64: u8 = 0x07; +const TYPE_END: u8 = 0x08; +const TYPE_INT64: u8 = 0x09; +const TYPE_END_ALT: u8 = 0x0b; + +struct Cursor<'a> { + buf: &'a [u8], + pos: usize, + ok: bool, +} + +impl<'a> Cursor<'a> { + fn new(buf: &'a [u8]) -> Self { + Self { + buf, + pos: 0, + ok: true, + } + } + + fn read_u8(&mut self) -> u8 { + if self.pos + 1 > self.buf.len() { + self.ok = false; + return 0; + } + let v = self.buf[self.pos]; + self.pos += 1; + v + } + + fn read_u32_le(&mut self) -> u32 { + if self.pos + 4 > self.buf.len() { + self.ok = false; + return 0; + } + let v = u32::from_le_bytes(self.buf[self.pos..self.pos + 4].try_into().unwrap()); + self.pos += 4; + v + } + + fn read_u64_le(&mut self) -> u64 { + let lo = self.read_u32_le() as u64; + let hi = self.read_u32_le() as u64; + lo | (hi << 32) + } + + fn read_f32_le(&mut self) -> f32 { + f32::from_bits(self.read_u32_le()) + } + + fn read_cstring(&mut self) -> String { + let mut out = Vec::new(); + while self.pos < self.buf.len() { + let b = self.buf[self.pos]; + self.pos += 1; + if b == 0 { + return String::from_utf8_lossy(&out).into_owned(); + } + out.push(b); + } + self.ok = false; + String::from_utf8_lossy(&out).into_owned() + } + + fn read_wide_cstring(&mut self) -> Vec { + let mut out = Vec::new(); + while self.pos + 1 < self.buf.len() { + let u = u16::from_le_bytes([self.buf[self.pos], self.buf[self.pos + 1]]); + self.pos += 2; + if u == 0 { + return out; + } + out.push(u); + } + self.ok = false; + out + } +} + +fn parse_value(cursor: &mut Cursor<'_>, ty: u8, node: &mut KVNode) -> bool { + match ty { + TYPE_NONE => { + while cursor.ok { + let inner_type = cursor.read_u8(); + if !cursor.ok { + return false; + } + if inner_type == TYPE_END || inner_type == TYPE_END_ALT { + return true; + } + let name = cursor.read_cstring(); + if !cursor.ok { + return false; + } + let mut child = KVNode::new(name); + if !parse_value(cursor, inner_type, &mut child) { + return false; + } + node.children.push(child); + } + false + } + TYPE_STRING => { + node.value = KVValue::String(cursor.read_cstring()); + cursor.ok + } + TYPE_INT32 => { + node.value = KVValue::Int32(cursor.read_u32_le() as i32); + cursor.ok + } + TYPE_FLOAT32 => { + node.value = KVValue::Float32(cursor.read_f32_le()); + cursor.ok + } + TYPE_POINTER | TYPE_COLOR => { + node.value = KVValue::UInt32(cursor.read_u32_le()); + cursor.ok + } + TYPE_WIDE_STRING => { + node.value = KVValue::WideString(cursor.read_wide_cstring()); + cursor.ok + } + TYPE_UINT64 => { + node.value = KVValue::UInt64(cursor.read_u64_le()); + cursor.ok + } + TYPE_INT64 => { + node.value = KVValue::Int64(cursor.read_u64_le() as i64); + cursor.ok + } + _ => false, + } +} + +pub fn parse_binary(body: &[u8]) -> Option { + if body.is_empty() { + return None; + } + let mut cursor = Cursor::new(body); + let ty = cursor.read_u8(); + if !cursor.ok { + return None; + } + let mut root = KVNode::new(cursor.read_cstring()); + if !cursor.ok || !parse_value(&mut cursor, ty, &mut root) { + return None; + } + Some(root) +} + +pub fn parse_binary_package(body: &[u8]) -> Option<(u32, KVNode)> { + if body.len() < 4 { + return None; + } + let package_id = u32::from_le_bytes(body[..4].try_into().unwrap()); + Some((package_id, parse_binary(&body[4..])?)) +} + +pub fn parse_auto(body: &[u8]) -> Option { + let first = body + .iter() + .copied() + .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))?; + if first == b'"' { + parse_text(body) + } else { + parse_binary(body) + } +} + +struct TextCursor<'a> { + buf: &'a [u8], + pos: usize, + ok: bool, +} + +impl<'a> TextCursor<'a> { + fn new(buf: &'a [u8]) -> Self { + Self { + buf, + pos: 0, + ok: true, + } + } + + fn eof(&self) -> bool { + self.pos >= self.buf.len() + } + + fn peek(&self) -> u8 { + self.buf.get(self.pos).copied().unwrap_or(0) + } + + fn next(&mut self) -> u8 { + let b = self.peek(); + if !self.eof() { + self.pos += 1; + } + b + } + + fn skip_ws_and_comments(&mut self) { + while self.pos < self.buf.len() { + match self.buf[self.pos] { + b' ' | b'\t' | b'\n' | b'\r' => self.pos += 1, + b'/' if self.buf.get(self.pos + 1) == Some(&b'/') => { + self.pos += 2; + while self.pos < self.buf.len() && self.buf[self.pos] != b'\n' { + self.pos += 1; + } + } + b'/' if self.buf.get(self.pos + 1) == Some(&b'*') => { + self.pos += 2; + while self.pos + 1 < self.buf.len() + && !(self.buf[self.pos] == b'*' && self.buf[self.pos + 1] == b'/') + { + self.pos += 1; + } + self.pos = (self.pos + 2).min(self.buf.len()); + } + _ => break, + } + } + } + + fn read_token(&mut self) -> Option { + self.skip_ws_and_comments(); + if self.eof() { + return None; + } + if self.peek() == b'"' { + self.pos += 1; + let mut out = Vec::new(); + while !self.eof() { + let c = self.next(); + if c == b'"' { + return Some(String::from_utf8_lossy(&out).into_owned()); + } + if c == b'\\' && !self.eof() { + out.push(match self.next() { + b'n' => b'\n', + b't' => b'\t', + b'r' => b'\r', + b'\\' => b'\\', + b'"' => b'"', + other => other, + }); + } else { + out.push(c); + } + } + self.ok = false; + return None; + } + + let start = self.pos; + while !self.eof() { + let c = self.peek(); + if matches!(c, b' ' | b'\t' | b'\n' | b'\r' | b'{' | b'}' | b'"') { + break; + } + self.pos += 1; + } + (self.pos > start).then(|| String::from_utf8_lossy(&self.buf[start..self.pos]).into_owned()) + } +} + +fn parse_text_object(cursor: &mut TextCursor<'_>, parent: &mut KVNode) -> bool { + loop { + cursor.skip_ws_and_comments(); + // An object that ends before its closing brace is a truncated file, not a complete one. + if cursor.eof() { + return false; + } + if cursor.peek() == b'}' { + cursor.pos += 1; + return true; + } + let Some(key) = cursor.read_token() else { + return false; + }; + cursor.skip_ws_and_comments(); + if cursor.eof() { + return false; + } + let mut child = KVNode::new(key); + if cursor.peek() == b'{' { + cursor.pos += 1; + if !parse_text_object(cursor, &mut child) { + return false; + } + } else { + let Some(value) = cursor.read_token() else { + return false; + }; + child.value = KVValue::String(value); + } + parent.children.push(child); + } +} + +pub fn parse_text(body: &[u8]) -> Option { + let mut cursor = TextCursor::new(body); + cursor.skip_ws_and_comments(); + let key = cursor.read_token()?; + cursor.skip_ws_and_comments(); + if cursor.peek() != b'{' { + return None; + } + cursor.pos += 1; + let mut root = KVNode::new(key); + parse_text_object(&mut cursor, &mut root).then_some(root) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refuses_a_truncated_text_object() { + assert!(parse_text(b"\"a\" { \"b\" \"1\" }").is_some()); + assert!(parse_text(b"\"a\" { \"b\" \"1\"").is_none()); + assert!(parse_text(b"\"a\" { \"b\" { \"c\" \"1\" }").is_none()); + assert!(parse_text(b"\"a\" { { }").is_none()); + } + + #[test] + fn parses_text_vdf_with_comments_and_case_insensitive_lookup() { + let text = br#" + // comment + "appinfo" { + "appid" "480" + "Common" { "name" "Spacewar" "type" "Game" } + /* block */ "enabled" "true" + } + "#; + let root = parse_text(text).unwrap(); + assert_eq!(root.name, "appinfo"); + assert_eq!(root.child("APPID").unwrap().as_int(0), 480); + assert_eq!( + root.child("common") + .unwrap() + .child("NAME") + .unwrap() + .as_string(""), + "Spacewar" + ); + assert!(root.child("enabled").unwrap().as_bool(false)); + } + + #[test] + fn parses_binary_tree() { + let mut bytes = Vec::new(); + bytes.extend_from_slice(&[TYPE_NONE]); + bytes.extend_from_slice(b"root\0"); + bytes.extend_from_slice(&[TYPE_STRING]); + bytes.extend_from_slice(b"name\0Spacewar\0"); + bytes.extend_from_slice(&[TYPE_INT32]); + bytes.extend_from_slice(b"appid\0"); + bytes.extend_from_slice(&480i32.to_le_bytes()); + bytes.extend_from_slice(&[TYPE_END]); + + let root = parse_binary(&bytes).unwrap(); + assert!(root.is_object()); + assert_eq!(root.child("name").unwrap().as_string(""), "Spacewar"); + assert_eq!(root.child("appid").unwrap().as_int(0), 480); + } + + #[test] + fn parses_package_prefix() { + let mut bytes = 123u32.to_le_bytes().to_vec(); + bytes.extend_from_slice(&[TYPE_NONE]); + bytes.extend_from_slice(b"package\0"); + bytes.extend_from_slice(&[TYPE_END]); + let (package_id, root) = parse_binary_package(&bytes).unwrap(); + assert_eq!(package_id, 123); + assert_eq!(root.name, "package"); + } + + // Manifest gid/size/download: proves the parser reads download (the 3rd value) + // correctly, ruling out a parser cause for the stale corrupt download sizes. + #[test] + fn parses_manifest_uint64_gid_size_download() { + let gid: u64 = 8072044898226043193; + let size: u64 = 30738676601; + let download: u64 = 15000000000; + let mut b = vec![TYPE_NONE]; + b.extend_from_slice(b"public\0"); + b.push(TYPE_UINT64); + b.extend_from_slice(b"gid\0"); + b.extend_from_slice(&gid.to_le_bytes()); + b.push(TYPE_UINT64); + b.extend_from_slice(b"size\0"); + b.extend_from_slice(&size.to_le_bytes()); + b.push(TYPE_UINT64); + b.extend_from_slice(b"download\0"); + b.extend_from_slice(&download.to_le_bytes()); + b.push(TYPE_END); + + let root = parse_binary(&b).unwrap(); + assert_eq!(root.child("gid").unwrap().as_string(""), gid.to_string()); + assert_eq!(root.child("size").unwrap().as_string(""), size.to_string()); + assert_eq!( + root.child("download").unwrap().as_string(""), + download.to_string() + ); + } + + #[test] + fn parses_manifest_text_vdf() { + let text = br#" + "public" + { + "gid" "8072044898226043193" + "size" "30738676601" + "download" "15000000000" + } + "#; + let root = parse_text(text).unwrap(); + assert_eq!(root.child("size").unwrap().as_string(""), "30738676601"); + assert_eq!(root.child("download").unwrap().as_string(""), "15000000000"); + } +} diff --git a/app/src/main/rust/stores/src/steam/wire_format.rs b/app/src/main/rust/stores/src/steam/wire_format.rs new file mode 100644 index 0000000000..6f7c3d7323 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/wire_format.rs @@ -0,0 +1,154 @@ +pub fn read_u16_le(p: &[u8]) -> u16 { + u16::from_le_bytes([p[0], p[1]]) +} + +pub fn read_u32_le(p: &[u8]) -> u32 { + u32::from_le_bytes([p[0], p[1], p[2], p[3]]) +} + +pub fn read_u64_le(p: &[u8]) -> u64 { + u64::from_le_bytes([p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]]) +} + +pub fn write_u16_le(out: &mut [u8], v: u16) { + out[..2].copy_from_slice(&v.to_le_bytes()); +} + +pub fn write_u32_le(out: &mut [u8], v: u32) { + out[..4].copy_from_slice(&v.to_le_bytes()); +} + +pub fn write_u64_le(out: &mut [u8], v: u64) { + out[..8].copy_from_slice(&v.to_le_bytes()); +} + +pub struct Reader<'a> { + buf: &'a [u8], + pos: usize, + ok: bool, +} + +impl<'a> Reader<'a> { + pub fn new(buf: &'a [u8]) -> Self { + Self { + buf, + pos: 0, + ok: true, + } + } + + pub fn ok(&self) -> bool { + self.ok + } + + pub fn position(&self) -> usize { + self.pos + } + + pub fn remaining(&self) -> usize { + self.buf.len().saturating_sub(self.pos) + } + + pub fn u16(&mut self) -> u16 { + if !self.check(2) { + return 0; + } + let v = read_u16_le(&self.buf[self.pos..]); + self.pos += 2; + v + } + + pub fn u32(&mut self) -> u32 { + if !self.check(4) { + return 0; + } + let v = read_u32_le(&self.buf[self.pos..]); + self.pos += 4; + v + } + + pub fn u64(&mut self) -> u64 { + if !self.check(8) { + return 0; + } + let v = read_u64_le(&self.buf[self.pos..]); + self.pos += 8; + v + } + + pub fn bytes(&mut self, n: usize) -> &'a [u8] { + if !self.check(n) { + return &[]; + } + let out = &self.buf[self.pos..self.pos + n]; + self.pos += n; + out + } + + fn check(&mut self, n: usize) -> bool { + if !self.ok || self.remaining() < n { + self.ok = false; + return false; + } + true + } +} + +pub struct Writer<'a> { + out: &'a mut Vec, +} + +impl<'a> Writer<'a> { + pub fn new(out: &'a mut Vec) -> Self { + Self { out } + } + + pub fn u16(&mut self, v: u16) { + self.out.extend_from_slice(&v.to_le_bytes()); + } + + pub fn u32(&mut self, v: u32) { + self.out.extend_from_slice(&v.to_le_bytes()); + } + + pub fn u64(&mut self, v: u64) { + self.out.extend_from_slice(&v.to_le_bytes()); + } + + pub fn bytes(&mut self, bytes: &[u8]) { + self.out.extend_from_slice(bytes); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reader_writer_little_endian_roundtrip() { + let mut buf = Vec::new(); + let mut writer = Writer::new(&mut buf); + writer.u16(0x1234); + writer.u32(0x89ab_cdef); + writer.u64(0x0123_4567_89ab_cdef); + + assert_eq!( + buf, + [0x34, 0x12, 0xef, 0xcd, 0xab, 0x89, 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01] + ); + + let mut reader = Reader::new(&buf); + assert_eq!(reader.u16(), 0x1234); + assert_eq!(reader.u32(), 0x89ab_cdef); + assert_eq!(reader.u64(), 0x0123_4567_89ab_cdef); + assert!(reader.ok()); + assert_eq!(reader.remaining(), 0); + } + + #[test] + fn reader_short_input_flips_ok() { + let mut reader = Reader::new(&[1, 2, 3]); + assert_eq!(reader.u32(), 0); + assert!(!reader.ok()); + } +} diff --git a/app/src/main/rust/stores/src/steam/ws_connection.rs b/app/src/main/rust/stores/src/steam/ws_connection.rs new file mode 100644 index 0000000000..ccb8fabcd1 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/ws_connection.rs @@ -0,0 +1,536 @@ +use crate::steam::transport::{Transport, TransportDisconnectReason, TransportState}; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; +use tungstenite::error::Error as WsError; +use tungstenite::stream::MaybeTlsStream; +use tungstenite::client::IntoClientRequest; +use tungstenite::Message; + +const NORMAL_CLOSE_CODE: u16 = 1000; +const READ_POLL_TIMEOUT: Duration = Duration::from_millis(100); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15); +/// A send that cannot progress for this long fails the connection instead of blocking the worker. +const SEND_TIMEOUT: Duration = Duration::from_secs(30); + +type MessageCallback = Arc; +type ConnectedCallback = Arc; +type DisconnectedCallback = Arc; + +pub struct WsConnection { + shared: Arc, + sender: Mutex>>, + worker: Mutex>>, +} + +#[derive(Default)] +struct WsConnectionShared { + state: AtomicU8, + user_initiated_close: AtomicBool, + ca_bundle_path: Mutex, + on_message: Mutex>, + on_connected: Mutex>, + on_disconnected: Mutex>, +} + +enum WsCommand { + Send(Vec), + Disconnect, +} + +impl WsConnection { + pub fn new() -> Self { + Self { + shared: Arc::new(WsConnectionShared { + state: AtomicU8::new(TransportState::Disconnected as u8), + user_initiated_close: AtomicBool::new(false), + ca_bundle_path: Mutex::new(String::new()), + on_message: Mutex::new(None), + on_connected: Mutex::new(None), + on_disconnected: Mutex::new(None), + }), + sender: Mutex::new(None), + worker: Mutex::new(None), + } + } + + pub fn set_ca_bundle_path(&self, path: &str) { + *self + .shared + .ca_bundle_path + .lock() + .expect("ws connection poisoned") = path.to_string(); + } + + pub fn ca_bundle_path(&self) -> String { + self.shared + .ca_bundle_path + .lock() + .expect("ws connection poisoned") + .clone() + } + + pub fn state(&self) -> TransportState { + match self.shared.state.load(Ordering::Relaxed) { + 1 => TransportState::Connecting, + 2 => TransportState::Connected, + 3 => TransportState::Disconnecting, + _ => TransportState::Disconnected, + } + } + + pub fn transition_connecting(&self) -> bool { + self.shared + .user_initiated_close + .store(false, Ordering::Relaxed); + self.shared + .state + .compare_exchange( + TransportState::Disconnected as u8, + TransportState::Connecting as u8, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + } + + pub fn mark_connected(&self) { + self.shared.mark_connected(); + } + + pub fn mark_disconnected(&self, close_code: u16, detail: &str, tls_failed: bool) { + self.shared + .mark_disconnected(close_code, detail, tls_failed); + } + + pub fn mark_user_disconnect(&self) { + self.shared + .user_initiated_close + .store(true, Ordering::Relaxed); + self.shared + .state + .store(TransportState::Disconnecting as u8, Ordering::Release); + } + + pub fn deliver_binary(&self, data: &[u8]) { + self.shared.deliver_binary(data); + } + + pub fn set_on_message(&self, cb: F) + where + F: Fn(&[u8]) + Send + Sync + 'static, + { + *self + .shared + .on_message + .lock() + .expect("ws connection poisoned") = Some(Arc::new(cb)); + } + + pub fn set_on_connected(&self, cb: F) + where + F: Fn() + Send + Sync + 'static, + { + *self + .shared + .on_connected + .lock() + .expect("ws connection poisoned") = Some(Arc::new(cb)); + } + + pub fn set_on_disconnected(&self, cb: F) + where + F: Fn(TransportDisconnectReason, &str) + Send + Sync + 'static, + { + *self + .shared + .on_disconnected + .lock() + .expect("ws connection poisoned") = Some(Arc::new(cb)); + } + + fn connect_worker(&self, url: &str) -> bool { + if !self.transition_connecting() { + return false; + } + let (tx, rx) = mpsc::channel(); + *self.sender.lock().expect("ws connection poisoned") = Some(tx); + let shared = Arc::clone(&self.shared); + let url = url.to_string(); + let worker = thread::spawn(move || run_ws_worker(shared, url, rx)); + *self.worker.lock().expect("ws connection poisoned") = Some(worker); + true + } +} + +impl Transport for WsConnection { + fn connect(&mut self, url: &str) -> bool { + self.connect_worker(url) + } + + fn send(&mut self, data: &[u8]) -> bool { + if self.state() != TransportState::Connected { + return false; + } + self.sender + .lock() + .expect("ws connection poisoned") + .as_ref() + .is_some_and(|tx| tx.send(WsCommand::Send(data.to_vec())).is_ok()) + } + + fn disconnect(&mut self) { + if self.state() == TransportState::Disconnected { + return; + } + self.mark_user_disconnect(); + let sent = self + .sender + .lock() + .expect("ws connection poisoned") + .as_ref() + .is_some_and(|tx| tx.send(WsCommand::Disconnect).is_ok()); + if !sent { + self.mark_disconnected(NORMAL_CLOSE_CODE, "client disconnect", false); + } + } + + fn state(&self) -> TransportState { + WsConnection::state(self) + } + + fn set_on_message(&mut self, cb: Box) { + *self + .shared + .on_message + .lock() + .expect("ws connection poisoned") = Some(Arc::from(cb)); + } + + fn set_on_connected(&mut self, cb: Box) { + *self + .shared + .on_connected + .lock() + .expect("ws connection poisoned") = Some(Arc::from(cb)); + } + + fn set_on_disconnected( + &mut self, + cb: Box, + ) { + *self + .shared + .on_disconnected + .lock() + .expect("ws connection poisoned") = Some(Arc::from(cb)); + } + + fn set_ca_bundle_path(&mut self, path: &str) { + WsConnection::set_ca_bundle_path(self, path); + } +} + +impl Default for WsConnection { + fn default() -> Self { + Self::new() + } +} + +impl Drop for WsConnection { + fn drop(&mut self) { + self.disconnect(); + } +} + +impl WsConnectionShared { + fn mark_connected(&self) { + self.state + .store(TransportState::Connected as u8, Ordering::Release); + self.fire_connected(); + } + + /// Publishes Connected only while still Connecting, so a disconnect queued during the + /// handshake wins. + fn mark_connected_if_connecting(&self) -> bool { + let won = self + .state + .compare_exchange( + TransportState::Connecting as u8, + TransportState::Connected as u8, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok(); + if won { + self.fire_connected(); + } + won + } + + fn fire_connected(&self) { + let cb = self + .on_connected + .lock() + .expect("ws connection poisoned") + .clone(); + if let Some(cb) = cb { + cb(); + } + } + + fn mark_disconnected(&self, close_code: u16, detail: &str, tls_failed: bool) { + self.state + .store(TransportState::Disconnected as u8, Ordering::Release); + let reason = if self.user_initiated_close.load(Ordering::Relaxed) { + TransportDisconnectReason::UserInitiated + } else { + map_close_reason(close_code, tls_failed) + }; + let cb = self + .on_disconnected + .lock() + .expect("ws connection poisoned") + .clone(); + if let Some(cb) = cb { + cb(reason, detail); + } + } + + fn deliver_binary(&self, data: &[u8]) { + let cb = self + .on_message + .lock() + .expect("ws connection poisoned") + .clone(); + if let Some(cb) = cb { + cb(data); + } + } +} + +type WsSocket = tungstenite::WebSocket>; + +/// One TLS WebSocket handshake with bounded connect and handshake times. Redirects are not +/// followed, so a CM cannot move the session to another scheme or host. +fn open_socket(url: &str) -> Result { + if !url.starts_with("wss://") { + return Err(format!("refusing non-TLS CM url {url}")); + } + let request = url.into_client_request().map_err(|e| e.to_string())?; + let host = request + .uri() + .host() + .ok_or_else(|| "CM url has no host".to_string())? + .trim_start_matches('[') + .trim_end_matches(']') + .to_string(); + let port = request.uri().port_u16().unwrap_or(443); + let addrs = std::net::ToSocketAddrs::to_socket_addrs(&(host.as_str(), port)) + .map_err(|e| e.to_string())?; + let mut last = "no address for CM host".to_string(); + for addr in addrs { + match std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) { + Ok(stream) => { + let _ = stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT)); + let _ = stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT)); + return tungstenite::client_tls(request, stream) + .map(|(socket, _)| socket) + .map_err(|e| e.to_string()); + } + Err(err) => last = err.to_string(), + } + } + Err(last) +} + +fn run_ws_worker(shared: Arc, url: String, rx: mpsc::Receiver) { + let mut socket = match open_socket(&url) { + Ok(socket) => socket, + Err(detail) => { + let reason = map_error_reason(&detail, false); + shared.mark_disconnected(reason_to_close_code(reason), &detail, false); + return; + } + }; + let _ = set_read_timeout(socket.get_mut(), Some(READ_POLL_TIMEOUT)); + if let MaybeTlsStream::Rustls(stream) = socket.get_mut() { + let _ = stream.sock.set_write_timeout(Some(SEND_TIMEOUT)); + } + if !shared.mark_connected_if_connecting() { + let _ = socket.close(None); + shared.mark_disconnected(NORMAL_CLOSE_CODE, "client disconnect", false); + return; + } + + loop { + while let Ok(cmd) = rx.try_recv() { + match cmd { + WsCommand::Send(data) => { + if let Err(err) = socket.send(Message::Binary(data.into())) { + let detail = err.to_string(); + let reason = map_error_reason(&detail, false); + shared.mark_disconnected(reason_to_close_code(reason), &detail, false); + return; + } + } + WsCommand::Disconnect => { + let _ = socket.close(None); + shared.mark_disconnected(NORMAL_CLOSE_CODE, "client disconnect", false); + return; + } + } + } + + match socket.read() { + Ok(Message::Binary(bytes)) => shared.deliver_binary(&bytes), + Ok(Message::Close(frame)) => { + let detail = frame + .as_ref() + .map(|frame| frame.reason.to_string()) + .unwrap_or_else(|| "remote close".to_string()); + let code = frame + .map(|frame| u16::from(frame.code)) + .unwrap_or(NORMAL_CLOSE_CODE); + shared.mark_disconnected(code, &detail, false); + return; + } + Ok(Message::Ping(_) | Message::Pong(_) | Message::Text(_) | Message::Frame(_)) => {} + Err(err) if is_timeout_error(&err) => {} + Err(WsError::ConnectionClosed | WsError::AlreadyClosed) => { + shared.mark_disconnected(NORMAL_CLOSE_CODE, "remote close", false); + return; + } + Err(err) => { + let detail = err.to_string(); + let reason = map_error_reason(&detail, false); + shared.mark_disconnected(reason_to_close_code(reason), &detail, false); + return; + } + } + } +} + +fn set_read_timeout( + stream: &mut MaybeTlsStream, + timeout: Option, +) -> std::io::Result<()> { + match stream { + MaybeTlsStream::Plain(stream) => stream.set_read_timeout(timeout), + MaybeTlsStream::Rustls(stream) => stream.sock.set_read_timeout(timeout), + #[allow(unreachable_patterns)] + _ => Ok(()), + } +} + +fn is_timeout_error(err: &WsError) -> bool { + matches!(err, WsError::Io(io) if matches!( + io.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + )) +} + +fn reason_to_close_code(reason: TransportDisconnectReason) -> u16 { + match reason { + TransportDisconnectReason::RemoteClose | TransportDisconnectReason::UserInitiated => { + NORMAL_CLOSE_CODE + } + _ => 0, + } +} + +pub fn map_close_reason(close_code: u16, tls_handshake_failed: bool) -> TransportDisconnectReason { + if tls_handshake_failed { + TransportDisconnectReason::TlsHandshakeFailed + } else if (1000..1016).contains(&close_code) { + TransportDisconnectReason::RemoteClose + } else { + TransportDisconnectReason::Unknown + } +} + +pub fn map_error_reason(reason: &str, user_initiated: bool) -> TransportDisconnectReason { + if user_initiated { + return TransportDisconnectReason::UserInitiated; + } + let tls_failed = reason.contains("tls") + || reason.contains("TLS") + || reason.contains("SSL") + || reason.contains("certificate"); + map_close_reason(0, tls_failed) +} + +pub fn normal_close_code() -> u16 { + NORMAL_CLOSE_CODE +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + #[test] + fn maps_close_reasons() { + assert_eq!( + map_close_reason(0, true), + TransportDisconnectReason::TlsHandshakeFailed + ); + assert_eq!( + map_close_reason(1000, false), + TransportDisconnectReason::RemoteClose + ); + assert_eq!( + map_close_reason(2000, false), + TransportDisconnectReason::Unknown + ); + assert_eq!(normal_close_code(), 1000); + assert_eq!( + map_error_reason("TLS certificate verify failed", false), + TransportDisconnectReason::TlsHandshakeFailed + ); + assert_eq!( + map_error_reason("connection reset", false), + TransportDisconnectReason::Unknown + ); + assert_eq!( + map_error_reason("connection reset", true), + TransportDisconnectReason::UserInitiated + ); + } + + #[test] + fn transitions_and_callbacks_fire() { + let ws = WsConnection::new(); + let (tx, rx) = mpsc::channel(); + ws.set_on_connected(move || tx.send("connected").unwrap()); + assert!(ws.transition_connecting()); + assert!(!ws.transition_connecting()); + ws.mark_connected(); + assert_eq!(ws.state(), TransportState::Connected); + assert_eq!(rx.recv().unwrap(), "connected"); + } + + #[test] + fn a_disconnect_during_the_handshake_keeps_connected_unpublished() { + let ws = WsConnection::new(); + assert!(ws.transition_connecting()); + ws.mark_user_disconnect(); + assert!(!ws.shared.mark_connected_if_connecting()); + assert_eq!(ws.state(), TransportState::Disconnecting); + } + + #[test] + fn a_callback_may_replace_itself() { + let ws = Arc::new(WsConnection::new()); + let inner = Arc::clone(&ws); + ws.set_on_message(move |_| inner.set_on_message(|_| {})); + ws.deliver_binary(b"x"); + } + + #[test] + fn refuses_plain_ws_urls() { + assert!(open_socket("ws://example.invalid/cmsocket/").is_err()); + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt b/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt index fb1fb71a5d..4137f0a81b 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt @@ -15,7 +15,7 @@ import org.robolectric.annotation.Config @Config(sdk = [33]) class StoresTabOrderTest { private val app get() = RuntimeEnvironment.getApplication() - private val defaults = Store.entries.map { it.id } + private val defaults = Store.tabbed.map { it.id } private fun shown() = arrangeStoreTabs(SessionPrefs.storesTabOrder(app), emptySet()).map { it.store.id } @Test diff --git a/app/src/test/java/com/droiddeck/launcher/stores/steam/SteamLibraryFoldersTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/steam/SteamLibraryFoldersTest.kt new file mode 100644 index 0000000000..5eadd93b3b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/steam/SteamLibraryFoldersTest.kt @@ -0,0 +1,278 @@ +package com.droiddeck.launcher.stores.steam + +import com.droiddeck.launcher.stores.download.DownloadStage +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SteamLibraryFoldersTest { + private val rootfs = File("/data/user/0/com.droiddeck.launcher/files/rootfs") + private val card = File("/storage/1A2B-3C4D/Android/data/com.droiddeck.launcher/files/steam") + private val lib = File("/storage/1A2B-3C4D/SteamLibrary") + private val games = File("/storage/1A2B-3C4D/Games") + private val armRoot = File(rootfs, "root/.local/share/Steam") + private val x64Root = File(rootfs, "root/.droiddeck-x64/.local/share/Steam") + private val armAliases = listOf("/root/.local/share/Steam", "/root/.steam/steam", "/root/.steam/root") + private val mounts = listOf( + SteamLibraryFolders.Mount("/mnt/droiddeck-sd", card), + SteamLibraryFolders.Mount("/mnt/droiddeck-lib/1", lib), + SteamLibraryFolders.Mount("/root/Games/Card/", games), + SteamLibraryFolders.Mount("/root/Storage", File("/storage/emulated/0")), + ) + + private val vdf = """ + "libraryfolders" + { + "contentstatsid" "-4785" + "0" + { + "path" "/root/.local/share/Steam" + "label" "Internal Storage" + "contentid" "123" + "totalsize" "0" + "apps" + { + "228980" "0" + } + } + "1" + { + "path" "/mnt/droiddeck-sd" + "label" "SD card" + "apps" + { + "291550" "1500000000" + } + } + "2" + { + "path" "/mnt/droiddeck-lib/1" + "label" "Steam \"Lib\"" + } + "3" + { + "path" "/root/Games/Card" + "label" "" + } + "4" + { + "path" "/root/.droiddeck-x64/shared/x86-64" + "label" "x86-64 client games" + } + "5" + { + "path" "/mnt/droiddeck-lib/9" + "label" "Removed" + } + "6" + { + "path" "/root/Games/Gone" + "label" "Gone" + } + } + """.trimIndent() + + @Test fun readsEveryFolderWithItsLabel() { + val folders = SteamLibraryFolders.parse(vdf) + assertEquals( + listOf("/root/.local/share/Steam", "/mnt/droiddeck-sd", "/mnt/droiddeck-lib/1", "/root/Games/Card", + "/root/.droiddeck-x64/shared/x86-64", "/mnt/droiddeck-lib/9", "/root/Games/Gone"), + folders.map { it.path }, + ) + assertEquals("Internal Storage", folders[0].label) + assertEquals("Steam \"Lib\"", folders[2].label) + assertEquals("", folders[3].label) + } + + @Test fun readsTheOldFormatAndEscapedPaths() { + val old = """ + "LibraryFolders" + { + "TimeNextStatsReport" "1700000000" + "ContentStatsID" "-1" + "1" "/mnt/droiddeck-sd" + "2" "/root/odd\\name" + } + """.trimIndent() + assertEquals( + listOf(SteamLibraryFolders.Folder("/mnt/droiddeck-sd", ""), SteamLibraryFolders.Folder("/root/odd\\name", "")), + SteamLibraryFolders.parse(old), + ) + assertTrue(SteamLibraryFolders.parse("").isEmpty()) + } + + @Test fun arm64LibrariesMapFromGuestToHost() { + val libraries = SteamLibraryFolders.resolve( + SteamLibraryFolders.parse(vdf), "/root/.local/share/Steam", armAliases, armRoot, mounts, rootfs, + ) + assertEquals( + listOf(armRoot, card, lib, games, File(rootfs, "root/.droiddeck-x64/shared/x86-64")), + libraries.map { it.host }, + ) + assertEquals(listOf(true, false, false, false, false), libraries.map { it.main }) + assertEquals("/mnt/droiddeck-sd", libraries[1].guest) + assertEquals("SD card", libraries[1].label) + } + + @Test fun x64LibrariesSitInsideTheCardAndAddedLibraries() { + val text = """ + "libraryfolders" + { + "0" { "path" "/root/.droiddeck-x64/.local/share/Steam" "label" "Internal Storage" } + "1" { "path" "/mnt/droiddeck-sd/x86-64" "label" "SD card" } + "2" { "path" "/mnt/droiddeck-lib/1/x86-64/" "label" "Lib" } + "3" { "path" "/root/.droiddeck-x64/shared/arm64" "label" "ARM64 client games" } + } + """.trimIndent() + val libraries = SteamLibraryFolders.resolve( + SteamLibraryFolders.parse(text), "/root/.droiddeck-x64/.local/share/Steam", + listOf("/root/.droiddeck-x64/.local/share/Steam", "/root/.droiddeck-x64/.steam/steam"), x64Root, mounts, rootfs, + ) + assertEquals( + listOf(x64Root, File(card, "x86-64"), File(lib, "x86-64"), File(rootfs, "root/.droiddeck-x64/shared/arm64")), + libraries.map { it.host }, + ) + assertEquals("/mnt/droiddeck-lib/1/x86-64", libraries[2].guest) + } + + @Test fun aGuestPathWithoutItsBindIsNotAnInstallTarget() { + assertNull(SteamLibraryFolders.hostFor("/mnt/droiddeck-sd", emptyList(), rootfs)) + assertNull(SteamLibraryFolders.hostFor("/root/Games/Gone", mounts, rootfs)) + assertNull(SteamLibraryFolders.hostFor("/root/Storage/Steam", emptyList(), rootfs)) + assertNull(SteamLibraryFolders.hostFor("/opt/steam", mounts, rootfs)) + assertNull(SteamLibraryFolders.hostFor("/root/../etc", mounts, rootfs)) + assertNull(SteamLibraryFolders.hostFor("relative/path", mounts, rootfs)) + assertEquals(File("/storage/emulated/0/Steam"), SteamLibraryFolders.hostFor("/root/Storage/Steam", mounts, rootfs)) + assertEquals(File(card, "x86-64"), SteamLibraryFolders.hostFor("/mnt/droiddeck-sd//x86-64/", mounts, rootfs)) + } + + @Test fun aliasesAreTheMainLibraryAndAMissingMainIsAddedFirst() { + val aliased = SteamLibraryFolders.resolve( + listOf(SteamLibraryFolders.Folder("/root/.steam/steam", "Internal Storage"), SteamLibraryFolders.Folder("/mnt/droiddeck-sd", "SD card")), + "/root/.local/share/Steam", armAliases, armRoot, mounts, rootfs, + ) + assertEquals(listOf(armRoot, card), aliased.map { it.host }) + assertEquals("/root/.steam/steam", aliased[0].guest) + + val missing = SteamLibraryFolders.resolve( + listOf(SteamLibraryFolders.Folder("/mnt/droiddeck-sd", "SD card"), SteamLibraryFolders.Folder("/mnt/droiddeck-sd/", "Again")), + "/root/.local/share/Steam", armAliases, armRoot, mounts, rootfs, + ) + assertEquals(listOf(armRoot, card), missing.map { it.host }) + assertEquals("/root/.local/share/Steam", missing[0].guest) + assertEquals("", missing[0].label) + } + + private fun acf(library: File, appId: Int, name: String, flags: Int, dir: String = name, size: Long = 0L) { + val apps = File(library, "steamapps").apply { mkdirs() } + File(apps, "appmanifest_$appId.acf").writeText( + """ + "AppState" + { + "appid" "$appId" + "name" "$name" + "StateFlags" "$flags" + "installdir" "$dir" + "SizeOnDisk" "$size" + } + """.trimIndent(), + ) + } + + @Test fun onlyFullyInstalledGamesCountAsInstalled() { + val base = Files.createTempDirectory("steam-libs").toFile() + try { + val first = SteamLibraryFolders.Library("/root/.local/share/Steam", File(base, "internal"), "Internal Storage", true) + val second = SteamLibraryFolders.Library("/mnt/droiddeck-sd", File(base, "card"), "SD card", false) + val missing = SteamLibraryFolders.Library("/mnt/droiddeck-lib/1", File(base, "gone"), "Gone", false) + acf(first.host, 291550, "Brawlhalla", 4, size = 1_500_000_000L) + acf(first.host, 620, "Portal 2", 1026) + acf(first.host, 1628350, "Steam Linux Runtime 3.0 (sniper)", 4, dir = "SteamLinuxRuntime_sniper") + acf(second.host, 291550, "Brawlhalla copy", 4) + acf(second.host, 413150, "Stardew Valley", 6) + File(second.host, "steamapps/appmanifest_400.acf.tmp").writeText("\"AppState\" { \"appid\" \"400\" \"StateFlags\" \"4\" }") + File(second.host, "steamapps/libraryfolder.vdf").writeText("\"libraryfolder\" { }") + + val found = SteamLibraryFolders.installed(listOf(first, second, missing)) + assertEquals(setOf(291550, 413150), found.keys) + assertEquals("Brawlhalla", found.getValue(291550).name) + assertEquals(first, found.getValue(291550).library) + assertEquals(1_500_000_000L, found.getValue(291550).sizeOnDisk) + assertEquals(second, found.getValue(413150).library) + assertEquals("Stardew Valley", found.getValue(413150).installDir) + } finally { + base.deleteRecursively() + } + } + + @Test fun theClientsRememberedAccountIsTheSavedSignIn() { + val users = """ + "users" + { + "76561190000000001" + { + "AccountName" "old" + "PersonaName" "Old One" + "RememberPassword" "1" + "MostRecent" "0" + "Timestamp" "1600000000" + } + "76561190000000002" + { + "AccountName" "player" + "PersonaName" "Player" + "RememberPassword" "1" + "MostRecent" "1" + "Timestamp" "1700000000" + } + } + """.trimIndent() + assertEquals("Player", SteamLibraryFolders.savedAccount(users)) + assertEquals(SteamLibraryFolders.SavedAccount("76561190000000002", "Player"), SteamLibraryFolders.savedLogin(users)) + assertEquals("Old One", SteamLibraryFolders.savedAccount(users.replace("\"MostRecent\"\t\t\"1\"", "\"MostRecent\"\t\t\"0\"").replace("\"1700000000\"", "\"1500000000\""))) + assertEquals("player", SteamLibraryFolders.savedAccount(users.replace("\"PersonaName\"\t\t\"Player\"", "\"PersonaName\"\t\t\"\"").replace("\"Old One\"", "\"\"").replace("\"1600000000\"", "\"1\""))) + assertNull(SteamLibraryFolders.savedAccount(users.replace("\"RememberPassword\"\t\t\"1\"", "\"RememberPassword\"\t\t\"0\""))) + assertNull(SteamLibraryFolders.savedAccount("")) + val registry = "\"Registry\"\n{\n\t\"HKCU\"\n\t{\n\t\t\"Software\"\n\t\t{\n\t\t\t\"Valve\"\n\t\t\t{\n\t\t\t\t\"Steam\"\n\t\t\t\t{\n\t\t\t\t\t\"AutoLoginUser\"\t\t\"OLD\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n" + assertEquals(SteamLibraryFolders.SavedAccount("76561190000000001", "Old One"), SteamLibraryFolders.savedLogin(users, registry)) + assertNull(SteamLibraryFolders.savedLogin(users.replace("\"RememberPassword\"\t\t\"1\"\n\t\t\"MostRecent\"\t\t\"0\"", "\"RememberPassword\"\t\t\"0\"\n\t\t\"MostRecent\"\t\t\"0\""), registry)) + } + + @Test fun theClientLanguageComesFromTheRegistry() { + val registry = """ + "Registry" + { + "HKCU" + { + "Software" + { + "Valve" + { + "Steam" + { + "AutoLoginUser" "player" + "language" "german" + } + } + } + } + } + """.trimIndent() + assertEquals("german", SteamLibraryFolders.language(registry)) + assertNull(SteamLibraryFolders.language("\"Registry\" { \"HKCU\" { } }")) + } + + @Test fun enginePhasesShowAsDownloadStages() { + assertEquals(DownloadStage.DOWNLOAD, SteamLibraryFolders.stageOf("download")) + assertEquals(DownloadStage.DOWNLOAD, SteamLibraryFolders.stageOf("Downloading")) + assertEquals(DownloadStage.DOWNLOAD, SteamLibraryFolders.stageOf("")) + assertEquals(DownloadStage.VERIFY, SteamLibraryFolders.stageOf("verify")) + assertEquals(DownloadStage.MANIFEST, SteamLibraryFolders.stageOf("manifests")) + assertEquals(DownloadStage.MANIFEST, SteamLibraryFolders.stageOf("cleanup")) + assertEquals(DownloadStage.INSTALL, SteamLibraryFolders.stageOf("register")) + assertEquals(DownloadStage.INSTALL, SteamLibraryFolders.stageOf("finalize")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index b168587e09..7cbf6ffc72 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -27,6 +27,17 @@ class LibraryEntriesTest { assertNull(entries[2].game) } + @Test fun ownedSteamGamesJoinTheSteamTabAndAnInstalledOneShowsOnce() { + val games = listOf(Library.SteamGame(440, "Team Fortress 2", null, "Steam library")) + val library = mapOf(Store.STEAM to listOf(owned(Store.STEAM, "440", "Team Fortress 2"), owned(Store.STEAM, "620", "Portal 2"))) + val entries = libraryEntries(games, library, emptySet()) + assertEquals(listOf("app:440", "app:steamstore:620"), entries.map { it.key }) + assertEquals(listOf(Library.SOURCE_STEAM, Library.SOURCE_STEAM), entries.map { it.source }) + assertFalse(entries[1].installed) + assertEquals("app:620", entries[1].favoriteKey) + assertEquals(listOf("steam"), librarySources(entries, listOf(Store.STEAM.id, "epic"))) + } + @Test fun theEpicLauncherIsNotAGame() { val launcher = Library.SteamGame(0, Library.EPIC_LAUNCHER_NAME, null, Library.EPIC_LAUNCHER) assertEquals(emptyList(), libraryEntries(listOf(launcher), emptyMap(), emptySet()).map { it.key })