diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index d9db3374e9..d0f4ea80a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -418,7 +418,7 @@ object AddedGames { private fun scanGame(context: Context, folder: File, out: MutableList, single: AddedExes.Entry? = null, reuse: Boolean = false) { run { val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) } - if (sidecar?.store == Store.ROCKSTAR && (!com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id) || sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER)) return + if (sidecar?.store == Store.ROCKSTAR && sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) return sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } } val ranking = rank(folder, reuse) val candidates = ranking.exes diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt index 37d731a2f7..f45a23c654 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt @@ -21,10 +21,6 @@ object StoreLaunch { val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT || sidecar.store == Store.ROCKSTAR val file = File(folder, LAUNCHER) if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(file.toPath())) return sidecar.copy(launcher = null) - if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) { - file.delete() - return sidecar.copy(launcher = null) - } if (!needs) { file.delete(); return sidecar.copy(launcher = null) } file.writeText(launcherText(sidecar)) return sidecar.copy(launcher = LAUNCHER) @@ -36,11 +32,11 @@ object StoreLaunch { ?: exe.substringBeforeLast('\\', "") val lines = ArrayList() lines += "@echo off" - lines += "setlocal" + lines += if (sidecar.store == Store.ROCKSTAR) "setlocal DisableDelayedExpansion" else "setlocal" if (sidecar.store != Store.ROCKSTAR) lines += "rem Written by DroidDeck for ${sidecar.store.label}: ${sidecar.title}. Steam's shortcut runs this file." lines += "cd /d \"%~dp0$dir\"" for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\"" - val args = sidecar.args.joinToString(" ") { quoteArg(it) } + val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) } val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "") if (sidecar.store == Store.EPIC) { lines += "if exist \"%~dp0$EPIC_ARGS\" goto client" @@ -60,8 +56,11 @@ object StoreLaunch { lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\"" lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%" } else if (sidecar.store == Store.ROCKSTAR) { + lines += "if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct" lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\"" lines += "exit /b %errorlevel%" + lines += ":direct" + lines += run } else if (sidecar.store == Store.UBISOFT) { lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct" lines += "if not exist \"$UBISOFT_SERVICE\" goto direct" @@ -85,6 +84,22 @@ object StoreLaunch { private val ENV_NAME = Regex("[A-Za-z_][A-Za-z0-9_]*") + private fun batchArg(arg: String): String { + val quoted = StringBuilder("\"") + var slashes = 0 + for (c in arg.filter { it >= ' ' && it != '\u007f' }) { + if (c == '\\') { slashes++; continue } + quoted.append("\\".repeat(if (c == '"') slashes * 2 + 1 else slashes)).append(c) + slashes = 0 + } + quoted.append("\\".repeat(slashes * 2)).append('"') + return quoted.toString().map { c -> when (c) { + '%' -> "%%" + in "^&|<>()\"" -> "^$c" + else -> c.toString() + } }.joinToString("") + } + fun quoteArg(arg: String): String { val clean = arg.filter { it >= ' ' && it != '\u007f' } return if (' ' in clean && !clean.contains('"')) "\"$clean\"" else clean @@ -103,11 +118,12 @@ object StoreLaunch { fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar { if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar - if (sidecar.store == Store.ROCKSTAR && !com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(sidecar.id)) return sidecar if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null) val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true) if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar - val exe = if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe + val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe + ?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null + val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe if (exe == sidecar.exe && sidecar.launcher == LAUNCHER && runCatching { File(folder, LAUNCHER).readText() }.getOrNull() == launcherText(sidecar)) return sidecar return runCatching { writeLauncher(folder, sidecar.copy(exe = exe)).also { it.write(folder) } }.getOrDefault(sidecar) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt index 781eddbe3f..b6c90cb41f 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarAuth.kt @@ -29,7 +29,7 @@ object RockstarAuth { private const val TICKET_MARGIN_MS = 15 * 60 * 1000L private val lock = Any() - class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long) + class Ticket(val ticket: String, val sessionKey: String, val sessionTicket: String, val rockstarId: String, val nickname: String, val expiresAt: Long, val email: String = "", val sdkTicket: String = "") internal fun fingerprint(context: Context): JSONObject { val p = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) @@ -159,7 +159,7 @@ object RockstarAuth { private fun stored(o: JSONObject): Ticket? { val t = o.optString("ticket").takeIf { it.isNotEmpty() } ?: return null - return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at")) + return Ticket(t, o.optString("session_key"), o.optString("session_ticket"), o.optString("rockstar_id"), o.optString("display_name"), o.optLong("ticket_expires_at"), o.optString("email"), o.optString("sdk_ticket").takeIf { o.optInt("sdk_ticket_version") == 1 }.orEmpty()) } private fun mint(context: Context): Ticket { @@ -176,7 +176,7 @@ object RockstarAuth { } val t = parseTicket(root) ?: throw IllegalStateException("no ticket in the answer") o.put("ticket", t.ticket).put("session_key", t.sessionKey).put("session_ticket", t.sessionTicket) - .put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt) + .put("rockstar_id", t.rockstarId).put("ticket_expires_at", t.expiresAt).put("email", t.email).put("sdk_ticket", t.sdkTicket).put("sdk_ticket_version", 1) if (t.nickname.isNotEmpty()) o.put("display_name", t.nickname) StoreAccounts.write(app, Store.ROCKSTAR, o) return t @@ -191,8 +191,49 @@ object RockstarAuth { (account?.let { RockstarRos.text(it, "RockstarId") } ?: RockstarRos.text(root, "RockstarId")).orEmpty(), account?.let { RockstarRos.text(it, "Nickname") }.orEmpty(), now + secs * 1000L, + account?.let { RockstarRos.text(it, "Email") }.orEmpty(), + sdkTicket(root), ) } + internal fun sdkTicket(root: org.w3c.dom.Element): String { + val document = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() + val response = document.createElement("Response").also { document.appendChild(it) } + val fields = setOf("Status", "Ticket", "SessionKey", "SessionTicket", "SecsUntilExpiration", "PlayerAccountId", "PlayerAccountRuid", + "Region", "Privileges", "Privs", "Services", "SslServices", "Hosts", "DisabledSecurityFlags", "SessionId", "CloudKey", "PublicIp", "PosixTime", "IsSubAccount") + val blocked = setOf("scauthtoken", "accesstoken", "refreshtoken", "rememberedmachinetoken", "loginguid", "password") + fun copy(source: org.w3c.dom.Element): org.w3c.dom.Element { + val target = document.createElement(source.tagName) + for (i in 0 until source.attributes.length) { + val attribute = source.attributes.item(i) + if (attribute.nodeName.lowercase() !in blocked) target.setAttribute(attribute.nodeName, attribute.nodeValue) + } + var child = source.firstChild + while (child != null) { + if (child is org.w3c.dom.Element) { + if (child.tagName.lowercase() !in blocked) target.appendChild(copy(child)) + } else if (child.nodeType == org.w3c.dom.Node.TEXT_NODE || child.nodeType == org.w3c.dom.Node.CDATA_SECTION_NODE) { + target.appendChild(document.createTextNode(child.nodeValue)) + } + child = child.nextSibling + } + return target + } + for (field in fields) RockstarRos.first(root, field)?.let { response.appendChild(copy(it)) } + RockstarRos.first(root, "RockstarAccount")?.let { account -> + val target = document.createElement("RockstarAccount") + for (field in setOf("RockstarId", "Nickname", "Email", "Age", "CountryCode", "LanguageCode", "AvatarUrl", "ZipCode", "Ruid")) { + RockstarRos.first(account, field)?.let { target.appendChild(copy(it)) } + } + response.appendChild(target) + } + val output = java.io.StringWriter() + javax.xml.transform.TransformerFactory.newInstance().newTransformer().apply { + setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes") + transform(javax.xml.transform.dom.DOMSource(document), javax.xml.transform.stream.StreamResult(output)) + } + return output.toString() + } + fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR) } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt index 3e878d3290..f816ed8ef1 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt @@ -147,6 +147,9 @@ object RockstarLibrary { internal fun owned(account: RockstarAccountApps): List = account.packages.filter { !it.featured }.flatMap { RockstarTitles.forName(it.title) }.distinct() + internal fun owns(account: RockstarAccountApps, rosId: Int, id: String): Boolean = + owned(account).any { it.rosTitleId == rosId } || account.packages.any { !it.featured && it.title == id } + internal fun games(account: RockstarAccountApps): List = owned(account).mapNotNull { t -> RockstarApps.deliverer(account.apps, t)?.let { RockstarTitles.item(t, owned = true, extra = mapOf("app" to it.name, "appId" to it.id)) } }.sortedBy { it.title.lowercase() } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt index c83b6548d8..52f1119f90 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarLaunch.kt @@ -10,9 +10,9 @@ import java.security.MessageDigest import java.util.Base64 object RockstarLaunch { - internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe") + internal val pipes = mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe") - fun supports(id: String?) = id != null && id in pipes + fun usesClassicLauncher(id: String) = id in pipes fun applyDefaults(app: Context, id: String, appId: Long) { val scope = (appId and 0xffffffffL).toString() @@ -23,16 +23,22 @@ object RockstarLaunch { } fun prepare(app: Context, id: String): JSONObject { - val pipe = pipes[id] ?: return failure("unsupported-title") - val title = RockstarTitles.byId(id) ?: return failure("unknown-title") val folder = StoreInstallRoot.gameFolders(app).firstOrNull { folder -> StoreGameSidecar.read(folder)?.let { it.store == Store.ROCKSTAR && it.id == id && it.isInstalled } == true } ?: return failure("not-installed") val installed = StoreGameSidecar.read(folder) ?: return failure("not-installed") val exe = installed.exeFile(folder).canonicalFile - if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile || - !java.io.File(folder, "MTLX.dll").isFile) return failure("missing-game-files") + if (!exe.path.startsWith(folder.canonicalPath + java.io.File.separator) || !exe.isFile) return failure("missing-game-files") + val metadata = RockstarMetadata.find(folder) + val pipe = pipes[id] + val sdk = (pipe == null && metadata != null) || id in setOf("gta4", "lanoire") || listOf(folder, exe.parentFile).any { dir -> + dir.listFiles().orEmpty().any { it.isFile && it.name.lowercase() in setOf("socialclub.dll", "socialclub64.dll") } + } + if (pipe == null && !sdk) return failure("no-launcher-protocol") + if (pipe != null && !listOf(folder, exe.parentFile).any { java.io.File(it, "MTLX.dll").isFile }) return failure("missing-game-files") + val rosId = metadata?.rosId ?: RockstarTitles.byId(id)?.rosTitleId ?: return failure("missing-title-metadata") var ticket = RockstarAuth.ticket(app) ?: RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out") + if (sdk && ticket.sdkTicket.isEmpty()) ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out") val account = try { RockstarApps.fetch(ticket.ticket) {} } catch (e: RockstarRos.RosException) { @@ -40,16 +46,23 @@ object RockstarLaunch { ticket = RockstarAuth.ticket(app, fresh = true) ?: return failure("signed-out") RockstarApps.fetch(ticket.ticket) {} } - if (RockstarLibrary.owned(account).none { it.id == id } || RockstarApps.deliverer(account.apps, title) == null) return failure("not-owned") - val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to title.rosTitleId.toString(), "platformId" to "8")) + if (metadata != null && account.apps.none { it.titleId.toIntOrNull() == rosId && (it.name == metadata.id || it.name.startsWith(metadata.id + "_")) }) return failure("title-metadata-mismatch") + val tokenRoot = RockstarRos.result("app.asmx/GetTitleAccessToken2", listOf("ticket" to ticket.ticket, "titleId" to rosId.toString(), "platformId" to "8")) val token = RockstarRos.text(tokenRoot, "Result")?.takeIf { it.isNotEmpty() } ?: return failure("no-title-token") + val result = JSONObject().put("ok", true).put("expiresAt", System.currentTimeMillis() + 90_000) + if (sdk) { + val session = JSONObject().put("accountId", ticket.rockstarId).put("identity", ticket.email.ifEmpty { ticket.nickname }).put("ticket", ticket.sdkTicket) + if (RockstarLibrary.owns(account, rosId, metadata?.id ?: id)) session.put("titleId", metadata?.id ?: id) + result.put("session", session) + } + if (pipe == null) return result val hash = MessageDigest.getInstance("SHA-256").digest(RockstarAuth.fingerprint(app).toString().toByteArray()).copyOf(16) val launch = RockstarRos.result("app.asmx/GetTitleLaunchData", listOf("ticket" to ticket.ticket, "titleAccessToken" to token, "machineHash" to Base64.getEncoder().encodeToString(hash))) val encoded = RockstarRos.text(launch, "Data") ?: return failure("no-launch-data") val iv = RockstarRos.text(launch, "EndpointIV") ?: return failure("no-launch-iv") val material = RockstarLaunchCipher.decode(encoded, iv) - return JSONObject().put("ok", true).put("pipe", pipe).put("material", material).put("expiresAt", System.currentTimeMillis() + 90_000) + return result.put("pipe", pipe).put("material", material) } private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadata.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadata.kt new file mode 100644 index 0000000000..5a7e052946 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadata.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.json.JSONObject +import java.io.File +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.charset.CodingErrorAction +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +internal object RockstarMetadata { + data class Title(val id: String, val rosId: Int, val exe: String) + + fun find(folder: File): Title? { + val root = folder.canonicalFile + var level = listOf(root) + repeat(4) { + val entries = level.map { it.listFiles().orEmpty() } + val metadata = entries.flatMap { files -> files.filter { it.name.equals("title.rgl", true) } } + for (file in metadata.filter { it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator) }) { + if (file.length() in 112..1_048_576) runCatching { decode(file.readBytes()) }.getOrNull()?.let { + return it.copy(exe = File(file.parentFile, it.exe).relativeTo(root).invariantSeparatorsPath) + } + } + level = entries.flatMap { files -> files.asSequence().filter { + it.isDirectory && !java.nio.file.Files.isSymbolicLink(it.toPath()) && it.canonicalPath.startsWith(root.path + File.separator) + }.take(256).toList() }.take(256) + } + return null + } + + fun decode(bytes: ByteArray): Title? = runCatching { + require(bytes.size in 112..1_048_576 && bytes.copyOfRange(0, 4).contentEquals(byteArrayOf(82, 71, 76, 77))) + val header = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + require(header.getInt(4) == 1 && header.getInt(8) == bytes.size - 80 && (bytes.size - 80) % 16 == 0) + val cipher = Cipher.getInstance("AES/CBC/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(bytes.copyOfRange(80, 96))) + val clear = cipher.doFinal(bytes, 96, bytes.size - 96) + val pad = clear.last().toInt() and 255 + val size = if (pad in 1..16 && clear.takeLast(pad).all { (it.toInt() and 255) == pad }) clear.size - pad + else clear.indexOfLast { it != 0.toByte() } + 1 + val text = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(clear, 0, size)).toString().removePrefix("\uFEFF") + val json = JSONObject(text) + val id = json.getString("titleId") + val rosId = json.get("rosTitleId").toString().takeIf { Regex("[1-9][0-9]{0,4}").matches(it) }?.toInt() ?: return null + val exe = json.getString("principalFileName").replace('\\', '/') + require(Regex("[a-z][a-z0-9_]{0,63}").matches(id) && rosId in 1..65535) + require(exe.isNotEmpty() && !exe.startsWith('/') && ':' !in exe && '\u0000' !in exe && exe.split('/').none { it == ".." }) + Title(id, rosId, exe) + }.getOrNull() +} 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 729fc5ad19..bee82bbd2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -400,7 +400,6 @@ internal fun GameActions( val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED } val cloud = game?.library == Library.XBOX_CLOUD && installed == null val downloadBytes = catalogSize(item) - val launchSupported = store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(id) Actions { when { s.shortcutPicker && game != null -> { @@ -412,8 +411,8 @@ internal fun GameActions( val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id) val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true PrimaryButton( - stringResource(if (!launchSupported) R.string.stores_rockstar_launch_unavailable else if (preparing) R.string.store_starting else R.string.stores_play), - enabled = launchSupported && !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false), + stringResource(if (preparing) R.string.store_starting else R.string.stores_play), + enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false), main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn, ) { if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt index d8daa53d58..0b1000e6e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt @@ -221,7 +221,7 @@ private fun FinishedRow(d: DownloadEntry, s: FrontEndState, a: FrontEndActions, val ctx = LocalContext.current ArtStrip(d.cover, d.name) { StripLabel(d.name, d.store.id, stringResource(if (d.state == DownloadState.INSTALLED) R.string.stores_installed_chip else R.string.stores_dl_cancelled), Color.White.copy(alpha = 0.72f)) - if (d.state == DownloadState.INSTALLED && (d.store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(d.id))) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) { + if (d.state == DownloadState.INSTALLED) Box(Modifier.bloomIn(bloom, GATHER_HOLD_MS + 150)) { RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) } } } @@ -374,7 +374,7 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) } CancelAction { DownloadQueue.clear(ctx, d.key) } } - DownloadState.INSTALLED -> if (d.store != Store.ROCKSTAR || com.droiddeck.launcher.stores.rockstar.RockstarLaunch.supports(d.id)) Box(Modifier.bloomIn(true, 420)) { + DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) { RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { if (d.key == EpicClient.DOWNLOAD_KEY) a.onEpicLauncher() else if (d.key == com.droiddeck.launcher.stores.battlenet.BattleNetClient.DOWNLOAD_KEY) a.onBattleNet() else launchStoreGame(d.store, d.id, s, a) } } DownloadState.CANCELLED -> {} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f1a5dcf3f3..734bfbb25e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3999,6 +3999,5 @@ Scarlet Snow White surfaces with red accents. - Launch unavailable No web browser is available to open this link. diff --git a/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadataTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadataTest.kt new file mode 100644 index 0000000000..cb07f0914e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarMetadataTest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.stores.rockstar + +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.nio.ByteBuffer +import java.nio.ByteOrder +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = android.app.Application::class) +class RockstarMetadataTest { + @Test fun findsRootMetadataAfterManyOtherFiles() { + val root = java.nio.file.Files.createTempDirectory("rockstar-many-files").toFile() + try { + repeat(300) { java.io.File(root, "asset-$it.dat").writeText("asset") } + java.io.File(root, "title.rgl").writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")) + assertEquals("game", RockstarMetadata.find(root)?.id) + java.io.File(root, "title.rgl").delete() + java.io.File(root, "Title.RGL").writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")) + assertEquals("game", RockstarMetadata.find(root)?.id) + } finally { + root.deleteRecursively() + } + } + + private fun container(json: String): ByteArray { + val iv = ByteArray(16) { it.toByte() } + val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") + cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(ByteArray(32), "AES"), IvParameterSpec(iv)) + val payload = iv + cipher.doFinal(json.toByteArray()) + val header = ByteBuffer.allocate(80).order(ByteOrder.LITTLE_ENDIAN) + header.put(byteArrayOf(82, 71, 76, 77)).putInt(1).putInt(payload.size) + return header.array() + payload + } + + @Test fun decodesInstalledTitleWithoutAnAppIdAllowlist() { + val title = RockstarMetadata.decode(container("""{"titleId":"new_title","rosTitleId":123,"principalFileName":"Game/Binaries/Win64/Game.exe"}"""))!! + assertEquals("new_title", title.id) + assertEquals(123, title.rosId) + assertEquals("Game/Binaries/Win64/Game.exe", title.exe) + } + + @Test fun rejectsBrokenContainersAndEscapingExecutables() { + val valid = container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""") + assertNull(RockstarMetadata.decode(valid.copyOf(90))) + assertNull(RockstarMetadata.decode(valid.copyOf().also { it[4] = 2 })) + assertNull(RockstarMetadata.decode(valid + byteArrayOf(0))) + assertNull(RockstarMetadata.decode(container("""{"titleId":"game","rosTitleId":1.5,"principalFileName":"Game.exe"}"""))) + for (exe in listOf("../outside.exe", "C:/outside.exe", "/outside.exe")) { + assertNull(RockstarMetadata.decode(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"$exe"}"""))) + } + } + + @Test fun doesNotFollowMetadataSymlinksOutsideTheGame() { + val root = java.nio.file.Files.createTempDirectory("rockstar-metadata").toFile() + val outside = java.io.File.createTempFile("rockstar-external", ".rgl") + try { + outside.writeBytes(container("""{"titleId":"game","rosTitleId":123,"principalFileName":"Game.exe"}""")) + val link = java.io.File(root, "title.rgl").toPath() + try { java.nio.file.Files.createSymbolicLink(link, outside.toPath()) } + catch (e: java.nio.file.FileSystemException) { org.junit.Assume.assumeNoException(e) } + assertNull(RockstarMetadata.find(root)) + java.nio.file.Files.delete(link) + java.io.File(root, "nested").mkdir() + outside.copyTo(java.io.File(root, "nested/title.rgl")) + assertEquals("game", RockstarMetadata.find(root)?.id) + assertEquals("nested/Game.exe", RockstarMetadata.find(root)?.exe) + } finally { + root.deleteRecursively() + outside.delete() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt index e356683511..755bd7320c 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/rockstar/RockstarTest.kt @@ -12,6 +12,54 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [33], application = android.app.Application::class) class RockstarTest { + @Test fun sdkTicketExportsOnlyTheShortLivedServerResponse() { + val root = RockstarRos.parse("""1opaque-game-ticket456session-keysession-ticketexample.invalidservice-refresh-secretrefresh-secret123Playerplayer@example.invalidnested-refresh-secret""") + val sdk = RockstarRos.parse(RockstarAuth.sdkTicket(root)) + assertEquals("opaque-game-ticket", RockstarRos.text(sdk, "Ticket")) + assertEquals("session-key", RockstarRos.text(sdk, "SessionKey")) + assertEquals("123", RockstarRos.text(sdk, "RockstarId")) + assertEquals("456", RockstarRos.text(sdk, "PlayerAccountId")) + assertEquals("1", RockstarRos.first(sdk, "Services")?.getAttribute("Count")) + assertEquals("example.invalid", RockstarRos.text(sdk, "Host")) + assertNull(RockstarRos.first(sdk, "ScAuthToken")) + assertFalse(RockstarAuth.sdkTicket(root).contains("refresh-secret")) + } + + @Test fun sdkTitleStateRequiresAnOwnedPackageInsteadOfCatalogVisibility() { + val visible = RockstarApp("1", "future_title", "123", emptyList()) + val featured = RockstarAccountApps(listOf(visible), listOf(RockstarPackage("future_title", true))) + assertFalse(RockstarLibrary.owns(featured, 123, "future_title")) + val owned = RockstarAccountApps(listOf(visible), listOf(RockstarPackage("future_title", false))) + assertTrue(RockstarLibrary.owns(owned, 123, "future_title")) + assertFalse(RockstarLibrary.owns(owned, 124, "other_title")) + } + + @Test fun directLaunchPreservesArgumentsThroughTheWindowsBatchInterpreter() { + org.junit.Assume.assumeTrue(java.io.File.separatorChar == '\\') + val root = java.nio.file.Files.createTempDirectory("rockstar-batch").toFile() + try { + java.io.File(System.getenv("SystemRoot"), "System32/cscript.exe").copyTo(java.io.File(root, "Game.exe")) + java.io.File(root, "probe.vbs").writeText(""" + Set output = CreateObject("Scripting.FileSystemObject").CreateTextFile("args.txt", True) + For Each arg In WScript.Arguments + output.WriteLine(arg) + Next + output.Close + """.trimIndent()) + val args = listOf("", "&literal", "one argument", "%PATH%", "!PATH!", "^&|<>()") + val game = com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, + "future_title", "Game", "Game.exe", args = listOf("//nologo", "probe.vbs") + args) + com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(root, game) + val process = ProcessBuilder("cmd.exe", "/d", "/c", java.io.File(root, com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER).path) + .directory(root).redirectErrorStream(true).start() + assertTrue(process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)) + assertEquals(process.inputStream.bufferedReader().readText(), 0, process.exitValue()) + assertEquals(args, java.io.File(root, "args.txt").readLines()) + } finally { + root.deleteRecursively() + } + } + @Test fun launcherAdoptionDoesNotFollowSymbolicLinks() { val folder = java.nio.file.Files.createTempDirectory("rockstar-launch-link").toFile() val outside = java.io.File.createTempFile("rockstar-keep", ".txt").apply { writeText("keep") } @@ -51,7 +99,7 @@ class RockstarTest { } } - @Test fun unsupportedGamesKeepTheirFilesWithoutRegisteringALauncher() { + @Test fun otherRockstarGamesRegisterAndLaunchTheirInstalledExecutable() { val app = org.robolectric.RuntimeEnvironment.getApplication() com.droiddeck.launcher.session.SessionPrefs.setGameStorage(app, com.droiddeck.launcher.session.SessionPrefs.GAME_STORAGE_OFF, "") val folder = java.io.File(com.droiddeck.launcher.stores.StoreInstallRoot.storeDir(com.droiddeck.launcher.stores.StoreInstallRoot.installRoot(app), com.droiddeck.launcher.stores.Store.ROCKSTAR), "RDR2").apply { mkdirs() } @@ -62,11 +110,27 @@ class RockstarTest { script.writeText("old launcher") val finished = com.droiddeck.launcher.stores.StoreLaunch.writeLauncher(folder, game) finished.write(folder) - assertFalse(RockstarLaunch.supports(game.id)) - assertNull(finished.launcher) - assertFalse(script.exists()) + assertFalse(RockstarLaunch.usesClassicLauncher(game.id)) + assertEquals(com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER, finished.launcher) + assertTrue(script.readText().contains("\"%~dp0RDR2.exe\"")) + assertTrue(script.readText().contains("if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct")) assertTrue(java.io.File(folder, game.exe).isFile) - assertNull(com.droiddeck.launcher.frontend.AddedGames.single(app, folder.path)) + } finally { + folder.deleteRecursively() + } + } + + @Test fun otherRockstarGamesCanRegisterShortcuts() { + org.junit.Assume.assumeTrue(java.io.File.separatorChar == '/') + val app = org.robolectric.RuntimeEnvironment.getApplication() + com.droiddeck.launcher.session.SessionPrefs.setGameStorage(app, com.droiddeck.launcher.session.SessionPrefs.GAME_STORAGE_OFF, "") + val folder = java.io.File(com.droiddeck.launcher.stores.StoreInstallRoot.storeDir(com.droiddeck.launcher.stores.StoreInstallRoot.installRoot(app), com.droiddeck.launcher.stores.Store.ROCKSTAR), "RDR2").apply { mkdirs() } + try { + java.io.File(folder, "RDR2.exe").writeText("installed game") + com.droiddeck.launcher.stores.StoreGameSidecar(com.droiddeck.launcher.stores.Store.ROCKSTAR, "rdr2", "RDR2", "RDR2.exe").write(folder) + val game = com.droiddeck.launcher.frontend.AddedGames.single(app, folder.path) + assertTrue(game != null) + assertTrue(game!!.guestExe.endsWith("/" + com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER)) } finally { folder.deleteRecursively() } @@ -110,7 +174,8 @@ class RockstarTest { } @Test fun classicTitlesUseTheirObservedPipeNames() { - assertEquals(mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe"), RockstarLaunch.pipes) + assertEquals(mapOf("gta3" to "GTA3_Pipe", "gtavc" to "GTA-VC_Pipe", "gtasa" to "GTA_SA_Pipe", "gta4" to "GTAIV_Pipe", "lanoire" to "LANOIRE_Pipe"), RockstarLaunch.pipes) + for (id in RockstarLaunch.pipes.keys) assertTrue(RockstarLaunch.usesClassicLauncher(id)) } @Test fun signingOutClearsOwnedShelfCards() { @@ -162,14 +227,15 @@ class RockstarTest { } @Test - fun classicGamesStartTheirParentLauncherWithoutEmbeddingCredentials() { + fun rockstarLaunchScriptsContainNoCredentials() { val sidecar = com.droiddeck.launcher.stores.StoreGameSidecar( com.droiddeck.launcher.stores.Store.ROCKSTAR, "gtavc", "Vice City", "gta-vc.exe", ) val text = com.droiddeck.launcher.stores.StoreLaunch.launcherText(sidecar) assertTrue(text.contains("\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\"")) assertTrue(text.contains("exit /b %errorlevel%")) - assertFalse(text.contains("gta-vc.exe")) + assertTrue(text.contains("goto direct")) + assertTrue(text.contains("\"%~dp0gta-vc.exe\"")) assertFalse(text.contains("ticket", true)) assertFalse(text.contains("rem ", true)) } diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index ebb9718942..3d07aaba6a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -315,14 +315,51 @@ UBISOFT_WINDOWS_DIR = "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/UbisoftConnectInstaller.exe" ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar") ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher" -ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas"} +ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas", + "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} -def rockstar_registry(folder, title, compat_data, proton): +def rockstar_sdk(folder, sidecar): + if str(sidecar.get("id")) in ("gta4", "lanoire"): + return True + root = folder.resolve() + exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve() + if not exe.is_relative_to(root): + return False + for directory in {root, exe.parent}: + if directory.is_dir() and any(p.is_file() and not p.is_symlink() and p.name.lower() in ("socialclub.dll", "socialclub64.dll") + for p in directory.iterdir()): + return True + if str(sidecar.get("id")) in ROCKSTAR_TITLES: + return False + level = [root] + for _ in range(4): + children = [] + for directory in level: + for path in directory.iterdir(): + if path.is_symlink(): + continue + if path.name.lower() == "title.rgl" and path.is_file() and path.resolve().is_relative_to(root) and 112 <= path.stat().st_size <= 1048576: + with path.open("rb") as source: + if source.read(4) == b"RGLM": + return True + if len(children) < 256 and path.is_dir() and path.resolve().is_relative_to(root): + children.append(path) + level = children + return False + + +def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): pfx = Path(compat_data) / "pfx" launcher = r"C:\Program Files\Rockstar Games\Launcher" - values = [(r"Rockstar Games\Launcher", launcher), ("Rockstar Games\\" + title, windows_path(str(folder)))] + values = [(r"Rockstar Games\Launcher", launcher)] + if title: + values.append(("Rockstar Games\\" + title, windows_path(str(folder)))) entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values] + if sdk_arch: + entries.append((r"Software\Rockstar Games\Rockstar Games Social Club", r"C:\Program Files\Rockstar Games\Social Club")) + program = "Program Files (x86)" if sdk_arch == "x86" else "Program Files" + entries.append((r"Software\Wow6432Node\Rockstar Games\Rockstar Games Social Club", "C:\\" + program + r"\Rockstar Games\Social Club")) reg = pfx / "system.reg" if all(has_value(reg, "[" + key.replace("\\", "\\\\") + "]", "InstallFolder", value) for key, value in entries): return True @@ -338,15 +375,88 @@ def rockstar_registry(folder, title, compat_data, proton): return result.returncode == 0 +def rockstar_runtime(folder, exe, compat_data, arch): + if arch == "x86": + rockstar_runtime(folder, exe, compat_data, "x64") + pfx = Path(compat_data) / "pfx" + target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club" + if not target.resolve().is_relative_to(pfx.resolve()): + raise ValueError("invalid Social Club destination") + required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ()) + marker = target / ".droiddeck-installing" + if all((target / name).is_file() for name in required) and not marker.exists(): + return "present" + root = folder.resolve() + installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None) + if installer is None: + return "game-runtime" + tool = shutil.which("7z") + if not tool: + return "no-unpacker" + listing = subprocess.run([tool, "l", "-t7z", "-slt", "-ba", str(installer)], capture_output=True, + stdin=subprocess.DEVNULL, timeout=30) + if listing.returncode: + return "installer-unreadable" + entries, size = [], 0 + for block in listing.stdout.decode("utf-8", "replace").split("\n\n"): + fields = dict(line.split(" = ", 1) for line in block.splitlines() if " = " in line) + name = fields.get("Path", "").replace("\\", "/") + if not name.startswith(arch + "/"): + continue + if ".." in name.split("/") or ":" in name or fields.get("Symbolic Link") or fields.get("Hard Link"): + raise ValueError("invalid Social Club archive path") + entry_size = int(fields.get("Size", "0")) + if entry_size < 0: + raise ValueError("invalid Social Club member size") + size += entry_size + entries.append(name) + if not entries or len(entries) > 2048 or size > 768 * 1024 * 1024: + raise ValueError("invalid Social Club archive size") + with tempfile.TemporaryDirectory(prefix="droiddeck-socialclub-") as temporary: + result = subprocess.run([tool, "x", "-t7z", "-y", "-o" + temporary, str(installer), arch + "/*"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, timeout=180) + source = Path(temporary) / arch + if result.returncode or not all((source / name).is_file() for name in required): + return "installer-incomplete" + target.mkdir(parents=True, exist_ok=True) + if marker.is_symlink(): + raise ValueError("invalid Social Club install marker") + marker.touch() + for path in source.rglob("*"): + if path.is_symlink() or not path.resolve().is_relative_to(source.resolve()): + raise ValueError("invalid Social Club archive member") + if not path.is_file(): + continue + output = target / path.relative_to(source) + if not output.resolve().is_relative_to(pfx.resolve()): + raise ValueError("invalid Social Club output path") + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=output.parent, delete=False) as stage: + stage_path = Path(stage.name) + try: + with path.open("rb") as stream: + shutil.copyfileobj(stream, stage) + except BaseException: + stage_path.unlink(missing_ok=True) + raise + os.replace(stage_path, output) + marker.unlink() + return "installed" + + def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_app=None): if not compat_data: return "no-prefix" target = Path(compat_data) / "pfx" / ROCKSTAR_FOLDER + if not target.resolve().is_relative_to((Path(compat_data) / "pfx").resolve()): + return "invalid-service-path" config = target / "launch.json" config.unlink(missing_ok=True) + legacy = str(sidecar.get("id")) in ROCKSTAR_TITLES + sdk = rockstar_sdk(folder, sidecar) title = ROCKSTAR_TITLES.get(str(sidecar.get("id"))) - if not title: - return "unsupported-title" if not launch_dir: return "no-channel" root = folder.resolve() @@ -354,7 +464,7 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap if not exe.is_relative_to(root): return "invalid-game-path" workdir = (folder / str(sidecar["workdir"])).resolve() if sidecar.get("workdir") is not None else exe.parent - if not workdir.is_relative_to(root) or not exe.is_file() or not (folder / "MTLX.dll").is_file(): + if not workdir.is_relative_to(root) or not exe.is_file() or legacy and not any((p / "MTLX.dll").is_file() for p in (root, exe.parent)): return "invalid-game-path" args = sidecar.get("args") or [] if not isinstance(args, list) or any(not isinstance(arg, str) or "\0" in arg for arg in args): @@ -376,7 +486,10 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap made = "present" if (Path(compat_data) / "pfx/user.reg").is_file() else create_prefix(compat_data, proton) if made not in ("created", "present"): return "prefix-" + made - if not rockstar_registry(folder, title, compat_data, proton): + arch = "x86" if signature[4:] == b"\x4c\x01" else "x64" + if sdk: + log("rockstar runtime: " + rockstar_runtime(folder, exe, compat_data, arch)) + if not rockstar_registry(folder, title, compat_data, proton, sdk_arch=arch if sdk else None): return "registry-unavailable" target.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(prefix="Launcher-", suffix=".exe", dir=target, delete=False) as temporary: @@ -391,14 +504,28 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "rockstar-launch", "store": "rockstar", "id": str(sidecar.get("id"))}, timeout=120.0) if not isinstance(answer, dict) or not answer.get("ok"): return "session-" + (str(answer.get("reason") or "refused") if isinstance(answer, dict) else "timeout") - if not isinstance(answer.get("material"), str) or not re.fullmatch(r"[0-9A-Fa-f]{640}", answer["material"]): + if legacy and (not isinstance(answer.get("material"), str) or not re.fullmatch(r"[0-9A-Fa-f]{640}", answer["material"])): return "invalid-material" expires = answer.get("expiresAt") if not isinstance(expires, int) or not time.time() * 1000 < expires <= time.time() * 1000 + 120_000: return "invalid-expiry" launch = {"folder": windows_path(str(root)), "exe": windows_path(str(exe)), "workdir": windows_path(str(workdir)), - "args": args, "pipe": answer.get("pipe"), "material": answer["material"], "expiresAt": expires} - if len(json.dumps(launch).encode("utf-8")) > 16384: + "args": args, "expiresAt": expires} + if legacy: + launch.update(pipe=answer.get("pipe"), material=answer["material"]) + if sdk: + session = answer.get("session") + if not isinstance(session, dict) or not isinstance(session.get("accountId"), str) \ + or not re.fullmatch(r"[1-9][0-9]{0,19}", session["accountId"]) or int(session["accountId"]) > 2**64 - 1 \ + or any(not isinstance(session.get(key), str) or not session[key] or "\0" in session[key] + or len(session[key].encode("utf-8")) > limit for key, limit in (("identity", 512), ("ticket", 49152))): + return "invalid-sdk-session" + launch["session"] = {key: session[key] for key in ("accountId", "identity", "ticket")} + if "titleId" in session: + if not isinstance(session["titleId"], str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", session["titleId"]): + return "invalid-sdk-title" + launch["session"]["titleId"] = session["titleId"] + if len(json.dumps(launch).encode("utf-8")) > 65536: return "handoff-too-large" with tempfile.NamedTemporaryFile(mode="w", prefix="launch-", suffix=".json", dir=target, delete=False) as temporary: temporary_path = Path(temporary.name) @@ -1446,6 +1573,10 @@ def main(argv): log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", ""))) log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("BL_STORE_PROTON", ""))) if store == "rockstar": + if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar): + if compat_data: + (Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True) + return STORE_GAME try: state = prepare_rockstar(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", "")) except (OSError, ValueError, subprocess.TimeoutExpired): diff --git a/tools/rockstar-launcher/README.md b/tools/rockstar-launcher/README.md index e22a4183c8..2965084713 100644 --- a/tools/rockstar-launcher/README.md +++ b/tools/rockstar-launcher/README.md @@ -1,11 +1,17 @@ # Rockstar launcher service -`Launcher.exe` starts the selected installed game and serves its launcher pipe. The Android app checks ownership and retrieves the launch response from Rockstar. Account credentials and ROS tickets stay in the app. +`Launcher.exe` starts the selected installed game and serves its launcher pipes. The Android app obtains title authorization from Rockstar. Refresh credentials stay in Android Keystore-backed storage. -The handoff is deleted before starting the game. It expires after 90 seconds. The pipe accepts the child process's greeting and returns the server-issued launch material. No game files are patched. +The handoff is mode 0600, expires after 90 seconds and is deleted before starting the game. Legacy launches carry server-issued launch material. SDK launches also carry a short-lived ROS ticket and account identity; those values are kept in memory after the handoff is consumed and are not logged. Pipes reject remote clients and check the client process against the launched child. No game files are patched. + +GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path. + +The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified. GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides. +Raw launcher identity requests use `INIT::` with a terminating colon. Framed requests carry their payload length. The reply echoes the complete challenge after `TINI:launcher:`; partial reads do not complete a raw request. + `build.sh` builds 32-bit and 64-bit executables with the GNU Windows targets and stages them as APK resources. `legacy-cipher.bin` contains the fixed client protocol tables, not account credentials or APK signing keys. Run the protocol tests with: diff --git a/tools/rockstar-launcher/examples/sdk_probe.rs b/tools/rockstar-launcher/examples/sdk_probe.rs new file mode 100644 index 0000000000..b280ce0409 --- /dev/null +++ b/tools/rockstar-launcher/examples/sdk_probe.rs @@ -0,0 +1,80 @@ +#[cfg(windows)] +fn run() -> Result<(), Box> { + use droiddeck_rockstar_launcher::{pipe::Pipe, sdk::Message, Frame, Length}; + use std::io::{Read, Write}; + for (path, framed) in [ + (b"\\\\.\\pipe\\ProbeLauncherPipe\0".as_slice(), true), + (b"\\\\.\\pipe\\RawProbeLauncher_Pipe\0".as_slice(), false), + ] { + let name = std::str::from_utf8(&path[9..path.len() - 1])?; + let mut pipe = Pipe::connect(name, std::time::Duration::from_secs(10))?; + let request = b"INIT:42:"; + if framed { + let mut bytes = (request.len() as u32).to_le_bytes().to_vec(); + bytes.extend_from_slice(request); + pipe.write_all(&bytes)?; + let response = Frame::read(&mut pipe, Length::Body)?; + if response.tag != *b"TINI" || response.payload != b"launcher:42:" { + return Err("invalid framed launcher identity reply".into()); + } + } else { + pipe.write_all(b"INIT:4")?; + std::thread::sleep(std::time::Duration::from_millis(20)); + pipe.write_all(b"2:")?; + let mut response = vec![0; b"TINI:launcher:42:".len()]; + pipe.read_exact(&mut response)?; + if response != b"TINI:launcher:42:" { + return Err("invalid raw launcher identity reply".into()); + } + } + } + let args: Vec<_> = std::env::args().collect(); + let instance: u32 = args + .iter() + .find_map(|arg| arg.strip_prefix("-processInstance=")) + .ok_or("missing instance")? + .parse()?; + let output = args + .windows(2) + .find(|pair| pair[0] == "--result") + .map(|pair| &pair[1]) + .ok_or("missing result path")?; + let mut pipe = Pipe::connect( + &format!("chrome.rgsc_gameinst_{instance}"), + std::time::Duration::from_secs(10), + )?; + if Message::read(&mut pipe)?.kind != 0xffff { + return Err("missing transport hello".into()); + } + Message { + routing: i32::MAX, + kind: 0x40000, + flags: 2, + payload: 4u32.to_le_bytes().to_vec(), + } + .write(&mut pipe)?; + let expected = [0x30002, 0x30003, 0x30004, 0x30000]; + for kind in expected { + let message = Message::read(&mut pipe)?; + if message.kind != kind || message.routing != i32::MAX || message.flags != 2 { + return Err("unexpected SDK message envelope".into()); + } + if kind == 0x30002 && message.payload != [3, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + { + return Err("unexpected fixture account".into()); + } + if kind == 0x30000 && message.payload != 4u32.to_le_bytes() { + return Err("launcher hello lost its context".into()); + } + } + std::fs::write(output, "SDK handshake accepted")?; + Ok(()) +} + +fn main() { + #[cfg(windows)] + if let Err(error) = run() { + eprintln!("SDK probe failed: {error}"); + std::process::exit(1); + } +} diff --git a/tools/rockstar-launcher/src/identity.rs b/tools/rockstar-launcher/src/identity.rs new file mode 100644 index 0000000000..795d56da1a --- /dev/null +++ b/tools/rockstar-launcher/src/identity.rs @@ -0,0 +1,170 @@ +use std::collections::BTreeSet; +use std::io::{self, Read}; + +const LIMIT: usize = 4096; + +fn invalid() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + "invalid launcher identity request", + ) +} + +fn collect(bytes: &[u8], names: &mut BTreeSet) { + let prefix = br"\\.\pipe\"; + for (index, window) in bytes.windows(prefix.len()).enumerate() { + if window != prefix { + continue; + } + let tail = &bytes[index + prefix.len()..]; + let Some(end) = tail.iter().take(97).position(|byte| *byte == 0) else { + continue; + }; + let name = &tail[..end]; + if !name.is_empty() + && name + .iter() + .all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(byte)) + { + let name = std::str::from_utf8(name).unwrap(); + if name.ends_with("LauncherPipe") || name.ends_with("Launcher_Pipe") { + names.insert(name.to_owned()); + } + } + } +} + +pub fn pipe_names(reader: &mut impl Read) -> io::Result> { + let mut names = BTreeSet::new(); + let mut carry = Vec::new(); + let mut chunk = [0; 65536]; + let mut total = 0usize; + loop { + let count = reader.read(&mut chunk)?; + if count == 0 { + break; + } + total += count; + if total > 256 * 1024 * 1024 { + return Err(invalid()); + } + carry.extend_from_slice(&chunk[..count]); + collect(&carry, &mut names); + for offset in 0..2 { + let ascii: Vec<_> = carry[offset..] + .chunks_exact(2) + .map(|pair| if pair[1] == 0 { pair[0] } else { 0 }) + .collect(); + collect(&ascii, &mut names); + } + if names.len() > 4 { + return Err(invalid()); + } + carry.drain(..carry.len().saturating_sub(256)); + } + Ok(names.into_iter().collect()) +} + +pub fn exchange(reader: &mut impl Read) -> io::Result> { + let mut header = [0; 4]; + reader.read_exact(&mut header)?; + let framed = header != *b"INIT"; + let mut request = if framed { + let size = u32::from_le_bytes(header) as usize; + if !(6..=LIMIT).contains(&size) { + return Err(invalid()); + } + let mut bytes = vec![0; size]; + reader.read_exact(&mut bytes)?; + bytes + } else { + let mut bytes = header.to_vec(); + let mut byte = [0]; + reader.read_exact(&mut byte)?; + if byte[0] != b':' { + return Err(invalid()); + } + bytes.push(b':'); + loop { + reader.read_exact(&mut byte)?; + if !(32..127).contains(&byte[0]) || bytes.len() >= 261 { + return Err(invalid()); + } + bytes.push(byte[0]); + if byte[0] == b':' { + break; + } + } + bytes + }; + if request.last() == Some(&0) { + request.pop(); + } + let challenge = request.strip_prefix(b"INIT:").ok_or_else(invalid)?; + if challenge.is_empty() + || !framed && challenge == b":" + || challenge.len() > 256 + || !challenge.iter().all(|byte| (32..127).contains(byte)) + { + return Err(invalid()); + } + let mut reply = b"TINI:launcher:".to_vec(); + reply.extend_from_slice(challenge); + if framed { + let mut bytes = (reply.len() as u32).to_le_bytes().to_vec(); + bytes.extend_from_slice(&reply); + Ok(bytes) + } else { + Ok(reply) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn discovers_ascii_and_wide_pipe_names_across_chunks() { + let mut bytes = vec![0; 65530]; + bytes.extend_from_slice(br"\\.\pipe\GameLauncherPipe"); + bytes.push(0); + for value in "\\\\.\\pipe\\OtherLauncher_Pipe\0".encode_utf16() { + bytes.extend_from_slice(&value.to_le_bytes()); + } + bytes.extend_from_slice(br"\\.\pipe\..\outsideLauncherPipe"); + bytes.push(0); + assert_eq!( + pipe_names(&mut Cursor::new(bytes)).unwrap(), + ["GameLauncherPipe", "OtherLauncher_Pipe"] + ); + } + + #[test] + fn identity_replies_echo_only_a_valid_challenge() { + struct Split(R); + impl Read for Split { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let size = buffer.len().min(2); + self.0.read(&mut buffer[..size]) + } + } + assert_eq!( + exchange(&mut Split(Cursor::new(b"INIT:123456789:\0"))).unwrap(), + b"TINI:launcher:123456789:" + ); + let request = b"INIT:nonce:123:"; + let mut bytes = (request.len() as u32).to_le_bytes().to_vec(); + bytes.extend_from_slice(request); + let reply = exchange(&mut Cursor::new(bytes)).unwrap(); + assert_eq!( + u32::from_le_bytes(reply[..4].try_into().unwrap()) as usize, + reply.len() - 4 + ); + assert_eq!(&reply[4..], b"TINI:launcher:nonce:123:"); + assert!(exchange(&mut Cursor::new(b"INIT:")).is_err()); + assert!(exchange(&mut Cursor::new(b"INIT:a\0b")).is_err()); + assert!(exchange(&mut Cursor::new(b"INIT:unterminated")).is_err()); + assert!(exchange(&mut Cursor::new([255; 4])).is_err()); + } +} diff --git a/tools/rockstar-launcher/src/lib.rs b/tools/rockstar-launcher/src/lib.rs index e08b2bc92b..e37ff76d85 100644 --- a/tools/rockstar-launcher/src/lib.rs +++ b/tools/rockstar-launcher/src/lib.rs @@ -3,6 +3,9 @@ use std::io::{self, Read, Write}; #[cfg(windows)] pub mod pipe; +pub mod identity; +pub mod sdk; + pub const MAX_FRAME_BYTES: usize = 64 * 1024; const OVERHEAD: usize = 4 + 4 + 1; @@ -111,6 +114,21 @@ impl Frame { #[cfg(test)] mod tests { use super::*; + + #[test] + fn launcher_era_reply_uses_total_length_and_a_terminator() { + let mut bytes = Vec::new(); + Frame { + tag: *b"DUNN", + payload: vec![b'A'; 640], + nul_terminated: true, + } + .write(&mut bytes, Length::Total) + .unwrap(); + assert_eq!(bytes.len(), 650); + assert_eq!(&bytes[..9], &[138, 2, 0, 0, b'D', b'U', b'N', b'N', b':']); + assert_eq!(bytes[649], 0); + } use std::io::Cursor; #[test] diff --git a/tools/rockstar-launcher/src/main.rs b/tools/rockstar-launcher/src/main.rs index fe5923ab37..0913c6d548 100644 --- a/tools/rockstar-launcher/src/main.rs +++ b/tools/rockstar-launcher/src/main.rs @@ -23,17 +23,21 @@ fn log(message: &str) { #[cfg(windows)] fn run() -> Result> { - use droiddeck_rockstar_launcher::{pipe::Listener, wait_for_game, Frame, Length}; - use std::io::Read; + use droiddeck_rockstar_launcher::{ + pipe::Listener, + sdk::{Message, Session}, + wait_for_game, Frame, Length, + }; + use std::io::{Read, Write}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; let config_path = std::env::current_exe()?.with_file_name("launch.json"); let mut data = Vec::new(); std::fs::File::open(&config_path)? - .take(16385) + .take(65537) .read_to_end(&mut data)?; std::fs::remove_file(&config_path)?; - if data.len() > 16384 { + if data.len() > 65536 { return Err("launch handoff exceeds size limit".into()); } let config: serde_json::Value = serde_json::from_slice(&data)?; @@ -51,16 +55,48 @@ fn run() -> Result> { if expires <= now || expires - now > 120_000 { return Err("launch handoff expired".into()); } - let material = text("material")?.as_bytes().to_vec(); - if material.len() != 640 || !material.iter().all(u8::is_ascii_hexdigit) { - return Err("invalid launch material".into()); - } - let pipe_name = text("pipe")?.to_owned(); - if !matches!( - pipe_name.as_str(), - "GTA3_Pipe" | "GTA-VC_Pipe" | "GTA_SA_Pipe" - ) { - return Err("unsupported Rockstar launch pipe".into()); + let legacy = if config.get("pipe").is_some() { + let pipe_name = text("pipe")?.to_owned(); + if !matches!( + pipe_name.as_str(), + "GTA3_Pipe" | "GTA-VC_Pipe" | "GTA_SA_Pipe" | "GTAIV_Pipe" | "LANOIRE_Pipe" + ) { + return Err("invalid Rockstar launch pipe".into()); + } + let material = text("material")?.as_bytes().to_vec(); + if material.len() != 640 || !material.iter().all(u8::is_ascii_hexdigit) { + return Err("invalid launch material".into()); + } + Some((pipe_name, material)) + } else { + None + }; + let session = config + .get("session") + .map(|value| -> Result> { + let account = value + .get("accountId") + .and_then(|v| v.as_str()) + .ok_or("missing SDK account")? + .parse::()?; + let identity = value + .get("identity") + .and_then(|v| v.as_str()) + .ok_or("missing SDK identity")?; + let ticket = value + .get("ticket") + .and_then(|v| v.as_str()) + .ok_or("missing SDK ticket")?; + let session = Session::new(account, identity.to_owned(), ticket.to_owned())?; + Ok(if let Some(title) = value.get("titleId") { + session.with_title(title.as_str().ok_or("invalid SDK title")?.to_owned())? + } else { + session + }) + }) + .transpose()?; + if legacy.is_none() && session.is_none() { + return Err("missing launch protocol".into()); } let root = std::fs::canonicalize(text("folder")?)?; let exe = std::fs::canonicalize(text("exe")?)?; @@ -68,7 +104,9 @@ fn run() -> Result> { if !exe.is_file() || !exe.starts_with(&root) || !workdir.starts_with(&root) - || !root.join("MTLX.dll").is_file() + || legacy.is_some() + && !root.join("MTLX.dll").is_file() + && !exe.parent().unwrap_or(&root).join("MTLX.dll").is_file() { return Err("invalid Rockstar game path".into()); } @@ -91,40 +129,125 @@ fn run() -> Result> { .map(|value| value.as_str().ok_or("invalid game argument")) .collect(); log("launch handoff accepted"); - let listener = Listener::new(&pipe_name, Duration::from_secs(30))?; - log("launcher pipe created"); - let mut child = std::process::Command::new(exe) - .current_dir(workdir) - .args(args?) - .spawn()?; + let legacy = legacy + .map(|(name, material)| { + let terminated = matches!(name.as_str(), "GTAIV_Pipe" | "LANOIRE_Pipe"); + Listener::new(&name, Duration::from_secs(90)) + .map(|listener| (listener, material, terminated)) + }) + .transpose()?; + let instance = std::process::id(); + let sdk_listener = if session.is_some() { + Some(Listener::new( + &format!("chrome.rgsc_gameinst_{instance}"), + Duration::from_secs(90), + )?) + } else { + None + }; + let mut identity_listeners = Vec::new(); + if session.is_some() { + for name in + droiddeck_rockstar_launcher::identity::pipe_names(&mut std::fs::File::open(&exe)?)? + { + identity_listeners.push(Listener::new(&name, Duration::from_secs(90))?); + } + } + log("launcher pipes created"); + let mut command = std::process::Command::new(exe); + command.current_dir(workdir).args(args?); + if session.is_some() { + command.arg(format!("-processInstance={instance}")); + } + let mut child = command.spawn()?; let pid = child.id(); log("game process started"); + for listener in identity_listeners { + std::thread::spawn(move || { + let serve = || -> std::io::Result<()> { + let mut pipe = listener.accept()?.with_deadline(Duration::from_secs(90)); + if pipe.client_pid()? != pid { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "unexpected launcher identity client", + )); + } + let reply = droiddeck_rockstar_launcher::identity::exchange(&mut pipe)?; + pipe.write_all(&reply)?; + log("launcher identity challenge complete"); + pipe = pipe.with_timeout(Duration::from_secs(86400)); + let mut progress = [0; 4096]; + while matches!(pipe.read(&mut progress), Ok(size) if size > 0) {} + Ok(()) + }; + if let Err(error) = serve() { + log(&format!("launcher identity exchange ended: {error}")); + } + }); + } let (result, handshake) = std::sync::mpsc::sync_channel(1); std::thread::spawn(move || { let serve = || -> std::io::Result<()> { - let mut pipe = listener.accept()?; - log("launcher pipe connected"); - if pipe.client_pid()? != pid { - return Err(std::io::Error::new( - std::io::ErrorKind::PermissionDenied, - "unexpected Rockstar pipe client", - )); + if let Some((listener, material, terminated)) = legacy { + let mut pipe = listener.accept()?; + log("legacy launcher pipe connected"); + if pipe.client_pid()? != pid { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "unexpected Rockstar pipe client", + )); + } + let request = Frame::read(&mut pipe, Length::Total)?; + if request.tag != *b"COLE" || !request.payload.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "unexpected Rockstar greeting", + )); + } + Frame { + tag: *b"DUNN", + payload: material, + nul_terminated: terminated, + } + .write( + &mut pipe, + if terminated { + Length::Total + } else { + Length::Body + }, + )?; + log("legacy launcher handshake complete"); } - let request = Frame::read(&mut pipe, Length::Total)?; - log("game greeting received"); - if request.tag != *b"COLE" || !request.payload.is_empty() { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "unexpected Rockstar greeting", - )); + if let (Some(listener), Some(session)) = (sdk_listener, session) { + let mut pipe = listener.accept()?.with_deadline(Duration::from_secs(90)); + if pipe.client_pid()? != pid { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "unexpected Rockstar SDK client", + )); + } + Message::hello(instance).write(&mut pipe)?; + let mut authenticated = false; + loop { + let request = match Message::read(&mut pipe) { + Ok(request) => request, + Err(_) if authenticated => return Ok(()), + Err(error) => return Err(error), + }; + let responses = session.respond(&request)?; + let sends_login = request.kind == 0x40000; + for response in responses { + response.write(&mut pipe)?; + } + if sends_login && !authenticated { + authenticated = true; + pipe = pipe.with_timeout(Duration::from_secs(86400)); + log("SDK login sent"); + let _ = result.send(Ok(())); + } + } } - Frame { - tag: *b"DUNN", - payload: material, - nul_terminated: false, - } - .write(&mut pipe, Length::Body)?; - log("launcher handshake complete"); Ok(()) }; let outcome = serve(); diff --git a/tools/rockstar-launcher/src/pipe.rs b/tools/rockstar-launcher/src/pipe.rs index 79ab4d9e42..9bffedde38 100644 --- a/tools/rockstar-launcher/src/pipe.rs +++ b/tools/rockstar-launcher/src/pipe.rs @@ -84,6 +84,7 @@ impl Drop for OwnedHandle { pub struct Pipe { handle: OwnedHandle, timeout: Duration, + deadline: Option, } pub struct Listener(Pipe); @@ -119,6 +120,7 @@ impl Listener { Ok(Self(Pipe { handle: OwnedHandle(handle), timeout, + deadline: None, })) } @@ -174,6 +176,18 @@ impl Listener { } impl Pipe { + pub fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self.deadline = None; + self + } + + pub fn with_deadline(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self.deadline = Some(Instant::now() + timeout); + self + } + pub fn client_pid(&self) -> io::Result { let mut pid = 0; if unsafe { GetNamedPipeClientProcessId(self.handle.0, &mut pid) } == 0 || pid == 0 { @@ -210,6 +224,7 @@ impl Pipe { return Ok(Self { handle: OwnedHandle(handle), timeout, + deadline: None, }); } let error = io::Error::last_os_error(); @@ -234,6 +249,16 @@ impl Pipe { if size == 0 { return Ok(0); } + let timeout = self + .deadline + .map(|deadline| deadline.saturating_duration_since(Instant::now())) + .unwrap_or(self.timeout); + if timeout.is_zero() { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "Rockstar pipe deadline exceeded", + )); + } let event = unsafe { CreateEventW(null(), 1, 0, null()) }; if event.is_null() { return Err(io::Error::last_os_error()); @@ -280,7 +305,7 @@ impl Pipe { let wait = unsafe { WaitForSingleObject( event.0, - self.timeout.as_millis().min(u32::MAX as u128 - 1) as u32, + timeout.as_millis().min(u32::MAX as u128 - 1) as u32, ) }; if wait != 0 { @@ -342,6 +367,28 @@ mod tests { ) } + #[test] + fn initialization_deadline_survives_partial_reads() { + let name = name(); + let listener = Listener::new(&name, Duration::from_secs(2)).unwrap(); + let worker = std::thread::spawn(move || { + let mut server = listener + .accept() + .unwrap() + .with_deadline(Duration::from_millis(150)); + let mut byte = [0]; + server.read_exact(&mut byte).unwrap(); + std::thread::sleep(Duration::from_millis(180)); + assert_eq!( + server.read(&mut byte).unwrap_err().kind(), + io::ErrorKind::TimedOut + ); + }); + let mut client = Pipe::connect(&name, Duration::from_secs(2)).unwrap(); + client.write_all(&[1]).unwrap(); + worker.join().unwrap(); + } + #[test] fn real_pipe_exchanges_both_framing_modes_and_identifies_the_client() { let name = name(); diff --git a/tools/rockstar-launcher/src/sdk.rs b/tools/rockstar-launcher/src/sdk.rs new file mode 100644 index 0000000000..9361ad54c2 --- /dev/null +++ b/tools/rockstar-launcher/src/sdk.rs @@ -0,0 +1,328 @@ +use std::io::{self, Read, Write}; + +const HEADER: usize = 16; +const MAX_BYTES: usize = 64 * 1024; +const CONTROL: i32 = i32::MAX; + +#[derive(PartialEq, Eq)] +pub struct Message { + pub routing: i32, + pub kind: u32, + pub flags: u32, + pub payload: Vec, +} + +impl std::fmt::Debug for Message { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Message") + .field("routing", &self.routing) + .field("kind", &self.kind) + .field("flags", &self.flags) + .field("payload_bytes", &self.payload.len()) + .finish() + } +} + +fn invalid() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "invalid Rockstar SDK message") +} + +impl Message { + pub fn read(reader: &mut impl Read) -> io::Result { + let mut header = [0; HEADER]; + reader.read_exact(&mut header)?; + let size = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize; + if size > MAX_BYTES - HEADER { + return Err(invalid()); + } + let mut payload = vec![0; size]; + reader.read_exact(&mut payload)?; + Ok(Self { + routing: i32::from_le_bytes(header[4..8].try_into().unwrap()), + kind: u32::from_le_bytes(header[8..12].try_into().unwrap()), + flags: u32::from_le_bytes(header[12..16].try_into().unwrap()), + payload, + }) + } + + pub fn write(&self, writer: &mut impl Write) -> io::Result<()> { + if self.payload.len() > MAX_BYTES - HEADER { + return Err(invalid()); + } + let mut bytes = Vec::with_capacity(HEADER + self.payload.len()); + bytes.extend_from_slice(&(self.payload.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&self.routing.to_le_bytes()); + bytes.extend_from_slice(&self.kind.to_le_bytes()); + bytes.extend_from_slice(&self.flags.to_le_bytes()); + bytes.extend_from_slice(&self.payload); + writer.write_all(&bytes) + } + + fn control(kind: u32, payload: Payload) -> Self { + Self { + routing: CONTROL, + kind, + flags: 2, + payload: payload.0, + } + } + + pub fn hello(pid: u32) -> Self { + Self { + routing: -2, + kind: 0xffff, + flags: 2, + payload: pid.to_le_bytes().to_vec(), + } + } +} + +#[derive(Default)] +struct Payload(Vec); + +impl Payload { + fn raw(mut self, bytes: &[u8]) -> Self { + self.0.resize((self.0.len() + 3) & !3, 0); + self.0.extend_from_slice(bytes); + self + } + + fn u32(self, value: u32) -> Self { + self.raw(&value.to_le_bytes()) + } + fn u64(self, value: u64) -> Self { + self.raw(&value.to_le_bytes()) + } + fn string(self, value: &str) -> Self { + self.u32(value.len() as u32).raw(value.as_bytes()) + } +} + +pub struct Session { + account: u64, + identity: String, + ticket: String, + title: Option, + api: std::cell::Cell, +} + +impl Session { + pub fn new(account: u64, identity: String, ticket: String) -> io::Result { + if account == 0 + || identity.is_empty() + || identity.len() > 512 + || ticket.is_empty() + || ticket.len() > 48 * 1024 + || identity.contains('\0') + || ticket.contains('\0') + { + return Err(invalid()); + } + Ok(Self { + account, + identity, + ticket, + title: None, + api: std::cell::Cell::new(3), + }) + } + + pub fn with_title(mut self, title: String) -> io::Result { + if title.is_empty() + || title.len() > 64 + || !title.as_bytes()[0].is_ascii_lowercase() + || !title + .bytes() + .all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == b'_') + { + return Err(invalid()); + } + self.title = Some(title); + Ok(self) + } + + fn app_sync(&self, challenge: u64) -> io::Result { + let mut payload = Payload::default().u32(u32::from(self.title.is_some())); + if let Some(title) = &self.title { + payload = payload + .u64(u64::MAX) + .u64(0) + .u64(0) + .string(title) + .u32(1) + .u32(1) + .string(""); + } + let mut inner = Vec::new(); + Message::control(0x80006, payload).write(&mut inner)?; + Ok(Message::control( + 0x80002, + Payload::default().u64(challenge).string(&base64(&inner)), + )) + } + + pub fn login(&self) -> Vec { + let offset = u32::from(self.api.get() >= 4); + vec![ + Message::control( + 0x30001 + offset, + Payload::default().u32(3).u64(self.account).u32(0), + ), + Message::control( + 0x30002 + offset, + Payload::default() + .u64(self.account) + .u32(0) + .string(&self.identity), + ), + Message::control( + 0x30003 + offset, + Payload::default() + .string(&self.identity) + .string(&self.ticket), + ), + ] + } + + pub fn respond(&self, message: &Message) -> io::Result> { + match message.kind { + 0x80000 => { + if message.payload.len() != 8 { + return Err(invalid()); + } + let challenge = u64::from_le_bytes(message.payload[..8].try_into().unwrap()); + Ok(vec![self.app_sync(challenge)?]) + } + 0x40000 => { + if message.payload.len() < 4 { + return Err(invalid()); + } + let context = u32::from_le_bytes(message.payload[..4].try_into().unwrap()); + self.api.set(context); + let mut result = self.login(); + result.push(Message::control(0x30000, Payload::default().u32(context))); + Ok(result) + } + 0x40005 | 0x40007 => Ok(vec![Message::control( + 0x30004 + u32::from(self.api.get() >= 4), + Payload::default(), + )]), + _ => Ok(Vec::new()), + } + } +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut output = String::with_capacity(bytes.len().div_ceil(3) * 4); + for part in bytes.chunks(3) { + let value = ((part[0] as u32) << 16) + | ((part.get(1).copied().unwrap_or(0) as u32) << 8) + | part.get(2).copied().unwrap_or(0) as u32; + output.push(ALPHABET[(value >> 18) as usize] as char); + output.push(ALPHABET[((value >> 12) & 63) as usize] as char); + output.push(if part.len() > 1 { + ALPHABET[((value >> 6) & 63) as usize] as char + } else { + '=' + }); + output.push(if part.len() > 2 { + ALPHABET[(value & 63) as usize] as char + } else { + '=' + }); + } + output +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn app_sync_echoes_challenge_without_inventing_owned_titles() { + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + let request = Message::control(0x80000, Payload::default().u64(42)); + let response = session.respond(&request).unwrap().remove(0); + assert_eq!(response.kind, 0x80002); + assert_eq!(&response.payload[..8], &42u64.to_le_bytes()); + assert_eq!(&response.payload[12..], b"BAAAAP///38GAAgAAgAAAAAAAAA="); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert!(session.with_title("../game".into()).is_err()); + } + + #[test] + fn transport_hello_matches_wire_layout() { + let mut bytes = Vec::new(); + Message::hello(0x1234).write(&mut bytes).unwrap(); + assert_eq!( + bytes, + [4, 0, 0, 0, 254, 255, 255, 255, 255, 255, 0, 0, 2, 0, 0, 0, 52, 18, 0, 0] + ); + } + + #[test] + fn login_preserves_string_lengths_and_alignment() { + let session = Session::new(0x1122334455667788, "a@b".into(), "ticket".into()).unwrap(); + let login = session.login(); + assert_eq!( + login[0].payload, + [3, 0, 0, 0, 136, 119, 102, 85, 68, 51, 34, 17, 0, 0, 0, 0] + ); + assert_eq!( + login[1].payload, + [136, 119, 102, 85, 68, 51, 34, 17, 0, 0, 0, 0, 3, 0, 0, 0, 97, 64, 98] + ); + assert_eq!( + login[2].payload, + [3, 0, 0, 0, 97, 64, 98, 0, 6, 0, 0, 0, 116, 105, 99, 107, 101, 116] + ); + } + + #[test] + fn init_sends_authenticated_state_before_launcher_hello() { + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + for (api, expected) in [ + (3, [0x30001, 0x30002, 0x30003, 0x30000]), + (4, [0x30002, 0x30003, 0x30004, 0x30000]), + ] { + let request = Message::control(0x40000, Payload::default().u32(api)); + let result = session.respond(&request).unwrap(); + assert_eq!(result.iter().map(|m| m.kind).collect::>(), expected); + assert_eq!( + result[0].payload, + [3, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ); + assert_eq!(result[3].payload, api.to_le_bytes()); + } + } + + #[test] + fn malformed_frames_and_sessions_are_rejected() { + assert!(Session::new(0, "name".into(), "ticket".into()).is_err()); + assert!(Session::new(123, "name".into(), "".into()).is_err()); + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + assert!(session + .respond(&Message::control(0x40000, Payload::default())) + .is_err()); + assert!(Message::read(&mut Cursor::new(vec![255; 16])).is_err()); + assert!(Message::read(&mut Cursor::new(vec![0; 15])).is_err()); + } + + #[test] + fn concatenated_messages_remain_separate() { + let session = Session::new(123, "name".into(), "ticket".into()).unwrap(); + let mut bytes = Vec::new(); + for message in session.login() { + message.write(&mut bytes).unwrap(); + } + let mut reader = Cursor::new(bytes); + for message in session.login() { + assert_eq!(Message::read(&mut reader).unwrap(), message); + } + } +} diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py index 68f4401544..23cd6ae632 100644 --- a/tools/tests/test_store_launch_rockstar.py +++ b/tools/tests/test_store_launch_rockstar.py @@ -1,4 +1,5 @@ import json +import os from pathlib import Path import tempfile import time @@ -9,6 +10,112 @@ from test_store_launch import store class RockstarLaunch(unittest.TestCase): + def test_service_directory_cannot_export_sessions_outside_the_prefix(self): + with tempfile.TemporaryDirectory() as root: + folder, sidecar, prefix, _, _ = self.setup_game(root) + outside = Path(root) / 'outside' + outside.mkdir() + target = prefix / 'pfx' / store.ROCKSTAR_FOLDER + target.parent.mkdir(parents=True) + target.symlink_to(outside, target_is_directory=True) + sentinel = outside / 'launch.json' + sentinel.write_text('keep') + with patch.object(store, 'ask') as ask: + self.assertEqual('invalid-service-path', store.prepare_rockstar(folder, sidecar, prefix, 'channel')) + ask.assert_not_called() + self.assertEqual('keep', sentinel.read_text()) + + def test_sdk_registration_does_not_use_an_untrusted_display_name_as_a_key(self): + with tempfile.TemporaryDirectory() as root: + folder, _, prefix, _, _ = self.setup_game(root) + with patch.object(store, 'wait_for_server', return_value=True): + self.assertTrue(store.rockstar_registry(folder, None, prefix, '', sdk_arch='x64')) + text = (prefix / 'pfx/system.reg').read_text() + self.assertIn(r'[Software\\Rockstar Games\\Rockstar Games Social Club]', text) + self.assertNotIn('Grand Theft Auto', text) + + def test_root_metadata_is_found_after_many_assets(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) + for index in range(300): + (folder / ('asset-%s.dat' % index)).write_bytes(b'asset') + (folder / 'title.rgl').write_bytes(b'RGLM' + bytes(108)) + self.assertTrue(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'})) + (folder / 'title.rgl').unlink() + (folder / 'Title.RGL').write_bytes(b'RGLM' + bytes(108)) + self.assertTrue(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'})) + + def test_sdk_titles_receive_only_their_short_lived_game_session(self): + with tempfile.TemporaryDirectory() as root: + def change(values): + folder, sidecar, _, _, answer = values + sidecar['id'] = 'future_title' + (folder / 'socialclub.dll').write_bytes(b'game-runtime') + answer['session'] = {'accountId': '123', 'identity': 'player@example.invalid', 'ticket': 'game-session', + 'ScAuthToken': 'never-export-refresh-token'} + result, path, _ = self.prepare(root, change) + self.assertEqual('ready', result) + data = json.loads(path.read_text()) + self.assertEqual({'accountId', 'identity', 'ticket'}, set(data['session'])) + self.assertNotIn('pipe', data) + self.assertNotIn('material', data) + self.assertNotIn('never-export-refresh-token', path.read_text()) + self.assertEqual(0o600, path.stat().st_mode & 0o777) + + def test_invalid_sdk_sessions_cannot_reuse_an_old_handoff(self): + for session in (None, {'accountId': '0', 'identity': 'player', 'ticket': 'session'}, + {'accountId': '123', 'identity': 'player', 'ticket': 'bad\0session'}): + with self.subTest(session=session), tempfile.TemporaryDirectory() as root: + def change(values): + folder, sidecar, _, _, answer = values + sidecar['id'] = 'future_title' + (folder / 'socialclub.dll').write_bytes(b'game-runtime') + answer['session'] = session + result, path, _ = self.prepare(root, change) + self.assertEqual('invalid-sdk-session', result) + self.assertFalse(path.exists()) + + def test_sdk_detection_does_not_follow_external_metadata(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) / 'game' + folder.mkdir() + metadata = Path(root) / 'outside.rgl' + metadata.write_bytes(b'RGLM' + bytes(108)) + (folder / 'title.rgl').symlink_to(metadata) + self.assertFalse(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'})) + + def test_sdk_installer_cannot_escape_its_architecture_folder(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) / 'game' + installer = folder / 'Installers/Social-Club-Setup.exe' + installer.parent.mkdir(parents=True) + installer.write_bytes(b'installer') + listing = type('Listing', (), {'returncode': 0, 'stdout': b'Path = x64/../../outside.dll\nSize = 1\n'})() + with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', return_value=listing): + with self.assertRaises(ValueError): + store.rockstar_runtime(folder, folder / 'Game.exe', str(Path(root) / 'prefix'), 'x64') + self.assertFalse((Path(root) / 'outside.dll').exists()) + + def test_other_titles_can_launch_without_the_classic_pipe_service(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) + sidecar = {'store': 'rockstar', 'id': 'rdr2', 'exe': 'RDR2.exe'} + with patch.object(store, 'find_store_game', return_value=(folder, sidecar)), \ + patch.object(store, 'prepare_rockstar') as prepare, \ + patch.object(store, 'ask') as ask, patch.dict(os.environ, {}, clear=True): + self.assertEqual(store.STORE_GAME, store.main([str(folder / 'RDR2.exe')])) + prepare.assert_not_called() + ask.assert_not_called() + + def test_classic_authentication_failure_still_stops_launch(self): + with tempfile.TemporaryDirectory() as root: + folder = Path(root) + sidecar = {'store': 'rockstar', 'id': 'gtavc', 'exe': 'gta-vc.exe'} + with patch.object(store, 'find_store_game', return_value=(folder, sidecar)), \ + patch.object(store, 'prepare_rockstar', return_value='session-not-owned'), \ + patch.dict(os.environ, {}, clear=True): + self.assertEqual(store.RAN_FAILED, store.main([str(folder / 'gta-vc.exe')])) + def setup_game(self, root): folder = Path(root) / 'game' folder.mkdir()