A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Isolate daemon lifetimes and cleanup by owned session (#65)
Vishnu Srivatsavab0b5961bf6eb
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex e436806..3bf2924 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -83,7 +83,9 @@ jobs:- name: Test root scans in a disposable Linux filesystemif: runner.os == 'Linux'- run: sudo -n env CXX=g++ python3 -m unittest discover -s tests -p test_root_scan.py -v+ run: |+ sudo -n env CXX=g++ python3 -m unittest discover -s tests -p test_root_scan.py -v+ sudo -n env CXX=g++ python3 -m unittest discover -s tests -p test_owned_session.py -v# ── Cross-compile C++ daemon for Android aarch64 ──────────────────────# The daemon always targets Android ARM64, regardless of host OS.diff --git a/README.md b/README.mdindex a51d1fb..3f8dc83 100644--- a/README.md+++ b/README.md@@ -255,6 +255,9 @@ binaries without the streaming capability are refused. See[the stream contract](docs/scan-stream-v1.md) for bounds, completion rules,cancellation, timing semantics and the remaining full-tree frontend limitation.+Current startup also requires the rebuilt daemon for+[owned session files, allocated ports, and lifetime cleanup](docs/daemon-sessions.md).+### 2. Install Frontend Dependencies```bashdiff --git a/docs/daemon-sessions.md b/docs/daemon-sessions.mdnew file mode 100644index 0000000..c42e0ac--- /dev/null+++ b/docs/daemon-sessions.md@@ -0,0 +1,117 @@+# Owned daemon sessions++Tracked in [#37](https://github.com/VishnuSrivatsava/SocketSweep/issues/37).+Rebuild the Android daemon before using this startup path. The scan wire+protocol remains version 3 with scan stream v1; the new startup flag is required+and there is no fallback to the old shared process/port.++## Ownership and lifetime++One Rust `Session` owns the selected device serial, privilege mode, secret,+loopback endpoint, read-only state, device files, and an unreaped ADB child.+Only a verified authenticated handshake publishes that session to commands.+Connection changes/scans/deletion retain their operation lock; cancellation and+progress acknowledgements retain their separate scan-ID scope.++Each connection creates `/data/local/tmp/socketsweep-<random-256-bit-id>/`+exclusively with mode 0700. It pushes a private `daemon` executable (0700) and+writes a distinct secret through stdin into `token` (0600). The daemon consumes+and unlinks the token before accepting connections. Neither the session secret+nor a public scan generation is used as a device-path identifier.++The daemon binds loopback port **0**, letting the device kernel allocate a free+port. 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+for `forward --no-rebind tcp:0 tcp:<device-port>` and records the returned host+port. All subsequent device commands use the selected `-s <serial>` explicitly.+Device selection still follows the existing first-authorized-device behavior;+the selection UI remains [#4](https://github.com/VishnuSrivatsava/SocketSweep/issues/4).++The foreground daemon is launched through **`adb shell -T`**, with an owned stdin+pipe held open by the Rust session. `--session-ready` also enables its lifetime+watcher. EOF/error on that input exits only that process, including when a TCP+command is blocked. This requires ADB shell v2; unsupported devices fail before+creating session files. There is no `nohup`, process-name kill, or remote PID+signal. A PID in a readiness file never grants termination authority.++[ADB documents raw non-PTY shells and allocated forwarding ports](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md).+Its [shell service](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/daemon/shell_service.cpp)+handles the shell-v2 close-stdin packet by shutting down input for a raw shell;+PTY shells cannot provide that half-close behavior. This is why `-T` and the+feature check are part of the contract.++## Teardown and failures++Stop first requests authenticated `SHUTDOWN` from the owned endpoint. Only the+actual `shutting down` acknowledgement produces a confirmed shutdown result.+Local scan authority is invalidated even when the reply is missing/rejected.+Cleanup always releases the lifetime pipe and its owned host child. EOF is a+safety/lifetime mechanism, not an invented remote acknowledgement.++Forward removal requires the recorded **serial + local port + remote port** to+match the current ADB table. A changed mapping is left intact. Cleanup removes+only the private session's known `token`, `ready`, `ready.tmp`, and `daemon`+files, then uses `rmdir`; unexpected extra files prevent directory removal.+There is no recursive session sweep, legacy-file deletion, `--remove-all`, or+ADB-server/adbd restart. Normal app exit cancels an active scan and drops the+owned session; host process death closes the pipe at the OS boundary.++Session startup has a shared 45-second budget after device discovery. Individual+ADB commands use at most 15 seconds. Cleanup shares a 5-second ADB budget plus+up to 250 ms of local-child grace; only the owned, unreaped host child is killed+and waited for if needed. Shutdown requests have an absolute 3-second network+deadline. Small command reads/writes use an absolute deadline and the existing+128 KiB response limit. ADB stdout/stderr each have a 256 KiB limit and share+their command deadline, including inherited pipes after child exit. Token stdin+is bounded to 128 bytes (the actual token line is 65 bytes).++| Failure | Ownership-safe result |+| --- | --- |+| Feature/root check or exclusive directory creation fails | No published session; no guessed directory cleanup. |+| Token, push, chmod, launch, readiness, or handshake fails | The guard releases its child and removes confirmed owned resources within the cleanup budget. |+| Forward creation reply is lost or malformed | The daemon/files are retired; the unknown local listener is not guessed. Startup reports that an unused forward may remain. |+| Mapping was rebound | Cleanup preserves the changed mapping. Other SocketSweep sessions allocate new ports and do not rebind existing ones. |+| Device disappears, root permission changes, or cleanup times out | Local state/child are released; private files or a forward may remain. Cleanup errors do not authorize broader deletion. |+| App crashes during startup | The lifetime channel retires a launched daemon; private files may remain, including a 0600 token if launch had not consumed it yet. |++ADB is a shared service controlled by the desktop account. This design isolates+cooperating SocketSweep sessions; it does not claim protection from that same+account deliberately force-rebinding mappings or replacing the bundled tools.+Android shell storage permission grants remain shared by the shell UID, as in+the existing setup. Root launches still use only an already-root adbd or+approved `su`, and the authenticated root daemon must report read-only mode.++## Validation and manual device check++The Rust fixtures use a fake ADB executable, private local files, and the real+host-built C++ daemon. They test same-serial and different-serial sessions,+independent secrets/ports/lifetimes, permissions, staged startup failures,+missing allocation replies, replaced mappings, root-handshake rejection, cleanup+deadlines, output bounds, and inherited-pipe timeouts. The fake forward uses the+host daemon's port directly: it validates ownership/command construction, not+the real USB tunnel or root-manager stdin behavior. Unix integration fixtures+run on Linux/macOS; Windows retains the common ownership guard and existing+Rust tests plus the full desktop build.++Four Python tests exercise actual daemon lifetime EOF, including an incomplete+authenticated command, two simultaneous listeners, root/read-only metadata,+atomic readiness permissions, and preservation of existing files/symlinks. CI+also runs these under root in a disposable Linux job. Existing protocol,+deletion, streaming, frontend, symbol, and packaging checks remain enabled.++No native app, real ADB, or phone test is run locally for this change. To check+the real device manually, run the following yourself from the repository:++```sh+bash engine/build.sh+npm run tauri build+```++Launch two copies of the built app (on macOS, use+`open -n /path/to/SocketSweep.app` for each). Connect/scan in both, stop one, and+rescan in the other. Repeat reconnects and check that an unrelated ADB forward+survives. Unplugging should clear local state without a false shutdown+acknowledgement. On an already-root-capable device, also validate approved-su+startup and read-only controls. Do not restart adbd or the shared ADB server as+part of an isolation test. Record actual device results separately from the+host fixtures.diff --git a/docs/daemon-symbols.md b/docs/daemon-symbols.mdindex d84b225..feaf3bf 100644--- a/docs/daemon-symbols.md+++ b/docs/daemon-symbols.md@@ -13,8 +13,9 @@ daemon-symbols-<platform>-aarch64-<full-workflow-commit-SHA>-attempt-<N>metadata.json```-`socketsweep_daemon` is the unstripped executable, named like the on-device-process. `metadata.json` records the workflow commit, host platform, Android+`socketsweep_daemon` is the unstripped archive filename. Owned sessions execute+a private copy named `daemon`; the explicit `--obj` lookup below works with+either on-device name. `metadata.json` records the workflow commit, host platform, Androidtarget, workflow run/attempt, shared ELF build ID, SHA-256 and size of both executables, and a realsymbol-lookup smoke check. Host jobs may use different NDK versions; theirsymbols are not interchangeable just because their source commit matches.diff --git a/engine/daemon.cpp b/engine/daemon.cppindex a0b4a6f..6a5a994 100644--- a/engine/daemon.cpp+++ b/engine/daemon.cpp@@ -32,6 +32,8 @@#include <poll.h>#include <atomic>#include <mutex>+#include <pthread.h>+#include <fcntl.h>// ── Configuration ───────────────────────────────────────────────────────────namespace cfg {@@ -53,6 +55,18 @@ static std::string g_session_token;static bool g_read_only = false;static int g_scan_threads = cfg::DEFAULT_SCAN_THREADS;+// 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.+static void* watch_session_owner(void*) {+ char buffer[128];+ for (;;) {+ const ssize_t n = ::read(STDIN_FILENO, buffer, sizeof(buffer));+ if (n < 0 && errno == EINTR) continue;+ if (n <= 0) ::_exit(0);+ }+}+// Per-phase scan timing (see SCAN in handle_client). Counters reset per scan.static int64_t g_sort_ns = 0; // cumulative time sorting directory childrenstatic int64_t g_send_ns = 0; // cumulative time blocked in ::send (socket writes)@@ -541,6 +555,7 @@ int main(int argc, char* argv[]) {// arguments. Consume and unlink it before accepting any connections.bool read_only_requested = false;bool threads_requested = false;+ const char* ready_path = nullptr;bool valid_args = argc >= 3;for (int i = 3; valid_args && i < argc; ++i) {if (std::strcmp(argv[i], "--read-only") == 0 && !read_only_requested) {@@ -551,12 +566,14 @@ int main(int argc, char* argv[]) {valid_args = value.size() == 1 && value[0] >= '1' &&value[0] <= '0' + parallel_scan::MAX_WORKERS;if (valid_args) g_scan_threads = value[0] - '0';+ } else if (std::strcmp(argv[i], "--session-ready") == 0 && !ready_path && i + 1 < argc) {+ ready_path = argv[++i];} else {valid_args = false;}}if (!valid_args) {- std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE [--read-only] [--threads 1..8]\n");+ std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE [--read-only] [--threads 1..8] [--session-ready FILE]\n");return 1;}// Even an already-root ADB shell using the default launch cannot delete.@@ -574,6 +591,15 @@ int main(int argc, char* argv[]) {::signal(SIGTERM, on_signal);::signal(SIGPIPE, SIG_IGN);+ if (ready_path) {+ pthread_t owner;+ if (::pthread_create(&owner, nullptr, watch_session_owner, nullptr) != 0) {+ std::fprintf(stderr, "[engine] Cannot watch session owner\n");+ return 1;+ }+ ::pthread_detach(owner);+ }+int srv = ::socket(AF_INET, SOCK_STREAM, 0);if (srv < 0) { std::perror("[engine] socket"); return 1; }@@ -596,6 +622,26 @@ int main(int argc, char* argv[]) {return 1;}+ socklen_t addr_len = sizeof(addr);+ if (::getsockname(srv, reinterpret_cast<sockaddr*>(&addr), &addr_len) != 0) {+ ::close(srv);+ return 1;+ }+ port = ntohs(addr.sin_port);+ if (ready_path) {+ const std::string temporary = std::string(ready_path) + ".tmp";+ 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; }+ const bool written = ::write(ready, message.data(), message.size()) == static_cast<ssize_t>(message.size());+ const bool closed = ::close(ready) == 0;+ // Publish a complete record without replacing an existing file/link.+ const bool published = written && closed && ::link(temporary.c_str(), ready_path) == 0;+ ::unlink(temporary.c_str());+ if (!published) { ::close(srv); return 1; }+ }+std::fprintf(stderr, "[engine] Listening on %s:%u (pid %d)\n",cfg::BIND_ADDR, port, static_cast<int>(::getpid()));diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 371f14c..7857475 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -19,16 +19,13 @@ use std::sync::{Arc, atomic::{AtomicBool, Ordering}};use tauri::ipc::Channel;mod scan_stream;mod scan_store;+mod session;use std::process::Command;use std::sync::Mutex;use std::time::Duration;// ── Constants ───────────────────────────────────────────────────────────────-const DAEMON_PORT: u16 = 5050;-const DAEMON_ADDR: &str = "127.0.0.1:5050";-const DEVICE_BIN_PATH: &str = "/data/local/tmp/socketsweep_daemon";-const DEVICE_TOKEN_PATH: &str = "/data/local/tmp/socketsweep_token";const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);const MAX_COMMAND_BYTES: usize = 16 * 1024;const MAX_COMMAND_RESPONSE_BYTES: usize = 128 * 1024;@@ -42,11 +39,8 @@ fn invalidate_scan() -> Result<(), String> {Ok(())}-/// Tracks the serial of the connected device so all ADB calls target the right device.-static DEVICE_SERIAL: Mutex<Option<String>> = Mutex::new(None);-static SESSION_TOKEN: Mutex<Option<String>> = Mutex::new(None);-static READ_ONLY: Mutex<bool> = Mutex::new(false);-static DEVICE_PRIVILEGE: Mutex<Privilege> = Mutex::new(Privilege::Shell);+/// A published session owns all connection state and cleanup authority.+static SESSION: Mutex<Option<session::Session>> = Mutex::new(None);// Keep connection changes, scans, and deletes in order across async commands.static DAEMON_OPERATION: Mutex<()> = Mutex::new(());@@ -79,11 +73,6 @@ fn device_shell_command(privilege: Privilege, command: &str) -> String {}}-fn device_shell(adb_path: &std::path::Path, command: &str) -> Result<String, String> {- let privilege = *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")?;- adb_s(adb_path, &["shell", &device_shell_command(privilege, command)])-}-// ── Resource Resolution ─────────────────────────────────────────────────────use tauri::Manager;@@ -119,103 +108,78 @@ fn adb(adb_path: &std::path::Path, args: &[&str]) -> Result<String, String> {}fn adb_with_input(adb_path: &std::path::Path, args: &[&str], input: Option<&[u8]>) -> Result<String, String> {- use std::io::Read;- use std::time::{Duration, Instant};-- let mut child = Command::new(adb_path)- .args(args)+ adb_with_input_timeout(adb_path, args, input, Duration::from_secs(15))+}++fn adb_with_input_timeout(adb_path: &std::path::Path, args: &[&str], input: Option<&[u8]>, timeout: Duration) -> Result<String, String> {+ use std::sync::mpsc::{sync_channel, Receiver};+ use std::time::Instant;+ const LIMIT: usize = 256 * 1024;+ // The only input is a 65-byte startup token. Keep writes smaller than an+ // empty pipe's capacity; a blocked child cannot stall a large stdin write.+ if input.is_some_and(|bytes| bytes.len() > 128) { return Err("ADB input exceeds limit".into()); }+ if timeout.is_zero() { return Err("ADB command timed out".into()); }+ let deadline = Instant::now() + timeout;+ let mut child = Command::new(adb_path).args(args).stdin(if input.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() })- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .spawn()- .map_err(|e| format!("Failed to execute adb binary at {:?}: {}", adb_path, e))?;-- let mut stdout_pipe = child.stdout.take().unwrap();- let mut stderr_pipe = child.stderr.take().unwrap();-- let stdout_thread = std::thread::spawn(move || {- let mut buf = Vec::new();- let _ = stdout_pipe.read_to_end(&mut buf);- buf- });-- let stderr_thread = std::thread::spawn(move || {- let mut buf = Vec::new();- let _ = stderr_pipe.read_to_end(&mut buf);- buf- });-- if let Some(bytes) = input {- let result = child.stdin.take().unwrap().write_all(bytes);- if let Err(e) = result {- let _ = child.kill();- let _ = child.wait();- return Err(format!("Failed to provide ADB input: {e}"));- }- }-- let timeout_secs = 15;- let timeout = Duration::from_secs(timeout_secs);- let start = Instant::now();- let status;-- loop {- if let Some(s) = child.try_wait().map_err(|e| format!("Failed to wait on adb process: {}", e))? {- status = s;- break;- }- if start.elapsed() > timeout {- let _ = child.kill();- let _ = child.wait();- return Err(format!("ADB command timed out after {} seconds. Please reconnect your device and try again.", timeout_secs));- }- std::thread::sleep(Duration::from_millis(50));+ .stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped())+ .spawn().map_err(|e| format!("Failed to execute adb binary at {:?}: {e}", adb_path))?;+ fn read_pipe(pipe: impl Read + Send + 'static) -> Receiver<Result<Vec<u8>, String>> {+ let (send, receive) = sync_channel(1);+ std::thread::spawn(move || {+ let mut bytes = Vec::new();+ let result = pipe.take((LIMIT + 1) as u64).read_to_end(&mut bytes)+ .map_err(|e| format!("Cannot read ADB output: {e}"))+ .and_then(|_| if bytes.len() > LIMIT { Err("ADB output exceeds limit".into()) } else { Ok(bytes) });+ let _ = send.send(result);+ });+ receive}-- let stdout_bytes = stdout_thread.join().unwrap_or_default();- let stderr_bytes = stderr_thread.join().unwrap_or_default();-- let stdout = String::from_utf8_lossy(&stdout_bytes).to_string();- let stderr = String::from_utf8_lossy(&stderr_bytes).to_string();-- if !status.success() {- let combined = format!("{stdout} {stderr}").to_lowercase();- if combined.contains("no devices") || combined.contains("device not found") {- return Err("No Android device detected. Connect your phone via USB and enable USB Debugging.".into());- }- if combined.contains("unauthorized") {- return Err("USB Debugging not authorised. Check the confirmation dialog on your phone.".into());+ let stdout = read_pipe(child.stdout.take().unwrap());+ let stderr = read_pipe(child.stderr.take().unwrap());+ let result = (|| {+ if let Some(input) = input {+ child.stdin.take().unwrap().write_all(input).map_err(|e| format!("Cannot provide ADB input: {e}"))?;}- return Err(format!(- "adb {} failed (exit {}):\n{stderr}",- args.join(" "),- status.code().unwrap_or(-1)- ));- }-- Ok(stdout)-}--/// Run an ADB command targeting the stored device serial (if any).-/// Prepends `-s <serial>` when a device serial is known.-fn adb_s(adb_path: &std::path::Path, args: &[&str]) -> Result<String, String> {- if let Ok(guard) = DEVICE_SERIAL.lock() {- if let Some(ref serial) = *guard {- let mut full_args = vec!["-s", serial.as_str()];- full_args.extend_from_slice(args);- return adb(adb_path, &full_args);+ let status = loop {+ if let Some(status) = child.try_wait().map_err(|e| format!("Cannot wait for ADB: {e}"))? { break status; }+ if Instant::now() >= deadline { return Err("ADB command timed out. Reconnect your device and retry.".into()); }+ std::thread::sleep(Duration::from_millis(10));+ };+ let receive = |pipe: Receiver<Result<Vec<u8>, String>>| {+ pipe.recv_timeout(deadline.saturating_duration_since(Instant::now()))+ .map_err(|_| "ADB output timed out".to_string())?+ };+ let stdout = String::from_utf8_lossy(&receive(stdout)?).into_owned();+ let stderr = String::from_utf8_lossy(&receive(stderr)?).into_owned();+ if !status.success() {+ let combined = format!("{stdout} {stderr}").to_lowercase();+ if combined.contains("no devices") || combined.contains("device not found") {+ return Err("No Android device detected. Connect your phone via USB and enable USB Debugging.".into());+ }+ if combined.contains("unauthorized") {+ return Err("USB Debugging not authorised. Check the confirmation dialog on your phone.".into());+ }+ return Err(format!("adb {} failed (exit {}):\n{stderr}", args.join(" "), status.code().unwrap_or(-1)));}- }- adb(adb_path, args)+ Ok(stdout)+ })();+ if result.is_err() { let _ = child.kill(); let _ = child.wait(); }+ result}// ── TCP helper ──────────────────────────────────────────────────────────────/// Send a one-line command to the daemon and read the full response.+fn active_connection() -> Result<session::Connection, String> {+ SESSION.lock().map_err(|_| "Session state is unavailable")?+ .as_ref().map(session::Session::connection)+ .ok_or_else(|| "No active daemon session. Connect your device first.".into())+}+fn daemon_command(cmd: &str) -> Result<String, String> {- let token = SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")?- .clone().ok_or("No active daemon session. Connect your device first.")?;- daemon_command_with_token(cmd, &token)+ let connection = active_connection()?;+ daemon_command_at(connection.address, cmd, &connection.token, TCP_READ_TIMEOUT)}fn command_payload(cmd: &str, token: &str) -> Result<String, String> {@@ -225,30 +189,40 @@ fn command_payload(cmd: &str, token: &str) -> Result<String, String> {Ok(format!("AUTH {token}\n{cmd}\n"))}-fn daemon_command_with_token(cmd: &str, token: &str) -> Result<String, String> {+fn daemon_command_at(address: std::net::SocketAddr, cmd: &str, token: &str, timeout: Duration) -> Result<String, String> {let payload = command_payload(cmd, token)?;- let mut stream = TcpStream::connect_timeout(- &DAEMON_ADDR.parse().unwrap(),- TCP_CONNECT_TIMEOUT,- )- .map_err(|e| format!("Cannot connect to daemon at {DAEMON_ADDR}: {e}"))?;-- stream- .set_read_timeout(Some(TCP_READ_TIMEOUT))- .map_err(|e| format!("Failed to set read timeout: {e}"))?;- stream.set_write_timeout(Some(TCP_CONNECT_TIMEOUT))- .map_err(|e| format!("Failed to set write timeout: {e}"))?;- stream- .write_all(payload.as_bytes())- .map_err(|e| format!("Failed to send command to daemon: {e}"))?;-- let mut response_bytes = Vec::with_capacity(1024);- stream- .take((MAX_COMMAND_RESPONSE_BYTES + 1) as u64)- .read_to_end(&mut response_bytes)- .map_err(|e| format!("Failed to read daemon response: {e}"))?;-- decode_daemon_response(response_bytes)+ let deadline = std::time::Instant::now() + timeout;+ let left = || {+ let left = deadline.saturating_duration_since(std::time::Instant::now());+ if left.is_zero() { Err("Daemon command timed out".to_string()) } else { Ok(left) }+ };+ let mut stream = TcpStream::connect_timeout(&address, TCP_CONNECT_TIMEOUT.min(left()?))+ .map_err(|e| format!("Cannot connect to daemon at {address}: {e}"))?;+ let mut sent = 0;+ while sent < payload.len() {+ stream.set_write_timeout(Some(TCP_CONNECT_TIMEOUT.min(left()?))).map_err(|e| e.to_string())?;+ match stream.write(&payload.as_bytes()[sent..]) {+ Ok(0) => return Err("Daemon command connection closed".into()),+ Ok(n) => sent += n,+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,+ Err(e) => return Err(format!("Failed to send command to daemon: {e}")),+ }+ }+ let mut response = Vec::with_capacity(1024);+ let mut buffer = [0; 4096];+ loop {+ stream.set_read_timeout(Some(left()?)).map_err(|e| e.to_string())?;+ match stream.read(&mut buffer) {+ Ok(0) => break,+ Ok(n) => {+ if n > MAX_COMMAND_RESPONSE_BYTES.saturating_sub(response.len()) { return Err("Daemon command response exceeds limit".into()); }+ response.extend_from_slice(&buffer[..n]);+ }+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,+ Err(e) => return Err(format!("Failed to read daemon response: {e}")),+ }+ }+ decode_daemon_response(response)}fn decode_daemon_response(bytes: Vec<u8>) -> Result<String, String> {@@ -315,126 +289,21 @@ fn check_adb(app: tauri::AppHandle) -> Result<String, String> {#[tauri::command(async)]fn init_daemon(app: tauri::AppHandle, root_mode: Option<bool>) -> Result<String, String> {let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;- invalidate_scan()?;- let has_session = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();- if has_session {- // An unreachable previous daemon is not proof it stopped. Local- // cleanup still releases its session; init performs fresh device setup.- let _ = stop_daemon_inner(&app);- }- clear_session()?;- let result = init_daemon_inner(app.clone(), root_mode.unwrap_or(false));- if result.is_err() {- // A failed push/start/handshake must not leave a live daemon or a- // startup secret behind. Only target the device selected by this init.- let has_device = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();- if has_device {- if let Ok(adb_path) = get_bundled_binary(&app, "adb") {- let _ = device_shell(&adb_path, "pkill -f '[s]ocketsweep_daemon' || true");- let _ = adb_s(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);- let _ = adb_s(&adb_path, &["shell", "rm", "-f", DEVICE_TOKEN_PATH]);- }- }- *DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;- *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = Privilege::Shell;- }- result-}--fn init_daemon_inner(app: tauri::AppHandle, root_mode: bool) -> Result<String, String> {+ // Reconnect can release only this app's previous session. An unconfirmed+ // remote stop still clears local authority before a fresh session starts.+ let _ = stop_daemon_inner();let adb_path = get_bundled_binary(&app, "adb")?;- let daemon_src = get_bundled_binary(&app, "daemon")?;-- // 1 — Verify ADB is reachable and a device is connected.+ let daemon = get_bundled_binary(&app, "daemon")?;adb(&adb_path, &["version"])?;let devices = adb(&adb_path, &["devices"])?;- let device_line = devices- .lines()- .find(|l| l.ends_with("\tdevice") && !l.starts_with("List"));-- let serial = match device_line {- Some(line) => line.split('\t').next().unwrap_or("").trim().to_string(),- None => {- // Check for unauthorized devices to give a better error.- if devices.lines().any(|l| l.contains("unauthorized")) {- return Err("USB Debugging not authorised. Check the confirmation dialog on your phone.".into());- }- return Err(- "No Android device detected. Connect your phone via USB and enable USB Debugging.".into(),- );- }- };-- // Store the serial so all subsequent ADB calls (including stop_daemon) target this device.- if let Ok(mut guard) = DEVICE_SERIAL.lock() {- *guard = Some(serial);- }-- let privilege = select_privilege(root_mode, |args| adb_s(&adb_path, args))?;- *DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = privilege;-- // 2 — Kill any zombie daemon before we push/start.- device_shell(&adb_path, "pkill -f '[s]ocketsweep_daemon' || true")?;- std::thread::sleep(Duration::from_millis(300));-- // Transfer the fresh secret over stdin into a shell-owned file. Neither- // the startup arguments nor the frontend response contain the secret.- let token = new_random_id()?;- let serial = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?- .clone().ok_or("No connected device")?;- let token_cmd = format!("rm -f {DEVICE_TOKEN_PATH} && umask 077 && cat > {DEVICE_TOKEN_PATH}");- adb_with_input(&adb_path, &["-s", &serial, "shell", &token_cmd], Some(format!("{token}\n").as_bytes()))?;-- // 2.5 — Automate MANAGE_EXTERNAL_STORAGE permission for the shell user.- let _ = adb_s(&adb_path, &["shell", "appops set com.android.shell MANAGE_EXTERNAL_STORAGE allow"]);-- // 4 — Push binary to device.- adb_s(&adb_path, &["push", &daemon_src.to_string_lossy(), DEVICE_BIN_PATH])?;-- // 5 — Make it executable.- adb_s(&adb_path, &["shell", "chmod", "+x", DEVICE_BIN_PATH])?;-- // 6 — Start the daemon in the background on the device.- let mode_arg = if root_mode { " --read-only" } else { "" };- let start_cmd = format!("nohup {DEVICE_BIN_PATH} {DAEMON_PORT} {DEVICE_TOKEN_PATH}{mode_arg} > /dev/null 2>&1 & echo $!; exit");- let pid_output = device_shell(&adb_path, &start_cmd)?;- let pid: u32 = pid_output.trim().parse().map_err(|_| "Daemon launch did not return a process ID")?;-- // 7 — Set up the USB TCP tunnel.- adb_s(&adb_path, &["forward", &format!("tcp:{DAEMON_PORT}"), &format!("tcp:{DAEMON_PORT}")])?;-- // 8 — Ping-Retry loop.- let mut pong = String::new();- let mut connected_daemon = false;- let mut handshake_error = String::new();- for _ in 0..15 {- std::thread::sleep(Duration::from_millis(150));- match daemon_command_with_token("PING", &token).and_then(|res| {- require_handshake(&res, root_mode)?;- Ok(res)- }) {- Ok(res) => {- pong = res;- connected_daemon = true;- break;- }- Err(error) => {- handshake_error = error;- continue;- }- }- }-- if !connected_daemon {- return Err(format!("Daemon did not complete the authenticated handshake: {handshake_error}"));- }-- *SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = Some(token);- *READ_ONLY.lock().map_err(|_| "Session state is unavailable")? = require_handshake(&pong, root_mode)?.read_only.unwrap();-- Ok(format!(- "{{\"daemon_pid\":\"{pid}\",\"ping_response\":{pong}}}"- ))+ let serial = devices.lines().find(|line| line.ends_with("\tdevice") && !line.starts_with("List"))+ .and_then(|line| line.split('\t').next()).map(str::to_string)+ .ok_or_else(|| if devices.lines().any(|line| line.contains("unauthorized")) {+ "USB Debugging not authorised. Check the confirmation dialog on your phone.".to_string()+ } else { "No Android device detected. Connect your phone via USB and enable USB Debugging.".to_string() })?;+ let (session, response) = session::Session::start(adb_path, &daemon, serial, root_mode.unwrap_or(false))?;+ *SESSION.lock().map_err(|_| "Session state is unavailable")? = Some(session);+ Ok(response)}// Cancellation deliberately bypasses DAEMON_OPERATION: otherwise it would@@ -514,15 +383,9 @@ fn run_scan(let effective_root = path.filter(|p| !p.is_empty()).unwrap_or_else(|| "/sdcard".into());- let token = SESSION_TOKEN- .lock()- .map_err(|_| "Session state is unavailable")?- .clone()- .ok_or("No active daemon session. Connect your device first.")?;- let payload = command_payload(&format!("SCAN_STREAM {effective_root}"), &token)?;- let read_only = *READ_ONLY- .lock()- .map_err(|_| "Session state is unavailable")?;+ let connection = active_connection()?;+ let payload = command_payload(&format!("SCAN_STREAM {effective_root}"), &connection.token)?;+ let read_only = connection.read_only;let cancelled = Arc::new(AtomicBool::new(false));let progress_pending = Arc::new(AtomicBool::new(false));*ACTIVE_SCAN@@ -536,8 +399,8 @@ fn run_scan(let _registration = ScanRegistration(scan_id.clone());let result = (|| {let mut stream =- TcpStream::connect_timeout(&DAEMON_ADDR.parse().unwrap(), TCP_CONNECT_TIMEOUT)- .map_err(|e| format!("Cannot connect to daemon at {DAEMON_ADDR}: {e}"))?;+ TcpStream::connect_timeout(&connection.address, TCP_CONNECT_TIMEOUT)+ .map_err(|e| format!("Cannot connect to daemon at {}: {e}", connection.address))?;stream.set_read_timeout(Some(TCP_READ_TIMEOUT)).map_err(|e| e.to_string())?;@@ -612,9 +475,9 @@ fn ping_daemon() -> Result<String, String> {}#[tauri::command(async)]-fn stop_daemon(app: tauri::AppHandle) -> Result<String, String> {+fn stop_daemon() -> Result<String, String> {let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;- stop_daemon_inner(&app)+ stop_daemon_inner()}fn confirm_shutdown(response: &str) -> Result<(), String> {@@ -627,59 +490,26 @@ fn confirm_shutdown(response: &str) -> Result<(), String> {fn clear_session() -> Result<(), String> {invalidate_scan()?;- *SESSION_TOKEN- .lock()- .map_err(|_| "Session state is unavailable")? = None;- *DEVICE_SERIAL- .lock()- .map_err(|_| "Device state is unavailable")? = None;- *DEVICE_PRIVILEGE- .lock()- .map_err(|_| "Device state is unavailable")? = Privilege::Shell;- *READ_ONLY- .lock()- .map_err(|_| "Session state is unavailable")? = false;+ let session = SESSION.lock().map_err(|_| "Session state is unavailable")?.take();+ drop(session); // release the lock before bounded remote cleanupOk(())}fn finish_stop(result: Result<String, String>) -> Result<String, String> {- // Even a missing ADB resource or lost phone connection must release local- // state. Preserve the remote outcome instead of inventing stopped status.clear_session()?;result}-fn stop_daemon_inner(app: &tauri::AppHandle) -> Result<String, String> {+fn stop_daemon_inner() -> Result<String, String> {invalidate_scan()?;- let result = (|| {- let adb_path = get_bundled_binary(app, "adb")?;- let response = daemon_command("SHUTDOWN");- let has_device = DEVICE_SERIAL- .lock()- .map_err(|_| "Device state is unavailable")?- .is_some();- if has_device {- if response.is_err() {- let _ = device_shell(&adb_path, "pkill -f '[s]ocketsweep_daemon' || true");- }- let _ = adb_s(- &adb_path,- &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")],- );- let _ = adb_s(- &adb_path,- &["shell", "rm", "-f", DEVICE_BIN_PATH, DEVICE_TOKEN_PATH],- );- }- // Preserve the existing transport-failure fallback. A rejected or- // unrelated reply must not introduce an extra process-kill attempt.- // Best-effort cleanup cannot substitute for an acknowledgement.- response.and_then(|response| {- confirm_shutdown(&response)?;- Ok(response)- })- })();- finish_stop(result)+ let mut session = SESSION.lock().map_err(|_| "Session state is unavailable")?+ .take().ok_or("No active daemon session")?;+ let connection = session.connection();+ let response = daemon_command_at(connection.address, "SHUTDOWN", &connection.token, Duration::from_secs(3));+ // EOF also retires this exact process after an unreachable/rejected reply,+ // but cleanup cannot substitute for the remote acknowledgement in the UI.+ for error in session.cleanup() { eprintln!("Session cleanup incomplete: {error}"); }+ finish_stop(response.and_then(|response| { confirm_shutdown(&response)?; Ok(response) }))}#[tauri::command(async)]@@ -739,8 +569,19 @@ pub fn run() {get_scan_view,get_scan_node,])- .run(tauri::generate_context!())- .expect("error while running tauri application");+ .build(tauri::generate_context!())+ .expect("error while building tauri application")+ .run(|_, event| {+ if matches!(event, tauri::RunEvent::Exit) {+ if let Ok(active) = ACTIVE_SCAN.lock() {+ if let Some(scan) = active.as_ref() {+ scan.cancelled.store(true, Ordering::SeqCst);+ if let Some(socket) = &scan.socket { let _ = socket.shutdown(Shutdown::Both); }+ }+ }+ let _ = clear_session();+ }+ });}#[cfg(test)]@@ -859,6 +700,25 @@ mod tests {assert!(decode_daemon_response(vec![b'x'; MAX_COMMAND_RESPONSE_BYTES + 1]).is_err());}+ #[test]+ fn small_command_deadline_cannot_be_extended_by_dripping_bytes() {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let peer = std::thread::spawn(move || {+ let (mut socket, _) = listener.accept().unwrap();+ socket.set_write_timeout(Some(Duration::from_secs(1))).unwrap();+ // Each byte arrives before the inactivity timeout would expire.+ for _ in 0..40 {+ if socket.write_all(b"x").is_err() { break; }+ std::thread::sleep(Duration::from_millis(25));+ }+ });+ let start = std::time::Instant::now();+ assert!(daemon_command_at(address, "PING", &"a".repeat(64), Duration::from_millis(150)).is_err());+ assert!(start.elapsed() < Duration::from_millis(800));+ peer.join().unwrap();+ }+#[test]fn invalid_filename_bytes_are_not_replaced() {assert!(decode_daemon_response(b"{\"path\":\"/sdcard/report\xff\"}".to_vec()).is_err());diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rsindex 7012380..2e06609 100644--- a/src-tauri/src/scan_store.rs+++ b/src-tauri/src/scan_store.rs@@ -961,16 +961,12 @@ mod tests {Err("Phone disconnected".into()), Err("Bundled ADB unavailable".into())] {let expected = outcome.clone();*crate::SCAN_STORE.lock().unwrap() = Some(Catalog::new(fixture(&wide(2), true), "generation-a".into()));- *crate::SESSION_TOKEN.lock().unwrap() = Some("fixture-secret".into());- *crate::DEVICE_SERIAL.lock().unwrap() = Some("fixture-device".into());- *crate::READ_ONLY.lock().unwrap() = true;- *crate::DEVICE_PRIVILEGE.lock().unwrap() = crate::Privilege::Su;+ *crate::SESSION.lock().unwrap() = Some(crate::session::Session::test_session());+ assert!(crate::active_connection().unwrap().read_only);assert_eq!(crate::finish_stop(outcome), expected);assert!(crate::SCAN_STORE.lock().unwrap().is_none());- assert!(crate::SESSION_TOKEN.lock().unwrap().is_none());- assert!(crate::DEVICE_SERIAL.lock().unwrap().is_none());- assert!(!*crate::READ_ONLY.lock().unwrap());- assert_eq!(*crate::DEVICE_PRIVILEGE.lock().unwrap(), crate::Privilege::Shell);+ assert!(crate::SESSION.lock().unwrap().is_none());+ assert!(crate::active_connection().is_err());assert!(crate::get_scan_view("generation-a".into(), 0, 0, None).is_err());}}diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rsnew file mode 100644index 0000000..3b4d396--- /dev/null+++ b/src-tauri/src/session.rs@@ -0,0 +1,650 @@+//! One connection owns its device files, allocated forward and lifetime child.+//! Teardown never identifies a remote process by a name or reusable PID.+use crate::{+ adb_with_input_timeout, device_shell_command, new_random_id, require_handshake,+ select_privilege, Privilege,+};+use std::net::{Ipv4Addr, SocketAddr};+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};++const START_TIMEOUT: Duration = Duration::from_secs(45);+const CLEANUP_TIMEOUT: Duration = Duration::from_secs(5);++#[derive(Clone)]+pub(super) struct Connection {+ pub address: SocketAddr,+ pub token: String,+ pub read_only: bool,+}++pub(super) struct Session {+ adb: PathBuf,+ serial: String,+ directory: String,+ privilege: Privilege,+ owned_directory: bool,+ parent: Option<Child>,+ device_port: Option<u16>,+ local_port: Option<u16>,+ forward_attempted: bool,+ connection: Connection,+}++#[derive(serde::Deserialize)]+#[serde(deny_unknown_fields)]+struct Ready {+ port: u16,+ pid: u32,+}++fn remaining(deadline: Instant) -> Result<Duration, String> {+ let time = deadline.saturating_duration_since(Instant::now());+ if time.is_zero() {+ Err("Session operation timed out".into())+ } else {+ Ok(time)+ }+}++impl Session {+ pub fn connection(&self) -> Connection {+ self.connection.clone()+ }++ fn adb(+ &self,+ args: &[&str],+ input: Option<&[u8]>,+ deadline: Instant,+ ) -> Result<String, String> {+ let mut targeted = vec!["-s", self.serial.as_str()];+ targeted.extend_from_slice(args);+ adb_with_input_timeout(+ &self.adb,+ &targeted,+ input,+ remaining(deadline)?.min(Duration::from_secs(15)),+ )+ }++ fn shell(&self, command: &str, deadline: Instant) -> Result<String, String> {+ self.adb(+ &["shell", &device_shell_command(self.privilege, command)],+ None,+ deadline,+ )+ }++ fn new(adb: PathBuf, serial: String) -> Result<Self, String> {+ Ok(Self {+ adb,+ serial,+ directory: format!("/data/local/tmp/socketsweep-{}", new_random_id()?),+ privilege: Privilege::Shell,+ owned_directory: false,+ parent: None,+ device_port: None,+ local_port: None,+ forward_attempted: false,+ connection: Connection {+ address: (Ipv4Addr::LOCALHOST, 0).into(),+ token: new_random_id()?,+ read_only: false,+ },+ })+ }++ #[cfg(test)]+ pub fn test_session() -> Self {+ let mut session = Self::new(PathBuf::from("fixture-adb"), "fixture-device".into()).unwrap();+ session.privilege = Privilege::Su;+ session.connection.read_only = true;+ session+ }++ pub fn start(+ adb: PathBuf,+ daemon: &Path,+ serial: String,+ root_mode: bool,+ ) -> Result<(Self, String), String> {+ let mut session = Self::new(adb, serial)?;+ let result = session.start_inner(daemon, root_mode);+ match result {+ Ok(response) => Ok((session, response)),+ Err(error) => {+ let cleanup = session.cleanup();+ Err(if cleanup.is_empty() {+ error+ } else {+ format!(+ "{error}; session cleanup incomplete: {}",+ cleanup.join("; ")+ )+ })+ }+ }+ }++ fn start_inner(&mut self, daemon: &Path, root_mode: bool) -> Result<String, String> {+ let deadline = Instant::now() + START_TIMEOUT;+ if !self+ .adb(&["features"], None, deadline)?+ .trim()+ .split(',')+ .any(|feature| feature == "shell_v2")+ {+ return Err("The connected device must support ADB shell v2 for owned sessions".into());+ }+ self.privilege = select_privilege(root_mode, |args| self.adb(args, None, deadline))?;+ // The directory is shell-owned even for su launches, so adb push can+ // write into it. mkdir must succeed exclusively before cleanup owns it.+ self.adb(+ &["shell", &format!("umask 077 && mkdir '{}'", self.directory)],+ None,+ deadline,+ )?;+ self.owned_directory = true;+ let token_path = format!("{}/token", self.directory);+ self.adb(+ &["shell", &format!("umask 077 && cat > '{token_path}'")],+ Some(format!("{}\n", self.connection.token).as_bytes()),+ deadline,+ )?;+ let _ = self.adb(+ &[+ "shell",+ "appops set com.android.shell MANAGE_EXTERNAL_STORAGE allow",+ ],+ None,+ deadline,+ );+ let executable = format!("{}/daemon", self.directory);+ self.adb(+ &["push", &daemon.to_string_lossy(), &executable],+ None,+ deadline,+ )?;+ self.adb(+ &["shell", &format!("chmod 700 '{executable}'")],+ None,+ deadline,+ )?;+ let ready_path = format!("{}/ready", self.directory);+ let mode = if root_mode { " --read-only" } else { "" };+ let launch = device_shell_command(+ self.privilege,+ &format!("exec '{executable}' 0 '{token_path}' --session-ready '{ready_path}'{mode}"),+ );+ // 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 ready = loop {+ remaining(deadline)?;+ if 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 text = self.shell(+ &format!("if [ -f '{ready_path}' ]; then cat '{ready_path}'; fi"),+ deadline,+ )?;+ if !text.trim().is_empty() {+ let ready: Ready = serde_json::from_str(&text)+ .map_err(|_| "Invalid daemon session announcement")?;+ if ready.port == 0 || ready.pid < 2 {+ return Err("Invalid daemon session endpoint".into());+ }+ break ready;+ }+ std::thread::sleep(Duration::from_millis(50));+ };+ self.device_port = Some(ready.port);+ self.forward_attempted = true;+ let remote = format!("tcp:{}", ready.port);+ let local = self.adb(+ &["forward", "--no-rebind", "tcp:0", &remote],+ None,+ deadline,+ )?;+ let port = local+ .trim()+ .parse::<u16>()+ .ok()+ .filter(|port| *port != 0)+ .ok_or("ADB did not return its allocated forwarding port")?;+ self.local_port = Some(port);+ self.connection.address.set_port(port);+ // The secret authenticates the exact listener; port/PID metadata alone+ // never confers deletion authority or permits process termination.+ let pong = crate::daemon_command_at(+ self.connection.address,+ "PING",+ &self.connection.token,+ remaining(deadline)?.min(Duration::from_secs(5)),+ )?;+ self.connection.read_only = require_handshake(&pong, root_mode)?.read_only.unwrap();+ Ok(format!(+ "{{\"daemon_pid\":\"{}\",\"ping_response\":{pong}}}",+ ready.pid+ ))+ }++ pub fn cleanup(&mut self) -> Vec<String> {+ let deadline = Instant::now() + CLEANUP_TIMEOUT;+ let mut errors = Vec::new();+ // A lost allocation reply does not identify the local listener. Never+ // guess which entry belongs to us from its remote port alone.+ if self.forward_attempted {+ self.forward_attempted = false;+ if let (Some(local), Some(remote)) = (self.local_port, self.device_port) {+ match self.adb(&["forward", "--list"], None, deadline) {+ Ok(list) => {+ for local in owned_forwards(&list, &self.serial, local, remote) {+ if let Err(error) =+ self.adb(&["forward", "--remove", &local], None, deadline)+ {+ errors.push(error);+ }+ }+ }+ Err(error) => errors.push(error),+ }+ } else {+ errors.push(+ "ADB did not confirm the allocated forward; an unused local forward may remain"+ .into(),+ );+ }+ }+ if let Some(mut child) = self.parent.take() {+ drop(child.stdin.take()); // authenticated lifetime ownership, not a remote PID kill+ let until = Instant::now() + Duration::from_millis(250);+ while matches!(child.try_wait(), Ok(None)) && Instant::now() < until {+ std::thread::sleep(Duration::from_millis(10));+ }+ if !matches!(child.try_wait(), Ok(Some(_))) {+ let _ = child.kill(); // only our unreaped host child+ let _ = child.wait();+ }+ }+ if self.owned_directory {+ self.owned_directory = false;+ // No recursive delete and no shared legacy paths. Unknown extra+ // files make rmdir fail instead of broadening deletion authority.+ let dir = &self.directory;+ let command = format!("[ ! -L '{dir}' ] && rm -f '{dir}/token' '{dir}/ready' '{dir}/ready.tmp' '{dir}/daemon' && rmdir '{dir}'");+ if let Err(error) = self.shell(&command, deadline) {+ errors.push(error);+ }+ }+ errors+ }+}++impl Drop for Session {+ fn drop(&mut self) {+ for error in self.cleanup() {+ eprintln!("Session cleanup incomplete: {error}");+ }+ }+}++fn owned_forwards(list: &str, serial: &str, local: u16, remote: u16) -> Vec<String> {+ let remote = format!("tcp:{remote}");+ list.lines()+ .filter_map(|line| {+ let fields: Vec<_> = line.split_whitespace().collect();+ if fields.len() != 3 || fields[0] != serial || fields[2] != remote {+ return None;+ }+ let port = fields[1].strip_prefix("tcp:")?.parse::<u16>().ok()?;+ if port == 0 || port != local {+ return None;+ }+ Some(format!("tcp:{port}"))+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn forward_cleanup_checks_device_local_and_remote_identity() {+ let list = "one tcp:1001 tcp:2001\none tcp:1002 tcp:2002\ntwo tcp:1003 tcp:2001\none tcp:0 tcp:2001\none localabstract:foreign tcp:2001\nbad line";+ assert_eq!(owned_forwards(list, "one", 1001, 2001), ["tcp:1001"]);+ assert!(owned_forwards(list, "one", 1001, 2002).is_empty());+ assert!(owned_forwards(list, "two", 1001, 2001).is_empty());+ assert!(owned_forwards(list, "one", 0, 2001).is_empty());+ }++ #[cfg(unix)]+ mod unix {+ use super::*;+ use std::fs;+ use std::os::unix::fs::PermissionsExt;+ use std::sync::OnceLock;++ fn quote(path: &Path) -> String {+ format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))+ }++ fn daemon() -> &'static Path {+ static BINARY: OnceLock<PathBuf> = OnceLock::new();+ BINARY.get_or_init(|| {+ let directory = std::env::temp_dir().join(format!(+ "socketsweep-session-build-{}",+ new_random_id().unwrap()+ ));+ fs::create_dir(&directory).unwrap();+ let binary = directory.join("daemon");+ let source = Path::new(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .unwrap()+ .join("engine/daemon.cpp");+ assert!(+ Command::new(std::env::var("CXX").unwrap_or_else(|_| "c++".into()))+ .args([+ "-std=c++17",+ "-O2",+ "-pthread",+ "-fno-exceptions",+ "-fno-rtti",+ "-Wall",+ "-Wextra",+ "-Wpedantic"+ ])+ .arg(source)+ .arg("-o")+ .arg(&binary)+ .status()+ .unwrap()+ .success()+ );+ binary+ })+ }++ struct Device {+ root: PathBuf,+ }+ impl Device {+ fn new() -> Self {+ let root = std::env::temp_dir().join(format!(+ "socketsweep session tests {}",+ new_random_id().unwrap()+ ));+ fs::create_dir(&root).unwrap();+ fs::create_dir(root.join("phone")).unwrap();+ // A foreign mapping must survive every cleanup and failure.+ fs::write(+ root.join("forwards.json"),+ r#"[["foreign","tcp:1234","tcp:5678"]]"#,+ )+ .unwrap();+ Self { root }+ }+ fn client(&self, name: &str, serial: &str) -> PathBuf {+ let base = self.root.join(name);+ fs::create_dir(&base).unwrap();+ let config = serde_json::json!({"base": base, "serial": serial, "phone":self.root.join("phone"), "registry":self.root.join("forwards.json")});+ let file = base.join("config.json");+ fs::write(&file, serde_json::to_vec(&config).unwrap()).unwrap();+ let helper = Path::new(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .unwrap()+ .join("tests/fake_session_adb.py");+ let executable = base.join("fake-adb");+ fs::write(+ &executable,+ format!(+ "#!/bin/sh\nexec python3 {} {} \"$@\"\n",+ quote(&helper),+ quote(&file)+ ),+ )+ .unwrap();+ fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();+ executable+ }+ fn rows(&self) -> Vec<Vec<String>> {+ serde_json::from_slice(&fs::read(self.root.join("forwards.json")).unwrap()).unwrap()+ }+ fn directories(&self) -> usize {+ fs::read_dir(self.root.join("phone")).unwrap().count()+ }+ }+ impl Drop for Device {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.root);+ }+ }+ fn fail(adb: &Path, stage: &str) {+ fs::write(adb.parent().unwrap().join("fail"), stage).unwrap();+ }+ fn ping(session: &Session) -> String {+ let c = session.connection();+ crate::daemon_command_at(c.address, "PING", &c.token, Duration::from_secs(2)).unwrap()+ }++ #[test]+ fn two_sessions_on_same_or_different_devices_remain_independent() {+ for serials in [("same", "same"), ("first", "second")] {+ let device = Device::new();+ let adb_a = device.client("client-a", serials.0);+ let adb_b = device.client("client-b", serials.1);+ let (mut a, response_a) =+ Session::start(adb_a.clone(), daemon(), serials.0.into(), false).unwrap();+ let (mut b, _) = Session::start(adb_b, daemon(), serials.1.into(), false).unwrap();+ assert_ne!(a.directory, b.directory);+ assert_ne!(a.connection.address, b.connection.address);+ assert_ne!(a.connection.token, b.connection.token);+ assert!(!response_a.contains(&a.connection.token));+ assert_eq!(device.rows().len(), 3);+ let local = device+ .root+ .join("phone")+ .join(a.directory.rsplit('/').next().unwrap());+ assert_eq!(+ fs::metadata(&local).unwrap().permissions().mode() & 0o777,+ 0o700+ );+ assert_eq!(+ fs::metadata(local.join("daemon"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o700+ );+ assert!(!local.join("token").exists());+ assert!(a.cleanup().is_empty());+ assert_eq!(device.rows().len(), 2);+ assert_eq!(device.directories(), 1);+ assert!(ping(&b).contains("\"status\":\"ok\""));+ let c = b.connection();+ let ack = crate::daemon_command_at(+ c.address,+ "SHUTDOWN",+ &c.token,+ Duration::from_secs(2),+ )+ .unwrap();+ crate::confirm_shutdown(&ack).unwrap();+ assert!(b.cleanup().is_empty());+ assert_eq!(device.rows().len(), 1);+ assert_eq!(device.directories(), 0);+ let calls =+ fs::read_to_string(adb_a.parent().unwrap().join("calls.jsonl")).unwrap();+ assert!(!calls.contains(&a.connection.token));+ for forbidden in ["pkill", "kill-server", "--remove-all", "nohup"] {+ assert!(!calls.contains(forbidden));+ }+ }+ }++ #[test]+ fn startup_failures_retire_only_the_failed_sessions_resources() {+ let device = Device::new();+ let (mut survivor, _) = Session::start(+ device.client("survivor", "same"),+ daemon(),+ "same".into(),+ false,+ )+ .unwrap();+ for stage in [+ "features",+ "mkdir",+ "token",+ "push",+ "chmod",+ "launch",+ "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}"+ );+ assert_eq!(+ device.rows().len(),+ 2,+ "leaked/collateral forward at {stage}"+ );+ assert_eq!(+ device.directories(),+ 1,+ "leaked/collateral directory at {stage}"+ );+ assert!(ping(&survivor).contains("\"status\":\"ok\""));+ }+ assert!(survivor.cleanup().is_empty());+ }++ #[test]+ fn unconfirmed_forward_allocations_are_reported_without_guessing_ownership() {+ for stage in ["forward", "bad-forward"] {+ let device = Device::new();+ let (mut survivor, _) = Session::start(+ device.client("survivor", "same"),+ daemon(),+ "same".into(),+ false,+ )+ .unwrap();+ let adb = device.client(stage, "same");+ fail(&adb, stage);+ let error = Session::start(adb, daemon(), "same".into(), false)+ .err()+ .unwrap();+ assert!(error.contains("unused local forward may remain"), "{error}");+ assert_eq!(device.rows().len(), 3); // foreign, survivor, unknown allocation+ assert_eq!(device.directories(), 1); // failed daemon/files are still retired+ assert!(ping(&survivor).contains("\"status\":\"ok\""));+ assert!(survivor.cleanup().is_empty());+ assert_eq!(device.rows().len(), 2);+ }+ }++ #[test]+ fn su_commands_preserve_privilege_but_cannot_fake_a_root_handshake() {+ let device = Device::new();+ let adb = device.client("su", "same");+ let result = Session::start(adb.clone(), daemon(), "same".into(), true);+ let root = Command::new("id").arg("-u").output().unwrap().stdout == b"0\n";+ assert_eq!(result.is_ok(), root);+ drop(result);+ assert_eq!(device.directories(), 0);+ assert_eq!(device.rows().len(), 1);+ let calls = fs::read_to_string(adb.parent().unwrap().join("calls.jsonl")).unwrap();+ assert!(calls.contains("--read-only"));+ assert!(calls.contains("su -c"));+ assert!(calls.contains("rmdir"));+ fail(&adb, "root");+ assert!(Session::start(adb, daemon(), "same".into(), true).is_err());+ assert_eq!(device.directories(), 0);+ }++ #[test]+ fn cleanup_deadline_still_closes_its_lifetime_channel() {+ let device = Device::new();+ let adb = device.client("slow", "same");+ let (mut session, _) =+ Session::start(adb.clone(), daemon(), "same".into(), false).unwrap();+ let address = session.connection.address;+ fail(&adb, "cleanup-timeout");+ let started = Instant::now();+ assert!(!session.cleanup().is_empty());+ assert!(started.elapsed() < Duration::from_secs(8));+ assert!(+ std::net::TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_err()+ );+ }++ #[test]+ fn cleanup_preserves_a_forward_that_was_rebound_to_a_foreign_endpoint() {+ let device = Device::new();+ let (mut session, _) = Session::start(+ device.client("rebound", "same"),+ daemon(),+ "same".into(),+ false,+ )+ .unwrap();+ let mut rows = device.rows();+ let local = format!("tcp:{}", session.connection.address.port());+ rows.iter_mut().find(|row| row[1] == local).unwrap()[2] = "tcp:9999".into();+ fs::write(+ device.root.join("forwards.json"),+ serde_json::to_vec(&rows).unwrap(),+ )+ .unwrap();+ assert!(session.cleanup().is_empty());+ assert_eq!(device.rows(), rows);+ assert_eq!(device.directories(), 0);+ }++ #[test]+ fn adb_output_is_bounded_and_inherited_pipes_cannot_extend_its_deadline() {+ let device = Device::new();+ let adb = device.client("pipes", "same");+ let call = |operation| {+ adb_with_input_timeout(+ &adb,+ &["-s", "same", operation],+ None,+ Duration::from_millis(200),+ )+ };+ let error =+ adb_with_input_timeout(&adb, &["-s", "same", "huge"], None, Duration::from_secs(2))+ .unwrap_err();+ assert!(error.contains("limit"), "{error}");+ let started = Instant::now();+ assert!(call("held-pipe").unwrap_err().contains("timed out"));+ assert!(started.elapsed() < Duration::from_secs(2));+ }+ }+}diff --git a/tests/fake_session_adb.py b/tests/fake_session_adb.pynew file mode 100644index 0000000..b9be20d--- /dev/null+++ b/tests/fake_session_adb.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""Unix-only ADB fixture: private local files and a real host-built daemon.++No Android commands or real ADB executable are invoked. Forwarding is modeled+by using the host daemon's port directly and recording the requested mapping.+"""+import fcntl+import json+import os+from pathlib import Path+import shlex+import shutil+import subprocess+import sys+import time++config = json.loads(Path(sys.argv[1]).read_text())+args = sys.argv[2:]+assert args[:2] == ["-s", config["serial"]], args+args = args[2:]+base = Path(config["base"])+with (base / "calls.jsonl").open("a") as stream:+ stream.write(json.dumps(args) + "\n") # the token is stdin, never logged+failure = (base / "fail").read_text().strip() if (base / "fail").exists() else ""+++def fail(stage):+ if failure == stage:+ sys.exit("Injected " + stage + " failure")+++def mapped(command):+ # Production session paths contain only a fixed prefix and random hex.+ return command.replace("/data/local/tmp/", str(Path(config["phone"])) + "/")+++if args == ["features"]:+ print("shell_v2" if failure != "features" else "other_feature")+elif args[0] == "push":+ fail("push")+ shutil.copyfile(args[1], mapped(args[2]))+elif args[0] == "shell":+ command = args[-1]+ elevated = command.startswith("su -c ")+ if elevated:+ command = shlex.split(command)[2]+ if command == "id -u":+ print("0" if elevated and failure != "root" else "2000")+ elif args[1] == "-T":+ fail("launch")+ command = shlex.split(mapped(command))+ assert command[0] == "exec"+ if failure == "handshake":+ Path(command[3]).write_text("0" * 64 + "\n")+ os.execv(command[1], command[1:])+ elif "appops set" in command:+ pass+ else:+ stage = ("mkdir" if "mkdir " in command else "token" if "cat > " in command else+ "chmod" if "chmod " in command else "ready" if "if [ -f " in command else "cleanup")+ fail(stage)+ if stage == "ready" and failure == "bad-ready":+ print("{}")+ sys.exit(0)+ sys.exit(subprocess.call(["/bin/sh", "-c", mapped(command)]))+elif args[0] == "forward":+ registry = Path(config["registry"])+ with Path(str(registry) + ".lock").open("a") as lock:+ fcntl.flock(lock, fcntl.LOCK_EX)+ rows = json.loads(registry.read_text()) if registry.exists() else []+ if args[1] == "--list":+ if failure == "cleanup-timeout":+ time.sleep(60)+ for row in rows:+ print(" ".join(row))+ elif args[1] == "--remove":+ rows = [row for row in rows if not (row[0] == config["serial"] and row[1] == args[2])]+ registry.write_text(json.dumps(rows))+ else:+ assert args[1:3] == ["--no-rebind", "tcp:0"], args+ remote = args[3]+ rows.append([config["serial"], remote, remote])+ registry.write_text(json.dumps(rows))+ fail("forward") # allocation happened, but the reply was lost+ print("invalid-port" if failure == "bad-forward" else remote.split(":")[1])+elif args == ["huge"]:+ sys.stdout.write("x" * (1024 * 1024))+elif args == ["held-pipe"]:+ subprocess.Popen([sys.executable, "-c", "import time; time.sleep(2)"], stdin=subprocess.DEVNULL)+else:+ raise AssertionError(args)diff --git a/tests/test_owned_session.py b/tests/test_owned_session.pynew file mode 100644index 0000000..6e4d655--- /dev/null+++ b/tests/test_owned_session.py@@ -0,0 +1,121 @@+"""Real host daemon lifetime tests; no Android device or ADB executable."""+import json+import os+from pathlib import Path+import secrets+import socket+import stat+import subprocess+import tempfile+import time++from test_daemon import DaemonHarness+++class OwnedSessionTests(DaemonHarness):+ def setUp(self):+ self.files = tempfile.TemporaryDirectory(prefix="socketsweep owned sessions ")+ self.addCleanup(self.files.cleanup)+ self.children = []+ self.addCleanup(self.close_children)++ def close_children(self):+ for child in self.children:+ if child.stdin:+ child.stdin.close()+ try:+ child.wait(timeout=2)+ except subprocess.TimeoutExpired:+ child.kill()+ child.wait()+ child.stderr.close()++ def launch(self, name, read_only=False, prepare=None, closed_input=False):+ directory = Path(self.files.name) / name+ directory.mkdir(mode=0o700)+ token = secrets.token_hex(32)+ token_file = directory / "token"+ token_file.write_text(token + "\n")+ token_file.chmod(0o600)+ ready = directory / "ready"+ if prepare:+ prepare(ready)+ args = [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,+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ self.children.append(child)+ return child, ready, token++ def wait_ready(self, child, path):+ deadline = time.monotonic() + 3+ while time.monotonic() < deadline:+ if path.exists():+ ready = json.loads(path.read_text())+ self.assertGreater(ready["port"], 0)+ self.assertEqual(ready["pid"], child.pid)+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)+ self.assertFalse(path.with_name("token").exists())+ self.assertFalse(Path(str(path) + ".tmp").exists())+ return ready["port"]+ if child.poll() is not None:+ self.fail(child.stderr.read().decode())+ time.sleep(0.01)+ self.fail("No complete readiness record")++ def command(self, port, token, command="PING"):+ with socket.create_connection(("127.0.0.1", port), timeout=2) as client:+ client.sendall(f"AUTH {token}\n{command}\n".encode())+ client.shutdown(socket.SHUT_WR)+ with client.makefile("rb") as response:+ return json.loads(response.readline())++ def test_two_live_sessions_have_distinct_ports_secrets_and_lifetimes(self):+ a, path_a, token_a = self.launch("one")+ b, path_b, token_b = self.launch("two", read_only=True)+ port_a, port_b = self.wait_ready(a, path_a), self.wait_ready(b, path_b)+ self.assertNotEqual(port_a, port_b)+ self.assertEqual(self.command(port_a, token_a)["read_only"], os.geteuid() == 0)+ self.assertTrue(self.command(port_b, token_b)["read_only"])+ self.assertEqual(self.command(port_a, token_b)["status"], "error")+ a.stdin.close()+ a.stdin = None+ self.assertEqual(a.wait(timeout=1), 0)+ self.assertEqual(self.command(port_b, token_b)["status"], "ok")+ self.assertEqual(self.command(port_b, token_b, "SHUTDOWN")["message"], "shutting down")+ self.assertEqual(b.wait(timeout=1), 0)++ def test_owner_eof_interrupts_an_incomplete_command_without_touching_other_session(self):+ a, ready_a, token_a = self.launch("blocked")+ b, ready_b, token_b = self.launch("survivor")+ port_a, port_b = self.wait_ready(a, ready_a), self.wait_ready(b, ready_b)+ with socket.create_connection(("127.0.0.1", port_a), timeout=2) as peer:+ peer.sendall(f"AUTH {token_a}".encode()) # no newline: command timeout would be 30 seconds+ started = time.monotonic()+ a.stdin.close()+ a.stdin = None+ self.assertEqual(a.wait(timeout=1), 0)+ self.assertLess(time.monotonic() - started, 1)+ self.assertEqual(self.command(port_b, token_b)["status"], "ok")++ def test_readiness_publication_does_not_replace_existing_files_or_symlinks(self):+ for kind in ("ready", "ready-link", "temporary", "temporary-link"):+ with self.subTest(kind=kind):+ def prepare(ready):+ target = ready.parent / "keep"+ target.write_text("keep")+ path = Path(str(ready) + ".tmp") if kind.startswith("temporary") else ready+ if kind.endswith("link"):+ path.symlink_to(target)+ else:+ path.write_text("keep")+ child, ready, _ = self.launch(kind, prepare=prepare)+ self.assertNotEqual(child.wait(timeout=2), 0)+ self.assertEqual((ready.parent / "keep").read_text(), "keep")+ path = Path(str(ready) + ".tmp") if kind.startswith("temporary") else ready+ self.assertEqual(path.read_text(), "keep")++ 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)