From 2e0e501ca5e6c18b3bcd6410e0908510ba25e089 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 11:59:46 +0200 Subject: [PATCH 01/10] test(routable): add transit-chain topology + failing routable-prefix tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds an isolated 4-node chain topology (leaf → natlit → natlde → far) to exercise the planned ROUTABLE_PREFIXES feature. TG 26305 is owned by `far` (prefix 263) which is unreachable from `leaf` without transit; test_01 asserts forward + return audio delivery and fails until the C++ feature lands. test_02 asserts that BLACKLIST_TGS=26307 on leaf's uplink vetoes that specific TG while leaving 26305 unaffected. Files added/modified: tests/topology.py — ROUTABLE_REFLECTORS dict + port/secret helpers tests/generate_configs.py — generate_routable_reflector_conf/docker_compose + ROUTABLE_PREFIXES/BLACKLIST_TGS emission in per-peer trunk loop; routable in default run tests/test_routable.py — new test file (mirrors test_twin.py pattern) tests/docker-compose.routable.yml — generated chain compose (4 services) --- tests/docker-compose.routable.yml | 90 +++++++++ tests/generate_configs.py | 143 ++++++++++++++ tests/test_routable.py | 307 ++++++++++++++++++++++++++++++ tests/topology.py | 49 +++++ 4 files changed, 589 insertions(+) create mode 100644 tests/docker-compose.routable.yml create mode 100644 tests/test_routable.py diff --git a/tests/docker-compose.routable.yml b/tests/docker-compose.routable.yml new file mode 100644 index 0000000..084133c --- /dev/null +++ b/tests/docker-compose.routable.yml @@ -0,0 +1,90 @@ +services: + reflector-far: + build: + context: .. + dockerfile: Dockerfile + volumes: + - ./configs/reflector-far.conf:/etc/svxlink/svxreflector.conf:ro + - pki-routable-far:/var/lib/svxlink/pki + ports: + - "54300:5300/tcp" + - "54300:5300/udp" + - "54302:5302/tcp" + - "57080:8080/tcp" + healthcheck: + test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/8080) 2>/dev/null'"] + interval: 2s + timeout: 2s + retries: 15 + networks: + - routable_mesh + + reflector-leaf: + build: + context: .. + dockerfile: Dockerfile + volumes: + - ./configs/reflector-leaf.conf:/etc/svxlink/svxreflector.conf:ro + - pki-routable-leaf:/var/lib/svxlink/pki + ports: + - "51300:5300/tcp" + - "51300:5300/udp" + - "51302:5302/tcp" + - "54080:8080/tcp" + healthcheck: + test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/8080) 2>/dev/null'"] + interval: 2s + timeout: 2s + retries: 15 + networks: + - routable_mesh + + reflector-natlde: + build: + context: .. + dockerfile: Dockerfile + volumes: + - ./configs/reflector-natlde.conf:/etc/svxlink/svxreflector.conf:ro + - pki-routable-natlde:/var/lib/svxlink/pki + ports: + - "53300:5300/tcp" + - "53300:5300/udp" + - "53302:5302/tcp" + - "56080:8080/tcp" + healthcheck: + test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/8080) 2>/dev/null'"] + interval: 2s + timeout: 2s + retries: 15 + networks: + - routable_mesh + + reflector-natlit: + build: + context: .. + dockerfile: Dockerfile + volumes: + - ./configs/reflector-natlit.conf:/etc/svxlink/svxreflector.conf:ro + - pki-routable-natlit:/var/lib/svxlink/pki + ports: + - "52300:5300/tcp" + - "52300:5300/udp" + - "52302:5302/tcp" + - "55080:8080/tcp" + healthcheck: + test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/8080) 2>/dev/null'"] + interval: 2s + timeout: 2s + retries: 15 + networks: + - routable_mesh + +volumes: + pki-routable-far: + pki-routable-leaf: + pki-routable-natlde: + pki-routable-natlit: + +networks: + routable_mesh: + driver: bridge diff --git a/tests/generate_configs.py b/tests/generate_configs.py index aa5957e..015254b 100644 --- a/tests/generate_configs.py +++ b/tests/generate_configs.py @@ -64,6 +64,12 @@ def generate_reflector_conf(name: str) -> str: f"SECRET={secret}", f"REMOTE_PREFIX={T.prefix_str(peer['prefix'])}", ] + routable = r.get("routable", {}).get(peer_name) + if routable: + lines.append(f"ROUTABLE_PREFIXES={','.join(routable)}") + blacklist = r.get("blacklist", {}).get(peer_name) + if blacklist: + lines.append(f"BLACKLIST_TGS={blacklist}") # Test harness trunk sections lines += [ @@ -546,6 +552,111 @@ networks: """ +def generate_routable_reflector_conf(name: str) -> str: + """Generate svxreflector.conf for one reflector in the ROUTABLE chain topology.""" + r = T.ROUTABLE_REFLECTORS[name] + + lines = [ + "[GLOBAL]", + 'TIMESTAMP_FORMAT="%c"', + f"LISTEN_PORT={T.INTERNAL_CLIENT_PORT}", + "TG_FOR_V1_CLIENTS=999", + f"LOCAL_PREFIX={T.prefix_str(r['prefix'])}", + f"TRUNK_LISTEN_PORT={T.INTERNAL_TRUNK_PORT}", + f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}", + "COMMAND_PTY=/dev/shm/reflector_ctrl", + "TRUNK_DEBUG=1", + "", + "[SERVER_CERT]", + f"COMMON_NAME={T.service_name(name)}", + "", + "[USERS]", + ] + groups_seen = set() + for client in T.TEST_CLIENTS: + lines.append(f"{client['callsign']}={client['group']}") + groups_seen.add(client['group']) + lines += [ + "", + "[PASSWORDS]", + ] + for client in T.TEST_CLIENTS: + if client['group'] in groups_seen: + lines.append(f"{client['group']}={client['password']}") + groups_seen.discard(client['group']) + + # Trunk sections for each peer in the routable chain + for peer_name in sorted(r.get("peers", [])): + peer = T.ROUTABLE_REFLECTORS[peer_name] + section = T.trunk_section_name(name, peer_name) + secret = T.routable_trunk_secret(name, peer_name) + lines += [ + "", + f"[{section}]", + f"HOST={T.service_name(peer_name)}", + f"PORT={T.INTERNAL_TRUNK_PORT}", + f"SECRET={secret}", + f"REMOTE_PREFIX={T.prefix_str(peer['prefix'])}", + ] + routable = r.get("routable", {}).get(peer_name) + if routable: + lines.append(f"ROUTABLE_PREFIXES={','.join(routable)}") + blacklist = r.get("blacklist", {}).get(peer_name) + if blacklist: + lines.append(f"BLACKLIST_TGS={blacklist}") + + lines.append("") + return "\n".join(lines) + + +def generate_routable_docker_compose() -> str: + """Generate docker-compose.routable.yml for the routable chain topology.""" + services = [] + volumes = [] + + for name in sorted(T.ROUTABLE_REFLECTORS): + svc = T.service_name(name) + client_port = T.routable_mapped_client_port(name) + trunk_port = T.routable_mapped_trunk_port(name) + http_port = T.routable_mapped_http_port(name) + vol = f"pki-routable-{name}" + volumes.append(vol) + + services.append(f""" {svc}: + build: + context: .. + dockerfile: Dockerfile + volumes: + - ./configs/{svc}.conf:/etc/svxlink/svxreflector.conf:ro + - {vol}:/var/lib/svxlink/pki + ports: + - "{client_port}:{T.INTERNAL_CLIENT_PORT}/tcp" + - "{client_port}:{T.INTERNAL_CLIENT_PORT}/udp" + - "{trunk_port}:{T.INTERNAL_TRUNK_PORT}/tcp" + - "{http_port}:{T.INTERNAL_HTTP_PORT}/tcp" + healthcheck: + test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/{T.INTERNAL_HTTP_PORT}) 2>/dev/null'"] + interval: 2s + timeout: 2s + retries: 15 + networks: + - routable_mesh""") + + services_block = "\n\n".join(services) + volumes_block = "\n".join(f" {v}:" for v in volumes) + + return f"""services: +{services_block} + +volumes: +{volumes_block} + +networks: + routable_mesh: + driver: bridge +""" + + def main(): # Topology selection: --topology twin or TOPOLOGY=twin env var topology = os.environ.get("TOPOLOGY", "default") @@ -574,6 +685,23 @@ def main(): f.write(generate_twin_docker_compose()) print(f" wrote docker-compose.test.yml") + elif topology == "routable": + configs_dir = os.path.join(script_dir, "configs") + os.makedirs(configs_dir, exist_ok=True) + + print("Generating ROUTABLE topology configs...") + for name in sorted(T.ROUTABLE_REFLECTORS): + path = os.path.join(configs_dir, f"{T.service_name(name)}.conf") + content = generate_routable_reflector_conf(name) + with open(path, "w") as f: + f.write(content) + print(f" wrote {os.path.relpath(path, script_dir)}") + + compose_path = os.path.join(script_dir, "docker-compose.routable.yml") + with open(compose_path, "w") as f: + f.write(generate_routable_docker_compose()) + print(f" wrote docker-compose.routable.yml") + else: configs_dir = os.path.join(script_dir, "configs") os.makedirs(configs_dir, exist_ok=True) @@ -599,6 +727,21 @@ def main(): f.write(generate_docker_compose()) print(f" wrote docker-compose.test.yml") + # Always regenerate the routable chain topology (separate compose file, + # no conflict with the default mesh). + print("Generating ROUTABLE topology configs...") + for name in sorted(T.ROUTABLE_REFLECTORS): + path = os.path.join(configs_dir, f"{T.service_name(name)}.conf") + content = generate_routable_reflector_conf(name) + with open(path, "w") as f: + f.write(content) + print(f" wrote {os.path.relpath(path, script_dir)}") + + routable_compose_path = os.path.join(script_dir, "docker-compose.routable.yml") + with open(routable_compose_path, "w") as f: + f.write(generate_routable_docker_compose()) + print(f" wrote docker-compose.routable.yml") + if __name__ == "__main__": main() diff --git a/tests/test_routable.py b/tests/test_routable.py new file mode 100644 index 0000000..90ed8cd --- /dev/null +++ b/tests/test_routable.py @@ -0,0 +1,307 @@ +#!/usr/bin/env python3 +"""Integration tests for GeuReflector routable-prefix transit feature. + +Verifies that ROUTABLE_PREFIXES config allows a reflector to forward audio +toward a peer it does not own, enabling multi-hop transit across a chain. + +Topology used: ROUTABLE (generate_configs.py --topology routable) + - reflector-leaf (LOCAL_PREFIX=222100) — leaf uplink, ROUTABLE_PREFIXES=* toward natlit + - reflector-natlit (LOCAL_PREFIX=222) — national Italy, ROUTABLE_PREFIXES=263 toward natlde + - reflector-natlde (LOCAL_PREFIX=262) — national DE, ROUTABLE_PREFIXES=263 toward far + - reflector-far (LOCAL_PREFIX=263) — far peer that owns TG 263xx + +Chain: leaf --TRUNK_LEAF_NATLIT--> natlit --TRUNK_NATLDE_NATLIT--> natlde --TRUNK_FAR_NATLDE--> far + +Without ROUTABLE_PREFIXES the 263xx TG is unreachable from leaf (263 is not +owned by any hop until far). These tests assert the forward + return audio +paths once the feature is implemented. + +test_01 uses TG 26305 (flows normally — no blacklist match). +test_02 uses TG 26307 (blacklisted on leaf's uplink — far must hear nothing). + +Requires: Python 3.7+, stdlib only (+ topology.py from this directory). +Docker must be running and the ROUTABLE topology must have been generated: + cd tests && python3 generate_configs.py --topology routable + docker compose -f docker-compose.routable.yml up -d --build --wait +""" + +import os +import sys +import time +import unittest +from urllib.request import urlopen +from urllib.error import URLError +import json + +# Reuse the V2 mock client and wire helpers from test_trunk.py +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from test_trunk import ( # noqa: E402 + ClientPeer, UDP_AUDIO, UDP_FLUSH, + CLIENT_CALLSIGN, CLIENT_PASSWORD, + CLIENT2_CALLSIGN, CLIENT2_PASSWORD, +) + +# Ensure tests/ is on the path so topology can be imported +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import topology as T + +# --------------------------------------------------------------------------- +# Derived endpoints (routable topology) +# --------------------------------------------------------------------------- + +HOST = "127.0.0.1" + +ROUTABLE_NAMES = sorted(T.ROUTABLE_REFLECTORS) + +COMPOSE_FILE = "docker-compose.routable.yml" +TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) + + +def _http(name: str): + return (HOST, T.routable_mapped_http_port(name)) + + +def _client_port(name: str) -> int: + return T.routable_mapped_client_port(name) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def get_status(host: str, port: int, timeout: float = 3.0) -> dict: + url = f"http://{host}:{port}/status" + with urlopen(url, timeout=timeout) as resp: + return json.loads(resp.read()) + + +def wait_until(predicate, timeout: float = 15.0, interval: float = 0.5, + msg: str = "condition not met"): + """Poll predicate() until it returns True or timeout expires.""" + deadline = time.monotonic() + timeout + last_exc = None + while time.monotonic() < deadline: + try: + if predicate(): + return + except Exception as e: + last_exc = e + time.sleep(interval) + detail = f" (last error: {last_exc})" if last_exc else "" + raise AssertionError(f"Timed out: {msg}{detail}") + + +def wait_for_reflector(host: str, port: int, timeout: float = 90.0): + """Wait until the reflector's /status endpoint responds.""" + def check(): + try: + get_status(host, port, timeout=2.0) + return True + except (URLError, OSError, json.JSONDecodeError): + return False + wait_until(check, timeout=timeout, interval=1.0, + msg=f"reflector at {host}:{port} not ready") + + +def wait_for_trunk_connected(host: str, port: int, trunk_section: str, + timeout: float = 30.0): + """Wait until a specific trunk section shows connected=True in /status.""" + def check(): + status = get_status(host, port) + return status.get("trunks", {}).get(trunk_section, {}).get("connected", False) + wait_until(check, timeout=timeout, + msg=f"trunk {trunk_section} on {host}:{port} not connected") + + +# --------------------------------------------------------------------------- +# Test class +# --------------------------------------------------------------------------- + +class TestRoutableIntegration(unittest.TestCase): + """Integration tests for the ROUTABLE_PREFIXES transit feature.""" + + @classmethod + def setUpClass(cls): + """Wait for all ROUTABLE reflectors to be healthy and mesh to stabilise.""" + D = "\033[2m" + G = "\033[32m" + RST = "\033[0m" + + sys.stderr.write(f" {D}waiting for routable reflectors...{RST}") + sys.stderr.flush() + for name in ROUTABLE_NAMES: + wait_for_reflector(*_http(name), timeout=90.0) + sys.stderr.write(f"\r\033[K {G}✔{RST} Routable reflectors up\n") + sys.stderr.flush() + + # Wait for trunk connections across the chain: + # leaf <--> natlit, natlit <--> natlde, natlde <--> far + sys.stderr.write(f" {D}waiting for trunk chain...{RST}") + sys.stderr.flush() + wait_for_trunk_connected(*_http("leaf"), "TRUNK_LEAF_NATLIT", timeout=30.0) + wait_for_trunk_connected(*_http("natlit"), "TRUNK_LEAF_NATLIT", timeout=30.0) + wait_for_trunk_connected(*_http("natlit"), "TRUNK_NATLDE_NATLIT", timeout=30.0) + wait_for_trunk_connected(*_http("natlde"), "TRUNK_NATLDE_NATLIT", timeout=30.0) + wait_for_trunk_connected(*_http("natlde"), "TRUNK_FAR_NATLDE", timeout=30.0) + wait_for_trunk_connected(*_http("far"), "TRUNK_FAR_NATLDE", timeout=30.0) + sys.stderr.write(f"\r\033[K {G}✔{RST} Trunk chain connected\n") + sys.stderr.flush() + + # Give interest-debounce timers a moment to settle + time.sleep(1.0) + + # ------------------------------------------------------------------ + # Test 01: explicit transit — leaf client can reach far client (TG 26305) + # ------------------------------------------------------------------ + def test_01_explicit_transit_forward_and_return(self): + """ROUTABLE_PREFIXES=* on leaf and ROUTABLE_PREFIXES=263 on natlit/natlde + must route TG 26305 all the way from leaf to far and back. + + leaf --[ROUTABLE_PREFIXES=*]--> natlit --[ROUTABLE_PREFIXES=263]--> natlde + --[ROUTABLE_PREFIXES=263]--> far + + Forward leg: leaf client selects TG 26305, far client selects 26305. + leaf sends 6 UDP audio frames + flush. + far must receive > 0 audio or flush packets. + + Return leg: far sends 6 UDP audio frames + flush. + leaf must receive > 0 audio or flush packets. + + NOTE: This test is expected to FAIL until ROUTABLE_PREFIXES is + implemented in the C++ reflector (Task 1 TDD anchor). + """ + tg = 26305 # owned by far (prefix 263); unreachable without transit + + leaf_port = _client_port("leaf") + far_port = _client_port("far") + + leaf_client = ClientPeer() + far_client = ClientPeer() + try: + # leaf client — selects TG 26305 + leaf_client.connect(HOST, leaf_port) + leaf_client.authenticate(callsign=CLIENT_CALLSIGN, + password=CLIENT_PASSWORD) + leaf_client.setup_udp(udp_port=leaf_port) + leaf_client.select_tg(tg) + + # far client — selects TG 26305 (owner side) + far_client.connect(HOST, far_port) + far_client.authenticate(callsign=CLIENT2_CALLSIGN, + password=CLIENT2_PASSWORD) + far_client.setup_udp(udp_port=far_port) + far_client.select_tg(tg) + + # Allow peer-interest debounce (500 ms each hop × 2 hops) + margin + time.sleep(2.0) + + # Drain any backlog before the measurement burst + leaf_client.recv_udp_all(timeout=0.05) + far_client.recv_udp_all(timeout=0.05) + + # --- Forward leg: leaf → far --- + for _ in range(6): + leaf_client.send_udp_audio(b"\xBE\xEF" * 80) + time.sleep(0.02) + leaf_client.send_udp_flush() + time.sleep(1.5) + + fwd_msgs = far_client.recv_udp_all(timeout=1.0) + fwd_audio = sum(1 for t, _ in fwd_msgs if t == UDP_AUDIO) + fwd_flush = sum(1 for t, _ in fwd_msgs if t == UDP_FLUSH) + self.assertGreater( + fwd_audio + fwd_flush, 0, + f"forward leg FAILED: far client heard 0 UDP frames for TG {tg}. " + f"ROUTABLE_PREFIXES transit is not yet implemented (expected failure).", + ) + + # --- Return leg: far → leaf --- + leaf_client.recv_udp_all(timeout=0.05) # flush stale + for _ in range(6): + far_client.send_udp_audio(b"\xCA\xFE" * 80) + time.sleep(0.02) + far_client.send_udp_flush() + time.sleep(1.5) + + ret_msgs = leaf_client.recv_udp_all(timeout=1.0) + ret_audio = sum(1 for t, _ in ret_msgs if t == UDP_AUDIO) + ret_flush = sum(1 for t, _ in ret_msgs if t == UDP_FLUSH) + self.assertGreater( + ret_audio + ret_flush, 0, + f"return leg FAILED: leaf client heard 0 UDP frames for TG {tg}. " + f"ROUTABLE_PREFIXES transit is not yet implemented (expected failure).", + ) + + finally: + leaf_client.close() + far_client.close() + + # ------------------------------------------------------------------ + # Test 02: wildcard + blacklist veto (TG 26307 blocked on leaf uplink) + # ------------------------------------------------------------------ + def test_02_wildcard_blacklist_veto(self): + """BLACKLIST_TGS=26307 on leaf's uplink must prevent TG 26307 from + reaching far, even though ROUTABLE_PREFIXES=* would otherwise route it. + + leaf selects TG 26307, far selects 26307. + leaf sends 6 UDP audio frames + flush. + far must receive EXACTLY 0 audio or flush packets. + + This test is expected to PASS once ROUTABLE_PREFIXES is implemented, + because the blacklist veto is a separate filter that suppresses the + specific TG before routable transit logic fires. Until the feature + lands, far also hears nothing (transit not working), so the assertion + holds trivially — but it documents the intended blacklist behaviour. + """ + tg = 26307 # blacklisted on leaf → natlit link; far must hear nothing + + leaf_port = _client_port("leaf") + far_port = _client_port("far") + + leaf_client = ClientPeer() + far_client = ClientPeer() + try: + # leaf client — selects TG 26307 + leaf_client.connect(HOST, leaf_port) + leaf_client.authenticate(callsign=CLIENT_CALLSIGN, + password=CLIENT_PASSWORD) + leaf_client.setup_udp(udp_port=leaf_port) + leaf_client.select_tg(tg) + + # far client — selects TG 26307 (owner side) + far_client.connect(HOST, far_port) + far_client.authenticate(callsign=CLIENT2_CALLSIGN, + password=CLIENT2_PASSWORD) + far_client.setup_udp(udp_port=far_port) + far_client.select_tg(tg) + + # Allow interest debounce to settle + time.sleep(2.0) + + # Drain backlog + far_client.recv_udp_all(timeout=0.05) + + # leaf sends audio — must NOT reach far + for _ in range(6): + leaf_client.send_udp_audio(b"\xDE\xAD" * 80) + time.sleep(0.02) + leaf_client.send_udp_flush() + time.sleep(1.5) + + veto_msgs = far_client.recv_udp_all(timeout=1.0) + veto_audio = sum(1 for t, _ in veto_msgs if t == UDP_AUDIO) + veto_flush = sum(1 for t, _ in veto_msgs if t == UDP_FLUSH) + self.assertEqual( + veto_audio + veto_flush, 0, + f"blacklist veto FAILED: far client received {veto_audio} audio " + f"+ {veto_flush} flush frames for TG {tg}, expected 0. " + f"BLACKLIST_TGS=26307 on leaf→natlit should suppress this TG.", + ) + + finally: + leaf_client.close() + far_client.close() + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/topology.py b/tests/topology.py index ea0799e..c17bab4 100644 --- a/tests/topology.py +++ b/tests/topology.py @@ -303,3 +303,52 @@ def twin_mapped_satellite_port(name: str) -> int: def twin_trunks_for(name: str) -> list: """Return all TWIN_TRUNKS entries that involve this reflector.""" return [t for t in TWIN_TRUNKS if name in t["peers"]] + + +# --------------------------------------------------------------------------- +# Routable-prefix chain (isolated topology, used by test_routable.py only) +# +# leaf 222100* --trunk--> natlit 222 --trunk--> natlde 262 --trunk--> far 263 +# +# `263` is a SIBLING of 222/262 (not nested), so it is unreachable without +# routable prefixes. The leaf uses "*" (default route to its only uplink); +# each backbone hop declares an explicit ROUTABLE_PREFIXES toward 263. +# +# blacklist on leaf's uplink vetoes TG 26307 exactly (test_02) while leaving +# TG 26305 (test_01) unaffected — the two tests use distinct TG numbers. +# --------------------------------------------------------------------------- +ROUTABLE_REFLECTORS = { + # name prefix trunk_port_base peers routable (per-peer additions) + "leaf": {"prefix": ["222100"], "trunk_port_base": 51000, + "peers": ["natlit"], "routable": {"natlit": ["*"]}, + "blacklist": {"natlit": "26307"}}, + "natlit": {"prefix": ["222"], "trunk_port_base": 52000, + "peers": ["leaf", "natlde"], "routable": {"natlde": ["263"]}}, + "natlde": {"prefix": ["262"], "trunk_port_base": 53000, + "peers": ["natlit", "far"], "routable": {"natlit": ["263"]}}, + "far": {"prefix": ["263"], "trunk_port_base": 54000, + "peers": ["natlde"]}, +} +ROUTABLE_NAMES = list(ROUTABLE_REFLECTORS.keys()) + + +# --------------------------------------------------------------------------- +# Routable topology helpers +# --------------------------------------------------------------------------- + +def routable_mapped_client_port(name: str) -> int: + return ROUTABLE_REFLECTORS[name]["trunk_port_base"] + 300 + + +def routable_mapped_trunk_port(name: str) -> int: + return ROUTABLE_REFLECTORS[name]["trunk_port_base"] + 302 + + +def routable_mapped_http_port(name: str) -> int: + return ROUTABLE_REFLECTORS[name]["trunk_port_base"] + 3080 + + +def routable_trunk_secret(name_a: str, name_b: str) -> str: + """Shared secret for a routable-topology link (sorted pair).""" + pair = tuple(sorted([name_a, name_b])) + return f"secret_routable_{pair[0]}_{pair[1]}" From 46979c1f8b719f13788df18b8368da54783135e7 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 16:34:18 +0200 Subject: [PATCH 02/10] test(routable): clarify return-path docs; drop dead test scaffolding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Document both forward and return legs of the 263xx transit chain in topology.py ROUTABLE_REFLECTORS comment block, making clear that natlde's routable entry toward natlit is the return-path hop and that the natlit→leaf final hop is carried by peer-interest (not a routable entry). Add inline note on natlde's entry. Drop ROUTABLE_NAMES from topology.py (dead — test files define their own sorted() locals, matching the REFLECTOR_NAMES/TWIN_NAMES convention). Remove duplicate sys.path.insert and unused COMPOSE_FILE/TESTS_DIR constants from test_routable.py. Add clarifying comment above the per-peer routable/blacklist injection in generate_configs.py. Generated configs are byte-identical; no topology routing changes. --- tests/generate_configs.py | 4 ++++ tests/test_routable.py | 8 ++------ tests/topology.py | 27 ++++++++++++++++++++++----- 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/tests/generate_configs.py b/tests/generate_configs.py index 015254b..dbfea17 100644 --- a/tests/generate_configs.py +++ b/tests/generate_configs.py @@ -64,6 +64,8 @@ def generate_reflector_conf(name: str) -> str: f"SECRET={secret}", f"REMOTE_PREFIX={T.prefix_str(peer['prefix'])}", ] + # Optional per-peer routable/blacklist (used only by the ROUTABLE_REFLECTORS + # topology; inert for the default mesh). routable = r.get("routable", {}).get(peer_name) if routable: lines.append(f"ROUTABLE_PREFIXES={','.join(routable)}") @@ -598,6 +600,8 @@ def generate_routable_reflector_conf(name: str) -> str: f"SECRET={secret}", f"REMOTE_PREFIX={T.prefix_str(peer['prefix'])}", ] + # Optional per-peer routable/blacklist (used only by the ROUTABLE_REFLECTORS + # topology; inert for the default mesh). routable = r.get("routable", {}).get(peer_name) if routable: lines.append(f"ROUTABLE_PREFIXES={','.join(routable)}") diff --git a/tests/test_routable.py b/tests/test_routable.py index 90ed8cd..62d6b61 100644 --- a/tests/test_routable.py +++ b/tests/test_routable.py @@ -33,7 +33,8 @@ from urllib.request import urlopen from urllib.error import URLError import json -# Reuse the V2 mock client and wire helpers from test_trunk.py +# Reuse the V2 mock client and wire helpers from test_trunk.py. +# Also ensures tests/ is on the path for topology import below. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from test_trunk import ( # noqa: E402 ClientPeer, UDP_AUDIO, UDP_FLUSH, @@ -41,8 +42,6 @@ from test_trunk import ( # noqa: E402 CLIENT2_CALLSIGN, CLIENT2_PASSWORD, ) -# Ensure tests/ is on the path so topology can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import topology as T # --------------------------------------------------------------------------- @@ -53,9 +52,6 @@ HOST = "127.0.0.1" ROUTABLE_NAMES = sorted(T.ROUTABLE_REFLECTORS) -COMPOSE_FILE = "docker-compose.routable.yml" -TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) - def _http(name: str): return (HOST, T.routable_mapped_http_port(name)) diff --git a/tests/topology.py b/tests/topology.py index c17bab4..c097d91 100644 --- a/tests/topology.py +++ b/tests/topology.py @@ -308,11 +308,27 @@ def twin_trunks_for(name: str) -> list: # --------------------------------------------------------------------------- # Routable-prefix chain (isolated topology, used by test_routable.py only) # -# leaf 222100* --trunk--> natlit 222 --trunk--> natlde 262 --trunk--> far 263 +# leaf 222100 --trunk--> natlit 222 --trunk--> natlde 262 --trunk--> far 263 # -# `263` is a SIBLING of 222/262 (not nested), so it is unreachable without -# routable prefixes. The leaf uses "*" (default route to its only uplink); -# each backbone hop declares an explicit ROUTABLE_PREFIXES toward 263. +# `263` is a SIBLING prefix to 222/262 (not nested), so it is unreachable +# from leaf without explicit routable-prefix declarations. +# +# Forward path (leaf → far): +# leaf uses ROUTABLE_PREFIXES=* toward natlit — default-route all non-local +# TGs up the only uplink. +# natlit uses ROUTABLE_PREFIXES=263 toward natlde — transits 263xx onward. +# natlde→far is native: far owns 263, so no routable entry is needed. +# +# Return path (far → leaf): +# far→natlde is native (far originates, natlde accepts as trunk owner relay). +# natlde uses ROUTABLE_PREFIXES=263 toward natlit — transits 263xx back up. +# (This is the return-path hop; the entry points upstream, not downstream.) +# natlit→leaf final hop is carried by PEER-INTEREST: leaf's ROUTABLE_PREFIXES=* +# caused it to advertise interest in 263xx up to natlit via MsgPeerTgInterest, +# so natlit forwards via isPeerInterestedTG — no routable entry on natlit +# toward leaf is needed or correct. +# leaf ACCEPTS the return audio because its uplink has the `*` wildcard +# (matchesRoutable), not because leaf has a routable entry pointing at itself. # # blacklist on leaf's uplink vetoes TG 26307 exactly (test_02) while leaving # TG 26305 (test_01) unaffected — the two tests use distinct TG numbers. @@ -324,12 +340,13 @@ ROUTABLE_REFLECTORS = { "blacklist": {"natlit": "26307"}}, "natlit": {"prefix": ["222"], "trunk_port_base": 52000, "peers": ["leaf", "natlde"], "routable": {"natlde": ["263"]}}, + # return-path hop: ROUTABLE_PREFIXES=263 toward natlit transits 263xx back + # up the chain (far→natlde native; natlit→leaf via peer-interest, not routable) "natlde": {"prefix": ["262"], "trunk_port_base": 53000, "peers": ["natlit", "far"], "routable": {"natlit": ["263"]}}, "far": {"prefix": ["263"], "trunk_port_base": 54000, "peers": ["natlde"]}, } -ROUTABLE_NAMES = list(ROUTABLE_REFLECTORS.keys()) # --------------------------------------------------------------------------- From 4b55d69bd61c0429abf3b8145fabc2efeda49470 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 16:48:43 +0200 Subject: [PATCH 03/10] feat(trunk): parse ROUTABLE_PREFIXES (members + initialize + reload) --- src/svxlink/reflector/TrunkLink.cpp | 49 +++++++++++++++++++++++++++++ src/svxlink/reflector/TrunkLink.h | 5 +++ 2 files changed, 54 insertions(+) diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index d942b8d..7bc1bf3 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -316,6 +316,23 @@ bool TrunkLink::initialize(void) return false; } + // ROUTABLE_PREFIXES — optional additional prefixes (or "*") reachable VIA + // this peer beyond what it owns. "*" is a default route (regional leaves); + // explicit prefixes enable backbone transit. See docs/PEER_PROTOCOL.md. + std::string routable_str; + if (m_cfg.getValue(m_section, "ROUTABLE_PREFIXES", routable_str) + && !routable_str.empty()) + { + for (const auto& p : splitPrefixes(routable_str)) + { + if (p == "*") m_routable_wildcard = true; + else m_routable_prefixes.push_back(p); + } + geulog::info("trunk", m_section, ": Routable prefixes: ", + joinPrefixes(m_routable_prefixes), + (m_routable_wildcard ? " *(default route)" : "")); + } + // PEER_ID — name we advertise in our hello (defaults to section name). // Used by the receiving peer as the MQTT topic component for this link. if (!m_cfg.getValue(m_section, "PEER_ID", m_peer_id_config) @@ -471,6 +488,22 @@ bool TrunkLink::isSharedTG(uint32_t tg) const } /* TrunkLink::isSharedTG */ +bool TrunkLink::matchesRoutable(uint32_t tg) const +{ + if (m_routable_wildcard) return true; + const std::string s = std::to_string(tg); + for (const auto& prefix : m_routable_prefixes) + { + if (s.size() >= prefix.size() && + s.compare(0, prefix.size(), prefix) == 0) + { + return true; + } + } + return false; +} /* TrunkLink::matchesRoutable */ + + bool TrunkLink::isOwnedTG(uint32_t tg) const { const std::string s = std::to_string(tg); @@ -1951,6 +1984,8 @@ void TrunkLink::reloadConfig(void) m_allow_filter = TgFilter{}; m_tg_map_in.clear(); m_tg_map_out.clear(); + m_routable_prefixes.clear(); + m_routable_wildcard = false; RedisStore* rs = m_reflector->redisStore(); @@ -1976,6 +2011,20 @@ void TrunkLink::reloadConfig(void) m_allow_filter = TgFilter::parse(allow_str); } + if (!rs) + { + std::string routable_str; + if (m_cfg.getValue(m_section, "ROUTABLE_PREFIXES", routable_str) + && !routable_str.empty()) + { + for (const auto& p : splitPrefixes(routable_str)) + { + if (p == "*") m_routable_wildcard = true; + else m_routable_prefixes.push_back(p); + } + } + } + if (rs) { auto tgmap = rs->loadTrunkTgMap(m_section); for (auto& kv : tgmap) { diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index cfc1cfd..92c8488 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -101,6 +101,9 @@ class TrunkLink : public sigc::trackable bool initialize(void); bool isSharedTG(uint32_t tg) const; + // True if tg matches an explicit ROUTABLE_PREFIXES entry on this link, + // or the "*" wildcard is set. Per-link; used by the inbound-accept gate. + bool matchesRoutable(uint32_t tg) const; void setAllPrefixes(const std::vector& all_prefixes) { m_all_prefixes = all_prefixes; @@ -206,6 +209,8 @@ class TrunkLink : public sigc::trackable std::string m_peer_id_received; // peer's hello id (set on hello rx) std::vector m_local_prefix; // our authoritative TG prefixes std::vector m_remote_prefix; // peer's authoritative TG prefixes + std::vector m_routable_prefixes; // explicit ROUTABLE_PREFIXES (non-"*") + bool m_routable_wildcard = false; // "*" present uint32_t m_priority; // our tie-break nonce (random, set once) uint32_t m_peer_priority; // peer's nonce, from MsgPeerHello FramedTcpClient m_con; // outbound client connection From 1e1d477957ab06239155e8e469d17b53b34122ab Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 16:57:10 +0200 Subject: [PATCH 04/10] feat(trunk): routable prefixes feed isSharedTG send/interest gate (* = zero-length) --- src/svxlink/reflector/TrunkLink.cpp | 35 ++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 7bc1bf3..f5774f2 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -456,34 +456,47 @@ bool TrunkLink::isSharedTG(uint32_t tg) const { const std::string s = std::to_string(tg); - // Find the best (longest) matching remote prefix for this peer - size_t best_remote_len = 0; + // Best (longest) prefix THIS link claims: an owned remote prefix or an + // explicit routable prefix. The "*" wildcard is a zero-length candidate + // (lowest precedence), considered only when no real prefix matches. + size_t best_link_len = 0; + bool matched = false; for (const auto& prefix : m_remote_prefix) { if (s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0 && - prefix.size() > best_remote_len) + prefix.size() > best_link_len) { - best_remote_len = prefix.size(); + best_link_len = prefix.size(); + matched = true; } } - if (best_remote_len == 0) + for (const auto& prefix : m_routable_prefixes) { - return false; // no remote prefix matches at all + if (s.size() >= prefix.size() && + s.compare(0, prefix.size(), prefix) == 0 && + prefix.size() > best_link_len) + { + best_link_len = prefix.size(); + matched = true; + } + } + if (!matched) + { + if (!m_routable_wildcard) return false; + best_link_len = 0; // wildcard: zero-length, any real prefix beats it } - // Check if any prefix in the mesh is a longer match — if so, that other - // reflector is more specific and this TG doesn't belong to this peer. + // A longer prefix anywhere in the mesh is more specific — not ours. for (const auto& prefix : m_all_prefixes) { - if (prefix.size() > best_remote_len && + if (prefix.size() > best_link_len && s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0) { - return false; // a longer prefix claims this TG + return false; } } - return true; } /* TrunkLink::isSharedTG */ From ce08a9886cc50ec9be64f7a9fac5a15dd8734f85 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 17:07:00 +0200 Subject: [PATCH 05/10] feat(reflector): explicit routable prefixes join m_all_prefixes for transit (excludes *) --- src/svxlink/reflector/Reflector.cpp | 21 +++++++++++++++++++++ src/svxlink/reflector/TrunkLink.h | 4 ++++ 2 files changed, 25 insertions(+) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index c02bec5..4b6dfe7 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2368,6 +2368,23 @@ void Reflector::initTrunkLinks(void) if (!token.empty()) all_prefixes.push_back(token); } } + + // Explicit routable prefixes are reachable via this peer and must + // participate in mesh-wide longest-prefix-match + hasPrefixRoute so + // transit fanout fires for them. "*" is intentionally NOT added — a + // wildcard route never transits (loop guard, spec section 5). + std::string routable_str; + m_cfg->getValue(section, "ROUTABLE_PREFIXES", routable_str); + { + std::istringstream rs(routable_str); + std::string token; + while (std::getline(rs, token, ',')) + { + token.erase(0, token.find_first_not_of(" \t")); + token.erase(token.find_last_not_of(" \t") + 1); + if (!token.empty() && token != "*") all_prefixes.push_back(token); + } + } } // Cache the mesh-wide prefix set for owner-relay decisions. @@ -3099,6 +3116,10 @@ std::vector Reflector::collectAllTrunkPrefixes(void) const std::vector all; for (const auto* link : m_trunk_links) { for (const std::string& p : link->remotePrefix()) all.push_back(p); + // Explicit routable prefixes (never "*" — m_routable_prefixes excludes it) + // must also join the mesh-wide set so hasPrefixRoute / shouldRelayInbound + // fire correctly for transit on reload. + for (const std::string& p : link->routablePrefixes()) all.push_back(p); } return all; } diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 92c8488..579c025 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -121,6 +121,10 @@ class TrunkLink : public sigc::trackable { return m_remote_prefix; } + const std::vector& routablePrefixes(void) const + { + return m_routable_prefixes; + } // Read-only view of TGs the peer is interested in (TalkerStart activity // or MsgPeerTgInterest advertisement). Used by Reflector to aggregate // interest for re-advertisement toward the prefix owner. From 92c8284b7cfd01611f9a28e00895e21e0d3eb1a5 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 17:24:52 +0200 Subject: [PATCH 06/10] feat(trunk): accept inbound for routable/transit TGs (hasPrefixRoute || matchesRoutable) --- src/svxlink/reflector/TrunkLink.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index f5774f2..0384a6d 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -1080,7 +1080,8 @@ void TrunkLink::handleMsgPeerTalkerStart(std::istream& is) return; } bool mapped = m_tg_map_in.count(wire_tg) > 0; - if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg) && + !m_reflector->hasPrefixRoute(wire_tg) && !matchesRoutable(wire_tg)) { return; } @@ -1144,7 +1145,8 @@ void TrunkLink::handleMsgPeerTalkerStop(std::istream& is) return; } bool mapped = m_tg_map_in.count(wire_tg) > 0; - if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg) && + !m_reflector->hasPrefixRoute(wire_tg) && !matchesRoutable(wire_tg)) { return; } @@ -1180,7 +1182,8 @@ void TrunkLink::handleMsgPeerAudio(std::istream& is) return; } bool mapped = m_tg_map_in.count(wire_tg) > 0; - if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg) && + !m_reflector->hasPrefixRoute(wire_tg) && !matchesRoutable(wire_tg)) { return; } @@ -1247,7 +1250,8 @@ void TrunkLink::handleMsgPeerFlush(std::istream& is) return; } bool mapped = m_tg_map_in.count(wire_tg) > 0; - if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg) && + !m_reflector->hasPrefixRoute(wire_tg) && !matchesRoutable(wire_tg)) { return; } From bf7c82b3ae9ae727f82f8757e751fc8ee2ea73c2 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 18:33:07 +0200 Subject: [PATCH 07/10] feat(trunk): warn when ROUTABLE_PREFIXES='*' set on a multi-trunk reflector --- src/svxlink/reflector/Reflector.cpp | 18 ++++++++++++++++++ src/svxlink/reflector/TrunkLink.h | 1 + 2 files changed, 19 insertions(+) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 4b6dfe7..39a5a1e 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2407,6 +2407,24 @@ void Reflector::initTrunkLinks(void) } } + // A "*" routable route on a node with >1 trunk is outside the intended + // regional-leaf pattern: "*" only affects this node's own local clients and + // is never transited (loop guard, spec section 5). Warn so it reads as + // likely misconfig. + if (m_trunk_links.size() > 1) + { + for (auto* l : m_trunk_links) + { + if (l->hasRoutableWildcard()) + { + geulog::warn("trunk", l->section(), + ": ROUTABLE_PREFIXES contains '*' on a multi-trunk reflector — " + "'*' affects only local clients and is never relayed between " + "trunks. Intended for single-uplink regional leaves."); + } + } + } + // Validate cluster TGs don't overlap with any prefix for (uint32_t tg : m_cluster_tgs) { diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 579c025..fe96c89 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -138,6 +138,7 @@ class TrunkLink : public sigc::trackable static const time_t PEER_INTEREST_TIMEOUT_S = 600; bool isPaired(void) const { return m_paired; } + bool hasRoutableWildcard(void) const { return m_routable_wildcard; } bool hasInboundConnection(void) const { return m_paired ? !m_ib_cons.empty() : (m_inbound_con != nullptr); From b18f3e81419ec1defdbf18c445174157cc728698 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 19:48:30 +0200 Subject: [PATCH 08/10] docs(routable): document ROUTABLE_PREFIXES across conf, README, protocol, tests --- README.md | 65 ++++++++++++++++++++++ docs/PEER_PROTOCOL.md | 56 +++++++++++++++++++ src/svxlink/reflector/svxreflector.conf.in | 11 ++++ tests/TESTS.md | 12 ++++ 4 files changed, 144 insertions(+) diff --git a/README.md b/README.md index a5ec5f8..0bfcd65 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,71 @@ link. For example, if reflectors A and B want to link, both configs must use the same name (e.g. `[TRUNK_AB]`). A connection from a peer whose section name does not match any local section will be rejected. +### 5. Routable prefixes — hierarchical and non-full-mesh topologies (optional) + +In a standard full mesh every pair of reflectors has a direct trunk link, so +each reflector can reach any TG via `REMOTE_PREFIX` alone. Some deployments +cannot or should not use a full mesh: + +- A **regional leaf** with a single uplink to a national backbone has no + direct path to sibling regions — it needs a default route via the parent. +- A **transit backbone** node between two meshes may carry traffic for prefix + groups it does not own and that are not adjacent in `REMOTE_PREFIX`. + +`ROUTABLE_PREFIXES` (per `[TRUNK_x]` section, comma-separated) declares +additional TG prefixes that are reachable *via* this peer beyond what +`REMOTE_PREFIX` already covers. + +**Explicit prefixes** (e.g. `263`) extend the mesh-wide prefix set so the +reflector will accept those TGs inbound and transit them onward toward the +owner via the existing gateway fanout (`shouldRelayInbound`). Each intermediate +hop along a chain must declare the same routable prefix on the appropriate trunk +— there is no automatic propagation. + +**`*` wildcard** acts as a default route for a single-uplink regional leaf: local +clients can reach any TG via that uplink, and the return audio is accepted back. +`*` is never relayed between trunks (loop-safe) and is not added to the +mesh-wide prefix set, so it is invisible to gateway forwarding. A `*` is a +zero-length, lowest-precedence match — it never overrides a real prefix. A +startup `WARNING` is logged when `*` is set on a reflector that has more than +one trunk, since that topology is outside the intended single-uplink leaf +pattern. + +**Blacklist precedence:** `BLACKLIST_TGS` is evaluated before any routable +logic — a blacklisted TG is never forwarded, accepted, or advertised as +interest, regardless of `ROUTABLE_PREFIXES`. + +**Ownership caveat:** do not set a routable prefix that is a longer +decimal-string match of a TG this reflector itself owns — the +longest-prefix-match ownership check would then incorrectly route that TG +away from the local owner. Keep routable prefixes pointed at TGs owned by +other reflectors (the same discipline that already applies to `REMOTE_PREFIX`). + +Example — three-hop chain where `leaf` (prefix `240`) needs to reach TG `2630xx` +owned by `far` (prefix `263`), transiting through `natl` (prefix `262`): + +```ini +# On leaf — default route via the only uplink +[TRUNK_LEAF_NATL] +HOST=natl.example.com +SECRET=secret_leaf_natl +REMOTE_PREFIX=262 +ROUTABLE_PREFIXES=* + +# On natl — explicit transit toward 263 via the natlde link +[TRUNK_NATL_NATLDE] +HOST=natlde.example.com +SECRET=secret_natl_natlde +REMOTE_PREFIX=262 +ROUTABLE_PREFIXES=263 + +# On natlde — native REMOTE_PREFIX=263 already covers the last hop +[TRUNK_NATLDE_FAR] +HOST=far.example.com +SECRET=secret_natlde_far +REMOTE_PREFIX=263 +``` + ### Network requirements **Trunk links** require **mutual reachability**: each reflector both listens for diff --git a/docs/PEER_PROTOCOL.md b/docs/PEER_PROTOCOL.md index 8eeb80b..9bb90b4 100644 --- a/docs/PEER_PROTOCOL.md +++ b/docs/PEER_PROTOCOL.md @@ -188,6 +188,62 @@ active QSO the fanout stays live indefinitely; on a TG that has been silent for ~10 minutes, the first PTT from a non-owner's client re-arms the fanout before the owner starts forwarding that TG back out. +### Routable Prefixes (`ROUTABLE_PREFIXES`) + +Standard prefix routing requires either a direct `REMOTE_PREFIX` match or full-mesh +connectivity. `ROUTABLE_PREFIXES` (per `[TRUNK_x]` section, comma-separated) adds +two complementary capabilities for hierarchical and non-full-mesh topologies. + +**Explicit prefixes** (e.g. `263`) are injected into `m_all_prefixes` at startup +alongside `LOCAL_PREFIX` and all `REMOTE_PREFIX` values. From that point they +participate in longest-prefix-match just like native prefixes: + +- **Send / interest gate (`isSharedTG`).** When evaluating whether to forward a local + talker event or audio frame on a given trunk link, `isSharedTG` performs a + longest-prefix-match against the remote peer's combined prefix set (its + `REMOTE_PREFIX` plus its `ROUTABLE_PREFIXES`). A TG that matches a routable + prefix on that link is forwarded toward the peer as if it matched `REMOTE_PREFIX`. +- **Interest advertisement (`MsgPeerTgInterest`, type 129).** The same `isSharedTG` + gate controls which TGs are advertised in interest messages, so a routable TG's + interest reaches the next hop toward the owner without a PTT. +- **Inbound accept gate.** On the receive side, `hasPrefixRoute(tg)` is true whenever + `m_all_prefixes` holds a prefix that matches the TG — including routable prefixes. + Combined with `isOwnedTG`, this covers accepting transit traffic for TGs this + reflector neither owns nor has as a direct `REMOTE_PREFIX`. +- **Transit (`shouldRelayInbound` / `hasPrefixRoute`).** Because the routable prefix + is in `m_all_prefixes`, `hasPrefixRoute(tg)` returns true and + `shouldRelayInbound` triggers the gateway fanout arm, re-forwarding the frame via + `onLocal*` toward the actual owner. Each intermediate hop in a chain must + declare the same routable prefix on its appropriate trunk; the declaration does + not propagate automatically. + +**`*` wildcard** is a zero-length default-route match. It is treated as the +lowest-precedence prefix — a real prefix always wins — and is **never** added to +`m_all_prefixes`. As a result: + +- `isSharedTG` admits any TG via a `*`-configured link for local-client forwarding + and interest advertisement. +- `hasPrefixRoute` is **not** set for `*`-matched TGs, so `shouldRelayInbound` does + not trigger the gateway arm. Wildcard-routed frames are delivered locally but + never transited between trunks. +- The **return leg** to a `*`-leaf relies on peer interest: because `*` matches every + TG in the send/interest gate, the leaf advertises interest in the TG toward the + parent (`MsgPeerTgInterest`), and the parent's `isPeerInterestedTG` carries the + return audio back without needing any routable entry on the parent side. + +A startup `WARNING` is emitted when `*` is set on a reflector with more than one +trunk, as that is outside the intended single-uplink leaf pattern and may produce +unexpected fanout behaviour. + +**Blacklist precedence.** `BLACKLIST_TGS` is evaluated before any routable prefix +logic. A blacklisted TG is dropped before `isSharedTG`, `hasPrefixRoute`, or +interest advertisement are consulted. + +**Ownership caveat.** A routable prefix must not be a longer decimal-string match +of a TG the local reflector owns: `isSharedTG` (and `hasPrefixRoute`) would then +route that TG away from the local owner. Keep routable prefixes pointed at TGs +owned by other reflectors — the same discipline that governs `REMOTE_PREFIX`. + ### Cluster TGs Cluster TGs bypass prefix routing entirely. A TG listed in `CLUSTER_TGS` is diff --git a/src/svxlink/reflector/svxreflector.conf.in b/src/svxlink/reflector/svxreflector.conf.in index c4c55a9..faa178f 100644 --- a/src/svxlink/reflector/svxreflector.conf.in +++ b/src/svxlink/reflector/svxreflector.conf.in @@ -129,6 +129,17 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py # Optional bidirectional TG remap (peer_tg:local_tg, comma-separated). # Mapped TGs bypass the prefix routing check on this link. #TG_MAP=1:2624123,2:2624124 +# Optional additional prefixes routable VIA this peer, on top of REMOTE_PREFIX. +# Use on a regional leaf's single uplink as "*" (default route to the parent), +# or on a backbone trunk as explicit prefixes to enable multi-hop transit to a +# sibling reflector (e.g. reach 263 via the 262 peer). "*" is never relayed +# between trunks (loop-safe) and only affects this node's local clients; +# explicit prefixes transit toward the owner and must be declared on each hop. +# Keep routable prefixes pointed at TGs owned by OTHER reflectors (do not let a +# routable prefix be a longer match of a TG this reflector owns). +# BLACKLIST_TGS still vetoes regardless of routable settings. +#ROUTABLE_PREFIXES=263 # backbone transit toward 263 +#ROUTABLE_PREFIXES=* # regional leaf default route via this uplink ############################################################################### # Twin (HA-pair) link — see docs/TWIN_PROTOCOL.md diff --git a/tests/TESTS.md b/tests/TESTS.md index 30b6753..57613c9 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -12,6 +12,8 @@ The integration tests verify the trunk protocol, satellite links, twin (HA-pair) A separate harness (`run_redis_tests.sh`) runs `test_redis.py` (13 tests) against a single-reflector + Redis stack. See [Redis Integration Tests](#redis-integration-tests) below. +A separate harness runs `test_routable.py` (2 tests) against a dedicated routable-prefix topology. See [Routable Prefixes](#routable-prefixes) below. + **Requirements:** Docker, Docker Compose, Python 3.7+ (stdlib only, no pip packages). ## Running @@ -131,6 +133,7 @@ Internal port for `[TWIN]` is always 5304; satellite is 5303. | `docker-compose.test.yml` | Generated compose file (do not edit manually) | | `topology_redis.py` | Topology for the Redis test harness (single reflector + Redis). | | `generate_redis_configs.py` | Generates `configs-redis/*.conf` and `docker-compose.redis.yml`. | +| `test_routable.py` | Routable-prefix tests (2 cases): explicit multi-hop transit (forward + return) and `*` wildcard with blacklist veto. Runs on a dedicated compose stack generated from `topology_routable.py`. | | `test_redis.py` | Redis-backed config-store tests (13 cases): users, trunk filters, live-state hashes, outage/resync, import idempotence, peer-node mirroring + sanitization, dynamic trunk add/remove. | | `run_redis_tests.sh` | Redis test orchestrator with `up`/`test`/`down`/`all` subcommands. | | `configs-redis/` | Generated Redis-harness configs (do not edit manually) | @@ -264,6 +267,15 @@ each filter independently of the other trunk fixtures. | 46 | Inbound heartbeat timeout — no crash | A non-paired trunk link whose inbound socket is closed on heartbeat timeout must not abort the process on the next send (e.g. a `MsgPeerTgInterest`) | | 47 | Inbound recovers after timeout | After the reflector times out and drops a silent inbound peer, the same peer can reconnect its inbound leg | +### Routable Prefixes + +Run separately via `test_routable.py` against a dedicated topology. + +| # | Test | What it verifies | +|---|------|-----------------| +| R1 | Explicit transit forward + return | A client on a leaf reflector activates a TG owned by a far reflector two hops away; audio traverses both transit hops (explicit `ROUTABLE_PREFIXES` on each intermediate trunk) and the return audio reaches the leaf via peer interest | +| R2 | `*` wildcard + blacklist veto | A client on a `*`-configured leaf reaches a remote TG via its single uplink; a TG listed in `BLACKLIST_TGS` on the same link is dropped regardless of the wildcard, confirming blacklist-before-routable evaluation order | + ### Twin Protocol (HA-pair) Run separately on the twin topology (`test_twin.py`). See `docs/TWIN_PROTOCOL.md` for the protocol. From 013040d1fbbfebe598c57f638a83c30194e545c0 Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 21:42:28 +0200 Subject: [PATCH 09/10] docs(routable): fix routing example, delegation note, return-leg accept, test refs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace wrong "ownership caveat" in all three files with a neutral delegation note: a more specific routable prefix intentionally delegates that sub-range via longest-prefix-match; point it at the reflector that actually owns those TGs. - Fix the README example: align it with the actual test topology (leaf 222100 → natlit 222 → natlde 262 → far 263, two transit nodes, three trunk links); every REMOTE_PREFIX now equals the peer's LOCAL_PREFIX with no collisions; add the natlde return-path trunk section. - Add a sentence in both README and PEER_PROTOCOL.md explaining that the *-leaf accepts returning audio via matchesRoutable on its inbound-accept gate (hasPrefixRoute cannot serve this role since * is not in m_all_prefixes). - Fix tests/TESTS.md: remove non-existent topology_routable.py reference (routable topology lives in topology.py/ROUTABLE_REFLECTORS, generated by python3 generate_configs.py → docker-compose.routable.yml); correct "two hops away" to "two transit nodes away (three trunk links)". --- README.md | 45 ++++++++++++++-------- docs/PEER_PROTOCOL.md | 13 ++++--- src/svxlink/reflector/svxreflector.conf.in | 6 +-- tests/TESTS.md | 6 +-- 4 files changed, 43 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 0bfcd65..46f459d 100644 --- a/README.md +++ b/README.md @@ -287,37 +287,50 @@ pattern. logic — a blacklisted TG is never forwarded, accepted, or advertised as interest, regardless of `ROUTABLE_PREFIXES`. -**Ownership caveat:** do not set a routable prefix that is a longer -decimal-string match of a TG this reflector itself owns — the -longest-prefix-match ownership check would then incorrectly route that TG -away from the local owner. Keep routable prefixes pointed at TGs owned by -other reflectors (the same discipline that already applies to `REMOTE_PREFIX`). +**Delegation note:** a routable prefix more specific than this reflector's own +`LOCAL_PREFIX` intentionally delegates that sub-range elsewhere +(longest-prefix-match: the more specific routable prefix wins). Point such a +prefix at the reflector that actually owns those TGs. -Example — three-hop chain where `leaf` (prefix `240`) needs to reach TG `2630xx` -owned by `far` (prefix `263`), transiting through `natl` (prefix `262`): +Example — four-node chain where `leaf` (prefix `222100`) needs to reach TG +`263xx` owned by `far` (prefix `263`), transiting through both `natlit` +(prefix `222`) and `natlde` (prefix `262`): ```ini -# On leaf — default route via the only uplink -[TRUNK_LEAF_NATL] -HOST=natl.example.com -SECRET=secret_leaf_natl -REMOTE_PREFIX=262 +# On leaf — default route via the only uplink toward natlit +[TRUNK_LEAF_NATLIT] +HOST=natlit.example.com +SECRET=secret_leaf_natlit +REMOTE_PREFIX=222 ROUTABLE_PREFIXES=* -# On natl — explicit transit toward 263 via the natlde link -[TRUNK_NATL_NATLDE] +# On natlit — explicit transit toward 263 via the natlde link +[TRUNK_NATLIT_NATLDE] HOST=natlde.example.com -SECRET=secret_natl_natlde +SECRET=secret_natlit_natlde REMOTE_PREFIX=262 ROUTABLE_PREFIXES=263 -# On natlde — native REMOTE_PREFIX=263 already covers the last hop +# On natlde — transit 263 back toward natlit (return path) and onward to far +[TRUNK_NATLDE_NATLIT] +HOST=natlit.example.com +SECRET=secret_natlit_natlde +REMOTE_PREFIX=222 +ROUTABLE_PREFIXES=263 + [TRUNK_NATLDE_FAR] HOST=far.example.com SECRET=secret_natlde_far REMOTE_PREFIX=263 +# far owns 263 natively — no ROUTABLE_PREFIXES needed on this last hop ``` +The `*` wildcard on leaf's uplink also handles the return leg: leaf advertises +interest in `263xx` toward natlit via `MsgPeerTgInterest`, and — on top of that +— accepts the returning audio via the wildcard match (`matchesRoutable`) on its +inbound-accept gate, since `*` is excluded from the mesh prefix set and +`hasPrefixRoute` alone cannot serve this role. + ### Network requirements **Trunk links** require **mutual reachability**: each reflector both listens for diff --git a/docs/PEER_PROTOCOL.md b/docs/PEER_PROTOCOL.md index 9bb90b4..d8a9989 100644 --- a/docs/PEER_PROTOCOL.md +++ b/docs/PEER_PROTOCOL.md @@ -229,7 +229,10 @@ lowest-precedence prefix — a real prefix always wins — and is **never** adde - The **return leg** to a `*`-leaf relies on peer interest: because `*` matches every TG in the send/interest gate, the leaf advertises interest in the TG toward the parent (`MsgPeerTgInterest`), and the parent's `isPeerInterestedTG` carries the - return audio back without needing any routable entry on the parent side. + return audio back. The leaf also accepts the returning audio via the wildcard match + (`matchesRoutable`) on its inbound-accept gate — because `*` is never added to + `m_all_prefixes`, `hasPrefixRoute` cannot serve this role, so the wildcard accept + is the mechanism that lets the leaf receive the return audio. A startup `WARNING` is emitted when `*` is set on a reflector with more than one trunk, as that is outside the intended single-uplink leaf pattern and may produce @@ -239,10 +242,10 @@ unexpected fanout behaviour. logic. A blacklisted TG is dropped before `isSharedTG`, `hasPrefixRoute`, or interest advertisement are consulted. -**Ownership caveat.** A routable prefix must not be a longer decimal-string match -of a TG the local reflector owns: `isSharedTG` (and `hasPrefixRoute`) would then -route that TG away from the local owner. Keep routable prefixes pointed at TGs -owned by other reflectors — the same discipline that governs `REMOTE_PREFIX`. +**Delegation note.** A routable prefix more specific than this reflector's own +`LOCAL_PREFIX` intentionally delegates that sub-range elsewhere: longest-prefix-match +honors it and the more specific routable prefix wins. Point such a prefix at the +reflector that actually owns those TGs. ### Cluster TGs diff --git a/src/svxlink/reflector/svxreflector.conf.in b/src/svxlink/reflector/svxreflector.conf.in index faa178f..6b99fa7 100644 --- a/src/svxlink/reflector/svxreflector.conf.in +++ b/src/svxlink/reflector/svxreflector.conf.in @@ -135,9 +135,9 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py # sibling reflector (e.g. reach 263 via the 262 peer). "*" is never relayed # between trunks (loop-safe) and only affects this node's local clients; # explicit prefixes transit toward the owner and must be declared on each hop. -# Keep routable prefixes pointed at TGs owned by OTHER reflectors (do not let a -# routable prefix be a longer match of a TG this reflector owns). -# BLACKLIST_TGS still vetoes regardless of routable settings. +# A more specific routable prefix intentionally delegates that sub-range to the +# declared peer (longest-prefix-match honors it); point it at the reflector +# that actually owns those TGs. BLACKLIST_TGS still vetoes regardless. #ROUTABLE_PREFIXES=263 # backbone transit toward 263 #ROUTABLE_PREFIXES=* # regional leaf default route via this uplink diff --git a/tests/TESTS.md b/tests/TESTS.md index 57613c9..c1e9153 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -12,7 +12,7 @@ The integration tests verify the trunk protocol, satellite links, twin (HA-pair) A separate harness (`run_redis_tests.sh`) runs `test_redis.py` (13 tests) against a single-reflector + Redis stack. See [Redis Integration Tests](#redis-integration-tests) below. -A separate harness runs `test_routable.py` (2 tests) against a dedicated routable-prefix topology. See [Routable Prefixes](#routable-prefixes) below. +A separate stack runs `test_routable.py` (2 tests) against a dedicated routable-prefix topology (defined in `topology.py`). See [Routable Prefixes](#routable-prefixes) below. **Requirements:** Docker, Docker Compose, Python 3.7+ (stdlib only, no pip packages). @@ -133,7 +133,7 @@ Internal port for `[TWIN]` is always 5304; satellite is 5303. | `docker-compose.test.yml` | Generated compose file (do not edit manually) | | `topology_redis.py` | Topology for the Redis test harness (single reflector + Redis). | | `generate_redis_configs.py` | Generates `configs-redis/*.conf` and `docker-compose.redis.yml`. | -| `test_routable.py` | Routable-prefix tests (2 cases): explicit multi-hop transit (forward + return) and `*` wildcard with blacklist veto. Runs on a dedicated compose stack generated from `topology_routable.py`. | +| `test_routable.py` | Routable-prefix tests (2 cases): explicit multi-hop transit (forward + return) and `*` wildcard with blacklist veto. Runs on a dedicated compose stack; configs and `docker-compose.routable.yml` are generated by `python3 generate_configs.py` (routable topology defined in `topology.py` under `ROUTABLE_REFLECTORS`), then started via `docker compose -f docker-compose.routable.yml up -d --build` and exercised with `python3 -m pytest test_routable.py`. | | `test_redis.py` | Redis-backed config-store tests (13 cases): users, trunk filters, live-state hashes, outage/resync, import idempotence, peer-node mirroring + sanitization, dynamic trunk add/remove. | | `run_redis_tests.sh` | Redis test orchestrator with `up`/`test`/`down`/`all` subcommands. | | `configs-redis/` | Generated Redis-harness configs (do not edit manually) | @@ -273,7 +273,7 @@ Run separately via `test_routable.py` against a dedicated topology. | # | Test | What it verifies | |---|------|-----------------| -| R1 | Explicit transit forward + return | A client on a leaf reflector activates a TG owned by a far reflector two hops away; audio traverses both transit hops (explicit `ROUTABLE_PREFIXES` on each intermediate trunk) and the return audio reaches the leaf via peer interest | +| R1 | Explicit transit forward + return | A client on a leaf reflector activates a TG owned by a far reflector two transit nodes away (three trunk links); audio traverses both transit hops (explicit `ROUTABLE_PREFIXES` on each intermediate trunk) and the return audio reaches the leaf via peer interest | | R2 | `*` wildcard + blacklist veto | A client on a `*`-configured leaf reaches a remote TG via its single uplink; a TG listed in `BLACKLIST_TGS` on the same link is dropped regardless of the wildcard, confirming blacklist-before-routable evaluation order | ### Twin Protocol (HA-pair) From 66f88a2f0042f5e6f75a496f71c0ad8d41b2c18b Mon Sep 17 00:00:00 2001 From: Audric Date: Mon, 15 Jun 2026 21:49:19 +0200 Subject: [PATCH 10/10] docs(routable): fix README link section-name match; note restart semantics; tighten wildcard wording --- README.md | 10 ++++++++-- docs/PEER_PROTOCOL.md | 5 +++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 46f459d..4e4e303 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,10 @@ interest, regardless of `ROUTABLE_PREFIXES`. (longest-prefix-match: the more specific routable prefix wins). Point such a prefix at the reflector that actually owns those TGs. +**Runtime note:** the mesh-wide prefix set used for transit is built at startup, +so changing `ROUTABLE_PREFIXES` takes full effect on reflector restart (as with +`REMOTE_PREFIX`). + Example — four-node chain where `leaf` (prefix `222100`) needs to reach TG `263xx` owned by `far` (prefix `263`), transiting through both `natlit` (prefix `222`) and `natlde` (prefix `262`): @@ -311,8 +315,10 @@ SECRET=secret_natlit_natlde REMOTE_PREFIX=262 ROUTABLE_PREFIXES=263 -# On natlde — transit 263 back toward natlit (return path) and onward to far -[TRUNK_NATLDE_NATLIT] +# On natlde — transit 263 back toward natlit (return path). +# The section name MUST be identical on both ends of a link (see section 4), +# so natlde's trunk to natlit reuses the same [TRUNK_NATLIT_NATLDE] name. +[TRUNK_NATLIT_NATLDE] HOST=natlit.example.com SECRET=secret_natlit_natlde REMOTE_PREFIX=222 diff --git a/docs/PEER_PROTOCOL.md b/docs/PEER_PROTOCOL.md index d8a9989..f9ee7e3 100644 --- a/docs/PEER_PROTOCOL.md +++ b/docs/PEER_PROTOCOL.md @@ -221,8 +221,9 @@ participate in longest-prefix-match just like native prefixes: lowest-precedence prefix — a real prefix always wins — and is **never** added to `m_all_prefixes`. As a result: -- `isSharedTG` admits any TG via a `*`-configured link for local-client forwarding - and interest advertisement. +- `isSharedTG` admits via a `*`-configured link any TG not claimed by a longer + real prefix in `m_all_prefixes`, for local-client forwarding and interest + advertisement (a real prefix always wins over the zero-length wildcard). - `hasPrefixRoute` is **not** set for `*`-matched TGs, so `shouldRelayInbound` does not trigger the gateway arm. Wildcard-routed frames are delivered locally but never transited between trunks.