Commit Graph
22 Commits
Author SHA1 Message Date
Audric e120951382 TrunkLink: sticky per-transmission socket selection with failover (PAIRED=1) 2026-04-15 22:18:32 +02:00
Audric 17bed97d1c TrunkLink: accept multiple inbound connections when PAIRED=1
Add PairedInboundState struct (parallel to PairedClientState) and
m_ib_states vector to track per-inbound heartbeat/hello state.
acceptInboundConnection branches on m_paired: in paired mode, push
each new inbound into m_ib_cons/m_ib_states, wire a lambda frameReceived
handler to onPairedInboundFrame, and send the hello reply immediately.
Non-paired path is unchanged.

Add onPairedInboundFrame (mirrors onPairedOutboundFrame: resets hb_rx_cnt,
dispatches data messages to shared handlers), onPairedInboundDisconnected
(removes by index from both vectors without deleting — Reflector owns the
object), pairedInboundIndex (linear scan), and sendMsgOnPairedInbound
(mirrors sendMsgOnPairedOutbound).

Route onInboundDisconnected through the paired handler when m_paired.
Update sendMsg paired fallback to iterate m_ib_cons instead of calling
the legacy sendMsgOnInbound. Update heartbeatTick paired branch to iterate
m_ib_cons/m_ib_states instead of m_inbound_con scalars. Update
isInboundReady to check m_ib_states in paired mode. Destructor clears
m_ib_cons/m_ib_states without deleting connections.
2026-04-15 22:08:55 +02:00
Audric 70195e10c3 TrunkLink: open one outbound per host when PAIRED=1
For each host in m_peer_hosts, create a FramedTcpClient with its own
connected/disconnected/frameReceived signal wiring and per-client
PairedClientState (hello_received, hb_tx_cnt, hb_rx_cnt).

- onPairedOutboundConnected: resets per-client state, enables heartbeat
  timer, sends MsgTrunkHello on that client
- onPairedOutboundDisconnected: resets per-client state; TcpPrioClient
  auto-reconnects
- onPairedOutboundFrame: per-client RX counter reset; dispatches
  MsgTrunkHello (HMAC verify, sets hello_received) and MsgTrunkHeartbeat
  inline; all other message types forwarded to shared handlers via ss
  (already positioned past header)
- sendMsgOnPairedOutbound(idx): serialises and writes on m_ob_cons[idx]
- pairedClientIndex: linear scan returning SIZE_MAX on miss
- sendMsg: paired branch iterates m_ob_cons in order, picks first with
  connected+hello_received (D4 will make this sticky); falls back to
  inbound
- heartbeatTick: paired branch iterates per-client counters; legacy OB
  block untouched; "disable timer" check uses any_ob_connected flag
- isOutboundReady: returns true if any paired client is ready
- ~TrunkLink: disconnects and deletes all m_ob_cons entries

Single-host path is unchanged; all new code is inside m_paired branches.
2026-04-15 21:54:25 +02:00
Audric adfe04e8b1 TrunkLink: parse PAIRED=1 + multi-host HOST list (no behavior yet) 2026-04-15 21:41:51 +02:00
Audric 6fb5aa4b91 TwinLink: mirror external trunk-talker state to partner
When TrunkLink receives MsgTrunkTalkerStart/Stop from an external peer,
Reflector now forwards those events to TwinLink via
notifyExternalTrunkTalkerStart/Stop.  TwinLink sends MsgTwinExtTalkerStart
(type 123) / MsgTwinExtTalkerStop (type 124) over the twin link, and the
receiving side calls TGHandler::setTrunkTalkerForTGViaPeer so the partner
twin blocks local clients from keying up the TG.  On disconnect,
clearPeerTalkerState iterates held TGs before clearing them so the partner
is also notified.  No echo loop: Reflector::onTrunkTalkerUpdated does not
feed back into TwinLink.
2026-04-15 21:30:14 +02:00
Audric ba3b100361 Fix 4 pre-existing legacy-test failures
Three distinct root causes, all pre-existing on master and confirmed
there with the same symptoms:

1. tests/generate_configs.py was missing COMMAND_PTY=, so the reflector
   never opened its admin PTY. Every PTY-driven test (MUTE, UNMUTE, CFG,
   TRUNK RELOAD) wrote to a regular file that nobody read. Adding the
   config entry makes those commands actually reach the reflector, fixing
   test_24_pty_trunk_mute and test_25_pty_trunk_reload.

