Release WiFi GPS Mapper v2.3.0

This commit is contained in:
2026-12-03 17:24:35 +03:00
parent 9682cc5b49
commit cec80c2b48
16 changed files with 2910 additions and 318 deletions
+632 -166
View File
@@ -78,10 +78,15 @@ from reports.vendors import render_vendors_page
from vendor_service import VendorService
from sudo import SudoChecker
from config import Config
from database import Database
from parser import CaptureParser
from session import Session
from reports.recovery import CAPTURES_DIR, _has_recoverable_capture
from gps_test import GPSTestService
from auto_gps import AutoGPSService
from auto_wifi_verification import AutoWiFiVerificationService
from wifi_connection import WiFiConnectionError, WiFiConnectionService
from gpsrelay_discovery import GPSRelayDiscoveryError, discover_gpsrelay
from gui.timezones import get_timezone_options
from logging_config import (
LOG_DATE_FORMAT,
@@ -273,6 +278,8 @@ def scanner_navigation_guard():
"api_wifi_verification_stop",
"api_wifi_verification_settings",
"api_wifi_verification_settings_save",
"api_wifi_verification_gpsrelay_discovery_start",
"api_wifi_verification_gpsrelay_discovery_status",
"api_wifi_verification_radius_apply",
"static",
}
@@ -309,6 +316,8 @@ def scanner_navigation_guard():
"scanner_stop",
"api_gps_test",
"gps_test_stop",
"api_wifi_verification_gpsrelay_discovery_start",
"api_wifi_verification_gpsrelay_discovery_status",
"static"
}
@@ -368,6 +377,10 @@ auto_wifi_verification_service = None
auto_wifi_verification_lock = threading.Lock()
gpsrelay_discovery_job = None
gpsrelay_discovery_thread = None
gpsrelay_discovery_lock = threading.Lock()
# Shared GPS service for the Auto Verification map and Auto Verification worker.
wifi_verification_shared_gps_service = None
wifi_verification_shared_gps_lock = threading.RLock()
@@ -642,35 +655,14 @@ def _stop_wifi_verification_shared_gps_locked():
def acquire_wifi_verification_network_owner(owner, gps_service):
if owner == "MANUAL_WIFI_VERIFY":
with scanner_lock:
return _acquire_network_owner_locked(owner)
if owner != "AUTO_WIFI_VERIFY":
return acquire_network_owner(owner)
with wifi_verification_shared_gps_lock:
if wifi_verification_map_monitor_enabled:
thread = gps_service.thread
if thread is None or not thread.is_alive():
return False, (
"Map GPS monitor is enabled, "
"but its GPS service is not running."
)
with scanner_lock:
transferred = _transfer_network_owner_locked(
"MAP_GPS_MONITOR",
"AUTO_WIFI_VERIFY"
)
if not transferred:
return False, (
"Unable to transfer network ownership "
"from the map GPS monitor."
)
return True, None
with scanner_lock:
acquired, error = _acquire_network_owner_locked(owner)
@@ -678,6 +670,11 @@ def acquire_wifi_verification_network_owner(owner, gps_service):
return False, error
try:
if gps_service is None:
raise RuntimeError(
"Shared GPS service is not configured."
)
thread = gps_service.thread
if thread is not None and thread.is_alive():
@@ -710,30 +707,19 @@ def acquire_wifi_verification_network_owner(owner, gps_service):
def release_wifi_verification_network_owner(owner):
if owner == "MANUAL_WIFI_VERIFY":
with scanner_lock:
if network_operation_owner == owner:
_release_network_owner_locked(owner)
return
if owner != "AUTO_WIFI_VERIFY":
release_network_owner(owner)
return
with wifi_verification_shared_gps_lock:
if wifi_verification_map_monitor_enabled:
with scanner_lock:
transferred = _transfer_network_owner_locked(
"AUTO_WIFI_VERIFY",
"MAP_GPS_MONITOR"
)
if not transferred:
logger.warning(
"Could not return network ownership "
"to the map GPS monitor."
)
return
with scanner_lock:
current_owner = network_operation_owner
if current_owner == owner:
@@ -742,7 +728,8 @@ def release_wifi_verification_network_owner(owner):
elif current_owner is not None:
return
_stop_wifi_verification_shared_gps_locked()
if not wifi_verification_map_monitor_enabled:
_stop_wifi_verification_shared_gps_locked()
def network_actions_busy():
@@ -2388,6 +2375,261 @@ def reports_trips():
)
@app.route(
"/reports/recovery/<directory_name>",
methods=["POST"]
)
def reports_recovery_restore(directory_name):
captures_root = Path(
CAPTURES_DIR
).resolve()
session_path = (
captures_root / directory_name
).resolve()
if session_path.parent != captures_root:
abort(400)
if not session_path.is_dir():
abort(404)
capture_file = (
session_path / "capture.pcapng"
)
if not capture_file.is_file():
return jsonify(
{
"error": "Capture file was not found."
}
), 400
if capture_file.stat().st_size <= 0:
return jsonify(
{
"error": "Capture file is empty."
}
), 400
if not _has_recoverable_capture(session_path):
return jsonify(
{
"error": (
"Capture duration is shorter than "
"the required 5 minutes."
)
}
), 400
acquired, lock_error = acquire_network_owner(
"SESSION_RECOVERY"
)
if not acquired:
return jsonify(
{
"error": (
lock_error
or "Network operation is currently busy."
)
}
), 409
db = None
try:
cfg = Config()
db = Database(
cfg.database
)
existing_sessions = db.conn.execute(
"""
SELECT
id,
capture_file
FROM capture_sessions
"""
).fetchall()
for row in existing_sessions:
stored_capture_file = row["capture_file"]
if not stored_capture_file:
continue
if Path(
stored_capture_file
).resolve() == capture_file.resolve():
return jsonify(
{
"error": (
"A database record already exists "
"for this capture."
),
"session_id": row["id"],
}
), 409
session = Session.from_existing(
session_path
)
session_id = db.create_session(
str(session.capture_file),
start_time=session.start_time
)
session.id = session_id
parser = CaptureParser(
cfg,
db
)
parser.parse(
session,
session_id
)
db.flush_observations()
event_times = []
timestamp_sources = (
("gps_track", "timestamp"),
("access_point_observations", "observed_at"),
("handshakes", "captured_at"),
)
for table, column in timestamp_sources:
rows = db.conn.execute(
f"""
SELECT {column}
FROM {table}
WHERE session_id = ?
AND {column} IS NOT NULL
""",
(session_id,),
).fetchall()
for row in rows:
try:
timestamp = datetime.fromisoformat(
str(row[0]).replace("Z", "+00:00")
)
except ValueError:
continue
if timestamp.tzinfo is None:
timestamp = timestamp.replace(
tzinfo=timezone.utc
)
else:
timestamp = timestamp.astimezone(
timezone.utc
)
event_times.append(timestamp)
if event_times:
start_time = min(event_times)
end_time = max(event_times)
db.conn.execute(
"""
UPDATE capture_sessions
SET start_time = ?,
end_time = ?
WHERE id = ?
""",
(
start_time.isoformat().replace("+00:00", "Z"),
end_time.isoformat().replace("+00:00", "Z"),
session_id,
),
)
recovered = db.finalize_session(
session_id
)
db.commit()
if not recovered:
return jsonify(
{
"error": (
"Parsing completed, but no GPS positions, "
"access points or handshakes were found. "
"The empty database record was removed."
)
}
), 422
logger.info(
"Interrupted capture recovered: %s (session_id=%s)",
session_path,
session_id,
)
return redirect(
url_for("reports_trips")
)
except Exception:
if db is not None:
try:
db.rollback()
except Exception:
logger.exception(
"Failed to rollback session recovery."
)
finally:
db.observation_buffer.clear()
logger.exception(
"Failed to recover interrupted capture: %s",
session_path,
)
return jsonify(
{
"error": "Failed to recover interrupted capture."
}
), 500
finally:
if db is not None:
try:
db.close()
except Exception:
logger.exception(
"Failed to close database after session recovery."
)
release_network_owner(
"SESSION_RECOVERY"
)
@app.route("/reports/trips/preview")
def reports_trips_preview():
@@ -3183,6 +3425,232 @@ def api_gps_test():
def _run_gpsrelay_discovery(port):
global gpsrelay_discovery_job
try:
result = discover_gpsrelay(port)
with gpsrelay_discovery_lock:
gpsrelay_discovery_job = {
"state": "SUCCEEDED",
"running": False,
"port": port,
"result": result,
"error": None,
}
except GPSRelayDiscoveryError as error:
with gpsrelay_discovery_lock:
gpsrelay_discovery_job = {
"state": "FAILED",
"running": False,
"port": port,
"result": None,
"error": str(error),
}
except Exception:
app.logger.exception(
"Unexpected GPSRelay discovery error"
)
with gpsrelay_discovery_lock:
gpsrelay_discovery_job = {
"state": "FAILED",
"running": False,
"port": port,
"result": None,
"error": "Unexpected GPSRelay discovery error.",
}
finally:
try:
release_network_owner("GPSRELAY_DISCOVERY")
except Exception:
app.logger.exception(
"Could not release GPSRelay discovery network owner"
)
@app.route(
"/api/wifi-verification/gpsrelay-discovery/start",
methods=["POST"]
)
def api_wifi_verification_gpsrelay_discovery_start():
global gpsrelay_discovery_job
global gpsrelay_discovery_thread
payload = request.get_json(silent=True)
if payload is None:
payload = {}
if not isinstance(payload, dict):
return jsonify(
{
"ok": False,
"error": "Invalid request body.",
}
), 400
raw_port = payload.get("port", 5000)
if raw_port is None or raw_port == "":
raw_port = 5000
if isinstance(raw_port, bool):
return jsonify(
{
"ok": False,
"error": "Port must be an integer between 1 and 65535.",
}
), 400
if isinstance(raw_port, int):
port = raw_port
elif isinstance(raw_port, str) and raw_port.strip().isdigit():
port = int(raw_port.strip())
else:
return jsonify(
{
"ok": False,
"error": "Port must be an integer between 1 and 65535.",
}
), 400
if not 1 <= port <= 65535:
return jsonify(
{
"ok": False,
"error": "Port must be between 1 and 65535.",
}
), 400
start_error = False
with auto_wifi_verification_lock:
current = auto_wifi_verification_service
if (
current is not None
and current.thread is not None
and current.thread.is_alive()
):
return jsonify(
{
"ok": False,
"error": "Auto Verification is running.",
}
), 409
with gpsrelay_discovery_lock:
if (
gpsrelay_discovery_thread is not None
and gpsrelay_discovery_thread.is_alive()
):
return jsonify(
{
"ok": False,
"error": "GPSRelay discovery is already running.",
}
), 409
acquired, error = acquire_network_owner(
"GPSRELAY_DISCOVERY"
)
if not acquired:
return jsonify(
{
"ok": False,
"error": error or "Network interface is busy.",
}
), 409
gpsrelay_discovery_job = {
"state": "RUNNING",
"running": True,
"port": port,
"result": None,
"error": None,
}
gpsrelay_discovery_thread = threading.Thread(
target=_run_gpsrelay_discovery,
args=(port,),
daemon=True,
)
try:
gpsrelay_discovery_thread.start()
except Exception:
app.logger.exception(
"Could not start GPSRelay discovery thread"
)
gpsrelay_discovery_thread = None
gpsrelay_discovery_job = {
"state": "FAILED",
"running": False,
"port": port,
"result": None,
"error": "Could not start GPSRelay discovery.",
}
start_error = True
if start_error:
release_network_owner("GPSRELAY_DISCOVERY")
return jsonify(
{
"ok": False,
"error": "Could not start GPSRelay discovery.",
}
), 500
return jsonify(
{
"ok": True,
"state": "RUNNING",
"port": port,
}
), 202
@app.route(
"/api/wifi-verification/gpsrelay-discovery/status",
methods=["GET"]
)
def api_wifi_verification_gpsrelay_discovery_status():
with gpsrelay_discovery_lock:
if gpsrelay_discovery_job is None:
job = {
"state": "IDLE",
"running": False,
"port": None,
"result": None,
"error": None,
}
else:
job = dict(gpsrelay_discovery_job)
return jsonify(
{
"ok": True,
**job,
}
)
@app.route("/api/wifi-verification/settings", methods=["GET"])
def api_wifi_verification_settings():
conn = None
@@ -3598,7 +4066,6 @@ def api_wifi_verification_map_gps_start():
service = wifi_verification_shared_gps_service
if wifi_verification_map_monitor_enabled:
if (
service is not None
and service.thread is not None
@@ -3613,42 +4080,45 @@ def api_wifi_verification_map_gps_start():
wifi_verification_map_monitor_enabled = False
if auto_running:
if auto_service.verification_mode == "MANUAL":
settings = auto_service.settings
else:
if (
service is None
or service.thread is None
or not service.thread.is_alive()
):
return jsonify({
"ok": False,
"error": (
"GPS service used by Auto Verification "
"is not running."
)
}), 409
wifi_verification_map_monitor_enabled = True
if (
service is None
or service.thread is None
or not service.thread.is_alive()
):
return jsonify({
"ok": False,
"error": (
"GPS service used by Auto Verification "
"is not running."
)
}), 409
"ok": True,
"monitor_enabled": True,
"gps": service.get_status()
})
wifi_verification_map_monitor_enabled = True
else:
connection = connect_database()
return jsonify({
"ok": True,
"monitor_enabled": True,
"gps": service.get_status()
})
row = connection.execute(
"""
SELECT *
FROM wifi_verification_settings
WHERE id = 1
"""
).fetchone()
connection = connect_database()
settings = dict(row) if row is not None else None
row = connection.execute(
"""
SELECT *
FROM wifi_verification_settings
WHERE id = 1
"""
).fetchone()
settings = dict(row) if row is not None else None
close_database(connection)
connection = None
close_database(connection)
connection = None
if settings is None:
return jsonify({
@@ -3665,20 +4135,7 @@ def api_wifi_verification_map_gps_start():
):
return jsonify({
"ok": False,
"error": (
"Select GPS source: gpsd or gpsrelay."
)
}), 409
acquired, owner_error = acquire_network_owner(
"MAP_GPS_MONITOR"
)
if not acquired:
return jsonify({
"ok": False,
"error": owner_error,
"owner": network_operation_owner
"error": "Select GPS source: gpsd or gpsrelay."
}), 409
service = _get_wifi_verification_shared_gps(
@@ -3699,22 +4156,16 @@ def api_wifi_verification_map_gps_start():
)
if not started:
cleanup_ok = True
thread = service.thread
if started_service:
cleanup_ok = (
if thread is None or not thread.is_alive():
if started_service:
_stop_wifi_verification_shared_gps_locked()
)
if cleanup_ok:
release_network_owner(
"MAP_GPS_MONITOR"
)
return jsonify({
"ok": False,
"error": "GPS service could not be started."
}), 409
return jsonify({
"ok": False,
"error": "GPS service could not be started."
}), 409
wifi_verification_map_monitor_enabled = True
@@ -3732,20 +4183,8 @@ def api_wifi_verification_map_gps_start():
with wifi_verification_shared_gps_lock:
cleanup_ok = True
if started_service and service is not None:
cleanup_ok = (
_stop_wifi_verification_shared_gps_locked()
)
if (
cleanup_ok
and network_operation_owner == "MAP_GPS_MONITOR"
):
release_network_owner(
"MAP_GPS_MONITOR"
)
_stop_wifi_verification_shared_gps_locked()
return jsonify({
"ok": False,
@@ -3769,12 +4208,9 @@ def api_wifi_verification_map_gps_stop():
with auto_wifi_verification_lock:
with wifi_verification_shared_gps_lock:
wifi_verification_map_monitor_enabled = False
owner = network_operation_owner
if owner == "AUTO_WIFI_VERIFY":
service = wifi_verification_shared_gps_service
gps_status = (
@@ -3783,67 +4219,39 @@ def api_wifi_verification_map_gps_stop():
else None
)
wifi_verification_map_monitor_enabled = False
return jsonify({
"ok": True,
"monitor_enabled": False,
"stop_deferred": True,
"owner": owner,
"gps": gps_status
})
if owner == "MAP_GPS_MONITOR":
stopped = (
_stop_wifi_verification_shared_gps_locked()
)
if not stopped:
return jsonify({
"ok": False,
"error": (
"GPS service did not stop. "
"Its state was preserved."
),
"monitor_enabled": False
}), 409
release_network_owner(
"MAP_GPS_MONITOR"
)
elif owner is not None:
stopped = (
_stop_wifi_verification_shared_gps_locked()
)
if not stopped:
return jsonify({
"ok": False,
"error": (
"GPS is owned by another operation."
"GPS service did not stop. "
"Its state was preserved."
),
"owner": owner,
"monitor_enabled": False
"monitor_enabled": (
wifi_verification_map_monitor_enabled
)
}), 409
else:
service = wifi_verification_shared_gps_service
if (
service is not None
and service.thread is not None
and service.thread.is_alive()
):
stopped = (
_stop_wifi_verification_shared_gps_locked()
)
if not stopped:
return jsonify({
"ok": False,
"error": "GPS service did not stop."
}), 409
wifi_verification_map_monitor_enabled = False
return jsonify({
"ok": True,
"monitor_enabled": False,
"stop_deferred": False
"stop_deferred": False,
"owner": owner
})
except Exception:
@@ -3919,6 +4327,51 @@ def api_wifi_verification_start():
interface = interface.strip()
mode = data.get("mode", "AUTO")
if not isinstance(mode, str):
return jsonify({
"ok": False,
"error": "Invalid verification mode."
}), 400
mode = mode.strip().upper()
if mode not in ("AUTO", "MANUAL"):
return jsonify({
"ok": False,
"error": "Invalid verification mode."
}), 400
manual_center = None
if mode == "MANUAL":
coordinates = data.get("manual_center")
if (
not isinstance(coordinates, list)
or len(coordinates) != 2
or any(type(value) not in (int, float) for value in coordinates)
):
return jsonify({
"ok": False,
"error": "Manual center must contain numeric latitude and longitude."
}), 400
latitude = float(coordinates[0])
longitude = float(coordinates[1])
if not (
-90 <= latitude <= 90
and -180 <= longitude <= 180
):
return jsonify({
"ok": False,
"error": "Manual center coordinates are out of range."
}), 400
manual_center = (latitude, longitude)
device, error, status = validate_network_interface(
interface
)
@@ -3977,7 +4430,10 @@ def api_wifi_verification_start():
}
), 409
if settings.get("gps_source") not in ("gpsd", "gpsrelay"):
if (
mode == "AUTO"
and settings.get("gps_source") not in ("gpsd", "gpsrelay")
):
return jsonify(
{
@@ -4002,9 +4458,17 @@ def api_wifi_verification_start():
}
), 409
shared_gps_service = (
_get_wifi_verification_shared_gps(settings)
)
if mode == "AUTO":
shared_gps_service = (
_get_wifi_verification_shared_gps(settings)
)
else:
with wifi_verification_shared_gps_lock:
shared_gps_service = (
wifi_verification_shared_gps_service
if wifi_verification_map_monitor_enabled
else None
)
service = AutoWiFiVerificationService(
settings=settings,
@@ -4019,7 +4483,9 @@ def api_wifi_verification_start():
),
release_network_owner=(
release_wifi_verification_network_owner
)
),
mode=mode,
manual_center=manual_center
)
auto_wifi_verification_service = service