mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 06:15:58 +00:00
fix(install): recheck cancellation after sha256 and wire package resume cancel
This commit is contained in:
commit
1b5cd6add9
399 files changed
+28516
-1432
No files matched your search
@@ -0,0 +1,420 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
import java.io.File
|
||||
|
||||
object BattleNet {
|
||||
private const val TAG = "BattleNet"
|
||||
|
||||
const val APP_ID = 2596113170L
|
||||
|
||||
const val FEX_REQUEST = "battlenet-fex.request"
|
||||
const val FEX_RESULT = "battlenet-fex.result"
|
||||
|
||||
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
|
||||
|
||||
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null)
|
||||
|
||||
internal val TITLES = listOf(
|
||||
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight", product = "wow"),
|
||||
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades", product = "wow_classic"),
|
||||
Title("wow_classic_era", "World of Warcraft Classic", "WoWC", product = "wow_classic_era"),
|
||||
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary"),
|
||||
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
|
||||
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
|
||||
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
|
||||
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
|
||||
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
|
||||
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm", product = "hero"),
|
||||
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch", product = "pro"),
|
||||
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged", product = "w3"),
|
||||
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4", product = "viper"),
|
||||
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare", product = "odin"),
|
||||
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered", product = "lazr"),
|
||||
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war", product = "zeus"),
|
||||
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard", product = "fore"),
|
||||
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii", product = "auks"),
|
||||
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii", product = "pinta"),
|
||||
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4", product = "wlby"),
|
||||
Title("osi", "Diablo II: Resurrected", "OSI", product = "osi"),
|
||||
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection", product = "rtro"),
|
||||
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal", product = "anbs"),
|
||||
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv", product = "fenris"),
|
||||
Title("d1", "Diablo", "D1", shop = "diablo", product = "drtl"),
|
||||
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans", product = "war1"),
|
||||
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition", product = "w2bn"),
|
||||
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered", product = "w1r"),
|
||||
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered", product = "w2r"),
|
||||
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble", product = "gryphon"),
|
||||
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages", product = "aris"),
|
||||
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves", product = "scor"),
|
||||
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2", product = "ark"),
|
||||
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710, product = "lbra"),
|
||||
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
|
||||
)
|
||||
|
||||
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
|
||||
|
||||
fun notInstalled(title: Title, installedIds: Collection<String?>) =
|
||||
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
|
||||
|
||||
private const val COVER_RETRY_MS = 24 * 3600_000L
|
||||
|
||||
private fun coverDir(context: Context, title: Title) =
|
||||
File(context.filesDir, "battlenet-art/${(TITLES.firstOrNull { it.code == title.code } ?: title).uid}")
|
||||
|
||||
fun cover(context: Context, title: Title): File? = art(context, title).cover
|
||||
|
||||
private val coverLock = Any()
|
||||
|
||||
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) {
|
||||
val art = com.droiddeck.launcher.frontend.AddedGameArt
|
||||
val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context)
|
||||
var got = false
|
||||
for (title in titles) {
|
||||
val dir = coverDir(context, title)
|
||||
val tried = File(dir, ".tried")
|
||||
val wide = File(dir, BLIZZARD)
|
||||
val done = File(dir, "p.jpg").isFile && (title.shop == null || wide.isFile)
|
||||
if (done || System.currentTimeMillis() - tried.lastModified() < COVER_RETRY_MS) continue
|
||||
dir.mkdirs()
|
||||
if (title.steam != null && runCatching { art.download(title.steam.toString(), dir) }.getOrDefault(false)) got = true
|
||||
if (title.shop != null && !wide.isFile) {
|
||||
val cover = File(dir, BLIZZARD_COVER).takeUnless { File(dir, "p.jpg").isFile }
|
||||
if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.shop, wide, cover) }
|
||||
.onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) got = true
|
||||
}
|
||||
if (!File(dir, "p.jpg").isFile && !File(dir, BLIZZARD_COVER).isFile && key.isNotEmpty()) {
|
||||
val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.gameId(key, title.steam, title.name) }.getOrNull()
|
||||
if (id != null && runCatching { com.droiddeck.launcher.frontend.SteamGridDb.download(key, id, dir) }.getOrDefault(false)) got = true
|
||||
}
|
||||
runCatching { tried.writeText("") ; tried.setLastModified(System.currentTimeMillis()) }
|
||||
}
|
||||
got
|
||||
}
|
||||
|
||||
private val LOCALES = setOf(
|
||||
"enus", "engb", "dede", "eses", "esmx", "frfr", "itit", "kokr", "plpl", "ptbr", "ptpt", "ruru", "zhcn", "zhtw", "jajp", "thth", "trtr", "arsa",
|
||||
)
|
||||
|
||||
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
|
||||
|
||||
class Game(val uid: String, val name: String, val code: String, val folder: File, val installUid: String = uid) {
|
||||
val title: Title get() = title(uid) ?: Title(uid, name, code)
|
||||
}
|
||||
|
||||
class Art(val cover: File?, val header: File?)
|
||||
|
||||
private const val BLIZZARD = "blizzard.jpg"
|
||||
private const val BLIZZARD_COVER = "p-blizzard.jpg"
|
||||
|
||||
fun art(context: Context, title: Title): Art {
|
||||
val dir = coverDir(context, title)
|
||||
fun first(vararg names: String) = names.map { File(dir, it) }.firstOrNull { it.isFile }
|
||||
return Art(first("p.jpg", BLIZZARD_COVER), first(BLIZZARD, "header.jpg"))
|
||||
}
|
||||
|
||||
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
|
||||
|
||||
fun client(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe")
|
||||
|
||||
fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe").isFile
|
||||
|
||||
fun profile(context: Context): Pair<String, String>? =
|
||||
(APP_ID.toString() to context.getString(com.droiddeck.launcher.R.string.bnet_name)).takeIf { installed(context) }
|
||||
|
||||
fun icon(context: Context): File? {
|
||||
val out = File(context.filesDir, "battlenet-art/launcher/icon.png")
|
||||
if (out.isFile) return out
|
||||
val exe = client(context).takeIf { it.isFile } ?: return null
|
||||
val bitmap = runCatching { com.droiddeck.launcher.files.PeIconExtractor.extract(exe) }.getOrNull() ?: return null
|
||||
return runCatching {
|
||||
out.parentFile?.mkdirs()
|
||||
val tmp = File(out.path + ".tmp")
|
||||
tmp.outputStream().use { check(bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it)) }
|
||||
check(tmp.renameTo(out))
|
||||
out
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
fun launcherEntry(installed: Boolean, art: File? = null): com.droiddeck.launcher.frontend.Library.SteamGame? =
|
||||
if (!installed) null
|
||||
else com.droiddeck.launcher.frontend.Library.SteamGame(
|
||||
appId = APP_ID.toInt(), name = com.droiddeck.launcher.stores.Store.BATTLENET.label, art = art,
|
||||
library = com.droiddeck.launcher.frontend.Library.BATTLENET_LAUNCHER, gameId = APP_ID,
|
||||
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
|
||||
)
|
||||
|
||||
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
|
||||
|
||||
internal fun title(uid: String): Title? {
|
||||
val id = uid.lowercase()
|
||||
TITLES.firstOrNull { it.uid == id }?.let { return it }
|
||||
val base = id.substringBeforeLast('_', "")
|
||||
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
|
||||
}
|
||||
|
||||
fun games(context: Context): List<Game> {
|
||||
val pfx = File(prefix(context), "pfx")
|
||||
val entries = installs(
|
||||
runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()),
|
||||
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrNull(),
|
||||
)
|
||||
val found = LinkedHashMap<String, Game>()
|
||||
for ((uid, path) in entries) {
|
||||
val title = title(uid)
|
||||
if (title == null) {
|
||||
if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)")
|
||||
continue
|
||||
}
|
||||
if (title.code in found) continue
|
||||
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
|
||||
found[title.code] = Game(title.uid, title.name, title.code, folder, uid)
|
||||
}
|
||||
return found.values.toList()
|
||||
}
|
||||
|
||||
internal fun installs(registry: List<Pair<String, String>>, agent: List<Pair<String, String>>?): List<Pair<String, String>> {
|
||||
if (agent == null) return registry
|
||||
val tracked = agent.map { it.first.lowercase() }.toSet()
|
||||
return registry.filter { it.first.lowercase() in tracked } + agent
|
||||
}
|
||||
|
||||
internal fun hostFolder(context: Context, path: String): File? {
|
||||
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
|
||||
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
|
||||
if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null
|
||||
return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative")
|
||||
else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative")
|
||||
}
|
||||
|
||||
private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""")
|
||||
private val UNINSTALL = Regex("""(?i)\\CurrentVersion\\Uninstall\\[^\\]+$""")
|
||||
private val VALUE = Regex("""^"((?:[^"\\]|\\.)*)"=(?:str\(\d+\):)?"((?:[^"\\]|\\.)*)"\s*$""")
|
||||
private val UID = Regex("""--uid=([A-Za-z0-9_.-]+)""")
|
||||
|
||||
internal fun uninstallEntries(lines: Sequence<String>): List<Pair<String, String>> {
|
||||
val out = ArrayList<Pair<String, String>>()
|
||||
var inside = false
|
||||
var uid: String? = null
|
||||
var location: String? = null
|
||||
fun flush() {
|
||||
val u = uid
|
||||
val l = location
|
||||
if (u != null && l != null) out.add(u to l)
|
||||
uid = null
|
||||
location = null
|
||||
}
|
||||
for (line in lines) {
|
||||
if (line.startsWith("[")) {
|
||||
flush()
|
||||
inside = KEY.matchEntire(line)?.groupValues?.get(1)?.let { UNINSTALL.containsMatchIn(unescape(it)) } == true
|
||||
continue
|
||||
}
|
||||
if (!inside) continue
|
||||
val value = VALUE.matchEntire(line) ?: continue
|
||||
val text = unescape(value.groupValues[2])
|
||||
when (unescape(value.groupValues[1]).lowercase()) {
|
||||
"uninstallstring" -> if (text.contains("battle.net", ignoreCase = true)) uid = UID.find(text)?.groupValues?.get(1)
|
||||
"installlocation" -> location = text
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return out
|
||||
}
|
||||
|
||||
private fun unescape(s: String): String {
|
||||
val out = StringBuilder(s.length)
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
val c = s[i++]
|
||||
if (c != '\\' || i >= s.length) { out.append(c); continue }
|
||||
when (val e = s[i++]) {
|
||||
'n' -> out.append('\n')
|
||||
'r' -> out.append('\r')
|
||||
't' -> out.append('\t')
|
||||
'0' -> out.append('\u0000')
|
||||
'x' -> {
|
||||
var end = i
|
||||
while (end < s.length && end - i < 4 && s[end].lowercaseChar() in "0123456789abcdef") end++
|
||||
if (end > i) { out.append(s.substring(i, end).toInt(16).toChar()); i = end } else out.append('x')
|
||||
}
|
||||
else -> out.append(e)
|
||||
}
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? {
|
||||
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
|
||||
return installs.map { (_, start, end) ->
|
||||
runCatching {
|
||||
val install = fields(bytes, start, end)
|
||||
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
|
||||
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { String(bytes, it.second, it.third - it.second) }
|
||||
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
|
||||
?.let { s -> varints(bytes, s.second, s.third)[1] }
|
||||
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
|
||||
}.getOrElse { return null }
|
||||
}.filterNotNull()
|
||||
}
|
||||
|
||||
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
|
||||
|
||||
private fun varints(bytes: ByteArray, from: Int, to: Int): Map<Int, Long> =
|
||||
HashMap<Int, Long>().also { found -> walk(bytes, from, to) { field, value -> found.putIfAbsent(field, value) } }
|
||||
|
||||
private fun walk(bytes: ByteArray, from: Int, to: Int, varint: (Int, Long) -> Unit): List<Triple<Int, Int, Int>> {
|
||||
val out = ArrayList<Triple<Int, Int, Int>>()
|
||||
var i = from
|
||||
fun next(): Long {
|
||||
var value = 0L
|
||||
var shift = 0
|
||||
while (true) {
|
||||
require(i < to && shift < 64) { "truncated" }
|
||||
val b = bytes[i++].toInt() and 0xff
|
||||
value = value or ((b and 0x7f).toLong() shl shift)
|
||||
if (b < 0x80) return value
|
||||
shift += 7
|
||||
}
|
||||
}
|
||||
while (i < to) {
|
||||
val key = next()
|
||||
when ((key and 7).toInt()) {
|
||||
0 -> varint((key ushr 3).toInt(), next())
|
||||
1 -> { require(to - i >= 8) { "truncated" }; i += 8 }
|
||||
2 -> {
|
||||
val n = next()
|
||||
require(n in 0..(to - i).toLong()) { "truncated" }
|
||||
out.add(Triple((key ushr 3).toInt(), i, i + n.toInt()))
|
||||
i += n.toInt()
|
||||
}
|
||||
5 -> { require(to - i >= 4) { "truncated" }; i += 4 }
|
||||
else -> error("wire type ${key and 7}")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
fun shortcut(context: Context, game: Game): com.droiddeck.launcher.frontend.AddedGames.Game? {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames
|
||||
val client = client(context)
|
||||
val guestExe = added.guestPath(context, client) ?: return null
|
||||
val guestDir = added.guestPath(context, client.parentFile ?: return null) ?: return null
|
||||
val guestPrefix = added.guestPath(context, prefix(context)) ?: return null
|
||||
val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value
|
||||
val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L)
|
||||
val exe = added.candidates(game.folder).firstOrNull() ?: client
|
||||
return com.droiddeck.launcher.frontend.AddedGames.Game(
|
||||
game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe),
|
||||
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid,
|
||||
launchOptions = "STEAM_COMPAT_DATA_PATH=$guestPrefix %command% --exec=\"launch ${game.code}\"",
|
||||
)
|
||||
}
|
||||
|
||||
fun remove(context: Context) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
com.droiddeck.launcher.core.FileUtils.delete(prefix(context))
|
||||
File(root, "usr/local/share/applications/droiddeck-battlenet.desktop").delete()
|
||||
com.droiddeck.launcher.core.FileUtils.delete(File(root, "root/.cache/droiddeck/battlenet"))
|
||||
ComponentsManager.clearGameComponents(context, APP_ID.toString())
|
||||
Log.i(TAG, "removed")
|
||||
}
|
||||
|
||||
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
|
||||
|
||||
private const val LISTING_MAX_AGE = 6 * 3600L
|
||||
|
||||
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
|
||||
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
|
||||
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
|
||||
}
|
||||
|
||||
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
|
||||
val m = D2RFIX.matchEntire(file) ?: return null
|
||||
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
||||
return version to (m.groupValues[2].toLongOrNull() ?: return null)
|
||||
}
|
||||
|
||||
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
|
||||
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
|
||||
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
|
||||
|
||||
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
|
||||
|
||||
@Synchronized
|
||||
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
|
||||
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
|
||||
val file = ComponentsManager.safeName(item.file)
|
||||
if (ComponentsManager.packages(context).none { it.file == file }) {
|
||||
Log.i(TAG, "downloading ${item.file}")
|
||||
ComponentsManager.download(context, item) {}
|
||||
}
|
||||
val scope = APP_ID.toString()
|
||||
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
|
||||
ComponentsManager.setGameComponent(context, scope, "fex", file)
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file")
|
||||
} else if (ComponentsManager.republish(context)) {
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
|
||||
val cached = ComponentsManager.catalog(context, false)
|
||||
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
|
||||
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
|
||||
val fetched = runCatching { refresh(context) }
|
||||
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
|
||||
return if (newestD2rFix(fetched) != null) fetched else cached.items
|
||||
}
|
||||
|
||||
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
|
||||
|
||||
internal fun videoMemoryOptions(megabytes: Int): String =
|
||||
"dxgi.maxDeviceMemory = $megabytes; dxgi.maxSharedMemory = $megabytes; d3d9.maxAvailableMemory = $megabytes"
|
||||
|
||||
fun ensureVideoMemory(context: Context): Boolean {
|
||||
val memory = ActivityManager.MemoryInfo()
|
||||
context.getSystemService(ActivityManager::class.java)?.getMemoryInfo(memory) ?: return false
|
||||
if (memory.totalMem <= 0) return false
|
||||
val options = videoMemoryOptions(videoMemory(memory.totalMem / (1024 * 1024)))
|
||||
val set = GameEnvironmentStore.setDefault(context, APP_ID.toString(), DXVK_CONFIG, options)
|
||||
if (set) Log.i(TAG, "DXVK_CONFIG for the Battle.net profile: $options")
|
||||
return set
|
||||
}
|
||||
|
||||
private const val DXVK_CONFIG = "DXVK_CONFIG"
|
||||
|
||||
fun ensureNoSteam(context: Context): Boolean {
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) return false
|
||||
GameEnvironmentStore.setGameNoSteam(context, APP_ID.toString(), true)
|
||||
com.droiddeck.launcher.session.SessionPrefs.setBattleNetNoSteamSet(context)
|
||||
Log.i(TAG, "Start without Steam for the Battle.net profile")
|
||||
return true
|
||||
}
|
||||
|
||||
fun answerFexRequest(context: Context, dir: File) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
|
||||
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
|
||||
val answer = try {
|
||||
"ok " + ensureFex(app)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "FEX for the Battle.net prefix", e)
|
||||
"error " + (e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
Log.i(TAG, "FEX request: $answer")
|
||||
val result = File(dir, FEX_RESULT)
|
||||
val partial = File(dir, "$FEX_RESULT.tmp")
|
||||
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
|
||||
}, "battlenet-fex").start()
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,7 @@ object BwrapSpawner {
|
||||
val binds = ArrayList<Bind>()
|
||||
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
|
||||
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
|
||||
File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) }
|
||||
env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev ->
|
||||
binds.addAll(bindsFor(session, rootfs, dev, dev))
|
||||
}
|
||||
@@ -227,6 +228,7 @@ object BwrapSpawner {
|
||||
}
|
||||
|
||||
private const val PRELOAD_DIR = "/run/droiddeck-preload"
|
||||
private const val NET_LINK = "etc/droiddeck-net"
|
||||
|
||||
private const val ZYPAK_SHIM = "#!/bin/sh\nprogram=\$1\nshift\nexec \"\$program\" --no-sandbox \"\$@\"\n"
|
||||
|
||||
|
||||
@@ -71,9 +71,22 @@ object DesktopCatalog {
|
||||
}
|
||||
|
||||
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
resumeInterrupted(context, null, listener)
|
||||
}
|
||||
|
||||
fun resumeInterrupted(
|
||||
context: Context,
|
||||
cancelled: Downloader.Cancellation?,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?,
|
||||
): String? = synchronized(installLock) {
|
||||
for (entry in interrupted(context)) {
|
||||
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
|
||||
install(context, entry, listener)?.let { return it }
|
||||
val problem = if (cancelled == null) {
|
||||
install(context, entry, listener)
|
||||
} else {
|
||||
install(context, entry, cancelled, listener)
|
||||
}
|
||||
if (problem != null) return problem
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.database.ContentObserver
|
||||
import android.media.AudioManager
|
||||
import android.os.FileObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.R
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class DeviceControlsComponent(context: Context, root: File, private val activityVisible: () -> Boolean = { false }) : SessionPart() {
|
||||
private val context = context.applicationContext
|
||||
private val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private val directory = directory(root)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var running = false
|
||||
private var permissionNotified = false
|
||||
private var previous = ""
|
||||
private var revision = 0L
|
||||
init { prepareBacklight(context, root) }
|
||||
private val observer = object : ContentObserver(handler) {
|
||||
override fun onChange(selfChange: Boolean) { if (running) publish() }
|
||||
}
|
||||
private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
if (path in REQUESTS) handler.post { if (running) consume() }
|
||||
}
|
||||
}
|
||||
private val refresh = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
consume()
|
||||
if (permissionNotified && Settings.System.canWrite(context))
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
publish()
|
||||
handler.postDelayed(this, 250)
|
||||
}
|
||||
}
|
||||
|
||||
fun publish(force: Boolean = false) {
|
||||
try {
|
||||
directory.mkdirs()
|
||||
val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
|
||||
val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
|
||||
write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
write("backlight/droiddeck/brightness", "$value\n")
|
||||
write("backlight/droiddeck/actual_brightness", "$value\n")
|
||||
val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0)
|
||||
.put("brightnessWritable", Settings.System.canWrite(context)).toString()
|
||||
if (force || state != previous) {
|
||||
write("state.json", JSONObject(state).put("revision", ++revision).toString())
|
||||
previous = state
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not publish Android controls", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
handler.post {
|
||||
REQUESTS.forEach {
|
||||
File(directory, it).delete()
|
||||
File(directory, "$it.processing").delete()
|
||||
}
|
||||
running = true
|
||||
permissionNotified = false
|
||||
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
|
||||
requests.startWatching()
|
||||
refresh.run()
|
||||
}
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
handler.post {
|
||||
running = false
|
||||
handler.removeCallbacks(refresh)
|
||||
requests.stopWatching()
|
||||
context.contentResolver.unregisterContentObserver(observer)
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
}
|
||||
}
|
||||
|
||||
private fun consume() {
|
||||
for (name in REQUESTS) {
|
||||
val file = File(directory, name)
|
||||
if (!file.isFile) continue
|
||||
val claimed = File(directory, "$name.processing")
|
||||
try {
|
||||
Files.move(file.toPath(), claimed.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
if (claimed.length() > 64) continue
|
||||
val text = claimed.readText().trim()
|
||||
when (name) {
|
||||
"brightness.request" -> text.toFloatOrNull()?.takeIf { it.isFinite() && it in 0f..1f }?.let(::brightness)
|
||||
"volume.request" -> text.toIntOrNull()?.let {
|
||||
audio.setStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0)
|
||||
}
|
||||
"mute.request" -> if (text == "0" || text == "1") {
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not apply $name", e)
|
||||
} finally {
|
||||
publish(force = true)
|
||||
claimed.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun brightness(value: Float) {
|
||||
if (!Settings.System.canWrite(context)) {
|
||||
if (!permissionNotified) {
|
||||
permissionNotified = true
|
||||
try {
|
||||
val intent = Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
|
||||
.setAction(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP)
|
||||
.putExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE, "BRIGHTNESS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL,
|
||||
context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT))
|
||||
val action = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
|
||||
manager.notify(PERMISSION_NOTIFICATION, Notification.Builder(context, PERMISSION_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(context.getString(R.string.brightness_permission_title))
|
||||
.setContentText(context.getString(R.string.brightness_permission_text))
|
||||
.setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build())
|
||||
if (activityVisible()) android.widget.Toast.makeText(context, R.string.integration_brightness_needed,
|
||||
android.widget.Toast.LENGTH_LONG).show()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not open brightness permission", e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val level = 1 + (value * 254).roundToInt()
|
||||
try {
|
||||
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
|
||||
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
|
||||
Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, level)
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Brightness permission was revoked", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(name: String, text: String) {
|
||||
val file = File(directory, name)
|
||||
if (file.isFile && file.readText() == text) return
|
||||
val staged = File(directory, "$name.tmp")
|
||||
staged.writeText(text)
|
||||
Files.move(staged.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DeviceControls"
|
||||
private const val PERMISSION_CHANNEL = "brightness_permission"
|
||||
private const val PERMISSION_NOTIFICATION = 0x4442
|
||||
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
|
||||
@JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls")
|
||||
@JvmStatic fun prepareBacklight(context: Context, root: File): File {
|
||||
val base = File(directory(root), "backlight")
|
||||
val panel = File(base, "droiddeck").apply { mkdirs() }
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
for ((name, text) in mapOf("type" to "raw", "max_brightness" to "255", "brightness" to "$value",
|
||||
"actual_brightness" to "$value", "bl_power" to "0", "scale" to "linear")) {
|
||||
File(panel, name).writeText("$text\n")
|
||||
}
|
||||
return base
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,19 @@ package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import com.droiddeck.launcher.core.DownloadSource
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionFiles
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object GuestCommand {
|
||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, onLine: (String) -> Unit): Int {
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||
onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
|
||||
@@ -19,14 +22,14 @@ object GuestCommand {
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
|
||||
try {
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||
fastPath: Boolean, onLine: (String) -> Unit): Int {
|
||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
@@ -45,6 +48,15 @@ object GuestCommand {
|
||||
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
|
||||
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
|
||||
)
|
||||
// The Steam client installer and the package tools inside the guest fetch over plain curl,
|
||||
// so the app proxy has to reach them through the environment proot starts them with.
|
||||
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
|
||||
cmd += listOf(
|
||||
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
|
||||
"HTTP_PROXY=http://$hostPort", "HTTPS_PROXY=http://$hostPort",
|
||||
"no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1",
|
||||
)
|
||||
}
|
||||
fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) }
|
||||
cmd += argv
|
||||
val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true)
|
||||
@@ -56,13 +68,32 @@ object GuestCommand {
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
if (cancelled?.get() == true) return 130
|
||||
val process = builder.start()
|
||||
val pid = HostProcess.pidOf(process)
|
||||
OrphanReaper.keep(pid)
|
||||
val watcher = cancelled?.let { flag ->
|
||||
Thread({
|
||||
try {
|
||||
while (process.isAlive && !flag.get()) Thread.sleep(200)
|
||||
if (flag.get()) {
|
||||
// PRoot ignores SIGTERM; SIGQUIT makes it kill its tracees and exit cleanly.
|
||||
if (pid > 0) {
|
||||
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
|
||||
} else {
|
||||
process.destroy()
|
||||
}
|
||||
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly()
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
}
|
||||
}, "guest-cancel").apply { isDaemon = true; start() }
|
||||
}
|
||||
try {
|
||||
process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) }
|
||||
return process.waitFor()
|
||||
} finally {
|
||||
watcher?.interrupt()
|
||||
OrphanReaper.release(pid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,15 +63,48 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
/** The downloaded add-on pack. The APK does not ship this binary. */
|
||||
public static final String PROOT_PACK = "add-on pack";
|
||||
/** Termux's unpatched proot inside the rootfs. Developer switch only. */
|
||||
public static final String PROOT_ROOTFS = "rootfs fallback";
|
||||
public static final String PROOT_MISSING = "missing";
|
||||
|
||||
private static File rootfsProot(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
}
|
||||
|
||||
private static File rootfsLoader(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
}
|
||||
|
||||
private static boolean rootfsProotReady(Context context) {
|
||||
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** Patched proot is the add-on pack. The rootfs copy is not that binary. */
|
||||
public static boolean patchedProot(Context context) {
|
||||
return AddonPack.PROOT.installed(context);
|
||||
}
|
||||
|
||||
public static File prootBinary(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
if (SessionPrefs.allowStockProot(context)) return rootfsProot(context);
|
||||
return AddonPack.PROOT.file(context, "libproot.so");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
if (SessionPrefs.allowStockProot(context)) return rootfsLoader(context);
|
||||
return AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
}
|
||||
|
||||
/** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */
|
||||
public static String prootSource(Context context) {
|
||||
File bin = prootBinary(context);
|
||||
if (!bin.isFile()) return PROOT_MISSING;
|
||||
if (AddonPack.PROOT.installed(context)
|
||||
&& bin.getPath().equals(AddonPack.PROOT.file(context, "libproot.so").getPath())) return PROOT_PACK;
|
||||
return PROOT_ROOTFS;
|
||||
}
|
||||
|
||||
public static String prootLibraryPath(Context context) {
|
||||
@@ -85,8 +118,7 @@ public final class LinuxRuntime {
|
||||
return new File(root, "usr/bin/gamescope").isFile()
|
||||
&& (new File(root, SESSION_SCRIPT.substring(1)).isFile()
|
||||
|| new File(root, LegacyNames.SESSION_SCRIPT.substring(1)).isFile())
|
||||
&& prootBinary(context).isFile()
|
||||
&& prootLoader(context).isFile();
|
||||
&& (patchedProot(context) || rootfsProotReady(context));
|
||||
}
|
||||
|
||||
public static File vulkanIcd(Context context) {
|
||||
@@ -160,6 +192,7 @@ public final class LinuxRuntime {
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
bind(cmd, "/sys");
|
||||
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
|
||||
bind(cmd, "/dev/urandom:/dev/random");
|
||||
bind(cmd, "/proc/self/fd:/dev/fd");
|
||||
bind(cmd, "/proc/self/fd/0:/dev/stdin");
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.util.Log;
|
||||
|
||||
|
||||
import com.droiddeck.launcher.R;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
import com.droiddeck.launcher.core.ArchivePaths;
|
||||
import com.droiddeck.launcher.core.Downloader;
|
||||
import com.droiddeck.launcher.core.Hashes;
|
||||
@@ -262,7 +263,9 @@ public final class LinuxRuntimeInstaller {
|
||||
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot");
|
||||
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context)
|
||||
&& !SessionPrefs.allowStockProot(context))
|
||||
throw new IOException("Cannot download proot");
|
||||
if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio");
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
|
||||
if (listener != null) {
|
||||
@@ -299,27 +302,50 @@ public final class LinuxRuntimeInstaller {
|
||||
discard(staging, null);
|
||||
return false;
|
||||
}
|
||||
java.util.List<String> carryPaths = root.isDirectory()
|
||||
? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList();
|
||||
if (root.isDirectory() && !root.renameTo(old)) {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return false;
|
||||
}
|
||||
File carryMarker = new File(staging, CARRY_MARKER);
|
||||
java.util.List<String> encodedPaths = new java.util.ArrayList<>();
|
||||
for (String rel : carryPaths) encodedPaths.add(java.net.URLEncoder.encode(rel, "UTF-8"));
|
||||
if (!FileUtils.writeString(carryMarker, String.join("\n", encodedPaths))) {
|
||||
if (old.isDirectory() && !old.renameTo(root))
|
||||
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
|
||||
discard(staging, null);
|
||||
return false;
|
||||
}
|
||||
|
||||
java.util.List<String> carried;
|
||||
try {
|
||||
RuntimeFileTree.carryHome(old, staging);
|
||||
carried = RuntimeFileTree.carryUserData(old, staging, false, carryPaths);
|
||||
} catch (IOException e) {
|
||||
Log.w(TAG, "could not carry root across the update; rolling back", e);
|
||||
old.renameTo(root);
|
||||
try { RuntimeFileTree.delete(staging, null); }
|
||||
catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
|
||||
Log.w(TAG, "could not carry user data across the update; rolling back", e);
|
||||
if (old.isDirectory() && !old.renameTo(root))
|
||||
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
|
||||
if (e.getSuppressed().length == 0) {
|
||||
new File(staging, CARRY_MARKER).delete();
|
||||
try { RuntimeFileTree.delete(staging, null); }
|
||||
catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
|
||||
} else {
|
||||
Log.w(TAG, "incomplete rollback; retaining user data in " + staging);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!staging.renameTo(root)) {
|
||||
File keptTo = new File(staging, USER_DATA);
|
||||
if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
if (old.isDirectory()) {
|
||||
try {
|
||||
RuntimeFileTree.carryBack(staging, old, carried);
|
||||
new File(staging, CARRY_MARKER).delete();
|
||||
} catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); }
|
||||
old.renameTo(root);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
new File(root, CARRY_MARKER).delete();
|
||||
discard(old, null);
|
||||
return LinuxRuntime.isInstalled(context);
|
||||
} catch (Exception e) {
|
||||
@@ -330,17 +356,41 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
static final String CARRY_MARKER = ".droiddeck-carry";
|
||||
|
||||
static void recoverInterruptedSwap(File root, File staging, File old) throws IOException {
|
||||
if (!root.isDirectory() && old.isDirectory()) {
|
||||
if (!old.renameTo(root)) throw new IOException("Cannot restore the previous runtime at " + old);
|
||||
Log.w(TAG, "restored the previous runtime after an interrupted update");
|
||||
}
|
||||
File marker = new File(staging, CARRY_MARKER);
|
||||
if (!RuntimeFileTree.exists(marker.toPath())) return;
|
||||
File target = root.isDirectory() ? root : old;
|
||||
String markerContent = FileUtils.readString(marker);
|
||||
if (markerContent == null) throw new IOException("Cannot read runtime recovery marker: " + marker);
|
||||
if (!markerContent.equals("1")) {
|
||||
java.util.List<String> intended = new java.util.ArrayList<>();
|
||||
for (String rel : markerContent.split("\\n"))
|
||||
if (!rel.isEmpty()) intended.add(java.net.URLDecoder.decode(rel, "UTF-8"));
|
||||
if (target.isDirectory()) RuntimeFileTree.recoverCarriedPaths(staging, target, intended);
|
||||
if (staging.isDirectory() && RuntimeFileTree.hasPaths(staging, intended))
|
||||
throw new IOException("User data still needs recovery from " + staging);
|
||||
marker.delete();
|
||||
return;
|
||||
}
|
||||
File stagedHome = new File(staging, USER_DATA);
|
||||
File home = new File(target, USER_DATA);
|
||||
if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
|
||||
if (target.isDirectory() && stagedHome.isDirectory() && (!RuntimeFileTree.exists(home.toPath()) || isEmptyDir(home))) {
|
||||
RuntimeFileTree.carryHome(staging, target);
|
||||
Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
|
||||
}
|
||||
if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
|
||||
Log.w(TAG, "restored the previous runtime after an interrupted update");
|
||||
if (target.isDirectory() && staging.isDirectory()) {
|
||||
java.util.List<String> rest = RuntimeFileTree.carryUserData(staging, target, true);
|
||||
if (!rest.isEmpty()) Log.w(TAG, "recovered " + rest + " from an interrupted update");
|
||||
}
|
||||
if (staging.isDirectory() && RuntimeFileTree.hasUserData(staging, target))
|
||||
throw new IOException("User data still needs recovery from " + staging);
|
||||
new File(staging, CARRY_MARKER).delete();
|
||||
}
|
||||
|
||||
static final String TRASH = ".runtime-trash";
|
||||
@@ -364,9 +414,10 @@ public final class LinuxRuntimeInstaller {
|
||||
Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash);
|
||||
}
|
||||
|
||||
private static boolean isEmptyDir(File dir) {
|
||||
String[] names = dir.list();
|
||||
return dir.isDirectory() && names != null && names.length == 0;
|
||||
private static boolean isEmptyDir(File dir) throws IOException {
|
||||
try (java.nio.file.DirectoryStream<java.nio.file.Path> entries = java.nio.file.Files.newDirectoryStream(dir.toPath())) {
|
||||
return !entries.iterator().hasNext();
|
||||
}
|
||||
}
|
||||
|
||||
public static Removal beginUninstall(Context context) {
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
object ProotFastPath {
|
||||
private const val TAG = "ProotFastPath"
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) &&
|
||||
LinuxRuntime.prootBinary(context).parentFile == AddonPack.PROOT.dir(context)
|
||||
/**
|
||||
* The fast path's trampoline is let through only by the proot built with patches/0014.
|
||||
* The rootfs copy (Termux's stock proot) is not that binary, so the library stays out.
|
||||
*/
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
|
||||
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
|
||||
|
||||
fun enabled(context: Context): Boolean {
|
||||
val preference = SessionPrefs.prootFastPath(context)
|
||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
||||
val source = LinuxRuntime.prootSource(context)
|
||||
val on = allows(preference, noSeccomp, source)
|
||||
if (preference && !noSeccomp && !on)
|
||||
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||
return on
|
||||
}
|
||||
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
|
||||
@@ -74,6 +74,163 @@ public final class RuntimeFileTree {
|
||||
throw new IOException("Cannot make directory removable: " + dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths in a runtime tree that belong to the user: the home folder, imported AppImages and script apps, and catalog
|
||||
* AppImages with their menu entries and markers. Tar-kind catalog packages (the desktop) unpack over /usr and cannot
|
||||
* be carried.
|
||||
*/
|
||||
static java.util.List<String> userPaths(File tree) throws IOException {
|
||||
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps"));
|
||||
for (String n : children(new File(tree, "usr/local/share/applications"))) {
|
||||
if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-")))
|
||||
paths.add("usr/local/share/applications/" + n);
|
||||
}
|
||||
for (String n : children(new File(tree, "opt/appimages"))) {
|
||||
if (!n.endsWith(".AppImage")) continue;
|
||||
String id = n.substring(0, n.length() - ".AppImage".length());
|
||||
java.util.Collections.addAll(paths, "opt/appimages/" + n,
|
||||
"usr/share/applications/droiddeck-" + id + ".desktop", ".droiddeck-pkg-" + id);
|
||||
}
|
||||
for (String n : children(new File(tree, "usr/share/applications"))) {
|
||||
if (!n.startsWith("droiddeck-") || !n.endsWith(".desktop")) continue;
|
||||
String id = n.substring("droiddeck-".length(), n.length() - ".desktop".length());
|
||||
if (!exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath()))
|
||||
paths.add("usr/share/applications/" + n);
|
||||
}
|
||||
for (String n : children(tree)) {
|
||||
if (!n.startsWith(".droiddeck-pkg-")) continue;
|
||||
String id = n.substring(".droiddeck-pkg-".length());
|
||||
boolean hasMenu = exists(new File(tree, "usr/share/applications/droiddeck-" + id + ".desktop").toPath());
|
||||
if (hasMenu && !exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath()))
|
||||
paths.add(n);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
static java.util.List<String> existingUserPaths(File from, File to) throws IOException {
|
||||
java.util.List<String> paths = new java.util.ArrayList<>();
|
||||
for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel);
|
||||
return paths;
|
||||
}
|
||||
|
||||
private static java.util.List<String> children(File dir) throws IOException {
|
||||
java.util.List<String> names = new java.util.ArrayList<>();
|
||||
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) {
|
||||
for (Path entry : entries) names.add(entry.getFileName().toString());
|
||||
} catch (NoSuchFileException e) {
|
||||
return names;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
static boolean exists(Path path) throws IOException {
|
||||
try { Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); return true; }
|
||||
catch (NoSuchFileException e) { return false; }
|
||||
}
|
||||
|
||||
private static java.util.Set<String> userPaths(File from, File to) throws IOException {
|
||||
java.util.Set<String> paths = new java.util.LinkedHashSet<>(userPaths(from));
|
||||
paths.addAll(userPaths(to));
|
||||
return paths;
|
||||
}
|
||||
|
||||
static boolean hasUserData(File from, File to) throws IOException {
|
||||
for (String rel : userPaths(from, to)) if (exists(new File(from, rel).toPath())) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves each user path that exists in {@code from} into {@code to}, replacing what {@code to} ships there. With
|
||||
* {@code onlyMissing}, a path already present in {@code to} is left alone. On failure the paths already moved go back
|
||||
* before the exception is thrown. Rollback failures are suppressed on that exception; callers must retain the source
|
||||
* of any incomplete rollback.
|
||||
* Returns the moved paths.
|
||||
*/
|
||||
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing) throws IOException {
|
||||
return carryUserData(from, to, onlyMissing, new java.util.ArrayList<>(userPaths(from, to)));
|
||||
}
|
||||
|
||||
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing, java.util.List<String> paths) throws IOException {
|
||||
java.util.List<String> moved = new java.util.ArrayList<>();
|
||||
try {
|
||||
for (String rel : paths) {
|
||||
File src = safePath(from, rel);
|
||||
if (!exists(src.toPath())) continue;
|
||||
File dst = safePath(to, rel);
|
||||
if (onlyMissing && exists(dst.toPath())) continue;
|
||||
move(from, to, rel);
|
||||
moved.add(rel);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
for (int i = moved.size() - 1; i >= 0; i--) {
|
||||
try { move(to, from, moved.get(i)); }
|
||||
catch (IOException back) { e.addSuppressed(back); }
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/** Puts the given paths back from {@code from} into {@code to}; failures are collected, not stopped on. */
|
||||
static void carryBack(File from, File to, java.util.List<String> paths) throws IOException {
|
||||
IOException failed = null;
|
||||
for (int i = paths.size() - 1; i >= 0; i--) {
|
||||
try { move(from, to, paths.get(i)); }
|
||||
catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); }
|
||||
}
|
||||
if (failed != null) throw failed;
|
||||
}
|
||||
|
||||
private static void move(File from, File to, String rel) throws IOException {
|
||||
File src = safePath(from, rel);
|
||||
File dst = safePath(to, rel);
|
||||
File parent = src.getParentFile();
|
||||
if (parent != null) makeWritable(parent);
|
||||
java.util.List<File> made = new java.util.ArrayList<>();
|
||||
for (File d = dst.getParentFile(); d != null; d = d.getParentFile()) {
|
||||
made.add(d);
|
||||
if (d.equals(to)) break;
|
||||
}
|
||||
for (int i = made.size() - 1; i >= 0; i--) {
|
||||
File d = made.get(i);
|
||||
if (!d.isDirectory() && !d.mkdirs()) throw new IOException("Cannot create " + d);
|
||||
makeWritable(d);
|
||||
}
|
||||
delete(dst, null);
|
||||
if (!src.renameTo(dst)) throw new IOException("Cannot carry " + rel + " across the update");
|
||||
}
|
||||
|
||||
static void recoverCarriedPaths(File staging, File target, java.util.List<String> paths) throws IOException {
|
||||
for (String rel : paths) {
|
||||
File src = safePath(staging, rel);
|
||||
if (!exists(src.toPath())) continue;
|
||||
File dst = safePath(target, rel);
|
||||
if (!exists(dst.toPath())) move(staging, target, rel);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean hasPaths(File tree, java.util.List<String> paths) throws IOException {
|
||||
for (String rel : paths) if (exists(safePath(tree, rel).toPath())) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static File safePath(File tree, String rel) throws IOException {
|
||||
Path relative = java.nio.file.Paths.get(rel);
|
||||
if (relative.isAbsolute() || relative.getNameCount() == 0) throw new IOException("Invalid runtime path: " + rel);
|
||||
for (Path part : relative) if (part.toString().equals("..")) throw new IOException("Invalid runtime path: " + rel);
|
||||
Path current = tree.toPath();
|
||||
for (int i = 0; i < relative.getNameCount() - 1; i++) {
|
||||
current = current.resolve(relative.getName(i));
|
||||
try {
|
||||
BasicFileAttributes attrs = Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
if (!attrs.isDirectory()) throw new IOException("Runtime path has a non-directory parent: " + current);
|
||||
} catch (NoSuchFileException ignored) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return tree.toPath().resolve(relative).toFile();
|
||||
}
|
||||
|
||||
static void carryHome(File old, File staging) throws IOException {
|
||||
File home = new File(old, "root");
|
||||
if (!home.isDirectory()) return;
|
||||
|
||||
Reference in new issue
Block a user