Each terminal logs in to the MASTER as one HBP peer with OPTIONS TERMINAL=1, relaying the MASTER's salt as its challenge. Voice, embedded data, text messages and locations go both ways; a call without a terminator ends 1 s after its last frame, on its own timer. A terminal always talks as its session's DMR ID (a 9-digit login as login // 100). Sessions are capped in total, per IP and per minute; only a login that opens a MASTER link counts. Tests run against a real HBPProtocol MASTER. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013jYm3g9skKGroRdrfwJsCGpull/162/head
parent
9f1430657a
commit
6d6346d37e
@ -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
|
||||
@ -0,0 +1,21 @@
|
||||
# ADN DMR Peer Server - ODTP gateway
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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."""
|
||||
@ -0,0 +1,121 @@
|
||||
# ADN DMR Peer Server - ODTP gateway
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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")
|
||||
@ -0,0 +1,286 @@
|
||||
# ADN DMR Peer Server - ODTP gateway text messages and locations
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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")
|
||||
@ -0,0 +1,71 @@
|
||||
# ADN DMR Peer Server - ODTP gateway ports
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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
|
||||
@ -0,0 +1,423 @@
|
||||
# ADN DMR Peer Server - ODTP terminal session
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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
|
||||
@ -0,0 +1,25 @@
|
||||
# ADN DMR Peer Server - ODTP gateway runtime
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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"]
|
||||
@ -0,0 +1,62 @@
|
||||
# ADN DMR Peer Server - ODTP gateway callsigns
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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 ""
|
||||
@ -0,0 +1,93 @@
|
||||
# ADN DMR Peer Server - ODTP gateway runtime
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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()
|
||||
@ -0,0 +1,106 @@
|
||||
# ADN DMR Peer Server - ODTP gateway UDP adapters
|
||||
#
|
||||
# Copyright (C) 2026 Rodrigo Pérez, CE5RPY <ce5rpy@qmd.cl>
|
||||
#
|
||||
###############################################################################
|
||||
# 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)
|
||||
@ -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("<IB", TERMINAL_ID, odtp.SERVICE_OPEN_TERMINAL))
|
||||
stack.advance(16.0)
|
||||
stack.gw.tick()
|
||||
assert not stack.gw.sessions, "a login the terminal never answers"
|
||||
|
||||
|
||||
def test_a_master_that_stops_answering_drops_the_session():
|
||||
stack, term = _up()
|
||||
stack.net.links.clear() # the MASTER's answers are lost
|
||||
for _ in range(3): # MAX_MISSED pings go unanswered
|
||||
term.send(odtp.KEEP_ALIVE)
|
||||
stack.gw.tick()
|
||||
assert stack.gw.sessions
|
||||
stack.gw.tick()
|
||||
assert not stack.gw.sessions and term.got(odtp.CLOSE) == [b""]
|
||||
|
||||
|
||||
def test_not_an_open_terminal_is_ignored():
|
||||
stack = Stack()
|
||||
term = stack.terminal()
|
||||
term.send(odtp.KEEP_ALIVE, struct.pack("<IB", TERMINAL_ID, 0x10))
|
||||
assert not term.inbox and stack.net.sent == []
|
||||
|
||||
|
||||
# ── caps: each one refuses what is over it, and only that ──
|
||||
|
||||
def _login_many(stack, n, ip="198.51.100.7"):
|
||||
terms = []
|
||||
for i in range(n):
|
||||
term = stack.terminal(51000 + i)
|
||||
term.addr = (ip, 51000 + i)
|
||||
stack.socket.terminals[term.addr] = term
|
||||
term.login(2130100 + i + len(stack.gw.sessions) * 1000)
|
||||
terms.append(term)
|
||||
return terms
|
||||
|
||||
|
||||
def test_cap_on_sessions_per_ip():
|
||||
stack = Stack(settings=OdtpSettings(max_sessions_per_ip=2))
|
||||
terms = _login_many(stack, 3)
|
||||
assert [bool(t.got(odtp.KEEP_ALIVE)) for t in terms] == [True, True, False]
|
||||
other = _login_many(stack, 1, ip="203.0.113.9")
|
||||
assert other[0].got(odtp.KEEP_ALIVE)
|
||||
|
||||
|
||||
def test_cap_on_total_sessions():
|
||||
stack = Stack(settings=OdtpSettings(max_sessions=2))
|
||||
a = _login_many(stack, 1, ip="203.0.113.1") + _login_many(stack, 1, ip="203.0.113.2")
|
||||
c = _login_many(stack, 1, ip="203.0.113.3")
|
||||
assert all(t.got(odtp.KEEP_ALIVE) for t in a) and not c[0].inbox and len(stack.gw.sessions) == 2
|
||||
|
||||
|
||||
def test_cap_on_logins_per_minute(caplog):
|
||||
stack = Stack(settings=OdtpSettings(max_logins_per_minute=2, max_sessions_per_ip=100))
|
||||
with caplog.at_level(logging.WARNING):
|
||||
terms = _login_many(stack, 5)
|
||||
assert [bool(t.got(odtp.KEEP_ALIVE)) for t in terms] == [True, True, False, False, False]
|
||||
refusals = [r for r in caplog.records if "refused" in r.getMessage()]
|
||||
assert len(refusals) == 1 and "logins per minute" in refusals[0].getMessage(), "one log line a minute"
|
||||
stack.advance(61.0)
|
||||
assert _login_many(stack, 1)[0].got(odtp.KEEP_ALIVE)
|
||||
|
||||
|
||||
def test_junk_does_not_spend_the_login_cap():
|
||||
stack = Stack(settings=OdtpSettings(max_logins_per_minute=2, max_sessions_per_ip=100))
|
||||
for i in range(60): # spoofed datagrams: no valid keep-alive, or not an Open DMR Terminal
|
||||
junk = stack.terminal(52000 + i)
|
||||
junk.send(odtp.KEEP_ALIVE, b"\x01" if i % 2 else struct.pack("<IB", TERMINAL_ID, 0x10))
|
||||
assert not stack.gw.sessions and stack.net.sent == []
|
||||
assert [bool(t.got(odtp.KEEP_ALIVE)) for t in _login_many(stack, 3)] == [True, True, False]
|
||||
|
||||
|
||||
|
||||
def test_an_id_too_big_for_a_dmr_id_opens_no_link():
|
||||
stack = Stack(settings=OdtpSettings(max_logins_per_minute=2, max_sessions_per_ip=100))
|
||||
for i, number in enumerate((0x1000000, 99_999_999)): # 8 digits, over 24 bits
|
||||
stack.terminal(53000 + i).send(odtp.KEEP_ALIVE, struct.pack("<IB", number, odtp.SERVICE_OPEN_TERMINAL))
|
||||
stack.advance(120)
|
||||
stack.gw.tick()
|
||||
assert not stack.gw.sessions and not stack.net.links and stack.net.sent == []
|
||||
assert [bool(t.got(odtp.KEEP_ALIVE)) for t in _login_many(stack, 3)] == [True, True, False]
|
||||
|
||||
def test_callsign_file_looks_up_without_loading(tmp_path):
|
||||
compact = tmp_path / "compact.json"
|
||||
compact.write_text('{"count":3,"results":[{"id":2130035,"callsign":"C31AG","fname":"A"},'
|
||||
'{"id":21300351,"callsign":"WRONG"},{"id":2140001,"callsign":"EA3XYZ"}]}')
|
||||
spaced = tmp_path / "spaced.json"
|
||||
spaced.write_text('{"results": [{"id": 2130035, "callsign": "C31AG"}]}')
|
||||
for path in (compact, spaced):
|
||||
assert CallsignFile(str(path))(2130035) == "C31AG"
|
||||
lookup = CallsignFile(str(compact))
|
||||
assert lookup(213003) == "" and lookup(2130035) == "C31AG" # a prefix is not an ID
|
||||
compact.write_text('{"results":[{"id":213003,"callsign":"NEW"}]}')
|
||||
assert lookup(213003) == "", "an ID not in the file is not looked up again"
|
||||
compact.unlink()
|
||||
assert lookup(2130035) == "C31AG", "found callsigns stay cached"
|
||||
later = CallsignFile(str(tmp_path / "later.json"))
|
||||
assert later(2130035) == ""
|
||||
(tmp_path / "later.json").write_text('{"results":[{"id":2130035,"callsign":"C31AG"}]}')
|
||||
assert later(2130035) == "C31AG", "a missing file is looked at again"
|
||||
@ -0,0 +1,217 @@
|
||||
"""ODTP gateway: embedded data, text messages and locations, end to end."""
|
||||
|
||||
import os
|
||||
import struct
|
||||
|
||||
from bitarray import bitarray
|
||||
|
||||
from adn_server.application.odtp.messages import Messages
|
||||
from adn_server.application.odtp.ports import OdtpSettings
|
||||
from adn_server.application.odtp.session import _Uplink
|
||||
from adn_server.domain import odtp
|
||||
from adn_server.domain.dmr import data_header as hd
|
||||
from adn_server.domain.dmr import hdap, ip_sms
|
||||
from adn_server.domain.dmr.crc import crc32_data
|
||||
from adn_server.domain.dmr.data_blocks import (
|
||||
DT_CSBK,
|
||||
DT_DATA_HEADER,
|
||||
build_blocks,
|
||||
data_frames,
|
||||
decode_block,
|
||||
decode_header_burst,
|
||||
)
|
||||
from adn_server.domain.dmr.embedded_lc import collect_embedded_lc
|
||||
from adn_server.domain.dmr.frames import DmrdStream, superframe_embedding
|
||||
from adn_server.domain.dmrd import parse_dmrd_header
|
||||
from tests.support.odtp_stack import PEER, TERMINAL_ID, FakeClock, Stack
|
||||
|
||||
RADIO = 2140001
|
||||
TA_HEADER = bytes([0x04, 0x00, 0x42]) + b"C31AG " # Talker Alias header: 7-bit, 6 characters
|
||||
NMEA = b"$GPRMC,120000,A,4230.378,N,00131.310,E,0.0,0.0,251026,,*00"
|
||||
|
||||
|
||||
def _up(**kw):
|
||||
stack = Stack(**kw)
|
||||
term = stack.terminal()
|
||||
term.login()
|
||||
assert term.got(odtp.KEEP_ALIVE)
|
||||
return stack, term
|
||||
|
||||
|
||||
def _packets(frames):
|
||||
"""(header, user data) of each packet in a list of DMRD frames (CSBK preambles skipped)."""
|
||||
out, cur = [], None
|
||||
for f in frames:
|
||||
h = parse_dmrd_header(f)
|
||||
if h.dtype_vseq == DT_CSBK:
|
||||
continue
|
||||
if h.dtype_vseq == DT_DATA_HEADER:
|
||||
cur = [hd.DataHeader.from_bytes(decode_header_burst(f[20:53])), []]
|
||||
out.append(cur)
|
||||
else:
|
||||
cur[1].append((h.dtype_vseq, f[20:53]))
|
||||
result = []
|
||||
for header, data in out:
|
||||
confirmed = header.confirmed or (header.dpf == hd.DPF_SHORT_DATA_DEFINED and header.sarq)
|
||||
blocks = [decode_block(b, dt, confirmed, i == len(data) - 1) for i, (dt, b) in enumerate(data)]
|
||||
user = b"".join(b.data for b in blocks)
|
||||
assert not blocks or (all(b.crc_ok for b in blocks) and crc32_data(user) == blocks[-1].crc32)
|
||||
result.append((header, user))
|
||||
return result
|
||||
|
||||
|
||||
def _radio(fmt, text, dst=TERMINAL_ID):
|
||||
"""A private text from RADIO asking for every ACK it can, as the MASTER delivers it to the terminal's peer."""
|
||||
m = Messages(RADIO, RADIO * 100 + 1, OdtpSettings(sms_preambles=0), FakeClock(), lambda f: None, lambda *a: None)
|
||||
if fmt == "tms":
|
||||
tms = bytearray(ip_sms.tms_simple_text(text, 3))
|
||||
tms[2] |= 0x40 # application ACK wanted
|
||||
frames = m._ip_frames(dst, ip_sms.PORT_TMS, bytes(tms), 2)
|
||||
elif fmt == "hytera":
|
||||
tmp = hdap.text(9, dst, RADIO, text)
|
||||
frames = m._short_frames(dst, hdap.build(hdap.SERVICE_TMP, hdap.TMP_PRIVATE_MESSAGE, hdap.find(tmp)[0].payload), 2)
|
||||
else:
|
||||
frames = m._ip_frames(dst, ip_sms.PORT_DMR_STANDARD_SMS, ip_sms.standard_sms(text), 2)
|
||||
return [f[:11] + PEER + f[15:] for f in frames]
|
||||
|
||||
|
||||
def _lcs(frames):
|
||||
acc, out = {}, []
|
||||
for f in frames:
|
||||
h = parse_dmrd_header(f)
|
||||
if h.frame_type in (0, 1):
|
||||
lc = collect_embedded_lc(acc, h.dtype_vseq if h.frame_type == 0 else 0, f[20:53])
|
||||
if lc is not None:
|
||||
out.append(lc)
|
||||
return out
|
||||
|
||||
|
||||
def test_text_status_location_codecs():
|
||||
msg = odtp.text_message(TERMINAL_ID, RADIO, "hola ñandú")
|
||||
assert odtp.parse_text_message(msg) == (TERMINAL_ID, RADIO, False, "hola ñandú")
|
||||
assert odtp.parse_text_message(odtp.text_message(1, 213, "x", group=True))[2] is True
|
||||
assert odtp.parse_text_status(odtp.text_status(RADIO, TERMINAL_ID, 8)) == (RADIO, TERMINAL_ID, 8)
|
||||
report = struct.pack("<IIH", 0, odtp.LOCATION_FORMAT_NMEA, len(NMEA) + 1) + NMEA + b"\x00"
|
||||
assert odtp.parse_location_report(report) == NMEA
|
||||
|
||||
|
||||
def test_uplink_embedded_lc_takes_every_other_superframe():
|
||||
call = _Uplink(TERMINAL_ID, 666, PEER, False, 0.0)
|
||||
block1 = bytes([0x05]) + b"C31AG Ad"
|
||||
call.embed(TA_HEADER)
|
||||
call.embed(block1)
|
||||
frames = [call.voice(os.urandom(27), 0.0) for _ in range(30)]
|
||||
voice_lc = odtp.full_lc(666, TERMINAL_ID, False)
|
||||
assert _lcs(frames) == [TA_HEADER, voice_lc, block1, voice_lc, voice_lc]
|
||||
|
||||
|
||||
def test_embedded_data_both_ways():
|
||||
stack, term = _up()
|
||||
# Downlink: a radio's Talker Alias reaches the app once.
|
||||
stream = DmrdStream(RADIO.to_bytes(3, "big"), (666).to_bytes(3, "big"), PEER, 1, os.urandom(4))
|
||||
bits = bitarray(endian="big")
|
||||
bits.frombytes(os.urandom(27))
|
||||
ta = superframe_embedding(TA_HEADER)
|
||||
frames = [stream.header()] + [stream.burst(i, bits[:108], bits[108:], ta) for i in range(18)] + [stream.terminator()]
|
||||
stack.net.to_peer(PEER, frames)
|
||||
assert term.got(odtp.DMR_EMBEDDED_DATA) == [TA_HEADER]
|
||||
# Uplink: the app's Talker Alias rides in its call.
|
||||
term.send(odtp.VOICE_HEADER, odtp.voice_header(666, TERMINAL_ID, False))
|
||||
term.send(odtp.DMR_EMBEDDED_DATA, TA_HEADER + b"\x00")
|
||||
for _ in range(12):
|
||||
term.send(odtp.DMR_AUDIO_FRAME, os.urandom(27))
|
||||
assert TA_HEADER in _lcs(stack.net.dmrd)
|
||||
|
||||
|
||||
def test_text_from_the_app_to_a_radio_its_ack_and_one_retry():
|
||||
stack, term = _up()
|
||||
term.send(odtp.MESSAGE_TEXT, odtp.text_message(TERMINAL_ID, RADIO, "prueba ODTP"))
|
||||
stack.advance(1.0)
|
||||
[(header, user)] = _packets(stack.net.dmrd)
|
||||
assert (header.dpf, header.src, header.dst, header.response_requested) == (hd.DPF_CONFIRMED, TERMINAL_ID, RADIO, True)
|
||||
msg = ip_sms.parse_ip_udp(user)
|
||||
assert msg.radio_id == TERMINAL_ID and ip_sms.standard_sms_parse(msg.payload) == "prueba ODTP"
|
||||
stack.advance(6.0)
|
||||
assert len(_packets(stack.net.dmrd)) == 2, "no ACK: sent once more"
|
||||
# The radio's link ACK becomes MESSAGE_STATUS (ACK = 0x08).
|
||||
ack = hd.response_ack(TERMINAL_ID, RADIO, hd.SAP_IP, header.send_seq).to_bytes()
|
||||
stack.net.to_peer(PEER, [f[:11] + PEER + f[15:] for f in data_frames(ack, [], RADIO, TERMINAL_ID, RADIO, 2)])
|
||||
assert [odtp.parse_text_status(p) for p in term.got(odtp.MESSAGE_STATUS)] == [(RADIO, TERMINAL_ID, 0x08)]
|
||||
stack.advance(12.0)
|
||||
assert len(_packets(stack.net.dmrd)) == 2
|
||||
|
||||
|
||||
def _text_to_the_app(fmt):
|
||||
stack, term = _up()
|
||||
frames = _radio(fmt, "hola desde la radio")
|
||||
stack.net.to_peer(PEER, frames)
|
||||
assert [odtp.parse_text_message(p) for p in term.got(odtp.MESSAGE_TEXT)] == [
|
||||
(RADIO, TERMINAL_ID, False, "hola desde la radio")]
|
||||
stack.advance(2.0)
|
||||
headers = [h for h, _ in _packets(stack.net.dmrd)]
|
||||
acks = [h for h in headers if h.dpf == hd.DPF_RESPONSE]
|
||||
assert acks and all((h.src, h.dst, h.response_class, h.response_type) == (TERMINAL_ID, RADIO, 0, 1) for h in acks)
|
||||
if fmt != "standard":
|
||||
assert any(h.dpf != hd.DPF_RESPONSE and h.dst == RADIO for h in headers), "application ACK"
|
||||
stack.net.to_peer(PEER, frames) # the radio repeats it: the app does not get it twice
|
||||
assert len(term.got(odtp.MESSAGE_TEXT)) == 1
|
||||
|
||||
|
||||
def test_dmr_standard_text_to_the_app():
|
||||
_text_to_the_app("standard")
|
||||
|
||||
|
||||
def test_mototrbo_tms_text_to_the_app():
|
||||
_text_to_the_app("tms")
|
||||
|
||||
|
||||
def test_hytera_tmp_text_to_the_app():
|
||||
_text_to_the_app("hytera")
|
||||
|
||||
|
||||
def test_reply_goes_in_the_format_the_radio_wrote_in():
|
||||
stack, term = _up()
|
||||
stack.net.to_peer(PEER, _radio("tms", "hola"))
|
||||
stack.advance(2.0)
|
||||
stack.net.dmrd.clear()
|
||||
term.send(odtp.MESSAGE_TEXT, odtp.text_message(TERMINAL_ID, RADIO, "respuesta"))
|
||||
stack.advance(1.0)
|
||||
[(_header, user)] = _packets(stack.net.dmrd)
|
||||
msg = ip_sms.parse_ip_udp(user)
|
||||
assert msg.port == ip_sms.PORT_TMS and ip_sms.tms_parse(msg.payload).text == "respuesta"
|
||||
|
||||
|
||||
def test_group_text_both_ways():
|
||||
stack, term = _up()
|
||||
term.send(odtp.MESSAGE_TEXT, odtp.text_message(TERMINAL_ID, 213, "a todos", group=True))
|
||||
stack.advance(1.0)
|
||||
[(header, user)] = _packets(stack.net.dmrd)
|
||||
assert header.group and header.dst == 213 and header.dpf == hd.DPF_UNCONFIRMED
|
||||
assert "unit" not in {parse_dmrd_header(f).call_type for f in stack.net.dmrd}
|
||||
assert ip_sms.standard_sms_parse(ip_sms.parse_ip_udp(user).payload) == "a todos"
|
||||
stack.net.dmrd.clear()
|
||||
payload = ip_sms.ip_udp(RADIO, 213, ip_sms.PORT_DMR_STANDARD_SMS, ip_sms.standard_sms("hola grupo"), 7, dst_net=225)
|
||||
blocks, pad = build_blocks(payload, rate34=False, confirmed=False)
|
||||
h = hd.DataHeader(dpf=hd.DPF_UNCONFIRMED, dst=213, src=RADIO, sap=hd.SAP_IP, group=True,
|
||||
pad_octets=pad, blocks_to_follow=len(blocks)).to_bytes()
|
||||
stack.net.to_peer(PEER, data_frames(h, blocks, RADIO, 213, int.from_bytes(PEER, "big"), 2, group=True))
|
||||
assert [odtp.parse_text_message(p) for p in term.got(odtp.MESSAGE_TEXT)] == [(RADIO, 213, True, "hola grupo")]
|
||||
stack.advance(1.0)
|
||||
assert stack.net.dmrd == [], "no ACK to a group text"
|
||||
|
||||
|
||||
def test_location_goes_to_the_d_aprs_id_as_nmea_data_at_most_every_10_s():
|
||||
stack, term = _up(settings=OdtpSettings(location_dst=900999))
|
||||
report = struct.pack("<IIH", 0, 0, len(NMEA)) + NMEA
|
||||
term.send(odtp.LOCATION_REPORT, report)
|
||||
stack.advance(1.0)
|
||||
[(header, user)] = _packets(stack.net.dmrd)
|
||||
assert (header.dpf, header.src, header.dst, header.group) == (hd.DPF_UNCONFIRMED, TERMINAL_ID, 900999, False)
|
||||
assert user.rstrip(b"\x00") == NMEA + b"\r\n"
|
||||
term.send(odtp.LOCATION_REPORT, report)
|
||||
stack.advance(1.0)
|
||||
assert len(_packets(stack.net.dmrd)) == 1
|
||||
stack.advance(9.0)
|
||||
term.send(odtp.LOCATION_REPORT, report)
|
||||
stack.advance(1.0)
|
||||
assert len(_packets(stack.net.dmrd)) == 2
|
||||
@ -0,0 +1,176 @@
|
||||
"""ODTP gateway against a real HBP MASTER (HBPProtocol), with a manual clock and no sockets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import struct
|
||||
from collections import deque
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from adn_server.application.odtp.gateway import OdtpGateway
|
||||
from adn_server.application.odtp.ports import OdtpSettings
|
||||
from adn_server.domain import odtp
|
||||
from adn_server.infrastructure.config_normalizer import ensure_system_runtime_config
|
||||
from adn_server.infrastructure.twisted_adapters.udp_hbp import HBPProtocol
|
||||
|
||||
PASSWORD = b"s3cret"
|
||||
TERMINAL_ID = 2130035
|
||||
PEER = (TERMINAL_ID * 100 + 98).to_bytes(4, "big")
|
||||
|
||||
|
||||
class FakeClock:
|
||||
def __init__(self) -> 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("<IB", number, odtp.SERVICE_OPEN_TERMINAL) + b"Z3DMR 1.9.9")
|
||||
for salt in self.got(odtp.CHALLENGE)[-1:]:
|
||||
self.send(odtp.AUTHENTICATION, hashlib.sha256(salt + password).digest())
|
||||
|
||||
def subscribe(self, tg: int, kind: int = odtp.SESSION_TYPE_GROUP_VOICE, add: bool = True) -> None:
|
||||
self.send(odtp.SUBSCRIPTION if add else odtp.CANCELLING, struct.pack("<II", kind, tg))
|
||||
|
||||
|
||||
class _Socket:
|
||||
def __init__(self) -> 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()
|
||||
Loading…
Reference in new issue