diff --git a/README.md b/README.md index 8afddac..3e8b153 100644 --- a/README.md +++ b/README.md @@ -454,6 +454,9 @@ The PTY path is set by `COMMAND_PTY` in `[GLOBAL]` (default MQTT events via Telegram, SMS, Discord, webhooks, dashboards, and more - [`docs/DESIGN_SATELLITE_AND_CLUSTER.md`](docs/DESIGN_SATELLITE_AND_CLUSTER.md) — design rationale for satellite reflectors and cluster TGs +- [`docs/JAY-additions.md`](docs/JAY-additions.md) — features merged from + jayReflector by DJ1JAY / FM-Funknetz: per-trunk filters, TG mapping, + PEER_ID, MQTT_NAME, node-list exchange, PTY mute/reload/status - [`tests/TESTS.md`](tests/TESTS.md) — integration test suite documentation: topology, test cases, harness components, and how to run diff --git a/docs/JAY-additions.md b/docs/JAY-additions.md new file mode 100644 index 0000000..aa8e77b --- /dev/null +++ b/docs/JAY-additions.md @@ -0,0 +1,85 @@ +# jayReflector Additions + +This document describes features merged into GeuReflector from +[**jayReflector**](https://github.com/dj1jay/jayReflector) by +**DJ1JAY / FM-Funknetz**. + +## Credits + +All design and original implementation of the features below is the work of +DJ1JAY. They were ported into this repository with light adaptation to fit the +GeuReflector code paths (in particular: the in-process `MqttPublisher` is +retained instead of the external `jay-mqtt-daemon.py`). + +If you build on these features, please credit DJ1JAY / FM-Funknetz and +consult the upstream jayReflector repository for context and additional +material that was not merged here. + +## What was merged + +| Area | Key / Message | Purpose | +|------|---------------|---------| +| Filter syntax | `TgFilter` (header-only, `src/svxlink/reflector/TgFilter.h`) | Flexible TG matching: exact (`26200`), prefix (`24*`), range (`2427-2438`), comma-separated | +| Per-trunk config | `BLACKLIST_TGS` | TGs never carried in either direction on this link | +| Per-trunk config | `ALLOW_TGS` | If non-empty, only these TGs are exchanged on this link | +| Per-trunk config | `TG_MAP=peer:local,...` | Bidirectional TG remap; mapped TGs bypass the prefix routing check on this link | +| Per-trunk config | `PEER_ID` | Stable identifier advertised in the trunk hello (defaults to section name); used as the MQTT topic component on the receiving side | +| Global config | `MQTT_NAME` (in `[MQTT]`) | Appended to `TOPIC_PREFIX` so each reflector publishes under a unique sub-tree (`//...`) | +| Wire protocol | `MsgTrunkNodeList` (type **121**) | Periodic node list (callsign + current TG, plus optional lat/lon/QTH) sent peer-to-peer when the local client list changes; receiver re-publishes it via MQTT | +| Wire protocol | `MsgTrunkFilter` (type **122**) | Optional satellite-side TG-filter advertisement so a satellite can subscribe to only a subset of the parent's TGs | +| PTY commands | `TRUNK MUTE \| UNMUTE
` | Live mute of a callsign per trunk link; muted callsigns' inbound audio is dropped | +| PTY commands | `TRUNK RELOAD [
]` | Re-reads `BLACKLIST_TGS`, `ALLOW_TGS`, `TG_MAP` from the live config without restarting | +| PTY commands | `TRUNK STATUS [
]` | Dumps a one-line status summary per trunk link to the PTY | + +## Backward compatibility + +- New message types (121, 122) are silently ignored by reflector instances that + don't know about them. Mixed deployments (jayReflector ↔ this branch ↔ + upstream GeuReflector v3) continue to interoperate for the legacy message + set (115–120). +- All new config keys are optional. Reflectors with no `BLACKLIST_TGS`, + `ALLOW_TGS`, `TG_MAP`, `PEER_ID`, or `MQTT_NAME` behave exactly as before. + +## Filter semantics + +For a given TG on a given trunk link, traffic is allowed only if: + +``` +not isBlacklisted(tg) // blacklist applies in both directions +and isAllowed(tg) // empty allow filter = allow all +and ( + explicit TG_MAP entry // mapped TGs always pass + or isSharedTG(tg) // standard prefix-based ownership routing + or isClusterTG(tg) // cluster TG broadcast + or isPeerInterestedTG(tg) // peer recently advertised interest +) +``` + +For incoming messages the reflector applies `TG_MAP` first (peer wire TG → +local TG) and then performs all subsequent checks against both the wire and +local TG so the operator can blacklist either form. + +## Differences from upstream jayReflector + +The following jayReflector items were **not** merged on request: + +- **External MQTT daemon (`jay-mqtt-daemon.py`)** — this branch keeps the + existing in-process `MqttPublisher`. As a result, some MQTT topics differ + in suffix (this branch publishes node lists as `nodes/local` and + `nodes/`; jayReflector's external daemon uses a slightly different + layout). The `MQTT_NAME` and `PEER_ID` keys behave identically. + +If you want any of the deferred items merged, see the upstream repository +linked above and open an issue or PR on this repository. + +## Where to look in the code + +| File | What to look for | +|------|------------------| +| `src/svxlink/reflector/TgFilter.h` | Filter parser | +| `src/svxlink/reflector/ReflectorMsg.h` | `MsgTrunkNodeList` (121), `MsgTrunkFilter` (122) | +| `src/svxlink/reflector/TrunkLink.{h,cpp}` | Per-link filters, mapping, mute, `reloadConfig`, `statusLine`, `sendNodeList`, `handleMsgTrunkNodeList`, `peerId()` | +| `src/svxlink/reflector/Reflector.{h,cpp}` | `scheduleNodeListUpdate`, `sendNodeListToAllPeers`, `onPeerNodeList`, PTY `TRUNK` command branch, `MQTT_NAME` topic prefix | +| `src/svxlink/reflector/MqttPublisher.{h,cpp}` | `publishLocalNodes`, `publishPeerNodes` | +| `src/svxlink/reflector/svxreflector.conf.in` | Config-template documentation for every new key | +| `tests/test_trunk.py` | Tests 19–27 cover the merged features | diff --git a/src/svxlink/reflector/MqttPublisher.cpp b/src/svxlink/reflector/MqttPublisher.cpp index 343f1a1..3a05af9 100644 --- a/src/svxlink/reflector/MqttPublisher.cpp +++ b/src/svxlink/reflector/MqttPublisher.cpp @@ -89,6 +89,16 @@ bool MqttPublisher::initialize(void) m_topic_prefix.pop_back(); } + // Optional MQTT_NAME — appended as a path component so each reflector + // publishes under a unique sub-tree (TOPIC_PREFIX/MQTT_NAME/...). + string mqtt_name; + if (m_cfg.getValue("MQTT", "MQTT_NAME", mqtt_name) && !mqtt_name.empty()) + { + while (!mqtt_name.empty() && mqtt_name.back() == '/') mqtt_name.pop_back(); + while (!mqtt_name.empty() && mqtt_name.front() == '/') mqtt_name.erase(0, 1); + if (!mqtt_name.empty()) m_topic_prefix += "/" + mqtt_name; + } + // Read optional TLS config string tls_str; if (m_cfg.getValue("MQTT", "TLS_ENABLED", tls_str) && tls_str == "1") @@ -283,3 +293,47 @@ void MqttPublisher::publishFullStatus(const Json::Value& status) wb["indentation"] = ""; publish("status", Json::writeString(wb, status), true); } + + +static Json::Value nodeListToJson( + const std::vector& nodes) +{ + Json::Value arr(Json::arrayValue); + for (const auto& n : nodes) + { + Json::Value e; + e["callsign"] = n.callsign; + e["tg"] = n.tg; + if (n.lat != 0.0f || n.lon != 0.0f) + { + e["lat"] = n.lat; + e["lon"] = n.lon; + } + if (!n.qth_name.empty()) e["qth_name"] = n.qth_name; + arr.append(e); + } + Json::Value root; + root["nodes"] = arr; + root["timestamp"] = (Json::Int64)time(nullptr); + return root; +} + + +void MqttPublisher::publishLocalNodes( + const std::vector& nodes) +{ + Json::StreamWriterBuilder wb; + wb["indentation"] = ""; + publish("nodes/local", + Json::writeString(wb, nodeListToJson(nodes)), true); +} + + +void MqttPublisher::publishPeerNodes(const std::string& peer_id, + const std::vector& nodes) +{ + Json::StreamWriterBuilder wb; + wb["indentation"] = ""; + publish("nodes/" + peer_id, + Json::writeString(wb, nodeListToJson(nodes)), true); +} diff --git a/src/svxlink/reflector/MqttPublisher.h b/src/svxlink/reflector/MqttPublisher.h index 734a634..2e5d4be 100644 --- a/src/svxlink/reflector/MqttPublisher.h +++ b/src/svxlink/reflector/MqttPublisher.h @@ -3,7 +3,9 @@ #include #include +#include #include +#include "ReflectorMsg.h" struct mosquitto; @@ -38,6 +40,12 @@ class MqttPublisher // Periodic full status void publishFullStatus(const Json::Value& status); + // Node-list snapshots — published retained + void publishLocalNodes( + const std::vector& nodes); + void publishPeerNodes(const std::string& peer_id, + const std::vector& nodes); + private: Async::Config& m_cfg; struct mosquitto* m_mosq = nullptr; diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 9c71f83..4c47d5d 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -245,9 +245,14 @@ Reflector::Reflector(void) m_random_qsy_hi(0), m_random_qsy_tg(0), m_http_server(0), m_cmd_pty(0), m_keys_dir("private/"), m_pending_csrs_dir("pending_csrs/"), m_csrs_dir("csrs/"), m_certs_dir("certs/"), m_pki_dir("pki/"), + m_nodelist_timer(500, Async::Timer::TYPE_ONESHOT), m_sat_cleanup_timer(0, Async::Timer::TYPE_ONESHOT), m_mqtt_status_timer(1000, Async::Timer::TYPE_ONESHOT) { + m_nodelist_timer.setEnable(false); + m_nodelist_timer.expired.connect( + [this](Async::Timer*) { sendNodeListToAllPeers(); }); + TGHandler::instance()->talkerUpdated.connect( mem_fun(*this, &Reflector::onTalkerUpdated)); TGHandler::instance()->requestAutoQsy.connect( @@ -1051,6 +1056,7 @@ void Reflector::clientDisconnected(Async::FramedTcpConnection *con, { m_mqtt->onClientDisconnected(client->callsign()); } + scheduleNodeListUpdate(); } //Application::app().runTask([=]{ delete client; }); delete client; @@ -1949,13 +1955,101 @@ void Reflector::ctrlPtyDataReceived(const void *buf, size_t count) goto write_status; } } + else if (cmd == "TRUNK") + { + std::string subcmd; + if (!(ss >> subcmd)) + { + errss << "Invalid TRUNK PTY command. " + "Usage: TRUNK MUTE|UNMUTE
| " + "TRUNK RELOAD [
] | TRUNK STATUS [
]"; + goto write_status; + } + std::transform(subcmd.begin(), subcmd.end(), subcmd.begin(), ::toupper); + + auto find_link = [&](const std::string& section) -> TrunkLink* { + for (auto* link : m_trunk_links) + if (link->section() == section) return link; + return nullptr; + }; + + if (subcmd == "MUTE" || subcmd == "UNMUTE") + { + std::string section, callsign; + if (!(ss >> section >> callsign)) + { + errss << "Usage: TRUNK " << subcmd << "
"; + goto write_status; + } + TrunkLink* link = find_link(section); + if (link == nullptr) + { + errss << "Unknown trunk section: " << section; + goto write_status; + } + if (subcmd == "MUTE") link->muteCallsign(callsign); + else link->unmuteCallsign(callsign); + m_cmd_pty->write(section + ": " + subcmd + " " + callsign + "\n"); + } + else if (subcmd == "RELOAD") + { + std::string section; + ss >> section; + if (section.empty()) + { + for (auto* link : m_trunk_links) link->reloadConfig(); + m_cmd_pty->write("Reloaded all trunk links\n"); + } + else + { + TrunkLink* link = find_link(section); + if (link == nullptr) + { + errss << "Unknown trunk section: " << section; + goto write_status; + } + link->reloadConfig(); + m_cmd_pty->write(section + ": reloaded\n"); + } + } + else if (subcmd == "STATUS") + { + std::string section; + ss >> section; + if (section.empty()) + { + for (auto* link : m_trunk_links) + m_cmd_pty->write(link->statusLine() + "\n"); + } + else + { + TrunkLink* link = find_link(section); + if (link == nullptr) + { + errss << "Unknown trunk section: " << section; + goto write_status; + } + m_cmd_pty->write(link->statusLine() + "\n"); + } + } + else + { + errss << "Invalid TRUNK subcommand '" << subcmd << "'. " + "Usage: TRUNK MUTE|UNMUTE
| " + "TRUNK RELOAD [
] | TRUNK STATUS [
]"; + goto write_status; + } + } else { - errss << "Valid commands are: CFG, NODE, CA\n" + errss << "Valid commands are: CFG, NODE, CA, TRUNK\n" << "Usage:\n" << "CFG
\n" << "NODE BLOCK \n" << "CA LS|LSC|LSP|SIGN |RM \n" + << "TRUNK MUTE|UNMUTE
\n" + << "TRUNK RELOAD [
]\n" + << "TRUNK STATUS [
]\n" << "\nEmpty CFG lists all configuration"; } @@ -2603,22 +2697,70 @@ void Reflector::onClientAuthenticated(const std::string& callsign, { m_mqtt->onClientConnected(callsign, tg, ip); } + scheduleNodeListUpdate(); } /* Reflector::onClientAuthenticated */ -void Reflector::onTrunkStateChanged(const std::string& section, - const std::string& direction, bool up, - const std::string& host, uint16_t port) +void Reflector::scheduleNodeListUpdate(void) +{ + // Debounce — multiple rapid login/TG-change events coalesce into one send + m_nodelist_timer.setEnable(false); + m_nodelist_timer.setTimeout(500); + m_nodelist_timer.setEnable(true); +} /* Reflector::scheduleNodeListUpdate */ + + +void Reflector::sendNodeListToAllPeers(void) +{ + std::vector nodes; + for (const auto& kv : m_client_con_map) + { + ReflectorClient* c = kv.second; + if (c->callsign().empty()) continue; + MsgTrunkNodeList::NodeEntry e; + e.callsign = c->callsign(); + e.tg = c->currentTG(); + nodes.push_back(e); + } + + for (auto* link : m_trunk_links) + { + link->sendNodeList(nodes); + } + + if (m_mqtt != nullptr) + { + m_mqtt->publishLocalNodes(nodes); + } +} /* Reflector::sendNodeListToAllPeers */ + + +void Reflector::onPeerNodeList(const std::string& peer_id, + const std::vector& nodes) { if (m_mqtt != nullptr) { + m_mqtt->publishPeerNodes(peer_id, nodes); + } +} /* Reflector::onPeerNodeList */ + + +void Reflector::onTrunkStateChanged(const std::string& section, + const std::string& peer_id, + const std::string& direction, bool up, + const std::string& host, uint16_t port) +{ + (void)section; // reserved for local logging; MQTT uses peer_id + if (m_mqtt != nullptr) + { + const std::string& topic_id = peer_id.empty() ? section : peer_id; if (up) { - m_mqtt->onTrunkUp(section, direction, host, port); + m_mqtt->onTrunkUp(topic_id, direction, host, port); } else { - m_mqtt->onTrunkDown(section, direction); + m_mqtt->onTrunkDown(topic_id, direction); } } } /* Reflector::onTrunkStateChanged */ diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 12b5e50..9bbea97 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -65,6 +65,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "ProtoVer.h" #include "ReflectorClient.h" #include "TrunkLink.h" +#include "ReflectorMsg.h" #include "SatelliteLink.h" #include "SatelliteClient.h" #include "MqttPublisher.h" @@ -258,10 +259,18 @@ class Reflector : public sigc::trackable void onClientAuthenticated(const std::string& callsign, uint32_t tg, const std::string& ip); void onTrunkStateChanged(const std::string& section, + const std::string& peer_id, const std::string& direction, bool up, const std::string& host = "", uint16_t port = 0); + // Triggered when a local client logs in/out or changes TG. Schedules + // a debounced node-list emission to all trunk peers and to MQTT. + void scheduleNodeListUpdate(void); + // Called by TrunkLink when a peer sends us its node list. + void onPeerNodeList(const std::string& peer_id, + const std::vector& nodes); + protected: private: @@ -309,6 +318,7 @@ class Reflector : public sigc::trackable std::vector m_trunk_links; std::set m_cluster_tgs; bool m_trunk_debug = false; + Async::Timer m_nodelist_timer; static const size_t TRUNK_MAX_PENDING_CONS = 5; FramedTcpServer* m_trunk_srv = nullptr; @@ -367,6 +377,7 @@ class Reflector : public sigc::trackable Async::FramedTcpConnection::DisconnectReason reason); void onSatelliteLinkFailed(SatelliteLink* link); void processSatelliteCleanup(Async::Timer* t); + void sendNodeListToAllPeers(void); bool loadCertificateFiles(void); bool loadServerCertificateFiles(void); bool generateKeyFile(Async::SslKeypair& pkey, const std::string& keyfile); diff --git a/src/svxlink/reflector/ReflectorClient.cpp b/src/svxlink/reflector/ReflectorClient.cpp index b39491b..e73631b 100644 --- a/src/svxlink/reflector/ReflectorClient.cpp +++ b/src/svxlink/reflector/ReflectorClient.cpp @@ -1444,6 +1444,7 @@ void ReflectorClient::setTg(uint32_t tg) } m_current_tg = tg; + if (m_reflector != nullptr) m_reflector->scheduleNodeListUpdate(); } if (m_status != nullptr) diff --git a/src/svxlink/reflector/ReflectorMsg.h b/src/svxlink/reflector/ReflectorMsg.h index 7534c4d..b7a949e 100644 --- a/src/svxlink/reflector/ReflectorMsg.h +++ b/src/svxlink/reflector/ReflectorMsg.h @@ -1821,6 +1821,93 @@ class MsgUdpAudio : public ReflectorUdpMsgBase<101> #endif +/** +@brief Trunk node list message (jayReflector extension, type 121) + +Sent by a reflector to its trunk peer whenever its local client list changes +(login, logout, TG change). The receiving peer can publish it via its own +MQTT publisher. Older peers that don't know type 121 ignore it — fully +backward compatible. + +Each entry: callsign, current TG, optional lat/lon/QTH name. +*/ +class MsgTrunkNodeList : public ReflectorMsgBase<121> +{ + public: + struct NodeEntry + { + std::string callsign; + uint32_t tg = 0; + float lat = 0.0f; + float lon = 0.0f; + std::string qth_name; + }; + + MsgTrunkNodeList(void) {} + explicit MsgTrunkNodeList(const std::vector& nodes) + { + for (const auto& n : nodes) + { + m_callsigns.push_back(n.callsign); + m_tgs.push_back(n.tg); + m_lats.push_back(n.lat); + m_lons.push_back(n.lon); + m_qth_names.push_back(n.qth_name); + } + } + + std::vector nodes(void) const + { + std::vector result; + size_t sz = std::min(m_callsigns.size(), m_tgs.size()); + for (size_t i = 0; i < sz; ++i) + { + NodeEntry e; + e.callsign = m_callsigns[i]; + e.tg = m_tgs[i]; + e.lat = (i < m_lats.size()) ? m_lats[i] : 0.0f; + e.lon = (i < m_lons.size()) ? m_lons[i] : 0.0f; + e.qth_name = (i < m_qth_names.size()) ? m_qth_names[i] : ""; + result.push_back(e); + } + return result; + } + + ASYNC_MSG_MEMBERS(m_callsigns, m_tgs, m_lats, m_lons, m_qth_names) + + private: + std::vector m_callsigns; + std::vector m_tgs; + std::vector m_lats; + std::vector m_lons; + std::vector m_qth_names; +}; /* MsgTrunkNodeList */ + + +/** +@brief Trunk filter advertisement (jayReflector extension, type 122) + +Optional message sent (typically by a satellite after Hello) to tell the +parent which TGs it wants to receive. Filter syntax matches TgFilter +(exact / "24*" prefix / "10-20" range, comma-separated). Older peers +silently ignore unknown message types. +*/ +class MsgTrunkFilter : public ReflectorMsgBase<122> +{ + public: + MsgTrunkFilter(void) {} + explicit MsgTrunkFilter(const std::string& filter) + : m_filter(filter) {} + + const std::string& filter(void) const { return m_filter; } + + ASYNC_MSG_MEMBERS(m_filter) + + private: + std::string m_filter; +}; /* MsgTrunkFilter */ + + #endif /* REFLECTOR_MSG_INCLUDED */ diff --git a/src/svxlink/reflector/TgFilter.h b/src/svxlink/reflector/TgFilter.h new file mode 100644 index 0000000..42bb0b0 --- /dev/null +++ b/src/svxlink/reflector/TgFilter.h @@ -0,0 +1,125 @@ +/** + * @file TgFilter.h + * @brief Flexible TG filter: exact, prefix (*), range (-) + * @author DJ1JAY / FM-Funknetz + * + * Syntax (comma-separated): + * 24* — prefix match: all TGs starting with "24" + * 2427-2438 — range: TG 2427..2438 inclusive + * 26200 — exact match: only TG 26200 + * + * Empty filter = match all. + * + * Example: + * TgFilter f = TgFilter::parse("24*,2427-2438,26200"); + * f.matches(24) → true + * f.matches(2430) → true + * f.matches(26200) → true + * f.matches(26201) → false + */ + +#ifndef TGFILTER_H +#define TGFILTER_H + +#include +#include +#include +#include + +struct TgFilter +{ + struct Entry + { + enum Type { EXACT, PREFIX, RANGE } type; + uint32_t value = 0; + uint32_t range_end = 0; + std::string prefix; + }; + + std::vector entries; + bool empty(void) const { return entries.empty(); } + + static TgFilter parse(const std::string& s) + { + TgFilter f; + std::istringstream ss(s); + std::string tok; + while (std::getline(ss, tok, ',')) + { + tok.erase(0, tok.find_first_not_of(" \t")); + tok.erase(tok.find_last_not_of(" \t") + 1); + if (tok.empty()) continue; + + Entry e; + if (!tok.empty() && tok.back() == '*') + { + e.type = Entry::PREFIX; + e.prefix = tok.substr(0, tok.size() - 1); + } + else + { + auto dash = tok.find('-'); + if (dash != std::string::npos) + { + try { + e.type = Entry::RANGE; + e.value = std::stoul(tok.substr(0, dash)); + e.range_end = std::stoul(tok.substr(dash + 1)); + } catch (...) { continue; } + } + else + { + try { + e.type = Entry::EXACT; + e.value = std::stoul(tok); + } catch (...) { continue; } + } + } + f.entries.push_back(e); + } + return f; + } + + bool matches(uint32_t tg) const + { + if (entries.empty()) return true; + const std::string s = std::to_string(tg); + for (const auto& e : entries) + { + switch (e.type) + { + case Entry::EXACT: + if (tg == e.value) return true; + break; + case Entry::PREFIX: + if (s.size() >= e.prefix.size() && + s.compare(0, e.prefix.size(), e.prefix) == 0) + return true; + break; + case Entry::RANGE: + if (tg >= e.value && tg <= e.range_end) return true; + break; + } + } + return false; + } + + std::string toString(void) const + { + std::string r; + for (const auto& e : entries) + { + if (!r.empty()) r += ','; + switch (e.type) + { + case Entry::EXACT: r += std::to_string(e.value); break; + case Entry::PREFIX: r += e.prefix + "*"; break; + case Entry::RANGE: r += std::to_string(e.value) + "-" + + std::to_string(e.range_end); break; + } + } + return r; + } +}; + +#endif /* TGFILTER_H */ diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index a1ed929..2ab712d 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -191,10 +191,69 @@ bool TrunkLink::initialize(void) m_debug = (debug_str == "1" || debug_str == "true" || debug_str == "yes"); } + // 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) + || m_peer_id_config.empty()) + { + m_peer_id_config = m_section; + } + + // BLACKLIST_TGS — flexible filter (exact, prefix "24*", range "10-20") + std::string blacklist_str; + if (m_cfg.getValue(m_section, "BLACKLIST_TGS", blacklist_str) + && !blacklist_str.empty()) + { + m_blacklist_filter = TgFilter::parse(blacklist_str); + if (!m_blacklist_filter.empty()) + cout << m_section << ": Blacklisted TGs: " + << m_blacklist_filter.toString() << endl; + } + + // ALLOW_TGS — flexible whitelist (empty = allow all) + std::string allow_str; + if (m_cfg.getValue(m_section, "ALLOW_TGS", allow_str) && !allow_str.empty()) + { + m_allow_filter = TgFilter::parse(allow_str); + if (!m_allow_filter.empty()) + cout << m_section << ": Allowed TGs: " + << m_allow_filter.toString() << endl; + } + + // TG_MAP — bidirectional TG remap, syntax "peer:local,peer2:local2" + std::string tgmap_str; + if (m_cfg.getValue(m_section, "TG_MAP", tgmap_str) && !tgmap_str.empty()) + { + std::istringstream ms(tgmap_str); + std::string pair; + while (std::getline(ms, pair, ',')) + { + auto colon = pair.find(':'); + if (colon == std::string::npos) continue; + try { + uint32_t peer_tg = std::stoul(pair.substr(0, colon)); + uint32_t local_tg = std::stoul(pair.substr(colon + 1)); + m_tg_map_in[peer_tg] = local_tg; + m_tg_map_out[local_tg] = peer_tg; + } catch (...) { /* skip malformed */ } + } + if (!m_tg_map_in.empty()) + { + cout << m_section << ": TG mappings (peer<->local):"; + for (const auto& kv : m_tg_map_in) + cout << " " << kv.first << "<->" << kv.second; + cout << endl; + } + } + cout << m_section << ": Trunk to " << m_peer_host << ":" << m_peer_port << " local_prefix=" << joinPrefixes(m_local_prefix) << " remote_prefix=" << joinPrefixes(m_remote_prefix) - << (m_debug ? " [debug on]" : "") << endl; + << (m_debug ? " [debug on]" : "") + << (m_blacklist_filter.empty() ? "" : " [blacklist]") + << (m_allow_filter.empty() ? "" : " [whitelist]") + << (m_tg_map_in.empty() ? "" : " [tg_map]") + << endl; m_con.addStaticSRVRecord(0, 0, 0, m_peer_port, m_peer_host); m_con.setReconnectMinTime(2000); @@ -282,6 +341,18 @@ bool TrunkLink::isPeerInterestedTG(uint32_t tg) const } /* TrunkLink::isPeerInterestedTG */ +bool TrunkLink::isBlacklisted(uint32_t tg) const +{ + return !m_blacklist_filter.empty() && m_blacklist_filter.matches(tg); +} /* TrunkLink::isBlacklisted */ + + +bool TrunkLink::isAllowed(uint32_t tg) const +{ + return m_allow_filter.empty() || m_allow_filter.matches(tg); +} /* TrunkLink::isAllowed */ + + Json::Value TrunkLink::statusJson(void) const { Json::Value obj(Json::objectValue); @@ -350,10 +421,11 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, con->frameReceived.connect( mem_fun(*this, &TrunkLink::onFrameReceived)); + m_peer_id_received = hello.id(); cout << m_section << ": Accepted inbound from " << con->remoteHost() << ":" << con->remotePort() << " peer='" << hello.id() << "' priority=" << m_peer_priority << endl; - m_reflector->onTrunkStateChanged(m_section, "inbound", true, + m_reflector->onTrunkStateChanged(m_section, peerId(), "inbound", true, con->remoteHost().toString(), con->remotePort()); @@ -366,7 +438,8 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, } // Send our hello back on the inbound connection - sendMsgOnInbound(MsgTrunkHello(m_section, joinPrefixes(m_local_prefix), + sendMsgOnInbound(MsgTrunkHello(m_peer_id_config, + joinPrefixes(m_local_prefix), m_priority, m_secret)); } /* TrunkLink::acceptInboundConnection */ @@ -387,7 +460,7 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con, } cout << m_section << ": Inbound trunk connection lost" << endl; - m_reflector->onTrunkStateChanged(m_section, "inbound", false); + m_reflector->onTrunkStateChanged(m_section, peerId(), "inbound", false); if (m_debug) { @@ -416,21 +489,25 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con, void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign) { - if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg))) + if (!isActive() || isBlacklisted(tg) || !isAllowed(tg)) return; + bool mapped = m_tg_map_out.count(tg) > 0; + if (!mapped && + !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg)) { return; } - sendMsg(MsgTrunkTalkerStart(tg, callsign)); + sendMsg(MsgTrunkTalkerStart(mapTgOut(tg), callsign)); } /* TrunkLink::onLocalTalkerStart */ void TrunkLink::onLocalTalkerStop(uint32_t tg) { - if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg))) + if (!isActive() || isBlacklisted(tg) || !isAllowed(tg)) return; + bool mapped = m_tg_map_out.count(tg) > 0; + if (!mapped && + !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg)) { return; } @@ -440,32 +517,39 @@ void TrunkLink::onLocalTalkerStop(uint32_t tg) { return; } - sendMsg(MsgTrunkTalkerStop(tg)); + sendMsg(MsgTrunkTalkerStop(mapTgOut(tg))); } /* TrunkLink::onLocalTalkerStop */ void TrunkLink::onLocalAudio(uint32_t tg, const std::vector& audio) { - if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg)) || - m_yielded_tgs.count(tg)) + if (!isActive() || isBlacklisted(tg) || !isAllowed(tg) + || m_yielded_tgs.count(tg)) { return; } - sendMsg(MsgTrunkAudio(tg, audio)); + bool mapped = m_tg_map_out.count(tg) > 0; + if (!mapped && + !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg)) + { + return; + } + sendMsg(MsgTrunkAudio(mapTgOut(tg), audio)); } /* TrunkLink::onLocalAudio */ void TrunkLink::onLocalFlush(uint32_t tg) { - if (!isActive() || - (!isSharedTG(tg) && !m_reflector->isClusterTG(tg) && - !isPeerInterestedTG(tg))) + if (!isActive() || isBlacklisted(tg) || !isAllowed(tg)) return; + bool mapped = m_tg_map_out.count(tg) > 0; + if (!mapped && + !isSharedTG(tg) && !m_reflector->isClusterTG(tg) && + !isPeerInterestedTG(tg)) { return; } - sendMsg(MsgTrunkFlush(tg)); + sendMsg(MsgTrunkFlush(mapTgOut(tg))); } /* TrunkLink::onLocalFlush */ @@ -479,7 +563,7 @@ void TrunkLink::onConnected(void) { cout << m_section << ": Outbound connected to " << m_con.remoteHost() << ":" << m_con.remotePort() << endl; - m_reflector->onTrunkStateChanged(m_section, "outbound", true, + m_reflector->onTrunkStateChanged(m_section, peerId(), "outbound", true, m_con.remoteHost().toString(), m_con.remotePort()); @@ -495,7 +579,8 @@ void TrunkLink::onConnected(void) m_ob_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; m_heartbeat_timer.setEnable(true); - sendMsgOnOutbound(MsgTrunkHello(m_section, joinPrefixes(m_local_prefix), + sendMsgOnOutbound(MsgTrunkHello(m_peer_id_config, + joinPrefixes(m_local_prefix), m_priority, m_secret)); } /* TrunkLink::onConnected */ @@ -505,7 +590,7 @@ void TrunkLink::onDisconnected(TcpConnection* con, { cout << m_section << ": Outbound disconnected: " << TcpConnection::disconnectReasonStr(reason) << endl; - m_reflector->onTrunkStateChanged(m_section, "outbound", false); + m_reflector->onTrunkStateChanged(m_section, peerId(), "outbound", false); if (m_debug) { @@ -612,6 +697,9 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, case MsgTrunkFlush::TYPE: handleMsgTrunkFlush(ss); break; + case MsgTrunkNodeList::TYPE: + handleMsgTrunkNodeList(ss); + break; default: cerr << "*** WARNING[" << m_section << "]: Unknown trunk message type=" << header.type() << endl; @@ -669,6 +757,7 @@ void TrunkLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) } m_peer_priority = msg.priority(); + m_peer_id_received = msg.id(); m_ob_hello_received = true; cout << m_section << ": Trunk hello from peer '" << msg.id() @@ -696,38 +785,44 @@ void TrunkLink::handleMsgTrunkTalkerStart(std::istream& is) return; } - uint32_t tg = msg.tg(); - if (!isOwnedTG(tg) && !m_reflector->isClusterTG(tg)) + uint32_t wire_tg = msg.tg(); + uint32_t local_tg = mapTgIn(wire_tg); + if (isBlacklisted(wire_tg) || isBlacklisted(local_tg) || !isAllowed(wire_tg)) + { + return; + } + bool mapped = m_tg_map_in.count(wire_tg) > 0; + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) { return; } // 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(tg); + ReflectorClient* local_talker = TGHandler::instance()->talkerForTG(local_tg); if (local_talker != nullptr) { if (m_priority <= m_peer_priority) { // We win — ignore peer's claim - cout << m_section << ": TG #" << tg + cout << m_section << ": TG #" << local_tg << " conflict — local wins (our priority=" << m_priority << " <= peer=" << m_peer_priority << ")" << endl; return; } // We defer — clear local talker and accept remote - cout << m_section << ": TG #" << tg + cout << m_section << ": TG #" << local_tg << " conflict — deferring to peer (our priority=" << m_priority << " > peer=" << m_peer_priority << ")" << endl; - m_yielded_tgs.insert(tg); - TGHandler::instance()->setTalkerForTG(tg, nullptr); + m_yielded_tgs.insert(local_tg); + TGHandler::instance()->setTalkerForTG(local_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(tg); - m_peer_interested_tgs[tg] = std::time(nullptr); - TGHandler::instance()->setTrunkTalkerForTG(tg, msg.callsign()); + m_peer_active_tgs.insert(local_tg); + m_peer_interested_tgs[local_tg] = std::time(nullptr); + TGHandler::instance()->setTrunkTalkerForTG(local_tg, msg.callsign()); } /* TrunkLink::handleMsgTrunkTalkerStart */ @@ -741,15 +836,21 @@ void TrunkLink::handleMsgTrunkTalkerStop(std::istream& is) return; } - uint32_t tg = msg.tg(); - if (!isOwnedTG(tg) && !m_reflector->isClusterTG(tg)) + uint32_t wire_tg = msg.tg(); + uint32_t local_tg = mapTgIn(wire_tg); + if (isBlacklisted(wire_tg) || isBlacklisted(local_tg) || !isAllowed(wire_tg)) + { + return; + } + bool mapped = m_tg_map_in.count(wire_tg) > 0; + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) { return; } - m_yielded_tgs.erase(tg); - m_peer_active_tgs.erase(tg); - TGHandler::instance()->clearTrunkTalkerForTG(tg); + m_yielded_tgs.erase(local_tg); + m_peer_active_tgs.erase(local_tg); + TGHandler::instance()->clearTrunkTalkerForTG(local_tg); } /* TrunkLink::handleMsgTrunkTalkerStop */ @@ -763,27 +864,41 @@ void TrunkLink::handleMsgTrunkAudio(std::istream& is) return; } - uint32_t tg = msg.tg(); - if ((!isOwnedTG(tg) && !m_reflector->isClusterTG(tg)) || msg.audio().empty()) + uint32_t wire_tg = msg.tg(); + uint32_t local_tg = mapTgIn(wire_tg); + if (msg.audio().empty()) return; + if (isBlacklisted(wire_tg) || isBlacklisted(local_tg) || !isAllowed(wire_tg)) + { + return; + } + bool mapped = m_tg_map_in.count(wire_tg) > 0; + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) { return; } // Only forward audio if this peer has claimed the TG via TalkerStart - if (m_peer_active_tgs.find(tg) == m_peer_active_tgs.end()) + if (m_peer_active_tgs.find(local_tg) == m_peer_active_tgs.end()) + { + return; + } + + // PTY-driven mute: drop audio if the current peer talker is muted + std::string cs = TGHandler::instance()->trunkTalkerForTG(local_tg); + if (!cs.empty() && isCallsignMuted(cs)) { return; } // Refresh peer interest timestamp on audio to keep alive during long TX - m_peer_interested_tgs[tg] = std::time(nullptr); + m_peer_interested_tgs[local_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)); + m_reflector->broadcastUdpMsg(udp_msg, ReflectorClient::TgFilter(local_tg)); // Forward trunk audio to connected satellites - m_reflector->forwardAudioToSatellitesExcept(nullptr, tg, msg.audio()); + m_reflector->forwardAudioToSatellitesExcept(nullptr, local_tg, msg.audio()); } /* TrunkLink::handleMsgTrunkAudio */ @@ -797,17 +912,23 @@ void TrunkLink::handleMsgTrunkFlush(std::istream& is) return; } - uint32_t tg = msg.tg(); - if (!isOwnedTG(tg) && !m_reflector->isClusterTG(tg)) + uint32_t wire_tg = msg.tg(); + uint32_t local_tg = mapTgIn(wire_tg); + if (isBlacklisted(wire_tg) || isBlacklisted(local_tg) || !isAllowed(wire_tg)) + { + return; + } + bool mapped = m_tg_map_in.count(wire_tg) > 0; + if (!mapped && !isOwnedTG(wire_tg) && !m_reflector->isClusterTG(wire_tg)) { return; } m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), - ReflectorClient::TgFilter(tg)); + ReflectorClient::TgFilter(local_tg)); // Forward trunk flush to connected satellites - m_reflector->forwardFlushToSatellitesExcept(nullptr, tg); + m_reflector->forwardFlushToSatellitesExcept(nullptr, local_tg); } /* TrunkLink::handleMsgTrunkFlush */ @@ -970,6 +1091,90 @@ void TrunkLink::clearPeerTalkerState(void) } /* TrunkLink::clearPeerTalkerState */ +void TrunkLink::reloadConfig(void) +{ + m_blacklist_filter = TgFilter{}; + m_allow_filter = TgFilter{}; + m_tg_map_in.clear(); + m_tg_map_out.clear(); + + std::string blacklist_str; + if (m_cfg.getValue(m_section, "BLACKLIST_TGS", blacklist_str) + && !blacklist_str.empty()) + { + m_blacklist_filter = TgFilter::parse(blacklist_str); + } + + std::string allow_str; + if (m_cfg.getValue(m_section, "ALLOW_TGS", allow_str) && !allow_str.empty()) + { + m_allow_filter = TgFilter::parse(allow_str); + } + + std::string tgmap_str; + if (m_cfg.getValue(m_section, "TG_MAP", tgmap_str) && !tgmap_str.empty()) + { + std::istringstream ms(tgmap_str); + std::string pair; + while (std::getline(ms, pair, ',')) + { + auto colon = pair.find(':'); + if (colon == std::string::npos) continue; + try { + uint32_t peer_tg = std::stoul(pair.substr(0, colon)); + uint32_t local_tg = std::stoul(pair.substr(colon + 1)); + m_tg_map_in[peer_tg] = local_tg; + m_tg_map_out[local_tg] = peer_tg; + } catch (...) { /* skip malformed */ } + } + } + + cout << m_section << ": Reloaded filters" + << (m_blacklist_filter.empty() ? "" : + " blacklist=" + m_blacklist_filter.toString()) + << (m_allow_filter.empty() ? "" : + " allow=" + m_allow_filter.toString()) + << " tg_map_entries=" << m_tg_map_in.size() << endl; +} /* TrunkLink::reloadConfig */ + + +void TrunkLink::sendNodeList( + const std::vector& nodes) +{ + if (!isActive()) return; + sendMsg(MsgTrunkNodeList(nodes)); +} /* TrunkLink::sendNodeList */ + + +void TrunkLink::handleMsgTrunkNodeList(std::istream& is) +{ + MsgTrunkNodeList msg; + if (!msg.unpack(is)) + { + cerr << "*** ERROR[" << m_section + << "]: Failed to unpack MsgTrunkNodeList" << endl; + return; + } + m_reflector->onPeerNodeList(peerId(), msg.nodes()); +} /* TrunkLink::handleMsgTrunkNodeList */ + + +std::string TrunkLink::statusLine(void) const +{ + ostringstream s; + s << m_section + << " peer_id=" << peerId() + << " ob=" << (isOutboundReady() ? "up" : "down") + << " ib=" << (isInboundReady() ? "up" : "down") + << " active_tgs=" << m_peer_active_tgs.size() + << " muted=" << m_muted_callsigns.size() + << (m_blacklist_filter.empty() ? "" : " [blacklist]") + << (m_allow_filter.empty() ? "" : " [allow]") + << (m_tg_map_in.empty() ? "" : " [tg_map]"); + return s.str(); +} /* TrunkLink::statusLine */ + + /* * This file has not been truncated */ diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 520f5db..876639f 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -52,6 +52,9 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include #include +#include "TgFilter.h" +#include "ReflectorMsg.h" + /**************************************************************************** * @@ -103,6 +106,10 @@ class TrunkLink : public sigc::trackable m_all_prefixes = all_prefixes; } const std::string& section(void) const { return m_section; } + const std::string& peerId(void) const + { + return m_peer_id_received.empty() ? m_section : m_peer_id_received; + } Json::Value statusJson(void) const; @@ -130,6 +137,28 @@ class TrunkLink : public sigc::trackable // Called by Reflector when a local talker's audio stream ends void onLocalFlush(uint32_t tg); + // Send the local node list (callsign + current TG per local client) + // to the peer. Called from Reflector after debounce. + void sendNodeList(const std::vector& nodes); + + // PTY-driven controls + void muteCallsign(const std::string& callsign) + { + m_muted_callsigns.insert(callsign); + } + void unmuteCallsign(const std::string& callsign) + { + m_muted_callsigns.erase(callsign); + } + bool isCallsignMuted(const std::string& callsign) const + { + return m_muted_callsigns.count(callsign) > 0; + } + // Re-parse BLACKLIST_TGS, ALLOW_TGS and TG_MAP from current config + void reloadConfig(void); + // One-line summary for TRUNK STATUS + std::string statusLine(void) const; + private: static const unsigned HEARTBEAT_TX_CNT_RESET = 10; static const unsigned HEARTBEAT_RX_CNT_RESET = 15; @@ -145,6 +174,8 @@ class TrunkLink : public sigc::trackable std::string m_peer_host; uint16_t m_peer_port; std::string m_secret; + std::string m_peer_id_config; // our hello id (from PEER_ID; defaults to section) + 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 uint32_t m_priority; // our tie-break nonce (random, set once) @@ -153,6 +184,11 @@ class TrunkLink : public sigc::trackable Async::FramedTcpConnection* m_inbound_con = nullptr; // accepted inbound Async::Timer m_heartbeat_timer; std::vector m_all_prefixes; // all prefixes in the mesh + TgFilter m_blacklist_filter; // TGs never carried on this link + TgFilter m_allow_filter; // if non-empty: only these TGs pass + std::map m_tg_map_in; // peer wire TG -> local TG + std::map m_tg_map_out; // local TG -> peer wire TG + std::set m_muted_callsigns; // TGs where we suppressed our local talker to defer to the peer std::set m_yielded_tgs; // TGs currently held by this specific trunk peer (for scoped cleanup) @@ -180,6 +216,18 @@ class TrunkLink : public sigc::trackable bool isInboundReady(void) const; bool isOwnedTG(uint32_t tg) const; bool isPeerInterestedTG(uint32_t tg) const; + bool isBlacklisted(uint32_t tg) const; + bool isAllowed(uint32_t tg) const; + uint32_t mapTgIn(uint32_t peer_tg) const + { + auto it = m_tg_map_in.find(peer_tg); + return (it != m_tg_map_in.end()) ? it->second : peer_tg; + } + uint32_t mapTgOut(uint32_t local_tg) const + { + auto it = m_tg_map_out.find(local_tg); + return (it != m_tg_map_out.end()) ? it->second : local_tg; + } void onConnected(void); void onDisconnected(Async::TcpConnection* con, @@ -193,6 +241,7 @@ class TrunkLink : public sigc::trackable void handleMsgTrunkAudio(std::istream& is); void handleMsgTrunkFlush(std::istream& is); void handleMsgTrunkHeartbeat(void); + void handleMsgTrunkNodeList(std::istream& is); void sendMsg(const ReflectorMsg& msg); void sendMsgOnOutbound(const ReflectorMsg& msg); diff --git a/src/svxlink/reflector/svxreflector.conf.in b/src/svxlink/reflector/svxreflector.conf.in index aa19e61..cefa9ee 100644 --- a/src/svxlink/reflector/svxreflector.conf.in +++ b/src/svxlink/reflector/svxreflector.conf.in @@ -104,6 +104,17 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py #PORT=5302 #SECRET=change_this_shared_secret #REMOTE_PREFIX=2 +# Optional PEER_ID — name advertised to the peer in the trunk hello +# (defaults to section name). The peer uses it as the MQTT topic +# component for this link, so set it to a stable, broker-friendly name. +#PEER_ID=reflector-a +# Optional per-trunk TG filters (syntax: exact "26200", prefix "24*", +# range "2427-2438", comma-separated): +#BLACKLIST_TGS=666,777* # never carried in either direction on this link +#ALLOW_TGS=24*,2624123 # if set, ONLY these TGs are exchanged +# 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 # --- Satellite reflectors --- # A satellite is a lightweight reflector that connects to a parent @@ -136,6 +147,10 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py #USERNAME=reflector #PASSWORD=secret #TOPIC_PREFIX=svxreflector/myreflector +# Optional MQTT_NAME — appended as a path component, so topics become +# //... — useful when several reflectors share +# the same TOPIC_PREFIX. Leave unset to keep topics flat. +#MQTT_NAME=reflector-01 #STATUS_INTERVAL=1000 #TLS_ENABLED=0 #TLS_CA_CERT=/path/to/ca.crt diff --git a/src/versions b/src/versions index fcbdf24..5a21944 100644 --- a/src/versions +++ b/src/versions @@ -37,4 +37,4 @@ DEVCAL=1.0.4.99.3 SVXSERVER=0.0.6.99.0 # Version for SvxReflector -SVXREFLECTOR=1.3.99.12+trunk +SVXREFLECTOR=1.3.99.13+trunk diff --git a/tests/TESTS.md b/tests/TESTS.md index 87131c4..139bae9 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -16,7 +16,7 @@ bash run_tests.sh This will: 1. Generate configs and `docker-compose.test.yml` from `topology.py` 2. Build and start the 3-reflector mesh -3. Run 17 automated tests +3. Run 27 automated tests 4. Enter an interactive prompt to manually test any TG number 5. Tear down the mesh on exit (or Ctrl-C) @@ -126,6 +126,36 @@ Simulates a V2 SvxLink client. Performs the full TCP authentication handshake (P |---|------|-----------------| | 17 | Bidirectional trunk conversation | Client-A on reflector-a talks on a TG owned by reflector-b, Client-B on reflector-b receives it; Client-B replies, Client-A receives the return audio (peer interest tracking) | +### MQTT Publishing + +| # | Test | What it verifies | +|---|------|-----------------| +| 18 | MQTT talker event | Talker start/stop on a trunk publishes to `/talker//(start|stop)` | +| 26 | `MQTT_NAME` in topic | Reflector with `MQTT_NAME=mqname-c` publishes node-list under `/c/mqname-c/nodes/local` | + +### Per-Trunk Filters and Mapping (jayReflector additions) + +A third test peer `TRUNK_TEST_FILTER` (prefix `7`, secret `test_secret_filter`) +is configured with `PEER_ID=filter-peer`, `BLACKLIST_TGS=12345`, +`ALLOW_TGS=7*,1220`, and `TG_MAP=7000:1220` so these tests can verify +each filter independently of the other trunk fixtures. + +| # | Test | What it verifies | +|---|------|-----------------| +| 19 | `PEER_ID` in hello | Reflector advertises the configured `PEER_ID` (not the section name) in `MsgTrunkHello` | +| 20 | `BLACKLIST_TGS` drops TG | TalkerStart on a blacklisted TG is dropped (not in `/status` active talkers) | +| 21 | `ALLOW_TGS` whitelist | TG matching the whitelist passes; TG outside is dropped | +| 22 | `TG_MAP` remap | TalkerStart on wire TG `7000` is remapped and tracked as local TG `1220` | +| 23 | PTY `TRUNK STATUS` | Command is accepted; `TRUNK_TEST_FILTER` is loaded by the reflector | +| 24 | PTY `TRUNK MUTE` | Audio from a muted callsign is dropped before reaching local clients | +| 25 | PTY `TRUNK RELOAD` | After live `CFG` update of `BLACKLIST_TGS`, `TRUNK RELOAD` re-reads it and the formerly-allowed TG is now blocked | + +### Trunk Node-List Exchange + +| # | Test | What it verifies | +|---|------|-----------------| +| 27 | `MsgTrunkNodeList` emission | Connecting a V2 client triggers a debounced node-list send to trunk peers; the harness receives a `MsgTrunkNodeList` (type 121) containing the new client | + ## Interactive Mode After the automated tests pass, an interactive prompt lets you test any TG number: diff --git a/tests/generate_configs.py b/tests/generate_configs.py index b79b860..b4d20da 100644 --- a/tests/generate_configs.py +++ b/tests/generate_configs.py @@ -73,6 +73,16 @@ def generate_reflector_conf(name: str) -> str: f"SECRET={T.TEST_PEER_RX['secret']}", f"REMOTE_PREFIX={T.prefix_str(T.TEST_PEER_RX['prefix'])}", "", + "[TRUNK_TEST_FILTER]", + "HOST=192.0.2.1", + "PORT=59304", + f"SECRET={T.TEST_PEER_FILTER['secret']}", + f"REMOTE_PREFIX={T.prefix_str(T.TEST_PEER_FILTER['prefix'])}", + f"PEER_ID={T.TEST_PEER_FILTER['peer_id']}", + f"BLACKLIST_TGS={T.TEST_PEER_FILTER['blacklist_tgs']}", + f"ALLOW_TGS={T.TEST_PEER_FILTER['allow_tgs']}", + f"TG_MAP={T.TEST_PEER_FILTER['tg_map']}", + "", ] # Satellite server section (only on the primary reflector) @@ -94,8 +104,10 @@ def generate_reflector_conf(name: str) -> str: f"PASSWORD={T.MQTT['password']}", f"TOPIC_PREFIX=svxreflector/{name}", "STATUS_INTERVAL=1000", - "", ] + if name in T.MQTT_NAMES: + lines.append(f"MQTT_NAME={T.MQTT_NAMES[name]}") + lines.append("") return "\n".join(lines) diff --git a/tests/test_trunk.py b/tests/test_trunk.py index bc09b8e..5dc91e6 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -17,6 +17,7 @@ import os import re import socket import struct +import subprocess import sys import threading import time @@ -67,6 +68,11 @@ MSG_TRUNK_TALKER_STOP = 117 MSG_TRUNK_AUDIO = 118 MSG_TRUNK_FLUSH = 119 MSG_TRUNK_HEARTBEAT = 120 +MSG_TRUNK_NODE_LIST = 121 + +# Filter test peer constants +FILTER_SECRET = T.TEST_PEER_FILTER["secret"] +FILTER_PREFIX = T.prefix_str(T.TEST_PEER_FILTER["prefix"]) # --------------------------------------------------------------------------- # Wire format helpers @@ -196,6 +202,32 @@ def parse_msg(data: bytes): return msg_type, {"tg": tg} elif msg_type == MSG_TRUNK_HEARTBEAT: return msg_type, {} + elif msg_type == MSG_TRUNK_NODE_LIST: + # vec callsigns, vec tgs, vec lat, vec lon, + # vec qth_names. Each vector is u32-prefixed length. + def read_vec_str(off): + n = struct.unpack_from("!I", data, off)[0]; off += 4 + out = [] + for _ in range(n): + s, off = unpack_string(data, off) + out.append(s) + return out, off + + def read_vec_u32(off): + n = struct.unpack_from("!I", data, off)[0]; off += 4 + out = list(struct.unpack_from(f"!{n}I", data, off)) + off += 4 * n + return out, off + + def read_vec_f32(off): + n = struct.unpack_from("!I", data, off)[0]; off += 4 + out = list(struct.unpack_from(f"!{n}f", data, off)) + off += 4 * n + return out, off + + callsigns, off = read_vec_str(off) + tgs, off = read_vec_u32(off) + return msg_type, {"callsigns": callsigns, "tgs": tgs} else: return msg_type, {"raw": data[off:]} @@ -530,6 +562,38 @@ def wait_for_trunk_connected(host: str, port: int, trunk_name: str, msg=f"trunk {trunk_name} on {host}:{port} not connected") +def pty_send(reflector_name: str, command: str, timeout: float = 5.0) -> str: + """Write a line to /dev/shm/reflector_ctrl inside a reflector container + and return the captured stdout (the reflector echoes responses there + over the next ~200ms — we just confirm the write succeeded).""" + svc = T.service_name(reflector_name) + # bash here-string ensures a trailing newline (line-buffered PTY) + proc = subprocess.run( + ["docker", "compose", "-f", "docker-compose.test.yml", + "exec", "-T", svc, + "bash", "-c", f"printf '%s\\n' {repr(command)} > /dev/shm/reflector_ctrl"], + cwd=os.path.dirname(os.path.abspath(__file__)), + capture_output=True, text=True, timeout=timeout, + ) + if proc.returncode != 0: + raise RuntimeError( + f"pty_send to {svc} failed: rc={proc.returncode} " + f"stderr={proc.stderr.strip()}") + return proc.stdout + + +def docker_logs_since(reflector_name: str, since: str = "5s") -> str: + """Return the stdout/stderr of a reflector container since N seconds ago.""" + svc = T.service_name(reflector_name) + proc = subprocess.run( + ["docker", "compose", "-f", "docker-compose.test.yml", + "logs", "--no-color", "--since", since, svc], + cwd=os.path.dirname(os.path.abspath(__file__)), + capture_output=True, text=True, timeout=10.0, + ) + return proc.stdout + proc.stderr + + # --------------------------------------------------------------------------- # Test cases # --------------------------------------------------------------------------- @@ -1273,6 +1337,325 @@ class TestTrunkIntegration(unittest.TestCase): mc.loop_stop() mc.disconnect() + # ------------------------------------------------------------------ + # Test 19: PEER_ID is advertised in MsgTrunkHello + # ------------------------------------------------------------------ + def test_19_peer_id_in_hello(self): + """When PEER_ID is configured, the reflector advertises it (not the + section name) in its outbound hello on the TRUNK_TEST_FILTER link.""" + # Listen for an outbound connection on port 59304 — the reflector + # is configured to dial 192.0.2.1:59304 which is a black hole, so + # we can't capture *that*. Instead we verify the PEER_ID via the + # inbound side: we connect to the reflector's trunk port and send + # a hello as the FILTER peer; the reflector replies with its hello + # using PEER_ID="filter-peer". + peer = TrunkPeer() + peer.connect(*_trunk(self.PRIMARY)) + msg_type, fields = peer.handshake( + trunk_id="TRUNK_TEST_FILTER", + local_prefix=FILTER_PREFIX, + secret=FILTER_SECRET, + ) + try: + self.assertEqual(msg_type, MSG_TRUNK_HELLO) + self.assertEqual(fields["id"], T.TEST_PEER_FILTER["peer_id"], + f"Expected PEER_ID '{T.TEST_PEER_FILTER['peer_id']}' " + f"in reflector's hello, got '{fields['id']}'") + finally: + peer.close() + + # ------------------------------------------------------------------ + # Test 20: BLACKLIST_TGS drops talker on receive path + # ------------------------------------------------------------------ + def test_20_blacklist_drops_tg(self): + """A TalkerStart on a blacklisted TG must NOT appear as an active + talker on the receiving reflector.""" + peer = TrunkPeer() + peer.connect(*_trunk(self.PRIMARY)) + peer.handshake(trunk_id="TRUNK_TEST_FILTER", + local_prefix=FILTER_PREFIX, + secret=FILTER_SECRET) + try: + blocked_tg = int(T.TEST_PEER_FILTER["blacklist_tgs"]) + peer.send_talker_start(blocked_tg, "N0BLACK") + time.sleep(1.0) + + status = get_status(*_http(self.PRIMARY)) + active = status["trunks"].get( + "TRUNK_TEST_FILTER", {}).get("active_talkers", {}) + self.assertNotIn(str(blocked_tg), active, + f"Blacklisted TG {blocked_tg} appeared as active talker: " + f"{active}") + finally: + peer.close() + + # ------------------------------------------------------------------ + # Test 21: ALLOW_TGS rejects TGs not in the whitelist + # ------------------------------------------------------------------ + def test_21_allow_tgs_blocks_others(self): + """ALLOW_TGS=7*,1220 — TG 7100 must pass, TG 99 must be dropped.""" + peer = TrunkPeer() + peer.connect(*_trunk(self.PRIMARY)) + peer.handshake(trunk_id="TRUNK_TEST_FILTER", + local_prefix=FILTER_PREFIX, + secret=FILTER_SECRET) + try: + allowed_tg = 7100 # matches "7*" + peer.send_talker_start(allowed_tg, "N0ALLOW") + disallowed_tg = 99 # matches neither "7*" nor "1220" + peer.send_talker_start(disallowed_tg, "N0BLOCK") + time.sleep(1.0) + + active = get_status(*_http(self.PRIMARY))[ + "trunks"]["TRUNK_TEST_FILTER"]["active_talkers"] + self.assertIn(str(allowed_tg), active, + f"Allowed TG {allowed_tg} missing from active talkers: " + f"{active}") + self.assertNotIn(str(disallowed_tg), active, + f"Disallowed TG {disallowed_tg} should not be active: " + f"{active}") + finally: + peer.close() + + # ------------------------------------------------------------------ + # Test 22: TG_MAP remaps incoming TGs + # ------------------------------------------------------------------ + def test_22_tg_map_remap_in(self): + """TG_MAP=7000:1220 — peer sends TalkerStart on wire TG 7000, + reflector should track it as local TG 1220.""" + peer = TrunkPeer() + peer.connect(*_trunk(self.PRIMARY)) + peer.handshake(trunk_id="TRUNK_TEST_FILTER", + local_prefix=FILTER_PREFIX, + secret=FILTER_SECRET) + try: + wire_tg, local_tg = 7000, 1220 + peer.send_talker_start(wire_tg, "N0MAP") + time.sleep(1.0) + + active = get_status(*_http(self.PRIMARY))[ + "trunks"]["TRUNK_TEST_FILTER"]["active_talkers"] + # After mapping, the reflector tracks the LOCAL TG + self.assertIn(str(local_tg), active, + f"Mapped local TG {local_tg} not active " + f"(after wire TG {wire_tg}): {active}") + self.assertNotIn(str(wire_tg), active, + f"Wire TG {wire_tg} should have been remapped to " + f"{local_tg}: {active}") + finally: + peer.close() + + # ------------------------------------------------------------------ + # Test 23: PTY TRUNK STATUS lists trunks + # ------------------------------------------------------------------ + def test_23_pty_trunk_status(self): + """`TRUNK STATUS` over PTY enumerates the configured trunks.""" + # Issue command and read the docker logs for the reflector's PTY + # echo (the reflector also writes the response back to the PTY, + # which our subprocess can't read — so we check that the command + # was accepted via no-error from pty_send). + out = pty_send(self.PRIMARY, "TRUNK STATUS") + # The actual list goes back to the PTY reader. Best we can do + # without a PTY reader is verify the command did not error and + # the per-link config was previously logged at startup. + logs = docker_logs_since(self.PRIMARY, since="120s") + self.assertIn("TRUNK_TEST_FILTER", logs, + "TRUNK_TEST_FILTER section was not loaded by reflector " + f"(out={out!r}, logs head={logs[:400]!r})") + + # ------------------------------------------------------------------ + # Test 24: PTY TRUNK MUTE blocks audio from the muted callsign + # ------------------------------------------------------------------ + def test_24_pty_trunk_mute(self): + """After TRUNK MUTE on a callsign, audio from that callsign on + the muted trunk link is dropped (not delivered to local clients).""" + peer = TrunkPeer() + peer.connect(*_trunk(self.PRIMARY)) + peer.handshake(trunk_id="TRUNK_TEST_FILTER", + local_prefix=FILTER_PREFIX, + secret=FILTER_SECRET) + try: + local_tg = 1220 # via TG_MAP from wire 7000 + wire_tg = 7000 + + # Mute first, then claim TG and send audio + pty_send(self.PRIMARY, + "TRUNK MUTE TRUNK_TEST_FILTER N0MUTE") + time.sleep(0.3) + + # Local listener + listener = ClientPeer() + port = T.mapped_client_port(self.PRIMARY) + listener.connect(HOST, port) + listener.authenticate(callsign=CLIENT_CALLSIGN, + password=CLIENT_PASSWORD) + listener.setup_udp(udp_port=port) + listener.select_tg(local_tg) + time.sleep(0.3) + + peer.send_talker_start(wire_tg, "N0MUTE") + for _ in range(5): + peer.send_audio(wire_tg, b"\xAA" * 80) + time.sleep(0.02) + time.sleep(1.0) + + msgs = listener.recv_udp_all(timeout=1.0) + audio_count = sum(1 for t, _ in msgs if t == UDP_AUDIO) + listener.close() + + # Cleanup mute + pty_send(self.PRIMARY, + "TRUNK UNMUTE TRUNK_TEST_FILTER N0MUTE") + + self.assertEqual(audio_count, 0, + f"Listener received {audio_count} audio frame(s) for " + f"muted callsign N0MUTE on TG {local_tg}") + finally: + peer.close() + + # ------------------------------------------------------------------ + # Test 25: PTY TRUNK RELOAD re-reads BLACKLIST after live CFG update + # ------------------------------------------------------------------ + def test_25_pty_trunk_reload(self): + """CFG-update BLACKLIST_TGS for TRUNK_TEST_FILTER, then TRUNK RELOAD + — a TG that was previously allowed must now be blocked.""" + peer = TrunkPeer() + peer.connect(*_trunk(self.PRIMARY)) + peer.handshake(trunk_id="TRUNK_TEST_FILTER", + local_prefix=FILTER_PREFIX, + secret=FILTER_SECRET) + try: + tg_to_block = 7200 # currently allowed by ALLOW_TGS=7* + + # Sanity: it currently goes through + peer.send_talker_start(tg_to_block, "N0PRE") + time.sleep(0.5) + active = get_status(*_http(self.PRIMARY))[ + "trunks"]["TRUNK_TEST_FILTER"]["active_talkers"] + self.assertIn(str(tg_to_block), active, + f"Pre-reload: TG {tg_to_block} should be active, got {active}") + peer.send_talker_stop(tg_to_block) + time.sleep(0.3) + + # Update config + reload + pty_send(self.PRIMARY, + f"CFG TRUNK_TEST_FILTER BLACKLIST_TGS {tg_to_block}") + pty_send(self.PRIMARY, "TRUNK RELOAD TRUNK_TEST_FILTER") + time.sleep(0.5) + + # Now it must be blocked + peer.send_talker_start(tg_to_block, "N0POST") + time.sleep(0.5) + active = get_status(*_http(self.PRIMARY))[ + "trunks"]["TRUNK_TEST_FILTER"]["active_talkers"] + self.assertNotIn(str(tg_to_block), active, + f"Post-reload: TG {tg_to_block} should be blacklisted, " + f"got {active}") + + # Restore original config so other tests aren't affected + pty_send(self.PRIMARY, + f"CFG TRUNK_TEST_FILTER BLACKLIST_TGS " + f"{T.TEST_PEER_FILTER['blacklist_tgs']}") + pty_send(self.PRIMARY, "TRUNK RELOAD TRUNK_TEST_FILTER") + finally: + peer.close() + + # ------------------------------------------------------------------ + # Test 26: MQTT_NAME inserts a path component before the topic suffix + # ------------------------------------------------------------------ + def test_26_mqtt_name_in_topic(self): + """Reflector 'c' has MQTT_NAME=mqname-c → topics live under + svxreflector/c/mqname-c/... — verify a node-list update arrives + on the namespaced 'nodes/local' topic.""" + received = [] + connected_event = threading.Event() + topic_sub = f"svxreflector/c/{T.MQTT_NAMES['c']}/nodes/local" + + def on_connect(client, userdata, flags, rc): + client.subscribe(topic_sub) + connected_event.set() + + def on_message(client, userdata, msg): + received.append((msg.topic, msg.payload.decode())) + + mc = mqtt_client.Client() + mc.on_connect = on_connect + mc.on_message = on_message + mc.connect(HOST, 11883, 60) + mc.loop_start() + try: + self.assertTrue(connected_event.wait(timeout=5), + "MQTT subscribe timed out") + time.sleep(0.5) + + # Trigger a node-list update by connecting a client to 'c' + client = ClientPeer() + port = T.mapped_client_port("c") + client.connect(HOST, port) + client.authenticate(callsign=CLIENT_CALLSIGN, + password=CLIENT_PASSWORD) + try: + # Wait for a retained or fresh message + wait_until(lambda: len(received) > 0, timeout=5.0, + msg=f"no message on {topic_sub}") + topic, payload = received[-1] + self.assertEqual(topic, topic_sub) + self.assertIn("nodes", payload) + finally: + client.close() + finally: + mc.loop_stop() + mc.disconnect() + + # ------------------------------------------------------------------ + # Test 27: MsgTrunkNodeList is emitted on local client login + # ------------------------------------------------------------------ + def test_27_node_list_emitted_to_trunk_peer(self): + """Connect as the TRUNK_TEST_RX harness, then connect a V2 client + on the primary reflector — within the debounce window the harness + must receive a MsgTrunkNodeList containing that client.""" + rx = TrunkPeer() + rx.connect(*_trunk(self.PRIMARY)) + rx.handshake(trunk_id="TRUNK_TEST_RX", + local_prefix=TEST_RX_PREFIX, + secret=TEST_RX_SECRET) + try: + # Drain any messages already queued from existing local state + rx.sock.settimeout(0.5) + try: + while True: + recv_frame(rx.sock) + except (socket.timeout, ConnectionError): + pass + rx.sock.settimeout(5.0) + + # Trigger: new client connects → debounced node-list emission + client = ClientPeer() + port = T.mapped_client_port(self.PRIMARY) + client.connect(HOST, port) + client.authenticate(callsign=CLIENT_CALLSIGN, + password=CLIENT_PASSWORD) + try: + # Wait up to 5s for a NodeList frame containing our callsign + deadline = time.monotonic() + 5.0 + found = False + while time.monotonic() < deadline and not found: + try: + msg_type, fields = rx.recv_msg(timeout=1.0) + except socket.timeout: + continue + if msg_type != MSG_TRUNK_NODE_LIST: + continue + if CLIENT_CALLSIGN in fields["callsigns"]: + found = True + self.assertTrue(found, + f"No MsgTrunkNodeList containing {CLIENT_CALLSIGN} " + f"was received on the trunk") + finally: + client.close() + finally: + rx.close() + # --------------------------------------------------------------------------- # Custom test runner with clean, readable output diff --git a/tests/topology.py b/tests/topology.py index dac7cc5..e1da69b 100644 --- a/tests/topology.py +++ b/tests/topology.py @@ -29,6 +29,25 @@ TEST_PEER_RX = { "secret": "test_secret_rx", } +# Third test peer used to exercise per-link BLACKLIST_TGS / ALLOW_TGS / +# TG_MAP / PEER_ID. Kept isolated from TEST_PEER so routing tests don't +# interact with filter tests. +TEST_PEER_FILTER = { + "prefix": ["7"], + "secret": "test_secret_filter", + "peer_id": "filter-peer", + "blacklist_tgs": "12345", + "allow_tgs": "7*,1220", + "tg_map": "7000:1220", +} + +# Per-reflector MQTT_NAME overrides — when set, the reflector publishes +# under //... so tests can verify the new key +# without breaking the flat-topic MQTT test on reflector 'a'. +MQTT_NAMES = { + "c": "mqname-c", +} + # Cluster TGs — forwarded to all peers regardless of prefix ownership # 8000: no prefix match (not owned by any reflector) # 1201: starts with prefix "120" (overlaps with reflector-a's ownership)