A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
fix: pkill self-kill, multi-device serial, server-side delete guard, CSP
Vishnu Srivatsava239c32aa6254
diff --git a/engine/daemon.cpp b/engine/daemon.cppindex 4303537..fac1589 100644--- a/engine/daemon.cpp+++ b/engine/daemon.cpp@@ -34,6 +34,37 @@ namespace cfg {// ── Globals ─────────────────────────────────────────────────────────────────static volatile sig_atomic_t g_running = 1;static void on_signal(int) { g_running = 0; }+static std::string g_scan_root; // tracks the active scan root for delete validation++// ── Delete path validation ──────────────────────────────────────────────────++/// Returns true if `target` is strictly inside `root` (component-wise).+/// Rejects: the root itself, paths that escape via "..", and non-existent paths.+static bool path_is_safe_to_delete(const std::string& target, const std::string& root) {+ if (target.empty() || root.empty()) return false;++ // Canonicalize both paths to resolve "..", symlinks, etc.+ char* real_target = ::realpath(target.c_str(), nullptr);+ char* real_root = ::realpath(root.c_str(), nullptr);+ if (!real_target || !real_root) {+ free(real_target);+ free(real_root);+ return false;+ }++ std::string rt(real_target);+ std::string rr(real_root);+ free(real_target);+ free(real_root);++ // Target must not be the root itself.+ if (rt == rr) return false;++ // Target must start with root + "/" (component-wise, not just prefix).+ // This prevents /sdcard/Down from matching /sdcard/Downloads.+ if (rr.back() != '/') rr += '/';+ return rt.size() > rr.size() && rt.compare(0, rr.size(), rr) == 0;+}// ── Network & Streaming Helpers ─────────────────────────────────────────────class JsonStream {@@ -242,16 +273,24 @@ static void handle_client(int fd) {}else if (cmd.rfind("DELETE ", 0) == 0) {std::string target = trim(cmd.substr(7));- std::error_code ec;- std::uintmax_t removed = std::filesystem::remove_all(target, ec);- if (ec) {- out.write("{\"status\":\"error\",\"message\":\"");- json_escape_into(out, ec.message());- out.write("\"}\n");++ // Server-side delete guard: validate target is strictly inside the scan root.+ if (g_scan_root.empty()) {+ out.write("{\"status\":\"error\",\"message\":\"No scan performed yet — cannot validate delete target\"}\n");+ } else if (!path_is_safe_to_delete(target, g_scan_root)) {+ out.write("{\"status\":\"error\",\"message\":\"Delete rejected: path is outside scan root or equals scan root\"}\n");} else {- out.write("{\"status\":\"ok\",\"message\":\"Deleted ");- out.write(std::to_string(removed));- out.write(" items\"}\n");+ std::error_code ec;+ std::uintmax_t removed = std::filesystem::remove_all(target, ec);+ if (ec) {+ out.write("{\"status\":\"error\",\"message\":\"");+ json_escape_into(out, ec.message());+ out.write("\"}\n");+ } else {+ out.write("{\"status\":\"ok\",\"message\":\"Deleted ");+ out.write(std::to_string(removed));+ out.write(" items\"}\n");+ }}}else if (cmd.rfind("SCAN", 0) == 0) {@@ -268,6 +307,7 @@ static void handle_client(int fd) {root_name = root.substr(pos + 1);std::fprintf(stderr, "[engine] SCAN \"%s\" ...\n", root.c_str());+ g_scan_root = root; // store for delete validationauto t0 = std::chrono::steady_clock::now();ScanStats stats{};diff --git a/package-lock.json b/package-lock.jsonindex 71ea4c5..1336f4b 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,13 @@{- "name": "tauri-app",- "version": "0.1.0",+ "name": "socketsweep",+ "version": "1.0.0","lockfileVersion": 3,"requires": true,"packages": {"": {- "name": "tauri-app",- "version": "0.1.0",+ "name": "socketsweep",+ "version": "1.0.0",+ "license": "GPL-3.0","dependencies": {"@tailwindcss/vite": "^4.3.0","@tauri-apps/api": "^2",diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 831c326..46b18a1 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -28,6 +28,9 @@ const TCP_READ_TIMEOUT: Duration = Duration::from_secs(120); // scans can be slo/// Tracks the root path of the last successful scan so we can prevent its deletion.static SCAN_ROOT: Mutex<Option<String>> = Mutex::new(None);+/// Tracks the serial of the connected device so all ADB calls target the right device.+static DEVICE_SERIAL: Mutex<Option<String>> = Mutex::new(None);+// ── Resource Resolution ─────────────────────────────────────────────────────use tauri::Manager;@@ -126,6 +129,19 @@ fn adb(adb_path: &std::path::Path, args: &[&str]) -> Result<String, String> {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);+ }+ }+ adb(adb_path, args)+}+// ── TCP helper ──────────────────────────────────────────────────────────────/// Send a one-line command to the daemon and read the full response.@@ -176,39 +192,51 @@ fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {// 1 — Verify ADB is reachable and a device is connected.adb(&adb_path, &["version"])?;let devices = adb(&adb_path, &["devices"])?;- let connected = devices+ let device_line = devices.lines()- .filter(|l| l.contains("device") && !l.starts_with("List"))- .count();- if connected == 0 {- return Err(- "No Android device detected. Connect your phone via USB and enable USB Debugging.".into(),- );+ .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);}// 2 — Kill any zombie daemon before we push/start.- let _ = adb(&adb_path, &["shell", "pkill -f socketsweep_daemon || true"]);+ let _ = adb_s(&adb_path, &["shell", "pkill -f '[s]ocketsweep_daemon' || true"]);// 2.5 — Automate MANAGE_EXTERNAL_STORAGE permission for the shell user.- let _ = adb(&adb_path, &["shell", "appops set com.android.shell MANAGE_EXTERNAL_STORAGE allow"]);+ let _ = adb_s(&adb_path, &["shell", "appops set com.android.shell MANAGE_EXTERNAL_STORAGE allow"]);// 4 — Push binary to device.- adb(&adb_path, &["push", &daemon_src.to_string_lossy(), DEVICE_BIN_PATH])?;+ adb_s(&adb_path, &["push", &daemon_src.to_string_lossy(), DEVICE_BIN_PATH])?;// 5 — Make it executable.- adb(&adb_path, &["shell", "chmod", "+x", DEVICE_BIN_PATH])?;+ adb_s(&adb_path, &["shell", "chmod", "+x", DEVICE_BIN_PATH])?;// 5 — Kill any previously running instance (ignore errors).- let _ = adb(&adb_path, &["shell", "pkill", "-f", "socketsweep_daemon"]);+ let _ = adb_s(&adb_path, &["shell", "pkill", "-f", "'[s]ocketsweep_daemon'"]);std::thread::sleep(Duration::from_millis(300));// 6 — Start the daemon in the background on the device.let start_cmd = format!("nohup {DEVICE_BIN_PATH} > /dev/null 2>&1 & echo $!; exit");- let pid_output = adb(&adb_path, &["shell", &start_cmd])?;+ let pid_output = adb_s(&adb_path, &["shell", &start_cmd])?;let pid = pid_output.trim().to_string();// 7 — Set up the USB TCP tunnel.- adb(&adb_path, &["forward", &format!("tcp:{DAEMON_PORT}"), &format!("tcp:{DAEMON_PORT}")])?;+ adb_s(&adb_path, &["forward", &format!("tcp:{DAEMON_PORT}"), &format!("tcp:{DAEMON_PORT}")])?;// 8 — Ping-Retry loop.let mut pong = String::new();@@ -260,8 +288,8 @@ fn ping_daemon() -> Result<String, String> {fn stop_daemon(app: tauri::AppHandle) -> Result<String, String> {let adb_path = get_bundled_binary(&app, "adb")?;let response = daemon_command("SHUTDOWN").unwrap_or_else(|_| "daemon already stopped".into());- let _ = adb(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);- let _ = adb(&adb_path, &["shell", "rm", DEVICE_BIN_PATH]);+ let _ = adb_s(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);+ let _ = adb_s(&adb_path, &["shell", "rm", DEVICE_BIN_PATH]);Ok(response)}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex ffb1b69..5bafdd0 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -18,7 +18,7 @@}],"security": {- "csp": null+ "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ipc: http://ipc.localhost"}},"bundle": {