Compare commits

...
Author SHA1 Message Date
MaxsTechReview 46f99b9e08 fix(nativeguest): Downloads and Documents are writable in the desktop file manager (#3274)
fix(nativeguest): shared storage files are root's like the SD card's

Android's internal shared storage reports its files as owned by the media
provider with the media_rw group, so desktop file managers saw Downloads and
Documents as someone else's and showed them read-only, with rename, delete and
new folder unavailable. Files in the media_rw group are now presented as
owned by root, as the SD card already is; the group is kept.
2026-11-26 10:30:32 -05:00
MaxsTechReview dcb1a3001b fix(desktop): Downloads, Documents and game folder links work again without proot (#3273)
Links made in a proot session store the guest path as their target, which the
kernel cannot follow in the middle of a path once the session runs without
proot: the folders listed, but nothing inside them could be opened or created.
The desktop setup now makes a link again when it cannot be walked into, so it
is stored in the form the current mode follows.
2026-11-26 10:30:28 -05:00
MaxsTechReview dbfcd764f3 perf(nativeguest): keep relative parent walks relative inside mounts without links (#3249)
* perf(nativeguest): keep relative parent walks relative inside mounts without links

A relative path with .. made the hook rebuild the full absolute host
path, so every component was looked up again from the root of the card.
Inside a mount that cannot hold symlinks, a path that never climbs
above the mount resolves the same way relative to the working
directory, so the kernel now gets it unchanged.

* Keep the absolute walk when another guest bind sits inside the mount

* Check every guest path of the card's folder for nested binds

* Keep the absolute walk inside the rootfs and under identity binds

* Keep the absolute walk when two binds share a guest path
2026-11-26 09:48:56 -05:00
8 changed files with 301 additions and 3 deletions

No files matched your search

@@ -115,7 +115,7 @@ def link_libraries():
common = os.path.join(library, "steamapps", "common")
link = os.path.join(HOME, label)
if os.path.isdir(common):
if os.path.islink(link) and os.readlink(link) == common:
if os.path.islink(link) and os.readlink(link) == common and os.path.isdir(os.path.join(link, ".")):
continue
if os.path.islink(link) or os.path.isfile(link):
os.unlink(link)
@@ -10,7 +10,7 @@ free_name() {
share() {
local android=$HOME/Storage/$1 link=$HOME/$2 f
[ -d "$android" ] && [ -w "$android" ] || return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && [ -d "$link/." ] && return 0
if [ -L "$link" ]; then
rm -f "$link"
elif [ -d "$link" ]; then
+3
View File
@@ -445,12 +445,15 @@ static void load_app_ids(void) {
__atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED);
}
#define ANDROID_MEDIA_RW_GID ((gid_t)1023)
static void present_owner_as_root(uid_t *uid, gid_t *gid) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
if (app_uid == (uid_t)-1) return;
if (uid && *uid == app_uid) *uid = 0;
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = 0;
if (gid && *gid == app_gid) *gid = 0;
}
+22
View File
@@ -1081,6 +1081,27 @@ static void ddnatv_build_at_dirs(void) {
}
#if defined(__aarch64__)
static int stays_in_plain_bind(const char *host, const char *rel) {
if (get_rootfs_subpath(host)) return 0;
struct ddnatv_bind *best = NULL;
for (int i = 0; i < g_nbinds; i++) {
struct ddnatv_bind *b = &g_binds[i];
if (b->identity || !is_path_prefix(host, b->src, b->src_len)) continue;
if (!best || b->src_len > best->src_len) best = b;
}
if (!best) return 0;
for (int i = 0; i < g_nbinds; i++) {
struct ddnatv_bind *cover = &g_binds[i];
if (cover->identity || !is_path_prefix(host, cover->src, cover->src_len)) continue;
for (int j = 0; j < g_nbinds; j++) {
struct ddnatv_bind *b = &g_binds[j];
if (j != i && b->dst_len >= cover->dst_len && is_path_prefix(b->dst, cover->dst, cover->dst_len))
return 0;
}
}
return !climbs_past_root(host + best->src_len, rel) && bind_holds_no_links(best);
}
static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) {
char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX];
if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd");
@@ -1088,6 +1109,7 @@ static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t
long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1);
if (n <= 0 || host[0] != '/') return NULL;
host[n] = '\0';
if (stays_in_plain_bind(host, rel)) return NULL;
const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf));
if (!dir || strcmp(dir, host) == 0) return NULL;
if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL;
+59
View File
@@ -0,0 +1,59 @@
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-downloads"
class DesktopDownloadsTest(unittest.TestCase):
def run_script(self, home, shim=None):
env = dict(os.environ, HOME=str(home))
if shim:
env["PATH"] = f"{shim}:{env['PATH']}"
subprocess.run(["bash", str(SCRIPT)], env=env, check=True)
def make_home(self, temp):
home = Path(temp) / "home"
for name in ("Download", "Documents"):
(home / "Storage" / name).mkdir(parents=True)
return home
def test_links_to_the_android_folders_are_made(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
self.run_script(home)
self.assertEqual(str(home / "Storage/Download"), os.readlink(home / "Downloads"))
self.assertEqual(str(home / "Storage/Documents"), os.readlink(home / "Documents"))
def test_working_links_are_kept(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
self.run_script(home)
before = os.lstat(home / "Downloads").st_ino
self.run_script(home)
self.assertEqual(before, os.lstat(home / "Downloads").st_ino)
def test_links_that_name_the_folder_but_cannot_be_walked_are_made_again(self):
with tempfile.TemporaryDirectory() as temp:
home = self.make_home(temp)
for link in ("Downloads", "Documents"):
os.symlink(str(Path(temp) / "gone"), home / link)
shim = Path(temp) / "bin"
shim.mkdir()
(shim / "readlink").write_text(
'#!/bin/bash\ncase "${@: -1}" in\n'
f' "{home}/Downloads") echo "{home}/Storage/Download" ;;\n'
f' "{home}/Documents") echo "{home}/Storage/Documents" ;;\n'
' *) exec /usr/bin/readlink "$@" ;;\nesac\n')
(shim / "readlink").chmod(0o755)
self.run_script(home, shim)
for link, folder in (("Downloads", "Download"), ("Documents", "Documents")):
self.assertEqual(str(home / "Storage" / folder), os.readlink(home / link))
self.assertTrue((home / link / ".").is_dir())
self.assertEqual([], sorted(p.name for p in home.iterdir() if ".old." in p.name))
if __name__ == "__main__":
unittest.main()
+62 -1
View File
@@ -195,7 +195,7 @@ class NativeHookMountTest(unittest.TestCase):
if syscalls and not shutil.which("strace"):
self.skipTest("no strace")
if syscalls:
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat"]
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat,newfstatat,fstatat64,statx"]
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
@@ -482,6 +482,67 @@ class NativeHookMountTest(unittest.TestCase):
self.assertNotEqual(self.readlinks_of(log, f"{self.links}/guest"), [], table)
self.assertNotEqual(self.readlinks_of(log, f"{self.root}/etc/hostname"), [], table)
def test_relative_parent_walks_inside_mounts_without_links_stay_relative(self):
real, _, _ = self.links_volume()
binds = f"{self.links}:/mnt/links"
paths = {"sub/deeper/../file.txt": ["1", "deep"], "sub/deeper/more/../more/leaf.txt": ["1", "leaf"],
"../real/sub/file.txt": ["1", "deep"], "../../../etc/hostname": ["1", "rootfs"],
"sub/../../../../etc/hostname": ["1", "rootfs"]}
for kind, relative in (("exfat", True), ("ext4", False)):
table = [("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")]
result, log = self.run_probe("cd:/mnt/links/real", *paths, binds=binds, mounts=table, syscalls=True)
for path, want in paths.items():
self.assertEqual(result[path], want, (path, kind))
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
for path in ("sub/deeper/../file.txt", "sub/deeper/more/../more/leaf.txt", "../real/sub/file.txt"):
self.assertEqual(path in stats, relative, (path, kind, stats))
for path in ("../../../etc/hostname", "sub/../../../../etc/hostname"):
self.assertNotIn(path, stats, (path, kind))
nested = f"{binds}|{self.library}:/mnt/links/real/sub"
table = [("/", "ext4", "/dev/root"), (real, "exfat", "/dev/sdb1")]
result, log = self.run_probe("cd:/mnt/links/real", "sub/deeper/../game.txt", binds=nested, mounts=table,
syscalls=True)
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
self.assertNotIn("sub/deeper/../game.txt", stats)
walk = "sub/Some Game/../Some Game/game.txt"
for order in ((f"{self.links}:/mnt/links", f"{self.links}:/mnt/longer/alias"),
(f"{self.links}:/mnt/longer/alias", f"{self.links}:/mnt/links")):
shared = "|".join(order) + f"|{self.library}:/mnt/links/real/sub"
results = [self.run_probe("cd:/mnt/links/real", walk, binds=shared,
mounts=[("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")])[walk]
for kind in ("ext4", "exfat")]
self.assertEqual(results[0], results[1], order)
def test_relative_parent_walks_honour_identity_binds_shared_guest_paths_and_the_rootfs(self):
real, _, _ = self.links_volume()
tmp = os.path.realpath(self.tmp.name)
card = f"{tmp}/identity-card"
os.makedirs(f"{card}/real/sub/deeper", exist_ok=True)
Path(f"{card}/real/sub/file.txt").write_text("identity")
binds = f"{self.links}:{card}|{card}/real/sub:{card}/real/sub"
walk = "sub/deeper/../file.txt"
results = [self.run_probe(f"cd:{card}/real", walk, binds=binds,
mounts=[("/", "ext4", "/dev/root"), (real, kind, "/dev/sdb1")])[walk]
for kind in ("ext4", "exfat")]
self.assertEqual(results[0], results[1])
twins = (f"{tmp}/twin-a", f"{tmp}/twin-b")
for twin in twins:
os.makedirs(f"{twin}/only/sub/deeper", exist_ok=True)
Path(f"{twin}/only/sub/file.txt").write_text(os.path.basename(twin))
for order in (twins, twins[::-1]):
shared = "|".join(f"{src}:/mnt/twin" for src in order)
result, log = self.run_probe("cd:/mnt/twin/only", walk, binds=shared, syscalls=True,
mounts=[("/", "ext4", "/dev/root")] +
[(twin, "exfat", f"/dev/sd{i}1") for i, twin in zip("bc", twins)])
stats = [m.group(1) for m in re.finditer(r'(?:fstatat|statx)\([^,"]*,\s*"([^"]*)"', log)]
self.assertEqual(result[walk], ["1", os.path.basename(order[0])], order)
self.assertNotIn(walk, stats, order)
climb = "../../etc/hostname"
for kind in ("ext4", "exfat"):
result = self.run_probe("cd:/etc", climb, binds=f"{tmp}:/mnt/card",
mounts=[("/", "ext4", "/dev/root"), (tmp, kind, "/dev/sdb1")])
self.assertEqual(result[climb], ["1", "rootfs"], kind)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,131 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
OWNERS = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
static void owner(const char *path, unsigned *uid, unsigned *gid) {
if (!path) return;
if (strstr(path, "shared")) { *uid = 4242; *gid = 1023; }
else if (strstr(path, "other")) { *uid = 4242; *gid = 4242; }
}
int stat(const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, "stat");
int ret = next(path, st);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int lstat(const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, "lstat");
int ret = next(path, st);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
int (*next)(int, const char *, struct stat *, int) = dlsym(RTLD_NEXT, "fstatat");
int ret = next(dirfd, path, st, flags);
if (ret == 0) owner(path, &st->st_uid, &st->st_gid);
return ret;
}
int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *sx) {
int (*next)(int, const char *, int, unsigned, struct statx *) = dlsym(RTLD_NEXT, "statx");
int ret = next(dirfd, path, flags, mask, sx);
if (ret == 0) owner(path, &sx->stx_uid, &sx->stx_gid);
return ret;
}
"""
PROBE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
struct stat st;
struct statx sx;
for (int i = 1; i < argc; i++) {
if (stat(argv[i], &st) != 0) return 2;
printf("%s\tstat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (lstat(argv[i], &st) != 0) return 3;
printf("%s\tlstat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (fstatat(AT_FDCWD, argv[i], &st, 0) != 0) return 4;
printf("%s\tfstatat\t%u\t%u\n", argv[i], st.st_uid, st.st_gid);
if (statx(AT_FDCWD, argv[i], 0, STATX_BASIC_STATS, &sx) != 0) return 5;
printf("%s\tstatx\t%u\t%u\n", argv[i], sx.stx_uid, sx.stx_gid);
}
return 0;
}
"""
class NativeHookStorageOwnerTest(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(dir="/tmp")
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 / "owners.c").write_text(OWNERS)
cls.owners = tmp / "owners.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.owners), str(tmp / "owners.c"), "-ldl"], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
for name in ("shared", "other", "own"):
(cls.root / name).write_text("")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def owners_of(self, *paths):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook} {self.owners}"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *paths], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
result = {}
for line in out.stdout.splitlines():
path, call, uid, gid = line.split("\t")
result.setdefault(path, {})[call] = (int(uid), int(gid))
return result
def test_shared_storage_files_are_owned_by_root_and_keep_their_group(self):
for call, ids in self.owners_of("/shared")["/shared"].items():
self.assertEqual((0, 1023), ids, call)
def test_other_owners_and_the_apps_own_files_are_unchanged(self):
result = self.owners_of("/other", "/own")
for call, ids in result["/other"].items():
self.assertEqual((4242, 4242), ids, call)
for call, ids in result["/own"].items():
self.assertEqual((0, 0), ids, call)
if __name__ == "__main__":
unittest.main()
+22
View File
@@ -150,6 +150,28 @@ class CompatLibrariesTest(unittest.TestCase):
class DesktopGamesTest(unittest.TestCase):
def test_library_links_that_cannot_be_walked_are_made_again(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
steam, home = root / "Steam", root / "home"
(steam / "steamapps/common/Game").mkdir(parents=True)
home.mkdir()
common = str(steam / "steamapps/common")
stale, kept = home / "Steam Games", home / "SD Games"
os.symlink(str(root / "elsewhere"), stale)
card = root / "card/steamapps/common"
card.mkdir(parents=True)
os.symlink(str(card), kept)
before = os.lstat(kept).st_ino
real = os.readlink
with patch.object(desktop, "HOME", str(home)), \
patch.object(desktop, "LIBRARIES", ((str(steam), "Steam Games"), (str(root / "card"), "SD Games"))), \
patch.object(desktop.os, "readlink", lambda p: common if p == str(stale) else real(p)):
desktop.link_libraries()
self.assertEqual(common, os.readlink(stale))
self.assertTrue((stale / "Game").is_dir())
self.assertEqual(before, os.lstat(kept).st_ino)
def test_games_in_registered_libraries_get_entries(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)