mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
Rename the app SteamDeck → DroidDeck
App name, app ID and code package: DroidDeck, com.droiddeck.launcher (sources moved to com/droiddeck/launcher, the 68 JNI functions renamed with them). The new app ID installs beside SteamDeck rather than over it. Everywhere the name was the app's own: the sidebar title, the session report, share zips, the shell title, wake-lock and log tags, User-Agents, the Compose theme, the Download folder and switch files (droiddeck-env, -osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the old names are not read), and inside the runtime (droiddeck-desktop, Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project, README and the progress log follow. Kept on purpose: Valve's Steam Deck (the -steamdeck flag, steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud package URLs) and names inside the hosted desktop package (steamdeck.png, steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for labwc instead of the launcher the app stages itself. A committed __pycache__ .pyc is removed.
This commit is contained in:
1 parent
a19dfb88a0
commit
d160f464b6
118 files changed
+498
-487
No files matched your search
@@ -0,0 +1,132 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The hosted packages that go into the runtime on request - the desktop, the emulators, and the
|
||||
* builds we mirror or make ourselves - described by desktop.json beside the runtime's own catalog.
|
||||
*
|
||||
* Two kinds. A `tar` extracts over the rootfs like the runtime itself (the same extractor, links
|
||||
* and modes preserved). An `appimage` is one file dropped in /opt/appimages with a .desktop entry
|
||||
* written for it; proot has no FUSE, so it runs extracted (APPIMAGE_EXTRACT_AND_RUN).
|
||||
*/
|
||||
object DesktopCatalog {
|
||||
private const val TAG = "DesktopCatalog"
|
||||
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/desktop.json"
|
||||
|
||||
class Entry(
|
||||
val id: String, val name: String, val tier: Int, val version: String, val kind: String,
|
||||
val url: String, val sha256: String, val size: Long, val notes: String,
|
||||
/** For an appimage: the icon name and menu category of its .desktop entry. */
|
||||
val icon: String, val category: String,
|
||||
)
|
||||
|
||||
fun fetch(): List<Entry>? {
|
||||
val body = Downloader.downloadString(CATALOG_URL) ?: return null
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val arr = json.getJSONArray("packages")
|
||||
(0 until arr.length()).map { i ->
|
||||
val o = arr.getJSONObject(i)
|
||||
Entry(
|
||||
o.getString("id"), o.getString("name"), o.optInt("tier", 1), o.optString("version", ""),
|
||||
o.optString("kind", "tar"), o.getString("url"), o.optString("sha256", ""),
|
||||
o.optLong("size", 0L), o.optString("notes", ""),
|
||||
o.optString("icon", "applications-games"), o.optString("category", "Game"),
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "catalog: $e"); null
|
||||
}
|
||||
}
|
||||
|
||||
private fun marker(context: Context, id: String) = File(LinuxRuntime.rootDir(context), ".droiddeck-pkg-$id")
|
||||
|
||||
/** The installed version of a package, or null. */
|
||||
fun installed(context: Context, id: String): String? =
|
||||
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
// labwc comes with the hosted desktop package itself (its launcher is staged by the app at
|
||||
// every session, so it cannot tell whether the package is there); SessionFiles uses the same test.
|
||||
fun desktopInstalled(context: Context): Boolean =
|
||||
File(LinuxRuntime.rootDir(context), "usr/bin/labwc").isFile
|
||||
|
||||
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!root.isDirectory) return "The Linux runtime is not installed"
|
||||
val download = File(context.cacheDir, "pkg-${entry.id}.download")
|
||||
try {
|
||||
listener?.onProgress("Downloading ${entry.name}", 0)
|
||||
val ok = Downloader.downloadFile(entry.url, download, true) { f ->
|
||||
listener?.onProgress("Downloading ${entry.name}", if (f < 0) -1 else Math.round(f * 100f))
|
||||
}
|
||||
if (!ok) return "Download failed"
|
||||
if (entry.sha256.isNotEmpty()) {
|
||||
listener?.onProgress("Verifying", -1)
|
||||
val actual = LinuxRuntimeInstaller.sha256(download)
|
||||
if (!entry.sha256.equals(actual, ignoreCase = true)) return "Checksum mismatch - nothing was changed"
|
||||
}
|
||||
listener?.onProgress("Installing ${entry.name}", -1)
|
||||
when (entry.kind) {
|
||||
"appimage" -> {
|
||||
val dir = File(root, "opt/appimages").apply { mkdirs() }
|
||||
val target = File(dir, "${entry.id}.AppImage")
|
||||
// Some projects zip the AppImage (melonDS); the one file inside is what we want.
|
||||
val placed = if (entry.url.endsWith(".zip", ignoreCase = true)) unzipAppImage(download, target)
|
||||
else download.renameTo(target)
|
||||
if (!placed) return "Could not place the AppImage"
|
||||
target.setExecutable(true, false)
|
||||
FileUtils.writeString(File(root, "usr/share/applications/droiddeck-${entry.id}.desktop"),
|
||||
"[Desktop Entry]\nType=Application\nName=${entry.name}\n" +
|
||||
"Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/${entry.id}.AppImage\n" +
|
||||
"Icon=${entry.icon}\nTerminal=false\nCategories=${entry.category};\n")
|
||||
}
|
||||
else -> if (!LinuxRuntimeInstaller.extract(download, root, listener)) return "Extraction failed"
|
||||
}
|
||||
FileUtils.writeString(marker(context, entry.id), entry.version)
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "install ${entry.id}", e)
|
||||
return e.message ?: "Install failed"
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun unzipAppImage(zip: File, target: File): Boolean {
|
||||
try {
|
||||
java.util.zip.ZipInputStream(java.io.BufferedInputStream(java.io.FileInputStream(zip))).use { zin ->
|
||||
var entry = zin.nextEntry
|
||||
while (entry != null) {
|
||||
if (!entry.isDirectory && entry.name.endsWith(".AppImage", ignoreCase = true)) {
|
||||
java.io.FileOutputStream(target).use { out -> FileUtils.copy(zin, out) }
|
||||
return true
|
||||
}
|
||||
entry = zin.nextEntry
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "unzip ${zip.name}", e)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an appimage package outright. A tar package is spread through the rootfs and is
|
||||
* not tracked file by file; only its marker is dropped, which offers it again.
|
||||
*/
|
||||
fun remove(context: Context, entry: Entry) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (entry.kind == "appimage") {
|
||||
File(root, "opt/appimages/${entry.id}.AppImage").delete()
|
||||
File(root, "usr/share/applications/droiddeck-${entry.id}.desktop").delete()
|
||||
}
|
||||
marker(context, entry.id).delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
|
||||
/**
|
||||
* The device's network link, published for the Linux runtime's processes.
|
||||
*
|
||||
* Android denies an app the rtnetlink dump behind getifaddrs() and if_nameindex(), the hardware
|
||||
* address ioctl and every table under /proc/net. Wine builds its adapter, address, route and
|
||||
* neighbour tables from those, so a game under the runtime saw no adapter, no address, no gateway
|
||||
* and no MAC - and one that checks its adapters before going online waited for good. The link the
|
||||
* app can see through ConnectivityManager is written here, kept current while the session runs,
|
||||
* and the session shim answers whatever the kernel refuses from it (tools/linuxfs/preload/netif.c).
|
||||
*
|
||||
* Shape follows WinNative's LinuxNetworkLinkComponent (maxjivi05, f76a5c4a), GPL-3.0.
|
||||
*/
|
||||
class LinuxNetworkLinkComponent(
|
||||
context: Context,
|
||||
private val rootDir: File,
|
||||
) : SessionPart() {
|
||||
private val appContext = context.applicationContext
|
||||
private val connectivity =
|
||||
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
private val lock = Any()
|
||||
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||
|
||||
/** Called before the session starts, so its first process already sees the link. */
|
||||
fun publish() = write(connectivity.activeNetwork?.let(connectivity::getLinkProperties))
|
||||
|
||||
override fun start() {
|
||||
val registered = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) = write(properties)
|
||||
override fun onLost(network: Network) = write(null)
|
||||
}
|
||||
synchronized(lock) { callback = registered }
|
||||
connectivity.registerDefaultNetworkCallback(registered)
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
val registered = synchronized(lock) { callback.also { callback = null } } ?: return
|
||||
try {
|
||||
connectivity.unregisterNetworkCallback(registered)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.w(TAG, "Network callback was already gone", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(properties: LinkProperties?) {
|
||||
val file = File(rootDir, LINK_FILE)
|
||||
synchronized(lock) {
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
val staged = File(file.path + ".staged")
|
||||
staged.writeText(describe(properties))
|
||||
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not publish the network link", e)
|
||||
}
|
||||
writeResolver(properties)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's resolver, from the network it is actually on. glibc reads /etc/resolv.conf,
|
||||
* and the image ships two public servers there, which is why Steam resolves at all - but a
|
||||
* captive portal, a private-DNS network or a v6-only carrier wants the network's own
|
||||
* servers. Those come first, IPv4 before IPv6 and never a link-local one (Android lists
|
||||
* fe80:: resolvers a guest cannot reach; handing Bannerlator's Wine guests exactly that was
|
||||
* the Pale Moon "no internet"). The public ones stay as fallback so nothing is ever worse
|
||||
* than the image was.
|
||||
*/
|
||||
private fun writeResolver(properties: LinkProperties?) {
|
||||
val own = properties?.dnsServers.orEmpty()
|
||||
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
|
||||
.sortedBy { if (it is Inet4Address) 0 else 1 }
|
||||
.mapNotNull { it.hostAddress?.substringBefore('%') }
|
||||
val servers = (own + listOf("8.8.8.8", "1.1.1.1", "2001:4860:4860::8888")).distinct().take(6)
|
||||
val text = buildString {
|
||||
append("# Written by the app from the device's active network; edits are overwritten.\n")
|
||||
for (server in servers) append("nameserver $server\n")
|
||||
append("options timeout:2 attempts:2\n")
|
||||
}
|
||||
try {
|
||||
val etc = File(rootDir, "etc")
|
||||
val staged = File(etc, "resolv.conf.staged")
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(File(etc, "resolv.conf"))) throw IOException("Could not replace resolv.conf")
|
||||
val hosts = File(etc, "hosts")
|
||||
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
|
||||
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
|
||||
}
|
||||
Log.i(TAG, "resolver: " + servers.joinToString(" "))
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "Could not write the resolver", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun describe(properties: LinkProperties?): String {
|
||||
val addresses = properties?.linkAddresses.orEmpty()
|
||||
.filter { it.address is Inet4Address || it.address is Inet6Address }
|
||||
val name = properties?.interfaceName?.takeIf { addresses.isNotEmpty() } ?: OFFLINE_NAME
|
||||
val mtu = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) properties?.mtu ?: 0 else 0
|
||||
return buildString {
|
||||
append("if $name $LINK_INDEX ${if (mtu > 0) mtu else DEFAULT_MTU}\n")
|
||||
append("mac ${seededMac()}\n")
|
||||
if (addresses.isEmpty()) {
|
||||
append("addr $OFFLINE_ADDRESS\n")
|
||||
return@buildString
|
||||
}
|
||||
for (address in addresses) {
|
||||
append("addr ${address.address.hostAddress?.substringBefore('%')} ${address.prefixLength}\n")
|
||||
}
|
||||
for (family in listOf(Inet4Address::class.java, Inet6Address::class.java)) {
|
||||
val gateway = properties?.routes.orEmpty()
|
||||
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
|
||||
?.gateway ?: continue
|
||||
append("gw ${gateway.hostAddress?.substringBefore('%')}\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A stable, locally administered address for this device. Android hides the real one, and a
|
||||
* title should see the same hardware identity every session.
|
||||
*/
|
||||
private fun seededMac(): String {
|
||||
val id = Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) ?: "bannerlator"
|
||||
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
|
||||
val b0 = (bytes[0].toInt() and 0xfc) or 0x02
|
||||
return listOf(b0, bytes[1].toInt(), bytes[2].toInt(), bytes[3].toInt(), bytes[4].toInt(), bytes[5].toInt())
|
||||
.joinToString(":") { "%02x".format(it and 0xff) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "LinuxNetworkLink"
|
||||
private const val LINK_FILE = "etc/bannerlator-net"
|
||||
private const val LINK_INDEX = 2
|
||||
private const val DEFAULT_MTU = 1500
|
||||
private const val OFFLINE_NAME = "eth0"
|
||||
private const val OFFLINE_ADDRESS = "10.0.0.2 24"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.droiddeck.launcher.runtime;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The glibc arm64 rootfs at {@code files/linuxfs} and the proot invocation that runs a program in
|
||||
* it as this app's own uid. It is a second runtime beside the Wine imagefs, not a container: no
|
||||
* Wine, no box64, no FEX. proot is packaged as {@code libproot.so} so the installer places it, with
|
||||
* its loader, in the native library directory - the only place an app on targetSdk 28 may execute
|
||||
* a file from.
|
||||
*
|
||||
* <p>Ported from WinNative's gamescope runtime (GPL-3.0).
|
||||
*/
|
||||
public final class LinuxRuntime {
|
||||
public static final String DIR = "linuxfs";
|
||||
public static final String SESSION_SCRIPT = "/usr/local/bin/bannerlator-session";
|
||||
public static final String MODE_DESKTOP = "desktop";
|
||||
public static final String MODE_STEAM = "steam";
|
||||
public static final String MODE_RUN = "run";
|
||||
/** Shortcut extra naming which of the modes above a Linux entry launches. */
|
||||
public static final String EXTRA_LINUX_MODE = "linux_mode";
|
||||
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
|
||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
|
||||
public static File debugLogDir() {
|
||||
return new File(android.os.Environment.getExternalStoragePublicDirectory(
|
||||
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
|
||||
}
|
||||
|
||||
private LinuxRuntime() {}
|
||||
|
||||
public static File rootDir(Context context) {
|
||||
return new File(context.getFilesDir(), DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's own small tree beside the rootfs: the fake evdev nodes and their rings. In
|
||||
* Bannerlator these lived in the Wine imagefs; here there is no Wine, so the session owns them.
|
||||
* Bound into the guest at its own host path, so nothing needs translating.
|
||||
*/
|
||||
public static File sessionRoot(Context context) {
|
||||
return new File(context.getFilesDir(), "session");
|
||||
}
|
||||
|
||||
/** Where the runtime carries the host-side proot; see tools/linuxfs/prebuilt/proot/README.md. */
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
|
||||
/**
|
||||
* proot, preferred from the installed runtime and falling back to the copy in the apk.
|
||||
*
|
||||
* <p>It is an Android binary rather than part of the rootfs - it is what creates the rootfs -
|
||||
* but it travels in the runtime tarball so that reinstalling the app cannot replace the one
|
||||
* binary everything else depends on, and so a device with no working packaged proot can still
|
||||
* run the runtime.
|
||||
*/
|
||||
public static File prootBinary(Context context) {
|
||||
File shipped = new File(rootDir(context), HOST_DIR + "/proot");
|
||||
if (shipped.isFile()) return shipped;
|
||||
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot.so");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
File shipped = new File(rootDir(context), HOST_DIR + "/loader");
|
||||
if (shipped.isFile()) return shipped;
|
||||
return new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
|
||||
}
|
||||
|
||||
/** proot links against libtalloc, which sits beside it; empty when the apk copy is in use. */
|
||||
public static String prootLibraryPath(Context context) {
|
||||
File dir = new File(rootDir(context), HOST_DIR);
|
||||
return new File(dir, "proot").isFile() ? dir.getPath() : "";
|
||||
}
|
||||
|
||||
/** The rootfs is present with gamescope and the session script the launcher hands control to. */
|
||||
public static boolean isInstalled(Context context) {
|
||||
File root = rootDir(context);
|
||||
return new File(root, "usr/bin/gamescope").isFile()
|
||||
&& new File(root, SESSION_SCRIPT.substring(1)).isFile()
|
||||
&& prootBinary(context).isFile()
|
||||
&& prootLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** The Vulkan ICD manifest the rootfs ships for the device GPU, or null when it has none. */
|
||||
public static File vulkanIcd(Context context) {
|
||||
File icdDir = new File(rootDir(context), "usr/share/vulkan/icd.d");
|
||||
File[] manifests = icdDir.listFiles((dir, name) -> name.endsWith(".json"));
|
||||
if (manifests == null) return null;
|
||||
for (File manifest : manifests) {
|
||||
if (manifest.getName().contains("freedreno")) return manifest;
|
||||
}
|
||||
return manifests.length > 0 ? manifests[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The proot command line running {@code guestCommand} inside the rootfs. Host paths the session
|
||||
* needs - the app's files directory for the compositor and audio sockets, external storage for
|
||||
* the user's games - are bound at their own paths, so nothing on either side needs translating
|
||||
* and proot never touches the fds a dma-buf travels in. Android has no /dev/shm; a directory
|
||||
* under the cache stands in, which glibc's shm_open and Chromium's shared memory accept.
|
||||
*/
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> guestCommand) {
|
||||
return command(context, sessionRoot, runtimeDir, externalStorage, null, guestCommand);
|
||||
}
|
||||
|
||||
/** As above, plus {@code host:guest} bind specs - the installed games handed to Steam. */
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand) {
|
||||
File root = rootDir(context);
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(prootBinary(context).getPath());
|
||||
cmd.add("--kill-on-exit");
|
||||
// Android's app seccomp policy traps the whole set*id family. Xwayland's Popen() calls
|
||||
// setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without
|
||||
// this the keymap never compiles and Xwayland dies. -i makes proot answer those calls
|
||||
// itself while still reporting our real ids, so nothing inside sees a different user.
|
||||
int uid = Process.myUid();
|
||||
cmd.add("-i");
|
||||
cmd.add(uid + ":" + uid);
|
||||
cmd.add("-r");
|
||||
cmd.add(root.getPath());
|
||||
cmd.add("-w");
|
||||
cmd.add("/root");
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
bind(cmd, "/sys");
|
||||
bind(cmd, "/dev/urandom:/dev/random");
|
||||
bind(cmd, "/proc/self/fd:/dev/fd");
|
||||
bind(cmd, "/proc/self/fd/0:/dev/stdin");
|
||||
bind(cmd, "/proc/self/fd/1:/dev/stdout");
|
||||
bind(cmd, "/proc/self/fd/2:/dev/stderr");
|
||||
bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux");
|
||||
bind(cmd, context.getFilesDir().getPath());
|
||||
bind(cmd, context.getCacheDir().getPath());
|
||||
bind(cmd, runtimeDir.getPath());
|
||||
if (sessionRoot != null) bind(cmd, sessionRoot.getPath());
|
||||
if (externalStorage != null && externalStorage.isDirectory()) {
|
||||
bind(cmd, externalStorage.getPath());
|
||||
}
|
||||
File shm = new File(context.getCacheDir(), "shm");
|
||||
shm.mkdirs();
|
||||
bind(cmd, shm.getPath() + ":/dev/shm");
|
||||
|
||||
// Android denies apps these; glibc, Steam and libcap read them at startup.
|
||||
File fakeProc = new File(root, "etc/bannerlator/proc");
|
||||
// libpci picks its procfs backend on whether it can read the /proc/bus/pci directory, which
|
||||
// the app can, then die()s - exit(1) on the calling process - on the devices file inside
|
||||
// it, which the app cannot. Chromium loads libpci in its GPU process to name the video
|
||||
// card, so that exit kills the process; after a few tries CEF gives up on hardware and
|
||||
// draws the rest of the session on SwiftShader: the client's interface rendered on the
|
||||
// CPU. An empty list is the truthful answer from in here - nothing the app can see is on
|
||||
// a PCI bus. Created at session start rather than shipped in the rootfs so an installed
|
||||
// runtime is fixed too, and the table's guard below binds it only when the real file
|
||||
// cannot be read, so it can never stand in front of real data. (WinNative, maxjivi05,
|
||||
// deff1ac6, via Bannerlator 8fb668d1: 44 -> 85 fps scrolling the Big Picture library on a
|
||||
// OnePlus 15, GPU-process crashes 12 -> 0.)
|
||||
File pciDevices = new File(fakeProc, "pci_devices");
|
||||
if (!pciDevices.isFile()) {
|
||||
try {
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
pciDevices.getParentFile().mkdirs();
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
pciDevices.createNewFile();
|
||||
} catch (java.io.IOException e) {
|
||||
// It then fails the isFile() test below and the session runs as it did before.
|
||||
}
|
||||
}
|
||||
String[][] procFiles = {
|
||||
{"pci_devices", "/proc/bus/pci/devices"},
|
||||
{"stat", "/proc/stat"},
|
||||
{"version", "/proc/version"},
|
||||
{"loadavg", "/proc/loadavg"},
|
||||
{"uptime", "/proc/uptime"},
|
||||
{"vmstat", "/proc/vmstat"},
|
||||
{"cap_last_cap", "/proc/sys/kernel/cap_last_cap"},
|
||||
{"overflowuid", "/proc/sys/kernel/overflowuid"},
|
||||
{"overflowgid", "/proc/sys/kernel/overflowgid"},
|
||||
};
|
||||
for (String[] entry : procFiles) {
|
||||
File fake = new File(fakeProc, entry[0]);
|
||||
if (fake.isFile() && !new File(entry[1]).canRead()) {
|
||||
bind(cmd, fake.getPath() + ":" + entry[1]);
|
||||
}
|
||||
}
|
||||
bindGpuNode(context, cmd);
|
||||
if (extraBinds != null) {
|
||||
for (String spec : extraBinds) bind(cmd, spec);
|
||||
}
|
||||
cmd.addAll(guestCommand);
|
||||
return cmd;
|
||||
}
|
||||
|
||||
/**
|
||||
* An app process may not open {@code /dev/dri} - the nodes exist but are labelled
|
||||
* {@code graphics_device}, which stock policy grants surfaceflinger and not us - yet libdrm and
|
||||
* everything built on it identify a GPU by its render node, and gamescope refuses to offer
|
||||
* linux-dmabuf without one. The KGSL device Turnip actually drives ({@code gpu_device}, which we
|
||||
* may open) stands in: it appears as a render node with the sysfs entries libdrm reads, and our
|
||||
* Turnip build reports the same device numbers for it.
|
||||
*/
|
||||
private static void bindGpuNode(Context context, List<String> cmd) {
|
||||
StructStat st;
|
||||
try {
|
||||
st = Os.stat(KGSL_DEVICE);
|
||||
} catch (ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
long dev = st.st_rdev;
|
||||
long major = ((dev >> 8) & 0xfff) | ((dev >> 32) & ~0xfffL);
|
||||
long minor = (dev & 0xff) | ((dev >> 12) & ~0xffL);
|
||||
String node = "renderD" + minor;
|
||||
File base = new File(context.getCacheDir(), "drm");
|
||||
File dri = new File(base, "dri");
|
||||
File device = new File(base, "sys/" + major + ":" + minor + "/device");
|
||||
File drm = new File(device, "drm/" + node);
|
||||
try {
|
||||
if ((!dri.isDirectory() && !dri.mkdirs()) || (!drm.isDirectory() && !drm.mkdirs())) {
|
||||
return;
|
||||
}
|
||||
new File(dri, node).createNewFile();
|
||||
Files.write(new File(drm, "dev").toPath(),
|
||||
(major + ":" + minor + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
Files.write(new File(device, "uevent").toPath(),
|
||||
"DRIVER=kgsl-3d0\nMODALIAS=platform:kgsl-3d0\n".getBytes(StandardCharsets.UTF_8));
|
||||
File subsystem = new File(device, "subsystem");
|
||||
if (!Files.isSymbolicLink(subsystem.toPath())) {
|
||||
Os.symlink("/sys/bus/platform", subsystem.getPath());
|
||||
}
|
||||
} catch (IOException | ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
|
||||
bind(cmd, dri.getPath() + ":/dev/dri");
|
||||
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
|
||||
}
|
||||
|
||||
private static void bind(List<String> cmd, String spec) {
|
||||
cmd.add("-b");
|
||||
cmd.add(spec);
|
||||
}
|
||||
|
||||
/** X access control and Steam look the session user up by uid: the app uid is root inside. */
|
||||
public static void writeAccounts(Context context) throws IOException {
|
||||
File root = rootDir(context);
|
||||
int uid = Process.myUid();
|
||||
Files.write(new File(root, "etc/passwd").toPath(),
|
||||
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
|
||||
Files.write(new File(root, "etc/group").toPath(),
|
||||
("root:x:" + uid + ":\n").getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package com.droiddeck.launcher.runtime;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
import com.droiddeck.launcher.core.Downloader;
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Downloads and unpacks the Linux runtime rootfs into {@code files/linuxfs}. It is opt-in: nothing
|
||||
* fetches it until the user asks for it, and a gamescope session refuses to start without it.
|
||||
*
|
||||
* <p>The catalog row names the build, its URL and its sha256, so an interrupted or corrupted
|
||||
* download is caught before anything is written into the app's files directory.
|
||||
*/
|
||||
public final class LinuxRuntimeInstaller {
|
||||
private static final String TAG = "LinuxRuntimeInstaller";
|
||||
|
||||
/** Catalog row, beside the other component catalogs in winlator-contents. */
|
||||
public static final String CATALOG_URL =
|
||||
"https://raw.githubusercontent.com/The412Banner/winlator-contents/main/linuxfs.json";
|
||||
|
||||
private static final String VERSION_FILE = ".version";
|
||||
|
||||
public interface ProgressListener {
|
||||
/** {@code percent} is -1 while the size is unknown. */
|
||||
void onProgress(String stage, int percent);
|
||||
}
|
||||
|
||||
public static final class Release {
|
||||
public final String version;
|
||||
public final String url;
|
||||
public final String sha256;
|
||||
public final long size;
|
||||
|
||||
Release(String version, String url, String sha256, long size) {
|
||||
this.version = version;
|
||||
this.url = url;
|
||||
this.sha256 = sha256;
|
||||
this.size = size;
|
||||
}
|
||||
}
|
||||
|
||||
private LinuxRuntimeInstaller() {}
|
||||
|
||||
/** The build currently unpacked, or null when the runtime is not installed. */
|
||||
public static String installedVersion(Context context) {
|
||||
File marker = new File(LinuxRuntime.rootDir(context), VERSION_FILE);
|
||||
if (!marker.isFile() || !LinuxRuntime.isInstalled(context)) return null;
|
||||
String v = FileUtils.readString(marker);
|
||||
return v == null ? null : v.trim();
|
||||
}
|
||||
|
||||
/** The catalog's current build, or null when it cannot be reached or read. */
|
||||
public static Release fetchRelease() {
|
||||
String body = Downloader.downloadString(CATALOG_URL);
|
||||
if (body == null || body.isEmpty()) return null;
|
||||
try {
|
||||
JSONObject json = new JSONObject(body);
|
||||
String version = json.optString("version", "");
|
||||
String url = json.optString("url", "");
|
||||
String sha256 = json.optString("sha256", "");
|
||||
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null;
|
||||
return new Release(version, url, sha256, json.optLong("size", 0L));
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "catalog: " + e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's home directory, carried across an update rather than replaced with the tarball's
|
||||
* empty one. Steam installs itself here - the client, the signed-in account and every
|
||||
* downloaded game - so replacing the rootfs wholesale used to delete all three and leave the
|
||||
* user re-downloading Steam and signing in again, with their library gone.
|
||||
*/
|
||||
private static final String USER_DATA = "root";
|
||||
|
||||
/**
|
||||
* Downloads {@code release} and replaces whatever is installed with it. Returns false and
|
||||
* leaves the existing runtime alone if the download or the checksum fails; the new rootfs is
|
||||
* only moved into place once it has been unpacked whole.
|
||||
*
|
||||
* <p>{@link #USER_DATA} survives the swap: the system is replaced, what the user put in it is
|
||||
* not. An update therefore keeps Steam, the login and the installed games.
|
||||
*/
|
||||
public static boolean install(Context context, Release release, ProgressListener listener) {
|
||||
File archive = new File(context.getCacheDir(), "linuxfs.tar.zst");
|
||||
try {
|
||||
if (listener != null) listener.onProgress("Downloading", 0);
|
||||
// Downloader reports a 0..1 fraction, or -1 while the total size is unknown.
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, (fraction) -> {
|
||||
if (listener != null) {
|
||||
listener.onProgress("Downloading",
|
||||
fraction < 0 ? -1 : Math.round(fraction * 100f));
|
||||
}
|
||||
});
|
||||
if (!ok) {
|
||||
Log.w(TAG, "download failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (listener != null) listener.onProgress("Verifying", -1);
|
||||
String actual = sha256(archive);
|
||||
if (!release.sha256.equalsIgnoreCase(actual)) {
|
||||
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unpack beside the live rootfs and swap, so a failure here cannot leave a half
|
||||
// runtime that isInstalled() would happily launch.
|
||||
File root = LinuxRuntime.rootDir(context);
|
||||
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
|
||||
FileUtils.delete(staging);
|
||||
if (!staging.mkdirs()) return false;
|
||||
if (listener != null) listener.onProgress("Extracting", -1);
|
||||
if (!extract(archive, staging, listener)) {
|
||||
FileUtils.delete(staging);
|
||||
return false;
|
||||
}
|
||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||
|
||||
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
|
||||
FileUtils.delete(old);
|
||||
if (root.isDirectory() && !root.renameTo(old)) {
|
||||
FileUtils.delete(staging);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Carry the user's home over before the new rootfs takes the name. A rename inside the
|
||||
// same filesystem, so a 30 GB library costs nothing and cannot half-copy; the tarball's
|
||||
// own empty /root is dropped first so the rename has somewhere to land. If this fails
|
||||
// the update is abandoned and the previous runtime is put back untouched - shipping a
|
||||
// working system with the user's games gone is the worse outcome.
|
||||
File keptFrom = new File(old, USER_DATA);
|
||||
if (keptFrom.isDirectory()) {
|
||||
File keptTo = new File(staging, USER_DATA);
|
||||
FileUtils.delete(keptTo);
|
||||
if (!keptFrom.renameTo(keptTo)) {
|
||||
Log.w(TAG, "could not carry " + USER_DATA + " across the update; rolling back");
|
||||
FileUtils.delete(staging);
|
||||
old.renameTo(root);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!staging.renameTo(root)) {
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
return false;
|
||||
}
|
||||
FileUtils.delete(old);
|
||||
return LinuxRuntime.isInstalled(context);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "install", e);
|
||||
return false;
|
||||
} finally {
|
||||
archive.delete();
|
||||
}
|
||||
}
|
||||
|
||||
public static void uninstall(Context context) {
|
||||
FileUtils.delete(LinuxRuntime.rootDir(context));
|
||||
}
|
||||
|
||||
/**
|
||||
* A whole-rootfs tar, which is not the shape the shared extractor handles: a distribution
|
||||
* rootfs is full of hard links (one binary under several names), and an entry written as an
|
||||
* empty file instead of its link target is a rootfs that boots to nothing. Symlinks, hard
|
||||
* links and the executable bit are all carried over here.
|
||||
*/
|
||||
public static boolean extract(File archive, File destination, ProgressListener listener) {
|
||||
long entries = 0;
|
||||
try (InputStream in = new ZstdCompressorInputStream(
|
||||
new BufferedInputStream(new FileInputStream(archive), 1 << 16));
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||
TarArchiveEntry entry;
|
||||
String base = destination.getCanonicalPath() + File.separator;
|
||||
while ((entry = tar.getNextTarEntry()) != null) {
|
||||
File file = new File(destination, entry.getName());
|
||||
// Refuse anything that would land outside the runtime directory.
|
||||
if (!(file.getCanonicalPath() + (entry.isDirectory() ? File.separator : "")).startsWith(base)
|
||||
&& !file.getCanonicalPath().equals(destination.getCanonicalPath())) {
|
||||
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
|
||||
continue;
|
||||
}
|
||||
if (entry.isDirectory()) {
|
||||
file.mkdirs();
|
||||
continue;
|
||||
}
|
||||
File parent = file.getParentFile();
|
||||
if (parent != null && !parent.isDirectory()) parent.mkdirs();
|
||||
|
||||
if (entry.isSymbolicLink()) {
|
||||
file.delete();
|
||||
FileUtils.symlink(entry.getLinkName(), file.getAbsolutePath());
|
||||
} else if (entry.isLink()) {
|
||||
// A hard link to an earlier entry. Link where the filesystem allows it and
|
||||
// fall back to a copy, which costs space but always works.
|
||||
File target = new File(destination, entry.getLinkName());
|
||||
file.delete();
|
||||
try {
|
||||
Files.createLink(file.toPath(), target.toPath());
|
||||
} catch (IOException | UnsupportedOperationException e) {
|
||||
if (target.isFile()) {
|
||||
Files.copy(target.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
try (OutputStream out = new FileOutputStream(file)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
int read;
|
||||
while ((read = tar.read(buffer)) != -1) out.write(buffer, 0, read);
|
||||
}
|
||||
if ((entry.getMode() & 0111) != 0) file.setExecutable(true, false);
|
||||
} else {
|
||||
continue; // device nodes and fifos: the runtime binds the real ones
|
||||
}
|
||||
if (++entries % 2000 == 0 && listener != null) {
|
||||
listener.onProgress("Extracting", -1);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "extract", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String sha256(File file) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(file), 1 << 16)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) != -1) digest.update(buffer, 0, read);
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : digest.digest()) sb.append(String.format("%02x", b));
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user