2. TrunkLink::statusJson built active_talkers by iterating the global
   trunk-talker map and filtering by isSharedTG(tg), which checks the
   peer's remote_prefix. When TG_MAP remaps a peer-owned wire TG to a
   local-owned TG, the local TG no longer matches the peer's prefix, so
   the view silently dropped it. Iterate m_peer_active_tgs directly
   instead — that set already contains post-remap local TGs for this
   specific peer. Fixes test_22_tg_map_remap_in.

3. Python test harness parsed MsgTrunkNodeList vector-length prefixes as
   u32 ('!I'), but AsyncMsg.h MsgPacker<std::vector> emits u16 lengths.
   The parser mis-read into garbage at huge offsets and crashed with a
   struct.error. Switch read_vec_str/u32/f32 to u16 ('!H') to match the
   wire format. Fixes test_27_node_list_emitted.

Legacy suite: 27/27 passing (was 23/27).
Redis suite: 10/10 still passing.
2026-04-15 15:59:36 +02:00
Audric bc412e1847 Remove Redis mute plumbing; expose mute list in /status JSON
Dashboard will write mutes directly to the PTY rather than Redis; the
Redis addTrunkMute/removeTrunkMute/loadTrunkMutes methods and the PTY
write-through were unused. Mute state is now reflected in the /status
JSON as a per-trunk 'muted' array so operators and dashboards can see
current state without polling Redis.
2026-04-15 13:45:00 +02:00
Audric 11751a08ed TrunkLink reads filters/mutes from Redis when [REDIS] is configured 2026-04-15 09:04:49 +02:00
Audric 5708e2d0e8 Merge jayReflector additions: per-trunk filters, node-list, PTY mute
Ports DJ1JAY / FM-Funknetz' jayReflector features (https://github.com/dj1jay/jayReflector)
into GeuReflector while keeping the in-process MqttPublisher.

Per-trunk config (TrunkLink): BLACKLIST_TGS, ALLOW_TGS, TG_MAP (with
explicit-route bypass of the prefix routing check), PEER_ID. New helpers
TgFilter.h provide exact / "24*" / "10-20" syntax shared across keys.

Wire protocol (additive, backward compatible — older peers ignore unknown
types): MsgTrunkNodeList (type 121) carries callsign + current_tg + optional
lat/lon/QTH; MsgTrunkFilter (type 122) reserved for satellite TG filters.

Reflector emits debounced (500 ms) MsgTrunkNodeList to all trunk peers on
local client login/logout/TG change. Inbound lists are republished via MQTT
under nodes/<peer_id>; the local list under nodes/local. New MQTT_NAME global
key inserts a path component so several reflectors can share a TOPIC_PREFIX.

PTY commands (Reflector): TRUNK MUTE|UNMUTE <section> <callsign>,
TRUNK RELOAD [<section>] re-reads BLACKLIST_TGS/ALLOW_TGS/TG_MAP without
restart, TRUNK STATUS [<section>] dumps a one-line summary per link.
Mute is applied on the inbound audio path.

Tests: 8 new integration tests (19-27) plus a TEST_PEER_FILTER fixture in
topology.py. Tests cover PEER_ID hello, BLACKLIST/ALLOW/TG_MAP semantics,
PTY MUTE/RELOAD/STATUS via docker exec, MQTT_NAME topic namespacing, and
node-list emission. Total now 27 tests.

Docs: docs/JAY-additions.md credits DJ1JAY / FM-Funknetz and lists every
merged feature with file pointers and the filter-evaluation order.
README.md links it. svxreflector.conf.in documents every new key.

Bumps SVXREFLECTOR to 1.3.99.13+trunk.
2026-04-14 23:48:03 +02:00
Audric 5b7a3dd8cd Wire MqttPublisher into Reflector event handlers 2026-04-08 20:32:02 +02:00
Audric 175cb15254 Ignore duplicate hello on inbound trunk connection
handleMsgTrunkHello was called for hellos arriving on both outbound
and inbound connections. Inbound hellos are already handled by
acceptInboundConnection, so a second one arriving via onFrameReceived
(e.g. from TcpPrioClient background reconnect) is a duplicate.
Silently ignore it instead of printing a misleading double hello log.
2026-04-08 17:33:04 +02:00
Audric 05c4c88ff3 Require matching trunk section names and cap audio debug at 500 frames
Trunk link matching now requires the peer's hello ID (section name) to
match the local [TRUNK_x] section name. Both sides of a trunk link must
use the same section name, agreed upon by both sysops. This replaces
the previous matching by secret+prefix only.

