Skip to content

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: authenticate daemon sessions and preserve delete paths (#20)

Vishnu Srivatsava515422c3d3b3
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 6402a0a..e27e74a 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -69,6 +69,10 @@ jobs:
- name: Install frontend dependencies
run: npm ci
+ - name: Test daemon protocol on host
+ if: runner.os != 'Windows'
+ run: python3 -m unittest discover -s tests -v
+
# ── Cross-compile C++ daemon for Android aarch64 ──────────────────────
# The daemon always targets Android ARM64, regardless of host OS.
# Uses the pre-installed Android NDK on GitHub Actions runners.
@@ -178,6 +182,9 @@ jobs:
- name: Build Tauri app
run: npm run tauri build
+ - name: Test Rust bridge
+ run: cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
+
# ── Fix AppImage: guarantee root icon + .DirIcon + sane modes ─────────
# Required for AppImage catalog validation. tauri-bundler 2.11.1 emits a
# .DirIcon whose target is an ABSOLUTE path into the build machine
diff --git a/.gitignore b/.gitignore
index d71a6ea..25ce5d9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,5 @@ output.json
# Exclude local JSON test dumps
out*.json
+# Python daemon regression tests
+__pycache__/
diff --git a/README.md b/README.md
index 9a9dddc..b65e549 100644
--- a/README.md
+++ b/README.md
@@ -110,6 +110,11 @@ Instead of going through MTP, SocketSweep does something completely different:
The architecture was inspired by [scrcpy](https://github.com/Genymobile/scrcpy) — the "push a native binary via ADB, communicate over a local socket" pattern.
+Each connection authenticates with a fresh 256-bit session secret before the
+daemon accepts a command. The secret reaches the phone through a shell-owned
+startup file with mode `0600`; the daemon reads and removes that file before
+listening. The app and daemon must use the same protocol version.
+
---
## 🏗 Architecture (For Developers)
@@ -154,8 +159,9 @@ sequenceDiagram
R->>A: pkill daemon (Cleanup)
R->>A: push daemon /data/local/tmp
R->>A: appops set MANAGE_EXTERNAL_STORAGE allow
- R->>A: nohup ./daemon &
+ R->>A: Write private startup secret, launch daemon
R->>A: adb forward tcp:5050 tcp:5050
+ R->>D: AUTH session secret (on every connection)
R->>D: Ping-Retry Loop (150ms)
D-->>R: ACK Connection
R-->>U: Connected!
@@ -195,7 +201,9 @@ export NDK=/path/to/your/android-ndk-r26d
cd engine
bash ./build.sh
```
-*This generates the stripped `daemon` binary in the `engine/` directory.*
+*This generates the stripped `daemon` binary in the `engine/` directory and
+copies it into `src-tauri/bin/daemon`, which Tauri bundles. Rebuild after changing
+the daemon so local development uses the current protocol.*
### 2. Install Frontend Dependencies
```bash
@@ -209,6 +217,22 @@ npm run tauri dev
```
*Ensure your Android device is plugged in via USB and **USB Debugging** is enabled.*
+### 4. Run regression tests
+
+```bash
+# macOS/Linux: compiles the host daemon and uses disposable local files
+python3 -m unittest discover -s tests -v
+
+# Build the frontend first when testing from a clean checkout
+npm run build
+cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
+```
+
+The line-based protocol preserves spaces in filenames. Paths containing a
+newline, carriage return, or null byte are rejected before sending, so they
+cannot cause a different file to be deleted. Scan responses containing invalid
+UTF-8 filenames are also rejected rather than replacing filename bytes.
+
---
## 🛠 Troubleshooting
diff --git a/engine/build.sh b/engine/build.sh
index 5a37dbc..1a80797 100644
--- a/engine/build.sh
+++ b/engine/build.sh
@@ -46,7 +46,13 @@ echo "[build] Compiling daemon.cpp → daemon (aarch64-linux-android) ..."
-std=c++17 -O2 -Wall -Wextra -Wpedantic \
-fno-exceptions -fno-rtti -DNDEBUG \
-static-libstdc++ \
+ -s \
-o "$OUT" "$SRC"
+# Tauri bundles this copy, rather than engine/daemon. Keep both in sync so
+# local development uses the same protocol and guards as release builds.
+cp "$OUT" "$SCRIPT_DIR/../src-tauri/bin/daemon"
+
echo "[build] Output: $OUT ($(wc -c < "$OUT" | tr -d ' ') bytes)"
+echo "[build] Updated src-tauri/bin/daemon"
echo "[build] Done."
diff --git a/engine/daemon.cpp b/engine/daemon.cpp
index f8a4e52..15d1392 100644
--- a/engine/daemon.cpp
+++ b/engine/daemon.cpp
@@ -7,6 +7,8 @@
#include <cstdint>
#include <cstdio>
#include <cstring>
+#include <cstdlib>
+#include <cerrno>
#include <string>
#include <vector>
@@ -20,6 +22,8 @@
#include <unistd.h>
#include <filesystem>
#include <iostream>
+#include <fstream>
+#include <poll.h>
// ── Configuration ───────────────────────────────────────────────────────────
namespace cfg {
@@ -29,12 +33,14 @@ namespace cfg {
constexpr int LISTEN_BACKLOG = 4;
constexpr int MAX_DEPTH = 64;
constexpr int RECV_TIMEOUT_SEC = 30;
+ constexpr size_t MAX_COMMAND_BYTES = 16 * 1024;
}
// ── 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
+static std::string g_session_token;
// Per-phase scan timing (see SCAN in handle_client). Counters reset per scan.
static int64_t g_sort_ns = 0; // cumulative time sorting directory children
@@ -123,23 +129,33 @@ public:
}
};
-static std::string recv_line(int fd) {
- std::string line;
+static bool recv_line(int fd, std::string& line) {
+ line.clear();
+ const auto deadline = std::chrono::steady_clock::now() +
+ std::chrono::seconds(cfg::RECV_TIMEOUT_SEC);
char c;
while (true) {
+ const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
+ deadline - std::chrono::steady_clock::now()).count();
+ if (remaining <= 0) return false;
+ struct pollfd event { fd, POLLIN, 0 };
+ int ready = ::poll(&event, 1, static_cast<int>(remaining));
+ if (ready < 0 && errno == EINTR) continue;
+ if (ready <= 0) return false;
ssize_t n = ::recv(fd, &c, 1, 0);
if (n < 0 && errno == EINTR) continue;
- if (n <= 0) break;
- if (c == '\n') break;
- if (c != '\r') line += c;
+ if (n <= 0) return false;
+ if (c == '\n') return true;
+ // Never normalize path bytes or execute an incomplete/oversized line.
+ if (c == '\r' || c == '\0' || line.size() >= cfg::MAX_COMMAND_BYTES) return false;
+ line += c;
}
- return line;
}
-static std::string trim(std::string s) {
- while (!s.empty() && s.back() == ' ') s.pop_back();
- size_t start = s.find_first_not_of(' ');
- return (start == std::string::npos) ? "" : s.substr(start);
+static bool valid_token(const std::string& token) {
+ return token.size() == 64 && std::all_of(token.begin(), token.end(), [](char c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
+ });
}
// ── Data Model ──────────────────────────────────────────────────────────────
@@ -271,14 +287,22 @@ static FileNode scan(const std::string& path, const std::string& name,
static void handle_client(int fd) {
struct timeval tv { cfg::RECV_TIMEOUT_SEC, 0 };
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
-
- std::string cmd = trim(recv_line(fd));
- if (cmd.empty()) return;
+ ::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
JsonStream out(fd);
+ std::string auth;
+ if (!recv_line(fd, auth) || auth != "AUTH " + g_session_token) {
+ out.write("{\"status\":\"error\",\"message\":\"Authentication failed\"}\n");
+ return;
+ }
+ std::string cmd;
+ if (!recv_line(fd, cmd) || cmd.empty()) {
+ out.write("{\"status\":\"error\",\"message\":\"Invalid command framing\"}\n");
+ return;
+ }
if (cmd == "PING") {
- out.write("{\"status\":\"ok\",\"message\":\"pong\"}\n");
+ out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":2}\n");
}
else if (cmd == "SHUTDOWN") {
out.write("{\"status\":\"ok\",\"message\":\"shutting down\"}\n");
@@ -287,7 +311,7 @@ static void handle_client(int fd) {
return;
}
else if (cmd.rfind("DELETE ", 0) == 0) {
- std::string target = trim(cmd.substr(7));
+ std::string target = cmd.substr(7);
// Server-side delete guard: validate target is strictly inside the scan root.
if (g_scan_root.empty()) {
@@ -308,10 +332,10 @@ static void handle_client(int fd) {
}
}
}
- else if (cmd.rfind("SCAN", 0) == 0) {
+ else if (cmd == "SCAN" || cmd.rfind("SCAN ", 0) == 0) {
std::string root = cfg::DEFAULT_ROOT;
if (cmd.size() > 4) {
- std::string arg = trim(cmd.substr(4));
+ std::string arg = cmd.substr(5);
if (!arg.empty()) root = arg;
}
while (root.size() > 1 && root.back() == '/') root.pop_back();
@@ -322,7 +346,13 @@ 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 validation
+ g_scan_root.clear();
+
+ struct stat root_info{};
+ if (::stat(root.c_str(), &root_info) != 0 || !S_ISDIR(root_info.st_mode)) {
+ out.write("{\"status\":\"error\",\"message\":\"Scan root is not an accessible directory\"}\n");
+ return;
+ }
g_sort_ns = 0;
g_send_ns = 0;
@@ -331,6 +361,7 @@ static void handle_client(int fd) {
auto t0 = std::chrono::steady_clock::now();
ScanStats stats{};
FileNode tree = scan(root, root_name, stats, 0);
+ g_scan_root = root;
auto t1 = std::chrono::steady_clock::now();
int64_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();
int64_t traverse_ms = ms - ns_to_ms(g_sort_ns);
@@ -392,6 +423,21 @@ int main(int argc, char* argv[]) {
uint16_t port = cfg::PORT;
if (argc > 1) port = static_cast<uint16_t>(std::atoi(argv[1]));
+ // A shell-owned 0600 file supplies the secret, keeping it out of process
+ // arguments. Consume and unlink it before accepting any connections.
+ if (argc != 3) {
+ std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE\n");
+ return 1;
+ }
+ {
+ std::ifstream token_file(argv[2]);
+ std::getline(token_file, g_session_token);
+ }
+ if (::unlink(argv[2]) != 0 || !valid_token(g_session_token)) {
+ std::fprintf(stderr, "[engine] Failed to load session token\n");
+ return 1;
+ }
+
::signal(SIGINT, on_signal);
::signal(SIGTERM, on_signal);
::signal(SIGPIPE, SIG_IGN);
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 92345de..dc56a5c 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -3360,6 +3360,7 @@ dependencies = [
name = "tauri-app"
version = "0.1.0"
dependencies = [
+ "getrandom 0.3.4",
"serde",
"serde_json",
"tauri",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 5ac0ba5..88baa94 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -23,4 +23,4 @@ tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
-
+getrandom = "0.3"
diff --git a/src-tauri/bin/daemon b/src-tauri/bin/daemon
index b89e5bb..53c532f 100755
Binary files a/src-tauri/bin/daemon and b/src-tauri/bin/daemon differ
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index ec46fe5..988706f 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -6,7 +6,8 @@
// React frontend can display meaningful error messages.
//
// Wire protocol (matches Phase 1 daemon):
-// → "PING\n" ← {"status":"ok","message":"pong"}
+// Each connection starts with "AUTH <session token>\n", then one command.
+// → "PING\n" ← {"status":"ok","message":"pong","protocol_version":2}
// → "SCAN [path]\n" ← {"status":"ok","scan_time_ms":…,"tree":{…}}
// → "SHUTDOWN\n" ← {"status":"ok","message":"shutting down"}
// ============================================================================
@@ -22,6 +23,7 @@ use std::time::Duration;
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 TCP_READ_TIMEOUT: Duration = Duration::from_secs(120); // scans can be slow
@@ -30,6 +32,9 @@ 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);
+static SESSION_TOKEN: Mutex<Option<String>> = Mutex::new(None);
+// Keep connection changes, scans, and deletes in order across async commands.
+static DAEMON_OPERATION: Mutex<()> = Mutex::new(());
// ── Resource Resolution ─────────────────────────────────────────────────────
@@ -62,11 +67,16 @@ fn get_bundled_binary(app: &tauri::AppHandle, name: &str) -> Result<std::path::P
/// Run an ADB command and return its stdout. Maps any failure to a
/// human-readable `Err(String)`.
fn adb(adb_path: &std::path::Path, args: &[&str]) -> Result<String, String> {
+ adb_with_input(adb_path, args, None)
+}
+
+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)
+ .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()
@@ -87,6 +97,15 @@ fn adb(adb_path: &std::path::Path, args: &[&str]) -> Result<String, String> {
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();
@@ -146,6 +165,20 @@ fn adb_s(adb_path: &std::path::Path, args: &[&str]) -> Result<String, String> {
/// Send a one-line command to the daemon and read the full response.
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)
+}
+
+fn command_payload(cmd: &str, token: &str) -> Result<String, String> {
+ if cmd.is_empty() || cmd.len() > 16 * 1024 || cmd.contains(['\r', '\n', '\0']) {
+ return Err("This path cannot be sent safely: it contains a line break or null byte, or is too long.".into());
+ }
+ Ok(format!("AUTH {token}\n{cmd}\n"))
+}
+
+fn daemon_command_with_token(cmd: &str, token: &str) -> Result<String, String> {
+ let payload = command_payload(cmd, token)?;
let mut stream = TcpStream::connect_timeout(
&DAEMON_ADDR.parse().unwrap(),
TCP_CONNECT_TIMEOUT,
@@ -155,12 +188,8 @@ fn daemon_command(cmd: &str) -> Result<String, String> {
stream
.set_read_timeout(Some(TCP_READ_TIMEOUT))
.map_err(|e| format!("Failed to set read timeout: {e}"))?;
-
- let payload = if cmd.ends_with('\n') {
- cmd.to_string()
- } else {
- format!("{cmd}\n")
- };
+ 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}"))?;
@@ -170,8 +199,38 @@ fn daemon_command(cmd: &str) -> Result<String, String> {
.read_to_end(&mut response_bytes)
.map_err(|e| format!("Failed to read daemon response: {e}"))?;
- let response = String::from_utf8_lossy(&response_bytes).trim().to_string();
- Ok(response)
+ decode_daemon_response(response_bytes)
+}
+
+fn decode_daemon_response(bytes: Vec<u8>) -> Result<String, String> {
+ // Replacement characters would change paths, potentially selecting a
+ // different file when a displayed node is later deleted.
+ String::from_utf8(bytes)
+ .map(|response| response.trim().to_string())
+ .map_err(|_| "Daemon returned invalid UTF-8 filenames. This scan cannot be displayed safely.".into())
+}
+
+#[derive(serde::Deserialize)]
+struct DaemonStatus {
+ status: String,
+ message: Option<String>,
+ protocol_version: Option<u32>,
+}
+
+fn require_ok(response: &str) -> Result<DaemonStatus, String> {
+ // Ignore the tree here rather than allocating a second copy of the scan.
+ let parsed: DaemonStatus = serde_json::from_str(response)
+ .map_err(|_| "Daemon returned an invalid response".to_string())?;
+ if parsed.status != "ok" {
+ return Err(parsed.message.unwrap_or_else(|| "Daemon command failed".into()));
+ }
+ Ok(parsed)
+}
+
+fn new_session_token() -> Result<String, String> {
+ let mut bytes = [0_u8; 32];
+ getrandom::fill(&mut bytes).map_err(|e| format!("Failed to create daemon session: {e}"))?;
+ Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}
// ── Tauri Commands ──────────────────────────────────────────────────────────
@@ -186,6 +245,28 @@ fn check_adb(app: tauri::AppHandle) -> Result<String, String> {
#[tauri::command(async)]
fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {
+ let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
+ *SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = None;
+ *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
+ *DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;
+ let result = init_daemon_inner(app.clone());
+ 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 _ = adb_s(&adb_path, &["shell", "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;
+ }
+ result
+}
+
+fn init_daemon_inner(app: tauri::AppHandle) -> Result<String, String> {
let adb_path = get_bundled_binary(&app, "adb")?;
let daemon_src = get_bundled_binary(&app, "daemon")?;
@@ -217,6 +298,14 @@ fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {
// 2 — Kill any zombie daemon before we push/start.
let _ = adb_s(&adb_path, &["shell", "pkill -f '[s]ocketsweep_daemon' || true"]);
+ // 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_session_token()?;
+ 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"]);
@@ -231,7 +320,7 @@ fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {
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 start_cmd = format!("nohup {DEVICE_BIN_PATH} {DAEMON_PORT} {DEVICE_TOKEN_PATH} > /dev/null 2>&1 & echo $!; exit");
let pid_output = adb_s(&adb_path, &["shell", &start_cmd])?;
let pid = pid_output.trim().to_string();
@@ -243,7 +332,13 @@ fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {
let mut connected_daemon = false;
for _ in 0..15 {
std::thread::sleep(Duration::from_millis(150));
- match daemon_command("PING") {
+ match daemon_command_with_token("PING", &token).and_then(|res| {
+ let parsed = require_ok(&res)?;
+ if parsed.protocol_version != Some(2) {
+ return Err("Bundled daemon is outdated. Rebuild it before connecting.".into());
+ }
+ Ok(res)
+ }) {
Ok(res) => {
pong = res;
connected_daemon = true;
@@ -254,9 +349,11 @@ fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {
}
if !connected_daemon {
- return Err("Daemon started but failed to respond to PING over TCP tunnel.".into());
+ return Err("Daemon did not complete the authenticated handshake. Rebuild the bundled daemon and reconnect.".into());
}
+ *SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = Some(token);
+
Ok(format!(
"{{\"daemon_pid\":\"{pid}\",\"ping_response\":{pong}}}"
))
@@ -264,12 +361,15 @@ fn init_daemon(app: tauri::AppHandle) -> Result<String, String> {
#[tauri::command(async)]
fn run_scan(path: Option<String>) -> Result<String, String> {
+ let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
let effective_root = match path {
Some(ref p) if !p.is_empty() => p.clone(),
_ => "/sdcard".to_string(), // daemon default
};
let cmd = format!("SCAN {effective_root}");
+ *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
let response = daemon_command(&cmd)?;
+ require_ok(&response)?;
// Store the scan root so delete_item can guard against it.
if let Ok(mut root) = SCAN_ROOT.lock() {
@@ -279,30 +379,38 @@ fn run_scan(path: Option<String>) -> Result<String, String> {
Ok(response)
}
-#[tauri::command]
+#[tauri::command(async)]
fn ping_daemon() -> Result<String, String> {
+ let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
daemon_command("PING")
}
#[tauri::command(async)]
fn stop_daemon(app: tauri::AppHandle) -> Result<String, String> {
+ let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
let adb_path = get_bundled_binary(&app, "adb")?;
let response = daemon_command("SHUTDOWN").unwrap_or_else(|_| "daemon already stopped".into());
let _ = adb_s(&adb_path, &["forward", "--remove", &format!("tcp:{DAEMON_PORT}")]);
- let _ = adb_s(&adb_path, &["shell", "rm", DEVICE_BIN_PATH]);
+ let _ = adb_s(&adb_path, &["shell", "rm", "-f", DEVICE_BIN_PATH, DEVICE_TOKEN_PATH]);
+ *SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = None;
+ *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
+ *DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;
Ok(response)
}
#[tauri::command(async)]
fn delete_item(path: String) -> Result<String, String> {
+ let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
// Prevent deletion of the scan root directory.
- if let Ok(root) = SCAN_ROOT.lock() {
- if let Some(ref scan_root) = *root {
- if path == *scan_root {
- return Err("Cannot delete the scan root directory.".into());
- }
+ let root = SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")?;
+ match root.as_ref() {
+ Some(scan_root) if path == *scan_root => {
+ return Err("Cannot delete the scan root directory.".into());
}
+ None => return Err("Scan your device before deleting files.".into()),
+ _ => {}
}
+ drop(root);
daemon_command(&format!("DELETE {path}"))
}
@@ -323,3 +431,46 @@ pub fn run() {
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn paths_keep_their_exact_spaces() {
+ assert_eq!(command_payload("DELETE /sdcard/ report ", "token").unwrap(),
+ "AUTH token\nDELETE /sdcard/ report \n");
+ }
+
+ #[test]
+ fn paths_with_protocol_delimiters_are_rejected() {
+ for path in ["/sdcard/report\nother", "/sdcard/report\r", "/sdcard/report\0other"] {
+ assert!(command_payload(&format!("DELETE {path}"), "token").is_err());
+ assert!(command_payload(&format!("SCAN {path}"), "token").is_err());
+ }
+ assert!(command_payload(&"x".repeat(16 * 1024 + 1), "token").is_err());
+ }
+
+ #[test]
+ fn session_tokens_are_fresh_and_have_full_entropy() {
+ let first = new_session_token().unwrap();
+ let second = new_session_token().unwrap();
+ assert_eq!(first.len(), 64);
+ assert!(first.bytes().all(|b| b.is_ascii_hexdigit()));
+ assert_ne!(first, second);
+ }
+
+ #[test]
+ fn daemon_errors_cannot_be_treated_as_success() {
+ assert!(require_ok("{\"status\":\"ok\"}").is_ok());
+ assert!(require_ok("{\"status\":\"error\",\"message\":\"Authentication failed\"}").is_err());
+ assert!(require_ok("invalid").is_err());
+ }
+
+ #[test]
+ fn invalid_filename_bytes_are_not_replaced() {
+ assert!(decode_daemon_response(b"{\"path\":\"/sdcard/report\xff\"}".to_vec()).is_err());
+ assert_eq!(decode_daemon_response("{\"path\":\"/sdcard/写真\"}\n".as_bytes().to_vec()).unwrap(),
+ "{\"path\":\"/sdcard/写真\"}");
+ }
+}
diff --git a/tests/test_daemon.py b/tests/test_daemon.py
new file mode 100644
index 0000000..9ca0f9a
--- /dev/null
+++ b/tests/test_daemon.py
@@ -0,0 +1,157 @@
+"""Exercise the daemon against disposable files, without an Android device.
+
+Run: python3 -m unittest discover -s tests -v
+"""
+
+import json
+import os
+from pathlib import Path
+import secrets
+import shutil
+import socket
+import subprocess
+import tempfile
+import time
+import unittest
+
+
+class DaemonTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.build_dir = tempfile.TemporaryDirectory(prefix="socketsweep-test-build-")
+ cls.binary = str(Path(cls.build_dir.name) / "daemon")
+ 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", "-Wall", "-Wextra",
+ "-Wpedantic", "-fno-exceptions", "-fno-rtti",
+ str(source), "-o", cls.binary], check=True)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.build_dir.cleanup()
+
+ def setUp(self):
+ self.files = tempfile.TemporaryDirectory(prefix="socketsweep-test-files-")
+ self.addCleanup(self.files.cleanup)
+ self.root = Path(self.files.name) / "storage"
+ self.root.mkdir()
+ self.token = secrets.token_hex(32)
+ token_file = Path(self.files.name) / "session"
+ token_file.write_text(self.token + "\n")
+ token_file.chmod(0o600)
+ with socket.socket() as reservation:
+ reservation.bind(("127.0.0.1", 0))
+ self.port = reservation.getsockname()[1]
+ self.process = subprocess.Popen([self.binary, str(self.port), str(token_file)],
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ self.addCleanup(self.stop)
+ for _ in range(100):
+ try:
+ self.request("PING")
+ break
+ except OSError:
+ if self.process.poll() is not None:
+ self.fail(self.process.stderr.read().decode())
+ time.sleep(0.01)
+ else:
+ self.fail("Daemon did not start")
+ self.assertFalse(token_file.exists(), "Startup secret must be consumed")
+
+ def stop(self):
+ if self.process.poll() is None:
+ try:
+ self.request("SHUTDOWN")
+ self.process.wait(timeout=2)
+ except (OSError, subprocess.TimeoutExpired):
+ self.process.kill()
+ self.process.wait()
+ self.process.stderr.close()
+
+ def raw_request(self, payload):
+ with socket.create_connection(("127.0.0.1", self.port), timeout=2) as client:
+ client.sendall(payload)
+ client.shutdown(socket.SHUT_WR)
+ data = b""
+ while not data.endswith(b"\n"):
+ chunk = client.recv(65536)
+ if not chunk:
+ break
+ data += chunk
+ return json.loads(data)
+
+ def request(self, command):
+ return self.raw_request(f"AUTH {self.token}\n{command}\n".encode())
+
+ def scan(self):
+ result = self.request(f"SCAN {self.root}")
+ self.assertEqual(result["status"], "ok")
+ return result
+
+ def test_authenticated_ping_and_scan(self):
+ (self.root / "photo").write_bytes(b"1234567")
+ self.assertEqual(self.request("PING")["protocol_version"], 2)
+ result = self.scan()
+ self.assertEqual(result["total_files"], 1)
+ self.assertEqual(result["total_size"], 7)
+
+ def test_commands_require_the_current_secret(self):
+ target = self.root / "keep"
+ target.write_text("keep")
+ self.scan()
+ for command in ["PING", f"SCAN {self.root}", f"DELETE {target}", "SHUTDOWN"]:
+ self.assertEqual(self.raw_request((command + "\n").encode())["status"], "error")
+ wrong = f"AUTH {'0' * 64}\n{command}\n".encode()
+ self.assertEqual(self.raw_request(wrong)["status"], "error")
+ self.assertTrue(target.exists())
+ self.assertEqual(self.request("PING")["status"], "ok")
+
+ def test_delete_preserves_filename_spaces(self):
+ sibling = self.root / "report"
+ sibling.write_text("keep")
+ for name in ["report ", " report", " report "]:
+ target = self.root / name
+ target.write_text("delete")
+ self.scan()
+ self.assertEqual(self.request(f"DELETE {target}")["status"], "ok")
+ self.assertFalse(target.exists())
+ self.assertTrue(sibling.exists())
+
+ def test_invalid_frames_do_not_delete_a_shorter_path(self):
+ target = self.root / "report"
+ target.write_text("keep")
+ self.scan()
+ for suffix in [b"\r\n", b"\0other\n", b"", b"x" * (16 * 1024) + b"\n"]:
+ payload = f"AUTH {self.token}\nDELETE {target}".encode() + suffix
+ self.assertEqual(self.raw_request(payload)["status"], "error")
+ self.assertTrue(target.exists())
+
+ def test_delete_requires_scan_and_rejects_root_and_escapes(self):
+ target = self.root / "keep"
+ target.write_text("keep")
+ self.assertEqual(self.request(f"DELETE {target}")["status"], "error")
+ outside = Path(self.files.name) / "storage-other"
+ outside.mkdir()
+ other = outside / "keep"
+ other.write_text("keep")
+ (self.root / "escape").symlink_to(outside, target_is_directory=True)
+ self.scan()
+ for path in [self.root, outside, other, self.root / ".." / "storage-other" / "keep",
+ self.root / "escape" / "keep"]:
+ self.assertEqual(self.request(f"DELETE {path}")["status"], "error")
+ self.assertTrue(target.exists())
+ self.assertTrue(other.exists())
+
+ def test_failed_scan_clears_previous_delete_root(self):
+ target = self.root / "keep"
+ target.write_text("keep")
+ self.scan()
+ self.assertEqual(self.request(f"SCAN {self.root / 'missing'}")["status"], "error")
+ self.assertEqual(self.request(f"DELETE {target}")["status"], "error")
+ self.assertTrue(target.exists())
+
+ def test_scan_verb_must_be_exact(self):
+ self.assertEqual(self.request(f"SCANOTHER {self.root}")["status"], "error")
+
+
+if __name__ == "__main__":
+ unittest.main()