Merge main (c298da6f) into feat/bionic-runtime

One conflict: .github/workflows/build.yml. This branch had a step that
fetched Robolectric's Android jars from a DroidDeck-CI release because
Maven Central answered the runners with HTTP 429; main now caches those
jars (#3127, #3134), so build.yml is main's again and this pull request
no longer changes it.

ProtonMenu, ProtonExtras, SessionService, SessionOverlay and
droiddeck-game-env merged cleanly; test_game_environment.py and
test_proton_extra.py pass (207 tests).
This commit is contained in:
The412Banner committed 2026-11-24 21:38:54 +00:00
commit cc5de0ba63
308 files changed
+14468 -3934

No files matched your search

@@ -1206,6 +1206,15 @@ def handle(agent_dir, req):
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
def reply(agent_dir, req):
try:
return dict(handle(agent_dir, req), ok=True)
except AgentError as e:
return {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
def answer(agent_dir, path):
rid = path.stem
try:
@@ -1225,12 +1234,7 @@ def answer(agent_dir, path):
except OSError:
pass
if req is not None:
try:
result = dict(handle(agent_dir, req), ok=True)
except AgentError as e:
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
result = reply(agent_dir, req)
write_json(agent_dir / "resp" / (rid + ".json"), result)
@@ -1257,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1):
def main(argv):
if argv and argv[0] == "--cdp-inspector":
if len(argv) != 4:
print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr)
return 2
print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2],
"expression": argv[3], "commandLineApi": True})))
return 0
base = os.environ.get("DD_LAUNCH_DIR")
if not base:
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
@@ -9,6 +9,40 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;;
esac
fi
if [ -n "${DDNATV_ROOT:-}" ]; then
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
fi
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
fi
if [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$image
exec /usr/local/lib/droiddeck/uruntime "$@"
@@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
export QT_QPA_PLATFORM=xcb
fi
arch=$(cat "$dir/arch" 2>/dev/null)
if [ "$arch" = arm64 ]; then
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
while IFS= read -r lib; do
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
done
fi
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("$APPDIR/AppRun")
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $fex:$(cat "$dir/arch" 2>/dev/null) in
case $fex:$arch in
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
auto:arm64) ;;
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
@@ -79,8 +79,7 @@ AGENT_START = 90
AGENT_HELPER = "agent.js"
AGENT_RUNTIME = "agent-runtime"
AGENT_LOG = "agent.log"
AGENT_LOG_LIMIT = 4 << 20
HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"]
HEADLESS = "/usr/local/bin/droiddeck-headless"
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
COUNTRY = re.compile(r"[A-Z]{3}")
@@ -1416,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
windows = install_path(root, folder)
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
os.makedirs(CACHE, exist_ok=True)
for suffix in (".json", ".game", ".form", ".error"):
try:
os.unlink(base + suffix)
except OSError:
pass
runtime = os.path.join(CACHE, AGENT_RUNTIME)
os.makedirs(runtime, mode=0o700, exist_ok=True)
env = agent_env()
for name in ("DISPLAY", "WAYLAND_DISPLAY"):
env.pop(name, None)
env["XDG_RUNTIME_DIR"] = runtime
cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--",
os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
output = os.path.join(CACHE, AGENT_LOG)
try:
if os.path.getsize(output) > AGENT_LOG_LIMIT:
os.replace(output, output + ".1")
except OSError:
pass
before = {pid for pid, _ in wine_processes(pfx)}
with open(output, "ab") as log:
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
seen = None
mark = None
moved = time.monotonic()
@@ -5,39 +5,17 @@ self=${BASH_SOURCE[0]}
proc=${DD_PROC:-/proc}
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless}
wait_s=${DD_CURSEFORGE_WAIT:-60}
cmd=${1:-}
dir=${2:-}
flag=--inspect-publish-uid=stderr
case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display <imported AppImage directory>" >&2; exit 2 ;; esac
if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then
case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac
if [ ! -d "$dir/app" ]; then
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
exit 2
fi
x_display() {
if [ -n "${DISPLAY:-}" ]; then
printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}"
return 0
fi
local p name a prev display auth
for p in "$proc"/[0-9]*; do
name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1)
case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac
display= auth= prev=
while IFS= read -r a; do
case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac
[ "$prev" = -auth ] && auth=$a
prev=$a
done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline")
if [ -n "$display" ]; then
printf '%s\n%s\n' "$display" "$auth"
return 0
fi
done
return 1
}
running() {
local p
for p in "$proc"/[0-9]*; do
@@ -79,7 +57,7 @@ inspector() {
}
start() {
local shown display auth url pid
local url pid child=
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
if ! ours >/dev/null; then
if tracked >/dev/null || running; then
@@ -87,18 +65,18 @@ start() {
echo busy
return 3
fi
shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; }
display=$(sed -n 1p <<<"$shown")
auth=$(sed -n 2p <<<"$shown")
env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \
setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >"$state/log" 2>&1 9>&- &
mv -f "$state/log" "$state/log.1" 2>/dev/null
env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \
"$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- &
pid=$!
child=$pid
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
fi
exec 9>&-
for _ in $(seq 1 $((wait_s * 2))); do
if url=$(inspector); then
echo "$url"
hold "$child"
return 0
fi
ours >/dev/null || break
@@ -108,6 +86,18 @@ start() {
return 5
}
hold() {
local pid
if [ -n "$1" ]; then
wait "$1"
return 0
fi
pid=$(ours) || return 0
while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do
sleep 1
done
}
stop() {
local pid p
lock || return 1
@@ -118,6 +108,7 @@ stop() {
sleep 0.5
done
kill -KILL -- "-$pid" 2>/dev/null
kill -KILL "$pid" 2>/dev/null
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
done
@@ -127,22 +118,10 @@ stop() {
}
case $cmd in
display)
x_display || exit 4
;;
start)
start
exit $?
;;
hold)
start >/dev/null || exit $?
trap 'stop; exit 0' TERM INT HUP
while ours >/dev/null; do
sleep 1 &
wait $!
done
exit 0
;;
stop)
stop
exit 0
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
"libssl.so.3", "libcrypto.so.3",
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
))
PROVIDED_NEEDS = {
"libwayland-client.so.0": ("libffi.so.8",),
@@ -670,6 +670,8 @@ def guest_environment(fex, env):
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
result.pop("GLIBC_TUNABLES", None)
if "aarch64" in result.get("GCONV_PATH", ""):
result["GCONV_PATH"] = ""
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
@@ -849,8 +851,12 @@ def extract(image):
clear_extracted()
x86 = elf_arch(image) in X86.values()
if os.access(URUNTIME, os.X_OK):
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=image))
with open(image, "rb") as source:
native = bool(os.environ.get("DDNATV_ROOT"))
target = "/proc/self/fd/%d" % source.fileno() if native else image
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=target),
pass_fds=(source.fileno(),) if native else ())
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
@@ -880,7 +886,17 @@ def extract(image):
want_fex()
return 0
say("unsquashfs could not extract it (status %d)" % status)
elif fex is None:
seven = shutil.which("7z")
if seven:
clear_extracted()
status = subprocess.call([seven, "x", "-tSquashFS", "-y", "-osquashfs-root", image], stdout=subprocess.DEVNULL)
if status == 0 and extracted():
if x86:
want_fex()
return 0
say("7-Zip could not extract it (status %d)" % status)
clear_extracted()
elif fex is None and not unsquashfs:
say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs")
return 1
@@ -164,6 +164,12 @@ def ff7_rebirth_feature_level(game):
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)"
@fix
def hades2_feature_level(game):
if game.stem == "hades2":
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Hades II: D3D12 feature level 12_2 (on Adreno 6xx/7xx it finds no D3D12 adapter at the detected level)"
@fix
def kcd2_feature_level(game):
if game.app_id == "1771300":
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
set -u
runtime=${1:-}
shift
log=
if [ "${1:-}" = --log ]; then
log=${2:-}
shift 2
fi
if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then
echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2
exit 2
fi
shift
umask 077
mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1
if [ -n "$log" ]; then
size=$(stat -c %s "$log" 2>/dev/null || echo 0)
[ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1"
exec >>"$log" 2>&1
fi
unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY
export XDG_RUNTIME_DIR=$runtime
exec gamescope --backend headless -w 640 -h 480 -- "$@"
@@ -65,12 +65,15 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
cache_only=
applied=
[ "${1:-}" = --cache ] && cache_only=1
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
@@ -130,6 +133,156 @@ fetch() {
done
}
# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries:
# the shell here cannot open /dev/fd for process substitution from a background job.
fetch_one() {
local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait
while :; do
if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then
echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0
rm -f "$dest"
finished=0 bad=$((bad + 1))
[ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; }
fi
before=$(size_of "$dest")
http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$?
if [ "$rc" = 0 ]; then finished=1; continue; fi
case "$rc:${http:-}" in
22:416 | 33:*) rm -f "$dest" ;;
22:4??)
echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2
return 1
;;
esac
if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi
if [ "$failures" -gt "${#delays[@]}" ]; then
echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2
return 1
fi
wait=${delays[$((failures > 0 ? failures - 1 : 0))]}
step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s"
sleep "$wait"
done
}
parallel=${DD_STEAM_PARALLEL:-4}
case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac
flock_command=${DD_STEAM_FLOCK:-flock}
command -v "$flock_command" > /dev/null 2>&1 || parallel=1
# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into
# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the
# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover.
unzip_alone() {
local rc
( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$?
return $rc
}
# Takes the next unclaimed line number from a counter under a flock, and prints 0 when none is left. mkdir was tried for this
# and handed the same line to two workers now and then in the app's guest shell, so only the kernel's lock is trusted here.
claim_next() {
local n
while :; do
# A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none.
n=$( { "$flock_command" 8 || exit 1
n=$(cat "$state/next") || exit 1
case $n in ''|*[!0-9]*) exit 1 ;; esac
echo $((n + 1)) > "$state/next" || exit 1
echo "$n"; } 8> "$state/claim.lock" ) || return 1
[ "$n" -le "$count" ] || { echo 0; return; }
if [ ! -e "$state/$n.done" ]; then
: > "$state/claim.$n"
echo "$n"
return
fi
done
}
# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third
# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a
# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves
# (claim_next) and only plain background jobs and wait on a pid are used, so nothing depends on job control.
run_parallel() {
local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size
local -a blocks=() files=() sums=() sizes=() pids=()
state=$work/parallel
rm -rf "$state"
mkdir -p "$state"
echo 1 > "$state/next"
while read -r block file sum size; do
index=$((index + 1))
blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size
if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then
: > "$state/$index.done"
fi
done < "$list"
local count=$index total_bytes=0
for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done
local slot
for slot in $(seq 1 "$parallel"); do
(
trap ': > "$state/exit.$slot"' EXIT
while [ ! -e "$state/failed" ]; do
# run_parallel is called in an || list, which switches set -e off in here: a failed claim has to be checked by hand.
index=$(claim_next) || { : > "$state/failed"; exit 1; }
[ "$index" -gt 0 ] || exit 0
file=${files[index]}
fetched=""
for host in "${cdn_order[@]}"; do
if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then
fetched=$host
break
fi
done
if [ -z "$fetched" ]; then
echo "droiddeck-steam-install: $file failed on every CDN" >&2
: > "$state/failed"
exit 1
fi
if [ -n "$unpack" ]; then
unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; }
: > "$dir/$file.unpacked"
rm -f "$dir/$file"
fi
: > "$state/$index.done"
done
) &
pids+=($!)
done
local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90}
while :; do
alive=0
for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done
got=0 n=0 current=""
for index in $(seq 1 "$count"); do
if [ -e "$state/$index.done" ]; then
got=$((got + sizes[index])) n=$((n + 1))
elif [ -e "$state/claim.$index" ]; then
current=$index
[ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}")))
fi
done
mark=$((got / 1000000))
if [ -n "$current" ] && [ "$mark" != "$shown" ]; then
shown=$mark
step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB"
fi
[ "$n" -lt "$count" ] || alive=0
if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi
# A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while
# and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging.
[ $((SECONDS - since)) -lt "$stall" ] || alive=0
[ "$alive" = 1 ] || break
sleep 1
done
local failed=""
for slot in "${pids[@]}"; do wait "$slot" || failed=1; done
[ ! -e "$state/failed" ] || failed=1
rm -rf "$state"
[ -z "$failed" ]
}
fetch_manifest() {
cdn=""
for candidate in $cdn_list; do
@@ -167,6 +320,66 @@ if ! fetch_manifest; then
fallback=1
fetch_manifest || exit 1
fi
if [ -n "$cache_only" ]; then
cache=$steam_root/package
cached=$cache/droiddeck-cached
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
$2 == "size" { size[block] = $4 }
$2 == "zipvz" { vz[block] = $4 }
$2 == "sha2vz" { vzsha[block] = $4 }
END {
for (b in file) {
f = file[b]; h = sha[b]; n = size[b] + 0
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
print b, f, h, n
}
}
' "$work/manifest" | sort > "$work/cache"
mkdir -p "$cache"
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
done_bytes=0
i=0
if [ "$parallel" -gt 1 ]; then
run_parallel "$work/cache" "$cache" || exit 1
else
while read -r block file sum size; do
i=$((i + 1))
progress "$cache/$file" "$block"
fetched=""
for host in "${cdn_order[@]}"; do
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
fetched=$host
break
fi
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
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"
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)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
@@ -175,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")
@@ -186,6 +400,9 @@ for left in "$parts"/*; do
grep -qF " $name " "$work/parts" || rm -rf "$left"
done
done_bytes=0
if [ "$parallel" -gt 1 ]; then
run_parallel "$work/parts" "$parts" unpack || exit 1
else
while read -r block file sum size; do
i=$((${i:-0} + 1))
if [ -f "$parts/$file.unpacked" ]; then
@@ -206,6 +423,8 @@ while read -r block file sum size; do
rm -f "$parts/$file"
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])
@@ -125,6 +125,14 @@ RECORD = ".droiddeck-shortcuts.json"
AWAY_LIMIT = 256
FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions")
FOLLOWED = ("StartDir", "LaunchOptions")
# Guest mountpoints whose contents live on storage the user can unplug. The app creates
# the mountpoint before binding it, so it outlives a removed card; libraries, store
# volumes and added game folders get one mountpoint each under these families.
REMOVABLE_ROOTS = ("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")
REMOVABLE_FAMILIES = ("/mnt/droiddeck-lib", "/mnt/droiddeck-stores", "/root/Games")
# Guest trees the app always has, whatever storage is in the device. A target that is
# missing from one of these is gone even when its whole folder was removed.
INTERNAL_ROOTS = ("/root/Games/Stores", "/root/.local/share/Steam")
def unquoted(value):
@@ -146,6 +154,46 @@ def read_record(path):
}
def under(path, root):
return path == root or path.startswith(root + "/")
def internal_target(target):
path = os.path.normpath(target)
return any(under(path, root) for root in INTERNAL_ROOTS)
def removable_mount(target):
"""The guest mountpoint holding target, when it is storage the user can unplug."""
path = os.path.normpath(target)
for root in REMOVABLE_ROOTS:
if under(path, root):
return root
for family in REMOVABLE_FAMILIES:
prefix = family + "/"
if path.startswith(prefix):
return prefix + path[len(prefix):].split("/", 1)[0]
return None
def storage_mounted(target):
"""Whether the storage holding target is there this session.
The app creates a guest mountpoint before binding storage to it, so a mountpoint that
lists nothing is one a removed card or volume left behind. A target under it may work
again when that storage returns, so its absence is not proof the file is gone.
"""
if internal_target(target):
return True
mount = removable_mount(target)
if mount is None:
return True
try:
return bool(os.listdir(mount))
except OSError:
return False
def merge(fresh, current, state, seen):
state = state if isinstance(state, dict) else {}
rev = state.get("rev") if isinstance(state.get("rev"), int) else 0
@@ -158,7 +206,16 @@ def merge(fresh, current, state, seen):
entry = dict(current)
entry["appid"] = fresh["appid"]
exe = unquoted(fresh["Exe"])
if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev):
target = unquoted(current.get("Exe"))
# A target Steam still points at after the file is gone starts nothing, so it is not
# an edit to keep: the app's own exe replaces it (#694: a hand-typed Target outlived
# the game update that removed the file, and every launch died before the game ran).
# Only when its storage is mounted and it is missing from a tree the app always has or
# from a folder that is still there. An absent folder under a mountpoint can equally be
# unplugged storage, and that target may work again next session.
gone = (bool(target) and not os.path.isfile(target) and storage_mounted(target) and
(internal_target(target) or os.path.isdir(os.path.dirname(target))))
if exe != target and (gone or exe != unquoted(base.get("Exe")) or seen == rev):
entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"]
for field in ("AppName", "icon"):
if current.get(field) == base.get(field):
@@ -10,6 +10,7 @@ import tempfile
DISPLAY = "External: gamescope|||Windowed"
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
@@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text):
return seed_value(text, SCREENSAVER_IN_GAME, '0')
def seed_bouncing_logo(text):
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
def atomic_write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
@@ -179,6 +184,11 @@ def initialize_screensaver(steam_root):
'== steam: no screensaver over a running game')
def initialize_screensaver_choice(steam_root):
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
'== steam: bouncing logo screensaver')
if __name__ == '__main__':
status = 0
try:
@@ -186,7 +196,7 @@ if __name__ == '__main__':
except (OSError, ValueError, RecursionError) as error:
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
status = 1
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
try:
step(sys.argv[1])
except (OSError, ValueError, RecursionError) as error: