summaryrefslogtreecommitdiff
path: root/ysf-zapper.py
blob: 46b33c85185d3dbd1489f4b893f3a01a0b0cb215 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python3
"""ysf-zapper: drop YSF links requested over RF by stations with no valid callsign.

Follows the newest /var/log/pi-star/YSFGateway-YYYY-MM-DD.log (rolls at UTC
midnight) and watches for lines like:

  M: 2026-11-24 15:43:23.513 Connect to 28054 - "US-XLX458       " has been requested by 0

If the requesting callsign is blank, has no letters, or is in DENYLIST, it
sends "UnLink" to YSFGateway's remote command port, retrying until status
reports "disc".
"""
import glob
import os
import re
import subprocess
import sys
import time

LOG_GLOB = os.environ.get("YSFZ_LOG_GLOB", "/var/log/pi-star/YSFGateway-*.log")
REMOTE_CMD = os.environ.get("YSFZ_REMOTE_CMD", "/usr/local/bin/RemoteCommand")
PORT = os.environ.get("YSFZ_PORT", "6073")
DENYLIST = {c.strip().upper() for c in os.environ.get("YSFZ_DENYLIST", "").split(",") if c.strip()}
DRY_RUN = os.environ.get("YSFZ_DRY_RUN", "0") == "1"

REQ_RE = re.compile(r"Connect to (.*?) has been requested by(.*)$")


def log(msg):
    print(msg, flush=True)  # goes to journald under systemd


def is_bad(callsign):
    cs = callsign.strip().upper()
    if not cs:
        return True
    if cs in DENYLIST or cs.split("-")[0] in DENYLIST:
        return True
    # Every real amateur callsign has at least one letter and one digit.
    return not (re.search(r"[A-Z]", cs) and re.search(r"[0-9]", cs))


def remote(cmd):
    r = subprocess.run([REMOTE_CMD, PORT, cmd], capture_output=True, text=True, timeout=10)
    return (r.stdout + r.stderr).strip()


def unlink(reason):
    if DRY_RUN:
        log(f"DRY RUN: would UnLink ({reason})")
        return
    time.sleep(1.5)  # let YSFGateway finish linking ("Linked to ..." follows ~100ms later)
    for attempt in range(1, 6):
        log(f"UnLink attempt {attempt}: {remote('UnLink').splitlines()[-1:]}")
        time.sleep(1)
        status = remote("status")
        if "disc" in status:
            log(f"Link dropped ({reason}); status: {status.splitlines()[-1]}")
            return
        time.sleep(2)
    log(f"WARNING: link still up after retries ({reason})")


def newest_log():
    files = sorted(glob.glob(LOG_GLOB))
    return files[-1] if files else None


def follow():
    path, fh, buf = None, None, ""
    first = True
    while True:
        latest = newest_log()
        if latest and latest != path:
            if fh:
                # drain the old file before switching
                for line in fh.read().splitlines():
                    handle(line)
                fh.close()
            path = latest
            fh = open(path, "r", errors="replace")
            if first:
                fh.seek(0, os.SEEK_END)  # don't act on history at startup
            log(f"Following {path}")
            first = False
        if fh:
            # detect truncation (WPSD log cleanup)
            try:
                if os.path.getsize(path) < fh.tell():
                    fh.seek(0)
            except FileNotFoundError:
                path = None
                continue
            chunk = fh.read()
            if chunk:
                buf += chunk
                *lines, buf = buf.split("\n")
                for line in lines:
                    handle(line)
        time.sleep(0.5)


def handle(line):
    m = REQ_RE.search(line)
    if not m:
        return
    target, who = m.group(1).strip(), m.group(2).strip()
    if is_bad(who):
        reason = f"connect to {target} requested by invalid callsign {who!r}"
        log(f"ZAP: {reason}")
        unlink(reason)
    else:
        log(f"OK: connect to {target} requested by {who}")


if __name__ == "__main__":
    log(f"ysf-zapper starting (port {PORT}, denylist {sorted(DENYLIST) or 'none'}, dry_run={DRY_RUN})")
    try:
        follow()
    except KeyboardInterrupt:
        sys.exit(0)