mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +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,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=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
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user