mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
Move the Linux runtime to Ubuntu 26.04 LTS with a separate Kubuntu desktop (#1733)
This commit is contained in:
1 parent
5de690ef39
commit
29c83976d0
305 files changed
+9383
-462
No files matched your search
@@ -11,8 +11,30 @@ icon, Plasma's default bottom panel, and "Return to Gaming Mode" and Steam on th
|
||||
- `overlay/`: our files on top - system-wide KDE defaults in `/etc/xdg`, the Vapor theme and its
|
||||
layout script, the menu entries Steam and Return to Gaming Mode use.
|
||||
|
||||
pacman works on the desktop. `pacman-db.py` writes an install record for every package the desktop
|
||||
ships into `/var/lib/pacman/local`, and builds the `droiddeck` repository: Arch Linux ARM's core,
|
||||
extra and alarm databases as they were at build time, with the runtime's and the desktop's own
|
||||
packages at the installed versions. The release carries that database (`droiddeck.db`) and the
|
||||
packages `mirror.txt` names; everything else downloads from Arch Linux ARM as a `CacheServer`, so its
|
||||
404s never disable a mirror. Installs therefore resolve against the desktop's exact Qt and KDE
|
||||
versions, and `pacman -Syu` only ever moves packages the user added.
|
||||
|
||||
- `/usr/local/bin/pacman` runs the real pacman with `/usr/share/droiddeck/pacman/pacman.conf`, first
|
||||
copying in the shipped database and dropping the runtime's records for packages the desktop
|
||||
replaced (`prepare`). As root it adds `--needed` to installs, so guides that reinstall
|
||||
something the desktop has just skip it.
|
||||
- `sudo`, `su` and `sudoedit` run commands as root: the session is the app's own Android user, and
|
||||
`libdroiddeck-root.so` (`root/root.c`, preloaded by `sudo`) reports uid 0, accepts ownership
|
||||
changes and shows the runtime's 0700 directories as 0755. It grants nothing the user lacked.
|
||||
- `hooks/droiddeck-system.hook` refuses to remove or replace any runtime or desktop package;
|
||||
`droiddeck-remember.hook` keeps the user's own packages in
|
||||
`~/.local/share/droiddeck/pacman/packages.txt`, and `restore` (autostarted) reinstalls them after a
|
||||
runtime update and upgrades them after a desktop update. Hooks that need systemd, udev, kernel
|
||||
modules or an initramfs are masked.
|
||||
|
||||
`.github/workflows/build-desktop-kde.yml` builds it and, run with a new tag, publishes it as a
|
||||
release in Droid-Deck/DroidDeck-Components. `release.env` pins the tag, sha256 and size the apk
|
||||
release in Droid-Deck/DroidDeck-Components (tags with `-rc` are published as pre-releases for testing
|
||||
before an app build points at them). `release.env` pins the tag, sha256 and size the apk
|
||||
installs (`DesktopCatalog.desktopEntry`); a published tag is never replaced, so a changed package
|
||||
is a new tag and a `release.env` update.
|
||||
|
||||
@@ -20,6 +42,8 @@ At run time the desktop is started by `tools/linuxfs/desktop/droiddeck-desktop`
|
||||
at every session): Plasma's own `startplasma-wayland`, with KWin nested in the app's compositor
|
||||
through `kwin_wayland_wrapper`. The package's `kwin-compositor` marker selects OpenGL through
|
||||
Zink for KWin 6.8, which removed QPainter. Older packages retain their software compositor.
|
||||
KWin runs without Gallium's threaded context and without overlay layers. With the threaded context, KWin crashed
|
||||
uploading windows' shared-memory buffers by reading past their end, and the host shows only a single buffer.
|
||||
On Android the launcher explicitly selects the KGSL render node; the nested backend can use it
|
||||
when the host's dmabuf feedback cannot name a DRM device. Games and emulators from the menu go
|
||||
through `droiddeck-gpu`, and Steam goes back to the app as a Steam session.
|
||||
@@ -35,6 +59,9 @@ The behavior is enabled only with `DROIDDECK_NESTED_SCALE`, which the desktop sc
|
||||
`0002-select-explicit-nested-render-node.patch` lets that nested backend use one explicitly
|
||||
selected `KWIN_RENDER_NODES` device when host feedback cannot identify it. It does not guess
|
||||
between GPUs or change normal KWin device selection.
|
||||
`0003-forward-nested-scroll-source.patch` passes the host's scroll source, wheel steps and scroll stops
|
||||
through the nested backend, which upstream leaves as a TODO. Two-finger touch scrolling then reaches
|
||||
apps as touchpad scrolling, and wheel steps stay whole clicks.
|
||||
|
||||
`pins/mesa/desc` keeps Mesa 26.2.4 and its actual package dependencies ahead of the rolling
|
||||
repository metadata. Mesa 26.2.5 crashes in Zink shader compilation on Thor with the selected
|
||||
@@ -44,7 +71,7 @@ both build jobs verify the Arch Linux ARM signature and pinned SHA-256 as for ev
|
||||
The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest
|
||||
comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch,
|
||||
executable, library and build package hashes. Corresponding source is
|
||||
https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz plus the patch in this repository.
|
||||
https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz plus the patch in this repository.
|
||||
|
||||
The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips
|
||||
its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes.
|
||||
|
||||
@@ -6,7 +6,7 @@ here=$(cd "$(dirname "$0")" && pwd)
|
||||
source "$here/kwin.env"
|
||||
source "$here/mesa.env"
|
||||
version=$DESKTOP_KWIN_VERSION
|
||||
source_sha=4bfaf31e29a8f9fdf231dc3bbb9b09b0ce07cae9fee7a01cfc86425ece796258
|
||||
source_sha=ea5e68d957c7d70abed97222a592d4445fda29129e20942658badd224ee138b4
|
||||
mirror=https://fl.us.mirror.archlinuxarm.org/aarch64
|
||||
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
|
||||
work=$(mktemp -d)
|
||||
@@ -52,6 +52,7 @@ sudo mount -t proc proc "$work/root/proc"
|
||||
sudo tar -xf "$work/kwin.tar.xz" -C "$work/root/build"
|
||||
sudo patch -d "$work/root/build/kwin-$version" -p1 < "$here/patches/0001-respect-nested-desktop-scale.patch"
|
||||
sudo patch -d "$work/root/build/kwin-$version" -p1 < "$here/patches/0002-select-explicit-nested-render-node.patch"
|
||||
sudo patch -d "$work/root/build/kwin-$version" -p1 < "$here/patches/0003-forward-nested-scroll-source.patch"
|
||||
sudo chroot "$work/root" /usr/bin/env PATH=/usr/bin:/bin HOME=/root LC_ALL=C.UTF-8 \
|
||||
/usr/bin/cmake -S "/build/kwin-$version" -B /build/out -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBEXECDIR=lib \
|
||||
@@ -72,6 +73,7 @@ grep -aq DROIDDECK_NESTED_SCALE "$out/libkwin.so.$version"
|
||||
echo "KWin $version source sha256 $source_sha"
|
||||
echo "Patch sha256 $(sha256sum "$here/patches/0001-respect-nested-desktop-scale.patch" | cut -d' ' -f1)"
|
||||
echo "Render node patch sha256 $(sha256sum "$here/patches/0002-select-explicit-nested-render-node.patch" | cut -d' ' -f1)"
|
||||
echo "Scroll source patch sha256 $(sha256sum "$here/patches/0003-forward-nested-scroll-source.patch" | cut -d' ' -f1)"
|
||||
echo "Executable sha256 $(sha256sum "$out/kwin_wayland" | cut -d' ' -f1)"
|
||||
echo "Library sha256 $(sha256sum "$out/libkwin.so.$version" | cut -d' ' -f1)"
|
||||
echo 'Build packages (Arch Linux ARM signatures verified):'
|
||||
|
||||
@@ -38,6 +38,12 @@ while read -r entry sum; do
|
||||
done < "$work/pkglist.txt"
|
||||
|
||||
cp -a "$here/overlay/." "$work/root/"
|
||||
mkdir -p "$work/root/usr/lib/droiddeck"
|
||||
${CC_AARCH64:-aarch64-linux-gnu-gcc} -shared -fPIC -O2 -Wall -Wextra \
|
||||
-o "$work/root/usr/lib/droiddeck/libdroiddeck-root.so" "$here/root/root.c" -ldl
|
||||
${STRIP_AARCH64:-aarch64-linux-gnu-strip} --strip-unneeded "$work/root/usr/lib/droiddeck/libdroiddeck-root.so"
|
||||
python3 "$here/pacman-db.py" "$work/db" "$pkgs" "$work/pkglist.txt" "$here/runtime-packages.txt" \
|
||||
"$here/mirror.txt" "${DESKTOP_KDE_RELEASE_TAG:-}" "$work/root" "$out/repo"
|
||||
|
||||
if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then
|
||||
kwin_package=$(awk '$1 ~ /^extra\/kwin-.*-aarch64\.pkg\.tar\./ {print $1}' "$work/pkglist.txt")
|
||||
@@ -61,7 +67,7 @@ if [ -d "$work/root/usr/share/locale" ]; then
|
||||
echo "i18n: $(wc -l < "$out/desktop-kde.i18n.txt") language packs"
|
||||
fi
|
||||
|
||||
rm -rf "$work/root/usr/share/doc" "$work/root/usr/share/man" "$work/root/usr/share/info" \
|
||||
rm -rf "$work/root/usr/share/doc" "$work/root/usr/share/info" \
|
||||
"$work/root/usr/share/gtk-doc" "$work/root/usr/include" "$work/root/usr/lib/pkgconfig" \
|
||||
"$work/root/usr/lib/cmake" "$work/root/usr/share/help"
|
||||
find "$work/root/usr/share/locale" -mindepth 1 -maxdepth 1 -type d ! -name 'en*' -exec rm -rf {} + 2>/dev/null || true
|
||||
|
||||
@@ -1 +1 @@
|
||||
DESKTOP_KWIN_VERSION=6.8.0
|
||||
DESKTOP_KWIN_VERSION=6.8.2
|
||||
@@ -0,0 +1,16 @@
|
||||
neovim
|
||||
tmux
|
||||
screen
|
||||
rsync
|
||||
jq
|
||||
ripgrep
|
||||
fd
|
||||
bat
|
||||
ncdu
|
||||
btop
|
||||
fastfetch
|
||||
lsof
|
||||
strace
|
||||
python-pip
|
||||
nodejs
|
||||
npm
|
||||
@@ -0,0 +1,7 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Restore pacman packages
|
||||
Exec=/usr/share/droiddeck/pacman/restore
|
||||
NoDisplay=true
|
||||
OnlyShowIn=KDE;
|
||||
X-KDE-autostart-phase=2
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
dir=/usr/share/droiddeck/pacman
|
||||
[ -r "$dir/pacman.conf" ] || exec /usr/bin/pacman "$@"
|
||||
"$dir/prepare" || exit 1
|
||||
install=0
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
letters= install=1
|
||||
for arg in "$@"; do
|
||||
case $arg in
|
||||
--) break ;;
|
||||
--sync) letters+=S ;;
|
||||
--search|--info|--clean|--groups|--list|--print|--print-format|--downloadonly) install=0 ;;
|
||||
--*) ;;
|
||||
-*) letters+=${arg#-} ;;
|
||||
esac
|
||||
done
|
||||
case $letters in *S*) ;; *) install=0 ;; esac
|
||||
case $letters in *[sicglpw]*) install=0 ;; esac
|
||||
[ "$install" = 1 ] && set -- --needed "$@"
|
||||
fi
|
||||
[ "$install" = 1 ] || exec /usr/bin/pacman --config "$dir/pacman.conf" "$@"
|
||||
/usr/bin/pacman --config "$dir/pacman.conf" "$@" && exit 0
|
||||
status=$?
|
||||
mapfile -t paths < <("$dir/adopt" "$@")
|
||||
[ ${#paths[@]} -gt 0 ] || exit "$status"
|
||||
overwrite=()
|
||||
for path in "${paths[@]}"; do overwrite+=(--overwrite "$path"); done
|
||||
/usr/bin/pacman --config "$dir/pacman.conf" "${overwrite[@]}" "$@" || exit
|
||||
mapfile -t shared < <(/usr/bin/pacman --config "$dir/pacman.conf" -Qqd 2>/dev/null | grep -xF -f /var/lib/pacman/droiddeck-shared)
|
||||
[ ${#shared[@]} -eq 0 ] || /usr/bin/pacman --config "$dir/pacman.conf" -D --asexplicit "${shared[@]}" >/dev/null
|
||||
"$dir/remember"
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
login=0 command= shell=
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-|-l|--login) login=1; shift ;;
|
||||
-c|--command) [ $# -ge 2 ] || { echo "su: option requires an argument -- 'c'" >&2; exit 1; }; command=$2; shift 2 ;;
|
||||
--command=*) command=${1#*=}; shift ;;
|
||||
-s|--shell) [ $# -ge 2 ] || { echo "su: option requires an argument -- 's'" >&2; exit 1; }; shell=$2; shift 2 ;;
|
||||
--shell=*) shell=${1#*=}; shift ;;
|
||||
-m|-p|--preserve-environment|-P|--pty|-f|--fast) shift ;;
|
||||
-h|--help) echo "usage: su [-] [-c command] [-s shell] [root]"; exit 0 ;;
|
||||
-V|--version) echo "DroidDeck su: runs a root shell inside the DroidDeck desktop"; exit 0 ;;
|
||||
--) shift; break ;;
|
||||
-*) echo "su: invalid option -- '${1#-}'" >&2; exit 1 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
user=${1:-root}
|
||||
[ $# -gt 0 ] && shift
|
||||
case $user in
|
||||
root|0|"$(id -un 2>/dev/null)") ;;
|
||||
*) echo "su: user $user does not exist or the user entry does not contain all the required fields" >&2; exit 1 ;;
|
||||
esac
|
||||
args=()
|
||||
[ "$login" = 1 ] && args+=(-i)
|
||||
if [ -n "$shell" ]; then
|
||||
if [ -n "$command" ]; then exec /usr/local/bin/sudo "${args[@]}" "$shell" -c "$command" "$@"; fi
|
||||
exec /usr/local/bin/sudo "${args[@]}" "$shell" "$@"
|
||||
fi
|
||||
if [ -n "$command" ]; then exec /usr/local/bin/sudo "${args[@]}" -s "$command"; fi
|
||||
[ "$login" = 1 ] && exec /usr/local/bin/sudo -i
|
||||
exec /usr/local/bin/sudo -s
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
lib=/usr/lib/droiddeck/libdroiddeck-root.so
|
||||
me=${0##*/}
|
||||
usage() {
|
||||
echo "usage: $me [-EHiknsSv] [-u user] [-g group] [-D directory] [--] command [arg ...]"
|
||||
echo " $me -e file ..."
|
||||
}
|
||||
known_user() {
|
||||
case $1 in
|
||||
''|root|0|'#0'|"$(id -un 2>/dev/null)"|"#$(id -ru 2>/dev/null)") return 0 ;;
|
||||
esac
|
||||
echo "$me: unknown user $1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
login=0 shell=0 edit=0 background=0 dir=
|
||||
[ "$me" = sudoedit ] && edit=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--) shift; break ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
-V|--version) echo "DroidDeck sudo: runs commands as root inside the DroidDeck desktop"; exit 0 ;;
|
||||
-l|--list) echo "User $(id -un 2>/dev/null) may run the following commands on $(uname -n):"; echo " (ALL : ALL) ALL"; exit 0 ;;
|
||||
-v|--validate|-K|--remove-timestamp) exit 0 ;;
|
||||
-k|--reset-timestamp) shift; [ $# -eq 0 ] && exit 0 ;;
|
||||
-i|--login) login=1; shift ;;
|
||||
-s|--shell) shell=1; shift ;;
|
||||
-e|--edit) edit=1; shift ;;
|
||||
-b|--background) background=1; shift ;;
|
||||
-E|--preserve-env|--preserve-env=*|-H|--set-home|-n|--non-interactive|-S|--stdin|-P|--preserve-groups|-A|--askpass|-B|--bell|-N|--no-update) shift ;;
|
||||
-u|--user|-g|--group) [ $# -ge 2 ] || { usage >&2; exit 1; }; known_user "$2"; shift 2 ;;
|
||||
--user=*|--group=*) known_user "${1#*=}"; shift ;;
|
||||
-u*|-g*) known_user "${1:2}"; shift ;;
|
||||
-D|--chdir) [ $# -ge 2 ] || { usage >&2; exit 1; }; dir=$2; shift 2 ;;
|
||||
--chdir=*) dir=${1#*=}; shift ;;
|
||||
-p|--prompt|-C|--close-from|-r|--role|-t|--type|-T|--command-timeout|-R|--chroot) [ $# -ge 2 ] || { usage >&2; exit 1; }; shift 2 ;;
|
||||
--prompt=*|--close-from=*|--role=*|--type=*|--command-timeout=*) shift ;;
|
||||
-[A-Za-z][A-Za-z]*)
|
||||
flags=${1#-}; shift
|
||||
split=()
|
||||
while [ -n "$flags" ]; do
|
||||
split+=("-${flags:0:1}")
|
||||
case ${flags:0:1} in
|
||||
u|g|D|p|C|r|t|T|R) [ -n "${flags:1}" ] && split+=("${flags:1}"); flags= ;;
|
||||
*) flags=${flags:1} ;;
|
||||
esac
|
||||
done
|
||||
set -- "${split[@]}" "$@"
|
||||
;;
|
||||
-*) echo "$me: invalid option -- '${1#-}'" >&2; usage >&2; exit 1 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ "$edit" = 1 ]; then
|
||||
[ $# -gt 0 ] || { usage >&2; exit 1; }
|
||||
editor=${SUDO_EDITOR:-${VISUAL:-${EDITOR:-nano}}}
|
||||
exec $editor "$@"
|
||||
fi
|
||||
|
||||
if [ ! -r "$lib" ]; then
|
||||
echo "$me: $lib is missing; reinstall the desktop from DroidDeck's Desktop page" >&2
|
||||
exit 1
|
||||
fi
|
||||
case ":${LD_PRELOAD:-}:" in
|
||||
*":$lib:"*) ;;
|
||||
*) export LD_PRELOAD="$lib${LD_PRELOAD:+:$LD_PRELOAD}" ;;
|
||||
esac
|
||||
export SUDO_USER=${SUDO_USER:-$(id -un 2>/dev/null)}
|
||||
export SUDO_UID=${SUDO_UID:-$(id -ru 2>/dev/null)}
|
||||
export SUDO_GID=${SUDO_GID:-$(id -rg 2>/dev/null)}
|
||||
export SUDO_COMMAND="$*"
|
||||
[ -z "$dir" ] || cd "$dir" || exit 1
|
||||
|
||||
target_shell=$(getent passwd "$(id -un 2>/dev/null)" | cut -d: -f7)
|
||||
target_shell=${target_shell:-/bin/bash}
|
||||
if [ "$login" = 1 ]; then
|
||||
cd "${HOME:-/root}" 2>/dev/null
|
||||
if [ $# -gt 0 ]; then set -- "$target_shell" -l -c "$*"; else set -- "$target_shell" -l; fi
|
||||
elif [ "$shell" = 1 ]; then
|
||||
if [ $# -gt 0 ]; then set -- "${SHELL:-$target_shell}" -c "$*"; else set -- "${SHELL:-$target_shell}"; fi
|
||||
elif [ $# -eq 0 ]; then
|
||||
usage >&2
|
||||
exit 1
|
||||
elif ! command -v "$1" >/dev/null 2>&1; then
|
||||
echo "$me: $1: command not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$background" = 1 ]; then
|
||||
"$@" &
|
||||
exit 0
|
||||
fi
|
||||
exec "$@"
|
||||
@@ -0,0 +1 @@
|
||||
sudo
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Avahi Zeroconf Browser
|
||||
Exec=/usr/bin/avahi-discover
|
||||
Icon=network-wired
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Avahi SSH Server Browser
|
||||
Exec=/usr/bin/bssh
|
||||
Icon=network-wired
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Avahi VNC Server Browser
|
||||
Exec=/usr/bin/bvnc
|
||||
Icon=network-wired
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Foot Server
|
||||
Exec=foot --server
|
||||
Icon=foot
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Foot Client
|
||||
Exec=footclient
|
||||
Icon=foot
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Hardware Locality lstopo
|
||||
Exec=lstopo
|
||||
Icon=hwloc
|
||||
NoDisplay=true
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=IBus Preferences
|
||||
Exec=ibus-setup
|
||||
Icon=ibus-setup
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Qt V4L2 test Utility
|
||||
Exec=qv4l2
|
||||
Icon=qv4l2
|
||||
NoDisplay=true
|
||||
@@ -0,0 +1,6 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Qt V4L2 video capture utility
|
||||
Exec=qvidcap
|
||||
Icon=qvidcap
|
||||
NoDisplay=true
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
SHARE = "/usr/share/droiddeck/pacman"
|
||||
LIB = "/var/lib/pacman"
|
||||
CACHE = "/var/cache/pacman/pkg"
|
||||
SHARED = os.path.join(LIB, "droiddeck-shared")
|
||||
SHARED_FILES = SHARED + "-files"
|
||||
|
||||
|
||||
def owned():
|
||||
paths = set()
|
||||
local = os.path.join(LIB, "local")
|
||||
for entry in os.listdir(local):
|
||||
try:
|
||||
with open(os.path.join(local, entry, "files"), encoding="utf-8", errors="surrogateescape") as f:
|
||||
lines = f.read().split("\n")
|
||||
except OSError:
|
||||
continue
|
||||
reading = False
|
||||
for line in lines:
|
||||
if line.startswith("%"):
|
||||
reading = line == "%FILES%"
|
||||
elif reading and line:
|
||||
paths.add(line.rstrip("/"))
|
||||
return paths
|
||||
|
||||
|
||||
def same(archive, member, path):
|
||||
if member.issym():
|
||||
return os.path.islink(path) and os.readlink(path) == member.linkname
|
||||
if not member.isfile() or os.path.islink(path) or not os.path.isfile(path):
|
||||
return False
|
||||
if os.path.getsize(path) != member.size:
|
||||
return False
|
||||
with archive.extractfile(member) as packaged, open(path, "rb") as installed:
|
||||
return hashlib.file_digest(packaged, "sha256").digest() == hashlib.file_digest(installed, "sha256").digest()
|
||||
|
||||
|
||||
def planned(args):
|
||||
query = []
|
||||
for arg in args:
|
||||
if arg == "--refresh" or arg == "--noconfirm":
|
||||
continue
|
||||
if re.fullmatch(r"-[A-Za-z]+", arg):
|
||||
arg = arg.replace("y", "")
|
||||
if arg == "-":
|
||||
continue
|
||||
query.append(arg)
|
||||
run = subprocess.run(["/usr/bin/pacman", "--config", os.path.join(SHARE, "pacman.conf"), "--noconfirm", *query,
|
||||
"--print", "--print-format", "%n %f"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True)
|
||||
if run.returncode != 0:
|
||||
return []
|
||||
return [line.split(" ", 1) for line in run.stdout.splitlines() if " " in line]
|
||||
|
||||
|
||||
def main():
|
||||
targets = [(name, os.path.join(CACHE, os.path.basename(file))) for name, file in planned(sys.argv[1:])]
|
||||
targets = [(name, path) for name, path in targets if os.path.isfile(path)]
|
||||
if not targets:
|
||||
return 0
|
||||
have = owned()
|
||||
paths, names = [], []
|
||||
for name, path in targets:
|
||||
found = False
|
||||
with tarfile.open(path) as archive:
|
||||
for member in archive:
|
||||
if member.isdir() or member.name.startswith("."):
|
||||
continue
|
||||
if member.name in have or not os.path.lexists("/" + member.name) or os.path.isdir("/" + member.name):
|
||||
continue
|
||||
if not same(archive, member, "/" + member.name):
|
||||
continue
|
||||
paths.append("/" + member.name)
|
||||
found = True
|
||||
if found:
|
||||
names.append(name)
|
||||
if not paths:
|
||||
return 0
|
||||
shared = set()
|
||||
try:
|
||||
with open(SHARED) as f:
|
||||
shared = {line.strip() for line in f if line.strip()}
|
||||
except OSError:
|
||||
pass
|
||||
with open(SHARED + ".tmp", "w") as f:
|
||||
f.write("".join(f"{name}\n" for name in sorted(shared | set(names))))
|
||||
os.replace(SHARED + ".tmp", SHARED)
|
||||
files = set()
|
||||
try:
|
||||
with open(SHARED_FILES, encoding="utf-8", errors="surrogateescape") as f:
|
||||
files = {line.rstrip("\n") for line in f if line.strip()}
|
||||
except OSError:
|
||||
pass
|
||||
with open(SHARED_FILES + ".tmp", "w", encoding="utf-8", errors="surrogateescape") as f:
|
||||
f.write("".join(f"{path}\n" for path in sorted(files | set(paths))))
|
||||
os.replace(SHARED_FILES + ".tmp", SHARED_FILES)
|
||||
print(f":: Other DroidDeck software already installed {len(paths)} files from {' '.join(names)}.", file=sys.stderr)
|
||||
print(":: pacman will take them over and keep these packages installed so that software keeps working.",
|
||||
file=sys.stderr)
|
||||
for path in paths:
|
||||
print(re.sub(r"([\\*?\[])", r"\\\1", path))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (OSError, tarfile.TarError) as e:
|
||||
print(f"error: could not check for files other DroidDeck software installed: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
+1
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
@@ -0,0 +1 @@
|
||||
/dev/null
|
||||
@@ -0,0 +1,11 @@
|
||||
[Trigger]
|
||||
Operation = Install
|
||||
Operation = Upgrade
|
||||
Operation = Remove
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Remembering the packages you installed...
|
||||
When = PostTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/remember
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
[Trigger]
|
||||
Operation = Upgrade
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Putting back files other DroidDeck software needs...
|
||||
When = PostTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/keep restore
|
||||
@@ -0,0 +1,9 @@
|
||||
[Trigger]
|
||||
Operation = Upgrade
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Saving files other DroidDeck software needs...
|
||||
When = PreTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/keep save
|
||||
@@ -0,0 +1,11 @@
|
||||
[Trigger]
|
||||
Operation = Remove
|
||||
Type = Package
|
||||
Target = *
|
||||
|
||||
[Action]
|
||||
Description = Checking for files other DroidDeck software needs...
|
||||
When = PreTransaction
|
||||
Exec = /usr/share/droiddeck/pacman/shared
|
||||
NeedsTargets
|
||||
AbortOnFail
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
list=/var/lib/pacman/droiddeck-shared-files
|
||||
store=/var/lib/pacman/droiddeck-shared-keep
|
||||
[ -s "$list" ] || exit 0
|
||||
case $1 in
|
||||
save)
|
||||
mkdir -p "$store"
|
||||
while IFS= read -r path; do
|
||||
[ -e "$path" ] || [ -L "$path" ] || continue
|
||||
mkdir -p "$store${path%/*}"
|
||||
rm -f -- "$store$path"
|
||||
cp -a -- "$path" "$store$path"
|
||||
done < "$list"
|
||||
;;
|
||||
restore)
|
||||
[ -d "$store" ] || exit 0
|
||||
while IFS= read -r path; do
|
||||
[ -e "$path" ] || [ -L "$path" ] && continue
|
||||
[ -e "$store$path" ] || [ -L "$store$path" ] || continue
|
||||
mkdir -p "${path%/*}"
|
||||
cp -a -- "$store$path" "$path"
|
||||
done < "$list"
|
||||
rm -rf -- /var/lib/pacman/droiddeck-shared-keep
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
SHARE = "/usr/share/droiddeck/pacman"
|
||||
LIB = "/var/lib/pacman"
|
||||
STATE = os.path.join(LIB, "droiddeck-desktop")
|
||||
|
||||
|
||||
def digest(path):
|
||||
with open(path, "rb") as f:
|
||||
return hashlib.sha256(f.read()).hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
for path in ("/var/cache/pacman/pkg", os.path.join(LIB, "sync"), "/etc/pacman.d/hooks", "/var/log"):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
stamp = digest(os.path.join(SHARE, "desktop-packages.txt")) + " " + digest(os.path.join(SHARE, "droiddeck.db"))
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
if f.read().strip() == stamp:
|
||||
return 0
|
||||
except OSError:
|
||||
pass
|
||||
want = dict(line.split() for line in open(os.path.join(SHARE, "desktop-packages.txt")) if line.strip())
|
||||
local = os.path.join(LIB, "local")
|
||||
for entry in os.listdir(local):
|
||||
desc = os.path.join(local, entry, "desc")
|
||||
if not os.path.isfile(desc):
|
||||
continue
|
||||
name = version = None
|
||||
with open(desc, encoding="utf-8", errors="replace") as f:
|
||||
lines = f.read().split("\n")
|
||||
for i, line in enumerate(lines[:-1]):
|
||||
if line == "%NAME%":
|
||||
name = lines[i + 1]
|
||||
elif line == "%VERSION%":
|
||||
version = lines[i + 1]
|
||||
if name in want and version != want[name]:
|
||||
shutil.rmtree(os.path.join(local, entry))
|
||||
shutil.copyfile(os.path.join(SHARE, "droiddeck.db"), os.path.join(LIB, "sync", "droiddeck.db"))
|
||||
with open(STATE + ".tmp", "w") as f:
|
||||
f.write(stamp + "\n")
|
||||
os.replace(STATE + ".tmp", STATE)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except OSError as e:
|
||||
print(f"error: could not prepare pacman's database: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
packages=$(tr '\n' ' ')
|
||||
echo "error: ${packages% } came with DroidDeck, so pacman can't remove or replace it." >&2
|
||||
echo "error: DroidDeck updates these itself; packages you installed with pacman are yours to change." >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
dir=/usr/share/droiddeck/pacman
|
||||
state=/root/.local/share/droiddeck/pacman
|
||||
mkdir -p "$state"
|
||||
if [ -z "${DROIDDECK_PACMAN_RESTORING:-}" ] && explicit=$(/usr/bin/pacman --config "$dir/pacman.conf" -Qqe 2>/dev/null); then
|
||||
printf '%s\n' "$explicit" | grep -vxF -f "$dir/system-packages.txt" > "$state/packages.txt.tmp"
|
||||
if [ $? -le 1 ] && [ -f "$state/packages.txt.tmp" ]; then
|
||||
mv -f "$state/packages.txt.tmp" "$state/packages.txt"
|
||||
else
|
||||
rm -f "$state/packages.txt.tmp"
|
||||
fi
|
||||
fi
|
||||
[ -s "$state/restored" ] || sha256sum "$dir/droiddeck.db" | cut -d' ' -f1 > "$state/restored"
|
||||
rm -f /var/cache/pacman/pkg/*.pkg.tar.* /var/cache/pacman/pkg/*.pkg.tar.*.sig 2>/dev/null
|
||||
exit 0
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
dir=/usr/share/droiddeck/pacman
|
||||
state=/root/.local/share/droiddeck/pacman
|
||||
list=$state/packages.txt
|
||||
log=/root/.cache/droiddeck/pacman-restore.log
|
||||
[ -s "$list" ] && [ -r "$dir/pacman.conf" ] || exit 0
|
||||
pacman() { /usr/local/bin/pacman "$@"; }
|
||||
"$dir/prepare" || exit 0
|
||||
snapshot=$(sha256sum "$dir/droiddeck.db" | cut -d' ' -f1)
|
||||
mapfile -t missing < <(grep -vxF -f <(pacman -Qq 2>/dev/null) "$list")
|
||||
done_for=$(cat "$state/restored" 2>/dev/null)
|
||||
[ ${#missing[@]} -eq 0 ] && [ "$done_for" = "$snapshot" ] && exit 0
|
||||
attempt="$snapshot ${missing[*]}"
|
||||
[ "$(cat "$state/attempted" 2>/dev/null)" = "$attempt" ] && exit 0
|
||||
tries=$(cat "$state/tries" 2>/dev/null)
|
||||
count=0
|
||||
[ "${tries#* }" = "$attempt" ] && count=${tries%% *}
|
||||
count=$((count + 1))
|
||||
echo "$count $attempt" > "$state/tries"
|
||||
[ "$count" -ge 3 ] && echo "$attempt" > "$state/attempted"
|
||||
export DROIDDECK_PACMAN_RESTORING=1
|
||||
mkdir -p "${log%/*}"
|
||||
notify() { notify-send -a DroidDeck -i system-software-update "$@" 2>/dev/null; }
|
||||
notify "Restoring your packages" "Reinstalling software you added with pacman after a DroidDeck update."
|
||||
export LD_PRELOAD="/usr/lib/droiddeck/libdroiddeck-root.so${LD_PRELOAD:+:$LD_PRELOAD}"
|
||||
{
|
||||
date
|
||||
ok=1
|
||||
[ "$done_for" = "$snapshot" ] || pacman -Su --noconfirm || ok=0
|
||||
[ ${#missing[@]} -eq 0 ] || pacman -S --needed --noconfirm "${missing[@]}" || ok=0
|
||||
} >> "$log" 2>&1
|
||||
if [ "$ok" = 1 ]; then
|
||||
echo "$snapshot" > "$state/restored"
|
||||
notify "Packages restored" "Your pacman packages are installed again."
|
||||
else
|
||||
notify "Some packages couldn't be restored" "See $log, then try sudo pacman -S in Konsole."
|
||||
fi
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
list=/var/lib/pacman/droiddeck-shared
|
||||
[ -s "$list" ] || exit 0
|
||||
mapfile -t packages < <(grep -xF -f "$list")
|
||||
[ ${#packages[@]} -eq 0 ] && exit 0
|
||||
echo "error: ${packages[*]} shares files with other DroidDeck software, so pacman can't remove it." >&2
|
||||
exit 1
|
||||
@@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay)
|
||||
- steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme),
|
||||
GPL-3.0.
|
||||
|
||||
- kwin_wayland: KWin 6.8.0, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.0/kwin-6.8.0.tar.xz and
|
||||
- kwin_wayland: KWin 6.8.2, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
|
||||
Corresponding source: https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz and
|
||||
https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches
|
||||
(the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package).
|
||||
|
||||
|
||||
+9
@@ -14,6 +14,14 @@ kickoff.currentConfigGroup = ["Shortcuts"];
|
||||
kickoff.writeConfig("global", "Alt+F1");
|
||||
kickoff.currentConfigGroup = ["General"];
|
||||
kickoff.writeConfig("icon", "distributor-logo-steamdeck");
|
||||
kickoff.writeConfig("favorites", [
|
||||
"preferred://browser",
|
||||
"applications:org.kde.dolphin.desktop",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
"applications:org.kde.discover.desktop",
|
||||
"applications:systemsettings.desktop",
|
||||
]);
|
||||
|
||||
panel.addWidget("org.kde.plasma.pager");
|
||||
|
||||
@@ -24,6 +32,7 @@ tasks.writeConfig("launchers", [
|
||||
"preferred://filemanager",
|
||||
"preferred://browser",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
]);
|
||||
|
||||
panel.addWidget("org.kde.plasma.marginsseparator");
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
panels().forEach(function (panel) {
|
||||
panel.widgets("org.kde.plasma.icontasks").forEach(function (tasks) {
|
||||
tasks.currentConfigGroup = ["General"];
|
||||
var launchers = tasks.readConfig("launchers");
|
||||
if (typeof launchers === "string") launchers = launchers.length ? launchers.split(",") : [];
|
||||
if (launchers.indexOf("applications:org.kde.kate.desktop") < 0) {
|
||||
launchers.push("applications:org.kde.kate.desktop");
|
||||
tasks.writeConfig("launchers", launchers);
|
||||
}
|
||||
});
|
||||
});
|
||||
Executable
+258
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
|
||||
REPOS = ("core", "extra", "alarm")
|
||||
FIELDS = ("NAME", "VERSION", "BASE", "DESC", "URL", "ARCH", "BUILDDATE", "INSTALLDATE", "PACKAGER", "SIZE",
|
||||
"GROUPS", "LICENSE", "VALIDATION", "REPLACES", "DEPENDS", "OPTDEPENDS", "CONFLICTS", "PROVIDES", "XDATA")
|
||||
PKGINFO = {"pkgname": "NAME", "pkgbase": "BASE", "pkgver": "VERSION", "pkgdesc": "DESC", "url": "URL",
|
||||
"builddate": "BUILDDATE", "packager": "PACKAGER", "size": "SIZE", "arch": "ARCH", "license": "LICENSE",
|
||||
"replaces": "REPLACES", "group": "GROUPS", "conflict": "CONFLICTS", "provides": "PROVIDES",
|
||||
"depend": "DEPENDS", "optdepend": "OPTDEPENDS", "xdata": "XDATA"}
|
||||
BLOCKED = re.compile(r"^(sudo|opendoas|doas|mkinitcpio.*|linux|linux-.*|.*-firmware|firmware-.*|grub|uboot-.*|"
|
||||
r"raspberrypi-.*|archlinuxarm-keyring|pacman|pacman-mirrorlist)$")
|
||||
ALARM = "http://mirror.archlinuxarm.org/aarch64"
|
||||
RELEASES = "https://github.com/Droid-Deck/DroidDeck-Components/releases/download"
|
||||
BUILDER = "68B3537F39A313B3E574D06777193F152BDBE6A6"
|
||||
|
||||
|
||||
def read_entry(path):
|
||||
fields, key = {}, None
|
||||
for name in ("desc", "depends"):
|
||||
file = os.path.join(path, name)
|
||||
if not os.path.exists(file):
|
||||
continue
|
||||
for line in open(file, encoding="utf-8", errors="replace"):
|
||||
line = line.rstrip("\n")
|
||||
if line.startswith("%") and line.endswith("%") and len(line) > 2:
|
||||
key = line.strip("%")
|
||||
fields[key] = []
|
||||
elif line == "":
|
||||
key = None
|
||||
elif key:
|
||||
fields[key].append(line)
|
||||
return fields
|
||||
|
||||
|
||||
def write_fields(fields, order):
|
||||
out = []
|
||||
for key in order:
|
||||
values = fields.get(key)
|
||||
if values:
|
||||
out.append("%" + key + "%\n" + "".join(v + "\n" for v in values))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def dep_name(dep):
|
||||
return re.split(r"[<>=]", dep, maxsplit=1)[0]
|
||||
|
||||
|
||||
def asset_name(name):
|
||||
return re.sub(r"[^A-Za-z0-9._-]", ".", name)
|
||||
|
||||
|
||||
def package_members(path):
|
||||
if path.endswith(".zst"):
|
||||
data = subprocess.run(["zstd", "-dc", path], check=True, stdout=subprocess.PIPE).stdout
|
||||
return tarfile.open(fileobj=io.BytesIO(data), mode="r:")
|
||||
return tarfile.open(path)
|
||||
|
||||
|
||||
def local_record(path, installed):
|
||||
with package_members(path) as tar:
|
||||
info, mtree, install, files = None, None, None, []
|
||||
for member in tar:
|
||||
name = member.name.removeprefix("./")
|
||||
if name == ".PKGINFO":
|
||||
info = tar.extractfile(member).read().decode("utf-8", "replace")
|
||||
elif name == ".MTREE":
|
||||
mtree = tar.extractfile(member).read()
|
||||
elif name == ".INSTALL":
|
||||
install = tar.extractfile(member).read()
|
||||
elif name in (".BUILDINFO", ".CHANGELOG") or not name:
|
||||
continue
|
||||
else:
|
||||
files.append(name.rstrip("/") + ("/" if member.isdir() else ""))
|
||||
if info is None or mtree is None:
|
||||
raise SystemExit(f"{path}: no .PKGINFO or .MTREE")
|
||||
fields, backup = {}, []
|
||||
for line in info.splitlines():
|
||||
if " = " not in line or line.startswith("#"):
|
||||
continue
|
||||
key, value = line.split(" = ", 1)
|
||||
if key == "backup":
|
||||
backup.append(value)
|
||||
elif key in PKGINFO:
|
||||
fields.setdefault(PKGINFO[key], []).append(value)
|
||||
fields["INSTALLDATE"] = [str(installed)]
|
||||
fields["VALIDATION"] = ["pgp"]
|
||||
for dir_ in sorted({f.rsplit("/", 1)[0] + "/" for f in files if "/" in f.rstrip("/")}):
|
||||
parts = dir_.rstrip("/").split("/")
|
||||
for i in range(1, len(parts) + 1):
|
||||
entry = "/".join(parts[:i]) + "/"
|
||||
if entry not in files:
|
||||
files.append(entry)
|
||||
sums = {}
|
||||
if backup:
|
||||
with package_members(path) as tar:
|
||||
for member in tar:
|
||||
name = member.name.removeprefix("./")
|
||||
if name in backup and member.isfile():
|
||||
sums[name] = hashlib.md5(tar.extractfile(member).read()).hexdigest()
|
||||
listing = "%FILES%\n" + "".join(f + "\n" for f in sorted(set(files)))
|
||||
if backup:
|
||||
listing += "\n%BACKUP%\n" + "".join(f"{b}\t{sums.get(b, '')}\n" for b in backup)
|
||||
return fields, listing, mtree, install
|
||||
|
||||
|
||||
def fetch(dest, *urls):
|
||||
for url in urls:
|
||||
if subprocess.run(["curl", "-fsSL", "--retry", "6", "--retry-delay", "5", "--retry-all-errors",
|
||||
"-o", dest, url]).returncode == 0:
|
||||
return
|
||||
raise SystemExit(f"could not download {os.path.basename(dest)}")
|
||||
|
||||
|
||||
def main():
|
||||
dbdir, cache, pkglist, runtime_file, mirror_file, tag, root, repo = sys.argv[1:9]
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
installed = int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
|
||||
|
||||
entries = {}
|
||||
for source, path in [("extra", os.path.join(here, "pins"))] + [(r, os.path.join(dbdir, "x_" + r)) for r in REPOS]:
|
||||
for entry in sorted(os.listdir(path)):
|
||||
fields = read_entry(os.path.join(path, entry))
|
||||
name = fields.get("NAME", [None])[0]
|
||||
if name and name not in entries:
|
||||
entries[name] = (source, fields)
|
||||
by_file = {fields["FILENAME"][0]: name for name, (_, fields) in entries.items()}
|
||||
|
||||
runtime = dict(line.split() for line in open(runtime_file) if len(line.split()) == 2)
|
||||
shipped = {}
|
||||
for line in open(pkglist):
|
||||
file = line.split()[0].split("/", 1)[1]
|
||||
shipped[by_file[file]] = file
|
||||
|
||||
local = os.path.join(root, "var/lib/pacman/local")
|
||||
os.makedirs(local, exist_ok=True)
|
||||
for name, file in sorted(shipped.items()):
|
||||
fields, listing, mtree, install = local_record(os.path.join(cache, file), installed)
|
||||
if fields["NAME"][0] != name:
|
||||
raise SystemExit(f"{file}: .PKGINFO names {fields['NAME'][0]}, not {name}")
|
||||
record = os.path.join(local, f"{name}-{fields['VERSION'][0]}")
|
||||
os.makedirs(record, exist_ok=True)
|
||||
with open(os.path.join(record, "desc"), "w") as out:
|
||||
out.write(write_fields(fields, FIELDS))
|
||||
with open(os.path.join(record, "files"), "w") as out:
|
||||
out.write(listing)
|
||||
with open(os.path.join(record, "mtree"), "wb") as out:
|
||||
out.write(mtree)
|
||||
if install:
|
||||
with open(os.path.join(record, "install"), "wb") as out:
|
||||
out.write(install)
|
||||
|
||||
system = set(runtime) | set(shipped)
|
||||
available = {n for n in entries if not BLOCKED.match(n)} | system
|
||||
providers = {}
|
||||
for name in available:
|
||||
if name in entries:
|
||||
for p in entries[name][1].get("PROVIDES", []):
|
||||
providers.setdefault(dep_name(p), name)
|
||||
satisfied = set(system)
|
||||
for name in system:
|
||||
if name in entries:
|
||||
satisfied.update(dep_name(p) for p in entries[name][1].get("PROVIDES", []))
|
||||
|
||||
wanted = [l.strip() for l in open(mirror_file) if l.strip() and not l.startswith("#")]
|
||||
mirrored, queue = set(), list(wanted)
|
||||
while queue:
|
||||
dep = dep_name(queue.pop())
|
||||
if dep in satisfied:
|
||||
continue
|
||||
name = dep if dep in available and dep in entries else providers.get(dep)
|
||||
if name is None:
|
||||
raise SystemExit(f"mirror.txt: nothing in the repository provides {dep}")
|
||||
if name in mirrored or name in system:
|
||||
continue
|
||||
mirrored.add(name)
|
||||
queue.extend(entries[name][1].get("DEPENDS", []))
|
||||
|
||||
os.makedirs(repo, exist_ok=True)
|
||||
for name in sorted(mirrored):
|
||||
source, fields = entries[name]
|
||||
file = fields["FILENAME"][0]
|
||||
dest = os.path.join(repo, asset_name(file))
|
||||
if not os.path.exists(dest) or hashlib.sha256(open(dest, "rb").read()).hexdigest() != fields["SHA256SUM"][0]:
|
||||
fetch(dest, f"{ALARM}/{source}/{file}")
|
||||
if hashlib.sha256(open(dest, "rb").read()).hexdigest() != fields["SHA256SUM"][0]:
|
||||
raise SystemExit(f"{file}: sha256 differs from the repository database's")
|
||||
signature = fields.get("PGPSIG", [None])[0]
|
||||
sig = dest + ".sig"
|
||||
if signature:
|
||||
with open(sig, "wb") as out:
|
||||
out.write(base64.b64decode(signature))
|
||||
else:
|
||||
fetch(sig, f"{ALARM}/{source}/{file}.sig")
|
||||
check = subprocess.run(["gpgv", "--status-fd", "1", "--keyring", os.path.join(here, "archlinuxarm-builder.gpg"),
|
||||
sig, dest], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True).stdout
|
||||
if not re.search(rf"^\[GNUPG:\] VALIDSIG .* {BUILDER}$", check, re.M):
|
||||
raise SystemExit(f"{file}: no valid Arch Linux ARM Build System signature")
|
||||
if not signature:
|
||||
fields["PGPSIG"] = [base64.b64encode(open(sig, "rb").read()).decode()]
|
||||
os.remove(sig)
|
||||
print(f"pacman: {len(shipped)} install records, {len(mirrored)} mirrored packages, "
|
||||
f"{sum(os.path.getsize(os.path.join(repo, asset_name(entries[n][1]['FILENAME'][0]))) for n in mirrored) // 1048576} MiB")
|
||||
|
||||
order = ["FILENAME", "NAME", "BASE", "VERSION", "DESC", "GROUPS", "CSIZE", "ISIZE", "MD5SUM", "SHA256SUM", "PGPSIG",
|
||||
"URL", "LICENSE", "ARCH", "BUILDDATE", "PACKAGER", "REPLACES", "CONFLICTS", "PROVIDES", "DEPENDS",
|
||||
"OPTDEPENDS", "MAKEDEPENDS", "CHECKDEPENDS", "XDATA"]
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.GNU_FORMAT) as db:
|
||||
for name in sorted(available):
|
||||
if name in entries and (name not in runtime or name in shipped or runtime[name] == entries[name][1]["VERSION"][0]):
|
||||
fields = dict(entries[name][1])
|
||||
else:
|
||||
fields = {"FILENAME": [f"{name}-{runtime[name]}-aarch64.pkg.tar.xz"], "NAME": [name],
|
||||
"VERSION": [runtime[name]], "ARCH": ["aarch64"]}
|
||||
if name in mirrored:
|
||||
fields["FILENAME"] = [asset_name(fields["FILENAME"][0])]
|
||||
data = write_fields(fields, order).encode()
|
||||
folder = f"{name}-{fields['VERSION'][0]}"
|
||||
info = tarfile.TarInfo(folder)
|
||||
info.type, info.mode, info.mtime = tarfile.DIRTYPE, 0o755, installed
|
||||
db.addfile(info)
|
||||
info = tarfile.TarInfo(folder + "/desc")
|
||||
info.size, info.mode, info.mtime = len(data), 0o644, installed
|
||||
db.addfile(info, io.BytesIO(data))
|
||||
with open(os.path.join(repo, "droiddeck.db"), "wb") as out:
|
||||
out.write(buffer.getvalue())
|
||||
|
||||
share = os.path.join(root, "usr/share/droiddeck/pacman")
|
||||
os.makedirs(os.path.join(share, "hooks"), exist_ok=True)
|
||||
with open(os.path.join(share, "droiddeck.db"), "wb") as out:
|
||||
out.write(buffer.getvalue())
|
||||
with open(os.path.join(share, "system-packages.txt"), "w") as out:
|
||||
out.write("".join(n + "\n" for n in sorted(system)))
|
||||
with open(os.path.join(share, "desktop-packages.txt"), "w") as out:
|
||||
out.write("".join(f"{n} {entries[n][1]['VERSION'][0]}\n" for n in sorted(shipped)))
|
||||
with open(os.path.join(share, "hooks", "droiddeck-system.hook"), "w") as out:
|
||||
out.write("[Trigger]\nOperation = Upgrade\nOperation = Remove\nType = Package\n")
|
||||
out.write("".join(f"Target = {n}\n" for n in sorted(system)))
|
||||
out.write("\n[Action]\nDescription = Keeping the packages DroidDeck installed...\nWhen = PreTransaction\n"
|
||||
"Exec = /usr/share/droiddeck/pacman/refuse\nNeedsTargets\nAbortOnFail\n")
|
||||
server = f"{RELEASES}/{tag}" if tag else f"{RELEASES}/unpublished"
|
||||
template = open(os.path.join(here, "pacman.conf.in")).read()
|
||||
with open(os.path.join(share, "pacman.conf"), "w") as out:
|
||||
out.write(template.replace("@SERVER@", server).replace("@ALARM@", ALARM))
|
||||
print(f"pacman: repository {server}, {len(available)} packages ({len(system)} installed by DroidDeck)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
[options]
|
||||
RootDir = /
|
||||
DBPath = /var/lib/pacman/
|
||||
CacheDir = /var/cache/pacman/pkg/
|
||||
LogFile = /var/log/pacman.log
|
||||
GPGDir = /etc/pacman.d/gnupg/
|
||||
HookDir = /etc/pacman.d/hooks/
|
||||
HookDir = /usr/share/droiddeck/pacman/hooks/
|
||||
HoldPkg = pacman glibc
|
||||
Architecture = aarch64
|
||||
Color
|
||||
ParallelDownloads = 4
|
||||
DisableSandbox
|
||||
SigLevel = Required DatabaseOptional
|
||||
LocalFileSigLevel = Optional
|
||||
NoExtract = usr/share/doc/* usr/share/gtk-doc/* usr/share/help/*
|
||||
|
||||
[droiddeck]
|
||||
Server = @SERVER@
|
||||
CacheServer = @ALARM@/extra
|
||||
CacheServer = @ALARM@/core
|
||||
CacheServer = @ALARM@/alarm
|
||||
@@ -0,0 +1,67 @@
|
||||
--- a/src/backends/wayland/wayland_backend.cpp
|
||||
+++ b/src/backends/wayland/wayland_backend.cpp
|
||||
@@ -30,6 +30,9 @@
|
||||
|
||||
#include <QAbstractEventDispatcher>
|
||||
|
||||
+#include <array>
|
||||
+#include <memory>
|
||||
+
|
||||
#include <drm_fourcc.h>
|
||||
#include <fcntl.h>
|
||||
#include <gbm.h>
|
||||
@@ -124,8 +127,31 @@
|
||||
}
|
||||
Q_EMIT pointerButtonChanged(button, state, std::chrono::milliseconds(time), this);
|
||||
});
|
||||
- // TODO: Send discreteDelta and source as well.
|
||||
- connect(pointer, &Pointer::axisChanged, this, [this](quint32 time, Pointer::Axis nativeAxis, qreal delta) {
|
||||
+ auto axisSource = std::make_shared<PointerAxisSource>(PointerAxisSource::Unknown);
|
||||
+ auto axisDiscrete = std::make_shared<std::array<qint32, 2>>();
|
||||
+ connect(pointer, &Pointer::axisSourceChanged, this, [axisSource](Pointer::AxisSource source) {
|
||||
+ switch (source) {
|
||||
+ case Pointer::AxisSource::Wheel:
|
||||
+ *axisSource = PointerAxisSource::Wheel;
|
||||
+ break;
|
||||
+ case Pointer::AxisSource::Finger:
|
||||
+ *axisSource = PointerAxisSource::Finger;
|
||||
+ break;
|
||||
+ case Pointer::AxisSource::Continuous:
|
||||
+ *axisSource = PointerAxisSource::Continuous;
|
||||
+ break;
|
||||
+ case Pointer::AxisSource::WheelTilt:
|
||||
+ *axisSource = PointerAxisSource::WheelTilt;
|
||||
+ break;
|
||||
+ default:
|
||||
+ *axisSource = PointerAxisSource::Unknown;
|
||||
+ break;
|
||||
+ }
|
||||
+ });
|
||||
+ connect(pointer, &Pointer::axisDiscreteChanged, this, [axisDiscrete](Pointer::Axis nativeAxis, qint32 discreteDelta) {
|
||||
+ (*axisDiscrete)[nativeAxis == Pointer::Axis::Vertical ? 0 : 1] = discreteDelta * 120;
|
||||
+ });
|
||||
+ connect(pointer, &Pointer::axisChanged, this, [this, axisSource, axisDiscrete](quint32 time, Pointer::Axis nativeAxis, qreal delta) {
|
||||
PointerAxis axis;
|
||||
switch (nativeAxis) {
|
||||
case Pointer::Axis::Horizontal:
|
||||
@@ -137,10 +163,18 @@
|
||||
default:
|
||||
Q_UNREACHABLE();
|
||||
}
|
||||
- Q_EMIT pointerAxisChanged(axis, delta, 0, PointerAxisSource::Unknown, false, false, std::chrono::milliseconds(time), this);
|
||||
+ qint32 &discrete = (*axisDiscrete)[nativeAxis == Pointer::Axis::Vertical ? 0 : 1];
|
||||
+ Q_EMIT pointerAxisChanged(axis, delta, discrete, *axisSource, false, false, std::chrono::milliseconds(time), this);
|
||||
+ discrete = 0;
|
||||
+ });
|
||||
+ connect(pointer, &Pointer::axisStopped, this, [this, axisSource](quint32 time, Pointer::Axis nativeAxis) {
|
||||
+ const PointerAxis axis = nativeAxis == Pointer::Axis::Vertical ? PointerAxis::Vertical : PointerAxis::Horizontal;
|
||||
+ Q_EMIT pointerAxisChanged(axis, 0, 0, *axisSource, false, false, std::chrono::milliseconds(time), this);
|
||||
});
|
||||
|
||||
- connect(pointer, &Pointer::frame, this, [this]() {
|
||||
+ connect(pointer, &Pointer::frame, this, [this, axisSource, axisDiscrete]() {
|
||||
+ *axisSource = PointerAxisSource::Unknown;
|
||||
+ axisDiscrete->fill(0);
|
||||
Q_EMIT pointerFrame(this);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
DESKTOP_KDE_REPO=Droid-Deck/DroidDeck-Components
|
||||
DESKTOP_KDE_TAG=desktop-kde-r2
|
||||
DESKTOP_KDE_SHA256=9ba832677b498654136c69d8c8330434d17e4d53cd099acac9bde3ba429b35bf
|
||||
DESKTOP_KDE_SIZE=846933224
|
||||
DESKTOP_KDE_TAG=desktop-kde-r3
|
||||
DESKTOP_KDE_SHA256=8b7142fcec8d86143ae39fc14ffc86907d30d9a5b5a45f49cb1b55109d6fc4eb
|
||||
DESKTOP_KDE_SIZE=972598429
|
||||
@@ -4,6 +4,7 @@
|
||||
Usage: removal-manifests.py <LXQt tar.zst> <KDE r1 tar.zst> <KDE r2 tar.zst>
|
||||
<emulators tar.zst> <verified KDE package cache> <output dir>
|
||||
<verified LXQt package cache>
|
||||
removal-manifests.py --add <KDE tar.zst> <tag> <sha256> <verified KDE package cache> <output dir>
|
||||
Removal includes desktop applications/themes and our overlay, not their shared dependencies.
|
||||
The KDE cache is verified against the published desktop-kde.packages.txt before use.
|
||||
The LXQt cache contains the signed application packages listed by desktop.packages.txt;
|
||||
@@ -63,10 +64,7 @@ def write(out, name, records):
|
||||
gz.write(('\n'.join(sorted(set(records))) + '\n').encode())
|
||||
|
||||
|
||||
def main():
|
||||
archives = [pathlib.Path(p) for p in sys.argv[1:5]]
|
||||
cache, out, legacy_cache = map(pathlib.Path, sys.argv[5:8])
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
def application_paths(here, cache):
|
||||
seeds = {line.strip() for line in (here / 'seeds.txt').read_text().splitlines() if line.strip() and not line.startswith('#')} - SHARED_SEEDS
|
||||
packages = dict(line.split() for line in (cache / 'desktop-kde.packages.txt').read_text().splitlines())
|
||||
selected = set()
|
||||
@@ -79,10 +77,39 @@ def main():
|
||||
if sha(archive) != digest:
|
||||
raise ValueError(f'{filename}: source package checksum mismatch')
|
||||
with tarfile.open(archive) as tar:
|
||||
selected.update(e.name.removeprefix('./').rstrip('/') for e in tar if not e.isdir())
|
||||
selected.update(e.name.removeprefix('./').rstrip('/') for e in tar if not e.isdir() and not e.name.removeprefix('./').startswith('.'))
|
||||
found.add(package)
|
||||
assert found == seeds, f'missing desktop packages: {seeds - found}'
|
||||
selected.update(str(p.relative_to(here / 'overlay')) for p in (here / 'overlay').rglob('*') if p.is_file())
|
||||
selected.update(str(p.relative_to(here / 'overlay')) for p in (here / 'overlay').rglob('*') if p.is_file() or p.is_symlink())
|
||||
return selected, packages, seeds
|
||||
|
||||
|
||||
def add(archive, tag, digest, cache, out):
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
selected, packages, seeds = application_paths(here, cache)
|
||||
inv = inventory(archive, digest)
|
||||
generated = ('usr/share/droiddeck/pacman/', 'usr/lib/droiddeck/')
|
||||
remove = gzip.decompress((out / 'kde-remove.tsv.gzip').read_bytes()).decode().splitlines()
|
||||
keep = gzip.decompress((out / 'kde-keep.txt.gzip').read_bytes()).decode().splitlines()
|
||||
remove += [record for path, record in inv.items() if path in selected or path.startswith(generated)]
|
||||
keep += list(inv)
|
||||
write(out, 'kde-remove.tsv.gzip', remove)
|
||||
write(out, 'kde-keep.txt.gzip', keep)
|
||||
versions = (out / 'versions.txt').read_text().split()
|
||||
(out / 'versions.txt').write_text('\n'.join(dict.fromkeys(versions + [tag])) + '\n')
|
||||
sources = json.loads((out / 'sources.json').read_text())
|
||||
sources['archives'][tag] = digest
|
||||
sources['desktopApplications'] = {n: h for n, h in packages.items() if n.rsplit('-', 3)[0] in seeds}
|
||||
(out / 'sources.json').write_text(json.dumps(sources, indent=2) + '\n')
|
||||
print(tag, digest)
|
||||
print('KDE removable paths', sum(path in selected or path.startswith(generated) for path in inv))
|
||||
|
||||
|
||||
def main():
|
||||
archives = [pathlib.Path(p) for p in sys.argv[1:5]]
|
||||
cache, out, legacy_cache = map(pathlib.Path, sys.argv[5:8])
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
selected, packages, seeds = application_paths(here, cache)
|
||||
inventories = [inventory(p, pin[1]) for p, pin in zip(archives, PINS)]
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
legacy_seeds = {line.strip() for line in (here / 'lxqt-applications.txt').read_text().splitlines()
|
||||
@@ -115,4 +142,7 @@ def main():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
if sys.argv[1:2] == ['--add']:
|
||||
add(pathlib.Path(sys.argv[2]), sys.argv[3], sys.argv[4], pathlib.Path(sys.argv[5]), pathlib.Path(sys.argv[6]))
|
||||
else:
|
||||
main()
|
||||
@@ -0,0 +1,190 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <grp.h>
|
||||
#include <pwd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define REAL(name) static __typeof__(name) *real_##name; if (!real_##name) real_##name = dlsym(RTLD_NEXT, #name)
|
||||
|
||||
static uid_t real_uid(void) { return (uid_t)syscall(SYS_getuid); }
|
||||
static gid_t real_gid(void) { return (gid_t)syscall(SYS_getgid); }
|
||||
|
||||
uid_t getuid(void) { return 0; }
|
||||
uid_t geteuid(void) { return 0; }
|
||||
gid_t getgid(void) { return 0; }
|
||||
gid_t getegid(void) { return 0; }
|
||||
|
||||
int getresuid(uid_t *r, uid_t *e, uid_t *s) {
|
||||
if (r) *r = 0;
|
||||
if (e) *e = 0;
|
||||
if (s) *s = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int getresgid(gid_t *r, gid_t *e, gid_t *s) {
|
||||
if (r) *r = 0;
|
||||
if (e) *e = 0;
|
||||
if (s) *s = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int setuid(uid_t u) { (void)u; return 0; }
|
||||
int seteuid(uid_t u) { (void)u; return 0; }
|
||||
int setgid(gid_t g) { (void)g; return 0; }
|
||||
int setegid(gid_t g) { (void)g; return 0; }
|
||||
int setreuid(uid_t r, uid_t e) { (void)r; (void)e; return 0; }
|
||||
int setregid(gid_t r, gid_t e) { (void)r; (void)e; return 0; }
|
||||
int setresuid(uid_t r, uid_t e, uid_t s) { (void)r; (void)e; (void)s; return 0; }
|
||||
int setresgid(gid_t r, gid_t e, gid_t s) { (void)r; (void)e; (void)s; return 0; }
|
||||
int setgroups(size_t n, const gid_t *list) { (void)n; (void)list; return 0; }
|
||||
int initgroups(const char *user, gid_t group) { (void)user; (void)group; return 0; }
|
||||
|
||||
static int owner_result(int rc) {
|
||||
if (rc != 0 && (errno == EPERM || errno == EINVAL)) {
|
||||
errno = 0;
|
||||
return 0;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
int chown(const char *path, uid_t u, gid_t g) {
|
||||
REAL(chown);
|
||||
return owner_result(real_chown(path, u, g));
|
||||
}
|
||||
|
||||
int lchown(const char *path, uid_t u, gid_t g) {
|
||||
REAL(lchown);
|
||||
return owner_result(real_lchown(path, u, g));
|
||||
}
|
||||
|
||||
int fchown(int fd, uid_t u, gid_t g) {
|
||||
REAL(fchown);
|
||||
return owner_result(real_fchown(fd, u, g));
|
||||
}
|
||||
|
||||
int fchownat(int dirfd, const char *path, uid_t u, gid_t g, int flags) {
|
||||
REAL(fchownat);
|
||||
return owner_result(real_fchownat(dirfd, path, u, g, flags));
|
||||
}
|
||||
|
||||
static struct passwd *as_root_user(struct passwd *pw) {
|
||||
if (pw && pw->pw_uid == real_uid()) {
|
||||
pw->pw_uid = 0;
|
||||
pw->pw_gid = 0;
|
||||
}
|
||||
return pw;
|
||||
}
|
||||
|
||||
static struct group *as_root_group(struct group *gr) {
|
||||
if (gr && gr->gr_gid == real_gid()) gr->gr_gid = 0;
|
||||
return gr;
|
||||
}
|
||||
|
||||
struct passwd *getpwuid(uid_t uid) {
|
||||
REAL(getpwuid);
|
||||
return as_root_user(real_getpwuid(uid == 0 ? real_uid() : uid));
|
||||
}
|
||||
|
||||
struct passwd *getpwnam(const char *name) {
|
||||
REAL(getpwnam);
|
||||
return as_root_user(real_getpwnam(name));
|
||||
}
|
||||
|
||||
struct passwd *getpwent(void) {
|
||||
REAL(getpwent);
|
||||
return as_root_user(real_getpwent());
|
||||
}
|
||||
|
||||
int getpwuid_r(uid_t uid, struct passwd *pw, char *buf, size_t len, struct passwd **out) {
|
||||
REAL(getpwuid_r);
|
||||
int rc = real_getpwuid_r(uid == 0 ? real_uid() : uid, pw, buf, len, out);
|
||||
if (rc == 0) as_root_user(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int getpwnam_r(const char *name, struct passwd *pw, char *buf, size_t len, struct passwd **out) {
|
||||
REAL(getpwnam_r);
|
||||
int rc = real_getpwnam_r(name, pw, buf, len, out);
|
||||
if (rc == 0) as_root_user(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
struct group *getgrgid(gid_t gid) {
|
||||
REAL(getgrgid);
|
||||
return as_root_group(real_getgrgid(gid == 0 ? real_gid() : gid));
|
||||
}
|
||||
|
||||
struct group *getgrnam(const char *name) {
|
||||
REAL(getgrnam);
|
||||
return as_root_group(real_getgrnam(name));
|
||||
}
|
||||
|
||||
int getgrgid_r(gid_t gid, struct group *gr, char *buf, size_t len, struct group **out) {
|
||||
REAL(getgrgid_r);
|
||||
int rc = real_getgrgid_r(gid == 0 ? real_gid() : gid, gr, buf, len, out);
|
||||
if (rc == 0) as_root_group(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int getgrnam_r(const char *name, struct group *gr, char *buf, size_t len, struct group **out) {
|
||||
REAL(getgrnam_r);
|
||||
int rc = real_getgrnam_r(name, gr, buf, len, out);
|
||||
if (rc == 0) as_root_group(*out);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int shown_mode(int rc, struct stat *st) {
|
||||
if (rc == 0 && S_ISDIR(st->st_mode) && (st->st_mode & 0777) == 0700) st->st_mode = (st->st_mode & ~0777) | 0755;
|
||||
return rc;
|
||||
}
|
||||
|
||||
int stat(const char *path, struct stat *st) {
|
||||
REAL(stat);
|
||||
return shown_mode(real_stat(path, st), st);
|
||||
}
|
||||
|
||||
int lstat(const char *path, struct stat *st) {
|
||||
REAL(lstat);
|
||||
return shown_mode(real_lstat(path, st), st);
|
||||
}
|
||||
|
||||
int fstat(int fd, struct stat *st) {
|
||||
REAL(fstat);
|
||||
return shown_mode(real_fstat(fd, st), st);
|
||||
}
|
||||
|
||||
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
|
||||
REAL(fstatat);
|
||||
return shown_mode(real_fstatat(dirfd, path, st, flags), st);
|
||||
}
|
||||
|
||||
int statx(int dirfd, const char *path, int flags, unsigned int mask, struct statx *st) {
|
||||
REAL(statx);
|
||||
int rc = real_statx(dirfd, path, flags, mask, st);
|
||||
if (rc == 0 && S_ISDIR(st->stx_mode) && (st->stx_mode & 0777) == 0700) st->stx_mode = (st->stx_mode & ~0777) | 0755;
|
||||
return rc;
|
||||
}
|
||||
|
||||
int stat64(const char *path, struct stat64 *st) {
|
||||
REAL(stat64);
|
||||
return shown_mode(real_stat64(path, st), (struct stat *)st);
|
||||
}
|
||||
|
||||
int lstat64(const char *path, struct stat64 *st) {
|
||||
REAL(lstat64);
|
||||
return shown_mode(real_lstat64(path, st), (struct stat *)st);
|
||||
}
|
||||
|
||||
int fstat64(int fd, struct stat64 *st) {
|
||||
REAL(fstat64);
|
||||
return shown_mode(real_fstat64(fd, st), (struct stat *)st);
|
||||
}
|
||||
|
||||
int fstatat64(int dirfd, const char *path, struct stat64 *st, int flags) {
|
||||
REAL(fstatat64);
|
||||
return shown_mode(real_fstatat64(dirfd, path, st, flags), (struct stat *)st);
|
||||
}
|
||||
@@ -26,3 +26,23 @@ noto-fonts-emoji
|
||||
xdg-utils
|
||||
firefox
|
||||
mpv
|
||||
zip
|
||||
unzip
|
||||
7zip
|
||||
unrar
|
||||
less
|
||||
man-db
|
||||
man-pages
|
||||
htop
|
||||
wl-clipboard
|
||||
xclip
|
||||
git
|
||||
wget
|
||||
kcalc
|
||||
okular
|
||||
filelight
|
||||
kfind
|
||||
plasma-systemmonitor
|
||||
elisa
|
||||
discover
|
||||
flatpak-kcm
|
||||
@@ -11,6 +11,7 @@ export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_S
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export KWIN_USE_OVERLAYS=0
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
for conf in client client-rt; do
|
||||
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
|
||||
@@ -35,7 +36,7 @@ cat > /usr/share/applications/droiddeck-steam-x64.desktop <<'ENTRY'
|
||||
Type=Application
|
||||
Name=Steam x86-64 (FEX, experimental)
|
||||
Comment=Valve's x86-64 Linux client under FEX, in its own home with its own login
|
||||
Exec=qterminal -e /usr/local/bin/droiddeck-steam-x64
|
||||
Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
@@ -43,6 +44,19 @@ python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
|
||||
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
|
||||
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
|
||||
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
|
||||
mkdir -p /usr/local/share/applications
|
||||
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Android keyboard
|
||||
Exec=/usr/local/bin/droiddeck-ime
|
||||
NoDisplay=true
|
||||
X-KDE-Wayland-VirtualKeyboard=true
|
||||
ENTRY
|
||||
input_method=$(kreadconfig6 --file kwinrc --group Wayland --key InputMethod 2>/dev/null)
|
||||
case $input_method in
|
||||
''|*/droiddeck-ime.desktop) kwriteconfig6 --file kwinrc --group Wayland --key InputMethod /usr/local/share/applications/droiddeck-ime.desktop ;;
|
||||
esac
|
||||
python3 /usr/local/bin/droiddeck-open --install 2>&1 | sed 's/^/[open] /'
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
[ -e /etc/xdg/kiorc ] || printf '[Executable scripts]\nbehaviourOnLaunch=execute\n' >/etc/xdg/kiorc 2>/dev/null
|
||||
@@ -55,6 +69,19 @@ if [ ! -e "$HOME/.config/droiddeck-desktop-icons" ]; then
|
||||
touch "$HOME/.config/droiddeck-desktop-icons"
|
||||
fi
|
||||
[ -f "$desktop_dir/Return.desktop" ] && cp -f /usr/share/applications/droiddeck-return-gaming.desktop "$desktop_dir/Return.desktop" 2>/dev/null
|
||||
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
|
||||
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
|
||||
fi
|
||||
skel_done=$HOME/.local/share/droiddeck/skel-copied
|
||||
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
|
||||
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
|
||||
mkdir -p "${skel_done%/*}" && : > "$skel_done"
|
||||
fi
|
||||
if [ -x /usr/lib/snapd/snap-confine ] && [ ! -d /var/lib/pacman ]; then
|
||||
/usr/local/bin/droiddeck-snapd >/dev/null 2>&1 &
|
||||
export XDG_DATA_DIRS=/var/lib/snapd/desktop:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
|
||||
export PATH=$PATH:/snap/bin
|
||||
fi
|
||||
update-mime-database /usr/share/mime >/dev/null 2>&1 &
|
||||
[ -f /usr/share/icons/hicolor/icon-theme.cache ] || gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null &
|
||||
[ -f /usr/share/glib-2.0/schemas/gschemas.compiled ] || glib-compile-schemas /usr/share/glib-2.0/schemas 2>/dev/null
|
||||
@@ -82,6 +109,10 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
|
||||
if [ -z "${KWIN_RENDER_NODES:-}" ] && [ -c /dev/dri/renderD0 ]; then
|
||||
export KWIN_RENDER_NODES=/dev/dri/renderD0
|
||||
fi
|
||||
mkdir -p /run/droiddeck/kwin
|
||||
printf '#!/bin/sh\nGALLIUM_THREAD=0 exec /usr/bin/kwin_wayland "$@"\n' > /run/droiddeck/kwin/kwin_wayland
|
||||
chmod 755 /run/droiddeck/kwin/kwin_wayland
|
||||
export PATH=/run/droiddeck/kwin:$PATH
|
||||
fi
|
||||
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
|
||||
dbus-run-session -- startplasma-wayland
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/python3
|
||||
import base64
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
@@ -87,6 +88,7 @@ class Spec:
|
||||
self.info_fds = []
|
||||
self.json_fds = []
|
||||
self.keep_fds = []
|
||||
self.lock_files = []
|
||||
self.command = []
|
||||
self.argv0 = None
|
||||
|
||||
@@ -159,6 +161,8 @@ def parse(argv):
|
||||
read_fd(int(args[0]))
|
||||
elif a == "--sync-fd":
|
||||
s.keep_fds.append(int(args[0]))
|
||||
elif a == "--lock-file":
|
||||
s.lock_files.append(args[0])
|
||||
elif a == "--info-fd":
|
||||
s.info_fds.append(int(args[0]))
|
||||
elif a == "--json-status-fd":
|
||||
@@ -203,6 +207,31 @@ def remaps_nothing(s):
|
||||
return True
|
||||
|
||||
|
||||
def host_path(s, path):
|
||||
for op in reversed(s.ops):
|
||||
if op["t"] != "bind":
|
||||
continue
|
||||
dest = op["dest"].rstrip("/")
|
||||
if path == dest or path.startswith(dest + "/"):
|
||||
return op["src"].rstrip("/") + path[len(dest):]
|
||||
return path
|
||||
|
||||
|
||||
def hold_locks(s):
|
||||
for path in s.lock_files:
|
||||
try:
|
||||
fd = os.open(host_path(s, path), os.O_RDONLY)
|
||||
except OSError as e:
|
||||
sys.stderr.write("bwrap: Can't open lock file %s: %s\n" % (path, e.strerror))
|
||||
sys.exit(1)
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
except OSError as e:
|
||||
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
|
||||
sys.exit(1)
|
||||
os.set_inheritable(fd, True)
|
||||
|
||||
|
||||
def report_pid(s, pid):
|
||||
for fd in s.info_fds:
|
||||
try:
|
||||
@@ -282,7 +311,7 @@ def run_by_app(s):
|
||||
if payload is None:
|
||||
break
|
||||
if kind == b"P":
|
||||
report_pid(s, int(payload))
|
||||
report_pid(s, os.getpid())
|
||||
elif kind == b"O":
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
@@ -301,6 +330,7 @@ def run_by_app(s):
|
||||
|
||||
def main():
|
||||
s = parse(expand(sys.argv[1:]))
|
||||
hold_locks(s)
|
||||
if remaps_nothing(s):
|
||||
run_here(s)
|
||||
else:
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
free_name() {
|
||||
local dir=$1 name=$2 base ext n=2
|
||||
[ -e "$dir/$name" ] || { echo "$name"; return; }
|
||||
base=${name%.*} ext=
|
||||
[ "$base" != "$name" ] && [ -n "$base" ] && ext=.${name##*.} || base=$name
|
||||
while [ -e "$dir/$base ($n)$ext" ]; do n=$((n + 1)); done
|
||||
echo "$base ($n)$ext"
|
||||
}
|
||||
share() {
|
||||
local android=$HOME/Storage/$1 link=$HOME/$2 f
|
||||
[ -d "$android" ] && [ -w "$android" ] || return 0
|
||||
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
|
||||
if [ -L "$link" ]; then
|
||||
rm -f "$link"
|
||||
elif [ -d "$link" ]; then
|
||||
shopt -s dotglob nullglob
|
||||
for f in "$link"/*; do
|
||||
mv -n -- "$f" "$android/$(free_name "$android" "${f##*/}")" || return 1
|
||||
done
|
||||
shopt -u dotglob nullglob
|
||||
rmdir "$link" 2>/dev/null || mv "$link" "$link.old.$$" || return 1
|
||||
elif [ -e "$link" ]; then
|
||||
mv "$link" "$link.old.$$" || return 1
|
||||
fi
|
||||
ln -s "$android" "$link"
|
||||
}
|
||||
status=0
|
||||
share Download Downloads || status=1
|
||||
share Documents Documents || status=1
|
||||
exit $status
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
set -u
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
cores="libretro-core-info libretro-beetle-pce-fast libretro-beetle-psx libretro-beetle-vb libretro-beetle-wswan
|
||||
libretro-bsnes-mercury-performance libretro-desmume libretro-gambatte libretro-genesisplusgx libretro-mgba
|
||||
libretro-nestopia libretro-sameboy libretro-snes9x"
|
||||
case "${1:-}" in
|
||||
install)
|
||||
echo "== STEP RetroArch"
|
||||
droiddeck-root /usr/bin/apt-get update -q || { echo "== FAIL apt-get update"; exit 1; }
|
||||
droiddeck-root /usr/bin/apt-get install -y -q retroarch retroarch-assets $cores || { echo "== FAIL apt-get install"; exit 1; }
|
||||
echo "== STEP PPSSPP"
|
||||
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || { echo "== FAIL flathub"; exit 1; }
|
||||
flatpak install --user -y --noninteractive flathub org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
|
||||
printf '#!/bin/sh\nexec /usr/local/bin/droiddeck-flatpak-run org.ppsspp.PPSSPP "$@"\n' > /usr/local/bin/PPSSPPSDL.new &&
|
||||
chmod 755 /usr/local/bin/PPSSPPSDL.new && mv -f /usr/local/bin/PPSSPPSDL.new /usr/local/bin/PPSSPPSDL || { echo "== FAIL PPSSPPSDL"; exit 1; }
|
||||
;;
|
||||
*)
|
||||
echo "usage: droiddeck-emulators install" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -5,6 +5,7 @@ step() { echo "== STEP $*"; }
|
||||
fail() { echo "== FAIL $*"; exit 1; }
|
||||
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
|
||||
|
||||
if command -v pacman >/dev/null 2>&1; then
|
||||
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
|
||||
while read -r pkg probe; do
|
||||
[ -n "$pkg" ] || continue
|
||||
@@ -77,7 +78,13 @@ done
|
||||
mv -f "$WORK/installed.new" "$WORK/installed"
|
||||
find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null
|
||||
|
||||
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
|
||||
else
|
||||
command -v flatpak >/dev/null 2>&1 || fail "Flatpak is missing from the runtime"
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
fi
|
||||
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/lib/aarch64-linux-gnu/libflatpak.so.0 /usr/lib/aarch64-linux-gnu/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
|
||||
[ -e "$f" ] || continue
|
||||
ldd "$f" 2>&1 | grep -E 'not found|version .* not found'
|
||||
done | sort -u)
|
||||
[ -z "$missing" ] || { echo "$missing"; fail "Flatpak is missing libraries"; }
|
||||
@@ -97,7 +104,7 @@ Description=Central repository of Flatpak applications
|
||||
Icon=https://dl.flathub.org/repo/logo.svg
|
||||
GPGKey=mQINBFlD2sABEADsiUZUOYBg1UdDaWkEdJYkTSZD68214m8Q1fbrP5AptaUfCl8KYKFMNoAJRBXn9FbE6q6VBzghHXj/rSnA8WPnkbaEWR7xltOqzB1yHpCQ1l8xSfH5N02DMUBSRtD/rOYsBKbaJcOgW0K21sX+BecMY/AI2yADvCJEjhVKrjR9yfRX+NQEhDcbXUFRGt9ZT+TI5yT4xcwbvvTu7aFUR/dH7+wjrQ7lzoGlZGFFrQXSs2WI0WaYHWDeCwymtohXryF8lcWQkhH8UhfNJVBJFgCY8Q6UHkZG0FxMu8xnIDBMjBmSZKwKQn0nwzwM2afskZEnmNPYDI8nuNsSZBZSAw+ThhkdCZHZZRwzmjzyRuLLVFpOj3XryXwZcSefNMPDkZAuWWzPYjxS80cm2hG1WfqrG0Gl8+iX69cbQchb7gbEb0RtqNskTo9DDmO0bNKNnMbzmIJ3/rTbSahKSwtewklqSP/01o0WKZiy+n/RAkUKOFBprjJtWOZkc8SPXV/rnoS2dWsJWQZhuPPtv3tefdDiEyp7ePrfgfKxuHpZES0IZRiFI4J/nAUP5bix+srcIxOVqAam68CbAlPvWTivRUMRVbKjJiGXIOJ78wAMjqPg3QIC0GQ0EPAWwAOzzpdgbnG7TCQetaVV8rSYCuirlPYN+bJIwBtkOC9SWLoPMVZTwQARAQABtC5GbGF0aHViIFJlcG8gU2lnbmluZyBLZXkgPGZsYXRodWJAZmxhdGh1Yi5vcmc+iQJUBBMBCAA+FiEEblwF2XnHba+TwIE1QYTdTZB6fK4FAllD2sACGwMFCRLMAwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQQYTdTZB6fK5RJQ/+Ptd4sWxaiAW91FFk7+wmYOkEe1NY2UDNJjEEz34PNP/1RoxveHDt43kYJQ23OWaPJuZAbu+fWtjRYcMBzOsMCaFcRSHFiDIC9aTp4ux/mo+IEeyarYt/oyKb5t5lta6xaAqg7rwt65jW5/aQjnS4h7eFZ+dAKta7Y/fljNrOznUp81/SMcx4QA5G2Pw0hs4Xrxg59oONOTFGBgA6FF8WQghrpR7SnEe0FSEOVsAjwQ13Cfkfa7b70omXSWp7GWfUzgBKyoWxKTqzMN3RQHjjhPJcsQnrqH5enUu4Pcb2LcMFpzimHnUgb9ft72DP5wxfzHGAWOUiUXHbAekfq5iFks8cha/RST6wkxG3Rf44Zn09aOxh1btMcGL+5xb1G0BuCQnA0fP/kDYIPwh9z22EqwRQOspIcvGeLVkFeIfubxpcMdOfQqQnZtHMCabV5Q/Rk9K1ZGc8M2hlg8gHbXMFch2xJ0Wu72eXbA/UY5MskEeBgawTQnQOK/vNm7t0AJMpWK26Qg6178UmRghmeZDj9uNRc3EI1nSbgvmGlpDmCxaAGqaGL1zW4KPW5yN25/qeqXcgCvUjZLI9PNq3Kvizp1lUrbx7heRiSoazCucvHQ1VHUzcPVLUKKTkoTP8okThnRRRsBcZ1+jI4yMWIDLOCT7IW3FePr+3xyuy5eEo9a25Ag0EWUPa7AEQALT/CmSyZ8LWlRYQZKYw417p7Z2hxqd6TjwkwM3IQ1irumkWcTZBZIbBgrSOg6CcXD2oWydCQHWi9qaxhuhEl2bJL5LskmBcMxVdQeD0LLHd8QUnbnnIby8ocvWN1alPfvJFjCUTrmD22U1ycOzRw2lIe4kiQONbOZtdWrVImQQSndjFlisitbmlWHvHm2lOOYy8+GJB7YffVV193hmnBSJffCy4bvkuLxsI+n1DhOzc7MPV3z6HGk4HiEcF0yyt9tCYhpsxHFdBoq2h771HfAcS0s98EVAqYMFnf9em+4cnYpdI6mhIfS1FQiKl6DBAYA8tT3ggla00DurPo0JwX/zN+PaO5h/6O9aCZwV7G6rbkgMuqMergXaf8oP38gr0z+MqWnkfM63Bodq68GP4l4hd02BoFBbDf38TMuGQB14+twJMdfbAxo2MbgluvQgfwHfZ2ca6gyEY+9s/YD1gugLjV+S6CB51WkFNe1z4tAPgJZNxUcKCbeaHNbthl8Hks/pY9RCEseX/EdfzF18epbSjJMPh4DPQXbUoFwmyuYcoBOPmvZHNl9hK7B/1RP8w1ZrXk8qdupC0SNbafX7270B7lMMVImzZetGsM9ypXJ6llhp3FwW09iseNyGJGPsr/dvTMGDXqOPfU/9SAS1LSTY4K9PbRtdrBE318YX8mIk5ABEBAAGJBHIEGAEIACYWIQRuXAXZecdtr5PAgTVBhN1NkHp8rgUCWUPa7AIbAgUJEswDAAJACRBBhN1NkHp8rsF0IAQZAQgAHRYhBFSmzd2JGfsgQgDYrFYnAunj7X7oBQJZQ9rsAAoJEFYnAunj7X7oR6AP/0KYmiAFeqx14Z43/6s2gt3VhxlSd8bmcVV7oJFbMhdHBIeWBp2BvsUf00I0Zl14ZkwCKfLwbbORC2eIxvzJ+QWjGfPhDmS4XUSmhlXxWnYEveSek5Tde+fmu6lqKM8CHg5BNx4GWIX/vdLi1wWJZyhrUwwICAxkuhKxuP2Z1An48930eslTD2GGcjByc27+9cIZjHKa07I/aLffo04V+oMT9/tgzoquzgpVV4jwekADo2MJjhkkPveSNI420bgT+Q7Fi1l0X1aFUniBvQMsaBa27PngWm6xE2ZYvh7nWCdd5g0c0eLIHxWwzV1lZ4Ryx4ITO/VL25ItECcjhTRdYa64sA62MYSaB0x3eR+SihpgP3wSNPFu3MJo6FKTFdi4CBAEmpWHFW7FcRmd+cQXeFrHLN3iNVWryy0HK/CUEJmiZEmpNiXecl4vPIIuyF0zgSCztQtKoMr+injpmQGC/rF/ELBVZTUSLNB350S0Ztvw0FKWDAJSxFmoxt3xycqvvt47rxTrhi78nkk6jATKGyvP55sO+K7Q7Wh0DXA69hvPrYW2eu8jGCdVGxi6HX7L1qcfEd0378S71dZ3g9o6KKl1OsDWWQ6MJ6FGBZedl/ibRfs8p5+sbCX3lQSjEFy3rx6n0rUrXx8U2qb+RCLzJlmC5MNBOTDJwHPcX6gKsUcXZrEQALmRHoo3SrewO41RCr+5nUlqiqV3AohBMhnQbGzyHf2+drutIaoh7Rj80XRh2bkkuPLwlNPf+bTXwNVGse4bej7B3oV6Ae1N7lTNVF4Qh+1OowtGjmfJPWo0z1s6HFJVxoIof9z58Msvgao0zrKGqaMWaNQ6LUeC9g9Aj/9Uqjbo8X54aLiYs8Z1WNc06jKP+gv8AWLtv6CR+l2kLez1YMDucjm7v6iuCMVAmZdmxhg5I/X2+OM3vBsqPDdQpr2TPDLX3rCrSBiS0gOQ6DwN5N5QeTkxmY/7QO8bgLo/Wzu1iilH4vMKW6LBKCaRx5UEJxKpL4wkgITsYKneIt3NTHo5EOuaYk+y2+Dvt6EQFiuMsdbfUjs3seIHsghX/cbPJa4YUqZAL8C4OtVHaijwGo0ymt9MWvS9yNKMyT0JhN2/BdeOVWrHk7wXXJn/ZjpXilicXKPx4udCF76meE+6N2u/T+RYZ7fP1QMEtNZNmYDOfA6sViuPDfQSHLNbauJBo/n1sRYAsL5mcG22UDchJrlKvmK3EOADCQg+myrm8006LltubNB4wWNzHDJ0Ls2JGzQZCd/xGyVmUiidCBUrD537WdknOYE4FD7P0cHaM9brKJ/M8LkEH0zUlo73bY4XagbnCqve6PvQb5G2Z55qhWphd6f4B6DGed86zJEa/RhS
|
||||
REPO
|
||||
if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; then
|
||||
if ! flatpak remote-list --columns=name 2>/dev/null | grep -qx flathub; then
|
||||
out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1)
|
||||
rc=$?
|
||||
echo "$out"
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
DISPLAY_ID = 1
|
||||
REGISTRY_ID = 2
|
||||
METHOD_ID = 3
|
||||
SETTLE = 0.15
|
||||
|
||||
|
||||
def wl_string(value):
|
||||
data = value.encode() + b"\0"
|
||||
return struct.pack("<I", len(data)) + data + b"\0" * (-len(data) % 4)
|
||||
|
||||
|
||||
def read_string(payload, offset):
|
||||
(length,) = struct.unpack_from("<I", payload, offset)
|
||||
start = offset + 4
|
||||
text = payload[start:start + length - 1].decode(errors="replace")
|
||||
return text, start + length + (-length % 4)
|
||||
|
||||
|
||||
class Connection:
|
||||
def __init__(self, sock):
|
||||
self.sock = sock
|
||||
self.buffer = b""
|
||||
|
||||
def send(self, obj, opcode, payload=b""):
|
||||
self.sock.sendall(struct.pack("<II", obj, ((8 + len(payload)) << 16) | opcode) + payload)
|
||||
|
||||
def messages(self, timeout):
|
||||
ready, _, _ = select.select([self.sock], [], [], timeout)
|
||||
if not ready:
|
||||
return []
|
||||
data, _, _, _ = self.sock.recvmsg(65536, socket.CMSG_SPACE(16 * 4))
|
||||
if not data:
|
||||
raise EOFError
|
||||
self.buffer += data
|
||||
out = []
|
||||
while len(self.buffer) >= 8:
|
||||
obj, word = struct.unpack_from("<II", self.buffer)
|
||||
size = word >> 16
|
||||
if size < 8 or len(self.buffer) < size:
|
||||
break
|
||||
out.append((obj, word & 0xFFFF, self.buffer[8:size]))
|
||||
self.buffer = self.buffer[size:]
|
||||
return out
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self, directory):
|
||||
self.directory = directory
|
||||
self.seq = 0
|
||||
self.sent = None
|
||||
|
||||
def write(self, field, hint=0, purpose=0):
|
||||
state = (field, purpose)
|
||||
if state == self.sent or not self.directory:
|
||||
return
|
||||
self.sent = state
|
||||
self.seq += 1
|
||||
os.makedirs(self.directory, exist_ok=True)
|
||||
target = os.path.join(self.directory, "ime.json")
|
||||
temp = target + ".tmp"
|
||||
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as handle:
|
||||
json.dump({"textField": field, "hint": hint, "purpose": purpose, "seq": self.seq}, handle)
|
||||
os.replace(temp, target)
|
||||
print(f"droiddeck-ime: text field {'focused' if field else 'left'}", file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def connect():
|
||||
fd = os.environ.pop("WAYLAND_SOCKET", "")
|
||||
if fd.isdigit():
|
||||
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, fileno=int(fd))
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.connect(os.path.join(os.environ["XDG_RUNTIME_DIR"], os.environ.get("WAYLAND_DISPLAY", "wayland-0")))
|
||||
return sock
|
||||
|
||||
|
||||
def main():
|
||||
launch = os.environ.get("BL_LAUNCH_DIR", "")
|
||||
report = Report(os.path.join(launch, "agent") if launch else "")
|
||||
conn = Connection(connect())
|
||||
conn.send(DISPLAY_ID, 1, struct.pack("<I", REGISTRY_ID))
|
||||
contexts = {}
|
||||
current = None
|
||||
pending = None
|
||||
while True:
|
||||
timeout = None if pending is None else max(0.0, pending - time.monotonic())
|
||||
try:
|
||||
batch = conn.messages(timeout)
|
||||
except (EOFError, ConnectionError):
|
||||
report.write(False)
|
||||
return 0
|
||||
for obj, opcode, payload in batch:
|
||||
if obj == DISPLAY_ID and opcode == 0:
|
||||
_, code = struct.unpack_from("<II", payload)
|
||||
message, _ = read_string(payload, 8)
|
||||
print(f"droiddeck-ime: protocol error {code}: {message}", file=sys.stderr, flush=True)
|
||||
report.write(False)
|
||||
return 1
|
||||
if obj == REGISTRY_ID and opcode == 0:
|
||||
(name,) = struct.unpack_from("<I", payload)
|
||||
interface, offset = read_string(payload, 4)
|
||||
(version,) = struct.unpack_from("<I", payload, offset)
|
||||
if interface == "zwp_input_method_v1":
|
||||
conn.send(REGISTRY_ID, 0, struct.pack("<I", name) + wl_string(interface)
|
||||
+ struct.pack("<II", min(version, 1), METHOD_ID))
|
||||
elif obj == METHOD_ID and opcode == 0:
|
||||
(context,) = struct.unpack_from("<I", payload)
|
||||
contexts[context] = [0, 0]
|
||||
current = context
|
||||
pending = None
|
||||
report.write(True)
|
||||
elif obj == METHOD_ID and opcode == 1:
|
||||
(context,) = struct.unpack_from("<I", payload)
|
||||
contexts.pop(context, None)
|
||||
conn.send(context, 0)
|
||||
if context == current:
|
||||
current = None
|
||||
pending = time.monotonic() + SETTLE
|
||||
elif obj in contexts and opcode == 2:
|
||||
hint, purpose = struct.unpack_from("<II", payload)
|
||||
contexts[obj] = [hint, purpose]
|
||||
if obj == current:
|
||||
report.write(True, hint, purpose)
|
||||
if pending is not None and time.monotonic() >= pending:
|
||||
pending = None
|
||||
if current is None:
|
||||
report.write(False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/python3
|
||||
import array
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
SOCKET_FILE = "/etc/droiddeck/root-socket"
|
||||
|
||||
|
||||
def socket_name():
|
||||
name = os.environ.get("DROIDDECK_ROOT_SOCKET", "")
|
||||
if not name:
|
||||
try:
|
||||
with open(SOCKET_FILE, encoding="utf-8") as f:
|
||||
name = f.read().strip()
|
||||
except OSError:
|
||||
pass
|
||||
return "\0" + (name or "com.droiddeck.launcher.root")
|
||||
|
||||
|
||||
def frame(sock, kind, payload):
|
||||
sock.sendall(kind.encode() + struct.pack(">i", len(payload)) + payload)
|
||||
|
||||
|
||||
def read_exact(sock, n):
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
chunk = sock.recv(n - len(data))
|
||||
if not chunk:
|
||||
return None
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 2 or argv[1] in ("-h", "--help"):
|
||||
print("usage: droiddeck-root [--check] command [arg ...]", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.connect(socket_name())
|
||||
except OSError as e:
|
||||
print(f"droiddeck-root: DroidDeck's root service is not reachable: {e}", file=sys.stderr)
|
||||
return 126
|
||||
if argv[1] == "--check":
|
||||
return 0
|
||||
env = dict(os.environ)
|
||||
for name in ("LD_PRELOAD", "PROOT_FASTPATH", "DROIDDECK_ROOT_SOCKET"):
|
||||
env.pop(name, None)
|
||||
for name in [k for k in env if k.startswith("PROOT_")]:
|
||||
env.pop(name, None)
|
||||
try:
|
||||
cwd = os.getcwd()
|
||||
except OSError:
|
||||
cwd = "/root"
|
||||
body = json.dumps({"argv": argv[1:], "env": env, "cwd": cwd}).encode()
|
||||
fds = array.array("i", [0, 1, 2])
|
||||
sock.sendmsg([b"R" + struct.pack(">i", len(body))], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
|
||||
sock.sendall(body)
|
||||
|
||||
def forward(signum, _frame):
|
||||
try:
|
||||
frame(sock, "S", str(signum).encode())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2):
|
||||
signal.signal(signum, forward)
|
||||
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
|
||||
status = 1
|
||||
while True:
|
||||
try:
|
||||
head = read_exact(sock, 5)
|
||||
except InterruptedError:
|
||||
continue
|
||||
except OSError:
|
||||
break
|
||||
if head is None:
|
||||
break
|
||||
kind = chr(head[0])
|
||||
payload = read_exact(sock, struct.unpack(">i", head[1:])[0]) or b""
|
||||
if kind == "E":
|
||||
print("droiddeck-root: " + payload.decode(errors="replace"), file=sys.stderr)
|
||||
elif kind == "X":
|
||||
status = int(payload.decode() or "1")
|
||||
break
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -14,22 +14,48 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
|
||||
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
|
||||
mv -f "$BL_LOG" "$BL_LOG.1"
|
||||
fi
|
||||
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
dd=$(command -v gnudd || echo dd)
|
||||
exec > >({ "$dd" of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
echo "== droiddeck-session $(date) mode=$mode $*"
|
||||
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
||||
fi
|
||||
|
||||
write_system_bus_config() {
|
||||
mkdir -p /run/dbus /usr/local/share/droiddeck
|
||||
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>system</type>
|
||||
<listen>unix:path=/run/dbus/system_bus_socket</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<servicedir>/usr/share/droiddeck/system-services</servicedir>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
<allow own="*"/>
|
||||
<allow send_destination="*"/>
|
||||
<allow receive_sender="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
BUSCONF
|
||||
rm -f /run/dbus/system_bus_socket
|
||||
}
|
||||
|
||||
prepare_locale() {
|
||||
local dir=/usr/lib/locale stamp=/usr/lib/locale/.droiddeck-archive want have= pkg
|
||||
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
|
||||
want=${pkg[0]##*/}
|
||||
if [ -d /var/lib/pacman/local ]; then
|
||||
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
|
||||
want=${pkg[0]##*/}
|
||||
else
|
||||
want=libc6-$(dpkg-query -W -f='${Version}' libc6 2>/dev/null)
|
||||
fi
|
||||
[ -f "$stamp" ] && read -r have < "$stamp"
|
||||
[ "$have" = "$want" ] && [ -f "$dir/locale-archive" ] && [ ! "$dir/locale-archive" -nt "$stamp" ] && return 0
|
||||
[ -d "$dir/C.utf8" ] && command -v localedef >/dev/null 2>&1 || return 0
|
||||
DROIDDECK_LINK_RENAME=1 localedef --add-to-archive --replace "$dir/C.utf8" >/dev/null 2>&1 || return 0
|
||||
rm -f /usr/lib/gconv/gconv-modules.cache
|
||||
rm -f /usr/lib/gconv/gconv-modules.cache /usr/lib/aarch64-linux-gnu/gconv/gconv-modules.cache
|
||||
command -v iconvconfig >/dev/null 2>&1 && iconvconfig >/dev/null 2>&1
|
||||
printf '%s\n' "$want" > "$stamp"
|
||||
echo "== locale archive built for $want"
|
||||
@@ -65,7 +91,16 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
fi
|
||||
|
||||
steam_update_stuck() {
|
||||
[ "$1" -lt 60 ] || steam_updates=0
|
||||
local stamp
|
||||
stamp=$(stat -c '%n %Y %s' "${steam_root:-}"/package/*.installed 2>/dev/null)
|
||||
if [ "$1" -ge 60 ]; then
|
||||
steam_updates=0
|
||||
steam_installs=0
|
||||
elif [ "$stamp" != "${steam_update_stamp-$stamp}" ] && [ "${steam_installs:-0}" -lt 5 ]; then
|
||||
steam_updates=0
|
||||
steam_installs=$((${steam_installs:-0} + 1))
|
||||
fi
|
||||
steam_update_stamp=$stamp
|
||||
steam_updates=$((steam_updates + 1))
|
||||
[ "$steam_updates" -ge 3 ]
|
||||
}
|
||||
@@ -134,6 +169,7 @@ rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
|
||||
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
|
||||
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
|
||||
/usr/local/bin/droiddeck-desktop-bookmarks || true
|
||||
/usr/local/bin/droiddeck-downloads || true
|
||||
fi
|
||||
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
|
||||
export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
|
||||
@@ -201,6 +237,20 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
step "starting the desktop"
|
||||
start_agent --no-focus
|
||||
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
write_system_bus_config
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
for _ in $(seq 1 50); do
|
||||
[ -S /run/dbus/system_bus_socket ] && break
|
||||
nap 0.1
|
||||
done
|
||||
if [ -S /run/dbus/system_bus_socket ]; then
|
||||
droiddeck-login1 --with-netmanager &
|
||||
echo "== desktop: system bus up, network and power services running"
|
||||
else
|
||||
echo "== desktop: the system bus did not come up"
|
||||
fi
|
||||
fi
|
||||
cores=$(program_cores)
|
||||
if [ -n "$cores" ]; then
|
||||
echo "== desktop cores: $cores (the desktop and every program started from it)"
|
||||
@@ -842,23 +892,7 @@ case $mode in
|
||||
set -- "$@" "$_bl_url"
|
||||
fi
|
||||
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
|
||||
mkdir -p /run/dbus /usr/local/share/droiddeck
|
||||
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>system</type>
|
||||
<listen>unix:path=/run/dbus/system_bus_socket</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
<allow own="*"/>
|
||||
<allow send_destination="*"/>
|
||||
<allow receive_sender="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
BUSCONF
|
||||
rm -f /run/dbus/system_bus_socket
|
||||
write_system_bus_config
|
||||
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
|
||||
system_bus=$!
|
||||
for _ in $(seq 1 50); do
|
||||
@@ -998,6 +1032,8 @@ BUSCONF
|
||||
fi
|
||||
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
|
||||
steam_updates=0
|
||||
steam_installs=0
|
||||
steam_update_stamp=$(stat -c '%n %Y %s' "$steam_root"/package/*.installed 2>/dev/null)
|
||||
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
|
||||
steam_other_game_running() {
|
||||
local line value n open
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
[ "${1:-}" = run ] || exec /usr/bin/snap "$@"
|
||||
shift
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--) shift; break ;;
|
||||
-*) shift ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
target=${1:?usage: snap run <snap>[.<app>] [args...]}
|
||||
shift
|
||||
name=${target%%.*}
|
||||
app=${target#*.}
|
||||
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/bash
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--classic) shift ;;
|
||||
--base) shift 2 ;;
|
||||
--*) shift ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
tag=${1:?security tag}
|
||||
shift
|
||||
[ "${1##*/}" = snap-exec ] && shift
|
||||
app=${1:-}
|
||||
shift
|
||||
name=${tag#snap.}
|
||||
name=${name%%.*}
|
||||
app=${app#*.}
|
||||
[ -n "$app" ] || app=$name
|
||||
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
SNAP_DIR = "/snap"
|
||||
HOST_DIRS = ("/etc", "/home", "/root", "/tmp", "/run", "/var/snap", "/var/lib/snapd", "/var/tmp", "/var/log",
|
||||
"/media", "/mnt", "/snap", "/usr/src", "/lib/modules")
|
||||
|
||||
|
||||
def load(name):
|
||||
with open(f"{SNAP_DIR}/{name}/current/meta/snap.yaml") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
|
||||
|
||||
def expand(value, env):
|
||||
return re.sub(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?", lambda m: env.get(m.group(1), ""), str(value))
|
||||
|
||||
|
||||
def provider_path(path, provider, revision):
|
||||
snap = f"{SNAP_DIR}/{provider}/{revision}"
|
||||
for var, value in (("$SNAP_DATA", f"/var/snap/{provider}/{revision}"),
|
||||
("$SNAP_COMMON", f"/var/snap/{provider}/common"), ("$SNAP", snap)):
|
||||
if path == var or path.startswith(var + "/"):
|
||||
return os.path.normpath(value + path[len(var):])
|
||||
return os.path.normpath(f"{snap}/{path}")
|
||||
|
||||
|
||||
def content_binds(name, meta, env):
|
||||
out = []
|
||||
for plug_name, plug in (meta.get("plugs") or {}).items():
|
||||
if not isinstance(plug, dict) or plug.get("interface") != "content" or not plug.get("target"):
|
||||
continue
|
||||
provider = (plug.get("default-provider") or "").split(":")[0]
|
||||
if not provider or not os.path.isdir(f"{SNAP_DIR}/{provider}/current"):
|
||||
continue
|
||||
try:
|
||||
slots = load(provider).get("slots") or {}
|
||||
except OSError:
|
||||
continue
|
||||
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{provider}/current"))
|
||||
target = expand(plug["target"], env)
|
||||
for slot_name, slot in slots.items():
|
||||
if not isinstance(slot, dict) or slot.get("interface") != "content":
|
||||
continue
|
||||
if slot.get("content", slot_name) != plug.get("content", plug_name):
|
||||
continue
|
||||
nested = "source" in slot
|
||||
reads = (slot.get("source") or {}).get("read") if nested else slot.get("read")
|
||||
for path in reads or []:
|
||||
source = provider_path(str(path), provider, revision)
|
||||
out.append((plug_name, source, os.path.join(target, os.path.basename(source)) if nested else target))
|
||||
if not nested:
|
||||
break
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 3:
|
||||
print("usage: droiddeck-snap-run SNAP APP [ARG...]", file=sys.stderr)
|
||||
return 2
|
||||
name, app, args = argv[1], argv[2], argv[3:]
|
||||
meta = load(name)
|
||||
spec = (meta.get("apps") or {}).get(app)
|
||||
if spec is None:
|
||||
print(f"error: snap \"{name}\" has no app \"{app}\"", file=sys.stderr)
|
||||
return 1
|
||||
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{name}/current"))
|
||||
home = os.environ.get("HOME", "/root")
|
||||
snap = f"{SNAP_DIR}/{name}/{revision}"
|
||||
env = dict(os.environ)
|
||||
for k in ("LD_PRELOAD", "LD_LIBRARY_PATH"):
|
||||
env.pop(k, None)
|
||||
env.update({
|
||||
"SNAP": snap, "SNAP_NAME": name, "SNAP_INSTANCE_NAME": name, "SNAP_INSTANCE_KEY": "",
|
||||
"SNAP_REVISION": revision, "SNAP_VERSION": str(meta.get("version", "")), "SNAP_ARCH": "arm64",
|
||||
"SNAP_LIBRARY_PATH": "/var/lib/snapd/lib/gl:/var/lib/snapd/lib/gl32:/var/lib/snapd/void",
|
||||
"SNAP_DATA": f"/var/snap/{name}/{revision}", "SNAP_COMMON": f"/var/snap/{name}/common",
|
||||
"SNAP_USER_DATA": f"{home}/snap/{name}/{revision}", "SNAP_USER_COMMON": f"{home}/snap/{name}/common",
|
||||
"SNAP_REAL_HOME": home, "SNAP_UID": str(os.getuid()), "SNAP_EUID": str(os.geteuid()),
|
||||
"SNAP_COOKIE": "", "SNAP_CONTEXT": "", "SNAP_REEXEC": "0",
|
||||
})
|
||||
for d in (env["SNAP_USER_DATA"], env["SNAP_USER_COMMON"], env["SNAP_DATA"], env["SNAP_COMMON"]):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
current = f"{home}/snap/{name}/current"
|
||||
if os.path.realpath(current) != env["SNAP_USER_DATA"]:
|
||||
try:
|
||||
os.unlink(current)
|
||||
except OSError:
|
||||
pass
|
||||
os.symlink(revision, current)
|
||||
confinement = meta.get("confinement", "strict")
|
||||
if confinement != "classic":
|
||||
env["HOME"] = env["SNAP_USER_DATA"]
|
||||
env["PATH"] = ":".join([f"{snap}/usr/sbin", f"{snap}/usr/bin", f"{snap}/sbin", f"{snap}/bin",
|
||||
"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/games"])
|
||||
env["LD_LIBRARY_PATH"] = env["SNAP_LIBRARY_PATH"]
|
||||
for scope in (meta.get("environment") or {}, spec.get("environment") or {}):
|
||||
for k, v in scope.items():
|
||||
env[k] = expand(v, env)
|
||||
command = shlex.split(expand(spec.get("command", ""), env))
|
||||
if command and not command[0].startswith("/"):
|
||||
command[0] = f"{snap}/{command[0]}"
|
||||
chain = [c if c.startswith("/") else f"{snap}/{c}" for c in (meta.get("command-chain") or []) + (spec.get("command-chain") or [])]
|
||||
program = chain + command + args
|
||||
if confinement == "classic":
|
||||
os.execvpe(program[0], program, env)
|
||||
base = meta.get("base") or "core"
|
||||
root = f"{SNAP_DIR}/{base}/current"
|
||||
if not os.path.isdir(root):
|
||||
print(f"error: the base snap \"{base}\" is not installed; run: snap install {base}", file=sys.stderr)
|
||||
return 1
|
||||
bwrap = ["/usr/local/bin/droiddeck-bwrap", "--bind", root, "/", "--dev-bind", "/dev", "/dev", "--proc", "/proc",
|
||||
"--bind", "/sys", "/sys"]
|
||||
for d in HOST_DIRS:
|
||||
if os.path.isdir(d):
|
||||
bwrap += ["--bind", d, d]
|
||||
bwrap += ["--bind", "/", "/var/lib/snapd/hostfs"]
|
||||
bwrap += ["--bind", "/dev/null", "/etc/ld.so.preload"]
|
||||
binds = content_binds(name, meta, env)
|
||||
for _, source, target in binds:
|
||||
if os.path.isdir(source):
|
||||
bwrap += ["--bind", source, target]
|
||||
content = {k for k, v in (meta.get("plugs") or {}).items() if isinstance(v, dict) and v.get("interface") == "content"}
|
||||
plugs = (set(meta.get("plugs") or {}) | set(spec.get("plugs") or [])) - content | {plug for plug, _, _ in binds}
|
||||
env["DROIDDECK_SNAP_PLUGS"] = " ".join(sorted(plugs))
|
||||
bwrap += ["--bind", "/usr/local/bin/droiddeck-snapctl", "/usr/lib/snapd/snapctl"]
|
||||
bwrap += ["--chdir", os.getcwd() if os.path.isdir(os.getcwd()) else env["HOME"], "--clearenv"]
|
||||
for k, v in env.items():
|
||||
bwrap += ["--setenv", k, v]
|
||||
os.execv(bwrap[0], bwrap + ["--"] + program)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
case $1 in
|
||||
is-connected)
|
||||
shift
|
||||
while [ $# -gt 1 ]; do shift; done
|
||||
case " $DROIDDECK_SNAP_PLUGS " in
|
||||
*" ${1:-} "*) exit 0 ;;
|
||||
esac
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
#!/usr/bin/python3
|
||||
import datetime
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socketserver
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
STORE = "https://api.snapcraft.io/v2"
|
||||
ARCH = "arm64"
|
||||
SNAP_DIR = "/snap"
|
||||
BIN_DIR = "/snap/bin"
|
||||
LIB = "/var/lib/snapd"
|
||||
STATE = LIB + "/droiddeck-state.json"
|
||||
DESKTOP_DIR = LIB + "/desktop/applications"
|
||||
SOCKETS = ("/run/snapd.socket", "/run/snapd-snap.socket")
|
||||
FIND_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
|
||||
"media,categories,store-url,download,type,channel,common-ids,links")
|
||||
INFO_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
|
||||
"media,categories,snap-id,store-url,download,type,channel-map,common-ids,links,created-at")
|
||||
HEADERS = {"Snap-Device-Series": "16", "Snap-Device-Architecture": ARCH, "User-Agent": "snapd/2.70 droiddeck"}
|
||||
|
||||
lock = threading.RLock()
|
||||
install_lock = threading.Lock()
|
||||
changes = {}
|
||||
change_seq = [0]
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
|
||||
|
||||
def load_state():
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {"snaps": {}}
|
||||
|
||||
|
||||
def save_state(state):
|
||||
tmp = STATE + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(state, f, indent=1)
|
||||
os.replace(tmp, STATE)
|
||||
|
||||
|
||||
def store_get(path, params=None):
|
||||
url = STORE + path + ("?" + urllib.parse.urlencode(params) if params else "")
|
||||
req = urllib.request.Request(url, headers=HEADERS)
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def publisher(p):
|
||||
p = p or {}
|
||||
return {"id": p.get("id", ""), "username": p.get("username", ""), "display-name": p.get("display-name", ""),
|
||||
"validation": p.get("validation", "unproven")}
|
||||
|
||||
|
||||
def media_of(snap):
|
||||
out = []
|
||||
for m in snap.get("media") or []:
|
||||
if m.get("type") in ("icon", "screenshot", "banner") and m.get("url"):
|
||||
item = {"type": m["type"], "url": m["url"]}
|
||||
if m.get("width"):
|
||||
item["width"] = m["width"]
|
||||
item["height"] = m.get("height", 0)
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def icon_of(media):
|
||||
return next((m["url"] for m in media if m["type"] == "icon"), "")
|
||||
|
||||
|
||||
def from_store(name, snap, revision=None, channel=None):
|
||||
media = media_of(snap)
|
||||
rev = revision or snap.get("revision") or {}
|
||||
out = {
|
||||
"id": snap.get("snap-id", ""), "name": name, "title": snap.get("title") or name,
|
||||
"summary": snap.get("summary", ""), "description": snap.get("description", ""),
|
||||
"type": rev.get("type") or snap.get("type") or "app", "version": rev.get("version", ""),
|
||||
"revision": str(rev.get("revision", "")), "channel": channel or "stable",
|
||||
"confinement": rev.get("confinement") or "strict", "base": rev.get("base") or "",
|
||||
"publisher": publisher(snap.get("publisher")), "developer": (snap.get("publisher") or {}).get("username", ""),
|
||||
"license": snap.get("license", ""), "contact": snap.get("contact", ""), "website": snap.get("website", ""),
|
||||
"media": media, "icon": icon_of(media), "store-url": snap.get("store-url", ""),
|
||||
"download-size": (rev.get("download") or {}).get("size", 0), "status": "available",
|
||||
"categories": [{"name": c.get("name", ""), "featured": bool(c.get("featured"))} for c in snap.get("categories") or []],
|
||||
"common-ids": rev.get("common-ids") or snap.get("common-ids") or [],
|
||||
"private": False, "devmode": False, "jailmode": False, "trymode": False, "apps": [],
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def installed_snap(name, entry):
|
||||
snap = dict(entry["info"])
|
||||
snap["status"] = "active"
|
||||
snap["install-date"] = entry.get("installed", now())
|
||||
snap["installed-size"] = entry.get("size", 0)
|
||||
snap["revision"] = str(entry["revision"])
|
||||
snap["version"] = entry.get("version", snap.get("version", ""))
|
||||
snap["tracking-channel"] = entry.get("channel", "latest/stable")
|
||||
snap["channel"] = entry.get("channel", "latest/stable")
|
||||
snap["mounted-from"] = f"{LIB}/snaps/{name}_{entry['revision']}.snap"
|
||||
snap["apps"] = [{"name": a, "snap": name, "desktop-file": f"{DESKTOP_DIR}/{name}_{a}.desktop"} for a in entry.get("apps", [])]
|
||||
return snap
|
||||
|
||||
|
||||
def find(query, section=None, name_exact=False):
|
||||
if name_exact:
|
||||
try:
|
||||
info = store_get(f"/snaps/info/{query}", {"architecture": ARCH, "fields": INFO_FIELDS})
|
||||
except Exception:
|
||||
return []
|
||||
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
|
||||
and c["channel"]["risk"] == "stable"), None)
|
||||
if not rev:
|
||||
return []
|
||||
return [from_store(info["name"], dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, "stable")]
|
||||
params = {"architecture": ARCH, "fields": FIND_FIELDS}
|
||||
if query:
|
||||
params["q"] = query
|
||||
if section:
|
||||
params["category"] = section
|
||||
if not query and not section:
|
||||
params["featured"] = "true"
|
||||
result = store_get("/snaps/find", params)
|
||||
out = []
|
||||
state = load_state()
|
||||
for r in result.get("results", []):
|
||||
snap = from_store(r["name"], dict(r.get("snap", {}), **{"snap-id": r.get("snap-id", "")}), r.get("revision"))
|
||||
if r["name"] in state["snaps"]:
|
||||
snap["status"] = "active"
|
||||
snap["installed-size"] = state["snaps"][r["name"]].get("size", 0)
|
||||
out.append(snap)
|
||||
return out
|
||||
|
||||
|
||||
def new_change(kind, summary, snaps):
|
||||
with lock:
|
||||
change_seq[0] += 1
|
||||
cid = str(change_seq[0])
|
||||
changes[cid] = {"id": cid, "kind": kind, "summary": summary, "status": "Doing", "ready": False,
|
||||
"spawn-time": now(), "tasks": [{"id": cid + "-1", "kind": kind, "summary": summary, "status": "Doing",
|
||||
"progress": {"label": "", "done": 0, "total": 1},
|
||||
"spawn-time": now()}],
|
||||
"data": {"snap-names": snaps}}
|
||||
return cid
|
||||
|
||||
|
||||
def progress(cid, label, done, total):
|
||||
with lock:
|
||||
task = changes[cid]["tasks"][0]
|
||||
task["progress"] = {"label": label, "done": done, "total": max(total, 1)}
|
||||
task["summary"] = changes[cid]["summary"]
|
||||
|
||||
|
||||
def finish(cid, err=None):
|
||||
with lock:
|
||||
c = changes[cid]
|
||||
c["status"] = "Error" if err else "Done"
|
||||
c["ready"] = True
|
||||
c["ready-time"] = now()
|
||||
c["tasks"][0]["status"] = c["status"]
|
||||
if err:
|
||||
c["err"] = err
|
||||
|
||||
|
||||
def root_run(argv):
|
||||
if os.getuid() == 0:
|
||||
return subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
return subprocess.run(["/usr/local/bin/droiddeck-root"] + argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True)
|
||||
|
||||
|
||||
def snap_yaml(path):
|
||||
try:
|
||||
import yaml
|
||||
with open(path) as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def download(cid, name, url, sha3, size, target):
|
||||
tmp = target + ".partial"
|
||||
h = hashlib.sha3_384()
|
||||
req = urllib.request.Request(url, headers=HEADERS)
|
||||
with urllib.request.urlopen(req, timeout=120) as r, open(tmp, "wb") as out:
|
||||
done = 0
|
||||
while True:
|
||||
chunk = r.read(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
out.write(chunk)
|
||||
h.update(chunk)
|
||||
done += len(chunk)
|
||||
progress(cid, f"Download snap \"{name}\"", done, size)
|
||||
if sha3 and h.hexdigest() != sha3:
|
||||
os.unlink(tmp)
|
||||
raise RuntimeError(f"{name}: downloaded snap does not match the store's sha3-384")
|
||||
os.replace(tmp, target)
|
||||
|
||||
|
||||
def write_desktop(name, rev, meta):
|
||||
os.makedirs(DESKTOP_DIR, exist_ok=True)
|
||||
gui = f"{SNAP_DIR}/{name}/{rev}/meta/gui"
|
||||
apps = (meta.get("apps") or {})
|
||||
for app, spec in apps.items():
|
||||
source = os.path.join(gui, f"{app}.desktop")
|
||||
if (spec or {}).get("daemon") or not os.path.isfile(source):
|
||||
continue
|
||||
command = name if app == name else f"{name}.{app}"
|
||||
out = []
|
||||
with open(source, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
if line.startswith("Exec="):
|
||||
args = line[5:].strip().split(" ", 1)
|
||||
rest = (" " + args[1]) if len(args) > 1 else ""
|
||||
line = f"Exec={BIN_DIR}/{command}{rest}\n"
|
||||
elif line.startswith("Icon="):
|
||||
line = "Icon=" + line[5:].replace("${SNAP}", f"{SNAP_DIR}/{name}/current")
|
||||
out.append(line)
|
||||
out.append(f"X-SnapInstanceName={name}\n")
|
||||
target = f"{DESKTOP_DIR}/{name}_{app}.desktop"
|
||||
with open(target + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.writelines(out)
|
||||
os.replace(target + ".tmp", target)
|
||||
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def link_bins(name, meta):
|
||||
os.makedirs(BIN_DIR, exist_ok=True)
|
||||
apps = []
|
||||
for app, spec in (meta.get("apps") or {}).items():
|
||||
if (spec or {}).get("daemon"):
|
||||
continue
|
||||
command = name if app == name else f"{name}.{app}"
|
||||
path = os.path.join(BIN_DIR, command)
|
||||
with open(path + ".tmp", "w") as f:
|
||||
f.write(f"#!/bin/sh\nexec /usr/local/bin/droiddeck-snap-run {name} {app} \"$@\"\n")
|
||||
os.chmod(path + ".tmp", 0o755)
|
||||
os.replace(path + ".tmp", path)
|
||||
apps.append(app)
|
||||
return apps
|
||||
|
||||
|
||||
def remove_tree(top):
|
||||
if os.path.isdir(top) and not os.path.islink(top):
|
||||
os.chmod(top, 0o700)
|
||||
for root, dirs, _ in os.walk(top):
|
||||
for d in dirs:
|
||||
path = os.path.join(root, d)
|
||||
if not os.path.islink(path):
|
||||
os.chmod(path, 0o700)
|
||||
shutil.rmtree(top, ignore_errors=True)
|
||||
|
||||
|
||||
def install_one(cid, name, channel, state, parents=()):
|
||||
if name in state["snaps"] or name in parents:
|
||||
return
|
||||
info = store_get(f"/snaps/info/{name}", {"architecture": ARCH, "fields": INFO_FIELDS})
|
||||
risk = channel.split("/")[-1] if channel else "stable"
|
||||
track = channel.split("/")[0] if channel and "/" in channel else "latest"
|
||||
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
|
||||
and c["channel"]["risk"] == risk and c["channel"]["track"] == track), None)
|
||||
if not rev:
|
||||
raise RuntimeError(f"snap \"{name}\" has no {track}/{risk} release for {ARCH}")
|
||||
number = rev["revision"]
|
||||
os.makedirs(f"{LIB}/snaps", exist_ok=True)
|
||||
blob = f"{LIB}/snaps/{name}_{number}.snap"
|
||||
d = rev.get("download") or {}
|
||||
with lock:
|
||||
changes[cid]["summary"] = f"Install \"{name}\" snap"
|
||||
download(cid, name, d["url"], d.get("sha3-384"), d.get("size", 0), blob)
|
||||
progress(cid, f"Unpack snap \"{name}\"", 0, 1)
|
||||
target = f"{SNAP_DIR}/{name}/{number}"
|
||||
remove_tree(target)
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
r = root_run(["unsquashfs", "-q", "-n", "-no-xattrs", "-f", "-excludes", "-d", target, blob, "dev"])
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError(f"cannot unpack {name}: {r.stdout.strip()[-400:]}")
|
||||
os.makedirs(f"{target}/dev", exist_ok=True)
|
||||
current = f"{SNAP_DIR}/{name}/current"
|
||||
if os.path.islink(current):
|
||||
os.unlink(current)
|
||||
os.symlink(str(number), current)
|
||||
for sub in (f"/var/snap/{name}/{number}", f"/var/snap/{name}/common"):
|
||||
os.makedirs(sub, exist_ok=True)
|
||||
cur = f"/var/snap/{name}/current"
|
||||
if os.path.islink(cur):
|
||||
os.unlink(cur)
|
||||
os.symlink(str(number), cur)
|
||||
meta = snap_yaml(f"{target}/meta/snap.yaml")
|
||||
entry = {"revision": number, "version": rev.get("version", ""), "channel": f"{track}/{risk}",
|
||||
"installed": now(), "size": d.get("size", 0), "info": from_store(name, dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, f"{track}/{risk}"),
|
||||
"base": meta.get("base") or ("core" if (meta.get("type") or "app") == "app" else ""), "apps": []}
|
||||
base = meta.get("base")
|
||||
if (meta.get("type") or "app") == "app":
|
||||
install_one(cid, base or "core", "latest/stable", state, parents + (name,))
|
||||
for plug in (meta.get("plugs") or {}).values():
|
||||
if isinstance(plug, dict) and plug.get("interface") == "content" and plug.get("default-provider"):
|
||||
provider = plug["default-provider"].split(":")[0]
|
||||
install_one(cid, provider, "latest/stable", state, parents + (name,))
|
||||
entry["apps"] = link_bins(name, meta)
|
||||
write_desktop(name, number, meta)
|
||||
state["snaps"][name] = entry
|
||||
save_state(state)
|
||||
|
||||
|
||||
def remove_one(name, state):
|
||||
entry = state["snaps"].pop(name, None)
|
||||
if not entry:
|
||||
raise RuntimeError(f"snap \"{name}\" is not installed")
|
||||
for app in entry.get("apps", []):
|
||||
command = name if app == name else f"{name}.{app}"
|
||||
try:
|
||||
os.unlink(os.path.join(BIN_DIR, command))
|
||||
except OSError:
|
||||
pass
|
||||
if os.path.isdir(DESKTOP_DIR):
|
||||
for f in os.listdir(DESKTOP_DIR):
|
||||
if f.startswith(name + "_") and f.endswith(".desktop"):
|
||||
os.unlink(os.path.join(DESKTOP_DIR, f))
|
||||
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
remove_tree(f"{SNAP_DIR}/{name}")
|
||||
for f in os.listdir(f"{LIB}/snaps"):
|
||||
if f.startswith(name + "_"):
|
||||
os.unlink(os.path.join(f"{LIB}/snaps", f))
|
||||
save_state(state)
|
||||
|
||||
|
||||
def run_change(cid, action, names, channel):
|
||||
with install_lock:
|
||||
apply_change(cid, action, names, channel)
|
||||
|
||||
|
||||
def apply_change(cid, action, names, channel):
|
||||
try:
|
||||
state = load_state()
|
||||
for name in names:
|
||||
if action == "install":
|
||||
install_one(cid, name, channel or "latest/stable", state)
|
||||
elif action == "remove":
|
||||
remove_one(name, state)
|
||||
elif action == "refresh":
|
||||
old = state["snaps"].get(name)
|
||||
if old:
|
||||
remove_one(name, state)
|
||||
install_one(cid, name, old.get("channel", "latest/stable"), state)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported action {action}")
|
||||
finish(cid)
|
||||
except Exception as e:
|
||||
finish(cid, str(e))
|
||||
|
||||
|
||||
SECTIONS = ["featured", "art-and-design", "books-and-reference", "development", "devices-and-iot", "education",
|
||||
"entertainment", "finance", "games", "health-and-fitness", "music-and-audio", "news-and-weather",
|
||||
"personalisation", "photo-and-video", "productivity", "science", "security", "server-and-cloud",
|
||||
"social", "utilities"]
|
||||
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
def address_string(self):
|
||||
return "snapd"
|
||||
|
||||
def reply(self, body, code=200, kind="sync"):
|
||||
payload = {"type": kind, "status-code": code, "status": http.client.responses.get(code, "")}
|
||||
payload.update(body)
|
||||
data = json.dumps(payload).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def ok(self, result):
|
||||
self.reply({"result": result})
|
||||
|
||||
def error(self, code, message, kind=""):
|
||||
self.reply({"result": {"message": message, "kind": kind}}, code, "error")
|
||||
|
||||
def body(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n) if n else b"{}"
|
||||
try:
|
||||
return json.loads(raw or b"{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
def do_GET(self):
|
||||
url = urllib.parse.urlsplit(self.path)
|
||||
q = urllib.parse.parse_qs(url.query)
|
||||
path = url.path
|
||||
try:
|
||||
if path == "/v2/system-info":
|
||||
return self.ok({"series": "16", "version": "2.70+droiddeck", "build-id": "droiddeck", "os-release": {"id": "ubuntu", "version-id": "26.04"},
|
||||
"on-classic": True, "managed": False, "kernel-version": os.uname().release,
|
||||
"locations": {"snap-mount-dir": SNAP_DIR, "snap-bin-dir": BIN_DIR},
|
||||
"refresh": {"timer": "00:00~24:00/4"}, "confinement": "partial",
|
||||
"sandbox-features": {}, "architecture": ARCH})
|
||||
if path == "/v2/snaps":
|
||||
state = load_state()
|
||||
wanted = (q.get("snaps", [""])[0] or "").split(",")
|
||||
snaps = [installed_snap(n, e) for n, e in state["snaps"].items() if not wanted[0] or n in wanted]
|
||||
return self.ok(snaps)
|
||||
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
|
||||
if m:
|
||||
state = load_state()
|
||||
if m.group(1) in state["snaps"]:
|
||||
return self.ok(installed_snap(m.group(1), state["snaps"][m.group(1)]))
|
||||
return self.error(404, f"snap not installed", "snap-not-found")
|
||||
if path == "/v2/find":
|
||||
name = q.get("name", [None])[0]
|
||||
query = name or q.get("q", [""])[0]
|
||||
section = q.get("section", [None])[0] or q.get("category", [None])[0]
|
||||
if section == "featured":
|
||||
section = None
|
||||
select = q.get("select", [""])[0]
|
||||
if select == "refresh":
|
||||
return self.ok([])
|
||||
if select == "private":
|
||||
return self.ok([])
|
||||
return self.ok(find(query, section, bool(name)))
|
||||
if path in ("/v2/sections",):
|
||||
return self.ok(SECTIONS)
|
||||
if path == "/v2/categories":
|
||||
return self.ok([{"name": s} for s in SECTIONS if s != "featured"])
|
||||
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
|
||||
if m:
|
||||
with lock:
|
||||
c = changes.get(m.group(1))
|
||||
c = json.loads(json.dumps(c)) if c else None
|
||||
return self.ok(c) if c else self.error(404, "cannot find change", "")
|
||||
if path == "/v2/changes":
|
||||
with lock:
|
||||
return self.ok([json.loads(json.dumps(c)) for c in changes.values()])
|
||||
m = re.fullmatch(r"/v2/icons/([^/]+)/icon", path)
|
||||
if m:
|
||||
return self.icon(m.group(1))
|
||||
if path == "/v2/apps":
|
||||
state = load_state()
|
||||
apps = [{"snap": n, "name": a, "desktop-file": f"{DESKTOP_DIR}/{n}_{a}.desktop"}
|
||||
for n, e in state["snaps"].items() for a in e.get("apps", [])]
|
||||
return self.ok(apps)
|
||||
if path in ("/v2/connections", "/v2/interfaces"):
|
||||
return self.ok({"established": [], "plugs": [], "slots": []})
|
||||
if path in ("/v2/aliases", "/v2/users", "/v2/notices", "/v2/assertions/model"):
|
||||
return self.ok({} if path == "/v2/aliases" else [])
|
||||
return self.error(404, f"not found: {path}")
|
||||
except Exception as e:
|
||||
return self.error(500, str(e))
|
||||
|
||||
def icon(self, name):
|
||||
state = load_state()
|
||||
entry = state["snaps"].get(name)
|
||||
if not entry:
|
||||
return self.error(404, "not installed", "snap-not-found")
|
||||
for candidate in ("meta/gui/icon.png", "meta/gui/icon.svg"):
|
||||
path = f"{SNAP_DIR}/{name}/current/{candidate}"
|
||||
if os.path.isfile(path):
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "image/svg+xml" if path.endswith("svg") else "image/png")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
return self.error(404, "no icon", "")
|
||||
|
||||
def do_POST(self):
|
||||
path = urllib.parse.urlsplit(self.path).path
|
||||
body = self.body()
|
||||
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
|
||||
if m or path == "/v2/snaps":
|
||||
names = [m.group(1)] if m else body.get("snaps") or []
|
||||
action = body.get("action", "")
|
||||
channel = body.get("channel") or ""
|
||||
if channel and "/" not in channel:
|
||||
channel = "latest/" + channel
|
||||
if action not in ("install", "remove", "refresh"):
|
||||
return self.error(400, f"unsupported action \"{action}\"")
|
||||
cid = new_change(f"{action}-snap", f"{action.capitalize()} {', '.join(names)}", names)
|
||||
threading.Thread(target=run_change, args=(cid, action, names, channel), daemon=True).start()
|
||||
return self.reply({"change": cid}, 202, "async")
|
||||
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
|
||||
if m:
|
||||
return self.error(400, "changes cannot be aborted")
|
||||
if path in ("/v2/login", "/v2/logout", "/v2/snapctl"):
|
||||
return self.error(400, "not supported by DroidDeck's snap service")
|
||||
return self.error(404, f"not found: {path}")
|
||||
|
||||
def do_PUT(self):
|
||||
return self.do_POST()
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
daemon_threads = True
|
||||
|
||||
def get_request(self):
|
||||
conn, _ = self.socket.accept()
|
||||
return conn, ("snapd", 0)
|
||||
|
||||
|
||||
def serve(path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
server = Server(path, Handler)
|
||||
os.chmod(path, 0o666)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
for d in (LIB, SNAP_DIR, BIN_DIR, DESKTOP_DIR, LIB + "/snaps"):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
threads = [threading.Thread(target=serve, args=(p,), daemon=True) for p in SOCKETS]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -39,6 +39,7 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
|
||||
exit 69
|
||||
fi
|
||||
[ "$url" = steam://exit ] && exit 0
|
||||
export BL_INSIDE=1 BL_STEAM_UI=desktop
|
||||
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
|
||||
fi
|
||||
|
||||
@@ -6,6 +6,7 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
|
||||
for arg in "$@"; do
|
||||
case $arg in
|
||||
steam://*) url=$arg ;;
|
||||
-shutdown) url=steam://exit ;;
|
||||
-gamepadui|-bigpicture) ui=bigpicture ;;
|
||||
esac
|
||||
done
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/python3
|
||||
import os
|
||||
import sys
|
||||
|
||||
REAL = "/usr/bin/systemd-run"
|
||||
VALUED = {"-u", "--unit", "-p", "--property", "--description", "--slice", "-E", "--setenv",
|
||||
"--working-directory", "--uid", "--gid", "--nice", "-H", "--host", "-M", "--machine",
|
||||
"--on-active", "--on-boot", "--on-startup", "--on-unit-active", "--on-unit-inactive",
|
||||
"--on-calendar", "--path-property", "--socket-property", "--timer-property", "--service-type",
|
||||
"--shell", "--slice-inherit"}
|
||||
|
||||
|
||||
def main(argv):
|
||||
args = argv[1:]
|
||||
if "--user" not in args:
|
||||
os.execv(REAL, [REAL] + args)
|
||||
env = dict(os.environ)
|
||||
cwd = None
|
||||
foreground = False
|
||||
i = 0
|
||||
while i < len(args):
|
||||
a = args[i]
|
||||
if a == "--":
|
||||
i += 1
|
||||
break
|
||||
if not a.startswith("-"):
|
||||
break
|
||||
name, _, inline = a.partition("=")
|
||||
value = inline if inline else (args[i + 1] if name in VALUED and i + 1 < len(args) else "")
|
||||
if name in ("-E", "--setenv") and "=" in value:
|
||||
k, _, v = value.partition("=")
|
||||
env[k] = v
|
||||
elif name == "--working-directory":
|
||||
cwd = value
|
||||
elif name in ("--scope", "--wait", "-W", "--pipe", "-P", "-t", "--pty"):
|
||||
foreground = True
|
||||
i += 1 if inline or name not in VALUED else 2
|
||||
command = args[i:]
|
||||
if not command:
|
||||
os.execv(REAL, [REAL] + args)
|
||||
if cwd:
|
||||
os.chdir(cwd)
|
||||
if foreground:
|
||||
os.execvpe(command[0], command, env)
|
||||
if os.fork() == 0:
|
||||
os.setsid()
|
||||
null = os.open(os.devnull, os.O_RDWR)
|
||||
os.dup2(null, 0)
|
||||
try:
|
||||
os.execvpe(command[0], command, env)
|
||||
except OSError:
|
||||
os._exit(127)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
key=$1
|
||||
shift
|
||||
line=$(grep -m1 "^$key=" /etc/droiddeck/strings 2>/dev/null)
|
||||
text=${line#*=}
|
||||
[ -n "$line" ] || text=$key
|
||||
printf "$text\n" "$@"
|
||||
@@ -338,6 +338,26 @@ static int execveat_is_execve(const long *args) {
|
||||
return path[0] == '/' || (int)args[0] == AT_FDCWD;
|
||||
}
|
||||
|
||||
static long openat2_call(const long *args) {
|
||||
if (!real_syscall) {
|
||||
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
|
||||
}
|
||||
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
|
||||
long fd = real_syscall(SYS_openat2, args[0], args[1], args[2], args[3]);
|
||||
if (fd != -1 || errno != ENOSYS) {
|
||||
return fd;
|
||||
}
|
||||
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return openat2_via_openat(args);
|
||||
}
|
||||
|
||||
int bl_openat2(int dirfd, const char *path, void *how, size_t size) __asm__("openat2");
|
||||
int bl_openat2(int dirfd, const char *path, void *how, size_t size) {
|
||||
long args[6] = {dirfd, (long)path, (long)how, (long)size, 0, 0};
|
||||
return (int)openat2_call(args);
|
||||
}
|
||||
|
||||
int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden")));
|
||||
|
||||
long syscall(long number, ...) {
|
||||
@@ -369,14 +389,7 @@ long syscall(long number, ...) {
|
||||
return handled;
|
||||
}
|
||||
if (number == SYS_openat2) {
|
||||
if (!__atomic_load_n(&openat2_missing, __ATOMIC_RELAXED)) {
|
||||
long fd = real_syscall(number, args[0], args[1], args[2], args[3]);
|
||||
if (fd != -1 || errno != ENOSYS) {
|
||||
return fd;
|
||||
}
|
||||
__atomic_store_n(&openat2_missing, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return openat2_via_openat(args);
|
||||
return openat2_call(args);
|
||||
}
|
||||
if (number == SYS_openat) {
|
||||
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef WEBHELPER_DEFAULT
|
||||
#define WEBHELPER_DEFAULT "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
|
||||
@@ -25,8 +26,30 @@ static char *join_features(const char *have, const char *add) {
|
||||
return strcat(out, add);
|
||||
}
|
||||
|
||||
static char *const *chromium_argv(const char *path, char *const argv[]) {
|
||||
const char *slash = path ? strrchr(path, '/') : NULL;
|
||||
if (!slash || !argv || !argv[0]) return argv;
|
||||
int argc = 0;
|
||||
for (; argv[argc]; argc++)
|
||||
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
|
||||
size_t dir = (size_t)(slash - path) + 1;
|
||||
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
|
||||
if (!sandbox) return argv;
|
||||
memcpy(sandbox, path, dir);
|
||||
strcpy(sandbox + dir, "chrome-sandbox");
|
||||
int chromium = access(sandbox, F_OK) == 0;
|
||||
free(sandbox);
|
||||
if (!chromium) return argv;
|
||||
char **out = calloc((size_t)argc + 2, sizeof *out);
|
||||
if (!out) return argv;
|
||||
out[0] = argv[0];
|
||||
out[1] = (char *)"--no-sandbox";
|
||||
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
|
||||
return out;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) char *const *bl_webhelper_argv(const char *path, char *const argv[]) {
|
||||
if (!is_webhelper_browser(path, argv)) return argv;
|
||||
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
|
||||
const char *spec = getenv("BL_WEBHELPER_ARGS");
|
||||
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
|
||||
if (!strcmp(spec, "stock")) return argv;
|
||||
|
||||
+16
-2
@@ -39,8 +39,8 @@ Ported from WinNative (`main`, 53836ca9, "Fix/performance and vac"):
|
||||
- `0007-proc-self-thread-group.patch` - tracees track their thread group, `/proc/self` names it
|
||||
instead of the calling thread, and `/proc/thread-self` resolves to `/proc/<tgid>/task/<tid>`.
|
||||
- `0008-fchmodat2-openat2.patch` - `fchmodat2` paths are translated (honouring
|
||||
`AT_SYMLINK_NOFOLLOW`), `openat2` answers `ENOSYS` so callers fall back to the translated
|
||||
`openat`, and syscall numbers past the end of a table are rejected instead of read.
|
||||
`AT_SYMLINK_NOFOLLOW`), and syscall numbers past the end of a table are rejected instead of read.
|
||||
Its `openat2` answer is replaced by `0019`.
|
||||
- `0009-tracee-relatives-sweep.patch` - tracees count their children, so a terminating thread
|
||||
with no children or ptracees no longer walks every tracee; the per-stop memory collector is
|
||||
emptied instead of freed and reallocated.
|
||||
@@ -114,6 +114,20 @@ Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-per
|
||||
SM8850 (adb shell): `stat` 25.3 -> 0.6 us, `open+close` 25.3 -> 0.9 us, ENOENT 22.9 -> 1.6 us,
|
||||
8 threads `stat`ing 89k -> 3.6M/s; equivalence suite (`bench/equiv.py`) byte-identical to proot.
|
||||
|
||||
- `0019-openat2-emulation.patch` - `openat2` without `resolve` flags runs as a translated `openat`
|
||||
with the same flag and mode checks as the kernel. Any `resolve` flag still answers `ENOSYS`,
|
||||
because PRoot cannot confine symlinks or mounts, so callers keep their own confined fallback.
|
||||
- `0022-fake-root-statx-owners.patch` - with `0013` dropping the `statx` exit stop, fake root never
|
||||
rewrote the owner `statx` returns, so files read as owned by the app's uid while the process was
|
||||
root. Rust's `metadata` and GNU `stat` use `statx`, so uutils' `test -w` (Ubuntu's `/usr/bin/test`)
|
||||
said root could not write to its own directories and apt's AppStream hook never built Discover's
|
||||
catalog. fake_id0 keeps that exit stop when it fakes ids; identity-only mode is unchanged.
|
||||
- `0023-reused-pid-new-child.patch` - when a thread that is not its process's leader calls `execve`,
|
||||
the kernel retires that thread's ID without reporting an exit, so PRoot keeps its entry. Once the
|
||||
IDs wrap (32768 on many Android kernels) a new child can get that ID, and PRoot aborted on the
|
||||
assertion that a new child has no state, ending the whole session. Chromium-based programs such as
|
||||
Steam's client do this. PRoot now retires the stale entry and sets the new child up from scratch.
|
||||
|
||||
Old kernel fixes:
|
||||
|
||||
- `0015-lost-fork-events.patch` - works around a problem reported on Xiaomi's msm 4.14 kernel:
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 28 Oct 2026 14:12:04 -0400
|
||||
Subject: [PATCH] syscall: emulate openat2 through a translated openat
|
||||
|
||||
---
|
||||
src/syscall/enter.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++--
|
||||
1 file changed, 49 insertions(+), 2 deletions(-)
|
||||
|
||||
diff --git a/src/syscall/enter.c b/src/syscall/enter.c
|
||||
index 121c742..66b9e6b 100644
|
||||
--- a/src/syscall/enter.c
|
||||
+++ b/src/syscall/enter.c
|
||||
@@ -491,9 +491,56 @@ int translate_syscall_enter(Tracee *tracee)
|
||||
status = translate_path2(tracee, dirfd, path, SYSARG_2, REGULAR);
|
||||
break;
|
||||
|
||||
- case PR_openat2:
|
||||
- status = -ENOSYS;
|
||||
+ case PR_openat2: {
|
||||
+ struct { uint64_t flags; uint64_t mode; uint64_t resolve; } how;
|
||||
+ word_t size = peek_reg(tracee, CURRENT, SYSARG_4);
|
||||
+
|
||||
+ if (size < sizeof(how) || size > 4096) {
|
||||
+ status = size < sizeof(how) ? -EINVAL : -E2BIG;
|
||||
+ break;
|
||||
+ }
|
||||
+ status = read_data(tracee, &how, peek_reg(tracee, CURRENT, SYSARG_3), sizeof(how));
|
||||
+ if (status < 0)
|
||||
+ break;
|
||||
+ if ((how.resolve & ~(uint64_t) 0x3f) != 0
|
||||
+ || ((how.resolve & 0x08) != 0 && (how.resolve & 0x10) != 0)
|
||||
+ || (how.mode != 0 && (how.flags & (O_CREAT | __O_TMPFILE)) == 0)
|
||||
+ || (how.flags >> 32) != 0) {
|
||||
+ status = -EINVAL;
|
||||
+ break;
|
||||
+ }
|
||||
+ if ((how.resolve & 0x20) != 0) {
|
||||
+ status = -EAGAIN;
|
||||
+ break;
|
||||
+ }
|
||||
+ if ((how.resolve & 0x1f) != 0) {
|
||||
+ status = -ENOSYS;
|
||||
+ break;
|
||||
+ }
|
||||
+#ifdef __ANDROID__
|
||||
+ if ((how.flags & __O_TMPFILE) != 0) {
|
||||
+ status = -EOPNOTSUPP;
|
||||
+ break;
|
||||
+ }
|
||||
+#endif
|
||||
+ dirfd = peek_reg(tracee, CURRENT, SYSARG_1);
|
||||
+ status = get_sysarg_path(tracee, path, SYSARG_2);
|
||||
+ if (status < 0)
|
||||
+ break;
|
||||
+
|
||||
+ if ( ((how.flags & O_NOFOLLOW) != 0)
|
||||
+ || ((how.flags & O_EXCL) != 0 && (how.flags & O_CREAT) != 0))
|
||||
+ status = translate_path2(tracee, dirfd, path, SYSARG_2, SYMLINK);
|
||||
+ else
|
||||
+ status = translate_path2(tracee, dirfd, path, SYSARG_2, REGULAR);
|
||||
+ if (status < 0)
|
||||
+ break;
|
||||
+
|
||||
+ set_sysnum(tracee, PR_openat);
|
||||
+ poke_reg(tracee, SYSARG_3, how.flags);
|
||||
+ poke_reg(tracee, SYSARG_4, how.mode);
|
||||
break;
|
||||
+ }
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
From 771667d739c8501729b4037a7377793fd16e908e Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 28 Oct 2026 14:12:37 -0400
|
||||
Subject: [PATCH] execve: show the linked name as /proc/self/exe for
|
||||
link2symlink files
|
||||
|
||||
---
|
||||
src/execve/enter.c | 92 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||
1 file changed, 92 insertions(+)
|
||||
|
||||
diff --git a/src/execve/enter.c b/src/execve/enter.c
|
||||
index c562d14..f185e9a 100644
|
||||
--- a/src/execve/enter.c
|
||||
+++ b/src/execve/enter.c
|
||||
@@ -592,6 +592,96 @@ static inline const char *get_loader_path(const Tracee *tracee)
|
||||
* translate_load_*(). This function returns -errno if an error
|
||||
* occured, otherwise 0.
|
||||
*/
|
||||
+static bool is_l2s_name(const char *path)
|
||||
+{
|
||||
+ const char *name = strrchr(path, '/');
|
||||
+
|
||||
+ name = name != NULL ? name + 1 : path;
|
||||
+ return strncmp(name, ".l2s.", 5) == 0 || strncmp(name, ".proot.l2s.", 11) == 0;
|
||||
+}
|
||||
+
|
||||
+static void lexical_path(char path[PATH_MAX])
|
||||
+{
|
||||
+ char result[PATH_MAX];
|
||||
+ char *component;
|
||||
+ char *next;
|
||||
+ size_t length = 0;
|
||||
+
|
||||
+ for (component = path; *component != '\0'; component = next) {
|
||||
+ size_t size;
|
||||
+
|
||||
+ while (*component == '/')
|
||||
+ component++;
|
||||
+ next = strchrnul(component, '/');
|
||||
+ size = next - component;
|
||||
+ if (size == 0 || (size == 1 && component[0] == '.'))
|
||||
+ continue;
|
||||
+ if (size == 2 && component[0] == '.' && component[1] == '.') {
|
||||
+ while (length > 0 && result[length - 1] != '/')
|
||||
+ length--;
|
||||
+ if (length > 0)
|
||||
+ length--;
|
||||
+ continue;
|
||||
+ }
|
||||
+ result[length++] = '/';
|
||||
+ memcpy(result + length, component, size);
|
||||
+ length += size;
|
||||
+ }
|
||||
+ if (length == 0)
|
||||
+ result[length++] = '/';
|
||||
+ result[length] = '\0';
|
||||
+ strcpy(path, result);
|
||||
+}
|
||||
+
|
||||
+static void visible_exe(Tracee *tracee, const char *user_path, char exe[PATH_MAX])
|
||||
+{
|
||||
+ char path[PATH_MAX];
|
||||
+ char host[PATH_MAX];
|
||||
+ char target[PATH_MAX];
|
||||
+ char *slash;
|
||||
+ ssize_t length;
|
||||
+ int i;
|
||||
+
|
||||
+ if (user_path[0] == '/') {
|
||||
+ if (strlen(user_path) >= PATH_MAX)
|
||||
+ return;
|
||||
+ strcpy(path, user_path);
|
||||
+ }
|
||||
+ else if (join_paths(2, path, tracee->fs->cwd, user_path) < 0)
|
||||
+ return;
|
||||
+ lexical_path(path);
|
||||
+
|
||||
+ for (i = 0; i < 40; i++) {
|
||||
+ if (translate_path(tracee, host, AT_FDCWD, path, false) < 0)
|
||||
+ return;
|
||||
+ if (is_l2s_name(host))
|
||||
+ break;
|
||||
+ length = readlink(host, target, PATH_MAX - 1);
|
||||
+ if (length < 0)
|
||||
+ return;
|
||||
+ target[length] = '\0';
|
||||
+ if (is_l2s_name(target))
|
||||
+ break;
|
||||
+ if (target[0] == '/')
|
||||
+ strcpy(path, target);
|
||||
+ else {
|
||||
+ slash = strrchr(path, '/');
|
||||
+ *slash = '\0';
|
||||
+ if (translate_path(tracee, host, AT_FDCWD, path[0] != '\0' ? path : "/", true) < 0)
|
||||
+ return;
|
||||
+ if (detranslate_path(tracee, host, NULL) < 0)
|
||||
+ return;
|
||||
+ if (join_paths(2, path, host, target) < 0)
|
||||
+ return;
|
||||
+ }
|
||||
+ lexical_path(path);
|
||||
+ }
|
||||
+ if (i == 40)
|
||||
+ return;
|
||||
+
|
||||
+ strcpy(exe, path);
|
||||
+}
|
||||
+
|
||||
int translate_execve_enter(Tracee *tracee)
|
||||
{
|
||||
char user_path[PATH_MAX];
|
||||
@@ -642,6 +732,8 @@ int translate_execve_enter(Tracee *tracee)
|
||||
strcpy(new_exe, host_path);
|
||||
status = detranslate_path(tracee, new_exe, NULL);
|
||||
if (status >= 0) {
|
||||
+ if (is_l2s_name(new_exe))
|
||||
+ visible_exe(tracee, user_path, new_exe);
|
||||
talloc_unlink(tracee, tracee->new_exe);
|
||||
tracee->new_exe = talloc_strdup(tracee, new_exe);
|
||||
}
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
From 4486efde6200dc8a8df4097a868b65e449d20e82 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 28 Oct 2026 14:12:47 -0400
|
||||
Subject: [PATCH] fake_id0: report real errors for FIFO and socket mknod
|
||||
|
||||
---
|
||||
src/extension/fake_id0/fake_id0.c | 7 ++++++-
|
||||
1 file changed, 6 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/src/extension/fake_id0/fake_id0.c b/src/extension/fake_id0/fake_id0.c
|
||||
index 5c8a8cd..dc28529 100644
|
||||
--- a/src/extension/fake_id0/fake_id0.c
|
||||
+++ b/src/extension/fake_id0/fake_id0.c
|
||||
@@ -940,7 +940,12 @@ static int handle_sysexit_end(Tracee *tracee, Config *config)
|
||||
case PR_setgroups32:
|
||||
#endif
|
||||
case PR_mknod:
|
||||
- case PR_mknodat:
|
||||
+ case PR_mknodat: {
|
||||
+ mode_t mode = peek_reg(tracee, ORIGINAL, sysnum == PR_mknod ? SYSARG_2 : SYSARG_3);
|
||||
+ if (S_ISFIFO(mode) || S_ISSOCK(mode) || S_ISREG(mode) || (mode & S_IFMT) == 0)
|
||||
+ return 0;
|
||||
+ return handle_perm_err_exit_end(tracee, config, false);
|
||||
+ }
|
||||
case PR_capset:
|
||||
case PR_chmod:
|
||||
case PR_chown:
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
From facb0f6476b374cb9bdb07e388936f4ca0a829ce Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 28 Oct 2026 15:17:52 -0400
|
||||
Subject: [PATCH] fake_id0: keep the statx exit stop so owners stay faked
|
||||
|
||||
---
|
||||
src/extension/fake_id0/fake_id0.c | 1 +
|
||||
1 file changed, 1 insertion(+)
|
||||
|
||||
diff --git a/src/extension/fake_id0/fake_id0.c b/src/extension/fake_id0/fake_id0.c
|
||||
index dc28529..a5ee018 100644
|
||||
--- a/src/extension/fake_id0/fake_id0.c
|
||||
+++ b/src/extension/fake_id0/fake_id0.c
|
||||
@@ -349,6 +349,7 @@ static FilteredSysnum filtered_sysnums[] = {
|
||||
{ PR_stat64, FILTER_SYSEXIT },
|
||||
{ PR_statfs, FILTER_SYSEXIT },
|
||||
{ PR_statfs64, FILTER_SYSEXIT },
|
||||
+ { PR_statx, FILTER_SYSEXIT },
|
||||
FILTERED_SYSNUM_END,
|
||||
};
|
||||
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
From 3e47c091e500b274b255d9b8d326236744aa4347 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 28 Oct 2026 16:27:14 -0400
|
||||
Subject: [PATCH] tracee: replace a stale tracee when the kernel reuses its pid
|
||||
for a new child
|
||||
|
||||
---
|
||||
src/tracee/tracee.c | 20 ++++++++++++++++++++
|
||||
1 file changed, 20 insertions(+)
|
||||
|
||||
diff --git a/src/tracee/tracee.c b/src/tracee/tracee.c
|
||||
index 5029bbc..cbadaec 100644
|
||||
--- a/src/tracee/tracee.c
|
||||
+++ b/src/tracee/tracee.c
|
||||
@@ -57,6 +57,8 @@ static Tracees buckets[TRACEE_BUCKETS];
|
||||
|
||||
static bool terminations_pending = false;
|
||||
|
||||
+static Tracees reused_pid_tracees;
|
||||
+
|
||||
static Tracees *bucket_of(pid_t pid)
|
||||
{
|
||||
return &buckets[(unsigned int) pid % TRACEE_BUCKETS];
|
||||
@@ -599,6 +601,24 @@ static int new_child_setup(Tracee *parent, unsigned long pid, word_t clone_flags
|
||||
Tracee *child;
|
||||
|
||||
child = get_tracee(parent, (pid_t) pid, true);
|
||||
+ if (child != NULL
|
||||
+ && (child->exe != NULL
|
||||
+ || child->fs->cwd != NULL
|
||||
+ || child->qemu != NULL
|
||||
+ || child->glue != NULL
|
||||
+ || child->parent != NULL
|
||||
+ || child->as_ptracee.ptracer != NULL)) {
|
||||
+ note(parent, WARNING, USER,
|
||||
+ "pid %lu was reused before its previous task was released",
|
||||
+ pid);
|
||||
+ LIST_REMOVE(child, bucket_link);
|
||||
+ LIST_INSERT_HEAD(&reused_pid_tracees, child, bucket_link);
|
||||
+ if (child->as_ptracee.ptracer != NULL)
|
||||
+ detach_from_ptracer(child);
|
||||
+ child->terminated = true;
|
||||
+ terminations_pending = true;
|
||||
+ child = new_tracee((pid_t) pid);
|
||||
+ }
|
||||
if (child == NULL) {
|
||||
note(parent, WARNING, SYSTEM, "running out of memory");
|
||||
return -ENOMEM;
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -10,7 +10,7 @@ SESSION_FILES = OVERLAY.parents[2] / 'app/src/main/java/com/droiddeck/launcher/s
|
||||
|
||||
|
||||
def check_extraction(overlay, source):
|
||||
deployed = set(re.findall(r'"(usr/local/bin/droiddeck-[^"]+)"\s+to\s+"\1"', source))
|
||||
deployed = set(re.findall(r'"(usr/local/bin/droiddeck-[^"]+)"\s+to\s+"usr/local/bin/[^"/]+"', source))
|
||||
return ['not extracted at session start: ' + path.relative_to(overlay).as_posix()
|
||||
for path in sorted((overlay / 'usr/local/bin').glob('droiddeck-*'))
|
||||
if path.relative_to(overlay).as_posix() not in deployed]
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REMEMBER = Path(__file__).resolve().parents[1] / "ubuntu/overlay-runtime/usr/share/droiddeck/apt/remember"
|
||||
|
||||
|
||||
class AptRememberTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.top = Path(temp.name)
|
||||
self.dir = self.top / "share/apt"
|
||||
self.state = self.top / "state"
|
||||
self.etc = self.top / "etc/apt"
|
||||
self.keys = self.top / "keyrings"
|
||||
self.autostart = self.top / "autostart"
|
||||
for d in (self.dir, self.etc / "sources.list.d", self.keys, self.autostart, self.top / "bin"):
|
||||
d.mkdir(parents=True)
|
||||
(self.dir / "system-manual.txt").write_text("base\n")
|
||||
(self.dir / "runtime-id").write_text("new\n")
|
||||
system = self.keys / "ubuntu-archive.gpg"
|
||||
system.write_text("system key")
|
||||
(self.dir / "system-sources.txt").write_text("%s %s\n" % (system, hashlib.sha256(b"system key").hexdigest()))
|
||||
apt_mark = self.top / "bin/apt-mark"
|
||||
apt_mark.write_text("#!/bin/sh\nprintf 'base\\nvlc\\n'\n")
|
||||
apt_mark.chmod(0o755)
|
||||
script = REMEMBER.read_text()
|
||||
script = script.replace("/usr/share/droiddeck/apt", str(self.dir))
|
||||
script = script.replace("/root/.local/share/droiddeck/apt", str(self.state))
|
||||
script = script.replace("/etc/xdg/autostart", str(self.autostart))
|
||||
script = script.replace("/usr/share/keyrings", str(self.keys))
|
||||
script = script.replace("/etc/apt", str(self.etc))
|
||||
self.script = self.top / "remember"
|
||||
self.script.write_text(script)
|
||||
|
||||
def run_remember(self):
|
||||
env = dict(os.environ, PATH="%s:%s" % (self.top / "bin", os.environ["PATH"]))
|
||||
env.pop("DROIDDECK_APT_RESTORING", None)
|
||||
subprocess.run(["bash", str(self.script)], env=env, check=True, timeout=30)
|
||||
|
||||
def test_user_sources_and_keys_outside_etc_apt_are_kept(self):
|
||||
(self.etc / "sources.list").write_text("deb http://example.invalid stable main\n")
|
||||
(self.keys / "example.gpg").write_text("user key")
|
||||
self.run_remember()
|
||||
self.assertEqual("vlc\n", (self.state / "packages.txt").read_text())
|
||||
self.assertTrue((self.state / "sources/sources.list").is_file())
|
||||
self.assertEqual("user key", (self.state / "keyrings" / ("%s_example.gpg" % str(self.keys).lstrip("/").replace("/", "_"))).read_text())
|
||||
self.assertFalse(any("ubuntu-archive" in p.name for p in (self.state / "keyrings").iterdir()))
|
||||
|
||||
def test_the_previous_runtime_snapshot_waits_for_the_desktop_restore(self):
|
||||
(self.autostart / "droiddeck-apt-restore.desktop").write_text("")
|
||||
self.state.mkdir()
|
||||
(self.state / "packages.txt").write_text("old-app\n")
|
||||
(self.state / "restored").write_text("old\n")
|
||||
self.run_remember()
|
||||
self.assertEqual("old-app\n", (self.state / "packages.txt").read_text())
|
||||
(self.state / "attempted").write_text("new\n")
|
||||
self.run_remember()
|
||||
self.assertEqual("vlc\n", (self.state / "packages.txt").read_text())
|
||||
|
||||
def test_without_the_desktop_the_snapshot_follows_the_runtime(self):
|
||||
self.state.mkdir()
|
||||
(self.state / "packages.txt").write_text("old-app\n")
|
||||
(self.state / "restored").write_text("old\n")
|
||||
self.run_remember()
|
||||
self.assertEqual("vlc\n", (self.state / "packages.txt").read_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,107 @@
|
||||
import json
|
||||
import os
|
||||
import runpy
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
|
||||
|
||||
PROBE = """
|
||||
import fcntl, os, sys
|
||||
fd = os.open(sys.argv[1], os.O_RDWR)
|
||||
try:
|
||||
fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
print("held")
|
||||
else:
|
||||
print("free")
|
||||
"""
|
||||
|
||||
|
||||
class BwrapLockFileTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.shim = runpy.run_path(str(BWRAP))
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.instance = Path(self.temp.name) / "instance"
|
||||
self.instance.mkdir()
|
||||
(self.instance / ".ref").write_text("")
|
||||
|
||||
def spec(self, *extra):
|
||||
argv = ["--ro-bind", str(self.instance), "/run/user/1000/.flatpak/7", *extra, "--", "true"]
|
||||
return self.shim["parse"](argv)
|
||||
|
||||
def probe(self):
|
||||
return subprocess.run([sys.executable, "-c", PROBE, str(self.instance / ".ref")],
|
||||
capture_output=True, text=True, timeout=30, check=True).stdout.strip()
|
||||
|
||||
def test_sandbox_paths_resolve_through_the_binds(self):
|
||||
spec = self.spec()
|
||||
self.assertEqual(str(self.instance / ".ref"), self.shim["host_path"](spec, "/run/user/1000/.flatpak/7/.ref"))
|
||||
self.assertEqual("/etc/hosts", self.shim["host_path"](spec, "/etc/hosts"))
|
||||
|
||||
def test_the_instance_lock_is_held_while_the_sandbox_runs(self):
|
||||
spec = self.spec("--lock-file", "/run/user/1000/.flatpak/7/.ref")
|
||||
self.assertEqual("free", self.probe())
|
||||
self.shim["hold_locks"](spec)
|
||||
self.assertEqual("held", self.probe())
|
||||
|
||||
def test_without_a_lock_file_nothing_is_locked(self):
|
||||
self.shim["hold_locks"](self.spec())
|
||||
self.assertEqual("free", self.probe())
|
||||
|
||||
def test_the_lock_survives_exec(self):
|
||||
script = (
|
||||
"import runpy, sys; shim = runpy.run_path(sys.argv[1]); "
|
||||
"spec = shim['parse'](['--ro-bind', sys.argv[2], '/run/user/1000/.flatpak/7', "
|
||||
"'--lock-file', '/run/user/1000/.flatpak/7/.ref', '--', 'true']); "
|
||||
"shim['hold_locks'](spec); "
|
||||
"import os; os.execv(sys.executable, [sys.executable, '-c', "
|
||||
"'import subprocess, sys; print(subprocess.run([sys.executable, \"-c\", sys.argv[1], sys.argv[2]], "
|
||||
"capture_output=True, text=True).stdout.strip())', sys.argv[3], sys.argv[4]])"
|
||||
)
|
||||
out = subprocess.run([sys.executable, "-c", script, str(BWRAP), str(self.instance), PROBE,
|
||||
str(self.instance / ".ref")], capture_output=True, text=True, timeout=30, check=True)
|
||||
self.assertEqual("held", out.stdout.strip())
|
||||
|
||||
|
||||
class BwrapReportedPidTest(unittest.TestCase):
|
||||
def test_flatpak_is_given_the_wrapper_so_killing_it_ends_the_whole_sandbox(self):
|
||||
name = "droiddeck-bwrap-test-%d" % os.getpid()
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind("\0" + name)
|
||||
server.listen(1)
|
||||
self.addCleanup(server.close)
|
||||
|
||||
def answer():
|
||||
conn, _ = server.accept()
|
||||
with conn:
|
||||
head = conn.recv(5)
|
||||
size = struct.unpack(">I", head[1:])[0]
|
||||
while size > 0:
|
||||
size -= len(conn.recv(size))
|
||||
for kind, payload in ((b"P", b"424242"), (b"X", b"0")):
|
||||
conn.sendall(kind + struct.pack(">I", len(payload)) + payload)
|
||||
|
||||
thread = threading.Thread(target=answer, daemon=True)
|
||||
thread.start()
|
||||
read_end, write_end = os.pipe()
|
||||
env = dict(os.environ, DROIDDECK_BWRAP_SOCKET=name)
|
||||
proc = subprocess.Popen([sys.executable, str(BWRAP), "--ro-bind", "/", "/elsewhere", "--info-fd",
|
||||
str(write_end), "--", "true"], env=env, pass_fds=[write_end])
|
||||
os.close(write_end)
|
||||
info = os.read(read_end, 4096)
|
||||
os.close(read_end)
|
||||
self.assertEqual(0, proc.wait(30))
|
||||
thread.join(5)
|
||||
self.assertEqual({"child-pid": proc.pid}, json.loads(info))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,104 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
IME = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-ime'
|
||||
|
||||
|
||||
def message(obj, opcode, payload=b''):
|
||||
return struct.pack('<II', obj, ((8 + len(payload)) << 16) | opcode) + payload
|
||||
|
||||
|
||||
def wl_string(value):
|
||||
data = value.encode() + b'\0'
|
||||
return struct.pack('<I', len(data)) + data + b'\0' * (-len(data) % 4)
|
||||
|
||||
|
||||
class DesktopImeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.session = Path(self.temp.name)
|
||||
self.server, client = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(self.server.close)
|
||||
env = dict(os.environ, BL_LAUNCH_DIR=str(self.session), WAYLAND_SOCKET=str(client.fileno()))
|
||||
self.proc = subprocess.Popen(['python3', str(IME)], env=env, pass_fds=[client.fileno()],
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
client.close()
|
||||
self.addCleanup(self.stop)
|
||||
self.server.settimeout(5)
|
||||
self.assertEqual(self.read(12), message(1, 1, struct.pack('<I', 2)))
|
||||
self.server.sendall(message(2, 0, struct.pack('<I', 7) + wl_string('zwp_input_method_v1') + struct.pack('<I', 1)))
|
||||
bind = self.read(8 + 4 + len(wl_string('zwp_input_method_v1')) + 8)
|
||||
self.assertEqual(bind, message(2, 0, struct.pack('<I', 7) + wl_string('zwp_input_method_v1') + struct.pack('<II', 1, 3)))
|
||||
|
||||
def stop(self):
|
||||
if self.proc.poll() is None:
|
||||
self.proc.kill()
|
||||
self.proc.wait(5)
|
||||
self.proc.stderr.close()
|
||||
|
||||
def read(self, size):
|
||||
data = b''
|
||||
while len(data) < size:
|
||||
chunk = self.server.recv(size - len(data))
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
def state(self, seq, timeout=5):
|
||||
path = self.session / 'agent/ime.json'
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
snapshot = json.loads(path.read_text())
|
||||
except (OSError, ValueError):
|
||||
snapshot = None
|
||||
if snapshot and snapshot['seq'] >= seq:
|
||||
return snapshot
|
||||
time.sleep(0.02)
|
||||
self.fail('ime.json never reached seq %d' % seq)
|
||||
|
||||
def test_focus_and_blur_are_reported(self):
|
||||
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
|
||||
self.assertTrue(self.state(1)['textField'])
|
||||
self.server.sendall(message(100, 2, struct.pack('<II', 0, 9)))
|
||||
snapshot = self.state(2)
|
||||
self.assertEqual((snapshot['textField'], snapshot['purpose']), (True, 9))
|
||||
self.server.sendall(message(3, 1, struct.pack('<I', 100)))
|
||||
self.assertEqual(self.read(8), message(100, 0))
|
||||
self.assertFalse(self.state(3)['textField'])
|
||||
self.assertEqual(oct((self.session / 'agent/ime.json').stat().st_mode & 0o777), '0o600')
|
||||
|
||||
def test_switching_fields_does_not_flicker(self):
|
||||
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
|
||||
self.assertTrue(self.state(1)['textField'])
|
||||
self.server.sendall(message(3, 1, struct.pack('<I', 100)) + message(3, 0, struct.pack('<I', 101)))
|
||||
self.assertEqual(self.read(8), message(100, 0))
|
||||
time.sleep(0.4)
|
||||
self.assertEqual(self.state(1), {'textField': True, 'hint': 0, 'purpose': 0, 'seq': 1})
|
||||
|
||||
def test_compositor_exit_clears_the_field(self):
|
||||
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
|
||||
self.assertTrue(self.state(1)['textField'])
|
||||
self.server.close()
|
||||
self.assertEqual(self.proc.wait(5), 0)
|
||||
self.assertFalse(self.state(2)['textField'])
|
||||
|
||||
|
||||
def test_a_protocol_error_clears_the_field(self):
|
||||
self.server.sendall(message(3, 0, struct.pack('<I', 100)))
|
||||
self.assertTrue(self.state(1)['textField'])
|
||||
self.server.sendall(message(1, 0, struct.pack('<II', 3, 1) + wl_string('bad request')))
|
||||
self.assertEqual(self.proc.wait(5), 1)
|
||||
self.assertFalse(self.state(2)['textField'])
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -146,6 +146,49 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
"""
|
||||
|
||||
WRAPPER = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/filter.h>
|
||||
#include <linux/seccomp.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef SYS_openat2
|
||||
#define SYS_openat2 437
|
||||
#endif
|
||||
|
||||
struct how { uint64_t flags, mode, resolve; };
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
struct sock_filter filter[] = {
|
||||
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
|
||||
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_openat2, 0, 1),
|
||||
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),
|
||||
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
|
||||
};
|
||||
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
|
||||
if (argc < 3 || prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return 3;
|
||||
int (*call)(int, const char *, struct how *, size_t) = (int (*)(int, const char *, struct how *, size_t))dlsym(RTLD_DEFAULT, "openat2");
|
||||
if (!call) return 4;
|
||||
int dir = open(argv[1], O_PATH | O_DIRECTORY | O_CLOEXEC);
|
||||
struct how h = {O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644, 0x08};
|
||||
int fd = call(dir, argv[2], &h, sizeof(h));
|
||||
if (fd < 0) {
|
||||
printf("ERR %d\n", errno);
|
||||
return 1;
|
||||
}
|
||||
printf("OK\n");
|
||||
return close(fd);
|
||||
}
|
||||
"""
|
||||
|
||||
RAW_LOOKUP = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
@@ -326,6 +369,12 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so")))
|
||||
except subprocess.TimeoutExpired:
|
||||
cls.fex = None
|
||||
wrapper = cls.tmp / "wrapper.c"
|
||||
wrapper.write_text(WRAPPER)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "wrapper"), str(wrapper), "-ldl"], check=True)
|
||||
(cls.tmp / "extract").mkdir()
|
||||
cls.wrapper = subprocess.run([str(cls.tmp / "wrapper"), str(cls.tmp / "extract"), "file"], capture_output=True,
|
||||
text=True, timeout=20, env=dict(os.environ, LD_PRELOAD=str(cls.lib)))
|
||||
(cls.tmp / "fex-lookup").mkdir()
|
||||
shutil.copy(cls.tmp / "raw_lookup", cls.tmp / "fex-lookup/FEX")
|
||||
try:
|
||||
@@ -373,6 +422,10 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
self.assertEqual(self.fex.returncode, 0, self.fex.stderr)
|
||||
self.assertEqual(self.fex.stdout, "inside\n")
|
||||
|
||||
def test_the_libc_openat2_wrapper_creates_files_without_openat2(self):
|
||||
self.assertEqual(self.wrapper.returncode, 0, self.wrapper.stdout + self.wrapper.stderr)
|
||||
self.assertTrue((self.tmp / "extract/file").exists())
|
||||
|
||||
def test_the_kernel_agrees(self):
|
||||
if self.kernel is None:
|
||||
self.skipTest("this kernel or sandbox has no openat2")
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import io
|
||||
import os
|
||||
import runpy
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
PACMAN = Path(__file__).resolve().parents[1] / "desktop-kde/overlay/usr/share/droiddeck/pacman"
|
||||
|
||||
|
||||
class PacmanSharedFilesTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.top = Path(temp.name)
|
||||
|
||||
def keep(self, action):
|
||||
lib = self.top / "lib"
|
||||
lib.mkdir(exist_ok=True)
|
||||
script = (PACMAN / "keep").read_text().replace("/var/lib/pacman", str(lib))
|
||||
subprocess.run(["bash", "-c", script, "keep", action], check=True, timeout=30)
|
||||
return lib
|
||||
|
||||
def test_an_upgrade_that_drops_a_shared_file_gets_it_back(self):
|
||||
shared = self.top / "usr/lib/libshared.so"
|
||||
shared.parent.mkdir(parents=True)
|
||||
shared.write_text("shared")
|
||||
lib = self.top / "lib"
|
||||
lib.mkdir()
|
||||
(lib / "droiddeck-shared-files").write_text("%s\n%s\n" % (shared, self.top / "usr/lib/never-there"))
|
||||
self.keep("save")
|
||||
shared.unlink()
|
||||
self.keep("restore")
|
||||
self.assertEqual("shared", shared.read_text())
|
||||
self.assertFalse((self.top / "usr/lib/never-there").exists())
|
||||
self.assertFalse((lib / "droiddeck-shared-keep").exists())
|
||||
|
||||
def test_a_backup_for_a_file_still_missing_survives_the_next_save(self):
|
||||
shared = self.top / "usr/lib/libshared.so"
|
||||
shared.parent.mkdir(parents=True)
|
||||
shared.write_text("shared")
|
||||
lib = self.top / "lib"
|
||||
lib.mkdir()
|
||||
(lib / "droiddeck-shared-files").write_text("%s\n" % shared)
|
||||
self.keep("save")
|
||||
shared.unlink()
|
||||
self.keep("save")
|
||||
self.keep("restore")
|
||||
self.assertEqual("shared", shared.read_text())
|
||||
|
||||
def test_only_identical_files_are_taken_over(self):
|
||||
adopt = runpy.run_path(str(PACMAN / "adopt"), run_name="adopt")
|
||||
package = io.BytesIO()
|
||||
with tarfile.open(fileobj=package, mode="w") as archive:
|
||||
for name, data in (("same", b"one"), ("different", b"two")):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
(self.top / "same").write_bytes(b"one")
|
||||
(self.top / "different").write_bytes(b"other")
|
||||
package.seek(0)
|
||||
with tarfile.open(fileobj=package) as archive:
|
||||
members = {m.name: m for m in archive}
|
||||
self.assertTrue(adopt["same"](archive, members["same"], str(self.top / "same")))
|
||||
self.assertFalse(adopt["same"](archive, members["different"], str(self.top / "different")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -43,3 +43,10 @@ class SessionAssetsTest(unittest.TestCase):
|
||||
assets.check_extraction(self.overlay, ''))
|
||||
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1"'
|
||||
self.assertEqual([], assets.check_extraction(self.overlay, mapping))
|
||||
|
||||
def test_helper_extracted_under_another_name_counts(self):
|
||||
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/login1"'
|
||||
self.assertEqual([], assets.check_extraction(self.overlay, mapping))
|
||||
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"'
|
||||
self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'],
|
||||
assets.check_extraction(self.overlay, mapping))
|
||||
@@ -9,8 +9,8 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d
|
||||
|
||||
|
||||
def log_redirect():
|
||||
match = re.search(r"^\s*(exec > >\(.*\) 2>&1)$", SESSION.read_text(), re.M)
|
||||
return match.group(1)
|
||||
match = re.search(r"^\s*(dd=.*)\n\s*(exec > >\(.*\) 2>&1)$", SESSION.read_text(), re.M)
|
||||
return "%s\n%s" % match.groups()
|
||||
|
||||
|
||||
class SessionLogTest(unittest.TestCase):
|
||||
|
||||
@@ -57,6 +57,23 @@ class DesktopSteamLaunchTest(unittest.TestCase):
|
||||
self.assertEqual(result.stdout.splitlines()[-1], 'steam://rungameid/501590')
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_exit_without_a_running_client_starts_nothing(self):
|
||||
result = self.launch('desktop', 'steam://exit')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def test_shim_turns_shutdown_into_exit_url(self):
|
||||
launch = self.root / 'record-launch'
|
||||
launch.write_text('#!/bin/bash\nprintf "%s\\n" "$@"\n')
|
||||
launch.chmod(0o755)
|
||||
shim = self.root / 'shim'
|
||||
shim.write_text((BIN / 'droiddeck-steam-shim').read_text().replace(
|
||||
'/usr/local/bin/droiddeck-steam-launch', str(launch)))
|
||||
result = subprocess.run(['bash', str(shim), '-shutdown'], env=self.env, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), ['desktop', 'steam://exit'])
|
||||
|
||||
def test_second_click_forwards_without_another_supervisor(self):
|
||||
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
|
||||
lock.parent.mkdir(parents=True)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -20,6 +22,30 @@ class SteamRestartCapTest(unittest.TestCase):
|
||||
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,
|
||||
check=True).stdout.split()
|
||||
|
||||
def installs(self, *steps):
|
||||
function = stuck_function()
|
||||
self.assertIsNotNone(function, "droiddeck-session has no steam_update_stuck()")
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
script = function + "steam_root=%s\nmkdir -p \"$steam_root/package\"\n" % shlex.quote(root)
|
||||
script += "installed=\"$steam_root/package/steam_client_linuxarm64.installed\"\n"
|
||||
script += "echo 0 > \"$installed\"\nsteam_updates=0\nsteam_installs=0\n"
|
||||
script += "steam_update_stamp=$(stat -c '%n %Y %s' \"$steam_root\"/package/*.installed)\n"
|
||||
for n, installed in enumerate(steps, 1):
|
||||
if installed:
|
||||
script += "printf '%%0%dd' 0 > \"$installed\"\n" % (n + 1)
|
||||
script += "if steam_update_stuck 10; then echo stop; else echo restart; fi\n"
|
||||
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,
|
||||
check=True).stdout.split()
|
||||
|
||||
def test_restarts_that_each_install_an_update_go_on(self):
|
||||
self.assertEqual(["restart"] * 4, self.installs(True, False, True, False))
|
||||
|
||||
def test_an_update_that_never_installs_is_stopped_on_the_third(self):
|
||||
self.assertEqual(["restart", "restart", "stop"], self.installs(False, False, False))
|
||||
|
||||
def test_installs_that_never_settle_are_stopped(self):
|
||||
self.assertIn("stop", self.installs(*[True] * 12))
|
||||
|
||||
def test_an_update_that_keeps_asking_at_once_is_stopped_on_the_third(self):
|
||||
self.assertEqual(["restart", "restart", "stop"], self.restarts(11, 13, 9))
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import getpass
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SU = Path(__file__).resolve().parents[1] / "ubuntu/overlay-runtime/usr/local/bin/su"
|
||||
|
||||
|
||||
class SuWrapperTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.dir = Path(temp.name)
|
||||
sudo = self.dir / "sudo"
|
||||
sudo.write_text("#!/bin/bash\nprintf 'sudo'; printf ' <%s>' \"$@\"; echo\n")
|
||||
sudo.chmod(0o755)
|
||||
self.su = self.dir / "su"
|
||||
self.su.write_text(SU.read_text().replace("/usr/local/bin/sudo", str(sudo)))
|
||||
self.su.chmod(0o755)
|
||||
|
||||
def run_su(self, *args):
|
||||
env = dict(os.environ, SHELL="/bin/bash")
|
||||
return subprocess.run([str(self.su), *args], capture_output=True, text=True, timeout=30, env=env)
|
||||
|
||||
def test_a_command_after_the_user_reaches_the_root_shell(self):
|
||||
out = self.run_su("root", "-c", "echo hi")
|
||||
self.assertEqual("sudo <-s> <echo hi>\n", out.stdout)
|
||||
|
||||
def test_the_current_user_is_not_elevated(self):
|
||||
out = self.run_su(getpass.getuser(), "-c", "echo as-me")
|
||||
if getpass.getuser() == "root":
|
||||
self.assertEqual("sudo <-s> <echo as-me>\n", out.stdout)
|
||||
else:
|
||||
self.assertEqual("as-me\n", out.stdout)
|
||||
|
||||
def test_arguments_after_the_user_go_to_the_shell(self):
|
||||
out = self.run_su("-", "root", "-c", "echo $0 $1", "zero", "one")
|
||||
self.assertEqual("sudo <-i> </bin/bash> <-c> <echo $0 $1> <zero> <one>\n", out.stdout)
|
||||
|
||||
def test_other_users_are_refused(self):
|
||||
out = self.run_su("droiddeck-nobody-here")
|
||||
self.assertEqual(1, out.returncode)
|
||||
self.assertEqual("", out.stdout)
|
||||
|
||||
def test_plain_su_opens_a_root_shell(self):
|
||||
self.assertEqual("sudo <-s>\n", self.run_su().stdout)
|
||||
self.assertEqual("sudo <-i>\n", self.run_su("-").stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
# The Linux runtime (Ubuntu)
|
||||
|
||||
DroidDeck's Linux runtime: Ubuntu 26.04 LTS for arm64, with Kubuntu's Plasma desktop as a separate download, set up as
|
||||
SteamOS's desktop mode (Valve's Vapor theme, the Steam Deck wallpaper, "Return to Gaming Mode" and
|
||||
Steam on the desktop). The app installs it into `files/linuxfs` and runs it under its patched proot.
|
||||
|
||||
- `build-debs.sh` (run in an `ubuntu:26.04` container on an arm64 runner) rebuilds two Ubuntu source
|
||||
packages: Mesa with `-Dfreedreno-kmds=msm,kgsl`, so Turnip and freedreno reach Android's
|
||||
`/dev/kgsl-3d0`, and KWin with `patches/kwin` (nested desktop scale, an explicit render node,
|
||||
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds KGSL
|
||||
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
|
||||
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)).
|
||||
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
|
||||
`DD_TURNIP_SHA256` in `base.env`): Ubuntu's Turnip is diverted to `libvulkan_freedreno.so.distrib`
|
||||
because it lacks the Adreno 8xx fixes. Zink, EGL and llvmpipe stay Ubuntu's.
|
||||
- `build.sh` verifies Ubuntu's base image (`base.env`: signed `SHA256SUMS` from cdimage plus the
|
||||
pinned hash), chroots into it and runs `setup.sh` twice. The `runtime` stage is everything gaming
|
||||
mode needs; it is packed as `<tag>.tar.zst`. The `desktop` stage then adds Plasma on top, and
|
||||
`desktop-pack.py` packs only what that stage added or changed as `<tag>-desktop.tar.zst`, so the
|
||||
desktop shares every runtime file instead of shipping its own copy. The runtime carries
|
||||
`usr/share/droiddeck/desktop-pack.json` (tag, URL, hash, size) naming its matching desktop pack.
|
||||
- `setup.sh runtime` installs `packages-runtime.txt` without recommends and the `+droiddeck` debs from
|
||||
a local repository in `/var/lib/droiddeck/apt` (pinned at 1001 and held), then builds the
|
||||
`droiddeck-runtime` package from `overlay-runtime/`. `setup.sh desktop` installs
|
||||
`packages-desktop.txt`, Firefox from Mozilla's apt repository (`mozilla.asc`, fingerprint
|
||||
35BAA0B33E9EB396F59CA838C0BA5CE6DC6315A3) and builds `droiddeck-desktop` from `overlay-desktop/`.
|
||||
Both packages are Protected, depend on `protected-*.txt`, own our files and divert any Ubuntu file
|
||||
they replace, so apt neither removes the essentials nor overwrites our settings on upgrade.
|
||||
- The desktop pack's `usr/share/droiddeck/desktop/files.tsv.gz` lists each path the desktop added
|
||||
(N), changed (C) or removed (R), and `originals/` keeps the runtime's copies of changed and removed
|
||||
files. Removing the desktop restores those and deletes the added files the user has not changed;
|
||||
a runtime update replaces the tree, and the desktop is downloaded again when it is next opened.
|
||||
|
||||
At run time:
|
||||
|
||||
- `sudo`, `su`, `pkexec` and apt/aptitude (for commands that change the system) go through
|
||||
`droiddeck-root`: the app runs them in a separate proot with `-0 --link2symlink`, passing the
|
||||
caller's terminal, so dpkg gets root ownership emulation and hard links while the desktop keeps
|
||||
the fast path. PackageKit (Discover) and polkit are started the same way by the session's system
|
||||
bus (`/usr/share/droiddeck/system-services`).
|
||||
- `apt/remember` (a `DPkg::Post-Invoke` hook) keeps the packages, sources and keys the user added in
|
||||
`~/.local/share/droiddeck/apt`; `apt/restore` (autostarted) puts them back after a runtime update.
|
||||
- The installer turns the image's hard links into proot's link2symlink layout, and proot shows the
|
||||
linked name as `/proc/self/exe` (patch 0020), so Ubuntu's multi-call coreutils work.
|
||||
|
||||
`.github/workflows/build-ubuntu-runtime.yml` builds it and, run with a new tag (`ubuntu-rN`),
|
||||
publishes the runtime and its desktop pack in Droid-Deck/DroidDeck-Components; `linuxfs-ubuntu.json` there names the release the
|
||||
app installs.
|
||||
@@ -0,0 +1,5 @@
|
||||
APT::Install-Recommends "true";
|
||||
APT::Sandbox::User "root";
|
||||
Dpkg::Options { "--force-confdef"; "--force-confold"; };
|
||||
DPkg::Post-Invoke { "[ ! -x /usr/share/droiddeck/apt/remember ] || /usr/share/droiddeck/apt/remember"; };
|
||||
APT::Update::Post-Invoke { "[ ! -x /usr/share/droiddeck/apt/remember ] || /usr/share/droiddeck/apt/remember"; };
|
||||
@@ -0,0 +1,3 @@
|
||||
Package: plymouth plymouth-* grub-* initramfs-tools initramfs-tools-* cryptsetup-initramfs linux-image-* linux-headers-* linux-modules-* linux-generic* apport whoopsie
|
||||
Pin: release *
|
||||
Pin-Priority: -1
|
||||
@@ -0,0 +1,5 @@
|
||||
UBUNTU_BASE_URL=https://cdimage.ubuntu.com/ubuntu-base/releases/26.04/release/ubuntu-base-26.04.1-base-arm64.tar.gz
|
||||
UBUNTU_BASE_SHA256=5a1906794ced63a71a8119c3f211ef5f0bbe0a243001b4bbd41fdf80c5b219fd
|
||||
UBUNTU_CDIMAGE_KEY=843938DF228D22F7B3742BC0D94AA3F0EFE21092
|
||||
DD_TURNIP_URL=https://github.com/Droid-Deck/Drivers-CI/releases/download/DD-Turnip-v0.3.4/DD-Turnip-v0.3.4.zip
|
||||
DD_TURNIP_SHA256=81db74cff1bf6568581cfd79203bec22f48856006aeac09e9e0a3eb3f9416fc1
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out=$(realpath -m "${1:?out dir}")
|
||||
export DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 DEBEMAIL=maxjividen@gmail.com DEBFULLNAME=maxjivi05
|
||||
export DEB_BUILD_OPTIONS="nocheck noddebs parallel=$(nproc)"
|
||||
sed -i 's/^Types: deb$/Types: deb deb-src/' /etc/apt/sources.list.d/ubuntu.sources
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq build-essential devscripts equivs patch >/dev/null
|
||||
mkdir -p "$out"
|
||||
work=$(mktemp -d)
|
||||
cd "$work"
|
||||
|
||||
apt-get source -qq mesa
|
||||
cd mesa-*/
|
||||
sed -i '0,/GALLIUM_DRIVERS += freedreno/s//GALLIUM_DRIVERS += freedreno\n\tconfflags_GALLIUM += -Dfreedreno-kmds=msm,kgsl/' debian/rules
|
||||
grep -q 'freedreno-kmds=msm,kgsl' debian/rules
|
||||
for p in "$here"/patches/mesa/*.patch; do patch -p1 --forward < "$p"; done
|
||||
dch -l +droiddeck -D resolute "Enable the KGSL kernel interface for freedreno and Turnip."
|
||||
apt-get build-dep -y -qq ./ >/dev/null
|
||||
dpkg-buildpackage -b -uc -us >"$work/mesa.log" 2>&1 || { tail -80 "$work/mesa.log"; exit 1; }
|
||||
cd "$work"
|
||||
|
||||
apt-get source -qq kwin
|
||||
cd kwin-*/
|
||||
for p in "$here"/patches/kwin/*.patch; do patch -p1 --forward < "$p"; done
|
||||
dch -l +droiddeck -D resolute "Scale nested outputs, open the selected render node, forward scroll details."
|
||||
apt-get build-dep -y -qq ./ >/dev/null
|
||||
dpkg-buildpackage -b -uc -us >"$work/kwin.log" 2>&1 || { tail -80 "$work/kwin.log"; exit 1; }
|
||||
cd "$work"
|
||||
|
||||
for deb in *.deb; do
|
||||
case $deb in *-dbgsym_*) continue ;; esac
|
||||
cp "$deb" "$out/"
|
||||
done
|
||||
ls -l "$out"
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
debs=$(realpath "${1:?directory with the DroidDeck-built .deb files}")
|
||||
out=$(realpath -m "${2:?out dir}")
|
||||
runtime_id=${3:?runtime id, e.g. ubuntu-r1}
|
||||
[ "$(uname -m)" = aarch64 ] || { echo 'the Ubuntu runtime needs a native arm64 runner' >&2; exit 1; }
|
||||
source "$here/base.env"
|
||||
fetch() { curl -fsSL --proto '=https' --proto-redir '=https' --retry 6 --retry-delay 5 --retry-all-errors -o "$1" "$2"; }
|
||||
work=$(mktemp -d)
|
||||
root=$work/root
|
||||
cleanup() {
|
||||
for m in dev/pts dev proc sys; do sudo umount "$root/$m" 2>/dev/null || true; done
|
||||
sudo rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
mkdir -p "$root" "$out"
|
||||
base=$work/base.tar.gz
|
||||
fetch "$base" "$UBUNTU_BASE_URL"
|
||||
fetch "$work/SHA256SUMS" "${UBUNTU_BASE_URL%/*}/SHA256SUMS"
|
||||
fetch "$work/SHA256SUMS.gpg" "${UBUNTU_BASE_URL%/*}/SHA256SUMS.gpg"
|
||||
gpgv --status-fd 1 --keyring /usr/share/keyrings/ubuntu-archive-keyring.gpg "$work/SHA256SUMS.gpg" "$work/SHA256SUMS" 2>/dev/null \
|
||||
| grep -Eq "^\[GNUPG:\] VALIDSIG .* $UBUNTU_CDIMAGE_KEY\$"
|
||||
grep -q "^$UBUNTU_BASE_SHA256 \*${UBUNTU_BASE_URL##*/}\$" "$work/SHA256SUMS"
|
||||
echo "$UBUNTU_BASE_SHA256 $base" | sha256sum -c - >/dev/null
|
||||
|
||||
sudo tar -xzf "$base" -C "$root" --numeric-owner
|
||||
sudo cp /etc/resolv.conf "$root/etc/resolv.conf"
|
||||
for m in dev dev/pts proc sys; do sudo mount --bind "/$m" "$root/$m"; done
|
||||
sudo mkdir -p "$root/tmp/droiddeck/debs"
|
||||
sudo cp -r "$here/." "$root/tmp/droiddeck/src"
|
||||
sudo cp "$debs"/*.deb "$root/tmp/droiddeck/debs/"
|
||||
base_url=${DESKTOP_BASE_URL:-https://github.com/Droid-Deck/DroidDeck-Components/releases/download/$runtime_id}
|
||||
desktop_id=$runtime_id-desktop
|
||||
stage() {
|
||||
sudo chroot "$root" /bin/bash /tmp/droiddeck/src/setup.sh /tmp/droiddeck/debs "$runtime_id" "$1"
|
||||
}
|
||||
seal() {
|
||||
for m in dev/pts dev proc sys; do sudo umount "$root/$m"; done
|
||||
sudo rm -f "$root/etc/resolv.conf"
|
||||
printf 'nameserver 1.1.1.1\nnameserver 8.8.8.8\n' | sudo tee "$root/etc/resolv.conf" >/dev/null
|
||||
}
|
||||
unseal() {
|
||||
sudo cp /etc/resolv.conf "$root/etc/resolv.conf"
|
||||
for m in dev dev/pts proc sys; do sudo mount --bind "/$m" "$root/$m"; done
|
||||
}
|
||||
|
||||
stage runtime
|
||||
seal
|
||||
sudo mv "$root/tmp/droiddeck" "$work/src-keep"
|
||||
sudo chroot "$root" dpkg-query -W -f '${Package} ${Version}\n' > "$out/$runtime_id.packages.txt"
|
||||
sudo tar -C "$root" --numeric-owner -cf "$work/runtime.tar" .
|
||||
sudo python3 "$here/desktop-pack.py" manifest "$root" "$work/runtime.manifest"
|
||||
unseal
|
||||
sudo mv "$work/src-keep" "$root/tmp/droiddeck"
|
||||
stage desktop
|
||||
seal
|
||||
sudo rm -rf "$root/tmp/droiddeck"
|
||||
sudo chroot "$root" dpkg-query -W -f '${Package} ${Version}\n' > "$out/$desktop_id.packages.txt"
|
||||
sudo python3 "$here/desktop-pack.py" pack "$root" "$work/runtime.manifest" "$work/runtime.tar" "$work/desktop.tar" "$work/meta"
|
||||
sudo zstd -q -19 -T0 --rm "$work/desktop.tar" -o "$out/$desktop_id.tar.zst"
|
||||
sudo chown "$(id -u):$(id -g)" "$out/$desktop_id.tar.zst"
|
||||
sha256sum "$out/$desktop_id.tar.zst" | cut -d' ' -f1 > "$out/$desktop_id.sha256"
|
||||
|
||||
mkdir -p "$work/stamp"
|
||||
python3 "$here/desktop-pack.py" describe "$out/$desktop_id.tar.zst" "$base_url/$desktop_id.tar.zst" "$desktop_id" \
|
||||
"$work/stamp/usr/share/droiddeck/desktop-pack.json"
|
||||
sudo tar -C "$work/stamp" --numeric-owner --owner=0 --group=0 -rf "$work/runtime.tar" ./usr/share/droiddeck/desktop-pack.json
|
||||
sudo zstd -q -19 -T0 --rm "$work/runtime.tar" -o "$out/$runtime_id.tar.zst"
|
||||
sudo chown "$(id -u):$(id -g)" "$out/$runtime_id.tar.zst"
|
||||
sha256sum "$out/$runtime_id.tar.zst" | cut -d' ' -f1 > "$out/$runtime_id.sha256"
|
||||
ls -l "$out"
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
SKIP = {"proc", "sys", "dev", "run", "tmp", "var/tmp", "var/log", "var/cache/apt", "var/lib/apt/lists",
|
||||
"etc/resolv.conf", "etc/machine-id", "var/lib/dbus/machine-id"}
|
||||
META = "usr/share/droiddeck/desktop"
|
||||
|
||||
|
||||
def walk(root):
|
||||
out = {}
|
||||
for top, dirs, files in os.walk(root):
|
||||
rel_top = os.path.relpath(top, root)
|
||||
rel_top = "" if rel_top == "." else rel_top
|
||||
dirs[:] = [d for d in dirs if os.path.join(rel_top, d) not in SKIP]
|
||||
for name in dirs + files:
|
||||
rel = os.path.join(rel_top, name)
|
||||
if rel in SKIP or name.startswith(".l2s."):
|
||||
continue
|
||||
st = os.lstat(os.path.join(root, rel))
|
||||
if stat.S_ISDIR(st.st_mode):
|
||||
out[rel] = ("d", 0, st.st_mode & 0o7777, "", 0)
|
||||
elif stat.S_ISLNK(st.st_mode):
|
||||
out[rel] = ("l", 0, 0, os.readlink(os.path.join(root, rel)), 0)
|
||||
elif stat.S_ISREG(st.st_mode):
|
||||
out[rel] = ("f", st.st_size, st.st_mode & 0o7777, "%d.%d" % (st.st_ino, st.st_mtime_ns), 0)
|
||||
return out
|
||||
|
||||
|
||||
def sha256(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def save(manifest, path):
|
||||
with open(path, "w") as f:
|
||||
for rel, (kind, size, mode, extra, _) in sorted(manifest.items()):
|
||||
f.write("%s\t%d\t%o\t%s\t%s\n" % (kind, size, mode, extra, rel))
|
||||
|
||||
|
||||
def load(path):
|
||||
out = {}
|
||||
with open(path) as f:
|
||||
for line in f:
|
||||
kind, size, mode, extra, rel = line.rstrip("\n").split("\t", 4)
|
||||
if os.path.basename(rel).startswith(".l2s."):
|
||||
continue
|
||||
out[rel] = (kind, int(size), int(mode, 8), extra, 0)
|
||||
return out
|
||||
|
||||
|
||||
def describe(root, rel, entry):
|
||||
kind, size, _, extra, _ = entry
|
||||
if kind == "f":
|
||||
return "F\t%d\t%s" % (size, sha256(os.path.join(root, rel)))
|
||||
if kind == "l":
|
||||
return "L\t0\t%s" % extra
|
||||
return "D\t0\t-"
|
||||
|
||||
|
||||
def pack(root, before_path, runtime_tar, out_tar, meta_root):
|
||||
before = load(before_path)
|
||||
after = walk(root)
|
||||
added = sorted(p for p in after if p not in before)
|
||||
changed = sorted(p for p in after if p in before and after[p][:4] != before[p][:4] and after[p][0] != "d")
|
||||
removed = sorted(p for p in before if p not in after)
|
||||
if any(p.startswith(META + "/") or p == META for p in added + changed + removed):
|
||||
sys.exit("the desktop stage must not write " + META)
|
||||
meta = os.path.join(meta_root, META)
|
||||
originals = os.path.join(meta, "originals")
|
||||
os.makedirs(originals, exist_ok=True)
|
||||
restore = [p for p in changed + removed if before[p][0] != "d"]
|
||||
if restore:
|
||||
listing = os.path.join(meta_root, "restore.list")
|
||||
with open(listing, "w") as f:
|
||||
f.write("".join("./%s\n" % p for p in restore))
|
||||
subprocess.run(["tar", "-xf", runtime_tar, "-C", originals, "--numeric-owner", "--no-recursion", "-T", listing], check=True)
|
||||
os.unlink(listing)
|
||||
with gzip.open(os.path.join(meta, "files.tsv.gz"), "wt") as f:
|
||||
for p in added:
|
||||
f.write("N\t%s\t%s\n" % (describe(root, p, after[p]), p))
|
||||
for p in changed:
|
||||
f.write("C\t%s\t%s\n" % (describe(root, p, after[p]), p))
|
||||
for p in removed:
|
||||
f.write("R\t%s\t%s\n" % (describe(originals, p, before[p]) if before[p][0] != "d" else "D\t0\t-", p))
|
||||
listing = os.path.join(meta_root, "pack.list")
|
||||
with open(listing, "w") as f:
|
||||
f.write("".join("./%s\n" % p for p in added + changed))
|
||||
metalist = os.path.join(meta_root, "meta.list")
|
||||
with open(metalist, "w") as f:
|
||||
for top, dirs, files in os.walk(meta):
|
||||
for name in dirs + files:
|
||||
f.write("./%s\n" % os.path.relpath(os.path.join(top, name), meta_root))
|
||||
f.write("./%s\n" % META)
|
||||
subprocess.run(["tar", "--numeric-owner", "--no-recursion", "--hard-dereference", "-cf", out_tar, "-C", root, "-T", listing,
|
||||
"-C", meta_root, "-T", metalist], check=True)
|
||||
os.unlink(listing)
|
||||
os.unlink(metalist)
|
||||
print("desktop pack: %d added, %d changed, %d removed" % (len(added), len(changed), len(removed)))
|
||||
|
||||
|
||||
def describe_pack(archive, url, tag, out):
|
||||
digest = sha256(archive)
|
||||
size = os.path.getsize(archive)
|
||||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||||
with open(out, "w") as f:
|
||||
json.dump({"tag": tag, "url": url, "sha256": digest, "size": size}, f, indent=2)
|
||||
f.write("\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if command == "manifest" and len(sys.argv) == 4:
|
||||
save(walk(sys.argv[2]), sys.argv[3])
|
||||
elif command == "pack" and len(sys.argv) == 7:
|
||||
pack(*sys.argv[2:])
|
||||
elif command == "describe" and len(sys.argv) == 6:
|
||||
describe_pack(*sys.argv[2:])
|
||||
else:
|
||||
sys.exit("usage: desktop-pack.py manifest ROOT OUT | pack ROOT BEFORE RUNTIME_TAR OUT_TAR META_ROOT | describe ARCHIVE URL TAG OUT_JSON")
|
||||
@@ -0,0 +1,19 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
xsBNBGCRt7MBCADkYJHHQQoL6tKrW/LbmfR9ljz7ib2aWno4JO3VKQvLwjyUMPpq
|
||||
/SXXMOnx8jXwgWizpPxQYDRJ0SQXS9ULJ1hXRL/OgMnZAYvYDeV2jBnKsAIEdiG/
|
||||
e1qm8P4W9qpWJc+hNq7FOT13RzGWRx57SdLWSXo0KeY38r9lvjjOmT/cuOcmjwlD
|
||||
T9XYf/RSO+yJ/AsyMdAr+ZbDeQUd9HYJiPdI04lGaGM02MjDMnx+monc+y54t+Z+
|
||||
ry1WtQdzoQt9dHlIPlV1tR+xV5DHHsejCZxu9TWzzSlL5wfBBeEz7R/OIzivGJpW
|
||||
QdJzd+2QDXSRg9q2XYWP5ZVtSgjVVJjNlb6ZABEBAAHNVEFydGlmYWN0IFJlZ2lz
|
||||
dHJ5IFJlcG9zaXRvcnkgU2lnbmVyIDxhcnRpZmFjdC1yZWdpc3RyeS1yZXBvc2l0
|
||||
b3J5LXNpZ25lckBnb29nbGUuY29tPsLAjgQTAQoAOBYhBDW6oLM+nrOW9ZyoOMC6
|
||||
XObcYxWjBQJgkbezAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAAAoJEMC6XObc
|
||||
YxWj+igIAMFh6DrAYMeq9sbZ1ZG6oAMrinUheGQbEqe76nIDQNsZnhDwZ2wWqgVC
|
||||
7DgOMqlhQmOmzm7M6Nzmq2dvPwq3xC2OeI9fQyzjT72deBTzLP7PJok9PJFOMdLf
|
||||
ILSsUnmMsheQt4DUO0jYAX2KUuWOIXXJaZ319QyoRNBPYa5qz7qXS7wHLOY89IDq
|
||||
fHt6Aud8ER5zhyOyhytcYMeaGC1g1IKWmgewnhEq02FantMJGlmmFi2eA0EPD02G
|
||||
C3742QGqRxLwjWsm5/TpyuU24EYKRGCRm7QdVIo3ugFSetKrn0byOxWGBvtu4fH8
|
||||
XWvZkRT+u+yzH1s5yFYBqc2JTrrJvRU=
|
||||
=QnvN
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1 @@
|
||||
path-exclude=/etc/skel/Desktop/*
|
||||
@@ -0,0 +1,7 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=DroidDeck software restore
|
||||
Exec=/usr/share/droiddeck/apt/restore
|
||||
NoDisplay=true
|
||||
X-KDE-autostart-phase=2
|
||||
OnlyShowIn=KDE;
|
||||
@@ -0,0 +1,2 @@
|
||||
[Basic Settings]
|
||||
Indexing-Enabled=false
|
||||
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user