Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1703 lines (1388 loc) · 60.2 KB
/
Copy pathapp.py
File metadata and controls
1703 lines (1388 loc) · 60.2 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
INTERCEPT - Signal Intelligence Platform
Flask application and shared state.
"""
from __future__ import annotations
import site
import sys
from utils.database import get_db
# Ensure user site-packages is available (may be disabled when running as root/sudo)
if not site.ENABLE_USER_SITE:
user_site = site.getusersitepackages()
if user_site and user_site not in sys.path:
sys.path.insert(0, user_site)
import logging
import os
import platform
import queue
import re
import subprocess
import threading
from pathlib import Path
from flask import (
Flask,
Response,
flash,
jsonify,
redirect,
render_template,
request,
send_file,
send_from_directory,
session,
url_for,
)
from werkzeug.security import check_password_hash
from config import (
CHANGELOG,
DEFAULT_LATITUDE,
DEFAULT_LONGITUDE,
SHARED_OBSERVER_LOCATION_ENABLED,
SSL_CERT,
SSL_KEY,
VERSION,
)
from utils.cleanup import DataStore, cleanup_manager
from utils.constants import (
MAX_AIRCRAFT_AGE_SECONDS,
MAX_BT_DEVICE_AGE_SECONDS,
MAX_DEAUTH_ALERTS_AGE_SECONDS,
MAX_DSC_MESSAGE_AGE_SECONDS,
MAX_VESSEL_AGE_SECONDS,
MAX_WIFI_NETWORK_AGE_SECONDS,
QUEUE_MAX_SIZE,
)
from utils.dependencies import check_all_dependencies, check_tool
from utils.process import cleanup_stale_dump1090, cleanup_stale_processes
from utils.sdr import SDRFactory
from utils.sdr.device_config import describe_devices, set_device_config
try:
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
_has_limiter = True
except ImportError:
_has_limiter = False
try:
from flask_compress import Compress
_has_compress = True
except ImportError:
_has_compress = False
try:
from flask_wtf.csrf import CSRFProtect
_has_csrf = True
except ImportError:
_has_csrf = False
# Track application start time for uptime calculation
import contextlib
import time as _time
_app_start_time = _time.time()
logger = logging.getLogger("intercept.database")
# Create Flask app
app = Flask(__name__)
def _load_or_generate_secret_key():
"""Load secret key from env var or instance file, generating if needed."""
env_key = os.environ.get("INTERCEPT_SECRET_KEY")
if env_key:
return env_key
key_path = Path("instance/secret.key")
if key_path.exists():
return key_path.read_text().strip()
key_path.parent.mkdir(exist_ok=True)
key = os.urandom(32).hex()
key_path.write_text(key)
# Session-signing secret: readable only by the owner.
with contextlib.suppress(OSError):
key_path.chmod(0o600)
return key
app.secret_key = _load_or_generate_secret_key()
# Session cookie hardening. SameSite=Lax is what browsers already default to,
# but stating it means the protection is deliberate rather than inherited.
# Secure is set only when TLS is configured, since it would otherwise stop
# the cookie being sent at all over plain HTTP.
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = bool(SSL_CERT and SSL_KEY)
# Set up HTTP compression (gzip/brotli for HTML, CSS, JS, JSON)
if _has_compress:
Compress(app)
else:
logging.getLogger("intercept").warning(
"flask-compress not installed – HTTP compression disabled. Install with: pip install flask-compress"
)
# Set up rate limiting
if _has_limiter:
limiter = Limiter(
key_func=get_remote_address,
app=app,
storage_uri="memory://",
)
else:
logging.getLogger("intercept").warning(
"flask-limiter not installed – rate limiting disabled. Install with: pip install flask-limiter"
)
class _NoopLimiter:
"""Stub so @limiter.limit() decorators are silently ignored."""
def limit(self, *a, **kw):
def decorator(f):
return f
return decorator
limiter = _NoopLimiter()
# Set up CSRF protection
if _has_csrf:
csrf = CSRFProtect(app)
else:
logging.getLogger("intercept").warning(
"flask-wtf not installed – CSRF protection disabled. Install with: pip install flask-wtf"
)
csrf = None
# Disable Werkzeug debugger PIN (not needed for local development tool)
os.environ["WERKZEUG_DEBUG_PIN"] = "off"
# ============================================
# ERROR HANDLERS
# ============================================
@app.errorhandler(429)
def ratelimit_handler(e):
logger.warning(f"Rate limit exceeded for IP: {request.remote_addr}")
flash("Too many login attempts. Please wait one minute before trying again.", "error")
return render_template("login.html", version=VERSION), 429
# ============================================
# SECURITY HEADERS
# ============================================
@app.after_request
def add_security_headers(response):
"""Add security headers to all responses."""
# Prevent MIME type sniffing
response.headers["X-Content-Type-Options"] = "nosniff"
# Prevent clickjacking
response.headers["X-Frame-Options"] = "SAMEORIGIN"
# Enable XSS filter
response.headers["X-XSS-Protection"] = "1; mode=block"
# Referrer policy
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
# Permissions policy (disable unnecessary features)
response.headers["Permissions-Policy"] = "geolocation=(self), microphone=()"
# Cache-Control for static assets
if request.path.startswith("/static/"):
if "/vendor/" in request.path:
response.headers["Cache-Control"] = "public, max-age=604800" # 7 days for vendored libs
else:
response.headers["Cache-Control"] = "public, max-age=86400" # 24h for app assets
return response
# ============================================
# CONTEXT PROCESSORS
# ============================================
@app.url_defaults
def version_static_urls(endpoint: str, values: dict) -> None:
"""Every url_for('static', ...) carries ?v=<version>.
App assets are cached for a day, so without it a browser could pair a
new release's pages with the old release's scripts (GPS.setSkyView "is
not a function" after an upgrade). A new version is a new URL.
"""
if endpoint == "static" and "v" not in values:
values["v"] = VERSION
@app.context_processor
def inject_offline_settings():
"""Inject offline settings into all templates."""
from utils.database import get_setting
# Privacy-first defaults: keep dashboard assets/fonts local to avoid
# third-party tracker/storage defenses in strict browsers.
assets_source = str(get_setting("offline.assets_source", "local") or "local").lower()
fonts_source = str(get_setting("offline.fonts_source", "local") or "local").lower()
if assets_source not in ("local", "cdn"):
assets_source = "local"
if fonts_source not in ("local", "cdn"):
fonts_source = "local"
# Force local delivery for core dashboard pages.
assets_source = "local"
fonts_source = "local"
return {
"offline_settings": {
"enabled": get_setting("offline.enabled", False),
"assets_source": assets_source,
"fonts_source": fonts_source,
"tile_provider": get_setting("offline.tile_provider", "esri_world"),
"tile_server_url": get_setting("offline.tile_server_url", ""),
}
}
# ============================================
# GLOBAL PROCESS MANAGEMENT
# ============================================
# Pager decoder
current_process = None
output_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
process_lock = threading.Lock()
# RTL_433 sensor
sensor_process = None
sensor_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
sensor_lock = threading.Lock()
# WiFi
wifi_process = None
wifi_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
wifi_lock = threading.Lock()
# Bluetooth
bt_process = None
bt_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
bt_lock = threading.Lock()
# ADS-B aircraft
adsb_process = None
adsb_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
adsb_lock = threading.Lock()
# Satellite/Iridium
satellite_process = None
satellite_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
satellite_lock = threading.Lock()
# ACARS aircraft messaging
acars_process = None
acars_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
acars_lock = threading.Lock()
# VDL2 aircraft datalink
vdl2_process = None
vdl2_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
vdl2_lock = threading.Lock()
# APRS amateur radio tracking
aprs_process = None
aprs_rtl_process = None
aprs_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
aprs_lock = threading.Lock()
# RTLAMR utility meter reading
rtlamr_process = None
rtlamr_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
rtlamr_lock = threading.Lock()
# AIS vessel tracking
ais_process = None
ais_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
ais_lock = threading.Lock()
# DSC (Digital Selective Calling)
dsc_process = None
dsc_rtl_process = None
dsc_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
dsc_lock = threading.Lock()
# TSCM (Technical Surveillance Countermeasures)
tscm_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
tscm_lock = threading.Lock()
# Ground Station automation
ground_station_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
# SubGHz Transceiver (HackRF)
subghz_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
subghz_lock = threading.Lock()
# Radiosonde weather balloon tracking
radiosonde_process = None
radiosonde_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
radiosonde_lock = threading.Lock()
# CW/Morse code decoder
morse_process = None
morse_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
morse_lock = threading.Lock()
# Meteor scatter detection
meteor_process = None
meteor_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
meteor_lock = threading.Lock()
# Generic OOK signal decoder
ook_process = None
ook_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
ook_lock = threading.Lock()
# Deauth Attack Detection
deauth_detector = None
deauth_detector_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
deauth_detector_lock = threading.Lock()
# Drone Intelligence
drone_queue = queue.Queue(maxsize=QUEUE_MAX_SIZE)
# ============================================
# GLOBAL STATE DICTIONARIES
# ============================================
# Logging settings
logging_enabled = False
log_file_path = "pager_messages.log"
# WiFi state - using DataStore for automatic cleanup
wifi_monitor_interface = None
wifi_networks = DataStore(max_age_seconds=MAX_WIFI_NETWORK_AGE_SECONDS, name="wifi_networks")
wifi_clients = DataStore(max_age_seconds=MAX_WIFI_NETWORK_AGE_SECONDS, name="wifi_clients")
wifi_handshakes = [] # Captured handshakes (list, not auto-cleaned)
# Bluetooth state - using DataStore for automatic cleanup
bt_interface = None
bt_devices = DataStore(max_age_seconds=MAX_BT_DEVICE_AGE_SECONDS, name="bt_devices")
bt_beacons = DataStore(max_age_seconds=MAX_BT_DEVICE_AGE_SECONDS, name="bt_beacons")
bt_services = {} # MAC -> list of services (not auto-cleaned, user-requested)
# Aircraft (ADS-B) state - using DataStore for automatic cleanup
adsb_aircraft = DataStore(max_age_seconds=MAX_AIRCRAFT_AGE_SECONDS, name="adsb_aircraft")
# Vessel (AIS) state - using DataStore for automatic cleanup
ais_vessels = DataStore(max_age_seconds=MAX_VESSEL_AGE_SECONDS, name="ais_vessels")
# DSC (Digital Selective Calling) state - using DataStore for automatic cleanup
dsc_messages = DataStore(max_age_seconds=MAX_DSC_MESSAGE_AGE_SECONDS, name="dsc_messages")
# Deauth alerts - using DataStore for automatic cleanup
deauth_alerts = DataStore(max_age_seconds=MAX_DEAUTH_ALERTS_AGE_SECONDS, name="deauth_alerts")
# Satellite state
satellite_passes = [] # Predicted satellite passes (not auto-cleaned, calculated)
# Register data stores with cleanup manager
cleanup_manager.register(wifi_networks)
cleanup_manager.register(wifi_clients)
cleanup_manager.register(bt_devices)
cleanup_manager.register(bt_beacons)
cleanup_manager.register(adsb_aircraft)
cleanup_manager.register(ais_vessels)
cleanup_manager.register(dsc_messages)
cleanup_manager.register(deauth_alerts)
# ============================================
# SDR DEVICE REGISTRY
# ============================================
# Tracks which mode is using which SDR device to prevent conflicts
# Key: "sdr_type:device_index" (str), Value: mode_name (str)
sdr_device_registry: dict[str, str] = {}
sdr_device_registry_lock = threading.Lock()
def claim_sdr_device(device_index: int, mode_name: str, sdr_type: str = "rtlsdr") -> str | None:
"""Claim an SDR device for a mode.
Checks the in-app registry first, then probes the USB device to
catch stale handles held by external processes (e.g. a leftover
rtl_fm from a previous crash).
Args:
device_index: The SDR device index to claim
mode_name: Name of the mode claiming the device (e.g., 'sensor', 'rtlamr')
sdr_type: SDR type string (e.g., 'rtlsdr', 'hackrf', 'limesdr')
Returns:
Error message if device is in use, None if successfully claimed
"""
key = f"{sdr_type}:{device_index}"
with sdr_device_registry_lock:
if key in sdr_device_registry:
in_use_by = sdr_device_registry[key]
return f"SDR device {sdr_type}:{device_index} is in use by {in_use_by}. Stop {in_use_by} first or use a different device."
# Probe the USB device to catch external processes holding the handle
if sdr_type == "rtlsdr":
try:
from utils.sdr.detection import probe_rtlsdr_device
usb_error = probe_rtlsdr_device(device_index)
if usb_error:
return usb_error
except Exception:
pass # If probe fails, let the caller proceed normally
sdr_device_registry[key] = mode_name
return None
def release_sdr_device(device_index: int, sdr_type: str = "rtlsdr") -> None:
"""Release an SDR device from the registry.
Args:
device_index: The SDR device index to release
sdr_type: SDR type string (e.g., 'rtlsdr', 'hackrf', 'limesdr')
"""
key = f"{sdr_type}:{device_index}"
with sdr_device_registry_lock:
sdr_device_registry.pop(key, None)
def get_sdr_device_status() -> dict[str, str]:
"""Get current SDR device allocations.
Returns:
Dictionary mapping 'sdr_type:device_index' keys to mode names
"""
with sdr_device_registry_lock:
return dict(sdr_device_registry)
# ============================================
# MAIN ROUTES
# ============================================
@app.before_request
def require_login():
# Skip auth entirely when INTERCEPT_DISABLE_AUTH is set
if os.environ.get("INTERCEPT_DISABLE_AUTH", "").lower() in ("1", "true", "yes"):
session["logged_in"] = True
return None
# Routes that don't require login (to avoid infinite redirect loop)
allowed_routes = ["login", "static", "favicon", "health", "health_check", "change_password"]
# A WebSocket upgrade is an ordinary HTTP request until the handshake
# completes, so the session is checkable here. It used to be allowed
# through on the assumption that a page load had already authenticated
# the client, but a WebSocket client need not load a page, and these
# endpoints carry live RF data.
if request.path.startswith("/ws/"):
if "logged_in" in session:
return None
return Response("Authentication required", status=401)
# Controller API endpoints use API key auth, not session auth
# Allow agent push/pull endpoints without session login
if request.path.startswith("/controller/"):
return None # Skip session check, controller routes handle their own auth
# If user is not logged in and the current route is not allowed...
if "logged_in" not in session and request.endpoint not in allowed_routes:
return redirect(url_for("login"))
# An account seeded with a password the operator did not choose must set
# one before anything else is reachable. The flag is cleared by
# set_user_password(), so this resolves as soon as the change is made.
if session.get("must_change_password") and request.endpoint not in allowed_routes:
if request.path.startswith("/api/") or request.is_json:
return jsonify({"status": "error", "message": "Password change required"}), 403
return redirect(url_for("change_password"))
@app.route("/change-password", methods=["GET", "POST"])
@limiter.limit("10 per minute")
def change_password() -> Response | str:
"""Set a new password.
Reachable only when logged in. Required before anything else when the
account was seeded with a password the operator did not choose.
"""
if "logged_in" not in session:
return redirect(url_for("login"))
username = session.get("username")
forced = bool(session.get("must_change_password"))
if request.method == "POST":
from utils.database import set_user_password, verify_user_password
current = request.form.get("current_password") or ""
new = request.form.get("new_password") or ""
confirm = request.form.get("confirm_password") or ""
error = None
if not verify_user_password(username, current):
error = "Current password is incorrect"
elif len(new) < 12:
error = "New password must be at least 12 characters"
elif new != confirm:
error = "New passwords do not match"
elif new == current:
error = "New password must differ from the current one"
if error:
flash(error, "error")
else:
set_user_password(username, new)
session.pop("must_change_password", None)
logger.info(f"Password changed for user '{username}'.")
return redirect(url_for("index"))
return render_template("change_password.html", version=VERSION, forced=forced, username=username)
@app.route("/logout")
def logout():
session.clear()
return redirect(url_for("login"))
@app.route("/login", methods=["GET", "POST"])
@limiter.limit("5 per minute") # Limit to 5 login attempts per minute per IP
def login():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
# Connect to DB and find user
with get_db() as conn:
cursor = conn.execute("SELECT password_hash, role FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
# Verify user exists and password is correct
if user and check_password_hash(user["password_hash"], password):
# Store data in session
session["logged_in"] = True
session["username"] = username
session["role"] = user["role"]
from utils.database import user_must_change_password
if user_must_change_password(username):
session["must_change_password"] = True
logger.info(f"User '{username}' logged in; password change required.")
return redirect(url_for("change_password"))
session.pop("must_change_password", None)
logger.info(f"User '{username}' logged in successfully.")
return redirect(url_for("index"))
else:
logger.warning(f"Failed login attempt for username: {username}")
flash("ACCESS DENIED: INVALID CREDENTIALS", "error")
return render_template("login.html", version=VERSION)
@app.route("/")
def index() -> str:
if request.args.get("mode") == "satellite":
return redirect(url_for("satellite.satellite_dashboard"))
tools = {
"rtl_fm": check_tool("rtl_fm"),
"multimon": check_tool("multimon-ng"),
"rtl_433": check_tool("rtl_433"),
"rtlamr": check_tool("rtlamr"),
}
devices = describe_devices(SDRFactory.detect_devices())
return render_template(
"index.html",
tools=tools,
devices=devices,
version=VERSION,
changelog=CHANGELOG,
shared_observer_location=SHARED_OBSERVER_LOCATION_ENABLED,
default_latitude=DEFAULT_LATITUDE,
default_longitude=DEFAULT_LONGITUDE,
)
@app.route("/favicon.svg")
def favicon() -> Response:
return send_file("static/favicon.svg", mimetype="image/svg+xml")
@app.route("/sw.js")
def service_worker() -> Response:
resp = send_from_directory("static", "sw.js", mimetype="application/javascript")
resp.headers["Service-Worker-Allowed"] = "/"
return resp
@app.route("/manifest.json")
def pwa_manifest() -> Response:
return send_from_directory("static", "manifest.json", mimetype="application/manifest+json")
@app.route("/devices")
def get_devices() -> Response:
"""Get all detected SDR devices with hardware type info."""
return jsonify(describe_devices(SDRFactory.detect_devices()))
_NOTE_PROTOCOLS = {"bluetooth", "wifi", "rf", "adsb", "ais", "dsc", "aprs", "meshtastic", "meshcore", "other"}
_NOTE_IDENTIFIER = re.compile(r"^[A-Za-z0-9:._!-]{1,64}$")
def _clean_note(notes) -> str | None:
if notes is None:
return None
if not isinstance(notes, str):
raise ValueError("notes must be text")
notes = notes.strip()
if len(notes) > 2000:
raise ValueError("notes must be at most 2000 characters")
if any(ord(c) < 32 and c not in "\n\t" for c in notes):
raise ValueError("notes must not contain control characters")
return notes or None
def _clean_tags(tags) -> list[str]:
if tags is None:
return []
if not isinstance(tags, list) or len(tags) > 10:
raise ValueError("tags must be a list of at most 10")
cleaned = []
for tag in tags:
if not isinstance(tag, str) or not re.fullmatch(r"[\w .-]{1,32}", tag.strip()):
raise ValueError("each tag must be 1-32 letters, digits, spaces, dots or dashes")
if tag.strip() not in cleaned:
cleaned.append(tag.strip())
return cleaned
@app.route("/device-notes")
def list_device_notes() -> Response:
"""Every device an operator has noted or tagged, by identifier."""
from utils.database import get_device_annotations
return jsonify({"status": "success", "devices": get_device_annotations()})
@app.route("/device-notes/<identifier>", methods=["PUT", "DELETE"])
@(csrf.exempt if csrf else lambda f: f) # fetch() JSON API, like the blueprints
def update_device_notes(identifier: str) -> Response:
"""Set or clear an operator's note and tags on an observed device.
Shown wherever the device appears. A note does not make a device
known-good; that stays a separate, deliberate step.
"""
from utils.database import set_device_annotation
if not _NOTE_IDENTIFIER.match(identifier):
return jsonify({"status": "error", "message": "Invalid device identifier"}), 400
data = {} if request.method == "DELETE" else (request.get_json(silent=True) or {})
protocol = data.get("protocol") or "other"
if protocol not in _NOTE_PROTOCOLS:
return jsonify({"status": "error", "message": "Unknown protocol"}), 400
try:
notes = _clean_note(data.get("notes"))
tags = _clean_tags(data.get("tags"))
except ValueError as e:
return jsonify({"status": "error", "message": str(e)}), 400
return jsonify({"status": "success", "device": set_device_annotation(identifier, protocol, notes, tags)})
@app.route("/devices/config/<key>", methods=["PUT", "DELETE"])
@(csrf.exempt if csrf else lambda f: f) # fetch() JSON API, like the blueprints
def update_device_config(key: str) -> Response:
"""Set or clear a device's display name, PPM, default gain and bias-T."""
try:
data = {} if request.method == "DELETE" else request.get_json(silent=True)
config = set_device_config(key, data)
except ValueError as e:
return jsonify({"status": "error", "message": str(e)}), 400
return jsonify({"status": "success", "key": key, "config": config})
@app.route("/devices/status")
def get_devices_status() -> Response:
"""Get all SDR devices with usage status."""
devices = SDRFactory.detect_devices()
registry = get_sdr_device_status()
result = []
for device, d in zip(devices, describe_devices(devices)):
key = f"{device.sdr_type.value}:{device.index}"
d["in_use"] = key in registry
d["used_by"] = registry.get(key)
result.append(d)
return jsonify(result)
@app.route("/devices/debug")
def get_devices_debug() -> Response:
"""Get detailed SDR device detection diagnostics."""
import shutil
diagnostics = {
"tools": {},
"rtl_test": {},
"soapy": {},
"usb": {},
"kernel_modules": {},
"detected_devices": [],
"suggestions": [],
}
# Check for required tools
diagnostics["tools"]["rtl_test"] = shutil.which("rtl_test") is not None
diagnostics["tools"]["SoapySDRUtil"] = shutil.which("SoapySDRUtil") is not None
diagnostics["tools"]["lsusb"] = shutil.which("lsusb") is not None
# Run rtl_test and capture full output
if diagnostics["tools"]["rtl_test"]:
try:
result = subprocess.run(["rtl_test", "-t"], capture_output=True, text=True, timeout=5)
diagnostics["rtl_test"] = {
"returncode": result.returncode,
"stdout": result.stdout[:2000] if result.stdout else "",
"stderr": result.stderr[:2000] if result.stderr else "",
}
# Check for common errors
combined = (result.stdout or "") + (result.stderr or "")
if "No supported devices found" in combined:
diagnostics["suggestions"].append("No RTL-SDR device detected. Check USB connection.")
if "usb_claim_interface error" in combined:
diagnostics["suggestions"].append(
"Device busy - kernel DVB driver may have claimed it. Run: sudo modprobe -r dvb_usb_rtl28xxu"
)
if "Permission denied" in combined.lower():
diagnostics["suggestions"].append("USB permission denied. Add udev rules or run as root.")
except subprocess.TimeoutExpired:
diagnostics["rtl_test"] = {"error": "Timeout after 5 seconds"}
except Exception as e:
diagnostics["rtl_test"] = {"error": str(e)}
else:
diagnostics["suggestions"].append("rtl_test not found. Install rtl-sdr package.")
# Run SoapySDRUtil
if diagnostics["tools"]["SoapySDRUtil"]:
try:
result = subprocess.run(["SoapySDRUtil", "--find"], capture_output=True, text=True, timeout=10)
diagnostics["soapy"] = {
"returncode": result.returncode,
"stdout": result.stdout[:2000] if result.stdout else "",
"stderr": result.stderr[:2000] if result.stderr else "",
}
except subprocess.TimeoutExpired:
diagnostics["soapy"] = {"error": "Timeout after 10 seconds"}
except Exception as e:
diagnostics["soapy"] = {"error": str(e)}
# Check USB devices (Linux)
if diagnostics["tools"]["lsusb"]:
try:
result = subprocess.run(["lsusb"], capture_output=True, text=True, timeout=5)
# Filter for common SDR vendor IDs
sdr_vendors = ["0bda", "1d50", "1df7", "0403"] # Realtek, OpenMoko/HackRF, SDRplay, FTDI
usb_lines = [
l
for l in result.stdout.split("\n")
if any(v in l.lower() for v in sdr_vendors) or "rtl" in l.lower() or "sdr" in l.lower()
]
diagnostics["usb"]["devices"] = usb_lines if usb_lines else ["No SDR-related USB devices found"]
except Exception as e:
diagnostics["usb"] = {"error": str(e)}
# Check for loaded kernel modules that conflict (Linux)
if platform.system() == "Linux":
try:
result = subprocess.run(["lsmod"], capture_output=True, text=True, timeout=5)
conflicting = ["dvb_usb_rtl28xxu", "rtl2832", "rtl2830"]
loaded = [m for m in conflicting if m in result.stdout]
diagnostics["kernel_modules"]["conflicting_loaded"] = loaded
if loaded:
diagnostics["suggestions"].append(
f"Conflicting kernel modules loaded: {', '.join(loaded)}. Run: sudo modprobe -r {' '.join(loaded)}"
)
except Exception as e:
diagnostics["kernel_modules"] = {"error": str(e)}
# Get detected devices
devices = SDRFactory.detect_devices()
diagnostics["detected_devices"] = [d.to_dict() for d in devices]
if not devices and not diagnostics["suggestions"]:
diagnostics["suggestions"].append("No devices detected. Check USB connection and driver installation.")
return jsonify(diagnostics)
@app.route("/settings/theme", methods=["GET", "POST"])
def theme_setting() -> Response:
"""Read or save the UI theme, so it can sync across devices.
The page also keeps the theme in localStorage for an instant, flash-free
load; this is the shared copy it reconciles against.
"""
from utils.database import get_setting, set_setting
if request.method == "POST":
data = request.get_json(silent=True) or {}
value = data.get("value") or data.get("theme")
if value not in ("dark", "light"):
return jsonify({"status": "error", "message": "theme must be 'dark' or 'light'"}), 400
set_setting("ui.theme", value)
return jsonify({"status": "success", "value": value})
return jsonify({"status": "success", "value": get_setting("ui.theme", None)})
@app.route("/dependencies")
def get_dependencies() -> Response:
"""Get status of all tool dependencies."""
from utils.dependencies import install_hints, package_manager
results = check_all_dependencies()
return jsonify(
{
"status": "success",
"os": platform.system().lower(),
"pkg_manager": package_manager(),
"install_hints": install_hints(),
"modes": results,
}
)
@app.route("/export/aircraft", methods=["GET"])
def export_aircraft() -> Response:
"""Export aircraft data as JSON or CSV."""
import csv
import io
format_type = request.args.get("format", "json").lower()
if format_type == "csv":
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["icao", "callsign", "altitude", "speed", "heading", "lat", "lon", "squawk", "last_seen"])
for icao, ac in adsb_aircraft.items():
writer.writerow(
[
icao,
ac.get("callsign", "") if isinstance(ac, dict) else "",
ac.get("altitude", "") if isinstance(ac, dict) else "",
ac.get("speed", "") if isinstance(ac, dict) else "",
ac.get("heading", "") if isinstance(ac, dict) else "",
ac.get("lat", "") if isinstance(ac, dict) else "",
ac.get("lon", "") if isinstance(ac, dict) else "",
ac.get("squawk", "") if isinstance(ac, dict) else "",
ac.get("lastSeen", "") if isinstance(ac, dict) else "",
]
)
response = Response(output.getvalue(), mimetype="text/csv")
response.headers["Content-Disposition"] = "attachment; filename=aircraft.csv"
return response
else:
return jsonify(
{"timestamp": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).replace(tzinfo=None).isoformat(), "aircraft": adsb_aircraft.values()}
)
@app.route("/export/wifi", methods=["GET"])
def export_wifi() -> Response:
"""Export WiFi networks as JSON or CSV."""
import csv
import io
format_type = request.args.get("format", "json").lower()
if format_type == "csv":
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["bssid", "ssid", "channel", "signal", "encryption", "clients"])
for bssid, net in wifi_networks.items():
writer.writerow(
[
bssid,
net.get("ssid", "") if isinstance(net, dict) else "",
net.get("channel", "") if isinstance(net, dict) else "",
net.get("signal", "") if isinstance(net, dict) else "",
net.get("encryption", "") if isinstance(net, dict) else "",
net.get("clients", 0) if isinstance(net, dict) else 0,
]
)
response = Response(output.getvalue(), mimetype="text/csv")
response.headers["Content-Disposition"] = "attachment; filename=wifi_networks.csv"
return response
else:
return jsonify(
{
"timestamp": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).replace(tzinfo=None).isoformat(),
"networks": wifi_networks.values(),
"clients": wifi_clients.values(),
}
)
@app.route("/export/bluetooth", methods=["GET"])
def export_bluetooth() -> Response:
"""Export Bluetooth devices as JSON or CSV."""
import csv
import io
format_type = request.args.get("format", "json").lower()
if format_type == "csv":
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["mac", "name", "rssi", "type", "manufacturer", "last_seen"])
for mac, dev in bt_devices.items():
writer.writerow(
[
mac,
dev.get("name", "") if isinstance(dev, dict) else "",
dev.get("rssi", "") if isinstance(dev, dict) else "",
dev.get("type", "") if isinstance(dev, dict) else "",
dev.get("manufacturer", "") if isinstance(dev, dict) else "",
dev.get("lastSeen", "") if isinstance(dev, dict) else "",
]
)
response = Response(output.getvalue(), mimetype="text/csv")
response.headers["Content-Disposition"] = "attachment; filename=bluetooth_devices.csv"
return response
else:
return jsonify(
{
"timestamp": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).replace(tzinfo=None).isoformat(),
"devices": bt_devices.values(),
"beacons": bt_beacons.values(),
}
)
def _get_subghz_active() -> bool:
"""Check if SubGHz manager has an active process."""
try:
from utils.subghz import get_subghz_manager
return get_subghz_manager().active_mode != "idle"
except Exception:
return False
def _get_singleton_running(module_path: str, getter_name: str, attr: str) -> bool:
"""Safely check if a singleton-based mode is running without creating instances."""
try:
import importlib
mod = importlib.import_module(module_path)
getter = getattr(mod, getter_name)