From 9f349fff5cd497b1cc18832ce5a7d9a89820ad81 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 20:33:54 +0200 Subject: [PATCH] TwinLink: outbound connect, handshake, heartbeat skeleton Implements TwinLink.cpp with constructor (random priority nonce via std::random_device, signal wiring), initialize() (parse [TWIN] HOST/PORT/ SECRET and [GLOBAL] LOCAL_PREFIX, addStaticSRVRecord + reconnect policy, m_con.connect()), onConnected() sending MsgTrunkHello with ROLE_TWIN, handleMsgTrunkHello() validating role/HMAC/prefix-match, heartbeatTick() (2s TX / 5s RX thresholds), sendMsg/sendMsgOnOutbound/sendMsgOnInbound, and acceptInboundConnection(). Phase C handlers (talker mirror, audio, ext-trunk) are present as empty stubs. Wires Reflector::initTwinLink() to construct and initialize a real TwinLink (replaces stub), adds destructor cleanup, and adds TwinLink.cpp to CMakeLists sources. Build passes clean. --- src/svxlink/reflector/CMakeLists.txt | 1 + src/svxlink/reflector/Reflector.cpp | 14 +- src/svxlink/reflector/TwinLink.cpp | 538 +++++++++++++++++++++++++++ 3 files changed, 550 insertions(+), 3 deletions(-) create mode 100644 src/svxlink/reflector/TwinLink.cpp diff --git a/src/svxlink/reflector/CMakeLists.txt b/src/svxlink/reflector/CMakeLists.txt index fb6df21..f6edc37 100644 --- a/src/svxlink/reflector/CMakeLists.txt +++ b/src/svxlink/reflector/CMakeLists.txt @@ -35,6 +35,7 @@ set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS}) # Build the executable add_executable(svxreflector svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp + TwinLink.cpp SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp RedisStore.cpp RedisAsyncAdapter.cpp RedisLiveQueue.cpp ) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index ecf27f5..0dd5e2d 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -70,6 +70,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "ReflectorClient.h" #include "TGHandler.h" #include "TrunkLink.h" +#include "TwinLink.h" #include "RedisStore.h" #include @@ -324,6 +325,8 @@ Reflector::~Reflector(void) m_sat_srv = nullptr; delete m_satellite_client; m_satellite_client = nullptr; + delete m_twin_link; + m_twin_link = nullptr; m_client_con_map.clear(); ReflectorClient::cleanup(); delete TGHandler::instance(); @@ -3889,9 +3892,14 @@ void Reflector::initTwinLink(void) { return; } - std::cout << "TWIN: section present in config (parser stub, no link yet)" - << std::endl; - // Actual TwinLink creation lands in Task B2. + + m_twin_link = new TwinLink(this, *m_cfg); + if (!m_twin_link->initialize()) + { + delete m_twin_link; + m_twin_link = nullptr; + cerr << "*** ERROR: TwinLink initialization failed" << endl; + } } /* Reflector::initTwinLink */ diff --git a/src/svxlink/reflector/TwinLink.cpp b/src/svxlink/reflector/TwinLink.cpp new file mode 100644 index 0000000..778350d --- /dev/null +++ b/src/svxlink/reflector/TwinLink.cpp @@ -0,0 +1,538 @@ +/** +@file TwinLink.cpp +@brief HA-pair link between two reflectors sharing a LOCAL_PREFIX +@author GeuReflector +@date 2026-04-15 + +\verbatim +SvxReflector - An audio reflector for connecting SvxLink Servers +Copyright (C) 2003-2026 Tobias Blomberg / SM0SVX + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +\endverbatim +*/ + + +/**************************************************************************** + * + * System Includes + * + ****************************************************************************/ + +#include +#include +#include + + +/**************************************************************************** + * + * Project Includes + * + ****************************************************************************/ + +#include +#include + + +/**************************************************************************** + * + * Local Includes + * + ****************************************************************************/ + +#include "TwinLink.h" +#include "ReflectorMsg.h" +#include "Reflector.h" +#include "TGHandler.h" + + +/**************************************************************************** + * + * Namespaces to use + * + ****************************************************************************/ + +using namespace std; +using namespace Async; +using namespace sigc; + + +/**************************************************************************** + * + * TwinLink public methods + * + ****************************************************************************/ + +TwinLink::TwinLink(Reflector* reflector, Async::Config& cfg) + : m_reflector(reflector), m_cfg(cfg), + m_peer_port(5304), + m_peer_id_config("TWIN"), + m_priority(0), m_peer_priority(0), + m_inbound_con(nullptr), + m_heartbeat_timer(1000, Timer::TYPE_PERIODIC, false), + m_ob_hello_received(false), + m_ob_hb_tx_cnt(0), m_ob_hb_rx_cnt(0), + m_ib_hello_received(false), + m_ib_hb_tx_cnt(0), m_ib_hb_rx_cnt(0) +{ + // Generate a random priority nonce for tie-breaking (once, for lifetime) + std::random_device rd; + std::mt19937 rng(rd()); + std::uniform_int_distribution dist; + m_priority = dist(rng); + + m_heartbeat_timer.expired.connect( + mem_fun(*this, &TwinLink::heartbeatTick)); + + m_con.connected.connect(mem_fun(*this, &TwinLink::onConnected)); + m_con.disconnected.connect(mem_fun(*this, &TwinLink::onDisconnected)); + m_con.frameReceived.connect(mem_fun(*this, &TwinLink::onFrameReceived)); + m_con.setMaxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE); +} /* TwinLink::TwinLink */ + + +TwinLink::~TwinLink(void) +{ + m_heartbeat_timer.setEnable(false); + if (m_inbound_con) + { + m_inbound_con->disconnect(); + m_inbound_con = nullptr; + } + m_con.disconnect(); +} /* TwinLink::~TwinLink */ + + +bool TwinLink::initialize(void) +{ + // HOST + if (!m_cfg.getValue(m_peer_id_config, "HOST", m_peer_host) + || m_peer_host.empty()) + { + cerr << "*** ERROR[TWIN]: Missing HOST in [TWIN] section" << endl; + return false; + } + + // PORT (optional, default 5304) + std::string port_str; + if (m_cfg.getValue(m_peer_id_config, "PORT", port_str) && !port_str.empty()) + { + m_peer_port = static_cast(std::atoi(port_str.c_str())); + } + + // SECRET + if (!m_cfg.getValue(m_peer_id_config, "SECRET", m_secret) + || m_secret.empty()) + { + cerr << "*** ERROR[TWIN]: Missing SECRET in [TWIN] section" << endl; + return false; + } + + // LOCAL_PREFIX — must be present; both partners must share the same value + if (!m_cfg.getValue("GLOBAL", "LOCAL_PREFIX", m_local_prefix) + || m_local_prefix.empty()) + { + cerr << "*** ERROR[TWIN]: Missing LOCAL_PREFIX in [GLOBAL]" << endl; + return false; + } + + cout << "TWIN: partner=" << m_peer_host << ":" << m_peer_port + << " local_prefix=" << m_local_prefix + << " priority=" << m_priority << endl; + + m_con.addStaticSRVRecord(0, 0, 0, m_peer_port, m_peer_host); + m_con.setReconnectMinTime(2000); + m_con.setReconnectMaxTime(30000); + m_con.connect(); + + return true; +} /* TwinLink::initialize */ + + +void TwinLink::acceptInboundConnection(Async::FramedTcpConnection* con, + const MsgTrunkHello& hello) +{ + if (m_inbound_con != nullptr) + { + cerr << "*** WARNING[TWIN]: Already have an inbound connection, " + "rejecting new one" << endl; + con->disconnect(); + return; + } + + m_inbound_con = con; + m_peer_priority = hello.priority(); + m_ib_hello_received = true; + m_ib_hb_tx_cnt = 0; + m_ib_hb_rx_cnt = 0; + m_heartbeat_timer.setEnable(true); + + // Wire inbound frame handler to our message dispatcher + con->frameReceived.connect(mem_fun(*this, &TwinLink::onFrameReceived)); + + m_peer_id_received = hello.id(); + cout << "TWIN: Accepted inbound from " << con->remoteHost() << ":" + << con->remotePort() << " peer='" << hello.id() + << "' priority=" << m_peer_priority << endl; + + // Send our hello back on the inbound connection + sendMsgOnInbound(MsgTrunkHello(m_peer_id_config, m_local_prefix, + m_priority, m_secret, + MsgTrunkHello::ROLE_TWIN)); +} /* TwinLink::acceptInboundConnection */ + + +void TwinLink::onLocalTalkerUpdated(uint32_t /*tg*/, + const std::string& /*callsign*/) +{ + // Phase C1 +} /* TwinLink::onLocalTalkerUpdated */ + + +void TwinLink::onLocalAudio(uint32_t /*tg*/, + const std::vector& /*audio*/) +{ + // Phase C1 +} /* TwinLink::onLocalAudio */ + + +void TwinLink::onLocalFlush(uint32_t /*tg*/) +{ + // Phase C1 +} /* TwinLink::onLocalFlush */ + + +void TwinLink::onExternalTrunkTalkerStart(uint32_t /*tg*/, + const std::string& /*peer_id*/, + const std::string& /*callsign*/) +{ + // Phase C2 +} /* TwinLink::onExternalTrunkTalkerStart */ + + +void TwinLink::onExternalTrunkTalkerStop(uint32_t /*tg*/, + const std::string& /*peer_id*/) +{ + // Phase C2 +} /* TwinLink::onExternalTrunkTalkerStop */ + + +bool TwinLink::isActive(void) const +{ + return (m_con.isConnected() && m_ob_hello_received) || + (m_inbound_con != nullptr && m_ib_hello_received); +} /* TwinLink::isActive */ + + +/**************************************************************************** + * + * TwinLink private methods + * + ****************************************************************************/ + +void TwinLink::onConnected(void) +{ + cout << "TWIN: outbound connected to " << m_peer_host << ":" + << m_peer_port << endl; + m_ob_hello_received = false; + m_ob_hb_tx_cnt = 0; + m_ob_hb_rx_cnt = 0; + m_heartbeat_timer.setEnable(true); + + sendMsgOnOutbound(MsgTrunkHello(m_peer_id_config, m_local_prefix, + m_priority, m_secret, + MsgTrunkHello::ROLE_TWIN)); +} /* TwinLink::onConnected */ + + +void TwinLink::onDisconnected(TcpConnection* /*con*/, + TcpConnection::DisconnectReason reason) +{ + cout << "TWIN: outbound disconnected: " + << TcpConnection::disconnectReasonStr(reason) << endl; + m_ob_hello_received = false; + m_ob_hb_tx_cnt = 0; + m_ob_hb_rx_cnt = 0; + + // Disable heartbeat timer if inbound is also down + if (m_inbound_con == nullptr) + { + m_heartbeat_timer.setEnable(false); + } + + // TcpPrioClient auto-reconnects — nothing else to do +} /* TwinLink::onDisconnected */ + + +void TwinLink::onFrameReceived(FramedTcpConnection* con, + std::vector& data) +{ + bool is_inbound = (con == m_inbound_con); + bool hello_done = is_inbound ? m_ib_hello_received : m_ob_hello_received; + + auto buf = reinterpret_cast(data.data()); + stringstream ss; + ss.write(buf, data.size()); + + ReflectorMsg header; + if (!header.unpack(ss)) + { + cerr << "*** ERROR[TWIN]: Failed to unpack frame header" << endl; + return; + } + + // Only allow hello and heartbeat before hello exchange completes + if (!hello_done && + header.type() != MsgTrunkHello::TYPE && + header.type() != MsgTrunkHeartbeat::TYPE) + { + cerr << "*** WARNING[TWIN]: Ignoring message type=" << header.type() + << " before hello" << endl; + return; + } + + // Reset RX heartbeat counter for the correct connection + if (is_inbound) + { + m_ib_hb_rx_cnt = 0; + } + else + { + m_ob_hb_rx_cnt = 0; + } + + switch (header.type()) + { + case MsgTrunkHello::TYPE: + handleMsgTrunkHello(ss, is_inbound); + break; + case MsgTrunkHeartbeat::TYPE: + handleMsgTrunkHeartbeat(); + break; + case MsgTrunkTalkerStart::TYPE: + handleMsgTrunkTalkerStart(ss); + break; + case MsgTrunkTalkerStop::TYPE: + handleMsgTrunkTalkerStop(ss); + break; + case MsgTrunkAudio::TYPE: + handleMsgTrunkAudio(ss); + break; + case MsgTrunkFlush::TYPE: + handleMsgTrunkFlush(ss); + break; + case MsgTwinExtTalkerStart::TYPE: + handleMsgTwinExtTalkerStart(ss); + break; + case MsgTwinExtTalkerStop::TYPE: + handleMsgTwinExtTalkerStop(ss); + break; + default: + // Unknown / not-yet-implemented types silently ignored for now + break; + } +} /* TwinLink::onFrameReceived */ + + +void TwinLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) +{ + // Inbound hellos are already handled by acceptInboundConnection. + // A duplicate arriving here means the peer re-sent — ignore it silently. + if (is_inbound) + { + return; + } + + // Hello on outbound = peer's reply to our outbound hello + MsgTrunkHello msg; + if (!msg.unpack(is)) + { + cerr << "*** ERROR[TWIN]: Failed to unpack MsgTrunkHello" << endl; + return; + } + + if (msg.role() != MsgTrunkHello::ROLE_TWIN) + { + cerr << "*** ERROR[TWIN]: peer sent role=" << int(msg.role()) + << " but we expect ROLE_TWIN" << endl; + m_con.disconnect(); + return; + } + + // Verify shared secret via HMAC + if (!msg.verify(m_secret)) + { + cerr << "*** ERROR[TWIN]: HMAC authentication failed — peer '" << msg.id() + << "' sent invalid secret" << endl; + m_con.disconnect(); + return; + } + + // Both partners must share the same LOCAL_PREFIX + if (msg.localPrefix() != m_local_prefix) + { + cerr << "*** ERROR[TWIN]: local_prefix mismatch: ours='" + << m_local_prefix << "' theirs='" << msg.localPrefix() << "'" + << endl; + m_con.disconnect(); + return; + } + + m_peer_priority = msg.priority(); + m_peer_id_received = msg.id(); + m_ob_hello_received = true; + + cout << "TWIN: hello from partner '" << msg.id() + << "' priority=" << m_peer_priority << " (authenticated)" << endl; +} /* TwinLink::handleMsgTrunkHello */ + + +void TwinLink::handleMsgTrunkTalkerStart(std::istream& /*is*/) +{ + // Phase C1 +} /* TwinLink::handleMsgTrunkTalkerStart */ + + +void TwinLink::handleMsgTrunkTalkerStop(std::istream& /*is*/) +{ + // Phase C1 +} /* TwinLink::handleMsgTrunkTalkerStop */ + + +void TwinLink::handleMsgTrunkAudio(std::istream& /*is*/) +{ + // Phase C1 +} /* TwinLink::handleMsgTrunkAudio */ + + +void TwinLink::handleMsgTrunkFlush(std::istream& /*is*/) +{ + // Phase C1 +} /* TwinLink::handleMsgTrunkFlush */ + + +void TwinLink::handleMsgTrunkHeartbeat(void) +{ + // RX counter already reset in onFrameReceived +} /* TwinLink::handleMsgTrunkHeartbeat */ + + +void TwinLink::handleMsgTwinExtTalkerStart(std::istream& /*is*/) +{ + // Phase C2 +} /* TwinLink::handleMsgTwinExtTalkerStart */ + + +void TwinLink::handleMsgTwinExtTalkerStop(std::istream& /*is*/) +{ + // Phase C2 +} /* TwinLink::handleMsgTwinExtTalkerStop */ + + +void TwinLink::heartbeatTick(Async::Timer* /*t*/) +{ + // Outbound heartbeat + if (m_con.isConnected()) + { + if (++m_ob_hb_tx_cnt >= TWIN_HB_TX_THRESHOLD) + { + sendMsgOnOutbound(MsgTrunkHeartbeat()); + m_ob_hb_tx_cnt = 0; + } + if (++m_ob_hb_rx_cnt >= TWIN_HB_RX_THRESHOLD) + { + cerr << "*** TWIN: outbound RX timeout, disconnecting" << endl; + m_con.disconnect(); + m_ob_hb_rx_cnt = 0; + } + } + + // Inbound heartbeat + if (m_inbound_con != nullptr && m_inbound_con->isConnected()) + { + if (++m_ib_hb_tx_cnt >= TWIN_HB_TX_THRESHOLD) + { + sendMsgOnInbound(MsgTrunkHeartbeat()); + m_ib_hb_tx_cnt = 0; + } + if (++m_ib_hb_rx_cnt >= TWIN_HB_RX_THRESHOLD) + { + cerr << "*** TWIN: inbound RX timeout, disconnecting" << endl; + m_inbound_con->disconnect(); + m_inbound_con = nullptr; + m_ib_hb_rx_cnt = 0; + m_ib_hello_received = false; + } + } + + // Disable timer when both connections are down + if (!m_con.isConnected() && m_inbound_con == nullptr) + { + m_heartbeat_timer.setEnable(false); + } +} /* TwinLink::heartbeatTick */ + + +bool TwinLink::sendMsg(const ReflectorMsg& msg) +{ + if (m_con.isConnected() && m_ob_hello_received) + { + sendMsgOnOutbound(msg); + return true; + } + if (m_inbound_con != nullptr && m_inbound_con->isConnected() + && m_ib_hello_received) + { + sendMsgOnInbound(msg); + return true; + } + return false; +} /* TwinLink::sendMsg */ + + +void TwinLink::sendMsgOnOutbound(const ReflectorMsg& msg) +{ + ostringstream ss; + ReflectorMsg header(msg.type()); + if (!header.pack(ss) || !msg.pack(ss)) + { + cerr << "*** ERROR[TWIN]: Failed to pack message type=" << msg.type() + << endl; + return; + } + m_ob_hb_tx_cnt = 0; + m_con.write(ss.str().data(), ss.str().size()); +} /* TwinLink::sendMsgOnOutbound */ + + +void TwinLink::sendMsgOnInbound(const ReflectorMsg& msg) +{ + if (m_inbound_con == nullptr) return; + ostringstream ss; + ReflectorMsg header(msg.type()); + if (!header.pack(ss) || !msg.pack(ss)) + { + cerr << "*** ERROR[TWIN]: Failed to pack message type=" << msg.type() + << endl; + return; + } + m_ib_hb_tx_cnt = 0; + m_inbound_con->write(ss.str().data(), ss.str().size()); +} /* TwinLink::sendMsgOnInbound */ + + +/* + * This file has not been truncated + */