Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
Verify staged base64 uploads before replacing the destination
am-tmacb82492df39c5
diff --git a/tests/test_b64push_atomic.py b/tests/test_b64push_atomic.pynew file mode 100644index 000000000..8e1eca02d--- /dev/null+++ b/tests/test_b64push_atomic.py@@ -0,0 +1,146 @@+"""Device-free regression checks using isolated transport stubs."""+import hashlib+import json+import os+from pathlib import Path+import shutil+import stat+import subprocess+import sys+import tempfile+import unittest++ROOT = Path(__file__).resolve().parents[1]++# A tools/tv.py whose "TV shell" is /bin/sh on this machine, so b64push.py's real commands run.+FAKE_SHELL_TV = r'''+import json+import os+import subprocess++LOG = os.environ["FAKE_LOG"]+++class Device:+ max_chunk_size = int(os.environ.get("FAKE_MAX", "4096"))++ def shell(self, command, read_timeout_s=None):+ with open(LOG, "a") as f:+ f.write(json.dumps(command) + "\n")+ # Inject transport exceptions after staging exists, to verify cleanup on every failure phase.+ if os.environ.get("FAKE_RAISE") and command.startswith(os.environ["FAKE_RAISE"]):+ raise OSError("simulated transport failure")+ if os.environ.get("FAKE_CORRUPT") and command.startswith("echo '"):+ command = "echo 'QUJD' >>" + command.split(">>", 1)[1]+ return subprocess.run(["/bin/sh", "-c", command], capture_output=True, text=True).stdout++ def close(self):+ pass+++def connect():+ if os.environ.get("FAKE_NO_CONNECT"):+ raise RuntimeError("fake: connect() was called")+ return Device()+'''+++class TempDirTest(unittest.TestCase):+ def setUp(self):+ self.base = Path(tempfile.mkdtemp())+ self.addCleanup(shutil.rmtree, self.base, ignore_errors=True)++[email protected](shutil.which("md5sum") and shutil.which("base64"), "needs md5sum and base64")+class B64PushTest(TempDirTest):+ """M4 (safe replace of the remote file) and L3 (usage) in tools/b64push.py."""++ def setUp(self):+ super().setUp()+ self.tools = self.base / "tools"+ self.tools.mkdir()+ shutil.copy2(ROOT / "tools" / "b64push.py", self.tools / "b64push.py")+ (self.tools / "tv.py").write_text(FAKE_SHELL_TV)+ self.remote_dir = self.base / "remote"+ self.remote_dir.mkdir()+ self.log = self.base / "log.jsonl"++ def push(self, *args, **env):+ full = {k: v for k, v in os.environ.items() if k != "TV_HOST"}+ full.update(FAKE_LOG=str(self.log), **env)+ return subprocess.run([sys.executable, str(self.tools / "b64push.py"), *args], env=full,+ capture_output=True, text=True, timeout=120)++ def commands(self):+ return [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else []++ def local(self, data):+ path = self.base / "local.bin"+ path.write_bytes(data)+ return path++ def test_missing_arguments_print_usage_without_tv_host(self):+ for args in ([], ["only-one"], ["a", "b", "c"]):+ with self.subTest(args=args):+ result = self.push(*args, FAKE_NO_CONNECT="1")+ self.assertEqual(result.returncode, 2, result.stderr)+ self.assertIn("usage", result.stderr.lower())+ self.assertNotIn("Traceback", result.stderr)++ def test_unsafe_remote_path_is_refused_before_connecting(self):+ src = self.local(b"x")+ for remote in ("relative/path", "/data/local/tmp/a b", "/data/local/tmp/$(id)",+ "/data/local/tmp/a;rm -rf /", "/data/local/../tmp/x", "/data/'q'", ""):+ with self.subTest(remote=remote):+ result = self.push(str(src), remote, FAKE_NO_CONNECT="1")+ self.assertEqual(result.returncode, 2, result.stderr)+ self.assertNotIn("connect() was called", result.stderr)+ self.assertEqual(self.commands(), [])++ def test_transfer_replaces_the_target_only_after_the_checksum_matches(self):+ data = os.urandom(10000) # several chunks at a 4096-byte payload+ target = self.remote_dir / "file.apk"+ target.write_bytes(b"old contents")+ result = self.push(str(self.local(data)), str(target))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(target.read_bytes(), data)+ self.assertEqual(sorted(p.name for p in self.remote_dir.iterdir()), ["file.apk"],+ "temporary files are cleaned up")+ first = self.commands()[0]+ self.assertNotIn(f"rm -f '{target}' ", first + " ", "the target must not be deleted up front")+ for command in self.commands():+ self.assertIn(f"'{target}", command, "every remote path is single-quoted")++ def test_failed_checksum_leaves_the_original_intact(self):+ target = self.remote_dir / "file.apk"+ target.write_bytes(b"old contents")+ result = self.push(str(self.local(os.urandom(5000))), str(target), FAKE_CORRUPT="1")+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn("MISMATCH", result.stdout)+ self.assertEqual(target.read_bytes(), b"old contents")+ self.assertEqual(sorted(p.name for p in self.remote_dir.iterdir()), ["file.apk"])++ def test_transport_exceptions_remove_staging_and_keep_original(self):+ for phase in ("echo '", "base64 -d", "mv -f"):+ with self.subTest(phase=phase):+ target = self.remote_dir / "file.apk"+ target.write_bytes(b"old contents")+ result = self.push(str(self.local(b"new contents")), str(target), FAKE_RAISE=phase)+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(target.read_bytes(), b"old contents")+ self.assertEqual(sorted(p.name for p in self.remote_dir.iterdir()), ["file.apk"])++ def test_dot_dot_anywhere_is_refused(self):+ result = self.push(str(self.local(b"x")), str(self.remote_dir / "a..b"), FAKE_NO_CONNECT="1")+ self.assertEqual(result.returncode, 2, result.stderr)+ self.assertNotIn("connect() was called", result.stderr)++ def test_empty_file(self):+ target = self.remote_dir / "empty.txt"+ target.write_bytes(b"not empty yet")+ result = self.push(str(self.local(b"")), str(target))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(target.read_bytes(), b"")+ self.assertIn(hashlib.md5(b"").hexdigest(), result.stdout)+ self.assertEqual(sorted(p.name for p in self.remote_dir.iterdir()), ["empty.txt"])+diff --git a/tools/b64push.py b/tools/b64push.pyindex 02ff01d58..e98ea448e 100644--- a/tools/b64push.py+++ b/tools/b64push.py@@ -2,44 +2,98 @@"""Fallback file transfer: send a file to the TV as base64 chunks through plain shell commands.Usage: b64push.py <local file> <remote path>++The file is assembled under a temporary name next to the target and checked with md5sum; only a+matching copy is moved over the target, so a failed or corrupted transfer leaves the old file alone."""import base64import hashlibimport os+import reimport sys-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-import tv # noqa: E402-CHUNK = 48 * 1024 # raw bytes per shell command (base64 grows it by 4/3); capped per TV in main()# adbd before Android 7 aborts the connection on an ADB "open" payload over 4096 bytes, which# Android 5.x TVs announce as their max data size. Newer adbd takes the full 48 KB.+# The remote path is pasted into the TV's shell: absolute, plain characters, no "..".+REMOTE_RE = re.compile(r"/[A-Za-z0-9._/-]+")+USAGE = "usage: b64push.py <local file> <remote path>\n"+++def safe_remote(path):+ return bool(REMOTE_RE.fullmatch(path)) and ".." not in path and not path.endswith("/")+++def q(path):+ """Single-quoted for the TV's shell. safe_remote() already rules out a quote inside."""+ return "'" + path + "'"+def main():- local, remote = sys.argv[1], sys.argv[2]- data = open(local, "rb").read()+ args = sys.argv[1:]+ if len(args) != 2:+ sys.stderr.write(USAGE)+ return 2+ local, remote = args+ if not safe_remote(remote):+ sys.stderr.write(f"refusing remote path {remote!r}: use an absolute path of letters, digits, "+ "'.', '_', '-' and '/', without '..'\n")+ return 2+ with open(local, "rb") as f:+ data = f.read()want = hashlib.md5(data).hexdigest()++ # Imported only now: tv.py exits at import time when TV_HOST is unset, which would hide the+ # usage message above.+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import tv # noqa: E402+dev = tv.connect()- chunk = min(CHUNK, dev.max_chunk_size * 3 // 4 - 64) # base64 of the chunk plus the echo must fit one payload- chunk -= chunk % 3 # a multiple of 3, or each chunk ends in '=' padding mid-stream and base64 -d corrupts it- tmp = remote + ".b64"- dev.shell(f"rm -f {remote} {tmp}")- n = (len(data) + chunk - 1) // chunk- for i in range(n):- part = base64.b64encode(data[i * chunk:(i + 1) * chunk]).decode()- out = dev.shell(f"echo '{part}' >> {tmp} && echo ok{i}", read_timeout_s=60.0)- if f"ok{i}" not in out:- print(f"chunk {i} failed: {out}")- sys.exit(1)- print(f"\rchunk {i + 1}/{n}", end="", flush=True)- print()- out = dev.shell(f"base64 -d {tmp} > {remote} && rm {tmp} && md5sum {remote}", read_timeout_s=120.0)- got = out.split()[0] if out.strip() else ""- print("md5 remote:", got, "local:", want, "MATCH" if got == want else "MISMATCH")- dev.close()- sys.exit(0 if got == want else 1)+ b64 = remote + ".b64.part"+ part = remote + ".part"+ try:+ chunk = min(CHUNK, dev.max_chunk_size * 3 // 4 - 64) # base64 of the chunk plus the echo must fit one payload+ chunk -= chunk % 3 # a multiple of 3, or each chunk ends in '=' padding mid-stream and base64 -d corrupts it+ # Only our own temporary names are cleared; the target stays until the copy is verified.+ # `: >` creates the base64 file even for an empty upload, so `base64 -d` has an input.+ dev.shell(f"rm -f {q(b64)} {q(part)} && : > {q(b64)}")+ n = (len(data) + chunk - 1) // chunk+ for i in range(n):+ piece = base64.b64encode(data[i * chunk:(i + 1) * chunk]).decode()+ out = dev.shell(f"echo '{piece}' >> {q(b64)} && echo ok{i}", read_timeout_s=60.0)+ if f"ok{i}" not in out:+ print(f"chunk {i} failed: {out}")+ dev.shell(f"rm -f {q(b64)} {q(part)}")+ return 1+ print(f"\rchunk {i + 1}/{n}", end="", flush=True)+ if n:+ print()+ out = dev.shell(f"base64 -d < {q(b64)} > {q(part)} && md5sum {q(part)}; rm -f {q(b64)}",+ read_timeout_s=120.0)+ got = out.split()[0] if out.strip() else ""+ ok = got == want+ print("md5 remote:", got, "local:", want, "MATCH" if ok else "MISMATCH")+ if not ok:+ dev.shell(f"rm -f {q(part)}")+ print(f"{remote} was left as it was.", file=sys.stderr)+ return 1+ out = dev.shell(f"mv -f {q(part)} {q(remote)} && echo moved", read_timeout_s=60.0)+ if "moved" not in out:+ dev.shell(f"rm -f {q(part)}")+ print(f"could not move the verified copy over {remote}: {out.strip()}", file=sys.stderr)+ return 1+ return 0+ finally:+ # Exceptions (including interrupted transfers) must also clear staging. A disconnected TV+ # may refuse cleanup; report that without hiding the original failure or deleting the target.+ try:+ dev.shell(f"rm -f {q(b64)} {q(part)}")+ except Exception as error:+ print(f"could not remove temporary upload files: {error}", file=sys.stderr)+ finally:+ dev.close()if __name__ == "__main__":- main()+ sys.exit(main())