Skip to content

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

tools: relay.py honours TV_PORT and TV_HOST=ip:port

Mazin Kanuga9d77a82c62c2
diff --git a/tests/test_relay.py b/tests/test_relay.py
index 42ff5e1e1..4410540eb 100644
--- a/tests/test_relay.py
+++ b/tests/test_relay.py
@@ -5,6 +5,7 @@ A small echo server on this machine stands in for the TV, so the test needs no T
Run from the repository root: python3 -m unittest discover -s tests -v
"""
from pathlib import Path
+import os
import socket
import subprocess
import sys
@@ -44,10 +45,38 @@ def free_port():
return s.getsockname()[1]
+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
+
+
+HELLO = b"CNXN\x00\x00\x00\x01"
+
+
+def round_trip(port):
+ """Send a few bytes through the relay on PORT and return what comes back."""
+ with socket.create_connection(("127.0.0.1", port), timeout=10) as c:
+ c.settimeout(15)
+ c.sendall(HELLO)
+ got = b""
+ while len(got) < len(HELLO):
+ chunk = c.recv(65536)
+ if not chunk:
+ break
+ got += chunk
+ return got
+
+
class RelayTest(unittest.TestCase):
def start_relay(self, tv_port, *extra):
- proc = subprocess.Popen([sys.executable, str(ROOT / "tools" / "relay.py"), "127.0.0.1",
- "--tv-port", str(tv_port), "--port", "0", *extra],
+ proc, port, _ = self.launch("127.0.0.1", "--tv-port", str(tv_port), "--port", "0", *extra)
+ return proc, port
+
+ def launch(self, *args, env=None):
+ """Start the relay with ARGS; return it, its local port and the line that names where it forwards to."""
+ proc = subprocess.Popen([sys.executable, str(ROOT / "tools" / "relay.py"), *args], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Cleanups run last-in first-out: kill, wait, then close the pipes.
self.addCleanup(proc.stderr.close)
@@ -60,7 +89,7 @@ class RelayTest(unittest.TestCase):
self.fail(first + proc.stderr.read())
port = int(first.split()[1].split(":")[1])
self.assertIn(f"TV_HOST=127.0.0.1 TV_PORT={port}", proc.stdout.readline())
- return proc, port
+ return proc, port, first
def test_bytes_go_both_ways(self):
tv = echo_server()
@@ -118,6 +147,68 @@ class RelayTest(unittest.TestCase):
self.assertEqual(result.returncode, 2)
self.assertIn("the relay itself", result.stderr)
+ # The TV's port comes from where tv.py and adb-closed.py take it (#997): an explicit --tv-port, else a
+ # port in the address, else TV_PORT, else 5555. The relay used to ignore the address and TV_PORT, so a
+ # TV whose adbd has a port of its own (5877 on the Wanbo T6R Max) was relayed to 5555.
+ def stand_in_tv(self):
+ tv = echo_server()
+ self.addCleanup(tv.close)
+ return tv.getsockname()[1]
+
+ def assert_reaches(self, tv_port, *args, env):
+ _, port, first = self.launch(*args, "--port", "0", env=env)
+ self.assertIn(f"-> 127.0.0.1:{tv_port}\n", first)
+ self.assertEqual(round_trip(port), HELLO)
+
+ def test_tv_port_from_the_environment_is_used(self):
+ tv_port = self.stand_in_tv()
+ self.assert_reaches(tv_port, env=env_with(TV_HOST="127.0.0.1", TV_PORT=str(tv_port)))
+
+ def test_a_port_in_tv_host_is_used_ahead_of_tv_port(self):
+ tv_port = self.stand_in_tv()
+ self.assert_reaches(tv_port, env=env_with(TV_HOST=f"127.0.0.1:{tv_port}", TV_PORT=str(free_port())))
+
+ def test_a_port_in_the_address_argument_is_used(self):
+ tv_port = self.stand_in_tv()
+ self.assert_reaches(tv_port, f"127.0.0.1:{tv_port}", env=env_with(TV_PORT=str(free_port())))
+
+ def test_an_explicit_tv_port_wins(self):
+ tv_port = self.stand_in_tv()
+ env = env_with(TV_HOST=f"127.0.0.1:{free_port()}", TV_PORT=str(free_port()))
+ self.assert_reaches(tv_port, "--tv-port", str(tv_port), env=env)
+
+ def test_the_tools_own_settings_are_refused(self):
+ # The TV_HOST/TV_PORT exported for the tools, and then the relay started in that same terminal. With the
+ # TV's IP given too, that TV_PORT would send the relay to the TV's IP on a relay's port (15555).
+ tools = env_with(TV_HOST="127.0.0.1", TV_PORT="15555")
+ for args, env, said in (([], tools, "TV_PORT=15555 is a relay's port"),
+ (["192.0.2.1"], tools, "TV_PORT=15555 is a relay's port"),
+ (["192.0.2.1", "--port", "15556"], tools, "TV_PORT=15555 is a relay's port"),
+ (["192.0.2.1", "--port", "15556"], env_with(TV_PORT="15556"),
+ "TV_PORT=15556 is a relay's port"),
+ ([], env_with(TV_HOST="127.0.0.1:15555"), "the relay itself")):
+ with self.subTest(args=args, TV_HOST=env.get("TV_HOST"), TV_PORT=env.get("TV_PORT")):
+ result = subprocess.run([sys.executable, str(ROOT / "tools" / "relay.py"), *args], env=env,
+ capture_output=True, text=True, timeout=30)
+ self.assertEqual(result.returncode, 2, result.stderr)
+ self.assertIn(said, result.stderr)
+ self.assertEqual(result.stdout, "")
+
+ def test_tv_port_still_applies_to_the_tvs_ip_given(self):
+ # A TV_PORT that is not a relay's is the TV's, as for tv.py: TV_PORT=5877 relay.py <tv ip>.
+ tv_port = self.stand_in_tv()
+ self.assert_reaches(tv_port, "127.0.0.1", env=env_with(TV_PORT=str(tv_port)))
+
+ def test_a_port_that_is_not_a_number_is_refused(self):
+ for args, env in ((["127.0.0.1:55a5"], env_with()), (["127.0.0.1:70000"], env_with()),
+ ([], env_with(TV_HOST="127.0.0.1", TV_PORT="x"))):
+ with self.subTest(args=args, TV_PORT=env.get("TV_PORT")):
+ result = subprocess.run([sys.executable, str(ROOT / "tools" / "relay.py"), *args, "--port", "0"],
+ env=env, capture_output=True, text=True, timeout=30)
+ self.assertEqual(result.returncode, 2, result.stderr)
+ self.assertIn("not a port number", result.stderr)
+ self.assertEqual(result.stdout, "")
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/relay.md b/tools/relay.md
index 2f13a5856..4c95e1fb0 100644
--- a/tools/relay.md
+++ b/tools/relay.md
@@ -14,8 +14,9 @@ export TV_HOST=127.0.0.1 TV_PORT=15555
tools/venv/bin/python -I tools/tv.py --probe
```
-- **Options:** `--tv-port` if the TV's ADB port isn't 5555; `--port` for another local port (run one relay
- per TV, each on its own port). The TV's address defaults to `$TV_HOST`.
+- **Options:** `--tv-port` if the TV's ADB port isn't 5555, or give it with the address (`192.168.1.50:5877`);
+ `--port` for another local port (run one relay per TV, each on its own port). The TV's address defaults to
+ `$TV_HOST` and its port to `$TV_PORT`, as for `tools/tv.py`.
- **It prints the `TV_HOST`/`TV_PORT` to use**, and one line each time it can't reach the TV.
- **Stop it with Ctrl-C** when you're done.
@@ -31,8 +32,12 @@ tools/venv/bin/python -I tools/tv.py --probe
- **"cannot reach 192.168.1.50:5555"**, printed by the relay: the TV is off or in standby (some TVs drop off
the network), on another network, or network debugging was switched off. The tools then see the connection
- reset by peer.
+ reset by peer. If the port it names isn't the TV's, it came from a `TV_PORT` exported in this terminal: run
+ `unset TV_PORT`, or give the TV's port with the address (`192.168.1.50:5555`).
- **"cannot listen on 127.0.0.1:15555"**: a relay is already running on that port. Use it, or pick another
`--port`.
-- **"that is the relay itself"**: the TV's address was given as `127.0.0.1` with the relay's own port. Give
- the TV's IP address.
+- **"TV_PORT=15555 is a relay's port"**: the tools' `TV_HOST`/`TV_PORT` are exported in this terminal, so
+ the relay would forward to the TV's IP on a relay's port. Run `unset TV_HOST TV_PORT`, then give the TV's IP
+ address, or give the TV's port with the address (`192.168.1.50:5555`).
+- **"that is the relay itself"**: the TV's address was given as `127.0.0.1` with the relay's own port, perhaps
+ from a `TV_HOST=127.0.0.1:15555` exported for the tools in this terminal. Give the TV's IP address.
diff --git a/tools/relay.py b/tools/relay.py
index ae938a137..e658be8e5 100644
--- a/tools/relay.py
+++ b/tools/relay.py
@@ -8,7 +8,8 @@ terminal, then point the tools at it:
tools/venv/bin/python -I tools/relay.py 192.168.1.50 # leave it running
TV_HOST=127.0.0.1 TV_PORT=15555 tools/venv/bin/python -I tools/tv.py --probe
-Usage: relay.py [TV_HOST] [--tv-port 5555] [--port 15555]
+Usage: relay.py [TV_HOST[:PORT]] [--tv-port 5555] [--port 15555]
+The TV's port is --tv-port, else the one in the address, else TV_PORT, else 5555.
It listens on 127.0.0.1 only, never on the network. Read tools/relay.md first.
"""
import argparse
@@ -20,6 +21,22 @@ import threading
LISTEN = "127.0.0.1" # loopback only: the relay must never put the TV's ADB port on the network
+def split_host_port(endpoint):
+ """Split host:port or [ipv6]:port into (host, port_or_none)."""
+ if endpoint.startswith("["):
+ end = endpoint.find("]")
+ if end != -1:
+ host = endpoint[1:end]
+ rest = endpoint[end + 1:]
+ if rest.startswith(":"):
+ return host, rest[1:]
+ return host, None
+ elif endpoint.count(":") == 1:
+ host, port = endpoint.split(":", 1)
+ return host, port
+ return endpoint, None
+
+
def pipe(src, dst):
"""Copy one direction until either side closes, then close both directions."""
try:
@@ -56,13 +73,34 @@ def serve(srv, tv_host, tv_port):
def main():
p = argparse.ArgumentParser(description="Forward 127.0.0.1:PORT to the TV's ADB port. See tools/relay.md.")
p.add_argument("tv_host", nargs="?", default=os.environ.get("TV_HOST"),
- help="the TV's IP address (default: $TV_HOST)")
- p.add_argument("--tv-port", type=int, default=5555, help="the TV's ADB port (default 5555)")
+ help="the TV's IP address, or IP:port (default: $TV_HOST)")
+ p.add_argument("--tv-port", type=int,
+ help="the TV's ADB port (default: the port in the address, else $TV_PORT, else 5555)")
p.add_argument("--port", type=int, default=15555, help="local port to listen on (default 15555; 0 picks one)")
args = p.parse_args()
if not args.tv_host:
p.error("give the TV's IP address, e.g. tools/relay.py 192.168.1.50")
- if args.tv_host in ("127.0.0.1", "localhost") and args.tv_port == args.port:
+ # The same order as tv.py and adb-closed.py (#997). With 5555 fixed, a TV whose adbd has a port of its
+ # own (5877 on the Wanbo T6R Max) was relayed to 5555 whatever TV_HOST and TV_PORT said.
+ args.tv_host, endpoint_port = split_host_port(args.tv_host)
+ port_from_env = args.tv_port is None and not endpoint_port and bool(os.environ.get("TV_PORT"))
+ if args.tv_port is None:
+ port_str = endpoint_port or os.environ.get("TV_PORT") or "5555"
+ try:
+ args.tv_port = int(port_str)
+ if not (1 <= args.tv_port <= 65535):
+ raise ValueError
+ except ValueError:
+ p.error(f"not a port number: {port_str!r}")
+ # TV_HOST=127.0.0.1 TV_PORT=15555 exported for the tools, then the relay started in that same terminal: that
+ # TV_PORT is a relay's (this one's, or the one TV_HOST points at), not the TV's, and with the TV's IP given
+ # the relay would forward to IP:15555.
+ loopback = ("127.0.0.1", "localhost")
+ env_host = split_host_port(os.environ.get("TV_HOST", ""))[0]
+ if port_from_env and (args.tv_port == args.port or (env_host in loopback and args.tv_host not in loopback)):
+ p.error(f"TV_PORT={args.tv_port} is a relay's port, set for the tools: unset TV_HOST TV_PORT in this "
+ "terminal, or give the TV's port, e.g. tools/relay.py 192.168.1.50:5555")
+ if args.tv_host in loopback and args.tv_port == args.port:
p.error("that is the relay itself: give the TV's IP address")
srv = socket.socket()