From 742f9d46dcc31ca645e5f6cd4bd8d12fc4d5d18f Mon Sep 17 00:00:00 2001 From: bjorne Date: Wed, 18 Nov 2026 22:15:30 +0100 Subject: [PATCH] sync svxdr source from dev + beginner-friendly INSTALL howto MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - svxdr/: full current source (lastheard 24h/live split + pagination cap, operator location pass-through to both boxes, per-over history, write-once location). builds clean (CGO_ENABLED=0 go build). listen module included. - INSTALL.md: 'Before you begin' prerequisites checklist, per-step ✓ Check lines, and a final 'Done — does it all work?' end-to-end verification. No hardcoded secrets/IPs/logins — scanned clean. --- INSTALL.md | 66 ++++ svxdr/astmeta/astmeta.go | 9 - svxdr/config/config.go | 51 ++- svxdr/deploy/svxdr-import.py | 242 ++++++++++++ svxdr/deploy/svxdr.service | 21 + svxdr/go.mod | 2 +- svxdr/listen/listen.go | 602 ++++++++++++++++++++++++++++ svxdr/main.go | 24 +- svxdr/nodelist/local_trunks.go | 9 - svxdr/nodelist/monitor_nodes.go | 17 +- svxdr/nodelist/nodelist.go | 676 ++++++++++++++++++++++++++++---- svxdr/nodelist/nodes.go | 9 - svxdr/nodelist/nodes_flat.go | 9 - svxdr/nodelist/svxdrcfg.go | 97 ++++- svxdr/proxy/proxy.go | 9 - svxdr/statusnorm/statusnorm.go | 9 - 16 files changed, 1673 insertions(+), 179 deletions(-) create mode 100644 svxdr/deploy/svxdr-import.py create mode 100644 svxdr/deploy/svxdr.service create mode 100644 svxdr/listen/listen.go diff --git a/INSTALL.md b/INSTALL.md index 1388259..e667142 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -43,6 +43,33 @@ everywhere you see it. --- +## Before you begin — the 5-minute checklist + +Have these ready **first**. If one is missing, sort it out before step 0 or you +will get stuck halfway. + +- [ ] **A server** on Debian 12/13 or Ubuntu 24.04 where you have `sudo`/root. + A small 1 GB VPS or Raspberry Pi is plenty. +- [ ] **A domain name** (e.g. `svxportal.example.com`) with a DNS **A record** + pointing at the server's **public IP**. The login cookie is HTTPS-only, and + HTTPS needs a real name — a bare IP will **not** work. +- [ ] **Ports 80 and 443 reachable** from the internet (80 to get the TLS + certificate, 443 for the site itself). +- [ ] **A running SvxReflector** on this machine (or reachable from it), with + its HTTP status port enabled (`HTTP_SRV_PORT`, we use `8099`). No reflector + yet? Build GeuReflector first — see the link in step 9. +- [ ] About **30 minutes**. + +You do **not** need Docker, Node.js, composer, or any framework. Decide your +real host name now and type it wherever this guide shows `svxportal.example.com`. + +> **Lost on a step?** Most steps end with a `✓ Check:` line — the one thing to +> run to prove that step worked before moving on. If a check fails, fix that +> step before continuing; don't push forward hoping it sorts itself out. The +> very last section, **Done — does it all work?**, re-checks the whole thing. + +--- + ## 0. Get the code ```bash @@ -53,6 +80,9 @@ cd reflector-dashboard All paths below are relative to this checkout unless they start with `/`. +> **✓ Check:** `ls auth lib install svxdr index.html` lists them all — you are +> in the right folder. + ## 1. Packages Everything the web, Redis, TLS and svxdr need, in one go: @@ -87,6 +117,9 @@ sudo find /var/www/html/svxportal -type d -exec chmod 2775 {} + sudo find /var/www/html/svxportal -type f -exec chmod 0644 {} + ``` +> **✓ Check:** `ls -l /var/www/html/svxportal/index.html` exists and is owned by +> `www-data`. + ## 3. Redis (dedicated instance, unix socket) ```bash @@ -184,6 +217,11 @@ If you do not have one, add an SMTP relay instead and no MTA is needed: `config.php` is listed in `.gitignore` and is never served by nginx (all `*.php` go to PHP-FPM, which just executes `return [...]`). Keep it mode 640. +> **✓ Check:** +> `sudo -u www-data php -r '$c=require "/var/www/html/svxportal/auth/config.php"; echo $c["redis"]["unix_socket"],"\n";'` +> prints your socket path with **no** PHP error (a parse error means a typo in +> `config.php`). + ## 6. Talkgroup list file The talkgroup list is a JSON file the portal reads and writes: @@ -196,6 +234,9 @@ sudo systemd-tmpfiles --create /etc/tmpfiles.d/svxportal-tglist.conf This creates `/etc/svxlink/tglist.json` owned by `www-data`. The path is `tglist_file` in `config.php`; change both if you want it elsewhere. +> **✓ Check:** `ls -l /etc/svxlink/tglist.json` exists and is owned by +> `www-data`. + ### 6b. Optional: follower box that mirrors another portal's talkgroup list If you run several reflectors and want ONE talkgroup list, one portal is the @@ -275,6 +316,9 @@ Answer the prompts (callsign, e-mail, password, admin level). Levels: Log in on the web page with that callsign. The **Admin** menu appears. +> **✓ Check:** you can sign in with that callsign and the **Admin** menu is +> visible in the top bar. (If sign-in 500s, it's Redis — see section 11.) + ## 9. Live data backend: svxdr The dashboard (node list, map, monitor, last-heard, trunks) fetches JSON and @@ -393,6 +437,28 @@ with this portal: PKI/CA paths, `COMMAND_PTY`, `HTTP_SRV_PORT`, the `[USERS]`/`[PASSWORDS]` layout the helper edits, MQTT, and trunk/satellite sections. All secrets and hostnames in it are placeholders. +## Done — does it all work? + +Walk this once. Each line is something a visitor actually relies on; the arrow +says which step fixes it if it's red. + +1. **`https://YOUR.HOST.NAME/` loads** and shows the dashboard (not a 404, not a + cert warning). → nginx + web files + TLS (steps 2, 7). +2. **Sign in** on a wrong password gives a clean "wrong password", **not a 500**. + → Redis + PHP-FPM + config (steps 3, 4, 5). +3. **You can log in** as the admin you made, and the **Admin** menu shows. → step 8. +4. **The front page is live, not empty** — node list, map, last-heard show data. + Confirm the backend directly: + ```bash + curl -s http://127.0.0.1:8098/healthz # -> ok + curl -s http://127.0.0.1:8098/api/status | head -c 120 # -> JSON, not empty + ``` + → svxdr (step 9). Empty page + 404 on `/svxportal/api/status` = svxdr not running. +5. **Registering a test account sends the verification e-mail.** → mail (step 5). + +All five green → you're live. Any red → go to the step the arrow names, then the +checklist below. + ## 11. Checklist when something does not work - **500 on any `auth/*.php`**: `sudo tail -f /var/log/nginx/svxportal-error.log` and `journalctl -u php8.4-fpm`. Usually Redis auth or missing `php-redis`. diff --git a/svxdr/astmeta/astmeta.go b/svxdr/astmeta/astmeta.go index 35e97c2..3bbd006 100644 --- a/svxdr/astmeta/astmeta.go +++ b/svxdr/astmeta/astmeta.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - // Package astmeta is the svxdr astmeta subsystem — AllStar talker metadata, // folded in from the standalone svx-web/astmeta. It polls AMI (rpt xnode) for // keyed remote nodes, resolves callsign/system, feeds svxlink UsrpLogic (USRP), diff --git a/svxdr/config/config.go b/svxdr/config/config.go index de3c768..51047ff 100644 --- a/svxdr/config/config.go +++ b/svxdr/config/config.go @@ -1,19 +1,10 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - // Package config is the ONE config for svxdr — the merged svx daemon // (astmeta + nodelist + proxy + xlink). Lives at /etc/svxlink/svxdr.json. // // One file, sectioned per subsystem plus shared sections (redis, nodes, trunk, // lastheard). Read at start and on reload (SIGHUP / file-watch) and held in // memory. `modules` toggles which subsystems run on this box, so the same -// binary runs all of them on a reflector box and only astmeta on an AllStar bridge box. +// binary runs all of them on speed/aldmr and only astmeta on the allstar box. // // Secrets carry an @@PLACEHOLDER@@ that deploy-remote.sh --conf fills from the // live file per box, so the structure is one file but secrets differ per host. @@ -43,6 +34,39 @@ type Config struct { Proxy Proxy `json:"proxy"` Xlink Xlink `json:"xlink"` Tglist Tglist `json:"tglist"` // shared canonical TG->name list source + Listen Listen `json:"listen"` // Listen Live WS supervisor +} + +// Listen — the "Listen Live" WebSocket audio supervisor (was svx-listen.json). +// Folded into svxdr; the C++ svx-sat-bridge stays a child process (Bridge = its +// path). Nothing hardcoded: satellite host/port/secret/id, WS addr, policy and +// limits all come from here so any site runs it against its own reflector. +type Listen struct { + Addr string `json:"addr"` // WS listen address, default 127.0.0.1:8787 + Bridge string `json:"bridge"` // path to svx-sat-bridge (required) + Satellite ListenSat `json:"satellite"` + Policy ListenPolicy `json:"policy"` + MaxTGs int `json:"max_tgs"` // max distinct TGs at once (default 20) + MaxSubsPerTG int `json:"max_subs_per_tg"` // max listeners per TG (default 50) + TglistFile string `json:"tglist_file"` // tglist.json for per-TG listen level (empty = all free) + AuthURL string `json:"auth_url"` // me.php for the "members" login check +} + +// ListenSat — the single satellite login the bridge carries all TGs over. +type ListenSat struct { + Host string `json:"host"` // reflector host (usually 127.0.0.1) + Port int `json:"port"` // reflector satellite port + Secret string `json:"secret"` // shared SATELLITE secret (@@PLACEHOLDER@@) + ID string `json:"id"` // this satellite's id (e.g. "WEBLISTEN") + Priority int `json:"priority"` // tie-break priority (0 is fine) +} + +// ListenPolicy — operator TG guardrails. Entries may be exact ("2403"), prefix +// ("24*") or range ("2427-2438"). AcceptOnly (if non-empty) = ONLY these TGs may +// be listened to; Block = always denied (applied after AcceptOnly). +type ListenPolicy struct { + AcceptOnly []string `json:"accept_only"` + Block []string `json:"block"` } // Modules toggles which subsystems this box runs. Unset (all false) is treated @@ -53,6 +77,7 @@ type Modules struct { Nodelist bool `json:"nodelist"` Proxy bool `json:"proxy"` Xlink bool `json:"xlink"` + Listen bool `json:"listen"` } // Redis — shared connection (as today). @@ -179,6 +204,11 @@ type Nodelist struct { // How often a REMOTE Monitor->Nodes read hits the master status. Kept gentle so // a shared hub is never hammered (local reads stay fast). MonitorInterval Duration `json:"monitor_interval"` + // disable_rewrite_tgs: TGs whose Lastheard Location nodelist must NOT rewrite. + // For these, the Location is passed through from chan_svx_sat's live nodeLocation + // (the real hub operator, or its configured fallback) — never the tglist name, + // never blanked. (A TG simply absent from the tglist already passes through.) + DisableRewriteTGs []int `json:"disable_rewrite_tgs,omitempty"` // external reflector federation (the "which other reflectors we crawl" list) External External `json:"external"` Federation Federation `json:"federation"` @@ -194,6 +224,7 @@ type External struct { StatusPath string `json:"status_path"` ProxyPath string `json:"proxy_path"` DetailPath string `json:"detail_path"` + BridgePath string `json:"bridge_path"` MaxRefs int `json:"max_refs"` StaleTTL Duration `json:"stale_ttl"` } diff --git a/svxdr/deploy/svxdr-import.py b/svxdr/deploy/svxdr-import.py new file mode 100644 index 0000000..dc6659e --- /dev/null +++ b/svxdr/deploy/svxdr-import.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Generate /etc/svxlink/svxdr.json FROM a box's live config — derive, never guess. + +Reads whatever exists on the box and folds it into the one svxdr config: + /etc/default/nodelist -> redis, nodelist, external, federation, xlink, mqtt + /etc/default/svx-proxy -> proxy + /etc/astmeta.conf -> astmeta + /etc/nodes.json -> trunk, lastheard, nodes (the bridge map, if present) + +`modules` is auto-detected from which sources exist (and XLINK_ENABLED). Secrets +are copied verbatim from the live files, so run this ON the box and keep the +output there — never commit it. Unset keys are omitted so svxdr uses its defaults. + +Usage on the box: + sudo python3 svxdr-import.py # prints svxdr.json to stdout + sudo python3 svxdr-import.py | sudo tee /etc/svxlink/svxdr.json >/dev/null +""" +import json +import os +import re +import sys + + +def parse_env(path): + d = {} + try: + f = open(path) + except FileNotFoundError: + return d + with f: + for raw in f: + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + k, v = line.split("=", 1) + d[k.strip()] = v.strip().strip('"').strip("'") + return d + + +def parse_ini(path): + out, sec = {}, "" + try: + f = open(path) + except FileNotFoundError: + return out + with f: + for raw in f: + line = raw.strip() + if not line or line[0] in ";#": + continue + if line.startswith("[") and "]" in line: + sec = line[1:line.index("]")].strip().lower() + out.setdefault(sec, {}) + continue + if "=" in line: + k, v = line.split("=", 1) + if (i := re.search(r"[;#]", v)) is not None: + v = v[: i.start()] + out.setdefault(sec, {})[k.strip().lower()] = v.strip() + return out + + +def put(d, key, val, cast=str): + """Set d[key]=cast(val) only if val is a non-empty source value.""" + if val is None or val == "": + return + d[key] = cast(val) + + +def as_bool(v): + return str(v).lower() in ("1", "true", "yes", "on") + + +def as_int(v): + try: + return int(v) + except ValueError: + return 0 + + +def build(): + nl = parse_env("/etc/default/nodelist") + px = parse_env("/etc/default/svx-proxy") + am = parse_ini("/etc/astmeta.conf") + nodes_doc = {} + if os.path.exists("/etc/nodes.json"): + try: + nodes_doc = json.load(open("/etc/nodes.json")) + except (OSError, ValueError): + nodes_doc = {} + + doc = {} + doc["modules"] = { + "astmeta": bool(am), + "nodelist": bool(nl), + "proxy": bool(px), + "xlink": as_bool(nl.get("XLINK_ENABLED", "")), + } + + # ---- redis (from nodelist env) ---- + if nl: + r = {} + put(r, "socket", nl.get("REDIS_SOCKET")) + put(r, "password", nl.get("REDIS_PASSWORD")) + put(r, "status_key", nl.get("REDIS_STATUS_KEY")) + put(r, "status_hash_key", nl.get("REDIS_STATUS_HASH_KEY")) + put(r, "pubsub_chan", nl.get("REDIS_PUBSUB_CHAN")) + put(r, "nodes_online_key", nl.get("REDIS_NODES_ONLINE_KEY")) + put(r, "node_key_prefix", nl.get("REDIS_NODE_KEY_PREFIX")) + put(r, "node_connect_chan", nl.get("REDIS_NODE_CONNECT_CHAN")) + put(r, "node_disconnect_chan", nl.get("REDIS_NODE_DISCONNECT_CHAN")) + put(r, "node_update_chan", nl.get("REDIS_NODE_UPDATE_CHAN")) + put(r, "lastheard_key", nl.get("REDIS_LASTHEARD_KEY")) + if r: + doc["redis"] = r + + # ---- nodelist ---- + if nl: + n = {} + put(n, "listen_addr", nl.get("LISTEN_ADDR")) + put(n, "reflector_status_url", nl.get("REFLECTOR_STATUS_URL")) + put(n, "monitor_status_url", nl.get("MONITOR_STATUS_URL")) + put(n, "debug", nl.get("DEBUG"), as_bool) + put(n, "poll_interval", nl.get("POLL_INTERVAL")) + put(n, "reflector_log_path", nl.get("REFLECTOR_LOG_PATH")) + put(n, "network_json_path", nl.get("NETWORK_JSON_PATH")) + put(n, "astdb_url", nl.get("ASTDB_URL")) + put(n, "talker_meta_ttl", nl.get("TALKER_META_TTL")) + put(n, "talker_ingest_token", nl.get("TALKER_INGEST_TOKEN")) + put(n, "allstar_nodes_ttl", nl.get("ALLSTAR_NODES_TTL")) + put(n, "node_online_ttl", nl.get("NODE_ONLINE_TTL")) + put(n, "node_ttl", nl.get("NODE_TTL")) + put(n, "mqtt_broker", nl.get("MQTT_BROKER")) + put(n, "mqtt_user", nl.get("MQTT_USERNAME")) + put(n, "mqtt_pass", nl.get("MQTT_PASSWORD")) + put(n, "mqtt_prefix", nl.get("MQTT_TOPIC_PREFIX")) + ext = {} + put(ext, "pull_url", nl.get("EXTERNAL_PULL_URL")) + put(ext, "pull_scheme", nl.get("EXTERNAL_PULL_SCHEME")) + put(ext, "pull_port", nl.get("EXTERNAL_PULL_PORT")) + put(ext, "pull_path", nl.get("EXTERNAL_PULL_PATH")) + put(ext, "pull_interval", nl.get("EXTERNAL_PULL_INTERVAL")) + if nl.get("EXTERNAL_STATUS_PORTS"): + ext["status_ports"] = [p.strip() for p in nl["EXTERNAL_STATUS_PORTS"].split(",") if p.strip()] + put(ext, "status_path", nl.get("EXTERNAL_STATUS_PATH")) + put(ext, "proxy_path", nl.get("EXTERNAL_PROXY_PATH")) + put(ext, "detail_path", nl.get("EXTERNAL_DETAIL_PATH")) + put(ext, "max_refs", nl.get("EXTERNAL_MAX_REFS"), as_int) + put(ext, "stale_ttl", nl.get("EXTERNAL_STALE_TTL")) + if ext: + n["external"] = ext + fed = {} + if nl.get("FEDERATION_SEEDS"): + fed["seeds"] = [s.strip() for s in nl["FEDERATION_SEEDS"].split(",") if s.strip()] + put(fed, "aggregate_url", nl.get("FEDERATION_AGGREGATE_URL")) + put(fed, "aggregate_interval", nl.get("FEDERATION_AGGREGATE_INTERVAL")) + if fed: + n["federation"] = fed + if n: + doc["nodelist"] = n + + # ---- proxy ---- + if px: + p = {} + put(p, "listen", px.get("PROXY_LISTEN")) + put(p, "reflector_status_url", px.get("REFLECTOR_STATUS_URL")) + put(p, "cache_ttl", px.get("PROXY_CACHE_TTL")) + put(p, "fetch_timeout", px.get("PROXY_FETCH_TIMEOUT")) + put(p, "meta_ttl", px.get("PROXY_META_TTL")) + put(p, "ingest_token", px.get("INGEST_TOKEN")) + put(p, "upstream_status_url", px.get("UPSTREAM_STATUS_URL")) + put(p, "forward_talker_url", px.get("FORWARD_TALKER_URL")) + put(p, "sync_interval", px.get("PROXY_SYNC_INTERVAL")) + put(p, "remote_ttl", px.get("PROXY_REMOTE_TTL")) + if p: + doc["proxy"] = p + + # ---- xlink (from nodelist env) ---- + if nl.get("XLINK_BROKER"): + x = {} + put(x, "broker", nl.get("XLINK_BROKER")) + put(x, "user", nl.get("XLINK_USER")) + put(x, "pass", nl.get("XLINK_PASS")) + put(x, "topic", nl.get("XLINK_TOPIC")) + put(x, "origin", nl.get("XLINK_ORIGIN")) + doc["xlink"] = x + + # ---- astmeta (from astmeta.conf) ---- + if am: + ast = am.get("asterisk", {}) + a = {} + put(a, "ami_host", ast.get("ami_host")) + put(a, "ami_port", ast.get("ami_port")) + put(a, "ami_user", ast.get("ami_user")) + put(a, "ami_secret", ast.get("ami_secret")) + if ast.get("ignore_nodes"): + a["ignore_nodes"] = [s.strip() for s in ast["ignore_nodes"].split(",") if s.strip()] + put(a, "poll_interval", ast.get("poll_interval")) + put(a, "hang_time", ast.get("hang_time")) + usr = am.get("usrp", {}) + put(a, "network", am.get("nodelist", {}).get("network")) + put(a, "usrp_target", usr.get("target")) + put(a, "format", usr.get("format")) + put(a, "space_replace", usr.get("space_replace")) + put(a, "refresh_interval", usr.get("refresh_interval")) + lk = am.get("lookup", {}) + put(a, "lookup_enabled", lk.get("enabled"), as_bool) + put(a, "lookup_url", lk.get("url")) + put(a, "cache_ttl", lk.get("cache_ttl")) + rd = am.get("redis", {}) + put(a, "redis_cache", rd.get("enabled"), as_bool) + put(a, "redis_cache_prefix", rd.get("prefix")) + nlst = am.get("nodelist", {}) + put(a, "nodelist_url", nlst.get("url")) + put(a, "nodelist_token", nlst.get("token")) + # peers = "url|token, url|token" (token optional) -> the extra + # /api/talker-meta targets (e.g. the local proxy on :8080). + peers = [] + for part in (nlst.get("peers") or "").split(","): + part = part.strip() + if not part: + continue + url, _, tok = part.partition("|") + url = url.strip() + if url: + peers.append({"url": url, "token": tok.strip()}) + if peers: + a["nodelist_peers"] = peers + if a: + doc["astmeta"] = a + + # ---- shared bridge map (from /etc/nodes.json) ---- + for k in ("trunk", "lastheard", "nodes"): + if k in nodes_doc: + doc[k] = nodes_doc[k] + + return doc + + +if __name__ == "__main__": + json.dump(build(), sys.stdout, indent=2) + sys.stdout.write("\n") diff --git a/svxdr/deploy/svxdr.service b/svxdr/deploy/svxdr.service new file mode 100644 index 0000000..860e978 --- /dev/null +++ b/svxdr/deploy/svxdr.service @@ -0,0 +1,21 @@ +[Unit] +Description=svxdr — merged svx daemon (astmeta + nodelist + proxy + xlink) +After=network-online.target redis-server.service +Wants=network-online.target + +[Service] +Type=simple +# One binary, one config; which subsystems run is decided by "modules" in the +# JSON (or override with flags, e.g. ExecStart=... --nodelist --proxy). +ExecStart=/usr/local/bin/svxdr --config /etc/svxlink/svxdr.json +Restart=on-failure +RestartSec=3 +# Reload config in place (SIGHUP) without dropping the process. +ExecReload=/bin/kill -HUP $MAINPID +# Match the file/socket permissions the old services used (redis socket, logs, +# /var/www network.json). Adjust User/Group to whatever nodelist ran as. +#User=root +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target diff --git a/svxdr/go.mod b/svxdr/go.mod index b79a674..6f40829 100644 --- a/svxdr/go.mod +++ b/svxdr/go.mod @@ -4,13 +4,13 @@ go 1.24.4 require ( github.com/eclipse/paho.mqtt.golang v1.5.1 + github.com/gorilla/websocket v1.5.3 github.com/redis/go-redis/v9 v9.17.2 ) require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/gorilla/websocket v1.5.3 // indirect golang.org/x/net v0.44.0 // indirect golang.org/x/sync v0.17.0 // indirect ) diff --git a/svxdr/listen/listen.go b/svxdr/listen/listen.go new file mode 100644 index 0000000..c742905 --- /dev/null +++ b/svxdr/listen/listen.go @@ -0,0 +1,602 @@ +// svx-web/listen — WebSocket audio supervisor for "Listen Live". +// +// Browsers connect to ws:///listen?tg= and receive raw 16 kHz s16 +// little-endian mono PCM for that talkgroup (WebAudio plays it + runs the FFT). +// +// One single svx-sat-bridge subprocess holds ONE satellite login to the reflector +// and carries ALL TGs. This service: +// - demuxes the bridge's tagged PCM ([tg][n][pcm]) to the right listeners, +// - tracks listeners per TG and tells the bridge the current interest set +// ("I ..." on its stdin) — so the reflector + hub only forward the TGs +// actually being listened to, and stop when the last listener of a TG leaves, +// - enforces a per-site TG policy (accept_only / block) from the config. +// +// NOTHING is hardcoded: the reflector satellite host/port/secret/id, the WS +// address, the TG policy and the limits all come from a JSON config so anyone can +// run this against their own reflector. It refuses to start without the essentials. +// Package listen is the svxdr "Listen Live" WebSocket audio supervisor, folded in +// from the standalone svx-web/listen. The logic is preserved verbatim; only the +// config wiring changed: the JSON file/flags became the svxdr.json "listen" +// section, and main() became Run(ctx, cfg) with graceful ctx shutdown. The C++ +// svx-sat-bridge is still spawned as a child process (config "bridge" path). +package listen + +import ( + "bufio" + "context" + "encoding/binary" + "encoding/json" + "errors" + "io" + "log" + "net/http" + "os" + "os/exec" + "sort" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/gorilla/websocket" + + "svxportal/svxdr/config" +) + +// ── config (everything a site needs — nothing hardcoded) ───────────────────── + +type SatelliteCfg struct { + Host string `json:"host"` // reflector host (usually 127.0.0.1) + Port int `json:"port"` // reflector satellite port + Secret string `json:"secret"` // shared SATELLITE_SECRET + ID string `json:"id"` // this satellite's id (e.g. "WEBLISTEN") + Priority int `json:"priority"` // tie-break priority (0 is fine) +} + +type PolicyCfg struct { + // TG access control. Entries may be exact ("2403"), prefix ("24*") or range + // ("2427-2438"). AcceptOnly: if non-empty, ONLY matching TGs may be listened + // to. Block: matching TGs are always denied (applied after AcceptOnly). + AcceptOnly []string `json:"accept_only"` + Block []string `json:"block"` +} + +type Config struct { + Addr string `json:"addr"` // WS listen address, e.g. "127.0.0.1:8787" + Bridge string `json:"bridge"` // path to svx-sat-bridge + Satellite SatelliteCfg `json:"satellite"` + Policy PolicyCfg `json:"policy"` + MaxTGs int `json:"max_tgs"` // max distinct TGs listened to at once + MaxSubsPerTG int `json:"max_subs_per_tg"` // max listeners per TG + + // Per-TG Listen access, edited in the web admin (Admin -> Listen). The TG list + // file carries a "listen" level per TG: "free" (anyone, default), "members" + // (logged-in accounts only) or "off" (hidden). For "members" TGs the service + // asks AuthURL (the site's me.php) whether the browser's session is logged in, + // forwarding its cookies. Leave TglistFile empty to treat every TG as free. + TglistFile string `json:"tglist_file"` // path to tglist.json (same file the web serves) + AuthURL string `json:"auth_url"` // me.php URL used for the "members" login check +} + +func (c *Config) check() error { + if c.Addr == "" { + c.Addr = "127.0.0.1:8787" + } + if c.Bridge == "" { + return errors.New("config: 'bridge' (path to svx-sat-bridge) is required") + } + s := c.Satellite + if s.Host == "" || s.Port == 0 || s.Secret == "" || s.ID == "" { + return errors.New("config: satellite host/port/secret/id are all required") + } + if c.MaxTGs <= 0 { + c.MaxTGs = 20 + } + if c.MaxSubsPerTG <= 0 { + c.MaxSubsPerTG = 50 + } + return nil +} + +func (c *Config) bridgeArgs() []string { + a := []string{ + "--host", c.Satellite.Host, + "--port", strconv.Itoa(c.Satellite.Port), + "--secret", c.Satellite.Secret, + "--id", c.Satellite.ID, + } + if c.Satellite.Priority != 0 { + a = append(a, "--priority", strconv.Itoa(c.Satellite.Priority)) + } + return a +} + +// ── TG policy matching ─────────────────────────────────────────────────────── + +func matchSpec(spec string, tg int) bool { + spec = strings.TrimSpace(spec) + if spec == "" { + return false + } + if i := strings.IndexByte(spec, '-'); i > 0 { // range "a-b" + lo, e1 := strconv.Atoi(strings.TrimSpace(spec[:i])) + hi, e2 := strconv.Atoi(strings.TrimSpace(spec[i+1:])) + return e1 == nil && e2 == nil && tg >= lo && tg <= hi + } + if strings.HasSuffix(spec, "*") { // prefix "24*" + return strings.HasPrefix(strconv.Itoa(tg), spec[:len(spec)-1]) + } + n, err := strconv.Atoi(spec) // exact + return err == nil && n == tg +} + +func matchAny(specs []string, tg int) bool { + for _, s := range specs { + if matchSpec(s, tg) { + return true + } + } + return false +} + +func (p *PolicyCfg) allows(tg int) bool { + if len(p.AcceptOnly) > 0 && !matchAny(p.AcceptOnly, tg) { + return false + } + if matchAny(p.Block, tg) { + return false + } + return true +} + +// ── per-TG Listen access (admin-editable in the web; read from tglist.json) ── +// +// This is the day-to-day control set in Admin -> Listen; the static accept_only/ +// block above are coarse operator guardrails applied first. A TG's level is +// "free" unless tglist.json says "members" or "off". + +type tgAccess struct { + path string + authURL string + mu sync.Mutex + mtime time.Time + level map[int]string // tg -> "members"|"off" (absent means "free") +} + +func newTgAccess(path, authURL string) *tgAccess { + return &tgAccess{path: path, authURL: authURL, level: map[int]string{}} +} + +// reload re-reads the TG list if it changed on disk. Cheap enough to call per +// request (admin edits show up immediately, no restart). +func (a *tgAccess) reload() { + if a.path == "" { + return + } + st, err := os.Stat(a.path) + if err != nil { + return + } + a.mu.Lock() + defer a.mu.Unlock() + if st.ModTime().Equal(a.mtime) { + return + } + a.mtime = st.ModTime() // set first so a bad read doesn't loop re-parsing + raw, err := os.ReadFile(a.path) + if err != nil { + return + } + var doc struct { + Tgs []struct { + TG int `json:"tg"` + Listen string `json:"listen"` + } `json:"tgs"` + } + if json.Unmarshal(raw, &doc) != nil { + return + } + m := make(map[int]string, len(doc.Tgs)) + for _, t := range doc.Tgs { + switch strings.ToLower(strings.TrimSpace(t.Listen)) { + case "members": + m[t.TG] = "members" + case "off": + m[t.TG] = "off" + } + } + a.level = m +} + +// levelOf returns "free", "members" or "off" for a TG. +func (a *tgAccess) levelOf(tg int) string { + a.reload() + a.mu.Lock() + lv := a.level[tg] + a.mu.Unlock() + if lv == "" { + return "free" + } + return lv +} + +// loggedIn asks the site's auth endpoint (me.php) whether the request's session +// belongs to a logged-in account, forwarding the browser's cookies. Fail-closed: +// any error, or no auth_url configured, means "not logged in". +func (a *tgAccess) loggedIn(r *http.Request) bool { + if a.authURL == "" { + return false + } + req, err := http.NewRequest(http.MethodGet, a.authURL, nil) + if err != nil { + return false + } + if c := r.Header.Get("Cookie"); c != "" { + req.Header.Set("Cookie", c) + } + resp, err := (&http.Client{Timeout: 3 * time.Second}).Do(req) + if err != nil { + return false + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return false + } + var j struct { + LoggedIn bool `json:"logged_in"` + } + if json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&j) != nil { + return false + } + return j.LoggedIn +} + +// ── bridge: the single satellite subprocess ───────────────────────────────── + +type Bridge struct { + cfg Config + hub *Hub + mu sync.Mutex // guards stdin + cmd + stdin io.WriteCloser + cmd *exec.Cmd + closed bool +} + +func newBridge(cfg Config, hub *Hub) *Bridge { return &Bridge{cfg: cfg, hub: hub} } + +// run keeps one bridge alive, respawning it if it exits, until stop(). +func (b *Bridge) run() { + for { + b.mu.Lock() + if b.closed { + b.mu.Unlock() + return + } + cmd := exec.Command(b.cfg.Bridge, b.cfg.bridgeArgs()...) + cmd.Stderr = os.Stderr + stdin, err := cmd.StdinPipe() + if err != nil { + b.mu.Unlock() + log.Printf("bridge: stdin pipe: %v", err) + time.Sleep(2 * time.Second) + continue + } + stdout, err := cmd.StdoutPipe() + if err != nil { + b.mu.Unlock() + log.Printf("bridge: stdout pipe: %v", err) + time.Sleep(2 * time.Second) + continue + } + if err := cmd.Start(); err != nil { + b.mu.Unlock() + log.Printf("bridge: start: %v", err) + time.Sleep(2 * time.Second) + continue + } + b.cmd = cmd + b.stdin = stdin + b.mu.Unlock() + log.Printf("bridge: started (pid %d)", cmd.Process.Pid) + + b.sendInterest(b.hub.activeTGs()) // re-assert interest after a (re)start + b.readLoop(stdout) // blocks until the bridge exits + + _ = cmd.Wait() + log.Printf("bridge: exited — respawning") + b.mu.Lock() + closed := b.closed + b.mu.Unlock() + if closed { + return + } + time.Sleep(1 * time.Second) + } +} + +// readLoop demuxes tagged PCM frames from the bridge: [tg u32 BE][n u16 BE][pcm]. +func (b *Bridge) readLoop(stdout io.Reader) { + r := bufio.NewReaderSize(stdout, 1<<16) + var hdr [6]byte + for { + if _, err := io.ReadFull(r, hdr[:]); err != nil { + return + } + tg := int(binary.BigEndian.Uint32(hdr[0:4])) + n := int(binary.BigEndian.Uint16(hdr[4:6])) + pcm := make([]byte, n*2) + if _, err := io.ReadFull(r, pcm); err != nil { + return + } + b.hub.route(tg, pcm) + } +} + +func (b *Bridge) sendInterest(tgs []int) { + var sb strings.Builder + sb.WriteByte('I') + for _, tg := range tgs { + sb.WriteByte(' ') + sb.WriteString(strconv.Itoa(tg)) + } + sb.WriteByte('\n') + b.mu.Lock() + w := b.stdin + b.mu.Unlock() + if w != nil { + _, _ = io.WriteString(w, sb.String()) + } +} + +func (b *Bridge) stop() { + b.mu.Lock() + b.closed = true + if b.cmd != nil && b.cmd.Process != nil { + _ = b.cmd.Process.Signal(syscall.SIGTERM) + } + b.mu.Unlock() +} + +// ── hub: per-TG listener sets ──────────────────────────────────────────────── + +type sub struct { + ch chan []byte +} + +type Hub struct { + cfg Config + bridge *Bridge + access *tgAccess + mu sync.Mutex + tgs map[int]map[*sub]struct{} +} + +func newHub(cfg Config) *Hub { + return &Hub{ + cfg: cfg, + access: newTgAccess(cfg.TglistFile, cfg.AuthURL), + tgs: map[int]map[*sub]struct{}{}, + } +} + +func (h *Hub) activeTGs() []int { + h.mu.Lock() + out := make([]int, 0, len(h.tgs)) + for tg := range h.tgs { + out = append(out, tg) + } + h.mu.Unlock() + sort.Ints(out) + return out +} + +func (h *Hub) route(tg int, pcm []byte) { + h.mu.Lock() + for s := range h.tgs[tg] { + select { + case s.ch <- pcm: + default: // slow client — drop rather than stall everyone + } + } + h.mu.Unlock() +} + +// add registers a listener on a TG; returns whether the interest set changed. +func (h *Hub) add(tg int) (*sub, bool, error) { + h.mu.Lock() + g := h.tgs[tg] + newTg := g == nil + if newTg && len(h.tgs) >= h.cfg.MaxTGs { + h.mu.Unlock() + return nil, false, errors.New("server busy: too many talkgroups are being streamed") + } + if g == nil { + g = map[*sub]struct{}{} + h.tgs[tg] = g + } + if len(g) >= h.cfg.MaxSubsPerTG { + h.mu.Unlock() + return nil, false, errors.New("server busy: too many listeners on this talkgroup") + } + s := &sub{ch: make(chan []byte, 64)} + g[s] = struct{}{} + h.mu.Unlock() + return s, newTg, nil +} + +// drop removes a listener; returns whether the interest set changed (last leaver). +func (h *Hub) drop(tg int, s *sub) bool { + h.mu.Lock() + g := h.tgs[tg] + changed := false + if g != nil { + if _, ok := g[s]; ok { + delete(g, s) + close(s.ch) + } + if len(g) == 0 { + delete(h.tgs, tg) + changed = true + } + } + h.mu.Unlock() + return changed +} + +// ── websocket ──────────────────────────────────────────────────────────────── + +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 4096, + CheckOrigin: func(*http.Request) bool { return true }, +} + +const ( + writeWait = 10 * time.Second + pongWait = 30 * time.Second + pingPeriod = (pongWait * 9) / 10 +) + +func (h *Hub) handleListen(w http.ResponseWriter, r *http.Request) { + tg, err := strconv.Atoi(r.URL.Query().Get("tg")) + if err != nil || tg <= 0 { + http.Error(w, "bad or missing tg", http.StatusBadRequest) + return + } + if !h.cfg.Policy.allows(tg) { + http.Error(w, "talkgroup not allowed here", http.StatusForbidden) + return + } + // Per-TG access set in the web admin (Admin -> Listen): off = nobody, + // members = logged-in accounts only, free = anyone. + switch h.access.levelOf(tg) { + case "off": + http.Error(w, "this talkgroup is not available for listening", http.StatusForbidden) + return + case "members": + if !h.access.loggedIn(r) { + http.Error(w, "login required to listen to this talkgroup", http.StatusForbidden) + return + } + } + s, changed, err := h.add(tg) + if err != nil { + http.Error(w, err.Error(), http.StatusServiceUnavailable) + return + } + if changed { + h.bridge.sendInterest(h.activeTGs()) + } + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + if h.drop(tg, s) { + h.bridge.sendInterest(h.activeTGs()) + } + return + } + log.Printf("listener + TG%d (%s)", tg, ws.RemoteAddr()) + defer func() { + if h.drop(tg, s) { + h.bridge.sendInterest(h.activeTGs()) + } + _ = ws.Close() + log.Printf("listener - TG%d (%s)", tg, ws.RemoteAddr()) + }() + + // Reader: process pongs/close so a dead/crashed browser is reaped. + go func() { + ws.SetReadLimit(512) + _ = ws.SetReadDeadline(time.Now().Add(pongWait)) + ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(pongWait)) }) + for { + if _, _, err := ws.ReadMessage(); err != nil { + _ = ws.Close() + return + } + } + }() + + ping := time.NewTicker(pingPeriod) + defer ping.Stop() + for { + select { + case pcm, ok := <-s.ch: + if !ok { + return + } + _ = ws.SetWriteDeadline(time.Now().Add(writeWait)) + if err := ws.WriteMessage(websocket.BinaryMessage, pcm); err != nil { + return + } + case <-ping.C: + _ = ws.SetWriteDeadline(time.Now().Add(writeWait)) + if err := ws.WriteMessage(websocket.PingMessage, nil); err != nil { + return + } + } + } +} + +// ── main ───────────────────────────────────────────────────────────────────── + +// fromConfig translates the svxdr.json "listen" section into the supervisor's own +// Config. Kept here so the copied logic below is untouched. +func fromConfig(c *config.Config) Config { + lc := c.Listen + return Config{ + Addr: lc.Addr, + Bridge: lc.Bridge, + Satellite: SatelliteCfg{ + Host: lc.Satellite.Host, Port: lc.Satellite.Port, + Secret: lc.Satellite.Secret, ID: lc.Satellite.ID, + Priority: lc.Satellite.Priority, + }, + Policy: PolicyCfg{AcceptOnly: lc.Policy.AcceptOnly, Block: lc.Policy.Block}, + MaxTGs: lc.MaxTGs, + MaxSubsPerTG: lc.MaxSubsPerTG, + TglistFile: lc.TglistFile, + AuthURL: lc.AuthURL, + } +} + +// Run is the svxdr module entry point: start the WS supervisor + bridge and block +// until ctx is cancelled (graceful stop), mirroring the standalone main(). +func Run(ctx context.Context, c *config.Config) error { + cfg := fromConfig(c) + if err := cfg.check(); err != nil { + return err + } + + hub := newHub(cfg) + bridge := newBridge(cfg, hub) + hub.bridge = bridge + go bridge.run() + + mux := http.NewServeMux() + mux.HandleFunc("/listen", hub.handleListen) + mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok\n")) }) + + srv := &http.Server{Addr: cfg.Addr, Handler: mux} + errc := make(chan error, 1) + go func() { + log.Printf("listen: serving on %s (satellite %s:%d as '%s')", cfg.Addr, + cfg.Satellite.Host, cfg.Satellite.Port, cfg.Satellite.ID) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + errc <- err + } + }() + + select { + case <-ctx.Done(): + log.Print("listen: shutting down") + shutCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _ = srv.Shutdown(shutCtx) + cancel() + bridge.stop() + return nil + case err := <-errc: + bridge.stop() + return err + } +} diff --git a/svxdr/main.go b/svxdr/main.go index 4727579..7624992 100644 --- a/svxdr/main.go +++ b/svxdr/main.go @@ -1,17 +1,8 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - // svxdr — the merged svx daemon: astmeta + nodelist + proxy + xlink in ONE // process, each a subsystem goroutine, toggled per box by /etc/svxlink/svxdr.json. // -// One binary, one config. A reflector box runs all subsystems; a pure AllStar -// bridge box runs only astmeta. Co-located subsystems share memory (no localhost HTTP hop); +// One binary, one config. Runs all subsystems on speed/aldmr; only astmeta on +// the allstar box. Co-located subsystems share memory (no localhost HTTP hop); // the HTTP talker-meta ingest stays for a REMOTE astmeta feeding this box. // // Phase 1 scaffold: config + module toggles + lifecycle (start / SIGHUP reload / @@ -31,6 +22,7 @@ import ( "svxportal/svxdr/astmeta" "svxportal/svxdr/config" + "svxportal/svxdr/listen" "svxportal/svxdr/nodelist" "svxportal/svxdr/proxy" ) @@ -48,6 +40,7 @@ var modules = []module{ {"proxy", func(c *config.Config) bool { return c.Modules.Proxy }, proxy.Run}, {"astmeta", func(c *config.Config) bool { return c.Modules.Astmeta }, astmeta.Run}, {"nodelist", func(c *config.Config) bool { return c.Modules.Nodelist }, nodelist.Run}, + {"listen", func(c *config.Config) bool { return c.Modules.Listen }, listen.Run}, // xlink is not a separate process — it runs inside nodelist, gated by // modules.xlink in svxdr.json (see nodelist/svxdrcfg.go). } @@ -59,6 +52,7 @@ func main() { fNodelist := flag.Bool("nodelist", false, "run nodelist (overrides modules in config)") fProxy := flag.Bool("proxy", false, "run proxy (overrides modules in config)") fXlink := flag.Bool("xlink", false, "run xlink inside nodelist (overrides modules in config)") + fListen := flag.Bool("listen", false, "run the Listen Live supervisor (overrides modules in config)") flag.Parse() cfgPath := *path if cfgPath == "" { @@ -76,10 +70,10 @@ func main() { // If ANY module flag is passed, the flags fully define the set to run on this // box (config "modules" is overridden) — handy for per-box units and testing. - if *fAstmeta || *fNodelist || *fProxy || *fXlink { - cfg.Modules = config.Modules{Astmeta: *fAstmeta, Nodelist: *fNodelist, Proxy: *fProxy, Xlink: *fXlink} - log.Printf("svxdr: module set overridden by flags: astmeta=%v nodelist=%v proxy=%v xlink=%v", - *fAstmeta, *fNodelist, *fProxy, *fXlink) + if *fAstmeta || *fNodelist || *fProxy || *fXlink || *fListen { + cfg.Modules = config.Modules{Astmeta: *fAstmeta, Nodelist: *fNodelist, Proxy: *fProxy, Xlink: *fXlink, Listen: *fListen} + log.Printf("svxdr: module set overridden by flags: astmeta=%v nodelist=%v proxy=%v xlink=%v listen=%v", + *fAstmeta, *fNodelist, *fProxy, *fXlink, *fListen) } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) diff --git a/svxdr/nodelist/local_trunks.go b/svxdr/nodelist/local_trunks.go index 9e08dab..97e310e 100644 --- a/svxdr/nodelist/local_trunks.go +++ b/svxdr/nodelist/local_trunks.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - package nodelist // Monitor → Trunks lists ONLY the trunks THIS reflector is configured to connect diff --git a/svxdr/nodelist/monitor_nodes.go b/svxdr/nodelist/monitor_nodes.go index 2087faa..2785645 100644 --- a/svxdr/nodelist/monitor_nodes.go +++ b/svxdr/nodelist/monitor_nodes.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - package nodelist // Monitor Nodes, the simple way: read ONE reflector /status endpoint that @@ -15,8 +6,8 @@ package nodelist // // Which URL is read is per-box config MONITOR_STATUS_URL (falls back to // REFLECTOR_STATUS_URL): -// hub box → https:///geu/status/ (the master's full view) -// bridge box → http://127.0.0.1:8080/status (its own reflector) +// speed → https://reflector.sm2ampr.net/geu/status/ (the master's full view) +// aldmr → http://127.0.0.1:8080/status (its own reflector) import ( "encoding/json" @@ -309,8 +300,8 @@ func buildMonitor(client *http.Client, generated string) (monStatus, bool) { return monStatus{}, false } // Normalize at ingest: sat-login node callsigns -> per-TG name. Covers the - // case where monitorStatusURL is a foreign master (e.g. a hub box reads a foreign master - // where its satellite nodes federate in). A local read via the proxy is already + // case where monitorStatusURL is a foreign master (e.g. speed reads the SE hub + // where aldmr's sat nodes federate in). A local read via the proxy is already // normalized; re-normalizing is a harmless no-op. body = statusnorm.Normalize(body, renameSatNode) var raw struct { diff --git a/svxdr/nodelist/nodelist.go b/svxdr/nodelist/nodelist.go index 7df1c72..caca65d 100644 --- a/svxdr/nodelist/nodelist.go +++ b/svxdr/nodelist/nodelist.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - // Package nodelist is the svxdr nodelist subsystem — the reflector status crawl, // lastheard, talker-meta API, external federation and xlink, folded in from the // standalone svx-web/nodelist. The logic is preserved verbatim; only config @@ -66,8 +57,20 @@ var ( lastheardKey = env("REDIS_LASTHEARD_KEY", "/registry/svxlink/lastheard") lastheardWindowSec = int64(24 * 60 * 60) + // lastheardMaxRows CAPS the stored history at the newest N key-ups, matching the + // API's max page (so Redis never holds rows the API cannot return — "raderas i + // redis när den är uppe i 1000 som api"). How long that spans depends on traffic. + lastheardMaxRows = int64(1000) reflectorLogPath = env("REFLECTOR_LOG_PATH", "/var/log/svxreflector") + // A local (client) talker whose start never got a matching stop (swallowed + // stop / log rotation / node dropped mid-over) would otherwise keep + // localByTG[tg] > 0 forever, which makes every TRUNK talker on that TG look + // like our own outbound echo and get dropped — i.e. that TG silently vanishes + // from last-heard. Expire any talker 'active' longer than this (real overs are + // seconds) so the counter self-heals. Tunable; 0 disables the safety net. + staleTalkerAge = envDur("STALE_TALKER_AGE", 5*time.Minute) + nodeOnlineTTL = envDur("NODE_ONLINE_TTL", 0) nodeTTL = envDur("NODE_TTL", 0) @@ -122,6 +125,7 @@ var ( externalStatusPath = env("EXTERNAL_STATUS_PATH", "/status") externalProxyPath = env("EXTERNAL_PROXY_PATH", "/proxy_status.php") // dashboard's real per-ref status (nodes+trunks+trunks_UDP+routing) externalDetailPath = env("EXTERNAL_DETAIL_PATH", "/geu/status/") // merged roster with full per-node detail (location/freq/sw), enriches route nodes + externalBridgePath = env("EXTERNAL_BRIDGE_PATH", "/svxportal/api/bridge-nodes") // per-reflector bridge directory; config, not hard-coded (uses EXTERNAL_PULL_SCHEME/PORT too) externalMaxRefs = envInt("EXTERNAL_MAX_REFS", 100) // crawl bound (cycle-safe), 0 = unlimited externalStaleTTL = envDur("EXTERNAL_STALE_TTL", 5*time.Minute) // keep a reflector's last-good trunks this long when its probe times out — smooths flicker; 0 disables retention @@ -266,6 +270,7 @@ type xlinkMsg struct { Backend string `json:"backend"` // display backend: AllStar / SVXLink / trunk … Event string `json:"event"` // start | end TS int64 `json:"ts"` + Location string `json:"location"` // resolved talker location (e.g. "N7FGP/NC via 45225/ecr"), carried svx->svx so a downstream box shows the SAME location the source resolved — it never resolves it itself. callmgr2 ignores unknown fields. } var xlinkClient mqtt.Client @@ -304,7 +309,7 @@ func xlinkStart(rdb *redis.Client) { // xlinkPublishTalker announces a local SVX talker to the mesh (own numbering). // The DMR side gates on its TG map, so publishing every talker is harmless. -func xlinkPublishTalker(callsign, system, trunk, node string, tg int, backend, event string, ts int64) { +func xlinkPublishTalker(callsign, system, trunk, node string, tg int, backend, event string, ts int64, location string) { if xlinkClient == nil || tg <= 0 { return } @@ -312,39 +317,62 @@ func xlinkPublishTalker(callsign, system, trunk, node string, tg int, backend, e backend = "SVXLink" } b, _ := json.Marshal(xlinkMsg{Origin: xlinkOrigin, Network: "svx", - Callsign: callsign, System: system, Trunk: trunk, Node: node, TG: tg, Backend: backend, Event: event, TS: ts}) + Callsign: callsign, System: system, Trunk: trunk, Node: node, TG: tg, Backend: backend, Event: event, TS: ts, Location: location}) xlinkClient.Publish(xlinkTopic, 0, false, b) } -// xlinkOnMessage injects a peer (DMR/AllStar) talker into the SVX lastheard. -// Own-origin and svx-origin messages are ignored (loop guard); injected rows go -// straight to Redis (not the reflector log), so they are never re-published. +// xlinkOnMessage injects a peer talker into the SVX lastheard — a DMR/AllStar +// talker from callmgr2's crosslink, OR an svx talker from ANOTHER svx box (so a +// downstream box shows the SAME location the SOURCE resolved, without resolving it +// itself). Only OWN-origin is dropped (loop guard): an injected row goes straight +// to Redis (never the reflector log), so it is never re-published -> no loop even +// though svx-origin is now allowed. callmgr2 is unaffected (this is receive-side). func xlinkOnMessage(rdb *redis.Client, payload []byte) { var m xlinkMsg if json.Unmarshal(payload, &m) != nil { return } - if m.Origin == xlinkOrigin || m.Network == "svx" || m.Network == "" { - return + if m.Origin == xlinkOrigin || m.Network == "" { + return // own origin (loop) / malformed } if m.Event != "start" || m.TG <= 0 { - return // show on start; the DMR side is authoritative on gating/TG + return // show on start; the source is authoritative on gating/TG } ts := m.TS if ts == 0 { ts = time.Now().Unix() } - backend := m.Backend - if backend == "" { - backend = "DMR" + // Ingress class is box-local AND per-talker ("bara ur sprung, aldrig till"): a + // mesh-injected talker did NOT originate on THIS box, so unless THIS box itself + // bridges the TG AND the callsign is its own bridge node, it entered over the + // trunk — classify it "trunk", never the SOURCE's backend. The source box already + // shows the real class; a receiver shows how it reached that box (trunk). + net := localBridgeModeForTalker(m.TG, m.Callsign) + if net == "" { + net = "trunk" } - writeLastheardEvent(rdb, lastheardEvent{ + // The SOURCE resolved the location (e.g. aldmr's "N7FGP/NC via 45225/ecr"); carry + // it through. Write-once/keepSet means it never overwrites an already-set one, and + // an empty one falls back to the tglist name. + loc := m.Location + if isOperatorLoc(loc) { + // The SOURCE resolved the operator (e.g. aldmr's "N7FGP via 45225/ecr"). Keep it + // per-TG so THIS (downstream) box's locForTG returns it for the 24h log tailer + // too, not only the live feed below — the mesh is the only path the operator + // takes to a box that has no bridge satellite of its own. + setMeshTgLoc(m.TG, loc) + } + if loc == "" { + loc = locForTG(m.TG) + } + // A mesh "peer is talking" signal feeds LIVE only — "who is keyed now" on the + // peer. The 24h history on THIS box is owned by its own log tailer (one row per + // local key-up), so a mesh inject never adds a second 24h row for the same over. + _ = rdb + updateLiveTalker(lastheardEvent{ Ts: ts, Callsign: m.Callsign, TG: m.TG, Duration: 1, - Source: "crosslink", Network: backend, - // Location = the TG's reflector name (e.g. 314093 -> "WHITELIGHTNING"), so a - // cross-linked DMR talker gets the same Location label as an AllStar talker - // on that TG. From nodes[].system (svx_sat.conf), via locForTG's fallback. - Location: locForTG(m.TG), + Source: "crosslink", Network: net, + Location: loc, }) } @@ -1451,14 +1479,28 @@ func crawlBridgeNodes(sources []extSource) map[string]bridgeInfo { continue } seen[host] = true - hp := host - if strings.Contains(host, ":") { - hp = "[" + host + "]" // bracket IPv6 literals + // Bridge-directory URL built from the nodelist config (scheme/port/path), + // exactly like externalPullURLs — nothing hard-coded here either. Each box + // can point it at its own host/port/path via EXTERNAL_PULL_* / EXTERNAL_BRIDGE_PATH. + hostport := host + if externalPullPort != "" { + hostport = net.JoinHostPort(host, externalPullPort) + } else if strings.Contains(host, ":") { + hostport = "[" + host + "]" // bracket bare IPv6 } + scheme := externalPullScheme + if scheme == "" { + scheme = "https" + } + bpath := externalBridgePath + if !strings.HasPrefix(bpath, "/") { + bpath = "/" + bpath + } + bnURL := scheme + "://" + hostport + bpath wg.Add(1) - go func(hp string) { // parallel: whole crawl bounded by one client timeout + go func(bnURL string) { // parallel: whole crawl bounded by one client timeout defer wg.Done() - resp, err := bridgeHTTP.Get("https://" + hp + "/svxportal/api/bridge-nodes") + resp, err := bridgeHTTP.Get(bnURL) if err != nil { return } @@ -1478,7 +1520,7 @@ func crawlBridgeNodes(sources []extSource) map[string]bridgeInfo { } } mu.Unlock() - }(hp) + }(bnURL) } wg.Wait() return out @@ -1612,6 +1654,9 @@ func tglistPuller(ctx context.Context, c *config.Config) { m[e.TG] = s } } + // NOTE: the tglist "mode" field is deliberately NOT read for ingress class. + // It is a destination property (identical on every box); ingress class is + // box-local (localBridgeModeFor) so AllStar shows only on the bridging box. setTglistSystem(m) return len(m) } @@ -2374,13 +2419,30 @@ var live = struct { tgMeta: map[int]talkerMeta{}, asNodes: map[string]allstarNode{}, viaNode: map[string]bridgeInfo{}, tgLoc: map[int]string{}, tgMode: map[int]string{}} -// locForTG returns the gateway nodeLocation currently mapped to a TG (empty if none). +// locForTG returns the Location shown for a TG in Lastheard. The Location set at +// the SOURCE (chan_svx_sat's nodeLocation, resolved once there, propagated over the +// reflector trunk to every svxref and read from /status into live.tgLoc) WINS and +// is passed through unchanged — svxdr never rewrites it. Only when it is EMPTY does +// svxdr FILL from the tglist (the canonical per-TG name); a TG absent from the +// tglist stays empty. func locForTG(tg int) string { - // FROZEN DESIGN: the tglist is the SOLE source of the Location shown in - // Lastheard. No live gateway location, no astmeta, no nodes[].system — every - // talker on a TG shows exactly the tglist name for that TG (blank if the TG - // is not in the list), so the display is identical on every box. - return systemForTG(tg) + live.mu.RLock() + l := live.tgLoc[tg] + live.mu.RUnlock() + // Exactly two things may show: the resolved operator, else the tglist system + // name. A TG that is NOT in the tglist shows EMPTY — it was never added, so + // there is no name to show, and the raw satellite nodeLocation (the node's + // physical QTH, e.g. "Troy, AL") is NEVER used as a fallback. + if isOperatorLoc(l) { + return l // resolved operator from the roster tgLoc + } + // Downstream boxes have no bridge satellite in their roster, so the operator + // never reaches their tgLoc — it arrives over the mesh. Pass that through before + // falling back to the tglist name, so the operator is NOT rewritten downstream. + if op := meshOperatorForTG(tg); op != "" { + return op + } + return systemForTG(tg) // tglist system name, or "" when the TG is not in the tglist } // modeForTG returns the gateway Backend/mode currently mapped to a TG (empty if none). @@ -2566,6 +2628,11 @@ type talkerSession struct { type lastheardEvent struct { Ts int64 `json:"ts"` + // StartTs is the key-up start time; it identifies ONE over so the 24h history + // keeps every key-up as its own row (keyed effCS|TG|StartTs) instead of one + // row per (effCS,TG) that later overs overwrite. Ts tracks the latest activity + // (ordering/eviction); StartTs is the stable over identity. 0 => use Ts. + StartTs int64 `json:"start_ts,omitempty"` Callsign string `json:"callsign"` Trunk string `json:"trunk,omitempty"` TG int `json:"tg"` @@ -2987,10 +3054,14 @@ func Run(rctx context.Context, c *config.Config) error { for _, v := range vals { out = append(out, json.RawMessage(v)) } + // `events` = the 24h HISTORY (every key-up, newest first). `live` = the SEPARATE + // in-memory "who is keyed NOW" feed the live view renders — never mixed into the + // history, so repeated overs accumulate in 24h while live just swaps. _ = json.NewEncoder(w).Encode(map[string]any{ "window_s": lastheardWindowSec, "count": len(out), "events": out, + "live": liveTalkersSnapshot(), }) }) @@ -3520,16 +3591,24 @@ func poller(rdb *redis.Client) { // Location column, like an AllStar node's node_info.json. for _, sat := range env.Satellites { for _, n := range sat.Nodes { - if !n.IsTalker || n.Callsign == "" || n.TG <= 0 { + if n.TG <= 0 { continue } - newTgTalker[n.TG] = n.Callsign - newTgTalkerAt[n.TG] = crawlNow - if n.NodeLocation != "" { + // Fill the per-TG operator location from the satellite nodeLocation + // REGARDLESS of isTalker: chan_svx_sat keeps the LAST resolved operator + // there between overs, so tgLoc always holds it and locForTG never has to + // substitute the tglist name. The 5s poll otherwise races the over and + // misses isTalker=true, which is exactly when svxdr "rewrote" the operator + // to "East Coast Reflector". + if isOperatorLoc(n.NodeLocation) { newTgLoc[n.TG] = n.NodeLocation } - if m := monModeOf(n.SW); m != "" { - newTgMode[n.TG] = m + if n.IsTalker && n.Callsign != "" { + newTgTalker[n.TG] = n.Callsign + newTgTalkerAt[n.TG] = crawlNow + if m := monModeOf(n.SW); m != "" { + newTgMode[n.TG] = m + } } } } @@ -3552,6 +3631,16 @@ func poller(rdb *redis.Client) { if at := live.tgTalkerAt[tg]; at > 0 && crawlNow-at <= stickyWindow { newTgTalker[tg] = cs newTgTalkerAt[tg] = at + // Carry the gateway nodeLocation across the SAME gap as the callsign. + // The Lastheard row is written at talker-STOP; by then a crawl may have + // dropped the talker, clearing tgLoc — so without this the live Location + // (e.g. "KR4JLO via 45225/ecr") the crawl held while talking is lost and + // the row comes out with an empty location. Pass-through only, no rewrite. + if _, ok := newTgLoc[tg]; !ok { + if l := live.tgLoc[tg]; l != "" { + newTgLoc[tg] = l + } + } } } live.tgTalker = newTgTalker @@ -3561,6 +3650,92 @@ func poller(rdb *redis.Client) { live.nodeSysop = newNodeSysop live.mu.Unlock() + // Roster-driven LIVE lastheard. The reflector LOG only emits talker + // start/stop EVENTS, so a sustained/long over leaves the Lastheard row + // frozen and the live view blank while the station is still keyed. The + // roster (isTalker) is STATE and knows who is talking RIGHT NOW across + // local, trunk and satellite, with the current resolved location. Refresh + // a row (ts=now) for every active talker each crawl so the live view shows + // who is on air and the 24h list tracks every PTT; the row ages out of the + // live window a few seconds after isTalker clears. Ingress class is the SAME + // box-local rule as the log tailer: satellite/trunk is trunk-delivered (a + // bridge class only if THIS box bridges the TG), a local node is SVXLink. + seenLive := map[string]bool{} + // writeLive UPSERTs the active talker and, when the location is authoritative + // (the bridge-resolved operator from a satellite nodeLocation), publishes it + // to the mesh on CHANGE so downstream boxes show the SAME operator — bounded + // to actual changes, never a per-poll flood (callmgr2's broker is shared). + writeLive := func(callsign string, tg int, isTrunk bool, loc string) { + callsign = strings.TrimSpace(callsign) + if callsign == "" || tg <= 0 { + return + } + k := fmt.Sprintf("%s|%d", strings.ToUpper(callsign), tg) + if seenLive[k] { + return + } + seenLive[k] = true + net := defaultNetwork(isTrunk) + if isTrunk && net == "trunk" { + // Bridge class only when THIS talker is this box's bridge node for the + // TG (callsign match); a real user on a bridged TG arriving over the + // reflector trunk stays "trunk". + if bm := localBridgeModeForTalker(tg, callsign); bm != "" { + net = bm + } + } + if loc == "" { + loc = locForTG(tg) + } + // LIVE only: the roster poll feeds the in-memory "who is keyed NOW" state, + // NEVER the 24h history ZSET (that is the log tailer's, one row per key-up). + // This is the hard split the user requires — live swaps, 24h accumulates. + updateLiveTalker(lastheardEvent{ + Ts: crawlNow, Callsign: callsign, TG: tg, Duration: 1, + Source: sourceLabel(isTrunk), Network: net, Location: loc, + }) + } + // Satellites (the local AllStar/PBX bridge): nodeLocation carries the freshly + // resolved operator (e.g. "N7FGP/NC via 45225/ecr") during an over. Pass it + // through ONLY when it IS the operator; the idle raw QTH ("Troy, AL") must + // never show, so otherwise leave it empty and let the tglist name fill in. + for _, sat := range env.Satellites { + for _, n := range sat.Nodes { + if n.IsTalker { + loc := n.NodeLocation + if !isOperatorLoc(loc) { + loc = "" // not the operator -> let locForTG supply tglist name or empty + } + writeLive(n.Callsign, n.TG, true, loc) + } + } + } + // Reflector trunks: remote talkers (active_talkers) and partner-node talkers. + for _, tr := range env.Trunks { + for tgs, cs := range tr.ActiveTalkers { + if tg, e := strconv.Atoi(tgs); e == nil { + writeLive(cs, tg, true, "") + } + } + for _, n := range tr.Nodes { + if n.IsTalker { + writeLive(n.Callsign, n.TG, true, "") + } + } + } + // Local reflector nodes keyed up here (local RF / EchoLink clients). + for cs, raw := range env.Nodes { + var ni nodeInfo + if json.Unmarshal(raw, &ni) == nil && ni.IsTalker && ni.TG > 0 { + writeLive(cs, ni.TG, false, ni.NodeLocation) + } + } + // NOTE: the mesh publish is done by the LOG tailer at talker start/stop + // (event-timed), not here. The resolved operator ("N7FGP/NC via 45225/ecr") + // lives in the satellite nodeLocation only DURING the brief over; a 5s poll + // mostly samples the idle static QTH instead, so a poll-driven publish would + // flood that static value and clobber the operator the stop event carried. + nowOnline := map[string]struct{}{} for cs := range env.Nodes { nowOnline[cs] = struct{}{} @@ -3838,6 +4013,11 @@ var defaultRenderCfg = lastheardRenderCfg{ var ( renderCfgMu sync.RWMutex renderCfg = defaultRenderCfg + // operatorMarker is the literal that marks a resolved-operator Location — the + // text between two placeholders in the configured bridge_location_format (e.g. + // " via " from "{system} via {node} / {talker}"). It is DERIVED from config, not + // hardcoded: change bridge_location_format and the discriminator follows. + operatorMarker = deriveOperatorMarker(defaultRenderCfg.BridgeLocationFormat) ) func renderConfig() lastheardRenderCfg { @@ -3846,6 +4026,41 @@ func renderConfig() lastheardRenderCfg { return renderCfg } +// deriveOperatorMarker returns the longest literal run between two placeholders in +// a bridge location format. The operator string chan_svx_sat builds from the same +// format always contains that literal (e.g. " via "), so it is the config-driven +// way to recognise a resolved operator — nothing site-specific is hardcoded. +func deriveOperatorMarker(format string) string { + best, rest := "", format + for { + i := strings.IndexByte(rest, '{') + if i < 0 { + if len(strings.TrimSpace(rest)) > len(strings.TrimSpace(best)) { + best = rest + } + break + } + if i > 0 && len(strings.TrimSpace(rest[:i])) > len(strings.TrimSpace(best)) { + best = rest[:i] + } + j := strings.IndexByte(rest, '}') + if j < i { + break + } + rest = rest[j+1:] + } + return best // untrimmed: keep surrounding spaces so the match can't catch a substring +} + +// isOperatorLoc reports whether a Location is a resolved operator (" via +// /"), using the config-derived marker. Empty marker -> never (safe). +func isOperatorLoc(loc string) bool { + renderCfgMu.RLock() + m := operatorMarker + renderCfgMu.RUnlock() + return m != "" && strings.Contains(loc, m) +} + // loadRenderConfig merges the JSON file over the built-in defaults, so the // binary works with no file and a partial file only overrides what it sets. func loadRenderConfig(path string) { @@ -3872,6 +4087,7 @@ func loadRenderConfig(path string) { applyNodesRenderConfig(&cfg, nodesJSONPath()) renderCfgMu.Lock() renderCfg = cfg + operatorMarker = deriveOperatorMarker(cfg.BridgeLocationFormat) renderCfgMu.Unlock() } @@ -3896,43 +4112,217 @@ func watchRenderConfig(path string) { } } -// bridgeIdentity splits a talker into the (Callsign, Location) shown in -// lastheard, uniform for PBX and AllStar (approved layout). PBX / plain svxlink: -// Callsign = lt.Callsign (sip-tg / real callsign), Location = locForTG -// (SA7AUX-PBX / blank). AllStar/bridge (meta System known): the BRIDGE -// (lt.Via, e.g. KT4ROY-AS) is the Callsign, and Location carries -// " via / " (e.g. "East Coast Reflector via 45225 / W2ECR"). -// The AllStar node number is dynamic from astmeta (lt.Node), never hardcoded. +// bridgeIdentity splits a talker into the (Callsign, Location) shown in lastheard. +// svxdr is PURE PASS-THROUGH for the Location: it comes from locForTG — the source's +// own nodeLocation (chan_svx_sat's hubtalk label, resolved once there and propagated +// over the reflector trunk, read from /status), else the tglist name, else empty. +// svxdr NEVER builds or rewrites the Location; write-once is enforced by the upsert. +// For a bridge/AllStar talker the bridge login (effCS, per-TG suffixed, e.g. +// KT4ROY-050) is the Callsign; plain svxlink / PBX keep their own callsign. func bridgeIdentity(lt liveTalker, tg int) (callsign, location string) { callsign = lt.Callsign - location = locForTG(tg) bridge := lt.Via if bridge == "" { bridge = lt.Trunk } - // A bridge/AllStar talker has a bridge node (Via/Trunk) AND meta (Node or - // System) — the reflector name may be absent (e.g. ASL-dodropin). Plain - // svxlink / PBX carry no bridge node -> untouched. - if bridge == "" || (lt.Node == "" && lt.System == "") { - return callsign, location + if bridge != "" && (lt.Node != "" || lt.System != "") { + callsign = bridge } - // FROZEN DESIGN: Location is the tglist name ONLY (already set above via - // locForTG). We no longer build " via / " from live - // astmeta — the tglist is the sole source, so the row reads identically on - // every box. The bridge is still the Callsign (who spoke). - callsign = bridge - return callsign, location + return callsign, locForTG(tg) } +// lastheardIdx is the process-local index of the CURRENT lastheard record per +// (effCS,TG). nodelist is the sole writer to this box's local Redis lastheard, so +// one in-memory map is enough to UPSERT: one row per talker, fill-empty only, +// never rewriting a field that is already set. It is rebuilt from the ZSET at +// startup (see logTailer backfill) so a restart does not leave stale duplicates. +var lastheardIdx = struct { + mu sync.Mutex + m map[string]lastheardEvent // key "effCS|tg" -> current stored record +}{m: map[string]lastheardEvent{}} + +// lastheardKeyOf keys the 24h HISTORY index by (effCS, TG, StartTs) so EVERY +// key-up is its own row that later overs never overwrite ("24h = alla keyup, +// olika"). StartTs 0 falls back to ts (a single-write over). The separate LIVE +// state (poller, in-memory) is keyed only by (effCS,TG) and is NOT this set. +func lastheardKeyOf(callsign string, tg int, startTs int64) string { + return fmt.Sprintf("%s|%d|%d", effCS(callsign), tg, startTs) +} + +// keepSet implements "rör ej om satt": a field that already carries a value is +// never overwritten; only an empty field is filled from the incoming event. +func keepSet(cur, incoming string) string { + if cur != "" { + return cur + } + return incoming +} + +// meshTgLoc holds the resolved operator per TG as DELIVERED OVER THE MESH from the +// box that resolved it (aldmr). A DOWNSTREAM box (speed) does not have the bridge +// satellite in its own roster, so its poller can never fill tgLoc with the operator; +// the mesh is the only carrier. This map is written only by xlinkOnMessage and is +// NOT rebuilt by the poller, so it survives between polls. locForTG consults it so +// the operator shows downstream too, instead of being rewritten to the tglist name. +const meshTgLocLinger = int64(120) + +var meshTgLoc = struct { + mu sync.Mutex + m map[int]struct { + loc string + at int64 + } +}{m: map[int]struct { + loc string + at int64 +}{}} + +func setMeshTgLoc(tg int, loc string) { + if tg <= 0 || loc == "" { + return + } + meshTgLoc.mu.Lock() + meshTgLoc.m[tg] = struct { + loc string + at int64 + }{loc, time.Now().Unix()} + meshTgLoc.mu.Unlock() +} + +func meshOperatorForTG(tg int) string { + meshTgLoc.mu.Lock() + defer meshTgLoc.mu.Unlock() + if e, ok := meshTgLoc.m[tg]; ok && time.Now().Unix()-e.at <= meshTgLocLinger { + return e.loc + } + return "" +} + +// liveLingerSec is how long a talker is served in the LIVE feed after their last +// refresh; the web view applies its own (shorter) linger on top. The LIVE feed and +// the 24h HISTORY are DELIBERATELY SEPARATE ("mixa ej"): 24h keeps every key-up as +// its own row (the ZSET, log-tailer per over); LIVE is only who is keyed NOW and is +// replaced in place (this in-memory map, poller/mesh). They never share storage. +const liveLingerSec = 15 + +var liveState = struct { + mu sync.Mutex + m map[string]lastheardEvent // key "effCS|tg" -> the current over (ts bumped each poll) +}{m: map[string]lastheardEvent{}} + +// updateLiveTalker REPLACES the one live row per (effCS,TG) — this is the "live" +// behaviour the user split from 24h: it swaps the current talker, it does NOT +// accumulate. Nothing here touches the 24h ZSET. +func updateLiveTalker(ev lastheardEvent) { + ev.Callsign = effCS(ev.Callsign) + if ev.Callsign == "" || ev.TG <= 0 { + return + } + key := fmt.Sprintf("%s|%d", ev.Callsign, ev.TG) + cutoff := time.Now().Unix() - liveLingerSec + liveState.mu.Lock() + for k, e := range liveState.m { + if e.Ts < cutoff { + delete(liveState.m, k) + } + } + liveState.m[key] = ev + liveState.mu.Unlock() +} + +// liveTalkersSnapshot returns the current live talkers (within the linger window), +// newest first, for the /api/lastheard `live` array the LIVE view renders. +func liveTalkersSnapshot() []lastheardEvent { + cutoff := time.Now().Unix() - liveLingerSec + liveState.mu.Lock() + out := make([]lastheardEvent, 0, len(liveState.m)) + for k, e := range liveState.m { + if e.Ts < cutoff { + delete(liveState.m, k) + continue + } + out = append(out, e) + } + liveState.mu.Unlock() + sort.Slice(out, func(i, j int) bool { return out[i].Ts > out[j].Ts }) + return out +} + +// writeLastheardEvent UPSERTS a talker into the lastheard set: at most ONE row +// per (effCS,TG). Identity/location fields are fill-empty (write-once) — a later +// crawl/relay/tglist value only fills blanks, never rewrites a set field. Only +// Ts/Duration/Siglev track the newest over so the row floats to the top (newest +// first, oldest last). The old ZSET member is removed and the merged one added, +// so the read handler and the web stay unchanged (ZSET still holds JSON records). func writeLastheardEvent(rdb *redis.Client, ev lastheardEvent) { + ev.Callsign = effCS(ev.Callsign) + if ev.StartTs == 0 { + ev.StartTs = ev.Ts // a single-write over: its start IS its timestamp + } + // One row per KEY-UP (effCS|TG|StartTs): a later over has a different StartTs, so + // it is APPENDED, never collapsed onto the previous one. Same-key writes (a start + // then a stop/enrichment of the SAME over) still merge in place. + key := lastheardKeyOf(ev.Callsign, ev.TG, ev.StartTs) + cutoff := time.Now().Unix() - lastheardWindowSec + + lastheardIdx.mu.Lock() + prior, had := lastheardIdx.m[key] + if had { + merged := prior + merged.Callsign = keepSet(prior.Callsign, ev.Callsign) + // Location is STRICT WRITE-ONCE for EVERY box / everyone running svx-web + // ("om location innehåller något rör den ALDRIG — annars är det en bugg"): + // only an EMPTY location is ever filled; a set value is NEVER overwritten. + // The operator still shows because the key-up (inProgress) write deliberately + // writes the operator-or-EMPTY, so the operator either lands first or fills an + // empty at stop — never by overwriting a placeholder. + merged.Location = keepSet(prior.Location, ev.Location) + // Network (ingress class) tracks the LATEST over: on any one box a given + // (effCS,TG) always enters the same way (AllStar on the bridging box, trunk + // downstream), so the newest classification is the truth and simply wins. + // This also lets a stale wrong class (e.g. a row left "AllStar" by the old + // shared-tglist logic) self-correct to "trunk" on its next over here. + if ev.Network != "" { + merged.Network = ev.Network + } + merged.Node = keepSet(prior.Node, ev.Node) + merged.System = keepSet(prior.System, ev.System) + merged.Trunk = keepSet(prior.Trunk, ev.Trunk) + merged.RxName = keepSet(prior.RxName, ev.RxName) + merged.Source = keepSet(prior.Source, ev.Source) + if ev.Ts >= prior.Ts { // newest over wins Ts/Duration/Siglev only + merged.Ts, merged.Duration = ev.Ts, ev.Duration + if ev.Siglev != 0 { + merged.Siglev = ev.Siglev + } + } + ev = merged + } + lastheardIdx.m[key] = ev + // Evict entries past the 24h window so the index tracks the ZSET and can never + // grow unbounded (writes are per-over, the map is bounded by 24h of talkers). + for k, e := range lastheardIdx.m { + if e.Ts < cutoff { + delete(lastheardIdx.m, k) + } + } + lastheardIdx.mu.Unlock() + b, err := json.Marshal(ev) if err != nil { return } pipe := rdb.Pipeline() + if had { + if pb, perr := json.Marshal(prior); perr == nil && string(pb) != string(b) { + pipe.ZRem(ctx, lastheardKey, string(pb)) // drop the superseded member + } + } pipe.ZAdd(ctx, lastheardKey, redis.Z{Score: float64(ev.Ts), Member: string(b)}) - cutoff := time.Now().Unix() - lastheardWindowSec pipe.ZRemRangeByScore(ctx, lastheardKey, "-inf", fmt.Sprintf("(%d", cutoff)) + // Cap at the newest lastheardMaxRows: ranks ascend by score (ts), so rank 0 is the + // oldest; removing [0, -(N+1)] keeps the top N. Redis stays in lockstep with the API. + pipe.ZRemRangeByRank(ctx, lastheardKey, 0, -(lastheardMaxRows + 1)) if _, err := pipe.Exec(ctx); err != nil { log.Printf("lastheard write failed: %v", err) } @@ -3945,6 +4335,29 @@ func sourceLabel(isTrunk bool) string { return "local" } +// effCS normalizes a display callsign to the strict `XXXXXX-xxx` pattern — base +// callsign plus AT MOST ONE suffix — so the lastheard identity is unique per TG +// and two stations never collide on a bare callsign. Any middle designator is +// collapsed: the base (before the first '-') is joined to the LAST '-' segment +// only. Examples: "KT4ROY-ASL-A93" -> "KT4ROY-A93", "KT4ROY-A93" -> unchanged, +// "KT4ROY" -> unchanged. Empty stays empty. This is a pure render/identity +// normalization; nothing server-specific is hardcoded. +func effCS(callsign string) string { + cs := strings.TrimSpace(callsign) + if cs == "" { + return "" + } + i := strings.IndexByte(cs, '-') + if i < 0 { + return cs // no suffix at all + } + j := strings.LastIndexByte(cs, '-') + if i == j { + return cs // already exactly one suffix + } + return cs[:i] + cs[j:] // base + last '-segment', middle designators dropped +} + // defaultNetwork is the ingress mode when no talker meta enriches the row: // a trunk-delivered talker enters over a reflector↔reflector trunk, everything // else is a plain svxlink client. A bridge (AllStar via astmeta, later DMR via @@ -3974,6 +4387,37 @@ func logTailer(rdb *redis.Client, path string) { dropped := map[string]bool{} // trunk starts suppressed as outbound echo keyOf := func(cs string, tg int) string { return fmt.Sprintf("%s|%d", cs, tg) } + // Expire talkers that have been 'active' far longer than any real over (a + // missed stop). For a local talker this releases localByTG[tg] so a swallowed + // stop can't permanently suppress that TG's trunk talkers as echoes. + var lastPrune int64 + pruneStale := func(now int64) { + // 1) Drop talkers 'active' far longer than any real over (a missed stop). + if staleTalkerAge > 0 { + maxAge := int64(staleTalkerAge / time.Second) + for k, st := range active { + if now-st.StartTs >= maxAge { + delete(active, k) + delete(dropped, k) + log.Printf("logTailer: expired stale talker %s (age %ds)", k, now-st.StartTs) + } + } + } + // 2) Rebuild localByTG from the surviving active LOCAL talkers. The per-TG + // count could otherwise go ORPHANED > 0 (double-increment on a same-key + // re-start, or a swallowed stop) with no matching active entry — which then + // suppresses every TRUNK talker on that TG as an outbound echo forever, + // silently dropping the TG from last-heard. Deriving it from active is the + // single source of truth and self-heals that. + nb := map[int]int{} + for _, st := range active { + if !st.IsTrunk { + nb[st.TG]++ + } + } + localByTG = nb + } + mkLive := func(ev talkerLogEvent) liveTalker { cs, tn := resolveTalker(ev.Callsign, ev.TG, ev.IsTrunk) lt := liveTalker{StartTs: ev.Ts, TG: ev.TG, IsTrunk: ev.IsTrunk, @@ -3990,14 +4434,21 @@ func logTailer(rdb *redis.Client, path string) { lt.Trunk = ev.Callsign } } - // Gateway-node Backend (PBX etc.) wins over the generic "trunk" ingress. - if md := modeForTG(ev.TG); md != "" { - lt.Network = md + // Ingress class, box-local AND per-talker ("bara ur sprung, aldrig till"). + // A bridge class (AllStar/DMR) is set ONLY when the talker IS this box's own + // bridge node for the TG — i.e. its callsign is the bridge node callsign the + // AllStar/DMR side stamps on what it injects. A real user on the SAME bridged + // TG who reached us over the reflector trunk keeps "trunk": "AllStar" must + // mean it came from AllStar, nothing else. A LOCAL talker stays SVXLink. + if lt.IsTrunk && lt.Network == "trunk" { + if bm := localBridgeModeForTalker(ev.TG, lt.Callsign); bm != "" { + lt.Network = bm + } } return lt } - emit := func(start liveTalker, tg int, stopTs int64) { + emit := func(start liveTalker, tg int, stopTs int64, inProgress bool) { // The meta often arrives just after talker-start (astmeta polls AMI // about once a second), so short keyups miss it in mkLive. Re-check // at stop — the meta is still fresh at this point — so those rows @@ -4017,10 +4468,14 @@ func logTailer(rdb *redis.Client, path string) { if dur < 1 { dur = 1 } - // Re-apply the gateway Backend at stop: tgMode may not have been populated - // yet when mkLive ran at talker-start (crawl lag on short keyups). - if md := modeForTG(tg); md != "" { - start.Network = md + // Re-apply the ingress class at stop (crawl lag on short keyups), per-talker: + // bridge class only when THIS talker is this box's own bridge node for the TG + // (callsign match). A real user on a bridged TG who came over the reflector + // trunk stays "trunk"; a LOCAL talker stays SVXLink. + if start.IsTrunk && start.Network == "trunk" { + if bm := localBridgeModeForTalker(tg, start.Callsign); bm != "" { + start.Network = bm + } } // Location column, symmetric for PBX and AllStar: the gateway/reflector // descriptor lives here, the station stays in Callsign. PBX gets its @@ -4029,8 +4484,13 @@ func logTailer(rdb *redis.Client, path string) { // "East Coast Reflector via KT4ROY-AS") so it renders like the PBX rows. // Callsign + Location split (uniform PBX/AllStar). See bridgeIdentity. csOut, loc := bridgeIdentity(start, tg) + if inProgress && !isOperatorLoc(loc) { + // keydown with no operator yet -> empty; the stop FILLS it (write-once). + loc = "" + } writeLastheardEvent(rdb, lastheardEvent{ Ts: start.StartTs, + StartTs: start.StartTs, // over identity: this key-up gets its own 24h row Callsign: csOut, Trunk: start.Trunk, TG: tg, @@ -4051,8 +4511,53 @@ func logTailer(rdb *redis.Client, path string) { // enrich (tgTalker is empty for historical events), producing a second row. existing := map[int64]bool{} if zs, zerr := rdb.ZRangeWithScores(ctx, lastheardKey, 0, -1).Result(); zerr == nil { + // Rebuild the UPSERT index from the persisted set so a restart keeps one row + // per talker, collapse any legacy duplicates (same effCS|TG, newest wins), and + // migrate the stored members to the normalized effCS callsign form so the + // in-memory index matches each stored member exactly (keeps ZRem consistent). + best := map[string]lastheardEvent{} for _, z := range zs { existing[int64(z.Score)] = true + s, _ := z.Member.(string) + var e lastheardEvent + if s == "" || json.Unmarshal([]byte(s), &e) != nil { + continue + } + e.Callsign = effCS(e.Callsign) + // Normalize a stale non-operator location left by older logic (e.g. a raw + // QTH "Troy, AL") to the tglist system name. Guarded on the TG being + // listed so a cold start (tglist not yet loaded -> systemForTG "") does + // NOT blank every row; an unlisted TG is corrected to empty on its next + // over via locForTG. Operator locations are untouched. + if e.Location != "" && !isOperatorLoc(e.Location) { + if sysName := systemForTG(e.TG); sysName != "" { + e.Location = sysName + } + } + if e.StartTs == 0 { + e.StartTs = e.Ts + } + // Keyed per KEY-UP so restoring the set keeps every over (not one row per + // talker). Only an exact-same-over duplicate (same StartTs) collapses. + k := lastheardKeyOf(e.Callsign, e.TG, e.StartTs) + if cur, ok := best[k]; !ok || e.Ts >= cur.Ts { + best[k] = e + } + } + pipe := rdb.Pipeline() + pipe.Del(ctx, lastheardKey) + lastheardIdx.mu.Lock() + for k, e := range best { + lastheardIdx.m[k] = e + if b, mErr := json.Marshal(e); mErr == nil { + pipe.ZAdd(ctx, lastheardKey, redis.Z{Score: float64(e.Ts), Member: string(b)}) + } + } + lastheardIdx.mu.Unlock() + // Cap the rebuilt set at the newest lastheardMaxRows, same as live writes. + pipe.ZRemRangeByRank(ctx, lastheardKey, 0, -(lastheardMaxRows + 1)) + if _, err := pipe.Exec(ctx); err != nil { + log.Printf("lastheard index rebuild failed: %v", err) } } if f, err := os.Open(path); err == nil { @@ -4087,13 +4592,19 @@ func logTailer(rdb *redis.Client, path string) { localByTG[ev.TG]-- } if !existing[st.StartTs] { // already persisted by a previous run → don't duplicate - emit(st, ev.TG, ev.Ts) + emit(st, ev.TG, ev.Ts, false) } delete(active, k) } } f.Close() log.Printf("logTailer: backfill done, %d in-flight talkers", len(active)) + // Immediately drop anything backfill left 'in-flight' from long ago (e.g. a + // start whose stop was never logged) so a restart actually unwedges a TG + // instead of replaying the same stuck counter. + now := time.Now().Unix() + pruneStale(now) + lastPrune = now } else { log.Printf("logTailer: cannot open %s for backfill: %v", path, err) } @@ -4130,16 +4641,23 @@ func logTailer(rdb *redis.Client, path string) { if !ev.IsTrunk { localByTG[ev.TG]++ } - // Live only (not backfill): announce the SVX talker to the mesh. - xlinkPublishTalker(lt.Callsign, lt.System, lt.Trunk, lt.Node, ev.TG, lt.Network, "start", ev.Ts) + // Write the key-up to 24h AT KEYDOWN so a talker IN PROGRESS is in the + // history immediately — "den som pratar just nu" must appear while it is + // still talking, not only at stop. The matching stop re-emits the SAME + // over (same StartTs) and merges the final duration/location in place, so + // this never adds a second row. Live (poller, in-memory) stays separate. + emit(lt, ev.TG, ev.Ts, true) + // Live only (not backfill): announce the SVX talker to the mesh, + // carrying the resolved location so a downstream box shows it too. + xlinkPublishTalker(lt.Callsign, lt.System, lt.Trunk, lt.Node, ev.TG, lt.Network, "start", ev.Ts, locForTG(ev.TG)) } else if dropped[k] { delete(dropped, k) } else if st, was := active[k]; was { if !st.IsTrunk && localByTG[ev.TG] > 0 { localByTG[ev.TG]-- } - xlinkPublishTalker(st.Callsign, st.System, st.Trunk, st.Node, ev.TG, st.Network, "stop", ev.Ts) - emit(st, ev.TG, ev.Ts) + xlinkPublishTalker(st.Callsign, st.System, st.Trunk, st.Node, ev.TG, st.Network, "stop", ev.Ts, locForTG(ev.TG)) + emit(st, ev.TG, ev.Ts, false) delete(active, k) } else { if ev.IsTrunk && localByTG[ev.TG] > 0 { @@ -4165,6 +4683,10 @@ func logTailer(rdb *redis.Client, path string) { } if err == io.EOF { time.Sleep(300 * time.Millisecond) + if now := time.Now().Unix(); now-lastPrune >= 30 { // self-heal live, ~every 30 s + pruneStale(now) + lastPrune = now + } fi1, sErr := os.Stat(path) if sErr == nil && fi0 != nil { if !os.SameFile(fi0, fi1) || fi1.Size() < fi0.Size() { diff --git a/svxdr/nodelist/nodes.go b/svxdr/nodelist/nodes.go index e2c93f4..198a645 100644 --- a/svxdr/nodelist/nodes.go +++ b/svxdr/nodelist/nodes.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - package nodelist // nodes.json — shared bridge map (see svx-web/nodes.README.md). nodelist takes diff --git a/svxdr/nodelist/nodes_flat.go b/svxdr/nodelist/nodes_flat.go index cae996d..d0cefcc 100644 --- a/svxdr/nodelist/nodes_flat.go +++ b/svxdr/nodelist/nodes_flat.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - package nodelist // All-Nodes flat layer: one total, deduped node list across the whole crawled diff --git a/svxdr/nodelist/svxdrcfg.go b/svxdr/nodelist/svxdrcfg.go index 2bb3c79..eb69297 100644 --- a/svxdr/nodelist/svxdrcfg.go +++ b/svxdr/nodelist/svxdrcfg.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - package nodelist // svxdr config wiring. applyConfig overrides the package's env-derived globals @@ -101,6 +92,72 @@ func systemForTG(tg int) string { return tglistSystemMap[tg] } +// Per-TG ORIGIN mode for talkgroups THIS box itself bridges — built from this +// box's own nodes[] (incl. the chan_svx_sat svx_sat.conf nodes folded in by +// loadSatNodes, each Mode="AllStar", plus a DMR node's Mode="DMR"). It is the +// box-local authority for ingress class: a TG is AllStar/DMR/PBX ONLY on the box +// that actually bridges it. A downstream box does NOT have that TG in its config, +// so the same TG classifies as the plain "trunk" transport there — AllStar shows +// only on the first box in the chain, never after it has travelled the trunk. +// NOT the central/shared tglist (that is a destination property, same on every +// box, and must never set ingress class — "bara ur sprung, aldrig till"). +var ( + localBridgeModeMu sync.RWMutex + localBridgeModeMap = map[int]string{} + // Per-TG set of THIS box's own bridge-node effective callsigns (e.g. tg + // 3109050 -> {"KT4ROY-050"}). The AllStar/DMR bridge stamps its OWN node + // callsign on the talker it injects, so ONLY that callsign is a genuine + // bridge ingress. Any other callsign on the same TG reached us over the + // reflector trunk and must stay "trunk" — "AllStar" means it came from + // AllStar, nothing else. + localBridgeCSMap = map[int]map[string]bool{} +) + +func setLocalBridgeMode(mode map[int]string, cs map[int]map[string]bool) { + localBridgeModeMu.Lock() + localBridgeModeMap = mode + localBridgeCSMap = cs + localBridgeModeMu.Unlock() +} + +// localBridgeModeForTalker returns this box's own bridge mode (AllStar/DMR/…) for +// a talker ONLY when the talker IS one of this box's bridge nodes for that TG — +// i.e. its callsign is the bridge node's own callsign. A real user who happens to +// be on a bridged TG but arrived over the reflector trunk returns "" and stays on +// the transport class. "" also when this box does not bridge the TG at all. +func localBridgeModeForTalker(tg int, callsign string) string { + localBridgeModeMu.RLock() + defer localBridgeModeMu.RUnlock() + mode := localBridgeModeMap[tg] + if mode == "" { + return "" + } + if set := localBridgeCSMap[tg]; set != nil && set[effCS(callsign)] { + return mode + } + return "" +} + +// Disabled TGs: entries in the tglist with "disable": true. nodelist must NOT +// rewrite their Lastheard Location — it is passed through from chan_svx_sat's live +// nodeLocation. The TG still keeps its tglist name for other uses (listen, menus). +var ( + disabledTGMu sync.RWMutex + disabledTGSet = map[int]bool{} +) + +func setDisabledTGs(m map[int]bool) { + disabledTGMu.Lock() + disabledTGSet = m + disabledTGMu.Unlock() +} + +func isDisabledTG(tg int) bool { + disabledTGMu.RLock() + defer disabledTGMu.RUnlock() + return disabledTGSet[tg] +} + // Configured node display names (every nodes[] via/callsign). A configured node is // an intentional own node and is never hidden by the bridge/infra filter. var ( @@ -215,6 +272,7 @@ func applyConfig(c *config.Config) { setStr(&externalStatusPath, e.StatusPath) setStr(&externalProxyPath, e.ProxyPath) setStr(&externalDetailPath, e.DetailPath) + setStr(&externalBridgePath, e.BridgePath) if e.MaxRefs > 0 { externalMaxRefs = e.MaxRefs } @@ -260,6 +318,14 @@ func applyConfig(c *config.Config) { func applyRenderFromConfig(c *config.Config) { rc := defaultRenderCfg rc.ReflectorNames = map[string]string{} + // TGs nodelist must not rewrite (config nodelist.disable_rewrite_tgs). + dis := map[int]bool{} + for _, tg := range c.Nodelist.DisableRewriteTGs { + if tg > 0 { + dis[tg] = true + } + } + setDisabledTGs(dis) if s := strings.TrimSpace(c.Lastheard.BridgeLocationFormat); s != "" { rc.BridgeLocationFormat = s } @@ -322,6 +388,8 @@ func applyRenderFromConfig(c *config.Config) { modeMap := map[string]string{} confNames := map[string]bool{} tgSys := map[int]string{} + bridgeMode := map[int]string{} // TG -> ingress class for TGs THIS box bridges + bridgeCS := map[int]map[string]bool{} // TG -> set of this box's bridge-node callsigns for _, e := range c.Nodes { if !e.IsEnabled() || e.TG == 0 { continue @@ -329,6 +397,9 @@ func applyRenderFromConfig(c *config.Config) { if e.System != "" { tgSys[e.TG] = e.System // TG -> reflector name, Location fallback for any talker on this TG } + if e.Mode != "" { + bridgeMode[e.TG] = e.Mode // box-local: this box owns the bridge for this TG + } name := e.Via if name == "" { name = e.Callsign @@ -336,6 +407,12 @@ func applyRenderFromConfig(c *config.Config) { if name == "" { continue } + if e.Mode != "" { // remember WHICH callsign is the bridge node for this TG + if bridgeCS[e.TG] == nil { + bridgeCS[e.TG] = map[string]bool{} + } + bridgeCS[e.TG][effCS(name)] = true + } confNames[name] = true if any[e.TG] == nil { any[e.TG] = map[string]bool{} @@ -357,10 +434,12 @@ func applyRenderFromConfig(c *config.Config) { setSatLogins(logins) setSatTrunkTGs(groupTGs) setModeByName(modeMap) + setLocalBridgeMode(bridgeMode, bridgeCS) setConfiguredNames(confNames) setTgSystem(tgSys) renderCfgMu.Lock() renderCfg = rc + operatorMarker = deriveOperatorMarker(rc.BridgeLocationFormat) renderCfgMu.Unlock() } diff --git a/svxdr/proxy/proxy.go b/svxdr/proxy/proxy.go index af69928..1216fff 100644 --- a/svxdr/proxy/proxy.go +++ b/svxdr/proxy/proxy.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - // Package proxy is the svxdr proxy subsystem — the enriched SvxReflector status // proxy, folded in from the standalone svx-web/proxy. Behaviour is preserved // exactly (byte-identical status enrichment, same /status, /api/talker-meta, diff --git a/svxdr/statusnorm/statusnorm.go b/svxdr/statusnorm/statusnorm.go index eda5796..61e4f7e 100644 --- a/svxdr/statusnorm/statusnorm.go +++ b/svxdr/statusnorm/statusnorm.go @@ -1,12 +1,3 @@ -// svxdr — live-data daemon for Reflector Dashboard (nodelist + proxy + astmeta + xlink) -// Copyright (C) 2026 SA7AUX (Björn) -// SPDX-License-Identifier: AGPL-3.0-or-later -// -// This program is free software: you can redistribute it and/or modify it under -// the terms of the GNU Affero General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) any -// later version. See the LICENSE file for details. - // Package statusnorm holds the ONE rule that turns a reflector's shared sat-login // (e.g. KT4ROY-ASL, used by all its TG nodes) into the per-TG display callsign // (KT4ROY-ASL1..4). It is applied ONCE where a status is ingested (the proxy's