mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-04 20:15:44 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ed7afd672 | ||
|
|
d38fd373f0 | ||
|
|
a6fe10d8ff | ||
|
|
953549704a | ||
|
|
19d8819137 | ||
|
|
1b80b506cb | ||
|
|
4b289a4802 | ||
|
|
238ef76c5c | ||
|
|
906e66e3cf | ||
|
|
c0d14f9632 | ||
|
|
70bda85dd5 |
No files matched your search
@@ -58,6 +58,59 @@
|
||||
|
||||
#define EXPORT extern "C" __attribute__((visibility("default")))
|
||||
|
||||
struct SymbolSlot {
|
||||
std::atomic<void *> fn{nullptr};
|
||||
std::atomic<bool> resolved{false};
|
||||
};
|
||||
|
||||
template <typename Fn> static Fn resolved_symbol(SymbolSlot &slot, void *handle, const char *name) {
|
||||
if (!slot.resolved.load(std::memory_order_acquire)) {
|
||||
slot.fn.store(dlsym(handle, name), std::memory_order_relaxed);
|
||||
slot.resolved.store(true, std::memory_order_release);
|
||||
}
|
||||
return reinterpret_cast<Fn>(slot.fn.load(std::memory_order_relaxed));
|
||||
}
|
||||
|
||||
enum class Next : size_t {
|
||||
open,
|
||||
openat,
|
||||
close,
|
||||
write,
|
||||
ioctl,
|
||||
poll,
|
||||
ppoll,
|
||||
select,
|
||||
stat,
|
||||
stat64,
|
||||
fstat,
|
||||
fstat64,
|
||||
xstat,
|
||||
xstat64,
|
||||
fxstat,
|
||||
fxstat64,
|
||||
statx,
|
||||
statfs,
|
||||
fstatfs,
|
||||
access,
|
||||
faccessat,
|
||||
opendir,
|
||||
scandir,
|
||||
inotify_add_watch,
|
||||
count
|
||||
};
|
||||
|
||||
static const char *const next_names[] = {"open", "openat", "close", "write", "ioctl", "poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64", "__fxstat", "__fxstat64", "statx", "statfs", "fstatfs", "access", "faccessat", "opendir", "scandir", "inotify_add_watch"};
|
||||
static_assert(sizeof(next_names) / sizeof(next_names[0]) == static_cast<size_t>(Next::count), "next_names");
|
||||
static SymbolSlot next_slots[static_cast<size_t>(Next::count)];
|
||||
|
||||
template <typename Fn> static Fn next_symbol(Next which) {
|
||||
return resolved_symbol<Fn>(next_slots[static_cast<size_t>(which)], RTLD_NEXT, next_names[static_cast<size_t>(which)]);
|
||||
}
|
||||
|
||||
static void resolve_next_symbols() {
|
||||
for (size_t i = 0; i < static_cast<size_t>(Next::count); i++) next_symbol<void *>(static_cast<Next>(i));
|
||||
}
|
||||
|
||||
#ifdef __GLIBC__
|
||||
typedef unsigned long ioctl_request_t;
|
||||
#else
|
||||
@@ -442,6 +495,7 @@ void log(const char *message, ...) {
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void library_init() {
|
||||
resolve_next_symbols();
|
||||
config();
|
||||
controller_mutex();
|
||||
controller_map();
|
||||
@@ -733,7 +787,7 @@ open_fake_input_ring(const char *event, int flags) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
|
||||
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
|
||||
if (fd < 0)
|
||||
@@ -1000,7 +1054,7 @@ __attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
|
||||
std::string path = uinput_ring_path(node);
|
||||
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
|
||||
@@ -1027,7 +1081,7 @@ __attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out)
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
int fd = -1;
|
||||
int node = claim_uinput_node(&fd);
|
||||
if (node < 0) return -1;
|
||||
@@ -1440,7 +1494,7 @@ __attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() {
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
|
||||
tries.fetch_add(1, std::memory_order_relaxed);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
std::string path = get_ring_path_for_slot(0);
|
||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return nullptr;
|
||||
@@ -1793,7 +1847,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
|
||||
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
||||
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
if (!process_reads_pads()) {
|
||||
Logger::log("deck: %s refused: not the Steam client\n", path);
|
||||
errno = ENOENT;
|
||||
@@ -2002,7 +2056,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
if (!process_reads_pads()) {
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
@@ -2121,7 +2175,7 @@ __attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||
std::call_once(once, [] {
|
||||
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
||||
if (!path || !*path || !fake_deck_enabled()) return;
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
||||
@@ -2338,7 +2392,8 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
|
||||
const char *subsystem, const char *devname,
|
||||
unsigned major, unsigned minor) {
|
||||
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
||||
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject"));
|
||||
static SymbolSlot inject_slot;
|
||||
const auto inject = resolved_symbol<inject_fn>(inject_slot, RTLD_DEFAULT, "dd_udevmon_inject");
|
||||
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
|
||||
}
|
||||
|
||||
@@ -2496,7 +2551,7 @@ __attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *ho
|
||||
}
|
||||
|
||||
EXPORT int fstatfs(int fd, struct statfs *buf) {
|
||||
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
|
||||
const auto real = next_symbol<int (*)(int, struct statfs *)>(Next::fstatfs);
|
||||
int result = real(fd, buf);
|
||||
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
|
||||
note_deck_sysfs("fstatfs", result);
|
||||
@@ -2506,7 +2561,7 @@ EXPORT int fstatfs(int fd, struct statfs *buf) {
|
||||
}
|
||||
|
||||
EXPORT int statfs(const char *path, struct statfs *buf) {
|
||||
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
|
||||
const auto real = next_symbol<int (*)(const char *, struct statfs *)>(Next::statfs);
|
||||
int result = real(path, buf);
|
||||
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
|
||||
note_deck_sysfs(path, result);
|
||||
@@ -2555,7 +2610,7 @@ __attribute__((visibility("hidden"))) static int deck_imu_mode_change(const uint
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
|
||||
std::string path = get_ring_path_for_slot(0);
|
||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
||||
@@ -3064,7 +3119,7 @@ static int real_fstat(int fd, struct stat *buf);
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
||||
int dirfd, const char *path, int flags, struct statx *buf) {
|
||||
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
|
||||
const auto real_openat = next_symbol<decltype(&::openat)>(Next::openat);
|
||||
int target;
|
||||
if (!path || !*path) {
|
||||
if (!(flags & AT_EMPTY_PATH)) return false;
|
||||
@@ -3102,7 +3157,7 @@ __attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
||||
}
|
||||
|
||||
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
|
||||
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
|
||||
const auto real = next_symbol<decltype(&::statx)>(Next::statx);
|
||||
int result = real(dirfd, path, flags, mask, buf);
|
||||
int saved_errno = errno;
|
||||
constexpr unsigned unique_mount_id = 0x4000;
|
||||
@@ -3123,7 +3178,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
|
||||
#endif
|
||||
|
||||
EXPORT DIR *opendir(const char *name) {
|
||||
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
|
||||
const auto real = next_symbol<DIR *(*)(const char *)>(Next::opendir);
|
||||
DIR *dir = real(name);
|
||||
if (!dir) {
|
||||
note_sys_failure(AT_FDCWD, name);
|
||||
@@ -3153,7 +3208,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
|
||||
|
||||
va_end(va);
|
||||
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||
@@ -3231,7 +3286,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
|
||||
|
||||
va_end(va);
|
||||
|
||||
static auto my_openat = reinterpret_cast<int (*)(int, const char *, int, ...)>(dlsym(RTLD_NEXT, "openat"));
|
||||
const auto my_openat = next_symbol<int (*)(int, const char *, int, ...)>(Next::openat);
|
||||
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||
@@ -3390,10 +3445,10 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
|
||||
}
|
||||
|
||||
static int real_stat(const char *pathname, struct stat *statbuf) {
|
||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat *)>(dlsym(RTLD_NEXT, "stat"));
|
||||
const auto fn = next_symbol<int (*)(const char *, struct stat *)>(Next::stat);
|
||||
if (fn) return fn(pathname, statbuf);
|
||||
#ifdef _STAT_VER
|
||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
||||
const auto xfn = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -3401,10 +3456,10 @@ static int real_stat(const char *pathname, struct stat *statbuf) {
|
||||
}
|
||||
|
||||
static int real_fstat(int fd, struct stat *buf) {
|
||||
static auto fn = reinterpret_cast<int (*)(int, struct stat *)>(dlsym(RTLD_NEXT, "fstat"));
|
||||
const auto fn = next_symbol<int (*)(int, struct stat *)>(Next::fstat);
|
||||
if (fn) return fn(fd, buf);
|
||||
#ifdef _STAT_VER
|
||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
||||
const auto xfn = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -3420,7 +3475,7 @@ EXPORT int fstat(int fd, struct stat *buf) {
|
||||
}
|
||||
|
||||
EXPORT int access(const char *pathname, int mode) {
|
||||
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
||||
const auto my_access = next_symbol<decltype(&::access)>(Next::access);
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||
@@ -3461,7 +3516,7 @@ EXPORT int access(const char *pathname, int mode) {
|
||||
}
|
||||
|
||||
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
||||
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
||||
const auto my_faccessat = next_symbol<decltype(&::faccessat)>(Next::faccessat);
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||
@@ -3505,7 +3560,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
||||
int (*filter)(const struct dirent *),
|
||||
int (*compar)(const struct dirent **,
|
||||
const struct dirent **)) {
|
||||
static auto my_scandir = reinterpret_cast<decltype(&::scandir)>(dlsym(RTLD_NEXT, "scandir"));
|
||||
const auto my_scandir = next_symbol<decltype(&::scandir)>(Next::scandir);
|
||||
|
||||
if (dirp) {
|
||||
if (!strcmp(dirp, "/dev/input")) {
|
||||
@@ -3519,7 +3574,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
||||
}
|
||||
|
||||
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
||||
static auto my_inotify_add_watch = reinterpret_cast<decltype(&::inotify_add_watch)>(dlsym(RTLD_NEXT, "inotify_add_watch"));
|
||||
const auto my_inotify_add_watch = next_symbol<decltype(&::inotify_add_watch)>(Next::inotify_add_watch);
|
||||
|
||||
char *fake_path = nullptr;
|
||||
if (pathname) {
|
||||
@@ -3658,7 +3713,7 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
|
||||
|
||||
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
||||
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
||||
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
|
||||
const auto next = next_symbol<ioctl_fn>(Next::ioctl);
|
||||
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
||||
}
|
||||
|
||||
@@ -3897,7 +3952,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
}
|
||||
|
||||
EXPORT int close(int fd) {
|
||||
static auto my_close = reinterpret_cast<decltype(&::close)>(dlsym(RTLD_NEXT, "close"));
|
||||
const auto my_close = next_symbol<decltype(&::close)>(Next::close);
|
||||
|
||||
if (!watched(fd)) return my_close(fd);
|
||||
close_uinput(fd);
|
||||
@@ -4085,7 +4140,7 @@ EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
|
||||
}
|
||||
|
||||
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
||||
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
|
||||
const auto my_write = next_symbol<decltype(&::write)>(Next::write);
|
||||
|
||||
if (!watched(fd)) return my_write(fd, buf, count);
|
||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||
@@ -4160,8 +4215,8 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
|
||||
|
||||
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||
const sigset_t *sigmask) {
|
||||
static auto my_poll = reinterpret_cast<decltype(&::poll)>(dlsym(RTLD_NEXT, "poll"));
|
||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
||||
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
|
||||
nfds_t first = 0;
|
||||
while (first < nfds && !watched(fds[first].fd)) first++;
|
||||
@@ -4265,7 +4320,7 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
|
||||
|
||||
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
const struct timespec *timeout, const sigset_t *sigmask) {
|
||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
@@ -4292,7 +4347,7 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
|
||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
fd_set *exceptfds, struct timeval *timeout) {
|
||||
static auto my_select = reinterpret_cast<decltype(&::select)>(dlsym(RTLD_NEXT, "select"));
|
||||
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||
|
||||
fd_set original_readfds;
|
||||
fd_set original_writefds;
|
||||
@@ -4454,10 +4509,10 @@ EXPORT int openat64(int dirfd, const char *pathname, int flags, ...) {
|
||||
}
|
||||
|
||||
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "stat64"));
|
||||
const auto fn = next_symbol<int (*)(const char *, struct stat64 *)>(Next::stat64);
|
||||
if (fn) return fn(pathname, statbuf);
|
||||
#ifdef _STAT_VER
|
||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
||||
const auto xfn = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -4465,10 +4520,10 @@ static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
||||
}
|
||||
|
||||
static int real_fstat64(int fd, struct stat64 *buf) {
|
||||
static auto fn = reinterpret_cast<int (*)(int, struct stat64 *)>(dlsym(RTLD_NEXT, "fstat64"));
|
||||
const auto fn = next_symbol<int (*)(int, struct stat64 *)>(Next::fstat64);
|
||||
if (fn) return fn(fd, buf);
|
||||
#ifdef _STAT_VER
|
||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
||||
const auto xfn = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -4484,27 +4539,27 @@ EXPORT int fstat64(int fd, struct stat64 *buf) {
|
||||
}
|
||||
|
||||
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
|
||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
||||
const auto real = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||
if (!real) return stat(pathname, statbuf);
|
||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat *buf) { return real(version, path, buf); });
|
||||
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat *buf) { return real(version, path, buf); });
|
||||
}
|
||||
|
||||
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
|
||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
||||
const auto real = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||
if (!real) return stat64(pathname, statbuf);
|
||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
||||
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
||||
}
|
||||
|
||||
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
|
||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
||||
const auto real = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||
if (!real) return fstat(fd, buf);
|
||||
return fake_stat_fd(fd, buf, [version](int f, struct stat *b) { return real(version, f, b); });
|
||||
return fake_stat_fd(fd, buf, [version, real](int f, struct stat *b) { return real(version, f, b); });
|
||||
}
|
||||
|
||||
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
|
||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
||||
const auto real = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||
if (!real) return fstat64(fd, buf);
|
||||
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
|
||||
return fake_stat_fd(fd, buf, [version, real](int f, struct stat64 *b) { return real(version, f, b); });
|
||||
}
|
||||
|
||||
#if defined(__x86_64__) || defined(__i386__)
|
||||
@@ -4518,18 +4573,37 @@ static const char *const interposed_names[] = {
|
||||
};
|
||||
|
||||
static dlsym_fn next_dlsym() {
|
||||
static const dlsym_fn fn = [] {
|
||||
static std::atomic<dlsym_fn> fn{nullptr};
|
||||
static std::atomic<bool> resolved{false};
|
||||
if (!resolved.load(std::memory_order_acquire)) {
|
||||
#ifdef __x86_64__
|
||||
const char *base = "GLIBC_2.2.5";
|
||||
#else
|
||||
const char *base = "GLIBC_2.0";
|
||||
#endif
|
||||
dlsym_fn found{};
|
||||
for (const char *version : {base, "GLIBC_2.34"}) {
|
||||
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
|
||||
if ((found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version)))) break;
|
||||
}
|
||||
return dlsym_fn{};
|
||||
}();
|
||||
return fn;
|
||||
fn.store(found, std::memory_order_relaxed);
|
||||
resolved.store(true, std::memory_order_release);
|
||||
}
|
||||
return fn.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
static void *libc_handle() {
|
||||
static std::atomic<void *> handle{nullptr};
|
||||
static std::atomic<bool> resolved{false};
|
||||
if (!resolved.load(std::memory_order_acquire)) {
|
||||
handle.store(dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD), std::memory_order_relaxed);
|
||||
resolved.store(true, std::memory_order_release);
|
||||
}
|
||||
return handle.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void resolve_dlsym_targets() {
|
||||
next_dlsym();
|
||||
libc_handle();
|
||||
}
|
||||
|
||||
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
|
||||
@@ -4547,8 +4621,7 @@ extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_tar
|
||||
dlsym_fn next = next_dlsym();
|
||||
if (!next) return reinterpret_cast<void *>(missing_dlsym);
|
||||
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
|
||||
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
|
||||
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
|
||||
if (handle != libc_handle() || !interposed(name)) return reinterpret_cast<void *>(next);
|
||||
return reinterpret_cast<void *>(global_dlsym);
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(true)
|
||||
private var cursorComposite by mutableStateOf(false)
|
||||
private var cursorComposite by mutableStateOf(true)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.audio;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.CappedLogWriter;
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.SessionPart;
|
||||
import com.droiddeck.launcher.core.HostProcess;
|
||||
@@ -16,6 +17,7 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
|
||||
private final File socketPath;
|
||||
private File logFile;
|
||||
private volatile CappedLogWriter log;
|
||||
private final File micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
private final Object micLock = new Object();
|
||||
@@ -77,24 +79,23 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
}
|
||||
ArrayList<String> env = new ArrayList<>();
|
||||
env.add("HOME=" + app().getFilesDir());
|
||||
java.io.PrintWriter out = null;
|
||||
CappedLogWriter out = null;
|
||||
if (logFile != null) {
|
||||
try {
|
||||
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
||||
out.println("== DirectAudio relay helper starting"
|
||||
out = new CappedLogWriter(logFile, true);
|
||||
out.line("== DirectAudio relay helper starting"
|
||||
+ (withMic ? " with the microphone" : " (no microphone)"));
|
||||
out.flush();
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not open " + logFile, e);
|
||||
}
|
||||
}
|
||||
final java.io.PrintWriter log = out;
|
||||
final CappedLogWriter helperLog = out;
|
||||
log = out;
|
||||
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
|
||||
app().getFilesDir(), null,
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
if (helperLog == null || helperLog.line(line)) Log.i(TAG, line);
|
||||
if (withMic) trackMic(line);
|
||||
if (log != null) synchronized (log) { log.println(line); log.flush(); }
|
||||
});
|
||||
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
|
||||
+ (withMic ? " mic=" + micFifoPath : " (no microphone)"));
|
||||
@@ -141,6 +142,9 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
Process.killProcess(pid);
|
||||
pid = -1;
|
||||
}
|
||||
CappedLogWriter current = log;
|
||||
log = null;
|
||||
if (current != null) current.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.core.CappedLogWriter;
|
||||
import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.SessionPart;
|
||||
import com.droiddeck.launcher.core.HostProcess;
|
||||
@@ -32,6 +33,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
private final File workingDir;
|
||||
private final File deviceControls;
|
||||
private File logFile;
|
||||
private CappedLogWriter log;
|
||||
private final String micFifoPath;
|
||||
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
|
||||
|
||||
@@ -191,7 +193,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
+ " --system=false --disable-shm=true --fail=false"
|
||||
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
|
||||
+ " --log-level=info";
|
||||
final java.io.PrintWriter out = openLog();
|
||||
final CappedLogWriter out = openLog();
|
||||
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
|
||||
if (host.exited(generation)) {
|
||||
Log.w(TAG, "audio host exited with status " + status + "; restarting");
|
||||
@@ -199,8 +201,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
}
|
||||
},
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||
if (out == null || out.line(line)) Log.i(TAG, line);
|
||||
}))) return;
|
||||
long token = host.token();
|
||||
Thread guard = new Thread(() -> ensureClientSink(out, token), "pulse-sink-guard");
|
||||
@@ -208,7 +209,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
guard.start();
|
||||
}
|
||||
|
||||
private void ensureClientSink(java.io.PrintWriter out, long token) {
|
||||
private void ensureClientSink(CappedLogWriter out, long token) {
|
||||
try {
|
||||
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
|
||||
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
|
||||
@@ -253,17 +254,17 @@ public class PulseAudioComponent extends SessionPart {
|
||||
Log.w(TAG, line);
|
||||
}
|
||||
Log.i(TAG, line);
|
||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||
if (out != null) out.line(line);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "ensureClientSink failed", t);
|
||||
}
|
||||
}
|
||||
|
||||
/** A timestamped line in the session's audio log. */
|
||||
private void note(java.io.PrintWriter out, String what) {
|
||||
private void note(CappedLogWriter out, String what) {
|
||||
String line = "== " + new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + what;
|
||||
Log.i(TAG, line);
|
||||
if (out != null) synchronized (out) { out.println(line); out.flush(); }
|
||||
if (out != null) out.line(line);
|
||||
}
|
||||
|
||||
private String pactlFor(long token, String... args) {
|
||||
@@ -330,6 +331,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
@Override
|
||||
public void stop() {
|
||||
host.stop();
|
||||
closeLog();
|
||||
}
|
||||
|
||||
public boolean setSinkSuspended(boolean suspended) {
|
||||
@@ -380,19 +382,24 @@ public class PulseAudioComponent extends SessionPart {
|
||||
}
|
||||
}
|
||||
|
||||
private java.io.PrintWriter openLog() {
|
||||
private synchronized CappedLogWriter openLog() {
|
||||
closeLog();
|
||||
if (logFile == null) return null;
|
||||
try {
|
||||
java.io.PrintWriter w = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
|
||||
w.println("== PulseAudio daemon starting" + (micFifoPath != null ? " with a microphone source" : ""));
|
||||
w.flush();
|
||||
return w;
|
||||
log = new CappedLogWriter(logFile, true);
|
||||
log.line("== PulseAudio daemon starting" + (micFifoPath != null ? " with a microphone source" : ""));
|
||||
return log;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not open " + logFile, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void closeLog() {
|
||||
if (log != null) log.close();
|
||||
log = null;
|
||||
}
|
||||
|
||||
private void copyFromLibraryDir() {
|
||||
String[] libs = {"libltdl.so", "libpulseaudio.so", "libpulse.so",
|
||||
"libpulsecommon-13.0.so", "libpulsecore-13.0.so", "libsndfile.so", "libffi.so"};
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import java.io.BufferedWriter
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.OutputStreamWriter
|
||||
|
||||
class CappedLogWriter @JvmOverloads constructor(
|
||||
private val file: File,
|
||||
append: Boolean,
|
||||
private val limitBytes: Long = SESSION_LOG_LIMIT_BYTES,
|
||||
private val tailLines: Int = TAIL_LINES,
|
||||
) : Closeable {
|
||||
private val out = BufferedWriter(OutputStreamWriter(FileOutputStream(file, append), Charsets.UTF_8))
|
||||
private val tail = ArrayDeque<String>()
|
||||
private var dropped = 0L
|
||||
private var closed = false
|
||||
|
||||
@Synchronized
|
||||
fun line(text: String): Boolean {
|
||||
if (closed) return false
|
||||
if (dropped == 0L && file.length() + text.toByteArray(Charsets.UTF_8).size + 1 <= limitBytes) {
|
||||
runCatching { out.write(text); out.newLine(); out.flush() }
|
||||
return true
|
||||
}
|
||||
if (dropped == 0L) {
|
||||
runCatching {
|
||||
out.write("== this log reached its ${limitBytes / (1024 * 1024)} MB limit; later lines are dropped and only the last $tailLines are kept at the end")
|
||||
out.newLine()
|
||||
out.flush()
|
||||
}
|
||||
}
|
||||
dropped++
|
||||
tail.addLast(text)
|
||||
if (tail.size > tailLines) tail.removeFirst()
|
||||
return false
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
runCatching {
|
||||
if (dropped > 0) {
|
||||
out.write("== ${dropped - tail.size} lines dropped after the limit; the last ${tail.size} follow")
|
||||
out.newLine()
|
||||
tail.forEach { out.write(it); out.newLine() }
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
runCatching { out.close() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SESSION_LOG_LIMIT_BYTES = 64L * 1024 * 1024
|
||||
const val TAIL_LINES = 400
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.core
|
||||
import android.content.Context
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import java.io.BufferedWriter
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.file.Files
|
||||
@@ -14,7 +13,7 @@ object SessionLogCapture {
|
||||
private const val TAG = "SessionLogCapture"
|
||||
|
||||
private var pid = -1
|
||||
private var writer: BufferedWriter? = null
|
||||
private var writer: CappedLogWriter? = null
|
||||
private var target: File? = null
|
||||
private var syncer: Thread? = null
|
||||
|
||||
@@ -22,26 +21,20 @@ object SessionLogCapture {
|
||||
fun start(target: File, sinceMillis: Long) {
|
||||
stop()
|
||||
try {
|
||||
val out = target.bufferedWriter()
|
||||
out.write("The app's own log for this session (logcat, this process only).\n")
|
||||
out.write("Lines the app wrote before the session folder existed are in logcat only.\n\n")
|
||||
out.flush()
|
||||
val out = CappedLogWriter(target, false)
|
||||
out.line("The app's own log for this session (logcat, this process only).")
|
||||
out.line("Lines the app wrote before the session folder existed are in logcat only.")
|
||||
out.line("")
|
||||
writer = out
|
||||
this.target = target
|
||||
pid = HostProcess.start(
|
||||
command(Process.myPid(), sinceMillis),
|
||||
null, target.parentFile, null,
|
||||
) { line ->
|
||||
synchronized(this) {
|
||||
try {
|
||||
writer?.apply { write(line); newLine(); flush() }
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
synchronized(this) { writer?.line(line) }
|
||||
}
|
||||
if (pid == -1) {
|
||||
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
|
||||
out.flush()
|
||||
out.line("logcat could not be started; this ROM may not hand an app its own entries.")
|
||||
}
|
||||
target.parentFile?.let { syncer = startSyncing(it) }
|
||||
Log.i(TAG, "app log -> $target (logcat pid $pid)")
|
||||
@@ -81,10 +74,7 @@ object SessionLogCapture {
|
||||
}
|
||||
pid = -1
|
||||
}
|
||||
try {
|
||||
writer?.close()
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
writer?.close()
|
||||
writer = null
|
||||
}
|
||||
|
||||
|
||||
@@ -239,6 +239,7 @@ object AddedGames {
|
||||
for (entry in AddedExes.list(context)) {
|
||||
val folder = File(entry.folder)
|
||||
if (folder.path in removed || !folder.isDirectory) continue
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
|
||||
scanGame(context, folder, out, single = entry, reuse = true)
|
||||
}
|
||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
||||
@@ -337,9 +338,10 @@ object AddedGames {
|
||||
val owner = ownerFolder(app, exe)
|
||||
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
|
||||
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
|
||||
if (guestPath(app, it.exe) != null) {
|
||||
SessionPrefs.setAddedGameExe(app, owner.path, it.exe.path)
|
||||
AddedExes.put(app, AddedExes.Entry(owner.path, it.exe.path))
|
||||
val keep = listOf(it.exe, exe).firstOrNull { f -> guestPath(app, f) != null }
|
||||
if (keep != null) {
|
||||
SessionPrefs.setAddedGameExe(app, owner.path, keep.path)
|
||||
AddedExes.put(app, AddedExes.Entry(owner.path, keep.path))
|
||||
}
|
||||
return AddResult.Existing(it)
|
||||
}
|
||||
|
||||
@@ -207,7 +207,8 @@ object BattleNet {
|
||||
val taken = HashSet<File>()
|
||||
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
||||
for ((code, game) in games) {
|
||||
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
|
||||
val want = saved[code]?.let { runCatching { File(it).canonicalFile }.getOrNull() } ?: continue
|
||||
val keep = options(game.first, game.second).firstOrNull { runCatching { it.canonicalFile }.getOrNull() == want }?.takeIf { it !in taken } ?: continue
|
||||
out[code] = keep
|
||||
taken.add(keep)
|
||||
}
|
||||
@@ -244,6 +245,14 @@ object BattleNet {
|
||||
"/" + rootfs.relativize(resolved).joinToString("/")
|
||||
}
|
||||
}.trimEnd('/')
|
||||
if (mapped?.startsWith("/") == true) {
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
runCatching {
|
||||
val home = rootfs.canonicalFile.toPath()
|
||||
val host = File("$target/$relative").canonicalFile.toPath()
|
||||
if (host.startsWith(home)) File(rootfs, home.relativize(host).toString()) else null
|
||||
}.getOrNull()?.let { return it }
|
||||
}
|
||||
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
|
||||
}
|
||||
|
||||
|
||||
@@ -143,6 +143,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
|
||||
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
||||
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
||||
"usr/local/bin/droiddeck-documents" to "usr/local/bin/droiddeck-documents",
|
||||
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
|
||||
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
|
||||
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
|
||||
|
||||
@@ -1042,7 +1042,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
||||
}
|
||||
|
||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
|
||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
|
||||
|
||||
fun setCursorComposite(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
||||
|
||||
@@ -672,7 +672,7 @@
|
||||
<string name="perf_fastpath_needs_seccomp">Needs proot\'s seccomp filter.</string>
|
||||
<string name="perf_fastpath_hint">Faster file lookups and less stutter. Turn off if a program can\'t find its files.</string>
|
||||
<string name="perf_cursor_composite">Draw the cursor inside gamescope</string>
|
||||
<string name="perf_cursor_composite_hint">Gamescope paints the pointer itself instead of handing it to Android. Turn on for a controller-driven cursor. Off is faster on a phone. Applies next session.</string>
|
||||
<string name="perf_cursor_composite_hint">Gamescope paints the pointer itself instead of handing it to Android. Applies next session.</string>
|
||||
<string name="perf_identity">Session identity</string>
|
||||
<string name="perf_hostname">Host name</string>
|
||||
<string name="perf_hostname_hint">The name Steam sees for this device. Blank restores %1$s.</string>
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class CappedLogWriterTest {
|
||||
@get:Rule val folder = TemporaryFolder()
|
||||
|
||||
@Test fun aLogUnderTheLimitIsWrittenAsIs() {
|
||||
val file = folder.newFile("app.log")
|
||||
CappedLogWriter(file, false, 1024, 3).use { log ->
|
||||
assertTrue(log.line("first"))
|
||||
assertTrue(log.line("second"))
|
||||
}
|
||||
assertEquals(listOf("first", "second"), file.readLines())
|
||||
}
|
||||
|
||||
@Test fun aReconnectStormStopsAtTheLimitAndKeepsTheLastLines() {
|
||||
val file = folder.newFile("audio.log")
|
||||
val limit = 4096L
|
||||
val log = CappedLogWriter(file, true, limit, 3)
|
||||
var written = 0
|
||||
for (n in 0 until 10_000) {
|
||||
if (log.line("I: [linker64] client.c: Created $n \"Native client (UNIX socket client)\"")) written++
|
||||
}
|
||||
val capped = file.length()
|
||||
assertTrue("file grew to $capped bytes", capped <= limit + 200)
|
||||
assertFalse(log.line("after the limit"))
|
||||
log.close()
|
||||
val lines = file.readLines()
|
||||
assertEquals(written, lines.count { it.startsWith("I: [linker64] client.c: Created ") } - 2)
|
||||
assertTrue(lines.any { it.startsWith("== this log reached its") })
|
||||
assertEquals("== ${10_000 + 1 - written - 3} lines dropped after the limit; the last 3 follow", lines[lines.size - 4])
|
||||
assertEquals(
|
||||
listOf(
|
||||
"I: [linker64] client.c: Created 9998 \"Native client (UNIX socket client)\"",
|
||||
"I: [linker64] client.c: Created 9999 \"Native client (UNIX socket client)\"",
|
||||
"after the limit",
|
||||
),
|
||||
lines.takeLast(3),
|
||||
)
|
||||
assertTrue(file.length() < limit + 1024)
|
||||
}
|
||||
|
||||
@Test fun twoWritersOnOneFileShareItsLimit() {
|
||||
val file = folder.newFile("audio.log")
|
||||
val daemon = CappedLogWriter(file, true, 2048, 2)
|
||||
val relay = CappedLogWriter(file, true, 2048, 2)
|
||||
repeat(2_000) { daemon.line("I: [linker64] protocol-native.c: Connection died.") }
|
||||
assertFalse(relay.line("DA-Relay: mic enabled=1"))
|
||||
assertTrue(file.length() <= 2048 + 200)
|
||||
daemon.close()
|
||||
relay.close()
|
||||
assertEquals("DA-Relay: mic enabled=1", file.readLines().last())
|
||||
}
|
||||
|
||||
@Test fun appendKeepsWhatTheFileHeldAndOverwriteStartsFresh() {
|
||||
val file = folder.newFile("audio.log")
|
||||
file.writeText("== PulseAudio daemon starting\n")
|
||||
CappedLogWriter(file, true, 1024, 2).use { it.line("restarted") }
|
||||
assertEquals(listOf("== PulseAudio daemon starting", "restarted"), file.readLines())
|
||||
CappedLogWriter(file, false, 1024, 2).use { it.line("new session") }
|
||||
assertEquals(listOf("new session"), file.readLines())
|
||||
}
|
||||
|
||||
@Test fun linesAfterCloseAreIgnored() {
|
||||
val file = folder.newFile("app.log")
|
||||
val log = CappedLogWriter(file, false, 1024, 2)
|
||||
log.line("kept")
|
||||
log.close()
|
||||
assertFalse(log.line("late"))
|
||||
log.close()
|
||||
assertEquals(listOf("kept"), file.readLines())
|
||||
}
|
||||
}
|
||||
@@ -137,4 +137,30 @@ class AddedGamesStoreScanTest {
|
||||
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
|
||||
assertEquals("/root/Games/Stores/GOG/Witcher Game", game.guestDir)
|
||||
}
|
||||
|
||||
@Test fun aStoreGameThatIsUpdatingIsNotListedThroughItsSavedExe() {
|
||||
val folder = install(Store.GOG, "upd", "Updating GOG", "Binaries/Game.exe", launcher = true)
|
||||
val own = File(folder, "Binaries/Game.exe")
|
||||
assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing)
|
||||
assertTrue(AddedGames.scan(app).any { it.folder.absolutePath == folder.absolutePath })
|
||||
StoreGameSidecar.read(folder)!!.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
|
||||
assertTrue(AddedGames.scan(app).none { it.folder.absolutePath == folder.absolutePath })
|
||||
}
|
||||
|
||||
@Test fun reselectingTheMappedExeReplacesAnUnmappedAliasOfIt() {
|
||||
val folder = install(Store.EPIC, "alias", "Alias Epic", "Binaries/Game.exe", launcher = true)
|
||||
val own = File(folder, "Binaries/Game.exe")
|
||||
val alias = File(java.nio.file.Files.createTempDirectory("alias").toFile(), "bin")
|
||||
try {
|
||||
java.nio.file.Files.createSymbolicLink(alias.toPath(), File(folder, "Binaries").toPath())
|
||||
} catch (e: Exception) {
|
||||
org.junit.Assume.assumeNoException(e)
|
||||
}
|
||||
val aliased = File(alias, "Game.exe")
|
||||
assertNull(AddedGames.guestPath(app, aliased))
|
||||
SessionPrefs.setAddedGameExe(app, folder.path, aliased.path)
|
||||
assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing)
|
||||
assertEquals(own.path, SessionPrefs.addedGameExe(app, folder.path))
|
||||
assertEquals(own.path, AddedExes.list(app).single { it.folder == folder.path }.exe)
|
||||
}
|
||||
}
|
||||
@@ -216,6 +216,41 @@ class BattleNetTest {
|
||||
assertNull(BattleNet.hostFolder(context, "G:\\etc\\passwd"))
|
||||
}
|
||||
|
||||
@Test fun aDriveAtTheAppDataFolderHoldingTheRuntimeListsTheGamesInside() {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val data = context.filesDir.parentFile!!
|
||||
val pfx = File(BattleNet.prefix(context), "pfx")
|
||||
val devices = File(pfx, "dosdevices").apply { mkdirs() }
|
||||
java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), data.absoluteFile.toPath())
|
||||
java.nio.file.Files.createSymbolicLink(File(devices, "e:").toPath(), java.nio.file.Paths.get("/root/Games/Card"))
|
||||
val wow = File(root, "root/Games/Stores/Battle.net/World of Warcraft").apply { mkdirs() }
|
||||
File(wow, "_forever_").mkdirs()
|
||||
val drive = "D:/" + data.absoluteFile.toPath().relativize(wow.absoluteFile.toPath()).joinToString("/")
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
|
||||
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
|
||||
field(1, message(field(1, "wowf"), field(2, "wowf"), field(3, message(field(1, drive))))),
|
||||
))
|
||||
assertEquals(wow, BattleNet.hostFolder(context, drive))
|
||||
assertEquals(wow, BattleNet.games(context).single().folder)
|
||||
assertEquals(File(root, "root/Games/Card/Battle.net/X"), BattleNet.hostFolder(context, "E:\\Battle.net\\X"))
|
||||
assertNull(BattleNet.hostFolder(context, "D:\\..\\etc"))
|
||||
}
|
||||
|
||||
@Test fun aDriveAtAnAliasOfTheAppDataFolderListsTheGameUnderTheRuntimePath() {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val data = context.filesDir.parentFile!!
|
||||
val alias = File(data.parentFile, "alias-" + data.name)
|
||||
java.nio.file.Files.createSymbolicLink(alias.toPath(), data.absoluteFile.toPath())
|
||||
try {
|
||||
val devices = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() }
|
||||
java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), alias.absoluteFile.toPath())
|
||||
val game = File(root, "root/Games/Stores/Battle.net/StarCraft").apply { mkdirs() }
|
||||
val drive = "D:\\" + data.absoluteFile.toPath().relativize(game.absoluteFile.toPath()).joinToString("\\")
|
||||
assertEquals(game.path, BattleNet.hostFolder(context, drive)?.path)
|
||||
} finally {
|
||||
java.nio.file.Files.delete(alias.toPath())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun wowForeverIsListedBesideRetailInTheSharedWorldOfWarcraftFolder() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
@@ -274,6 +309,21 @@ class BattleNetTest {
|
||||
assertEquals(mapOf("WoWF" to root), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to "/elsewhere")))
|
||||
}
|
||||
|
||||
@Test fun aFolderSavedThroughAnAliasOfTheAppDataFolderIsKept() {
|
||||
val data = context.filesDir.parentFile!!
|
||||
val root = File(context.filesDir, "World of Warcraft").apply { mkdirs() }
|
||||
val foreverDir = File(root, "_forever_").apply { mkdirs() }
|
||||
val forever = BattleNet.title("wow_forever")!!
|
||||
val alias = File(data.parentFile, "alias-" + data.name)
|
||||
java.nio.file.Files.createSymbolicLink(alias.toPath(), data.absoluteFile.toPath())
|
||||
try {
|
||||
val saved = File(alias, data.absoluteFile.toPath().relativize(foreverDir.absoluteFile.toPath()).toString()).path
|
||||
assertEquals(mapOf("WoWF" to foreverDir), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to saved)))
|
||||
} finally {
|
||||
java.nio.file.Files.delete(alias.toPath())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theListedFolderIsRememberedAcrossScans() {
|
||||
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
|
||||
val wow = File(pfx, "drive_c/Program Files (x86)/World of Warcraft").apply { mkdirs() }
|
||||
|
||||
@@ -61,9 +61,11 @@ class BwrapSpawnerTest {
|
||||
"DDNATV_ROOT" to rootfs, "DDNATV_BINDS" to "/dev:/dev", "HOME" to "/root",
|
||||
"SPA_PLUGIN_DIR" to "/usr/local/lib/droiddeck-pipewire/lib/spa-0.2",
|
||||
"LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so:$rootfs/usr/local/lib/libddsession.so:$rootfs/usr/lib/libddnatv-hook.so",
|
||||
"DROIDDECK_FDS" to "droiddeck-fds-1",
|
||||
)
|
||||
BwrapSpawner.withoutRootfsSettings(env, rootfs)
|
||||
assertEquals(mapOf("HOME" to "/root", "LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so"), env)
|
||||
assertEquals(mapOf("HOME" to "/root", "LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so",
|
||||
"DROIDDECK_FDS" to "droiddeck-fds-1"), env)
|
||||
val onlySession = mutableMapOf("LD_PRELOAD" to "$rootfs/usr/lib/libddnatv-hook.so")
|
||||
BwrapSpawner.withoutRootfsSettings(onlySession, rootfs)
|
||||
assertTrue(onlySession.isEmpty())
|
||||
|
||||
@@ -34,6 +34,93 @@ ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/d
|
||||
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
|
||||
python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /'
|
||||
python3 /usr/local/bin/droiddeck-desktop-programs 2>&1 | sed 's/^/[programs] /'
|
||||
# Plasma lays out the SteamOS panel only for a profile without one. The layout is written at every
|
||||
# start, and a panel made before this version (Kubuntu's own, or the first SteamOS one without the
|
||||
# pager, clock and Plasma's stock pins) is set aside once so Plasma lays out the current one.
|
||||
dd_layout=/usr/share/plasma/look-and-feel/com.valve.vapor.desktop/contents/layouts
|
||||
if [ -d "$dd_layout" ]; then
|
||||
cat > "$dd_layout/org.kde.plasma.desktop-layout.js" <<'LAYOUT'
|
||||
var desktops = desktopsForActivity(currentActivity());
|
||||
for (var i = 0; i < desktops.length; i++) {
|
||||
desktops[i].wallpaperPlugin = "org.kde.image";
|
||||
desktops[i].currentConfigGroup = ["Wallpaper", "org.kde.image", "General"];
|
||||
desktops[i].writeConfig("Image", "file:///usr/share/wallpapers/DroidDeck");
|
||||
}
|
||||
|
||||
var panel = new Panel;
|
||||
var panelScreen = panel.screen;
|
||||
panel.location = "bottom";
|
||||
panel.height = 2 * Math.ceil(gridUnit * 2.5 / 2);
|
||||
|
||||
const maximumAspectRatio = 21 / 9;
|
||||
if (panel.formFactor === "horizontal") {
|
||||
const geo = screenGeometry(panelScreen);
|
||||
const maximumWidth = Math.ceil(geo.height * maximumAspectRatio);
|
||||
if (geo.width > maximumWidth) {
|
||||
panel.alignment = "center";
|
||||
panel.minimumLength = maximumWidth;
|
||||
panel.maximumLength = maximumWidth;
|
||||
}
|
||||
}
|
||||
|
||||
var kickoff = panel.addWidget("org.kde.plasma.kickoff");
|
||||
kickoff.currentConfigGroup = ["Shortcuts"];
|
||||
kickoff.writeConfig("global", "Alt+F1");
|
||||
kickoff.currentConfigGroup = ["General"];
|
||||
kickoff.writeConfig("icon", "distributor-logo-steamdeck");
|
||||
kickoff.writeConfig("favorites", [
|
||||
"preferred://browser",
|
||||
"applications:org.kde.dolphin.desktop",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
"applications:org.kde.discover.desktop",
|
||||
"applications:systemsettings.desktop",
|
||||
]);
|
||||
|
||||
panel.addWidget("org.kde.plasma.pager");
|
||||
|
||||
var tasks = panel.addWidget("org.kde.plasma.icontasks");
|
||||
tasks.currentConfigGroup = ["General"];
|
||||
tasks.writeConfig("launchers", [
|
||||
"applications:steamdeck-steam.desktop",
|
||||
"applications:systemsettings.desktop",
|
||||
"applications:org.kde.discover.desktop",
|
||||
"preferred://filemanager",
|
||||
"preferred://browser",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
]);
|
||||
|
||||
panel.addWidget("org.kde.plasma.marginsseparator");
|
||||
|
||||
const inputMethodLanguages = ["as", "bn", "bo", "brx", "doi", "gu", "hi", "ja", "kn", "ko", "kok", "ks", "lep", "mai",
|
||||
"ml", "mni", "mr", "ne", "or", "pa", "sa", "sat", "sd", "si", "ta", "te", "th", "ur", "vi", "zh_CN", "zh_TW"];
|
||||
if (inputMethodLanguages.indexOf(languageId) != -1) {
|
||||
panel.addWidget("org.kde.plasma.kimpanel");
|
||||
}
|
||||
|
||||
var tray = panel.addWidget("org.kde.plasma.systemtray");
|
||||
var trayId = tray.readConfig("SystrayContainmentId");
|
||||
if (trayId) {
|
||||
var trayContainment = desktopById(trayId);
|
||||
trayContainment.currentConfigGroup = ["General"];
|
||||
trayContainment.writeConfig("scaleIconsToFit", true);
|
||||
}
|
||||
var clock = panel.addWidget("org.kde.plasma.digitalclock");
|
||||
clock.currentConfigGroup = ["Appearance"];
|
||||
clock.writeConfig("dateFormat", "isoDate");
|
||||
panel.addWidget("org.kde.plasma.showdesktop");
|
||||
LAYOUT
|
||||
fi
|
||||
dd_panel_rc="${XDG_CONFIG_HOME:-$HOME/.config}/plasma-org.kde.plasma.desktop-appletsrc"
|
||||
dd_panel_stamp="${XDG_CONFIG_HOME:-$HOME/.config}/droiddeck-panel-layout"
|
||||
if [ "$(cat "$dd_panel_stamp" 2>/dev/null)" != steamos-2 ]; then
|
||||
dd_panel_backup="$dd_panel_rc.before-steamos-2"
|
||||
[ -e "$dd_panel_backup" ] && dd_panel_backup="$dd_panel_backup.$$"
|
||||
if [ ! -f "$dd_panel_rc" ] || mv "$dd_panel_rc" "$dd_panel_backup"; then
|
||||
mkdir -p "$(dirname "$dd_panel_stamp")" && echo steamos-2 > "$dd_panel_stamp"
|
||||
fi
|
||||
fi
|
||||
# startplasma applies this file over the session environment, and keeps what an earlier session wrote.
|
||||
kwriteconfig6 --file plasma-localerc --group Formats --key LANG "${LANG:-C.UTF-8}"
|
||||
if [ -n "${LANGUAGE:-}" ]; then
|
||||
|
||||
@@ -299,6 +299,27 @@ def map_drive(root, volume):
|
||||
return None
|
||||
|
||||
|
||||
def rootfs():
|
||||
host = os.environ.get("DDNATV_ROOT")
|
||||
return os.path.realpath(host) if host else None
|
||||
|
||||
|
||||
def guest_path(path):
|
||||
host = rootfs()
|
||||
if not host or not inside(path, host):
|
||||
return None
|
||||
return "/" + path[len(host):].strip("/")
|
||||
|
||||
|
||||
def rootfs_drive(root, text):
|
||||
found = re.match(r"(?i)^([abd-y]):[\\/]", text)
|
||||
host = rootfs()
|
||||
if not found or not host:
|
||||
return False
|
||||
link = os.path.join(dosdevices(root), found.group(1).lower() + ":")
|
||||
return os.path.islink(link) and inside(host, os.path.realpath(link))
|
||||
|
||||
|
||||
def install_path(root, library):
|
||||
library = library.rstrip("/") or "/"
|
||||
try:
|
||||
@@ -308,6 +329,9 @@ def install_path(root, library):
|
||||
return "Z:" + library
|
||||
if volume == "/":
|
||||
return "Z:" + library
|
||||
host = rootfs()
|
||||
if host and inside(host, volume):
|
||||
return "Z:" + (guest_path(path) or library)
|
||||
drive = mapped_drive(root, path, volume)
|
||||
if drive is None and not wine_processes(os.path.join(prefix(root), "pfx")):
|
||||
drive = map_drive(root, volume)
|
||||
@@ -586,11 +610,15 @@ def drive_folder(root, value):
|
||||
text = value.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return value
|
||||
if not re.match(r"(?i)^z:[\\/]", text):
|
||||
holds_root = rootfs_drive(root, text)
|
||||
if not holds_root and not re.match(r"(?i)^z:[\\/]", text):
|
||||
return value
|
||||
folder = windows_path(root, text)
|
||||
if not folder or not os.path.isdir(folder):
|
||||
return value
|
||||
if holds_root:
|
||||
guest = guest_path(os.path.realpath(folder))
|
||||
return value if guest is None else ("Z:" + guest).encode("utf-8")
|
||||
moved = install_path(root, folder)
|
||||
return value if moved.startswith("Z:") else moved.replace("\\", "/").encode("utf-8")
|
||||
|
||||
@@ -608,11 +636,115 @@ def move_installs(root):
|
||||
return False
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
write_bytes(path, moved)
|
||||
return True
|
||||
|
||||
|
||||
def rootfs_drives(root):
|
||||
host = rootfs()
|
||||
folder = dosdevices(root)
|
||||
if not host:
|
||||
return {}
|
||||
try:
|
||||
names = sorted(os.listdir(folder))
|
||||
except OSError:
|
||||
return {}
|
||||
drives = {}
|
||||
for name in names:
|
||||
link = os.path.join(folder, name)
|
||||
if len(name) == 2 and name[0].lower() in DRIVES and name[1] == ":" and os.path.islink(link):
|
||||
target = os.path.realpath(link)
|
||||
if inside(host, target):
|
||||
drives[name[0].lower()] = host[len(target):].strip("/")
|
||||
return drives
|
||||
|
||||
|
||||
def write_bytes(path, data):
|
||||
with open(path + ".tmp", "wb") as f:
|
||||
f.write(moved)
|
||||
f.write(data)
|
||||
shutil.copymode(path, path + ".tmp")
|
||||
os.replace(path + ".tmp", path)
|
||||
return True
|
||||
|
||||
|
||||
def install_folders(root):
|
||||
try:
|
||||
with open(os.path.join(drive_c(root), *PRODUCT_DB), "rb") as f:
|
||||
data = f.read()
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
folders = []
|
||||
rewrite_field(data, INSTALL_FOLDER, lambda value: folders.append(value) or value)
|
||||
return folders
|
||||
|
||||
|
||||
def json_strings(value):
|
||||
if isinstance(value, str):
|
||||
yield value
|
||||
elif isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
yield key
|
||||
yield from json_strings(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
yield from json_strings(item)
|
||||
|
||||
|
||||
def escapes(tail):
|
||||
depth = 0
|
||||
for part in re.split(rb"[\\/]+", tail):
|
||||
if part == b"..":
|
||||
depth -= 1
|
||||
if depth < 0:
|
||||
return True
|
||||
elif part and part != b".":
|
||||
depth += 1
|
||||
return False
|
||||
|
||||
|
||||
def drop_rootfs_drives(root):
|
||||
pfx = os.path.join(prefix(root), "pfx")
|
||||
drives = rootfs_drives(root)
|
||||
if not drives or wine_processes(pfx):
|
||||
return []
|
||||
try:
|
||||
folders = install_folders(root)
|
||||
except ValueError:
|
||||
return []
|
||||
texts = {}
|
||||
for path in (os.path.join(pfx, "system.reg"), os.path.join(pfx, "user.reg"), os.path.join(drive_c(root), *CONFIG)):
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
texts[path] = f.read()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
sep = rb"(?:\\\\|/)"
|
||||
changed = dict(texts)
|
||||
for letter, rest in drives.items():
|
||||
head = rb"(?<![A-Za-z0-9])[" + letter.encode() + letter.upper().encode() + rb"]:"
|
||||
inner = b"".join(sep + re.escape(part.encode()) for part in rest.split("/") if part)
|
||||
for path in changed:
|
||||
changed[path] = re.sub(head + inner + rb"(?=(" + sep + rb"[^\"\r\n]*))",
|
||||
lambda m: m.group(0) if escapes(m.group(1)) else b"Z:", changed[path])
|
||||
for path, data in changed.items():
|
||||
if data != texts[path]:
|
||||
write_bytes(path, data)
|
||||
seen = list(changed.values())
|
||||
config = os.path.join(drive_c(root), *CONFIG)
|
||||
if config in changed:
|
||||
try:
|
||||
seen += [text.encode("utf-8", "replace") for text in json_strings(json.loads(changed[config].decode("utf-8-sig")))]
|
||||
except ValueError:
|
||||
return []
|
||||
dropped = []
|
||||
for letter in sorted(drives):
|
||||
drive = letter.encode() + letter.upper().encode()
|
||||
used = rb"(?<![A-Za-z0-9])[" + drive + rb"]:[\\/]"
|
||||
if any(re.match(rb"[" + drive + rb"]:[\\/]", folder.lstrip()) for folder in folders):
|
||||
continue
|
||||
if not any(re.search(used, data) for data in seen):
|
||||
os.unlink(os.path.join(dosdevices(root), letter + ":"))
|
||||
dropped.append(letter)
|
||||
return dropped
|
||||
|
||||
|
||||
def wow_folders(root):
|
||||
@@ -725,9 +857,14 @@ def configure(root, library=None):
|
||||
return
|
||||
try:
|
||||
if move_installs(root):
|
||||
say("Battle.net's installed games on a mapped volume now use its Wine drive")
|
||||
say("Battle.net's installed games now use the Wine drive of their volume")
|
||||
except OSError as error:
|
||||
say("Battle.net's installed games not moved to their Wine drive: %s" % error)
|
||||
try:
|
||||
for letter in drop_rootfs_drives(root):
|
||||
say("Wine drive %s: held the runtime and is no longer used; removed" % letter.upper())
|
||||
except OSError as error:
|
||||
say("Battle.net's unused runtime drive not removed: %s" % error)
|
||||
try:
|
||||
wallpaper(root)
|
||||
except OSError as error:
|
||||
|
||||
@@ -3,13 +3,16 @@ import base64
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
|
||||
MAX_FORWARDED_FDS = 253
|
||||
|
||||
|
||||
def socket_name():
|
||||
@@ -94,6 +97,7 @@ class Spec:
|
||||
self.json_fds = []
|
||||
self.keep_fds = []
|
||||
self.lock_files = []
|
||||
self.lock_fds = []
|
||||
self.command = []
|
||||
self.argv0 = None
|
||||
self.env_tool = None
|
||||
@@ -363,6 +367,7 @@ def hold_locks(s):
|
||||
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
|
||||
sys.exit(1)
|
||||
os.set_inheritable(fd, True)
|
||||
s.lock_fds.append(fd)
|
||||
|
||||
|
||||
def report_pid(s, pid):
|
||||
@@ -379,8 +384,28 @@ def report_pid(s, pid):
|
||||
pass
|
||||
|
||||
|
||||
def bind_flatpak_info(s):
|
||||
if not s.env.get("DDNATV_ROOT"):
|
||||
return
|
||||
for op in s.ops:
|
||||
if op["t"] != "file" or op["dest"] != "/.flatpak-info":
|
||||
continue
|
||||
try:
|
||||
fd = os.memfd_create("flatpak-info", 0)
|
||||
except (AttributeError, OSError):
|
||||
return
|
||||
data = memoryview(op["data"])
|
||||
while data:
|
||||
data = data[os.write(fd, data):]
|
||||
os.lseek(fd, 0, os.SEEK_SET)
|
||||
entry = "/proc/%d/fd/%d:/.flatpak-info" % (os.getpid(), fd)
|
||||
binds = s.env.get("DDNATV_BINDS")
|
||||
s.env["DDNATV_BINDS"] = binds + "|" + entry if binds else entry
|
||||
|
||||
|
||||
def run_here(s):
|
||||
report_pid(s, os.getpid())
|
||||
bind_flatpak_info(s)
|
||||
for fd in s.json_fds:
|
||||
os.close(fd)
|
||||
if s.cwd:
|
||||
@@ -410,7 +435,53 @@ def recv_exact(sock, n):
|
||||
return buf
|
||||
|
||||
|
||||
def inherited_fds(s):
|
||||
own = set(s.info_fds + s.json_fds + s.keep_fds + s.lock_fds)
|
||||
fds = []
|
||||
for name in os.listdir("/proc/self/fd"):
|
||||
fd = int(name)
|
||||
if fd <= 2 or fd in own:
|
||||
continue
|
||||
try:
|
||||
if os.get_inheritable(fd):
|
||||
fds.append(fd)
|
||||
except OSError:
|
||||
pass
|
||||
return sorted(fds)
|
||||
|
||||
|
||||
def hand_over(listener, fds):
|
||||
try:
|
||||
conn, _ = listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
finally:
|
||||
listener.close()
|
||||
with conn:
|
||||
creds = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
|
||||
if struct.unpack("3i", creds)[1] != os.getuid():
|
||||
return
|
||||
conn.sendmsg([",".join(map(str, fds)).encode()],
|
||||
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, struct.pack("%di" % len(fds), *fds))])
|
||||
|
||||
|
||||
def offer_fds(s):
|
||||
fds = inherited_fds(s)
|
||||
if not fds:
|
||||
return
|
||||
if len(fds) > MAX_FORWARDED_FDS:
|
||||
sys.stderr.write("bwrap: Too many inherited file descriptors: %d\n" % len(fds))
|
||||
sys.exit(1)
|
||||
name = "droiddeck-fds-" + secrets.token_hex(16)
|
||||
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
listener.bind("\0" + name)
|
||||
listener.listen(1)
|
||||
s.env["DROIDDECK_FDS"] = name
|
||||
threading.Thread(target=hand_over, args=(listener, fds), daemon=True).start()
|
||||
|
||||
|
||||
def run_by_app(s):
|
||||
offer_fds(s)
|
||||
ops = []
|
||||
for op in s.ops:
|
||||
op = dict(op)
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/python3
|
||||
import configparser
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib
|
||||
|
||||
NAME = "org.freedesktop.portal.Documents"
|
||||
PATH = "/org/freedesktop/portal/documents"
|
||||
VERSION = 5
|
||||
PROC = sys.argv[1] if len(sys.argv) > 1 else "/proc"
|
||||
AS_NEEDED_BY_APP = 1 << 2
|
||||
DIRECTORY = 1 << 3
|
||||
FAILED = "org.freedesktop.portal.Error.Failed"
|
||||
NOT_FOUND = "org.freedesktop.portal.Error.NotFound"
|
||||
NOT_ALLOWED = "org.freedesktop.portal.Error.NotAllowed"
|
||||
INVALID = "org.freedesktop.portal.Error.InvalidArgument"
|
||||
INTROSPECTION = """
|
||||
<node>
|
||||
<interface name="org.freedesktop.portal.Documents">
|
||||
<method name="GetMountPoint"><arg type="ay" direction="out"/></method>
|
||||
<method name="Add">
|
||||
<arg type="h" direction="in"/><arg type="b" direction="in"/><arg type="b" direction="in"/>
|
||||
<arg type="s" direction="out"/>
|
||||
</method>
|
||||
<method name="AddNamed">
|
||||
<arg type="h" direction="in"/><arg type="ay" direction="in"/><arg type="b" direction="in"/>
|
||||
<arg type="b" direction="in"/><arg type="s" direction="out"/>
|
||||
</method>
|
||||
<method name="AddFull">
|
||||
<arg type="ah" direction="in"/><arg type="u" direction="in"/><arg type="s" direction="in"/>
|
||||
<arg type="as" direction="in"/><arg type="as" direction="out"/><arg type="a{sv}" direction="out"/>
|
||||
</method>
|
||||
<method name="AddNamedFull">
|
||||
<arg type="h" direction="in"/><arg type="ay" direction="in"/><arg type="u" direction="in"/>
|
||||
<arg type="s" direction="in"/><arg type="as" direction="in"/><arg type="s" direction="out"/>
|
||||
<arg type="a{sv}" direction="out"/>
|
||||
</method>
|
||||
<method name="GrantPermissions">
|
||||
<arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="as" direction="in"/>
|
||||
</method>
|
||||
<method name="RevokePermissions">
|
||||
<arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="as" direction="in"/>
|
||||
</method>
|
||||
<method name="Delete"><arg type="s" direction="in"/></method>
|
||||
<method name="Lookup"><arg type="ay" direction="in"/><arg type="s" direction="out"/></method>
|
||||
<method name="Info">
|
||||
<arg type="s" direction="in"/><arg type="ay" direction="out"/><arg type="a{sas}" direction="out"/>
|
||||
</method>
|
||||
<method name="List"><arg type="s" direction="in"/><arg type="a{say}" direction="out"/></method>
|
||||
<method name="GetHostPaths"><arg type="as" direction="in"/><arg type="a{say}" direction="out"/></method>
|
||||
<property name="version" type="u" access="read"/>
|
||||
</interface>
|
||||
</node>
|
||||
"""
|
||||
|
||||
|
||||
def passed_fds(invocation, handles):
|
||||
fd_list = invocation.get_message().get_unix_fd_list()
|
||||
fds = fd_list.peek_fds() if fd_list else []
|
||||
return [fds[h] if 0 <= h < len(fds) else -1 for h in handles]
|
||||
|
||||
|
||||
def usable(fd, flags):
|
||||
try:
|
||||
mode = os.fstat(fd).st_mode
|
||||
except OSError:
|
||||
return False
|
||||
return stat.S_ISDIR(mode) if flags & DIRECTORY else stat.S_ISREG(mode)
|
||||
|
||||
|
||||
def app_name(pid):
|
||||
info = configparser.ConfigParser(interpolation=None)
|
||||
try:
|
||||
with open(os.path.join(PROC, pid, "root/.flatpak-info")) as f:
|
||||
info.read_file(f)
|
||||
except (OSError, UnicodeDecodeError, configparser.Error):
|
||||
return None
|
||||
return info.get("Application", "name", fallback=None)
|
||||
|
||||
|
||||
def root_of(pid):
|
||||
try:
|
||||
return os.stat(os.path.join(PROC, str(pid), "root", "."))
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def app_pids(app_id):
|
||||
roots = {pid: root_of(pid) for pid in os.listdir(PROC) if pid.isdigit() and app_name(pid) == app_id}
|
||||
own = root_of(os.getpid())
|
||||
apart = [pid for pid, root in roots.items() if not (own and root and os.path.samestat(own, root))]
|
||||
return apart or list(roots)
|
||||
|
||||
|
||||
def access_mode(permissions):
|
||||
mode = os.R_OK if "read" in permissions else 0
|
||||
return mode | os.W_OK if "write" in permissions else mode
|
||||
|
||||
|
||||
def under(path, prefix):
|
||||
return path == prefix or path.startswith(prefix.rstrip("/") + "/")
|
||||
|
||||
|
||||
def spellings(path):
|
||||
root = os.environ.get("DDNATV_ROOT", "").rstrip("/")
|
||||
if root and under(path, root):
|
||||
path = path[len(root):] or "/"
|
||||
names = [path]
|
||||
for bind in filter(None, os.environ.get("DDNATV_BINDS", "").split("|")):
|
||||
host, _, guest = bind.partition(":")
|
||||
if host and guest and under(path, guest):
|
||||
name = host + path[len(guest.rstrip("/")):]
|
||||
if not (root and under(name, root)) and name not in names:
|
||||
names.append(name)
|
||||
return names
|
||||
|
||||
|
||||
def same_file(path, picked):
|
||||
try:
|
||||
return os.path.samestat(os.stat(path), picked)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def app_reaches(app_id, path, picked, permissions):
|
||||
if not app_id:
|
||||
return True
|
||||
mode = access_mode(permissions) or os.F_OK
|
||||
roots = [os.path.join(PROC, pid, "root") for pid in app_pids(app_id)]
|
||||
return any(same_file(root + name, picked) and os.access(root + name, mode)
|
||||
for root in roots for name in spellings(path))
|
||||
|
||||
|
||||
def fd_path(fd):
|
||||
try:
|
||||
path = os.readlink("/proc/self/fd/%d" % fd)
|
||||
except OSError:
|
||||
return None
|
||||
return path if path.startswith("/") else None
|
||||
|
||||
|
||||
def reachable_in_place(invocation, flags, handles, directories, app_id, permissions):
|
||||
if not flags & AS_NEEDED_BY_APP:
|
||||
invocation.return_dbus_error(NOT_ALLOWED, "Documents can only be shared in place")
|
||||
return False
|
||||
fds = passed_fds(invocation, handles)
|
||||
if not all(fd >= 0 and usable(fd, DIRECTORY if directories else flags) for fd in fds):
|
||||
invocation.return_dbus_error(INVALID, "Invalid fd passed")
|
||||
return False
|
||||
if not all(fd_path(fd) and app_reaches(app_id, fd_path(fd), os.fstat(fd), permissions) for fd in fds):
|
||||
invocation.return_dbus_error(NOT_ALLOWED, "The application can't reach this location without the document store")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def on_call(connection, sender, path, interface, method, params, invocation):
|
||||
args = params.unpack()
|
||||
if method == "AddFull":
|
||||
handles, flags = args[0], args[1]
|
||||
if reachable_in_place(invocation, flags, handles, False, args[2], args[3]):
|
||||
invocation.return_value(GLib.Variant("(asa{sv})", ([""] * len(handles), {})))
|
||||
elif method == "AddNamedFull":
|
||||
if reachable_in_place(invocation, args[2], [args[0]], True, args[3], args[4]):
|
||||
invocation.return_value(GLib.Variant("(sa{sv})", ("", {})))
|
||||
elif method == "Lookup":
|
||||
invocation.return_value(GLib.Variant("(s)", ("",)))
|
||||
elif method == "List":
|
||||
invocation.return_value(GLib.Variant("(a{say})", ({},)))
|
||||
elif method == "GetHostPaths":
|
||||
invocation.return_value(GLib.Variant("(a{say})", ({},)))
|
||||
elif method in ("Add", "AddNamed"):
|
||||
invocation.return_dbus_error(NOT_ALLOWED, "Documents can only be shared in place")
|
||||
elif method in ("GrantPermissions", "RevokePermissions", "Delete", "Info"):
|
||||
invocation.return_dbus_error(NOT_FOUND, "Invalid document id")
|
||||
else:
|
||||
invocation.return_dbus_error(FAILED, "No document store mount")
|
||||
|
||||
|
||||
def on_get(connection, sender, path, interface, prop):
|
||||
return GLib.Variant("u", VERSION) if prop == "version" else None
|
||||
|
||||
|
||||
def main():
|
||||
loop = GLib.MainLoop()
|
||||
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
|
||||
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
bus.register_object(PATH, info, on_call, on_get, None)
|
||||
Gio.bus_own_name_on_connection(bus, NAME, Gio.BusNameOwnerFlags.DO_NOT_QUEUE, None, lambda *_: loop.quit())
|
||||
loop.run()
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -6,6 +7,8 @@ import platform
|
||||
import re
|
||||
import runpy
|
||||
import signal
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -1046,6 +1049,9 @@ WINE_DLL_DIRS = ("/lib/wine/i386-windows", "/lib/wine/x86_64-windows", "/lib/win
|
||||
|
||||
|
||||
FOREIGN_SUFFIX = ".foreign-arch"
|
||||
WINE_SD = "user.wine.sd"
|
||||
SHARED_DATA = "pfx/drive_c/ProgramData"
|
||||
MACHINE_ID = "/etc/machine-id"
|
||||
PE = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe"))
|
||||
pe_machine = PE["pe_machine"]
|
||||
|
||||
@@ -1144,6 +1150,124 @@ def repair_foreign_system_dlls(prefix, proton, env=None):
|
||||
return repaired
|
||||
|
||||
|
||||
def wine_user_sid():
|
||||
try:
|
||||
with open(MACHINE_ID, "rb") as handle:
|
||||
text = handle.read(16)
|
||||
except OSError:
|
||||
return (21, 0, 0, 0, 1000)
|
||||
if len(text) != 16:
|
||||
return (21, 0, 0, 0, 1000)
|
||||
sign, digits = re.match(rb"\s*([+-]?)(?:0[xX])?([0-9a-fA-F]*)", text).groups()
|
||||
machine = int(digits, 16) if digits else 0
|
||||
if sign == b"-":
|
||||
machine = -machine % (1 << 64)
|
||||
return (21, machine >> 32, machine & 0xffffffff, os.getuid(), 1000)
|
||||
|
||||
|
||||
def wine_sd_owner(path):
|
||||
try:
|
||||
data = os.getxattr(path, WINE_SD, follow_symlinks=False)
|
||||
except OSError:
|
||||
return None
|
||||
if len(data) < 22:
|
||||
return None
|
||||
sid = data[22:22 + struct.unpack_from("<I", data, 6)[0]]
|
||||
if len(sid) < 8 or len(sid) < 8 + 4 * sid[1]:
|
||||
return None
|
||||
return sid[0], int.from_bytes(sid[2:8], "big"), struct.unpack_from("<%dI" % sid[1], sid, 8)
|
||||
|
||||
|
||||
def is_stale_owner(owner, user):
|
||||
if owner is None:
|
||||
return False
|
||||
revision, authority, subs = owner
|
||||
return revision == 1 and authority == 5 and len(subs) == 5 and subs[0] == 21 and subs[4] == 1000 \
|
||||
and subs != user
|
||||
|
||||
|
||||
def heal_wine_entry(path, is_dir, user):
|
||||
try:
|
||||
mode = stat.S_IMODE(os.lstat(path).st_mode)
|
||||
except OSError:
|
||||
return None, False
|
||||
readable = mode
|
||||
if not mode & stat.S_IRUSR:
|
||||
readable = mode | stat.S_IRUSR
|
||||
try:
|
||||
os.chmod(path, readable)
|
||||
except OSError:
|
||||
return None, False
|
||||
final = mode
|
||||
stale = is_stale_owner(wine_sd_owner(path), user)
|
||||
cleared = False
|
||||
if stale and (not mode & stat.S_IRUSR or is_dir and not mode & stat.S_IXUSR):
|
||||
final = mode | (stat.S_IRWXU if is_dir else stat.S_IRUSR | stat.S_IWUSR)
|
||||
try:
|
||||
if stale:
|
||||
os.chmod(path, final | stat.S_IWUSR)
|
||||
try:
|
||||
os.removexattr(path, WINE_SD, follow_symlinks=False)
|
||||
cleared = True
|
||||
except OSError:
|
||||
pass
|
||||
if not final & stat.S_IWUSR:
|
||||
os.chmod(path, final)
|
||||
elif final != readable:
|
||||
os.chmod(path, final)
|
||||
except OSError:
|
||||
return None, cleared
|
||||
return (mode, final), cleared
|
||||
|
||||
|
||||
def heal_shared_data(prefix):
|
||||
root = Path(prefix) / SHARED_DATA
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
return [], []
|
||||
try:
|
||||
lock = os.open(root.parent.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
except OSError:
|
||||
return [], []
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
return heal_shared_data_locked(root)
|
||||
finally:
|
||||
os.close(lock)
|
||||
|
||||
|
||||
def heal_shared_data_locked(root):
|
||||
user = wine_user_sid()
|
||||
unlocked = []
|
||||
cleared = []
|
||||
pending = [(str(root), True)]
|
||||
while pending:
|
||||
path, is_dir = pending.pop()
|
||||
modes, was_cleared = heal_wine_entry(path, is_dir, user)
|
||||
name = os.path.relpath(path, root)
|
||||
if was_cleared:
|
||||
cleared.append(name)
|
||||
if modes is None:
|
||||
continue
|
||||
mode, final = modes
|
||||
if final != mode:
|
||||
unlocked.append(name)
|
||||
if not is_dir or final & (stat.S_IRUSR | stat.S_IXUSR) != stat.S_IRUSR | stat.S_IXUSR:
|
||||
continue
|
||||
try:
|
||||
with os.scandir(path) as entries:
|
||||
for entry in entries:
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
pending.append((entry.path, True))
|
||||
elif entry.is_file(follow_symlinks=False):
|
||||
pending.append((entry.path, False))
|
||||
except OSError:
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
return sorted(unlocked), sorted(cleared)
|
||||
|
||||
|
||||
def is_wine_dll_link(path):
|
||||
try:
|
||||
return os.path.islink(path) and os.path.dirname(os.readlink(path)).endswith(WINE_DLL_DIRS)
|
||||
@@ -1486,6 +1610,14 @@ def main():
|
||||
except OSError as error:
|
||||
restored = fixed = []
|
||||
print("droiddeck-game-env: prefix system DLL check skipped (%s)" % error, file=sys.stderr)
|
||||
try:
|
||||
unlocked, cleared = heal_shared_data(prefix_path)
|
||||
except OSError as error:
|
||||
unlocked = cleared = []
|
||||
print("droiddeck-game-env: ProgramData owner check skipped (%s)" % error, file=sys.stderr)
|
||||
if cleared:
|
||||
print("droiddeck-game-env: cleared %d stale Windows owners in ProgramData; unlocked: %s"
|
||||
% (len(cleared), ", ".join(unlocked) or "none"), file=sys.stderr)
|
||||
if restored:
|
||||
print("droiddeck-game-env: restored system DLLs this Proton's own programs do not load: %s" % ", ".join(restored),
|
||||
file=sys.stderr)
|
||||
|
||||
@@ -66,6 +66,14 @@ ensure_machine_id() {
|
||||
} 2>/dev/null
|
||||
ensure_machine_id
|
||||
|
||||
write_document_store_service() {
|
||||
[ -x /usr/local/bin/droiddeck-documents ] || return 0
|
||||
mkdir -p /usr/local/share/dbus-1/services &&
|
||||
printf '[D-BUS Service]\nName=org.freedesktop.portal.Documents\nExec=/usr/local/bin/droiddeck-documents\n' \
|
||||
> /usr/local/share/dbus-1/services/org.freedesktop.portal.Documents.service
|
||||
} 2>/dev/null
|
||||
write_document_store_service
|
||||
|
||||
write_system_bus_config() {
|
||||
mkdir -p /run/dbus /usr/local/share/droiddeck
|
||||
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
|
||||
|
||||
@@ -419,9 +419,11 @@ static void *real_dlsym(void);
|
||||
* searches, so the handle the program opened is the only way back to the real implementation. */
|
||||
static _Atomic(void *) udev_handle;
|
||||
|
||||
__attribute__((visibility("hidden"))) void bl_inputudev_note_dlopen(const char *path, void *handle) {
|
||||
if (handle != NULL && path != NULL && strstr(path, "libudev") != NULL)
|
||||
atomic_store_explicit(&udev_handle, handle, memory_order_release);
|
||||
__attribute__((visibility("hidden"))) void bl_inputudev_note_dlopen(const char *path, void *handle,
|
||||
void *(*open)(const char *, int)) {
|
||||
if (handle == NULL || path == NULL || strstr(path, "libudev") == NULL) return;
|
||||
if (open(path, RTLD_LAZY | RTLD_NOLOAD | RTLD_NODELETE) == NULL) return;
|
||||
atomic_store_explicit(&udev_handle, handle, memory_order_release);
|
||||
}
|
||||
|
||||
static void *next_symbol(const char *name) {
|
||||
|
||||
@@ -100,7 +100,8 @@ static long path_statx(int dirfd, const char *path, int flags, unsigned int mask
|
||||
return next_statx(dirfd, path, flags, mask, out);
|
||||
}
|
||||
|
||||
void bl_inputudev_note_dlopen(const char *path, void *handle) __attribute__((weak, visibility("hidden")));
|
||||
void bl_inputudev_note_dlopen(const char *path, void *handle, void *(*open)(const char *, int))
|
||||
__attribute__((weak, visibility("hidden")));
|
||||
|
||||
void *dlopen(const char *filename, int flags) {
|
||||
void *handle;
|
||||
@@ -114,7 +115,7 @@ void *dlopen(const char *filename, int flags) {
|
||||
flags &= ~RTLD_DEEPBIND;
|
||||
}
|
||||
handle = real_dlopen != NULL ? real_dlopen(filename, flags) : NULL;
|
||||
if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle);
|
||||
if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle, real_dlopen);
|
||||
return handle;
|
||||
}
|
||||
|
||||
|
||||
@@ -213,7 +213,8 @@ int open(const char *pathname, int flags, ...) {
|
||||
int status_fd = open_proc_status(pathname, flags);
|
||||
if (status_fd != -2) return status_fd;
|
||||
char buf[PATH_MAX];
|
||||
const char *target = ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf));
|
||||
const char *target = proc_root_host(pathname, buf, sizeof(buf), !(flags & O_NOFOLLOW), !(flags & O_NOFOLLOW));
|
||||
if (!target) target = ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf));
|
||||
if (open_needs_mode(flags)) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
@@ -221,9 +222,12 @@ int open(const char *pathname, int flags, ...) {
|
||||
va_end(args);
|
||||
int fd = orig_open(target, flags, mode);
|
||||
if (fd < 0 && (flags & O_CREAT) && refused_in_repaired_dir(AT_FDCWD, target)) fd = orig_open(target, flags, mode);
|
||||
forget_proc_root_fd(fd);
|
||||
return fd;
|
||||
}
|
||||
return orig_open(target, flags);
|
||||
int fd = orig_open(target, flags);
|
||||
remember_proc_root_fd(fd, pathname);
|
||||
return fd;
|
||||
}
|
||||
|
||||
// Hook openat
|
||||
@@ -243,7 +247,8 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
|
||||
int status_fd = (pathname && pathname[0] == '/') ? open_proc_status(pathname, flags) : open_proc_status_at(dirfd, pathname, flags);
|
||||
if (status_fd != -2) return status_fd;
|
||||
char buf[PATH_MAX];
|
||||
const char *target = (pathname && pathname[0] == '/') ? ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
|
||||
const char *target = proc_root_host(pathname, buf, sizeof(buf), !(flags & O_NOFOLLOW), !(flags & O_NOFOLLOW));
|
||||
if (!target) target = (pathname && pathname[0] == '/') ? ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
|
||||
if (open_needs_mode(flags)) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
@@ -251,9 +256,12 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
|
||||
va_end(args);
|
||||
int fd = orig_openat(dirfd, target, flags, mode);
|
||||
if (fd < 0 && (flags & O_CREAT) && refused_in_repaired_dir(dirfd, target)) fd = orig_openat(dirfd, target, flags, mode);
|
||||
forget_proc_root_fd(fd);
|
||||
return fd;
|
||||
}
|
||||
return orig_openat(dirfd, target, flags);
|
||||
int fd = orig_openat(dirfd, target, flags);
|
||||
remember_proc_root_fd(fd, pathname);
|
||||
return fd;
|
||||
}
|
||||
|
||||
// Hook creat
|
||||
|
||||
@@ -244,6 +244,7 @@ int close(int fd) {
|
||||
if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0;
|
||||
clear_dns_redirect(fd);
|
||||
set_chosen_port_fd(fd, 0);
|
||||
forget_proc_root_fd(fd);
|
||||
return orig_close ? orig_close(fd) : -1;
|
||||
}
|
||||
|
||||
@@ -254,7 +255,9 @@ int dup2(int oldfd, int newfd) {
|
||||
clear_dns_redirect(newfd);
|
||||
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
|
||||
}
|
||||
return orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
|
||||
int ret = orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
|
||||
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int dup3(int oldfd, int newfd, int flags) {
|
||||
@@ -264,7 +267,9 @@ int dup3(int oldfd, int newfd, int flags) {
|
||||
clear_dns_redirect(newfd);
|
||||
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
|
||||
}
|
||||
return orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
|
||||
int ret = orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
|
||||
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int get_dns_redirect(int fd, struct sockaddr_storage *orig, socklen_t *orig_len) {
|
||||
|
||||
@@ -171,6 +171,11 @@ static int is_android_host_path(const char *path) {
|
||||
}
|
||||
|
||||
static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize);
|
||||
#ifndef DDNATV_HOST_TEST
|
||||
static const char *proc_root_host(const char *path, char *buf, size_t size, int bare, int follow);
|
||||
static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize);
|
||||
static const char *proc_root_at(int dirfd, const char *rel, char *buf, size_t size);
|
||||
#endif
|
||||
|
||||
#if defined(__aarch64__)
|
||||
static long raw_readlinkat(int dirfd, const char *path, char *buf, size_t size) {
|
||||
@@ -371,6 +376,13 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
|
||||
return buffer;
|
||||
}
|
||||
|
||||
#ifndef DDNATV_HOST_TEST
|
||||
if (path[1] == 'p' && strncmp(path, "/proc/", 6) == 0 && path[6] >= '1' && path[6] <= '9') {
|
||||
const char *other = proc_root_host(path, buffer, bufsize, 0, 0);
|
||||
if (other) return other;
|
||||
}
|
||||
#endif
|
||||
|
||||
for (int i = 0; i < g_nbinds; i++) {
|
||||
const struct ddnatv_bind *b = &g_binds[i];
|
||||
if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) {
|
||||
@@ -839,6 +851,10 @@ static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t
|
||||
static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
|
||||
#if defined(__aarch64__)
|
||||
if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL;
|
||||
#ifndef DDNATV_HOST_TEST
|
||||
const char *other = proc_root_at(dirfd, rel, buf, size);
|
||||
if (other) return other;
|
||||
#endif
|
||||
if (strstr(rel, "..")) {
|
||||
const char *walked = map_parent_walk(dirfd, rel, buf, size);
|
||||
if (walked || dirfd == AT_FDCWD) return walked;
|
||||
|
||||
@@ -446,6 +446,7 @@ static int close_range_part(unsigned int first, unsigned int last, void *flags)
|
||||
}
|
||||
|
||||
int close_range(unsigned int first, unsigned int last, int flags) {
|
||||
if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last);
|
||||
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
|
||||
if (g_kept_fd_count > 0 && !(flags & CLOSE_RANGE_CLOEXEC)) {
|
||||
return for_each_range_without(first, last, g_kept_fds, g_kept_fd_count, close_range_part, &flags);
|
||||
|
||||
@@ -136,7 +136,95 @@ static void init_ddnatv_hook(void) {
|
||||
// time it was read.
|
||||
static void compact_loader_args(int argc, char **argv);
|
||||
|
||||
#define DDNATV_MAX_FORWARDED_FDS 253
|
||||
|
||||
static int forwarded_targets(char *text, int *targets, int max) {
|
||||
int count = 0;
|
||||
for (char *p = text; *p && count < max;) {
|
||||
char *end;
|
||||
long fd = strtol(p, &end, 10);
|
||||
if (end == p) break;
|
||||
targets[count++] = fd >= 0 && fd <= INT_MAX ? (int)fd : -1;
|
||||
p = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
static int is_forwarded_target(int fd, const int *targets, int wanted) {
|
||||
for (int i = 0; i < wanted; i++) {
|
||||
if (targets[i] == fd) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void adopt_forwarded_fds(void) {
|
||||
const char *name = getenv("DROIDDECK_FDS");
|
||||
if (!name) return;
|
||||
struct sockaddr_un addr;
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sun_family = AF_UNIX;
|
||||
size_t len = strlen(name);
|
||||
int usable = len > 0 && len + 1 <= sizeof(addr.sun_path);
|
||||
if (usable) memcpy(addr.sun_path + 1, name, len);
|
||||
unsetenv("DROIDDECK_FDS");
|
||||
if (!usable) return;
|
||||
int sock = (int)syscall(SYS_socket, AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (sock < 0) return;
|
||||
static char text[4096];
|
||||
static int got[DDNATV_MAX_FORWARDED_FDS];
|
||||
int count = 0;
|
||||
int truncated = 0;
|
||||
ssize_t n = -1;
|
||||
socklen_t addr_len = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + len);
|
||||
if (syscall(SYS_connect, sock, &addr, addr_len) == 0) {
|
||||
static union {
|
||||
struct cmsghdr header;
|
||||
char buf[CMSG_SPACE(sizeof(got))];
|
||||
} control;
|
||||
struct iovec iov = {text, sizeof(text) - 1};
|
||||
struct msghdr msg;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.msg_iov = &iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = control.buf;
|
||||
msg.msg_controllen = sizeof(control.buf);
|
||||
do {
|
||||
n = syscall(SYS_recvmsg, sock, &msg, MSG_CMSG_CLOEXEC);
|
||||
} while (n < 0 && errno == EINTR);
|
||||
truncated = n >= 0 && (msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) != 0;
|
||||
for (struct cmsghdr *c = n >= 0 ? CMSG_FIRSTHDR(&msg) : NULL; c; c = CMSG_NXTHDR(&msg, c)) {
|
||||
if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) continue;
|
||||
size_t k = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int);
|
||||
for (size_t i = 0; i < k && count < DDNATV_MAX_FORWARDED_FDS; i++) {
|
||||
memcpy(&got[count++], CMSG_DATA(c) + i * sizeof(int), sizeof(int));
|
||||
}
|
||||
}
|
||||
}
|
||||
syscall(SYS_close, sock);
|
||||
text[n > 0 ? n : 0] = '\0';
|
||||
static int targets[DDNATV_MAX_FORWARDED_FDS];
|
||||
int wanted = truncated ? 0 : forwarded_targets(text, targets, DDNATV_MAX_FORWARDED_FDS);
|
||||
if (wanted != count) wanted = 0;
|
||||
static int parked[DDNATV_MAX_FORWARDED_FDS];
|
||||
int n_parked = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
int fd = got[i];
|
||||
while (fd >= 0 && is_forwarded_target(fd, targets, wanted) && n_parked < DDNATV_MAX_FORWARDED_FDS) {
|
||||
parked[n_parked++] = fd;
|
||||
fd = (int)syscall(SYS_fcntl, fd, F_DUPFD_CLOEXEC, 3);
|
||||
}
|
||||
got[i] = is_forwarded_target(fd, targets, wanted) ? -1 : fd;
|
||||
}
|
||||
for (int i = 0; i < n_parked; i++) syscall(SYS_close, parked[i]);
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (got[i] < 0) continue;
|
||||
if (i < wanted && targets[i] > 2) syscall(SYS_dup3, got[i], targets[i], 0);
|
||||
syscall(SYS_close, got[i]);
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) {
|
||||
adopt_forwarded_fds();
|
||||
init_ddnatv_hook();
|
||||
compact_loader_args(argc, argv);
|
||||
// The kernel names the process after what it executed, the rootfs ld.so: process monitors, and
|
||||
@@ -280,6 +368,200 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
|
||||
return found;
|
||||
}
|
||||
|
||||
static pid_t proc_root_pid(const char *path, const char **rest) {
|
||||
if (!path || strncmp(path, "/proc/", 6) != 0 || path[6] < '1' || path[6] > '9') return 0;
|
||||
const char *p = path + 6;
|
||||
long pid = 0;
|
||||
while (*p >= '0' && *p <= '9') {
|
||||
pid = pid * 10 + (*p++ - '0');
|
||||
if (pid > 0x3fffffff) return 0;
|
||||
}
|
||||
if (strncmp(p, "/root", 5) != 0 || (p[5] != '\0' && p[5] != '/')) return 0;
|
||||
*rest = p + 5;
|
||||
return (pid_t)pid;
|
||||
}
|
||||
|
||||
static int proc_view_of(pid_t pid, char **root, char **binds) {
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
|
||||
size_t used;
|
||||
int whole;
|
||||
*root = NULL;
|
||||
*binds = NULL;
|
||||
char *env = read_proc_file(path, &used, &whole);
|
||||
if (!env) return 0;
|
||||
for (char *e = env; e < env + used; e += strlen(e) + 1) {
|
||||
if (!*root && strncmp(e, "DDNATV_ROOT=", 12) == 0 && e[12] == '/') *root = strdup(e + 12);
|
||||
else if (!*binds && strncmp(e, "DDNATV_BINDS=", 13) == 0) *binds = strdup(e + 13);
|
||||
}
|
||||
free(env);
|
||||
if (*root) return 1;
|
||||
free(*binds);
|
||||
*binds = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char *proc_view_path(const char *root, char *binds, const char *guest, char *buf, size_t size) {
|
||||
const char *best_src = NULL, *best_dst = NULL;
|
||||
size_t best_len = 0;
|
||||
char *save = NULL;
|
||||
for (char *entry = binds ? strtok_r(binds, "|", &save) : NULL; entry; entry = strtok_r(NULL, "|", &save)) {
|
||||
char *colon = strchr(entry, ':');
|
||||
const char *dst = colon ? colon + 1 : entry;
|
||||
if (colon) *colon = '\0';
|
||||
size_t len = strlen(dst);
|
||||
while (len > 1 && dst[len - 1] == '/') len--;
|
||||
if (entry[0] != '/' || dst[0] != '/' || len < 2 || len <= best_len || !is_path_prefix(guest, dst, len)) continue;
|
||||
best_src = entry;
|
||||
best_dst = dst;
|
||||
best_len = len;
|
||||
}
|
||||
if (best_src && strncmp(best_src, best_dst, best_len) == 0 && best_src[best_len] == '\0') {
|
||||
ddnatv_copy_cstr(buf, size, guest);
|
||||
} else if (best_src) {
|
||||
size_t n = strncmp(best_src, "/proc/", 6) == 0 && best_src[6] >= '0' && best_src[6] <= '9'
|
||||
? ddnatv_copy_cstr(buf, size, best_src)
|
||||
: ddnatv_kernel_path(best_src, strlen(best_src), buf, size);
|
||||
ddnatv_append(buf, size, n, guest + best_len, strlen(guest + best_len));
|
||||
} else if (is_android_host_path(guest)) {
|
||||
ddnatv_copy_cstr(buf, size, guest);
|
||||
} else {
|
||||
size_t n = ddnatv_copy_cstr(buf, size, root);
|
||||
if (guest[1]) ddnatv_append(buf, size, n, guest, strlen(guest));
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
static const char *proc_view_host(const char *root, const char *binds, const char *guest, char *buf, size_t size) {
|
||||
char *copy = binds ? strdup(binds) : NULL;
|
||||
proc_view_path(root, copy, guest, buf, size);
|
||||
free(copy);
|
||||
return buf;
|
||||
}
|
||||
|
||||
static const char *proc_root_host(const char *path, char *buf, size_t size, int bare, int follow) {
|
||||
const char *rest = NULL;
|
||||
pid_t pid = proc_root_pid(path, &rest);
|
||||
if (pid <= 0 || (!bare && rest[0] == '\0')) return NULL;
|
||||
char *root, *binds;
|
||||
if (!proc_view_of(pid, &root, &binds)) return NULL;
|
||||
size_t root_len = strlen(root);
|
||||
while (root_len > 1 && root[root_len - 1] == '/') root_len--;
|
||||
char root_k[PATH_MAX], guest[PATH_MAX];
|
||||
ddnatv_kernel_path(root, root_len, root_k, sizeof(root_k));
|
||||
ddnatv_copy_cstr(guest, sizeof(guest), rest[0] ? rest : "/");
|
||||
normalize_path(guest);
|
||||
if (strcmp(root_k, g_ddnatv_root) == 0 && strcmp(binds ? binds : "", g_binds_raw ? g_binds_raw : "") == 0) {
|
||||
const char *own = (follow ? rewrite_path_follow : rewrite_path_in_root)(guest, buf, size);
|
||||
if (own != buf) ddnatv_copy_cstr(buf, size, own);
|
||||
} else {
|
||||
proc_view_host(root_k, binds, guest, buf, size);
|
||||
#if defined(__aarch64__)
|
||||
for (int depth = 0; follow && depth < 8 && strncmp(buf, "/proc/", 6) != 0; depth++) {
|
||||
char target[PATH_MAX];
|
||||
long n = raw_readlinkat(AT_FDCWD, buf, target, sizeof(target) - 1);
|
||||
if (n <= 0) break;
|
||||
target[n] = '\0';
|
||||
char joined[PATH_MAX];
|
||||
if (target[0] == '/') {
|
||||
ddnatv_copy_cstr(joined, sizeof(joined), target);
|
||||
} else {
|
||||
const char *slash = strrchr(guest, '/');
|
||||
size_t used = ddnatv_append(joined, sizeof(joined), 0, guest, slash ? (size_t)(slash - guest) : 0);
|
||||
used = ddnatv_append(joined, sizeof(joined), used, "/", 1);
|
||||
ddnatv_append(joined, sizeof(joined), used, target, strlen(target));
|
||||
}
|
||||
normalize_path(joined);
|
||||
ddnatv_copy_cstr(guest, sizeof(guest), joined);
|
||||
proc_view_host(root_k, binds, guest, buf, size);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
free(root);
|
||||
free(binds);
|
||||
return buf;
|
||||
}
|
||||
|
||||
struct ddnatv_proc_root_fd {
|
||||
int fd;
|
||||
pid_t pid;
|
||||
unsigned long dev, ino;
|
||||
};
|
||||
static struct ddnatv_proc_root_fd g_proc_root_fds[32];
|
||||
static int g_n_proc_root_fds = 0;
|
||||
static pthread_mutex_t g_proc_root_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static void forget_proc_root_range(unsigned int first, unsigned int last) {
|
||||
if (__atomic_load_n(&g_n_proc_root_fds, __ATOMIC_ACQUIRE) == 0) return;
|
||||
pthread_mutex_lock(&g_proc_root_mutex);
|
||||
for (int i = 0; i < g_n_proc_root_fds;) {
|
||||
unsigned int fd = (unsigned int)g_proc_root_fds[i].fd;
|
||||
if (fd >= first && fd <= last) g_proc_root_fds[i] = g_proc_root_fds[--g_n_proc_root_fds];
|
||||
else i++;
|
||||
}
|
||||
pthread_mutex_unlock(&g_proc_root_mutex);
|
||||
}
|
||||
|
||||
static void forget_proc_root_fd(int fd) {
|
||||
if (fd >= 0) forget_proc_root_range((unsigned int)fd, (unsigned int)fd);
|
||||
}
|
||||
|
||||
static void store_proc_root_fd(struct ddnatv_proc_root_fd entry) {
|
||||
pthread_mutex_lock(&g_proc_root_mutex);
|
||||
int slot = 0;
|
||||
while (slot < g_n_proc_root_fds && g_proc_root_fds[slot].fd != entry.fd) slot++;
|
||||
if (slot == g_n_proc_root_fds && slot == (int)(sizeof(g_proc_root_fds) / sizeof(g_proc_root_fds[0]))) slot = 0;
|
||||
g_proc_root_fds[slot] = entry;
|
||||
if (slot == g_n_proc_root_fds) __atomic_store_n(&g_n_proc_root_fds, g_n_proc_root_fds + 1, __ATOMIC_RELEASE);
|
||||
pthread_mutex_unlock(&g_proc_root_mutex);
|
||||
}
|
||||
|
||||
static void copy_proc_root_fd(int oldfd, int newfd) {
|
||||
if (newfd < 0 || oldfd == newfd) return;
|
||||
forget_proc_root_fd(newfd);
|
||||
if (oldfd < 0 || __atomic_load_n(&g_n_proc_root_fds, __ATOMIC_ACQUIRE) == 0) return;
|
||||
struct ddnatv_proc_root_fd entry = {-1, 0, 0, 0};
|
||||
pthread_mutex_lock(&g_proc_root_mutex);
|
||||
for (int i = 0; i < g_n_proc_root_fds; i++) {
|
||||
if (g_proc_root_fds[i].fd == oldfd) entry = g_proc_root_fds[i];
|
||||
}
|
||||
pthread_mutex_unlock(&g_proc_root_mutex);
|
||||
if (entry.fd < 0) return;
|
||||
entry.fd = newfd;
|
||||
store_proc_root_fd(entry);
|
||||
}
|
||||
|
||||
static void remember_proc_root_fd(int fd, const char *path) {
|
||||
const char *rest = NULL;
|
||||
pid_t pid = proc_root_pid(path, &rest);
|
||||
struct stat st;
|
||||
if (fd < 0) return;
|
||||
if (pid <= 0 || rest[strspn(rest, "/")] != '\0' || syscall(SYS_fstat, fd, &st) != 0 || !S_ISDIR(st.st_mode)) {
|
||||
forget_proc_root_fd(fd);
|
||||
return;
|
||||
}
|
||||
store_proc_root_fd((struct ddnatv_proc_root_fd){fd, pid, (unsigned long)st.st_dev, (unsigned long)st.st_ino});
|
||||
}
|
||||
|
||||
static const char *proc_root_at(int dirfd, const char *rel, char *buf, size_t size) {
|
||||
if (dirfd < 0 || __atomic_load_n(&g_n_proc_root_fds, __ATOMIC_ACQUIRE) == 0) return NULL;
|
||||
pid_t pid = 0;
|
||||
unsigned long dev = 0, ino = 0;
|
||||
pthread_mutex_lock(&g_proc_root_mutex);
|
||||
for (int i = 0; i < g_n_proc_root_fds; i++) {
|
||||
if (g_proc_root_fds[i].fd != dirfd) continue;
|
||||
pid = g_proc_root_fds[i].pid;
|
||||
dev = g_proc_root_fds[i].dev;
|
||||
ino = g_proc_root_fds[i].ino;
|
||||
break;
|
||||
}
|
||||
pthread_mutex_unlock(&g_proc_root_mutex);
|
||||
struct stat st;
|
||||
if (pid <= 0 || syscall(SYS_fstat, dirfd, &st) != 0 || (unsigned long)st.st_dev != dev || (unsigned long)st.st_ino != ino) return NULL;
|
||||
if (snprintf(buf, size, "/proc/%d/root/%s", (int)pid, rel) >= (int)size) return NULL;
|
||||
return buf;
|
||||
}
|
||||
|
||||
static int is_loader_option(const char *arg) {
|
||||
return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0;
|
||||
}
|
||||
@@ -475,6 +757,10 @@ static const char *rewrite_path_follow(const char *path, char *buffer, size_t bu
|
||||
if (!path) return NULL;
|
||||
if (path[0] != '/') return rewrite_path(path, buffer, bufsize);
|
||||
init_ddnatv_hook();
|
||||
if (path[1] == 'p' && strncmp(path, "/proc/", 6) == 0 && path[6] >= '1' && path[6] <= '9') {
|
||||
const char *other = proc_root_host(path, buffer, bufsize, 0, 1);
|
||||
if (other) return other;
|
||||
}
|
||||
int moved = 0;
|
||||
for (int i = 0; i < g_nbinds; i++) {
|
||||
const struct ddnatv_bind *b = &g_binds[i];
|
||||
|
||||
@@ -376,6 +376,134 @@ class DriveTest(Temp):
|
||||
self.assertEqual(os.readlink(self.devices / "d:"), str(self.card))
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
|
||||
def test_the_volume_holding_the_native_rootfs_gets_no_drive(self):
|
||||
rootfs = self.card / "files/linuxfs"
|
||||
library = rootfs / "root/Games/Stores/Battle.net"
|
||||
library.mkdir(parents=True)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.assertEqual(BNET["install_path"](self.root, str(library)), "Z:/root/Games/Stores/Battle.net")
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library))
|
||||
self.assertFalse(self.devices.exists())
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
|
||||
|
||||
def test_games_moved_to_a_drive_holding_the_native_rootfs_go_back_to_the_root_drive(self):
|
||||
rootfs = self.card / "files/linuxfs"
|
||||
game = rootfs / "root/Games/Stores/Battle.net/World of Warcraft"
|
||||
game.mkdir(parents=True)
|
||||
card = self.tmp / "sd"
|
||||
(card / "Diablo").mkdir(parents=True)
|
||||
self.devices.mkdir(parents=True)
|
||||
os.symlink(str(self.card), self.devices / "d:")
|
||||
os.symlink(str(card), self.devices / "e:")
|
||||
client = self.product("battle.net", "C:/Program Files (x86)/Battle.net")
|
||||
sd = self.product("d3", "E:/Diablo")
|
||||
gone = self.product("gone", "D:/files/linuxfs/root/Games/Missing")
|
||||
path = self.database(client, self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"), sd, gone)
|
||||
before = path.read_bytes()
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
self.assertEqual(path.read_bytes(), before)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
self.assertEqual(path.read_bytes(), client + self.product("wowf", "Z:/root/Games/Stores/Battle.net/World of Warcraft")
|
||||
+ sd + gone + self.field(7, b"tail"))
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
|
||||
def rootfs_prefix(self):
|
||||
rootfs = self.card / "files/linuxfs"
|
||||
game = rootfs / "root/Games/Stores/Battle.net/World of Warcraft"
|
||||
game.mkdir(parents=True)
|
||||
card = self.tmp / "sd"
|
||||
card.mkdir()
|
||||
self.devices.mkdir(parents=True)
|
||||
for letter, target in (("d", self.card), ("e", card), ("s", self.card)):
|
||||
os.symlink(str(target), self.devices / (letter + ":"))
|
||||
pfx = self.devices.parent
|
||||
system = pfx / "system.reg"
|
||||
system.write_text('[Software\\\\Uninstall\\\\wow] 1\n'
|
||||
'"InstallLocation"="D:\\\\files\\\\linuxfs\\\\root\\\\Games\\\\Stores\\\\Battle.net\\\\World of Warcraft"\n'
|
||||
'"DisplayIcon"="\\"d:\\\\files\\\\linuxfs\\\\root\\\\Games\\\\Wow.exe\\""\n'
|
||||
'"Card"="E:\\\\Diablo"\n"Other"="AD:\\\\files\\\\linuxfs\\\\x"\n')
|
||||
system.chmod(0o640)
|
||||
config = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"Client": {"Install": {"DefaultInstallPath": "D:\\files\\linuxfs\\root\\Games\\Stores\\Battle.net"}}}))
|
||||
self.database(self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"))
|
||||
return rootfs, system, config
|
||||
|
||||
def test_an_unused_drive_holding_the_native_rootfs_is_removed_once_its_paths_use_the_root_drive(self):
|
||||
rootfs, system, config = self.rootfs_prefix()
|
||||
before = system.read_text()
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertEqual(system.read_text(), before)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.running = [(5, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])]
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.running = []
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), ["d"])
|
||||
self.assertEqual(sorted(os.listdir(self.devices)), ["e:", "s:"])
|
||||
self.assertEqual(system.read_text(), before.replace("D:\\\\files\\\\linuxfs\\\\root", "Z:\\\\root")
|
||||
.replace("d:\\\\files\\\\linuxfs\\\\root", "Z:\\\\root"))
|
||||
self.assertEqual(system.stat().st_mode & 0o777, 0o640)
|
||||
self.assertEqual(json.loads(config.read_text())["Client"]["Install"]["DefaultInstallPath"], "Z:\\root\\Games\\Stores\\Battle.net")
|
||||
self.assertTrue(self.card.is_dir())
|
||||
self.assertTrue((rootfs / "root/Games/Stores/Battle.net/World of Warcraft").is_dir())
|
||||
|
||||
def test_a_drive_holding_the_native_rootfs_stays_while_a_path_outside_the_runtime_uses_it(self):
|
||||
rootfs, system, _ = self.rootfs_prefix()
|
||||
system.write_text(system.read_text() + '"Elsewhere"="D:\\\\Other\\\\Game"\n')
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
self.assertIn('"InstallLocation"="Z:\\\\root\\\\Games', system.read_text())
|
||||
self.assertIn('"Elsewhere"="D:\\\\Other\\\\Game"', system.read_text())
|
||||
|
||||
def test_a_drive_holding_the_native_rootfs_stays_while_a_game_outside_the_runtime_is_installed_on_it(self):
|
||||
rootfs, _, _ = self.rootfs_prefix()
|
||||
for folder in ("D:/Other/" + "x" * 40, "D:\\Other\\" + "x" * 39, " D:/Other/" + "x" * 39):
|
||||
with self.subTest(folder=folder):
|
||||
self.database(self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"),
|
||||
self.product("other", folder))
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
BNET["move_installs"](self.root)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
|
||||
def test_a_path_that_climbs_out_of_the_runtime_keeps_its_drive(self):
|
||||
rootfs, system, _ = self.rootfs_prefix()
|
||||
up = '"Up"="D:\\\\files\\\\linuxfs\\\\root\\\\..\\\\..\\\\Other"\n'
|
||||
system.write_text(system.read_text() + up)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
BNET["move_installs"](self.root)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
self.assertIn(up, system.read_text())
|
||||
self.assertIn('"InstallLocation"="Z:\\\\root\\\\Games', system.read_text())
|
||||
|
||||
def test_a_config_path_with_escaped_characters_keeps_its_drive(self):
|
||||
rootfs, _, config = self.rootfs_prefix()
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
BNET["move_installs"](self.root)
|
||||
settings = config.read_text()
|
||||
for text in (settings[:-1] + ', "Other": "D:\\/Other\\/Game"}', settings[:-1] + ', "Other": "D\\u003a/Other/Game"}', '{"Client": '):
|
||||
with self.subTest(text=text):
|
||||
config.write_text(text)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
config.write_text(settings)
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), ["d"])
|
||||
|
||||
def test_an_unreadable_database_keeps_the_drive(self):
|
||||
rootfs, _, _ = self.rootfs_prefix()
|
||||
path = Path(BNET["drive_c"](self.root)) / "ProgramData/Battle.net/Agent/product.db"
|
||||
path.write_bytes(b"\x0a\xff")
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
|
||||
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
|
||||
self.assertTrue(os.path.islink(self.devices / "d:"))
|
||||
|
||||
def test_registrations_stay_while_the_prefix_runs_or_the_database_is_unreadable(self):
|
||||
game = self.library / "World of Warcraft"
|
||||
game.mkdir()
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
|
||||
|
||||
PROBE = """
|
||||
import json, os
|
||||
print(json.dumps({"pid": os.getpid(), "binds": os.environ.get("DDNATV_BINDS")}))
|
||||
"""
|
||||
|
||||
INFO = b"[Application]\nname=org.example.App\n\n[Instance]\ninstance-id=42\n"
|
||||
|
||||
|
||||
class BwrapFlatpakInfoInPlaceTest(unittest.TestCase):
|
||||
def run_shim(self, env):
|
||||
read, write = os.pipe()
|
||||
os.write(write, INFO)
|
||||
os.close(write)
|
||||
self.addCleanup(os.close, read)
|
||||
full = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
|
||||
full.update(env)
|
||||
out = subprocess.run([sys.executable, str(BWRAP), "--ro-bind-data", str(read), "/.flatpak-info", "--",
|
||||
sys.executable, "-c", PROBE], env=full, pass_fds=(read,), capture_output=True,
|
||||
text=True, timeout=30)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return json.loads(out.stdout)
|
||||
|
||||
def file_bind(self, binds, pid):
|
||||
entries = [e for e in (binds or "").split("|") if e.endswith(":/.flatpak-info")]
|
||||
self.assertEqual(1, len(entries))
|
||||
src = entries[0][:-len(":/.flatpak-info")]
|
||||
self.assertTrue(src.startswith("/proc/%d/fd/" % pid), src)
|
||||
return src
|
||||
|
||||
def test_a_native_program_run_in_place_sees_its_flatpak_info(self):
|
||||
got = self.run_shim({"DDNATV_ROOT": "/data/rootfs"})
|
||||
self.file_bind(got["binds"], got["pid"])
|
||||
self.assertEqual(1, len(got["binds"].split("|")))
|
||||
|
||||
def test_the_session_binds_are_kept_in_front(self):
|
||||
got = self.run_shim({"DDNATV_ROOT": "/data/rootfs", "DDNATV_BINDS": "/proc:/proc|/sdcard:/media/sdcard"})
|
||||
self.file_bind(got["binds"], got["pid"])
|
||||
self.assertEqual(["/proc:/proc", "/sdcard:/media/sdcard"], got["binds"].split("|")[:2])
|
||||
|
||||
def test_the_bound_file_holds_the_data_and_outlives_exec(self):
|
||||
script = (
|
||||
"import os, sys; b = os.environ['DDNATV_BINDS'].split('|')[-1].split(':')[0]; "
|
||||
"sys.stdout.write(open(b.replace('/proc/%d/' % os.getpid(), '/proc/self/')).read())"
|
||||
)
|
||||
read, write = os.pipe()
|
||||
os.write(write, INFO)
|
||||
os.close(write)
|
||||
self.addCleanup(os.close, read)
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
|
||||
env["DDNATV_ROOT"] = "/data/rootfs"
|
||||
out = subprocess.run([sys.executable, str(BWRAP), "--ro-bind-data", str(read), "/.flatpak-info", "--",
|
||||
sys.executable, "-c", script], env=env, pass_fds=(read,), capture_output=True,
|
||||
timeout=30)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual(INFO, out.stdout)
|
||||
|
||||
def test_without_the_native_hook_nothing_is_added(self):
|
||||
got = self.run_shim({})
|
||||
self.assertIsNone(got["binds"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,226 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import secrets
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
printf("env\t%s\n", getenv("DROIDDECK_FDS") ? "set" : "-");
|
||||
for (int i = 1; i < argc; i++) {
|
||||
int fd = atoi(argv[i]);
|
||||
char buf[64];
|
||||
int flags = fcntl(fd, F_GETFD);
|
||||
ssize_t n = flags < 0 ? -1 : read(fd, buf, sizeof(buf) - 1);
|
||||
buf[n > 0 ? n : 0] = 0;
|
||||
printf("%d\t%s\t%s\n", fd, n > 0 ? buf : "-", flags < 0 ? "closed" : flags & FD_CLOEXEC ? "cloexec" : "kept");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def pipe_holding(data):
|
||||
read, write = os.pipe()
|
||||
os.write(write, data)
|
||||
os.close(write)
|
||||
return read
|
||||
|
||||
|
||||
def serve(listener, fds, targets):
|
||||
conn, _ = listener.accept()
|
||||
with conn, listener:
|
||||
conn.sendmsg([",".join(map(str, targets)).encode()],
|
||||
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, struct.pack("%di" % len(fds), *fds))])
|
||||
|
||||
|
||||
class FakeApp:
|
||||
def __init__(self, test, launch):
|
||||
self.name = "droiddeck-test-" + secrets.token_hex(8)
|
||||
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.listener.bind("\0" + self.name)
|
||||
self.listener.listen(1)
|
||||
self.launch = launch
|
||||
self.request = None
|
||||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||||
self.thread.start()
|
||||
test.addCleanup(self.listener.close)
|
||||
|
||||
def run(self):
|
||||
conn, _ = self.listener.accept()
|
||||
with conn:
|
||||
head = conn.recv(5, socket.MSG_WAITALL)
|
||||
body = conn.recv(struct.unpack(">I", head[1:])[0], socket.MSG_WAITALL)
|
||||
self.request = json.loads(body)
|
||||
output, status = self.launch(self.request)
|
||||
for kind, payload in ((b"O", output), (b"X", str(status).encode())):
|
||||
conn.sendall(kind + struct.pack(">I", len(payload)) + payload)
|
||||
|
||||
|
||||
def fetch(name):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn:
|
||||
conn.connect("\0" + name)
|
||||
text, fds, _, _ = socket.recv_fds(conn, 1024, 16)
|
||||
try:
|
||||
return text.decode(), [os.read(fd, 64) for fd in fds]
|
||||
finally:
|
||||
for fd in fds:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
class BwrapForwardsFdsTest(unittest.TestCase):
|
||||
def run_shim(self, launch, extra, pass_fds):
|
||||
app = FakeApp(self, launch)
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
|
||||
env["DROIDDECK_BWRAP_SOCKET"] = app.name
|
||||
work = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(work.cleanup)
|
||||
out = subprocess.run([sys.executable, str(BWRAP), "--bind", work.name, "/mnt/elsewhere", *extra, "--",
|
||||
"/nonexistent/program"], env=env, pass_fds=pass_fds, capture_output=True, timeout=30)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return app.request, out.stdout
|
||||
|
||||
def test_inherited_fds_are_offered_to_the_sandboxed_program(self):
|
||||
forwarded = pipe_holding(b"dbus peer")
|
||||
sync = pipe_holding(b"sync")
|
||||
self.addCleanup(os.close, forwarded)
|
||||
self.addCleanup(os.close, sync)
|
||||
got = {}
|
||||
|
||||
def launch(request):
|
||||
got.update(zip(("targets", "data"), fetch(request["env"]["DROIDDECK_FDS"])))
|
||||
return b"", 0
|
||||
|
||||
request, _ = self.run_shim(launch, ["--sync-fd", str(sync)], (forwarded, sync))
|
||||
self.assertEqual(str(forwarded), got["targets"])
|
||||
self.assertEqual([b"dbus peer"], got["data"])
|
||||
|
||||
def test_the_offer_is_taken_once(self):
|
||||
forwarded = pipe_holding(b"once")
|
||||
self.addCleanup(os.close, forwarded)
|
||||
second = []
|
||||
|
||||
def launch(request):
|
||||
fetch(request["env"]["DROIDDECK_FDS"])
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn:
|
||||
try:
|
||||
conn.connect("\0" + request["env"]["DROIDDECK_FDS"])
|
||||
second.append("connected")
|
||||
except OSError:
|
||||
second.append("refused")
|
||||
return b"", 0
|
||||
|
||||
self.run_shim(launch, [], (forwarded,))
|
||||
self.assertEqual(["refused"], second)
|
||||
|
||||
def test_more_descriptors_than_can_be_passed_stop_the_launch(self):
|
||||
fds = [pipe_holding(b"x") for _ in range(254)]
|
||||
for fd in fds:
|
||||
self.addCleanup(os.close, fd)
|
||||
app = FakeApp(self, lambda request: (b"", 0))
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
|
||||
env["DROIDDECK_BWRAP_SOCKET"] = app.name
|
||||
work = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(work.cleanup)
|
||||
out = subprocess.run([sys.executable, str(BWRAP), "--bind", work.name, "/mnt/elsewhere", "--",
|
||||
"/nonexistent/program"], env=env, pass_fds=fds, capture_output=True, timeout=30)
|
||||
self.assertNotEqual(0, out.returncode)
|
||||
self.assertIn(b"Too many inherited file descriptors", out.stderr)
|
||||
self.assertIsNone(app.request)
|
||||
|
||||
def test_nothing_is_offered_without_inherited_fds(self):
|
||||
request, _ = self.run_shim(lambda request: (b"", 0), [], ())
|
||||
self.assertNotIn("DROIDDECK_FDS", request["env"])
|
||||
|
||||
|
||||
class NativeHookAdoptsFdsTest(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 / "probe.c").write_text(PROBE)
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
|
||||
cls.probe_path = tmp / "probe"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def offer(self, fds, targets):
|
||||
name = "droiddeck-test-" + secrets.token_hex(8)
|
||||
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
listener.bind("\0" + name)
|
||||
listener.listen(1)
|
||||
listener.settimeout(60)
|
||||
threading.Thread(target=serve, args=(listener, fds, targets), daemon=True).start()
|
||||
self.addCleanup(listener.close)
|
||||
return name
|
||||
|
||||
def run_probe(self, name, *wanted, fd_limit=None):
|
||||
hook_env = {"DROIDDECK_FDS": name, "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD" and not k.startswith("DDNATV_")}
|
||||
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)
|
||||
limit = (lambda: resource.setrlimit(resource.RLIMIT_NOFILE, (fd_limit, fd_limit))) if fd_limit else None
|
||||
out = subprocess.run(cmd + [str(self.probe_path), *map(str, wanted)], env=env, capture_output=True,
|
||||
text=True, timeout=120, preexec_fn=limit)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def held(self, *data):
|
||||
fds = [pipe_holding(d) for d in data]
|
||||
for fd in fds:
|
||||
self.addCleanup(os.close, fd)
|
||||
return fds
|
||||
|
||||
def test_forwarded_fds_land_on_their_numbers_and_stay_inheritable(self):
|
||||
fds = self.held(b"peer", b"sync")
|
||||
got = self.run_probe(self.offer(fds, [22, 5]), 22, 5)
|
||||
self.assertEqual(["peer", "kept"], got["22"])
|
||||
self.assertEqual(["sync", "kept"], got["5"])
|
||||
self.assertEqual(["-"], got["env"])
|
||||
|
||||
def test_targets_that_overlap_the_received_numbers_are_not_mixed_up(self):
|
||||
fds = self.held(b"first", b"second")
|
||||
got = self.run_probe(self.offer(fds, [4, 3]), 4, 3)
|
||||
self.assertEqual("first", got["4"][0])
|
||||
self.assertEqual("second", got["3"][0])
|
||||
|
||||
def test_a_target_at_the_descriptor_limit_is_installed(self):
|
||||
fds = self.held(b"edge")
|
||||
got = self.run_probe(self.offer(fds, [255]), 255, fd_limit=256)
|
||||
self.assertEqual(["edge", "kept"], got["255"])
|
||||
|
||||
def test_a_missing_offer_changes_nothing(self):
|
||||
got = self.run_probe("droiddeck-test-gone-" + secrets.token_hex(4), 22)
|
||||
self.assertEqual(["-", "closed"], got["22"])
|
||||
self.assertEqual(["-"], got["env"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,110 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DESKTOP = (ROOT / 'linuxfs/desktop/droiddeck-desktop').read_text()
|
||||
OVERLAY_LAYOUT = (ROOT / 'ubuntu/overlay-desktop/usr/share/plasma/look-and-feel/com.valve.vapor.desktop'
|
||||
'/contents/layouts/org.kde.plasma.desktop-layout.js').read_text()
|
||||
LAYOUT_DIR = '/usr/share/plasma/look-and-feel/com.valve.vapor.desktop/contents/layouts'
|
||||
RC = 'plasma-org.kde.plasma.desktop-appletsrc'
|
||||
STAMP = 'droiddeck-panel-layout'
|
||||
|
||||
|
||||
def block(first, last):
|
||||
start = DESKTOP.index(first)
|
||||
return DESKTOP[start:DESKTOP.index(last, start) + len(last)]
|
||||
|
||||
|
||||
def run(script, home):
|
||||
environment = {key: value for key, value in os.environ.items() if key != 'XDG_CONFIG_HOME'}
|
||||
environment['HOME'] = str(home)
|
||||
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, text=True, timeout=5)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(result.stderr)
|
||||
|
||||
|
||||
class DesktopSteamosPanelTest(unittest.TestCase):
|
||||
def reset(self, home, panel=None, stamp=None):
|
||||
config = home / '.config'
|
||||
config.mkdir()
|
||||
if panel is not None:
|
||||
(config / RC).write_text(panel)
|
||||
if stamp is not None:
|
||||
(config / STAMP).write_text(stamp)
|
||||
run(block('dd_panel_rc=', '\nfi\n'), home)
|
||||
return config
|
||||
|
||||
def test_an_older_panel_is_set_aside_once_so_plasma_lays_out_the_current_one(self):
|
||||
for panel in ('icon=start-here-kubuntu\n', 'icon=distributor-logo-steamdeck\n'):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
config = self.reset(Path(home), panel)
|
||||
self.assertFalse((config / RC).exists())
|
||||
self.assertEqual(panel, (config / (RC + '.before-steamos-2')).read_text())
|
||||
self.assertEqual('steamos-2', (config / STAMP).read_text().strip())
|
||||
|
||||
def test_an_earlier_backup_is_never_overwritten(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
config = Path(home) / '.config'
|
||||
config.mkdir()
|
||||
(config / (RC + '.before-steamos-2')).write_text('original backup')
|
||||
(config / RC).write_text('icon=start-here-kubuntu\n')
|
||||
run(block('dd_panel_rc=', '\nfi\n'), Path(home))
|
||||
self.assertEqual('original backup', (config / (RC + '.before-steamos-2')).read_text())
|
||||
self.assertFalse((config / RC).exists())
|
||||
self.assertEqual(1, len([entry for entry in config.iterdir() if entry.name.startswith(RC + '.before-steamos-2.')]))
|
||||
self.assertEqual('steamos-2', (config / STAMP).read_text().strip())
|
||||
|
||||
def test_the_stamp_is_not_written_when_the_panel_could_not_be_moved(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
config = Path(home) / '.config'
|
||||
config.mkdir()
|
||||
(config / RC).write_text('icon=start-here-kubuntu\n')
|
||||
script = block('dd_panel_rc=', '\nfi\n').replace('mv "$dd_panel_rc"', 'false "$dd_panel_rc"')
|
||||
run(script, Path(home))
|
||||
self.assertTrue((config / RC).exists())
|
||||
self.assertFalse((config / STAMP).exists())
|
||||
|
||||
def test_a_panel_laid_out_by_this_version_is_left_alone(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
config = self.reset(Path(home), 'icon=my-logo\n', 'steamos-2\n')
|
||||
self.assertEqual('icon=my-logo\n', (config / RC).read_text())
|
||||
self.assertFalse((config / (RC + '.before-steamos-2')).exists())
|
||||
|
||||
def test_a_profile_without_a_panel_only_gets_the_stamp(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
config = self.reset(Path(home))
|
||||
self.assertEqual([STAMP], [entry.name for entry in config.iterdir()])
|
||||
|
||||
def test_the_layout_written_at_each_start_is_the_overlays(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
target = Path(home) / 'layouts'
|
||||
target.mkdir()
|
||||
run(block('dd_layout=', '\nfi\n').replace(LAYOUT_DIR, target.as_posix()), home)
|
||||
written = (target / 'org.kde.plasma.desktop-layout.js').read_text()
|
||||
self.assertEqual(OVERLAY_LAYOUT.replace('\r\n', '\n').rstrip('\n'), written.rstrip('\n'))
|
||||
|
||||
def test_the_layout_follows_plasmas_stock_panel_with_the_steam_deck_launcher(self):
|
||||
for widget in ('kickoff', 'pager', 'icontasks', 'marginsseparator', 'systemtray', 'digitalclock', 'showdesktop'):
|
||||
self.assertIn('org.kde.plasma.' + widget, OVERLAY_LAYOUT)
|
||||
self.assertIn('distributor-logo-steamdeck', OVERLAY_LAYOUT)
|
||||
for pin in ('steamdeck-steam', 'systemsettings', 'org.kde.discover', 'preferred://filemanager', 'preferred://browser'):
|
||||
self.assertIn(pin, OVERLAY_LAYOUT)
|
||||
|
||||
def test_the_layout_keeps_plasmas_stock_wide_screen_cap_and_input_method_panel(self):
|
||||
self.assertIn('const maximumAspectRatio = 21 / 9;', OVERLAY_LAYOUT)
|
||||
self.assertIn('panel.maximumLength = maximumWidth;', OVERLAY_LAYOUT)
|
||||
self.assertIn('org.kde.plasma.kimpanel', OVERLAY_LAYOUT)
|
||||
for language in ('ja', 'ko', 'th', 'zh_CN', 'zh_TW', 'hi'):
|
||||
self.assertIn('"' + language + '"', OVERLAY_LAYOUT)
|
||||
|
||||
def test_the_panel_is_prepared_before_plasma_starts(self):
|
||||
for marker in ('dd_layout=', 'dd_panel_rc='):
|
||||
self.assertLess(DESKTOP.index(marker), DESKTOP.index('dbus-run-session -- startplasma-wayland'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,205 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gio", "2.0")
|
||||
from gi.repository import Gio, GLib
|
||||
except ImportError:
|
||||
Gio = GLib = None
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-documents"
|
||||
NAME = "org.freedesktop.portal.Documents"
|
||||
PATH = "/org/freedesktop/portal/documents"
|
||||
REUSE_EXISTING = 1
|
||||
PERSISTENT = 2
|
||||
AS_NEEDED_BY_APP = 4
|
||||
DIRECTORY = 8
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class DocumentStoreTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.dir = Path(self.directory.name)
|
||||
self.file = self.dir / "picked.iso"
|
||||
self.file.write_text("data")
|
||||
self.proc = self.dir / "proc"
|
||||
self.sandbox = self.dir / "sandbox"
|
||||
(self.proc / "1234").mkdir(parents=True)
|
||||
(self.sandbox / self.dir.relative_to("/")).mkdir(parents=True)
|
||||
(self.sandbox / ".flatpak-info").write_text("[Application]\nname=org.example.App\n")
|
||||
(self.proc / "1234/root").symlink_to(self.sandbox)
|
||||
self.visible = self.share(self.file)
|
||||
self.saves = self.dir / "saves"
|
||||
self.saves.mkdir()
|
||||
(self.sandbox / self.saves.relative_to("/")).symlink_to(self.saves)
|
||||
self.bus = Gio.DBusConnection.new_for_address_sync(
|
||||
os.environ["DBUS_SESSION_BUS_ADDRESS"],
|
||||
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
|
||||
None, None)
|
||||
self.alias = self.dir / "alias"
|
||||
self.shared = self.dir / "shared"
|
||||
self.alias.mkdir()
|
||||
(self.alias / "game.iso").write_text("data")
|
||||
self.share(self.alias / "game.iso", self.shared / "game.iso")
|
||||
(self.alias / "inside.iso").write_text("data")
|
||||
self.share(self.alias / "inside.iso")
|
||||
(self.alias / "private.iso").write_text("data")
|
||||
(self.dir / "rootfs").mkdir()
|
||||
self.share(self.alias / "private.iso", self.dir / "rootfs/alias/private.iso")
|
||||
env = dict(os.environ, DDNATV_ROOT=str(self.dir / "rootfs"),
|
||||
DDNATV_BINDS="%s:%s|%s/rootfs/alias:%s" % (self.shared, self.alias, self.dir, self.alias))
|
||||
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT), str(self.proc)], stdout=subprocess.DEVNULL,
|
||||
env=env)
|
||||
self.session = self.dir / "session"
|
||||
(self.session / self.dir.relative_to("/")).mkdir(parents=True)
|
||||
(self.dir / "hidden.iso").write_text("data")
|
||||
os.link(self.dir / "hidden.iso", self.session / self.dir.relative_to("/") / "hidden.iso")
|
||||
(self.session / ".flatpak-info").write_text("[Application]\nname=org.example.App\n")
|
||||
for pid in (self.process.pid, 99):
|
||||
(self.proc / str(pid)).mkdir()
|
||||
(self.proc / str(pid) / "root").symlink_to(self.session)
|
||||
deadline = time.monotonic() + 10
|
||||
while not self.owned():
|
||||
self.assertIsNone(self.process.poll())
|
||||
self.assertLess(time.monotonic(), deadline)
|
||||
time.sleep(0.05)
|
||||
|
||||
def share(self, source, name=None):
|
||||
seen = self.sandbox / (name or source).relative_to("/")
|
||||
seen.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.link(source, seen)
|
||||
return seen
|
||||
|
||||
def tearDown(self):
|
||||
self.process.terminate()
|
||||
self.process.wait(timeout=5)
|
||||
self.bus.close_sync(None)
|
||||
self.directory.cleanup()
|
||||
|
||||
def owned(self):
|
||||
reply = self.bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
|
||||
"NameHasOwner", GLib.Variant("(s)", (NAME,)), None,
|
||||
Gio.DBusCallFlags.NONE, -1, None)
|
||||
return reply.unpack()[0]
|
||||
|
||||
def call(self, method, signature, args, paths=()):
|
||||
fds = Gio.UnixFDList.new()
|
||||
opened = [os.open(p, os.O_PATH | os.O_CLOEXEC) for p in paths]
|
||||
try:
|
||||
for fd in opened:
|
||||
fds.append(fd)
|
||||
reply, _ = self.bus.call_with_unix_fd_list_sync(
|
||||
NAME, PATH, NAME, method, GLib.Variant(signature, args), None, Gio.DBusCallFlags.NONE, -1,
|
||||
fds, None)
|
||||
return reply.unpack()
|
||||
finally:
|
||||
for fd in opened:
|
||||
os.close(fd)
|
||||
|
||||
def error_of(self, *args, **kwargs):
|
||||
with self.assertRaises(GLib.Error) as caught:
|
||||
self.call(*args, **kwargs)
|
||||
return Gio.DBusError.get_remote_error(caught.exception)
|
||||
|
||||
def test_a_picked_file_is_handed_back_in_place(self):
|
||||
got = self.call("AddFull", "(ahusas)", ([0], REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP, "org.example.App",
|
||||
["read", "write"]), [self.file])
|
||||
self.assertEqual(([""], {}), got)
|
||||
|
||||
def test_a_saved_file_name_is_handed_back_in_place(self):
|
||||
got = self.call("AddNamedFull", "(hayusas)", (0, b"new.txt\0", AS_NEEDED_BY_APP, "org.example.App", ["read"]),
|
||||
[self.saves])
|
||||
self.assertEqual(("", {}), got)
|
||||
|
||||
def test_a_picked_folder_needs_the_directory_flag(self):
|
||||
flags = REUSE_EXISTING | AS_NEEDED_BY_APP
|
||||
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags | DIRECTORY, "", []), [self.dir]))
|
||||
self.assertEqual("org.freedesktop.portal.Error.InvalidArgument",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "", []), [self.dir]))
|
||||
self.assertEqual("org.freedesktop.portal.Error.InvalidArgument",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags | DIRECTORY, "", []), [self.file]))
|
||||
|
||||
def test_a_file_the_application_cannot_reach_is_refused(self):
|
||||
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
|
||||
hidden = self.dir / "hidden.iso"
|
||||
self.assertTrue((self.proc / "99/root" / hidden.relative_to("/")).exists())
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [hidden]))
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.Other", ["read"]), [self.file]))
|
||||
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "", ["read"]), [hidden]))
|
||||
|
||||
def test_a_file_seen_through_a_bound_folder_is_found_under_its_host_name(self):
|
||||
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
|
||||
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
|
||||
[self.alias / "game.iso"]))
|
||||
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
|
||||
[self.alias / "inside.iso"]))
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
|
||||
[self.alias / "private.iso"]))
|
||||
(self.sandbox / self.shared.relative_to("/") / "game.iso").unlink()
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
|
||||
[self.alias / "game.iso"]))
|
||||
|
||||
def test_a_file_inside_the_root_filesystem_is_judged_by_its_own_name(self):
|
||||
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
|
||||
home = self.dir / "rootfs/home.iso"
|
||||
home.write_text("data")
|
||||
self.share(home)
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [home]))
|
||||
os.link(home, self.sandbox / "home.iso")
|
||||
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [home]))
|
||||
|
||||
def test_a_different_file_at_the_same_name_is_refused(self):
|
||||
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
|
||||
other = self.dir / "other.iso"
|
||||
other.write_text("data")
|
||||
(self.sandbox / other.relative_to("/")).write_text("data")
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [other]))
|
||||
|
||||
@unittest.skipIf(os.getuid() == 0, "root reads every file")
|
||||
def test_a_location_the_application_cannot_use_as_asked_is_refused(self):
|
||||
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
|
||||
self.visible.chmod(0)
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [self.file]))
|
||||
self.saves.chmod(0o500)
|
||||
try:
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddNamedFull", "(hayusas)",
|
||||
(0, b"new.txt\0", AS_NEEDED_BY_APP, "org.example.App", ["read", "write"]),
|
||||
[self.saves]))
|
||||
finally:
|
||||
self.saves.chmod(0o700)
|
||||
|
||||
def test_documents_that_would_need_the_store_mount_are_refused(self):
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("AddFull", "(ahusas)", ([0], REUSE_EXISTING, "", []), [self.file]))
|
||||
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
|
||||
self.error_of("Add", "(hbb)", (0, True, False), [self.file]))
|
||||
self.assertEqual("org.freedesktop.portal.Error.Failed", self.error_of("GetMountPoint", "()", ()))
|
||||
|
||||
def test_a_missing_descriptor_is_refused(self):
|
||||
self.assertEqual("org.freedesktop.portal.Error.InvalidArgument",
|
||||
self.error_of("AddFull", "(ahusas)", ([3], AS_NEEDED_BY_APP, "", []), [self.file]))
|
||||
|
||||
def test_no_documents_are_listed(self):
|
||||
self.assertEqual(("",), self.call("Lookup", "(ay)", (str(self.file).encode() + b"\0",)))
|
||||
self.assertEqual(({},), self.call("List", "(s)", ("org.example.App",)))
|
||||
version = self.bus.call_sync(NAME, PATH, "org.freedesktop.DBus.Properties", "Get",
|
||||
GLib.Variant("(ss)", (NAME, "version")), None, Gio.DBusCallFlags.NONE, -1, None)
|
||||
self.assertEqual(5, version.unpack()[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,80 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
|
||||
|
||||
LIBRARY = r"""
|
||||
#include <stdatomic.h>
|
||||
#include <sys/statfs.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern _Atomic int loading;
|
||||
|
||||
__attribute__((constructor)) static void start(void) {
|
||||
struct statfs buf;
|
||||
atomic_store_explicit(&loading, 1, memory_order_release);
|
||||
usleep(300000);
|
||||
statfs("/", &buf);
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/statfs.h>
|
||||
|
||||
_Atomic int loading;
|
||||
|
||||
static void *load(void *path) {
|
||||
return dlopen(path, RTLD_NOW);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
pthread_t loader;
|
||||
struct statfs buf;
|
||||
pthread_create(&loader, NULL, load, argv[1]);
|
||||
while (!atomic_load_explicit(&loading, memory_order_acquire)) sched_yield();
|
||||
statfs("/", &buf);
|
||||
void *handle = NULL;
|
||||
pthread_join(loader, &handle);
|
||||
puts(handle ? "ok" : dlerror());
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux" and shutil.which("gcc") and shutil.which("g++"),
|
||||
"needs Linux, gcc and g++")
|
||||
class FakeinputLoaderLockTest(unittest.TestCase):
|
||||
def test_a_first_hooked_call_while_another_thread_loads_a_library_does_not_deadlock(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp)
|
||||
(path / "program.c").write_text(PROGRAM)
|
||||
(path / "library.c").write_text(LIBRARY)
|
||||
subprocess.run(["gcc", "-rdynamic", "-pthread", "-o", str(path / "program"), str(path / "program.c"),
|
||||
"-ldl"], check=True)
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-o", str(path / "library.so"), str(path / "library.c")],
|
||||
check=True)
|
||||
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread",
|
||||
"-std=c++17", "-static-libstdc++", "-static-libgcc",
|
||||
"-Wl,--exclude-libs,ALL", "-o", str(path / "libfakeinput.so"),
|
||||
str(SOURCE), "-ldl"], check=True)
|
||||
for _ in range(5):
|
||||
result = subprocess.run([str(path / "program"), str(path / "library.so")],
|
||||
env=dict(os.environ, LD_PRELOAD=str(path / "libfakeinput.so")),
|
||||
capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "ok\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,5 @@
|
||||
import contextlib
|
||||
import fcntl
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
@@ -7,9 +8,11 @@ import shutil
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shlex
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from unittest import mock
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
@@ -3727,6 +3730,161 @@ class ForeignSystemDllTest(unittest.TestCase):
|
||||
self.assertEqual([], self.run_repair(Path(tmp) / "missing", proton))
|
||||
|
||||
|
||||
class SharedDataHealTest(unittest.TestCase):
|
||||
CURRENT = (21, 0x1234abcd, 0x5678ef01, os.getuid(), 1000)
|
||||
STALE = (21, 0x0badf00d, 0x0ddba11, 10122, 1000)
|
||||
|
||||
def setUp(self):
|
||||
self.globals = MODULE["heal_shared_data"].__globals__
|
||||
self.old_machine_id = self.globals["MACHINE_ID"]
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.cleanup)
|
||||
machine_id = Path(self.tmp.name) / "machine-id"
|
||||
machine_id.write_text("1234abcd5678ef01%s\n" % ("0" * 16))
|
||||
self.globals["MACHINE_ID"] = str(machine_id)
|
||||
self.compat = Path(self.tmp.name) / "compat"
|
||||
self.root = self.compat / "pfx/drive_c/ProgramData"
|
||||
self.root.mkdir(parents=True)
|
||||
probe = self.root / "probe"
|
||||
probe.write_text("")
|
||||
try:
|
||||
os.setxattr(probe, "user.wine.sd", b"x")
|
||||
except OSError:
|
||||
self.skipTest("needs user xattrs")
|
||||
probe.unlink()
|
||||
|
||||
def cleanup(self):
|
||||
self.globals["MACHINE_ID"] = self.old_machine_id
|
||||
for folder, dirs, files in os.walk(self.tmp.name):
|
||||
for name in dirs + files:
|
||||
path = os.path.join(folder, name)
|
||||
if not os.path.islink(path):
|
||||
os.chmod(path, 0o700)
|
||||
self.tmp.cleanup()
|
||||
|
||||
def own(self, path, subs, authority=5):
|
||||
sid = bytes([1, len(subs)]) + authority.to_bytes(6, "big") + struct.pack("<%dI" % len(subs), *subs)
|
||||
header = struct.pack("<BBHIIII", 1, 0, 0x8004, len(sid), 0, 0, 0)
|
||||
os.setxattr(path, "user.wine.sd", b"\x01\x00" + header + sid, follow_symlinks=False)
|
||||
|
||||
def heal(self):
|
||||
return MODULE["heal_shared_data"](str(self.compat))
|
||||
|
||||
def mode(self, path):
|
||||
return path.stat().st_mode & 0o777
|
||||
|
||||
def test_entries_a_stale_owner_locked_are_unlocked_and_every_stale_owner_is_cleared(self):
|
||||
agent = self.root / "Vendor/Agent"
|
||||
(agent / "Logs").mkdir(parents=True)
|
||||
(agent / "Agent.dat").write_text("1")
|
||||
(agent / "Tools.exe").write_text("x")
|
||||
(agent / "Icons").mkdir()
|
||||
for path in (agent.parent, agent, agent / "Logs", agent / "Agent.dat", agent / "Tools.exe", agent / "Icons"):
|
||||
self.own(path, self.STALE)
|
||||
(agent / "Tools.exe").chmod(0o550)
|
||||
(agent / "Icons").chmod(0o500)
|
||||
(agent / "Agent.dat").chmod(0)
|
||||
(agent / "Logs").chmod(0)
|
||||
agent.chmod(0)
|
||||
self.assertEqual((["Vendor/Agent", "Vendor/Agent/Agent.dat", "Vendor/Agent/Logs"],
|
||||
["Vendor", "Vendor/Agent", "Vendor/Agent/Agent.dat", "Vendor/Agent/Icons",
|
||||
"Vendor/Agent/Logs", "Vendor/Agent/Tools.exe"]), self.heal())
|
||||
self.assertEqual(0o500, self.mode(agent / "Icons"))
|
||||
self.assertEqual(0o700, self.mode(agent))
|
||||
self.assertEqual(0o700, self.mode(agent / "Logs"))
|
||||
self.assertEqual(0o600, self.mode(agent / "Agent.dat"))
|
||||
self.assertEqual(0o550, self.mode(agent / "Tools.exe"))
|
||||
self.assertEqual("1", (agent / "Agent.dat").read_text())
|
||||
(agent / "Logs/new").mkdir()
|
||||
for path in (agent.parent, agent, agent / "Logs", agent / "Agent.dat", agent / "Tools.exe", agent / "Icons"):
|
||||
self.assertNotIn("user.wine.sd", os.listxattr(path))
|
||||
self.assertEqual(([], []), self.heal())
|
||||
|
||||
def test_current_and_well_known_owners_untagged_entries_and_links_are_left_alone(self):
|
||||
mine = self.root / "Mine"
|
||||
mine.mkdir(mode=0o755)
|
||||
self.own(mine, self.CURRENT)
|
||||
(mine / "settings.ini").write_text("x")
|
||||
self.own(mine / "settings.ini", self.CURRENT)
|
||||
(mine / "settings.ini").chmod(0o444)
|
||||
denied = self.root / "Denied"
|
||||
denied.mkdir()
|
||||
self.own(denied, self.CURRENT)
|
||||
denied.chmod(0)
|
||||
admins = self.root / "Admins"
|
||||
admins.mkdir()
|
||||
self.own(admins, (32, 544))
|
||||
admins.chmod(0o500)
|
||||
plain = self.root / "Plain"
|
||||
plain.mkdir()
|
||||
plain.chmod(0)
|
||||
outside = Path(self.tmp.name) / "outside"
|
||||
outside.mkdir()
|
||||
self.own(outside, self.STALE)
|
||||
outside.chmod(0o500)
|
||||
(self.root / "Link").symlink_to(outside)
|
||||
self.assertEqual(([], []), self.heal())
|
||||
self.assertEqual(0o755, self.mode(mine))
|
||||
self.assertEqual(0o444, self.mode(mine / "settings.ini"))
|
||||
self.assertEqual(0, self.mode(denied))
|
||||
self.assertEqual(0o500, self.mode(admins))
|
||||
self.assertEqual(0, self.mode(plain))
|
||||
self.assertEqual(0o500, self.mode(outside))
|
||||
for path in (mine, mine / "settings.ini", admins, outside):
|
||||
self.assertIn("user.wine.sd", os.listxattr(path))
|
||||
|
||||
def test_a_locked_program_data_folder_is_healed_before_its_entries(self):
|
||||
(self.root / "Vendor").mkdir()
|
||||
self.own(self.root / "Vendor", self.STALE)
|
||||
(self.root / "Vendor").chmod(0)
|
||||
self.own(self.root, self.STALE)
|
||||
self.root.chmod(0)
|
||||
self.assertEqual(([".", "Vendor"], [".", "Vendor"]), self.heal())
|
||||
self.assertEqual(0o700, self.mode(self.root))
|
||||
self.assertEqual(0o700, self.mode(self.root / "Vendor"))
|
||||
|
||||
def test_a_heal_waits_while_another_launch_heals_the_same_prefix(self):
|
||||
(self.root / "Vendor").mkdir()
|
||||
self.own(self.root / "Vendor", self.STALE)
|
||||
(self.root / "Vendor").chmod(0)
|
||||
results = []
|
||||
lock = os.open(self.compat / "pfx", os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
worker = threading.Thread(target=lambda: results.append(self.heal()))
|
||||
worker.start()
|
||||
worker.join(0.3)
|
||||
self.assertTrue(worker.is_alive())
|
||||
self.assertEqual(0, self.mode(self.root / "Vendor"))
|
||||
finally:
|
||||
os.close(lock)
|
||||
worker.join(10)
|
||||
self.assertEqual([(["Vendor"], ["Vendor"])], results)
|
||||
|
||||
def test_user_sid_follows_wine_for_a_missing_or_short_machine_id(self):
|
||||
sid = MODULE["wine_user_sid"]
|
||||
self.assertEqual(self.CURRENT, sid())
|
||||
self.globals["MACHINE_ID"] = str(Path(self.tmp.name) / "missing")
|
||||
self.assertEqual((21, 0, 0, 0, 1000), sid())
|
||||
short = Path(self.tmp.name) / "short"
|
||||
short.write_text("1234\n")
|
||||
self.globals["MACHINE_ID"] = str(short)
|
||||
self.assertEqual((21, 0, 0, 0, 1000), sid())
|
||||
binary = Path(self.tmp.name) / "binary"
|
||||
binary.write_bytes(b"\xff\xfe" + b"0" * 15)
|
||||
self.globals["MACHINE_ID"] = str(binary)
|
||||
self.assertEqual((21, 0, 0, os.getuid(), 1000), sid())
|
||||
signed = Path(self.tmp.name) / "signed"
|
||||
signed.write_text("+234abcd5678ef01\n")
|
||||
self.globals["MACHINE_ID"] = str(signed)
|
||||
self.assertEqual((21, 0x234abcd, 0x5678ef01, os.getuid(), 1000), sid())
|
||||
signed.write_text("-000000000000001\n")
|
||||
self.assertEqual((21, 0xffffffff, 0xffffffff, os.getuid(), 1000), sid())
|
||||
|
||||
def test_prefix_without_shared_data_is_skipped(self):
|
||||
self.assertEqual(([], []), MODULE["heal_shared_data"](str(Path(self.tmp.name) / "missing")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
@@ -223,6 +223,9 @@ PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <link.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/sysmacros.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -466,6 +469,36 @@ static void run_probe(void) {
|
||||
printf("pad %d\n", new_device(&udev, PAD) != NULL);
|
||||
}
|
||||
|
||||
static int loaded_span(struct dl_phdr_info *info, size_t size, void *data) {
|
||||
uintptr_t *span = data;
|
||||
int i;
|
||||
|
||||
(void)size;
|
||||
if (info->dlpi_addr != span[0]) return 0;
|
||||
for (i = 0; i < info->dlpi_phnum; i++)
|
||||
if (info->dlpi_phdr[i].p_type == PT_LOAD && info->dlpi_phdr[i].p_vaddr + info->dlpi_phdr[i].p_memsz > span[1])
|
||||
span[1] = info->dlpi_phdr[i].p_vaddr + info->dlpi_phdr[i].p_memsz;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void run_reload(const char *path) {
|
||||
struct link_map *map = NULL;
|
||||
uintptr_t span[2] = {0, 0};
|
||||
void *first = enumerate_new(NULL);
|
||||
void *second;
|
||||
|
||||
dlinfo(lib, RTLD_DI_LINKMAP, &map);
|
||||
span[0] = map->l_addr;
|
||||
dl_iterate_phdr(loaded_span, span);
|
||||
dlclose(lib);
|
||||
mmap((void *)span[0], span[1], PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
|
||||
lib = dlopen(path, RTLD_NOW | RTLD_LOCAL);
|
||||
enumerate_new = sym("udev_enumerate_new");
|
||||
list = sym("udev_enumerate_get_list_entry");
|
||||
second = enumerate_new(NULL);
|
||||
printf("reload %s %s\n", entry_name(list(first)), entry_name(list(second)));
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char link[4096];
|
||||
|
||||
@@ -510,6 +543,7 @@ int main(int argc, char **argv) {
|
||||
else if (strcmp(argv[1], "every") == 0) run_every(argc - 3, argv + 3);
|
||||
else if (strcmp(argv[1], "stable") == 0) run_stable();
|
||||
else if (strcmp(argv[1], "enumerate") == 0) run_enumerate();
|
||||
else if (strcmp(argv[1], "reload") == 0) run_reload(argv[2]);
|
||||
else run_udev();
|
||||
fflush(stdout);
|
||||
return 0;
|
||||
@@ -650,6 +684,9 @@ class InputUdevPreloadTest(unittest.TestCase):
|
||||
"nothing added scan -1",
|
||||
])
|
||||
|
||||
def test_a_program_that_closes_and_reopens_libudev_keeps_working(self):
|
||||
self.assertEqual(self.run_program("reload"), ["reload real0 real1"])
|
||||
|
||||
def test_only_the_steam_client_and_its_remote_play_client_get_the_real_libudev(self):
|
||||
for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/streaming_client", 0),
|
||||
("steamrtarm64/streaming_client", 0), ("steamrt64/steam-probe", 1),
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
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"
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *what, int fd) {
|
||||
printf("%s\t", what);
|
||||
if (fd < 0) {
|
||||
printf("-\n");
|
||||
return;
|
||||
}
|
||||
unsigned char buf[256];
|
||||
ssize_t n;
|
||||
int any = 0;
|
||||
while ((n = read(fd, buf, sizeof(buf))) > 0) {
|
||||
for (ssize_t i = 0; i < n; i++) printf("%02x", buf[i]);
|
||||
any = 1;
|
||||
}
|
||||
printf("%s\n", any ? "" : "-");
|
||||
close(fd);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strncmp(argv[i], "at:", 3) == 0) {
|
||||
char *name = strrchr(argv[i], '/');
|
||||
*name++ = 0;
|
||||
int root = open(argv[i] + 3, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
int fd = root >= 0 ? openat(root, name, O_RDONLY | O_CLOEXEC) : -1;
|
||||
name[-1] = '/';
|
||||
show(argv[i], fd);
|
||||
if (root >= 0) close(root);
|
||||
} else if (strncmp(argv[i], "dup:", 4) == 0) {
|
||||
char *name = strrchr(argv[i], '/');
|
||||
*name++ = 0;
|
||||
int root = open(argv[i] + 4, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
int copy = root >= 0 ? dup2(root, 50) : -1;
|
||||
if (root >= 0) close(root);
|
||||
int fd = copy >= 0 ? openat(copy, name, O_RDONLY | O_CLOEXEC) : -1;
|
||||
name[-1] = '/';
|
||||
show(argv[i], fd);
|
||||
if (copy >= 0) close(copy);
|
||||
} else if (strncmp(argv[i], "nfat:", 5) == 0 || strncmp(argv[i], "link:", 5) == 0) {
|
||||
char *name = strrchr(argv[i], '/');
|
||||
*name++ = 0;
|
||||
int how = argv[i][0] == 'l' ? O_PATH : O_RDONLY | O_DIRECTORY;
|
||||
int root = open(argv[i] + 5, how | O_NOFOLLOW | O_CLOEXEC);
|
||||
int fd = root >= 0 ? openat(root, name, O_RDONLY | O_CLOEXEC) : -1;
|
||||
name[-1] = '/';
|
||||
show(argv[i], fd);
|
||||
if (root >= 0) close(root);
|
||||
} else if (strncmp(argv[i], "nofollow:", 9) == 0) {
|
||||
int fd = open(argv[i] + 9, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
printf("%s\t%s\n", argv[i], fd >= 0 ? "6f70656e" : "-");
|
||||
if (fd >= 0) close(fd);
|
||||
} else {
|
||||
show(argv[i], open(argv[i], O_RDONLY | O_CLOEXEC));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
SLEEPER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
int main(int argc, char **argv) {
|
||||
if (argc > 1) open(argv[1], O_RDONLY);
|
||||
puts("ready");
|
||||
fflush(stdout);
|
||||
sleep(60);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookProcRootTest(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)
|
||||
for name, source in (("probe", PROBE), ("sleeper", SLEEPER)):
|
||||
(tmp / f"{name}.c").write_text(source)
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(tmp / name), str(tmp / f"{name}.c")], check=True)
|
||||
cls.session = tmp / "session"
|
||||
(cls.session / "etc").mkdir(parents=True)
|
||||
(cls.session / "etc/os-release").write_text("session")
|
||||
cls.sandbox = tmp / "sandbox"
|
||||
(cls.sandbox / "etc").mkdir(parents=True)
|
||||
(cls.sandbox / "etc/os-release").write_text("sandbox")
|
||||
(cls.sandbox / ".flatpak-info").write_text("app")
|
||||
cls.app = tmp / "app"
|
||||
cls.app.mkdir()
|
||||
(cls.app / "manifest.json").write_text("bound")
|
||||
cls.view = tmp / "view"
|
||||
(cls.app / "link").symlink_to(cls.view / "manifest.json")
|
||||
cls.info = tmp / "proxy-info"
|
||||
cls.info.write_text("proxy")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def start(self, env, opened=None):
|
||||
full = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD",) and not k.startswith("DDNATV_")}
|
||||
full.update(env)
|
||||
cmd = list(self.prefix) + [str(Path(self.tmp.name) / "sleeper")] + ([str(opened)] if opened else [])
|
||||
child = subprocess.Popen(cmd, env=full, stdout=subprocess.PIPE, text=True)
|
||||
self.addCleanup(child.stdout.close)
|
||||
self.addCleanup(child.wait)
|
||||
self.addCleanup(child.kill)
|
||||
self.assertEqual("ready", child.stdout.readline().strip())
|
||||
return child.pid
|
||||
|
||||
def probe(self, *paths, binds="/proc:/proc"):
|
||||
hook_env = {"DDNATV_ROOT": str(self.session), "LD_PRELOAD": str(self.hook), "DDNATV_BINDS": binds}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD" and not k.startswith("DDNATV_")}
|
||||
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(Path(self.tmp.name) / "probe"), *paths], env=env, capture_output=True,
|
||||
text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {name: value if value == "-" else bytes.fromhex(value).decode()
|
||||
for name, value in (line.split("\t") for line in out.stdout.splitlines())}
|
||||
|
||||
def sandboxed(self):
|
||||
return self.start({"DDNATV_ROOT": str(self.sandbox), "DDNATV_BINDS": f"/proc:/proc|{self.app}:/app"})
|
||||
|
||||
def test_a_sandbox_root_shows_its_own_flatpak_info(self):
|
||||
pid = self.sandboxed()
|
||||
at, path = f"at:/proc/{pid}/root/.flatpak-info", f"/proc/{pid}/root/.flatpak-info"
|
||||
got = self.probe(at, path)
|
||||
self.assertEqual("app", got[at])
|
||||
self.assertEqual("app", got[path])
|
||||
|
||||
def test_a_sandbox_root_shows_its_files_and_mounts(self):
|
||||
pid = self.sandboxed()
|
||||
paths = (f"/proc/{pid}/root/etc/os-release", f"/proc/{pid}/root/app/manifest.json",
|
||||
f"at:/proc/{pid}/root/etc/os-release")
|
||||
got = self.probe(*paths)
|
||||
self.assertEqual(["sandbox", "bound", "sandbox"], [got[p] for p in paths])
|
||||
|
||||
def test_a_program_in_the_session_with_a_bound_flatpak_info_shows_it(self):
|
||||
pid = self.start({"DDNATV_ROOT": str(self.session), "DDNATV_BINDS": f"/proc:/proc|{self.info}:/.flatpak-info"})
|
||||
at, path = f"at:/proc/{pid}/root/.flatpak-info", f"/proc/{pid}/root/.flatpak-info"
|
||||
got = self.probe(at, path)
|
||||
self.assertEqual("proxy", got[at])
|
||||
self.assertEqual("proxy", got[path])
|
||||
|
||||
def test_a_file_bound_from_an_open_descriptor_is_read(self):
|
||||
holder = self.start({}, opened=self.info)
|
||||
fd = next(n for n in os.listdir(f"/proc/{holder}/fd") if os.path.realpath(f"/proc/{holder}/fd/{n}") == str(self.info))
|
||||
pid = self.start({"DDNATV_ROOT": str(self.session),
|
||||
"DDNATV_BINDS": f"/proc:/proc|/proc/{holder}/fd/{fd}:/.flatpak-info"})
|
||||
at = f"at:/proc/{pid}/root/.flatpak-info"
|
||||
self.assertEqual("proxy", self.probe(at)[at])
|
||||
|
||||
def test_a_program_in_the_same_session_is_not_a_flatpak(self):
|
||||
pid = self.start({"DDNATV_ROOT": str(self.session), "DDNATV_BINDS": "/proc:/proc"})
|
||||
at, path, etc = (f"at:/proc/{pid}/root/.flatpak-info", f"/proc/{pid}/root/.flatpak-info",
|
||||
f"/proc/{pid}/root/etc/os-release")
|
||||
got = self.probe(at, path, etc)
|
||||
self.assertEqual("-", got[at])
|
||||
self.assertEqual("-", got[path])
|
||||
self.assertEqual("session", got[etc])
|
||||
|
||||
def test_a_program_without_the_hook_is_looked_at_as_the_kernel_shows_it(self):
|
||||
pid = self.start({})
|
||||
path, at = f"/proc/{pid}/root{self.sandbox}/etc/os-release", f"at:/proc/{pid}/root/.flatpak-info"
|
||||
got = self.probe(path, at)
|
||||
self.assertEqual("sandbox", got[path])
|
||||
self.assertEqual(Path("/.flatpak-info").read_text() if Path("/.flatpak-info").exists() else "-", got[at])
|
||||
|
||||
def test_a_link_is_followed_in_the_sandbox_view(self):
|
||||
pid = self.start({"DDNATV_ROOT": str(self.sandbox),
|
||||
"DDNATV_BINDS": f"/proc:/proc|{self.app}:/app|{self.app}:{self.view}"})
|
||||
path = f"/proc/{pid}/root/app/link"
|
||||
self.assertEqual("bound", self.probe(path)[path])
|
||||
|
||||
def test_a_duplicated_root_descriptor_keeps_the_sandbox_view(self):
|
||||
pid = self.sandboxed()
|
||||
dup = f"dup:/proc/{pid}/root/.flatpak-info"
|
||||
self.assertEqual("app", self.probe(dup)[dup])
|
||||
|
||||
def test_a_bare_root_is_not_followed_with_nofollow(self):
|
||||
pid = self.sandboxed()
|
||||
bare, below = f"nofollow:/proc/{pid}/root", f"nofollow:/proc/{pid}/root/etc"
|
||||
got = self.probe(bare, below)
|
||||
self.assertEqual("-", got[bare])
|
||||
self.assertEqual("open", got[below])
|
||||
|
||||
def test_a_root_with_a_trailing_slash_keeps_the_sandbox_view_with_nofollow(self):
|
||||
pid = self.sandboxed()
|
||||
path = f"nfat:/proc/{pid}/root//.flatpak-info"
|
||||
self.assertEqual("app", self.probe(path)[path])
|
||||
|
||||
def test_a_descriptor_for_the_root_link_itself_is_not_a_directory(self):
|
||||
pid = self.sandboxed()
|
||||
path = f"link:/proc/{pid}/root/.flatpak-info"
|
||||
self.assertEqual("-", self.probe(path)[path])
|
||||
|
||||
def test_a_sandbox_cannot_be_climbed_out_of(self):
|
||||
pid = self.sandboxed()
|
||||
path = f"/proc/{pid}/root/../../etc/os-release"
|
||||
self.assertEqual("sandbox", self.probe(path)[path])
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+34
-6
@@ -5,11 +5,23 @@ for (var i = 0; i < desktops.length; i++) {
|
||||
desktops[i].writeConfig("Image", "file:///usr/share/wallpapers/DroidDeck");
|
||||
}
|
||||
|
||||
var dock = new Panel;
|
||||
dock.location = "bottom";
|
||||
dock.height = 2 * Math.ceil(gridUnit * 2.5 / 2);
|
||||
var panel = new Panel;
|
||||
var panelScreen = panel.screen;
|
||||
panel.location = "bottom";
|
||||
panel.height = 2 * Math.ceil(gridUnit * 2.5 / 2);
|
||||
|
||||
var kickoff = dock.addWidget("org.kde.plasma.kickoff");
|
||||
const maximumAspectRatio = 21 / 9;
|
||||
if (panel.formFactor === "horizontal") {
|
||||
const geo = screenGeometry(panelScreen);
|
||||
const maximumWidth = Math.ceil(geo.height * maximumAspectRatio);
|
||||
if (geo.width > maximumWidth) {
|
||||
panel.alignment = "center";
|
||||
panel.minimumLength = maximumWidth;
|
||||
panel.maximumLength = maximumWidth;
|
||||
}
|
||||
}
|
||||
|
||||
var kickoff = panel.addWidget("org.kde.plasma.kickoff");
|
||||
kickoff.currentConfigGroup = ["Shortcuts"];
|
||||
kickoff.writeConfig("global", "Alt+F1");
|
||||
kickoff.currentConfigGroup = ["General"];
|
||||
@@ -23,20 +35,36 @@ kickoff.writeConfig("favorites", [
|
||||
"applications:systemsettings.desktop",
|
||||
]);
|
||||
|
||||
var tasks = dock.addWidget("org.kde.plasma.icontasks");
|
||||
panel.addWidget("org.kde.plasma.pager");
|
||||
|
||||
var tasks = panel.addWidget("org.kde.plasma.icontasks");
|
||||
tasks.currentConfigGroup = ["General"];
|
||||
tasks.writeConfig("launchers", [
|
||||
"applications:steamdeck-steam.desktop",
|
||||
"applications:systemsettings.desktop",
|
||||
"applications:org.kde.discover.desktop",
|
||||
"preferred://filemanager",
|
||||
"preferred://browser",
|
||||
"applications:org.kde.konsole.desktop",
|
||||
"applications:org.kde.kate.desktop",
|
||||
]);
|
||||
|
||||
var tray = dock.addWidget("org.kde.plasma.systemtray");
|
||||
panel.addWidget("org.kde.plasma.marginsseparator");
|
||||
|
||||
const inputMethodLanguages = ["as", "bn", "bo", "brx", "doi", "gu", "hi", "ja", "kn", "ko", "kok", "ks", "lep", "mai",
|
||||
"ml", "mni", "mr", "ne", "or", "pa", "sa", "sat", "sd", "si", "ta", "te", "th", "ur", "vi", "zh_CN", "zh_TW"];
|
||||
if (inputMethodLanguages.indexOf(languageId) != -1) {
|
||||
panel.addWidget("org.kde.plasma.kimpanel");
|
||||
}
|
||||
|
||||
var tray = panel.addWidget("org.kde.plasma.systemtray");
|
||||
var trayId = tray.readConfig("SystrayContainmentId");
|
||||
if (trayId) {
|
||||
var trayContainment = desktopById(trayId);
|
||||
trayContainment.currentConfigGroup = ["General"];
|
||||
trayContainment.writeConfig("scaleIconsToFit", true);
|
||||
}
|
||||
var clock = panel.addWidget("org.kde.plasma.digitalclock");
|
||||
clock.currentConfigGroup = ["Appearance"];
|
||||
clock.writeConfig("dateFormat", "isoDate");
|
||||
panel.addWidget("org.kde.plasma.showdesktop");
|
||||
@@ -154,7 +154,7 @@ new file mode 100755
|
||||
index 0000000..d43c5fc
|
||||
--- /dev/null
|
||||
+++ b/crates/xodus-cli/src/commands/legacy_install.rs
|
||||
@@ -0,0 +1,1375 @@
|
||||
@@ -0,0 +1,1406 @@
|
||||
+//! Installs a legacy Store title: resolve, license, download, extract.
|
||||
+//!
|
||||
+//! `streaming` only understands MSIXVC, where the container *is* the game and
|
||||
@@ -1187,7 +1187,15 @@ index 0000000..d43c5fc
|
||||
+
|
||||
+fn declares_application(folder: &Path) -> bool {
|
||||
+ let text = manifest_text(folder);
|
||||
+ text.contains("<application ") || text.contains("<executable ")
|
||||
+ opens_element(&text, "<application") || opens_element(&text, "<executable")
|
||||
+}
|
||||
+
|
||||
+/// Whether [text] opens [tag] as its own element, so `<Application Id=` and an attribute on the next
|
||||
+/// line count and `<Applications>` does not.
|
||||
+fn opens_element(text: &str, tag: &str) -> bool {
|
||||
+ text.match_indices(tag).any(|(at, _)| {
|
||||
+ text[at + tag.len()..].chars().next().is_some_and(|next| next.is_whitespace() || next == '>' || next == '/')
|
||||
+ })
|
||||
+}
|
||||
+
|
||||
+/// Files a package container carries about itself. A bundle leaves its own copies at
|
||||
@@ -1392,6 +1400,29 @@ index 0000000..d43c5fc
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn hoist_recognises_an_application_whose_attributes_start_on_the_next_line() {
|
||||
+ let root = scratch("pretty-printed");
|
||||
+ let app = root.join("Game.x64");
|
||||
+ std::fs::create_dir_all(&app).unwrap();
|
||||
+ std::fs::write(app.join(LEGACY_MANIFEST), "<Package>
|
||||
+<Applications>
|
||||
+<Application
|
||||
+ Id=\"App\"
|
||||
+ Executable=\"Game.exe\"/>
|
||||
+</Applications></Package>").unwrap();
|
||||
+ std::fs::write(app.join("Game.exe"), b"MZ").unwrap();
|
||||
+ let resource = root.join("Game.language-de");
|
||||
+ std::fs::create_dir_all(&resource).unwrap();
|
||||
+ std::fs::write(resource.join(LEGACY_MANIFEST), "<Package><Resources/></Package>").unwrap();
|
||||
+
|
||||
+ hoist(&root).unwrap();
|
||||
+
|
||||
+ assert!(root.join("Game.exe").is_file());
|
||||
+ assert!(opens_element("<application id=\"a\"", "<application") && !opens_element("<applications>", "<application"));
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn hoist_prefers_the_x64_package_when_several_declare_an_application() {
|
||||
+ let root = scratch("two-applications");
|
||||
+ for (name, arch) in [("Game.x86", "x86"), ("Game.x64", "x64")] {
|
||||
|
||||
Reference in new issue
Block a user