BREAKING CHANGE: existing deployments must rename their [TRUNK_x]
sections so both sides use the same name for each link.

Also cap TRUNK_DEBUG audio frame logging at 500 frames per trunk link
to prevent excessive log output during sustained transmissions.
2026-04-05 18:22:04 +02:00
Audric 638d3c527e Add TRUNK_DEBUG option for verbose trunk connection diagnostics
Add TRUNK_DEBUG=1 config option in [GLOBAL] that enables detailed
logging of trunk connection lifecycle: state on connect/disconnect,
heartbeat countdown warnings near timeout, every non-heartbeat frame
with direction and type, send path decisions, and prefix matching
details on the trunk server. Helps diagnose connection issues
reported in #1 where the remote side kills connections.
2026-04-05 11:55:43 +02:00
Audric 7d1aeff623 Fix trunk reconnect storm with per-IP pending connection limit
When two trunk peers simultaneously reconnect, rapid retries from one
peer could fill the global pending connection pool (5 slots), starving
other peers and creating a reject→reconnect→reject loop.

Add a per-IP limit of 2 pending (pre-hello) connections in the trunk
server, so one misbehaving or rapidly-reconnecting peer cannot exhaust
the pool.  Also increase outbound reconnect backoff (2s min, 30s max)
to reduce retry pressure after connection failures.
2026-03-29 19:47:17 +02:00
Audric accb4b3686 Fix bidirectional trunk routing and monitoring client notifications
Two bugs prevented real-world trunk conversations from working:

1. onTrunkTalkerUpdated only notified clients selected on a TG, not
   clients monitoring it. SvxLink repeaters monitoring a foreign TG
   never received MsgTalkerStart and could not auto-switch. Fixed by
   adding TgMonitorFilter to trunk talker broadcasts, matching the
   existing behavior of onTalkerUpdated for local talkers.

2. Trunk TG routing was one-way: when a client visited a foreign TG,
   isSharedTG forwarded to the owner, but the owner had no return
   path. Added per-link peer interest tracking — when a peer sends
   MsgTrunkTalkerStart for a TG, the receiving side records interest
   and forwards local activity on that TG back. Interest refreshes
   on audio, expires after 10 minutes idle, clears on disconnect.

New integration test verifies the full round-trip: client-A talks on
a foreign TG, monitoring client-B receives the notification, client-B
replies, and client-A receives audio back through the trunk.
2026-03-28 19:09:38 +01:00
Audric 685d7253ff Fix trunk receive-side TG filtering and add integration test suite
The receive-side handlers (handleMsgTrunkTalkerStart, handleMsgTrunkAudio,
etc.) used isSharedTG() which only checks the remote peer's prefix. This
caused non-cluster TGs to be silently dropped on the receiving reflector —
e.g. a client on reflector-a talking on TG 40001 (owned by reflector-b)
would never reach reflector-b because reflector-b checked the TG against
reflector-a's prefix instead of its own.

Add isOwnedTG() that accepts TGs matching either the local or remote
prefix, and use it in all four receive handlers. The send-side still uses
isSharedTG() (remote prefix only) which is correct.

Also add a Docker-based integration test suite (tests/) with 11 automated
tests covering handshake, routing, cross-reflector audio delivery, cluster
TGs, heartbeat, disconnect cleanup, and trunk-to-trunk isolation. An
interactive mode lets users test arbitrary TG numbers with routing verified
via reflector logs. Topology is defined once in tests/topology.py.

Fix Dockerfile to copy built shared libraries to the runtime image.
2026-03-27 14:43:57 +01:00
Audric 3b7831c307 Decouple outbound and inbound trunk connections
The previous design treated outbound and inbound as mutually exclusive
via a ConDir state machine, causing a rapid reconnect loop when both
peers tried to connect simultaneously. Now both connections coexist
independently: outbound (TcpPrioClient, auto-reconnects) and inbound
(accepted from peer) each have their own hello state and heartbeat
counters. Data messages route through outbound with inbound as fallback.
2026-03-26 15:44:45 +01:00
Audric b8d0dd19af Add trunk TCP server for bidirectional peer connections
Previously TrunkLink only connected outbound — there was no server
listening on port 5302, so both reflectors got "Connection refused."

