From b268bfe595a6ebdba772a81aa4b21b9fac5db558 Mon Sep 17 00:00:00 2001 From: Audric Date: Thu, 21 May 2026 14:27:27 +0200 Subject: [PATCH] fix(trunk): guard inbound send paths against closed sockets; clean up on heartbeat timeout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A non-paired trunk link could abort the reflector (assert sock >= 0 in AsyncTcpConnection::write) when an inbound peer was timed out by the heartbeat. disconnect() closes the socket but does not emit the disconnected signal, so onInboundDisconnected never runs and m_inbound_con / m_ib_hello_received stay set. isInboundReady() then reports the dead link as ready, and the next send — e.g. a MsgPeerTgInterest scheduled by a client publishing its monitored-TG list — falls through to sendMsgOnInbound and writes to the closed socket. Reproduces the production abort seen on v1.3.12; TrunkLink is unchanged through v1.3.13. - sendMsgOnInbound / isInboundReady: bail when the inbound socket is closed. - inbound heartbeat timeout: drive the full cleanup (onInboundDisconnected + drop the dead connection from the reflector inbound map) so the link self-heals and /status is honest, instead of leaving a phantom inbound that makes acceptInboundConnection reject every reconnect until restart. - defense in depth: same isConnected() guard on sendMsgOnOutbound and SatelliteLink::sendMsg (currently unreachable, but never write to a closed socket regardless). - tests: test_46 (no crash on timeout + TG-interest send), test_47 (inbound recovers after a timeout). --- src/svxlink/reflector/Reflector.cpp | 6 ++ src/svxlink/reflector/Reflector.h | 6 ++ src/svxlink/reflector/SatelliteLink.cpp | 4 + src/svxlink/reflector/TrunkLink.cpp | 25 +++++- tests/test_trunk.py | 109 ++++++++++++++++++++++++ 5 files changed, 147 insertions(+), 3 deletions(-) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 2eefab9..c02bec5 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2482,6 +2482,12 @@ void Reflector::trunkClientConnected(Async::FramedTcpConnection* con) } /* Reflector::trunkClientConnected */ +void Reflector::forgetInboundTrunkConnection(Async::FramedTcpConnection* con) +{ + m_trunk_inbound_map.erase(con); +} /* Reflector::forgetInboundTrunkConnection */ + + void Reflector::trunkClientDisconnected(Async::FramedTcpConnection* con, Async::FramedTcpConnection::DisconnectReason reason) { diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 981bc79..3261dca 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -379,6 +379,12 @@ class Reflector : public sigc::trackable const std::string& host = "", uint16_t port = 0); + // Drop a no-longer-tracked inbound trunk connection from the inbound map. + // Used by TrunkLink when it proactively disconnects an inbound peer (e.g. + // a heartbeat timeout), since TcpConnection::disconnect() does not emit the + // disconnected signal that would otherwise trigger trunkClientDisconnected. + void forgetInboundTrunkConnection(Async::FramedTcpConnection* con); + // Triggered when a local client logs in/out or changes TG. Schedules // a debounced node-list emission to all trunk peers and to MQTT. void scheduleNodeListUpdate(void); diff --git a/src/svxlink/reflector/SatelliteLink.cpp b/src/svxlink/reflector/SatelliteLink.cpp index e2a0610..a88546e 100644 --- a/src/svxlink/reflector/SatelliteLink.cpp +++ b/src/svxlink/reflector/SatelliteLink.cpp @@ -453,6 +453,10 @@ void SatelliteLink::handleMsgPeerFlush(std::istream& is) void SatelliteLink::sendMsg(const ReflectorMsg& msg) { + // Defense in depth: never write to a closed socket — AsyncTcpConnection:: + // write() asserts sock >= 0. Mirrors the guard on the satellite (client) + // side (SatelliteClient gates every sender on isConnected()). + if (m_con == nullptr || !m_con->isConnected()) return; ostringstream ss; ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index d2dfadb..faad01d 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -1289,6 +1289,10 @@ void TrunkLink::sendMsg(const ReflectorMsg& msg) void TrunkLink::sendMsgOnOutbound(const ReflectorMsg& msg) { + // Defense in depth: callers gate on isOutboundReady() (which checks + // isConnected()), but never write to a closed socket regardless — + // AsyncTcpConnection::write() asserts sock >= 0. + if (!m_con.isConnected()) return; ostringstream ss; ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) @@ -1304,7 +1308,11 @@ void TrunkLink::sendMsgOnOutbound(const ReflectorMsg& msg) void TrunkLink::sendMsgOnInbound(const ReflectorMsg& msg) { - if (m_inbound_con == nullptr) return; + // Never write to a closed socket: AsyncTcpConnection::write() asserts + // sock >= 0. The pointer can outlive its socket when we disconnect() the + // inbound ourselves (heartbeat timeout) — disconnect() closes the fd + // without emitting the disconnected signal that clears m_inbound_con. + if (m_inbound_con == nullptr || !m_inbound_con->isConnected()) return; ostringstream ss; ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) @@ -1432,7 +1440,17 @@ void TrunkLink::heartbeatTick(Async::Timer* t) if (--m_ib_hb_rx_cnt == 0) { geulog::error("trunk", "[", m_section, "] Inbound heartbeat timeout"); - m_inbound_con->disconnect(); + // disconnect() closes the socket but does NOT emit the disconnected + // signal, so neither the trunk server's onDisconnected nor + // onInboundDisconnected runs on its own. Drive the cleanup ourselves so + // the link stops advertising a dead inbound (otherwise isInboundReady() + // lies and acceptInboundConnection rejects every reconnect), and drop + // the now-dead connection from the reflector's inbound map. + Async::FramedTcpConnection* dead = m_inbound_con; + dead->disconnect(); + m_reflector->forgetInboundTrunkConnection(dead); + onInboundDisconnected( + dead, Async::FramedTcpConnection::DR_ORDERED_DISCONNECT); } else if (m_ib_hb_rx_cnt <= 5) { @@ -1497,7 +1515,8 @@ bool TrunkLink::isInboundReady(void) const } return false; } - return m_inbound_con != nullptr && m_ib_hello_received; + return m_inbound_con != nullptr && m_ib_hello_received && + m_inbound_con->isConnected(); } /* TrunkLink::isInboundReady */ diff --git a/tests/test_trunk.py b/tests/test_trunk.py index 3c0e5c6..5e252a8 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -3119,6 +3119,115 @@ class TestTrunkIntegration(unittest.TestCase): a_client.close() c_client.close() + def test_46_inbound_heartbeat_timeout_no_crash(self): + """Regression: a non-paired trunk link whose inbound socket the + reflector closes on heartbeat timeout must not abort the process on + the next send (assert sock>=0 in AsyncTcpConnection::write). + + Mirrors the production incident. TRUNK_TEST's outbound leg points at + the unroutable 192.0.2.1, so only the inbound leg (this mock peer) is + ever up. The peer goes silent; ~15s later the reflector times out the + inbound RX heartbeat and calls m_inbound_con->disconnect(), which does + NOT emit the disconnected signal -> onInboundDisconnected never runs, + so m_inbound_con stays non-null and m_ib_hello_received stays true and + isInboundReady() lies. A client then publishes a monitored-TG set that + is shared toward TRUNK_TEST (prefix 9); the resulting MsgPeerTgInterest + send falls through to sendMsgOnInbound, which writes to the closed + socket -> SIGABRT. With no restart policy the container then exits, so + /status becomes unreachable. + """ + target = self.PRIMARY + + # 1. Inbound-only trunk peer on TRUNK_TEST (its outbound leg is down). + peer = TrunkPeer() + peer.connect(*_trunk(target)) + msg_type, _ = peer.handshake() # TRUNK_TEST, prefix 9, test_secret + self.assertEqual(msg_type, MSG_TRUNK_HELLO) + wait_until( + lambda: get_status(*_http(target))["trunks"]["TRUNK_TEST"] + .get("inbound_connected", False), + timeout=10.0, msg="TRUNK_TEST inbound did not connect") + + client = None + try: + # 2. Go silent (send no heartbeats, keep the socket open) so the + # reflector times out the inbound RX (HEARTBEAT_RX_CNT_RESET=15 + # @ 1s) and self-disconnects it. Do NOT peer.close() here: a + # clean close fires the disconnected signal and cleans up. + # The timeout log line has no /status equivalent on the buggy + # build (inbound_connected stays true), so gate on the log. + wait_until( + lambda: "Inbound heartbeat timeout" in + docker_logs_since(target, since="40s"), + timeout=30.0, interval=1.0, + msg="reflector did not time out the silent inbound trunk") + + # 3. Trigger: a client publishes a monitored-TG set shared toward + # TRUNK_TEST (prefix 9), scheduling a MsgPeerTgInterest on it. + shared_tg = int(TEST_PREFIX_FIRST + "123") # e.g. 9123, owned by peer + client = ClientPeer() + client.connect(HOST, T.mapped_client_port(target)) + client.authenticate() + client.monitor_tgs([shared_tg]) + + # 4. The 500ms TG-interest debounce fires the send. The reflector + # must still be alive afterwards (no assert abort / exit). + time.sleep(2.0) + try: + get_status(*_http(target)) + except Exception as e: + self.fail( + f"reflector '{target}' crashed after inbound heartbeat " + f"timeout + TG-interest send (write to closed socket): {e}") + finally: + if client is not None: + client.close() + peer.close() + + def test_47_inbound_recovers_after_heartbeat_timeout(self): + """Robustness: after the reflector times out and drops a silent inbound + trunk peer, the same peer must be able to reconnect its inbound leg. + + Guarding the send path alone stops the crash (test_46) but would leave + m_inbound_con dangling: /status would keep reporting a phantom inbound + and acceptInboundConnection (one inbound per non-paired link) would + reject every reconnect until the reflector restarts. The timeout path + must clear the inbound state so the link self-heals. + """ + target = self.PRIMARY + + # First inbound peer, then go silent until the reflector times it out. + peer1 = TrunkPeer() + peer1.connect(*_trunk(target)) + self.assertEqual(peer1.handshake()[0], MSG_TRUNK_HELLO) + wait_until( + lambda: get_status(*_http(target))["trunks"]["TRUNK_TEST"] + .get("inbound_connected", False), + timeout=10.0, msg="TRUNK_TEST inbound did not connect") + try: + # The reflector must clear the inbound from /status after timing it + # out — not leave a phantom that blocks reconnects. + wait_until( + lambda: not get_status(*_http(target))["trunks"]["TRUNK_TEST"] + .get("inbound_connected", True), + timeout=30.0, interval=0.5, + msg="reflector left a phantom inbound after heartbeat timeout") + finally: + peer1.close() + + # A fresh inbound from the same peer must now be accepted. + peer2 = TrunkPeer() + peer2.connect(*_trunk(target)) + try: + self.assertEqual(peer2.handshake()[0], MSG_TRUNK_HELLO) + wait_until( + lambda: get_status(*_http(target))["trunks"]["TRUNK_TEST"] + .get("inbound_connected", False), + timeout=10.0, + msg="TRUNK_TEST inbound did not recover after a timeout") + finally: + peer2.close() + # --------------------------------------------------------------------------- # Custom test runner with clean, readable output