feat(xbox): install legacy EAppx titles through Windows Update (on main) (#2825)

* feat(xbox): install legacy EAppx titles through Windows Update

A legacy Store title does not ship as MSIXVC. It ships as an encrypted
EAppx bundle, which streaming rejects, so the store could list the game
and never install it.

Accept EAPPX and EAPPXBUNDLE beside MSIXVC, carry the format through the
catalogue, the install record and the cached library, and dispatch
legacy-install for those formats.

Two backend patches do the work:

- droiddeck-legacy-packages.patch lets the plan, license and extract
  verbs handle a legacy package, and expands a bundle in place (nesting
  bounded at three), decrypting each inner EAppx with the same keys.
- droiddeck-legacy-install.patch adds legacy-install: resolve,
  license, download, extract, hoist AppxManifest.xml to the game root.
  Resolution asks the Xbox content service first and Windows Update
  second, because some legacy products return no files from the content
  service at all. The WU endpoint needs no Xbox credential but chains to
  Microsoft's ECC Product Root CA 2018, which Android's CA bundle does
  not carry, so that one public root is pinned for those requests.

The manifest reader accepts AppxManifest.xml as well as
MicrosoftGame.config, since a legacy package carries only the former.

Running it against a real title exposed four things that only show up at
full size:

- A licence names a key by its 16-byte content id, while a bundle header
  names it as a (content id, package id) pair. Reading the 16-byte id
  yields a different pair, so a complete key file reported every key
  missing and no bundle could be opened. Keys are now aligned against
  the header's own ids before the header is judged.
- Windows Update answers with several updates whose PackageContentId
  differs from the bundle's own. Licensing used to take the first and
  fail with content-http 400; every candidate is now tried in order,
  preferring the one the container is named after.
- A container already in .xodus-container is reused rather than fetched
  again, so a failed run does not cost another download of tens of
  gigabytes. The space preflight no longer counts a container twice for
  the same reason.
- A bundle that carries add-on packages unpacks each into its own
  folder, leaving the manifest one level down. Hoisting lifts the
  largest folder that holds a manifest, so the game still lands at the
  root beside its add-ons.

Unpacking now reports bytes written, so the install bubble fills while a
package is decrypted instead of holding a single unchanging word.

* fix(xbox): unpack a legacy package across cores and report the bytes

Unpacking one title ran as a single thread on a saturated core at about
40 MB/s. Files sit at independent offsets, so each worker now opens its own
handle and takes every Nth file, with a 1 MiB read buffer in place of the
8 KiB default that turned one 64 KiB block into eight reads. Measured on the
Forza Horizon 4 bundle, writes went from 40 MB/s to about 200 MB/s.

Two things the first full-size run exposed:

- The container was deleted only after the whole nested tree was unpacked,
  so a title that holds its package as one member held the archive and the
  decrypted copy at once. On this device that runs out of space partway
  through the second stage. The container is now deleted once its members
  are on disk, which frees the archive before they are decrypted.
- A bundle member is written as a single file, so a counter that advances
  when a file finishes stays at zero for the whole of the longest stage.
  The reported figure now also follows the growth of the destination while
  that is the case, and never moves backwards when the container is freed.

Progress is exact during the per-file stage: each file's declared length is
added as it lands, instead of walking the whole destination every tick.

* docs(xbox): record the completed legacy install

The evidence section said a finished legacy install and its decrypted
contents were unverified, because the first run was still unpacking when it
was written. That install has now completed on the same device: the
85,219,173,025-byte container produced 79.3 GB at the game root with
AppxManifest.xml and the package DLLs directly beneath it, and the launcher
lists the title as installed.

It also records what unpacking costs, since that decided the change: one
thread held a core at 100% for about 40 MB/s and four reach about 200 MB/s,
and releasing each container once its members are on disk is what keeps the
peak footprint at one package rather than the archive plus its contents.

The launch is not part of this evidence, and the entry says so.

* fix(xbox): place the 64-bit framework beside a legacy title

A Windows Update framework category lists one package per architecture under
identifier-only names. The first package was unpacked, which on this device was
the x86 build, so a 64-bit title got 32-bit DLLs and every load failed with
STATUS_INVALID_IMAGE_FORMAT. Candidates are unpacked now and only the one whose
manifest declares ProcessorArchitecture="x64" is kept.

The framework folder was also never created, so a finished download failed at the
move with "no such file or directory".

unzip.rs belongs to this patch: legacy-install calls it and the recipe left it out,
so a rebuild from the pinned source could not compile.

* feat(xbox): report a UWP entry point at launch

An unpacked package can name a COM class as its entry point instead of
Windows.FullTrustApplication. That class is a UWP application, which expects the
app model to activate a view; Wine has no host for it, so the launch died inside
the loader with no explanation. The launch now reads the entry point and reports
uwp-entry-point, and full-trust packages are unaffected.

Forza Horizon 4 is such a package: its manifest names Forza.App. Its frameworks
are installed and the loader is clean before that point.

* fix(xbox): report why a launch was refused

A failed prepare replaced the backend message with a fixed sign-in hint, so a title
that was not installed or a runtime that refused all read as a bad account. The
reason is kept, with paths and URLs dropped, and written to the store log.

* fix(adb): dismiss the keyboard on Search and Go

Search and Go were terminal IME actions but were not handled, so focus stayed in
the field and the keyboard covered the results it had just fetched.

* fix(xbox): keep a cache row without a legacy format plain

Decoding added a format key with an empty value to every cached title, so a
library restored from storage no longer matched the one that was saved.

* test(ui): match the manifest message a legacy package reports

The message covers both a MicrosoftGame.config and an AppxManifest, so the
assertion follows the text the content dialog now prints.

* fix(xbox): refuse to start a title that needs the Windows app model

A legacy package that names an entry point other than
Windows.FullTrustApplication is a UWP application. Wine has no app-model
host, so starting its executable crashes inside the loader and the launch
looks like nothing happened. Read the entry point from the manifest the
installer already parses and stop the Play action with a message instead.

Forza Horizon 4 names Forza.App, so it installs and reports as installed
but cannot be started here yet.

* fix(xbox): dispatch on the container format of the chosen package

The catalogue records the format of the first installable desktop package, and
the picker only replaced the content id. An offer that lists MSIXVC and a legacy
container would then hand the legacy id to streaming, or the streamed id to
legacy-install, and the install failed after resolution had succeeded.

The choice now carries its own format and the catalogue value only fills a gap.

* fix(xbox): keep an extraction reason that the sanitizer rewrote

The extraction sanitizer replaces anything outside letters, digits, space, dot,
underscore and dash with a question mark, so a reason such as "(os error 28)"
arrived as "?os error 28?" and the allowlist dropped the line. The failure then
showed only the stage code, with no cause.

Add that replacement character to the class the allowlist accepts.

* fix(xbox): print the reason a launch was refused

The account channel sends a reason with a refusal, and the guest replaced it
with a fixed sign-in message, so a title that was never installed still read as
a bad account. The guest now shows the reason it was given, and a token holding
a path is dropped whole instead of having its slashes removed and its directory
names kept.

* build(xbox): leave RUST_TEST_THREADS unset when the host has no value

The recipe always passed the variable, empty when the host had none, and the
pinned test harness rejects an empty count. On an ARM64 host that runs cargo
test, so the default local build failed before compiling.

* fix(xbox): rebuild the backend patches from the tree that ran

The two patches in this branch were not the ones the verified install ran, and
one of them did not compile. `unzip.rs` inflates deflated entries but the
dependency that provides the inflater was never added, so `prepare.py` produced
a tree that failed at `flate2::read::DeflateDecoder`. Anything else missing fell
into the same gap: the install stage reported no bytes, so the bar held one
value for the whole unpack, and a container a stopped run had finished was
downloaded again.

Rebuilt from the patched source, and fixed the defects a review of the patch
found:

- Unpacking reports bytes again: the workers count each file's declared length,
  and for the single-file bundle member the folder's growth stands in, which is
  what the device run showed.
- A finished container is reused, so a retry after a failure past the download
  does not spend hours fetching it again. The space preflight counts it as
  reclaimable, since the retry truncates it first.
- An install over a folder that already has a manifest replaces the old files
  instead of leaving the new package nested and reporting success. A first
  install still refuses to merge into an existing target.
- The manifest search looks at the depth a nested bundle writes, not only one
  level down.
- `withdraw_libraries` removes only the DLLs `copy_libraries` recorded copying,
  so a framework replacement cannot delete a library the title owns.
- ZIP64 sizes and offsets stay `u64`; truncating them to `u32` read the wrong
  local header past 4 GiB.
- The extraction checks the blockmap length against the footer's before writing,
  which the crate only does when asked.
- The container being unpacked is never treated as a nested member, so
  `extract-eappx title.eappx .` no longer re-enters and deletes its own input.
- `flate2` is declared and the lock is updated.

`prepare.py` reproduces this from a pristine checkout and `cargo test` passes on
it.

* fix(xbox): apply the legacy install patch over the Nexus 0.2.15 backend

* fix(xbox): install only the newest x64 build of a legacy title and size the space check at its real peak

* fix(xbox): install a store package that is a plain archive instead of an XVD

* fix(xbox): refuse a package entry that ends before its recorded size

* fix(xbox): credit only complete staged containers toward the free space a legacy install needs

* fix(xbox): bound each package entry to its data and check ZIP64 decoded sizes

* fix(xbox): refuse duplicate package names and clear an unfinished download before measuring space

* fix(xbox): bound package entries by the next header and stage a plain package until it validates

* fix(xbox): hold the install folder lock through a legacy install

* fix(xbox): fall back to an older build when Microsoft refuses the newest one a license

* fix(xbox): keep the registered device across sign-out

* feat(xbox): explain device-limit and license refusals, with a link to manage devices

* fix(xbox): locate each build only once licensed, roll back a failed package swap, report the final license answer

* fix(xbox): skip trial and preorder packages, read runtime behavior, keep licensing timeouts

* fix(xbox): keep a failed package swap recoverable, size bundles up front, report key-write and framework errors cleanly

* fix(xbox): drop a pending manifest check on any newer launch, keep committed backups out of restores, match the app-model order

* fix(xbox): cancel pending launch checks on a new intent, remember entries a rollback could not remove

* fix(xbox): clear the removal list before a restore moves old files back

---------

Co-authored-by: TimmyCraft <46533729+TimmyTurner51@users.noreply.github.com>
This commit is contained in:
Kurt HimebauchandTimmyCraft authored and GitHub committed 2026-11-18 14:14:26 -05:00
1 parent 7680b4d771
commit a5d8abeab4
31 files changed
+4072 -68

No files matched your search

@@ -963,13 +963,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
val request = gameLaunchRequest.incrementAndGet()
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
return
}
val files = game.gameFiles
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
if (startGame(game, returnHome, onHandled)) onSettled()
return
}
Thread({
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
ui.post {
when {
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
refused -> {
onHandled()
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
onSettled()
}
startGame(game, returnHome, onHandled) -> onSettled()
}
}
}, "xbox-app-model").start()
}
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
onHandled()
if (SessionState.running) {
@@ -1184,19 +1207,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
if (game == null) {
val link = intent
fun consume() {
if (intent !== link || pendingGameLink != id) return
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
link.data = null
link.action = Intent.ACTION_MAIN
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
if (game == null) {
consume()
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
} else if (launchGame(game, returnHome = true)) {
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
} else launchGame(game, returnHome = true, onSettled = ::consume)
}
private fun chooseGameShortcut(game: Library.SteamGame) {
@@ -1914,6 +1937,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
gameLaunchRequest.incrementAndGet()
if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false
pendingGameLink = null
@@ -60,8 +60,7 @@ object StoreLaunchRequests {
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
.getOrElse {
StoresState.logLine("Xbox: launch prepare failed (${it.javaClass.simpleName}: ${it.message})")
val reason = (it as? IllegalStateException)?.message ?: "Xbox account service is unavailable. Sign in again and retry."
JSONObject().put("ok", false).put("reason", reason)
JSONObject().put("ok", false).put("reason", reasonFor(it))
}
"ea-prepare" -> runCatching { lastLaunched = Store.EA to request.optString("id"); com.droiddeck.launcher.stores.ea.EaLaunch.prepare(app, request) }
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
@@ -176,4 +175,21 @@ object StoreLaunchRequests {
Log.w(TAG, "could not answer ${file.name}: ${e.message}")
}
}
/// What the guest prints when a launch is refused.
///
/// The message is the only thing that separates a stale sign-in from a title
/// that is not installed, so it is kept, minus anything that could carry a
/// device path or a token: segments lookng like a path are dropped and the
/// rest is folded to plain text.
internal fun reasonFor(error: Throwable): String {
val text = error.message.orEmpty()
.split(' ')
.filterNot { it.contains('/') || it.startsWith("http") }
.joinToString(" ")
.filter { it.isLetterOrDigit() || it in " .,:;_-()'" }
.trim()
.take(160)
return if (text.isEmpty()) "Xbox account service is unavailable. Sign in again and retry." else text
}
}
@@ -112,11 +112,21 @@ object XboxBackend : StoreBackend {
fun selectPackage(context: Context, choice: org.json.JSONObject) {
val pending = packageChoice ?: return
packageChoice = null
val item = pending.item.copy(extra = pending.item.extra + ("contentId" to choice.getString("contentId")))
val item = pending.item.chosen(choice)
com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, pending.root)
enqueue(context.applicationContext, item, pending.root)
}
/**
* The picker can offer a package in a different container format than the
* catalogue listed, and the installer dispatches on that format, so the
* choice decides it and the catalogue value only fills a missing one.
*/
private fun CatalogItem.chosen(choice: org.json.JSONObject): CatalogItem {
val format = choice.optString("packageFormat").takeIf { it.isNotBlank() } ?: extra["format"].orEmpty()
return copy(extra = extra + mapOf("contentId" to choice.getString("contentId"), "format" to format))
}
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
if (!item.extra["baseId"].isNullOrBlank()) { XboxContent.install(app, item); return }
@@ -128,7 +138,7 @@ object XboxBackend : StoreBackend {
val choices = XboxCatalog.objects(plan.getJSONArray("choices")).filter { it.optBoolean("supported") && it.optString("kind") == "Game" }
check(choices.isNotEmpty()) { "This offer has no supported PC package." }
if (plan.getString("status") == "ready" && choices.size == 1) {
val selected = item.copy(extra = item.extra + ("contentId" to choices.single().getString("contentId")))
val selected = item.chosen(choices.single())
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, selected, root)
enqueue(app, selected, root)
} else StoresState.post { packageChoice = PackageChoice(item, root, choices) }
@@ -18,6 +18,14 @@ internal object XboxCatalog {
"CFQ7TTC10QFD" to "Xbox Game Pass (Starter Edition)",
)
/**
* The formats the installer can put on disk, so the catalogue never lists a
* title it cannot install. `MSIXVC` streams in place; an EAppx container is a
* legacy package that takes `legacy-install` instead.
*/
internal fun installableFormat(format: String): Boolean =
format.equals("MSIXVC", true) || format.equals("EAPPX", true) || format.equals("EAPPXBUNDLE", true)
fun access(json: JSONObject, account: String, market: String, now: Instant = Instant.now(), report: (String) -> Unit = {}): Map<String, String> {
require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market)
val age = java.time.Duration.between(timestamp(json.getString("checkedAt")), now).seconds
@@ -102,11 +110,15 @@ internal object XboxCatalog {
if (!productId.matches(id) || json.optString("ProductType") != "Game") return null
val localized = objects(json.optJSONArray("LocalizedProperties")).firstOrNull() ?: return null
val title = localized.optString("ProductTitle").takeIf { it.isNotBlank() } ?: return null
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities")).flatMap {
objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages"))
}
val packages = objects(json.optJSONArray("DisplaySkuAvailabilities"))
.mapNotNull { it.optJSONObject("Sku")?.optJSONObject("Properties") }
.filter { it.opt("IsTrial") != true && it.opt("IsPreOrder") != true }
.flatMap { objects(it.optJSONArray("Packages")) }
val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
val installable = pc.any { it.optString("PackageFormat").equals("MSIXVC", true) }
val installable = pc.any { installableFormat(it.optString("PackageFormat")) }
// The installer needs the format, not just the fact that one exists: a
// legacy container takes a different subcommand from a streamed package.
val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty()
val streams = cloud?.streams(id, access[id].orEmpty()) == true
if (!installable && !streams) return null
val images = objects(localized.optJSONArray("Images"))
@@ -129,7 +141,8 @@ internal object XboxCatalog {
publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"),
description = localized.optString("ProductDescription"),
sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L,
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams)),
extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable),
"cloud" to flag(streams), "format" to format),
)
}
@@ -40,7 +40,8 @@ internal object XboxContent {
val item = CatalogItem(Store.XBOX, id, localized?.optString("ProductTitle")?.ifBlank { id } ?: id,
imageUrl = base.sidecar.cover, owned = access == "owned", subscription = access == "gamepass",
sizeBytes = pkg.optLong("MaxDownloadSizeInBytes"),
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market, "family" to pkg.getString("PackageFamilyName")))
extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market,
"family" to pkg.getString("PackageFamilyName"), "format" to pkg.optString("PackageFormat")))
Offer(item, File(base.folder, ".xbox-content/$id/.droiddeck-content.json").isFile)
}
StoresState.post { plan = Plan(base, offers) }
@@ -51,7 +52,7 @@ internal object XboxContent {
private fun packages(product: JSONObject?): List<JSONObject> = XboxCatalog.objects(product?.optJSONArray("DisplaySkuAvailabilities"))
.filter { it.optJSONObject("Sku")?.optJSONObject("Properties")?.optBoolean("IsTrial", true) == false }
.flatMap { XboxCatalog.objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages")) }
.filter { pkg -> pkg.optString("PackageFormat") == "MSIXVC" &&
.filter { pkg -> XboxCatalog.installableFormat(pkg.optString("PackageFormat")) &&
XboxCatalog.objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } }
private val parents = java.util.concurrent.ConcurrentHashMap<String, String>()
@@ -249,10 +249,17 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
block(current)
}
fun invalidate(app: Context, revoked: () -> Unit = {}) = storage(app) {
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
StoreAccounts.clear(app, Store.XBOX)
revoked()
try {
java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString())
val device = StoreAccounts.read(app, Store.XBOX)?.optJSONObject("slots")?.opt(DEVICE_SLOT)
val kept = device != null && runCatching { StoreAccounts.write(app, Store.XBOX, deviceOnly(device)) }.isSuccess
if (!kept) StoreAccounts.clear(app, Store.XBOX)
} finally {
revoked()
}
}
internal const val DEVICE_SLOT = "dev_license"
internal fun deviceOnly(device: Any): JSONObject = JSONObject().put("slots", JSONObject().put(DEVICE_SLOT, device))
fun <T> storage(app: Context, block: () -> T): T = synchronized(lock) {
java.io.RandomAccessFile(java.io.File(StoreAccounts.dir(app, Store.XBOX), "account.lock"), "rw").use { file ->
file.channel.lock().use { block() }
@@ -15,6 +15,10 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
private val paused = CountDownLatch(1)
@Volatile private var child: Xodus.Child? = null
@Volatile private var delete = false
/** A legacy container has no pause protocol: the downloader is killed instead. */
private val legacy = item.extra["format"]?.lowercase() in setOf("eappx", "eappxbundle")
/** Release builds hide logcat from adb, so the tail is reported in the failure itself. */
private val errors = java.util.concurrent.ConcurrentLinkedQueue<String>()
override fun run(handle: DownloadQueue.JobHandle): String? {
if (cancelled.get()) return null
@@ -41,13 +45,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
val source = if (content) selected else item.id
val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder)
val selection = if (content) emptyList() else listOf("--selected-content-id", selected)
Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market,
"--progress-json", "--control-stdin") + selection).use { process ->
// Streaming rejects a legacy container outright, so dispatch on the
// format the catalogue recorded rather than fail after a download.
val command = if (legacy) "legacy-install" else "streaming"
Xodus.start(app, if (legacy) {
listOf(command, source, guestFolder, "--market", market, "--progress-json", "--store-id", item.id) + selection
} else {
listOf(command, source, guestFolder, "--market", market, "--progress-json", "--control-stdin") + selection
}).use { process ->
child = process
val rejected = AtomicBoolean(false)
val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED)
val diagnostics = Xodus.diagnostics(process) { line ->
StoresState.logLine("Xbox: $line")
errors.add(line)
while (errors.size > MAX_ERROR_LINES) errors.poll()
if (line.matches(rejectedLine)) rejected.set(true)
}
if (cancelled.get()) process.process.destroy()
@@ -60,7 +72,16 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
when (progress.getString("phase")) {
"complete" -> complete = true
"downloading", "download", "transfer" -> handle.progress(progress.getLong("completedBytes"), progress.optLong("totalBytes"))
"finalizing", "installing" -> handle.stage(DownloadStage.INSTALL)
// Unpacking reports files, not bytes: the frontend hands
// over one container and the backend counts what it has
// written, which is the only measure that moves while a
// single multi-gigabyte member is decrypted.
"installing" -> {
handle.stage(DownloadStage.INSTALL)
val total = progress.optLong("totalBytes")
if (total > 0L) handle.stageProgress(progress.getLong("completedBytes"), total)
}
"finalizing" -> handle.stage(DownloadStage.INSTALL)
else -> handle.stage(DownloadStage.MANIFEST)
}
}
@@ -69,7 +90,14 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
diagnostics.join(2000)
if (cancelled.get()) return null
check(!rejected.get()) { app.getString(com.droiddeck.launcher.R.string.stores_xbox_sign_in_again) }
check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." }
val exit = process.process.exitValue()
if (exit != 0 || !complete) {
val tail = errors.toList().takeLast(MAX_ERROR_LINES)
report(command, source, market, exit, tail)
licenseRefusal(tail)?.let { error(app.getString(it)) }
error("Xbox download did not complete. Resume to retry with fresh licenses." +
tail.takeLast(3).joinToString("") { "\n$it" })
}
}
if (content) {
XboxContent.complete(app, item, folder)
@@ -87,6 +115,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
}
}
/** Writes the backend's words beside the app, where adb can read them. */
private fun report(command: String, source: String, market: String, exit: Int, tail: List<String>) {
val text = buildString {
appendLine("command: $command $source --market $market")
appendLine("legacy: $legacy")
appendLine("exit: $exit")
appendLine("--- stderr (last ${tail.size} lines) ---")
tail.forEach { appendLine(it) }
}
runCatching {
app.getExternalFilesDir(null)?.let { File(it, "xbox-install.log").writeText(text) }
}
StoresState.logLine("Xbox install failed (exit $exit): ${tail.lastOrNull().orEmpty()}")
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
delete = deleteFiles
@@ -98,14 +141,25 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
}
Thread({
runCatching {
process.send(JSONObject().put("schema", 1).put("command", "pause"))
paused.await(3, TimeUnit.SECONDS)
if (!legacy) {
process.send(JSONObject().put("schema", 1).put("command", "pause"))
paused.await(3, TimeUnit.SECONDS)
}
process.close()
}
process.close()
}, "xbox-download-stop").start()
}
companion object {
private const val MAX_ERROR_LINES = 40
const val DEVICES_URL = "https://account.microsoft.com/devices/content"
private const val LICENSE_DIAGNOSTIC = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 "
internal fun licenseRefusal(tail: List<String>): Int? = when (tail.lastOrNull { it.startsWith(LICENSE_DIAGNOSTIC) }
?.removePrefix(LICENSE_DIAGNOSTIC)?.substringBefore(' ')) {
"content-device-limit" -> com.droiddeck.launcher.R.string.stores_xbox_device_group_full
"content-device-name" -> com.droiddeck.launcher.R.string.stores_xbox_license_refused
else -> null
}
internal fun executable(folder: File): String = XboxManifest.executable(folder)
}
}
@@ -29,7 +29,10 @@ internal object XboxLibraryCache {
.put("image", game.imageUrl).put("poster", game.tallImageUrl).put("description", game.description)
.put("developer", game.developer).put("publisher", game.publisher).put("size", game.sizeBytes)
.put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none")
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty()))
.put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty())
// The installer picks its subcommand from this; without it a
// cached legacy game would fall back to streaming.
.put("format", game.extra["format"].orEmpty()))
}).toString()
internal fun decode(text: String?, account: String, market: String, now: Long = System.currentTimeMillis()): Snapshot? = runCatching {
@@ -46,13 +49,18 @@ internal object XboxLibraryCache {
val title = row.getString("title")
val access = row.getString("access")
val cloudId = row.optString("cloudId").takeIf { it.matches(Regex("[A-Z0-9]{12}")) }.orEmpty()
val format = row.optString("format").takeIf { XboxCatalog.installableFormat(it) }.orEmpty()
require(id.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && access in setOf("owned", "gamepass"))
// A title with no legacy format keeps the plain shape a cache written
// before formats existed has, so a restart round-trips unchanged.
val extra = linkedMapOf("market" to market, "access" to access,
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId)
if (format.isNotEmpty()) extra["format"] = format
CatalogItem(Store.XBOX, id, title, row.optString("image").takeIf { it.isNotEmpty() },
tallImageUrl = row.optString("poster").takeIf { it.isNotEmpty() },
description = row.optString("description"), developer = row.optString("developer"), publisher = row.optString("publisher"),
sizeBytes = row.optLong("size"), owned = access == "owned", subscription = access == "gamepass",
storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access,
"pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId))
storeUrl = "https://www.xbox.com/games/store/$id", extra = extra)
}
require(games.map { it.id }.distinct().size == games.size)
Snapshot(games, savedAt)
@@ -5,12 +5,25 @@ import org.xmlpull.v1.XmlPullParser
internal object XboxManifest {
data class Info(val storeId: String, val name: String, val publisher: String, val version: String,
val dependency: String, val related: List<String>, val executables: List<String>)
val dependency: String, val related: List<String>, val executables: List<String>, val entryPoint: String,
val runtimeBehavior: String = "")
/** A GameCore title describes itself with the config; a legacy package does not. */
private const val GAME_CONFIG = "MicrosoftGame.config"
private const val APPX_MANIFEST = "AppxManifest.xml"
private const val FULL_TRUST = "Windows.FullTrustApplication"
private const val APP_MODEL = "windowsApp"
private val directBehaviors = setOf("packagedClassicApp", "win32App")
fun read(folder: File): Info {
val manifests = folder.listFiles().orEmpty().filter { it.name.equals("MicrosoftGame.config", true) && it.isFile }
require(manifests.size == 1) { "Missing or ambiguous MicrosoftGame.config." }
val manifest = manifests.single()
// Both manifests are read the same way: an identity, an executable path and,
// for a Store package, related content.
val files = folder.listFiles().orEmpty()
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
val manifest = (config + legacy).single()
val rootTag = if (config.isEmpty()) "Package" else "Game"
require(manifest.length() <= 1_048_576)
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
val identities = ArrayList<List<String>>()
@@ -18,7 +31,11 @@ internal object XboxManifest {
val dependencies = ArrayList<String>()
val related = ArrayList<String>()
val entries = ArrayList<String>()
val entryPoints = ArrayList<String>()
val behaviors = ArrayList<String>()
fun attribute(name: String) = parser.getAttributeValue(null, name).orEmpty()
fun localAttribute(name: String) = (0 until parser.attributeCount)
.firstOrNull { parser.getAttributeName(it).substringAfterLast(':') == name }?.let(parser::getAttributeValue).orEmpty()
var root = false
var elements = 0
manifest.inputStream().use { input ->
@@ -29,16 +46,22 @@ internal object XboxManifest {
XmlPullParser.DOCDECL -> error("Xbox game manifests cannot contain a DTD.")
XmlPullParser.START_TAG -> {
require(++elements <= 10_000 && parser.depth <= 64) { "Xbox game manifest is too complex." }
if (parser.depth == 1) { require(!root && parser.name == "Game"); root = true }
if (parser.depth == 1) { require(!root && parser.name == rootTag); root = true }
when (parser.name) {
"Identity" -> identities.add(listOf(attribute("Name"), attribute("Publisher"), attribute("Version")))
"StoreId" -> storeIds.add(parser.nextText().trim())
"MainPackageDependency" -> dependencies.add(attribute("Name"))
"RelatedProduct" -> related.add(parser.nextText().trim())
"Executable" -> {
val path = attribute("Name").replace('\\', '/')
// Both carry the launch path: an attribute on the config's
// Executable, or on the AppxManifest's Application.
"Executable", "Application" -> {
val path = attribute("Name").ifEmpty { attribute("Executable") }.replace('\\', '/')
if (path.endsWith(".exe", true) && attribute("TargetDeviceFamily") in listOf("", "PC", "Windows.Desktop") &&
!attribute("IsDevOnly").equals("true", true)) entries.add(path)
if (parser.name == "Application") {
attribute("EntryPoint").takeIf { it.isNotEmpty() }?.let(entryPoints::add)
localAttribute("RuntimeBehavior").takeIf { it.isNotEmpty() }?.let(behaviors::add)
}
}
}
}
@@ -48,9 +71,25 @@ internal object XboxManifest {
require(root && identities.size <= 1 && storeIds.size <= 1 && dependencies.size <= 1) { "Invalid Xbox game manifest." }
val ids = related.distinct()
require(ids.size <= 128 && ids.all { it.matches(Regex("[A-Z0-9]{12}")) })
val entry = entryPoints.distinct()
val behavior = behaviors.distinct()
require(entry.size <= 1 && behavior.size <= 1) { "Invalid Xbox game manifest." }
val identity = identities.singleOrNull()
return Info(storeIds.singleOrNull().orEmpty(), identity?.get(0).orEmpty(), identity?.get(1).orEmpty(), identity?.get(2).orEmpty(),
dependencies.singleOrNull().orEmpty(), ids, entries)
dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty())
}
/**
* A full trust package starts its executable directly. Anything else is activated
* through the Windows app model, which this runtime has no host for, so starting
* the executable would only crash.
*/
fun needsAppModel(folder: File): Boolean {
val info = runCatching { read(folder) }.getOrNull() ?: return false
val behavior = info.runtimeBehavior
if (behavior.equals(APP_MODEL, true)) return true
if (directBehaviors.any { it.equals(behavior, true) }) return false
return info.entryPoint.isNotEmpty() && !info.entryPoint.equals(FULL_TRUST, true)
}
fun executable(folder: File): String {
@@ -155,10 +155,12 @@ internal object Xodus {
const val SIGN_IN_REJECTED = "Microsoft content licensing rejected sign-in \\(HTTP 401\\)\\. Sign in again in Settings\\."
internal val reportable = Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3}|NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 [a-z0-9-]{1,48}( [0-9]{1,6})?|NEXUS_LEGACY_INSTALL_DETAIL_V1 [A-Za-z0-9 .,;-]{1,220}|NEXUS_EXTRACT_DIAGNOSTIC_V1 [a-z-]{1,48}|NEXUS_EXTRACT_DETAIL_V1 [A-Za-z0-9 ._?-]{1,220}|$SIGN_IN_REJECTED")
fun diagnostics(child: Child, report: (String) -> Unit = { com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $it") }): Thread = Thread({
runCatching {
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{3}|$SIGN_IN_REJECTED")))
if (line.matches(reportable))
report(line)
} }
}
@@ -54,6 +54,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.focus.focusProperties
@@ -112,7 +113,8 @@ internal fun Actions(content: @Composable () -> Unit) = FlowRow(
) { content() }
@Composable
internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) }
internal fun ActionChip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) =
Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok, fraction, key) }
internal val Shape16 = RoundedCornerShape(16.dp)
@@ -139,13 +141,32 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un
}
@Composable
internal fun Chip(t: String, ok: Boolean) {
internal fun Chip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Text(
t, fontSize = 12.sp, color = if (ok) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp),
)
val shape = RoundedCornerShape(99.dp)
val ink = if (ok) pal.good else colors.onSurfaceVariant
Box(Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, shape)) {
if (fraction != null) ChipFill(fraction, key, pal.signal.copy(alpha = 0.3f))
Text(
t, fontSize = 12.sp, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp),
)
}
}
@Composable
internal fun androidx.compose.foundation.layout.BoxScope.ChipFill(fraction: Float, key: Any?, color: Color) {
androidx.compose.runtime.key(key) {
val target = fraction.coerceIn(0f, 1f)
val shown = remember { Animatable(target) }
LaunchedEffect(target) { shown.animateTo(target, androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing)) }
Box(
Modifier.matchParentSize().drawBehind {
drawRect(color, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height))
},
)
}
}
@Composable
@@ -458,7 +458,7 @@ internal fun GameActions(
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
ActionChip(downloadLabel(download), ok = false)
ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
@@ -473,7 +473,7 @@ internal fun GameActions(
}
}
download != null -> {
ActionChip(downloadLabel(download), ok = false)
ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
@@ -68,7 +68,7 @@ internal fun GogMaintenanceActions(game: InstalledStoreGame) {
}
}
if (active) {
ActionChip(downloadLabel(download!!), ok = false)
ActionChip(downloadLabel(download!!), ok = false, fraction = download!!.stageFraction.takeIf { it >= 0f }, key = download!!.stage)
if (download.interruptible) {
SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) {
if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key)
@@ -834,7 +834,9 @@ internal fun ArtCard(
},
)
badge?.invoke(this)
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) { StateChip(chip, ChipTone.BUSY, small = true) }
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.stageFraction?.takeIf { it >= 0f }, key = download?.stage)
}
val showName = LibraryDisplay.title || hot
val showDetail = LibraryDisplay.size || hot
if (showName || showDetail) Column(
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
@@ -73,7 +74,7 @@ internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifi
}
@Composable
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) {
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false, fraction: Float? = null, key: Any? = null) {
val pal = LocalPalette.current
val (fill, ink) = when (tone) {
ChipTone.OK -> Color(0xFF16321F) to pal.good
@@ -82,10 +83,14 @@ internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) {
ChipTone.DEAL -> Color(0xFF1E3A1A) to Color(0xFF9BE27A)
ChipTone.PLAIN -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
}
Text(
text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(fill).padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),
)
val shape = RoundedCornerShape(6.dp)
Box(Modifier.clip(shape).background(fill)) {
if (fraction != null) ChipFill(fraction, key, ink.copy(alpha = 0.26f))
Text(
text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1,
modifier = Modifier.padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp),
)
}
}
internal enum class ChipTone { OK, BUSY, WARN, DEAL, PLAIN }
@@ -61,6 +61,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -371,6 +372,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
DownloadState.FAILED -> {
if (d.store == Store.XBOX && d.error == stringResource(R.string.stores_xbox_device_group_full)) {
RoundAction(Icons.AutoMirrored.Filled.OpenInNew, stringResource(R.string.stores_xbox_manage_devices)) {
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.xbox.XboxInstaller.DEVICES_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
}
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
@@ -453,6 +453,20 @@ internal fun AdbTextField(
onDoneLatest.value?.invoke()
true
}
// Search and Go are terminal: leaving them unhandled
// keeps focus in the field, so the keyboard would stay
// up over the results it was used to find.
imeAction in setOf(ImeAction.Search, ImeAction.Go) &&
(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> {
onDoneLatest.value?.invoke()
post {
clearFocus()
(context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
as? android.view.inputmethod.InputMethodManager)
?.hideSoftInputFromWindow(windowToken, 0)
}
true
}
else -> false
}
}
+4
View File
@@ -1771,6 +1771,7 @@
<string name="game_link_missing">This game is no longer in your DroidDeck library.</string>
<string name="game_link_session_busy">Stop the current session before launching a Steam game.</string>
<string name="game_link_failed">Could not send the game to Steam. Try launching it again.</string>
<string name="game_needs_app_model">%1$s is a UWP app. This runtime has no Windows app-model host to start it.</string>
<string name="setup_retry_removal">Retry removal</string>
<string name="runtime_removing">Removing</string>
<string name="runtime_removal_incomplete">Removal incomplete</string>
@@ -2992,6 +2993,9 @@
<string name="stores_login_close">Close</string>
<string name="stores_login_retry">Try again</string>
<string name="stores_login_finishing">Finishing sign-in…</string>
<string name="stores_xbox_device_group_full">This Microsoft account is at its device limit. Remove an old device under Manage devices, then resume.</string>
<string name="stores_xbox_manage_devices">Manage devices</string>
<string name="stores_xbox_license_refused">Microsoft does not license any available version of this game to this device.</string>
<string name="stores_xbox_sign_in_again">Microsoft rejected the Xbox sign-in. Sign out of Xbox in Stores, sign in again, then resume.</string>
<string name="stores_login_error_network">The sign-in page could not be loaded: %1$s</string>
<string name="stores_login_error_idp_blocked">This provider refuses to sign in from an embedded page. Sign in with your store password instead.</string>
@@ -184,6 +184,23 @@ class XboxCatalogTest {
assertFalse(XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), null)!!.xboxCloud)
}
@Test fun trialAndPreorderSkusDoNotMakeAGamePcInstallable() {
fun sku(format: String, vararg flags: String) = JSONObject().put("Sku", JSONObject().put("Properties", JSONObject().apply {
flags.forEach { put(it, true) }
put("Packages", JSONArray().put(JSONObject().put("PackageFormat", format).put("MaxDownloadSizeInBytes", 7L)
.put("PlatformDependencies", JSONArray().put(JSONObject().put("PlatformName", "Windows.Desktop")))))
}))
fun offer(vararg skus: JSONObject) = JSONObject().put("ProductId", game).put("ProductType", "Game")
.put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A Game")))
.put("DisplaySkuAvailabilities", JSONArray(skus.toList()))
assertNull(XboxCatalog.product(offer(sku("EAPPX", "IsTrial")), mapOf(game to "owned")))
assertNull(XboxCatalog.product(offer(sku("MSIXVC", "IsPreOrder")), mapOf(game to "owned")))
val streamed = XboxCatalog.product(offer(sku("EAPPX", "IsTrial")), mapOf(game to "gamepass"), XboxCloudCatalog(setOf(game), emptySet()))!!
assertFalse(streamed.xboxPc); assertTrue(streamed.xboxCloud); assertEquals("", streamed.extra["format"]); assertEquals(0L, streamed.sizeBytes)
val retail = XboxCatalog.product(offer(sku("MSIXVC", "IsTrial"), sku("EAPPX")), mapOf(game to "owned"))!!
assertTrue(retail.xboxPc); assertEquals("EAPPX", retail.extra["format"]); assertEquals(7L, retail.sizeBytes)
}
@Test fun aCloudOnlyEditionFoldsIntoThePcCardWithTheSameTitle() {
val cloud = XboxCloudCatalog(gamePass = setOf(parent), all = emptySet())
val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!!
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.stores.xbox
import com.droiddeck.launcher.stores.CredentialCipher
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import org.json.JSONArray
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], application = android.app.Application::class)
class XboxDeviceKeptTest {
private val app get() = RuntimeEnvironment.getApplication()
private val key = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES")
@Before fun setUp() { StoreAccounts.keys = CredentialCipher.KeyProvider { key }; StoreAccounts.keystoreFailed = false }
@After fun tearDown() {
StoreAccounts.clear(app, Store.XBOX)
StoreAccounts.keys = CredentialCipher.Keystore; StoreAccounts.keystoreFailed = false
}
@Test fun signingOutKeepsOnlyTheRegisteredDevice() {
val device = JSONArray(listOf(1, 2, 3))
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player")
.put("slots", JSONObject().put(XboxCredentials.DEVICE_SLOT, device).put("user-tokens", JSONArray(listOf(9)))))
XboxCredentials.invalidate(app)
val record = StoreAccounts.read(app, Store.XBOX)!!
assertNull(StoreAccounts.signedInAs(app, Store.XBOX))
val slots = record.getJSONObject("slots")
assertEquals(listOf(XboxCredentials.DEVICE_SLOT), slots.keys().asSequence().toList())
assertEquals(device.toString(), slots.getJSONArray(XboxCredentials.DEVICE_SLOT).toString())
}
@Test fun aFailedDeviceRewriteStillSignsOutAndRevokes() {
var sealing = true
StoreAccounts.keys = object : CredentialCipher.KeyProvider {
override fun key() = if (sealing) key else throw java.security.KeyStoreException("sealing refused")
override fun existing() = key
}
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player")
.put("slots", JSONObject().put(XboxCredentials.DEVICE_SLOT, JSONArray(listOf(1)))))
sealing = false
var revoked = false
XboxCredentials.invalidate(app) { revoked = true }
assertTrue(revoked)
assertTrue(StoreAccounts.keystoreFailed)
assertNull(StoreAccounts.read(app, Store.XBOX))
assertNull(StoreAccounts.signedInAs(app, Store.XBOX))
}
@Test fun signingOutWithoutADeviceLeavesNoRecord() {
StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player").put("slots", JSONObject()))
XboxCredentials.invalidate(app)
assertNull(StoreAccounts.read(app, Store.XBOX))
}
}
@@ -0,0 +1,22 @@
package com.droiddeck.launcher.stores.xbox
import com.droiddeck.launcher.R
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class XboxInstallerRefusalTest {
private val refused = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-name 400"
private val full = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200"
private val granted = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-parsed 200"
@Test fun theLastLicensingAnswerDecidesTheMessage() {
assertEquals(R.string.stores_xbox_license_refused, XboxInstaller.licenseRefusal(listOf(refused, "NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 license-failed")))
assertEquals(R.string.stores_xbox_device_group_full, XboxInstaller.licenseRefusal(listOf(full)))
}
@Test fun aRefusalAnOlderBuildRecoveredFromIsNotReported() {
assertNull(XboxInstaller.licenseRefusal(listOf(refused, "NEXUS_LEGACY_INSTALL_DETAIL_V1 newest build has no license for this device, trying an older build", granted, "NEXUS_TRANSFER_DIAGNOSTIC_V1 transfer-short 0")))
assertNull(XboxInstaller.licenseRefusal(listOf("NEXUS_TRANSFER_DIAGNOSTIC_V1 transfer-short 0")))
}
}
@@ -47,6 +47,75 @@ class XboxManifestTest {
assertEquals(listOf("Retail.exe"), info.executables)
assertEquals("Retail.exe", XboxManifest.executable(root))
}
@Test fun legacyPackageManifestNamesItsExecutableTheSameWay() {
// A legacy EAppx package carries AppxManifest.xml and has no config; the
// launcher must still find the identity and the launch path, or an install
// that completed cannot be registered or started.
val root = temporary.newFolder()
java.io.File(root, "ForzaHorizon4.exe").writeText("encrypted")
java.io.File(root, "AppxManifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10">
<Identity Name="Microsoft.SunriseBaseGame" Publisher="CN=Microsoft Corporation" Version="2023.1122.1704.2"/>
<Applications><Application Id="Game" Executable="ForzaHorizon4.exe" EntryPoint="Windows.FullTrustApplication">
<uap:VisualElements DisplayName="Forza Horizon 4"/></Application></Applications></Package>""")
val info = XboxManifest.read(root)
assertEquals("Microsoft.SunriseBaseGame", info.name)
assertEquals("2023.1122.1704.2", info.version)
assertEquals(listOf("ForzaHorizon4.exe"), info.executables)
assertEquals("Windows.FullTrustApplication", info.entryPoint)
assertEquals("ForzaHorizon4.exe", XboxManifest.executable(root))
assertFalse(XboxManifest.needsAppModel(root))
}
@Test fun uwpEntryPointNeedsAnAppModelHost() {
// Forza Horizon 4's Store build declares Forza.App, so its executable is a view
// provider rather than a program: starting it directly only crashes.
val root = temporary.newFolder()
java.io.File(root, "ForzaHorizon4.exe").writeText("encrypted")
java.io.File(root, "AppxManifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">
<Identity Name="Microsoft.SunriseBaseGame" Publisher="CN=Microsoft Corporation" Version="1.478.564.2"/>
<Applications><Application Id="SunriseReleaseFinal" Executable="ForzaHorizon4.exe" EntryPoint="Forza.App"/></Applications></Package>""")
assertEquals("Forza.App", XboxManifest.read(root).entryPoint)
assertTrue(XboxManifest.needsAppModel(root))
}
private fun legacy(application: String): java.io.File {
val root = temporary.newFolder()
java.io.File(root, "Game.exe").writeText("encrypted")
java.io.File(root, "AppxManifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10">
<Identity Name="Test.Game" Publisher="CN=Test" Version="1.0.0.0"/>
<Applications>$application</Applications></Package>""")
return root
}
@Test fun windowsAppRuntimeBehaviorNeedsAnAppModelWithoutAnEntryPoint() {
val root = legacy("""<Application Id="Game" Executable="Game.exe" uap10:RuntimeBehavior="windowsApp"/>""")
assertEquals("windowsApp", XboxManifest.read(root).runtimeBehavior)
assertEquals("", XboxManifest.read(root).entryPoint)
assertTrue(XboxManifest.needsAppModel(root))
}
@Test fun classicRuntimeBehaviorsStartTheExecutableDirectly() {
for (behavior in listOf("packagedClassicApp", "win32App")) {
val root = legacy("""<Application Id="Game" Executable="Game.exe" uap10:RuntimeBehavior="$behavior"/>""")
assertEquals(behavior, XboxManifest.read(root).runtimeBehavior)
assertFalse(behavior, XboxManifest.needsAppModel(root))
val declared = legacy("""<Application Id="Game" Executable="Game.exe" EntryPoint="Game.App" uap10:RuntimeBehavior="$behavior"/>""")
assertFalse(behavior, XboxManifest.needsAppModel(declared))
}
}
@Test fun anEntryPointStillDecidesWithoutARuntimeBehavior() {
assertTrue(XboxManifest.needsAppModel(legacy("""<Application Id="Game" Executable="Game.exe" EntryPoint="Game.App"/>""")))
assertFalse(XboxManifest.needsAppModel(legacy("""<Application Id="Game" Executable="Game.exe"/>""")))
}
@Test fun aTitleWithoutALegacyManifestNeverNeedsAnAppModel() {
val root = temporary.newFolder()
java.io.File(root, "Game.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList><Executable Name=\"Game.exe\"/></ExecutableList></Game>")
assertEquals("", XboxManifest.read(root).entryPoint)
assertFalse(XboxManifest.needsAppModel(root))
assertFalse(XboxManifest.needsAppModel(temporary.newFolder()))
}
@Test fun signInBridgeRejectsUntrustedAndNonHttpsOrigins() {
assertTrue(XboxLoginActivity.trusted("https://login.live.com/ppsecure/InlineLogin.srf"))
for (url in listOf("http://login.live.com/", "https://login.live.com.evil.test/", "https://evil.test@login.live.com/", "https://login.live.com:8443/"))
@@ -1,6 +1,8 @@
package com.droiddeck.launcher.stores.xbox
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -16,4 +18,12 @@ class XodusDiagnosticsTest {
assertFalse("Microsoft content licensing rejected sign-in (HTTP 403). Sign in again in Settings.".matches(rejected))
assertFalse("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-http 401".matches(rejected))
}
@Test fun aLicensingTimeoutAfterARefusalReachesTheTailAndIsReported() {
val stderr = listOf("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-name 400", "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-timeout 0")
val tail = stderr.filter { it.matches(Xodus.reportable) }
assertEquals(stderr, tail)
assertNull(XboxInstaller.licenseRefusal(tail))
assertFalse("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-timeout 1000".matches(Xodus.reportable))
}
}
@@ -64,7 +64,7 @@ class StoreRestorationTest {
}
compose.mainClock.advanceTimeBy(100)
compose.onNodeWithText(ctx.getString(R.string.stores_xbox_content_title)).assertExists()
compose.onNodeWithText("Missing or ambiguous MicrosoftGame.config.").assertExists()
compose.onNodeWithText("Missing or ambiguous game manifest.").assertExists()
compose.onNodeWithText(ctx.getString(android.R.string.ok)).performClick()
compose.runOnIdle { assertNull(XboxContent.plan) }
}
+85 -2
View File
@@ -1,7 +1,8 @@
# Xbox / PC Game Pass on Thor
This integrates PC Microsoft Store MSIXVC packages,
not Xbox console emulation or UWP/APPX packages.
This integrates PC Microsoft Store packages, both streamed MSIXVC packages and the legacy
EAppx containers older desktop titles still ship as. It is not Xbox console emulation and
does not run UWP titles in a packaged-app host.
## Testing on Thor
@@ -69,14 +70,96 @@ not Xbox console emulation or UWP/APPX packages.
cleanup must preserve installed game files reached through view symlinks.
10. Sign out from Xbox. Installed files should remain, account library data should
clear, and Play/download licensing should require sign-in again.
11. Install a legacy title that ships an EAppx bundle, such as Forza Horizon 4
(`9PNQKHFLD2WQ`). The download shows as a percentage rather than a streamed
install, Stop kills it rather than pausing, and a finished install registers
the executable named by `AppxManifest.xml`. Expect tens of gigabytes: check
free space first, since the preflight needs the download plus two copies of
the largest container.
Do not uninstall DroidDeck or clear application data to troubleshoot this build.
The signed APK is installed in place to retain existing Steam and store data.
## Legacy EAppx packages
A title that predates MSIXVC ships as an EAppx bundle: an archive of Appx packages, encrypted,
with an `AppxManifest.xml` per package instead of `MicrosoftGame.config`. `streaming` rejects the
format, so the installer reads the format the catalogue recorded and runs `xodus-cli
legacy-install` instead. `MSIXVC`, `EAPPX` and `EAPPXBUNDLE` are the only formats listed for a
`Windows.Desktop` package; the format is carried into the install record so a later update or
resume dispatches the same way.
The verb resolves, licenses, downloads, extracts, then hoists the manifest to the game root:
- **Resolution.** The Xbox content service is asked first. Some legacy bundles it answers with no
files at all; Windows Update (`fe3cr.delivery.mp.microsoft.com`, SOAP `GetCookie`,
`SyncUpdates`, `GetExtendedUpdateInfo2`) is asked next through the title's `WuCategoryId` and
returns the full bundle with a time-signed CDN URL. That endpoint is a public Windows Update
service and needs no Xbox credential, but it presents a certificate chained to Microsoft's ECC
Product Root CA 2018, which Android's CA bundle does not carry, so `wu-root.pem` is pinned for
those requests only. A WU result is reduced to its `.eappx`/`.eappxbundle` files: the plain
`.appx` framework packages delivered beside it (VCLibs) and the differential `.cab` metadata are
not containers this path can unpack.
- **Licensing.** The existing `license` verb runs before the first byte is fetched and must return
content keys; no keys means no install.
- **Space.** Free space is checked up front against the download plus two copies of the largest
container, because a bundle is expanded in place. Each container is removed as soon as it is
unpacked, so the peak is the archive plus its contents rather than both plus the earlier
archives. A container a stopped attempt finished is counted as reclaimable, since the retry
truncates it before writing.
- **Pause and resume.** A legacy download has no control channel: Stop kills the downloader, and
the next attempt starts an unfinished container again from byte zero, while a container that
completed is kept and reused. Nothing is checkpointed inside a container.
- **Frameworks.** An installed package gets its `PackageDependency` frameworks from the package
graph; an unpacked folder has none, so the loader fails with `0xc0000135` on
`VCRUNTIME140_APP.dll` and friends. The verb fetches each declared framework from its Windows
Update category and copies its libraries beside the title, which is where the loader looks. A
category lists one package per architecture under identifier-only names, so each is unpacked
until one declares `ProcessorArchitecture="x64"`; taking the first one puts 32-bit DLLs into a
64-bit folder and every load fails with `0xc000007b`. Only the libraries that copy put there
are withdrawn when a framework is replaced, so a title's own DLL of the same name survives.
- **Updates.** Installing over a folder that already holds a manifest lifts the new package over
the old files; on a first install an existing target is an error rather than a merge.
- **Failure detail.** A release build hides logcat from adb, so a failed install writes the
backend's stderr tail to `files/xbox-install.log` beside the app and repeats the last lines in
the failure message.
## Evidence and limits
Verified during development:
- The catalogue lists a legacy title beside the MSIXVC ones, and its detail page
offers Install with the recorded format.
- Resolution of a real legacy PC bundle on Thor without any Xbox token: Forza
Horizon 4 (`9PNQKHFLD2WQ`) through Windows Update as
`Microsoft.SunriseBaseGame_2023.1122.1704.2_neutral_~_8wekyb3d8bbwe.eappxbundle`,
85,219,173,025 bytes, with a signed CDN URL. The Xbox content service returns
no files for that product, which is why the WU route exists.
- `AppxManifest.xml` identity and executable extraction, and its rejection rules,
are unit-tested against a manifest of that shape.
- An install of that bundle completed on Thor. The 85,219,173,025-byte container
produced 79.3 GB at the game root with `AppxManifest.xml` and the package DLLs
directly beneath it, which the launcher reports as installed.
- Unpacking that bundle ran at about 40 MB/s on one thread and about 200 MB/s
across four, measured as growth of the destination folder. The container is
deleted once its members are on disk, so the peak footprint is one package at
a time rather than the archive plus everything under it. The install bubble
advances through this stage: each file's declared length is counted as it is
written, and a bundle member is one file, so the folder's growth covers it.
- A launch of this title through Xodus/ARM64 Proton reaches the loader with every declared
framework in place, then fails inside Wine: its manifest names `EntryPoint="Forza.App"`, a UWP
application that expects the app model to activate a view, which Wine has no host for. The
Play action reads that entry point from `AppxManifest.xml` and refuses the launch with a
message, and a launch that does reach the runtime reports `uwp-entry-point` rather than dying
silently. A package naming `Windows.FullTrustApplication` starts as an ordinary Win32
executable instead.
- Activation itself is not the missing piece. A DLL registered under
`HKLM\Software\Microsoft\WindowsRuntime\ActivatableClassId\Windows.ApplicationModel.Core.CoreApplication`
is loaded by `combase.dll`, and its `DllGetActivationFactory` is called for that class. Such a
title still stops earlier: `GetCurrentPackageFullName` and `GetCurrentPackageFamilyName` are
Wine stubs, so a package has no identity, and an activation factory alone cannot supply the
`IFrameworkViewSource`/`CoreWindow` host the view asks for.
- Native AArch64 CLI execution on Thor's existing Linux runtime.
- Abstract-socket credential transport with a synthetic account on Thor; this
does not establish a real Microsoft sign-in.
+20 -2
View File
@@ -108,11 +108,29 @@ lets ARM64EC Wine load the AMD64 modules through its normal native DLL path.
Only each Xbox game's prefix receives these Windows modules. Existing
Steam games and other store prefixes retain their selected runtimes.
`droiddeck-legacy-packages.patch` lets the plan, license and extract verbs handle a legacy
package. A bundle is expanded in place, nesting is bounded at three, and each inner EAppx
container is decrypted with the same content keys; inner files without an EAppx header are left
as extracted. `streaming` still serves MSIXVC only.
`droiddeck-legacy-install.patch` adds `xodus-cli legacy-install`: resolve, license, download,
extract, hoist. Resolution asks the Xbox content service first and Windows Update
(`fe3cr.delivery.mp.microsoft.com`, SOAP) second, because some legacy products return no files
from the content service. The WU endpoint needs no Xbox credential but chains to Microsoft's ECC
Product Root CA 2018, which Android's CA bundle does not carry, so that one public root is
pinned in `wu-root.pem` for these requests. Only `.eappx`/`.eappxbundle` files from a WU result
are kept; the `.appx` framework packages and `.cab` metadata beside them are dropped. Licensing
runs before the first byte and must return content keys. Free space is checked against the
download plus two copies of the largest container, and each container is deleted once unpacked.
The download has no control channel: cancelling kills it and the next attempt starts that
container from zero.
Cloud saves and in-game identity use the reused XGameRuntime/service interfaces;
those are game-dependent. Entitlements distinguish purchases from Game Pass
access, and the backend performs a fresh license check for downloads and launch.
The store lists PC MSIXVC games only. It does not emulate Xbox consoles or add
support for UWP/APPX packages. Update / verify refreshes an installed package through the normal licensed
The store lists PC packages it can install: streamed MSIXVC, and the legacy EAppx bundles older
desktop titles still ship as. It does not emulate Xbox consoles or host UWP titles in a
packaged-app host. Update / verify refreshes an installed package through the normal licensed
streaming path. Manage content resolves manifest-related licensed PC DLC into
separate content roots and checks its parent identity after download. These
flows still require game/account validation; runtime API presence does not
+5 -2
View File
@@ -32,7 +32,10 @@ else
'"$build"
fi
mkdir -p "$cache"
threads=()
[[ -n "${RUST_TEST_THREADS:-}" ]] && threads=(-e RUST_TEST_THREADS="$RUST_TEST_THREADS")
docker run --rm --platform "$platform" -v "$repo:/src" -v "$cache:/work" -w /src \
-e CARGO_HOME=/work/cargo -e RUSTUP_HOME=/work/rustup -e XBOX_BUILD_DIR=/work/build "$image" \
-e CARGO_HOME=/work/cargo -e RUSTUP_HOME=/work/rustup -e XBOX_BUILD_DIR=/work/build \
${threads[@]+"${threads[@]}"} "$image" \
bash -lc "set -euo pipefail
trap 'chown -R $(id -u):$(id -g) /work /src/app/src/main/assets/linuxfs 2>/dev/null || true' EXIT$build"
trap 'chown -R $(id -u):$(id -g) /work /src/app/src/main/assets/linuxfs /src/app/build 2>/dev/null || true' EXIT$build"
File diff suppressed because it is too large. Load diff
+570
View File
@@ -0,0 +1,570 @@
diff --git a/crates/xodus-cli/src/commands/extract_eappx.rs b/crates/xodus-cli/src/commands/extract_eappx.rs
index c8d5ebf..5ea43da 100644
--- a/crates/xodus-cli/src/commands/extract_eappx.rs
+++ b/crates/xodus-cli/src/commands/extract_eappx.rs
@@ -1,80 +1,416 @@
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::process::ExitCode;
use eappx::EAppxFile;
-use eappx::keys::KeyCollection;
+use eappx::keys::{KeyCollection, KeyId};
+
+/// A bundle header names each content key as a pair of GUIDs, `(content id,
+/// package id)`, while the licence names the same key by its 16-byte content id
+/// alone. The crate reads a 16-byte id as `(static prefix, content id)`, so the
+/// two never compare equal and a complete key file looks incomplete. Pair every
+/// key the header asks for with the licence entry that carries its content id.
+const SHORT_KEY_PREFIX: uuid::Uuid = uuid::uuid!("BB1755DB-5052-4B10-B2AB-F3ABF5CA5B41");
+
+fn align_keys(keys: &mut KeyCollection, needed: &[KeyId]) {
+ for id in needed {
+ if keys.keys.contains_key(id) {
+ continue;
+ }
+ let KeyId::Guid((content, _)) = id else { continue };
+ let carried = keys.keys.get(&KeyId::Guid((SHORT_KEY_PREFIX, *content))).cloned();
+ if let Some(data) = carried {
+ keys.add(id.clone(), data);
+ }
+ }
+}
+
+/// A bundle can hold another bundle, but nesting is bounded so a malformed
+/// archive cannot drive unbounded recursion.
+const MAX_BUNDLE_DEPTH: usize = 3;
/// Extracts a locally-stored EAppx/EMSIX package.
///
-/// This is intentionally local-only for now: no store lookup or download.
-/// See issue #91 - the initial goal is understanding/unpacking the format,
-/// not full download integration, which can build on this once it lands.
+/// A bundle is extracted in place, then each inner package that is itself an
+/// EAppx container is decrypted with the same content keys. Inner files that
+/// are plain ZIP-based packages are left as extracted: they carry no EAppx
+/// header, so there is nothing to decrypt.
pub async fn run(path: String, destination: String, key_file: Option<String>) -> ExitCode {
- let infile = PathBuf::from(&path);
- let outdir = PathBuf::from(&destination);
-
- let file = match std::fs::File::open(&infile) {
- Ok(f) => f,
- Err(e) => {
- eprintln!("Failed to open {:?}: {e}", infile);
- return ExitCode::FAILURE;
- }
- };
- let mut reader = std::io::BufReader::new(file);
+ run_metered(path, destination, key_file, None).await
+}
- let mut eappx = match EAppxFile::from_stream(&mut reader) {
- Ok(e) => e,
- Err(e) => {
- eprintln!("Failed to parse EAppx header: {e}");
- return ExitCode::FAILURE;
- }
- };
+/// Where the extraction of the current package begins and how much it will write.
+///
+/// A bundle's inner package is one enormous member, so counting finished files
+/// leaves the bar frozen for the whole of it. The counter is exact: it advances by
+/// each file's declared length as that file is written.
+#[derive(Default)]
+pub struct Meter {
+ /// Bytes written by the package being unpacked now.
+ pub written: std::sync::atomic::AtomicU64,
+ /// Bytes written by packages that already finished.
+ pub banked: std::sync::atomic::AtomicU64,
+ /// Bytes the package being unpacked now will write in total.
+ pub total: std::sync::atomic::AtomicU64,
+ turn: std::sync::Mutex<()>,
+}
- println!("{eappx}");
+impl Meter {
+ /// Bytes written and bytes to write, read as one consistent pair.
+ pub fn snapshot(&self) -> (u64, u64) {
+ use std::sync::atomic::Ordering::Relaxed;
+ let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let banked = self.banked.load(Relaxed);
+ let total = self.total.load(Relaxed);
+ (banked + self.written.load(Relaxed).min(total), banked + total)
+ }
+ pub fn done(&self) -> u64 {
+ self.snapshot().0
+ }
+
+ pub fn all(&self) -> u64 {
+ self.snapshot().1
+ }
+
+ /// Closes the package being unpacked and opens the next one.
+ fn roll(&self, total: u64) {
+ use std::sync::atomic::Ordering::Relaxed;
+ let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ self.banked.fetch_add(self.total.load(Relaxed), Relaxed);
+ self.written.store(0, Relaxed);
+ self.total.store(total, Relaxed);
+ }
+}
+
+/// Extracts a package, publishing the size of the work in progress to `meter`.
+///
+/// `release` deletes the container once its members are on disk. A bundle of a
+/// full title is tens of gigabytes, and holding it while the members are
+/// decrypted can fill the device partway through.
+pub async fn run_metered(
+ path: String,
+ destination: String,
+ key_file: Option<String>,
+ meter: Option<&Meter>,
+) -> ExitCode {
+ run_blocking(path, destination, key_file, meter, false)
+}
+
+/// The extraction itself, without the async wrapper.
+///
+/// Callers that keep reporting while it works run this on a blocking thread,
+/// because it never yields: decryption and inflation are plain synchronous work.
+pub fn run_blocking(
+ path: String,
+ destination: String,
+ key_file: Option<String>,
+ meter: Option<&Meter>,
+ release: bool,
+) -> ExitCode {
let mut key_collection = KeyCollection::default();
if let Some(key_file) = key_file {
let mut keyfile = match std::fs::File::open(&key_file) {
Ok(f) => f,
Err(e) => {
- eprintln!("Failed to open key file {:?}: {e}", key_file);
- return ExitCode::FAILURE;
+ return report_failure(
+ &Failure::new("key-file-open", &key_file, &e.to_string()),
+ ExitCode::FAILURE,
+ );
}
};
match KeyCollection::from_reader(&mut keyfile) {
Ok(loaded) => key_collection.extend(loaded.keys),
Err(e) => {
- eprintln!("Failed to parse key file: {e}");
- return ExitCode::FAILURE;
+ return report_failure(
+ &Failure::new("key-file-parse", &key_file, &e.to_string()),
+ ExitCode::FAILURE,
+ );
}
}
}
- if !key_collection.has_required_keys(&eappx.header.key_ids) {
- eprintln!("Missing one or more required content keys for this package");
- return ExitCode::FAILURE;
+ match derive(
+ Path::new(&path),
+ Path::new(&destination),
+ &key_collection,
+ 0,
+ meter,
+ release,
+ ) {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(failure) => report_failure(&failure, ExitCode::FAILURE),
}
+}
+
+/// A failure the launcher can name without printing a device path.
+///
+/// The app only forwards stderr lines that are on a known allowlist, so the two
+/// lines below are what make a stopped install say why it stopped. The reason is
+/// reduced to letters, digits and a few punctuation marks, which keeps a path or
+/// a key out of the log while still naming the cause.
+struct Failure {
+ code: &'static str,
+ name: String,
+ reason: String,
+}
- if let Err(e) = eappx.load_keys(&key_collection) {
- eprintln!("Failed to load keys: {e}");
- return ExitCode::FAILURE;
+impl Failure {
+ fn new(code: &'static str, name: &str, reason: &str) -> Self {
+ Self {
+ code,
+ name: sanitize(name, 60),
+ reason: sanitize(reason, 120),
+ }
}
- if !outdir.exists() {
- if let Err(e) = std::fs::create_dir_all(&outdir) {
- eprintln!("Failed to create output directory {:?}: {e}", outdir);
- return ExitCode::FAILURE;
+ fn at(code: &'static str, path: &Path, reason: &str) -> Self {
+ let name = path.file_name().map(|name| name.to_string_lossy().into_owned());
+ Self::new(code, &name.unwrap_or_default(), reason)
+ }
+}
+
+fn sanitize(text: &str, limit: usize) -> String {
+ text.chars()
+ .map(|c| if c.is_ascii_alphanumeric() || matches!(c, ' ' | '.' | '_' | '-') { c } else { '?' })
+ .take(limit)
+ .collect::<String>()
+ .trim()
+ .to_string()
+}
+
+fn report_failure(failure: &Failure, code: ExitCode) -> ExitCode {
+ eprintln!("NEXUS_EXTRACT_DIAGNOSTIC_V1 {}", failure.code);
+ eprintln!("NEXUS_EXTRACT_DETAIL_V1 {} {}", failure.name, failure.reason);
+ eprintln!("Extraction failed: {}: {}: {}", failure.code, failure.name, failure.reason);
+ code
+}
+
+// EAppxMagic is EXPH (single), EXSH and EXBH (bundle). Anything else is not an
+// EAppx container, so a bundle's plain ZIP members are not recursed into.
+fn is_eappx(path: &Path) -> bool {
+ use std::io::Read;
+ let Ok(mut file) = std::fs::File::open(path) else { return false };
+ let mut magic = [0u8; 4];
+ if file.read_exact(&mut magic).is_err() {
+ return false;
+ }
+ matches!(&magic, b"EXPH" | b"EXSH" | b"EXBH")
+}
+
+fn derive(
+ infile: &Path,
+ outdir: &Path,
+ keys: &KeyCollection,
+ depth: usize,
+ meter: Option<&Meter>,
+ release: bool,
+) -> Result<(), Failure> {
+ let file = std::fs::File::open(infile)
+ .map_err(|e| Failure::at("open", infile, &e.to_string()))?;
+ let mut reader = std::io::BufReader::new(file);
+
+ let mut eappx = EAppxFile::from_stream(&mut reader)
+ .map_err(|e| Failure::at("header", infile, &e.to_string()))?;
+
+ println!("{eappx}");
+
+ // The licence and the header name the same key differently, so the set is
+ // rebuilt per package and reconciled before the header is judged.
+ let mut required = KeyCollection::new(&keys.keys);
+ align_keys(&mut required, &eappx.header.key_ids);
+
+ if !required.has_required_keys(&eappx.header.key_ids) {
+ // The count is the useful part: a license that carries one key cannot
+ // open a bundle whose members each declare their own.
+ return Err(Failure::new(
+ "missing-keys",
+ &infile.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(),
+ &format!("{} of {} content keys present", required.keys.len(), eappx.header.key_ids.len()),
+ ));
+ }
+
+ eappx
+ .load_keys(&required)
+ .map_err(|e| Failure::at("load-keys", infile, &e.to_string()))?;
+
+ std::fs::create_dir_all(outdir)
+ .map_err(|e| Failure::at("create-dir", outdir, &e.to_string()))?;
+
+ unpack(infile, &eappx, &mut reader, outdir, meter, release)?;
+ // The handle must close before a released container gives its space back.
+ drop(reader);
+
+ println!("Extracted {}", infile.file_name().unwrap_or_default().to_string_lossy());
+
+ let mut nested: Vec<PathBuf> = std::fs::read_dir(outdir)
+ .map_err(|e| Failure::at("list", outdir, &e.to_string()))?
+ .filter_map(|entry| entry.ok().map(|entry| entry.path()))
+ // The container being unpacked may itself sit in the destination, which is
+ // what `extract-eappx ./title.eappx .` asks for. Re-entering it would
+ // recurse into the same bytes and then delete the caller's file.
+ .filter(|path| std::fs::canonicalize(path).ok() != std::fs::canonicalize(infile).ok())
+ .filter(|path| path.is_file() && is_eappx(path))
+ .collect();
+ nested.sort();
+
+ if nested.is_empty() {
+ return Ok(());
+ }
+ if depth >= MAX_BUNDLE_DEPTH {
+ return Err(Failure::at("nesting", infile, "bundle nesting exceeds the limit"));
+ }
+
+ for child in nested {
+ let name = child
+ .file_stem()
+ .map(|name| name.to_string_lossy().into_owned())
+ .ok_or_else(|| Failure::at("no-name", &child, "package without a usable name"))?;
+ derive(&child, &outdir.join(&name), keys, depth + 1, meter, release)?;
+ // The member's bytes are no longer needed once its contents are on disk.
+ // A bundle of a full title holds tens of gigabytes, and keeping every
+ // member beside the decrypted copy doubles what the install occupies.
+ std::fs::remove_file(&child).ok();
+ }
+
+ Ok(())
+}
+
+/// Bytes currently on disk under `dir`.
+///
+/// A bundle member is written as one file, so a per-file counter says nothing
+/// until it is finished. Measuring the destination catches the bytes as they
+/// land, whatever is writing them.
+pub fn tree_size(dir: &Path) -> u64 {
+ let mut total = 0;
+ let Ok(entries) = std::fs::read_dir(dir) else { return 0 };
+ for entry in entries.flatten() {
+ let Ok(kind) = entry.file_type() else { continue };
+ if kind.is_dir() {
+ total += tree_size(&entry.path());
+ } else if let Ok(meta) = entry.metadata() {
+ total += meta.len();
}
}
+ total
+}
+
+/// Buffer sizes for each worker's own handle on the container.
+///
+/// The crate's default 8 KiB reader turns one 64 KiB block into eight system
+/// calls, and a full title is millions of blocks.
+const READ_BUFFER: usize = 1 << 20;
+
+/// Workers used to unpack one package.
+///
+/// Files sit at independent offsets, so each worker opens its own handle and
+/// takes every Nth file. Decryption and inflation are both CPU-bound and one
+/// core was saturated, so this is where the headroom is. The limit is the
+/// device's write speed, which is reached a few workers in.
+fn workers() -> usize {
+ std::thread::available_parallelism()
+ .map(|count| count.get())
+ .unwrap_or(1)
+ .clamp(1, 4)
+}
- match eappx.extract(&mut reader, &outdir) {
- Ok(_) => {
- println!("Extracted {:?} to {:?}", infile, outdir);
- ExitCode::SUCCESS
+/// Writes a package's files, publishing what is left to write.
+///
+/// This is the crate's own `extract`, split across workers and reported as it
+/// goes. The blockmap already totals every file's uncompressed length, so the
+/// end point is known before the first byte is written.
+fn unpack(
+ infile: &Path,
+ eappx: &EAppxFile,
+ reader: &mut std::io::BufReader<std::fs::File>,
+ outdir: &Path,
+ meter: Option<&Meter>,
+ release: bool,
+) -> Result<(), Failure> {
+ let total: u64 = eappx.blockmap.files.iter().map(|package| package.size).sum();
+ if let Some(meter) = meter {
+ meter.roll(total);
+ }
+
+ eappx
+ .extract_footprint_files(reader, outdir)
+ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
+
+ if eappx.header.is_bundle() {
+ eappx
+ .extract_blockmap_files(reader, outdir)
+ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
+ eappx
+ .extract_bundle_files(reader, outdir)
+ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
+ if release {
+ std::fs::remove_file(infile).ok();
}
- Err(e) => {
- eprintln!("Extraction failed: {e}");
- ExitCode::FAILURE
+ return Ok(());
+ }
+
+ let count = workers().min(eappx.blockmap.files.len().max(1));
+ let failure = std::sync::Mutex::new(None::<String>);
+ std::thread::scope(|scope| {
+ for shard in 0..count {
+ let failure = &failure;
+ scope.spawn(move || {
+ let Ok(handle) = std::fs::File::open(infile) else {
+ if let Ok(mut slot) = failure.lock() {
+ *slot = Some("a worker could not reopen the package".to_string());
+ }
+ return;
+ };
+ let mut stream = std::io::BufReader::with_capacity(READ_BUFFER, handle);
+ for (index, package) in eappx.blockmap.files.iter().enumerate() {
+ if index % count != shard {
+ continue;
+ }
+ if failure.lock().map(|slot| slot.is_some()).unwrap_or(true) {
+ return;
+ }
+ let Some(footer) = eappx.find_footer_for_file(package.id()) else {
+ if let Ok(mut slot) = failure.lock() {
+ *slot = Some("the blockmap names a file the package does not hold".to_string());
+ }
+ return;
+ };
+ let mut info = eappx::FileInfo::from(footer);
+ // The crate checks these only when asked, but filling them
+ // keeps the per-file path identical to its own extraction.
+ info.filehash = package.filehash_bytes();
+ info.block_hashes = Some(package.block_hashes());
+ // The blockmap's length and the footer's must agree, or the
+ // file written would be silently short.
+ if info.uncompressed_length != package.size {
+ if let Ok(mut slot) = failure.lock() {
+ *slot = Some("a package entry disagrees with its blockmap about its size".to_string());
+ }
+ return;
+ }
+ if let Err(error) = eappx.save_file_to_fs(&mut stream, info, outdir, &package.name) {
+ if let Ok(mut slot) = failure.lock() {
+ *slot = Some(error.to_string());
+ }
+ return;
+ }
+ if let Some(meter) = meter {
+ meter
+ .written
+ .fetch_add(package.size, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+ });
}
+ });
+
+ if let Some(reason) = failure.into_inner().unwrap_or(None) {
+ return Err(Failure::at("extract", infile, &reason));
+ }
+
+ if release {
+ // The files are on disk; the container is not read again unless the
+ // install is retried from scratch.
+ std::fs::remove_file(infile).ok();
}
+ Ok(())
}
diff --git a/crates/xodus-cli/src/commands/license.rs b/crates/xodus-cli/src/commands/license.rs
index 4540549..b9fd91c 100644
--- a/crates/xodus-cli/src/commands/license.rs
+++ b/crates/xodus-cli/src/commands/license.rs
@@ -1,5 +1,6 @@
use std::process::ExitCode;
+use base64::{Engine, engine::general_purpose::STANDARD};
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use xodus::tokens::TokenManager;
@@ -21,6 +22,10 @@ pub async fn run(
let (key, game_splicense) = license.unwrap();
tokio::fs::create_dir_all(&ciks).await.unwrap();
+ // eappx-rs reads a text [Keys] file with base64 Key IDs, while the .cik
+ // format below is the binary form other tools expect. Write both so the
+ // same license dump serves either extractor.
+ let mut eappx_keys = String::from("[Keys]\n");
for (uuid, content_key) in game_splicense.content_keys {
let unpacked = content_key.unpack(&key).expect("failed to unpack");
let mut file = OpenOptions::new()
@@ -33,7 +38,21 @@ pub async fn run(
file.write_all(&uuid_buf).await.unwrap();
file.write_all(&*unpacked).await.unwrap();
file.flush().await.unwrap();
+ eappx_keys.push_str(&format!(
+ "\"{}\" \"{}\"\n",
+ STANDARD.encode(uuid_buf),
+ STANDARD.encode(&*unpacked),
+ ));
}
+ let mut keys_file = OpenOptions::new()
+ .create(true)
+ .write(true)
+ .truncate(true)
+ .open(format!("{ciks}/eappx-keys.txt"))
+ .await
+ .unwrap();
+ keys_file.write_all(eappx_keys.as_bytes()).await.unwrap();
+ keys_file.flush().await.unwrap();
ExitCode::SUCCESS
}
diff --git a/crates/xodus-cli/src/commands/streaming.rs b/crates/xodus-cli/src/commands/streaming.rs
index 66e4135..a0136f8 100644
--- a/crates/xodus-cli/src/commands/streaming.rs
+++ b/crates/xodus-cli/src/commands/streaming.rs
@@ -160,7 +160,19 @@ pub async fn run(
.iter()
.find(|p| p.file_name.ends_with(".msixvc"))
else {
- eprintln!("No .msixvc file found");
+ // Legacy EAppx titles carry no .msixvc member: their bytes come
+ // from the download command and are unpacked by extract-eappx.
+ let legacy = package.package_files.iter().any(|p| {
+ let name = p.file_name.to_ascii_lowercase();
+ name.ends_with(".eappx") || name.ends_with(".eappxbundle")
+ });
+ if legacy {
+ eprintln!(
+ "This title uses a legacy EAppx package; use download then extract-eappx for this title"
+ );
+ } else {
+ eprintln!("No .msixvc file found");
+ }
return ExitCode::FAILURE;
};
let Some(root) = file.cdn_root_paths.first() else {
diff --git a/crates/xodus-cli/src/package_plan.rs b/crates/xodus-cli/src/package_plan.rs
index 6187d56..f784c07 100644
--- a/crates/xodus-cli/src/package_plan.rs
+++ b/crates/xodus-cli/src/package_plan.rs
@@ -93,7 +93,11 @@ fn inspect(product: &Value, id: &str) -> Result<(Vec<Choice>, Vec<String>), Stri
.filter(|name| package_family(name)).map(str::to_string);
let durable = kind == "Durable" && parent_product_id.is_some() && main_package_family_name.is_some()
&& list(package, "Architectures").iter().any(|arch| arch.as_str() == Some("x64"));
- let supported = desktop && format == "MSIXVC"
+ // Legacy Store packages are installable on PC too. FH4 and other
+ // pre-MSIXVC titles ship as EAPPXBUNDLE/EAPPX and were refused here,
+ // which made the Store offer look unavailable even when owned.
+ let supported = desktop
+ && matches!(format.as_str(), "MSIXVC" | "EAPPX" | "EAPPXBUNDLE")
&& (kind == "Game" || kind == "GameAddOn" || durable)
&& properties["IsTrial"].as_bool() != Some(true)
&& properties["IsPreOrder"].as_bool() != Some(true);
@@ -326,6 +330,17 @@ mod tests {
assert!(plan.select(None).is_err()); assert!(plan.select(Some(CID)).is_ok());
assert_eq!(plan.json("9CCCCCCCCCCC","US")["status"],"choice");
}
+ #[test] fn legacy_desktop_package_formats_are_installable() {
+ for format in ["EAPPX", "EAPPXBUNDLE"] {
+ let plan = from_products(ROOT,&BTreeMap::from([(ROOT.into(),package(ROOT,"Windows.Desktop",format))])).unwrap();
+ assert_eq!(plan.select(None).unwrap(), CID, "{format}");
+ assert_eq!(plan.json(ROOT,"US")["status"], "ready", "{format}");
+ }
+ // A console legacy package is still not installable on PC.
+ let plan = from_products(ROOT,&BTreeMap::from([(ROOT.into(),package(ROOT,"Xbox.One","EAPPXBUNDLE"))])).unwrap();
+ assert!(plan.select(None).is_err());
+ assert!(plan.select(Some(CID)).is_err());
+ }
#[test] fn durable_entitlement_back_references_do_not_form_bundle_cycles() {
const DURABLE: &str = "9DDDDDDDDDDD";
let durable = json!({"ProductId":DURABLE,"ProductType":"Durable",
+124
View File
@@ -0,0 +1,124 @@
diff --git a/crates/xodus-cli/src/commands/run.rs b/crates/xodus-cli/src/commands/run.rs
index 44ea870..1d8e218 100644
--- a/crates/xodus-cli/src/commands/run.rs
+++ b/crates/xodus-cli/src/commands/run.rs
@@ -20,6 +20,7 @@ use tokio::process::Command;
use xodus::models::secrets::Token;
use xodus::tokens::TokenManager;
+use crate::commands::legacy_install::{dependencies, ensure_frameworks};
use crate::license::get_license;
const PLAYFAB_RELYING_PARTY: &str = "http://playfab.xboxlive.com/";
@@ -135,6 +136,98 @@ fn wine_exit_code(status: std::process::ExitStatus) -> u8 {
status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(1)) as u8
}
+/// Start a title that was unpacked into its install folder.
+///
+/// There is no container to read a content key for or to build a launch view
+/// from, so the named executable runs as it lies, with the PlayFab header the
+/// game signs in with.
+async fn run_unpacked(
+ client: &reqwest::Client,
+ tokens: &TokenManager,
+ folder: &Path,
+ wine: String,
+ exe: Option<&str>,
+ materialize_chain: bool,
+ market: Option<String>,
+) -> ExitCode {
+ let Some(name) = exe.filter(|name| !name.is_empty()) else {
+ eprintln!("no executable was named for the unpacked folder {}", folder.display());
+ return ExitCode::FAILURE;
+ };
+ let image = folder.join(name);
+ if !image.is_file() {
+ eprintln!("{} is not in the unpacked folder {}", name, folder.display());
+ return ExitCode::FAILURE;
+ }
+ // A packaged Win32 program starts like any executable. A UWP application
+ // expects the app model to activate a view first, and this runtime has none,
+ // so say so when the launch dies instead of leaving a loader failure.
+ if let Some(entry) = crate::commands::legacy_install::entry_point(folder) {
+ if !entry.eq_ignore_ascii_case("Windows.FullTrustApplication") {
+ eprintln!("NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 uwp-entry-point");
+ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 {name} is activated by {entry}, a UWP app model this runtime has no host for");
+ }
+ }
+ // An unpacked title gets no package graph, so the frameworks its manifest
+ // declares are fetched here the first time it launches.
+ let declared = dependencies(folder);
+ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 unpacked launch {name} with {} declared frameworks", declared.len());
+ if !declared.is_empty() {
+ if let Ok(delivery) = crate::commands::store_delivery::client() {
+ let region = market.unwrap_or_else(|| "US".into()).to_uppercase();
+ if let Err(error) = ensure_frameworks(&delivery, folder, &region).await {
+ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 framework install failed {}", crate::commands::legacy_install::plain_for_log(&error));
+ }
+ }
+ }
+ let playfab = playfab_auth_header(client, tokens).await;
+
+ if wine == "droiddeck:prepare" {
+ use std::io::Write;
+ if !materialize_chain {
+ return ExitCode::FAILURE;
+ }
+ let ready = serde_json::json!({
+ "exe": image,
+ "playfab": playfab,
+ });
+ println!("DROIDDECK_LAUNCH_V1 {}", ready);
+ let _ = std::io::stdout().flush();
+ let mut release = String::new();
+ let _ = std::io::stdin().read_line(&mut release);
+ return ExitCode::SUCCESS;
+ }
+
+ let mut command = Command::new(&wine);
+ command.arg(&image);
+ match playfab {
+ Some(header) => {
+ command.env("XODUS_XSTS_PLAYFAB", header);
+ }
+ None => eprintln!("could not authorise a PlayFab token; in-game sign-in may fail"),
+ }
+
+ let mut wn = match command.spawn() {
+ Ok(child) => child,
+ Err(err) => {
+ eprintln!("failed to start Wine: {}", err);
+ return ExitCode::FAILURE;
+ }
+ };
+
+ let pid = wn.id().unwrap_or(0);
+
+ if pid > 0 {
+ let _ = ctrlc::set_handler(move || {
+ let _ = kill(Pid::from_raw(pid as i32), Signal::SIGINT);
+ });
+ }
+
+ let status = wn.wait().await.unwrap();
+
+ ExitCode::from(wine_exit_code(status))
+}
+
// Real files in a full launch view must not be redirected back into memfds.
// Keep source mappings and encrypted DLL mappings; no title/EAC special case.
fn launch_file_maps(
@@ -542,6 +635,12 @@ pub async fn run(
let out_absolute = std::fs::canonicalize(out).unwrap();
let final_path = out.join(".xodus-streaming.msixvc");
+ // A legacy package unpacks where it was installed and keeps no streaming
+ // container, so the folder itself is what gets launched.
+ if !final_path.is_file() {
+ return run_unpacked(client, tokens, &out_absolute, wine, exe.as_deref(), materialize_chain, market).await;
+ }
+
let mut file = OpenOptions::new()
.read(true)
.open(final_path.to_owned())
+2 -1
View File
@@ -10,7 +10,8 @@ cache = Path(sys.argv[1]).resolve()
lock = json.loads((recipe / 'backend.lock.json').read_text())
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch',
'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch',
'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch']
'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch',
'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch']
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest()
source = cache / ('source-' + identity[:16])
if not (source / '.prepared').is_file():