Compare commits

..
Author SHA1 Message Date
xXJsonDeruloXx ef261d9724 double down on PD 2026-10-07 17:18:26 -04:00
35 changed files with 694 additions and 1329 deletions

No files matched your search

-1
View File
@@ -4,7 +4,6 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Session logs go to Downloads so a failed run can be handed over as one folder. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
+5 -256
View File
@@ -1216,70 +1216,8 @@ struct DeckHidraw {
FakeInputRingHeader *ring = nullptr;
size_t mapping_size = 0;
uint8_t pending_feature = 0;
bool touch = false; // the Mobile Touch experiment below, not the Deck
int touch_index = 0;
};
// ---- EXPERIMENT: Steam's Mobile Touch controller as a local device ----
//
// docs/development/steam-touch-controller.md. Steam Link hands the host its touch controls as a
// remote HID device, 0000:11fb ("Mobile Touch Control"), which Steam's controller code classes as
// k_eControllerType_MobileTouch by its ids alone. FAKE_EVDEV_TOUCHCTL=1 offers the client the same
// ids as a local hidraw node, to see whether it builds the touch controller with no stream. The
// 40-byte input report is read from TOUCHCTL_REPORT_FILE (written by hand while experimenting); every
// output and feature report the client sends is logged and appended to TOUCHCTL_OUT_FILE.
// FAKE_EVDEV_TOUCHCTL=<n> offers n of them: /dev/hidraw17, 18, ... with serials MT-DROIDDECK0001, 0002,
// ..., each reading its own report file (touchctl.report, touchctl1.report, ...).
static constexpr unsigned int TOUCH_HIDRAW_MINOR = 17;
static constexpr int TOUCH_MAX = 4;
static constexpr int TOUCH_REPORT_BYTES = 40;
static constexpr int TOUCH_REPORT_INTERVAL_US = 8000;
static constexpr const char *TOUCH_NAME = "Mobile Touch Control";
static std::string touch_serial(int index) {
char serial[32];
snprintf(serial, sizeof(serial), "MT-DROIDDECK%04d", index + 1);
return serial;
}
static std::string touch_report_file(int index) {
return index == 0 ? std::string("/tmp/touchctl.report") : "/tmp/touchctl" + std::to_string(index) + ".report";
}
static constexpr const char *TOUCHCTL_OUT_FILE = "/tmp/touchctl.out";
// While this file exists the device is unplugged: the open stream ends and new opens fail.
static constexpr const char *TOUCHCTL_OFF_FILE = "/tmp/touchctl.off";
// Generic Desktop / Game Pad: one 40-byte input report, one 64-byte output report, one 64-byte feature report.
static const uint8_t kTouchReportDescriptor[] = {
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01,
0x09, 0x02, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x28, 0x81, 0x02,
0x09, 0x03, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02,
0x09, 0x04, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0};
static int touchctl_count() {
static int count = -1;
if (count < 0) count = getenv("FAKE_EVDEV_TOUCHCTL") ? std::max(0, std::min(TOUCH_MAX, atoi(getenv("FAKE_EVDEV_TOUCHCTL")))) : 0;
return count;
}
static bool fake_touchctl_enabled() { return touchctl_count() > 0; }
__attribute__((visibility("hidden"))) static void touchctl_note(const char *what, const uint8_t *data, size_t size) {
static std::atomic<unsigned> count{0};
unsigned n = ++count;
char hex[3 * 72 + 1] = {};
size_t shown = std::min<size_t>(size, 72);
for (size_t i = 0; i < shown; i++) snprintf(hex + 3 * i, 4, "%02x ", data[i]);
if (n <= 200 || (n & (n - 1)) == 0) Logger::log("touchctl: %s (%zu bytes): %s\n", what, size, hex);
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
int fd = my_open(TOUCHCTL_OUT_FILE, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
if (fd >= 0) {
char line[3 * 72 + 64];
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
int length = snprintf(line, sizeof(line), "%ld.%03ld %s %s\n", static_cast<long>(now.tv_sec),
now.tv_nsec / 1000000, what, hex);
syscall(SYS_write, fd, line, length);
syscall(SYS_close, fd);
}
}
// What the Deck has and an Xbox pad does not, after the ring's events: motion (PadMotion) and the
// back grips and trackpads (the second screen's Deck controls, DeckControls), already in the
// Deck's axes and units, under a seqlock (FakeInputWriter.writeMotion / writeDeckControls).
@@ -1369,8 +1307,7 @@ __attribute__((visibility("hidden"))) static bool process_is_steam_client() {
__attribute__((constructor)) static void log_client_start() {
config();
if (process_is_steam_client())
Logger::log("loaded in the Steam client: deck %s, touchctl %s, ring slot 0 %s\n", fake_deck_enabled() ? "on" : "off",
fake_touchctl_enabled() ? "on" : "off",
Logger::log("loaded in the Steam client: deck %s, ring slot 0 %s\n", fake_deck_enabled() ? "on" : "off",
get_ring_path_for_slot(0).empty() ? "(none configured)" : get_ring_path_for_slot(0).c_str());
}
@@ -1546,172 +1483,6 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) {
return pair[0];
}
__attribute__((visibility("hidden"))) static void *touch_report_thread(void *arg) {
auto *holder = static_cast<std::shared_ptr<DeckHidraw> *>(arg);
std::shared_ptr<DeckHidraw> self = *holder;
delete holder;
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
uint8_t last[TOUCH_REPORT_BYTES] = {};
for (;;) {
if (access(TOUCHCTL_OFF_FILE, F_OK) == 0) {
Logger::log("touchctl: unplugged\n");
break;
}
uint8_t report[TOUCH_REPORT_BYTES] = {};
int fd = my_open(touch_report_file(self->touch_index).c_str(), O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
syscall(SYS_read, fd, report, sizeof(report));
syscall(SYS_close, fd);
}
if (memcmp(report, last, sizeof(report))) {
touchctl_note(self->touch_index ? "input#1+" : "input", report, sizeof(report));
memcpy(last, report, sizeof(report));
}
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
struct timespec interval = {0, TOUCH_REPORT_INTERVAL_US * 1000L};
nanosleep(&interval, nullptr);
}
Logger::log("touchctl: reader closed\n");
syscall(SYS_close, self->peer);
return nullptr;
}
// Which of the experiment's sysfs files the client reads, each once: where its scan stops.
__attribute__((visibility("hidden"))) static void touchctl_trace(int dirfd, const char *pathname) {
if (!fake_touchctl_enabled() || !pathname || !process_is_steam_client()) return;
std::string path;
if (pathname[0] == '/' || dirfd == AT_FDCWD) {
path = pathname;
} else {
char link[64], dir[PATH_MAX];
snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd);
ssize_t length = readlink(link, dir, sizeof(dir) - 1);
if (length <= 0) return;
path.assign(dir, length);
path += '/';
path += pathname;
}
if (path.find("usb2") == std::string::npos && path.find("usb3") == std::string::npos && path.find("hidraw17") == std::string::npos &&
path.find("11FB") == std::string::npos && path.find("240:17") == std::string::npos)
return;
static std::mutex mutex;
static auto *seen = new std::vector<std::string>();
{
std::lock_guard<std::mutex> guard(mutex);
if (seen->size() >= 128 || std::find(seen->begin(), seen->end(), path) != seen->end()) return;
seen->push_back(path);
}
Logger::log("touchctl: client read %s\n", path.c_str());
}
// The index of the experiment's node at pathname, or -1.
__attribute__((visibility("hidden"))) static int touch_hidraw_index(const char *pathname) {
if (!pathname || !fake_touchctl_enabled() || strncmp(pathname, "/dev/hidraw", 11)) return -1;
char *end = nullptr;
long minor = strtol(pathname + 11, &end, 10);
if (!end || *end || minor < TOUCH_HIDRAW_MINOR || minor >= TOUCH_HIDRAW_MINOR + touchctl_count()) return -1;
return static_cast<int>(minor - TOUCH_HIDRAW_MINOR);
}
__attribute__((visibility("hidden"))) static bool is_touch_hidraw_path(const char *pathname) {
return touch_hidraw_index(pathname) >= 0;
}
__attribute__((visibility("hidden"))) static int open_touch_hidraw(int flags, int index) {
if (access(TOUCHCTL_OFF_FILE, F_OK) == 0) {
Logger::log("touchctl: open refused while unplugged\n");
errno = ENOENT;
return -1;
}
if (!process_is_steam_client()) {
errno = ENOENT;
return -1;
}
int pair[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) return -1;
int buffer = TOUCH_REPORT_BYTES * 4;
setsockopt(pair[1], SOL_SOCKET, SO_SNDBUF, &buffer, sizeof(buffer));
if (!(flags & O_CLOEXEC)) fcntl(pair[0], F_SETFD, 0);
if (flags & O_NONBLOCK) fcntl(pair[0], F_SETFL, fcntl(pair[0], F_GETFL) | O_NONBLOCK);
auto touch = std::make_shared<DeckHidraw>();
touch->peer = pair[1];
touch->touch = true;
touch->touch_index = index;
{
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
deck_map()[pair[0]] = touch;
}
pthread_t thread;
auto *arg = new std::shared_ptr<DeckHidraw>(touch);
if (pthread_create(&thread, nullptr, touch_report_thread, arg) != 0) {
delete arg;
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
deck_map().erase(pair[0]);
syscall(SYS_close, pair[0]);
syscall(SYS_close, pair[1]);
errno = ENOMEM;
return -1;
}
pthread_detach(thread);
Logger::log("touchctl: /dev/hidraw%u opened as fd %d\n", TOUCH_HIDRAW_MINOR + index, pair[0]);
return pair[0];
}
static int copy_ioctl_string(ioctl_request_t op, void *argp, const char *value);
__attribute__((visibility("hidden"))) static int ioctl_touch(DeckHidraw &touch, ioctl_request_t op, void *argp) {
if (_IOC_TYPE(op) != 'H') {
errno = ENOTTY;
return -1;
}
size_t size = _IOC_SIZE(op);
switch (_IOC_NR(op)) {
case 0x01:
*static_cast<int *>(argp) = sizeof(kTouchReportDescriptor);
return 0;
case 0x02: {
auto *descriptor = static_cast<uint8_t *>(argp);
uint32_t want;
memcpy(&want, descriptor, sizeof(want));
memcpy(descriptor + 4, kTouchReportDescriptor, std::min<size_t>(want, sizeof(kTouchReportDescriptor)));
return 0;
}
case 0x03: {
struct {
uint32_t bustype;
int16_t vendor;
int16_t product;
} info = {BUS_USB, 0x0000, static_cast<int16_t>(0x11fb)};
memcpy(argp, &info, sizeof(info));
return 0;
}
case 0x04: return copy_ioctl_string(op, argp, TOUCH_NAME);
case 0x05: return copy_ioctl_string(op, argp, ("usb-droiddeck-" + std::to_string(2 + touch.touch_index) + "/input0").c_str());
case 0x08: return copy_ioctl_string(op, argp, touch_serial(touch.touch_index).c_str());
case 0x06: // HIDIOCSFEATURE
touchctl_note("set-feature", static_cast<uint8_t *>(argp), size);
touch.pending_feature = size > 1 ? static_cast<uint8_t *>(argp)[1] : 0;
return static_cast<int>(size);
case 0x07: { // HIDIOCGFEATURE: report 2 is the battery in Steam Link's controller
auto *buf = static_cast<uint8_t *>(argp);
touchctl_note("get-feature", buf, std::min<size_t>(size, 8));
uint8_t id = buf[0];
memset(buf, 0, size);
buf[0] = id;
if (size > 2) {
buf[1] = 2;
buf[2] = 100;
}
return static_cast<int>(std::min<size_t>(size, 18));
}
default:
Logger::log("touchctl: unhandled hidraw ioctl 0x%02x\n", _IOC_NR(op));
errno = EINVAL;
return -1;
}
}
// libudev (systemd's sd-device) accepts a device only where its directory is on sysfs, which it
// checks with fstatfs on the directory it resolved. The Deck's sysfs is the app's own files bound
// into /sys, so those paths are said to be sysfs; nothing else is touched.
@@ -2052,8 +1823,6 @@ EXPORT int open(const char *pathname, int flags, ...) {
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
touchctl_trace(AT_FDCWD, pathname);
if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags, touch_hidraw_index(pathname));
if (is_withdrawn_pad_path(pathname)) {
errno = ENOENT;
return -1;
@@ -2128,8 +1897,6 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
touchctl_trace(dirfd, pathname);
if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags, touch_hidraw_index(pathname));
if (is_withdrawn_pad_path(pathname)) {
errno = ENOENT;
return -1;
@@ -2190,12 +1957,6 @@ static int fake_stat_path(const char *pathname, S *statbuf, Real real) {
errno = ENOENT;
return -1;
}
if (is_touch_hidraw_path(pathname) && process_is_steam_client()) {
memset(statbuf, 0, sizeof(*statbuf));
statbuf->st_mode = S_IFCHR | 0666;
statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR + touch_hidraw_index(pathname));
return 0;
}
if (is_deck_hidraw_path(pathname)) {
memset(statbuf, 0, sizeof(*statbuf));
statbuf->st_mode = S_IFCHR | 0666;
@@ -2247,7 +2008,7 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ret == 0 && deck_map().count(fd)) {
buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR;
buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, deck_map()[fd]->touch ? TOUCH_HIDRAW_MINOR + deck_map()[fd]->touch_index : DECK_HIDRAW_MINOR);
buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR);
return ret;
}
auto controller = controller_map().find(fd);
@@ -2293,7 +2054,6 @@ EXPORT int access(const char *pathname, int mode) {
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
if (is_touch_hidraw_path(pathname) && process_is_steam_client()) return 0;
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) {
errno = ENOENT;
return -1;
@@ -2330,7 +2090,6 @@ EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0;
if (is_touch_hidraw_path(pathname) && process_is_steam_client()) return 0;
if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) {
errno = ENOENT;
return -1;
@@ -2398,8 +2157,6 @@ EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
}
int ret = my_inotify_add_watch(fd, pathname, mask);
if (fake_touchctl_enabled() && process_is_steam_client())
Logger::log("touchctl: client watches %s (mask 0x%x) -> %d\n", pathname ? pathname : "(null)", mask, ret);
if (fake_path)
free(fake_path);
return ret;
@@ -2454,8 +2211,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
auto maker = uinput_map().find(fd);
if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp);
auto deck = deck_map().find(fd);
if (deck != deck_map().end())
return deck->second->touch ? ioctl_touch(*deck->second, op, argp) : ioctl_deck(*deck->second, op, argp);
if (deck != deck_map().end()) return ioctl_deck(*deck->second, op, argp);
auto controller = controller_map().find(fd);
if (controller == controller_map().end()) {
guard.unlock();
@@ -2781,10 +2537,7 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) {
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
auto made = uinput_map().find(fd);
if (made != uinput_map().end()) return write_uinput(*made->second, buf, count);
if (deck_map().count(fd)) {
if (deck_map()[fd]->touch) touchctl_note("output", static_cast<const uint8_t *>(buf), count);
return static_cast<ssize_t>(count);
}
if (deck_map().count(fd)) return static_cast<ssize_t>(count);
auto controller = controller_map().find(fd);
if (controller != controller_map().end()) {
if (fake_fd_is_stale(fd)) {
@@ -2809,11 +2562,7 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
if (deck_map().count(fd)) {
ssize_t total = 0;
bool touch = deck_map()[fd]->touch;
for (int i = 0; i < iovcnt; i++) {
if (touch) touchctl_note("output", static_cast<const uint8_t *>(iov[i].iov_base), iov[i].iov_len);
total += static_cast<ssize_t>(iov[i].iov_len);
}
for (int i = 0; i < iovcnt; i++) total += static_cast<ssize_t>(iov[i].iov_len);
return total;
}
auto made = uinput_map().find(fd);
@@ -822,9 +822,6 @@ class MainActivity : ComponentActivity() {
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
// The session's logs land in Downloads so a failed run can be handed over as a folder
// rather than dug out of app-private storage. targetSdk 28 means the old permission still
// grants exactly that.
val wanted = ArrayList<String>()
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
@@ -15,6 +15,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionService
@@ -50,6 +51,7 @@ class AgentBridgeProvider : ContentProvider() {
val response = try {
when (method) {
"state" -> state(context).put("ok", true)
"logs" -> exportLogs(context)
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
"stop" -> stop(context)
"resume" -> resume(context)
@@ -63,7 +65,7 @@ class AgentBridgeProvider : ContentProvider() {
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -101,10 +103,12 @@ class AgentBridgeProvider : ContentProvider() {
.put("session", session)
}
private fun latestSessionDirectory(): File? {
val parent = LinuxRuntime.debugLogDir()
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
private fun exportLogs(context: Context): JSONObject {
val dir = SessionState.logDirectory ?: SessionLogShare.latest(context)
?: return error("NO_SESSION_LOGS", "No session logs are available")
val zip = SessionLogShare.zipFolder(context, dir)
?: return error("NO_SESSION_LOGS", "No diagnostic logs are available")
return JSONObject().put("ok", true).put("sessionId", dir.name).put("path", zip.absolutePath)
}
private fun stop(context: Context): JSONObject {
@@ -36,11 +36,16 @@ object LogRedactor {
* WebAPI key is caught by [WEBAPI_KEY]. The value class excludes `<` and `>` so running this
* twice over an already-scrubbed line changes nothing.
*/
private val SECRET_KV = Regex(
"(?i)\\b(access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
private const val SECRET_KEYS =
"access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)" +
"(\\s*[=:]\\s*|=)([^\\s\"'<>&;,]{4,})"
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret"
private val SECRET_KV = Regex(
"(?i)\\b($SECRET_KEYS)" +
"([\"']?\\s*[=:]\\s*[\"']?)([^\\s\"'<>&;,]{1,})"
)
private val QUOTED_SECRET = Regex(
"(?i)\\b($SECRET_KEYS)([\"']?\\s*[=:]\\s*)(\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*')"
)
/** A Steam Guard code, only where the text around it says that is what it is. */
private val GUARD_CODE = Regex(
@@ -53,6 +58,7 @@ object LogRedactor {
"(?i)\\b(jwt|token|ticket|sessionid|steamloginsecure|machineauth)\\b[\\s=:]*([A-Za-z0-9+/=_\\-]{12,})"
)
private val LONG_TOKEN = Regex("[A-Za-z0-9_\\-]{88,}")
private val AUTHORIZATION = Regex("(?i)(\\b(?:proxy-)?authorization[\"']?\\s*[:=]\\s*[\"']?)[^\\r\\n\"']+")
private val STEAMID64 = Regex("\\b(76561)(\\d{8})(\\d{4})\\b")
private val STEAMID3 = Regex("\\[U:1:(\\d+)]")
/** "external address 2607:..." / "external IP: 203.0.113.9" - the client stating ours. */
@@ -179,30 +185,6 @@ object LogRedactor {
return out
}
/** A file worth scrubbing: text (no NUL in its first 4 KB) and not huge. */
fun isText(file: java.io.File): Boolean = try {
file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input ->
val buf = ByteArray(4096)
val n = input.read(buf)
n <= 0 || (0 until n).none { buf[it].toInt() == 0 }
}
} catch (e: Exception) {
false
}
/**
* Bump whenever a pattern is added or tightened. A session folder records the version it was
* scrubbed under (SessionArtifacts.SCRUBBED_TREE_MARKER), and a share copies a file as it is
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
* out.
*/
const val RULES_VERSION = 1
/** [src]'s lines, scrubbed, to [out]. */
fun scrubTo(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
}
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
fun redact(line: String): String {
if (line.isEmpty()) return line
@@ -211,6 +193,11 @@ object LogRedactor {
out = GUID.replace(out, "<redacted:guid>")
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
out = JWT_BASE64.replace(out, "<redacted:jwt>")
out = AUTHORIZATION.replace(out) { "${it.groupValues[1]}<redacted:authorization>" }
out = QUOTED_SECRET.replace(out) {
val quote = it.groupValues[3].first()
"${it.groupValues[1]}${it.groupValues[2]}$quote<redacted:token>$quote"
}
out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" }
out = GUARD_CODE.replace(out) { "${it.groupValues[1]}<redacted:code>" }
out = WEBAPI_KEY.replace(out, "<redacted:key>")
@@ -49,7 +49,7 @@ object SessionLogCapture {
) { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
if (writer === out) out.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
// A full or unmounted card must not take the session with it.
}
@@ -1020,7 +1020,6 @@ fun FileManagerScreen(
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
}
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
@@ -25,7 +25,7 @@ object GuestCommand {
linkDir: File? = null, onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
File(File(LinuxRuntime.debugLogDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
} catch (e: Exception) { null }
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
@@ -44,12 +44,10 @@ public final class LinuxRuntime {
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
private static final String SYSTEM_FONTS = "/system/fonts";
private static final String GUEST_SYSTEM_FONTS = "/usr/local/share/fonts/android";
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
public static final String DEBUG_LOG_DIR = "DroidDeck";
public static File debugLogDir() {
return new File(android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
public static File debugLogDir(Context context) {
return new File(context.getFilesDir(), "logs");
}
private LinuxRuntime() {}
@@ -31,21 +31,9 @@ object SessionArtifacts {
/** Written last; a folder without it did not get its ending. */
const val COMPLETE_MARKER = ".complete"
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
private const val SCRUBBED_MARKER = ".scrubbed-2"
/**
* Written by a session's own ending, and only when every file in the folder, subfolders
* included (whatever the session script copied into steam/ and droiddeck-esync/ as well as what
* the app wrote), went through the redactor without a failure. It lists each of those files
* with its size and modification time, under the redactor's rules version: a share copies a
* file as it is only when all three still match ([scrubbedFiles]), and scrubs anything else -
* a file added or changed since, a hidden one, or every file of a folder without it.
*/
const val SCRUBBED_TREE_MARKER = ".scrubbed-tree"
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
fun collect(context: Context, dir: File, reason: String) {
SessionLogCapture.stopFor(dir)
try {
val wayland = File(dir, "wayland.log")
if (!wayland.exists()) {
@@ -54,11 +42,10 @@ object SessionArtifacts {
}
}
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val record = Record(dir)
copySteamLogs(context, dir, record)
copySteamLogs(context, dir)
// A session the system killed leaves its trace here and nowhere else.
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
markScrubbed(scrubTree(record))
scrubTree(dir)
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
} catch (e: Exception) {
@@ -66,153 +53,52 @@ object SessionArtifacts {
}
}
/**
* Once, for session folders written before every file was scrubbed and before the device's own
* addresses were (network.txt listed them; the client's IPv6 check logs "external address"
* into steam/connection_log.txt): the whole folder, steam/ included, through the redactor.
* A marker records it. Runs at app start with [finishAbandoned].
*/
@Synchronized
fun scrubOlder(context: Context) {
val current = SessionPaths.current()
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
SessionPaths.isSessionFolder(f) && f != current && !File(f, SCRUBBED_MARKER).exists()
} ?: return
if (dirs.isEmpty()) return
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
dirs.forEach { dir ->
Record(dir).let { r -> scrubFolder(dir, r); File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it, r) } }
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
}
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
SessionPaths.sessionFolders(context).filter {
it.parentFile == LinuxRuntime.debugLogDir(context) && it != SessionPaths.current() &&
!File(it, COMPLETE_MARKER).exists()
}.forEach { scrubTree(it) }
}
/**
* The session's own files (session.log, app.log, desktop.log, the Steam desktop client's
* steam-desktop.log, ...) were written as they happened, unscrubbed; this pass puts every one
* through the redactor before the folder can be shared. A file is rewritten only if a line
* changed. steam/ was scrubbed on the way in.
*/
/** A file's size and modification time as they stood right after it was scrubbed. */
private class Scrubbed(val length: Long, val modified: Long)
/** Files of a folder as they stood right after scrubbing, filled by [scrubTree] and [copySteamLogs]. */
private class Record(val dir: File) {
val files = HashMap<File, Scrubbed>()
var failed = false
}
private fun scrubFolder(dir: File, record: Record) {
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
if (!LogRedactor.isText(f)) return@forEach
val done = scrubFile(dir, f)
if (done == null) record.failed = true else record.files[f] = done
}
}
/**
* Puts [f] through the redactor in place. Returns its size and modification time as it then
* stands, or null if it could not, and [f] may still hold the original. A writer still
* appending to [f] (the app's own log capture) changes its size afterwards, and a share then
* scrubs it again.
*/
private fun scrubFile(dir: File, f: File): Scrubbed? {
val tmp = File(dir, ".${f.name}.scrub")
return try {
val before = Scrubbed(f.length(), f.lastModified())
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
val scrubbed = tmp.readBytes()
if (scrubbed.contentEquals(f.readBytes())) {
tmp.delete()
// Unchanged by the redactor, and by anything else while it read.
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
} else {
// Shared storage can refuse a rename; then the scrubbed bytes are written over the
// original instead, so it never stays behind unscrubbed.
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${f.name}", e)
tmp.delete()
null
}
}
/**
* Records [record]'s folder as scrubbed - every file went through without a failure - or
* leaves it unmarked, so the next share and the pass over older folders scrub it again.
*/
private fun markScrubbed(record: Record) {
val dir = record.dir
val tree = File(dir, SCRUBBED_TREE_MARKER)
if (record.failed) {
tree.delete()
Log.w(TAG, "$dir is not fully scrubbed; it is scrubbed again when shared")
return
}
try {
File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n")
val lines = StringBuilder("rules ${LogRedactor.RULES_VERSION}\n")
record.files.forEach { (f, s) ->
lines.append(s.length).append('\t').append(s.modified).append('\t')
.append(f.relativeTo(dir).path).append('\n')
}
tree.writeText(lines.toString())
} catch (e: Exception) {
tree.delete()
}
}
/**
* The files of [dir] that its own ending scrubbed and that are unchanged since (same size and
* modification time), by path relative to [dir]. Empty when the folder has no such record, or
* one made under other redactor rules.
*/
fun scrubbedFiles(dir: File): Set<String> {
val lines = try { File(dir, SCRUBBED_TREE_MARKER).takeIf { it.isFile }?.readLines() } catch (e: Exception) { null }
?: return emptySet()
if (lines.firstOrNull() != "rules ${LogRedactor.RULES_VERSION}") return emptySet()
return lines.drop(1).mapNotNull { line ->
val parts = line.split('\t', limit = 3)
if (parts.size != 3) return@mapNotNull null
val f = File(dir, parts[2])
parts[2].takeIf { f.isFile && f.length().toString() == parts[0] && f.lastModified().toString() == parts[1] }
}.toSet()
}
/** The end-of-session scrub of [dir] on its own (steam/ already in place), for tests. */
@androidx.annotation.VisibleForTesting
internal fun scrubAndMark(dir: File) = markScrubbed(scrubTree(Record(dir)))
/**
* [record]'s folder and every folder under it (steam/, droiddeck-esync/): the session script
* copied files there verbatim, and a Steam log the app did not copy over again (gone from the
* runtime, or past its size limit) stayed as the script left it. Files [copySteamLogs] already
* redacted on the way in are in [record] and left alone.
*/
private fun scrubTree(record: Record): Record {
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
return record
}
/** Steam's logs: redacted into steam/, never copied verbatim. What it wrote goes in [record]. */
private fun copySteamLogs(context: Context, dir: File, record: Record) {
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
internal fun scrubTree(dir: File) {
SessionLogFiles.candidates(dir).forEach { file ->
if (!SessionLogFiles.safeFile(dir, file)) return@forEach
var tmp: File? = null
try {
val dst = File(out, src.name)
dst.bufferedWriter().use { w ->
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
tmp = File.createTempFile(".redacted-", ".tmp", dir)
val size = file.length()
val modified = file.lastModified()
val limit = if (file.parentFile?.name == "steam") SessionLogFiles.STEAM_MAX_BYTES else SessionLogFiles.MAX_BYTES
tmp.bufferedWriter().use { SessionLogFiles.scrubTo(dir, file, it, limit) }
if (file.length() == size && file.lastModified() == modified) {
check(tmp.renameTo(file))
}
record.files[dst] = Scrubbed(dst.length(), dst.lastModified())
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${file.name}", e)
} finally {
tmp?.delete()
}
}
}
private fun copySteamLogs(context: Context, dir: File) {
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
if (!logs.isDirectory || java.nio.file.Files.isSymbolicLink(logs.toPath())) return
val out = File(dir, "steam")
if (java.nio.file.Files.isSymbolicLink(out.toPath()) || !(out.isDirectory || out.mkdirs())) return
SessionLogFiles.steamNames.map { File(logs, it) }.filter { it.exists() }.forEach { src ->
val tmp = File.createTempFile(".redacted-", ".tmp", out)
try {
tmp.bufferedWriter().use { SessionLogFiles.scrubTo(logs, src, it, SessionLogFiles.STEAM_MAX_BYTES) }
check(tmp.renameTo(File(out, src.name)))
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e)
} finally {
tmp?.delete()
}
}
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
/**
@@ -223,10 +109,10 @@ object SessionArtifacts {
*/
@Synchronized
fun finishAbandoned(context: Context) {
val parent = LinuxRuntime.debugLogDir()
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists()
}?.sortedWith(SessionPaths.chronological) ?: return
SessionLogMigration.run(context)
val abandoned = SessionPaths.sessionFolders(context).filter {
it.parentFile == LinuxRuntime.debugLogDir(context) && !File(it, COMPLETE_MARKER).exists()
}
if (abandoned.isEmpty()) return
val current = SessionPaths.current()
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -244,11 +130,10 @@ object SessionArtifacts {
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
val record = Record(dir)
if (newest) copySteamLogs(context, dir, record)
if (newest) copySteamLogs(context, dir)
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
markScrubbed(scrubTree(record))
scrubTree(dir)
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
Log.i(TAG, "finished the abandoned session folder $dir")
} catch (e: Exception) {
@@ -268,7 +153,7 @@ object SessionArtifacts {
val current = SessionPaths.current()
val finished = SessionPaths.sessionFolders(context).filter { it != current && File(it, COMPLETE_MARKER).exists() }
val old = finished.dropLast(SessionPaths.KEEP_SESSIONS)
old.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
old.forEach { SessionLogFiles.deleteTree(it) }
if (old.isNotEmpty()) Log.i(TAG, "deleted ${old.size} session folder(s) past the newest ${SessionPaths.KEEP_SESSIONS}")
}
@@ -281,10 +166,11 @@ object SessionArtifacts {
fun clearAll(context: Context): Int {
val current = SessionPaths.current()
val gone = SessionPaths.sessionFolders(context).filter { it != current }
gone.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR))
gone.forEach { SessionLogFiles.deleteTree(it) }
LinuxRuntime.debugLogDir(context).listFiles { f -> f.name == SessionPaths.TOOLS_DIR || f.name.matches(Regex("tools-\\d+")) }
?.forEach { SessionLogFiles.deleteTree(it) }
// Before tools/, those logs sat loose beside the session folders.
LinuxRuntime.debugLogDir().listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
LinuxRuntime.debugLogDir(context).listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
Log.i(TAG, "cleared ${gone.size} session folder(s)")
return gone.size
}
@@ -349,26 +349,9 @@ object SessionFiles {
indent + "}",
).joinToString(newline)
/**
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
* folder rather than dug out of app-private storage - but the session script redirects its own
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
* shell. So a public directory is used only once it is proven writable; otherwise the app's
* own files directory, which is bound into the session anyway, stands in.
*/
fun logDirectory(context: Context): File {
val public = LinuxRuntime.debugLogDir()
if (public.isDirectory || public.mkdirs()) {
val probe = File(public, ".writable")
try {
if (probe.createNewFile() || probe.isFile) {
probe.delete()
return public
}
} catch (ignored: Exception) {
}
fun logDirectory(context: Context): File =
LinuxRuntime.debugLogDir(context).apply {
check(!java.nio.file.Files.isSymbolicLink(toPath()))
check(isDirectory || mkdirs())
}
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
return File(context.filesDir, "logs").apply { mkdirs() }
}
}
@@ -0,0 +1,107 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.LogRedactor
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Writer
import java.nio.channels.Channels
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardOpenOption.READ
internal object SessionLogFiles {
const val MAX_BYTES = 64L * 1024 * 1024
const val STEAM_MAX_BYTES = 8L * 1024 * 1024
private const val MAX_LINE_CHARS = 64 * 1024
val steamNames = setOf(
"bootstrap_log.txt", "connection_log.txt", "console_log.txt", "content_log.txt",
"controller.txt", "compat_log.txt", "cef_log.txt", "cef_log.previous.txt",
"shader_log.txt", "systemaudiomanager.txt", "steamwebhelper.log", "webhelper.txt",
"steamui_html.txt", "steamui_system.txt", "steamui_library.txt", "steamui_login.txt",
"remote_connections.txt", "streaming_log.txt", "video.txt", "vrclient_steam.txt"
)
private val paths = setOf(
"session.log", "session.log.1", "app.log", "crash.log", "crash-app.txt",
"wayland.log", "audio.log", "device.txt", "network.txt", "events.jsonl",
"desktop.log", "steam-desktop.log", "steam.log", "pad.log", "storage.log",
"ended-without-teardown.txt", "droiddeck-esync/launches.log",
"droiddeck-esync/tools.tsv", "droiddeck-esync/wanted.tsv",
"droiddeck-esync/prefixes.json", "droiddeck-fex/status.json", "droiddeck-fex/Config.json"
) + steamNames.map { "steam/$it" }
fun candidates(folder: File): List<File> = paths.map { File(folder, it) }
.filter { Files.exists(it.toPath(), NOFOLLOW_LINKS) }
fun deleteTree(file: File) {
if (!Files.exists(file.toPath(), NOFOLLOW_LINKS)) return
Files.walk(file.toPath()).use { stream ->
stream.iterator().asSequence().toList().asReversed().forEach { Files.deleteIfExists(it) }
}
}
fun safeFile(root: File, file: File): Boolean {
val base = root.toPath().toAbsolutePath().normalize()
var path = file.toPath().toAbsolutePath().normalize()
if (!path.startsWith(base) || path == base) return false
while (path != base) {
if (Files.isSymbolicLink(path)) return false
path = path.parent ?: return false
}
return !Files.isSymbolicLink(base) && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS)
}
fun scrubTo(root: File, file: File, out: Writer, maxBytes: Long = MAX_BYTES) {
if (!safeFile(root, file)) throw IOException("unsafe path")
Files.newByteChannel(file.toPath(), READ, NOFOLLOW_LINKS).use { channel ->
var remaining = channel.size()
if (remaining >= maxBytes) throw IOException("size limit")
val source = Channels.newInputStream(channel)
val snapshot = object : InputStream() {
override fun read(): Int {
val one = ByteArray(1)
return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 255
}
override fun read(bytes: ByteArray, offset: Int, length: Int): Int {
if (length == 0) return 0
if (remaining == 0L) return -1
val count = source.read(bytes, offset, minOf(length.toLong(), remaining).toInt())
if (count < 0) throw IOException("truncated snapshot")
remaining -= count
return count
}
}
val decoder = Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
val reader = InputStreamReader(snapshot, decoder)
val line = StringBuilder()
val buffer = CharArray(4096)
fun writeLine() {
out.write(LogRedactor.redact(line.toString().removeSuffix("\r")))
out.write("\n")
line.setLength(0)
}
while (true) {
val count = reader.read(buffer)
if (count < 0) break
for (i in 0 until count) {
val char = buffer[i]
if (char == '\u0000') throw IOException("binary data")
if (char == '\n') writeLine() else {
if (line.length >= MAX_LINE_CHARS) throw IOException("line limit")
line.append(char)
}
}
}
if (line.isNotEmpty()) {
if (channel.size() != channel.position()) out.write("<incomplete live line withheld>\n")
else writeLine()
}
}
}
}
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
internal object SessionLogMigration {
fun run(context: Context) {
val old = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), LinuxRuntime.DEBUG_LOG_DIR)
val target = LinuxRuntime.debugLogDir(context)
if (!old.isDirectory || Files.isSymbolicLink(old.toPath())) return
check(target.isDirectory || target.mkdirs())
old.listFiles().orEmpty().filter {
SessionPaths.isSessionFolder(it) || it.name == SessionPaths.TOOLS_DIR ||
(it.isFile && it.name.endsWith(".log"))
}.forEach { source ->
try {
move(source, target)
} catch (e: Exception) {
Log.w("SessionLogMigration", "could not move legacy logs into private storage", e)
}
}
}
internal fun move(source: File, target: File) {
check(!Files.isSymbolicLink(target.toPath()))
val paths = Files.walk(source.toPath()).use { it.iterator().asSequence().toList() }
check(paths.all { !Files.isSymbolicLink(it) &&
(Files.isRegularFile(it, NOFOLLOW_LINKS) || Files.isDirectory(it, NOFOLLOW_LINKS)) })
var destination = File(target, source.name)
var number = 1
val stem = Regex("^session-\\d{8}-\\d{6}").find(source.name)?.value ?: source.name
while (Files.exists(destination.toPath(), NOFOLLOW_LINKS)) {
val name = if (source.isFile) "${source.nameWithoutExtension}-${number++}.${source.extension}"
else "$stem-${number++}"
destination = File(target, name)
}
if (source.renameTo(destination)) return
val stage = File.createTempFile(".migrating-", ".tmp", target)
val versions = paths.associate { it.toFile().let { file -> file to (file.length() to file.lastModified()) } }
try {
if (source.isDirectory) { check(stage.delete()); check(stage.mkdir()) }
paths.forEach { path ->
val file = path.toFile()
val out = if (file == source) stage else File(stage, file.relativeTo(source).path)
if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
check(out.isDirectory || out.mkdirs())
} else {
check(file == source || SessionLogFiles.safeFile(source, file))
Files.newByteChannel(path, java.nio.file.StandardOpenOption.READ, NOFOLLOW_LINKS).use { input ->
out.outputStream().use { output -> java.nio.channels.Channels.newInputStream(input).copyTo(output) }
}
check(out.length() == versions.getValue(file).first)
}
}
check(versions.all { (file, version) -> file.length() == version.first && file.lastModified() == version.second })
paths.asReversed().forEach { path ->
val file = path.toFile()
val out = if (file == source) stage else File(stage, file.relativeTo(source).path)
check(out.setLastModified(versions.getValue(file).second))
}
check(stage.renameTo(destination))
paths.asReversed().forEach { Files.delete(it) }
} finally {
stage.deleteRecursively()
}
}
}
@@ -17,11 +17,6 @@ import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
/**
* Zips the most recent session's log folder and hands it to Android's share sheet. Works where
* the folder could not be written to Downloads (no storage permission, or a device that refuses
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
*/
object SessionLogShare {
private val main = Handler(Looper.getMainLooper())
@@ -51,71 +46,57 @@ object SessionLogShare {
/** The newest session folder in either place logs are written, or null if there is none. */
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
/** Builds the zip (blocking). Returns null when there is no session to share. */
/** Builds a zip for one specific session folder (blocking). */
@Synchronized
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
if (!folder.isDirectory) return null
// The client's logs past STEAM_LOG_MAX_BYTES stay out, as they do from the app's own copy: a
// CEF debug log or an old *.previous.txt reached 17 MB, every share scrubbed them line by
// line, and the share sheet took ten seconds to appear.
val files = folder.walkTopDown().filter { it.isFile }
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
if (files.isEmpty()) return null
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
val zip = File(out, "DroidDeck-${folder.name}.zip")
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
// session pass yet, and the redactor changes nothing in a line that is already clean.
if (!folder.isDirectory || java.nio.file.Files.isSymbolicLink(folder.toPath())) return null
val files = SessionLogFiles.candidates(folder).map { Triple(folder, it, it.relativeTo(folder).invariantSeparatorsPath) }
val liveRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
val live = if (folder == SessionPaths.current()) SessionLogFiles.steamNames
.filter { name -> files.none { it.third == "steam/$name" } }
.map { File(liveRoot, it) }.filter { java.nio.file.Files.exists(it.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS) }
.map { Triple(liveRoot, it, "steam/${it.name}") } else emptyList()
val sources = files + live
if (sources.isEmpty()) return null
val out = File(context.cacheDir, "shared-logs").apply { SessionLogFiles.deleteTree(this); check(mkdirs()) }
val name = folder.name.replace(Regex("[^A-Za-z0-9._-]"), "_")
val zip = File(out, "DroidDeck-$name.zip")
val partial = File(out, ".export")
val stage = File.createTempFile("redacted-", ".tmp", context.cacheDir)
val omitted = ArrayList<String>()
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
// A finished folder was scrubbed whole when it ended. A file its record lists, unchanged
// since, goes in as it is; anything else (added or changed since, hidden, or any file of a
// session still running) is scrubbed again. Scrubbing tens of MB of the client's logs on
// every share kept the share sheet from appearing for ten seconds or more.
val scrubbed = SessionArtifacts.scrubbedFiles(folder)
val live = liveSteamLogs(context, folder)
val total = (files + live).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
done += f.length()
val percent = (done * 100 / total).toInt()
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
try {
ZipOutputStream(partial.outputStream().buffered()).use { z ->
sources.forEachIndexed { index, (root, src, relative) ->
val limit = if (relative.startsWith("steam/")) SessionLogFiles.STEAM_MAX_BYTES else SessionLogFiles.MAX_BYTES
val failure = runCatching {
stage.bufferedWriter().use { SessionLogFiles.scrubTo(root, src, it, limit) }
}.exceptionOrNull()
if (failure == null) {
z.putNextEntry(ZipEntry("$name/$relative"))
stage.inputStream().use { it.copyTo(z) }
z.closeEntry()
} else {
omitted += "$relative: omitted because it could not be safely sanitized."
}
onProgress?.invoke((index + 1).toFloat() / sources.size)
}
if (omitted.isNotEmpty()) {
z.putNextEntry(ZipEntry("$name/omitted.txt"))
z.write((omitted.joinToString("\n") + "\n").toByteArray(Charsets.UTF_8))
z.closeEntry()
}
}
check(partial.renameTo(zip))
return zip
} catch (e: Exception) {
partial.delete()
zip.delete()
throw e
} finally {
stage.delete()
}
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f, f.relativeTo(folder).path in scrubbed); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f, false); advance(f) }
}
return zip
}
private fun addEntry(z: ZipOutputStream, name: String, f: File, scrubbed: Boolean) {
z.putNextEntry(ZipEntry(name))
if (!scrubbed && LogRedactor.isText(f)) {
val w = z.bufferedWriter()
LogRedactor.scrubTo(f, w)
w.flush()
} else {
f.inputStream().use { it.copyTo(z) }
}
z.closeEntry()
}
/**
* The client's own logs as they stand, for a session shared while it runs. The session script
* copies them into steam/ only as it exits, so a zip made from the drawer had none - and
* controller.txt (which pad the client opened, the touch mode it set) is what a controller or
* touch report needs most. Only for the running session: an older folder would get this
* session's logs. The same files the script copies; nothing holding credentials is in logs/.
*/
private fun liveSteamLogs(context: Context, folder: File): List<File> {
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
}
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
fun shareIntent(context: Context, zip: File): Intent {
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
val send = Intent(Intent.ACTION_SEND)
@@ -7,29 +7,6 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded,
* named for the day, that day's session number and what was run, so the one a report is about can
* be picked out without opening any:
*
* ```
* Download/DroidDeck/2026-09-30-03-steam/
* device.txt what this device is, and every setting the session ran with
* session.log the guest session: proot, gamescope, the client's stdout
* wayland.log the app's compositor
* steam.log the Steam client's own log, scrubbed (Steam mode)
* steam/ the rest of the client's logs, scrubbed (Steam mode)
* desktop.log labwc, the panel and the programs on it (desktop mode)
* Download/DroidDeck/tools/ one-off commands: Flatpak installs, AppImage imports
* ```
*
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
* pruned with the rest.
*
* The folder is claimed by whoever starts first - the activity starts the compositor before the
* service starts the session - so both write into the same one, and a recreated activity (a
* foldable opening mid-session) joins the folder in progress instead of opening another.
*/
object SessionPaths {
private const val TAG = "SessionPaths"
@@ -50,12 +27,6 @@ object SessionPaths {
@Volatile
private var ended: File? = null
/**
* The folder for the session now starting, or the one already in progress. With logs turned
* off on the main screen the folder lives in the app's cache instead of Downloads - the
* scripts and the compositor still need somewhere to write - and [release] deletes it.
* [label] says what is being run (see [label]); without one it comes from the session's state.
*/
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
@@ -104,8 +75,8 @@ object SessionPaths {
// next session may have claimed its own by the time the last one's collector gets here.
if (dir == ended) dir = null
// A folder kept in the cache was never meant to outlive its session.
if (ended != null && ended.path.startsWith(context.cacheDir.path)) {
com.droiddeck.launcher.core.FileUtils.delete(ended)
if (ended.parentFile == File(context.cacheDir, "session-logs")) {
SessionLogFiles.deleteTree(ended)
}
}
@@ -123,22 +94,28 @@ object SessionPaths {
/** Whether [f] is a session's folder, in either naming. */
fun isSessionFolder(f: File): Boolean =
f.isDirectory && (NAMED.matches(f.name) || LEGACY.matches(f.name))
f.isDirectory && !java.nio.file.Files.isSymbolicLink(f.toPath()) &&
(NAMED.matches(f.name) || LEGACY.matches(f.name))
/**
* Oldest first: by day, then by when in the day. A folder from before the new naming sorts
* ahead of a new one from the same day, which it always predates.
*/
val chronological: Comparator<File> = compareBy { f ->
val chronological: Comparator<File> = compareBy<File> { f ->
NAMED.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}${g[2]}${g[3]}1${g[4].padStart(6, '0')}" }
?: LEGACY.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}0${g[2]}${g[3].removePrefix("-").padStart(2, '0')}" }
?: f.name
}
}.thenBy { it.lastModified() }
/** Every session folder in the places logs are written, oldest first. */
fun sessionFolders(context: Context): List<File> =
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
.flatMap { parent -> parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList() }
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(context),
File(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS),
com.droiddeck.launcher.runtime.LinuxRuntime.DEBUG_LOG_DIR))
.flatMap { parent ->
if (java.nio.file.Files.isSymbolicLink(parent.toPath())) emptyList()
else parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList()
}
.sortedWith(chronological)
internal fun slug(text: String): String =
@@ -277,9 +277,6 @@ class SessionService : Service() {
try {
SessionArtifacts.collect(this, dir, "session stopped")
} finally {
// Last, so everything above is in the file it is about - and only this session's:
// a session that replaced this one may already own the capture and the folder.
SessionLogCapture.stopFor(dir)
SessionPaths.release(this, dir)
}
}
@@ -44,12 +44,6 @@ object SteamDeckPad {
private const val HIDRAW = "$HID/hidraw/$NODE"
private const val SERIAL = "DROIDDECK0001"
// EXPERIMENT (docs/development/steam-touch-controller.md): Steam's Mobile Touch controller,
// 0000:11fb, as a second local device. libfakeinput serves the node only with
// FAKE_EVDEV_TOUCHCTL=1 (fakeinput_steam.cpp: TOUCH_HIDRAW_*).
private const val TOUCH_MINOR = 17
private const val TOUCH_DEVICES = 2
/** InputPlumber's CONTROLLER_DESCRIPTOR, as libfakeinput answers HIDIOCGRDESC. */
private val REPORT_DESCRIPTOR = intArrayOf(
0x06, 0xff, 0xff, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00,
@@ -57,14 +51,6 @@ object SteamDeckPad {
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
).map { it.toByte() }.toByteArray()
/** Must match libfakeinput's kTouchReportDescriptor. */
private val TOUCH_REPORT_DESCRIPTOR = intArrayOf(
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01,
0x09, 0x02, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x28, 0x81, 0x02,
0x09, 0x03, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02,
0x09, 0x04, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
).map { it.toByte() }.toByteArray()
/** Where [prepare] puts the stand-in listings; bound into the guest at the same path. */
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
@@ -121,42 +107,6 @@ object SteamDeckPad {
val udevData = File(LinuxRuntime.rootDir(context), "run/udev/data").apply { mkdirs() }
File(udevData, "c$MAJOR:$MINOR").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
// EXPERIMENT: Mobile Touch controllers beside the Deck, two of them (hidraw17, 18).
for (index in 0 until TOUCH_DEVICES) {
val minor = TOUCH_MINOR + index
val node = "hidraw$minor"
val bus = 2 + index
val usb = "$GUEST_DEVICES/usb$bus"
val iface = "$usb/$bus-1:1.0"
val hid = "$iface/0003:0000:11FB.000${2 + index}"
val hidraw = "$hid/hidraw/$node"
val serial = "MT-DROIDDECK%04d".format(index + 1)
write(usb, "uevent", "DEVTYPE=usb_device\nPRODUCT=0/11fb/0\nTYPE=0/0/0\nBUSNUM=00$bus\nDEVNUM=002\n")
write(usb, "idVendor", "0000\n")
write(usb, "idProduct", "11fb\n")
write(usb, "bcdDevice", "0000\n")
write(usb, "manufacturer", "Valve Software\n")
write(usb, "product", "Mobile Touch Control\n")
write(usb, "serial", "$serial\n")
link(File(dir(usb), "subsystem"), "/sys/bus/usb")
write(iface, "uevent", "DEVTYPE=usb_interface\nPRODUCT=0/11fb/0\nINTERFACE=3/0/0\n")
write(iface, "bInterfaceNumber", "00\n")
write(iface, "bInterfaceClass", "03\n")
link(File(dir(iface), "subsystem"), "/sys/bus/usb")
write(hid, "uevent", "DRIVER=hid-generic\nHID_ID=0003:00000000:000011FB\n" +
"HID_NAME=Mobile Touch Control\nHID_PHYS=usb-droiddeck-$bus/input0\n" +
"HID_UNIQ=$serial\nMODALIAS=hid:b0003g0001v00000000p000011FB\n")
File(dir(hid), "report_descriptor").writeBytes(TOUCH_REPORT_DESCRIPTOR)
link(File(dir(hid), "subsystem"), "/sys/bus/hid")
write(hidraw, "uevent", "MAJOR=$MAJOR\nMINOR=$minor\nDEVNAME=$node\n")
write(hidraw, "dev", "$MAJOR:$minor\n")
link(File(dir(hidraw), "subsystem"), "/sys/class/hidraw")
link(File(dir(hidraw), "device"), hid)
link(File(hidrawClass, node), hidraw)
link(File(context.cacheDir, "drm/sys/$MAJOR:$minor"), hidraw)
File(udevData, "c$MAJOR:$minor").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n")
}
Log.i(TAG, "deck pad: /dev/$NODE described as a Steam Deck controller (28de:1205)")
listOf(devices.path + ":" + GUEST_DEVICES, hidrawClass.path + ":/sys/class/hidraw")
} catch (e: Exception) {
+1 -1
View File
@@ -640,7 +640,7 @@
<string name="setup_choose">Elegir</string>
<string name="setup_linux_apps">Apps de Linux (beta)</string>
<string name="setup_store">Tienda Flathub</string>
<string name="setup_store_on">En el menú. Algunas apps pueden no iniciarse; los registros están en Download/DroidDeck.</string>
<string name="setup_store_on">En el menú. Algunas apps pueden no iniciarse.</string>
<string name="setup_store_off">Instala apps y juegos de Linux desde Flathub</string>
<string name="setup_tool_files">Archivos</string>
<string name="setup_tool_files_hint">Explorar y gestionar archivos</string>
+1 -1
View File
@@ -534,7 +534,7 @@
<string name="setup_choose">Choisir</string>
<string name="setup_linux_apps">Applications Linux (bêta)</string>
<string name="setup_store">Boutique Flathub</string>
<string name="setup_store_on">Affiché dans le menu. Certaines applications peuvent ne pas se lancer ; les journaux se trouvent dans Download/DroidDeck.</string>
<string name="setup_store_on">Affiché dans le menu. Certaines applications peuvent ne pas se lancer.</string>
<string name="setup_store_off">Installer des applications et des jeux Linux depuis Flathub</string>
<string name="setup_tool_files">Fichiers</string>
<string name="setup_tool_files_hint">Parcourir et gérer les fichiers</string>
+1 -1
View File
@@ -638,7 +638,7 @@
<string name="setup_choose">選択</string>
<string name="setup_linux_apps">Linuxアプリ(ベータ版)</string>
<string name="setup_store">Flathubストア</string>
<string name="setup_store_on">メニューに表示されます。一部のアプリは起動できない場合があります。ログはDownload/DroidDeckにあります。</string>
<string name="setup_store_on">メニューに表示されます。一部のアプリは起動できない場合があります。</string>
<string name="setup_store_off">FlathubからLinuxアプリとゲームをインストール</string>
<string name="setup_tool_files">ファイル</string>
<string name="setup_tool_files_hint">ファイルの閲覧と管理</string>
+1 -1
View File
@@ -638,7 +638,7 @@
<string name="setup_choose">선택</string>
<string name="setup_linux_apps">Linux 앱(베타)</string>
<string name="setup_store">Flathub 스토어</string>
<string name="setup_store_on">메뉴에 표시됩니다. 일부 앱은 실행되지 않을 수 있습니다. 로그는 Download/DroidDeck에 있습니다.</string>
<string name="setup_store_on">메뉴에 표시됩니다. 일부 앱은 실행되지 않을 수 있습니다.</string>
<string name="setup_store_off">Flathub에서 Linux 앱 및 게임 설치</string>
<string name="setup_tool_files">파일</string>
<string name="setup_tool_files_hint">파일 탐색 및 관리</string>
+1 -1
View File
@@ -536,7 +536,7 @@
<string name="setup_choose">Выбрать</string>
<string name="setup_linux_apps">Приложения Linux (бета)</string>
<string name="setup_store">Магазин Flathub</string>
<string name="setup_store_on">Показывается в меню. Некоторые приложения могут не запускаться; журналы в Download/DroidDeck.</string>
<string name="setup_store_on">Показывается в меню. Некоторые приложения могут не запускаться.</string>
<string name="setup_store_off">Устанавливать приложения и игры Linux из Flathub</string>
<string name="setup_tool_files">Файлы</string>
<string name="setup_tool_files_hint">Просмотр и управление файлами</string>
+1 -1
View File
@@ -638,7 +638,7 @@
<string name="setup_choose">选择</string>
<string name="setup_linux_apps">Linux 应用(测试版)</string>
<string name="setup_store">Flathub 商店</string>
<string name="setup_store_on">显示在菜单中。部分应用可能无法启动;日志位于 Download/DroidDeck。</string>
<string name="setup_store_on">显示在菜单中。部分应用可能无法启动。</string>
<string name="setup_store_off">从 Flathub 安装 Linux 应用和游戏</string>
<string name="setup_tool_files">文件</string>
<string name="setup_tool_files_hint">浏览和管理文件</string>
+1 -1
View File
@@ -638,7 +638,7 @@
<string name="setup_choose">選擇</string>
<string name="setup_linux_apps">Linux 應用程式(測試版)</string>
<string name="setup_store">Flathub 商店</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動;記錄位於 Download/DroidDeck。</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動。</string>
<string name="setup_store_off">從 Flathub 安裝 Linux 應用程式和遊戲</string>
<string name="setup_tool_files">檔案</string>
<string name="setup_tool_files_hint">瀏覽及管理檔案</string>
+1 -1
View File
@@ -638,7 +638,7 @@
<string name="setup_choose">選擇</string>
<string name="setup_linux_apps">Linux 應用程式(測試版)</string>
<string name="setup_store">Flathub 商店</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動;日誌位於 Download/DroidDeck。</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動。</string>
<string name="setup_store_off">從 Flathub 安裝 Linux 應用程式和遊戲</string>
<string name="setup_tool_files">檔案</string>
<string name="setup_tool_files_hint">瀏覽和管理檔案</string>
+1 -1
View File
@@ -643,7 +643,7 @@
<string name="setup_choose">Choose</string>
<string name="setup_linux_apps">Linux apps (beta)</string>
<string name="setup_store">Flathub Store</string>
<string name="setup_store_on">In the menu. Some apps may not start; logs are in Download/DroidDeck.</string>
<string name="setup_store_on">In the menu. Some apps may not start.</string>
<string name="setup_store_off">Install Linux apps and games from Flathub</string>
<string name="setup_tool_files">Files</string>
<string name="setup_tool_files_hint">Browse and manage files</string>
@@ -55,4 +55,37 @@ class LogRedactorTest {
assertEquals(once, LogRedactor.redact(once))
}
}
@Test fun quotedAndShortSecretsAreRedacted() {
for (line in listOf("\"access_token\": \"short-secret\"", "\"password\"=\"abc\"", "pwd=x")) {
val out = LogRedactor.redact(line)
assertTrue(out.contains("<redacted:token>"))
assertEquals(out, LogRedactor.redact(out))
}
}
@Test fun authorizationHeadersAreRedacted() {
for (line in listOf("Authorization: Bearer secret-value", "Proxy-Authorization: Basic dXNlcjpwYXNz",
"\"Authorization\":\"Bearer secret-value\"")) {
val out = LogRedactor.redact(line)
assertFalse(out.contains("secret-value"))
assertFalse(out.contains("dXNlcjpwYXNz"))
assertTrue(out.contains("<redacted:authorization>"))
assertEquals(out, LogRedactor.redact(out))
}
}
@Test fun quotedSecretsWithSpacesAndEscapedQuotesAreFullyWithheld() {
val lines = listOf(
"password=\"my secret phrase\"",
"password='my secret phrase'",
"\"access_token\":\"my \\\"secret\\\" phrase\"",
)
for (line in lines) {
val out = LogRedactor.redact(line)
assertFalse(out.contains("phrase"))
assertFalse(out.contains("secret"))
assertTrue(out.contains("<redacted:token>"))
assertEquals(out, LogRedactor.redact(out))
}
}
}
@@ -0,0 +1,100 @@
package com.droiddeck.launcher.session
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.nio.file.Files
class SessionLogMigrationTest {
@get:Rule val tmp = TemporaryFolder()
private fun source(name: String = "2026-10-06-01-steam"): File = tmp.newFolder(name).apply {
File(this, "steam").mkdir()
File(this, "session.log").writeText("Using JWT 25484942796017334\n")
File(this, "steam/console_log.txt").writeText("password=private\n")
File(this, ".complete").writeText("done")
}
@Test fun legacySessionsMoveIntoPrivateStorage() {
val source = source()
val target = tmp.newFolder("private")
SessionLogMigration.move(source, target)
assertFalse(source.exists())
val moved = File(target, source.name)
assertTrue(SessionPaths.isSessionFolder(moved))
assertTrue(File(moved, "steam/console_log.txt").readText().contains("password=private"))
assertTrue(File(moved, ".complete").isFile)
}
@Test fun crossFilesystemFallbackCopiesEverythingBeforeRemovingTheOriginal() {
val original = source()
val source = object : File(original.path) {
override fun renameTo(dest: File): Boolean = false
}
val target = tmp.newFolder("private")
SessionLogMigration.move(source, target)
assertFalse(original.exists())
assertEquals("Using JWT 25484942796017334\n", File(target, "${original.name}/session.log").readText())
assertEquals(listOf(original.name), target.list()!!.toList())
}
@Test fun aCopyFailurePreservesAllOriginalFiles() {
val original = source()
val source = object : File(original.path) {
override fun renameTo(dest: File): Boolean = false
}
val target = tmp.newFolder("private")
target.setWritable(false)
try {
assertThrows(java.io.IOException::class.java) { SessionLogMigration.move(source, target) }
} finally {
target.setWritable(true)
}
assertTrue(File(original, "session.log").isFile)
assertTrue(File(original, "steam/console_log.txt").isFile)
assertTrue(target.list()!!.isEmpty())
}
@Test fun collisionsPreserveBothSessionsAndKeepLegacyNamesRecognizable() {
val original = source("session-20260930-180642-2")
val target = tmp.newFolder("private")
File(target, original.name).mkdir()
SessionLogMigration.move(original, target)
assertEquals(2, target.listFiles()!!.size)
assertTrue(target.listFiles()!!.all { SessionPaths.isSessionFolder(it) })
}
@Test fun linksAreRejectedWithoutReadingOrDeletingTheirTargets() {
val source = source()
val outside = tmp.newFile("outside").apply { writeText("outside data") }
Files.createSymbolicLink(File(source, "steam/connection_log.txt").toPath(), outside.toPath())
val target = tmp.newFolder("private")
assertThrows(IllegalStateException::class.java) { SessionLogMigration.move(source, target) }
assertTrue(File(source, "session.log").exists())
assertTrue(target.list()!!.isEmpty())
assertEquals("outside data", outside.readText())
}
@Test fun cleanupDoesNotFollowNestedDirectoryLinks() {
val source = source()
val outside = tmp.newFolder("outside")
val preserved = File(outside, "session.log").apply { writeText("outside data") }
Files.createSymbolicLink(File(source, "linked").toPath(), outside.toPath())
SessionLogFiles.deleteTree(source)
assertFalse(source.exists())
assertEquals("outside data", preserved.readText())
}
@Test fun aCopiedCollisionKeepsTheNewerSessionAsTheLatest() {
val original = source()
original.setLastModified(1000L)
val source = object : File(original.path) {
override fun renameTo(dest: File): Boolean = false
}
val target = tmp.newFolder("private")
val newer = File(target, original.name).apply { mkdir(); setLastModified(2000L) }
SessionLogMigration.move(source, target)
assertEquals(newer, target.listFiles()!!.sortedWith(SessionPaths.chronological).last())
}
}
@@ -1,9 +1,7 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.LogRedactor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
@@ -12,114 +10,197 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.io.RandomAccessFile
import java.io.StringWriter
import java.io.Writer
import java.nio.file.Files
import java.util.zip.ZipFile
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionLogShareTest {
@get:Rule val tmp = TemporaryFolder()
private val context get() = RuntimeEnvironment.getApplication()
private val secret = "Using JWT 25484942796017334 sessionid=abcdef123456 password=secret123"
private val leaked = listOf("25484942796017334", "abcdef123456", "secret123")
private val secret = "GET /x?sessionid=abcdef123456 200"
private val leaked = "abcdef123456"
private fun write(folder: File, path: String, text: String = "$secret\n"): File =
File(folder, path).apply { parentFile!!.mkdirs(); writeText(text) }
private fun zip(folder: File): Map<String, String> =
ZipFile(SessionLogShare.zipFolder(RuntimeEnvironment.getApplication(), folder)!!).use { z ->
ZipFile(SessionLogShare.zipFolder(context, folder)!!).use { z ->
z.entries().toList().associate { it.name.substringAfter('/') to z.getInputStream(it).bufferedReader().readText() }
}
/** A record as the session's ending writes it, listing [files] as they stand now. */
private fun record(folder: File, vararg files: String, rules: Int = LogRedactor.RULES_VERSION) {
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText(
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
private fun assertSafe(files: Map<String, String>) {
files.forEach { (name, text) -> leaked.forEach { assertFalse(name, text.contains(it)) } }
}
@Test fun aRecordedUnchangedFileGoesInAsItIs() {
@Test fun workingLogsAndCommandLogsUsePrivateStorage() {
assertEquals(File(context.filesDir, "logs"), SessionFiles.logDirectory(context))
assertEquals(SessionFiles.logDirectory(context), LinuxRuntime.debugLogDir(context))
assertTrue(File(LinuxRuntime.debugLogDir(context), SessionPaths.TOOLS_DIR).path.startsWith(context.filesDir.path + "/"))
val dir = SessionPaths.beginOrCurrent(context, "privacy-test")
try {
assertTrue(dir.path.startsWith(context.filesDir.path + "/") || dir.path.startsWith(context.cacheDir.path + "/"))
} finally {
SessionPaths.take()
SessionPaths.release(context, dir)
dir.deleteRecursively()
}
}
@Test fun forgedAndStaleScrubRecordsNeverBypassRedaction() {
val folder = tmp.newFolder("2026-10-06-01-steam")
// Stands in for a file the ending scrubbed; the share must not pass it through again.
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log")
assertTrue(zip(folder).getValue("session.log").contains(leaked))
val file = write(folder, "session.log")
write(folder, ".scrubbed-tree", "rules 1\n${file.length()}\t${file.lastModified()}\tsession.log\n")
write(folder, ".complete", "done")
assertSafe(zip(folder))
val modified = file.lastModified()
file.writeText("$secret\n")
file.setLastModified(modified)
assertSafe(zip(folder))
assertEquals(setOf("session.log"), zip(folder).keys)
}
@Test fun anythingTheRecordDoesNotVouchForIsScrubbed() {
@Test fun allowlistIncludesDiagnosticsAndExcludesCredentialStoresAndUnknownFiles() {
val folder = tmp.newFolder("2026-10-06-02-steam")
File(folder, "app.log").writeText("ok\n")
File(folder, "session.log").writeText("ok\n")
File(folder, "steam/deep").mkdirs()
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
File(folder, ".hidden.txt").writeText("$secret\n")
record(folder, "app.log", "session.log")
// Appended to after the ending (the app's log capture), and touched with an older time.
File(folder, "app.log").appendText("$secret\n")
File(folder, "session.log").apply { writeText("$secret\n".padEnd(3, ' ')); setLastModified(1_000L) }
File(folder, "events.jsonl").writeText("$secret\n")
val out = zip(folder)
for (name in listOf("app.log", "session.log", "steam/deep/nested.txt", ".hidden.txt", "events.jsonl"))
assertFalse(name, out.getValue(name).contains(leaked))
val allowed = listOf("session.log", "app.log", "crash-app.txt", "events.jsonl",
"steam/console_log.txt", "droiddeck-esync/launches.log", "droiddeck-fex/status.json")
val excluded = listOf(".hidden.txt", ".session.log.scrub", "steam/deep/nested.txt",
"steam/loginusers.vdf", "steam/config.vdf", "ssfn123", "arbitrary.txt",
"steam/token.txt", "droiddeck-fex/config/secrets.json")
(allowed + excluded).forEach { write(folder, it) }
val files = zip(folder)
assertEquals(allowed.toSet(), files.keys)
assertSafe(files)
}
@Test fun aRecordUnderOtherRedactorRulesVouchesForNothing() {
val folder = tmp.newFolder("2026-10-06-03-steam")
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log", rules = LogRedactor.RULES_VERSION - 1)
assertFalse(zip(folder).getValue("session.log").contains(leaked))
@Test fun oversizedLiveAndFinishedLogsAreOmittedWithoutRawFallback() {
for (finished in listOf(false, true)) for (size in listOf(SessionLogFiles.MAX_BYTES, SessionLogFiles.MAX_BYTES + 1)) {
val folder = tmp.newFolder("2026-10-06-${if (finished) "03" else "04"}-steam-$size")
write(folder, "app.log")
val large = write(folder, "session.log")
RandomAccessFile(large, "rw").use { it.setLength(size) }
if (finished) write(folder, ".complete", "done")
val files = zip(folder)
assertFalse(files.containsKey("session.log"))
assertTrue(files.getValue("omitted.txt").contains("session.log"))
assertSafe(files)
}
}
@Test fun withoutARecordEveryFileIsScrubbed() {
val folder = tmp.newFolder("2026-10-06-04-steam")
File(folder, "session.log").writeText("$secret\n")
File(folder, "steam").mkdirs()
File(folder, "steam/console_log.txt").writeText("$secret\n")
val out = zip(folder)
assertFalse(out.getValue("session.log").contains(leaked))
assertFalse(out.getValue("steam/console_log.txt").contains(leaked))
}
@Test fun theEndingScrubsEveryFolderAndRecordsWhatItScrubbed() {
@Test fun binaryDataPastTheProbeMalformedUtf8AndLongLinesAreOmitted() {
val folder = tmp.newFolder("2026-10-06-05-steam")
File(folder, "session.log").writeText("$secret\n")
File(folder, "droiddeck-esync").mkdirs()
File(folder, "droiddeck-esync/launches.log").writeText("$secret\n")
File(folder, "steam/deep").mkdirs()
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
SessionArtifacts.scrubAndMark(folder)
for (name in listOf("session.log", "droiddeck-esync/launches.log", "steam/deep/nested.txt"))
assertFalse(name, File(folder, name).readText().contains(leaked))
assertEquals(setOf("session.log", "droiddeck-esync/launches.log", "steam/deep/nested.txt"),
SessionArtifacts.scrubbedFiles(folder))
assertTrue(zip(folder).values.none { it.contains(leaked) })
write(folder, "session.log", "safe\n".repeat(2000) + "$secret\n\u0000")
File(folder, "app.log").writeBytes(byteArrayOf(0xc3.toByte(), 0x28))
write(folder, "crash.log", "x".repeat(65537) + secret)
val files = zip(folder)
assertEquals(setOf("omitted.txt"), files.keys)
assertSafe(files)
}
@Test fun aFileThatCouldNotBeScrubbedLeavesTheFolderUnrecorded() {
@Test fun symlinkFilesAndDirectoriesCannotExportOutsideData() {
val folder = tmp.newFolder("2026-10-06-06-steam")
File(folder, "session.log").writeText("$secret\n")
// A folder the scrubbed copy cannot be written into: the scrub fails, the original stays.
val outside = tmp.newFolder("outside")
val target = write(outside, "console_log.txt", "outside data\n")
Files.createSymbolicLink(File(folder, "session.log").toPath(), target.toPath())
Files.createSymbolicLink(File(folder, "steam").toPath(), outside.toPath())
val files = zip(folder)
assertEquals(setOf("omitted.txt"), files.keys)
assertTrue(files.values.none { it.contains("outside data") })
val alias = File(tmp.root, "2026-10-06-07-steam")
Files.createSymbolicLink(alias.toPath(), folder.toPath())
assertFalse(SessionPaths.isSessionFolder(alias))
assertNull(SessionLogShare.zipFolder(context, alias))
}
@Test fun failedTeardownScrubbingStillRedactsExports() {
val folder = tmp.newFolder("2026-10-06-08-steam")
val file = write(folder, "session.log")
folder.setWritable(false)
try {
SessionArtifacts.scrubAndMark(folder)
SessionArtifacts.scrubTree(folder)
} finally {
folder.setWritable(true)
}
assertTrue(File(folder, "session.log").readText().contains(leaked))
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
assertTrue(SessionArtifacts.scrubbedFiles(folder).isEmpty())
assertTrue(zip(folder).values.none { it.contains(leaked) })
assertTrue(file.readText().contains(leaked.first()))
assertSafe(zip(folder))
}
@Test fun steamLogsPastTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-07-steam")
File(folder, "session.log").writeText("ok\n")
File(folder, "steam").mkdirs()
File(folder, "steam/console_log.txt").writeText("ok\n")
File(folder, "steam/cef_log.previous.txt").outputStream().use { out ->
val line = ByteArray(1024) { 'x'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() }
repeat(9 * 1024) { out.write(line) }
@Test fun unreadableAllowedFilesAreOmitted() {
val folder = tmp.newFolder("2026-10-06-09-steam")
val file = write(folder, "session.log")
file.setReadable(false)
try {
val files = zip(folder)
assertEquals(setOf("omitted.txt"), files.keys)
assertSafe(files)
} finally {
file.setReadable(true)
}
val names = zip(folder).keys
assertTrue("steam/console_log.txt" in names)
assertFalse("steam/cef_log.previous.txt" in names)
}
@Test fun successfulTeardownScrubsNestedDiagnosticsWithoutRecords() {
val folder = tmp.newFolder("2026-10-06-10-steam")
val paths = listOf("session.log", "crash-app.txt", "droiddeck-esync/launches.log", "steam/console_log.txt")
paths.forEach { write(folder, it) }
SessionArtifacts.scrubTree(folder)
paths.forEach { path -> leaked.forEach { assertFalse(File(folder, path).readText().contains(it)) } }
assertSafe(zip(folder))
assertTrue(folder.walkTopDown().none { it.name.startsWith(".redacted-") })
}
@Test fun steamLogsAtTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-11-steam")
write(folder, "session.log")
val file = write(folder, "steam/console_log.txt")
RandomAccessFile(file, "rw").use { it.setLength(SessionLogFiles.STEAM_MAX_BYTES) }
val files = zip(folder)
assertFalse(files.containsKey("steam/console_log.txt"))
assertTrue(files.containsKey("omitted.txt"))
assertSafe(files)
}
@Test fun aGrowingFileIsLimitedToItsOpeningSnapshot() {
val folder = tmp.newFolder("2026-10-06-12-steam")
val file = write(folder, "session.log", "safe\n".repeat(2000) + "$secret\nunfinished")
val output = StringWriter()
var appended = false
val writer = object : Writer() {
override fun write(chars: CharArray, offset: Int, length: Int) {
if (!appended) { appended = true; file.appendText("appended-marker $secret\n") }
output.write(chars, offset, length)
}
override fun flush() = Unit
override fun close() = Unit
}
SessionLogFiles.scrubTo(folder, file, writer)
assertFalse(output.toString().contains("appended-marker"))
assertFalse(output.toString().contains("unfinished"))
assertTrue(output.toString().contains("<incomplete live line withheld>"))
leaked.forEach { assertFalse(output.toString().contains(it)) }
}
@Test fun aTruncatedFileFailsInsteadOfExportingAPartialSnapshot() {
val folder = tmp.newFolder("2026-10-06-13-steam")
val file = write(folder, "session.log", "safe\n".repeat(20000))
val writer = object : Writer() {
override fun write(chars: CharArray, offset: Int, length: Int) { file.writeText("") }
override fun flush() = Unit
override fun close() = Unit
}
assertThrows(java.io.IOException::class.java) { SessionLogFiles.scrubTo(folder, file, writer) }
}
@Test fun anOutputFailureDoesNotLeaveAShareableArchive() {
val folder = tmp.newFolder("2026-10-06-14-steam")
write(folder, "session.log")
assertThrows(IllegalStateException::class.java) {
SessionLogShare.zipFolder(context, folder) { throw IllegalStateException("failed output") }
}
val out = File(context.cacheDir, "shared-logs")
assertTrue(out.listFiles().orEmpty().isEmpty())
assertTrue(context.cacheDir.listFiles().orEmpty().none { it.name.startsWith("redacted-") })
}
}
+3 -1
View File
@@ -28,7 +28,7 @@ tools/droiddeckctl start desktop
tools/droiddeckctl run /usr/bin/foo -- arg1 arg2
tools/droiddeckctl stop
tools/droiddeckctl resume
tools/droiddeckctl logs latest ./session-artifacts
tools/droiddeckctl logs latest ./session-logs.zip
tools/droiddeckctl screenshot ./screen.png
```
@@ -39,3 +39,5 @@ Every command writes JSON to stdout and reports its resolved ADB serial to stder
The `state` response uses schema 1 and includes the build label, runtime version, session ID and phase, mode, requested program, suspend and first-frame state, output size, guest PID, failure details, and artifact paths. Phases are `IDLE`, `PREPARING`, `INSTALLING_RUNTIME`, `STARTING_COMPOSITOR`, `STARTING_GUEST`, `STARTING_STEAM`, `READY`, `SUSPENDED`, `STOPPING`, and `FAILED`. Each session also writes `events.jsonl` alongside its existing artifacts.
`tools/deploy_local.sh` uses the same device resolver. If multiple distinct devices are connected, select one with `ADB_SERIAL` or `ANDROID_SERIAL`.
`logs latest` exports the same sanitized ZIP as Share logs. Working logs stay in app-private storage; the command retrieves the ZIP through `run-as` on debug builds.
-402
View File
@@ -1,402 +0,0 @@
# Steam's touch controller in a DroidDeck session
Research notes, started 2026-10-07. The question: instead of DroidDeck drawing its own on-screen
pad and keeping its own profiles, can the session use the touch controller Steam already has for
the Steam Link app, so that touch layouts are per game, synced to the Steam account and shared
through Steam's community configs?
This page records what the Steam client contains, the candidate approaches, and the experiments
run on the Thor to decide between them; details are in the [Experiment log](#experiment-log).
## Conclusion
**Yes, and without streaming anything.** Steam's touch controller is a Steam Input controller type
(Mobile Touch, `controller_mobile_touch`) that Steam builds for any HID device with the ids
0000:11fb. Steam Link only supplies that device remotely; libfakeinput can supply it locally, the
way it already supplies the Deck pad. Shown on the Thor with an experimental build:
- Steam opens a local `/dev/hidraw17` 0000:11fb, builds the touch controller (type 43, the same
attributes as Steam Link's), loads the game's touch config for it (Valve's touch templates,
official per-game touch configs, the user's own synced ones, community ones), and games get
its input through Steam Input's virtual pad. A touch-controller stick report flew the ship in
Geometry Wars.
- Steam tells the device which app and action set are active (output report 4) and when action
set layers come and go (5, 6), live, plus rumble (1). That is what decides which layout to show.
- Big Picture treats it as a touch controller: the in-game menu shows the touch layout preview,
bindings are edited in Steam's own configurator.
- It can be plugged and unplugged mid-session (injected udev events), so it can step aside when
a physical pad is used, as Steam Link does.
- The layout is part of the config file (`touch_layout`, a `CVirtualControllerLayouts` protobuf),
so it syncs and is shared with the config. Steam loads a touch config written to disk.
**Recommended: approach D below.** DroidDeck draws the controls (from Steam's layout) and sends
the device's 40-byte report; Steam does everything else. It needs no stream, no pairing, no video
and no patching of Steam, and the parts it depends on are the ones Valve has to keep stable for
the Steam Link apps already installed on phones and TVs: the device's ids and report format.
Not settled yet: saving an edited layout goes through a file write rather than a Steam call (Steam
loads the written file and queues it for Steam Cloud like its own autosaves); the overlay must
reproduce Steam Link's default layout and its hiding of unbound controls; touch menus and gyro
were not exercised.
## How Steam Link's touch controller works
Sources: the arm64 client DroidDeck installs (`steam_client_steamdeck_publicbeta_linuxarm64`,
manifest version 1791249696), the protobuf definitions in
[SteamDatabase/Protobufs](https://github.com/SteamDatabase/Protobufs)
(`steam/steammessages_remoteplay.proto`, `steam/steammessages_virtualcontroller.proto`) and Valve's
[touch controller guide](https://steamcommunity.com/app/353380/discussions/4/1735462352489233412).
The work is split between the streaming client (what runs on the phone) and the Steam client being
streamed from (the host):
- **Client: drawing and editing.** `streaming_client` holds `CVirtualController`, built from
`streaming/client/virtualcontroller.cpp`: it draws the controls over the video, runs the layout
editor (tray, colour picker, move/scale), and sends raw touches to the host as
`CInputTouchFingerDownMsg` / `Motion` / `Up` (finger id, x and y normalised to the video).
- **Host: the controller.** `steamui.so` holds the stream server (`CStreamServer`,
`IStreamServerInputDelegate`). `steamclient.so` holds `CMobileTouchControllerAbstraction`, a
Steam Input controller backend next to `CSteamOSHandheldAbstraction` (the Deck),
`CSteamControllerAbstraction` and `CGenericGamepadControllerAbstraction`. Its display name is
"Steam Link Touch Controller" and its config type is `controller_mobile_touch`.
- **Host: the config.** The host owns the touch config and pushes it to the client:
`k_EStreamControlTouchConfigActive` (appid, revision, creator),
`GetTouchConfigData`/`SetTouchConfigData` (config data and layout blobs),
`SaveTouchConfigLayout` (the client sends back an edited layout), `Get`/`SetTouchIconData`,
`TouchActionSetActive` and `TouchActionSetLayerAdded`/`Removed`. Touch configs are Steam Input
configs like any other: per game, saved to the account, publishable. SteamInputDB counted
10,540 community configs for Mobile Touch in March 2026.
Every piece of this is in the arm64 package DroidDeck already installs: the host side in
`steamrtarm64/steamclient.so` and `steamui.so`, and the full renderer and editor in
`steamrtarm64/streaming_client`. The package also carries an `androidarm64/libsteamclient.so`
with the same touch strings.
## Where DroidDeck is today
The session's pad is presented to the Steam client as a Steam Deck controller (28de:1205 through a
served `hidraw` node and a written sysfs, see `SteamDeckPad.kt` and `fakeinput_steam.cpp`), so Deck
configs, per-game bindings and Deck community configs already apply. What Steam's touch controller
would add: control placement, icons, touch menus and on-device layout editing defined by Steam, and
the touch-specific community configs.
## Candidate approaches
| | How | Verdict |
|---|---|---|
| **A. Local Remote Play** | DroidDeck streams from its own Steam client the way the Steam Link app does (pairing, start stream, touch input negotiated). | **Works, not worth it.** The official Steam Link app on the Thor pairs with the session's Steam over loopback and its touch controls drive the session (experiment 2). But the host captures and software-encodes video (libx264, 72-85 % CPU, frames froze), the Steam Link app cannot turn video off, and an input-only client of our own means reimplementing the Remote Play transport and crypto. The protocol does have `enable_video_streaming` in the streaming request. Kept as a fallback only. |
| **B. In-process injection** | Feed touches into the path between the stream server (`steamui.so`) and `CMobileTouchControllerAbstraction` (`steamclient.so`). | **Not needed.** That path is a HID device; D supplies the device instead of patching Steam. |
| **C. Data only** | Read Steam's touch configs and layouts, draw them ourselves, keep feeding the Deck pad. | **Rejected.** Touch configs bind straight to keys, mouse and actions; honouring them would mean reimplementing Steam Input. (D still reads the layout from the config, but Steam does the bindings.) |
| **D. Local Mobile Touch device** | libfakeinput serves 0000:11fb as a local hidraw node; DroidDeck draws Steam's layout and writes the 40-byte report. | **Works (experiments 3, 4). Recommended.** |
## Experiments
1. **Host side alive?** Yes: discovery answers on loopback and Steam Link pairs.
2. **Touch controller over a stream?** Yes, end to end, with Steam Link on the same device.
3. **Loopback cost.** Too high: software video encode (part of 2).
4. **Input without video.** Not run: needs our own Remote Play client; superseded by D.
5. **Valve's renderer as an overlay.** Not run: `streaming_client` draws over decoded video and
lives behind the stream; superseded by D.
6. **Injection points.** The touch controller enters Steam as a HID device (0000:11fb), which is
approach D.
7. **Local 0000:11fb device.** Works: controller built, config loaded, games driven (section 3).
8. **Hotplug.** Works with injected udev events (section 4).
9. **Layout written to disk.** Steam loads it (section 5).
## Experiment log
### 1. Host side alive: yes (2026-10-07, Thor, Steam 1791249696)
- With a Steam session READY, the client listens on TCP 27036 and UDP 27036 (`/proc/net`, app
uid). A discovery probe built from `steammessages_remoteclient_discovery.proto` sent to
`127.0.0.1:27036` from the device gets a `CMsgRemoteClientBroadcastStatus` back: hostname
`DroidDeck`, `enabled_services` 98 (game streaming on), the signed-in user, `steam_deck`
unset, `gaming_device_type` 541.
- The official Steam Link app (Play Store, on the Thor's bottom screen while the session runs on
the top one) finds "DroidDeck" by itself, shows a PIN, and the session's Big Picture shows
**Authorize Device**. After the PIN the app runs its network test and lists DroidDeck as
paired. Pairing to the session's own client over loopback works with no changes.
- Launching Steam Link on display 0 instead puts DroidDeck's session activity into PiP; use
`am start --display 4`. On first start Steam Link sits on its splash until BLUETOOTH_CONNECT
is answered, and the permission dialog does not render on the second screen (granted with
`pm grant`).
### 2. Touch controller over the stream: works end to end
Starting a stream (`streaming_log.txt`, `console_log.txt` in the session's Steam `logs/`):
```
CLIENT: Sending HID device 2020/0112/-1 Xbox Wireless Controller at sdl://3
CLIENT: Sending HID device 0000/11fb/-1 Mobile Touch Control at touch://0
...
Remote Device Found type: 0000 11fb path: touch://0 Product: Mobile Touch Control
!! Steam controller device opened for index 1.
Controller device closed after hid_read failure
Controller 1 disconnected
```
- **The touch controller reaches the host as a remote HID device, 0000:11fb**, opened by the
same controller code that opens the Deck pad, and turned into a virtual controller. The
streaming client is what makes the reports; Steam on the host only sees a HID device.
- Video fails on the host: `PipeWire: Could not connect PipeWire context` (the session runs no
PipeWire), so the app gets audio but a black screen and keeps its loading spinner.
- The app then re-sends only the Thor's built-in pad and drops the touch device; it seems to
withdraw touch controls when a physical controller is present, or until video arrives.
With video fixed (below), **Steam's touch controller runs against the session's own client**:
- Steam Link withholds its touch controls while a physical pad is attached (the Thor's own pad
shows up as "Xbox Wireless Controller"). A four-finger tap opens its stream menu, which has
**Enable Touch Controls** (injected with `sendevent` on `/dev/input/event5`, the bottom panel).
- The client then re-sends `touch://0`; the host opens it as controller type 43, product 0x11fb,
serial `MT-<Steam Link device id>`, capabilities `0000007f83045bff`, creates a virtual controller
for it, and sends the client `TouchConfigActive`, `TouchActionSetActive` and
`SetTouchConfigData`. The app draws Big Picture's touch layout (d-pad, ABXY, Steam button,
keyboard, `...`).
- Touching the controls drives the session: the touch Steam button opens Big Picture's main
menu on the Thor's top screen, touch B closes it, and the session's glyphs switch to the touch
controller's. (D-pad taps from `input tap` did not register; not chased.)
- Cost: the host encodes with libx264 in software (`/dev/video-enc0` missing), 4 threads,
1240x698. CPU sat at 72-85 % in the overlay and `k_EStreamControlVideoOverflow` flooded the log;
the app's picture froze within a minute while input kept working. **Video loopback is not a
shippable path**; only the input half of the stream is useful.
Video fix used for this test only: PipeWire and WirePlumber are in the rootfs and gamescope is
built with PipeWire, so a `gamescope` wrapper on `PATH` (via `Download/droiddeck-env`) that starts
`pipewire` and `wireplumber` first gives gamescope a capture node (`stream available on node ID`)
and the client a picture. (Editing `droiddeck-session` on the device does not stick: the app
re-syncs the overlay each session.)
### Where Steam keeps touch configs
In the session's Steam, `steamapps/common/Steam Controller Configs/<account id>/config/`:
- `<appid>/controller_mobile_touch.vdf` for each game with a saved touch config (dozens already
there for this account, synced down from Steam Cloud), plus named copies like
`<appid>/default touch_0.vdf`;
- `configset_controller_mobile_touch.vdf`: which config each app uses (`autosave` = the per-app
file above, otherwise a template or workshop id);
- `configset_MT-<serial>.vdf`, `preferences_MT-<serial>.vdf` and `config/MT-<serial>_gyro.vdf`:
per touch device.
A touch config is an ordinary `controller_mappings` VDF (`controller_type` `controller_mobile_touch`,
bindings per action set and layer) with one extra key, **`touch_layout`: the on-screen layout as
a hex-encoded `CVirtualControllerLayouts` protobuf**: one layout per action set, each a list of
elements (`EControllerElementType`, visible, x/y position normalised to the screen, x/y scale)
and a colour, plus input mode, mouse mode and pinch-zoom settings. Bindings and layout travel
together in the one file that syncs and is shared as a community config.
### The touch device's HID protocol
From Steam Link for Android (`libmain.so`, exported symbols; `CVirtualController` is both the
renderer and the HID device behind `touch://0`):
- **Input report: 40 bytes** (`CVirtualController::Read`), kept at `this+200` and marked dirty
at `this+240` by every setter. Bytes 0-7: button/touch bits (e.g. bit 27, 19, 20: trackpads
0, 1, 2 touched). Bytes 16, 20, 24: trackpads 0-2 as int16 x (centred, `x*65535 ^ 0x8000`) and
y (inverted). Remaining fields (sticks, triggers, gyro) not yet mapped.
`CHIDDeviceReportGenerator::BInjectGamepadStateMobileTouch` is a stub; the report is the
controller's own format, not the generic SDL gamepad state.
- **Output reports from Steam** (`Write` → `QueueFeatureReport` → `HandleFeatureReports`),
at least 17 bytes, first byte the type:
- 1: rumble (u16 low, u16 high, u32 duration);
- 3: setting `0x30` with a u16 value (a flag at `this+1488`, likely gyro);
- **4: action set change** (u32 appid, u32 action set id): switches the layout shown;
- **5 / 6: action set layer added / removed** (u32 appid, u32 layer id).
- **Feature report 2**: battery (level, from `SDL_GetPowerInfo`), 17 bytes.
So Steam drives action sets, layers and rumble over HID. The only things that come solely over
the stream are the config and layout blobs (`SetTouchConfigData`), the active config's
appid/revision/creator (`TouchConfigActive`) and custom icons (`SetTouchIconData`); the first two
are on disk in the VDF above.
### 3. Without a stream: Steam takes a local 0000:11fb device (works)
Experimental build on this branch: `FAKE_EVDEV_TOUCHCTL=1` (in `Download/droiddeck-env`) makes
libfakeinput serve `/dev/hidraw17` as 0000:11fb "Mobile Touch Control" next to the Deck pad, with
its sysfs written by `SteamDeckPad.prepare` (a second USB device, `usb2`). The 40-byte input report
is read from `/tmp/touchctl.report` in the session; every output and feature report the client
sends is logged to `pad.log` and appended to `/tmp/touchctl.out`.
- With a vendor-page report descriptor (`06 ff ff 09 01`, as the Deck's) the client walks the
whole sysfs tree, reads the descriptor and never opens the node. **With Generic Desktop / Game
Pad (`05 01 09 05`) it opens it**: for a non-Valve vendor id the client wants a gamepad usage.
- Steam then builds the touch controller exactly as it does for Steam Link:
```
Local Device Found type: 0000 11fb path: /dev/hidraw17 serial_number: MT-DROIDDECK0001
!! Controller 0 attributes: Type: 43 ProductID: 4603 Serial: MT-MT-DROIDDECK0001
Capabilities: 0000007f83045bff
```
and speaks the touch protocol to it: `get-feature 02` (battery), output `03 30 ..` (the setting
report), and **output `04 01 03 00 00 01 00 00 00`: action set 1 of app 769** (Big Picture).
- Writing button bits into the report drives the client: Steam (`0x2000`) opens Big Picture's
main menu, B (`0x20`) closes it. Opening the menu made Steam send `04` with app 443510 (the
Steam menu's own touch config; it is one of the app folders in the config directory) and
closing it `04` with 769 / 1 again: **the active app and action set arrive over HID, live.**
Button bits (Steam Link's `CVirtualController` table at `0x463e70`, indexed by
`EControllerElementType - 1`), the same layout as the Deck report's low word:
| Element | Bit | | Element | Bit |
|---|---|---|---|---|
| A | 7 | | Select | 12 |
| B | 5 | | Steam | 13 |
| X | 6 | | Start | 14 |
| Y | 4 | | Left stick click | 22 |
| Left bumper | 3 | | Right stick click | 26 |
| Right bumper | 2 | | Macro 0-7 | 32-39 |
| Left trigger | 1 | | 1-finger / 2-finger macro | 48, 49 |
| Right trigger | 0 | | Trackpad 0 / 1 / 2 touched | 27 / 19 / 20 |
Report layout, all little-endian (Steam Link `CVirtualController`: `TouchControl_JoyButton`,
`TouchControl_JoyStick`, `SetTrackpad`, `UpdateControllerState`):
| Bytes | Field |
|---|---|
| 0-7 | u64 buttons and touch flags (table above; d-pad as the Deck's: up 8, right 9, left 10, down 11; left / right stick touched 46 / 47) |
| 8-15 | int16 left X, left Y, right X, right Y: `x * 32767`, Y stored inverted (`~(y * 32767)`) |
| 16-27 | three trackpads, int16 x (`x * 65535 ^ 0x8000`) and y (`0x7fff - y * 65535`) |
| 28-33 | accelerometer xyz, int16, ±2 g (19.61 m/s²) to ±32767 |
| 34-39 | gyro xyz, int16 |
**Games, through Steam Input, with no stream.** With the session started on Geometry Wars:
Retro Evolved (8400) and the game launched by pressing A twice on the local device, the client
loaded `controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf` for app 8400 on the
touch controller (Valve's stock touch template), told the device `04 d0 20 00 00 ...` (app 8400),
and a left-stick report flew the ship across the screen. Steam's own path end to end:
DroidDeck → `/dev/hidraw17` → Mobile Touch controller → the game's touch config → Steam Input's
virtual Xbox pad → the game. D-pad bits navigated the Steam menu the same way.
What the stream gives that the local device does not:
- **The active config and its layout.** Steam Link asks for it (`GetTouchConfigData`) and the host
answers with the config and the layout. Locally the device is told only the app id and action
set (report 4), so the overlay has to resolve the config itself: `configset_controller_mobile_touch.vdf`
per app (`autosave` = `<appid>/controller_mobile_touch.vdf`, otherwise a template or workshop
config), and the console log line `Loaded Config for ... App ID <n>, Controller <i>: <path>`
names the file Steam actually loaded. Stock templates carry no `touch_layout`; Steam Link draws
its built-in default layout for them (`CVirtualController::ResetLayoutToDefault`), hiding
elements the config leaves unbound (`UpdateElementAvailability`).
- **Saving an edited layout.** Steam Link sends `SaveTouchConfigLayout`; the host writes it into
the app's autosave config, which is what syncs. The local device has no such message. Big
Picture's `SteamClient.Input` API (seen in `steamui/sp.js`) has the config editing calls
(`StartEditingControllerConfigurationForAppIDAndControllerIndex`,
`SetEditingControllerConfigurationMiscSetting`, `SaveEditingControllerConfiguration`,
`GetConfigForAppAndController`, `QueryControllerConfigsForApp`, `SetSelectedConfigForApp`,
`GetTouchMenuIconsForApp`, `RegisterForTouchMenuMessages`) but no layout call; whether
`touch_layout` goes through the misc-setting call is untested. The session's devtools port only
admits guest processes (`BL_CDP_GUARD`), so this needs the agent bridge's guest commands rather
than a probe from adb.
- **Custom icons** (`SetTouchIconData`).
Everything else (bindings, action sets, layers, touch menus, rumble, the configurator, community
configs, cloud sync) is Steam's own and works with the local device.
### 4. Two controllers, and hotplug
With the touch device present beside the Deck pad, Steam creates a virtual pad for each
(`Created virtual controller at slot 0 for controller 0` / `slot 1 for controller 1`): a game
sees two players. Steam Link avoids this by withdrawing its touch controls while a physical pad is
in use, and a local device has to do the same, which needs hotplug.
- **Unplug works as is.** Ending the device's report stream (`/tmp/touchctl.off` in the experiment)
gives `Controller device closed after hid_read failure`, `Controller 0 disconnected`, and the
virtual pad is destroyed. Steam re-enumerates at once, and an open refused then keeps it off.
- **Plugging back in needs an event.** The client watches only `/dev/input` with inotify (already
redirected by libfakeinput) and never rescans hidraw on its own; an inotify event in
`/dev/input` did not trigger a HID rescan. Its HID discovery is SDL's, driven by a udev monitor,
and the session's monitor is `udevmon.c`'s silent stand-in (the sandbox refuses netlink).
- **Injected udev events work.** The experiment extends the stand-in: a file in `/tmp/udev-inject`
(`ACTION`, `DEVPATH`, `SUBSYSTEM=hidraw`, `DEVNAME`, `MAJOR`, `MINOR`) is sent by every process
with a stand-in as udevd's message format (`libudev` header, magic `0xfeedcafe`, properties plus
`SEQNUM`), and the stand-in's `recvmsg` (through `ntsync.c`, which owns the symbol) reports the
udev multicast group as the sender and root credentials, as libudev requires. An injected `add`
for `hidraw17` made the client open the node again within a second and rebuild the touch
controller (type 43) and its virtual pad, mid-session. (The sender address has to be written
from the room `msg_namelen` had before the call; a unix socket sets it to 0.)
So DroidDeck can show and hide Steam's touch controller the way Steam Link does: plug the device
in when the on-screen controls are shown, unplug it when a physical pad takes over.
### 5. Configs and layouts written by DroidDeck
With the session stopped, a `config/8400/controller_mobile_touch.vdf` was written (Valve's gamepad
template plus a `touch_layout` taken from another config) and `"8400" { "autosave" "1" }` added to
`configset_controller_mobile_touch.vdf`. Launching the game:
```
Loaded Config for Local Selection Path for App ID 8400, Controller 0:
.../Steam Controller Configs/392297941/config/8400/controller_mobile_touch.vdf
```
Steam used it as the game's touch config and left the file (and its `touch_layout`) as written.
**Steam Cloud picked it up too**: Steam Controller Configs sync as app 241100's cloud files, and
`userdata/<account>/241100/remotecache.vdf` gained an entry for
`392297941/config/8400/controller_mobile_touch.vdf` (`syncstate` 3, `remotetime` 0: queued for
upload), the same bookkeeping as the account's other touch configs. Both files were put back
afterwards.
Also seen: pressing A on the touch device logged `Seating controller 1 in slot 0`. Steam moves the
controller in use to the first player slot, which softens the two-controller problem even before
the device is unplugged.
### 6. Steam Link's default layout
Stock templates carry no `touch_layout`. Steam Link then places each control from a built-in table
(`CVirtualController::BInitializeDefaultElement`, table at `0x463d48`, positions on a 1280x720
reference):
| Element | Position (of 1280x720) |
|---|---|
| Thumb (menu) | 75, 75 |
| Select / Steam / Start | 516, 75 / 636, 75 / 756, 75 |
| Paste / Keyboard | 1115, 75 / 1205, 75 |
| Magnifying glass / record / playback | 1205, 165 / 255 / 345 |
| D-pad | 200, 525 |
| X / Y / B / A | 1003, 527 / 1083, 447 / 1163, 527 / 1083, 607 |
Sticks, triggers, bumpers and macros are not in the table; they appear when the config binds them
(`UpdateElementAvailability`), and the overlay has to reproduce that rule.
## What building D would take
- **libfakeinput:** the 0000:11fb node as in the experiment (Generic Desktop / Game Pad report
descriptor, 40-byte input reports, output reports 1, 3-6 and feature report 2), fed from a
ring the app writes, like the Deck pad's.
- **SteamDeckPad.kt:** the second device's sysfs, as in the experiment.
- **udevmon.c:** event injection for plug and unplug, with a proper channel from the app instead of
the experiment's file drop.
- **The overlay (Kotlin):** read the active config (configset per app, else the template Steam
logged loading), decode `touch_layout` (or the default table above), show the elements of the
action set Steam names in report 4 and the layers in 5/6, hit-test touches into the report
(buttons, sticks, trackpads; motion from PadMotion into the gyro fields), rumble from report 1.
Hide the unbound controls as Steam Link does.
- **Editing:** move/scale in the overlay, saved by writing `touch_layout` into the app's autosave
config, as Steam does when Steam Link saves a layout.
- **Policy:** plug the device in while the on-screen controls are up and no physical pad is in use;
unplug it otherwise.
The experimental pieces on this branch (`FAKE_EVDEV_TOUCHCTL`, `/tmp/touchctl.*`,
`/tmp/udev-inject`) are research scaffolding to be replaced, not shipped.
### 7. Several controllers
`FAKE_EVDEV_TOUCHCTL=2` serves two touch devices (`/dev/hidraw17` and `18`, serials
`MT-DROIDDECK0001` and `0002`, each with its own sysfs `usb2`/`usb3` and report file). With the
Deck pad that is three controllers, and Steam takes all three:
```
Controller 15 Type 4 (Deck pad, /dev/hidraw16)
Controller 0 Type 43 Serial MT-MT-DROIDDECK0001
Controller 1 Type 43 Serial MT-MT-DROIDDECK0002
Created virtual controller at slot 0 / 1 / 2
uinput: "Microsoft X-Box 360 pad 0" / "pad 1" / "pad 2" is /dev/input/event16 / 17 / 18
```
Each gets its own Steam Input config and its own virtual pad, so a game sees three players; a
Steam press on the second device alone opened the Steam menu (Steam answered it with report 4 for
the menu's action set). Several touch controllers would allow, say, a second player on the Thor's
bottom screen. The other physical pads DroidDeck passes through (ring slots 1-3 as evdev pads) sit
beside these as ordinary gamepads; no external pad was connected for this test.
+14 -11
View File
@@ -71,14 +71,14 @@ def _content_result(output: str) -> dict:
raise ControlError("Could not decode the agent provider response", "INVALID_PROVIDER_RESPONSE") from exc
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None) -> dict:
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None, timeout: int = 30) -> dict:
command = ["shell", "content", "call", "--uri", AUTHORITY, "--method", method]
if arg is not None:
command.extend(["--arg", arg])
if request is not None:
encoded = base64.b64encode(json.dumps(request, separators=(",", ":")).encode()).decode()
command.extend(["--extra", f"request:s:{encoded}"])
result = run_adb(adb, serial, *command)
result = run_adb(adb, serial, *command, timeout=timeout)
output = (result.stdout + result.stderr).decode(errors="replace")
response = _content_result(output)
if result.returncode != 0 and response.get("ok") is not False:
@@ -248,15 +248,18 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if not session.get("running") and session.get("artifactsAvailable") and not session.get("artifactsComplete"):
state = wait_for_artifacts(adb, serial, state, args.timeout)
session = state.get("session", {})
remote_dir = session.get("logDir")
if not remote_dir or not session.get("id") or not session.get("artifactsAvailable"):
raise ControlError("No session artifact directory is available", "NO_SESSION_LOGS")
destination = Path(args.destination or session["id"]).expanduser().resolve()
result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120)
response = provider_call(adb, serial, "logs", timeout=120)
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", "log export failed"), error.get("code", "LOG_EXPORT_FAILED"))
destination = Path(args.destination or f"{response['sessionId']}.zip").expanduser().resolve()
result = run_adb(adb, serial, "exec-out", "run-as", "com.droiddeck.launcher", "cat", response["path"], timeout=120)
if result.returncode != 0:
detail = (result.stderr or result.stdout).decode(errors="replace").strip()
raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED")
return add_serial({"ok": True, "command": "logs", "sessionId": session["id"], "path": str(destination)}, serial)
detail = result.stderr.decode(errors="replace").strip()
raise ControlError(detail or "log export failed", "LOG_PULL_FAILED")
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(result.stdout)
return add_serial({"ok": True, "command": "logs", "sessionId": response["sessionId"], "path": str(destination)}, serial)
if args.command == "screenshot":
destination = Path(args.path).expanduser().resolve()
@@ -302,7 +305,7 @@ def build_parser() -> argparse.ArgumentParser:
stop.add_argument("--timeout", type=float, default=90)
commands.add_parser("resume", help="resume a suspended session")
logs = commands.add_parser("logs", help="pull the latest session artifact directory")
logs = commands.add_parser("logs", help="export sanitized session logs as a ZIP")
logs.add_argument("which", choices=["latest"])
logs.add_argument("destination", nargs="?")
logs.add_argument("--timeout", type=float, default=90)
-5
View File
@@ -1237,14 +1237,9 @@ static void ns_received(struct msghdr *msg) {
}
}
int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int),
ssize_t *result) __attribute__((visibility("hidden")));
ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
static ssize_t (*real)(int, struct msghdr *, int);
if (!real) real = (ssize_t (*)(int, struct msghdr *, int))dlsym(RTLD_NEXT, "recvmsg");
ssize_t answered;
if (msg && bl_udevmon_recvmsg(fd, msg, flags, real, &answered)) return answered;
ssize_t r = real(fd, msg, flags);
if (r >= 0 && msg && msg->msg_control && msg->msg_controllen && ns_on()) {
int saved = errno;
-184
View File
@@ -32,10 +32,6 @@
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <endian.h>
#include <stdio.h>
#include <time.h>
struct stand_in {
int fd; /* the descriptor handed out, -1 when the slot is free */
@@ -99,11 +95,8 @@ static int is_wine_process(void) {
return known == 1;
}
static void start_injector(void);
static int make_stand_in(int type) {
int sv[2];
start_injector();
int saved = errno;
int flags = SOCK_DGRAM | (type & (SOCK_CLOEXEC | SOCK_NONBLOCK));
if (socketpair(AF_UNIX, flags, 0, sv) != 0) {
@@ -196,180 +189,3 @@ int setsockopt(int fd, int level, int optname, const void *optval, socklen_t opt
}
return real_setsockopt(fd, level, optname, optval, optlen);
}
/* EXPERIMENT (docs/development/steam-touch-controller.md): hotplug through the stand-in.
*
* A file dropped in INJECT_DIR is a udev event: KEY=VALUE lines (ACTION, DEVPATH, SUBSYSTEM,
* DEVNAME, MAJOR, MINOR...). It is sent to every stand-in as udevd would send it to the "udev"
* group, and recvmsg below dresses it as udevd's: the udev multicast group as the sender address
* and root credentials, without which libudev drops a message. SDL's HID discovery counts an
* add or remove and enumerates again, so a hidraw node can come and go while the client runs. */
#define INJECT_DIR "/tmp/udev-inject"
struct monitor_netlink_header {
char prefix[8];
unsigned magic;
unsigned header_size;
unsigned properties_off;
unsigned properties_len;
unsigned filter_subsystem_hash;
unsigned filter_devtype_hash;
unsigned filter_tag_bloom_hi;
unsigned filter_tag_bloom_lo;
};
static unsigned murmur_hash2(const char *key, size_t len) {
/* systemd's string_hash32 (MurmurHash2, seed 0) */
const unsigned m = 0x5bd1e995;
const int r = 24;
unsigned h = (unsigned)len;
const unsigned char *data = (const unsigned char *)key;
while (len >= 4) {
unsigned k;
memcpy(&k, data, 4);
k *= m; k ^= k >> r; k *= m;
h *= m; h ^= k;
data += 4; len -= 4;
}
switch (len) {
case 3: h ^= data[2] << 16; /* fallthrough */
case 2: h ^= data[1] << 8; /* fallthrough */
case 1: h ^= data[0]; h *= m;
}
h ^= h >> 13; h *= m; h ^= h >> 15;
return h;
}
static void inject_file(const char *path, unsigned long long seqnum) {
char text[2048];
FILE *f = fopen(path, "re");
if (f == NULL) return;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
text[n] = '\0';
char props[2300];
size_t used = 0;
char subsystem[64] = "";
char *save = NULL;
for (char *line = strtok_r(text, "\n", &save); line != NULL; line = strtok_r(NULL, "\n", &save)) {
size_t len = strlen(line);
if (len == 0 || used + len + 1 > sizeof(props) - 64) continue;
if (strncmp(line, "SUBSYSTEM=", 10) == 0) snprintf(subsystem, sizeof(subsystem), "%s", line + 10);
memcpy(props + used, line, len + 1);
used += len + 1;
}
used += (size_t)snprintf(props + used, sizeof(props) - used, "SEQNUM=%llu", seqnum) + 1;
struct monitor_netlink_header header;
memset(&header, 0, sizeof(header));
memcpy(header.prefix, "libudev", 8);
header.magic = htobe32(0xfeedcafe);
header.header_size = sizeof(header);
header.properties_off = sizeof(header);
header.properties_len = (unsigned)used;
header.filter_subsystem_hash = htobe32(murmur_hash2(subsystem, strlen(subsystem)));
char message[sizeof(header) + sizeof(props)];
memcpy(message, &header, sizeof(header));
memcpy(message + sizeof(header), props, used);
int sent = 0;
pthread_mutex_lock(&lock);
for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) {
if (stand_ins[i].fd == -1) continue;
if (send(stand_ins[i].peer, message, sizeof(header) + used, MSG_DONTWAIT | MSG_NOSIGNAL) > 0) sent++;
}
pthread_mutex_unlock(&lock);
FILE *done = fopen(INJECT_DIR "/.log", "ae");
if (done) {
char exe[PATH_MAX] = "";
ssize_t len = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
if (len > 0) exe[len] = '\0';
fprintf(done, "%s: pid %d (%s) sent to %d stand-in(s)\n", path, (int)getpid(), exe, sent);
fclose(done);
}
}
static void *injector(void *arg) {
(void)arg;
unsigned long long seqnum = 900000;
/* Every process with a stand-in sends each event file once (the client is one of several), so
* files are never claimed; whoever sees one older than a few seconds removes it. */
static char seen[32][128];
size_t next_seen = 0;
for (;;) {
DIR *dir = opendir(INJECT_DIR);
if (dir != NULL) {
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue;
char path[300];
snprintf(path, sizeof(path), INJECT_DIR "/%s", entry->d_name);
struct stat st;
if (stat(path, &st) != 0) continue;
if (time(NULL) - st.st_mtime > 5) {
unlink(path);
continue;
}
char key[128];
snprintf(key, sizeof(key), "%s:%lu", entry->d_name, (unsigned long)st.st_ino);
int done = 0;
for (size_t i = 0; i < 32; i++)
if (strcmp(seen[i], key) == 0) done = 1;
if (done) continue;
snprintf(seen[next_seen++ % 32], sizeof(seen[0]), "%s", key);
inject_file(path, ++seqnum);
}
closedir(dir);
}
struct timespec interval = {0, 100 * 1000 * 1000};
nanosleep(&interval, NULL);
}
return NULL;
}
static void spawn_injector(void) {
pthread_t thread;
if (pthread_create(&thread, NULL, injector, NULL) == 0) pthread_detach(thread);
}
static void start_injector(void) {
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, spawn_injector);
}
/* For ntsync.c's recvmsg(), which owns the symbol: 1 when fd was a stand-in and was answered here
* (*result holds what recvmsg returns), 0 when it is not one. */
__attribute__((visibility("hidden"))) int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags,
ssize_t (*real_recvmsg)(int, struct msghdr *, int),
ssize_t *result) {
if (!is_stand_in(fd)) return 0;
size_t control_room = msg->msg_controllen;
socklen_t name_room = msg->msg_namelen;
ssize_t n = real_recvmsg(fd, msg, flags);
*result = n;
if (n >= 0) {
FILE *log = fopen(INJECT_DIR "/.recv", "ae");
if (log) {
fprintf(log, "pid %d fd %d got %zd bytes, name room %u, control room %zu\n", (int)getpid(), fd, n,
(unsigned)name_room, control_room);
fclose(log);
}
}
if (n < 0) return 1;
if (msg->msg_name != NULL && name_room >= sizeof(struct sockaddr_nl)) {
struct sockaddr_nl nl;
memset(&nl, 0, sizeof(nl));
nl.nl_family = AF_NETLINK;
nl.nl_groups = 2; /* udev's multicast group */
memcpy(msg->msg_name, &nl, sizeof(nl));
msg->msg_namelen = sizeof(nl);
}
if (msg->msg_control != NULL && control_room >= CMSG_SPACE(sizeof(struct ucred))) {
struct cmsghdr *cmsg = (struct cmsghdr *)msg->msg_control;
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
struct ucred cred = {.pid = 1, .uid = 0, .gid = 0};
memcpy(CMSG_DATA(cmsg), &cred, sizeof(cred));
msg->msg_controllen = CMSG_SPACE(sizeof(struct ucred));
}
return 1;
}
+51
View File
@@ -0,0 +1,51 @@
import argparse
import importlib.machinery
import importlib.util
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
loader = importlib.machinery.SourceFileLoader("droiddeckctl", str(TOOLS / "droiddeckctl"))
spec = importlib.util.spec_from_loader(loader.name, loader)
ctl = importlib.util.module_from_spec(spec)
loader.exec_module(ctl)
class LogExportTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.destination = Path(self.tmp.name) / "session.zip"
self.args = argparse.Namespace(command="logs", timeout=90, destination=str(self.destination))
self.state = {"session": {"running": True, "id": "session1", "artifactsAvailable": True}}
def test_logs_fetch_only_the_provider_sanitized_zip(self):
response = {"ok": True, "sessionId": "session1", "path": "/data/user/0/com.droiddeck.launcher/cache/shared-logs/session.zip"}
result = subprocess.CompletedProcess([], 0, b"sanitized ZIP", b"")
with patch.object(ctl, "get_state", return_value=self.state), patch.object(ctl, "provider_call", return_value=response) as provider, patch.object(ctl, "run_adb", return_value=result) as adb:
output = ctl.execute(self.args, "adb", "device")
provider.assert_called_once_with("adb", "device", "logs", timeout=120)
adb.assert_called_once_with("adb", "device", "exec-out", "run-as", "com.droiddeck.launcher", "cat", response["path"], timeout=120)
self.assertEqual(b"sanitized ZIP", self.destination.read_bytes())
self.assertEqual(str(self.destination.resolve()), output["path"])
def test_export_failure_never_falls_back_to_pulling_raw_logs(self):
response = {"ok": False, "error": {"code": "NO_SESSION_LOGS", "message": "unavailable"}}
with patch.object(ctl, "get_state", return_value=self.state), patch.object(ctl, "provider_call", return_value=response), patch.object(ctl, "run_adb") as adb:
with self.assertRaises(ctl.ControlError):
ctl.execute(self.args, "adb", "device")
adb.assert_not_called()
self.assertFalse(self.destination.exists())
def test_failed_retrieval_does_not_write_a_partial_zip(self):
response = {"ok": True, "sessionId": "session1", "path": "/private/session.zip"}
result = subprocess.CompletedProcess([], 1, b"partial data", b"read failure")
with patch.object(ctl, "get_state", return_value=self.state), patch.object(ctl, "provider_call", return_value=response), patch.object(ctl, "run_adb", return_value=result):
with self.assertRaises(ctl.ControlError):
ctl.execute(self.args, "adb", "device")
self.assertFalse(self.destination.exists())