From fc127e8dc20c5353dadfdc1a7d4e992a9dfea9df Mon Sep 17 00:00:00 2001 From: yo Date: Sun, 4 Oct 2026 22:04:57 +0200 Subject: [PATCH] fix(hbp): reset a MASTER's bridges only when its last peer is gone A failed login (REG_ACL / unregistered ID), a callsign mismatch or one hotspot closing down set _reset on the whole system. With many hotspots on one MASTER that dropped the next frame routed to it ("disallow transmission until reset cycle is complete", which also stops a plugin announcement as "slot taken"), and BRIDGERESET then set every leg of the system IDLE: calls the other hotspots were listening to stopped and their dynamic TGs were gone until someone keyed up again. Seen on 2131 at 20:00:15 UTC: an invalid login from ID 2131 cut the hourly announcement at packet 113/115, and the reset 5 s later stopped a TG 21472 over a connected hotspot was receiving (it arrived over OBP with 0.42 % loss and ran 5 s longer). 64 such resets in 24 h there. All paths now do what the peer timeout already did: restore the default OPTIONS and set _reset only when no peer is left. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JnjAx7G27d9q88j9PFLj11 --- .../twisted_adapters/udp_hbp.py | 44 +++--- tests/hbp/test_reset_only_without_peers.py | 149 ++++++++++++++++++ 2 files changed, 172 insertions(+), 21 deletions(-) create mode 100644 tests/hbp/test_reset_only_without_peers.py diff --git a/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py b/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py index 2289247..e578c74 100644 --- a/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py +++ b/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py @@ -1246,19 +1246,28 @@ class HBPProtocol(DatagramProtocol): ) self.transport.write(b"".join([MSTCL, peer]), self._peers[peer]["SOCKADDR"]) self._remove_peer(peer) - if not self._peers: - sys_cfg = self._CONFIG["SYSTEMS"][self._system] - if "OPTIONS" in sys_cfg: - if "_default_options" in sys_cfg: - logger.info("(%s) Setting default Options: %s", self._system, sys_cfg["_default_options"]) - sys_cfg["OPTIONS"] = sys_cfg["_default_options"] - else: - del sys_cfg["OPTIONS"] - logger.info("(%s) Deleting HBP Options", self._system) - sys_cfg["_reset"] = True + self._reset_if_no_peers() if remove_list: self._push_config_to_monitor() + def _reset_if_no_peers(self) -> None: + """Last peer gone: restore default OPTIONS and let BRIDGERESET clear this system's legs. + + The legs and OPTIONS belong to every hotspot on this MASTER, so a failed login or one + peer leaving must not reset them while others are still connected. + """ + if self._peers: + return + sys_cfg = self._CONFIG.setdefault("SYSTEMS", {}).setdefault(self._system, {}) + if "OPTIONS" in sys_cfg: + if "_default_options" in sys_cfg: + logger.info("(%s) Setting default Options: %s", self._system, sys_cfg["_default_options"]) + sys_cfg["OPTIONS"] = sys_cfg["_default_options"] + else: + del sys_cfg["OPTIONS"] + logger.info("(%s) Deleting HBP Options", self._system) + sys_cfg["_reset"] = True + def _on_peer_disconnected(self, peer_id: bytes) -> None: """Drop stale slot STATUS when a hotspot leaves; keep persisted UA state in sys_cfg.""" peer = self._peers.get(peer_id) @@ -1676,7 +1685,7 @@ class HBPProtocol(DatagramProtocol): if self._config.get("PROXY_CONTROL"): self.proxy_IPBlackList(_peer_id, _sockaddr) logger.warning("(%s) Invalid Login from %s Radio ID: %s Denied by Registation ACL or not registered ID", self._system, _sockaddr[0], int_id(_peer_id)) - if self._CONFIG.get("SYSTEMS", {}).get(self._system): + if self._CONFIG.get("SYSTEMS", {}).get(self._system) and not self._peers: self._CONFIG["SYSTEMS"][self._system]["_reset"] = True else: self.transport.write(b"".join([MSTNAK, _peer_id]), _sockaddr) @@ -1727,15 +1736,7 @@ class HBPProtocol(DatagramProtocol): logger.info("(%s) Peer is closing down: %s (%s)", self._system, _rptc_field_str(self._peers[_peer_id]["CALLSIGN"]), int_id(_peer_id)) self.transport.write(b"".join([MSTNAK, _peer_id]), _sockaddr) self._remove_peer(_peer_id) - sys_cfg = self._CONFIG.get("SYSTEMS", {}).get(self._system, {}) - if "OPTIONS" in sys_cfg: - if "_default_options" in sys_cfg: - sys_cfg["OPTIONS"] = sys_cfg["_default_options"] - logger.info("(%s) Setting default Options: %s", self._system, sys_cfg["_default_options"]) - else: - logger.info("(%s) Deleting HBP Options", self._system) - del sys_cfg["OPTIONS"] - sys_cfg["_reset"] = True + self._reset_if_no_peers() self._push_config_to_monitor() else: _peer_id = _data[4:8] @@ -1769,7 +1770,8 @@ class HBPProtocol(DatagramProtocol): if self._config.get("PROXY_CONTROL"): self.proxy_IPBlackList(_peer_id, _sockaddr) self.transport.write(b"".join([MSTNAK, _peer_id]), _sockaddr) - self._CONFIG.setdefault("SYSTEMS", {}).setdefault(self._system, {})["_reset"] = True + if not self._peers: + self._CONFIG.setdefault("SYSTEMS", {}).setdefault(self._system, {})["_reset"] = True logger.info("(%s) Callsign does not match subscriber database: ID: %s, Sent Call: %s, DB call %s", self._system, int_id(_peer_id), _sent_call, self.validate_id(_peer_id)) else: self.send_peer(_peer_id, b"".join([RPTACK, _peer_id])) diff --git a/tests/hbp/test_reset_only_without_peers.py b/tests/hbp/test_reset_only_without_peers.py new file mode 100644 index 0000000..c4e16d4 --- /dev/null +++ b/tests/hbp/test_reset_only_without_peers.py @@ -0,0 +1,149 @@ +# ADN DMR Peer Server - tests hbp bridge reset only without peers +# +# Copyright (C) 2026 Rodrigo Pérez, CE5RPY +# +############################################################################### +# 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 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +############################################################################### + +"""BRIDGERESET clears every leg of a MASTER: only when its last peer is gone. + +A failed login, a callsign mismatch or one hotspot closing down used to set ``_reset`` on +the whole system, so the next frame was dropped ("disallow transmission") and every TG +the other hotspots were listening to went IDLE, cutting their calls and announcements. +""" + +from __future__ import annotations + +import time + +from adn_server.domain.value_objects import bytes_4 +from adn_server.infrastructure.config_normalizer import ensure_system_runtime_config +from adn_server.infrastructure.hbp_constants import MSTNAK, RPTC, RPTCL, RPTK, RPTL +from adn_server.infrastructure.twisted_adapters.udp_hbp import ( + HBPProtocol, + _calc_hash, + _get_passphrase_bytes, +) + +_LISTENER = bytes_4(213003591) +_LISTENER_ADDR = ("192.168.1.10", 62031) +_OTHER = bytes_4(1234567) +_OTHER_ADDR = ("192.168.1.50", 62031) +_DENIED = bytes_4(2131) + + +class _Transport: + def __init__(self) -> None: + self.sent: list[tuple[bytes, tuple[str, int]]] = [] + + def write(self, data: bytes, addr: tuple[str, int]) -> None: + self.sent.append((data, addr)) + + +class _Router: + def acl_check(self, peer_id: bytes, acl: object) -> bool: + return peer_id != _DENIED + + +def _master() -> tuple[HBPProtocol, _Transport, dict]: + config = { + "GLOBAL": {"PING_TIME": 10, "MAX_MISSED": 3, "USE_ACL": False}, + "SYSTEMS": { + "SYSTEM": { + "MODE": "MASTER", + "ENABLED": True, + "MAX_PEERS": 8, + "PASSPHRASE": b"test-passphrase", + "OPTIONS": "TS2=3340;", + "_default_options": "TS2=9990;", + } + }, + } + ensure_system_runtime_config(config) + hbp = HBPProtocol("SYSTEM", config, router=_Router()) # type: ignore[arg-type] + transport = _Transport() + hbp.transport = transport # type: ignore[assignment] + return hbp, transport, config["SYSTEMS"]["SYSTEM"] + + +def _connect(hbp: HBPProtocol, peer: bytes, addr: tuple[str, int], callsign: bytes = b"C31AG ") -> None: + hbp.datagramReceived(RPTL + peer, addr) + salt = bytes_4(hbp._peers[peer]["SALT"]) + hbp.datagramReceived(RPTK + peer + _calc_hash(salt, _get_passphrase_bytes(hbp._config)), addr) + hbp.datagramReceived(RPTC + peer + callsign + b"\x00" * 85 + b"4", addr) + + +def test_failed_login_does_not_reset_a_master_with_peers() -> None: + hbp, transport, sys_cfg = _master() + _connect(hbp, _LISTENER, _LISTENER_ADDR) + assert hbp._peers[_LISTENER]["CONNECTION"] == "YES" + transport.sent.clear() + + hbp.datagramReceived(RPTL + _DENIED, _OTHER_ADDR) + + assert transport.sent and transport.sent[0][0].startswith(MSTNAK) + assert not sys_cfg.get("_reset"), "the listener's TGs must stay up" + assert sys_cfg["OPTIONS"] == "TS2=3340;" + + +def test_failed_login_still_resets_an_empty_master() -> None: + hbp, _transport, sys_cfg = _master() + hbp.datagramReceived(RPTL + _DENIED, _OTHER_ADDR) + assert sys_cfg.get("_reset") is True + + +def test_callsign_mismatch_does_not_reset_a_master_with_peers() -> None: + hbp, transport, sys_cfg = _master() + hbp._config["ALLOW_UNREG_ID"] = False + hbp._CONFIG["_SUB_IDS"] = {2130035: "C31AG", 213003591: "C31AG", 1234567: "CE1TEST"} + _connect(hbp, _LISTENER, _LISTENER_ADDR) + assert hbp._peers[_LISTENER]["CONNECTION"] == "YES" + + _connect(hbp, _OTHER, _OTHER_ADDR, callsign=b"WRONG ") + + assert _OTHER not in hbp._peers + assert not sys_cfg.get("_reset") + + +def test_one_peer_closing_keeps_the_others_options_and_legs() -> None: + hbp, transport, sys_cfg = _master() + _connect(hbp, _LISTENER, _LISTENER_ADDR) + _connect(hbp, _OTHER, _OTHER_ADDR) + assert hbp._peers[_OTHER]["CONNECTION"] == "YES" + + hbp.datagramReceived(RPTCL + _OTHER, _OTHER_ADDR) + + assert _OTHER not in hbp._peers and _LISTENER in hbp._peers + assert not sys_cfg.get("_reset") + assert sys_cfg["OPTIONS"] == "TS2=3340;" + + # the last one leaving resets as before, back to the default OPTIONS + hbp.datagramReceived(RPTCL + _LISTENER, _LISTENER_ADDR) + assert sys_cfg.get("_reset") is True + assert sys_cfg["OPTIONS"] == "TS2=9990;" + + +def test_one_peer_timing_out_keeps_the_others_legs() -> None: + hbp, _transport, sys_cfg = _master() + _connect(hbp, _LISTENER, _LISTENER_ADDR) + _connect(hbp, _OTHER, _OTHER_ADDR) + hbp._peers[_OTHER]["LAST_PING"] = 0 + hbp._peers[_LISTENER]["LAST_PING"] = time.time() + + hbp._master_maintenance_loop() + + assert _OTHER not in hbp._peers + assert not sys_cfg.get("_reset")