Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: adb-closed.py names an address that is a URL or a path instead of asking it

xbshengbb6d0bf9ccfe
diff --git a/tests/test_adb_closed_address_words.py b/tests/test_adb_closed_address_words.py
new file mode 100644
index 000000000..867db7d8a
--- /dev/null
+++ b/tests/test_adb_closed_address_words.py
@@ -0,0 +1,171 @@
+"""tools/adb-closed.py names a first word that is a URL or a path, instead of asking it.
+
+The closing step in PROMPT.md, AGENTS.md and the README FAQ runs `tools/adb-closed.py <tv ip> [port]`,
+and an address pasted from a browser (or a page opened at it) reached the socket, where the answer was
+about something else:
+
+ * `http://<tv ip>` split into the host "http" and the port "//<tv ip>", and the run answered
+ "not a port number: '//<tv ip>'" - a sentence about a port fragment for a word that is a URL.
+ * `http://<tv ip>:5555` became a host literally named for the URL, and the lookup failed into
+ "could not check http://<tv ip>:5555:5555 (...). Is the TV on and on this network?" - a question
+ about the TV's power, for an argument this check cannot use.
+ * `<tv ip>:5555/` and `<tv ip>/6/system` read the same way ("not a port number: '5555/'", and the
+ "Is the TV on" question for the path).
+
+The status was already 2 in all four, so only the words were wrong; the word is named before the socket
+now. Left alone on purpose: the second word still wins over a port in the address (`<tv ip>:5877 5555`
+asks 5555), the command line the tool documents and tests/test_adb_closed.py pins with
+test_cli_port_overrides_endpoint_port.
+
+The TV cases run the script under a stand-in for socket.create_connection, so they reach no network: it
+refuses, takes or never answers by port, and notes every connection it is asked for - the note is how a
+test says nothing was asked.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+"""
+import importlib.util
+import os
+from pathlib import Path
+import subprocess
+import sys
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPT = ROOT / "tools" / "adb-closed.py"
+TV = "192.0.2.1" # a documentation address: the stand-in answers for it, nothing on the network does
+
+# Replaces socket.create_connection, then runs the script as `python3 tools/adb-closed.py ...` would.
+# STAND_IN_TV maps a port to how the TV answers it: refused, open, or silent (nothing within the timeout).
+STAND_IN = r"""
+import os, runpy, socket, sys
+answers = dict(item.split("=") for item in os.environ["STAND_IN_TV"].split(","))
+def stand_in(address, timeout=None, *args, **kwargs):
+ sys.stderr.write("[stand-in] connect %s:%s\n" % address)
+ answer = answers.get(str(address[1]), "refused")
+ if answer == "silent":
+ raise socket.timeout("timed out")
+ if answer == "refused":
+ raise ConnectionRefusedError(61, "Connection refused")
+ return socket.socket()
+socket.create_connection = stand_in
+sys.argv = sys.argv[1:]
+runpy.run_path(sys.argv[0], run_name="__main__")
+"""
+
+
+def env_with(**values):
+ """This environment without the shell's own TV_HOST/TV_PORT, plus the given ones."""
+ env = {k: v for k, v in os.environ.items() if k not in ("TV_HOST", "TV_PORT")}
+ env.update(values)
+ return env
+
+
+def check_tv(*args, tv, env=None):
+ """The script against the stand-in TV: tv is "5555=open,15555=refused" and the like."""
+ env = dict(env if env is not None else env_with())
+ env["STAND_IN_TV"] = tv
+ return subprocess.run([sys.executable, "-I", "-c", STAND_IN, str(SCRIPT), *args],
+ capture_output=True, text=True, timeout=30, env=env)
+
+
+def asked(result):
+ """The connections the run made, from the stand-in's own notes."""
+ return [line for line in result.stderr.splitlines() if line.startswith("[stand-in] connect")]
+
+
+def address_problem_module():
+ """The script imported as a module, for address_problem() itself."""
+ spec = importlib.util.spec_from_file_location("adb_closed_under_test", SCRIPT)
+ assert spec is not None and spec.loader is not None, f"{SCRIPT} cannot be loaded"
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class AnAddressThatIsNotOneTest(unittest.TestCase):
+ def test_a_url_with_a_port_is_named_and_nothing_is_asked(self):
+ # Before: the host was the whole URL, so the lookup failed and the answer asked whether the TV
+ # was on - about a word that names no host at all.
+ result = check_tv(f"http://{TV}:5555", tv="5555=refused")
+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
+ self.assertEqual("", result.stdout)
+ self.assertEqual([], asked(result))
+ self.assertIn("that is a URL, not the TV's address", result.stderr)
+ self.assertNotIn("Is the TV on", result.stderr)
+
+ def test_a_url_without_a_port_is_named_as_a_url(self):
+ result = check_tv(f"http://{TV}", tv="5555=refused")
+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
+ self.assertIn("that is a URL, not the TV's address", result.stderr)
+ self.assertNotIn("not a port number", result.stderr)
+ self.assertNotIn("Is the TV on", result.stderr)
+ self.assertEqual([], asked(result))
+
+ def test_a_tv_host_that_is_a_url_is_named_too(self):
+ # The address comes from TV_HOST as often as from the command line (tools/relay.md).
+ result = check_tv(tv="5555=refused", env=env_with(TV_HOST=f"https://{TV}"))
+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
+ self.assertIn("that is a URL, not the TV's address", result.stderr)
+ self.assertEqual([], asked(result))
+
+ def test_a_page_at_the_address_is_named_as_a_path(self):
+ result = check_tv(f"{TV}:5555/", tv="5555=refused")
+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
+ self.assertIn("that is a path, not the TV's address", result.stderr)
+ self.assertNotIn("not a port number", result.stderr)
+ self.assertEqual([], asked(result))
+
+ def test_a_page_at_the_bare_address_is_named_as_a_path(self):
+ result = check_tv(f"{TV}/6/system", tv="5555=refused")
+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
+ self.assertIn("that is a path, not the TV's address", result.stderr)
+ self.assertNotIn("Is the TV on", result.stderr)
+ self.assertEqual([], asked(result))
+
+ def test_an_ipv6_address_still_is_one(self):
+ # The control: a bracketed address with a port is an address, and is asked as one.
+ result = check_tv("[2001:db8::1]:5877", tv="5877=refused")
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertEqual(["[stand-in] connect 2001:db8::1:5877"], asked(result))
+ # The sentence writes the host and port it asked, as every other line of the script does.
+ self.assertEqual("2001:db8::1:5877 is closed: the TV refused the connection.\n", result.stdout)
+
+ def test_the_reader_names_the_url_and_the_path_and_leaves_addresses_alone(self):
+ module = address_problem_module()
+ self.assertIn("URL", module.address_problem(f"http://{TV}"))
+ self.assertIn("URL", module.address_problem(f"https://{TV}:5555"))
+ # A page opened at the TV's address is a path, not a URL, and is named as the one it is.
+ self.assertIn("path", module.address_problem(f"{TV}/6/system"))
+ self.assertIn("path", module.address_problem(f"{TV}:5555/x"))
+ for word in (TV, f"{TV}:5555", "[2001:db8::1]", "[2001:db8::1]:5555", "localhost",
+ "tv.local", "tv.local:5877"):
+ with self.subTest(word=word):
+ self.assertIsNone(module.address_problem(word),
+ f"{word} is an address this check takes and was refused")
+
+
+class TheCommandLineItAlreadyTookTest(unittest.TestCase):
+ """What this change must not move: the address and port forms the tool documents still work."""
+
+ def test_an_address_with_its_port_still_checks_that_port(self):
+ result = check_tv(f"{TV}:5555", tv="5555=refused")
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertEqual([f"[stand-in] connect {TV}:5555"], asked(result))
+ self.assertEqual(f"{TV}:5555 is closed: the TV refused the connection.\n", result.stdout)
+
+ def test_a_second_word_still_wins_over_a_port_in_the_address(self):
+ # The documented command line (tests/test_adb_closed.py's
+ # test_cli_port_overrides_endpoint_port): `:5877` in the address and 5555 after it asks 5555.
+ result = check_tv(f"{TV}:5877", "5555", tv="5877=open,5555=refused")
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertEqual([f"[stand-in] connect {TV}:5555"], asked(result))
+
+ def test_a_second_word_that_is_not_a_port_keeps_its_own_message(self):
+ result = check_tv(f"{TV}:5555", "abc", tv="5555=refused")
+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
+ self.assertIn("not a port number: 'abc'", result.stderr)
+ self.assertEqual([], asked(result))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/adb-closed.py b/tools/adb-closed.py
index 0507f2106..d0ed7648f 100755
--- a/tools/adb-closed.py
+++ b/tools/adb-closed.py
@@ -6,7 +6,8 @@
Exits 0 when the TV refuses the connection, 1 when the port is still open, and 2 when the check
could not tell: nothing answered (the TV off, asleep or rebooting, at another address, or out of reach
from here), nothing listened on 127.0.0.1, or the check itself could not run (a name that does not
-resolve or is not a hostname, no route to the TV). Only the TV's own refusal shows the port closed.
+resolve or is not a hostname, no route to the TV, an address that is a URL or a path rather than an
+IP). Only the TV's own refusal shows the port closed.
On macOS a "No route to host" (`EHOSTUNREACH`) is also what Local Network privacy looks like: the
permission belongs to the app that runs this check, not to python or adb, so a terminal that was never
@@ -68,6 +69,27 @@ def split_host_port(endpoint):
return endpoint, None
+def address_problem(word):
+ """Why this first word cannot be the TV's address, or None.
+
+ A URL pasted from a browser was read as an address: `http://<tv ip>` split into the host "http" and
+ the port "//<tv ip>", which answered "not a port number: '//<tv ip>'" - a sentence about a port
+ fragment for a word that is an address of another kind - and `http://<tv ip>:5555` became a host
+ literally named "http://<tv ip>:5555", whose lookup failed into the OSError branch's question about
+ whether the TV is on, for a word this check cannot use. A page at the address (`<tv ip>:5555/`,
+ `<tv ip>/6/system`) read the same way. All of them exit 2 already; naming the word is what tells the
+ owner which of the two to fix.
+ """
+ word = word.strip()
+ if "://" in word:
+ return ("that is a URL, not the TV's address: this check asks the TV's own ADB port, so give the "
+ "IP (or IP:port) alone, e.g. tools/adb-closed.py <tv ip>")
+ if "/" in word:
+ return ("that is a path, not the TV's address: give the IP (or IP:port) alone, without a / or the "
+ "page it opens, e.g. tools/adb-closed.py <tv ip>")
+ return None
+
+
def main():
args = sys.argv[1:]
if len(args) > 2 or args[:1] in (["-h"], ["--help"]):
@@ -77,6 +99,10 @@ def main():
if not raw_host:
sys.stderr.write("usage: adb-closed.py <tv ip> [port]\n")
return 2
+ problem = address_problem(raw_host)
+ if problem:
+ sys.stderr.write(problem + "\n")
+ return 2
host, endpoint_port = split_host_port(raw_host)
port_from_env = False
if len(args) == 2: