perf(steam): setup applies Steam's client update so the first launch has nothing to unpack (#3152)

* perf(steam): setup applies Steam's client update itself so the first launch has nothing to unpack

The setup already downloads every package of Steam's client update. droiddeck-steam-preapply now extracts them and writes the .installed and .manifest records the way Steam's updater does, so the first launch verifies and starts instead of unpacking for about half a minute and restarting. When it cannot, the packages stay and Steam updates itself as before.

* perf(setup): the Steam stage skips the plain packages it just applied, and Proton's install trusts the prefetch's checksum

With the whole client update applied from the cached packages, the separate 362 MB plain-package install is redundant: the cache pass applies the update and finishes the install, and the plain install stays as the fallback. DroidDeck Proton's archive was hashed twice more at install time after the prefetch had already verified it; the install now reuses that result while the file is unchanged.

* fix(steam): a failed or cancelled apply leaves nothing stale, extraction stays inside the Steam root, and a cache failure still installs

A failed apply removes its record and the cache marker so the next run retries; cancelling stops the helper; entries that leave the Steam root, directly or through a symlink, are refused; the plain install still runs when the cache pass fails; Proton's install reuses the prefetch's verification only for the same digest.

* fix(steam): a cancelled apply clears the cache marker too
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-24 15:18:41 -05:00
1 parent 9db80cebd9
commit 2e3b69e9ff
7 files changed
+369 -8

No files matched your search

