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

Read bounded command chunks without consuming surplus lines (#50)

Vishnu Srivatsava9326b4221adb
diff --git a/docs/scan-stream-v1.md b/docs/scan-stream-v1.md
index 31fc630..726b685 100644
--- a/docs/scan-stream-v1.md
+++ b/docs/scan-stream-v1.md
@@ -8,6 +8,11 @@ reference tests and diagnostics. Keep the client's write side open until the
response finishes: half-close, disconnect, and extra command bytes abort the
stream. Commands cannot contain CR, LF, or NUL, and retain the 16 KiB limit.
+Command input is read in bounded 4 KiB chunks. The daemon peeks before consuming
+through one newline, leaving surplus bytes in the socket for the next AUTH/command
+read or the stream's extra-byte check. Each line has one absolute 30-second
+deadline; short reads and interrupted syscalls do not reset it.
+
## Framing and records
Each frame is a four-byte unsigned big-endian byte length followed by UTF-8
diff --git a/engine/daemon.cpp b/engine/daemon.cpp
index 69c5507..a0b4a6f 100644
--- a/engine/daemon.cpp
+++ b/engine/daemon.cpp
@@ -114,7 +114,7 @@ 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;
+ char buffer[4096];
while (true) {
const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now()).count();
@@ -123,13 +123,27 @@ static bool recv_line(int fd, std::string& line) {
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 (std::chrono::steady_clock::now() >= deadline) return false;
+
+ // Peek a bounded chunk, then consume only through its first newline.
+ // Surplus bytes stay in the socket across AUTH/command reads, where
+ // ScanOutput can still detect and reject extra command bytes.
+ ssize_t n = ::recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT);
+ if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue;
if (n <= 0) return false;
- if (c == '\n') return true;
+ const char* newline = static_cast<const char*>(std::memchr(buffer, '\n', static_cast<size_t>(n)));
+ const size_t length = newline ? static_cast<size_t>(newline - buffer) + 1 : static_cast<size_t>(n);
+ n = ::recv(fd, buffer, length, MSG_DONTWAIT);
+ if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue;
+ if (n <= 0 || std::chrono::steady_clock::now() >= deadline) return false;
+
+ const bool complete = buffer[n - 1] == '\n';
+ const size_t payload = static_cast<size_t>(n) - (complete ? 1 : 0);
// 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;
+ if (payload > cfg::MAX_COMMAND_BYTES - line.size() ||
+ std::memchr(buffer, '\r', payload) || std::memchr(buffer, '\0', payload)) return false;
+ line.append(buffer, payload);
+ if (complete) return true;
}
}
diff --git a/tests/command_input_test.cpp b/tests/command_input_test.cpp
new file mode 100644
index 0000000..b1d0a60
--- /dev/null
+++ b/tests/command_input_test.cpp
@@ -0,0 +1,221 @@
+#include <atomic>
+#include <cerrno>
+#include <chrono>
+#include <cstring>
+#include <poll.h>
+#include <sys/socket.h>
+#include <thread>
+#include <vector>
+
+// Instrument real syscalls in this test translation unit, without production hooks.
+static std::atomic<size_t> receive_calls{0}, poll_calls{0};
+static size_t peek_limit = 4096, consume_limit = 4096;
+static int peek_faults = 0, consume_faults = 0, poll_interrupts = 0;
+static bool simulated_timeout = false, record_timeouts = false;
+static std::vector<int> timeouts;
+
+static ssize_t measured_recv(int fd, void* buffer, size_t length, int flags) {
+ ++receive_calls;
+ const bool peek = (flags & MSG_PEEK) != 0;
+ int& faults = peek ? peek_faults : consume_faults;
+ if (faults > 0) {
+ errno = --faults % 2 ? EINTR : EAGAIN;
+ return -1;
+ }
+ const size_t cap = peek ? peek_limit : consume_limit;
+ return ::recv(fd, buffer, length < cap ? length : cap, flags);
+}
+
+static int measured_poll(struct pollfd* fds, nfds_t count, int timeout) {
+ ++poll_calls;
+ if (record_timeouts) timeouts.push_back(timeout);
+ if (poll_interrupts > 0) {
+ --poll_interrupts;
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ errno = EINTR;
+ return -1;
+ }
+ if (simulated_timeout) return 0;
+ return ::poll(fds, count, timeout);
+}
+
+#define recv measured_recv
+#define poll measured_poll
+#define main daemon_main
+#include "../engine/daemon.cpp"
+#undef main
+#undef poll
+#undef recv
+
+static void require(bool ok, const char* message) {
+ if (!ok) { std::fprintf(stderr, "%s\n", message); std::exit(1); }
+}
+
+struct Sockets {
+ safe_delete::Fd reader, writer;
+ Sockets() {
+ int pair[2];
+ require(::socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0, "socketpair failed");
+ reader.reset(pair[0]); writer.reset(pair[1]);
+ int capacity = 128 * 1024;
+ require(::setsockopt(writer.get(), SOL_SOCKET, SO_SNDBUF, &capacity, sizeof(capacity)) == 0,
+ "socket buffer setup failed");
+ }
+ void write(const std::string& data) {
+ require(JsonStream::send_all(writer.get(), data.data(), data.size()), "fixture write failed");
+ }
+};
+
+static const std::string auth = "AUTH " + std::string(64, 'a');
+
+static void coalesced() {
+ Sockets sockets;
+ sockets.write(auth + "\nPING\nSHUTDOWN\n");
+ std::string line;
+ require(recv_line(sockets.reader.get(), line) && line == auth, "AUTH framing changed");
+ require(recv_line(sockets.reader.get(), line) && line == "PING", "command framing changed");
+ require(receive_calls <= 6 && poll_calls <= 3, "reader still performs per-byte syscalls");
+ char extra[16];
+ const auto n = ::recv(sockets.reader.get(), extra, sizeof(extra), MSG_PEEK | MSG_DONTWAIT);
+ require(n == 9 && std::string(extra, static_cast<size_t>(n)) == "SHUTDOWN\n",
+ "surplus bytes disappeared from the socket");
+}
+
+static void splits() {
+ const std::string command = u8"DELETE /storage/ 写真 trailing ";
+ for (size_t cap = 1; cap <= auth.size() + command.size(); ++cap) {
+ peek_limit = cap;
+ consume_limit = cap % 7 + 1;
+ Sockets sockets;
+ sockets.write(auth + "\n" + command + "\nNEXT\n");
+ std::string line;
+ require(recv_line(sockets.reader.get(), line) && line == auth, "split AUTH changed");
+ require(recv_line(sockets.reader.get(), line) && line == command, "split path bytes changed");
+ require(recv_line(sockets.reader.get(), line) && line == "NEXT", "split surplus lost");
+ }
+}
+
+static void bounds() {
+ for (size_t length : {size_t(0), size_t(1), size_t(4095), size_t(4096), size_t(4097),
+ cfg::MAX_COMMAND_BYTES - 1, cfg::MAX_COMMAND_BYTES, cfg::MAX_COMMAND_BYTES + 1}) {
+ Sockets sockets;
+ const std::string expected(length, 'x');
+ sockets.write(expected + "\nNEXT\n");
+ std::string line;
+ const bool valid = recv_line(sockets.reader.get(), line);
+ require(valid == (length <= cfg::MAX_COMMAND_BYTES), "line bound changed");
+ require(line.size() <= cfg::MAX_COMMAND_BYTES, "line grew beyond its bound");
+ if (valid) {
+ require(line == expected, "bounded line changed");
+ require(recv_line(sockets.reader.get(), line) && line == "NEXT", "boundary lost next line");
+ }
+ }
+}
+
+static void invalid() {
+ for (char bad : {'\r', '\0'}) {
+ for (size_t position : {size_t(0), size_t(4095), size_t(4096), cfg::MAX_COMMAND_BYTES - 1}) {
+ Sockets sockets;
+ std::string data(cfg::MAX_COMMAND_BYTES, 'x');
+ data[position] = bad;
+ sockets.write(data + "\nNEXT\n");
+ std::string line;
+ require(!recv_line(sockets.reader.get(), line), "invalid delimiter accepted");
+ }
+ }
+ for (const auto& data : {std::string(), std::string("PING")}) {
+ Sockets sockets;
+ sockets.write(data);
+ require(::shutdown(sockets.writer.get(), SHUT_WR) == 0, "half-close failed");
+ std::string line;
+ require(!recv_line(sockets.reader.get(), line), "EOF accepted as a newline");
+ }
+}
+
+static void interruptions() {
+ Sockets sockets;
+ sockets.write(auth + "\nPING\n");
+ peek_faults = consume_faults = 2;
+ std::string line;
+ require(recv_line(sockets.reader.get(), line) && line == auth, "interrupted AUTH changed");
+ require(recv_line(sockets.reader.get(), line) && line == "PING", "interrupted command changed");
+ require(peek_faults == 0 && consume_faults == 0, "retry paths not exercised");
+}
+
+static void deadline() {
+ Sockets sockets;
+ poll_interrupts = 2;
+ simulated_timeout = record_timeouts = true;
+ std::string line;
+ require(!recv_line(sockets.reader.get(), line), "poll timeout did not fail the read");
+ require(timeouts.size() == 3 && timeouts.front() <= cfg::RECV_TIMEOUT_SEC * 1000 &&
+ timeouts.back() < timeouts.front() - 10, "interruptions reset the absolute deadline");
+ require(receive_calls == 0, "read attempted after timeout");
+}
+
+static void dispatch() {
+ g_session_token = std::string(64, 'a');
+ for (const auto& request : {auth + "\nPING\nSHUTDOWN\n", std::string("AUTH wrong\nSHUTDOWN\n")}) {
+ Sockets sockets;
+ sockets.write(request);
+ handle_client(sockets.reader.get());
+ require(g_running == 1, "extra or unauthenticated command was dispatched");
+ char response[512];
+ const auto n = ::recv(sockets.writer.get(), response, sizeof(response), MSG_DONTWAIT);
+ require(n > 0, "dispatch response missing");
+ const std::string text(response, static_cast<size_t>(n));
+ require(text.find(request == auth + "\nPING\nSHUTDOWN\n" ? "pong" : "Authentication failed") !=
+ std::string::npos, "dispatch semantics changed");
+ }
+}
+
+static void stream_extra() {
+ char pattern[] = "/tmp/socketsweep-command-XXXXXX";
+ char* root = ::mkdtemp(pattern);
+ require(root != nullptr, "root fixture setup failed");
+ g_session_token = std::string(64, 'a');
+ for (const auto& extra : {std::string("SHUTDOWN\n"), std::string("\0", 1),
+ std::string("\r\n"), std::string("x")}) {
+ require(g_scan_root.open(root), "previous root fixture setup failed");
+ Sockets sockets;
+ sockets.write(auth + "\nSCAN_STREAM " + root + "\n" + extra);
+ handle_client(sockets.reader.get());
+ require(g_running == 1 && g_scan_root.fd.get() < 0, "extra stream enabled dispatch or deletion");
+ char byte;
+ const auto n = ::recv(sockets.writer.get(), &byte, 1, MSG_DONTWAIT);
+ require(n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK), "extra stream published data");
+ }
+ require(::rmdir(root) == 0, "root fixture cleanup failed");
+}
+
+static void benchmark(int iterations, size_t length) {
+ require(iterations > 0 && length >= 4 && length <= cfg::MAX_COMMAND_BYTES, "bad benchmark arguments");
+ Sockets sockets;
+ const std::string command = length == 4 ? "PING" : std::string(length, 'x');
+ const std::string request = auth + "\n" + command + "\n";
+ std::string line;
+ const auto start = std::chrono::steady_clock::now();
+ for (int i = 0; i < iterations; ++i) {
+ sockets.write(request);
+ require(recv_line(sockets.reader.get(), line) && line == auth, "benchmark AUTH changed");
+ require(recv_line(sockets.reader.get(), line) && line == command, "benchmark command changed");
+ }
+ const auto elapsed = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
+ std::printf("{\"iterations\":%d,\"request_bytes\":%zu,\"recv_calls\":%zu,\"poll_calls\":%zu,\"wall_ms\":%.3f}\n",
+ iterations, request.size(), receive_calls.load(), poll_calls.load(), elapsed);
+}
+
+int main(int argc, char** argv) {
+ require(argc >= 2, "missing case");
+ const std::string name = argv[1];
+ if (name == "coalesced") coalesced();
+ else if (name == "splits") splits();
+ else if (name == "bounds") bounds();
+ else if (name == "invalid") invalid();
+ else if (name == "interruptions") interruptions();
+ else if (name == "deadline") deadline();
+ else if (name == "dispatch") dispatch();
+ else if (name == "stream_extra") stream_extra();
+ else if (name == "benchmark" && argc == 4) benchmark(std::atoi(argv[2]), static_cast<size_t>(std::atoi(argv[3])));
+ else require(false, "unknown case");
+}
diff --git a/tests/parallel_scan_test.cpp b/tests/parallel_scan_test.cpp
index b23c210..0071456 100644
--- a/tests/parallel_scan_test.cpp
+++ b/tests/parallel_scan_test.cpp
@@ -75,7 +75,8 @@ static Snapshot run(const std::string& path, int workers, bool streaming = false
snapshot.result.workers = pool.run(snapshot.stats, workers);
snapshot.result.queue_peak = pool.queue_peak();
require(output.finish(snapshot.stats, 0, snapshot.result.workers), "stream finish failed");
- ::shutdown(writer.get(), SHUT_WR);
+ // Match the daemon's terminal close before waiting for the receiver's EOF.
+ writer.reset();
drain.join();
} else {
snapshot.result = parallel_scan::run(root, snapshot.tree, snapshot.stats, workers, cfg::MAX_DEPTH);
@@ -302,7 +303,7 @@ static void stream_limits_and_root_replacement(bool replace) {
ScanStats stats; const int workers = pool.run(stats, 4);
require(!output.finish(stats, 0, workers), "staging budget ignored");
}
- ::shutdown(writer.get(), SHUT_WR); drain.join();
+ writer.reset(); drain.join();
require(wire.find("\"type\":\"error\"") != std::string::npos, "missing stream failure");
require(wire.find("\"type\":\"done\"") == std::string::npos, "failed stream reported success");
}
diff --git a/tests/test_command_input.py b/tests/test_command_input.py
new file mode 100644
index 0000000..cd03d6d
--- /dev/null
+++ b/tests/test_command_input.py
@@ -0,0 +1,89 @@
+"""Bounded command ingestion, controlled short reads, and real TCP framing."""
+import json
+import os
+from pathlib import Path
+import shutil
+import socket
+import subprocess
+import tempfile
+import unittest
+
+from test_daemon import DaemonHarness
+
+
+class CommandReaderTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.build = tempfile.TemporaryDirectory(prefix="socketsweep-command-build-")
+ cls.binary = str(Path(cls.build.name) / "command-tests")
+ compiler = os.environ.get("CXX") or shutil.which("clang++") or "c++"
+ subprocess.run([compiler, "-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra",
+ "-Wpedantic", "-fno-exceptions", "-fno-rtti",
+ str(Path(__file__).with_name("command_input_test.cpp")),
+ "-o", cls.binary], check=True)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.build.cleanup()
+
+ def run_case(self, case):
+ result = subprocess.run([self.binary, case], capture_output=True, text=True, timeout=5)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+ def test_coalesced_lines_reduce_syscalls_and_preserve_surplus(self): self.run_case("coalesced")
+ def test_forced_short_reads_preserve_utf8_and_spaces(self): self.run_case("splits")
+ def test_chunk_and_exact_line_boundaries(self): self.run_case("bounds")
+ def test_invalid_delimiters_and_truncated_input(self): self.run_case("invalid")
+ def test_interrupted_and_would_block_reads_retry_without_loss(self): self.run_case("interruptions")
+ def test_poll_interruptions_consume_the_same_deadline_budget(self): self.run_case("deadline")
+ def test_authentication_and_single_command_dispatch(self): self.run_case("dispatch")
+ def test_coalesced_extra_stream_bytes_cannot_enable_deletion(self): self.run_case("stream_extra")
+
+
+class CommandFramingTests(DaemonHarness):
+ def fragmented_request(self, pieces):
+ with socket.create_connection(("127.0.0.1", self.port), timeout=2) as client:
+ for piece in pieces:
+ client.sendall(piece)
+ client.shutdown(socket.SHUT_WR)
+ with client.makefile("rb") as response:
+ return json.loads(response.readline())
+
+ def test_auth_and_ping_accept_every_two_piece_split(self):
+ payload = f"AUTH {self.token}\nPING\n".encode()
+ for split in range(1, len(payload)):
+ self.assertEqual(self.fragmented_request([payload[:split], payload[split:]])["status"], "ok")
+
+ @unittest.skipIf(os.geteuid() == 0, "Writable daemon test requires an unprivileged user")
+ def test_fragmented_delete_keeps_unicode_and_trailing_spaces_exact(self):
+ sibling = self.root / " 写真"
+ sibling.write_text("keep")
+ target = self.root / " 写真 "
+ payload = f"AUTH {self.token}\nDELETE {target}\n".encode()
+ start = payload.index("写真".encode())
+ for split in range(start, len(payload)):
+ target.write_text("delete")
+ self.scan()
+ result = self.fragmented_request([payload[:split], payload[split:]])
+ self.assertEqual(result["status"], "ok")
+ self.assertFalse(target.exists())
+ self.assertEqual(sibling.read_text(), "keep")
+
+ def test_legacy_request_dispatches_only_its_first_command(self):
+ target = self.root / "keep"
+ target.write_text("keep")
+ self.scan()
+ payload = f"AUTH {self.token}\nPING\nDELETE {target}\nSHUTDOWN\n".encode()
+ self.assertEqual(self.raw_request(payload)["message"], "pong")
+ self.assertTrue(target.exists())
+ self.assertEqual(self.request("PING")["status"], "ok")
+
+ def test_line_limit_counts_bytes_and_accepts_exactly_16_kib(self):
+ for command in ["x" * (16 * 1024), "é" * (8 * 1024)]:
+ self.assertEqual(self.request(command)["message"], "Unknown command")
+ self.assertEqual(self.request(command + "x")["message"], "Invalid command framing")
+
+ def test_missing_newline_never_dispatches_shutdown(self):
+ for payload in [f"AUTH {self.token}".encode(), f"AUTH {self.token}\nSHUTDOWN".encode()]:
+ self.assertEqual(self.raw_request(payload)["status"], "error")
+ self.assertEqual(self.request("PING")["status"], "ok")