#!/usr/bin/env python3 """Two sections must never use the same port. A port collision is the most misleading failure this suite can produce: the second router dies with "Address already in use", the checks then fail with a message about its behaviour ("missing 'served by POOR'"), and the next person debugs the wrong file. Two collisions happened on 2026-11-18: a new stub on 9995 (section 16 owns it) and a new router on PORT+16 (ctx-vision owns it). The scan covers what actually binds: `listen :` and `stub `. Ports that only appear as a base URL or in a throwaway `printf` config are not listeners and are ignored. """ import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent ASSIGN = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.+)$") EXPR = re.compile(r"^\$\(\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\+\s*(\d+)\s*\)\)$") VAR = re.compile(r"^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$") LISTEN = re.compile(r"\blisten\s+[^:\s]+:(\S+)") STUB = re.compile(r"(?:\S*/)?tests/stub\s+(\S+)") def assignments(text): for line in text.splitlines(): line = line.split("#", 1)[0] for part in line.split(";"): m = ASSIGN.match(part.strip()) if m: yield m.group(1), m.group(2).strip().strip("\"'") def resolve(tok, values): tok = tok.strip().strip("\"'") if tok.isdigit(): return int(tok) m = EXPR.match(tok) if m and m.group(1) in values: return values[m.group(1)] + int(m.group(2)) m = VAR.match(tok) if m: return values.get(m.group(1)) return None def main(): sources = {p.name: p.read_text() for p in sorted(ROOT.glob("*.sh"))} values = {} # Fixed point: a variable may be defined in a file sourced later, and may # itself be $((OTHER+7)). for _ in range(8): for text in sources.values(): for name, raw in assignments(text): v = resolve(raw, values) if v is not None: values[name] = v sites = {} unresolved = 0 for name, text in sources.items(): # A variable can be reassigned in the same file (RDP is one port for # the stub and another for the router later on); resolve in file order # so each site sees the value it really had. local = dict(values) for no, line in enumerate(text.splitlines(), 1): for var, raw in assignments(line): v = resolve(raw, local) if v is not None: local[var] = v if "printf" in line: continue # throwaway configs that are only --check'ed m = LISTEN.search(line) or STUB.search(line) if not m: continue port = resolve(m.group(1), local) if port is None: unresolved += 1 continue sites.setdefault(port, []).append(f"{name}:{no}") dups = {p: where for p, where in sites.items() if len(where) > 1} if dups: print("port collision in the test suite:", file=sys.stderr) for port in sorted(dups): print(f" {port}: {', '.join(dups[port])}", file=sys.stderr) return 1 if unresolved: print(f"check_ports: {unresolved} listener(s) use a port this scan " "cannot resolve (checked the rest)", file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())