@@ -25,6 +25,10 @@ object ProtonExtras {
var installInProgress = false
@Volatile var prefetching = false
private set
@Volatile private var checkedArchive: Triple<String, Long, Long>? = 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 }
@@ -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",
@@ -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<String>, label: (Int) -> String, from: Int, to: Int): String? {
@@ -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")"
@@ -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("<I", d[8:12])[0]
crc, size = struct.unpack("<II", d[-10:-2])
f = [{"id": lzma.FILTER_LZMA1, "dict_size": dict_size,
"lc": props % 9, "lp": (props // 9) % 5, "pb": props // 45}]
out = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=f).decompress(d[12:-10], max_length=size)
if len(out) != size or zlib.crc32(out) & 0xFFFFFFFF != crc:
raise ValueError("bad VZip")
return out
def inside(root, path):
return os.path.commonpath([root, path]) == root
def main(package_dir, steam_root, manifest_path, name):
steam_root = os.path.realpath(steam_root)
manifest = open(manifest_path, encoding="utf-8", errors="replace").read()
rows = {}
for block, attrs in blocks(manifest).items():
for key in ("zipvz", "file"):
f = attrs.get(key)
if f and os.path.isfile(os.path.join(package_dir, f)):
break
else:
raise SystemExit(f"missing package for {block}")
data = open(os.path.join(package_dir, f), "rb").read()
zdata = unvz(data) if key == "zipvz" else data
del data
with zipfile.ZipFile(io.BytesIO(zdata)) as z:
for info in z.infolist():
rel = info.filename.replace("\\", "/")
if rel.startswith("/") or ".." in rel.split("/"):
raise SystemExit(f"unsafe path in {block}: {rel}")
dest = os.path.join(steam_root, rel)
if not inside(steam_root, os.path.realpath(os.path.dirname(dest.rstrip("/")))):
raise SystemExit(f"path leaves the Steam root in {block}: {rel}")
mode = (info.external_attr >> 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])
+84
View File
@@ -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)
+157
View File
@@ -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('<I', 1 << 20) + body
+ struct.pack('<II', zlib.crc32(data) & 0xFFFFFFFF, len(data)) + b'zv')
class SteamPreapplyTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.packages = root / 'packages'
self.packages.mkdir()
self.steam = root / 'Steam'
self.manifest = root / 'manifest'
def write_manifest(self, blocks):
text = '"linuxarm64"\n{\n\t"version"\t\t"42"\n'
for block, attrs in blocks.items():
text += f'\t"{block}"\n\t{{\n'
for key, value in attrs.items():
text += f'\t\t"{key}"\t\t"{value}"\n'
text += '\t}\n'
self.manifest.write_text(text + '}\n')
def run_script(self):
return subprocess.run([sys.executable, '-I', str(SCRIPT), str(self.packages), str(self.steam),
str(self.manifest), NAME], text=True, capture_output=True)
def installed(self):
return (self.steam / 'package' / (NAME + '.installed')).read_text().split('\n')
def prepare(self):
stamp = (2025, 5, 17, 10, 30, 0)
plain = zip_bytes([
('bin/', b'', 0o40755, stamp),
('bin/Tool', b'tool', 0o100755, stamp),
('bin\\Backslash.txt', b'bs', 0o100644, stamp),
('lib/libx.so.1', b'libx', 0o100644, stamp),
('lib/libx.so', b'libx.so.1', 0o120777, stamp),
])
packed = zip_bytes([('data/z_file', b'zed', 0o100644, stamp), ('data/A_file', b'aaa', 0o100644, stamp)])
(self.packages / 'a.zip.1111').write_bytes(plain)
(self.packages / 'b.zip.vz.2222_14').write_bytes(vzip(packed))
self.write_manifest({
'a_all': {'file': 'a.zip.1111', 'size': len(plain), 'sha2': '00'},
'b_all': {'file': 'b.zip.9999', 'size': 99, 'sha2': '00', 'zipvz': 'b.zip.vz.2222_14', 'sha2vz': '00'},
})
def test_extracts_every_package_including_packed_ones(self):
self.prepare()
result = self.run_script()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(b'tool', (self.steam / 'bin/Tool').read_bytes())
self.assertTrue(os.access(self.steam / 'bin/Tool', os.X_OK))
self.assertEqual(b'bs', (self.steam / 'bin/Backslash.txt').read_bytes())
self.assertEqual('libx.so.1', os.readlink(self.steam / 'lib/libx.so'))
self.assertEqual(b'zed', (self.steam / 'data/z_file').read_bytes())
def test_records_what_steams_updater_records(self):
self.prepare()
self.assertEqual(0, self.run_script().returncode)
stamp = 1747477800 + 28800
crc = lambda data: zlib.crc32(data) & 0xFFFFFFFF
lines = self.installed()
self.assertEqual([
f'bin/,-1;{stamp};0',
f'bin/Backslash.txt,2;{stamp};{crc(b"bs")}',
f'bin/Tool,4;{stamp};{crc(b"tool")}',
f'data/A_file,3;{stamp};{crc(b"aaa")}',
f'data/z_file,3;{stamp};{crc(b"zed")}',
f'lib/libx.so,-2;{stamp};{crc(b"libx.so.1")}',
f'lib/libx.so.1,4;{stamp};{crc(b"libx")}',
'OSVER=-184',
'VERSION=3',
], lines[:-2])
body = ''.join(line + '\n' for line in lines[:-2])
self.assertEqual('SHA1=' + hashlib.sha1(body.encode()).hexdigest().upper(), lines[-2])
self.assertEqual('', lines[-1])
def test_a_missing_package_leaves_no_record_so_steam_extracts_for_itself(self):
self.prepare()
(self.packages / 'b.zip.vz.2222_14').unlink()
result = self.run_script()
self.assertNotEqual(0, result.returncode)
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
def test_a_corrupt_package_leaves_no_record(self):
self.prepare()
packed = (self.packages / 'b.zip.vz.2222_14').read_bytes()
(self.packages / 'b.zip.vz.2222_14').write_bytes(packed[:-12] + b'\0' * 12)
self.assertNotEqual(0, self.run_script().returncode)
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
def package_with(self, entries):
(self.packages / 'a.zip.1111').write_bytes(zip_bytes(entries))
self.write_manifest({'a_all': {'file': 'a.zip.1111', 'size': 1, 'sha2': '00'}})
def test_a_path_that_leaves_the_steam_root_is_refused(self):
stamp = (2025, 5, 17, 10, 30, 0)
for name in ('../outside', '/abs/outside', 'a/../../outside'):
with self.subTest(name=name):
self.package_with([(name, b'x', 0o100644, stamp)])
self.assertNotEqual(0, self.run_script().returncode)
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
self.assertFalse((Path(self.temp.name) / 'outside').exists())
def test_a_file_cannot_be_written_through_a_symlink_that_leaves_the_steam_root(self):
stamp = (2025, 5, 17, 10, 30, 0)
target = Path(self.temp.name) / 'elsewhere'
target.mkdir()
self.package_with([('link', str(target).encode(), 0o120777, stamp), ('link/file', b'x', 0o100644, stamp)])
self.assertNotEqual(0, self.run_script().returncode)
self.assertFalse((target / 'file').exists())
def test_a_symlink_inside_the_steam_root_still_carries_files(self):
stamp = (2025, 5, 17, 10, 30, 0)
self.package_with([('real/', b'', 0o40755, stamp), ('alias', b'real', 0o120777, stamp),
('alias/file', b'x', 0o100644, stamp)])
self.assertEqual(0, self.run_script().returncode)
self.assertEqual(b'x', (self.steam / 'real/file').read_bytes())
if __name__ == '__main__':
unittest.main()