Compare commits

..
Author SHA1 Message Date
Kurt Himebauch d4b2402dc2 Merge branch 'main' into fix/long-app-storage-socket-path 2026-11-24 17:51:13 -05:00
Kurt Himebauch 5fec4a2d25 fix(wayland): hooked guest clients reach sockets whose host path is longer than sun_path
The native-userland hook and the Go shim name a long socket path through /proc/self/fd/<dir>/<name>, the rule the compositor listener and proot already use, instead of a hashed /tmp name nobody listens on.
2026-11-24 17:06:23 -05:00
Kurt Himebauch 81e6aef669 fix(wayland): the compositor listens when its socket path is longer than sun_path 2026-11-24 17:03:53 -05:00
21 changed files with 386 additions and 276 deletions

No files matched your search

@@ -22,6 +22,7 @@ add_library(droiddeckwayland SHARED
src/hdr_compose.c
src/blend_pass.c
src/gpu_busy.c
src/unix_listen.c
generated/color-management-v1-protocol.c
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
+10 -1
View File
@@ -39,6 +39,7 @@
#include "droiddeck_color.h"
#include "compositor_internal.h"
#include "clock_domain.h"
#include "unix_listen.h"
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", __VA_ARGS__)
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", __VA_ARGS__)
@@ -4368,7 +4369,15 @@ int droiddeck_wayland_run(void) {
snprintf(p, sizeof(p), "%s/wayland-0", rt); unlink(p);
snprintf(p, sizeof(p), "%s/wayland-0.lock", rt); unlink(p);
}
if (wl_display_add_socket(display, "wayland-0") != 0) {
int listening = -1;
if (rt && *rt && !droiddeck_unix_path_fits(rt, "wayland-0")) {
int fd = droiddeck_unix_listen(rt, "wayland-0", 128);
if (fd >= 0 && wl_display_add_socket_fd(display, fd) == 0) listening = 0;
else if (fd >= 0) close(fd);
} else {
listening = wl_display_add_socket(display, "wayland-0");
}
if (listening != 0) {
WLOGE("add_socket(wayland-0) failed in XDG_RUNTIME_DIR=%s (errno path/perms?)",
rt ? rt : "(null)");
return 1;
@@ -0,0 +1,37 @@
#include "unix_listen.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
bool droiddeck_unix_path_fits(const char *dir, const char *name) {
struct sockaddr_un addr;
return strlen(dir) + 1 + strlen(name) < sizeof(addr.sun_path);
}
int droiddeck_unix_listen(const char *dir, const char *name, int backlog) {
struct sockaddr_un addr = { .sun_family = AF_UNIX };
int dir_fd = open(dir, O_PATH | O_DIRECTORY | O_CLOEXEC);
if (dir_fd < 0) return -1;
int written = snprintf(addr.sun_path, sizeof(addr.sun_path), "/proc/self/fd/%d/%s", dir_fd, name);
if (written < 0 || (size_t)written >= sizeof(addr.sun_path)) {
close(dir_fd);
errno = ENAMETOOLONG;
return -1;
}
int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd >= 0 && (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, backlog) != 0)) {
int saved = errno;
close(fd);
fd = -1;
errno = saved;
}
int saved = errno;
close(dir_fd);
errno = saved;
return fd;
}
@@ -0,0 +1,7 @@
#ifndef UNIX_LISTEN_H
#define UNIX_LISTEN_H
#include <stdbool.h>
bool droiddeck_unix_path_fits(const char *dir, const char *name);
int droiddeck_unix_listen(const char *dir, const char *name, int backlog);
#endif
@@ -626,7 +626,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var cardboard by mutableStateOf(Cardboard.OFF)
private var headTracker: HeadTracker? = null
private var steamVrStatus by mutableStateOf<SteamVr.Status?>(null)
private var steamVrPercent by mutableStateOf<Int?>(null)
private var steamVrSwitchedPicture by mutableStateOf(false)
private var steamVrSeenRunning = false
private val steamVrRecovery by lazy { com.droiddeck.launcher.gpu.SteamVrRecovery(this) {
@@ -1391,12 +1390,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val request = steamVrRequestGeneration
val session = SessionState.sessionId
val now = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
SteamVr.report(this@SessionActivity)
}
if (request == steamVrRequestGeneration && session == SessionState.sessionId) {
steamVrPercent = now.percent
onSteamVrStatus(now.status)
SteamVr.status(this@SessionActivity)
}
if (request == steamVrRequestGeneration && session == SessionState.sessionId) onSteamVrStatus(now)
kotlinx.coroutines.delay(3000)
}
}
@@ -1509,7 +1505,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.glasses.GlassesMenuMirror.recenter()
},
steamVr = steamVrStatus,
steamVrPercent = steamVrPercent,
immersiveSteamVr = com.droiddeck.launcher.session.QuestExperimental.isSupported(),
onSteamVr = { action -> steamVrAction(action) },
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
@@ -32,21 +32,9 @@ object SteamVr {
}
}
data class Report(val status: Status, val percent: Int? = null)
fun status(context: Context): Status = report(context).status
fun report(context: Context): Report = runCatching {
report(AgentGuest.call(context, JSONObject().put("kind", "vr").put("action", "status"), STATUS_TIMEOUT_MS))
}.getOrDefault(Report(Status.UNAVAILABLE))
fun report(answer: JSONObject): Report {
val status = parse(answer)
val size = answer.optLong("size", 0L)
val done = answer.optLong("downloaded", -1L)
val percent = if (status == Status.INSTALLING && size > 0 && done in 0 until size) (done * 100 / size).toInt() else null
return Report(status, percent)
}
fun status(context: Context): Status = runCatching {
parse(AgentGuest.call(context, JSONObject().put("kind", "vr").put("action", "status"), STATUS_TIMEOUT_MS))
}.getOrDefault(Status.UNAVAILABLE)
fun run(context: Context, action: String): Boolean = runCatching {
require(action in setOf("install", "start", "stop"))
@@ -948,7 +948,7 @@ internal object EnhancedSessionLogShare {
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "droiddeck-steamvr-install.log", "cef_log.txt", "cef_log.previous.txt",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
"rpcs3", "RPCS3.log",
)
@@ -265,7 +265,6 @@ class DrawerActions(
val cardboard: Cardboard = Cardboard.OFF,
val cardboardSensor: Boolean = false,
val steamVr: SteamVr.Status? = null,
val steamVrPercent: Int? = null,
val glassesPresent: Boolean = false,
val glassesOutput: Boolean = false,
val immersiveSteamVr: Boolean = false,
@@ -1403,7 +1402,7 @@ private fun SteamVrGroup(a: DrawerActions, track: (String) -> Modifier) {
}
when (a.steamVr) {
SteamVr.Status.NOT_INSTALLED -> button(vrLabel, stringResource(R.string.cardboard_steamvr_install), "install")
SteamVr.Status.INSTALLING -> SteamVrInstalling(vrLabel, a.steamVrPercent)
SteamVr.Status.INSTALLING -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_installing)) {}
SteamVr.Status.READY -> button(vrLabel, enterLabel, "start")
SteamVr.Status.RUNNING -> {
if (a.immersiveSteamVr) button(vrLabel, enterLabel, "start")
@@ -1418,19 +1417,12 @@ private fun SteamVrGroup(a: DrawerActions, track: (String) -> Modifier) {
}
}
@Composable
private fun SteamVrInstalling(label: String, percent: Int?) {
SettingsRow(label, stringResource(R.string.cardboard_steamvr_installing)) {
if (percent != null) Text(stringResource(R.string.ctrl_percent, percent), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
private fun SteamVrRow(a: DrawerActions) {
val vrLabel = stringResource(R.string.cardboard_steamvr)
when (a.steamVr) {
SteamVr.Status.NOT_INSTALLED -> ActionRow(vrLabel, null, stringResource(R.string.cardboard_steamvr_install), { a.onSteamVr("install") })
SteamVr.Status.INSTALLING -> SteamVrInstalling(vrLabel, a.steamVrPercent)
SteamVr.Status.INSTALLING -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_installing)) {}
SteamVr.Status.READY -> ActionRow(vrLabel, null, stringResource(R.string.cardboard_steamvr_start), { a.onSteamVr("start") })
SteamVr.Status.RUNNING -> ActionRow(vrLabel, null, stringResource(R.string.cardboard_steamvr_stop), { a.onSteamVr("stop") })
SteamVr.Status.UNAVAILABLE -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_unavailable)) {}
@@ -64,22 +64,6 @@ class CardboardTest {
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true).put("exitCode", 1)))
}
@Test fun steamVrReportsDownloadPercentOnlyWhileInstalling() {
fun answer(installing: Boolean, downloaded: Long?, size: Long?) = JSONObject().apply {
put("ok", true)
put("installing", installing)
put("driver", true)
downloaded?.let { put("downloaded", it) }
size?.let { put("size", it) }
}
assertEquals(SteamVr.Report(SteamVr.Status.INSTALLING, 0), SteamVr.report(answer(true, 0, 571_309_057)))
assertEquals(SteamVr.Report(SteamVr.Status.INSTALLING, 49), SteamVr.report(answer(true, 285_654_528, 571_309_057)))
assertEquals(SteamVr.Report(SteamVr.Status.INSTALLING, 99), SteamVr.report(answer(true, 571_309_056, 571_309_057)))
assertEquals(SteamVr.Report(SteamVr.Status.INSTALLING, null), SteamVr.report(answer(true, 571_309_057, 571_309_057)))
assertEquals(SteamVr.Report(SteamVr.Status.INSTALLING, null), SteamVr.report(answer(true, null, null)))
assertEquals(SteamVr.Report(SteamVr.Status.NOT_INSTALLED, null), SteamVr.report(answer(false, 1_000, 571_309_057)))
}
@Test fun steamVrActionsSucceedOnlyWhenTheHelperDid() {
fun answer(ok: Boolean, exitCode: Int? = null, started: Boolean? = null) = JSONObject().apply {
put("ok", ok)
+1 -4
View File
@@ -55,10 +55,7 @@ the lens exactly.
Valve's ARM64 SteamVR, the build the Steam Frame runs, comes from Valve's public SteamOS package
server (`deckard-steamvr`, pinned by version and SHA-256 in `droiddeck-steamvr`; the same hash
[steam-frame-nixos](https://github.com/y0usaf/steam-frame-nixos) pins). `droiddeck-steamvr install`
unpacks it to `/opt/steamvr`. The drawer's **Install** button runs that (571 MB) and shows the
download percentage. A download that stays under 1 KB/s for 60 seconds is stopped and resumed, up to
five tries without progress; each step is written to Steam's logs as `droiddeck-steamvr-install.log`,
which the session log share includes. **Start** then
unpacks it to `/opt/steamvr`. The drawer's **Install** button runs that (571 MB). **Start** then
switches the picture to side-by-side and runs SteamVR with three DroidDeck pieces (`tools/vr`):
1. **`driver_droiddeck.so`**, an OpenVR driver with one HMD:
@@ -1082,8 +1082,6 @@ def steamvr(req):
key, _, value = part.partition("=")
if key in ("installed", "running", "installing", "driver"):
result[key] = value == "1"
elif key in ("downloaded", "size") and value.isdigit():
result[key] = int(value)
return result
@@ -13,15 +13,6 @@ chmod 700 "$state"
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
PKG_SIZE=571309057
pkg=$HOME/.cache/droiddeck-vr/steamvr.pkg.tar.zst
install_log=$logs/droiddeck-steamvr-install.log
bytes() { stat -c %s "$1" 2>/dev/null || echo 0; }
note() {
mkdir -p "$logs"
printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" | tee -a "$install_log"
}
running() { pgrep -x vrserver >/dev/null 2>&1; }
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
@@ -99,7 +90,7 @@ status)
if idle; then unregister; fi
n=0; [ -f "$state/installing" ] && n=1
d=0; [ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] && [ -f "$layer/libVkLayer_droiddeck_vr.so" ] && d=1
echo "installed=$i running=$r installing=$n driver=$d downloaded=$(bytes "$pkg") size=$PKG_SIZE"
echo "installed=$i running=$r installing=$n driver=$d"
;;
install)
exec 7>"$state/install.lock"
@@ -107,30 +98,18 @@ install)
installed && { echo "SteamVR is already in $steamvr"; exit 0; }
: > "$state/installing"
trap 'rm -f "$state/installing"' EXIT
cache=$(dirname "$pkg")
cache=$HOME/.cache/droiddeck-vr
mkdir -p "$cache"
attempt=1
while [ "$(bytes "$pkg")" -lt "$PKG_SIZE" ]; do
before=$(bytes "$pkg")
note "downloading SteamVR from Valve's package server: attempt $attempt, $before of $PKG_SIZE bytes"
curl -fsSL --connect-timeout 30 --speed-limit 1024 --speed-time 60 -C - -o "$pkg" "$PKG_URL" 2>>"$install_log"
code=$?
note "curl exited $code with $(bytes "$pkg") of $PKG_SIZE bytes"
[ "$code" = 0 ] && break
[ "$(bytes "$pkg")" -gt "$before" ] && attempt=0
[ "$attempt" -lt 5 ] || { note "download failed"; exit 1; }
attempt=$((attempt + 1))
sleep 5
done
note "checking sha256"
echo "$PKG_SHA256 $pkg" | sha256sum -c - >/dev/null 2>&1 || { note "checksum mismatch: removing the download"; rm -f "$pkg"; exit 1; }
pkg=$cache/steamvr.pkg.tar.zst
echo "downloading SteamVR (571 MB) from Valve's package server"
curl -fsSL --retry 5 -C - -o "$pkg" "$PKG_URL" || { echo "download failed"; exit 1; }
echo "$PKG_SHA256 $pkg" | sha256sum -c - >/dev/null 2>&1 || { echo "checksum mismatch: removing the download"; rm -f "$pkg"; exit 1; }
tmp=$cache/extract
rm -rf "$tmp" && mkdir -p "$tmp"
note "unpacking SteamVR"
zstd -dc "$pkg" 2>>"$install_log" | tar -x -C "$tmp" opt/steamvr 2>>"$install_log" || { note "extract failed"; rm -rf "$tmp"; exit 1; }
zstd -dc "$pkg" | tar -x -C "$tmp" opt/steamvr || { echo "extract failed"; rm -rf "$tmp"; exit 1; }
mkdir -p "$(dirname "$steamvr")"
rm -rf "$steamvr" && mv "$tmp/opt/steamvr" "$steamvr" && rm -rf "$tmp" "$pkg" || { note "could not move SteamVR into $steamvr"; exit 1; }
note "SteamVR installed in $steamvr"
rm -rf "$steamvr" && mv "$tmp/opt/steamvr" "$steamvr" && rm -rf "$tmp" "$pkg"
echo "SteamVR installed in $steamvr"
;;
stop)
stop || exit 1
+29 -22
View File
@@ -34,7 +34,7 @@ enum {
NR_LLISTXATTR = 12, NR_REMOVEXATTR = 14, NR_LREMOVEXATTR = 15, NR_GETCWD = 17,
NR_INOTIFY_ADD_WATCH = 27, NR_MKNODAT = 33, NR_MKDIRAT = 34, NR_UNLINKAT = 35, NR_SYMLINKAT = 36,
NR_LINKAT = 37, NR_RENAMEAT = 38, NR_STATFS = 43, NR_TRUNCATE = 45, NR_FACCESSAT = 48,
NR_CHDIR = 49, NR_CHROOT = 51, NR_FCHMODAT = 53, NR_FCHOWNAT = 54, NR_OPENAT = 56,
NR_CHDIR = 49, NR_CHROOT = 51, NR_FCHMODAT = 53, NR_FCHOWNAT = 54, NR_OPENAT = 56, NR_CLOSE = 57,
NR_READLINKAT = 78, NR_NEWFSTATAT = 79, NR_UTIMENSAT = 88, NR_BIND = 200, NR_CONNECT = 203,
NR_EXECVE = 221, NR_NAME_TO_HANDLE_AT = 264, NR_RENAMEAT2 = 276, NR_STATX = 291,
NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, NR_SETREGID = 143, NR_SETGID = 144,
@@ -269,17 +269,17 @@ static i64 unmap_prefix(const struct gosys_hdr *h, char *buf, i64 n, int nul) {
// ---- Unix sockets ------------------------------------------------------------------------
static void put_hex16(char *out, u64 v) {
static const char digits[] = "0123456789abcdef";
for (int i = 15; i >= 0; i--) {
out[i] = digits[v & 15];
v >>= 4;
}
static u64 put_dec(char *out, u64 v) {
char digits[20];
u64 n = 0;
do {
digits[n++] = (char)('0' + v % 10);
v /= 10;
} while (v);
for (u64 i = 0; i < n; i++) out[i] = digits[n - 1 - i];
return n;
}
// bind() and connect() of a Unix socket with a path: mapped like hook/setup.c does, and hashed
// into /tmp when it does not fit the 108 bytes of sun_path (the same name, so a Go server and a
// program using the C library find each other)
static i64 with_sockaddr(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, i64 a2) {
const unsigned char *sa = (const unsigned char *)a1;
if (!sa || a2 < 4 || a2 > 128 || sa[0] != 1 /* AF_UNIX */ || sa[1] != 0 || sa[2] != '/')
@@ -290,7 +290,7 @@ static i64 with_sockaddr(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i
if (max > 108) max = 108;
mcopy(orig, (const char *)sa + 2, max);
orig[max] = '\0';
const char *rw = rw_path(h, orig, slot + SLOT_PATH_B, SLOT_PATH_CAP);
char *rw = (char *)rw_path(h, orig, slot + SLOT_PATH_B, SLOT_PATH_CAP);
u64 rl = slen(rw);
char *out = slot + SLOT_ARGV;
out[0] = 1;
@@ -299,18 +299,25 @@ static i64 with_sockaddr(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i
mcopy(out + 2, rw, rl + 1);
return sc(nr, a0, (i64)out, (i64)(2 + rl + 1), 0, 0, 0);
}
u64 hash = 14695981039346656037ULL;
for (const char *p = rw; *p; p++) {
hash ^= (unsigned char)*p;
hash *= 1099511628211ULL;
u64 cut = rl;
while (cut > 0 && rw[cut - 1] != '/') cut--;
if (cut < 2 || cut == rl) return sc(nr, a0, a1, a2, 0, 0, 0);
rw[cut - 1] = '\0';
i64 dir = sc(NR_OPENAT, -100 /* AT_FDCWD */, (i64)rw, 0x200000 | 0x4000 | 0x80000 /* O_PATH | O_DIRECTORY | O_CLOEXEC */, 0, 0, 0);
if (dir < 0) return dir;
mcopy(out + 2, "/proc/self/fd/", 14);
u64 n = 14;
n += put_dec(out + 2 + n, (u64)dir);
out[2 + n++] = '/';
u64 name = rl - cut;
if (n + name + 1 > 108) {
sc(NR_CLOSE, dir, 0, 0, 0, 0, 0);
return -36 /* ENAMETOOLONG */;
}
u64 n = h->root_len;
if (n + 5 + 11 + 16 + 1 > 108) return sc(nr, a0, a1, a2, 0, 0, 0);
mcopy(out + 2, h->root, n);
mcopy(out + 2 + n, "/tmp/.ctx_sock_", 15);
put_hex16(out + 2 + n + 15, hash);
out[2 + n + 15 + 16] = '\0';
return sc(nr, a0, (i64)out, (i64)(2 + n + 15 + 16 + 1), 0, 0, 0);
mcopy(out + 2 + n, rw + cut, name + 1);
i64 r = sc(nr, a0, (i64)out, (i64)(2 + n + name + 1), 0, 0, 0);
sc(NR_CLOSE, dir, 0, 0, 0, 0, 0);
return r;
}
// ---- Starting programs -------------------------------------------------------------------
+1 -5
View File
@@ -113,7 +113,6 @@ int unlink(const char *pathname) {
if (!orig_unlink) orig_unlink = (int (*)(const char *))dlsym(RTLD_NEXT, "unlink");
char buf[PATH_MAX];
const char *target = rewrite_path(pathname, buf, sizeof(buf));
unlink_mapped_unix_socket(target);
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = lookup_emulated_hardlink_at(AT_FDCWD, target, &hl_dev, &hl_ino);
@@ -137,10 +136,7 @@ int unlinkat(int dirfd, const char *pathname, int flags) {
dev_t hl_dev = 0;
ino_t hl_ino = 0;
int hardlinked = 0;
if (target) {
unlink_mapped_unix_socket(target);
hardlinked = lookup_emulated_hardlink_at(dirfd, target, &hl_dev, &hl_ino);
}
if (target) hardlinked = lookup_emulated_hardlink_at(dirfd, target, &hl_dev, &hl_ino);
int ret = orig_unlinkat ? orig_unlinkat(dirfd, target, flags) : -1;
if (ret != 0 && orig_unlinkat && refused_in_repaired_dir(dirfd, target)) {
hardlinked = target ? lookup_emulated_hardlink_at(dirfd, target, &hl_dev, &hl_ino) : 0;
+33 -49
View File
@@ -563,63 +563,47 @@ static const char *usrmerge_retry_path(const char *target, char *alt, size_t alt
return alt;
}
static const char *rewrite_unix_socket_path(const char *sun_path, char *out_buf, size_t out_size) {
if (!sun_path || out_size == 0) return sun_path;
// Abstract sockets start with null byte (\0); leave untouched
if (sun_path[0] == '\0') {
return sun_path;
}
static int unix_socket_address(const char *sun_path, struct sockaddr_un *out, int *dir_fd) {
char full[PATH_MAX];
*dir_fd = -1;
memset(out, 0, sizeof(*out));
out->sun_family = AF_UNIX;
const char *rw = (sun_path[0] == '/') ? rewrite_path(sun_path, full, sizeof(full)) : sun_path;
size_t rw_len = strlen(rw);
// If rewritten path fits safely in sockaddr_un.sun_path (usually 108 bytes)
if (rw_len < out_size) {
strncpy(out_buf, rw, out_size - 1);
out_buf[out_size - 1] = '\0';
return out_buf;
if (rw_len < sizeof(out->sun_path)) {
memcpy(out->sun_path, rw, rw_len + 1);
return 0;
}
// Path exceeds sockaddr_un 108-byte limit!
// Deterministically hash the path into /tmp to guarantee it fits safely (< 80 bytes)
// while remaining 100% deterministic between server and client.
unsigned long long hash = 14695981039346656037ULL;
for (const char *p = rw; *p; p++) {
hash ^= (unsigned char)(*p);
hash *= 1099511628211ULL;
const char *slash = strrchr(rw, '/');
if (!slash || slash == rw || !slash[1]) {
errno = ENAMETOOLONG;
return -1;
}
init_ddnatv_hook();
if (g_ddnatv_root[0] != '\0') {
snprintf(out_buf, out_size, "%s/tmp/.ctx_sock_%016llx", g_ddnatv_root, hash);
} else {
snprintf(out_buf, out_size, "/tmp/.ctx_sock_%016llx", hash);
char dir[PATH_MAX];
size_t dir_len = (size_t)(slash - rw);
if (dir_len >= sizeof(dir)) {
errno = ENAMETOOLONG;
return -1;
}
out_buf[out_size - 1] = '\0';
return out_buf;
memcpy(dir, rw, dir_len);
dir[dir_len] = '\0';
int fd = (int)syscall(SYS_openat, AT_FDCWD, dir, O_PATH | O_DIRECTORY | O_CLOEXEC);
if (fd < 0) return -1;
int written = snprintf(out->sun_path, sizeof(out->sun_path), "/proc/self/fd/%d/%s", fd, slash + 1);
if (written < 0 || (size_t)written >= sizeof(out->sun_path)) {
syscall(SYS_close, fd);
errno = ENAMETOOLONG;
return -1;
}
*dir_fd = fd;
return 0;
}
static void unlink_mapped_unix_socket(const char *target) {
if (!target) return;
size_t t_len = strlen(target);
if (t_len >= 107) {
unsigned long long hash = 14695981039346656037ULL;
for (const char *p = target; *p; p++) {
hash ^= (unsigned char)(*p);
hash *= 1099511628211ULL;
}
char short_path[PATH_MAX];
init_ddnatv_hook();
if (g_ddnatv_root[0] != '\0') {
snprintf(short_path, sizeof(short_path), "%s/tmp/.ctx_sock_%016llx", g_ddnatv_root, hash);
} else {
snprintf(short_path, sizeof(short_path), "/tmp/.ctx_sock_%016llx", hash);
}
static int (*orig_unlink)(const char *) = NULL;
if (!orig_unlink) orig_unlink = (int (*)(const char *))dlsym(RTLD_NEXT, "unlink");
if (orig_unlink) orig_unlink(short_path);
}
static void release_socket_dir(int dir_fd) {
if (dir_fd < 0) return;
int saved_errno = errno;
syscall(SYS_close, dir_fd);
errno = saved_errno;
}
#endif /* !DDNATV_HOST_TEST */
+10 -8
View File
@@ -109,12 +109,13 @@ int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
const struct sockaddr_un *sun = (const struct sockaddr_un *)addr;
if (sun->sun_path[0] != '\0') {
struct sockaddr_un mod_sun;
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
char guest[sizeof(sun->sun_path) + 1];
copy_unix_path(sun, addrlen, guest);
rewrite_unix_socket_path(guest, mod_sun.sun_path, sizeof(mod_sun.sun_path));
return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
int dir_fd;
if (unix_socket_address(guest, &mod_sun, &dir_fd) != 0) return -1;
int ret = orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
release_socket_dir(dir_fd);
return ret;
}
}
int ret = orig_bind ? orig_bind(sockfd, addr, addrlen) : -1;
@@ -139,14 +140,15 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
const struct sockaddr_un *sun = (const struct sockaddr_un *)addr;
if (sun->sun_path[0] != '\0') {
struct sockaddr_un mod_sun;
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
char guest[sizeof(sun->sun_path) + 1];
copy_unix_path(sun, addrlen, guest);
char followed[PATH_MAX];
const char *path = guest[0] == '/' ? follow_guest_link(guest, followed, sizeof(followed)) : guest;
rewrite_unix_socket_path(path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
return orig_connect ? orig_connect(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
int dir_fd;
if (unix_socket_address(path, &mod_sun, &dir_fd) != 0) return -1;
int ret = orig_connect ? orig_connect(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
release_socket_dir(dir_fd);
return ret;
}
}
-5
View File
@@ -179,11 +179,6 @@ class AgentTest(unittest.TestCase):
self.assertEqual((True, False, False, True),
(answer["installed"], answer["running"], answer["installing"], answer["driver"]))
def test_vr_status_reports_download_progress(self):
self.vr_helper('echo "installed=0 running=0 installing=1 driver=1 downloaded=1234 size=571309057"\n')
answer = self.ask({"kind": "vr", "action": "status"})
self.assertEqual((True, 1234, 571309057), (answer["installing"], answer["downloaded"], answer["size"]))
def test_vr_runs_only_its_own_actions(self):
log = self.dir / "args"
self.vr_helper('echo "$@" > %s\n' % log)
+144
View File
@@ -0,0 +1,144 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
ROOT = Path(__file__).resolve().parents[2]
HOOK_BUILD = ROOT / "tools/nativeguest/build.sh"
LISTEN_SRC = ROOT / "app/src/main/cpp/waylandcomp/src/unix_listen.c"
SUN_PATH = 108
GUEST_SOCKET = "/run/droiddeck/wayland-0"
HOOKED = r"""
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main(int argc, char **argv) {
struct sockaddr_un addr = { .sun_family = AF_UNIX };
strncpy(addr.sun_path, argv[2], sizeof(addr.sun_path) - 1);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (strcmp(argv[1], "serve") == 0) {
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 4) != 0) {
perror("serve");
return 1;
}
puts("ready");
fflush(stdout);
int peer = accept(fd, NULL, NULL);
char got = 0;
if (peer < 0 || read(peer, &got, 1) != 1) return 1;
printf("got %c\n", got);
return 0;
}
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
perror("connect");
return 1;
}
return write(fd, "x", 1) == 1 ? 0 : 1;
}
"""
PLAIN_LISTENER = r"""
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include "unix_listen.h"
int main(int argc, char **argv) {
int fd = droiddeck_unix_listen(argv[1], "wayland-0", 4);
if (fd < 0) {
perror("listen");
return 1;
}
puts("ready");
fflush(stdout);
int peer = accept(fd, NULL, NULL);
char got = 0;
if (peer < 0 || read(peer, &got, 1) != 1) return 1;
printf("got %c\n", got);
return 0;
}
"""
class LongSocketPathTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "hooked.c").write_text(HOOKED)
(tmp / "listener.c").write_text(PLAIN_LISTENER)
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "hooked"), str(tmp / "hooked.c")], check=True)
subprocess.run([cls.cc, "-O1", "-D_GNU_SOURCE", "-I", str(LISTEN_SRC.parent), "-o", str(tmp / "listener"),
str(tmp / "listener.c"), str(LISTEN_SRC)], check=True)
cls.hooked = tmp / "hooked"
cls.listener = tmp / "listener"
cls.root = tmp / "root"
cls.root.mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def runtime_dir(self, long):
directory = Path(tempfile.mkdtemp(dir=self.tmp.name))
while long and len(str(directory)) + len("/wayland-0") < SUN_PATH + 10:
directory = directory / ("e" * 30)
directory.mkdir(parents=True, exist_ok=True)
return directory
def start(self, argv, hooked, directory):
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": f"{directory}:/run/droiddeck", "LD_PRELOAD": str(self.hook)}
cmd = list(self.prefix)
if hooked:
if self.prefix:
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
env.update(hook_env)
return subprocess.Popen(cmd + [str(a) for a in argv], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def exchange(self, directory, server_hooked):
server = self.start([self.hooked, "serve", GUEST_SOCKET] if server_hooked else [self.listener, directory], server_hooked, directory)
try:
self.assertEqual("ready", server.stdout.readline().strip(), server.stderr.read() if server.poll() is not None else "")
client = self.start([self.hooked, "connect", GUEST_SOCKET], True, directory)
_, client_err = client.communicate(timeout=30)
self.assertEqual(0, client.returncode, client_err)
out, err = server.communicate(timeout=30)
self.assertEqual(0, server.returncode, err)
self.assertIn("got x", out)
finally:
server.kill()
server.communicate()
def test_hooked_client_reaches_a_listener_at_a_path_longer_than_sun_path(self):
directory = self.runtime_dir(True)
self.assertGreaterEqual(len(str(directory)) + len("/wayland-0"), SUN_PATH)
self.exchange(directory, False)
def test_hooked_server_and_client_share_a_path_longer_than_sun_path(self):
directory = self.runtime_dir(True)
self.exchange(directory, True)
self.assertTrue((directory / "wayland-0").exists())
def test_a_path_that_fits_is_unchanged(self):
directory = self.runtime_dir(False)
self.assertLess(len(str(directory)) + len("/wayland-0"), SUN_PATH)
self.exchange(directory, True)
self.assertTrue((directory / "wayland-0").exists())
if __name__ == "__main__":
unittest.main()
-101
View File
@@ -1,13 +1,9 @@
import hashlib
import io
import os
import json
import shlex
import shutil
import socket
import subprocess
import sys
import tarfile
import tempfile
import time
import unittest
@@ -253,102 +249,5 @@ class SteamVrHelperTest(unittest.TestCase):
self.assertTrue(xr.is_symlink())
def package(self):
payload = io.BytesIO()
with tarfile.open(fileobj=payload, mode='w') as archive:
body = b'#!/bin/sh\n' + os.urandom(6000).hex().encode() + b'\n'
entry = tarfile.TarInfo('opt/steamvr/bin/linuxarm64/vrstartup')
entry.size = len(body)
entry.mode = 0o755
archive.addfile(entry, io.BytesIO(body))
data = payload.getvalue()
source = self.root / 'package'
source.write_bytes(data)
text = self.helper.read_text()
for old, new in (('PKG_SIZE=571309057', 'PKG_SIZE=%d' % len(data)),
('PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9',
'PKG_SHA256=' + hashlib.sha256(data).hexdigest())):
self.assertIn(old, text)
text = text.replace(old, new)
self.helper.write_text(text, encoding='utf-8')
self.executable(self.commands / 'zstd', 'exec cat "$2"')
self.environment['STEAMVR'] = str(self.root / 'fresh/steamvr')
return source, len(data)
def fake_curl(self, source, chunk, exit_code):
self.executable(self.commands / 'curl', '\n'.join((
'out=; previous=',
'for argument in "$@"; do [ "$previous" = -o ] && out=$argument; previous=$argument; done',
'echo "$*" >> %s' % shlex.quote(str(self.root / 'curl-calls')),
'have=$(stat -c %s "$out" 2>/dev/null || echo 0)',
'tail -c +$((have + 1)) %s | head -c %d >> "$out"' % (shlex.quote(str(source)), chunk),
'[ "$(stat -c %%s "$out")" -lt "$(stat -c %%s %s)" ] || exit 0' % shlex.quote(str(source)),
'echo "curl: (28) Operation too slow" >&2',
'exit %d' % exit_code,
)))
def install(self):
return subprocess.run(['sh', str(self.helper), 'install'], env=self.environment,
capture_output=True, text=True, timeout=30)
def install_log(self):
return (self.home / '.local/share/Steam/logs/droiddeck-steamvr-install.log').read_text()
def test_install_resumes_a_stalled_download_and_logs_each_step(self):
source, size = self.package()
self.fake_curl(source, size // 8 + 1, 28)
result = self.install()
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertTrue((self.root / 'fresh/steamvr/bin/linuxarm64/vrstartup').is_file())
calls = (self.root / 'curl-calls').read_text().splitlines()
self.assertEqual(len(calls), 8)
for call in calls:
self.assertIn('--speed-limit 1024 --speed-time 60', call)
self.assertIn('--connect-timeout 30', call)
self.assertIn('-C -', call)
log = self.install_log()
self.assertIn('curl exited 28', log)
self.assertIn('curl: (28) Operation too slow', log)
self.assertIn('curl exited 0 with %d of %d bytes' % (size, size), log)
self.assertIn('checking sha256', log)
self.assertIn('unpacking SteamVR', log)
self.assertIn('SteamVR installed in', log)
self.assertFalse((self.runtime / 'droiddeck-steamvr/installing').exists())
self.assertFalse((self.home / '.cache/droiddeck-vr/steamvr.pkg.tar.zst').exists())
def test_install_gives_up_when_the_download_makes_no_progress(self):
source, size = self.package()
self.fake_curl(source, 0, 28)
result = self.install()
self.assertEqual(result.returncode, 1)
self.assertEqual(len((self.root / 'curl-calls').read_text().splitlines()), 5)
self.assertIn('download failed', self.install_log())
self.assertFalse((self.runtime / 'droiddeck-steamvr/installing').exists())
self.assertFalse((self.root / 'fresh/steamvr').exists())
def test_install_removes_a_corrupt_download(self):
source, size = self.package()
self.fake_curl(source, size, 0)
corrupt = self.home / '.cache/droiddeck-vr/steamvr.pkg.tar.zst'
corrupt.parent.mkdir(parents=True)
corrupt.write_bytes(b'x' * size)
result = self.install()
self.assertEqual(result.returncode, 1)
self.assertFalse((self.root / 'curl-calls').exists())
self.assertIn('checksum mismatch', self.install_log())
self.assertFalse(corrupt.exists())
def test_status_reports_download_progress(self):
partial = self.home / '.cache/droiddeck-vr/steamvr.pkg.tar.zst'
partial.parent.mkdir(parents=True)
partial.write_bytes(b'x' * 1234)
result = subprocess.run(['sh', str(self.helper), 'status'], env=self.environment,
capture_output=True, text=True, timeout=5, check=True)
self.assertIn('downloaded=1234 size=571309057', result.stdout)
partial.unlink()
result = subprocess.run(['sh', str(self.helper), 'status'], env=self.environment,
capture_output=True, text=True, timeout=5, check=True)
self.assertIn('downloaded=0 size=571309057', result.stdout)
if __name__ == '__main__':
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>
#include "../../app/src/main/cpp/waylandcomp/src/unix_listen.h"
int main(int argc, char **argv) {
assert(argc == 3);
const char *dir = argv[1];
int expect_fits = atoi(argv[2]);
assert(droiddeck_unix_path_fits(dir, "wayland-0") == (expect_fits != 0));
int listener = droiddeck_unix_listen(dir, "wayland-0", 4);
assert(listener >= 0);
char path[4096];
snprintf(path, sizeof(path), "%s/wayland-0", dir);
struct stat st;
assert(stat(path, &st) == 0 && S_ISSOCK(st.st_mode));
int dir_fd = open(dir, O_PATH | O_DIRECTORY | O_CLOEXEC);
assert(dir_fd >= 0);
struct sockaddr_un addr = { .sun_family = AF_UNIX };
snprintf(addr.sun_path, sizeof(addr.sun_path), "/proc/self/fd/%d/wayland-0", dir_fd);
int client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
assert(client >= 0 && connect(client, (struct sockaddr *)&addr, sizeof(addr)) == 0);
int peer = accept(listener, NULL, NULL);
assert(peer >= 0);
assert(write(client, "x", 1) == 1);
char got = 0;
assert(read(peer, &got, 1) == 1 && got == 'x');
assert(droiddeck_unix_listen(dir, "wayland-0", 4) < 0);
assert(droiddeck_unix_listen("/nonexistent-dir", "wayland-0", 4) < 0);
puts("PASS: unix listen");
return 0;
}
+53
View File
@@ -0,0 +1,53 @@
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
SRC = ROOT / 'app/src/main/cpp/waylandcomp/src'
SUN_PATH = 108
@unittest.skipUnless(sys.platform.startswith('linux') and shutil.which('cc'), 'requires a Linux C compiler')
class UnixListenTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.folder = tempfile.TemporaryDirectory()
cls.binary = pathlib.Path(cls.folder.name) / 'unix-listen-test'
subprocess.run([
'cc', '-std=c11', '-D_GNU_SOURCE', '-Wall', '-Wextra', '-Werror',
str(ROOT / 'tools/tests/test_unix_listen.c'), str(SRC / 'unix_listen.c'),
'-o', str(cls.binary),
], check=True)
@classmethod
def tearDownClass(cls):
cls.folder.cleanup()
def run_in(self, minimum):
with tempfile.TemporaryDirectory() as base:
directory = pathlib.Path(base)
while len(str(directory)) + len('/wayland-0') < minimum:
directory = directory / ('e' * 30)
directory.mkdir(parents=True, exist_ok=True)
fits = len(str(directory)) + len('/wayland-0') < SUN_PATH
result = subprocess.run([str(self.binary), str(directory), '1' if fits else '0'],
capture_output=True, text=True, timeout=10)
return directory, result
def test_a_path_that_fits_binds_directly(self):
directory, result = self.run_in(0)
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('PASS: unix listen', result.stdout)
def test_a_path_longer_than_sun_path_still_listens_and_accepts(self):
directory, result = self.run_in(140)
self.assertGreaterEqual(len(str(directory)) + len('/wayland-0'), SUN_PATH)
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('PASS: unix listen', result.stdout)
if __name__ == '__main__':
unittest.main()