redis: mirror peer node lists + sanitize trunk-received strings
Peer node lists (MsgTrunkNodeList, type 121) now propagate into Redis alongside the existing MQTT publish, so dashboards reading Redis see a complete view of local + peer rosters. Each remote entry is stored as live:peer_node:<peer_id>:<callsign> with 60s TTL; a per-peer cache diffs incoming snapshots so dropped callsigns are DEL'd, and a full trunk-down deletes all of that peer's entries. All untrusted strings arriving via the trunk (peer_id from the hello, plus callsign/qth/lat/lon in node lists) are now sanitized at receive: control chars + ':' stripped, length bounded (32 callsign, 64 peer_id and qth), non-finite and out-of-range coordinates cleared. Entries whose callsign becomes empty after sanitization are dropped. Also reorders TrunkLink in/outbound onDisconnected so the state-change notification fires after the per-direction state is cleared, letting consumers that inspect isActive() (like the Redis peer-node cleanup) see the correct post-disconnect state. Adds RedisPeerNodeTest (3 cases: populate+diff, sanitization, trunk- down cleanup) and a build_node_list wire helper in test_trunk.py. Exposes the trunk port in docker-compose.redis.yml so the host can inject trunk frames against the r1 test reflector.
This commit is contained in:
1 parent
0700e01453
commit
7b95d0d2ce
10 files changed
+399
-9
No files matched your search
@@ -314,6 +314,43 @@ void RedisStore::clearLiveClient(const std::string& callsign) {
|
|||||||
m_live_queue->push(std::move(op));
|
m_live_queue->push(std::move(op));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void RedisStore::pushPeerNode(const std::string& peer_id,
|
||||||
|
const std::string& callsign,
|
||||||
|
uint32_t tg,
|
||||||
|
float lat, float lon,
|
||||||
|
const std::string& qth_name) {
|
||||||
|
if (!m_live_queue) return;
|
||||||
|
RedisLiveQueue::Op op;
|
||||||
|
op.op = RedisLiveQueue::OpType::HSET;
|
||||||
|
op.key = keyFor("live:peer_node:" + peer_id + ":" + callsign);
|
||||||
|
m_live_keys.insert(op.key);
|
||||||
|
op.fields = {
|
||||||
|
{"peer_id", peer_id},
|
||||||
|
{"callsign", callsign},
|
||||||
|
{"tg", std::to_string(tg)},
|
||||||
|
{"updated_at", std::to_string(std::time(nullptr))}
|
||||||
|
};
|
||||||
|
if (lat != 0.0f || lon != 0.0f) {
|
||||||
|
op.fields.emplace_back("lat", std::to_string(lat));
|
||||||
|
op.fields.emplace_back("lon", std::to_string(lon));
|
||||||
|
}
|
||||||
|
if (!qth_name.empty()) {
|
||||||
|
op.fields.emplace_back("qth_name", qth_name);
|
||||||
|
}
|
||||||
|
op.ttl_s = 60;
|
||||||
|
m_live_queue->push(std::move(op));
|
||||||
|
}
|
||||||
|
|
||||||
|
void RedisStore::clearPeerNode(const std::string& peer_id,
|
||||||
|
const std::string& callsign) {
|
||||||
|
if (!m_live_queue) return;
|
||||||
|
RedisLiveQueue::Op op;
|
||||||
|
op.op = RedisLiveQueue::OpType::DEL;
|
||||||
|
op.key = keyFor("live:peer_node:" + peer_id + ":" + callsign);
|
||||||
|
m_live_keys.erase(op.key);
|
||||||
|
m_live_queue->push(std::move(op));
|
||||||
|
}
|
||||||
|
|
||||||
void RedisStore::pushLiveTrunk(const std::string& section,
|
void RedisStore::pushLiveTrunk(const std::string& section,
|
||||||
const std::string& state,
|
const std::string& state,
|
||||||
const std::string& peer_id) {
|
const std::string& peer_id) {
|
||||||
|
|||||||
@@ -81,6 +81,13 @@ class RedisStore : public sigc::trackable
|
|||||||
void pushLiveTrunk(const std::string& section,
|
void pushLiveTrunk(const std::string& section,
|
||||||
const std::string& state,
|
const std::string& state,
|
||||||
const std::string& peer_id);
|
const std::string& peer_id);
|
||||||
|
void pushPeerNode(const std::string& peer_id,
|
||||||
|
const std::string& callsign,
|
||||||
|
uint32_t tg,
|
||||||
|
float lat, float lon,
|
||||||
|
const std::string& qth_name);
|
||||||
|
void clearPeerNode(const std::string& peer_id,
|
||||||
|
const std::string& callsign);
|
||||||
|
|
||||||
uint64_t droppedLiveWrites(void) const { return m_dropped_live_writes; }
|
uint64_t droppedLiveWrites(void) const { return m_dropped_live_writes; }
|
||||||
size_t liveQueueSize(void) const;
|
size_t liveQueueSize(void) const;
|
||||||
|
|||||||
@@ -3034,6 +3034,27 @@ void Reflector::onPeerNodeList(const std::string& peer_id,
|
|||||||
{
|
{
|
||||||
m_mqtt->publishPeerNodes(peer_id, nodes);
|
m_mqtt->publishPeerNodes(peer_id, nodes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (m_redis != nullptr && !peer_id.empty())
|
||||||
|
{
|
||||||
|
std::set<std::string> seen;
|
||||||
|
for (const auto& n : nodes)
|
||||||
|
{
|
||||||
|
if (n.callsign.empty()) continue;
|
||||||
|
seen.insert(n.callsign);
|
||||||
|
m_redis->pushPeerNode(peer_id, n.callsign, n.tg,
|
||||||
|
n.lat, n.lon, n.qth_name);
|
||||||
|
}
|
||||||
|
auto& prev = m_peer_node_cache[peer_id];
|
||||||
|
for (const std::string& cs : prev)
|
||||||
|
{
|
||||||
|
if (seen.find(cs) == seen.end())
|
||||||
|
{
|
||||||
|
m_redis->clearPeerNode(peer_id, cs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prev = std::move(seen);
|
||||||
|
}
|
||||||
} /* Reflector::onPeerNodeList */
|
} /* Reflector::onPeerNodeList */
|
||||||
|
|
||||||
|
|
||||||
@@ -3059,6 +3080,30 @@ void Reflector::onTrunkStateChanged(const std::string& section,
|
|||||||
{
|
{
|
||||||
m_redis->pushLiveTrunk(section, up ? "up" : "down", peer_id);
|
m_redis->pushLiveTrunk(section, up ? "up" : "down", peer_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// When a trunk link is fully down (both directions), clear any node
|
||||||
|
// entries we were mirroring from this peer into Redis. Keeps Redis in
|
||||||
|
// sync with the fact that we can no longer observe the peer's roster.
|
||||||
|
if (!up && m_redis != nullptr && !peer_id.empty())
|
||||||
|
{
|
||||||
|
TrunkLink* link = nullptr;
|
||||||
|
for (auto* l : m_trunk_links)
|
||||||
|
{
|
||||||
|
if (l->section() == section) { link = l; break; }
|
||||||
|
}
|
||||||
|
if (link == nullptr || !link->isActive())
|
||||||
|
{
|
||||||
|
auto it = m_peer_node_cache.find(peer_id);
|
||||||
|
if (it != m_peer_node_cache.end())
|
||||||
|
{
|
||||||
|
for (const std::string& cs : it->second)
|
||||||
|
{
|
||||||
|
m_redis->clearPeerNode(peer_id, cs);
|
||||||
|
}
|
||||||
|
m_peer_node_cache.erase(it);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
} /* Reflector::onTrunkStateChanged */
|
} /* Reflector::onTrunkStateChanged */
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -325,6 +325,9 @@ class Reflector : public sigc::trackable
|
|||||||
Json::Value m_status;
|
Json::Value m_status;
|
||||||
|
|
||||||
std::vector<TrunkLink*> m_trunk_links;
|
std::vector<TrunkLink*> m_trunk_links;
|
||||||
|
// Tracks last-seen callsign set per peer_id so we can DEL dropped
|
||||||
|
// callsigns from Redis when a peer's node list shrinks.
|
||||||
|
std::map<std::string, std::set<std::string>> m_peer_node_cache;
|
||||||
std::set<std::string> m_redis_trunk_sections; // sections loaded from Redis
|
std::set<std::string> m_redis_trunk_sections; // sections loaded from Redis
|
||||||
std::set<uint32_t> m_cluster_tgs;
|
std::set<uint32_t> m_cluster_tgs;
|
||||||
bool m_trunk_debug = false;
|
bool m_trunk_debug = false;
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
#include <cmath>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <cerrno>
|
#include <cerrno>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -75,6 +76,42 @@ using namespace Async;
|
|||||||
using namespace sigc;
|
using namespace sigc;
|
||||||
|
|
||||||
|
|
||||||
|
// Strip control chars (< 0x20 and 0x7f) and ':' (Redis key delimiter),
|
||||||
|
// then truncate to `max_len`. Used for untrusted identifiers received
|
||||||
|
// over the trunk: peer_id from hellos and callsigns from node lists.
|
||||||
|
static 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<unsigned char>(c);
|
||||||
|
if (u < 0x20 || u == 0x7f) continue;
|
||||||
|
if (c == ':') continue;
|
||||||
|
out += c;
|
||||||
|
if (out.size() >= max_len) break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip control chars only and truncate to `max_bytes`. Used for free-
|
||||||
|
// form text fields (e.g. QTH name) where non-ASCII bytes (UTF-8) are
|
||||||
|
// legitimate. Truncation is byte-level; callers tolerate the possibility
|
||||||
|
// of a split UTF-8 sequence at the boundary.
|
||||||
|
static 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<unsigned char>(c);
|
||||||
|
if (u < 0x20 || u == 0x7f) continue;
|
||||||
|
out += c;
|
||||||
|
if (out.size() >= max_bytes) break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
static std::vector<std::string> splitPrefixes(const std::string& s)
|
static std::vector<std::string> splitPrefixes(const std::string& s)
|
||||||
{
|
{
|
||||||
std::vector<std::string> result;
|
std::vector<std::string> result;
|
||||||
@@ -508,7 +545,7 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con,
|
|||||||
// (all twins share same priority; last-writer wins is fine)
|
// (all twins share same priority; last-writer wins is fine)
|
||||||
m_peer_priority = hello.priority();
|
m_peer_priority = hello.priority();
|
||||||
if (m_peer_id_received.empty())
|
if (m_peer_id_received.empty())
|
||||||
m_peer_id_received = hello.id();
|
m_peer_id_received = sanitizeIdent(hello.id(), 64);
|
||||||
|
|
||||||
cout << m_section << ": paired inbound accepted from peer '"
|
cout << m_section << ": paired inbound accepted from peer '"
|
||||||
<< hello.id() << "' " << con->remoteHost() << ":"
|
<< hello.id() << "' " << con->remoteHost() << ":"
|
||||||
@@ -556,7 +593,7 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con,
|
|||||||
con->frameReceived.connect(
|
con->frameReceived.connect(
|
||||||
mem_fun(*this, &TrunkLink::onFrameReceived));
|
mem_fun(*this, &TrunkLink::onFrameReceived));
|
||||||
|
|
||||||
m_peer_id_received = hello.id();
|
m_peer_id_received = sanitizeIdent(hello.id(), 64);
|
||||||
cout << m_section << ": Accepted inbound from " << con->remoteHost()
|
cout << m_section << ": Accepted inbound from " << con->remoteHost()
|
||||||
<< ":" << con->remotePort() << " peer='" << hello.id()
|
<< ":" << con->remotePort() << " peer='" << hello.id()
|
||||||
<< "' priority=" << m_peer_priority << endl;
|
<< "' priority=" << m_peer_priority << endl;
|
||||||
@@ -601,7 +638,6 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con,
|
|||||||
}
|
}
|
||||||
|
|
||||||
cout << m_section << ": Inbound trunk connection lost" << endl;
|
cout << m_section << ": Inbound trunk connection lost" << endl;
|
||||||
m_reflector->onTrunkStateChanged(m_section, peerId(), "inbound", false);
|
|
||||||
|
|
||||||
if (m_debug)
|
if (m_debug)
|
||||||
{
|
{
|
||||||
@@ -625,6 +661,10 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con,
|
|||||||
{
|
{
|
||||||
m_heartbeat_timer.setEnable(false);
|
m_heartbeat_timer.setEnable(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Emit after state is cleared so isActive()-based cleanup in consumers
|
||||||
|
// (e.g. Redis peer-node mirror) sees the correct post-disconnect state.
|
||||||
|
m_reflector->onTrunkStateChanged(m_section, peerId(), "inbound", false);
|
||||||
} /* TrunkLink::onInboundDisconnected */
|
} /* TrunkLink::onInboundDisconnected */
|
||||||
|
|
||||||
|
|
||||||
@@ -731,7 +771,6 @@ void TrunkLink::onDisconnected(TcpConnection* con,
|
|||||||
{
|
{
|
||||||
cout << m_section << ": Outbound disconnected: "
|
cout << m_section << ": Outbound disconnected: "
|
||||||
<< TcpConnection::disconnectReasonStr(reason) << endl;
|
<< TcpConnection::disconnectReasonStr(reason) << endl;
|
||||||
m_reflector->onTrunkStateChanged(m_section, peerId(), "outbound", false);
|
|
||||||
|
|
||||||
if (m_debug)
|
if (m_debug)
|
||||||
{
|
{
|
||||||
@@ -751,6 +790,10 @@ void TrunkLink::onDisconnected(TcpConnection* con,
|
|||||||
m_heartbeat_timer.setEnable(false);
|
m_heartbeat_timer.setEnable(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Emit after state is cleared so isActive()-based cleanup in consumers
|
||||||
|
// sees the correct post-disconnect state.
|
||||||
|
m_reflector->onTrunkStateChanged(m_section, peerId(), "outbound", false);
|
||||||
|
|
||||||
// TcpPrioClient auto-reconnects — nothing else to do
|
// TcpPrioClient auto-reconnects — nothing else to do
|
||||||
} /* TrunkLink::onDisconnected */
|
} /* TrunkLink::onDisconnected */
|
||||||
|
|
||||||
@@ -898,7 +941,7 @@ void TrunkLink::handleMsgTrunkHello(std::istream& is, bool is_inbound)
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_peer_priority = msg.priority();
|
m_peer_priority = msg.priority();
|
||||||
m_peer_id_received = msg.id();
|
m_peer_id_received = sanitizeIdent(msg.id(), 64);
|
||||||
m_ob_hello_received = true;
|
m_ob_hello_received = true;
|
||||||
|
|
||||||
cout << m_section << ": Trunk hello from peer '" << msg.id()
|
cout << m_section << ": Trunk hello from peer '" << msg.id()
|
||||||
@@ -1605,7 +1648,7 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client,
|
|||||||
// (all twins share the same peer priority; last-writer wins is fine here)
|
// (all twins share the same peer priority; last-writer wins is fine here)
|
||||||
m_peer_priority = msg.priority();
|
m_peer_priority = msg.priority();
|
||||||
if (m_peer_id_received.empty())
|
if (m_peer_id_received.empty())
|
||||||
m_peer_id_received = msg.id();
|
m_peer_id_received = sanitizeIdent(msg.id(), 64);
|
||||||
|
|
||||||
cout << m_section << ": paired outbound #" << idx
|
cout << m_section << ": paired outbound #" << idx
|
||||||
<< " hello received (peer='" << msg.id()
|
<< " hello received (peer='" << msg.id()
|
||||||
@@ -1746,7 +1789,50 @@ void TrunkLink::handleMsgTrunkNodeList(std::istream& is)
|
|||||||
<< "]: Failed to unpack MsgTrunkNodeList" << endl;
|
<< "]: Failed to unpack MsgTrunkNodeList" << endl;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
m_reflector->onPeerNodeList(peerId(), msg.nodes());
|
|
||||||
|
// Sanitize every entry before handing off. Untrusted strings from peer
|
||||||
|
// reflectors flow into Redis key names, MQTT payloads and log output;
|
||||||
|
// keep them byte-bounded and free of control / delimiter characters.
|
||||||
|
std::vector<MsgTrunkNodeList::NodeEntry> 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);
|
||||||
|
|
||||||
|
// Lat/lon: reject non-finite; drop out-of-range values by zeroing
|
||||||
|
// them (keep the callsign, lose the coordinates). Downstream consumers
|
||||||
|
// already treat (0,0) as "no location".
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
e.lat = 0.0f;
|
||||||
|
e.lon = 0.0f;
|
||||||
|
}
|
||||||
|
sanitized.push_back(std::move(e));
|
||||||
|
}
|
||||||
|
if (dropped > 0)
|
||||||
|
{
|
||||||
|
cerr << "*** WARN[" << m_section << "]: dropped " << dropped
|
||||||
|
<< " node list entrie(s) with empty/invalid callsign after "
|
||||||
|
"sanitization" << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_reflector->onPeerNodeList(peerId(), sanitized);
|
||||||
} /* TrunkLink::handleMsgTrunkNodeList */
|
} /* TrunkLink::handleMsgTrunkNodeList */
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -124,6 +124,8 @@ class TrunkLink : public sigc::trackable
|
|||||||
{
|
{
|
||||||
return m_paired ? !m_ib_cons.empty() : (m_inbound_con != nullptr);
|
return m_paired ? !m_ib_cons.empty() : (m_inbound_con != nullptr);
|
||||||
}
|
}
|
||||||
|
// True when at least one direction (inbound or outbound) is ready.
|
||||||
|
bool isActive(void) const;
|
||||||
|
|
||||||
// Accept an inbound connection from a peer that has already sent a hello
|
// Accept an inbound connection from a peer that has already sent a hello
|
||||||
void acceptInboundConnection(Async::FramedTcpConnection* con,
|
void acceptInboundConnection(Async::FramedTcpConnection* con,
|
||||||
@@ -228,7 +230,6 @@ class TrunkLink : public sigc::trackable
|
|||||||
TrunkLink(const TrunkLink&);
|
TrunkLink(const TrunkLink&);
|
||||||
TrunkLink& operator=(const TrunkLink&);
|
TrunkLink& operator=(const TrunkLink&);
|
||||||
|
|
||||||
bool isActive(void) const;
|
|
||||||
bool isOutboundReady(void) const;
|
bool isOutboundReady(void) const;
|
||||||
bool isInboundReady(void) const;
|
bool isInboundReady(void) const;
|
||||||
bool isOwnedTG(uint32_t tg) const;
|
bool isOwnedTG(uint32_t tg) const;
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ def generate_docker_compose() -> str:
|
|||||||
for name in sorted(T.REFLECTORS):
|
for name in sorted(T.REFLECTORS):
|
||||||
svc = T.service_name(name)
|
svc = T.service_name(name)
|
||||||
client_port = T.mapped_client_port(name)
|
client_port = T.mapped_client_port(name)
|
||||||
|
trunk_port = T.mapped_trunk_port(name)
|
||||||
http_port = T.mapped_http_port(name)
|
http_port = T.mapped_http_port(name)
|
||||||
vol = f"pki-redis-{name}"
|
vol = f"pki-redis-{name}"
|
||||||
volumes.append(vol)
|
volumes.append(vol)
|
||||||
@@ -62,6 +63,7 @@ def generate_docker_compose() -> str:
|
|||||||
ports:
|
ports:
|
||||||
- "{client_port}:{T.INTERNAL_CLIENT_PORT}/tcp"
|
- "{client_port}:{T.INTERNAL_CLIENT_PORT}/tcp"
|
||||||
- "{client_port}:{T.INTERNAL_CLIENT_PORT}/udp"
|
- "{client_port}:{T.INTERNAL_CLIENT_PORT}/udp"
|
||||||
|
- "{trunk_port}:{T.INTERNAL_TRUNK_PORT}/tcp"
|
||||||
- "{http_port}:{T.INTERNAL_HTTP_PORT}/tcp"
|
- "{http_port}:{T.INTERNAL_HTTP_PORT}/tcp"
|
||||||
depends_on:
|
depends_on:
|
||||||
redis:
|
redis:
|
||||||
|
|||||||
+165
-1
@@ -14,7 +14,7 @@ import unittest
|
|||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
import topology_redis as T
|
import topology_redis as T
|
||||||
from test_trunk import ClientPeer
|
from test_trunk import ClientPeer, TrunkPeer
|
||||||
|
|
||||||
HOST = "127.0.0.1"
|
HOST = "127.0.0.1"
|
||||||
|
|
||||||
@@ -458,6 +458,170 @@ TG_MAP=1:2624123,2:2624124
|
|||||||
"second import produced different Redis state")
|
"second import produced different Redis state")
|
||||||
|
|
||||||
|
|
||||||
|
class RedisPeerNodeTest(unittest.TestCase):
|
||||||
|
"""Verify peer node lists received over the trunk are mirrored into
|
||||||
|
Redis as live:peer_node:<peer_id>:<callsign> hashes, with removed
|
||||||
|
callsigns DEL'd on shrink and full cleanup on trunk disconnect."""
|
||||||
|
|
||||||
|
# Matches topology_redis.TRUNK_TEST (the static trunk section in the
|
||||||
|
# generated r1 config).
|
||||||
|
SECTION = T.TRUNK_TEST["section"] # "TRUNK_TEST"
|
||||||
|
SECRET = T.TRUNK_TEST["secret"] # "test_secret"
|
||||||
|
# Reflector's REMOTE_PREFIX for this section — peer must advertise it
|
||||||
|
# as its local_prefix to pass the inbound prefix check.
|
||||||
|
LOCAL_PREFIX = T.TRUNK_TEST["remote_prefix"] # "9"
|
||||||
|
|
||||||
|
TRUNK_PORT = T.mapped_trunk_port(R1)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
flushdb()
|
||||||
|
|
||||||
|
def _peer_key(self, callsign: str) -> str:
|
||||||
|
return k(f"live:peer_node:{self.SECTION}:{callsign}")
|
||||||
|
|
||||||
|
def _wait_for_hash(self, key: str, present: bool, timeout: float = 3.0):
|
||||||
|
deadline = time.time() + timeout
|
||||||
|
while time.time() < deadline:
|
||||||
|
exists = redis_cli("EXISTS", key).strip() == "1"
|
||||||
|
if present and exists:
|
||||||
|
return redis_cli("HGETALL", key)
|
||||||
|
if (not present) and (not exists):
|
||||||
|
return ""
|
||||||
|
time.sleep(0.1)
|
||||||
|
self.fail(
|
||||||
|
f"Timed out waiting for {key} "
|
||||||
|
f"{'to exist' if present else 'to be absent'}")
|
||||||
|
|
||||||
|
def _hgetall_dict(self, key: str) -> dict:
|
||||||
|
raw = redis_cli("HGETALL", key)
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
fields = raw.splitlines()
|
||||||
|
return dict(zip(fields[0::2], fields[1::2]))
|
||||||
|
|
||||||
|
def _connect_peer(self) -> TrunkPeer:
|
||||||
|
peer = TrunkPeer()
|
||||||
|
peer.connect(HOST, self.TRUNK_PORT)
|
||||||
|
peer.handshake(trunk_id=self.SECTION,
|
||||||
|
local_prefix=self.LOCAL_PREFIX,
|
||||||
|
secret=self.SECRET)
|
||||||
|
return peer
|
||||||
|
|
||||||
|
def test_peer_node_list_creates_and_updates_hashes(self):
|
||||||
|
"""Inbound node list populates live:peer_node:* hashes;
|
||||||
|
subsequent shrunk list DELs dropped callsigns."""
|
||||||
|
peer = self._connect_peer()
|
||||||
|
try:
|
||||||
|
peer.send_node_list([
|
||||||
|
("N1AAA", 123, 0.0, 0.0, ""),
|
||||||
|
("N1BBB", 456, 52.5, 13.4, "Berlin"),
|
||||||
|
])
|
||||||
|
self._wait_for_hash(self._peer_key("N1AAA"), present=True)
|
||||||
|
self._wait_for_hash(self._peer_key("N1BBB"), present=True)
|
||||||
|
|
||||||
|
aaa = self._hgetall_dict(self._peer_key("N1AAA"))
|
||||||
|
self.assertEqual(aaa["callsign"], "N1AAA")
|
||||||
|
self.assertEqual(aaa["peer_id"], self.SECTION)
|
||||||
|
self.assertEqual(aaa["tg"], "123")
|
||||||
|
self.assertIn("updated_at", aaa)
|
||||||
|
# No lat/lon/qth expected when lat==lon==0 and qth empty.
|
||||||
|
self.assertNotIn("lat", aaa)
|
||||||
|
self.assertNotIn("lon", aaa)
|
||||||
|
self.assertNotIn("qth_name", aaa)
|
||||||
|
|
||||||
|
bbb = self._hgetall_dict(self._peer_key("N1BBB"))
|
||||||
|
self.assertEqual(bbb["tg"], "456")
|
||||||
|
self.assertIn("lat", bbb)
|
||||||
|
self.assertIn("lon", bbb)
|
||||||
|
self.assertEqual(bbb["qth_name"], "Berlin")
|
||||||
|
|
||||||
|
# Shrink the list: drop N1BBB, update N1AAA's TG.
|
||||||
|
peer.send_node_list([("N1AAA", 789)])
|
||||||
|
self._wait_for_hash(self._peer_key("N1BBB"), present=False)
|
||||||
|
deadline = time.time() + 3.0
|
||||||
|
while time.time() < deadline:
|
||||||
|
aaa = self._hgetall_dict(self._peer_key("N1AAA"))
|
||||||
|
if aaa.get("tg") == "789":
|
||||||
|
break
|
||||||
|
time.sleep(0.1)
|
||||||
|
else:
|
||||||
|
self.fail(f"N1AAA tg did not update to 789, got {aaa!r}")
|
||||||
|
finally:
|
||||||
|
peer.close()
|
||||||
|
|
||||||
|
def test_hostile_strings_are_sanitized(self):
|
||||||
|
"""Callsigns/QTH with control chars, ':' delimiters, or oversized
|
||||||
|
lengths must be stripped/truncated before Redis write. Entries
|
||||||
|
whose callsign becomes empty after sanitization must be dropped
|
||||||
|
entirely; entries with invalid lat/lon must keep callsign but
|
||||||
|
lose the coordinates."""
|
||||||
|
peer = self._connect_peer()
|
||||||
|
try:
|
||||||
|
peer.send_node_list([
|
||||||
|
# 1) Control chars + ':' removed from callsign
|
||||||
|
("N1\x01AAA:EVIL", 111, 0.0, 0.0, ""),
|
||||||
|
# 2) Over-length callsign is truncated to 32
|
||||||
|
("Z" * 64, 222, 0.0, 0.0, ""),
|
||||||
|
# 3) Callsign is only stripped chars → entry dropped
|
||||||
|
(":::\x00\x01\x02", 333, 0.0, 0.0, ""),
|
||||||
|
# 4) QTH control chars stripped; other bytes kept
|
||||||
|
("N1QTH", 444, 52.5, 13.4, "Bad\x01\x02QTH"),
|
||||||
|
# 5) Invalid coordinates → keep callsign, drop lat/lon
|
||||||
|
("N1GEOX", 555, float("nan"), 13.4, ""),
|
||||||
|
("N1GEOY", 556, 52.5, 999.0, ""),
|
||||||
|
])
|
||||||
|
|
||||||
|
# (1) sanitized callsign = "N1AAAEVIL"
|
||||||
|
self._wait_for_hash(self._peer_key("N1AAAEVIL"), present=True)
|
||||||
|
# (2) truncated to 32 'Z'
|
||||||
|
self._wait_for_hash(self._peer_key("Z" * 32), present=True)
|
||||||
|
# (3) dropped entirely — no key with the stripped form should exist.
|
||||||
|
# Sanity-check by listing live:peer_node:TRUNK_TEST:* and verifying
|
||||||
|
# only expected callsigns appear.
|
||||||
|
raw = redis_cli("KEYS", k(f"live:peer_node:{self.SECTION}:*"))
|
||||||
|
present_keys = set(raw.splitlines()) if raw else set()
|
||||||
|
expected = {
|
||||||
|
self._peer_key("N1AAAEVIL"),
|
||||||
|
self._peer_key("Z" * 32),
|
||||||
|
self._peer_key("N1QTH"),
|
||||||
|
self._peer_key("N1GEOX"),
|
||||||
|
self._peer_key("N1GEOY"),
|
||||||
|
}
|
||||||
|
self.assertEqual(present_keys, expected,
|
||||||
|
f"unexpected peer_node keys: got={sorted(present_keys)} "
|
||||||
|
f"expected={sorted(expected)}")
|
||||||
|
|
||||||
|
# (4) QTH stripped of control chars
|
||||||
|
qth_entry = self._hgetall_dict(self._peer_key("N1QTH"))
|
||||||
|
self.assertEqual(qth_entry["qth_name"], "BadQTH")
|
||||||
|
|
||||||
|
# (5) Invalid coordinates → no lat/lon fields
|
||||||
|
geox = self._hgetall_dict(self._peer_key("N1GEOX"))
|
||||||
|
self.assertNotIn("lat", geox)
|
||||||
|
self.assertNotIn("lon", geox)
|
||||||
|
geoy = self._hgetall_dict(self._peer_key("N1GEOY"))
|
||||||
|
self.assertNotIn("lat", geoy)
|
||||||
|
self.assertNotIn("lon", geoy)
|
||||||
|
finally:
|
||||||
|
peer.close()
|
||||||
|
|
||||||
|
def test_peer_nodes_cleared_on_trunk_disconnect(self):
|
||||||
|
"""Closing the trunk link (no other direction active) must DEL all
|
||||||
|
of that peer's node keys from Redis."""
|
||||||
|
peer = self._connect_peer()
|
||||||
|
try:
|
||||||
|
peer.send_node_list([("N1AAA", 123), ("N1BBB", 456)])
|
||||||
|
self._wait_for_hash(self._peer_key("N1AAA"), present=True)
|
||||||
|
self._wait_for_hash(self._peer_key("N1BBB"), present=True)
|
||||||
|
finally:
|
||||||
|
peer.close()
|
||||||
|
|
||||||
|
# Outbound peer (192.0.2.1) is unroutable, so isActive() becomes
|
||||||
|
# false as soon as our inbound closes — cleanup should fire.
|
||||||
|
self._wait_for_hash(self._peer_key("N1AAA"), present=False, timeout=5.0)
|
||||||
|
self._wait_for_hash(self._peer_key("N1BBB"), present=False, timeout=5.0)
|
||||||
|
|
||||||
|
|
||||||
class RedisTrunkAddRemoveTest(unittest.TestCase):
|
class RedisTrunkAddRemoveTest(unittest.TestCase):
|
||||||
"""Verify dashboard-style add/remove of trunk peers at runtime via
|
"""Verify dashboard-style add/remove of trunk peers at runtime via
|
||||||
pub/sub. Uses a dedicated section name so we don't collide with the
|
pub/sub. Uses a dedicated section name so we don't collide with the
|
||||||
|
|||||||
@@ -166,6 +166,45 @@ def build_heartbeat() -> bytes:
|
|||||||
return struct.pack("!H", MSG_TRUNK_HEARTBEAT)
|
return struct.pack("!H", MSG_TRUNK_HEARTBEAT)
|
||||||
|
|
||||||
|
|
||||||
|
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<string> callsigns, vec<u32> tgs,
|
||||||
|
vec<float> lat, vec<float> lon, vec<string> qth_names — each vector
|
||||||
|
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, ""
|
||||||
|
elif len(n) == 5:
|
||||||
|
cs, tg, lat, lon, qth = n
|
||||||
|
else:
|
||||||
|
raise ValueError("node tuple must be (cs, tg) or (cs, tg, lat, lon, qth)")
|
||||||
|
norm.append((cs, tg, lat, lon, qth))
|
||||||
|
|
||||||
|
payload = struct.pack("!H", MSG_TRUNK_NODE_LIST)
|
||||||
|
payload += struct.pack("!H", len(norm))
|
||||||
|
for cs, _tg, _lat, _lon, _qth in norm:
|
||||||
|
payload += pack_string(cs)
|
||||||
|
payload += struct.pack("!H", len(norm))
|
||||||
|
for _cs, tg, _lat, _lon, _qth in norm:
|
||||||
|
payload += struct.pack("!I", tg)
|
||||||
|
payload += struct.pack("!H", len(norm))
|
||||||
|
for _cs, _tg, lat, _lon, _qth in norm:
|
||||||
|
payload += struct.pack("!f", lat)
|
||||||
|
payload += struct.pack("!H", len(norm))
|
||||||
|
for _cs, _tg, _lat, lon, _qth in norm:
|
||||||
|
payload += struct.pack("!f", lon)
|
||||||
|
payload += struct.pack("!H", len(norm))
|
||||||
|
for _cs, _tg, _lat, _lon, qth in norm:
|
||||||
|
payload += pack_string(qth)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Message parser
|
# Message parser
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -271,6 +310,9 @@ class TrunkPeer:
|
|||||||
def send_heartbeat(self):
|
def send_heartbeat(self):
|
||||||
send_frame(self.sock, build_heartbeat())
|
send_frame(self.sock, build_heartbeat())
|
||||||
|
|
||||||
|
def send_node_list(self, nodes):
|
||||||
|
send_frame(self.sock, build_node_list(nodes))
|
||||||
|
|
||||||
def recv_msg(self, timeout: float = 5.0):
|
def recv_msg(self, timeout: float = 5.0):
|
||||||
old = self.sock.gettimeout()
|
old = self.sock.gettimeout()
|
||||||
self.sock.settimeout(timeout)
|
self.sock.settimeout(timeout)
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ def service_name(name: str) -> str:
|
|||||||
def mapped_client_port(name: str) -> int:
|
def mapped_client_port(name: str) -> int:
|
||||||
return REFLECTORS[name]["trunk_port_base"] + 300
|
return REFLECTORS[name]["trunk_port_base"] + 300
|
||||||
|
|
||||||
|
def mapped_trunk_port(name: str) -> int:
|
||||||
|
return REFLECTORS[name]["trunk_port_base"] + 302
|
||||||
|
|
||||||
def mapped_http_port(name: str) -> int:
|
def mapped_http_port(name: str) -> int:
|
||||||
return REFLECTORS[name]["trunk_port_base"] + 3080
|
return REFLECTORS[name]["trunk_port_base"] + 3080
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user