From b8d0dd19afd6dbdb6aff29486b7aa4254f52dcd6 Mon Sep 17 00:00:00 2001 From: Audric Date: Thu, 26 Mar 2026 12:59:04 +0100 Subject: [PATCH] Add trunk TCP server for bidirectional peer connections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously TrunkLink only connected outbound — there was no server listening on port 5302, so both reflectors got "Connection refused." Changes: - Reflector: add trunk TcpServer (default port 5302, configurable via TRUNK_LISTEN_PORT) that accepts inbound peer connections, authenticates via HMAC, and matches by secret + prefix - TrunkLink: support both outbound and inbound directions with automatic conflict resolution (lower priority keeps outbound) - Security: pre-auth frame size cap (4KB), max 5 pending connections, 10s hello timeout, log-injection sanitization - Docs: updated TRUNK_PROTOCOL.md, README.md, CLAUDE.md --- README.md | 15 +- docs/TRUNK_PROTOCOL.md | 79 +++++-- src/svxlink/reflector/Reflector.cpp | 227 ++++++++++++++++++++ src/svxlink/reflector/Reflector.h | 14 ++ src/svxlink/reflector/TrunkLink.cpp | 238 +++++++++++++++++++-- src/svxlink/reflector/TrunkLink.h | 27 ++- src/svxlink/reflector/svxreflector.conf.in | 1 + 7 files changed, 563 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 5154a1d..672bc10 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,9 @@ when a single reflector owns multiple prefix groups: ```ini [GLOBAL] LISTEN_PORT=5300 -LOCAL_PREFIX=1 # owns TGs 1, 10, 100, 1000, ... -# LOCAL_PREFIX=11,12,13 # multiple prefixes on one instance +LOCAL_PREFIX=1 # owns TGs 1, 10, 100, 1000, ... +# LOCAL_PREFIX=11,12,13 # multiple prefixes on one instance +# TRUNK_LISTEN_PORT=5302 # trunk server port (default 5302) ``` ### 2. Cluster TGs (optional) @@ -145,9 +146,13 @@ Repeat for each peer (`[TRUNK_3]`, `[TRUNK_4]`, …). ### Network requirements -**Trunk links** require **mutual reachability**: each reflector connects outbound -to every peer, so all reflectors in the mesh need a static IP (or stable DNS -name) and the trunk port (default 5302) open for inbound TCP connections. +**Trunk links** require **mutual reachability**: each reflector both listens for +inbound trunk connections and connects outbound to every peer. Both sides +attempt to connect simultaneously; the first connection that authenticates +becomes the active link (duplicate connections are resolved automatically via +priority-based tie-breaking). All reflectors in the mesh need a static IP (or +stable DNS name) and the trunk port (default 5302, configurable via +`TRUNK_LISTEN_PORT`) open for inbound TCP connections. **Satellite links** are **one-way**: the satellite connects outbound to the parent. Only the parent needs a static IP and its satellite port (default 5303) diff --git a/docs/TRUNK_PROTOCOL.md b/docs/TRUNK_PROTOCOL.md index 0ef7969..963c7d0 100644 --- a/docs/TRUNK_PROTOCOL.md +++ b/docs/TRUNK_PROTOCOL.md @@ -37,9 +37,13 @@ local talker. (full mesh) ``` -Each reflector runs one `TrunkLink` instance per configured peer. The trunk -is a persistent outbound TCP connection from each reflector to its peer on a -dedicated port (default 5302, separate from the client port 5300). +Each reflector runs one `TrunkLink` instance per configured peer and a trunk +TCP server (default port 5302, configurable via `TRUNK_LISTEN_PORT`). Each +`TrunkLink` attempts an outbound connection to the peer while simultaneously +accepting inbound connections from the peer on the trunk server. Only one +connection per peer is active at a time — when both directions connect +simultaneously, a deterministic tie-break selects which connection to keep +(see [Connection Conflict Resolution](#connection-conflict-resolution)). --- @@ -128,21 +132,66 @@ directions: ## Connection and Handshake -On TCP connect, both sides immediately send `MsgTrunkHello`. No challenge/response -is used; authentication relies on network-level access control (firewall rules) -and the shared secret validated at the application level in future versions. +Each reflector both listens for inbound trunk connections on its trunk server +port (default 5302) and actively connects outbound to each configured peer. +Whichever direction succeeds first becomes the active connection for that peer. + +### Outbound connection + +When a `TrunkLink` connects outbound to a peer, it immediately sends +`MsgTrunkHello`. The peer's trunk server accepts the connection, verifies the +HMAC-authenticated shared secret, matches it to the corresponding `TrunkLink`, +and sends its own `MsgTrunkHello` in response. ``` Reflector A (prefix "1") Reflector B (prefix "2") - │──── MsgTrunkHello(id, local_prefix="1", priority) ──►│ - │◀─── MsgTrunkHello(id, local_prefix="2", priority) ───│ + │──── TCP connect to B:5302 ──────────────────────────►│ + │──── MsgTrunkHello(id, prefix="1", priority, HMAC) ──►│ + │ B verifies HMAC, matches TrunkLink + │◀─── MsgTrunkHello(id, prefix="2", priority, HMAC) ───│ │ (both sides ready) │ ``` -`MsgTrunkHello` carries: +### Inbound connection + +The trunk server (`Reflector::m_trunk_srv`) listens on the configured +`TRUNK_LISTEN_PORT` (default 5302). When a peer connects: + +1. The connection enters a **pending** state with a 10-second hello timeout +2. The server waits for a `MsgTrunkHello` frame +3. The shared secret is verified via HMAC against each configured `TrunkLink` +4. On match, the connection is handed off to the corresponding `TrunkLink` +5. The `TrunkLink` pauses its own outbound connection attempts and uses the + inbound connection + +**Security hardening:** +- Pre-authentication frame size is limited to 4 KB (vs 32 KB post-auth) +- Maximum 5 pending (unauthenticated) connections at a time +- 10-second timeout for hello message; connections that don't authenticate are + dropped +- Peer identifiers are sanitized before logging (control characters stripped, + length capped at 64) + +### Connection Conflict Resolution + +Because both sides connect outbound simultaneously, it is possible for both an +inbound and outbound connection to be active at the same time for the same peer. +When this is detected, a deterministic tie-break resolves the conflict: + +- The side with the **lower** priority nonce keeps its **outbound** connection +- The side with the higher priority nonce keeps the **inbound** connection +- Both sides independently reach the same conclusion, so exactly one TCP + connection survives + +This ensures convergence regardless of timing. + +### `MsgTrunkHello` fields + - `id` — the config section name (e.g. `TRUNK_2`), used for logging - `local_prefix` — the sender's authoritative TG prefix (e.g. `"1"`) -- `priority` — random 32-bit nonce generated at startup, used for tie-breaking +- `priority` — random 32-bit nonce, regenerated per connection, used for + tie-breaking (both talker arbitration and connection conflict resolution) +- `nonce` + `digest` — HMAC authentication of the shared secret --- @@ -306,12 +355,14 @@ of the request. It is empty when no trunk conversations are in progress. ### Global setting (both reflectors) Add `LOCAL_PREFIX` to the `[GLOBAL]` section. This declares which TG prefix -this reflector is authoritative for: +this reflector is authoritative for. `TRUNK_LISTEN_PORT` sets the TCP port +the trunk server listens on (default 5302): ```ini [GLOBAL] ... -LOCAL_PREFIX=1 # this reflector owns TGs 1, 10, 100, 1000, ... +LOCAL_PREFIX=1 # this reflector owns TGs 1, 10, 100, 1000, ... +TRUNK_LISTEN_PORT=5302 # trunk server port (default 5302, optional) ``` ### Per-trunk section @@ -377,8 +428,8 @@ REMOTE_PREFIX=2 | `src/svxlink/reflector/ReflectorMsg.h` | Added `MsgTrunkHello`–`MsgTrunkHeartbeat` (types 115–120); `MsgTrunkHello` carries `local_prefix` string instead of TG list | | `src/svxlink/reflector/TGHandler.h` | Added trunk talker map, 5 methods + snapshot accessor, `trunkTalkerUpdated` signal | | `src/svxlink/reflector/TGHandler.cpp` | Implemented trunk talker methods including `clearAllTrunkTalkers` | -| `src/svxlink/reflector/Reflector.h` | Added `m_trunk_links`, `initTrunkLinks()`, `onTrunkTalkerUpdated()` | -| `src/svxlink/reflector/Reflector.cpp` | Wired trunk init, signals, audio relay, arbitration guard, HTTP status | +| `src/svxlink/reflector/Reflector.h` | Added `m_trunk_links`, `m_trunk_srv`, `initTrunkLinks()`, `initTrunkServer()`, `onTrunkTalkerUpdated()`, trunk inbound connection handling | +| `src/svxlink/reflector/Reflector.cpp` | Wired trunk init, trunk server (listen + accept + auth), signals, audio relay, arbitration guard, HTTP status | | `src/svxlink/reflector/TrunkLink.h` | **New** — `TrunkLink` class declaration | | `src/svxlink/reflector/TrunkLink.cpp` | **New** — full trunk link implementation | | `src/svxlink/reflector/CMakeLists.txt` | Added `TrunkLink.cpp` to sources | diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 44c1302..60846f6 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -31,6 +31,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include +#include #include #include #include @@ -291,6 +292,14 @@ Reflector::~Reflector(void) delete link; } m_trunk_links.clear(); + for (auto& kv : m_trunk_pending_cons) + { + delete kv.second; + } + m_trunk_pending_cons.clear(); + m_trunk_inbound_map.clear(); + delete m_trunk_srv; + m_trunk_srv = nullptr; for (auto& kv : m_satellite_con_map) { delete kv.second; @@ -446,6 +455,7 @@ bool Reflector::initialize(Async::Config &cfg) } initTrunkLinks(); + initTrunkServer(); initSatelliteServer(); return true; @@ -2054,6 +2064,223 @@ void Reflector::initTrunkLinks(void) } /* Reflector::initTrunkLinks */ +void Reflector::initTrunkServer(void) +{ + if (m_trunk_links.empty()) + { + return; // No trunk links configured — no need for a trunk server + } + + std::string trunk_port("5302"); + m_cfg->getValue("GLOBAL", "TRUNK_LISTEN_PORT", trunk_port); + + m_trunk_srv = new TcpServer(trunk_port); + m_trunk_srv->clientConnected.connect( + sigc::mem_fun(*this, &Reflector::trunkClientConnected)); + m_trunk_srv->clientDisconnected.connect( + sigc::mem_fun(*this, &Reflector::trunkClientDisconnected)); + + std::cout << "Trunk server listening on port " << trunk_port << std::endl; +} /* Reflector::initTrunkServer */ + + +void Reflector::trunkClientConnected(Async::FramedTcpConnection* con) +{ + // Reject connections beyond the pending limit to prevent fd exhaustion + if (m_trunk_pending_cons.size() >= TRUNK_MAX_PENDING_CONS) + { + std::cerr << "*** WARNING: TRUNK inbound from " + << con->remoteHost() + << ": too many pending connections — rejecting" << std::endl; + con->disconnect(); + return; + } + + std::cout << "TRUNK: Inbound connection from " + << con->remoteHost() << ":" << con->remotePort() << std::endl; + + // Set up a timeout for receiving the hello message + auto* timer = new Async::Timer(10000, Async::Timer::TYPE_ONESHOT); + timer->expired.connect( + sigc::mem_fun(*this, &Reflector::trunkPendingTimeout)); + m_trunk_pending_cons[con] = timer; + + // Use a limited frame size — only a hello message is expected. + // MsgTrunkHello contains strings + HMAC, so needs more than PREAUTH (64). + // Cap at SSL_SETUP size (4096) which is plenty for a hello. + con->setMaxFrameSize(ReflectorMsg::MAX_SSL_SETUP_FRAME_SIZE); + con->frameReceived.connect( + sigc::mem_fun(*this, &Reflector::trunkPendingFrameReceived)); +} /* Reflector::trunkClientConnected */ + + +void Reflector::trunkClientDisconnected(Async::FramedTcpConnection* con, + Async::FramedTcpConnection::DisconnectReason reason) +{ + // Check pending (pre-hello) connections + auto pit = m_trunk_pending_cons.find(con); + if (pit != m_trunk_pending_cons.end()) + { + delete pit->second; // timer + m_trunk_pending_cons.erase(pit); + std::cout << "TRUNK: Pending inbound from " + << con->remoteHost() << " disconnected" << std::endl; + return; + } + + // Check handed-off connections + auto tit = m_trunk_inbound_map.find(con); + if (tit != m_trunk_inbound_map.end()) + { + tit->second->onInboundDisconnected(con, reason); + m_trunk_inbound_map.erase(tit); + } +} /* Reflector::trunkClientDisconnected */ + + +void Reflector::trunkPendingFrameReceived(Async::FramedTcpConnection* con, + std::vector& data) +{ + auto pit = m_trunk_pending_cons.find(con); + if (pit == m_trunk_pending_cons.end()) + { + return; // Not a pending connection (already handed off) + } + + auto buf = reinterpret_cast(data.data()); + std::stringstream ss; + ss.write(buf, data.size()); + + ReflectorMsg header; + if (!header.unpack(ss)) + { + std::cerr << "*** ERROR: TRUNK inbound: failed to unpack message header" + << std::endl; + con->disconnect(); + return; + } + + if (header.type() != MsgTrunkHello::TYPE) + { + std::cerr << "*** WARNING: TRUNK inbound: expected MsgTrunkHello, got type=" + << header.type() << std::endl; + con->disconnect(); + return; + } + + MsgTrunkHello msg; + if (!msg.unpack(ss)) + { + std::cerr << "*** ERROR: TRUNK inbound: failed to unpack MsgTrunkHello" + << std::endl; + con->disconnect(); + return; + } + + if (msg.id().empty()) + { + std::cerr << "*** ERROR: TRUNK inbound: peer sent empty trunk ID" + << std::endl; + con->disconnect(); + return; + } + + // Sanitize peer ID for safe logging (strip control chars) + std::string safe_id; + for (char c : msg.id()) + { + if (c >= 0x20 && c < 0x7f) + { + safe_id += c; + } + } + if (safe_id.size() > 64) + { + safe_id.resize(64); + } + + // Find the matching TrunkLink by verifying the shared secret AND matching + // the peer's declared prefix against our configured REMOTE_PREFIX. + // This allows multiple trunk sections to share the same secret safely. + TrunkLink* matched_link = nullptr; + for (auto* link : m_trunk_links) + { + if (!msg.verify(link->secret())) + { + continue; + } + + // Check if the peer's local_prefix matches this link's remote_prefix. + // The peer sends a comma-separated prefix string; we compare the sorted + // sets for equality. + const auto& expected = link->remotePrefix(); + std::vector peer_prefixes; + { + std::istringstream pss(msg.localPrefix()); + std::string tok; + while (std::getline(pss, tok, ',')) + { + tok.erase(0, tok.find_first_not_of(" \t")); + tok.erase(tok.find_last_not_of(" \t") + 1); + if (!tok.empty()) peer_prefixes.push_back(tok); + } + } + std::vector sorted_expected(expected); + std::vector sorted_peer(peer_prefixes); + std::sort(sorted_expected.begin(), sorted_expected.end()); + std::sort(sorted_peer.begin(), sorted_peer.end()); + if (sorted_expected == sorted_peer) + { + matched_link = link; + break; + } + } + + if (matched_link == nullptr) + { + std::cerr << "*** ERROR: TRUNK inbound: peer '" << safe_id + << "' failed authentication (no matching secret/prefix)" + << std::endl; + con->disconnect(); + return; + } + + // Clean up the pending entry + delete pit->second; // timer + m_trunk_pending_cons.erase(pit); + + // Disconnect the pending frame handler (Reflector will no longer handle + // frames for this connection — the TrunkLink takes over) + con->frameReceived.clear(); + + // Upgrade to full frame size now that the peer is authenticated + con->setMaxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE); + + // Hand off to the TrunkLink + m_trunk_inbound_map[con] = matched_link; + matched_link->acceptInboundConnection(con, msg); +} /* Reflector::trunkPendingFrameReceived */ + + +void Reflector::trunkPendingTimeout(Async::Timer* t) +{ + // Find which pending connection this timer belongs to + for (auto it = m_trunk_pending_cons.begin(); + it != m_trunk_pending_cons.end(); ++it) + { + if (it->second == t) + { + std::cerr << "*** WARNING: TRUNK inbound from " + << it->first->remoteHost() + << ": hello timeout — disconnecting" << std::endl; + it->first->disconnect(); + // trunkClientDisconnected will clean up + return; + } + } +} /* Reflector::trunkPendingTimeout */ + + void Reflector::initSatelliteServer(void) { std::string sat_port; diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 78b979e..5aac4dd 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -299,6 +299,13 @@ class Reflector : public sigc::trackable std::vector m_trunk_links; std::set m_cluster_tgs; + static const size_t TRUNK_MAX_PENDING_CONS = 5; + + FramedTcpServer* m_trunk_srv = nullptr; + // Inbound trunk connections waiting for MsgTrunkHello identification + std::map m_trunk_pending_cons; + // Handed-off inbound trunk connections mapped to their TrunkLink + std::map m_trunk_inbound_map; // Satellite support bool m_is_satellite = false; @@ -332,6 +339,13 @@ class Reflector : public sigc::trackable void onTrunkTalkerUpdated(uint32_t tg, std::string old_cs, std::string new_cs); void initTrunkLinks(void); + void initTrunkServer(void); + void trunkClientConnected(Async::FramedTcpConnection* con); + void trunkClientDisconnected(Async::FramedTcpConnection* con, + Async::FramedTcpConnection::DisconnectReason reason); + void trunkPendingFrameReceived(Async::FramedTcpConnection* con, + std::vector& data); + void trunkPendingTimeout(Async::Timer* t); void initSatelliteServer(void); void satelliteConnected(Async::FramedTcpConnection* con); void satelliteDisconnected(Async::FramedTcpConnection* con, diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 4b5a318..06994c3 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -237,7 +237,7 @@ Json::Value TrunkLink::statusJson(void) const Json::Value obj(Json::objectValue); obj["host"] = m_peer_host; obj["port"] = m_peer_port; - obj["connected"] = m_con.isConnected(); + obj["connected"] = isActive(); Json::Value local_arr(Json::arrayValue); for (const auto& p : m_local_prefix) local_arr.append(p); obj["local_prefix"] = local_arr; @@ -262,9 +262,81 @@ Json::Value TrunkLink::statusJson(void) const } /* TrunkLink::statusJson */ +void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, + const MsgTrunkHello& hello) +{ + if (m_active_dir == ConDir::INBOUND) + { + cerr << "*** WARNING[" << m_section + << "]: Already have an inbound connection, rejecting new one" << endl; + con->disconnect(); + return; + } + + if (m_active_dir == ConDir::OUTBOUND) + { + // We already have an outbound connection. Resolve the conflict. + m_inbound_con = con; + m_peer_priority = hello.priority(); + resolveConnectionConflict(); + return; + } + + // No active connection — accept inbound and pause outbound + m_inbound_con = con; + m_active_dir = ConDir::INBOUND; + m_peer_priority = hello.priority(); + m_hello_received = true; + + // Regenerate our priority for this session + std::random_device rd; + std::mt19937 rng(rd()); + std::uniform_int_distribution dist; + m_priority = dist(rng); + + m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; + m_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; + m_heartbeat_timer.setEnable(true); + m_yielded_tgs.clear(); + m_peer_active_tgs.clear(); + + pauseOutbound(); + + // Wire inbound frame handler to our message dispatcher + con->frameReceived.connect( + mem_fun(*this, &TrunkLink::onFrameReceived)); + + cout << m_section << ": Accepted inbound from " << con->remoteHost() + << ":" << con->remotePort() << " peer='" << hello.id() + << "' priority=" << m_peer_priority << endl; + + // Send our hello back on the inbound connection + sendMsg(MsgTrunkHello(m_section, joinPrefixes(m_local_prefix), m_priority, + m_secret)); +} /* TrunkLink::acceptInboundConnection */ + + +void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con, + Async::FramedTcpConnection::DisconnectReason reason) +{ + if (m_active_dir != ConDir::INBOUND || con != m_inbound_con) + { + return; + } + + cout << m_section << ": Inbound trunk connection lost" << endl; + + m_inbound_con = nullptr; + cleanupTrunkState(); + + // Resume outbound connection attempts + resumeOutbound(); +} /* TrunkLink::onInboundDisconnected */ + + void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign) { - if (!m_con.isConnected() || !m_hello_received || + if (!isActive() || !m_hello_received || (!isSharedTG(tg) && !m_reflector->isClusterTG(tg))) { return; @@ -275,7 +347,7 @@ void TrunkLink::onLocalTalkerStart(uint32_t tg, const std::string& callsign) void TrunkLink::onLocalTalkerStop(uint32_t tg) { - if (!m_con.isConnected() || !m_hello_received || + if (!isActive() || !m_hello_received || (!isSharedTG(tg) && !m_reflector->isClusterTG(tg))) { return; @@ -292,7 +364,7 @@ void TrunkLink::onLocalTalkerStop(uint32_t tg) void TrunkLink::onLocalAudio(uint32_t tg, const std::vector& audio) { - if (!m_con.isConnected() || !m_hello_received || + if (!isActive() || !m_hello_received || (!isSharedTG(tg) && !m_reflector->isClusterTG(tg)) || m_yielded_tgs.count(tg)) { @@ -304,7 +376,7 @@ void TrunkLink::onLocalAudio(uint32_t tg, const std::vector& audio) void TrunkLink::onLocalFlush(uint32_t tg) { - if (!m_con.isConnected() || !m_hello_received || + if (!isActive() || !m_hello_received || (!isSharedTG(tg) && !m_reflector->isClusterTG(tg))) { return; @@ -321,9 +393,17 @@ void TrunkLink::onLocalFlush(uint32_t tg) void TrunkLink::onConnected(void) { - cout << m_section << ": Connected to " << m_con.remoteHost() + cout << m_section << ": Outbound connected to " << m_con.remoteHost() << ":" << m_con.remotePort() << endl; + if (m_active_dir == ConDir::INBOUND) + { + // We already have an active inbound connection — resolve conflict + resolveConnectionConflict(); + return; + } + + m_active_dir = ConDir::OUTBOUND; m_hello_received = false; m_yielded_tgs.clear(); m_peer_active_tgs.clear(); @@ -346,20 +426,18 @@ void TrunkLink::onConnected(void) void TrunkLink::onDisconnected(TcpConnection* con, TcpConnection::DisconnectReason reason) { + // If we're using an inbound connection, ignore outbound disconnect events + // (the outbound was paused or is being cycled by TcpPrioClient) + if (m_active_dir == ConDir::INBOUND) + { + return; + } + cout << m_section << ": Disconnected from " << m_con.remoteHost() << ":" << m_con.remotePort() << ": " << TcpConnection::disconnectReasonStr(reason) << endl; - m_heartbeat_timer.setEnable(false); - m_hello_received = false; - - // Release only trunk talkers held by this peer - for (uint32_t tg : m_peer_active_tgs) - { - TGHandler::instance()->clearTrunkTalkerForTG(tg); - } - m_peer_active_tgs.clear(); - m_yielded_tgs.clear(); + cleanupTrunkState(); } /* TrunkLink::onDisconnected */ @@ -595,7 +673,14 @@ void TrunkLink::sendMsg(const ReflectorMsg& msg) return; } m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; - m_con.write(ss.str().data(), ss.str().size()); + if (m_active_dir == ConDir::INBOUND && m_inbound_con != nullptr) + { + m_inbound_con->write(ss.str().data(), ss.str().size()); + } + else + { + m_con.write(ss.str().data(), ss.str().size()); + } } /* TrunkLink::sendMsg */ @@ -610,11 +695,128 @@ void TrunkLink::heartbeatTick(Async::Timer* t) { cerr << "*** ERROR[" << m_section << "]: Trunk heartbeat timeout — disconnecting" << endl; - m_con.disconnect(); + if (m_active_dir == ConDir::INBOUND && m_inbound_con != nullptr) + { + m_inbound_con->disconnect(); + } + else + { + m_con.disconnect(); + } } } /* TrunkLink::heartbeatTick */ +bool TrunkLink::isActive(void) const +{ + if (m_active_dir == ConDir::INBOUND) + { + return m_inbound_con != nullptr; + } + return m_con.isConnected(); +} /* TrunkLink::isActive */ + + +void TrunkLink::pauseOutbound(void) +{ + m_con.disconnect(); +} /* TrunkLink::pauseOutbound */ + + +void TrunkLink::resumeOutbound(void) +{ + m_con.connect(); +} /* TrunkLink::resumeOutbound */ + + +void TrunkLink::resolveConnectionConflict(void) +{ + // Both an inbound and outbound connection exist. + // Lower priority value keeps its outbound connection. + if (m_priority < m_peer_priority) + { + // We win — keep outbound, drop inbound + cout << m_section << ": Connection conflict — keeping outbound " + << "(our priority=" << m_priority + << " < peer=" << m_peer_priority << ")" << endl; + if (m_inbound_con != nullptr) + { + m_inbound_con->disconnect(); + m_inbound_con = nullptr; + } + // If we didn't already have outbound as active, switch to it + if (m_active_dir != ConDir::OUTBOUND) + { + cleanupTrunkState(); + m_active_dir = ConDir::OUTBOUND; + m_hello_received = false; + m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; + m_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; + + std::random_device rd; + std::mt19937 rng(rd()); + std::uniform_int_distribution dist; + m_priority = dist(rng); + + sendMsg(MsgTrunkHello(m_section, joinPrefixes(m_local_prefix), + m_priority, m_secret)); + m_heartbeat_timer.setEnable(true); + } + } + else + { + // Peer wins — keep inbound, drop outbound + cout << m_section << ": Connection conflict — keeping inbound " + << "(our priority=" << m_priority + << " >= peer=" << m_peer_priority << ")" << endl; + + // Clean up outbound state + cleanupTrunkState(); + m_con.disconnect(); + + // Set up inbound as the active connection + m_active_dir = ConDir::INBOUND; + m_hello_received = true; + m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; + m_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; + m_heartbeat_timer.setEnable(true); + + // Regenerate our priority for this session + std::random_device rd; + std::mt19937 rng(rd()); + std::uniform_int_distribution dist; + m_priority = dist(rng); + + // Wire inbound frame handler + m_inbound_con->frameReceived.connect( + mem_fun(*this, &TrunkLink::onFrameReceived)); + + cout << m_section << ": Accepted inbound from " + << m_inbound_con->remoteHost() << ":" + << m_inbound_con->remotePort() << endl; + + // Send our hello back on the inbound connection + sendMsg(MsgTrunkHello(m_section, joinPrefixes(m_local_prefix), + m_priority, m_secret)); + } +} /* TrunkLink::resolveConnectionConflict */ + + +void TrunkLink::cleanupTrunkState(void) +{ + m_heartbeat_timer.setEnable(false); + m_hello_received = false; + m_active_dir = ConDir::NONE; + + for (uint32_t tg : m_peer_active_tgs) + { + TGHandler::instance()->clearTrunkTalkerForTG(tg); + } + m_peer_active_tgs.clear(); + m_yielded_tgs.clear(); +} /* TrunkLink::cleanupTrunkState */ + + /* * This file has not been truncated */ diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index a8affa8..883dc71 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -60,6 +60,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class Reflector; class ReflectorMsg; +class MsgTrunkHello; class MsgUdpAudio; @@ -100,6 +101,20 @@ class TrunkLink : public sigc::trackable Json::Value statusJson(void) const; + const std::string& secret(void) const { return m_secret; } + const std::vector& remotePrefix(void) const + { + return m_remote_prefix; + } + + // Accept an inbound connection from a peer that has already sent a hello + void acceptInboundConnection(Async::FramedTcpConnection* con, + const MsgTrunkHello& hello); + + // Called by Reflector when the inbound connection disconnects + void onInboundDisconnected(Async::FramedTcpConnection* con, + Async::FramedTcpConnection::DisconnectReason reason); + // Called by Reflector when a local client starts/stops on a shared TG void onLocalTalkerStart(uint32_t tg, const std::string& callsign); void onLocalTalkerStop(uint32_t tg); @@ -114,6 +129,8 @@ class TrunkLink : public sigc::trackable static const unsigned HEARTBEAT_TX_CNT_RESET = 10; static const unsigned HEARTBEAT_RX_CNT_RESET = 15; + enum class ConDir { NONE, OUTBOUND, INBOUND }; + using FramedTcpClient = Async::TcpPrioClient; @@ -128,7 +145,9 @@ class TrunkLink : public sigc::trackable uint32_t m_priority; // our tie-break nonce (random) uint32_t m_peer_priority; // peer's nonce, from MsgTrunkHello bool m_hello_received; - FramedTcpClient m_con; + FramedTcpClient m_con; // outbound client connection + Async::FramedTcpConnection* m_inbound_con = nullptr; // accepted inbound + ConDir m_active_dir = ConDir::NONE; Async::Timer m_heartbeat_timer; unsigned m_hb_tx_cnt; unsigned m_hb_rx_cnt; @@ -141,6 +160,12 @@ class TrunkLink : public sigc::trackable TrunkLink(const TrunkLink&); TrunkLink& operator=(const TrunkLink&); + bool isActive(void) const; + void pauseOutbound(void); + void resumeOutbound(void); + void resolveConnectionConflict(void); + void cleanupTrunkState(void); + void onConnected(void); void onDisconnected(Async::TcpConnection* con, Async::TcpConnection::DisconnectReason reason); diff --git a/src/svxlink/reflector/svxreflector.conf.in b/src/svxlink/reflector/svxreflector.conf.in index e824500..9a2185e 100644 --- a/src/svxlink/reflector/svxreflector.conf.in +++ b/src/svxlink/reflector/svxreflector.conf.in @@ -93,6 +93,7 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py # Reflector B: LOCAL_PREFIX=2, [TRUNK_1] with REMOTE_PREFIX=1 # #LOCAL_PREFIX=1 +#TRUNK_LISTEN_PORT=5302 #[TRUNK_2] #HOST=reflector-b.example.com