diff --git a/.gitignore b/.gitignore index f9388ab..ab5ab4a 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ _deps/ # Claude .claude/ CLAUDE.md +docs/superpowers/ # Test generated files (regenerated by tests/generate_configs.py) tests/configs/ diff --git a/docs/TRUNK_PROTOCOL.md b/docs/TRUNK_PROTOCOL.md index 0d3659d..2b42234 100644 --- a/docs/TRUNK_PROTOCOL.md +++ b/docs/TRUNK_PROTOCOL.md @@ -95,7 +95,7 @@ forwarded to **all** trunk peers regardless of `LOCAL_PREFIX` or `REMOTE_PREFIX` The routing decision in `TrunkLink` is: ``` -Sending: if isClusterTG(tg) or isSharedTG(tg) → send to peer +Sending: if isClusterTG(tg) or isSharedTG(tg) or isPeerInterestedTG(tg) → send to peer Receiving: if isClusterTG(tg) or isOwnedTG(tg) → accept from peer Otherwise: drop silently ``` @@ -104,9 +104,12 @@ This check is applied **independently on both sides** of each trunk link, using different prefix checks appropriate to each direction: - **Sending side:** `TrunkLink::onLocalTalkerStart`, `onLocalAudio`, and - `onLocalFlush` check `isSharedTG(tg) || isClusterTG(tg)` before sending. - `isSharedTG` matches the TG against the **remote** peer's prefix — i.e. it - only forwards TGs that belong to the peer. + `onLocalFlush` check `isSharedTG(tg) || isClusterTG(tg) || + isPeerInterestedTG(tg)` before sending. `isSharedTG` matches the TG + against the **remote** peer's prefix — i.e. it forwards TGs that belong + to the peer. Additionally, `isPeerInterestedTG` matches TGs that the + peer has previously sent traffic for, enabling the return path for + bidirectional conversations (see below). - **Receiving side:** `TrunkLink::handleMsgTrunkTalkerStart`, `handleMsgTrunkAudio`, and `handleMsgTrunkFlush` check `isOwnedTG(tg) || isClusterTG(tg)` before accepting. `isOwnedTG` matches @@ -121,6 +124,24 @@ the receiving side silently ignores the traffic — this is normal operation, no a misconfiguration. Only reflectors that both subscribe to a given cluster TG will exchange audio for it. +### Peer Interest Tracking + +Prefix-based routing is inherently one-directional: when a client on +reflector A visits a TG owned by reflector B, `isSharedTG` causes A to +forward to B. But when B's client replies on that same TG, B sees it as a +local TG and has no reason to forward back to A. + +To enable the return path, each `TrunkLink` tracks **peer interest**: when +a peer sends `MsgTrunkTalkerStart(tg)`, the receiving side records that the +peer has active clients on that TG. From that point, local talker activity +on the same TG is also forwarded to the peer via `isPeerInterestedTG`. + +Interest is refreshed on each `MsgTrunkAudio` received for the TG (keeping +it alive during long transmissions). It expires after 10 minutes of +inactivity on that TG from the peer, and is cleared immediately on trunk +disconnect. The interest map is per-link — disconnecting one peer does not +affect interest tracked for other peers. + ### Satellite Links — No TG Filtering Satellite links (`SatelliteClient` / `SatelliteLink`) do **not** apply any TG diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 60846f6..eb8b390 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2440,7 +2440,9 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, broadcastMsg(MsgTalkerStop(tg, old_cs), ReflectorClient::mkAndFilter( ge_v2_client_filter, - ReflectorClient::TgFilter(tg))); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg)))); broadcastUdpMsg(MsgUdpFlushSamples(), ReflectorClient::TgFilter(tg)); } @@ -2450,7 +2452,9 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, broadcastMsg(MsgTalkerStart(tg, new_cs), ReflectorClient::mkAndFilter( ge_v2_client_filter, - ReflectorClient::TgFilter(tg))); + ReflectorClient::mkOrFilter( + ReflectorClient::TgFilter(tg), + ReflectorClient::TgMonitorFilter(tg)))); } // Forward trunk talker events to connected satellites diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index deec319..d6efd20 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -36,6 +36,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include #include #include +#include /**************************************************************************** @@ -260,6 +261,17 @@ bool TrunkLink::isOwnedTG(uint32_t tg) const } /* TrunkLink::isOwnedTG */ +bool TrunkLink::isPeerInterestedTG(uint32_t tg) const +{ + auto it = m_peer_interested_tgs.find(tg); + if (it == m_peer_interested_tgs.end()) + { + return false; + } + return (std::time(nullptr) - it->second) < PEER_INTEREST_TIMEOUT_S; +} /* TrunkLink::isPeerInterestedTG */ + + Json::Value TrunkLink::statusJson(void) const { Json::Value obj(Json::objectValue); @@ -357,7 +369,8 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con, void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign) { if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg))) + (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg))) { return; } @@ -368,7 +381,8 @@ void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign) void TrunkLink::onLocalTalkerStop(uint32_t tg) { if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg))) + (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg))) { return; } @@ -385,7 +399,8 @@ void TrunkLink::onLocalTalkerStop(uint32_t tg) void TrunkLink::onLocalAudio(uint32_t tg, const std::vector& audio) { if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg)) || + (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg)) || m_yielded_tgs.count(tg)) { return; @@ -397,7 +412,8 @@ void TrunkLink::onLocalAudio(uint32_t tg, const std::vector& audio) void TrunkLink::onLocalFlush(uint32_t tg) { if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg))) + (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg))) { return; } @@ -599,6 +615,7 @@ void TrunkLink::handleMsgTrunkTalkerStart(std::istream& is) } m_peer_active_tgs.insert(tg); + m_peer_interested_tgs[tg] = std::time(nullptr); TGHandler::instance()->setTrunkTalkerForTG(tg, msg.callsign()); } /* TrunkLink::handleMsgTrunkTalkerStart */ @@ -647,6 +664,9 @@ void TrunkLink::handleMsgTrunkAudio(std::istream& is) return; } + // Refresh peer interest timestamp on audio to keep alive during long TX + m_peer_interested_tgs[tg] = std::time(nullptr); + // Rebuild a UDP audio message and broadcast to local clients on this TG MsgUdpAudio udp_msg(msg.audio()); m_reflector->broadcastUdpMsg(udp_msg, ReflectorClient::TgFilter(tg)); @@ -756,6 +776,21 @@ void TrunkLink::heartbeatTick(Async::Timer* t) } } + // Prune expired peer interest entries + time_t now = std::time(nullptr); + for (auto it = m_peer_interested_tgs.begin(); + it != m_peer_interested_tgs.end(); ) + { + if ((now - it->second) >= PEER_INTEREST_TIMEOUT_S) + { + it = m_peer_interested_tgs.erase(it); + } + else + { + ++it; + } + } + // Disable timer when both connections are down if (!m_con.isConnected() && m_inbound_con == nullptr) { @@ -790,6 +825,7 @@ void TrunkLink::clearPeerTalkerState(void) } m_peer_active_tgs.clear(); m_yielded_tgs.clear(); + m_peer_interested_tgs.clear(); } /* TrunkLink::clearPeerTalkerState */ diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 36d0f0f..e2385d5 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -34,6 +34,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include +#include #include #include #include @@ -155,6 +156,12 @@ class TrunkLink : public sigc::trackable // TGs currently held by this specific trunk peer (for scoped cleanup) std::set m_peer_active_tgs; + // TGs the peer has shown interest in (sent TalkerStart for). + // Maps TG number to last activity timestamp. Entries expire after + // PEER_INTEREST_TIMEOUT_S seconds of inactivity. + static const time_t PEER_INTEREST_TIMEOUT_S = 600; // 10 minutes + std::map m_peer_interested_tgs; + // Per-connection state bool m_ob_hello_received = false; unsigned m_ob_hb_tx_cnt = 0; @@ -170,6 +177,7 @@ class TrunkLink : public sigc::trackable bool isOutboundReady(void) const; bool isInboundReady(void) const; bool isOwnedTG(uint32_t tg) const; + bool isPeerInterestedTG(uint32_t tg) const; void onConnected(void); void onDisconnected(Async::TcpConnection* con, diff --git a/tests/test_trunk.py b/tests/test_trunk.py index 93f7d72..a6f2878 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -292,7 +292,10 @@ MSG_AUTH_CHALLENGE = 10 MSG_AUTH_RESPONSE = 11 MSG_AUTH_OK = 12 MSG_SERVER_INFO = 100 +MSG_TALKER_START = 104 +MSG_TALKER_STOP = 105 MSG_SELECT_TG = 106 +MSG_TG_MONITOR = 107 # Client UDP message types UDP_HEARTBEAT = 1 @@ -310,6 +313,8 @@ class ClientPeer: self._udp_seq = 0 self._drain_thread = None self._drain_stop = threading.Event() + self._tcp_msgs = [] + self._tcp_msgs_lock = threading.Lock() def connect(self, host: str, tcp_port: int, timeout: float = 5.0): self.tcp = socket.create_connection((host, tcp_port), timeout=timeout) @@ -383,11 +388,19 @@ class ClientPeer: assert hdr_type == UDP_HEARTBEAT, f"expected UDP heartbeat, got {hdr_type}" def select_tg(self, tg: int): - """Send MsgSelectTG to monitor a talk group.""" + """Send MsgSelectTG to switch to a talk group.""" payload = struct.pack("!H", MSG_SELECT_TG) payload += struct.pack("!I", tg) send_frame(self.tcp, payload) + def monitor_tgs(self, tgs: list): + """Send MsgTgMonitor with a set of TGs to passively monitor.""" + payload = struct.pack("!H", MSG_TG_MONITOR) + payload += struct.pack("!H", len(tgs)) + for tg in sorted(tgs): + payload += struct.pack("!I", tg) + send_frame(self.tcp, payload) + def recv_udp(self, timeout: float = 3.0): """Receive one UDP datagram, return (type, payload_bytes).""" self.udp.settimeout(timeout) @@ -426,14 +439,24 @@ class ClientPeer: self._udp_seq = (self._udp_seq + 1) & 0xFFFF self.udp.sendto(pkt, self._udp_target) + def get_tcp_msgs(self, msg_type=None): + """Return captured TCP messages, optionally filtered by type.""" + with self._tcp_msgs_lock: + if msg_type is None: + return list(self._tcp_msgs) + return [(t, d) for t, d in self._tcp_msgs if t == msg_type] + def _tcp_drain_loop(self): - """Background: read and discard TCP frames to keep connection alive.""" + """Background: read and capture TCP frames to keep connection alive.""" while not self._drain_stop.is_set(): try: if self.tcp is None: break self.tcp.settimeout(0.5) - recv_frame(self.tcp) + data = recv_frame(self.tcp) + msg_type = struct.unpack_from("!H", data, 0)[0] + with self._tcp_msgs_lock: + self._tcp_msgs.append((msg_type, data)) except (socket.timeout, ConnectionError, OSError): pass @@ -1105,6 +1128,96 @@ class TestTrunkIntegration(unittest.TestCase): wait_until(sat_gone, timeout=20.0, msg="satellite not cleared from /status after disconnect") + # ------------------------------------------------------------------ + # Test 17: Trunk talker notification reaches monitoring clients + # ------------------------------------------------------------------ + def test_17_bidirectional_trunk_conversation(self): + """Full bidirectional conversation through trunk. + + 1. Client-A on reflector-a (prefix 122) selects TG 121001 (owned by b) + 2. Client-B on reflector-b (prefix 121) monitors TG 121001 + 3. Client-A talks → audio reaches client-B via trunk (existing behavior) + 4. Client-B replies on TG 121001 → audio reaches client-A via trunk + (new: peer interest tracking enables the return path) + Also verifies that monitoring clients receive MsgTalkerStart for + trunk talkers (TgMonitorFilter fix). + """ + other = [n for n in REFLECTOR_NAMES if n != self.PRIMARY][0] + other_prefix = T.first_prefix(T.REFLECTORS[other]["prefix"]) + foreign_tg = int(other_prefix + "001") + + # Home TG for monitoring client on the OTHER reflector + home_prefix_other = T.first_prefix(T.REFLECTORS[other]["prefix"]) + home_tg_other = int(home_prefix_other + "000") + + # --- Client-A on PRIMARY reflector: selected on the foreign TG --- + client_a = ClientPeer() + a_port = T.mapped_client_port(self.PRIMARY) + client_a.connect(HOST, a_port) + client_a.authenticate(callsign=CLIENT_CALLSIGN, + password=CLIENT_PASSWORD) + client_a.setup_udp(udp_port=a_port) + client_a.select_tg(foreign_tg) + time.sleep(0.3) + + # --- Client-B on OTHER reflector: home TG, monitoring foreign TG --- + client_b = ClientPeer() + b_port = T.mapped_client_port(other) + client_b.connect(HOST, b_port) + client_b.authenticate(callsign=CLIENT2_CALLSIGN, + password=CLIENT2_PASSWORD) + client_b.setup_udp(udp_port=b_port) + client_b.select_tg(home_tg_other) + client_b.monitor_tgs([foreign_tg]) + time.sleep(0.3) + + try: + # === Phase 1: Client-A talks on foreign TG === + # This establishes peer interest on reflector-b's trunk to refl-a + for _ in range(5): + client_a.send_udp_audio(b"\xCA\xFE" * 80) + time.sleep(0.02) + client_a.send_udp_flush() + + # Wait for trunk propagation + time.sleep(2.0) + + # Client-B (monitoring) should have received MsgTalkerStart + talker_starts = client_b.get_tcp_msgs(MSG_TALKER_START) + found_start = any( + struct.unpack_from("!I", d, 2)[0] == foreign_tg + for _, d in talker_starts if len(d) >= 6 + ) + self.assertTrue(found_start, + f"Monitoring client-B did not receive MsgTalkerStart for " + f"TG {foreign_tg} via trunk") + + # === Phase 2: Client-B switches to foreign TG and replies === + client_b.select_tg(foreign_tg) + time.sleep(0.3) + + for _ in range(5): + client_b.send_udp_audio(b"\xBE\xEF" * 80) + time.sleep(0.02) + client_b.send_udp_flush() + + # Wait for trunk propagation (return path via interest tracking) + time.sleep(2.0) + + # Client-A should receive audio on the return path + msgs_a = client_a.recv_udp_all(timeout=2.0) + audio_count = sum(1 for t, _ in msgs_a if t == UDP_AUDIO) + flush_count = sum(1 for t, _ in msgs_a if t == UDP_FLUSH) + + self.assertGreater(audio_count + flush_count, 0, + f"Client-A on {self.PRIMARY} received no audio/flush for " + f"TG {foreign_tg} reply from {other} " + f"(peer interest tracking failed)") + + finally: + client_a.close() + client_b.close() + # --------------------------------------------------------------------------- # Custom test runner with clean, readable output diff --git a/tests/topology.py b/tests/topology.py index b452c49..7956e97 100644 --- a/tests/topology.py +++ b/tests/topology.py @@ -11,9 +11,9 @@ to regenerate configs/ and docker-compose.test.yml. The test harness REFLECTORS = { # name prefixes (list) host-port-base - "a": {"prefix": ["120", "2", "3"], "trunk_port_base": 15000}, - "b": {"prefix": ["40", "5"], "trunk_port_base": 25000}, - "c": {"prefix": ["6"], "trunk_port_base": 35000}, + "a": {"prefix": ["122"], "trunk_port_base": 15000}, + "b": {"prefix": ["121"], "trunk_port_base": 25000}, + "c": {"prefix": ["1"], "trunk_port_base": 35000}, } # Fake trunk peers used by the test harness. @@ -33,7 +33,7 @@ TEST_PEER_RX = { # 8000: no prefix match (not owned by any reflector) # 1201: starts with prefix "120" (overlaps with reflector-a's ownership) # 9999: starts with test peer prefix "9" -CLUSTER_TGS = [8000, 1201, 9999] +CLUSTER_TGS = [222, 999] # Satellite test config (parent is the first reflector in REFLECTORS) SATELLITE = {