mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Restrict Xbox credential IPC and address launch review findings (#1164)
* Restrict Xbox credentials to host backends and lease game launches * Verify mapped PRoot backend images and retry lease heartbeat timeouts * Bound Xbox backend shutdown and isolate service socket lifetimes * Keep unique Xbox service sockets within Unix address limits * Own licensed launch directories and recover abandoned views safely * Serialize Xbox account revocation with sign-in commits and launch authorization
This commit is contained in:
1 parent
a63f3b1fbc
commit
7eae6ca3e7
27 files changed
+834
-85
No files matched your search
@@ -83,6 +83,10 @@ object StoreLaunch {
|
||||
}
|
||||
|
||||
fun prepare(context: Context, store: Store, id: String, onReady: () -> Unit) {
|
||||
if (store == Store.XBOX && !com.droiddeck.launcher.stores.xbox.XboxRuntime.authorize(context, id)) {
|
||||
StoresState.problems[Store.XBOX] = "Xbox account is unavailable. Sign in again and retry."
|
||||
return
|
||||
}
|
||||
if (store != Store.EPIC) { onReady(); return }
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
|
||||
@@ -37,7 +37,7 @@ object StoreLaunchRequests {
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
Thread({ com.droiddeck.launcher.stores.xbox.XboxRuntime.stop() }, "xbox-service-stop").start()
|
||||
com.droiddeck.launcher.stores.xbox.XboxRuntime.stop()
|
||||
synchronized(lock) {
|
||||
observer?.stopWatching()
|
||||
observer = null
|
||||
@@ -52,9 +52,10 @@ object StoreLaunchRequests {
|
||||
}
|
||||
val reply = when (request.optString("op")) {
|
||||
"xbox-released" -> {
|
||||
com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("id"))
|
||||
com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("lease"))
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
"xbox-renew" -> JSONObject().put("ok", com.droiddeck.launcher.stores.xbox.XboxRuntime.renew(app, request.optString("id"), request.optString("lease")))
|
||||
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
|
||||
.getOrElse { JSONObject().put("ok", false).put("reason", "Xbox account service is unavailable. Sign in again and retry.") }
|
||||
"gog-achievements" -> runCatching { com.droiddeck.launcher.stores.gog.GogComet.prepare(app, request.optString("id")) }
|
||||
|
||||
@@ -168,10 +168,12 @@ object StoresState {
|
||||
fun signOut(context: Context, store: Store) {
|
||||
val app = context.applicationContext
|
||||
background("stores-signout") {
|
||||
backends[store]?.signOut(app)
|
||||
val backend = backends[store]
|
||||
backend?.signOut(app)
|
||||
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
|
||||
else StoreAccounts.clear(app, store)
|
||||
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
|
||||
main.post {
|
||||
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
|
||||
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store)
|
||||
logLine("${store.label}: signed out")
|
||||
}
|
||||
|
||||
@@ -19,12 +19,15 @@ object XboxBackend : StoreBackend {
|
||||
context.startActivity(Intent(context, XboxLoginActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
@Synchronized override fun signOut(context: Context) {
|
||||
generation++
|
||||
XboxCredentials.invalidate(context)
|
||||
XboxLibraryCache.clear(context)
|
||||
XboxRuntime.stop()
|
||||
access = emptyMap()
|
||||
override fun signOut(context: Context) {
|
||||
XboxCredentials.invalidate(context) {
|
||||
synchronized(this) {
|
||||
generation++
|
||||
access = emptyMap()
|
||||
}
|
||||
XboxLibraryCache.clear(context)
|
||||
XboxRuntime.stop()
|
||||
}
|
||||
StoresState.post { packageChoice = null; StoresState.shelves.remove(store); StoresState.found.remove(store) }
|
||||
}
|
||||
|
||||
|
||||
@@ -28,15 +28,16 @@ internal object XboxCatalog {
|
||||
(row.isNull("satisfiedByProductId") || productId.matches(row.optString("satisfiedByProductId")))
|
||||
if (!valid || id in rows || id in blocked) { blocked.add(id); rows.remove(id) } else rows[id] = row
|
||||
}
|
||||
fun active(row: JSONObject) = row.getString("status") == "Active" && !row.getBoolean("isTrial") && !row.getBoolean("special") &&
|
||||
row.getString("sharingSource") == "None" && timestamp(row.getString("endDate")).isAfter(now)
|
||||
fun kind(id: String, visited: Set<String> = emptySet()): String? {
|
||||
if (id in blocked || id in visited || visited.size >= 16) return null
|
||||
val row = rows[id] ?: return null
|
||||
if (row.getString("status") != "Active" || row.getBoolean("isTrial") || row.getBoolean("special") ||
|
||||
row.getString("sharingSource") != "None" || !timestamp(row.getString("endDate")).isAfter(now)) return null
|
||||
if (!active(row)) return null
|
||||
val parent = row.optString("satisfiedByProductId").takeUnless { it.isBlank() || it == "null" }
|
||||
if (parent == null) return if (id in plans) null else "owned"
|
||||
if (parent in blocked) return null
|
||||
if (parent in plans) return "gamepass"
|
||||
if (parent in plans) return if (rows[parent]?.let(::active) == true) "gamepass" else null
|
||||
return kind(parent, visited + id)
|
||||
}
|
||||
return rows.keys.mapNotNull { id -> kind(id)?.let { id to it } }.toMap()
|
||||
|
||||
@@ -10,11 +10,68 @@ import java.io.Closeable
|
||||
import java.io.InputStream
|
||||
import java.util.UUID
|
||||
|
||||
internal class XboxCredentials(private val app: Context) : Closeable {
|
||||
internal class XboxCredentials(private val app: Context, expectedGeneration: String? = null) : Closeable {
|
||||
val name = "droiddeck-xbox-${UUID.randomUUID()}"
|
||||
private val generation = storage(app) { epoch(app) }
|
||||
private val generation = lifecycle(app, expectedGeneration) { it }
|
||||
private val server = LocalServerSocket(name)
|
||||
@Volatile private var closed = false
|
||||
private val bound = java.util.concurrent.CountDownLatch(1)
|
||||
private var backend: Process? = null
|
||||
private var binaryHash = byteArrayOf()
|
||||
private lateinit var binary: java.io.File
|
||||
private val peers = java.util.concurrent.ConcurrentHashMap<Int, String>()
|
||||
|
||||
fun bind(process: Process, file: java.io.File, digest: ByteArray) {
|
||||
backend = process
|
||||
binary = file.canonicalFile
|
||||
binaryHash = digest
|
||||
bound.countDown()
|
||||
}
|
||||
|
||||
private fun rejected(reason: String): Boolean {
|
||||
android.util.Log.w("XboxCredentials", "Rejected credential peer: $reason")
|
||||
return false
|
||||
}
|
||||
|
||||
private fun authorized(pid: Int): Boolean {
|
||||
if (!bound.await(5, java.util.concurrent.TimeUnit.SECONDS) || closed) return rejected("unbound")
|
||||
val process = backend ?: return rejected("missing-child")
|
||||
if (!process.isAlive) return rejected("exited-child")
|
||||
val root = com.droiddeck.launcher.core.HostProcess.pidOf(process)
|
||||
if (root <= 0 || pid <= 0) return rejected("missing-process-id")
|
||||
val identity = identity(pid, root) ?: return rejected("foreign-backend")
|
||||
if (peers[pid] == identity) return true
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256")
|
||||
binary.inputStream().use { input ->
|
||||
val buffer = ByteArray(65536)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
||||
}
|
||||
if (!java.security.MessageDigest.isEqual(binaryHash, digest.digest())) return rejected("different-executable")
|
||||
peers[pid] = identity
|
||||
return true
|
||||
}
|
||||
|
||||
private fun identity(pid: Int, root: Int): String? {
|
||||
if (root <= 0 || pid <= 0) return null
|
||||
val status = java.io.File("/proc/$pid/status").readLines()
|
||||
val tracer = status.first { it.startsWith("TracerPid:") }.substringAfter(':').trim().toInt()
|
||||
val tracerGroup = java.io.File("/proc/$tracer/status").readLines()
|
||||
.first { it.startsWith("Tgid:") }.substringAfter(':').trim().toInt()
|
||||
if (tracerGroup != root) return null
|
||||
val executable = android.system.Os.stat(binary.path)
|
||||
if (!mapsBackend(java.io.File("/proc/$pid/maps").readText(), binary.path, executable.st_ino))
|
||||
return null
|
||||
return java.io.File("/proc/$pid/stat").readText().substringAfterLast(") ").split(' ')[19] + ":${executable.st_dev}:${executable.st_ino}"
|
||||
}
|
||||
|
||||
fun signalBackend(signal: Int) {
|
||||
val process = backend ?: return
|
||||
if (!process.isAlive) return
|
||||
val root = com.droiddeck.launcher.core.HostProcess.pidOf(process)
|
||||
peers.forEach { (pid, expected) -> runCatching {
|
||||
if (identity(pid, root) == expected) android.system.Os.kill(pid, signal)
|
||||
} }
|
||||
}
|
||||
|
||||
init {
|
||||
Thread({
|
||||
@@ -23,12 +80,17 @@ internal class XboxCredentials(private val app: Context) : Closeable {
|
||||
socket.use {
|
||||
it.soTimeout = 10_000
|
||||
val reply = runCatching {
|
||||
check(it.peerCredentials.uid == android.os.Process.myUid())
|
||||
val peer = it.peerCredentials
|
||||
check(peer.uid == android.os.Process.myUid() && authorized(peer.pid))
|
||||
val request = JSONObject(readLine(it.inputStream.buffered(), 2_097_152))
|
||||
storage(app) {
|
||||
check(epoch(app) == generation)
|
||||
answer(JSONObject(readLine(it.inputStream.buffered(), 2_097_152)))
|
||||
check(!closed && epoch(app) == generation && authorized(peer.pid))
|
||||
answer(request)
|
||||
}
|
||||
}.getOrElse { JSONObject().put("ok", false) }
|
||||
}.getOrElse {
|
||||
android.util.Log.w("XboxCredentials", "Credential request rejected: ${it.javaClass.simpleName}")
|
||||
JSONObject().put("ok", false)
|
||||
}
|
||||
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
|
||||
}
|
||||
}
|
||||
@@ -58,14 +120,25 @@ internal class XboxCredentials(private val app: Context) : Closeable {
|
||||
return result
|
||||
}
|
||||
|
||||
override fun close() { closed = true; runCatching { server.close() } }
|
||||
override fun close() { closed = true; bound.countDown(); runCatching { server.close() } }
|
||||
|
||||
companion object {
|
||||
val lock = Any()
|
||||
internal fun mapsBackend(maps: String, path: String, inode: Long): Boolean = maps.lineSequence().any { line ->
|
||||
val fields = line.trim().split(Regex("\\s+"), limit = 6)
|
||||
fields.size == 6 && 'x' in fields[1] && fields[4].toLongOrNull() == inode &&
|
||||
runCatching { java.io.File(fields[5]).canonicalPath == path }.getOrDefault(false)
|
||||
}
|
||||
private fun epoch(app: Context): String = runCatching { java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").readText() }.getOrDefault("")
|
||||
fun invalidate(app: Context) = storage(app) {
|
||||
fun <T> lifecycle(app: Context, expected: String? = null, block: (String) -> T): T = storage(app) {
|
||||
val current = epoch(app)
|
||||
check(expected == null || expected == current) { "Xbox account changed during the request" }
|
||||
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()
|
||||
}
|
||||
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 ->
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import java.io.Closeable
|
||||
import java.util.UUID
|
||||
|
||||
internal class XboxLaunchLeases(private val now: () -> Long) {
|
||||
private data class Permit(val account: String, val expires: Long)
|
||||
private data class Lease(val id: String, val account: String, val session: String, var expires: Long, var child: Closeable? = null)
|
||||
private val permits = HashMap<String, Permit>()
|
||||
private val leases = HashMap<String, Lease>()
|
||||
|
||||
@Synchronized fun authorize(id: String, account: String) { permits[id] = Permit(account, now() + 180_000) }
|
||||
@Synchronized fun active(id: String) = leases.values.any { it.id == id }
|
||||
@Synchronized fun begin(id: String, account: String, session: String): String {
|
||||
val permit = permits.remove(id)
|
||||
check(permit != null && permit.account == account && permit.expires > now()) { "Start this Xbox game from DroidDeck." }
|
||||
check(!active(id)) { "This Xbox game is already starting or running." }
|
||||
val token = UUID.randomUUID().toString()
|
||||
leases[token] = Lease(id, account, session, now() + 180_000)
|
||||
return token
|
||||
}
|
||||
@Synchronized fun attach(token: String, child: Closeable): Boolean {
|
||||
val lease = leases[token] ?: return false
|
||||
lease.child = child
|
||||
return true
|
||||
}
|
||||
@Synchronized fun renew(token: String, id: String, account: String?, session: String?): Boolean {
|
||||
val lease = leases[token] ?: return false
|
||||
if (lease.id != id || lease.account != account || lease.session != session || lease.expires <= now()) return false
|
||||
lease.expires = now() + 60_000
|
||||
return true
|
||||
}
|
||||
@Synchronized fun release(token: String): Closeable? = leases.remove(token)?.child
|
||||
@Synchronized fun stale(account: String?, session: String?, suspended: Boolean): List<Closeable> {
|
||||
if (suspended) leases.values.filter { it.account == account && it.session == session }
|
||||
.forEach { it.expires = maxOf(it.expires, now() + 60_000) }
|
||||
val expired = leases.filterValues { it.account != account || it.session != session || (!suspended && it.expires <= now()) }.keys
|
||||
return expired.mapNotNull { leases.remove(it)?.child }
|
||||
}
|
||||
@Synchronized fun clear(): List<Closeable> {
|
||||
permits.clear()
|
||||
return leases.values.mapNotNull { it.child }.also { leases.clear() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.stores.xbox
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
|
||||
internal class XboxLaunchViews {
|
||||
private val recovered = HashSet<String>()
|
||||
|
||||
@Synchronized fun create(files: File): File {
|
||||
val parent = File(files, "xbox-runtime/views").canonicalFile
|
||||
check(parent == File(files.canonicalFile, "xbox-runtime/views")) { "Xbox launch storage contains a redirected path" }
|
||||
check(parent.mkdirs() || parent.isDirectory)
|
||||
if (parent.path !in recovered) {
|
||||
parent.listFiles()?.filter { it.name.startsWith("launch-") }?.forEach(::remove)
|
||||
recovered.add(parent.path)
|
||||
}
|
||||
return Files.createTempDirectory(parent.toPath(), "launch-").toFile()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun remove(directory: File) {
|
||||
if (!Files.exists(directory.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) return
|
||||
Files.walkFileTree(directory.toPath(), object : SimpleFileVisitor<Path>() {
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
Files.deleteIfExists(file)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
override fun postVisitDirectory(dir: Path, error: java.io.IOException?): FileVisitResult {
|
||||
if (error != null) throw error
|
||||
Files.deleteIfExists(dir)
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,8 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
Thread({
|
||||
if (closed) return@Thread
|
||||
try {
|
||||
Xodus.start(applicationContext, listOf("--external-webview-stdio", "login")).use { process ->
|
||||
val accountGeneration = XboxCredentials.lifecycle(applicationContext) { it }
|
||||
Xodus.start(applicationContext, listOf("--external-webview-stdio", "login"), credentialGeneration = accountGeneration).use { process ->
|
||||
child = process
|
||||
if (closed) return@use
|
||||
Xodus.diagnostics(process)
|
||||
@@ -99,9 +100,9 @@ class XboxLoginActivity : ComponentActivity() {
|
||||
}
|
||||
child = null
|
||||
if (closed) return@Thread
|
||||
val account = Xodus.run(applicationContext, listOf("account", "--json"))
|
||||
val account = Xodus.run(applicationContext, listOf("account", "--json"), credentialGeneration = accountGeneration)
|
||||
check(account.optBoolean("stored"))
|
||||
XboxCredentials.storage(this) {
|
||||
XboxCredentials.lifecycle(this, accountGeneration) {
|
||||
val record = StoreAccounts.read(this, Store.XBOX) ?: error("Xbox credentials missing")
|
||||
record.put("username", account.getString("username"))
|
||||
StoreAccounts.write(this, Store.XBOX, record)
|
||||
|
||||
@@ -7,40 +7,117 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
internal object XboxRuntime {
|
||||
private val state = Any()
|
||||
private val startup = Any()
|
||||
private var child: Xodus.Child? = null
|
||||
private var owner: String? = null
|
||||
private val activeGames = HashMap<String, Int>()
|
||||
@Synchronized fun isActive(id: String): Boolean = activeGames.getOrDefault(id, 0) > 0
|
||||
@Synchronized fun released(id: String) {
|
||||
val count = activeGames.getOrDefault(id, 0)
|
||||
if (count <= 1) activeGames.remove(id) else activeGames[id] = count - 1
|
||||
}
|
||||
private var serviceSocket: File? = null
|
||||
private var generation = 0L
|
||||
private val views = XboxLaunchViews()
|
||||
private val launches = XboxLaunchLeases { android.os.SystemClock.uptimeMillis() }
|
||||
fun isActive(id: String): Boolean = launches.active(id)
|
||||
fun authorize(app: Context, id: String): Boolean = runCatching {
|
||||
XboxCredentials.lifecycle(app) {
|
||||
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: return@lifecycle false
|
||||
launches.authorize(id, account)
|
||||
true
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
fun released(token: String) { runCatching { launches.release(token)?.close() } }
|
||||
fun renew(app: Context, id: String, token: String): Boolean = launches.renew(token, id,
|
||||
StoreAccounts.signedInAs(app, Store.XBOX), SessionState.sessionId.takeIf { SessionState.running })
|
||||
|
||||
@Synchronized fun prepare(app: Context, id: String): JSONObject {
|
||||
private data class Authorization(val account: String, val token: String, val runtime: Long, val credentials: String)
|
||||
|
||||
fun prepare(app: Context, id: String): JSONObject {
|
||||
check(!XboxContent.busy(id)) { "Wait for Xbox content downloads to finish" }
|
||||
check(SessionState.running) { "No running DroidDeck session" }
|
||||
check(StoreGameSidecar.find(app, Store.XBOX, id)?.isInstalled == true) { "Xbox game is not installed" }
|
||||
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: error("Sign in to Xbox before playing")
|
||||
val socket = File(app.filesDir, "xbox-runtime/xodus.sock")
|
||||
if (child?.process?.isAlive != true || owner != account) {
|
||||
stop()
|
||||
socket.delete()
|
||||
val service = Xodus.start(app, emptyList(), service = true)
|
||||
child = service; owner = account
|
||||
Xodus.diagnostics(service)
|
||||
Thread({ runCatching { service.process.inputStream.use { val buffer = ByteArray(8192); while (it.read(buffer) >= 0) {} } } }, "xbox-service-output").start()
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 90_000
|
||||
while (!socket.exists() && service.process.isAlive && SessionState.running && android.os.SystemClock.elapsedRealtime() < deadline) Thread.sleep(100)
|
||||
if (!socket.exists() || !service.process.isAlive || !SessionState.running) {
|
||||
stop(); error("Xbox account service did not become ready. Check your sign-in and network connection.")
|
||||
}
|
||||
val session = SessionState.sessionId ?: error("No running DroidDeck session")
|
||||
val game = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
||||
StoreGameSidecar.read(folder)?.takeIf { it.store == Store.XBOX && it.id == id && it.isInstalled }?.let { folder to it }
|
||||
}.firstOrNull() ?: error("Xbox game is not installed")
|
||||
val (account, token, current, credentials) = XboxCredentials.lifecycle(app) { epoch ->
|
||||
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: error("Sign in to Xbox before playing")
|
||||
synchronized(state) { Authorization(account, launches.begin(id, account, session), generation, epoch) }
|
||||
}
|
||||
activeGames[id] = activeGames.getOrDefault(id, 0) + 1
|
||||
return JSONObject().put("ok", true).put("socket", socket.path).put("credentials", child!!.credentialSocket)
|
||||
Thread({
|
||||
while (isActive(id)) {
|
||||
Thread.sleep(10_000)
|
||||
launches.stale(StoreAccounts.signedInAs(app, Store.XBOX), SessionState.sessionId.takeIf { SessionState.running },
|
||||
SessionState.suspended).forEach { runCatching { it.close() } }
|
||||
}
|
||||
}, "xbox-launch-expiry").start()
|
||||
try {
|
||||
val socket = service(app, account, current, credentials)
|
||||
check(synchronized(state) { generation == current }) { "Xbox launch was cancelled" }
|
||||
val market = game.second.extra["market"]?.takeIf { it.matches(Regex("[A-Z]{2}")) } ?: Xodus.market()
|
||||
val directory = views.create(app.filesDir)
|
||||
val process = try {
|
||||
Xodus.start(app, listOf("run", game.first.path, "droiddeck:prepare", "--exe", game.second.exe,
|
||||
"--materialize-chain", "--market", market), launchDirectory = directory, credentialGeneration = credentials)
|
||||
} catch (e: Exception) { XboxLaunchViews.remove(directory); throw e }
|
||||
if (!launches.attach(token, process)) { process.close(); error("Xbox launch was cancelled") }
|
||||
Xodus.diagnostics(process)
|
||||
val result = java.util.concurrent.FutureTask {
|
||||
val input = process.process.inputStream.buffered()
|
||||
var line: String
|
||||
do { line = XboxCredentials.readLine(input, 131_072) } while (!line.startsWith("DROIDDECK_LAUNCH_V1 "))
|
||||
JSONObject(line.removePrefix("DROIDDECK_LAUNCH_V1 "))
|
||||
}
|
||||
Thread(result, "xbox-launch-view").start()
|
||||
val view = result.get(90, java.util.concurrent.TimeUnit.SECONDS)
|
||||
check(renew(app, id, token) && synchronized(state) { generation == current }) { "Xbox launch was cancelled" }
|
||||
return JSONObject().put("ok", true).put("socket", socket.path).put("lease", token)
|
||||
.put("exe", view.getString("exe")).put("playfab", view.opt("playfab"))
|
||||
} catch (e: Exception) { released(token); throw e }
|
||||
}
|
||||
|
||||
@Synchronized fun stop() {
|
||||
val process = child; child = null; owner = null; activeGames.clear()
|
||||
runCatching { process?.close() }
|
||||
internal fun newServiceSocket(files: File): File =
|
||||
File(files, "xbox-runtime/s-${java.util.UUID.randomUUID().toString().replace("-", "")}/xodus.sock")
|
||||
|
||||
private fun service(app: Context, account: String, current: Long, credentials: String): File = synchronized(startup) {
|
||||
val existing = synchronized(state) {
|
||||
check(generation == current) { "Xbox launch was cancelled" }
|
||||
serviceSocket?.takeIf { child?.process?.isAlive == true && owner == account }
|
||||
}
|
||||
val socket = existing ?: newServiceSocket(app.filesDir)
|
||||
if (existing == null) {
|
||||
val old = synchronized(state) { child.also { child = null; owner = null; serviceSocket = null } }
|
||||
old?.close()
|
||||
socket.delete()
|
||||
val service = Xodus.start(app, emptyList(), service = true, runtimeDirectory = socket.parentFile!!, credentialGeneration = credentials)
|
||||
val accepted = synchronized(state) {
|
||||
(generation == current).also { if (it) { child = service; owner = account; serviceSocket = socket } }
|
||||
}
|
||||
if (!accepted) { service.close(); error("Xbox launch was cancelled") }
|
||||
try {
|
||||
Xodus.diagnostics(service)
|
||||
Thread({ runCatching { service.process.inputStream.use { input ->
|
||||
val buffer = ByteArray(8192)
|
||||
while (input.read(buffer) >= 0) { Thread.yield() }
|
||||
} } }, "xbox-service-output").start()
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 90_000
|
||||
while (!socket.exists() && service.process.isAlive && SessionState.running &&
|
||||
synchronized(state) { generation == current } && android.os.SystemClock.elapsedRealtime() < deadline) Thread.sleep(100)
|
||||
check(socket.exists() && service.process.isAlive && SessionState.running) {
|
||||
"Xbox account service did not become ready. Check your sign-in and network connection."
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
synchronized(state) { if (child === service) { child = null; owner = null; serviceSocket = null } }
|
||||
service.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
socket
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val processes = synchronized(state) {
|
||||
generation++
|
||||
val all = launches.clear() + listOfNotNull(child)
|
||||
child = null; owner = null; serviceSocket = null
|
||||
all
|
||||
}
|
||||
Thread({ processes.forEach { runCatching { it.close() } } }, "xbox-runtime-stop").start()
|
||||
}
|
||||
}
|
||||
@@ -13,16 +13,32 @@ internal object Xodus {
|
||||
const val DIR = "/usr/local/lib/droiddeck-xbox"
|
||||
fun market(): String = java.util.Locale.getDefault().country.uppercase().takeIf { it.matches(Regex("[A-Z]{2}")) } ?: "US"
|
||||
|
||||
class Child(val process: Process, private val credentials: XboxCredentials) : Closeable {
|
||||
val credentialSocket: String get() = credentials.name
|
||||
class Child(val process: Process, private val credentials: XboxCredentials, private val runtimeDirectory: File? = null, private val launchDirectory: File? = null) : Closeable {
|
||||
@Synchronized fun send(frame: JSONObject) {
|
||||
process.outputStream.write((frame.toString() + "\n").toByteArray())
|
||||
process.outputStream.flush()
|
||||
}
|
||||
override fun close() {
|
||||
process.destroy()
|
||||
if (!process.waitFor(2, TimeUnit.SECONDS)) process.destroyForcibly()
|
||||
credentials.close()
|
||||
try {
|
||||
credentials.close()
|
||||
runCatching { process.outputStream.close() }
|
||||
if (!process.waitFor(2, TimeUnit.SECONDS)) {
|
||||
credentials.signalBackend(android.system.OsConstants.SIGINT)
|
||||
if (!process.waitFor(2, TimeUnit.SECONDS)) {
|
||||
credentials.signalBackend(android.system.OsConstants.SIGKILL)
|
||||
if (!process.waitFor(1, TimeUnit.SECONDS)) {
|
||||
val pid = com.droiddeck.launcher.core.HostProcess.pidOf(process)
|
||||
if (pid > 0) android.os.Process.killProcess(pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
runtimeDirectory?.let { directory ->
|
||||
File(directory, "xodus.sock").delete()
|
||||
directory.delete()
|
||||
}
|
||||
launchDirectory?.let(XboxLaunchViews::remove)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,19 +61,20 @@ internal object Xodus {
|
||||
File(root, "version").writeText(packaged)
|
||||
}
|
||||
|
||||
fun start(app: Context, args: List<String>, service: Boolean = false): Child {
|
||||
fun start(app: Context, args: List<String>, service: Boolean = false, runtimeDirectory: File? = null, launchDirectory: File? = null, credentialGeneration: String? = null): Child {
|
||||
check(LinuxRuntime.isInstalled(app)) { "Install the Linux runtime before using Xbox." }
|
||||
stage(app)
|
||||
val binary = "$DIR/${if (service) "xodus-service" else "xodus-cli"}"
|
||||
check(File(LinuxRuntime.rootDir(app), binary.removePrefix("/")).isFile) { "The Xbox backend is missing. Update the Linux runtime." }
|
||||
val credentials = XboxCredentials(app)
|
||||
val credentials = XboxCredentials(app, credentialGeneration)
|
||||
try {
|
||||
val runtime = File(app.filesDir, "xbox-runtime").apply { mkdirs() }
|
||||
val runtime = (runtimeDirectory ?: File(app.filesDir, "xbox-runtime")).apply { mkdirs() }
|
||||
val command = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), listOf(
|
||||
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
|
||||
"XDG_RUNTIME_DIR=${runtime.path}", "DROIDDECK_XBOX_CREDENTIAL_SOCKET=${credentials.name}", binary,
|
||||
) + args)
|
||||
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
|
||||
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
|
||||
builder.environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
@@ -65,12 +82,19 @@ internal object Xodus {
|
||||
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
return Child(builder.start(), credentials)
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256")
|
||||
app.assets.open("linuxfs$binary").use { input ->
|
||||
val buffer = ByteArray(65536)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
||||
}
|
||||
val process = builder.start()
|
||||
credentials.bind(process, File(LinuxRuntime.rootDir(app), binary.removePrefix("/")), digest.digest())
|
||||
return Child(process, credentials, runtimeDirectory, launchDirectory)
|
||||
} catch (e: Exception) { credentials.close(); throw e }
|
||||
}
|
||||
|
||||
fun run(app: Context, args: List<String>, timeout: Long = 90): JSONObject {
|
||||
start(app, args).use { child ->
|
||||
fun run(app: Context, args: List<String>, timeout: Long = 90, credentialGeneration: String? = null): JSONObject {
|
||||
start(app, args, credentialGeneration = credentialGeneration).use { child ->
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
var readError: Throwable? = null
|
||||
val reader = Thread({
|
||||
|
||||
@@ -125,7 +125,8 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
ActionChip(stringResource(R.string.stores_in_steam), ok = true)
|
||||
if (store == Store.XBOX) {
|
||||
SecondaryButton("Update / verify", enabled = download == null && !com.droiddeck.launcher.stores.xbox.XboxRuntime.isActive(id)) {
|
||||
com.droiddeck.launcher.stores.xbox.XboxBackend.update(ctx, installed)
|
||||
runCatching { com.droiddeck.launcher.stores.xbox.XboxBackend.update(ctx, installed) }
|
||||
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: "Close this Xbox game before updating it." }
|
||||
}
|
||||
SecondaryButton("Manage content", enabled = download == null) {
|
||||
com.droiddeck.launcher.stores.xbox.XboxContent.manage(ctx, installed)
|
||||
|
||||
Reference in new issue
Block a user