diff --git a/.gitignore b/.gitignore index 27337c9..77b1da6 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ # Production config (use *.example.yaml as template) adn-server.yaml adn-echo.yaml +adn-odtp.yaml adn-voice.yaml *.local.yaml *.local.yml diff --git a/adn-odtp.example.yaml b/adn-odtp.example.yaml new file mode 100644 index 0000000..1a2a8f9 --- /dev/null +++ b/adn-odtp.example.yaml @@ -0,0 +1,32 @@ +# ADN ODTP gateway — config (copy to adn-odtp.yaml; do not commit). +# +# Separate process, same binary as adn-server: +# python adn-server.py --odtp -c adn-odtp.yaml +# +# Each phone app / IP terminal that logs in over ODTP becomes one HBP PEER of +# MASTER_IP:MASTER_PORT (ID = DMR ID x 100 + PEER_SUFFIX; a 9-digit login is used as is +# and talks as login // 100), authenticated with the user's own (selfcare) password and sent +# with OPTIONS TERMINAL=1. See docs/en/server/user-guide/odtp.md. + +LOGGER: + LOG_FILE: /var/log/adn-server/odtp.log + LOG_LEVEL: INFO + +ODTP: + LISTEN_IP: 0.0.0.0 + LISTEN_PORT: 54006 # UDP port the apps connect to + MASTER_IP: 127.0.0.1 # the adn-server MASTER the terminals log in to + MASTER_PORT: 62031 + PEER_SUFFIX: 98 # 0-99; suffix of the HBP peer ID (fallback 97 when it is taken) + SUBSCRIBERS_FILE: "" # optional RadioID subscriber_ids.json: callsign sent in the RPTC + + # Caps (each refusal is logged once per minute with counters) + MAX_SESSIONS: 500 # the MASTER's MAX_PEERS caps them too, shared with its hotspots + MAX_SESSIONS_PER_IP: 4 + MAX_LOGINS_PER_MINUTE: 60 + + # Text messages from the app to radios: standard (ETSI), tms (Motorola) or hytera + SMS_FORMAT: standard + SMS_PREAMBLES: 2 + # Private call target for the app's GPS position (0 = do not send) + LOCATION_DST: 0 diff --git a/examples/systemd/adn-odtp.service b/examples/systemd/adn-odtp.service new file mode 100644 index 0000000..16e8457 --- /dev/null +++ b/examples/systemd/adn-odtp.service @@ -0,0 +1,32 @@ +# ADN ODTP gateway (phone apps and IP terminals) – systemd unit (terminals → MASTER on adn-server) +# +# Copy: +# sudo cp /opt/adn-server/examples/systemd/adn-odtp.service /etc/systemd/system/ +# Edit User / paths if needed, then: +# sudo systemctl daemon-reload +# sudo systemctl enable --now adn-odtp +# +# adn-odtp.yaml: start from adn-odtp.example.yaml; MASTER_IP/PORT = the MASTER the terminals log in to. +# Logrotate: SIGUSR2 reopens log files (not SIGHUP). postrotate example: +# kill -USR2 $(systemctl show adn-odtp -p MainPID --value) +# Or: systemctl reload adn-odtp (ExecReload below sends USR2) + +[Unit] +Description=ADN ODTP gateway (phone apps and IP terminals) +After=network-online.target adn-server.service +Wants=network-online.target + +[Service] +User=adn +Type=simple +Restart=always +RestartSec=3 +SyslogIdentifier=adn-odtp +WorkingDirectory=/opt/adn-server +ExecStart=/opt/.pyenv/versions/3.11.8/bin/python3 /opt/adn-server/adn-server.py --echo -c /opt/adn-server/adn-odtp.yaml +ExecReload=/bin/kill -USR2 $MAINPID +KillSignal=SIGTERM +TimeoutStopSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/src/adn_server/application/odtp/__init__.py b/src/adn_server/application/odtp/__init__.py new file mode 100644 index 0000000..f18de2f --- /dev/null +++ b/src/adn_server/application/odtp/__init__.py @@ -0,0 +1,21 @@ +# ADN DMR Peer Server - ODTP gateway +# +# 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 +############################################################################### + +"""ODTP gateway: phone apps and IP terminals log in to a MASTER as terminals.""" diff --git a/src/adn_server/application/odtp/gateway.py b/src/adn_server/application/odtp/gateway.py new file mode 100644 index 0000000..5686490 --- /dev/null +++ b/src/adn_server/application/odtp/gateway.py @@ -0,0 +1,121 @@ +# ADN DMR Peer Server - ODTP gateway +# +# 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 +############################################################################### + +"""ODTP gateway: one TerminalSession per terminal address, with caps on sessions and logins.""" + +from __future__ import annotations + +import logging +from collections import deque +from collections.abc import Callable + +from ...domain import odtp +from .ports import Clock, MasterLinks, OdtpSettings, TerminalSocket +from .session import SessionState, TerminalSession + +logger = logging.getLogger(__name__) + +REJECT_LOG_EVERY_S = 60.0 + + +class OdtpGateway: + def __init__( + self, + settings: OdtpSettings, + socket: TerminalSocket, + links: MasterLinks, + clock: Clock, + callsigns: Callable[[int], str], + ) -> None: + self.settings = settings + self.socket = socket + self.links = links + self.clock = clock + self.callsigns = callsigns + self.sessions: dict[tuple[str, int], TerminalSession] = {} + self.sessions_by_key: dict[int, TerminalSession] = {} + self._logins: deque[float] = deque() + self._rejected: dict[str, int] = {} + self._rejected_logged = -REJECT_LOG_EVERY_S + + def datagram(self, data: bytes, addr: tuple[str, int]) -> None: + msg = odtp.unpack(data) + if msg is None: + return + msg_type, _flags, _seq, payload = msg + session = self.sessions.get(addr) + if session is not None: + session.received(msg_type, payload) + elif msg_type == odtp.KEEP_ALIVE and self._admit(addr): + session = TerminalSession(self, addr) + session.received(msg_type, payload) + if session.state not in (SessionState.NEW, SessionState.CLOSED): # kept once its MASTER link is open + self.sessions[addr] = session + + def _admit(self, addr: tuple[str, int]) -> bool: + """A new session opens a login to the MASTER: cap them in total, per IP and per minute.""" + s, now = self.settings, self.clock.now() + while self._logins and now - self._logins[0] > 60.0: + self._logins.popleft() + if len(self.sessions) >= s.max_sessions: + return self._reject("sessions", addr) + if sum(1 for a in self.sessions if a[0] == addr[0]) >= s.max_sessions_per_ip: + return self._reject("sessions per IP", addr) + if len(self._logins) >= s.max_logins_per_minute: + return self._reject("logins per minute", addr) + return True + + def count_login(self) -> None: + """A session opened its link to the MASTER: only those spend the logins-per-minute cap.""" + self._logins.append(self.clock.now()) + + def _reject(self, cap: str, addr: tuple[str, int]) -> bool: + self._rejected[cap] = self._rejected.get(cap, 0) + 1 + now = self.clock.now() + if now - self._rejected_logged >= REJECT_LOG_EVERY_S: # at most one line a minute + logger.warning("(ODTP) new terminals refused, cap reached: %s (last from %s)", + ", ".join(f"{k} x{v}" for k, v in sorted(self._rejected.items())), addr[0]) + self._rejected.clear() + self._rejected_logged = now + return False + + def register(self, session: TerminalSession) -> None: + """A session the MASTER accepted replaces an older one of the same DMR ID or login.""" + old = self.sessions_by_key.get(session.key) + if old is not None and old is not session: + self.drop(old, "same DMR ID connected again") + self.sessions_by_key[session.key] = session + + def drop(self, session: TerminalSession, reason: str, notify: bool = True) -> None: + logger.info("(ODTP) %s dropped: %s", session, reason) + session.close(notify) + if self.sessions.get(session.addr) is session: + del self.sessions[session.addr] + if self.sessions_by_key.get(session.key) is session: + del self.sessions_by_key[session.key] + + def tick(self) -> None: + now = self.clock.now() + for session in list(self.sessions.values()): + session.tick(now) + + def close(self) -> None: + for session in list(self.sessions.values()): + self.drop(session, "gateway stopping") diff --git a/src/adn_server/application/odtp/messages.py b/src/adn_server/application/odtp/messages.py new file mode 100644 index 0000000..97f7de8 --- /dev/null +++ b/src/adn_server/application/odtp/messages.py @@ -0,0 +1,286 @@ +# ADN DMR Peer Server - ODTP gateway text messages and locations +# +# 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 +############################################################################### + +"""Text messages and locations of one ODTP terminal, as DMR packet data on the MASTER.""" + +# From the terminal: a private text goes as a confirmed packet in the format the addressee last +# wrote in (MOTOTRBO TMS, "DMR standard" UDP 5016, Hytera TMP), the configured one otherwise, and +# the radio's link ACK becomes MESSAGE_STATUS; a group text goes unconfirmed to the talkgroup; a +# location goes as unconfirmed NMEA data to ``location_dst``. To the terminal: packets for its +# peer are reassembled and checked, and the gateway answers the ACKs the sender asks for. + +from __future__ import annotations + +import logging +import os +from collections.abc import Callable +from dataclasses import dataclass, field + +from ...domain import odtp +from ...domain.dmr import data_header as hd +from ...domain.dmr import hdap, ip_sms +from ...domain.dmr.crc import crc32_data +from ...domain.dmr.data_blocks import ( + DT_DATA_HEADER, + DT_RATE12, + DT_RATE34, + Block, + build_blocks, + data_frames, + decode_block, + decode_header_burst, +) +from ...domain.dmrd import DmrdHeader +from .ports import Clock, OdtpSettings, SmsFormat + +logger = logging.getLogger(__name__) + +STATUS_ACK = 0x08 # octet 9 of an ACK response header: class 0, type 1, status 0 +GROUP_NET = 225 # MOTOTRBO group addresses: 225.x.y.z = talkgroup +_DUPLICATE_S = 120.0 +_PACKET_TIMEOUT_S = 10.0 +_RETRY_S = 6.0 + + +@dataclass +class _Rx: + header: hd.DataHeader + seen: float + blocks: list[Block] = field(default_factory=list) + + +@dataclass +class _Pending: + frames: list[bytes] + retried: bool = False + + +class Messages: + """Packet data of one terminal: ``id`` is its DMR ID, ``peer`` its HBP peer ID.""" + + def __init__( + self, + terminal_id: int, + peer_id: int, + settings: OdtpSettings, + clock: Clock, + send_frames: Callable[[list[bytes]], None], + send_terminal: Callable[[int, bytes], None], + ) -> None: + self.id = terminal_id + self.peer = peer_id + self._s = settings + self._clock = clock + self._send = send_frames + self._send_terminal = send_terminal + self._rx: dict[bytes, _Rx] = {} + self._format: dict[int, SmsFormat] = {} + self._seen: dict[tuple[int, str], float] = {} + self._pending: dict[int, _Pending] = {} + self._ip_id = 0 + self._tms_seq = 0 + self._tmp_id = 0 + self._send_seq = 0 + self._last_location = -1e9 + + def text_from_terminal(self, payload: bytes) -> None: + parsed = odtp.parse_text_message(payload) + if parsed is None: + return + _src, dst, group, text = parsed + text = text.strip() + if not text or not 0 < dst < 0x1000000: + return + if group: + body = ip_sms.ip_udp(self.id, dst, ip_sms.PORT_DMR_STANDARD_SMS, ip_sms.standard_sms(text), + self._next_ip_id(), dst_net=GROUP_NET) + blocks, pad = build_blocks(body, rate34=False, confirmed=False) + header = hd.DataHeader(dpf=hd.DPF_UNCONFIRMED, dst=dst, src=self.id, sap=hd.SAP_IP, group=True, + pad_octets=pad, blocks_to_follow=len(blocks)).to_bytes() + self._send(data_frames(header, blocks, self.id, dst, self.peer, 2, self._s.sms_preambles, group=True)) + logger.info("(ODTP) %s text -> TG %s: %r", self.id, dst, text) + return + fmt = self._format.get(dst, self._s.sms_format) + frames = self._private_text(dst, text, fmt) + self._pending[dst] = _Pending(frames) + self._send(frames) + self._clock.call_later(_RETRY_S, self._retry, dst, frames) + logger.info("(ODTP) %s text -> %s (%s): %r", self.id, dst, fmt, text) + + def _private_text(self, dst: int, text: str, fmt: SmsFormat) -> list[bytes]: + if fmt == "hytera": + self._tmp_id = (self._tmp_id + 1) & 0xFFFFFFFF + return self._short_frames(dst, hdap.text(self._tmp_id, dst, self.id, text), 2) + if fmt == "tms": + self._tms_seq = (self._tms_seq + 1) & 0x1F + return self._ip_frames(dst, ip_sms.PORT_TMS, ip_sms.tms_simple_text(text, self._tms_seq), 2) + return self._ip_frames(dst, ip_sms.PORT_DMR_STANDARD_SMS, ip_sms.standard_sms(text), 2) + + def _retry(self, radio: int, frames: list[bytes]) -> None: + pending = self._pending.get(radio) + if pending is None or pending.frames is not frames: + return + if pending.retried: + del self._pending[radio] + logger.info("(ODTP) %s: no ACK from %s for the text", self.id, radio) + return + pending.retried = True + self._send(frames) + self._clock.call_later(_RETRY_S, self._retry, radio, frames) + + def location_from_terminal(self, payload: bytes) -> None: + nmea = odtp.parse_location_report(payload) + now = self._clock.now() + if not nmea or not self._s.location_dst or now - self._last_location < self._s.location_min_gap_s: + return + self._last_location = now + if not nmea.endswith(b"\r\n"): + nmea += b"\r\n" + blocks, pad = build_blocks(nmea, rate34=False, confirmed=False) + dst = self._s.location_dst + header = hd.DataHeader(dpf=hd.DPF_UNCONFIRMED, dst=dst, src=self.id, sap=hd.SAP_IP, + pad_octets=pad, blocks_to_follow=len(blocks)).to_bytes() + self._send(data_frames(header, blocks, self.id, dst, self.peer, 2)) + logger.info("(ODTP) %s location -> %s: %s", self.id, dst, nmea.strip().decode("ascii", "replace")) + + def data_frame(self, h: DmrdHeader, burst: bytes) -> None: + """One data burst the MASTER delivered to this terminal's peer.""" + if h.call_type == "unit" and int.from_bytes(h.dst_id, "big") != self.id: + return + now = self._clock.now() + if h.dtype_vseq == DT_DATA_HEADER: + header = hd.DataHeader.from_bytes(decode_header_burst(burst)) + if header is None: + return + if header.dpf == hd.DPF_RESPONSE: + self._response(header) + return + self._rx = {k: v for k, v in self._rx.items() if now - v.seen < _PACKET_TIMEOUT_S} + if header.blocks: + self._rx[h.stream_id] = _Rx(header, now) + return + rx = self._rx.get(h.stream_id) + if rx is None or h.dtype_vseq not in (DT_RATE12, DT_RATE34): + return + confirmed = rx.header.confirmed or (rx.header.dpf == hd.DPF_SHORT_DATA_DEFINED and rx.header.sarq) + last = len(rx.blocks) + 1 >= rx.header.blocks + block = decode_block(burst, h.dtype_vseq, confirmed, last) + if block is None: + self._rx.pop(h.stream_id, None) + return + rx.blocks.append(block) + if not last: + return + self._rx.pop(h.stream_id, None) + user = b"".join(b.data for b in rx.blocks) + if not all(b.crc_ok for b in rx.blocks) or crc32_data(user) != rx.blocks[-1].crc32: + logger.info("(ODTP) %s: packet from %s with CRC errors, dropped", self.id, rx.header.src) + return + self._packet(rx.header, user, h.slot) + + def _response(self, header: hd.DataHeader) -> None: + if header.dst != self.id or self._pending.pop(header.src, None) is None: + return + # An ACK is 0x08 whatever N(S) it acknowledges; anything else goes as the radio sent it. + if (header.response_class, header.response_type) == hd.RESPONSE_ACK: + status = STATUS_ACK + else: + status = (header.response_class << 6) | (header.response_type << 3) | header.response_status + self._send_terminal(odtp.MESSAGE_STATUS, odtp.text_status(header.src, self.id, status)) + logger.info("(ODTP) %s: %s answered the text (class %d type %d)", self.id, header.src, + header.response_class, header.response_type) + + def _packet(self, h: hd.DataHeader, user: bytes, slot: int) -> None: + radio, group = h.src, h.group + if h.response_requested and not group: + send_seq = h.send_seq if h.dpf == hd.DPF_CONFIRMED else 0 + ack = hd.response_ack(radio, self.id, h.sap, send_seq).to_bytes() + self._send(data_frames(ack, [], self.id, radio, self.peer, slot)) + text, fmt = None, None + if h.sap == hd.SAP_IP: + text, fmt = self._ip_text(h, user, radio, group, slot) + elif h.sap == hd.SAP_SHORT_DATA: + found = hdap.find(user) + tm = hdap.text_message(found[0]) if found else None + if tm is not None: + if tm.ack_required and not group: + self._send(self._short_frames(radio, hdap.text_ack(tm.request_id, radio, self.id), slot)) + text, fmt = tm.text, "hytera" + if not text: + return + if not group: + self._format[radio] = fmt + now = self._clock.now() + key = (radio, text) + if now - self._seen.get(key, -1e9) < _DUPLICATE_S: # a radio repeats a text it got no ACK for + return + self._seen = {k: t for k, t in self._seen.items() if now - t < _DUPLICATE_S} + self._seen[key] = now + dst = h.dst if group else self.id + self._send_terminal(odtp.MESSAGE_TEXT, odtp.text_message(radio, dst, text, group)) + logger.info("(ODTP) %s text <- %s%s (%s): %r", self.id, radio, f" on TG {dst}" if group else "", fmt, text) + + def _ip_text(self, h: hd.DataHeader, user: bytes, radio: int, group: bool, slot: int) -> tuple[str | None, SmsFormat | None]: + msg = ip_sms.parse_ip_udp(user) + if msg is None: + return None, None + if msg.port == ip_sms.PORT_TMS: + tms = ip_sms.tms_parse(msg.payload) + if tms is None or tms.is_ack: + return None, None + if tms.ack_required and not group: + self._send(self._ip_frames(radio, ip_sms.PORT_TMS, ip_sms.tms_ack(tms.sequence), slot, msg.dst_net)) + return tms.text, "tms" + if msg.port != ip_sms.PORT_DMR_STANDARD_SMS: + return None, None + text = ip_sms.standard_sms_parse(msg.payload) + if text is not None: + return text, "standard" + found = hdap.find(msg.payload) # Hytera TMP over UDP 5016 + tm = hdap.text_message(found[0]) if found else None + if tm is None: + return None, None + if tm.ack_required and not group: + ack = hdap.text_ack(tm.request_id, radio, self.id) + self._send(self._ip_frames(radio, ip_sms.PORT_DMR_STANDARD_SMS, ack, slot, msg.dst_net)) + return tm.text, "standard" + + def _ip_frames(self, radio: int, port: int, payload: bytes, slot: int, src_net: int = ip_sms.RADIO_NET) -> list[bytes]: + """A confirmed IPv4/UDP packet to ``radio`` (rate 3/4, link ACK requested).""" + user = ip_sms.ip_udp(self.id, radio, port, payload, self._next_ip_id(), src_net) + blocks, pad = build_blocks(user, rate34=True, confirmed=True) + self._send_seq = (self._send_seq + 1) & 7 + header = hd.DataHeader(dpf=hd.DPF_CONFIRMED, dst=radio, src=self.id, sap=hd.SAP_IP, response_requested=True, + pad_octets=pad, blocks_to_follow=len(blocks), resync=True, + send_seq=self._send_seq, fsn=hd.FSN_SINGLE_CONFIRMED).to_bytes() + return data_frames(header, blocks, self.id, radio, self.peer, slot, self._s.sms_preambles) + + def _short_frames(self, radio: int, message: bytes, slot: int) -> list[bytes]: + """Hytera short data as the radio sends a text: rate 3/4 with SARQ.""" + user = bytes([0x01, 0x00]) + message + blocks, pad = build_blocks(user, rate34=True, confirmed=True) + header = hd.DataHeader(dpf=hd.DPF_SHORT_DATA_DEFINED, dst=radio, src=self.id, sap=hd.SAP_SHORT_DATA, + response_requested=True, appended_blocks=len(blocks), sarq=True, + bit_padding=pad * 8).to_bytes() + return data_frames(header, blocks, self.id, radio, self.peer, slot, self._s.sms_preambles) + + def _next_ip_id(self) -> int: + self._ip_id = (self._ip_id + 1) & 0xFFFF + return self._ip_id or int.from_bytes(os.urandom(2), "big") diff --git a/src/adn_server/application/odtp/ports.py b/src/adn_server/application/odtp/ports.py new file mode 100644 index 0000000..2f63f14 --- /dev/null +++ b/src/adn_server/application/odtp/ports.py @@ -0,0 +1,71 @@ +# ADN DMR Peer Server - ODTP gateway ports +# +# 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 +############################################################################### + +"""What the ODTP gateway needs from the outside: the ODTP socket, MASTER links, a clock, callsigns.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Literal, Protocol, get_args + +SmsFormat = Literal["standard", "tms", "hytera"] +SMS_FORMATS: tuple[str, ...] = get_args(SmsFormat) + + +class TerminalSocket(Protocol): + def send(self, data: bytes, addr: tuple[str, int]) -> None: ... + + +class MasterLink(Protocol): + def send(self, packet: bytes) -> None: ... + + def close(self) -> None: ... + + +class MasterLinks(Protocol): + def open(self, on_datagram: Callable[[bytes], None]) -> MasterLink: ... + + +class Clock(Protocol): + def now(self) -> float: ... + + def call_later(self, delay: float, fn: Callable[..., Any], *args: Any) -> Any: ... + + +@dataclass(frozen=True) +class OdtpSettings: + master_ip: str = "127.0.0.1" + master_port: int = 62031 + peer_suffix: int = 98 + max_sessions: int = 500 + max_sessions_per_ip: int = 4 + max_logins_per_minute: int = 60 + sms_format: SmsFormat = "standard" + sms_preambles: int = 2 + location_dst: int = 0 + location_min_gap_s: float = 10.0 + terminal_timeout_s: float = 30.0 + login_timeout_s: float = 15.0 + max_missed: int = 3 + + @property + def alt_suffix(self) -> int: + return self.peer_suffix - 1 if self.peer_suffix > 0 else 1 diff --git a/src/adn_server/application/odtp/session.py b/src/adn_server/application/odtp/session.py new file mode 100644 index 0000000..4f8daed --- /dev/null +++ b/src/adn_server/application/odtp/session.py @@ -0,0 +1,423 @@ +# ADN DMR Peer Server - ODTP terminal session +# +# 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 +############################################################################### + +"""One ODTP terminal: logged in to the MASTER as an HBP peer whose OPTIONS carry TERMINAL=1.""" + +# The gateway holds no password: ODTP and HBP both answer SHA-256(salt + password), so the +# MASTER's salt is the terminal's challenge and the terminal's answer goes to the MASTER as the +# RPTK, which checks it like any hotspot's (self-care password, else the passphrase). + +from __future__ import annotations + +import logging +import os +from collections import deque +from enum import Enum +from typing import TYPE_CHECKING + +from bitarray import bitarray + +from ...domain import odtp +from ...domain.dmr.embedded_lc import collect_embedded_lc +from ...domain.dmr.frames import DmrdStream, superframe_embedding, voice_bits +from ...domain.dmrd import DmrdHeader, parse_dmrd_header +from ...domain.hbp_protocol import ( + DMRD, + HBPF_DATA_SYNC, + HBPF_SLT_VHEAD, + HBPF_SLT_VTERM, + HBPF_VOICE, +) +from ..hbp_peer_login import PeerLogin +from ..routing.helpers import UNIT_DATA_DTYPES +from .messages import Messages + +if TYPE_CHECKING: + from .gateway import OdtpGateway + from .ports import MasterLink + +logger = logging.getLogger(__name__) + +RPTO_BATCH_S = 0.1 # every RPTO makes the MASTER recompute the peer's statics: batch a scan burst +UPLINK_IDLE_S = 1.0 # a call ends this long after its last frame when no terminator comes +DOWNLINK_IDLE_S = 1.0 +FRAME_SPACING_S = 0.06 +_EPSILON_S = 0.001 + + +class SessionState(str, Enum): + NEW = "new" + OPENING = "opening" # link to the MASTER open, RPTL sent + CHALLENGED = "challenged" # the MASTER's salt went to the terminal + CONNECTING = "connecting" # the terminal's answer went to the MASTER as the RPTK + UP = "up" + CLOSED = "closed" + + +def _field(text: str, size: int) -> bytes: + return text.encode("ascii", "replace").ljust(size)[:size] + + +class _Uplink: + """One call from the terminal as a DMRD stream; terminal embedded data rides every other superframe.""" + + def __init__(self, src: int, dst: int, peer: bytes, private: bool, now: float) -> None: + self.dst, self.private, self.last, self.frames = dst, private, now, 0 + self.stream = DmrdStream(src.to_bytes(3, "big"), dst.to_bytes(3, "big"), peer, 1, os.urandom(4), private=private) + self._extra: deque[bytes] = deque(maxlen=8) + self._superframe = self.stream.embedding + + def embed(self, lc: bytes) -> None: + lc = bytes(lc[:odtp.LC_LEN]) + if len(lc) == odtp.LC_LEN and lc[0] & 0x3F in odtp.EMBEDDED_FLCOS and lc not in self._extra: + self._extra.append(lc) + + def voice(self, ambe: bytes, now: float) -> bytes: + n = self.frames % 6 + if n == 0: + if self._extra and self._superframe is self.stream.embedding: + self._superframe = superframe_embedding(self._extra.popleft()) + else: + self._superframe = self.stream.embedding + bits = bitarray(endian="big") + bits.frombytes(ambe[:odtp.AUDIO_PAYLOAD]) + self.frames += 1 + self.last = now + return self.stream.burst(n, bits[:108], bits[108:216], self._superframe) + + +class TerminalSession: + def __init__(self, gw: OdtpGateway, addr: tuple[str, int]) -> None: + self.gw = gw + self.addr = addr + self.state = SessionState.NEW + self.dmr_id = 0 + self.login_peer_id = 0 # the terminal logged in with a 9-digit peer ID, used as is + self.suffix = gw.settings.peer_suffix + self.description = "" + self.since = self.last_rx = gw.clock.now() + self.subs: set[int] = set() + self.private_subs: set[int] = set() + self.link: MasterLink | None = None + self.peer_login: PeerLogin | None = None + self._stats: dict = {} + self._config: dict = {} + self._seq = 0 + self._rt_seq = 0 + self._rpto_pending = False + self.uplink: _Uplink | None = None + self.messages: Messages | None = None + self._down_stream: bytes | None = None + self._down_last = 0.0 + self._down_frames = 0 + self._down_acc: dict = {} + self._down_lcs: set[bytes] = set() + self._busy_stream: bytes | None = None + + def __str__(self) -> str: + who = f"{self.login_peer_id}/{self.dmr_id or '?'}" if self.login_peer_id else str(self.dmr_id or "?") + return f"terminal {who} {self.addr[0]}:{self.addr[1]}" + + @property + def key(self) -> int: + return self.login_peer_id or self.dmr_id + + @property + def peer_id(self) -> bytes: + return (self.login_peer_id or self.dmr_id * 100 + self.suffix).to_bytes(4, "big") + + def options(self) -> bytes: + tgs = ",".join(str(tg) for tg in sorted(self.subs)) + return f"TERMINAL=1;TS2={tgs};".encode() if tgs else b"TERMINAL=1;" + + def send(self, msg_type: int, payload: bytes = b"") -> None: + if msg_type in odtp.REAL_TIME_SEQUENCE: + self._rt_seq += 1 + flags = odtp.FLAG_REAL_TIME_1 if msg_type in odtp.REAL_TIME_FLAGGED else 0 + data = odtp.pack(msg_type, self._rt_seq, payload, flags) + else: + self._seq += 1 + data = odtp.pack(msg_type, self._seq, payload) + self.gw.socket.send(data, self.addr) + + def _to_master(self, packet: bytes) -> None: + if self.link is not None: + self.link.send(packet) + + def _send_frames(self, frames: list[bytes]) -> None: + """A data packet for the MASTER, one DMRD frame per TDMA burst time.""" + for i, frame in enumerate(frames): + self.gw.clock.call_later(i * FRAME_SPACING_S, self._to_master, frame) + + # ── from the terminal ── + + def received(self, msg_type: int, payload: bytes) -> None: + self.last_rx = self.gw.clock.now() + if msg_type == odtp.KEEP_ALIVE: + self._keep_alive(payload) + elif msg_type == odtp.AUTHENTICATION: + if self.state is SessionState.CHALLENGED and len(payload) >= 32 and self.peer_login is not None: + self.state = SessionState.CONNECTING + self.peer_login.send_key(payload[:32]) + elif msg_type == odtp.CLOSE: + self.gw.drop(self, "closed by the terminal") + elif self.state is not SessionState.UP: + return + elif msg_type in (odtp.SUBSCRIPTION, odtp.CANCELLING): + self._subscribe(payload, add=msg_type == odtp.SUBSCRIPTION) + elif msg_type == odtp.BUSY_NOTICE: + self._busy_stream = self._down_stream + elif msg_type == odtp.VOICE_HEADER: + self._uplink_header(payload) + elif msg_type == odtp.DMR_AUDIO_FRAME: + if self.uplink is not None and len(payload) >= odtp.AUDIO_PAYLOAD: + self._to_master(self.uplink.voice(payload, self.gw.clock.now())) + elif msg_type == odtp.VOICE_TERMINATOR: + self._uplink_end("terminator") + elif msg_type == odtp.DMR_EMBEDDED_DATA: + if self.uplink is not None: + self.uplink.embed(payload) + elif msg_type == odtp.MESSAGE_TEXT: + self.messages.text_from_terminal(payload) + elif msg_type == odtp.LOCATION_REPORT: + self.messages.location_from_terminal(payload) + + def _keep_alive(self, payload: bytes) -> None: + if self.state is SessionState.UP: + self.send(odtp.KEEP_ALIVE) + return + parsed = odtp.parse_keep_alive(payload) if self.state is SessionState.NEW else None + if parsed is None: + return + number, service, self.description = parsed + if service != odtp.SERVICE_OPEN_TERMINAL or not 0 < number < 1_000_000_000: + logger.info("(ODTP) %s: not an Open DMR Terminal (service 0x%02x, ID %s)", self, service, number) + return + dmr_id = number // 100 if number >= 100_000_000 else number # a 9-digit login is DMR ID x 100 + 2 digits + if dmr_id > 0xFFFFFF: + logger.info("(ODTP) %s: ID %s is not a DMR ID", self, number) + return + self.dmr_id = dmr_id + if number >= 100_000_000: + self.login_peer_id = number + else: + old = self.gw.sessions_by_key.get(number) + if old is not None: + # The MASTER drops a connected peer when its ID logs in again: a second session + # takes the other suffix and replaces the first only once the MASTER accepts it. + s = self.gw.settings + self.suffix = s.alt_suffix if old.suffix == s.peer_suffix else s.peer_suffix + callsign = self.gw.callsigns(self.dmr_id) + self._config = { + "RADIO_ID": self.peer_id, "CALLSIGN": _field(callsign, 8), "RX_FREQ": _field("000000000", 9), + "TX_FREQ": _field("000000000", 9), "TX_POWER": _field("01", 2), "COLORCODE": _field("01", 2), + "LATITUDE": _field("0.0", 8), "LONGITUDE": _field("0.0", 9), "HEIGHT": _field("000", 3), + "LOCATION": _field("ODTP terminal", 20), "DESCRIPTION": _field(self.description, 19), + "SLOTS": b"4", "URL": _field("", 124), "SOFTWARE_ID": _field(self.description, 40), + "PACKAGE_ID": _field("ODTP", 40), "OPTIONS": self.options(), + "MASTER_IP": self.gw.settings.master_ip, "MASTER_PORT": self.gw.settings.master_port, + } + self.peer_login = PeerLogin(str(self), self._config, self._stats, self._to_master, logger, on_salt=self._salt) + # The link opens last: a session that fails before it leaves nothing open. + try: + self.link = self.gw.links.open(self.from_master) + except OSError as e: + self.gw.drop(self, f"cannot reach the MASTER: {e}", notify=False) + return + self.gw.count_login() + self.state = SessionState.OPENING + self.since = self.gw.clock.now() + self.peer_login.tick(self.gw.settings.max_missed) + + def _salt(self, salt: bytes) -> None: + """The MASTER's salt is the terminal's challenge; its answer comes back as AUTHENTICATION.""" + if self.state is SessionState.OPENING: + self.state = SessionState.CHALLENGED + self.send(odtp.CHALLENGE, salt) + + def _subscribe(self, payload: bytes, *, add: bool) -> None: + parsed = odtp.parse_subscription(payload) + if parsed is None: + if payload or add: + return + self.subs.clear() + self.private_subs.clear() + else: + kind, number = parsed + group = kind == odtp.SESSION_TYPE_GROUP_VOICE + target = self.subs if group else self.private_subs + (target.add if add else target.discard)(number) + self.send(odtp.SUBSCRIPTION if add else odtp.CANCELLING) + self._config["OPTIONS"] = self.options() + if not self._rpto_pending: + self._rpto_pending = True + self.gw.clock.call_later(RPTO_BATCH_S, self._send_options) + logger.info("(ODTP) %s subscriptions: TG %s, private %s", self, sorted(self.subs) or "-", sorted(self.private_subs) or "-") + + def _send_options(self) -> None: + self._rpto_pending = False + if self.peer_login is not None: + self.peer_login.send_options() + + def _uplink_header(self, payload: bytes) -> None: + parsed = odtp.parse_voice_header(payload) + if parsed is None: + return + dst, _src, private = parsed # the source is never the header's + if self.uplink is not None and (self.uplink.dst, self.uplink.private) == (dst, private): + return # the header comes 2-3 times + self._uplink_end("new call") + # The source is always the session's DMR ID, never the header's: the 7-digit login or + # login // 100. A terminal cannot talk as somebody else. + self.uplink = uplink = _Uplink(self.dmr_id, dst, self.peer_id, private, self.gw.clock.now()) + for _ in range(3): + self._to_master(uplink.stream.header()) + self.gw.clock.call_later(UPLINK_IDLE_S, self._watch_uplink, uplink) + logger.info("(ODTP) %s TX %s %s", self, "private" if private else "TG", dst) + + def _watch_uplink(self, uplink: _Uplink) -> None: + if self.uplink is not uplink: + return + left = uplink.last + UPLINK_IDLE_S - self.gw.clock.now() + if left > _EPSILON_S: + self.gw.clock.call_later(left, self._watch_uplink, uplink) + else: + self._uplink_end("no terminator from the app") + + def _uplink_end(self, reason: str) -> None: + if self.uplink is not None: + self._to_master(self.uplink.stream.terminator()) + logger.info("(ODTP) %s TX end (%d frames, %s)", self, self.uplink.frames, reason) + self.uplink = None + + # ── from the MASTER ── + + def from_master(self, data: bytes) -> None: + if data[:4] == DMRD: + if self.state is SessionState.UP: + self._downlink(data) + return + if self.peer_login is None: + return + before = self._stats.get("CONNECTION") + self.peer_login.datagram(data[:4], data) + after = self._stats.get("CONNECTION") + if after == "YES" and before != "YES": + self._master_up() + elif after == "NO" and before != "NO": + if self.state is SessionState.UP: + self.gw.drop(self, "MASTER dropped the peer") + else: # silence to the terminal, as BrandMeister does + what = "wrong password" if before == "AUTHENTICATED" else f"refused ({before})" + self.gw.drop(self, f"MASTER login failed: {what}", notify=False) + + def _master_up(self) -> None: + self.gw.register(self) + self.state = SessionState.UP + self.messages = Messages(self.dmr_id, int.from_bytes(self.peer_id, "big"), self.gw.settings, self.gw.clock, + self._send_frames, self.send) + self.send(odtp.KEEP_ALIVE) + logger.info("(ODTP) %s up as peer %s (%s)", self, int.from_bytes(self.peer_id, "big"), self.description) + + def _downlink(self, data: bytes) -> None: + h = parse_dmrd_header(data) + if h is None: + return + private = h.call_type == "unit" + if private and self.dmr_id and int.from_bytes(h.dst_id, "big") != self.dmr_id: + return + burst = data[20:53] + if h.stream_id == self._down_stream: + self._down_last = self.gw.clock.now() + if h.stream_id == self._busy_stream: + if h.frame_type == HBPF_DATA_SYNC and h.dtype_vseq == HBPF_SLT_VTERM: + self._end_downlink("terminator") + return + if h.frame_type == HBPF_DATA_SYNC: + if h.dtype_vseq in UNIT_DATA_DTYPES: + self.messages.data_frame(h, burst) + elif h.dtype_vseq == HBPF_SLT_VHEAD and h.stream_id != self._down_stream: + self._start_downlink(h) # the MASTER repeats the header 2-3 times + elif h.dtype_vseq == HBPF_SLT_VTERM and h.stream_id == self._down_stream: + self._end_downlink("terminator") + return + if h.stream_id != self._down_stream: + self._start_downlink(h) # joined late, or the header was lost + self.send(odtp.DMR_AUDIO_FRAME, voice_bits(burst).tobytes()) + self._down_frames += 1 + lc = collect_embedded_lc(self._down_acc, h.dtype_vseq if h.frame_type == HBPF_VOICE else 0, burst) + if lc is not None and lc[0] & 0x3F in odtp.EMBEDDED_FLCOS and lc not in self._down_lcs: + self._down_lcs.add(lc) + self.send(odtp.DMR_EMBEDDED_DATA, lc) + + def _start_downlink(self, h: DmrdHeader) -> None: + if self._down_stream is not None: + self._end_downlink("new call") + self._down_stream = h.stream_id + self._down_last = self.gw.clock.now() + self._down_frames = 0 + self._down_acc = {} + self._down_lcs = set() + dst, src, private = int.from_bytes(h.dst_id, "big"), int.from_bytes(h.rf_src, "big"), h.call_type == "unit" + self.send(odtp.VOICE_HEADER, odtp.voice_header(dst, src, private)) + logger.info("(ODTP) %s RX %s %s from %s", self, "private" if private else "TG", dst, src) + self.gw.clock.call_later(DOWNLINK_IDLE_S, self._watch_downlink, h.stream_id) + + def _watch_downlink(self, stream_id: bytes) -> None: + if self._down_stream != stream_id or self.state is not SessionState.UP: + return + left = self._down_last + DOWNLINK_IDLE_S - self.gw.clock.now() + if left > _EPSILON_S: + self.gw.clock.call_later(left, self._watch_downlink, stream_id) + else: + self._end_downlink("no terminator from the MASTER") + + def _end_downlink(self, reason: str) -> None: + """The terminal leaves RX; a call it said it was busy for ends silently.""" + if self._down_stream != self._busy_stream: + self.send(odtp.VOICE_TERMINATOR) + logger.info("(ODTP) %s RX end (%d frames, %s)", self, self._down_frames, reason) + self._down_stream = self._busy_stream = None + + # ── housekeeping ── + + def tick(self, now: float) -> None: + s = self.gw.settings + if self.state is not SessionState.UP: + if now - self.since > s.login_timeout_s: + self.gw.drop(self, f"login not finished ({self.state})", notify=False) + return + if self._stats.get("PING_OUTSTANDING") and self._stats.get("NUM_OUTSTANDING", 0) + 1 >= s.max_missed: + self.gw.drop(self, "MASTER silent") + return + self.peer_login.tick(s.max_missed) + if now - self.last_rx > s.terminal_timeout_s: + self.gw.drop(self, "keep-alive timeout") + + def close(self, notify: bool) -> None: + self._uplink_end("session closed") + if notify and self.state is SessionState.UP: + self.send(odtp.CLOSE) + if self.peer_login is not None: + self.peer_login.close() + if self.link is not None: + self.link.close() + self.link = None + self.state = SessionState.CLOSED diff --git a/src/adn_server/infrastructure/config_loader.py b/src/adn_server/infrastructure/config_loader.py index 0e5789e..94f71ee 100644 --- a/src/adn_server/infrastructure/config_loader.py +++ b/src/adn_server/infrastructure/config_loader.py @@ -118,6 +118,9 @@ class YamlConfigLoader: # "absent" (defaults apply) from "present but disabled". if isinstance(data.get("OBP_PROXY"), dict): config["OBP_PROXY"] = data["OBP_PROXY"] + # ODTP is the gateway's own config (adn-odtp.yaml). + if isinstance(data.get("ODTP"), dict): + config["ODTP"] = data["ODTP"] # PLUGINS (directory, master_kill, overrides, send) is read by the plugin manager. if isinstance(data.get("PLUGINS"), dict): config["PLUGINS"] = data["PLUGINS"] diff --git a/src/adn_server/infrastructure/config_validator.py b/src/adn_server/infrastructure/config_validator.py index 435a9ec..b37e72b 100644 --- a/src/adn_server/infrastructure/config_validator.py +++ b/src/adn_server/infrastructure/config_validator.py @@ -23,6 +23,7 @@ from __future__ import annotations from typing import Any +from adn_server.application.odtp.ports import SMS_FORMATS from adn_server.application.proxy.deployment import config_has_enabled_openbridge from adn_server.application.routing.loop_guard import MAX_LOOP_GUARD_HOLD_S @@ -424,6 +425,35 @@ def _validate_system(name: str, sys_cfg: dict[str, Any], errors: list[str]) -> N _expect_number(f"{prefix}.{key}", sys_cfg[key], errors) +_ODTP_INT_RANGES = { + "LISTEN_PORT": (1, 65535), "MASTER_PORT": (1, 65535), "PEER_SUFFIX": (0, 99), "MAX_SESSIONS": (1, 100000), + "MAX_SESSIONS_PER_IP": (1, 100000), "MAX_LOGINS_PER_MINUTE": (1, 100000), "SMS_PREAMBLES": (0, 10), + "LOCATION_DST": (0, 0xFFFFFF), +} + + +def _validate_odtp(odtp_cfg: Any, errors: list[str]) -> None: + if odtp_cfg is None: + return + if not isinstance(odtp_cfg, dict): + errors.append(f"ODTP: expected mapping, got {type(odtp_cfg).__name__}.") + return + for key in ("LISTEN_IP", "MASTER_IP", "SUBSCRIBERS_FILE"): + if key in odtp_cfg: + _expect_str(f"ODTP.{key}", odtp_cfg[key], errors) + for key, (low, high) in _ODTP_INT_RANGES.items(): + value = odtp_cfg.get(key) + if _is_empty(value): + continue + before = len(errors) + _expect_int(f"ODTP.{key}", value, errors) + if len(errors) == before and not low <= value <= high: + errors.append(f"ODTP.{key}: {value} out of range {low}-{high}.") + fmt = odtp_cfg.get("SMS_FORMAT") + if not _is_empty(fmt) and fmt not in SMS_FORMATS: + errors.append(f"ODTP.SMS_FORMAT: {fmt!r}, expected one of {', '.join(SMS_FORMATS)}.") + + def validate_config(config: dict[str, Any], *, config_path: str | None = None) -> None: """Validate config structure and scalar types. Raises ConfigError with all issues found.""" errors: list[str] = [] @@ -454,6 +484,7 @@ def validate_config(config: dict[str, Any], *, config_path: str | None = None) - ) if proxy_port is not None and proxy_port == obp_port: errors.append(f"PROXY.LISTEN_PORT and OBP_PROXY.LISTEN_PORT: both {proxy_port}, would collide on bind.") + _validate_odtp(config.get("ODTP"), errors) if _config_requires_database(config): _validate_database(config.get("DATABASE"), errors) diff --git a/src/adn_server/infrastructure/odtp/__init__.py b/src/adn_server/infrastructure/odtp/__init__.py new file mode 100644 index 0000000..7e90317 --- /dev/null +++ b/src/adn_server/infrastructure/odtp/__init__.py @@ -0,0 +1,25 @@ +# ADN DMR Peer Server - ODTP gateway runtime +# +# 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 +############################################################################### + +"""ODTP gateway runtime: phone apps and IP terminals as terminals of a MASTER.""" + +from .runtime import run_odtp + +__all__ = ["run_odtp"] diff --git a/src/adn_server/infrastructure/odtp/callsigns.py b/src/adn_server/infrastructure/odtp/callsigns.py new file mode 100644 index 0000000..c70b443 --- /dev/null +++ b/src/adn_server/infrastructure/odtp/callsigns.py @@ -0,0 +1,62 @@ +# ADN DMR Peer Server - ODTP gateway callsigns +# +# 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 +############################################################################### + +"""DMR ID -> callsign from a RadioID subscriber_ids.json, looked up at login without loading the file.""" + +# Parsed whole, the file is ~200 MB of Python objects for 300k IDs; a login needs one entry, and a +# plain find over the mapped file takes ~15 ms. Lookups, found or not, are kept in a small cache. + +from __future__ import annotations + +import mmap +import re + +_CALLSIGN = re.compile(rb'\s*"callsign":\s*"([^"]*)"') + + +class CallsignFile: + _CACHE = 1024 + + def __init__(self, path: str) -> None: + self.path = path + self._cache: dict[int, str] = {} + + def __call__(self, dmr_id: int) -> str: + if dmr_id in self._cache: + return self._cache[dmr_id] + callsign = self._find(dmr_id) # "" for an ID not in the file, kept too: no scan on every login + if callsign is None: + return "" + if len(self._cache) >= self._CACHE: + self._cache.pop(next(iter(self._cache))) + self._cache[dmr_id] = callsign + return callsign + + def _find(self, dmr_id: int) -> str | None: + try: + with open(self.path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm: + for key in (b'"id":%d,' % dmr_id, b'"id": %d,' % dmr_id): + at = mm.find(key) + if at >= 0: + match = _CALLSIGN.match(mm[at + len(key):at + len(key) + 200]) + return match.group(1).decode("utf-8", "replace") if match else "" + except (OSError, ValueError): # no file (yet): look again next time + return None + return "" diff --git a/src/adn_server/infrastructure/odtp/runtime.py b/src/adn_server/infrastructure/odtp/runtime.py new file mode 100644 index 0000000..624b949 --- /dev/null +++ b/src/adn_server/infrastructure/odtp/runtime.py @@ -0,0 +1,93 @@ +# ADN DMR Peer Server - ODTP gateway runtime +# +# 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 +############################################################################### + +"""ODTP gateway runtime (``adn-server --odtp -c adn-odtp.yaml``).""" + +from __future__ import annotations + +import logging +import signal +import socket +from typing import Any + +from twisted.internet import reactor + +from ...application.odtp.gateway import OdtpGateway +from ...application.odtp.ports import OdtpSettings +from .. import reopen_file_handlers +from ..twisted_adapters.looping import start_loop +from .callsigns import CallsignFile +from .udp import OdtpListener, ReactorClock, TwistedMasterLinks + +TICK_S = 5.0 # keepalives to the MASTER and session timeouts +DNS_REFRESH_S = 600.0 + + +def odtp_settings(cfg: dict[str, Any]) -> OdtpSettings: + """OdtpSettings from the ODTP section; absent keys keep their defaults.""" + keys = { + "MASTER_IP": "master_ip", "MASTER_PORT": "master_port", "PEER_SUFFIX": "peer_suffix", + "MAX_SESSIONS": "max_sessions", "MAX_SESSIONS_PER_IP": "max_sessions_per_ip", + "MAX_LOGINS_PER_MINUTE": "max_logins_per_minute", "SMS_FORMAT": "sms_format", + "SMS_PREAMBLES": "sms_preambles", "LOCATION_DST": "location_dst", + } + return OdtpSettings(**{field: cfg[key] for key, field in keys.items() if key in cfg}) + + +def run_odtp(config: dict[str, Any], *, logger: logging.Logger) -> None: + """Start the ODTP listener and run the Twisted reactor (blocks until shutdown).""" + cfg = config.get("ODTP", {}) + settings = odtp_settings(cfg) + master_ip = socket.gethostbyname(settings.master_ip) # a connected UDP socket needs an address + subscribers = cfg.get("SUBSCRIBERS_FILE") or "" + listener = OdtpListener() + links = TwistedMasterLinks(settings.master_ip, master_ip, settings.master_port) + gateway = OdtpGateway( + settings, + listener, + links, + ReactorClock(), + CallsignFile(subscribers) if subscribers else (lambda _dmr_id: ""), + ) + listener.gateway = gateway + listen_ip, listen_port = cfg.get("LISTEN_IP", "0.0.0.0"), cfg.get("LISTEN_PORT", 54006) + reactor.listenUDP(listen_port, listener, interface=listen_ip) + start_loop(gateway.tick, TICK_S, logger, name="odtp sessions") + if master_ip != settings.master_ip: + start_loop(links.refresh, DNS_REFRESH_S, logger, now=False, name="odtp MASTER address") + + def stop() -> None: + logger.info("SHUTDOWN: ODTP GATEWAY IS TERMINATING") + gateway.close() # CLOSE to the terminals and RPTCL to the MASTER: UDP writes go out at once + + def reopen_logs(_sig: int, _frame: Any) -> None: + logger.info("(LOGGER) Reopened %s file log handler(s) after SIGUSR2", reopen_file_handlers()) + + # Twisted's own SIGTERM/SIGINT handlers stop the reactor; this runs on any stop. + reactor.addSystemEventTrigger("before", "shutdown", stop) + signal.signal(signal.SIGUSR2, reopen_logs) + if hasattr(signal, "SIGHUP"): + signal.signal(signal.SIGHUP, lambda *_: logger.debug("(ODTP) SIGHUP ignored (restart to apply config)")) + + logger.info( + "(ODTP) gateway on %s:%s -> MASTER %s:%s (peer suffix %s, callsigns %s)", + listen_ip, listen_port, settings.master_ip, settings.master_port, settings.peer_suffix, subscribers or "off", + ) + reactor.run() diff --git a/src/adn_server/infrastructure/odtp/udp.py b/src/adn_server/infrastructure/odtp/udp.py new file mode 100644 index 0000000..135df8a --- /dev/null +++ b/src/adn_server/infrastructure/odtp/udp.py @@ -0,0 +1,106 @@ +# ADN DMR Peer Server - ODTP gateway UDP adapters +# +# 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 +############################################################################### + +"""Twisted adapters of the ODTP gateway: the terminals' socket, one UDP link to the MASTER per terminal, the clock.""" + +from __future__ import annotations + +import logging +import time +from collections.abc import Callable +from typing import Any + +from twisted.internet import reactor +from twisted.internet.protocol import DatagramProtocol + +from ...application.odtp.gateway import OdtpGateway + +logger = logging.getLogger(__name__) + + +class OdtpListener(DatagramProtocol): + """The ODTP port: every datagram goes to the gateway.""" + + def __init__(self) -> None: + self.gateway: OdtpGateway | None = None + + def datagramReceived(self, data: bytes, addr: tuple[str, int]) -> None: + if self.gateway is not None: + self.gateway.datagram(data, addr) + + def send(self, data: bytes, addr: tuple[str, int]) -> None: + if self.transport is not None: + self.transport.write(data, addr) + + +class _MasterProtocol(DatagramProtocol): + def __init__(self, master: tuple[str, int], on_datagram: Callable[[bytes], None]) -> None: + self._master = master + self._on_datagram = on_datagram + + def startProtocol(self) -> None: + self.transport.connect(*self._master) + + def datagramReceived(self, data: bytes, _addr: tuple[str, int]) -> None: + self._on_datagram(data) + + +class _MasterLink: + def __init__(self, protocol: _MasterProtocol, port: Any) -> None: + self._protocol = protocol + self._port = port + + def send(self, packet: bytes) -> None: + if self._protocol.transport is not None: + self._protocol.transport.write(packet) + + def close(self) -> None: + self._port.stopListening() + + +class TwistedMasterLinks: + """Each terminal logs in from its own UDP socket, as a hotspot would.""" + + def __init__(self, master_host: str, master_ip: str, master_port: int) -> None: + self._host = master_host + self._master = (master_ip, master_port) + + def refresh(self) -> None: + """Resolve the MASTER's name again, as the PEER mode does; new links use the new address.""" + d = reactor.resolve(self._host) + d.addCallback(self._resolved) + d.addErrback(lambda failure: logger.info("(ODTP) cannot resolve %s: %s", self._host, failure.getErrorMessage())) + + def _resolved(self, ip: str) -> None: + if ip != self._master[0]: + logger.info("(ODTP) MASTER %s is now %s", self._host, ip) + self._master = (ip, self._master[1]) + + def open(self, on_datagram: Callable[[bytes], None]) -> _MasterLink: + protocol = _MasterProtocol(self._master, on_datagram) + return _MasterLink(protocol, reactor.listenUDP(0, protocol)) + + +class ReactorClock: + def now(self) -> float: + return time.monotonic() + + def call_later(self, delay: float, fn: Callable[..., Any], *args: Any) -> Any: + return reactor.callLater(delay, fn, *args) diff --git a/src/adn_server/main.py b/src/adn_server/main.py index 9f53d05..dd47035 100644 --- a/src/adn_server/main.py +++ b/src/adn_server/main.py @@ -27,9 +27,10 @@ ADN DMR Peer Server entrypoint. Run: python -m adn_server.main [-c adn-server.yaml] [--logging LEVEL] python -m adn_server.main --echo [-c adn-echo.yaml] + python -m adn_server.main --odtp [-c adn-odtp.yaml] python -m adn_server.main --doctor [-c adn-server.yaml] python -m adn_server.main --replay capture.pcap [--system OBP-FR] -Config default: adn-server.yaml (or adn-echo.yaml with --echo). +Config default: adn-server.yaml (adn-echo.yaml with --echo, adn-odtp.yaml with --odtp). """ from __future__ import annotations @@ -47,10 +48,14 @@ if str(_ROOT) not in sys.path: from adn_server.domain.errors import ConfigError from adn_server.infrastructure import YamlConfigLoader, setup_logging from adn_server.infrastructure.bootstrap import run_peer_server -from adn_server.infrastructure.config_normalizer import apply_talker_alias_defaults, normalize_obp_config +from adn_server.infrastructure.config_normalizer import ( + apply_talker_alias_defaults, + normalize_obp_config, +) from adn_server.infrastructure.doctor import run_doctor -from adn_server.infrastructure.obp_replay import run_replay from adn_server.infrastructure.echo import run_echo +from adn_server.infrastructure.obp_replay import run_replay +from adn_server.infrastructure.odtp import run_odtp def _project_root() -> str: @@ -71,6 +76,11 @@ def _parse_args() -> argparse.Namespace: action="store_true", help="Playback mode: run ECHO PEER(s) from adn-echo.yaml (default config)", ) + parser.add_argument( + "--odtp", + action="store_true", + help="ODTP gateway: phone apps and IP terminals log in to a MASTER (default config adn-odtp.yaml)", + ) parser.add_argument( "--no-proxy", action="store_true", @@ -130,7 +140,7 @@ def main() -> None: args = _parse_args() project_root = _project_root() - default_config = "adn-echo.yaml" if args.echo else "adn-server.yaml" + default_config = "adn-echo.yaml" if args.echo else "adn-odtp.yaml" if args.odtp else "adn-server.yaml" config_path = args.CONFIG_FILE or os.path.join(project_root, default_config) if args.doctor: @@ -164,11 +174,12 @@ def main() -> None: ) ) - if not args.echo: + standalone = args.echo or args.odtp + if not standalone: apply_talker_alias_defaults(config) voice_config_path = os.path.join(os.path.dirname(os.path.abspath(config_path)), "adn-voice.yaml") - voice_data = loader.load_voice_config(voice_config_path) if not args.echo else None + voice_data = loader.load_voice_config(voice_config_path) if not standalone else None if voice_data: config.setdefault("VOICE", {}).update(voice_data) @@ -180,6 +191,9 @@ def main() -> None: if args.echo: run_echo(config, logger=logger) return + if args.odtp: + run_odtp(config, logger=logger) + return run_peer_server( config, diff --git a/tests/infrastructure/test_config_validator.py b/tests/infrastructure/test_config_validator.py index 8032409..ce24ef2 100644 --- a/tests/infrastructure/test_config_validator.py +++ b/tests/infrastructure/test_config_validator.py @@ -161,3 +161,14 @@ def test_rejects_tg4000_voice_outside_a_master() -> None: with pytest.raises(ConfigError) as exc: validate_config(config) assert "SYSTEMS.BRIDGE.TG4000_VOICE: only on MASTER" in str(exc.value) + + +def test_odtp_section_is_checked() -> None: + config = _minimal_config() + config["ODTP"] = {"LISTEN_PORT": 54006, "PEER_SUFFIX": 98, "SMS_FORMAT": "tms", "MASTER_IP": "127.0.0.1"} + validate_config(config) + config["ODTP"].update(PEER_SUFFIX=100, SMS_FORMAT="sms", MAX_SESSIONS="many") + with pytest.raises(ConfigError) as exc: + validate_config(config) + assert "ODTP.PEER_SUFFIX" in str(exc.value) and "ODTP.SMS_FORMAT" in str(exc.value) + assert "ODTP.MAX_SESSIONS" in str(exc.value) diff --git a/tests/odtp/test_gateway.py b/tests/odtp/test_gateway.py new file mode 100644 index 0000000..092f53b --- /dev/null +++ b/tests/odtp/test_gateway.py @@ -0,0 +1,283 @@ +"""ODTP gateway end to end: terminal -> gateway -> real HBP MASTER, and back.""" + +import logging +import os +import struct + +from bitarray import bitarray + +from adn_server.application.odtp.ports import OdtpSettings +from adn_server.domain import odtp +from adn_server.domain.dmr.frames import DmrdStream, voice_bits +from adn_server.domain.dmrd import parse_dmrd_header +from adn_server.infrastructure.odtp.callsigns import CallsignFile +from tests.support.odtp_stack import PEER, TERMINAL_ID, Stack + +RADIO = 2140001 + + +def _call(tg: int, n: int, ambe: bytes, *, src: int = RADIO, private: bool = False) -> list[bytes]: + """A call as the MASTER delivers it to the terminal's peer: header, ``n`` voice bursts, terminator.""" + bits = bitarray(endian="big") + bits.frombytes(ambe) + stream = DmrdStream(src.to_bytes(3, "big"), tg.to_bytes(3, "big"), PEER, 1, os.urandom(4), private=private) + return [stream.header(), *(stream.burst(i, bits[:108], bits[108:]) for i in range(n)), stream.terminator()] + + +def _up(**kw): + stack = Stack(**kw) + term = stack.terminal() + term.login() + assert term.got(odtp.KEEP_ALIVE) == [b""], "authenticated and logged in to the MASTER" + return stack, term + + +def test_the_challenge_is_the_masters_salt_and_the_peer_is_a_terminal(): + stack, term = _up() + peer = stack.net.peer(PEER) + assert peer["CONNECTION"] == "YES" and peer["OPTIONS"] == b"TERMINAL=1;" + assert peer["CALLSIGN"].startswith(b"C31AG") + assert len(term.got(odtp.CHALLENGE)[0]) == 4 + + +def test_voice_both_ways_and_subscriptions(): + stack, term = _up() + term.subscribe(666) + assert term.got(odtp.SUBSCRIPTION) == [b""] + stack.advance(0.2) + assert stack.net.peer(PEER)["OPTIONS"] == b"TERMINAL=1;TS2=666;" + + ambe = os.urandom(27) + stack.net.to_peer(PEER, _call(666, 2, ambe)) + assert odtp.parse_voice_header(term.got(odtp.VOICE_HEADER)[0]) == (666, RADIO, False) + assert term.got(odtp.DMR_AUDIO_FRAME) == [ambe, ambe] + assert len(term.got(odtp.VOICE_TERMINATOR)) == 1 + + # The source is always the authenticated ID. + for _ in range(2): + term.send(odtp.VOICE_HEADER, odtp.voice_header(666, 9999999, False)) + term.send(odtp.DMR_AUDIO_FRAME, ambe) + term.send(odtp.VOICE_TERMINATOR) + frames = [parse_dmrd_header(f) for f in stack.net.dmrd] + assert [(h.frame_type, h.dtype_vseq) for h in frames] == [(2, 1)] * 3 + [(1, 0), (2, 2)] + assert {(int.from_bytes(h.rf_src, "big"), int.from_bytes(h.dst_id, "big"), h.slot, h.peer_id) for h in frames} == { + (TERMINAL_ID, 666, 2, PEER)} + assert voice_bits(stack.net.dmrd[3][20:53]).tobytes() == ambe + + term.send(odtp.CANCELLING) + stack.advance(0.2) + assert stack.net.peer(PEER)["OPTIONS"] == b"TERMINAL=1;" + + +def test_a_burst_of_subscriptions_is_one_rpto(): + stack, term = _up() + for tg in (214, 666, 901, 902, 903): + term.subscribe(tg) + stack.advance(0.2) + assert stack.net.options() == [b"TERMINAL=1;", b"TERMINAL=1;TS2=214,666,901,902,903;"] + + +def test_rx_ends_one_second_after_the_last_frame_without_a_terminator(): + stack, term = _up() + frames = _call(666, 6, os.urandom(27))[:-1] # the MASTER never sends the terminator + for frame in frames: + stack.net.to_peer(PEER, [frame]) + stack.advance(0.5) # frames keep the call open + assert len(term.got(odtp.DMR_AUDIO_FRAME)) == 6 and not term.got(odtp.VOICE_TERMINATOR) + stack.advance(0.6) + assert len(term.got(odtp.VOICE_TERMINATOR)) == 1 + stack.advance(5.0) + assert len(term.got(odtp.VOICE_TERMINATOR)) == 1, "once" + + # The next call opens as usual, and its own terminator ends it once. + stack.net.to_peer(PEER, _call(666, 2, os.urandom(27))) + stack.advance(2.0) + assert len(term.got(odtp.VOICE_HEADER)) == 2 and len(term.got(odtp.VOICE_TERMINATOR)) == 2 + + +def test_tx_ends_one_second_after_the_apps_last_frame(): + stack, term = _up() + term.send(odtp.VOICE_HEADER, odtp.voice_header(666, TERMINAL_ID, False)) + term.send(odtp.DMR_AUDIO_FRAME, os.urandom(27)) + stack.advance(0.9) + term.send(odtp.DMR_AUDIO_FRAME, os.urandom(27)) + stack.advance(0.9) + assert [parse_dmrd_header(f).dtype_vseq for f in stack.net.dmrd][-1] != 2, "still talking" + stack.advance(0.2) # no gateway tick: the call's own timer + assert parse_dmrd_header(stack.net.dmrd[-1]).dtype_vseq == 2 and stack.gw.sessions_by_key[TERMINAL_ID].uplink is None + + +def test_busy_notice_drops_the_rest_of_the_call(): + stack, term = _up() + frames = _call(666, 3, os.urandom(27)) + stack.net.to_peer(PEER, frames[:2]) + term.send(odtp.BUSY_NOTICE) + stack.net.to_peer(PEER, frames[2:]) + stack.advance(2.0) + assert len(term.got(odtp.DMR_AUDIO_FRAME)) == 1 and not term.got(odtp.VOICE_TERMINATOR) + + +def test_wrong_password_gets_silence_and_no_master_login(): + stack = Stack() + term = stack.terminal() + term.login(password=b"wrong") + assert [t for t, _ in term.inbox] == [odtp.CHALLENGE] + assert stack.net.peer(PEER) is None and not stack.gw.sessions + + +def test_a_failed_login_does_not_kick_the_connected_session(): + stack, term = _up() + intruder = stack.terminal(50001) + intruder.login(password=b"guess") + assert [t for t, _ in intruder.inbox] == [odtp.CHALLENGE] + assert stack.gw.sessions_by_key[TERMINAL_ID].addr == term.addr and len(stack.gw.sessions) == 1 + assert stack.net.peer(PEER)["CONNECTION"] == "YES" + assert stack.net.sent[-2][4:8] == (TERMINAL_ID * 100 + 97).to_bytes(4, "big"), "the other suffix" + + # The app reconnecting from a new port with the right password replaces the session. + again = stack.terminal(50002) + again.login() + assert again.got(odtp.KEEP_ALIVE) == [b""] + assert list(stack.gw.sessions) == [again.addr] and stack.gw.sessions_by_key[TERMINAL_ID].suffix == 97 + assert term.got(odtp.CLOSE) == [b""] + + +def _uplink_sources(stack) -> set: + return {(int.from_bytes(h.rf_src, "big"), int.from_bytes(h.dst_id, "big"), h.peer_id) + for h in map(parse_dmrd_header, stack.net.dmrd)} + + +def test_a_9_digit_login_talks_only_as_its_own_dmr_id(): + login = TERMINAL_ID * 100 + 76 + stack = Stack() + term = stack.terminal() + term.login(login) + assert stack.net.peer(login.to_bytes(4, "big"))["CONNECTION"] == "YES" + assert stack.gw.sessions_by_key[login].dmr_id == TERMINAL_ID, "login // 100, from the start" + term.subscribe(9999999, kind=5) # a private subscription for somebody else changes nothing + term.send(odtp.VOICE_HEADER, odtp.voice_header(666, 9999999, False)) + term.send(odtp.DMR_AUDIO_FRAME, os.urandom(27)) + term.send(odtp.VOICE_TERMINATOR) + assert stack.net.dmrd and _uplink_sources(stack) == {(TERMINAL_ID, 666, login.to_bytes(4, "big"))} + + +def test_private_calls_reach_only_their_addressee(): + stack, term = _up() + stack.net.to_peer(PEER, _call(2130001, 1, os.urandom(27), private=True)) + assert not term.got(odtp.VOICE_HEADER) + stack.net.to_peer(PEER, _call(TERMINAL_ID, 1, os.urandom(27), private=True)) + assert odtp.parse_voice_header(term.got(odtp.VOICE_HEADER)[0]) == (TERMINAL_ID, RADIO, True) + + +def test_timeouts_drop_the_session_and_log_out_of_the_master(): + stack, term = _up() + for _ in range(5): + stack.advance(5.0) + stack.gw.tick() + term.send(odtp.KEEP_ALIVE) # pings to the MASTER are answered + assert stack.net.peer(PEER)["CONNECTION"] == "YES" + stack.advance(31.0) + stack.gw.tick() + assert not stack.gw.sessions and stack.net.sent[-1] == b"RPTCL" + PEER + + half = stack.terminal(50001) + half.send(odtp.KEEP_ALIVE, struct.pack(" None: + self.t = 1000.0 + self._due: list[tuple[float, int, Callable[..., Any], tuple]] = [] + self._n = 0 + + def now(self) -> float: + return self.t + + def call_later(self, delay: float, fn: Callable[..., Any], *args: Any) -> None: + self._n += 1 + self._due.append((self.t + delay, self._n, fn, args)) + + def advance(self, seconds: float) -> None: + end = self.t + seconds + while True: + due = sorted(d for d in self._due if d[0] <= end) + if not due: + break + self._due.remove(due[0]) + self.t = max(self.t, due[0][0]) + due[0][2](*due[0][3]) + self.t = end + + +class _Transport: + def __init__(self, net: Net) -> None: + self._net = net + + def write(self, data: bytes, addr: tuple[str, int]) -> None: + self._net.queue.append((addr, data)) + + +class _Link: + def __init__(self, net: Net, addr: tuple[str, int]) -> None: + self._net, self.addr = net, addr + + def send(self, packet: bytes) -> None: + if packet[:4] == b"DMRD": + self._net.dmrd.append(packet) + else: + self._net.to_master(packet, self.addr) + + def close(self) -> None: + self._net.links.pop(self.addr, None) + + +class Net: + """The MASTER and the gateway's links to it; datagrams are delivered in order, never re-entrantly.""" + + def __init__(self, passphrase: bytes = PASSWORD) -> None: + config = { + "GLOBAL": {"PING_TIME": 5, "MAX_MISSED": 3, "USE_ACL": False}, + "SYSTEMS": {"MASTER-1": {"MODE": "MASTER", "ENABLED": True, "MAX_PEERS": 50, + "PASSPHRASE": passphrase, "OPTIONS": "TS2=9990;"}}, + } + ensure_system_runtime_config(config) + self.master = HBPProtocol("MASTER-1", config, router=_AllowAll()) + self.master.transport = _Transport(self) + self.queue: deque[tuple[tuple[str, int], bytes]] = deque() + self.links: dict[tuple[str, int], Callable[[bytes], None]] = {} + self.sent: list[bytes] = [] # control packets the MASTER got + self.dmrd: list[bytes] = [] # DMRD frames the terminals sent + self._port = 40000 + self._busy = False + + def open(self, on_datagram: Callable[[bytes], None]) -> _Link: + self._port += 1 + addr = ("127.0.0.1", self._port) + self.links[addr] = on_datagram + return _Link(self, addr) + + def to_master(self, packet: bytes, addr: tuple[str, int]) -> None: + self.sent.append(packet) + self.queue.append((None, (packet, addr))) # delivered by pump(), as the reactor would + + def pump(self) -> None: + if self._busy: + return + self._busy = True + try: + while self.queue: + addr, data = self.queue.popleft() + if addr is None: + self.master.datagramReceived(*data) + elif addr in self.links: + self.links[addr](data) + finally: + self._busy = False + + def peer(self, peer_id: bytes) -> dict | None: + return self.master._peers.get(peer_id) + + def to_peer(self, peer_id: bytes, frames: list[bytes]) -> None: + """The MASTER sends frames to one connected peer.""" + addr = self.master._peers[peer_id]["SOCKADDR"] + for frame in frames: + self.queue.append((addr, frame)) + self.pump() + + def options(self) -> list[bytes]: + return [p[8:] for p in self.sent if p[:4] == b"RPTO"] + + +class _AllowAll: + def acl_check(self, *_a: Any) -> bool: + return True + + +class Terminal: + def __init__(self, gw: OdtpGateway, port: int) -> None: + self.gw, self.addr, self.seq, self.inbox = gw, ("198.51.100.7", port), 0, [] + + def send(self, msg_type: int, payload: bytes = b"") -> None: + self.seq += 1 + self.gw.datagram(odtp.pack(msg_type, self.seq, payload), self.addr) + self.gw.links.pump() + + def got(self, msg_type: int) -> list[bytes]: + return [p for t, p in self.inbox if t == msg_type] + + def login(self, number: int = TERMINAL_ID, password: bytes = PASSWORD) -> None: + self.send(odtp.KEEP_ALIVE, struct.pack(" None: + self.send(odtp.SUBSCRIPTION if add else odtp.CANCELLING, struct.pack(" None: + self.terminals: dict[tuple[str, int], Terminal] = {} + + def send(self, data: bytes, addr: tuple[str, int]) -> None: + msg = odtp.unpack(data) + if addr in self.terminals and msg is not None: + self.terminals[addr].inbox.append((msg[0], msg[3])) + + +class Stack: + def __init__(self, settings: OdtpSettings | None = None, callsigns: Callable[[int], str] = lambda _i: "C31AG") -> None: + self.net = Net() + self.clock = FakeClock() + self.socket = _Socket() + self.gw = OdtpGateway(settings or OdtpSettings(), self.socket, self.net, self.clock, callsigns) + + def terminal(self, port: int = 50000) -> Terminal: + term = Terminal(self.gw, port) + self.socket.terminals[term.addr] = term + return term + + def advance(self, seconds: float) -> None: + self.clock.advance(seconds) + self.net.pump()