From 13abcb5b8da2264b06c359d38f9bfb66a1db0392 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 8 Nov 2026 17:09:32 +0000 Subject: [PATCH] Protect unit data and grant bounded Gateway slot admission --- bridge_master.py | 108 ++++++++++++++- config.py | 1 + docs/release-notes-unreleased.md | 10 ++ docs/unit-data-hold.md | 65 +++++++++ hblink.py | 23 ++++ tests/test_gateway_admission.py | 140 ++++++++++++++++++++ tests/test_unit_data_hold.py | 219 +++++++++++++++++++++++++++++++ 7 files changed, 565 insertions(+), 1 deletion(-) create mode 100644 docs/unit-data-hold.md create mode 100644 tests/test_gateway_admission.py create mode 100644 tests/test_unit_data_hold.py diff --git a/bridge_master.py b/bridge_master.py index a56f19e..f16b4c7 100644 --- a/bridge_master.py +++ b/bridge_master.py @@ -1300,6 +1300,28 @@ def stream_trimmer_loop(): else: logger.debug('(%s) Attemped to remove OpenBridge Stream ID %s not in the Stream ID list: %s', system, int_id(stream_id), [id for id in systems[system].STATUS]) +def unitDataHold(_system, _slot, pkt_time): + if not CONFIG['SYSTEMS'][_system].get('UNIT_DATA_HOLD', True): + return None + hold = _slot.get('TX_UNIT_DATA_HOLD') + return hold if hold is not None and pkt_time < hold[2] else None + +def unitDataAvailable(_system, _slot, _rf_src, _dst_id, pkt_time, ingress=None): + if not CONFIG['SYSTEMS'][_system].get('UNIT_DATA_HOLD', True): + return True + hold = unitDataHold(_system, _slot, pkt_time) + if hold is not None: + return (hold[:2] == (_rf_src, _dst_id) + and _slot.get('TX_UNIT_DATA_LINK', ingress) == ingress) + return not _slot.get('TX_PROMPT_ACTIVE', False) + +def recordUnitData(_system, _slot, source, destination, now): + if not CONFIG['SYSTEMS'][_system].get('UNIT_DATA_HOLD', True): + return + if unitDataHold(_system, _slot, now) is None: + _slot.pop('TX_UNIT_DATA_LINK', None) + _slot['TX_UNIT_DATA_HOLD'] = (source, destination, now + 5) + def _beginGeneratedVoice(_slot): _token = object() _slot['TX_PROMPT_ACTIVE'] = True @@ -1323,6 +1345,9 @@ def sendVoicePacket(self,pkt,_source_id,_dest_id,_slot): system = self._system _stream_id = pkt[16:20] _pkt_time = time() + if unitDataHold(system, _slot, _pkt_time): + _cancelGeneratedVoice(_slot) + return if _slot.get('TX_PROMPT_CANCEL', False): return if _stream_id not in systems[system].STATUS: @@ -1918,6 +1943,65 @@ def options_config(): class routerOBP(OPENBRIDGE): + def admission_requested(self, request_id, source_id, destination_id): + """Atomically check/hold a local slot in the packet reactor context.""" + now = time() + cache = getattr(self, '_admission_requests', {}) + self._admission_requests = cache + for key, entry in list(cache.items()): + if now >= entry[4]: + del cache[key] + if request_id in cache: + source, destination, result, deadline, _ = cache[request_id] + if (source, destination) != (source_id, destination_id): + return 3, 0 + return result, max(0, min(500, int((deadline - now) * 1000))) if result == 0 else 0 + if len(cache) >= 256: + return 1, 0 + + result, deadline = 3, now + allowed = dataGatewayEnabled() and self._system == 'DATA-GATEWAY' and 'STUN' not in CONFIG + for policy in (CONFIG['GLOBAL'], self._config): + if policy.get('USE_ACL', False): + allowed = allowed and acl_check(source_id, policy['SUB_ACL']) and acl_check(destination_id, policy['TG1_ACL']) + if allowed: + target = subMapTarget(destination_id) + if not target: + # Match the existing hotspot-ID fallback, but never reserve ambiguously. + matches = [(name, 2, now) for name, config in CONFIG['SYSTEMS'].items() + if config['MODE'] == 'MASTER' and config['ENABLED'] + and any(str(int_id(peer))[:7] == str(int_id(destination_id))[:7] + for peer in config['PEERS'])] + target = matches[0] if len(matches) == 1 else None + if not target: + result = 2 + else: + system, slot, _ = target + config = CONFIG['SYSTEMS'][system] + status = systems[system].STATUS.get(slot) if config['MODE'] == 'MASTER' else None + if status is None or not config['ENABLED'] or not config['PEERS']: + result = 2 + elif not config.get('UNIT_DATA_HOLD', True): + result = 3 + elif (status['RX_TYPE'] != HBPF_SLT_VTERM or status['TX_TYPE'] != HBPF_SLT_VTERM + or now - status['TX_TIME'] <= config['GROUP_HANGTIME'] + or status.get('TX_PROMPT_ACTIVE', False)): + result = 1 + else: + hold = unitDataHold(system, status, now) + if hold is not None: + if (hold[:2] == (source_id, destination_id) + and status.get('TX_UNIT_DATA_LINK') == self._system): + result, deadline = 0, min(now + .5, hold[2]) + else: + result = 1 + else: + result, deadline = 0, now + .5 + status['TX_UNIT_DATA_HOLD'] = (source_id, destination_id, deadline) + status['TX_UNIT_DATA_LINK'] = self._system + cache[request_id] = (source_id, destination_id, result, deadline, now + 30) + return result, max(0, min(500, int(round((deadline - now) * 1000)))) if result == 0 else 0 + def __init__(self, _name, _config, _report): OPENBRIDGE.__init__(self, _name, _config, _report) @@ -2053,6 +2137,11 @@ class routerOBP(OPENBRIDGE): # From the same group as the last TX to this HBSystem, but from a different subscriber, and it has been less than stream timeout # The "continue" at the end of each means the next iteration of the for loop that tests for matching rules # + if unitDataHold(_target['SYSTEM'], _target_status[_target['TS']], pkt_time): + if not self.STATUS[_stream_id]['CONTENTION']: + self.STATUS[_stream_id]['CONTENTION'] = True + logger.info('(%s) Call not routed, target in unit-data hold: %s TS: %s', self._system, _target['SYSTEM'], _target['TS']) + continue if ((_target['TGID'] != _target_status[_target['TS']]['RX_TGID']) and ((pkt_time - _target_status[_target['TS']]['RX_TIME']) < _target_system['GROUP_HANGTIME'])): if self.STATUS[_stream_id]['CONTENTION'] == False: self.STATUS[_stream_id]['CONTENTION'] = True @@ -2142,10 +2231,15 @@ class routerOBP(OPENBRIDGE): def sendDataToHBP(self,_d_system,_d_slot,_dst_id,_tmp_bits,_data,dmrpkt,_rf_src,_stream_id,_peer_id): _int_dst_id = int_id(_dst_id) + _dst_slot = systems[_d_system].STATUS[_d_slot] + if not unitDataAvailable(_d_system, _dst_slot, _rf_src, _dst_id, time(), self._system): + logger.debug('(%s) UNIT Data not bridged - data hold or prompt active: %s TS: %s', self._system, _d_system, _d_slot) + return #Assemble transmit HBP packet header _tmp_data = b''.join([_data[:15], _tmp_bits.to_bytes(1, 'big'), _data[16:20]]) _tmp_data = b''.join([_tmp_data, dmrpkt]) systems[_d_system].send_system(_tmp_data) + recordUnitData(_d_system, _dst_slot, _rf_src, _dst_id, time()) logger.debug('(%s) UNIT Data Bridged to HBP on slot %s: %s DST_ID: %s',self._system,_d_slot,_d_system,_int_dst_id) if CONFIG['REPORTS']['REPORT']: systems[_d_system]._report.send_bridgeEvent('UNIT DATA,DATA,TX,{},{},{},{},{},{}'.format(_d_system, int_id(_stream_id), int_id(_peer_id), int_id(_rf_src), _d_slot, _int_dst_id).encode(encoding='utf-8', errors='ignore')) @@ -2765,6 +2859,10 @@ class routerHBP(HBSYSTEM): # From the same group as the last TX to this HBSystem, but from a different subscriber, and it has been less than stream timeout # The "continue" at the end of each means the next iteration of the for loop that tests for matching rules # + if unitDataHold(_target['SYSTEM'], _target_status[_target['TS']], pkt_time): + if _frame_type == HBPF_DATA_SYNC and _dtype_vseq == HBPF_SLT_VHEAD and self.STATUS[_slot]['RX_STREAM_ID'] != _stream_id: + logger.info('(%s) Call not routed, target in unit-data hold: %s TS: %s', self._system, _target['SYSTEM'], _target['TS']) + continue if ((_target['TGID'] != _target_status[_target['TS']]['RX_TGID']) and ((pkt_time - _target_status[_target['TS']]['RX_TIME']) < _target_system['GROUP_HANGTIME'])): if _frame_type == HBPF_DATA_SYNC and _dtype_vseq == HBPF_SLT_VHEAD and self.STATUS[_slot]['RX_STREAM_ID'] != _stream_id: logger.info('(%s) Call not routed to TGID %s, target active or in group hangtime: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(_target['TGID']), _target['SYSTEM'], _target['TS'], int_id(_target_status[_target['TS']]['RX_TGID'])) @@ -2783,7 +2881,10 @@ class routerHBP(HBSYSTEM): continue # Is this a new call stream? - if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']): + # A data hold may have suppressed this target's call start. + if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']) or ( + _target_system.get('UNIT_DATA_HOLD', True) + and _target_status[_target['TS']]['TX_STREAM_ID'] != _stream_id): if not _data_control: _cancelGeneratedVoice(_target_status[_target['TS']]) # Record the DST TGID and Stream ID @@ -2853,9 +2954,14 @@ class routerHBP(HBSYSTEM): def sendDataToHBP(self,_d_system,_d_slot,_dst_id,_tmp_bits,_data,dmrpkt,_rf_src,_stream_id,_peer_id): #Assemble transmit HBP packet header _int_dst_id = int_id(_dst_id) + _dst_slot = systems[_d_system].STATUS[_d_slot] + if not unitDataAvailable(_d_system, _dst_slot, _rf_src, _dst_id, time(), self._system): + logger.debug('(%s) UNIT Data not bridged - data hold or prompt active: %s TS: %s', self._system, _d_system, _d_slot) + return _tmp_data = b''.join([_data[:15], _tmp_bits.to_bytes(1, 'big'), _data[16:20]]) _tmp_data = b''.join([_tmp_data, dmrpkt]) systems[_d_system].send_system(_tmp_data,None) + recordUnitData(_d_system, _dst_slot, _rf_src, _dst_id, time()) logger.debug('(%s) UNIT Data Bridged to HBP on slot %s: %s DST_ID: %s',self._system,_d_slot,_d_system,_int_dst_id) if CONFIG['REPORTS']['REPORT']: systems[_d_system]._report.send_bridgeEvent('UNIT DATA,DATA,TX,{},{},{},{},{},{}'.format(_d_system, int_id(_stream_id), int_id(_peer_id), int_id(_rf_src), _d_slot, _int_dst_id).encode(encoding='utf-8', errors='ignore')) diff --git a/config.py b/config.py index b8785be..81c12e4 100755 --- a/config.py +++ b/config.py @@ -366,6 +366,7 @@ def build_config(_config_file): 'PORT': config.getint(section, 'PORT', fallback=54000), 'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE', fallback=''), 'utf-8'), 'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME',fallback=5), + 'UNIT_DATA_HOLD': config.getboolean(section, 'UNIT_DATA_HOLD', fallback=True), 'USE_ACL': config.getboolean(section, 'USE_ACL', fallback=False), 'REG_ACL': config.get(section, 'REG_ACL', fallback=''), 'SUB_ACL': config.get(section, 'SUB_ACL', fallback=''), diff --git a/docs/release-notes-unreleased.md b/docs/release-notes-unreleased.md index 062e9a2..c95749c 100644 --- a/docs/release-notes-unreleased.md +++ b/docs/release-notes-unreleased.md @@ -1,5 +1,15 @@ # Unreleased Changes +- Added link-local `BCRQ`/`BCTS` request-to-send controls on the dedicated + DATA-GATEWAY FBP5 relationship. A successful request holds a local slot for + 500ms until matching data starts. Legacy controls, DMR bytes and ordinary + unreserved SMS/data forwarding are unchanged. See [limitations](unit-data-hold.md). +- Added per-master `UNIT_DATA_HOLD` (default `True`, including existing + configurations that omit it; set `False` to retain prior behaviour). Admitted + unit data holds its outbound HBP slot for the same source/destination pair until five + seconds of inactivity, preventing competing network voice/data and generated + prompts from interrupting it. Existing voice-start admission is preserved. + See [configuration and limitations](unit-data-hold.md). - Added `/api/v1/peer/dial` for dashboard Self Service using the connected hotspot/repeater's OPTIONS key. Existing backend Dial authentication and routing, RF-busy, timer and voice-announcement behavior are unchanged. diff --git a/docs/unit-data-hold.md b/docs/unit-data-hold.md new file mode 100644 index 0000000..7d8ec7c --- /dev/null +++ b/docs/unit-data-hold.md @@ -0,0 +1,65 @@ +# Unit-Data Slot Hold + +Unit-data slot protection is enabled by default for every `MODE: MASTER` +section. It can also be set explicitly in the FreeDMR configuration: + +```ini +UNIT_DATA_HOLD: True +``` + +Existing configurations that omit this setting enable the hold on upgrade. +Set `UNIT_DATA_HOLD: False` to restore the previous admission behaviour. +The setting applies independently to both slots of that master, not to the +whole server or mesh. In a worker deployment, configure the receiving HBP +worker's master section. + +Existing voice activity and voice hangtime checks still determine whether unit +data may start. An admitted outbound unit-data burst, including a preamble, +holds its destination slot for its ordered source/destination DMR-ID pair for +five seconds. Each further admitted burst for that pair refreshes the hold. +Stream IDs do not identify ownership, and packet contents are not reassembled +or changed by the hold. This applies to unit data generally, including SMS, +not exclusively to IP service 5005. + +During the hold, competing network voice, generated prompts/beacons and unit +data for other pairs are suppressed on that slot. An already-active generated +prompt prevents a new data hold. Suppressed prompts are cancelled, not queued +for replay. After five seconds without admitted data, normal admission resumes +without waiting for a background cleanup task. Continuous data can retain the +slot indefinitely; there is no fairness or packet-count limit in this version. + +This is server-side outbound protection, not an RF reservation or a +bidirectional session lock. It does not stop an RF station transmitting, measure +modem buffering, queue busy-dropped packets, add +retries, or contain IP traffic to the local server. The hold expires from the +last network submission, not measured RF completion. Disable it where these +trade-offs are inappropriate for the particular access master. + +## Gateway Request To Send + +The enabled, authenticated `DATA-GATEWAY` FBP5 relationship can request a +provisional hold using `BCRQ`; `BCTS` replies with granted, busy, no local route +or denied. Ordinary mesh relationships cannot request holds. The new controls +use a 16-byte keyed BLAKE2b tag; existing FBCP controls are unchanged. + +The worker resolves the local destination through its subscriber map or an +unambiguous connected-hotspot match. A grant reserves that slot for 500ms for +the requesting relationship and ordered source/destination pair. The first +matching admitted burst promotes it to the five-second hold above. With no +packet, it expires automatically. Existing voice/hangtime and prompt checks +still apply, and `UNIT_DATA_HOLD: False` denies requests for that master. + +Duplicate request IDs return the original result and remaining window, not a +renewed hold. Changed addresses under the same ID are denied. New request IDs +also cannot prolong an unused hold. The cache holds at most 256 requests for +30 seconds per Gateway relationship. It is a bounded duplicate cache, not +cryptographic replay protection across that window or a process restart. + +The sender must correlate the reply, allow for round-trip latency, and start +within its remaining budget. A grant is not an RF lock or delivery receipt: +new RF activity or a changed route can still prevent admission. There is no +cancel, packet-count fairness, new DMR field or mesh-wide reservation. Ordinary +unreserved SMS/data remains supported. The experimental Gateway IP sender uses +the new exchange. Gateway SMS can opt in with `FREEDMR_GATEWAY_SMS_ADMISSION=true`; +its default remains off for compatibility with older workers. Opt-in clients +must understand the Gateway API's `queued` state before transport submission. diff --git a/hblink.py b/hblink.py index f384f3d..e9cf55f 100755 --- a/hblink.py +++ b/hblink.py @@ -263,9 +263,32 @@ class OPENBRIDGE(DatagramProtocol): pass #print(int_id(_peer_id), int_id(_rf_src), int_id(_dst_id), int_id(_seq), _slot, _call_type, _frame_type, repr(_dtype_vseq), int_id(_stream_id)) + def admission_requested(self, request_id, source_id, destination_id): + """Routing subclasses may implement the dedicated Gateway control.""" + return 3, 0 + def datagramReceived(self, _packet, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! #logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_packet)) + + if _packet[:4] == b'BCRQ': + if (self._system != 'DATA-GATEWAY' + or not self._CONFIG['GLOBAL'].get('DATA_GATEWAY', False) + or not self._config['ENABLED'] or not self._config['ENHANCED_OBP'] + or self._config['VER'] != 5 + or _sockaddr != self._config['TARGET_SOCK'] or len(_packet) != 30): + return + digest = blake2b(_packet[:14], key=self._config['PASSPHRASE'], digest_size=16).digest() + if not compare_digest(_packet[14:], digest): + return + source, destination = _packet[8:11], _packet[11:14] + if not int_id(source) or not int_id(destination): + return + result, window = self.admission_requested(int_id(_packet[4:8]), source, destination) + response = b'BCTS' + _packet[4:8] + bytes((result,)) + window.to_bytes(2, 'big') + response += blake2b(response, key=self._config['PASSPHRASE'], digest_size=16).digest() + self.transport.write(response, _sockaddr) + return if _packet[:3] == DMR: # DMRData -- encapsulated DMR data frame if _packet[:4] == DMRD: diff --git a/tests/test_gateway_admission.py b/tests/test_gateway_admission.py new file mode 100644 index 0000000..c99a019 --- /dev/null +++ b/tests/test_gateway_admission.py @@ -0,0 +1,140 @@ +"""Dedicated-link admission controls through real receive/routing handlers.""" +from hashlib import blake2b +from dataclasses import replace +import unittest + +from tests.harness.deterministic import ( + DeterministicScenario, PacketSpec, minimal_config, add_openbridge_system, + active_bridge, bytes_3, HBPF_DATA_SYNC, HBPF_VOICE, +) + + +class GatewayAdmissionTests(unittest.TestCase): + def scenario(self, slot=2): + config = minimal_config(("MASTER-A", "MASTER-B")) + config['GLOBAL']['DATA_GATEWAY'] = True + for name in ('DATA-GATEWAY', 'OBP-1'): + add_openbridge_system(config, name, network_id=3001) + config['SYSTEMS'][name]['ENHANCED_OBP'] = True + return DeterministicScenario(config=config, bridges=active_bridge( + '91', 91, (('MASTER-A', slot), ('MASTER-B', slot), ('OBP-1', 1)))) + + def prepare(self, s, slot=2): + s.clock.advance(10) + s.register_peer('MASTER-B', 123456701) + s.bm.SUB_MAP[bytes_3(1234567)] = ('MASTER-B', slot, s.clock.time()) + + def wire(self, s, request=1, source=5005, destination=1234567, system='DATA-GATEWAY'): + body = b'BCRQ' + request.to_bytes(4, 'big') + bytes_3(source) + bytes_3(destination) + return body + blake2b(body, key=s.config['SYSTEMS'][system]['PASSPHRASE'], digest_size=16).digest() + + def request(self, s, **kwargs): + config = s.config['SYSTEMS']['DATA-GATEWAY'] + s.inject_datagram('DATA-GATEWAY', self.wire(s, **kwargs), config['TARGET_SOCK']) + packet, address = s.transports['DATA-GATEWAY'].writes[-1] + self.assertEqual(address, config['TARGET_SOCK']) + self.assertEqual(len(packet), 27) + self.assertEqual(packet[:4], b'BCTS') + self.assertEqual(packet[-16:], blake2b(packet[:-16], key=config['PASSPHRASE'], digest_size=16).digest()) + return packet[8], int.from_bytes(packet[9:11], 'big') + + def test_grant_holds_voice_and_expires_without_a_packet(self): + for slot in (1, 2): + with self.subTest(slot=slot), self.scenario(slot) as s: + self.prepare(s, slot) + self.assertEqual(self.request(s), (0, 500)) + voice = PacketSpec(rf_src=3120001, dst_id=91, slot=1, + stream_id=100, frame_type=HBPF_VOICE, dtype_vseq=1) + s.inject_obp('OBP-1', voice) + self.assertFalse(s.capture.for_system('MASTER-B')) + s.clock.advance(.5) + s.inject_obp('OBP-1', replace(voice, seq=2, stream_id=101)) + self.assertEqual(len(s.capture.for_system('MASTER-B')), 1) + + def test_duplicate_and_new_requests_cannot_renew_unused_hold(self): + with self.scenario() as s: + self.prepare(s) + self.assertEqual(self.request(s), (0, 500)) + slot = s.systems['MASTER-B'].STATUS[2] + expiry = slot['TX_UNIT_DATA_HOLD'][2] + s.clock.advance(.25) + self.assertEqual(self.request(s), (0, 250)) + self.assertEqual(self.request(s, request=2), (0, 250)) + self.assertEqual(slot['TX_UNIT_DATA_HOLD'][2], expiry) + self.assertEqual(self.request(s, source=5006), (3, 0)) + self.assertEqual(self.request(s, request=3, source=5006), (1, 0)) + s.clock.advance(.25) + self.assertEqual(self.request(s), (0, 0)) + self.assertEqual(self.request(s, request=4), (0, 500)) + + def test_matching_data_promotes_hold_but_other_relationship_cannot(self): + with self.scenario() as s: + self.prepare(s) + self.request(s) + packet = PacketSpec(rf_src=5005, dst_id=1234567, slot=1, + call_type='unit', frame_type=HBPF_DATA_SYNC, dtype_vseq=6) + s.inject_obp('OBP-1', packet) + self.assertFalse(s.capture.for_system('MASTER-B')) + s.clock.advance(.2) + s.inject_obp('DATA-GATEWAY', replace(packet, seq=2, stream_id=102)) + self.assertEqual(len(s.capture.for_system('MASTER-B')), 1) + slot = s.systems['MASTER-B'].STATUS[2] + self.assertAlmostEqual(slot['TX_UNIT_DATA_HOLD'][2], s.clock.time() + 5) + s.inject_obp('OBP-1', replace(packet, seq=3, stream_id=103)) + self.assertEqual(len(s.capture.for_system('MASTER-B')), 1) + + def test_busy_disabled_denied_and_missing_routes(self): + for reason in ('rx', 'tx', 'hangtime', 'prompt', 'disabled', 'acl', 'route', 'peer'): + with self.subTest(reason=reason), self.scenario() as s: + self.prepare(s) + status = s.systems['MASTER-B'].STATUS[2] + expected = 1 + if reason == 'rx': status['RX_TYPE'] = 1 + if reason == 'tx': status['TX_TYPE'] = 1 + if reason == 'hangtime': status['TX_TIME'] = s.clock.time() + if reason == 'prompt': status['TX_PROMPT_ACTIVE'] = True + if reason == 'disabled': + s.config['SYSTEMS']['MASTER-B']['UNIT_DATA_HOLD'] = False + expected = 3 + if reason == 'acl': + s.config['GLOBAL']['USE_ACL'] = True + s.config['GLOBAL']['SUB_ACL'] = (False, [(5005, 5005)]) + expected = 3 + if reason == 'route': + s.bm.SUB_MAP.clear() + s.config['SYSTEMS']['MASTER-B']['PEERS'].clear() + expected = 2 + if reason == 'peer': + s.config['SYSTEMS']['MASTER-B']['PEERS'].clear() + expected = 2 + self.assertEqual(self.request(s), (expected, 0)) + self.assertNotIn('TX_UNIT_DATA_HOLD', status) + + def test_untrusted_controls_are_silent_and_do_not_reserve(self): + for reason in ('mesh', 'endpoint', 'digest', 'short', 'long', 'zero', 'version', 'disabled'): + with self.subTest(reason=reason), self.scenario() as s: + self.prepare(s) + system = 'OBP-1' if reason == 'mesh' else 'DATA-GATEWAY' + config = s.config['SYSTEMS'][system] + address = config['TARGET_SOCK'] + wire = self.wire(s, source=0 if reason == 'zero' else 5005, system=system) + if reason == 'endpoint': address = ('192.0.2.3', 62031) + if reason == 'digest': wire = wire[:-1] + bytes((wire[-1] ^ 1,)) + if reason == 'short': wire = wire[:-1] + if reason == 'long': wire += b'\0' + if reason == 'version': config['VER'] = 1 + if reason == 'disabled': config['ENABLED'] = False + s.inject_datagram(system, wire, address) + self.assertFalse(s.transports[system].writes) + self.assertNotIn('TX_UNIT_DATA_HOLD', s.systems['MASTER-B'].STATUS[2]) + + def test_cache_is_bounded_and_ages_out(self): + with self.scenario() as s: + self.prepare(s) + for request in range(256): + self.request(s, request=request) + self.assertEqual(self.request(s, request=256), (1, 0)) + self.assertEqual(len(s.systems['DATA-GATEWAY']._admission_requests), 256) + s.clock.advance(30) + self.assertEqual(self.request(s, request=256), (0, 500)) + self.assertEqual(len(s.systems['DATA-GATEWAY']._admission_requests), 1) diff --git a/tests/test_unit_data_hold.py b/tests/test_unit_data_hold.py new file mode 100644 index 0000000..b1be72e --- /dev/null +++ b/tests/test_unit_data_hold.py @@ -0,0 +1,219 @@ +"""Slot-local unit-data holds through the real routing handlers.""" +import os +import tempfile +import unittest + +import config as freedmr_config +from tests.harness.deterministic import ( + DeterministicScenario, PacketSpec, minimal_config, add_openbridge_system, + active_bridge, bytes_3, HBPF_DATA_SYNC, HBPF_VOICE, HBPF_SLT_VTERM, +) + + +class UnitDataHoldTests(unittest.TestCase): + def scenario(self, enabled=True, slot=2): + config = minimal_config(("MASTER-A", "MASTER-B")) + config["SYSTEMS"]["MASTER-B"]["UNIT_DATA_HOLD"] = enabled + add_openbridge_system(config, "OBP-1", network_id=3001) + bridges = active_bridge("91", 91, ( + ("MASTER-A", slot), ("MASTER-B", slot), ("OBP-1", 1), + )) + return DeterministicScenario(config=config, bridges=bridges) + + def prepare(self, scenario, slot=2): + scenario.clock.advance(10) + scenario.bm.SUB_MAP[bytes_3(1234567)] = ("MASTER-B", slot, scenario.clock.time()) + scenario.bm.SUB_MAP[bytes_3(1234568)] = ("MASTER-B", slot, scenario.clock.time()) + + def data(self, scenario, source="OBP-1", seq=1, src=5005, dst=1234567, dtype=7): + packet = PacketSpec(rf_src=src, dst_id=dst, slot=1, seq=seq, + stream_id=0x10000000+seq, call_type="unit", + frame_type=HBPF_DATA_SYNC, dtype_vseq=dtype) + inject = scenario.inject_obp if source.startswith("OBP") else scenario.inject_hbp + inject(source, packet) + return packet + + def voice(self, scenario, source="OBP-1", slot=2, seq=1): + packet = PacketSpec(rf_src=3120001, dst_id=91, + slot=1 if source.startswith("OBP") else slot, seq=seq, + stream_id=0x20000000+seq, frame_type=HBPF_VOICE, dtype_vseq=1) + inject = scenario.inject_obp if source.startswith("OBP") else scenario.inject_hbp + inject(source, packet) + + def test_hold_blocks_both_voice_paths_on_either_slot(self): + for slot in (1, 2): + for data_source in ("MASTER-A", "OBP-1"): + for voice_source in ("MASTER-A", "OBP-1"): + with self.subTest(slot=slot, data=data_source, voice=voice_source): + with self.scenario(slot=slot) as s: + self.prepare(s, slot) + self.data(s, data_source, dtype=6) + self.voice(s, voice_source, slot) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 1) + + def test_continuation_refreshes_without_stream_id_dependency(self): + with self.scenario() as s: + self.prepare(s) + for seq, dtype in enumerate((3, 3, 6, 7), 1): + self.data(s, seq=seq, dtype=dtype) + s.clock.advance(4) + self.voice(s) + captured = s.capture.for_system("MASTER-B") + self.assertEqual(len(captured), 4) + self.assertEqual([p.fields["dtype_vseq"] for p in captured], [3, 3, 6, 7]) + self.assertEqual(s.systems["MASTER-B"].STATUS[2]["TX_TYPE"], HBPF_SLT_VTERM) + + def test_other_pairs_are_rejected_without_refreshing_expiry(self): + with self.scenario() as s: + self.prepare(s) + self.data(s) + s.clock.advance(4) + self.data(s, seq=2, src=5006) + self.data(s, seq=3, dst=1234568) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 1) + s.clock.advance(1) + self.data(s, seq=4, src=5006) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 2) + + def test_voice_resumes_at_expiry_without_trimmer(self): + with self.scenario() as s: + self.prepare(s) + self.data(s) + s.clock.advance(4.99) + self.voice(s) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 1) + s.clock.advance(.01) + self.voice(s, seq=2) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 2) + + def test_disabled_preserves_voice_interruption(self): + with self.scenario(enabled=False) as s: + self.prepare(s) + self.data(s) + self.voice(s) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 2) + self.assertNotIn("TX_UNIT_DATA_HOLD", s.systems["MASTER-B"].STATUS[2]) + + def test_missing_runtime_setting_enables_hold(self): + for source in ("MASTER-A", "OBP-1"): + with self.subTest(source=source), self.scenario() as s: + del s.config["SYSTEMS"]["MASTER-B"]["UNIT_DATA_HOLD"] + self.prepare(s) + self.data(s, source) + self.voice(s, source) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 1) + self.assertIn("TX_UNIT_DATA_HOLD", s.systems["MASTER-B"].STATUS[2]) + + def test_ongoing_voice_can_enter_after_hold_without_stale_target_lc(self): + for source in ("MASTER-A", "OBP-1"): + with self.subTest(source=source), self.scenario() as s: + self.prepare(s) + self.data(s) + self.voice(s, source) + s.clock.advance(5) + inject = s.inject_obp if source.startswith("OBP") else s.inject_hbp + for seq, frame, dtype in ((2, HBPF_VOICE, 1), (3, HBPF_DATA_SYNC, HBPF_SLT_VTERM)): + inject(source, PacketSpec(rf_src=3120001, dst_id=91, + slot=1 if source.startswith("OBP") else 2, seq=seq, + stream_id=0x20000001, frame_type=frame, dtype_vseq=dtype)) + captured = s.capture.for_system("MASTER-B") + self.assertEqual(len(captured), 3) + self.assertEqual(len(captured[-1].fields["dmr_payload"]), 33) + self.assertEqual(s.systems["MASTER-B"].STATUS[2]["TX_STREAM_ID"], (0x20000001).to_bytes(4, "big")) + self.assertEqual(s.systems["MASTER-B"].STATUS[2]["TX_TYPE"], HBPF_SLT_VTERM) + + def test_other_slot_not_held(self): + with self.scenario(slot=1) as s: + self.prepare(s, slot=2) + self.data(s) + self.voice(s, slot=1) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 2) + + def test_hold_preserves_payload_and_data_reporting_not_voice_state(self): + for source in ("MASTER-A", "OBP-1"): + with self.subTest(source=source), self.scenario() as s: + self.prepare(s) + s.config["REPORTS"]["REPORT"] = True + slot = s.systems["MASTER-B"].STATUS[2] + original = dict(slot) + packet = self.data(s, source, dtype=6) + actual = s.capture.for_system("MASTER-B")[0].packet + expected = packet.data()[:15] + bytes((packet.data()[15] | 0x80,)) + packet.data()[16:53] + self.assertEqual(actual, expected) + self.assertEqual({key: slot[key] for key in original}, original) + self.assertTrue(s.reports["MASTER-B"].events[-1].startswith(b"UNIT DATA,DATA,TX,")) + + def test_rejected_voice_and_prompt_do_not_extend_hold(self): + with self.scenario() as s: + self.prepare(s) + self.data(s) + slot = s.systems["MASTER-B"].STATUS[2] + original = slot["TX_UNIT_DATA_HOLD"] + s.clock.advance(4) + self.voice(s) + s.bm._beginGeneratedVoice(slot) + s.bm.sendVoicePacket(s.systems["MASTER-B"], PacketSpec(slot=2).data(), + bytes_3(5000), bytes_3(9), slot) + self.assertEqual(slot["TX_UNIT_DATA_HOLD"], original) + s.clock.advance(1) + self.voice(s, seq=2) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 2) + + def test_generated_voice_cannot_interrupt_hold(self): + with self.scenario() as s: + self.prepare(s) + self.data(s) + slot = s.systems["MASTER-B"].STATUS[2] + s.bm._beginGeneratedVoice(slot) + packet = PacketSpec(dst_id=9, slot=2).data() + s.bm.sendVoicePacket(s.systems["MASTER-B"], packet, bytes_3(5000), bytes_3(9), slot) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 1) + self.assertTrue(slot["TX_PROMPT_CANCEL"]) + self.data(s, seq=2) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 2) + + def test_active_generated_voice_prevents_new_hold(self): + with self.scenario() as s: + self.prepare(s) + slot = s.systems["MASTER-B"].STATUS[2] + token = s.bm._beginGeneratedVoice(slot) + self.data(s) + self.assertFalse(s.capture.for_system("MASTER-B")) + self.assertNotIn("TX_UNIT_DATA_HOLD", slot) + s.bm._endGeneratedVoice(slot, token) + self.data(s, seq=2) + self.assertEqual(len(s.capture.for_system("MASTER-B")), 1) + + def test_existing_voice_and_hangtime_still_prevent_data_start(self): + with self.scenario() as s: + self.prepare(s) + s.config["SYSTEMS"]["MASTER-B"]["GROUP_HANGTIME"] = 5 + self.voice(s) + self.data(s) + slot = s.systems["MASTER-B"].STATUS[2] + self.assertNotIn("TX_UNIT_DATA_HOLD", slot) + # End the actual network call, then exercise its existing hangtime. + s.inject_obp("OBP-1", PacketSpec(rf_src=3120001, dst_id=91, slot=1, + seq=2, stream_id=0x20000001, frame_type=HBPF_DATA_SYNC, dtype_vseq=HBPF_SLT_VTERM)) + self.data(s, seq=3) + self.assertNotIn("TX_UNIT_DATA_HOLD", slot) + s.clock.advance(5.01) + self.data(s, seq=4) + self.assertIn("TX_UNIT_DATA_HOLD", slot) + + def test_master_config_default_and_explicit_overrides(self): + for setting, expected in (("", True), ("UNIT_DATA_HOLD: True", True), + ("UNIT_DATA_HOLD: False", False)): + with self.subTest(setting=setting): + fd, path = tempfile.mkstemp(suffix=".cfg") + try: + with os.fdopen(fd, "w") as handle: + handle.write("[GLOBAL]\n[ALIASES]\n[MASTER-A]\nMODE: MASTER\nENABLED: True\n"+setting) + parsed = freedmr_config.build_config(path) + self.assertIs(parsed["SYSTEMS"]["MASTER-A"]["UNIT_DATA_HOLD"], expected) + finally: + os.unlink(path) + + +if __name__ == "__main__": + unittest.main()