diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index f5a01d984d..c68ecd3ba1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -25,6 +25,10 @@ object ProtonExtras { var installInProgress = false @Volatile var prefetching = false private set + @Volatile private var checkedArchive: Triple? = null + @Volatile private var checkedDigest: String? = null + + private fun fingerprint(archive: File) = Triple(archive.path, archive.length(), archive.lastModified()) @Volatile private var replacing = false @@ -259,7 +263,10 @@ object ProtonExtras { if (asset.size > 0 && archive.length() > asset.size) archive.delete() val missing = (asset.size - archive.length()).coerceAtLeast(0L) if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name) - return fetchArchive(context, tool, asset, archive, onProgress) + val problem = fetchArchive(context, tool, asset, archive, onProgress) + checkedArchive = if (problem == null && asset.sha256 != null && asset.size > 0 && archive.length() == asset.size) fingerprint(archive) else null + checkedDigest = if (checkedArchive != null) asset.sha256 else null + return problem } private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { @@ -275,7 +282,9 @@ object ProtonExtras { return context.getString(R.string.pextra_no_space, tool.name) } - fetchArchive(context, tool, asset, archive, onProgress)?.let { return it } + val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) && + checkedDigest.equals(asset.sha256, ignoreCase = true) + if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it } if (asset.size > 0 && archive.length() != asset.size) { if (archive.length() > asset.size) { archive.delete() @@ -286,6 +295,7 @@ object ProtonExtras { onProgress(context.getString(R.string.pextra_verifying), -1) val verified = when { + checked -> true asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true) asset.sha512 != null -> { val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 9ec5f5cba4..101e413933 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -130,6 +130,7 @@ object SessionFiles { "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", + "usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply", "usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale", "usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language", "usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt index 66db50355a..8f96cf7a4e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -71,11 +71,9 @@ object SteamClientPrefetch { LinuxRuntime.writeAccounts(context) SessionFiles.stage(context, root) val install = installPending(context) - if (install) { - val problem = script(context, emptyList(), label, 0, 35) - if (problem != null) return problem - } - return script(context, listOf("--cache"), label, if (install) 35 else 0, 100) + val cacheProblem = script(context, listOf("--cache"), label, 0, if (install) 90 else 100) + if (cacheProblem == CANCELLED || !install) return cacheProblem + return script(context, emptyList(), label, 90, 100) } private fun script(context: Context, args: List, label: (Int) -> String, from: Int, to: Int): String? { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index 1578b24042..bbacb7652f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -66,6 +66,7 @@ if [ -n "$repair" ]; then done fi cache_only= +applied= [ "${1:-}" = --cache ] && cache_only=1 sync= if [ "${1:-}" = --sync ]; then @@ -360,8 +361,24 @@ if [ -n "$cache_only" ]; then done_bytes=$((done_bytes + size)) done < "$work/cache" fi + applier= + trap 'kill "$applier" 2>/dev/null || :; wait "$applier" 2>/dev/null || :; rm -f "$cache/$manifest.installed" "$cached"; exit 143' TERM INT HUP echo "$version" > "$cached" - exit 0 + preapply=${DD_STEAM_PREAPPLY:-/usr/local/bin/droiddeck-steam-preapply} + if [ -x "$preapply" ] && command -v python3 >/dev/null 2>&1; then + python3 "$preapply" "$cache" "$steam_root" "$work/manifest" "$manifest" & + applier=$! + if wait "$applier"; then + cp -f "$work/manifest" "$cache/$manifest.manifest" + chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true + while read -r _ file _; do rm -f "$cache/$file"; done < "$work/cache" + [ -f "$stamp" ] || applied=1 + else + rm -f "$cache/$manifest.installed" "$cached" + fi + fi + trap - TERM INT HUP + [ -n "$applied" ] || exit 0 fi if [ -n "$sync" ]; then installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true) @@ -371,6 +388,7 @@ if [ -n "$sync" ]; then fi echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client" fi +if [ -z "$applied" ]; then total=$(grep -c . "$work/parts" 2>/dev/null || echo 0) total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/parts") @@ -406,6 +424,7 @@ while read -r block file sum size; do done_bytes=$((done_bytes + size)) done < "$work/parts" fi +fi find "$steam_root" -depth -name '*\\*' | while read -r odd; do fixed=${odd//\\//} mkdir -p "$(dirname "$fixed")" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply new file mode 100755 index 0000000000..841111af21 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Extract Steam's cached update packages and record them the way Steam's own updater does.""" +import hashlib, lzma, os, re, stat, struct, sys, time, zipfile, io, zlib, calendar + +OSVER = "-184" +MTIME_OFFSET = 28800 + + +def blocks(manifest): + out, cur, depth = {}, None, 0 + for line in manifest.splitlines(): + m = re.match(r'^(\t+)"([^"]+)"\s*(?:"([^"]*)")?\s*$', line) + if m and m.group(3) is None and len(m.group(1)) == 1: + cur = m.group(2) + out[cur] = {} + elif m and m.group(3) is not None and len(m.group(1)) == 2 and cur: + out[cur][m.group(2)] = m.group(3) + return out + + +def unvz(d): + if d[:3] != b"VZa" or d[-2:] != b"zv": + raise ValueError("not a VZip") + props = d[7] + dict_size = struct.unpack("> 16) & 0xFFFF + mtime = calendar.timegm(info.date_time + (0, 0, 0)) + MTIME_OFFSET + if rel.endswith("/"): + os.makedirs(dest, exist_ok=True) + rows[rel] = (-1, mtime, 0) + continue + os.makedirs(os.path.dirname(dest), exist_ok=True) + if stat.S_ISLNK(mode): + if os.path.lexists(dest): + os.unlink(dest) + os.symlink(z.read(info).decode(), dest) + rows[rel] = (-2, mtime, info.CRC) + continue + with open(dest + ".dd-tmp", "wb") as out: + out.write(z.read(info)) + os.chmod(dest + ".dd-tmp", (mode & 0o777) | 0o644 if mode else 0o644) + os.replace(dest + ".dd-tmp", dest) + rows[rel] = (info.file_size, mtime, info.CRC) + del zdata + body = "".join(f"{p},{s};{m};{c}\n" for p, (s, m, c) in sorted(rows.items(), key=lambda kv: kv[0].upper())) + body += f"OSVER={OSVER}\nVERSION=3\n" + sha = hashlib.sha1(body.encode()).hexdigest().upper() + pkg = os.path.join(steam_root, "package") + os.makedirs(pkg, exist_ok=True) + tmp = os.path.join(pkg, name + ".installed.dd-tmp") + with open(tmp, "w", encoding="utf-8") as f: + f.write(body + f"SHA1={sha}\n") + os.replace(tmp, os.path.join(pkg, name + ".installed")) + + +if __name__ == "__main__": + main(*sys.argv[1:5]) diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index 836372c29c..b575a81d22 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -359,6 +359,90 @@ done(28 if end < len(data) else 0) self.assertFalse((package / 'b.zip.9999').exists()) self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + PREAPPLY = SCRIPT.with_name('droiddeck-steam-preapply') + + def real_cache_manifest(self): + import io + out = io.BytesIO() + with zipfile.ZipFile(out, 'w') as z: + z.writestr('steamrtarm64/steam', b'client') + data = out.getvalue() + (self.cdn / 'a.zip.1111').write_bytes(data) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(data)}"\n\t\t"sha2" "{hashlib.sha256(data).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_applies_the_update_so_steam_has_nothing_to_extract(self): + self.real_cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + name = 'steam_client_steamdeck_publicbeta_linuxarm64' + self.assertEqual(b'client', (self.steam / 'steamrtarm64/steam').read_bytes()) + self.assertTrue(os.access(self.steam / 'steamrtarm64/steam', os.X_OK)) + self.assertIn('steamrtarm64/steam,6;', (package / (name + '.installed')).read_text()) + self.assertEqual((self.cdn / name).read_text(), (package / (name + '.manifest')).read_text()) + self.assertFalse((package / 'a.zip.1111').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + def test_an_applied_update_finishes_the_install_without_fetching_the_plain_packages_again(self): + self.real_cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual('123456\n', (package / 'droiddeck-installed').read_text()) + self.assertEqual('steamdeck_publicbeta\n', (package / 'beta').read_text()) + self.assertEqual((self.steam / 'linuxarm64').resolve(), (self.home / '.steam/sdkarm64').resolve()) + self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', 'a.zip.1111'], self.requested()) + again = self.install(None) + self.assertEqual(0, again.returncode, again.stderr) + self.assertEqual(2, len(self.requested())) + + def test_a_failed_apply_clears_the_cache_marker_and_the_old_record_so_it_is_retried(self): + self.real_cache_manifest() + package = self.steam / 'package' + package.mkdir(parents=True) + name = 'steam_client_steamdeck_publicbeta_linuxarm64' + (package / (name + '.installed')).write_text('old\n') + failing = self.root / 'failing-apply' + failing.write_text('import sys\nsys.exit(1)\n') + failing.chmod(0o755) + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(failing)) + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse((package / (name + '.installed')).exists()) + self.assertFalse((package / 'droiddeck-cached').exists()) + self.assertEqual((self.cdn / 'a.zip.1111').read_bytes(), (package / 'a.zip.1111').read_bytes()) + + def test_cancelling_the_cache_pass_stops_the_apply_helper(self): + self.real_cache_manifest() + pidfile = self.root / 'apply.pid' + slow = self.root / 'slow-apply' + slow.write_text(f'import os, time\nopen({str(pidfile)!r}, "w").write(str(os.getpid()))\ntime.sleep(30)\n') + slow.chmod(0o755) + process = subprocess.Popen(['bash', str(SCRIPT), '--cache'], env=dict(self.env, DD_STEAM_PREAPPLY=str(slow)), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(100): + if pidfile.exists() and pidfile.read_text().strip(): + break + time.sleep(0.1) + helper = int(pidfile.read_text()) + process.terminate() + process.wait(timeout=10) + time.sleep(0.3) + with self.assertRaises(ProcessLookupError): + os.kill(helper, 0) + self.assertFalse((self.steam / 'package/droiddeck-cached').exists()) + + def test_a_cache_pass_that_cannot_apply_the_update_keeps_the_packages_for_steam(self): + self.cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertFalse(list(package.glob('*.installed'))) + self.assertFalse(list(package.glob('*.manifest'))) + def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self): self.cache_manifest() self.assertEqual(0, self.install(None, '--cache').returncode) diff --git a/tools/tests/test_steam_preapply.py b/tools/tests/test_steam_preapply.py new file mode 100644 index 0000000000..9300b1bcce --- /dev/null +++ b/tools/tests/test_steam_preapply.py @@ -0,0 +1,157 @@ +import hashlib +import io +import lzma +from pathlib import Path +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import zipfile +import zlib + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply' +NAME = 'steam_client_steamdeck_publicbeta_linuxarm64' + + +def zip_bytes(entries): + out = io.BytesIO() + with zipfile.ZipFile(out, 'w') as z: + for name, data, mode, stamp in entries: + info = zipfile.ZipInfo(name, stamp) + info.external_attr = mode << 16 + z.writestr(info, data) + return out.getvalue() + + +def vzip(data): + packer = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[ + {'id': lzma.FILTER_LZMA1, 'dict_size': 1 << 20, 'lc': 3, 'lp': 0, 'pb': 2}]) + body = packer.compress(data) + packer.flush() + props = (2 * 5 + 0) * 9 + 3 + return (b'VZa' + b'\0\0\0\0' + bytes([props]) + struct.pack('