diff --git a/docs/TRUNK_PROTOCOL.md b/docs/TRUNK_PROTOCOL.md index d826c3f..b3a6d28 100644 --- a/docs/TRUNK_PROTOCOL.md +++ b/docs/TRUNK_PROTOCOL.md @@ -388,7 +388,7 @@ payload, packed using the `ASYNC_MSG_MEMBERS` macro. | 118 | `MsgTrunkAudio` | `uint32 tg`, `uint8[] audio` | | 119 | `MsgTrunkFlush` | `uint32 tg` | | 120 | `MsgTrunkHeartbeat` | *(no fields)* | -| 121 | `MsgTrunkNodeList` | `string[] callsigns`, `uint32[] tgs`, `float[] lats`, `float[] lons`, `string[] qth_names`, `string[] status_blobs` | +| 121 | `MsgTrunkNodeList` | `string[] callsigns`, `uint32[] tgs`, `float[] lats`, `float[] lons`, `string[] qth_names`, `string[] status_blobs`, `string[] sat_ids` | | 122 | `MsgTrunkFilter` | `string filter` (shared-syntax TG filter: exact / `24*` / `10-20`, comma-separated) | Type numbers 115–120 are chosen to follow the last existing SvxReflector TCP @@ -414,12 +414,47 @@ would be stale by the time it arrives); it is derived on the receive side from the live trunk-talker map maintained by `MsgTrunkTalkerStart` / `MsgTrunkTalkerStop`. -Wire-format note: extending this message (the `status_blobs` vector was -added on top of the original 5 vectors) is a lockstep change. A peer -running an older fork build that knows type 121 but expects only 5 -vectors will fail to unpack and reject the message, which silently empties -the partner roster on that peer until it is upgraded. Peers that don't -know type 121 at all (pre-jayReflector) keep ignoring it as before. +The optional `sat_ids[i]` field tags each entry with the satellite that +the client is actually attached to. Interpretation is **recipient-relative**: +an empty string means *"on whoever sent this list"*, and a non-empty value +identifies a satellite hanging off the sender. The field exists so a parent +reflector can advertise both its own clients (`sat_id=""`) and clients +learned from each connected satellite (`sat_id=`) in a single +message, while letting the recipient distinguish them in `/status` and +Redis. Receivers preserve `sat_id` verbatim under +`/status.trunks[
].nodes[i].sat_id` (and `/status.twin.nodes[i].sat_id` +on twin links). + +Wire-format note: type 121 has been extended **twice** since its initial +shipment. Each addition is a hard lockstep change (Async-msg unpack +expects an exact vector count): first `status_blobs` (raising the count +from 5 to 6), then `sat_ids` (raising it to 7). A peer running an older +fork build that knows type 121 but expects fewer vectors will fail to +unpack and reject the message, which silently empties the partner roster +on that peer until it is upgraded. **All trunk, twin, and satellite peers +in a mesh must be upgraded together.** Peers that don't know type 121 at +all (pre-jayReflector) keep ignoring it as before. + +### Node-list flow with multiple satellites + +When a parent reflector has two or more satellites (S1, S2) attached, each +participant is given a single shared view of the mesh roster: + +- **Parent → trunks/twin:** sends parent-local clients (`sat_id=""`) + merged with every connected satellite's contribution (`sat_id=`). +- **Parent → satellite Si:** sends parent-local + every *other* + satellite's contribution; Si's own roster is excluded + (self-echo guard). The list is additionally filtered by + Si's `SATELLITE_FILTER` if any. +- **Satellite → parent:** sends the satellite's local clients only, with + `sat_id=""` on the wire. The parent stamps each ingested entry with + `sat_id=` so subsequent fanouts attribute correctly. + +Result: every reflector and every satellite shows the same set of callsigns +in its `/status`, with each entry tagged so consumers can tell where it +physically lives. Re-broadcasts are debounced (500 ms) and triggered by: +local client login/logout/TG change, satellite hello completion, and +inbound satellite node-list updates. `MsgTrunkFilter` is used by satellite links to advertise TG interest to the parent. A satellite with `SATELLITE_FILTER` set sends one `MsgTrunkFilter` diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 8cb3721..550aa86 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -1768,6 +1768,30 @@ void Reflector::refreshStatus(void) sat_cfg["parent_host"] = sat_of; if (!sat_port_str.empty()) sat_cfg["parent_port"] = sat_port_str; if (!sat_id.empty()) sat_cfg["id"] = sat_id; + if (m_satellite_client != nullptr) + { + const auto& parent_id = m_satellite_client->parentId(); + if (!parent_id.empty()) sat_cfg["parent_id"] = parent_id; + Json::Value pnodes(Json::arrayValue); + for (const auto& n : m_satellite_client->parentNodes()) + { + Json::Value entry = n.status.isObject() + ? n.status : Json::Value(Json::objectValue); + entry["callsign"] = n.callsign; + entry["tg"] = static_cast(n.tg); + if (n.lat != 0.0f || n.lon != 0.0f) + { + entry["lat"] = n.lat; + entry["lon"] = n.lon; + } + if (!n.qth_name.empty()) entry["qth_name"] = n.qth_name; + if (!n.sat_id.empty()) entry["sat_id"] = n.sat_id; + entry["isTalker"] = + (TGHandler::instance()->trunkTalkerForTG(n.tg) == n.callsign); + pnodes.append(entry); + } + sat_cfg["parent_nodes"] = pnodes; + } m_status["satellite"] = sat_cfg; } else @@ -3218,7 +3242,8 @@ void Reflector::scheduleNodeListUpdate(void) void Reflector::sendNodeListToAllPeers(void) { - std::vector nodes; + // 1. Local clients — sat_id stays empty (recipient-relative: "on me"). + std::vector local_nodes; for (const auto& kv : m_client_con_map) { ReflectorClient* c = kv.second; @@ -3248,22 +3273,63 @@ void Reflector::sendNodeListToAllPeers(void) e.qth_name = qth["name"].asString(); } } - nodes.push_back(e); + local_nodes.push_back(e); } + // 2. Combined view = local + every connected satellite's stamped roster. + // Each sat-supplied entry already carries sat_id == its satelliteId. + std::vector combined = local_nodes; + for (const auto& kv : m_satellite_con_map) + { + const auto& sat_nodes = kv.second->partnerNodes(); + combined.insert(combined.end(), sat_nodes.begin(), sat_nodes.end()); + } + + // 3. Trunks and twin: full combined view. Trunk peers and twin partners + // see the parent's clients (sat_id="") and every satellite's clients + // (sat_id=) in a single list. for (auto* link : m_trunk_links) { - link->sendNodeList(nodes); + link->sendNodeList(combined); } - if (m_twin_link != nullptr) { - m_twin_link->onLocalNodeListUpdated(nodes); + m_twin_link->onLocalNodeListUpdated(combined); } + // 4. Each satellite gets the combined view minus its own contribution + // (self-echo guard: a satellite must not be told about its own + // clients). SatelliteLink::sendNodeList additionally applies that + // satellite's announced TG filter. + for (const auto& kv : m_satellite_con_map) + { + SatelliteLink* link = kv.second; + const std::string& this_sat_id = link->satelliteId(); + + std::vector for_this_sat; + for_this_sat.reserve(combined.size()); + for (const auto& n : combined) + { + if (!this_sat_id.empty() && n.sat_id == this_sat_id) continue; + for_this_sat.push_back(n); + } + link->sendNodeList(for_this_sat); + } + + // 5. If we are a satellite ourselves, advertise our local roster up to + // the parent. We send local clients only (sat_id=""); any deeper + // satellite hierarchy is collapsed by the parent's ingest stamping. + if (m_is_satellite && m_satellite_client != nullptr) + { + m_satellite_client->sendNodeList(local_nodes); + } + + // 6. MQTT — keep scope to parent-local clients (sat-supplied entries + // already get a publish via SatelliteLink::handleMsgTrunkNodeList + // calling onPeerNodeList → MqttPublisher::publishPeerNodes). if (m_mqtt != nullptr) { - m_mqtt->publishLocalNodes(nodes); + m_mqtt->publishLocalNodes(local_nodes); } } /* Reflector::sendNodeListToAllPeers */ diff --git a/src/svxlink/reflector/ReflectorMsg.h b/src/svxlink/reflector/ReflectorMsg.h index b5e5e1d..34aeb06 100644 --- a/src/svxlink/reflector/ReflectorMsg.h +++ b/src/svxlink/reflector/ReflectorMsg.h @@ -1829,16 +1829,23 @@ Sent by a reflector to its trunk peer whenever its local client list changes MQTT publisher. Older peers that don't know type 121 ignore it — fully backward compatible. -Each entry carries callsign, current TG, optional lat/lon/QTH name, and +Each entry carries callsign, current TG, optional lat/lon/QTH name, the full per-client status blob (rx/tx config, qth array, monitoredTGs, -restrictedTG, protoVer, ...) so that a peer's /status, MQTT topic and -Redis snapshot can render partner nodes with the same richness as local -ones. The blob is the source reflector's `m_status["nodes"][callsign]` -JSON serialised verbatim; receivers parse and sanitise it. +restrictedTG, protoVer, ...), and an optional sat_id tagging the +satellite the client is actually attached to (empty when the client is +on the sender directly). The blob is the source reflector's +`m_status["nodes"][callsign]` JSON serialised verbatim; receivers parse +and sanitise it. -Wire-format note: extending this message (m_status_blobs added on top of -the original 5 vectors) is NOT compatible with peers running an older -build of the same fork — the unpack expects exactly six vectors. All +The sat_id is interpreted recipient-relative: an empty string means +"directly attached to whoever sent me this list." Used so that when a +parent reflector advertises both its own clients and clients learned +from its satellites, the recipient (a trunk peer or another satellite) +can tell them apart. + +Wire-format note: this message has been extended TWICE — first to add +m_status_blobs, then to add m_sat_ids. Each extension is a hard +lockstep bump because the unpack expects an exact vector count. All peers in a mesh must be upgraded together. */ class MsgTrunkNodeList : public ReflectorMsgBase<121> @@ -1853,6 +1860,9 @@ class MsgTrunkNodeList : public ReflectorMsgBase<121> std::string qth_name; Json::Value status; // rich per-client status; transported as // m_status_blobs[i] over the wire + std::string sat_id; // empty = on sender directly; otherwise + // satellite_id of the satellite attached to + // the sender that this client lives on }; MsgTrunkNodeList(void) {} @@ -1870,6 +1880,7 @@ class MsgTrunkNodeList : public ReflectorMsgBase<121> m_status_blobs.push_back( n.status.isNull() ? std::string() : Json::writeString(wb, n.status)); + m_sat_ids.push_back(n.sat_id); } } @@ -1901,13 +1912,14 @@ class MsgTrunkNodeList : public ReflectorMsgBase<121> } } } + e.sat_id = (i < m_sat_ids.size()) ? m_sat_ids[i] : ""; result.push_back(e); } return result; } ASYNC_MSG_MEMBERS(m_callsigns, m_tgs, m_lats, m_lons, m_qth_names, - m_status_blobs) + m_status_blobs, m_sat_ids) private: std::vector m_callsigns; @@ -1916,6 +1928,7 @@ class MsgTrunkNodeList : public ReflectorMsgBase<121> std::vector m_lons; std::vector m_qth_names; std::vector m_status_blobs; + std::vector m_sat_ids; }; /* MsgTrunkNodeList */ diff --git a/src/svxlink/reflector/SatelliteClient.cpp b/src/svxlink/reflector/SatelliteClient.cpp index 7f3f913..19d3869 100644 --- a/src/svxlink/reflector/SatelliteClient.cpp +++ b/src/svxlink/reflector/SatelliteClient.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -16,6 +17,75 @@ using namespace std; using namespace Async; using namespace sigc; +namespace { + +std::string sanitizeIdent(const std::string& in, size_t max_len) +{ + std::string out; + out.reserve(std::min(in.size(), max_len)); + for (char c : in) + { + unsigned char u = static_cast(c); + if (u < 0x20 || u == 0x7f) continue; + if (c == ':') continue; + out += c; + if (out.size() >= max_len) break; + } + return out; +} + +std::string sanitizeText(const std::string& in, size_t max_bytes) +{ + std::string out; + out.reserve(std::min(in.size(), max_bytes)); + for (char c : in) + { + unsigned char u = static_cast(c); + if (u < 0x20 || u == 0x7f) continue; + out += c; + if (out.size() >= max_bytes) break; + } + return out; +} + +void sanitizeJsonStrings(Json::Value& v, unsigned depth = 0) +{ + static constexpr unsigned MAX_DEPTH = 8; + static constexpr Json::ArrayIndex MAX_LEN = 256; + static constexpr size_t MAX_STR_BYTES = 1024; + if (depth >= MAX_DEPTH) { v = Json::Value(); return; } + if (v.isString()) + { + v = sanitizeText(v.asString(), MAX_STR_BYTES); + } + else if (v.isArray()) + { + if (v.size() > MAX_LEN) v.resize(MAX_LEN); + for (Json::ArrayIndex i = 0; i < v.size(); ++i) + { + sanitizeJsonStrings(v[i], depth + 1); + } + } + else if (v.isObject()) + { + auto names = v.getMemberNames(); + if (names.size() > MAX_LEN) + { + for (size_t i = MAX_LEN; i < names.size(); ++i) + { + v.removeMember(names[i]); + } + names.resize(MAX_LEN); + } + for (const auto& k : names) + { + sanitizeJsonStrings(v[k], depth + 1); + } + } +} + +} // namespace + SatelliteClient::SatelliteClient(Reflector* reflector, Async::Config& cfg) : m_reflector(reflector), m_cfg(cfg), @@ -143,6 +213,15 @@ void SatelliteClient::onDisconnected(TcpConnection* con, m_heartbeat_timer.setEnable(false); m_hello_received = false; TGHandler::instance()->clearAllTrunkTalkers(); + + if (!m_parent_nodes.empty() && !m_parent_id.empty()) + { + // Tombstone-clear Redis live:peer_node::* and let MQTT + // emit an empty list so consumers see the partner roster drop. + m_reflector->onPeerNodeList(m_parent_id, + std::vector{}); + m_parent_nodes.clear(); + } } /* SatelliteClient::onDisconnected */ @@ -189,6 +268,9 @@ void SatelliteClient::onFrameReceived(FramedTcpConnection* con, case MsgTrunkFlush::TYPE: handleMsgTrunkFlush(ss); break; + case MsgTrunkNodeList::TYPE: + handleMsgTrunkNodeList(ss); + break; default: break; } @@ -217,11 +299,17 @@ void SatelliteClient::handleMsgTrunkHello(std::istream& is) } m_hello_received = true; + m_parent_id = sanitizeIdent(msg.id(), 64); geulog::info("satellite", "Parent authenticated (id='", msg.id(), "')"); // Advertise our TG filter to the parent so it can skip TGs we // don't want. The parent applies the filter on its outbound path. sendFilter(); + + // Trigger the reflector to push our local roster up immediately so the + // parent can fan it out (debounced) — otherwise the first node-list + // emission only happens on the next client login/TG-change. + m_reflector->scheduleNodeListUpdate(); } /* SatelliteClient::handleMsgTrunkHello */ @@ -276,6 +364,72 @@ void SatelliteClient::handleMsgTrunkFlush(std::istream& is) } /* SatelliteClient::handleMsgTrunkFlush */ +void SatelliteClient::handleMsgTrunkNodeList(std::istream& is) +{ + MsgTrunkNodeList msg; + if (!msg.unpack(is)) + { + geulog::error("satellite", "Failed to unpack MsgTrunkNodeList"); + return; + } + + std::vector sanitized; + sanitized.reserve(msg.nodes().size()); + unsigned dropped = 0; + for (const auto& n : msg.nodes()) + { + MsgTrunkNodeList::NodeEntry e; + e.callsign = sanitizeIdent(n.callsign, 32); + if (e.callsign.empty()) { ++dropped; continue; } + e.tg = n.tg; + e.qth_name = sanitizeText(n.qth_name, 64); + if (std::isfinite(n.lat) && std::isfinite(n.lon) && + n.lat >= -90.0f && n.lat <= 90.0f && + n.lon >= -180.0f && n.lon <= 180.0f) + { + e.lat = n.lat; + e.lon = n.lon; + } + e.status = n.status; + sanitizeJsonStrings(e.status); + // Recipient-relative sat_id from the parent passes through unchanged: + // empty = "on the parent itself", non-empty = "on a sibling sat + // attached to the parent". + e.sat_id = sanitizeIdent(n.sat_id, 64); + sanitized.push_back(std::move(e)); + } + if (dropped > 0) + { + geulog::warn("satellite", "Dropped ", dropped, + " parent-roster entrie(s) with empty/invalid callsign"); + } + + if (!m_parent_id.empty()) + { + m_reflector->onPeerNodeList(m_parent_id, sanitized); + } + m_parent_nodes = std::move(sanitized); +} /* SatelliteClient::handleMsgTrunkNodeList */ + + +void SatelliteClient::sendNodeList( + const std::vector& nodes) +{ + if (!m_con.isConnected() || !m_hello_received) return; + + // Apply our outbound TG filter so we only push roster entries the + // parent cares about (consistent with the audio-path scoping rule). + std::vector filtered; + filtered.reserve(nodes.size()); + for (const auto& n : nodes) + { + if (!m_filter.empty() && !m_filter.matches(n.tg)) continue; + filtered.push_back(n); + } + sendMsg(MsgTrunkNodeList(filtered)); +} /* SatelliteClient::sendNodeList */ + + void SatelliteClient::sendMsg(const ReflectorMsg& msg) { ostringstream ss; diff --git a/src/svxlink/reflector/SatelliteClient.h b/src/svxlink/reflector/SatelliteClient.h index 039c02f..08d4acd 100644 --- a/src/svxlink/reflector/SatelliteClient.h +++ b/src/svxlink/reflector/SatelliteClient.h @@ -10,9 +10,9 @@ #include #include "TgFilter.h" +#include "ReflectorMsg.h" class Reflector; -class ReflectorMsg; /** @brief Satellite-side outbound connection to a parent reflector @@ -43,6 +43,19 @@ class SatelliteClient : public sigc::trackable void onLocalAudio(uint32_t tg, const std::vector& audio); void onLocalFlush(uint32_t tg); + // Send our local roster up to the parent. Caller has already filtered + // to "this satellite's local clients" (sat_id empty on the wire). + void sendNodeList( + const std::vector& nodes); + + // Read-only access to the parent's combined-view roster, surfaced + // by Reflector::statusJson under /status.parent.nodes. + const std::vector& parentNodes(void) const + { + return m_parent_nodes; + } + const std::string& parentId(void) const { return m_parent_id; } + private: static const unsigned HEARTBEAT_TX_CNT_RESET = 10; static const unsigned HEARTBEAT_RX_CNT_RESET = 15; @@ -64,6 +77,12 @@ class SatelliteClient : public sigc::trackable unsigned m_hb_rx_cnt; TgFilter m_filter; // optional TG filter (SATELLITE_FILTER) std::string m_filter_str; // raw config string for MsgTrunkFilter + // Parent's id from MsgTrunkHello (used as the peer_id key for Redis + // tombstone bookkeeping when storing the parent-supplied roster). + std::string m_parent_id; + // Parent's combined roster (parent-local + every sibling satellite, + // minus our own contribution). Surfaced via /status.parent.nodes. + std::vector m_parent_nodes; void onConnected(void); void onDisconnected(Async::TcpConnection* con, @@ -76,6 +95,7 @@ class SatelliteClient : 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 sendFilter(void); void heartbeatTick(Async::Timer* t); diff --git a/src/svxlink/reflector/SatelliteLink.cpp b/src/svxlink/reflector/SatelliteLink.cpp index 4664137..6a078b8 100644 --- a/src/svxlink/reflector/SatelliteLink.cpp +++ b/src/svxlink/reflector/SatelliteLink.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -12,6 +13,78 @@ using namespace std; using namespace Async; +namespace { + +// Byte-bound and strip control chars / ':' from an identifier coming over +// the wire. Mirrors the sanitizer used in TrunkLink/TwinLink — wire data +// flows into Redis key names, MQTT payloads and log output. +std::string sanitizeIdent(const std::string& in, size_t max_len) +{ + std::string out; + out.reserve(std::min(in.size(), max_len)); + for (char c : in) + { + unsigned char u = static_cast(c); + if (u < 0x20 || u == 0x7f) continue; + if (c == ':') continue; + out += c; + if (out.size() >= max_len) break; + } + return out; +} + +std::string sanitizeText(const std::string& in, size_t max_bytes) +{ + std::string out; + out.reserve(std::min(in.size(), max_bytes)); + for (char c : in) + { + unsigned char u = static_cast(c); + if (u < 0x20 || u == 0x7f) continue; + out += c; + if (out.size() >= max_bytes) break; + } + return out; +} + +void sanitizeJsonStrings(Json::Value& v, unsigned depth = 0) +{ + static constexpr unsigned MAX_DEPTH = 8; + static constexpr Json::ArrayIndex MAX_LEN = 256; + static constexpr size_t MAX_STR_BYTES = 1024; + if (depth >= MAX_DEPTH) { v = Json::Value(); return; } + if (v.isString()) + { + v = sanitizeText(v.asString(), MAX_STR_BYTES); + } + else if (v.isArray()) + { + if (v.size() > MAX_LEN) v.resize(MAX_LEN); + for (Json::ArrayIndex i = 0; i < v.size(); ++i) + { + sanitizeJsonStrings(v[i], depth + 1); + } + } + else if (v.isObject()) + { + auto names = v.getMemberNames(); + if (names.size() > MAX_LEN) + { + for (size_t i = MAX_LEN; i < names.size(); ++i) + { + v.removeMember(names[i]); + } + names.resize(MAX_LEN); + } + for (const auto& k : names) + { + sanitizeJsonStrings(v[k], depth + 1); + } + } +} + +} // namespace + SatelliteLink::SatelliteLink(Reflector* reflector, Async::FramedTcpConnection* con, @@ -39,6 +112,15 @@ SatelliteLink::~SatelliteLink(void) TGHandler::instance()->clearTrunkTalkerForTG(tg); } m_sat_active_tgs.clear(); + // Drop any partner roster we held for this satellite so Reflector's + // tombstone bookkeeping (Redis live:peer_node::) gets + // a chance to clear those keys before we go away. + if (!m_partner_nodes.empty() && !m_satellite_id.empty()) + { + m_reflector->onPeerNodeList(m_satellite_id, + std::vector{}); + m_partner_nodes.clear(); + } } /* SatelliteLink::~SatelliteLink */ @@ -59,6 +141,27 @@ Json::Value SatelliteLink::statusJson(void) const { obj["filter"] = m_tg_filter.toString(); } + + Json::Value nodes_arr(Json::arrayValue); + for (const auto& n : m_partner_nodes) + { + Json::Value entry = n.status.isObject() ? n.status + : Json::Value(Json::objectValue); + entry["callsign"] = n.callsign; + entry["tg"] = static_cast(n.tg); + if (n.lat != 0.0f || n.lon != 0.0f) + { + entry["lat"] = n.lat; + entry["lon"] = n.lon; + } + if (!n.qth_name.empty()) entry["qth_name"] = n.qth_name; + if (!n.sat_id.empty()) entry["sat_id"] = n.sat_id; + entry["isTalker"] = + (TGHandler::instance()->trunkTalkerForTG(n.tg) == n.callsign); + nodes_arr.append(entry); + } + obj["nodes"] = nodes_arr; + return obj; } /* SatelliteLink::statusJson */ @@ -145,6 +248,9 @@ void SatelliteLink::onFrameReceived(FramedTcpConnection* con, case MsgTrunkFilter::TYPE: handleMsgTrunkFilter(ss); break; + case MsgTrunkNodeList::TYPE: + handleMsgTrunkNodeList(ss); + break; default: geulog::warn("satellite", "Unknown message type=", header.type()); break; @@ -201,6 +307,11 @@ void SatelliteLink::handleMsgTrunkHello(std::istream& is) sendMsg(MsgTrunkHello("PARENT", "", 0, m_secret, MsgTrunkHello::ROLE_PEER)); + // Bring the new satellite up to speed: schedule a debounced node-list + // emission so it receives the parent's combined view (parent-local + // + every sibling satellite, minus its own contribution). + m_reflector->scheduleNodeListUpdate(); + statusChanged(this); } /* SatelliteLink::handleMsgTrunkHello */ @@ -343,3 +454,75 @@ bool SatelliteLink::filterPassesTg(uint32_t tg) const if (m_tg_filter.empty()) return true; return m_tg_filter.matches(tg); } /* SatelliteLink::filterPassesTg */ + + +void SatelliteLink::handleMsgTrunkNodeList(std::istream& is) +{ + MsgTrunkNodeList msg; + if (!msg.unpack(is)) + { + geulog::error("satellite", "Failed to unpack MsgTrunkNodeList from '", + m_satellite_id, "'"); + return; + } + + std::vector sanitized; + sanitized.reserve(msg.nodes().size()); + unsigned dropped = 0; + for (const auto& n : msg.nodes()) + { + MsgTrunkNodeList::NodeEntry e; + e.callsign = sanitizeIdent(n.callsign, 32); + if (e.callsign.empty()) { ++dropped; continue; } + e.tg = n.tg; + e.qth_name = sanitizeText(n.qth_name, 64); + if (std::isfinite(n.lat) && std::isfinite(n.lon) && + n.lat >= -90.0f && n.lat <= 90.0f && + n.lon >= -180.0f && n.lon <= 180.0f) + { + e.lat = n.lat; + e.lon = n.lon; + } + e.status = n.status; + sanitizeJsonStrings(e.status); + // Stamp every entry with this satellite's id. Wire sat_id from a + // direct satellite is normally empty (its own clients are local to + // it); a non-empty value would indicate a deeper sat-of-sat + // hierarchy, which we collapse to a single level here. + e.sat_id = m_satellite_id; + sanitized.push_back(std::move(e)); + } + if (dropped > 0) + { + geulog::warn("satellite", "'", m_satellite_id, "' dropped ", dropped, + " node list entrie(s) with empty/invalid callsign"); + } + + m_reflector->onPeerNodeList(m_satellite_id, sanitized); + m_partner_nodes = std::move(sanitized); + + // The parent's combined view changed — re-broadcast (debounced) to + // trunks, twin, and sibling satellites so they pick up the new sat + // contribution. + m_reflector->scheduleNodeListUpdate(); + + statusChanged(this); +} /* SatelliteLink::handleMsgTrunkNodeList */ + + +void SatelliteLink::sendNodeList( + const std::vector& nodes) +{ + if (!m_hello_received) return; + + // Apply this satellite's announced filter so we only forward TGs the + // satellite cares about (matches the audio-path scoping rule). + std::vector filtered; + filtered.reserve(nodes.size()); + for (const auto& n : nodes) + { + if (!filterPassesTg(n.tg)) continue; + filtered.push_back(n); + } + sendMsg(MsgTrunkNodeList(filtered)); +} /* SatelliteLink::sendNodeList */ diff --git a/src/svxlink/reflector/SatelliteLink.h b/src/svxlink/reflector/SatelliteLink.h index a832142..3c07636 100644 --- a/src/svxlink/reflector/SatelliteLink.h +++ b/src/svxlink/reflector/SatelliteLink.h @@ -10,9 +10,9 @@ #include #include "TgFilter.h" +#include "ReflectorMsg.h" class Reflector; -class ReflectorMsg; /** @brief Handles one inbound satellite connection on the parent reflector @@ -55,6 +55,22 @@ class SatelliteLink : public sigc::trackable void onParentAudio(uint32_t tg, const std::vector& audio); void onParentFlush(uint32_t tg); + // Send a node list down to the satellite. Caller passes the combined + // parent-known roster minus this satellite's own contribution; this + // method additionally drops entries whose TG falls outside the + // satellite's announced filter (if any). + void sendNodeList( + const std::vector& nodes); + + // Read-only access to the satellite-supplied roster (this satellite's + // local clients), already sanitised and stamped with sat_id = + // satelliteId(). Used by Reflector to merge into the parent's + // outbound advertisements. + const std::vector& partnerNodes(void) const + { + return m_partner_nodes; + } + private: static const unsigned HEARTBEAT_TX_CNT_RESET = 10; static const unsigned HEARTBEAT_RX_CNT_RESET = 15; @@ -69,6 +85,12 @@ class SatelliteLink : public sigc::trackable unsigned m_hb_rx_cnt; std::set m_sat_active_tgs; TgFilter m_tg_filter; + // Roster of clients attached to this satellite, learned via + // MsgTrunkNodeList from the satellite. Each entry carries + // sat_id == m_satellite_id (stamped on ingest) so the Reflector can + // merge it into outbound trunk/twin/sibling-sat lists with correct + // attribution. + std::vector m_partner_nodes; void onFrameReceived(Async::FramedTcpConnection* con, std::vector& data); @@ -79,6 +101,7 @@ class SatelliteLink : public sigc::trackable void handleMsgTrunkFlush(std::istream& is); void handleMsgTrunkHeartbeat(void); void handleMsgTrunkFilter(std::istream& is); + void handleMsgTrunkNodeList(std::istream& is); bool filterPassesTg(uint32_t tg) const; void sendMsg(const ReflectorMsg& msg); void heartbeatTick(Async::Timer* t); diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 17ee7c8..bfde9f0 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -571,6 +571,7 @@ Json::Value TrunkLink::statusJson(void) const entry["lon"] = n.lon; } if (!n.qth_name.empty()) entry["qth_name"] = n.qth_name; + if (!n.sat_id.empty()) entry["sat_id"] = n.sat_id; // Derive isTalker from the live trunk-talker map maintained by // MsgTrunkTalkerStart/Stop. Authoritative for partner nodes; the // sender's own isTalker is stale by the time it arrives in the @@ -1837,6 +1838,10 @@ void TrunkLink::handleMsgTrunkNodeList(std::istream& is) } e.status = n.status; sanitizeJsonStrings(e.status); + // Recipient-relative sat_id from the peer. Pass through as-is after + // bounded sanitisation: empty = "on the peer itself", non-empty = + // "on a satellite attached to the peer". + e.sat_id = sanitizeIdent(n.sat_id, 64); sanitized.push_back(std::move(e)); } if (dropped > 0) diff --git a/src/svxlink/reflector/TwinLink.cpp b/src/svxlink/reflector/TwinLink.cpp index aac5004..2c190a9 100644 --- a/src/svxlink/reflector/TwinLink.cpp +++ b/src/svxlink/reflector/TwinLink.cpp @@ -390,6 +390,7 @@ Json::Value TwinLink::statusJson(void) const entry["lon"] = n.lon; } if (!n.qth_name.empty()) entry["qth_name"] = n.qth_name; + if (!n.sat_id.empty()) entry["sat_id"] = n.sat_id; entry["isTalker"] = (TGHandler::instance()->trunkTalkerForTG(n.tg) == n.callsign); nodes_arr.append(entry); @@ -691,6 +692,7 @@ void TwinLink::handleMsgTrunkNodeList(std::istream& is) } e.status = n.status; sanitizeJsonStrings(e.status); + e.sat_id = sanitizeIdent(n.sat_id, 64); sanitized.push_back(std::move(e)); } if (dropped > 0) diff --git a/tests/test_trunk.py b/tests/test_trunk.py index 117e216..c3ab5eb 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -178,39 +178,48 @@ def build_trunk_filter(filter_str: str) -> bytes: def build_node_list(nodes) -> bytes: """Build a MsgTrunkNodeList frame. - `nodes` is an iterable of (callsign, tg[, lat, lon, qth_name]) tuples. - Unspecified lat/lon default to 0.0 and qth_name to "". - Matches the on-wire layout: vec callsigns, vec tgs, - vec lat, vec lon, vec qth_names — each vector + `nodes` is an iterable of (callsign, tg[, lat, lon, qth_name[, status_blob, sat_id]]) + tuples. Unspecified fields default to 0.0/"". Wire layout: 7 vectors + (callsigns, tgs, lats, lons, qth_names, status_blobs, sat_ids), each prefixed with a u16 element count. """ norm = [] for n in nodes: if len(n) == 2: cs, tg = n - lat, lon, qth = 0.0, 0.0, "" + lat, lon, qth, blob, sat_id = 0.0, 0.0, "", "", "" elif len(n) == 5: cs, tg, lat, lon, qth = n + blob, sat_id = "", "" + elif len(n) == 7: + cs, tg, lat, lon, qth, blob, sat_id = n else: - raise ValueError("node tuple must be (cs, tg) or (cs, tg, lat, lon, qth)") - norm.append((cs, tg, lat, lon, qth)) + raise ValueError("node tuple must be (cs,tg), (cs,tg,lat,lon,qth) " + "or (cs,tg,lat,lon,qth,blob,sat_id)") + norm.append((cs, tg, lat, lon, qth, blob, sat_id)) payload = struct.pack("!H", MSG_TRUNK_NODE_LIST) payload += struct.pack("!H", len(norm)) - for cs, _tg, _lat, _lon, _qth in norm: + for cs, *_ in norm: payload += pack_string(cs) payload += struct.pack("!H", len(norm)) - for _cs, tg, _lat, _lon, _qth in norm: + for _cs, tg, *_ in norm: payload += struct.pack("!I", tg) payload += struct.pack("!H", len(norm)) - for _cs, _tg, lat, _lon, _qth in norm: + for _cs, _tg, lat, *_ in norm: payload += struct.pack("!f", lat) payload += struct.pack("!H", len(norm)) - for _cs, _tg, _lat, lon, _qth in norm: + for _cs, _tg, _lat, lon, *_ in norm: payload += struct.pack("!f", lon) payload += struct.pack("!H", len(norm)) - for _cs, _tg, _lat, _lon, qth in norm: + for _cs, _tg, _lat, _lon, qth, *_ in norm: payload += pack_string(qth) + payload += struct.pack("!H", len(norm)) + for *_, blob, _sat_id in norm: + payload += pack_string(blob) + payload += struct.pack("!H", len(norm)) + for *_, sat_id in norm: + payload += pack_string(sat_id) return payload @@ -251,10 +260,9 @@ def parse_msg(data: bytes): 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. - # Vector length prefixes are u16 (MsgPacker in - # AsyncMsg.h uses uint16_t for element counts). + # 7 u16-prefixed vectors: callsigns, tgs, lats, lons, qth_names, + # status_blobs, sat_ids. (MsgPacker in AsyncMsg.h + # uses uint16_t for element counts.) def read_vec_str(off): n = struct.unpack_from("!H", data, off)[0]; off += 2 out = [] @@ -277,7 +285,18 @@ def parse_msg(data: bytes): callsigns, off = read_vec_str(off) tgs, off = read_vec_u32(off) - return msg_type, {"callsigns": callsigns, "tgs": tgs} + # Best-effort decode of trailing vectors. Older builds may emit + # fewer than 7 vectors; tolerate truncation. + try: + _lats, off = read_vec_f32(off) + _lons, off = read_vec_f32(off) + _qth_names, off = read_vec_str(off) + _status_blobs, off = read_vec_str(off) + sat_ids, off = read_vec_str(off) + except struct.error: + sat_ids = [] + return msg_type, {"callsigns": callsigns, "tgs": tgs, + "sat_ids": sat_ids} else: return msg_type, {"raw": data[off:]} @@ -2234,6 +2253,206 @@ class TestTrunkIntegration(unittest.TestCase): for c in clients.values(): c.close() + # ------------------------------------------------------------------ + # Test 33: Satellite-attached client visible on parent /status + # ------------------------------------------------------------------ + def test_33_satellite_attached_client_on_parent_status(self): + """A V2 client attached to the satellite reflector (sat) shows up + in the parent's /status under satellites[].nodes. + + Verifies the sat → parent MsgTrunkNodeList carriage and the + per-satellite roster surfacing in Reflector::refreshStatus. + """ + sat_id = T.SATELLITE_NODE["id"] + parent = T.sat_node_parent() + callsign = "N0THRD" # third test client to avoid colliding with others + + client = ClientPeer() + try: + client.connect(HOST, T.sat_node_mapped_client_port()) + client.authenticate(callsign=callsign, + password=CLIENT_PASSWORD) + + def has_node(): + status = get_status(*_http(parent)) + sat = status.get("satellites", {}).get(sat_id, {}) + for n in sat.get("nodes", []): + if n.get("callsign") == callsign: + return True + return False + + wait_until(has_node, timeout=8.0, + msg=f"satellite-attached client {callsign} not " + f"visible under /status.satellites.{sat_id}.nodes " + f"on parent {parent}") + finally: + client.close() + + # ------------------------------------------------------------------ + # Test 34: Satellite-attached client visible on a far-trunk peer + # ------------------------------------------------------------------ + def test_34_satellite_attached_client_on_trunk_peer(self): + """A V2 client attached to the satellite reflector shows up on a + far-trunk peer's /status.trunks[
].nodes with the sat_id + field set, proving the parent re-merges sat-supplied entries + into its outbound MsgTrunkNodeList with attribution. + """ + sat_id = T.SATELLITE_NODE["id"] + parent = T.sat_node_parent() + callsign = "N0THRD" + + # Pick any reflector that trunks to the parent + peer = next(n for n in REFLECTOR_NAMES if n != parent) + section = T.trunk_section_name(peer, parent) + + client = ClientPeer() + try: + client.connect(HOST, T.sat_node_mapped_client_port()) + client.authenticate(callsign=callsign, + password=CLIENT_PASSWORD) + + def has_attributed_node(): + status = get_status(*_http(peer)) + trunk = status.get("trunks", {}).get(section, {}) + for n in trunk.get("nodes", []): + if n.get("callsign") == callsign and \ + n.get("sat_id") == sat_id: + return True + return False + + wait_until(has_attributed_node, timeout=10.0, + msg=f"satellite client {callsign} not visible with " + f"sat_id={sat_id} under /status.trunks.{section} " + f".nodes on far-trunk peer {peer}") + finally: + client.close() + + # ------------------------------------------------------------------ + # Test 35: Parent-local clients visible on the satellite's /status + # ------------------------------------------------------------------ + def test_35_parent_local_visible_on_satellite_status(self): + """A V2 client connected to the parent reflector shows up on the + satellite's /status under satellite.parent_nodes — proving the + parent → satellite MsgTrunkNodeList path delivers the parent's + combined view down to subordinate sats. + """ + parent = T.sat_node_parent() + sat_name = T.SATELLITE_NODE["name"] + callsign = CLIENT_CALLSIGN # standard test client + + client = ClientPeer() + try: + client.connect(HOST, T.mapped_client_port(parent)) + client.authenticate(callsign=callsign, + password=CLIENT_PASSWORD) + + def has_parent_node(): + status = get_status(HOST, T.sat_node_mapped_http_port()) + sat_blob = status.get("satellite", {}) + for n in sat_blob.get("parent_nodes", []): + if n.get("callsign") == callsign: + # parent-local entries must NOT carry a sat_id; + # absence (or empty) means "on the parent itself" + return n.get("sat_id", "") == "" + return False + + wait_until(has_parent_node, timeout=8.0, + msg=f"parent-local client {callsign} not visible " + f"under /status.satellite.parent_nodes on " + f"satellite {sat_name}") + finally: + client.close() + + # ------------------------------------------------------------------ + # Test 36: Multi-satellite cross-visibility through the parent + # ------------------------------------------------------------------ + def test_36_multi_sat_cross_visibility(self): + """Two fake satellites attached to the same parent each see the + other's roster contribution, with sat_id stamping that identifies + the originating satellite. Self-echo guard: neither satellite + ever sees its own contribution echoed back. + + Exercises: + - parent stamps incoming sat-supplied entries with the SatelliteLink's + satelliteId() on ingest + - sendNodeListToAllPeers merges every satellite's roster into + the outbound list to other satellites and trunks + - per-recipient skip rule: combined view minus the recipient's + own contribution + """ + parent = T.sat_node_parent() + sat_a = SatellitePeer() + sat_b = SatellitePeer() + + SAT_A_ID = "SAT_FAKE_A" + SAT_B_ID = "SAT_FAKE_B" + A_CS, A_TG = "S1CLIENT", 12200 + B_CS, B_TG = "S2CLIENT", 12201 + + def find_entry(fields, callsign): + """Return the sat_id stamp for `callsign` in this NodeList, + or None if the callsign isn't present.""" + for cs, sat_id in zip(fields["callsigns"], fields["sat_ids"]): + if cs == callsign: + return sat_id + return None + + def wait_for_entry(peer, target_cs, target_sat_id, forbid_cs, + forbid_sat_id, timeout=8.0): + """Drain NodeLists until we see (target_cs, target_sat_id). + Fails the test if (forbid_cs, forbid_sat_id) is ever seen + (self-echo guard violation).""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + msg_type, fields = peer.recv_msg(timeout=1.0) + except socket.timeout: + continue + if msg_type != MSG_TRUNK_NODE_LIST: + continue + forbid_stamp = find_entry(fields, forbid_cs) + if forbid_stamp == forbid_sat_id: + self.fail( + f"self-echo violation: callsign {forbid_cs} " + f"appeared with sat_id={forbid_sat_id} on the " + f"recipient that owns it") + if find_entry(fields, target_cs) == target_sat_id: + return True + return False + + try: + sat_a.connect_satellite(name=parent) + sat_a.handshake(sat_id=SAT_A_ID, secret=SAT_SECRET) + sat_b.connect_satellite(name=parent) + sat_b.handshake(sat_id=SAT_B_ID, secret=SAT_SECRET) + + # Drain any node lists already queued from the parent's + # bootstrap fanout (debounce + initial scheduleNodeListUpdate + # on hello completion). + for s in (sat_a, sat_b): + s.sock.settimeout(0.5) + try: + while True: + recv_frame(s.sock) + except (socket.timeout, ConnectionError): + pass + s.sock.settimeout(5.0) + + # Both satellites publish their local rosters. Each push + # triggers the parent to re-broadcast its combined view. + sat_a.send_node_list([(A_CS, A_TG)]) + sat_b.send_node_list([(B_CS, B_TG)]) + + self.assertTrue( + wait_for_entry(sat_b, A_CS, SAT_A_ID, B_CS, SAT_B_ID), + f"sat_b never received {A_CS} stamped with sat_id={SAT_A_ID}") + self.assertTrue( + wait_for_entry(sat_a, B_CS, SAT_B_ID, A_CS, SAT_A_ID), + f"sat_a never received {B_CS} stamped with sat_id={SAT_B_ID}") + finally: + sat_a.close() + sat_b.close() + # --------------------------------------------------------------------------- # Custom test runner with clean, readable output