Changes:
- Reflector: add trunk TcpServer (default port 5302, configurable
  via TRUNK_LISTEN_PORT) that accepts inbound peer connections,
  authenticates via HMAC, and matches by secret + prefix
- TrunkLink: support both outbound and inbound directions with
  automatic conflict resolution (lower priority keeps outbound)
- Security: pre-auth frame size cap (4KB), max 5 pending connections,
  10s hello timeout, log-injection sanitization
- Docs: updated TRUNK_PROTOCOL.md, README.md, CLAUDE.md
2026-03-26 12:59:04 +01:00
Audric 53a9a6fc75 Support overlapping TG prefixes with longest-prefix-match routing
isSharedTG now finds the longest matching remote prefix and verifies
no other prefix in the mesh is more specific. Each TrunkLink receives
the full set of all prefixes at startup via setAllPrefixes().
initTrunkLinks is split into two passes: collect all prefixes first,
then create links with full knowledge.
2026-03-26 10:55:47 +01:00
Audric 551cfa70cd Implement satellite reflectors
Satellite reflectors are lightweight relay instances that connect to a
parent reflector instead of joining the full trunk mesh. Clients connect
to the satellite normally; it relays all TGs bidirectionally to the
parent. The parent forwards satellite events to local clients, trunk
peers, and other satellites.

New classes:
- SatelliteLink: parent-side handler for each inbound satellite
  connection (HMAC auth, heartbeat, all-TG relay)
- SatelliteClient: satellite-side outbound connection to parent

Wire protocol: MsgTrunkHello gains m_role field (ROLE_PEER=0,
ROLE_SATELLITE=1) to distinguish satellite handshakes.

Config:
- Parent: [SATELLITE] section with LISTEN_PORT and SECRET
- Satellite: SATELLITE_OF, SATELLITE_PORT, SATELLITE_SECRET in [GLOBAL]

HTTP /config endpoint now shows mode (reflector/satellite),
satellite_server config on parents, and satellite connection info.

Docs updated: README, DEPLOYMENT_ITALY, Italian translation.
2026-03-20 13:53:17 +01:00
Audric 166e57f445 Implement cluster TGs and /config HTTP endpoint
Cluster TGs (BrandMeister-style): talk groups broadcast to all trunk
peers regardless of prefix ownership. Configured via CLUSTER_TGS in
[GLOBAL]. Routing checks in TrunkLink now accept isSharedTG || isClusterTG
for all 8 inbound/outbound handlers. Validated at startup to not overlap
with any LOCAL_PREFIX or REMOTE_PREFIX.

New GET /config endpoint returns static configuration (local_prefix,
cluster_tgs, listen_port, http_port, trunk peers) for dashboard use.

Docs: cluster TG sections added to README, DEPLOYMENT_ITALY, and
Italian translation. Design doc for satellite reflectors and cluster
TGs added.
2026-03-20 12:41:26 +01:00
Audric fca7c33794 Security hardening: fix 19 of 22 vulnerabilities found in audit
Critical:
- Trunk HMAC-SHA1 auth: MsgTrunkHello now carries nonce+digest,
  peer disconnected on secret mismatch (was loaded but never verified)

High:
- Pre-hello guard: reject all trunk messages before handshake completes
- CSPRNG for password generator: random.choice -> secrets.choice

Medium:
- Path traversal protection on callsign-based file operations
- Replace assert() on network-derived UDP data with error handling
- HTTP server connection throttling (matching main TCP server)
- try/catch on regex compilation in callsignOk()/emailOk()
- Per-link trunk talker tracking (clearAllTrunkTalkers scoped to peer)
- Regenerate priority nonce on each new trunk connection
- Cap active TGs and trunk talkers at 10000 each
- Don't reset heartbeat for unauthenticated client app messages
- Fix RENEW_AFTER integer division (2/3 -> 2.0/3.0)

Low:
- JSON-escape HTTP method in error response
- snprintf for pidfile error message
- MsgAuthResponse::digest() null check on empty vector
- Check unpack() return values in AsyncMsg.h vector/map/string
- Replace stack VLA with std::string; reserve+push_back vs resize
- Require TalkerStart before accepting trunk audio
2026-03-20 11:54:18 +01:00