A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Publish Android session readiness without hard links (#74)
Vishnu Srivatsava1c9660d4dec0
diff --git a/docs/daemon-sessions.md b/docs/daemon-sessions.mdindex b35dc4f..6349ea8 100644--- a/docs/daemon-sessions.md+++ b/docs/daemon-sessions.md@@ -21,7 +21,13 @@ nor a public scan generation is used as a device-path identifier.The daemon binds loopback port **0**, letting the device kernel allocate a freeport. It atomically publishes a complete 0600 `ready` record containing its port-and PID, without replacing an existing file or symlink. The host then asks ADB+and PID, without replacing an existing file or symlink. Publication uses atomic+no-overwrite rename (`renameat2` with `RENAME_NOREPLACE` on Android/Linux,+`renamex_np` with `RENAME_EXCL` in macOS host tests). It does not require hard+links: [Android shell policy](https://android.googlesource.com/platform/system/sepolicy/+/refs/heads/main/private/shell.te)+grants creation and rename of shell data files, while the+[creation permission set](https://android.googlesource.com/platform/system/sepolicy/+/refs/heads/main/public/global_macros)+does not include hard linking. The host then asks ADBfor `forward --no-rebind tcp:0 tcp:<device-port>` and records the returned hostport. All subsequent device commands use the selected `-s <serial>` explicitly.Setup offers [explicit device selection](device-selection.md). Startup checks@@ -72,6 +78,13 @@ deadline. Small command reads/writes use an absolute deadline and the existingtheir command deadline, including inherited pipes after child exit. Token stdinis bounded to 128 bytes (the actual token line is 65 bytes).+Early daemon exit reports its exit status and a bounded 2 KiB prefix of startup+stderr in the diagnostic log. Remaining stderr is drained without retaining it,+so verbose output cannot block the lifetime child. Waiting for the prefix after+exit uses at most 250 ms within the startup deadline. The connection toast uses+only the first summary line; raw diagnostics do not fill it. Readiness creation,+write, close and publication failures identify their stage on stderr.+| Failure | Ownership-safe result || --- | --- || Feature/root check or exclusive directory creation fails | No published session; no guessed directory cleanup. |@@ -122,3 +135,9 @@ acknowledgement. On an already-root-capable device, also validate approved-sustartup and read-only controls. Do not restart adbd or the shared ADB server aspart of an isolation test. Record actual device results separately from thehost fixtures.++The host readiness regression also links a test executable whose `link()` always+fails with `EPERM`. The former publication failed before readiness in that+fixture; atomic rename succeeds, while existing-file/symlink rejection and+owner-EOF tests remain enforced. This models the missing permission, not a full+Android SELinux environment. Physical-device confirmation remains required.diff --git a/engine/daemon.cpp b/engine/daemon.cppindex 6a5a994..ee2de46 100644--- a/engine/daemon.cpp+++ b/engine/daemon.cpp@@ -14,6 +14,7 @@#include <set>#include <limits>#if defined(__linux__)+#include <linux/fs.h>#include <linux/magic.h>#include <sys/vfs.h>#endif@@ -55,6 +56,16 @@ static std::string g_session_token;static bool g_read_only = false;static int g_scan_threads = cfg::DEFAULT_SCAN_THREADS;+static int publish_no_replace(const char* temporary, const char* destination) {+ // Android shell policy permits rename, but does not grant hard links.+ // Both platform operations atomically reject any existing destination.+#if defined(__APPLE__)+ return ::renamex_np(temporary, destination, RENAME_EXCL);+#else+ return ::renameat2(AT_FDCWD, temporary, AT_FDCWD, destination, RENAME_NOREPLACE);+#endif+}+// A session owns this process through a non-PTY ADB stdin channel. EOF exits// only this process, including during a blocked command; no PID/name lookup// can race with another session. Legacy diagnostic launches do not opt in.@@ -633,11 +644,17 @@ int main(int argc, char* argv[]) {const int ready = ::open(temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);const std::string message = "{\"port\":" + std::to_string(port) +",\"pid\":" + std::to_string(::getpid()) + "}\n";- if (ready < 0) { ::close(srv); return 1; }+ if (ready < 0) {+ std::perror("[engine] Cannot create session announcement");+ ::close(srv); return 1;+ }const bool written = ::write(ready, message.data(), message.size()) == static_cast<ssize_t>(message.size());+ if (!written) std::fprintf(stderr, "[engine] Cannot write complete session announcement\n");const bool closed = ::close(ready) == 0;+ if (!closed) std::perror("[engine] Cannot close session announcement");// Publish a complete record without replacing an existing file/link.- const bool published = written && closed && ::link(temporary.c_str(), ready_path) == 0;+ const bool published = written && closed && publish_no_replace(temporary.c_str(), ready_path) == 0;+ if (written && closed && !published) std::perror("[engine] Cannot publish session announcement");::unlink(temporary.c_str());if (!published) { ::close(srv); return 1; }}diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rsindex 9b60ecc..deb1a8c 100644--- a/src-tauri/src/session.rs+++ b/src-tauri/src/session.rs@@ -4,9 +4,11 @@ use crate::{adb_with_input_timeout, device_shell_command, new_random_id, require_handshake,select_privilege, Privilege,};+use std::io::Read;use std::net::{Ipv4Addr, SocketAddr};use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};+use std::sync::mpsc::{sync_channel, Receiver};use std::time::{Duration, Instant};const START_TIMEOUT: Duration = Duration::from_secs(45);@@ -53,6 +55,24 @@ fn supports_shell_v2(output: &str) -> bool {output.lines().any(|feature| feature.trim() == "shell_v2")}+fn startup_stderr(mut pipe: impl Read + Send + 'static) -> Receiver<String> {+ let (send, receive) = sync_channel(1);+ std::thread::spawn(move || {+ const LIMIT: usize = 2048;+ let mut prefix = Vec::new();+ let _ = pipe.by_ref().take((LIMIT + 1) as u64).read_to_end(&mut prefix);+ let truncated = prefix.len() > LIMIT;+ prefix.truncate(LIMIT);+ let mut text = String::from_utf8_lossy(&prefix).trim().to_string();+ if truncated { text.push_str("\n[startup diagnostics truncated]"); }+ let _ = send.send(text);+ // Keep draining after the prefix so verbose children cannot block or+ // receive SIGPIPE. The receiver never waits beyond its own deadline.+ let _ = std::io::copy(&mut pipe, &mut std::io::sink());+ });+ receive+}+impl Session {pub fn connection(&self) -> Connection {self.connection.clone()@@ -180,26 +200,31 @@ impl Session {);// Raw shell protocol forwards stdin EOF. No nohup, PTY, token argv,// inherited terminal input, or unbounded captured daemon diagnostics.- self.parent = Some(- Command::new(&self.adb)- .args(["-s", &self.serial, "shell", "-T", &launch])- .stdin(Stdio::piped())- .stdout(Stdio::null())- .stderr(Stdio::null())- .spawn()- .map_err(|e| format!("Cannot launch session daemon: {e}"))?,- );+ let mut child = Command::new(&self.adb)+ .args(["-s", &self.serial, "shell", "-T", &launch])+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("Cannot launch session daemon: {e}"))?;+ let diagnostics = startup_stderr(child.stderr.take().unwrap());+ self.parent = Some(child);let ready = loop {remaining(deadline)?;- if self+ if let Some(status) = self.parent.as_mut().unwrap().try_wait().map_err(|e| e.to_string())?- .is_some(){- return Err("Daemon exited before announcing its endpoint. Rebuild the bundled daemon and check root access.".into());+ let details = diagnostics.recv_timeout(+ deadline.saturating_duration_since(Instant::now()).min(Duration::from_millis(250)),+ ).unwrap_or_default();+ return Err(format!(+ "Daemon exited before announcing its endpoint ({status}). See the log for startup details.\n{}",+ if details.is_empty() { "No startup diagnostics were received." } else { &details },+ ));}let text = self.shell(&format!("if [ -f '{ready_path}' ]; then cat '{ready_path}'; fi"),@@ -581,16 +606,23 @@ mod tests {"push","chmod","launch",+ "launch-output","ready","bad-ready","handshake",] {let adb = device.client(stage, "same");fail(&adb, stage);- assert!(- Session::start(adb, daemon(), "same".into(), false).is_err(),- "accepted {stage}"- );+ let error = Session::start(adb, daemon(), "same".into(), false).err()+ .unwrap_or_else(|| panic!("accepted {stage}"));+ if stage == "launch" {+ assert!(error.contains("Injected launch failure"), "{error}");+ } else if stage == "launch-output" {+ assert!(error.contains("fixture startup failure:"), "{error}");+ assert!(error.contains("diagnostics truncated"), "{error}");+ assert!(error.contains("exit status: 9"), "{error}");+ assert!(error.len() < 2300, "Unbounded startup diagnostics");+ }assert_eq!(device.rows().len(),2,diff --git a/src/App.tsx b/src/App.tsxindex 9df0cba..2304429 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -699,7 +699,7 @@ function App() {try { await invoke<string>("stop_daemon"); } catch { /* show the original connection error */ }}const message = err instanceof Error ? err.message : String(err);- pushToast(message, message === "Scan cancelled" ? "info" : "error");+ pushToast(message.split("\n", 1)[0], message === "Scan cancelled" ? "info" : "error");addLog(`${message === "Scan cancelled" ? "[SCAN]" : "[ERROR]"} ${message}`);setPhase("setup");} finally {diff --git a/tests/fake_session_adb.py b/tests/fake_session_adb.pyindex 8259a7e..0eda2b6 100644--- a/tests/fake_session_adb.py+++ b/tests/fake_session_adb.py@@ -54,6 +54,9 @@ elif args[0] == "shell":print("0" if elevated and failure != "root" else "2000")elif args[1] == "-T":fail("launch")+ if failure == "launch-output":+ sys.stderr.write("fixture startup failure: " + "x" * (256 * 1024))+ sys.exit(9)command = shlex.split(mapped(command))assert command[0] == "exec"if failure == "handshake":diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.jsindex e03517f..ee3068d 100644--- a/tests/scan_ui_fixture.js+++ b/tests/scan_ui_fixture.js@@ -81,7 +81,7 @@}if (command === "check_adb") return "Mock ADB " + "x".repeat(20000);if (command === "init_daemon") {- check(listedDevices.some(device => device.serial === args.serial && device.state === "device"), "Selected device disconnected before startup");+ check(listedDevices.some(device => device.serial === args.serial && device.state === "device"), "Selected device disconnected before startup\nfixture startup details <stderr>");activeDevice = args.serial;return "Mock daemon";}@@ -214,6 +214,8 @@connect.click();await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-refresh-devices").disabled && document.querySelector("#device-status").textContent.includes("disconnected"), "Stale selected device did not return to setup");check(calls.filter(call => call.command === "init_daemon").length === 1 && !calls.some(call => call.command === "run_scan"), "Failed/duplicate connect started a scan or silently chose another device");+ check(!document.querySelector("#toast-container").textContent.includes("fixture startup details"), "Startup diagnostics filled the toast");+ check(document.querySelector("#terminal-log").textContent.includes("fixture startup details <stderr>") && !document.querySelector("#terminal-log stderr"), "Startup diagnostics were lost or treated as markup");check(picker().value === "phone-two" && document.querySelector("#btn-connect").disabled, "Failed startup replaced selected serial");listedDevices = readyDevices;await refreshDevices();diff --git a/tests/test_owned_session.py b/tests/test_owned_session.pyindex 6e4d655..d3c1f7d 100644--- a/tests/test_owned_session.py+++ b/tests/test_owned_session.py@@ -3,6 +3,7 @@ import jsonimport osfrom pathlib import Pathimport secrets+import shutilimport socketimport statimport subprocess@@ -30,7 +31,7 @@ class OwnedSessionTests(DaemonHarness):child.wait()child.stderr.close()- def launch(self, name, read_only=False, prepare=None, closed_input=False):+ def launch(self, name, read_only=False, prepare=None, closed_input=False, binary=None):directory = Path(self.files.name) / namedirectory.mkdir(mode=0o700)token = secrets.token_hex(32)@@ -40,7 +41,7 @@ class OwnedSessionTests(DaemonHarness):ready = directory / "ready"if prepare:prepare(ready)- args = [self.binary, "0", str(token_file), "--session-ready", str(ready)]+ args = [binary or self.binary, "0", str(token_file), "--session-ready", str(ready)]if read_only:args.append("--read-only")child = subprocess.Popen(args, stdin=subprocess.DEVNULL if closed_input else subprocess.PIPE,@@ -116,6 +117,27 @@ class OwnedSessionTests(DaemonHarness):path = Path(str(ready) + ".tmp") if kind.startswith("temporary") else readyself.assertEqual(path.read_text(), "keep")+ def test_readiness_does_not_require_hard_link_permission(self):+ # Stock Android shell policy allows file creation/rename, not hard links.+ # Override link in this host-only executable to reproduce that denial.+ stub = Path(self.files.name) / "deny_link.cpp"+ stub.write_text('#include <cerrno>\n#include <cstdio>\n'+ 'extern "C" int link(const char*, const char*) {\n'+ ' std::fputs("[fixture] hard links denied\\n", stderr);\n'+ ' errno = EPERM; return -1;\n}\n')+ binary = str(Path(self.files.name) / "daemon-no-hardlinks")+ compiler = os.environ.get("CXX") or shutil.which("clang++") or "c++"+ source = Path(__file__).resolve().parents[1] / "engine/daemon.cpp"+ subprocess.run([compiler, "-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra",+ "-Wpedantic", "-fno-exceptions", "-fno-rtti", str(source), str(stub),+ "-o", binary], check=True)+ child, ready, token = self.launch("no-hardlinks", binary=binary)+ port = self.wait_ready(child, ready)+ self.assertEqual(self.command(port, token)["status"], "ok")+ child.stdin.close()+ child.stdin = None+ self.assertEqual(child.wait(timeout=1), 0)+def test_missing_owner_input_exits_without_a_detached_process(self):child, _, _ = self.launch("already-closed", closed_input=True)self.assertEqual(child.wait(timeout=1), 0)