fix(desktop): let desktop apps save read-only game files, and make game libraries writable (#1781)

This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-10-29 15:16:17 -04:00
1 parent 5786e89ff4
commit 22d39998f0
8 files changed
+366 -4

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ 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] /'
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
mkdir -p /usr/local/share/applications
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
[Desktop Entry]
@@ -0,0 +1,93 @@
#!/usr/bin/python3
import os
import re
import stat
import sys
HOME = os.environ.get("HOME", "/root")
STEAM = os.path.join(HOME, ".local/share/Steam")
STORES = os.environ.get("DROIDDECK_STORES_ROOT", "/mnt/droiddeck-stores")
TOOLS = re.compile(r"^(Proton |Proton$|SteamLinuxRuntime|Steamworks Shared$)")
def libraries():
paths = [STEAM]
try:
with open(os.path.join(STEAM, "steamapps/libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
paths += [p.replace("\\\\", "\\") for p in re.findall(r'"path"\s+"([^"]+)"', f.read())]
except OSError:
pass
seen = []
for path in paths:
real = os.path.realpath(path)
if real not in seen:
seen.append(real)
return seen
def roots():
found = []
for library in libraries():
for name in ("common", "compatdata"):
found.append((os.path.join(library, "steamapps", name), name == "common"))
found.append((os.path.join(HOME, "Games"), False))
try:
found += [(entry.path, False) for entry in os.scandir(STORES) if entry.is_dir(follow_symlinks=False)]
except OSError:
pass
return [(path, skip_tools) for path, skip_tools in found if os.path.isdir(path)]
def fix(path, st, wanted):
if st.st_uid != os.geteuid() or st.st_mode & wanted == wanted:
return 0
try:
os.chmod(path, stat.S_IMODE(st.st_mode) | wanted)
return 1
except OSError:
return 0
def walk(top, skip_tools):
fixed = 0
stack = [(top, True)]
while stack:
directory, first = stack.pop()
try:
entries = list(os.scandir(directory))
except OSError:
continue
for entry in entries:
if first and skip_tools and TOOLS.match(entry.name):
continue
try:
st = entry.stat(follow_symlinks=False)
except OSError:
continue
if stat.S_ISDIR(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRWXU)
stack.append((entry.path, False))
elif stat.S_ISREG(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRUSR | stat.S_IWUSR)
return fixed
def main():
try:
os.nice(19)
except OSError:
pass
total = 0
for top, skip_tools in roots():
try:
fixed = fix(top, os.stat(top), stat.S_IRWXU) + walk(top, skip_tools)
except OSError:
continue
if fixed:
print(f"droiddeck-library-perms: {top}: {fixed} made writable")
total += fixed
print(f"droiddeck-library-perms: {total} files and folders made writable")
if __name__ == "__main__":
sys.exit(main())
+21 -2
View File
@@ -139,17 +139,31 @@ static int (*next_faccessat(void))(int, const char *, int, int) {
}
__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode);
__attribute__((visibility("hidden"))) int bl_writable_access(int dirfd, const char *path, int mode, int flags);
static int writable_as_owner(int (*real)(int, const char *, int, int), int dirfd, const char *path, int mode, int flags) {
if (!bl_writable_access(dirfd, path, mode, flags)) return -1;
if ((mode & ~W_OK) == 0 || real(dirfd, path, mode & ~W_OK, flags) == 0) return 0;
return -1;
}
static int check_cwd(const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int) = next_faccessat();
int result;
int err;
if (real == NULL) {
errno = ENOSYS;
return -1;
}
result = real(AT_FDCWD, path, mode, flags);
return result != 0 && errno == EACCES && bl_binfmt_runnable(path, mode) ? 0 : result;
if (result == 0) return 0;
err = errno;
if (err == EACCES && bl_binfmt_runnable(path, mode)) return 0;
errno = err;
if (writable_as_owner(real, AT_FDCWD, path, mode, flags) == 0) return 0;
errno = err;
return result;
}
int access(const char *path, int mode) {
@@ -166,6 +180,7 @@ int eaccess(const char *path, int mode) {
int faccessat(int dirfd, const char *path, int mode, int flags) {
int (*real)(int, const char *, int, int);
int err;
if (dirfd == AT_FDCWD) {
return cached_access(path, mode, flags, check_cwd);
@@ -175,5 +190,9 @@ int faccessat(int dirfd, const char *path, int mode, int flags) {
errno = ENOSYS;
return -1;
}
return real(dirfd, path, mode, flags);
if (real(dirfd, path, mode, flags) == 0) return 0;
err = errno;
if (writable_as_owner(real, dirfd, path, mode, flags) == 0) return 0;
errno = err;
return -1;
}
+42 -1
View File
@@ -3,6 +3,7 @@
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -23,6 +24,34 @@ static int is_steam_client(void) {
return cached;
}
static int wine_name(const char *path) {
const char *base;
size_t n;
if (path == NULL) return 0;
base = strrchr(path, '/');
base = base ? base + 1 : path;
n = strlen(path);
return strncmp(base, "wine", 4) == 0 || strstr(path, "/lib/wine/") != NULL
|| (n > 4 && strcasecmp(path + n - 4, ".exe") == 0);
}
static int is_wine(void) {
static int cached = -1;
char exe[PATH_MAX];
ssize_t n;
if (cached >= 0) return cached;
n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (n > 0) exe[n] = '\0';
cached = (n > 0 && wine_name(exe)) || wine_name(program_invocation_name);
return cached;
}
static int acts_as_root(void) {
return is_steam_client() || !is_wine();
}
static int grant_owner_write(int dirfd, const char *path) {
struct stat st;
@@ -37,7 +66,7 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
char parent[PATH_MAX];
const char *slash;
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !is_steam_client()) return 0;
if (saved != EACCES || path == NULL || (flags & O_ACCMODE) == O_RDONLY || !acts_as_root()) return 0;
if (faccessat(dirfd, path, F_OK, 0) == 0) {
granted = grant_owner_write(dirfd, path);
} else if (flags & O_CREAT) {
@@ -53,3 +82,15 @@ int bl_writable_retry(int dirfd, const char *path, int flags) {
errno = saved;
return granted;
}
__attribute__((visibility("hidden")))
int bl_writable_access(int dirfd, const char *path, int mode, int flags) {
int saved = errno;
struct stat st;
int owned;
if (saved != EACCES || path == NULL || !(mode & W_OK) || !acts_as_root()) return 0;
owned = fstatat(dirfd, path, &st, flags & AT_SYMLINK_NOFOLLOW) == 0 && st.st_uid == geteuid();
errno = saved;
return owned;
}
+1 -1
View File
@@ -60,7 +60,7 @@ class BinfmtPreloadTest(unittest.TestCase):
cls.library = cls.tmp / "libbinfmt.so"
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DBINFMT_TEST",
'-DBINFMT_HANDLER="%s"' % cls.handler, "-o", str(cls.library),
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "webhelper.c")] + ["-ldl"],
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")] + ["-ldl"],
check=True)
source = cls.tmp / "program.c"
source.write_text(PROGRAM)
+98
View File
@@ -0,0 +1,98 @@
import os
from pathlib import Path
import stat
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-library-perms"
class LibraryPermsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.restore)
self.root = Path(self.temp.name)
self.home = self.root / "home"
self.steam = self.home / ".local/share/Steam"
self.card = self.root / "card"
self.stores = self.root / "stores"
(self.steam / "steamapps").mkdir(parents=True)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n\t"1"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n'
% (self.steam, self.card))
self.locked = []
def restore(self):
for path in self.locked:
if path.exists() and not path.is_symlink():
path.chmod(0o700 if path.is_dir() else 0o600)
for path in sorted(self.root.rglob("*"), key=lambda p: len(p.parts), reverse=True):
if path.is_dir() and not path.is_symlink():
path.chmod(0o700)
self.temp.cleanup()
def file(self, path, mode=0o400):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("x")
path.chmod(mode)
self.locked.append(path)
return path
def folder(self, path, mode=0o500):
path.mkdir(parents=True, exist_ok=True)
self.locked.append(path)
return path
def run_script(self):
env = dict(os.environ, HOME=str(self.home), DROIDDECK_STORES_ROOT=str(self.stores))
for path in reversed(self.locked):
if path.is_dir():
path.chmod(0o500)
return subprocess.run([sys.executable, str(SCRIPT)], env=env, check=True, capture_output=True, text=True).stdout
def mode(self, path):
return stat.S_IMODE(os.lstat(path).st_mode)
def test_read_only_game_files_and_folders_become_writable_in_every_library(self):
ini = self.file(self.steam / "steamapps/compatdata/3712566526/pfx/drive_c/users/steamuser/Documents/My Games/FalloutNV/FALLOUT.INI")
data = self.folder(self.steam / "steamapps/common/Game/Data")
game = self.file(data / "game.esm", 0o444)
card = self.file(self.card / "steamapps/common/Other/settings.ini")
gog = self.file(self.home / "Games/Stores/GOG/Fallout New Vegas/Fallout_default.ini")
store = self.file(self.stores / "abc/Game/config.cfg")
out = self.run_script()
self.assertEqual(self.mode(ini) & 0o600, 0o600)
self.assertEqual(self.mode(game), 0o644)
self.assertEqual(self.mode(data) & 0o700, 0o700)
for path in (card, gog, store):
self.assertEqual(self.mode(path) & 0o600, 0o600, path)
self.assertIn("made writable", out)
def test_proton_and_steam_runtimes_are_left_as_valve_ships_them(self):
proton = self.file(self.steam / "steamapps/common/Proton Experimental (ARM64)/files/lib/wine/a.so", 0o444)
runtime = self.file(self.card / "steamapps/common/SteamLinuxRuntime_sniper/run", 0o555)
nested = self.file(self.steam / "steamapps/common/Game/Proton notes.txt")
self.run_script()
self.assertEqual(self.mode(proton), 0o444)
self.assertEqual(self.mode(runtime), 0o555)
self.assertEqual(self.mode(nested) & 0o600, 0o600)
def test_symlinks_are_not_followed(self):
outside = self.file(self.root / "outside/keep.ini")
link = self.steam / "steamapps/compatdata/1/pfx/dosdevices/z:"
link.parent.mkdir(parents=True)
link.symlink_to(self.root / "outside")
self.run_script()
self.assertEqual(self.mode(outside), 0o400)
def test_writable_files_are_untouched_and_missing_libraries_are_fine(self):
fine = self.file(self.steam / "steamapps/common/Game/ok.ini", 0o640)
out = self.run_script()
self.assertEqual(self.mode(fine), 0o640)
self.assertIn("0 files and folders made writable", out)
if __name__ == "__main__":
unittest.main()
+109
View File
@@ -0,0 +1,109 @@
import os
from pathlib import Path
import shutil
import stat
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
for (int i = 1; i + 1 < argc; i += 2) {
const char *op = argv[i], *path = argv[i + 1];
int ok;
if (strcmp(op, "access") == 0) ok = access(path, W_OK) == 0;
else if (strcmp(op, "access-rw") == 0) ok = access(path, R_OK | W_OK) == 0;
else if (strcmp(op, "faccessat") == 0) {
int dir = open(".", O_RDONLY | O_DIRECTORY);
ok = faccessat(dir, path, W_OK, 0) == 0;
close(dir);
} else if (strcmp(op, "write") == 0) {
int fd = open(path, O_WRONLY | O_TRUNC);
ok = fd >= 0 && write(fd, "saved", 5) == 5;
if (fd >= 0) close(fd);
} else if (strcmp(op, "create") == 0) {
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
ok = fd >= 0;
if (fd >= 0) close(fd);
} else ok = 0;
printf("%s %d\n", op, ok);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc") and os.geteuid() != 0, "needs a C compiler and a non-root user")
class WritablePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
(build / "program.c").write_text(PROGRAM)
cls.preload = build / "libblsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
cls.editor = build / "kate"
subprocess.run(["cc", "-O2", "-o", str(cls.editor), str(build / "program.c")], check=True)
cls.wine = build / "wine64-preloader"
shutil.copy(cls.editor, cls.wine)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def setUp(self):
self.work = Path(tempfile.mkdtemp(dir=self.dir))
self.addCleanup(self.unlock)
self.ini = self.work / "My Games/FalloutNV/FALLOUT.INI"
self.ini.parent.mkdir(parents=True)
self.ini.write_text("bUseThreadedAI=0\n")
self.ini.chmod(0o400)
self.locked = self.work / "Locked"
self.locked.mkdir()
self.locked.chmod(0o500)
def unlock(self):
for path in (self.ini, self.locked):
path.chmod(0o700)
def run_as(self, program, *args, preload=True):
env = dict(os.environ)
env.pop("LD_PRELOAD", None)
if preload:
env["LD_PRELOAD"] = str(self.preload)
out = subprocess.run([str(program), *map(str, args)], env=env, cwd=self.ini.parent,
capture_output=True, text=True, check=True, timeout=60).stdout
return dict(line.split() for line in out.splitlines())
def test_without_the_preload_a_read_only_file_cannot_be_saved(self):
out = self.run_as(self.editor, "access", self.ini, "write", self.ini, preload=False)
self.assertEqual(out, {"access": "0", "write": "0"})
def test_a_desktop_app_can_save_a_read_only_file_like_root(self):
out = self.run_as(self.editor, "access", self.ini, "access-rw", self.ini, "faccessat", self.ini.name,
"write", self.ini, "create", self.locked / "new.tmp")
self.assertEqual(out, {"access": "1", "access-rw": "1", "faccessat": "1", "write": "1", "create": "1"})
self.assertEqual(self.ini.read_text(), "saved")
def test_checking_access_alone_leaves_the_mode_alone(self):
self.run_as(self.editor, "access", self.ini)
self.assertEqual(stat.S_IMODE(self.ini.stat().st_mode), 0o400)
def test_wine_keeps_windows_read_only_files_read_only(self):
out = self.run_as(self.wine, "access", self.ini, "write", self.ini, "create", self.locked / "new.tmp")
self.assertEqual(out, {"access": "0", "write": "0", "create": "0"})
self.assertEqual(self.ini.read_text(), "bUseThreadedAI=0\n")
if __name__ == "__main__":
unittest.main()