From 5da075f150f11ff790504e7eae04fd80939e26e8 Mon Sep 17 00:00:00 2001 From: Audric Date: Fri, 3 Jul 2026 18:17:16 +0200 Subject: [PATCH] feat(alias): add LOCAL_ALIASES to re-home short local TGs under an owned prefix Re-home a short local talk group (e.g. 8) under the reflector's own owned prefix as a globally-unique number (e.g. 2620008) via a single [GLOBAL] LOCAL_ALIASES entry, so it routes across the trunk mesh like any owned TG while local users keep dialing the short number. - Config: LOCAL_ALIASES=localTG:aliasTG[/dir] (dir in|out, omitted = two-way); aliasTG must be owned by a LOCAL_PREFIX. Rejects unowned alias, an owned short side, duplicate short keys, and numeric overflow. - Boundary rewrite: prefix routing / owner-relay / peer-interest run on the long owned number; local delivery and talker arbitration run on the short number, bridged in the four inbound trunk handlers. - Rewrite-on-select folds a client that dials the long number onto the short number (select + monitor), so the two are one conversation locally and on the mesh. - Twin: external-talker notify uses the short number to match the audio mirror; disconnect cleanup folds to short so an aliased TG cannot wedge. - /status exposes local_aliases; satellite nodes warn that the setting is ignored (a local alias belongs on the mesh parent that owns the prefix). - Docs (PEER_PROTOCOL, CONCEPTS, conf template) and integration tests (tests/test_alias.py): two-way / in / out, rewrite-on-select, status, validation, disconnect-wedge, and duplicate-key coverage. --- docs/CONCEPTS.md | 41 ++ docs/PEER_PROTOCOL.md | 66 ++ src/svxlink/reflector/Reflector.cpp | 135 ++++ src/svxlink/reflector/Reflector.h | 30 + src/svxlink/reflector/ReflectorClient.cpp | 39 +- src/svxlink/reflector/TrunkLink.cpp | 112 +-- src/svxlink/reflector/svxreflector.conf.in | 6 + tests/TESTS.md | 31 +- tests/generate_configs.py | 6 + tests/run_tests.sh | 3 + tests/test_alias.py | 774 +++++++++++++++++++++ tests/topology.py | 8 +- 12 files changed, 1187 insertions(+), 64 deletions(-) create mode 100644 tests/test_alias.py diff --git a/docs/CONCEPTS.md b/docs/CONCEPTS.md index be16876..8e7dbb6 100644 --- a/docs/CONCEPTS.md +++ b/docs/CONCEPTS.md @@ -185,6 +185,47 @@ A listener on each is monitoring TG `25` (owned by **B**). --- +## 9. Local aliases: giving a short TG a global number + +Section 2 established the rule: a number is only reachable mesh-wide if its +prefix is owned by a reflector. That leaves a common problem — a club or +region wants a short, easy-to-remember local TG (e.g. `8`) that its own users +already dial, but also wants it reachable from anywhere in the mesh by a +proper globally-unique number under the reflector's own prefix (e.g. +`2620008` under `LOCAL_PREFIX=262`). Renumbering the local TG isn't +attractive, and neither is asking every peer to special-case it. + +`LOCAL_ALIASES` re-homes the short TG under the long, owned number: the +reflector treats `8` and `2620008` as the same conversation, uses the long +number for everything that crosses the mesh (routing, owner-relay), and the +short number for everything local clients see (selection, talker +arbitration). Local users keep dialing `8`; anyone elsewhere in the mesh +reaches the same traffic by dialing `2620008`. + +This sits alongside two other tools that shape TG reachability, and it's easy +to reach for the wrong one: + +- **`CLUSTER_TGS`** (section 5) is for TGs that **every** participating + reflector already agrees to broadcast everywhere, regardless of ownership — + a nationwide or mesh-wide talk group both sides opted into. +- **`TG_MAP`** (per `[TRUNK_x]` section) is a **per-link** curated remap: it + translates one TG number to another on a single trunk, so it must be + repeated identically on every link that needs it, and it is invisible to + hops beyond that one link. +- **Local alias** re-homes a curated subset of your own local TGs under a + number you already own, once, in `[GLOBAL]`. Because the long number is a + real, longest-prefix-matched, owned number, it routes across every hop in + the mesh exactly like any other owned TG — no per-link repetition, and no + cooperation required from peers or intermediate gateways. + +The underlying rule doesn't change: anything meant to be reachable +internationally must have one unique number that falls under a country (MCC) +prefix. A local alias doesn't create an exception to that — it's a way to let +a short, locally-convenient number satisfy it without forcing local users to +dial the long form. + +--- + ## Where to go next - [`PEER_PROTOCOL.md`](PEER_PROTOCOL.md) — the exact messages, handshake, and diff --git a/docs/PEER_PROTOCOL.md b/docs/PEER_PROTOCOL.md index f9ee7e3..dca75e4 100644 --- a/docs/PEER_PROTOCOL.md +++ b/docs/PEER_PROTOCOL.md @@ -726,6 +726,9 @@ The `/status` JSON endpoint includes a `trunks` object alongside `nodes`: "200": "LA8PV" } } + }, + "local_aliases": { + "8": { "alias": 2620008, "direction": "two-way" } } } ``` @@ -733,6 +736,14 @@ The `/status` JSON endpoint includes a `trunks` object alongside `nodes`: `active_talkers` contains only TGs with an active remote talker at the moment of the request. It is empty when no trunk conversations are in progress. +`local_aliases` is keyed by the short local TG and lists every configured +`LOCAL_ALIASES` entry: `alias` is the long, mesh-routable number it is +re-homed under, and `direction` is `"two-way"`, `"in"`, or `"out"` (see +"Local aliases" below). Note that this is the *local* view — `active_talkers` +above (and MQTT/Redis mirrors of it) report the long mesh number for aliased +traffic, since that is the identity used for routing, while local clients +experience the short number. + --- ## Configuration @@ -807,6 +818,61 @@ SECRET=secret_bc REMOTE_PREFIX=2 ``` +### Local aliases + +`LOCAL_ALIASES` (in `[GLOBAL]`) re-homes a short local TG under one of this +reflector's own `LOCAL_PREFIX` values, so it gets a globally-unique number +reachable from anywhere in the mesh while local users keep dialing the short +number: + +```ini +[GLOBAL] +LOCAL_PREFIX=262 +LOCAL_ALIASES=8:2620008,9:2620009/out,4001:2620400/in +``` + +**Syntax.** Comma-separated entries of the form `localTG:aliasTG[/dir]`. +`dir` is `in` or `out`; when omitted the alias is two-way. + +**Ownership rule.** `aliasTG` must fall under one of this reflector's +`LOCAL_PREFIX` values (checked with the same longest-prefix match used for +TG ownership everywhere else). An entry whose `aliasTG` is not owned is +rejected at config load — logged as an error and skipped — so a typo can +never claim a number the reflector doesn't own; the reflector still starts +and the remaining valid entries take effect. + +**Direction semantics.** +- **two-way** (no suffix): talk on the short local TG is exported to the + mesh under the long number, and traffic arriving from the mesh on the + long number is delivered to local clients on the short number. +- **`/out`**: local talk is exported to the mesh under the long number, but + inbound mesh traffic on the long number is *not* folded back to the short + number — the alias is publish-only. +- **`/in`**: mesh traffic on the long number is delivered locally on the + short number, but the short number is *not* exported to the mesh — the + alias is listen-only. + +**Rewrite-on-select.** A client — local or remote — that dials the long +alias number directly is folded onto the short number as soon as it +selects or monitors that TG, so `8` and `2620008` are always the same +conversation locally; there is no way to end up split across both numbers +on this reflector. + +**Routing on long, delivery on short.** The alias is a translation applied +at the local-client / trunk-mesh boundary, not a rename. All prefix +routing, owner-relay fan-out, and peer-interest bookkeeping run on the +*long* number, because that is the identity the rest of the mesh sees and +uses for longest-prefix-match. All local delivery and talker arbitration +(which client currently holds the TG, PTT interruption, monitor filters, +mute) run on the *short* number, because that is what local clients +select and expect to see. One documented consequence: `/status.local_aliases` +(above) is the local, short-keyed view of the mapping, but +`/status.active_talkers` in a trunk's status block — and the equivalent +MQTT/Redis mirrors — report the *long* mesh number while local clients are +simultaneously experiencing the *short* number for the same transmission. +This is intentional: it reflects the two identities (mesh-routing vs. +local-delivery) the alias deliberately keeps separate. + --- ## Files Changed vs Upstream SvxLink diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 39a5a1e..ec68c58 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -31,7 +31,10 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include +#include +#include #include +#include #include #include #include @@ -530,6 +533,15 @@ bool Reflector::initialize(Async::Config &cfg) "accept child satellites; remove the [SATELLITE] block or " "unset SATELLITE_OF."); } + std::string aliases_probe; + if (cfg.getValue("GLOBAL", "LOCAL_ALIASES", aliases_probe) && + !aliases_probe.empty()) + { + geulog::warn("core", + "LOCAL_ALIASES is ignored on a satellite node (SATELLITE_OF is " + "set). A local alias must be configured on the parent reflector " + "that owns the prefix and participates in the trunk mesh."); + } m_satellite_client = new SatelliteClient(this, cfg); if (!m_satellite_client->initialize()) { @@ -1748,6 +1760,21 @@ void Reflector::refreshStatus(void) } m_status["cluster_tgs"] = cluster_arr; + { + Json::Value aliases(Json::objectValue); + for (const auto& kv : m_alias_select) // long -> short, one per alias + { + Json::Value a(Json::objectValue); + a["alias"] = kv.first; // routable long number + a["direction"] = + (m_alias_route.count(kv.second) && m_alias_deliver.count(kv.first)) + ? "two-way" + : (m_alias_route.count(kv.second) ? "out" : "in"); + aliases[std::to_string(kv.second)] = a; // keyed by short local number + } + m_status["local_aliases"] = aliases; + } + { Json::Value sats(Json::objectValue); for (auto& kv : m_satellite_con_map) @@ -2440,6 +2467,10 @@ void Reflector::initTrunkLinks(void) } } } + + // Parse local aliases now that m_local_prefixes and m_all_prefixes are + // both fully populated, since validation calls isLocalTG(). + parseLocalAliases(); } /* Reflector::initTrunkLinks */ @@ -3172,6 +3203,110 @@ bool Reflector::isLocalTG(uint32_t tg) const } /* Reflector::isLocalTG */ +void Reflector::parseLocalAliases(void) +{ + m_alias_route.clear(); + m_alias_deliver.clear(); + m_alias_select.clear(); + + std::string aliases_str; + if (!m_cfg->getValue("GLOBAL", "LOCAL_ALIASES", aliases_str) || + aliases_str.empty()) + { + return; + } + + std::istringstream ss(aliases_str); + std::string entry; + std::set seen_short; + while (std::getline(ss, entry, ',')) + { + // trim surrounding whitespace + size_t b = entry.find_first_not_of(" \t"); + size_t e = entry.find_last_not_of(" \t"); + if (b == std::string::npos) continue; + entry = entry.substr(b, e - b + 1); + + // split optional "/dir" suffix + std::string dir; + size_t slash = entry.find('/'); + if (slash != std::string::npos) + { + dir = entry.substr(slash + 1); + entry = entry.substr(0, slash); + } + if (!dir.empty() && dir != "in" && dir != "out") + { + geulog::error("core", "LOCAL_ALIASES: bad direction '", dir, + "' in entry (expected in|out); skipping"); + continue; + } + + size_t colon = entry.find(':'); + if (colon == std::string::npos) + { + geulog::error("core", "LOCAL_ALIASES: entry '", entry, + "' missing ':'; skipping"); + continue; + } + char* endp = nullptr; + errno = 0; + unsigned long local_tg = std::strtoul(entry.substr(0, colon).c_str(), + &endp, 10); + bool local_ok = (endp != nullptr && *endp == '\0' && local_tg > 0 && + errno != ERANGE); + endp = nullptr; + errno = 0; + unsigned long alias_tg = std::strtoul(entry.substr(colon + 1).c_str(), + &endp, 10); + bool alias_ok = (endp != nullptr && *endp == '\0' && alias_tg > 0 && + errno != ERANGE); + if (!local_ok || !alias_ok) + { + geulog::error("core", "LOCAL_ALIASES: non-numeric TG in entry '", + entry, "'; skipping"); + continue; + } + + if (!isLocalTG(static_cast(alias_tg))) + { + geulog::error("core", "LOCAL_ALIASES: alias TG ", alias_tg, + " is not under any LOCAL_PREFIX; rejecting alias ", + local_tg, ":", alias_tg); + continue; + } + + if (isLocalTG(static_cast(local_tg))) + { + geulog::error("core", "LOCAL_ALIASES: local TG ", local_tg, + " is itself owned by a LOCAL_PREFIX; the short side of an " + "alias must be a non-owned number; rejecting alias ", + local_tg, ":", alias_tg); + continue; + } + + uint32_t s = static_cast(local_tg); + uint32_t l = static_cast(alias_tg); + + if (seen_short.count(s)) + { + geulog::error("core", "LOCAL_ALIASES: duplicate local TG ", s, + "; keeping the first mapping, ignoring ", s, ":", l); + continue; + } + seen_short.insert(s); + + if (dir != "in") m_alias_route[s] = l; // two-way or /out publishes + if (dir != "out") m_alias_deliver[l] = s; // two-way or /in delivers + m_alias_select[l] = s; // reserve number in all cases + + geulog::info("core", "LOCAL_ALIAS ", s, " <-> ", l, + (dir.empty() ? " (two-way)" : + dir == "in" ? " (in)" : " (out)")); + } +} /* Reflector::parseLocalAliases */ + + bool Reflector::hasPrefixRoute(uint32_t tg) const { const std::string s = std::to_string(tg); diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 3261dca..e92c036 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -253,6 +253,29 @@ class Reflector : public sigc::trackable // Used to gate owner-relay fanout of trunk-received audio. bool isLocalTG(uint32_t tg) const; + // Local alias table (see docs/PEER_PROTOCOL.md "Local aliases"). A short + // local TG is re-homed under an owned prefix so it routes + // internationally. Populated from [GLOBAL] LOCAL_ALIASES. + // + // short -> long for the trunk wire (identity if not aliased) + uint32_t aliasToRoute(uint32_t tg) const + { + auto it = m_alias_route.find(tg); + return (it != m_alias_route.end()) ? it->second : tg; + } + // long -> short for local delivery (identity if not aliased or /out-only) + uint32_t aliasToLocal(uint32_t tg) const + { + auto it = m_alias_deliver.find(tg); + return (it != m_alias_deliver.end()) ? it->second : tg; + } + // long -> short for rewrite-on-select (identity if not aliased) + uint32_t aliasSelect(uint32_t tg) const + { + auto it = m_alias_select.find(tg); + return (it != m_alias_select.end()) ? it->second : tg; + } + // True iff any prefix in m_all_prefixes (local + every configured // [TRUNK_x] REMOTE_PREFIX) prefix-matches this TG. Used to gate // trunk-to-trunk fanout: a non-owner gateway forwards onward only if @@ -456,6 +479,12 @@ class Reflector : public sigc::trackable // initTrunkLinks() and refreshed by addTrunkLink/removeTrunkLink. std::vector m_local_prefixes; std::vector m_all_prefixes; + // Local alias table (see docs/PEER_PROTOCOL.md "Local aliases"). + // A short local TG is re-homed under an owned prefix so it routes + // internationally. Populated from [GLOBAL] LOCAL_ALIASES. + std::map m_alias_route; // short -> long (publish outbound) + std::map m_alias_deliver; // long -> short (deliver inbound) + std::map m_alias_select; // long -> short (rewrite-on-select, all dirs) // Tracks last-seen callsign set per peer_id so we can DEL dropped // callsigns from Redis when a peer's node list shrinks. std::map> m_peer_node_cache; @@ -540,6 +569,7 @@ class Reflector : public sigc::trackable std::vector collectAllTrunkPrefixes(void) const; void refreshStatus(void); void initTrunkLinks(void); + void parseLocalAliases(void); void initTrunkServer(void); void initTwinLink(void); void initTwinServer(void); diff --git a/src/svxlink/reflector/ReflectorClient.cpp b/src/svxlink/reflector/ReflectorClient.cpp index 7825ccc..37c133d 100644 --- a/src/svxlink/reflector/ReflectorClient.cpp +++ b/src/svxlink/reflector/ReflectorClient.cpp @@ -934,7 +934,18 @@ void ReflectorClient::handleSelectTG(std::istream& is) sendError("Illegal MsgSelectTG protocol message received"); return; } - if (msg.tg() != m_current_tg) + uint32_t sel_tg = msg.tg(); + if (m_reflector != nullptr) + { + uint32_t folded = m_reflector->aliasSelect(sel_tg); + if (folded != sel_tg) + { + geulog::info("client", m_callsign, ": alias-fold select TG #", sel_tg, + " -> #", folded); + sel_tg = folded; + } + } + if (sel_tg != m_current_tg) { auto talker = TGHandler::instance()->talkerForTG(m_current_tg); if (talker == this) @@ -949,7 +960,7 @@ void ReflectorClient::handleSelectTG(std::istream& is) sendUdpMsg(MsgUdpFlushSamples()); } - setTg(msg.tg()); + setTg(sel_tg); } } /* ReflectorClient::handleSelectTG */ @@ -964,18 +975,26 @@ void ReflectorClient::handleTgMonitor(std::istream& is) sendError("Illegal MsgTgMonitor protocol message received"); return; } - auto tgs = msg.tgs(); - auto it = tgs.cbegin(); - while (it != tgs.end()) + std::set tgs; + for (const auto& tg : msg.tgs()) { - const auto& tg = *it; - if (!TGHandler::instance()->allowTgMonitoring(this, tg) || (tg == 0)) + uint32_t mon_tg = tg; + if (m_reflector != nullptr) { - geulog::info("client", m_callsign, ": Not allowed to monitor TG #", tg); - tgs.erase(it++); + mon_tg = m_reflector->aliasSelect(mon_tg); + if (mon_tg != tg) + { + geulog::info("client", m_callsign, ": alias-fold monitor TG #", tg, + " -> #", mon_tg); + } + } + if (!TGHandler::instance()->allowTgMonitoring(this, mon_tg) || (mon_tg == 0)) + { + geulog::info("client", m_callsign, ": Not allowed to monitor TG #", + mon_tg); continue; } - ++it; + tgs.insert(mon_tg); } { std::ostringstream tglist; diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 0384a6d..d1e77c7 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -596,7 +596,8 @@ Json::Value TrunkLink::statusJson(void) const Json::Value talkers(Json::objectValue); for (uint32_t tg : m_peer_active_tgs) { - const std::string cs = TGHandler::instance()->trunkTalkerForTG(tg); + const std::string cs = + TGHandler::instance()->trunkTalkerForTG(m_reflector->aliasToLocal(tg)); if (!cs.empty()) { talkers[std::to_string(tg)] = cs; @@ -782,67 +783,71 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con, void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign) { - if (!isActive() || isBlacklisted(tg) || !isAllowed(tg)) return; - bool mapped = m_tg_map_out.count(tg) > 0; + if (!isActive()) return; + uint32_t rtg = m_reflector->aliasToRoute(tg); // short -> long for the mesh + if (isBlacklisted(rtg) || !isAllowed(rtg)) return; + bool mapped = m_tg_map_out.count(rtg) > 0; if (!mapped && - !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg)) + !isSharedTG(rtg) && !m_reflector->isClusterTG(rtg) && + !isPeerInterestedTG(rtg)) { return; } - sendMsg(MsgPeerTalkerStart(mapTgOut(tg), callsign)); + sendMsg(MsgPeerTalkerStart(mapTgOut(rtg), callsign)); } /* TrunkLink::onLocalTalkerStart */ void TrunkLink::onLocalTalkerStop(uint32_t tg) { - if (!isActive() || isBlacklisted(tg) || !isAllowed(tg)) return; - bool mapped = m_tg_map_out.count(tg) > 0; + if (!isActive()) return; + uint32_t rtg = m_reflector->aliasToRoute(tg); + if (isBlacklisted(rtg) || !isAllowed(rtg)) return; + bool mapped = m_tg_map_out.count(rtg) > 0; if (!mapped && - !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg)) + !isSharedTG(rtg) && !m_reflector->isClusterTG(rtg) && + !isPeerInterestedTG(rtg)) { return; } // If we cleared our local talker because we were yielding to this peer, // don't send TrunkTalkerStop — the peer already owns the TG. - if (m_yielded_tgs.count(tg)) + if (m_yielded_tgs.count(tg)) // yielded is keyed by the short/local number { return; } - sendMsg(MsgPeerTalkerStop(mapTgOut(tg))); + sendMsg(MsgPeerTalkerStop(mapTgOut(rtg))); } /* TrunkLink::onLocalTalkerStop */ void TrunkLink::onLocalAudio(uint32_t tg, const std::vector& audio) { - if (!isActive() || isBlacklisted(tg) || !isAllowed(tg) - || m_yielded_tgs.count(tg)) - { - return; - } - bool mapped = m_tg_map_out.count(tg) > 0; + if (!isActive() || m_yielded_tgs.count(tg)) return; + uint32_t rtg = m_reflector->aliasToRoute(tg); + if (isBlacklisted(rtg) || !isAllowed(rtg)) return; + bool mapped = m_tg_map_out.count(rtg) > 0; if (!mapped && - !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg)) + !isSharedTG(rtg) && !m_reflector->isClusterTG(rtg) && + !isPeerInterestedTG(rtg)) { return; } - sendMsg(MsgPeerAudio(mapTgOut(tg), audio)); + sendMsg(MsgPeerAudio(mapTgOut(rtg), audio)); } /* TrunkLink::onLocalAudio */ void TrunkLink::onLocalFlush(uint32_t tg) { - if (!isActive() || isBlacklisted(tg) || !isAllowed(tg)) return; - bool mapped = m_tg_map_out.count(tg) > 0; + if (!isActive()) return; + uint32_t rtg = m_reflector->aliasToRoute(tg); + if (isBlacklisted(rtg) || !isAllowed(rtg)) return; + bool mapped = m_tg_map_out.count(rtg) > 0; if (!mapped && - !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg)) + !isSharedTG(rtg) && !m_reflector->isClusterTG(rtg) && + !isPeerInterestedTG(rtg)) { return; } - sendMsg(MsgPeerFlush(mapTgOut(tg))); + sendMsg(MsgPeerFlush(mapTgOut(rtg))); } /* TrunkLink::onLocalFlush */ @@ -1086,34 +1091,36 @@ void TrunkLink::handleMsgPeerTalkerStart(std::istream& is) return; } + uint32_t deliver_tg = m_reflector->aliasToLocal(local_tg); + // Tie-break: if we already have a local talker on this TG, decide who wins. // Lower priority value wins. If equal (shouldn't happen), local wins. - ReflectorClient* local_talker = TGHandler::instance()->talkerForTG(local_tg); + ReflectorClient* local_talker = TGHandler::instance()->talkerForTG(deliver_tg); if (local_talker != nullptr) { if (m_priority <= m_peer_priority) { // We win — ignore peer's claim - geulog::info("trunk", m_section, ": TG #", local_tg, + geulog::info("trunk", m_section, ": TG #", deliver_tg, " conflict — local wins (our priority=", m_priority, " <= peer=", m_peer_priority, ")"); return; } // We defer — clear local talker and accept remote - geulog::info("trunk", m_section, ": TG #", local_tg, + geulog::info("trunk", m_section, ": TG #", deliver_tg, " conflict — deferring to peer (our priority=", m_priority, " > peer=", m_peer_priority, ")"); - m_yielded_tgs.insert(local_tg); - TGHandler::instance()->setTalkerForTG(local_tg, nullptr); + m_yielded_tgs.insert(deliver_tg); + TGHandler::instance()->setTalkerForTG(deliver_tg, nullptr); // onTalkerUpdated will fire; Reflector must not re-send TrunkTalkerStart // for this TG since it's in m_yielded_tgs (checked in Reflector.cpp) } m_peer_active_tgs.insert(local_tg); m_peer_interested_tgs[local_tg] = std::time(nullptr); - TGHandler::instance()->setTrunkTalkerForTGViaPeer(local_tg, msg.callsign(), + TGHandler::instance()->setTrunkTalkerForTGViaPeer(deliver_tg, msg.callsign(), peerId()); - m_reflector->notifyExternalTrunkTalkerStart(local_tg, m_section, msg.callsign()); + m_reflector->notifyExternalTrunkTalkerStart(deliver_tg, m_section, msg.callsign()); // Prefix-routed fanout: forward to every other trunk peer if we have a // route for this TG in our prefix table. isSharedTG inside the per-trunk @@ -1151,10 +1158,12 @@ void TrunkLink::handleMsgPeerTalkerStop(std::istream& is) return; } - m_yielded_tgs.erase(local_tg); + uint32_t deliver_tg = m_reflector->aliasToLocal(local_tg); + + m_yielded_tgs.erase(deliver_tg); m_peer_active_tgs.erase(local_tg); - TGHandler::instance()->clearTrunkTalkerForTG(local_tg); - m_reflector->notifyExternalTrunkTalkerStop(local_tg, m_section); + TGHandler::instance()->clearTrunkTalkerForTG(deliver_tg); + m_reflector->notifyExternalTrunkTalkerStop(deliver_tg, m_section); // Prefix-routed fanout (mirrors talker-start): only fan out if we have // a route. Cluster TGs without a prefix match stay single-hop. @@ -1188,6 +1197,8 @@ void TrunkLink::handleMsgPeerAudio(std::istream& is) return; } + uint32_t deliver_tg = m_reflector->aliasToLocal(local_tg); + // Only forward audio if this peer has claimed the TG via TalkerStart if (m_peer_active_tgs.find(local_tg) == m_peer_active_tgs.end()) { @@ -1195,7 +1206,7 @@ void TrunkLink::handleMsgPeerAudio(std::istream& is) } // PTY-driven mute: drop audio if the current peer talker is muted - std::string cs = TGHandler::instance()->trunkTalkerForTG(local_tg); + std::string cs = TGHandler::instance()->trunkTalkerForTG(deliver_tg); if (!cs.empty() && isCallsignMuted(cs)) { return; @@ -1209,21 +1220,21 @@ void TrunkLink::handleMsgPeerAudio(std::istream& is) MsgUdpAudio udp_msg(msg.audio()); m_reflector->broadcastUdpMsg(udp_msg, ReflectorClient::mkOrFilter( - ReflectorClient::TgFilter(local_tg), + ReflectorClient::TgFilter(deliver_tg), ReflectorClient::mkAndFilter( - ReflectorClient::TgMonitorFilter(local_tg), + ReflectorClient::TgMonitorFilter(deliver_tg), ReflectorClient::mkAndFilter( ReflectorClient::PassiveObserverFilter(), - ReflectorClient::EarliestMonitorTalkerFilter(local_tg))))); + ReflectorClient::EarliestMonitorTalkerFilter(deliver_tg))))); // Forward trunk audio to connected satellites - m_reflector->forwardAudioToSatellitesExcept(nullptr, local_tg, msg.audio()); + m_reflector->forwardAudioToSatellitesExcept(nullptr, deliver_tg, msg.audio()); // Mirror inbound trunk audio to the [TWIN] partner so PAIRED inbound // (sticky on one twin) still reaches the non-sticky twin's local clients // and its satellites. TwinLink::handleMsgPeerAudio does not re-forward to // trunks, so no echo back to the originating peer. - m_reflector->forwardTrunkAudioToTwin(local_tg, msg.audio()); + m_reflector->forwardTrunkAudioToTwin(deliver_tg, msg.audio()); // Prefix-routed fanout (mirrors talker-start): only fan out if we have // a route. Cluster TGs without a prefix match stay single-hop. @@ -1256,20 +1267,22 @@ void TrunkLink::handleMsgPeerFlush(std::istream& is) return; } + uint32_t deliver_tg = m_reflector->aliasToLocal(local_tg); + m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), ReflectorClient::mkOrFilter( - ReflectorClient::TgFilter(local_tg), + ReflectorClient::TgFilter(deliver_tg), ReflectorClient::mkAndFilter( - ReflectorClient::TgMonitorFilter(local_tg), + ReflectorClient::TgMonitorFilter(deliver_tg), ReflectorClient::mkAndFilter( ReflectorClient::PassiveObserverFilter(), - ReflectorClient::EarliestMonitorTalkerFilter(local_tg))))); + ReflectorClient::EarliestMonitorTalkerFilter(deliver_tg))))); // Forward trunk flush to connected satellites - m_reflector->forwardFlushToSatellitesExcept(nullptr, local_tg); + m_reflector->forwardFlushToSatellitesExcept(nullptr, deliver_tg); // Mirror flush to the [TWIN] partner — pairs with the audio mirror above. - m_reflector->forwardTrunkFlushToTwin(local_tg); + m_reflector->forwardTrunkFlushToTwin(deliver_tg); // Prefix-routed fanout (mirrors talker-start): only fan out if we have // a route. Cluster TGs without a prefix match stay single-hop. @@ -1864,8 +1877,9 @@ void TrunkLink::clearPeerTalkerState(void) { for (uint32_t tg : m_peer_active_tgs) { - TGHandler::instance()->clearTrunkTalkerForTG(tg); - m_reflector->notifyExternalTrunkTalkerStop(tg, m_section); + uint32_t deliver_tg = m_reflector->aliasToLocal(tg); + TGHandler::instance()->clearTrunkTalkerForTG(deliver_tg); + m_reflector->notifyExternalTrunkTalkerStop(deliver_tg, m_section); } m_peer_active_tgs.clear(); m_yielded_tgs.clear(); diff --git a/src/svxlink/reflector/svxreflector.conf.in b/src/svxlink/reflector/svxreflector.conf.in index 6b99fa7..0f89f5a 100644 --- a/src/svxlink/reflector/svxreflector.conf.in +++ b/src/svxlink/reflector/svxreflector.conf.in @@ -13,6 +13,12 @@ LISTEN_PORT=5300 #CODECS=OPUS TG_FOR_V1_CLIENTS=999 #LOCAL_PREFIX=1 +# LOCAL_ALIASES — re-home short local TGs under an owned prefix so they are +# reachable internationally by their globally-unique number. Comma-separated +# entries "localTG:aliasTG[/dir]"; dir is "in" or "out" (omitted = two-way). +# The aliasTG MUST fall under a LOCAL_PREFIX or the entry is rejected at load. +# Local users keep dialing localTG; the trunk mesh sees aliasTG. +#LOCAL_ALIASES=8:2620008,9:2620009/out,4001:2620400/in #CLUSTER_TGS=222,2221,91 #RANDOM_QSY_RANGE=12399:100 #HTTP_SRV_PORT=8080 diff --git a/tests/TESTS.md b/tests/TESTS.md index 1b81e59..8cd801d 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -4,10 +4,11 @@ The integration tests verify the trunk protocol, satellite links, twin (HA-pair) protocol, Redis-backed config store, and end-to-end audio routing by spinning up reflector meshes in Docker Compose and connecting fake peers and clients from a Python test harness. -`run_tests.sh` runs in **three phases** (89 tests total): +`run_tests.sh` runs in **three phases** (98 tests total): 1. A 3-reflector trunk mesh + a satellite-mode reflector, exercising - `test_trunk.py` (52 tests), `test_mqtt_deltas.py` (7 tests), - `test_satellite_secrets.py` (5 tests), and `test_logging.py` (6 tests). + `test_trunk.py` (52 tests), `test_alias.py` (9 tests), + `test_mqtt_deltas.py` (7 tests), `test_satellite_secrets.py` (5 tests), + and `test_logging.py` (6 tests). 2. A 4-reflector twin topology exercising `test_twin.py` (17 tests). 3. A dedicated routable-prefix chain exercising `test_routable.py` (2 tests). See [Routable Prefixes](#routable-prefixes) below. @@ -26,7 +27,7 @@ bash run_tests.sh This will: 1. Generate the default configs and `docker-compose.test.yml` from `topology.py` 2. Build and start the 3-reflector mesh (+ a satellite-mode reflector) -3. Run `test_trunk.py` (52), then `test_mqtt_deltas.py` (7), `test_satellite_secrets.py` (5), and `test_logging.py` (6). When run in a terminal, `test_trunk.py` ends with an interactive TG prompt (see [Interactive Mode](#interactive-mode)) before the other suites run +3. Run `test_trunk.py` (52), then `test_alias.py` (9), `test_mqtt_deltas.py` (7), `test_satellite_secrets.py` (5), and `test_logging.py` (6). When run in a terminal, `test_trunk.py` ends with an interactive TG prompt (see [Interactive Mode](#interactive-mode)) before the other suites run 4. Tear down the default mesh and regenerate with `--topology twin` (4-reflector twin topology) 5. Rebuild the mesh and run `test_twin.py` (17 twin-protocol tests) 6. Tear down the twin mesh, regenerate with `--topology routable`, bring up @@ -56,6 +57,8 @@ reflector-a (prefix 122) ◄──► reflector-b (prefix 121) **Cluster TGs** (222, 999) are broadcast to all peers regardless of prefix ownership. +**Local aliases** (reflector-a only): `LOCAL_ALIASES=8:1220008,90:1220090/out,91:1220091/in` re-homes three short local TGs under a's own prefix `122` — see [Local Aliases](#local-aliases) below and `test_alias.py`. + Two fake trunk peers connect from the test harness: - **TRUNK_TEST** (prefix `9`) — primary sender for most tests - **TRUNK_TEST_RX** (prefix `8`) — passive receiver for isolation tests @@ -127,6 +130,7 @@ Internal port for `[TWIN]` is always 5304; satellite is 5303. | `topology.py` | Single source of truth — prefixes, ports, secrets, cluster TGs, test clients. Contains both the default mesh (`REFLECTORS`) and the `TWIN_REFLECTORS` / `TWIN_TRUNKS` definitions. | | `generate_configs.py` | Generates `configs/*.conf` and `docker-compose.test.yml` from topology. Supports `--topology default` (implicit) and `--topology twin`. | | `test_trunk.py` | Test harness: fake trunk peers, satellite peer, V2 client, 52 test cases, interactive loop. | +| `test_alias.py` | Local-alias tests (9 cases): two-way/`out`/`in` direction semantics, rewrite-on-select, `/status.local_aliases`, unowned-alias rejection at load. Runs on the default mesh; reuses `ClientPeer`/`get_status`/`wait_until` from `test_trunk.py`. See [Local Aliases](#local-aliases) below. | | `test_mqtt_deltas.py` | Peer-client liveness MQTT delta tests (7 cases): per-client connect/disconnect/rx events published as `peer//client//`, across the satellite axis and trunk-peer non-propagation. Runs on the default mesh. | | `test_satellite_secrets.py` | Per-satellite secret resolver tests (5 cases): `SECRET_` match accepts, mismatch rejects with no fallback, unknown id falls back to `[SATELLITE].SECRET`. Runs on the default mesh. | | `test_logging.py` | Logging-facade (`geulog::`) tests (6 cases): `LOG` PTY commands (SHOW/SET/RESET), level filtering, error rejection via the `/dev/shm/reflector_ctrl` PTY. Runs on the default mesh. | @@ -270,6 +274,25 @@ 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 | +### Local Aliases + +Phase 1 of `run_tests.sh`: `test_alias.py` on the default mesh. Reflector-a +carries `LOCAL_ALIASES=8:1220008,90:1220090/out,91:1220091/in`; reflector-b +(direct trunk peer, prefix `121`) plays the "peer abroad" whose clients dial +the long numbers directly (b has no alias table of its own). + +| # | Test | What it verifies | +|---|------|-----------------| +| 01 | Two-way — local delivery unaffected | Both nodes select the short TG `8`; plain same-reflector delivery still works, and `/status.nodes[*].tg == 8` for both | +| 02 | Two-way — reaches peer | A-node keys short TG `8`; a B-node that selected the long TG `1220008` (expressing interest) receives the audio — outbound `aliasToRoute` publish | +| 03 | Two-way — inbound folds to local | B-node keys the long TG `1220008` directly; an A-node monitoring short TG `8` receives it — inbound `aliasToLocal` delivery | +| 04 | `/out` — publishes, no inbound | Alias `90:1220090/out`: A's short TG `90` still reaches B, but B keying the long TG `1220090` is NOT delivered to an A-node monitoring short TG `90` | +| 05 | `/in` — folds inbound, no publish | Alias `91:1220091/in`: A's short TG `91` does NOT reach a B-node monitoring the long TG `1220091`, but B keying the long TG `1220091` IS delivered to an A-node on short TG `91` | +| 06 | Rewrite-on-select | A client selecting the long TG `1220008` directly is folded onto the short TG — `/status.nodes[].tg == 8` | +| 07 | `/status` exposes aliases | `/status.local_aliases` matches the configured table exactly, keyed by short TG with `alias` (long number) and `direction` | +| 08 | Reject unowned alias | A standalone reflector booted with `LOCAL_ALIASES=8:1220008,7:9990007` (`9990007` outside `LOCAL_PREFIX=122`) keeps the valid entry, rejects the invalid one (absent from `/status.local_aliases`, logged), and still starts | +| 09 | Multi-hop by number | Skipped on the default topology: the only extra hop (`d`, prefix `1219`) nests under b's prefix (`121`), not under a's owned prefix (`122`) that hosts the alias table, so peer-interest can't propagate through b to d without extra `ROUTABLE_PREFIXES` plumbing out of scope for this topology change | + ### Routable Prefixes Phase 3 of `run_tests.sh`: `test_routable.py` against a dedicated routable-prefix diff --git a/tests/generate_configs.py b/tests/generate_configs.py index dbfea17..133e978 100644 --- a/tests/generate_configs.py +++ b/tests/generate_configs.py @@ -25,6 +25,12 @@ def generate_reflector_conf(name: str) -> str: "TG_FOR_V1_CLIENTS=999", f"LOCAL_PREFIX={T.prefix_str(r['prefix'])}", f"CLUSTER_TGS={cluster_str}", + ] + # Optional local-alias re-homing (tests/test_alias.py). Only reflectors + # that declare "local_aliases" in topology.py get the line. + if r.get("local_aliases"): + lines.append(f"LOCAL_ALIASES={r['local_aliases']}") + lines += [ f"TRUNK_LISTEN_PORT={T.INTERNAL_TRUNK_PORT}", f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}", "COMMAND_PTY=/dev/shm/reflector_ctrl", diff --git a/tests/run_tests.sh b/tests/run_tests.sh index b4a85a1..6a44ae3 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -18,6 +18,9 @@ docker compose -f docker-compose.test.yml up -d --build --wait echo "=== Running integration tests ===" python3 test_trunk.py +echo "=== Running local-alias integration tests ===" +python3 test_alias.py -v + echo "=== Running MQTT-deltas integration tests ===" python3 test_mqtt_deltas.py diff --git a/tests/test_alias.py b/tests/test_alias.py new file mode 100644 index 0000000..fbe5cff --- /dev/null +++ b/tests/test_alias.py @@ -0,0 +1,774 @@ +#!/usr/bin/env python3 +"""Integration tests for the local-alias feature (LOCAL_ALIASES). + +A "local alias" re-homes a short local TG (e.g. `8`) under the reflector's +own owned prefix as a long, globally-routable number (e.g. `1220008`) so it +routes internationally like any owned TG, while local users keep dialing the +short number. See docs/PEER_PROTOCOL.md "Local aliases" for the full spec. + +Test topology: reflector `a` (default mesh, prefix `122`) is configured with + + LOCAL_ALIASES=8:1220008,90:1220090/out,91:1220091/in + + - 8 <-> 1220008 two-way (local talk exported to mesh AND foreign talk + heard locally) + - 90 <-> 1220090 /out (export only: a's TG 90 reaches the mesh; the + mesh's 1220090 is NOT delivered to a's local TG 90) + - 91 <-> 1220091 /in (import only: mesh's 1220091 is delivered to a's + local TG 91; a's local TG 91 is NOT published outward) + +Reflector `b` (prefix `121`) trunks directly to `a` and plays the role of +"peer abroad" whose clients dial the long numbers directly (b has no alias +table of its own — the raw long number IS the identity there). + +Reuses ClientPeer / get_status / wait_until / wait_for_reflector / +wait_for_trunk_connected from test_trunk.py — same harness, same assertion +style. Requires: Python 3.7+ (stdlib only) + topology.py + test_trunk.py +from this directory. +""" + +import os +import subprocess +import sys +import tempfile +import time +import unittest +from urllib.error import URLError + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import topology as T +from test_trunk import ( # noqa: E402 + ClientPeer, TrunkPeer, UDP_AUDIO, UDP_FLUSH, + CLIENT_CALLSIGN, CLIENT_PASSWORD, + CLIENT2_CALLSIGN, CLIENT2_PASSWORD, + CLIENT3_CALLSIGN, CLIENT3_PASSWORD, + HOST, REFLECTOR_NAMES, + get_status, wait_until, wait_for_reflector, wait_for_trunk_connected, +) + +# --------------------------------------------------------------------------- +# Topology constants +# --------------------------------------------------------------------------- + +ALIAS_OWNER = "a" # reflector carrying LOCAL_ALIASES (prefix 122) +ALIAS_PEER = "b" # peer reflector trunked directly to ALIAS_OWNER + +# Alias table configured on reflector 'a' (must match topology.py verbatim) +TG_TWOWAY_SHORT, TG_TWOWAY_LONG = 8, 1220008 +TG_OUT_SHORT, TG_OUT_LONG = 90, 1220090 +TG_IN_SHORT, TG_IN_LONG = 91, 1220091 + +EXPECTED_ALIASES = { + str(TG_TWOWAY_SHORT): {"alias": TG_TWOWAY_LONG, "direction": "two-way"}, + str(TG_OUT_SHORT): {"alias": TG_OUT_LONG, "direction": "out"}, + str(TG_IN_SHORT): {"alias": TG_IN_LONG, "direction": "in"}, +} + +TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) +SVXREFLECTOR_BIN = os.path.join( + os.path.dirname(TESTS_DIR), "build", "bin", "svxreflector") + + +def _http(name: str): + return (HOST, T.mapped_http_port(name)) + + +def _client_port(name: str): + return T.mapped_client_port(name) + + +def _peer_roster_tg(peer_name: str, owner_name: str, callsign: str): + """Return the TG a `peer_name` reflector sees for `callsign` in the + owner reflector's trunk roster (`/status.trunks[].nodes`), or None + if the callsign is not (yet) present. + + This is the observable used to verify the node's effective TG WITHOUT + the client having to send a MsgNodeInfo blob (the harness ClientPeer + never does): the per-client trunk node-list is emitted on client + connect/select and carries the reflector-side current TG — which is the + *folded* (short) number after rewrite-on-select. Same signal test_27b + in test_trunk.py relies on. + """ + section = T.trunk_section_name(owner_name, peer_name) + status = get_status(*_http(peer_name)) + nodes = status.get("trunks", {}).get(section, {}).get("nodes", []) + for n in nodes: + if n.get("callsign") == callsign: + return n.get("tg") + return None + + +# --------------------------------------------------------------------------- +# Test cases +# --------------------------------------------------------------------------- + +class TestLocalAlias(unittest.TestCase): + + @classmethod + def setUpClass(cls): + """Wait for the default mesh to be up with a<->b trunked.""" + D = "\033[2m" + G = "\033[32m" + RST = "\033[0m" + + sys.stderr.write(f" {D}waiting for reflectors...{RST}") + sys.stderr.flush() + for name in REFLECTOR_NAMES: + wait_for_reflector(*_http(name), timeout=90.0) + sys.stderr.write(f"\r\033[K {G}✔{RST} Reflectors up\n") + + sys.stderr.write(f" {D}waiting for mesh...{RST}") + sys.stderr.flush() + for name in REFLECTOR_NAMES: + for peer in REFLECTOR_NAMES: + if peer != name and T.should_trunk(name, peer): + wait_for_trunk_connected( + *_http(name), T.trunk_section_name(name, peer), + timeout=30.0) + sys.stderr.write(f"\r\033[K {G}✔{RST} Mesh connected\n") + sys.stderr.write(f"\033[2m{'-' * 50}\033[0m\n") + + # ------------------------------------------------------------------ + # Test 01: two-way alias — plain local same-TG delivery is unaffected + # ------------------------------------------------------------------ + def test_01_two_way_local_delivery(self): + """A local same-TG conversation on the short number 8 still works + exactly like any normal TG once an alias table is configured — + both nodes select the short number, and both nodes are tracked + reflector-side on TG 8 (observed via the trunk-peer roster, which + carries each client's effective reflector-side TG).""" + node1 = ClientPeer() + node2 = ClientPeer() + try: + port = _client_port(ALIAS_OWNER) + node1.connect(HOST, port) + node1.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + node1.setup_udp(udp_port=port) + node1.select_tg(TG_TWOWAY_SHORT) + + node2.connect(HOST, port) + node2.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + node2.setup_udp(udp_port=port) + node2.select_tg(TG_TWOWAY_SHORT) + + time.sleep(0.5) + node2.recv_udp_all(timeout=0.05) # drain bootstrap traffic + + for _ in range(6): + node1.send_udp_audio(b"\xAB\xCD" * 80) + time.sleep(0.02) + node1.send_udp_flush() + time.sleep(0.8) + + msgs = node2.recv_udp_all(timeout=1.0) + audio = sum(1 for t, _ in msgs if t == UDP_AUDIO) + flush = sum(1 for t, _ in msgs if t == UDP_FLUSH) + self.assertGreater(audio + flush, 0, + "node2 (short TG 8) received no audio from node1 — plain " + "same-reflector delivery broken by the presence of an " + "alias table") + + # Both clients are tracked on the short TG 8 reflector-side. + for cs in (CLIENT_CALLSIGN, CLIENT2_CALLSIGN): + wait_until( + lambda cs=cs: _peer_roster_tg(ALIAS_PEER, ALIAS_OWNER, cs) + == TG_TWOWAY_SHORT, + timeout=8.0, + msg=f"{cs} not tracked on TG {TG_TWOWAY_SHORT} in " + f"reflector-{ALIAS_PEER}'s view of reflector-" + f"{ALIAS_OWNER}'s roster") + finally: + node1.close() + node2.close() + + # ------------------------------------------------------------------ + # Test 02: two-way alias — local talk on the short TG reaches a peer + # ------------------------------------------------------------------ + def test_02_two_way_reaches_peer(self): + """A-node keys the short number 8; a B-node that expressed interest + in the long number 1220008 must hear it (published to the mesh + under the owned long number).""" + a_node = ClientPeer() + b_node = ClientPeer() + try: + b_port = _client_port(ALIAS_PEER) + b_node.connect(HOST, b_port) + b_node.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + b_node.setup_udp(udp_port=b_port) + b_node.select_tg(TG_TWOWAY_LONG) # expresses interest on B + + a_port = _client_port(ALIAS_OWNER) + a_node.connect(HOST, a_port) + a_node.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + a_node.setup_udp(udp_port=a_port) + a_node.select_tg(TG_TWOWAY_SHORT) + + # Let B's TG-interest advertisement (500 ms debounce) reach A. + time.sleep(1.2) + b_node.recv_udp_all(timeout=0.05) + + for _ in range(6): + a_node.send_udp_audio(b"\xBE\xEF" * 80) + time.sleep(0.02) + a_node.send_udp_flush() + time.sleep(1.2) + + msgs = b_node.recv_udp_all(timeout=1.0) + audio = sum(1 for t, _ in msgs if t == UDP_AUDIO) + flush = sum(1 for t, _ in msgs if t == UDP_FLUSH) + self.assertGreater(audio + flush, 0, + f"B-node (selected long TG {TG_TWOWAY_LONG}) received no " + f"audio from A's short TG {TG_TWOWAY_SHORT} — outbound " + f"alias publish (aliasToRoute) broken") + finally: + a_node.close() + b_node.close() + + # ------------------------------------------------------------------ + # Test 03: two-way alias — inbound long-number traffic folds to local + # ------------------------------------------------------------------ + def test_03_two_way_inbound_to_local(self): + """B-node keys the long number 1220008 directly; an A-node + monitoring the short number 8 must hear it (inbound delivery folds + the owned long number back onto the local short number).""" + a_node = ClientPeer() + b_node = ClientPeer() + try: + a_port = _client_port(ALIAS_OWNER) + a_node.connect(HOST, a_port) + a_node.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + a_node.setup_udp(udp_port=a_port) + a_node.select_tg(0) + a_node.monitor_tgs([TG_TWOWAY_SHORT]) + + b_port = _client_port(ALIAS_PEER) + b_node.connect(HOST, b_port) + b_node.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + b_node.setup_udp(udp_port=b_port) + b_node.select_tg(TG_TWOWAY_LONG) + + time.sleep(0.8) + a_node.recv_udp_all(timeout=0.05) + + for _ in range(6): + b_node.send_udp_audio(b"\xCA\xFE" * 80) + time.sleep(0.02) + b_node.send_udp_flush() + time.sleep(1.2) + + msgs = a_node.recv_udp_all(timeout=1.0) + audio = sum(1 for t, _ in msgs if t == UDP_AUDIO) + flush = sum(1 for t, _ in msgs if t == UDP_FLUSH) + self.assertGreater(audio + flush, 0, + f"A-node monitoring short TG {TG_TWOWAY_SHORT} received no " + f"audio from B's long TG {TG_TWOWAY_LONG} — inbound alias " + f"delivery (aliasToLocal) broken") + finally: + a_node.close() + b_node.close() + + # ------------------------------------------------------------------ + # Test 04: /out alias — publishes outbound, does not accept inbound + # ------------------------------------------------------------------ + def test_04_out_only_no_inbound(self): + """Alias 90:1220090/out. Outbound (A's short TG 90 -> mesh) still + works; inbound (mesh's long TG 1220090 -> A's short TG 90) must + NOT be delivered locally.""" + a_sender = ClientPeer() + a_monitor = ClientPeer() + b_node = ClientPeer() + try: + b_port = _client_port(ALIAS_PEER) + b_node.connect(HOST, b_port) + b_node.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + b_node.setup_udp(udp_port=b_port) + b_node.select_tg(TG_OUT_LONG) # primes B's interest for the leg below + + a_port = _client_port(ALIAS_OWNER) + a_sender.connect(HOST, a_port) + a_sender.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + a_sender.setup_udp(udp_port=a_port) + a_sender.select_tg(TG_OUT_SHORT) + + a_monitor.connect(HOST, a_port) + a_monitor.authenticate(callsign=CLIENT3_CALLSIGN, password=CLIENT3_PASSWORD) + a_monitor.setup_udp(udp_port=a_port) + a_monitor.select_tg(0) + a_monitor.monitor_tgs([TG_OUT_SHORT]) + + time.sleep(1.2) # let B's interest advertisement land at A + + # --- Outbound still publishes: A's short TG 90 -> B --- + b_node.recv_udp_all(timeout=0.05) + for _ in range(6): + a_sender.send_udp_audio(b"\x11\x22" * 80) + time.sleep(0.02) + a_sender.send_udp_flush() + time.sleep(1.2) + + out_msgs = b_node.recv_udp_all(timeout=1.0) + out_audio = sum(1 for t, _ in out_msgs if t == UDP_AUDIO) + out_flush = sum(1 for t, _ in out_msgs if t == UDP_FLUSH) + self.assertGreater(out_audio + out_flush, 0, + f"B-node received no audio for /out alias TG {TG_OUT_LONG} " + f"— outbound publish of a /out alias must still work") + + # --- Inbound must NOT be delivered: B's long TG -> A monitor --- + a_monitor.recv_udp_all(timeout=0.05) + for _ in range(6): + b_node.send_udp_audio(b"\x33\x44" * 80) + time.sleep(0.02) + b_node.send_udp_flush() + time.sleep(1.2) + + in_msgs = a_monitor.recv_udp_all(timeout=1.0) + in_audio = sum(1 for t, _ in in_msgs if t == UDP_AUDIO) + in_flush = sum(1 for t, _ in in_msgs if t == UDP_FLUSH) + self.assertEqual(in_audio + in_flush, 0, + f"A-node monitoring short TG {TG_OUT_SHORT} received " + f"{in_audio} audio / {in_flush} flush frames from the mesh " + f"— a /out-only alias must not deliver inbound traffic " + f"locally") + finally: + a_sender.close() + a_monitor.close() + b_node.close() + + # ------------------------------------------------------------------ + # Test 05: /in alias — folds inbound, does not publish outbound + # ------------------------------------------------------------------ + def test_05_in_only_no_publish(self): + """Alias 91:1220091/in. Outbound (A's short TG 91 -> mesh) must NOT + be published; inbound (mesh's long TG 1220091 -> A's short TG 91) + still folds and is delivered locally.""" + a_node = ClientPeer() + b_monitor = ClientPeer() + b_node = ClientPeer() + try: + a_port = _client_port(ALIAS_OWNER) + a_node.connect(HOST, a_port) + a_node.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + a_node.setup_udp(udp_port=a_port) + a_node.select_tg(TG_IN_SHORT) + + b_port = _client_port(ALIAS_PEER) + b_monitor.connect(HOST, b_port) + b_monitor.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + b_monitor.setup_udp(udp_port=b_port) + b_monitor.select_tg(0) + b_monitor.monitor_tgs([TG_IN_LONG]) + + time.sleep(0.8) + + # --- Outbound must NOT publish: A's short TG 91 -> mesh --- + b_monitor.recv_udp_all(timeout=0.05) + for _ in range(6): + a_node.send_udp_audio(b"\x55\x66" * 80) + time.sleep(0.02) + a_node.send_udp_flush() + time.sleep(1.2) + + out_msgs = b_monitor.recv_udp_all(timeout=1.0) + out_audio = sum(1 for t, _ in out_msgs if t == UDP_AUDIO) + out_flush = sum(1 for t, _ in out_msgs if t == UDP_FLUSH) + # NOTE: TG 91 is a plain local-only number (not owned, not cluster, + # not peer-shared), so absent the alias it is never exported anyway. + # This assertion therefore guards that an `/in` alias adds NO outbound + # route (m_alias_route is not populated for `/in`) — it does NOT prove + # active suppression of an otherwise-shareable TG, which `/in` by design + # does not do (cluster/shared publishing is independent of aliasing). + self.assertEqual(out_audio + out_flush, 0, + f"B-node monitoring long TG {TG_IN_LONG} received " + f"{out_audio} audio / {out_flush} flush frames from A's " + f"short TG {TG_IN_SHORT} — a /in-only alias must not " + f"publish outbound traffic") + + # --- Inbound still folds: B's long TG -> A's short TG --- + b_node.connect(HOST, b_port) + b_node.authenticate(callsign=CLIENT3_CALLSIGN, password=CLIENT3_PASSWORD) + b_node.setup_udp(udp_port=b_port) + b_node.select_tg(TG_IN_LONG) + time.sleep(0.5) + + a_node.recv_udp_all(timeout=0.05) + for _ in range(6): + b_node.send_udp_audio(b"\x77\x88" * 80) + time.sleep(0.02) + b_node.send_udp_flush() + time.sleep(1.2) + + in_msgs = a_node.recv_udp_all(timeout=1.0) + in_audio = sum(1 for t, _ in in_msgs if t == UDP_AUDIO) + in_flush = sum(1 for t, _ in in_msgs if t == UDP_FLUSH) + self.assertGreater(in_audio + in_flush, 0, + f"A-node on short TG {TG_IN_SHORT} received no audio from " + f"B's long TG {TG_IN_LONG} — inbound fold for a /in alias " + f"is broken") + finally: + a_node.close() + b_monitor.close() + b_node.close() + + # ------------------------------------------------------------------ + # Test 06: rewrite-on-select — dialing the long number folds locally + # ------------------------------------------------------------------ + def test_06_rewrite_on_select(self): + """A client that selects the long alias number directly is folded + onto the short number — the reflector tracks it on TG 8, not + 1220008 (observed via the trunk-peer roster, whose per-client TG is + the reflector-side current TG after rewrite-on-select).""" + node = ClientPeer() + try: + port = _client_port(ALIAS_OWNER) + node.connect(HOST, port) + node.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + node.setup_udp(udp_port=port) + node.select_tg(TG_TWOWAY_LONG) # dial the LONG number directly + + wait_until( + lambda: _peer_roster_tg(ALIAS_PEER, ALIAS_OWNER, + CLIENT_CALLSIGN) == TG_TWOWAY_SHORT, + timeout=8.0, + msg=f"{CLIENT_CALLSIGN} selecting long TG {TG_TWOWAY_LONG} " + f"was not folded onto short TG {TG_TWOWAY_SHORT} " + f"(reflector-{ALIAS_PEER}'s roster view of reflector-" + f"{ALIAS_OWNER})") + # And it must NOT be tracked on the long number. + self.assertNotEqual( + _peer_roster_tg(ALIAS_PEER, ALIAS_OWNER, CLIENT_CALLSIGN), + TG_TWOWAY_LONG, + f"{CLIENT_CALLSIGN} is still tracked on the long TG " + f"{TG_TWOWAY_LONG} — rewrite-on-select fold did not apply") + finally: + node.close() + + # ------------------------------------------------------------------ + # Test 07: /status exposes the alias table + # ------------------------------------------------------------------ + def test_07_status_exposes_aliases(self): + """/status.local_aliases matches the configured LOCAL_ALIASES table + exactly: keyed by short number, with alias (long number) and + direction (two-way/out/in).""" + status = get_status(*_http(ALIAS_OWNER)) + aliases = status.get("local_aliases") + self.assertIsNotNone(aliases, "/status is missing 'local_aliases'") + self.assertEqual(aliases, EXPECTED_ALIASES, + f"/status.local_aliases does not match the configured table.\n" + f"expected: {EXPECTED_ALIASES}\ngot: {aliases}") + + # ------------------------------------------------------------------ + # Test 08: an alias TG outside any LOCAL_PREFIX is rejected at load + # ------------------------------------------------------------------ + def test_08_reject_unowned_alias(self): + """A LOCAL_ALIASES entry whose alias number is not under any + LOCAL_PREFIX is rejected at config load: absent from + /status.local_aliases, a rejection line is logged, and the + reflector still starts (other, valid entries are kept).""" + if not os.path.isfile(SVXREFLECTOR_BIN): + self.skipTest( + f"svxreflector binary not found at {SVXREFLECTOR_BIN}; " + f"run 'cmake --build build' first") + + with tempfile.TemporaryDirectory() as tmpdir: + pki_dir = os.path.join(tmpdir, "pki") + os.makedirs(pki_dir, exist_ok=True) + http_port = 19080 + listen_port = 19300 + trunk_port = 19302 + + # 8:1220008 is valid (under LOCAL_PREFIX=122); 7:9990007 is not + # (9990007 does not start with 122) and must be rejected. + config_content = f"""\ +[GLOBAL] +TIMESTAMP_FORMAT="%c" +LISTEN_PORT={listen_port} +TG_FOR_V1_CLIENTS=999 +LOCAL_PREFIX=122 +LOCAL_ALIASES=8:1220008,7:9990007 +TRUNK_LISTEN_PORT={trunk_port} +HTTP_SRV_PORT={http_port} +CERT_PKI_DIR={pki_dir} + +[SERVER_CERT] +COMMON_NAME=reflector-test-alias-reject + +[USERS] +N0TEST=TestGroup + +[PASSWORDS] +TestGroup=testpass +""" + conf_path = os.path.join(tmpdir, "svxreflector.conf") + with open(conf_path, "w") as f: + f.write(config_content) + + proc = subprocess.Popen( + [SVXREFLECTOR_BIN, f"--config={conf_path}"], + cwd=tmpdir, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + status = None + try: + status = self._wait_for_status(http_port, timeout=60.0) + finally: + proc.terminate() + try: + out, _ = proc.communicate(timeout=10.0) + except subprocess.TimeoutExpired: + proc.kill() + out, _ = proc.communicate(timeout=5.0) + + self.assertIsNotNone(status, + "reflector never reached a ready /status — cannot verify " + "alias rejection") + + aliases = status.get("local_aliases", {}) + self.assertIn("8", aliases, + "valid alias 8:1220008 is missing from /status.local_aliases " + "— it should have been kept alongside the rejected entry") + self.assertEqual(aliases["8"]["alias"], 1220008) + self.assertNotIn("7", aliases, + "unowned alias 7:9990007 should have been rejected and " + "absent from /status.local_aliases") + self.assertIn("not under any LOCAL_PREFIX", out, + f"expected rejection log line not found in reflector " + f"output; output tail:\n{out[-1000:]}") + + def test_08b_reject_duplicate_short_alias(self): + """Two LOCAL_ALIASES entries sharing the same short (local) TG must + keep only the FIRST mapping: the second is rejected at config load + with a 'duplicate local TG' log line, and /status.local_aliases + reflects the first entry's alias number.""" + if not os.path.isfile(SVXREFLECTOR_BIN): + self.skipTest( + f"svxreflector binary not found at {SVXREFLECTOR_BIN}; " + f"run 'cmake --build build' first") + + with tempfile.TemporaryDirectory() as tmpdir: + pki_dir = os.path.join(tmpdir, "pki") + os.makedirs(pki_dir, exist_ok=True) + http_port = 19081 + listen_port = 19301 + trunk_port = 19303 + + # Both 1220008 and 1220009 are valid alias targets under + # LOCAL_PREFIX=122, but they share the same short TG 8 — the + # second entry must be rejected, keeping the first (1220008). + config_content = f"""\ +[GLOBAL] +TIMESTAMP_FORMAT="%c" +LISTEN_PORT={listen_port} +TG_FOR_V1_CLIENTS=999 +LOCAL_PREFIX=122 +LOCAL_ALIASES=8:1220008,8:1220009 +TRUNK_LISTEN_PORT={trunk_port} +HTTP_SRV_PORT={http_port} +CERT_PKI_DIR={pki_dir} + +[SERVER_CERT] +COMMON_NAME=reflector-test-alias-dup + +[USERS] +N0TEST=TestGroup + +[PASSWORDS] +TestGroup=testpass +""" + conf_path = os.path.join(tmpdir, "svxreflector.conf") + with open(conf_path, "w") as f: + f.write(config_content) + + proc = subprocess.Popen( + [SVXREFLECTOR_BIN, f"--config={conf_path}"], + cwd=tmpdir, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + status = None + try: + status = self._wait_for_status(http_port, timeout=60.0) + finally: + proc.terminate() + try: + out, _ = proc.communicate(timeout=10.0) + except subprocess.TimeoutExpired: + proc.kill() + out, _ = proc.communicate(timeout=5.0) + + self.assertIsNotNone(status, + "reflector never reached a ready /status — cannot verify " + "duplicate-short-alias rejection") + + aliases = status.get("local_aliases", {}) + self.assertIn("8", aliases, + "short TG 8 is missing from /status.local_aliases — the " + "first mapping should have been kept") + self.assertEqual(aliases["8"]["alias"], 1220008, + "duplicate short TG 8 must keep the FIRST mapping " + "(1220008), not the second (1220009)") + self.assertIn("duplicate local TG", out, + f"expected duplicate-rejection log line not found in " + f"reflector output; output tail:\n{out[-1000:]}") + + @staticmethod + def _wait_for_status(port, timeout=60.0): + deadline = time.monotonic() + timeout + last_exc = None + while time.monotonic() < deadline: + try: + return get_status(HOST, port, timeout=2.0) + except (URLError, OSError, ValueError) as e: + last_exc = e + time.sleep(0.5) + raise AssertionError( + f"reflector on port {port} never became ready " + f"(last error: {last_exc})") + + # ------------------------------------------------------------------ + # Test 09: multi-hop delivery by number (skipped on this topology) + # ------------------------------------------------------------------ + def test_09_multi_hop_by_number(self): + """A C-node dialing the long alias number should hear an A-node on + the short number through a gateway B, with no alias/TG_MAP config + on B — proving the alias routes purely by number, hop by hop. + + The default mesh's only extra hop ('d', prefix 1219) is nested + UNDER b's prefix ('121' is a prefix of '1219') specifically so + gateway/peer-interest propagation works for TGs owned BY d (see + test_37_gateway_prefix_routing / test_39_passive_monitor_multihop + in test_trunk.py). Reflector 'a' (the alias owner here, prefix + '122') has no such nesting relationship with b/d's prefixes: a + d-side client selecting the long alias number (1220008) fails the + isSharedTG gate on d's single TRUNK_B_D link (1220008 does not + start with b's prefix '121'), so d never advertises interest in it + upstream, and b never learns to relay a's aliased traffic onward. + Reaching a true 3-hop scenario for an aliased TG would require + additional ROUTABLE_PREFIXES plumbing on TRUNK_B_D that is out of + scope for this alias-only topology change (adding it would also + risk perturbing test_37/test_39, which depend on the current + b<->d prefix relationship). + """ + self.skipTest( + "default topology's only 3rd hop ('d', prefix 1219) nests " + "under b's prefix (121), not under a's owned prefix (122) " + "that hosts the alias table; multi-hop-by-number for an " + "aliased TG would require additional ROUTABLE_PREFIXES " + "plumbing on TRUNK_B_D that is out of scope for this " + "alias-only topology change") + + # ------------------------------------------------------------------ + # Test 10: mid-talk trunk drop must clear the aliased trunk-talker + # state (regression for TrunkLink::clearPeerTalkerState) + # ------------------------------------------------------------------ + def test_10_disconnect_clears_aliased_trunk_talker(self): + """Reproduces the bug fixed in TrunkLink::clearPeerTalkerState(): + that loop iterates m_peer_active_tgs, which holds LONG numbers, + but handleMsgPeerTalkerStart records the trunk-talker in + TGHandler under the SHORT (folded) number via + aliasToLocal(local_tg). If clearPeerTalkerState clears the LONG + key instead of folding it first, the SHORT TG's trunk-talker + entry is never released after a trunk drop, and a local client + can never win talker arbitration on it again — see + TGHandler::hasTrunkTalker() gating local talker claims in + Reflector::udpDatagramReceived. + + We use a fake trunk peer on the isolated TRUNK_TEST section + (same harness facility as test_trunk.py; a black-hole outbound + HOST so only our inbound connection is ever active) to avoid + perturbing the real a<->b mesh link used by the rest of this + suite. The fake peer claims the two-way alias's LONG number + (1220008) as talker and is then dropped via a raw TCP close + WITHOUT a TalkerStop — the closest achievable simulation of a + trunk link failing mid-transmission with this harness (there is + no supported way to kill only the data channel of a live Docker + trunk link out from under a container). + + The only externally observable effect of hasTrunkTalker(8) is + whether a local client's audio on the short number is ever + accepted as talker and relayed; that is the real assertion here. + """ + owner_http = _http(ALIAS_OWNER) + fake_peer = TrunkPeer() + talker_claimed = False + try: + fake_peer.connect(HOST, T.mapped_trunk_port(ALIAS_OWNER)) + fake_peer.handshake() # TRUNK_TEST section, prefix 9, test_secret + wait_for_trunk_connected(*owner_http, "TRUNK_TEST", timeout=10.0) + + fake_peer.send_talker_start(TG_TWOWAY_LONG, "N0FAKE") + talker_claimed = True + for _ in range(4): + fake_peer.send_audio(TG_TWOWAY_LONG, b"\x99\x11" * 80) + time.sleep(0.02) + + # Confirm the reflector actually recorded the claim (folded + # onto the short number via deliver_tg) before we pull the + # rug out — otherwise the recovery check below would be + # vacuous (nothing was ever wedged to begin with). + wait_until( + lambda: get_status(*owner_http)["trunks"]["TRUNK_TEST"] + .get("active_talkers", {}).get(str(TG_TWOWAY_LONG)) + == "N0FAKE", + timeout=5.0, + msg=f"fake peer's TalkerStart on long TG {TG_TWOWAY_LONG} " + f"never showed up in TRUNK_TEST's active_talkers — " + f"cannot exercise the disconnect-clears-state path") + + # Mid-talk drop: raw TCP close, no TalkerStop. This triggers + # TrunkLink::onInboundDisconnected -> clearPeerTalkerState(). + fake_peer.close() + + wait_until( + lambda: not get_status(*owner_http)["trunks"]["TRUNK_TEST"] + .get("connected", True), + timeout=10.0, + msg="TRUNK_TEST link on reflector-" + ALIAS_OWNER + + " did not register as disconnected after the fake " + "peer's TCP close") + finally: + if talker_claimed: + fake_peer.close() # no-op if already closed above + + # Recovery check: a local client on the SHORT number must now be + # able to win talker arbitration and have its audio delivered to + # another local client on the same short number. Before the fix, + # clearPeerTalkerState left TG 8's trunk-talker entry wedged on + # TGHandler forever, so hasTrunkTalker(8) stayed true and this + # audio would never be accepted/relayed. + node1 = ClientPeer() + node2 = ClientPeer() + try: + port = _client_port(ALIAS_OWNER) + node1.connect(HOST, port) + node1.authenticate(callsign=CLIENT_CALLSIGN, password=CLIENT_PASSWORD) + node1.setup_udp(udp_port=port) + node1.select_tg(TG_TWOWAY_SHORT) + + node2.connect(HOST, port) + node2.authenticate(callsign=CLIENT2_CALLSIGN, password=CLIENT2_PASSWORD) + node2.setup_udp(udp_port=port) + node2.select_tg(TG_TWOWAY_SHORT) + + time.sleep(0.5) + node2.recv_udp_all(timeout=0.05) # drain bootstrap traffic + + for _ in range(6): + node1.send_udp_audio(b"\xDE\xAD" * 80) + time.sleep(0.02) + node1.send_udp_flush() + time.sleep(0.8) + + msgs = node2.recv_udp_all(timeout=1.0) + audio = sum(1 for t, _ in msgs if t == UDP_AUDIO) + flush = sum(1 for t, _ in msgs if t == UDP_FLUSH) + self.assertGreater(audio + flush, 0, + f"node2 received no audio from node1 on short TG " + f"{TG_TWOWAY_SHORT} after the fake trunk peer's mid-talk " + f"drop — TG {TG_TWOWAY_SHORT}'s trunk-talker state is " + f"still wedged, meaning clearPeerTalkerState() did not " + f"fold the long alias number to the short number before " + f"clearing TGHandler's trunk-talker map") + finally: + node1.close() + node2.close() + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/topology.py b/tests/topology.py index c097d91..7a248b8 100644 --- a/tests/topology.py +++ b/tests/topology.py @@ -11,7 +11,13 @@ to regenerate configs/ and docker-compose.test.yml. The test harness REFLECTORS = { # name prefixes (list) host-port-base redis - "a": {"prefix": ["122"], "trunk_port_base": 15000}, + # `a` also carries LOCAL_ALIASES so tests/test_alias.py can verify the + # local-alias feature (short local TG re-homed under an owned prefix): + # 8 <-> 1220008 (two-way) + # 90 (/out) <-> 1220090 (export only: local TG 90 -> mesh, no fold-in) + # 91 (/in) <-> 1220091 (import only: mesh -> local TG 91, no publish) + "a": {"prefix": ["122"], "trunk_port_base": 15000, + "local_aliases": "8:1220008,90:1220090/out,91:1220091/in"}, "b": {"prefix": ["121"], "trunk_port_base": 25000}, "c": {"prefix": ["1"], "trunk_port_base": 35000}, # `d` is sparse-trunked: only connects to `b`. With prefix `1219`