diff --git a/README.md b/README.md index 44bc3fa..920ce8a 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,23 @@ does not already exist. Local configuration, databases, captures and generated map data are not part of the source repository. +## Network scanning and connection verification + +An active VPN connection may affect Wi-Fi scanning, local network +reachability and Wi-Fi connection verification. + +The application can detect active VPN connections managed by +NetworkManager and display an advisory warning. VPN connections +started outside NetworkManager may not be detected. + +It is recommended to disable VPN connections while scanning Wi-Fi +networks and performing Wi-Fi connection verification. Results +cannot be guaranteed when a VPN is active. + +The warning is advisory only. The application does not block user +actions, disconnect VPN connections, modify VPN settings or attempt +to restore a previous VPN state. + ## License WiFi GPS Mapper is distributed under the MIT License. diff --git a/gui/app.py b/gui/app.py index 2f2a6c8..e12ab92 100644 --- a/gui/app.py +++ b/gui/app.py @@ -34,6 +34,10 @@ from flask import ( ) from reports.database import close as close_database + +from flask import jsonify, render_template, send_from_directory +from reports.map_popups import build_standard_popup +from reports.map_service import get_map_style_url from reports.database import connect as connect_database from reports.dashboard import ( generate_capture_sessions, @@ -75,6 +79,8 @@ from vendor_service import VendorService from sudo import SudoChecker from config import Config from gps_test import GPSTestService +from auto_gps import AutoGPSService +from auto_wifi_verification import AutoWiFiVerificationService from wifi_connection import WiFiConnectionError, WiFiConnectionService from gui.timezones import get_timezone_options from logging_config import ( @@ -248,6 +254,37 @@ def internal_server_error(error): @app.before_request def scanner_navigation_guard(): + # Keep the application isolated while Auto owns the Wi-Fi interface. + with auto_wifi_verification_lock: + auto_service = auto_wifi_verification_service + + if auto_service is not None: + auto_status = auto_service.get_status() + + if auto_status.get("running"): + auto_allowed_endpoints = { + "auto_verification_map", + "auto_verification_map_asset", + "api_wifi_verification_map_data", + "api_wifi_verification_map_gps_status", + "api_wifi_verification_map_gps_start", + "api_wifi_verification_map_gps_stop", + "api_wifi_verification_status", + "api_wifi_verification_stop", + "api_wifi_verification_settings", + "api_wifi_verification_settings_save", + "api_wifi_verification_radius_apply", + "static", + } + + if ( + request.endpoint is not None + and request.endpoint not in auto_allowed_endpoints + ): + return redirect(url_for("auto_verification_map")) + + return None + status = get_scanner_status() @@ -289,6 +326,8 @@ scanner_starting = False network_action_active = False +network_operation_owner = None + scanner_health = "READY" scanner_stopped_at = None @@ -321,6 +360,20 @@ gps_test_service = None gps_test_lock = threading.Lock() +auto_gps_service = None + +auto_gps_lock = threading.Lock() + +auto_wifi_verification_service = None + +auto_wifi_verification_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() +wifi_verification_map_monitor_enabled = False +wifi_verification_map_monitor_last_seen = 0.0 + sudo_keepalive_stop_event = threading.Event() sudo_keepalive_thread = None @@ -399,11 +452,306 @@ def get_gps_test_status(): "error": service.error } +def _acquire_network_owner_locked(owner): + + global network_action_active + global network_operation_owner + + if network_operation_owner is not None: + + return False, ( + f"Wi-Fi adapter is busy: " + f"{network_operation_owner}." + ) + + if network_action_active: + + return False, ( + "Another Wi-Fi connection operation is in progress." + ) + + if ( + scanner_starting + or + ( + scanner_process is not None + and + scanner_process.poll() is None + ) + ): + + return False, ( + "Wi-Fi operation is unavailable while the scanner is running." + ) + + with gps_test_lock: + + if ( + gps_test_service is not None + and + gps_test_service.thread is not None + and + gps_test_service.thread.is_alive() + ): + + return False, ( + "Wi-Fi operation is unavailable while the GPS test is running." + ) + + network_operation_owner = owner + + if owner == "MANUAL_NETWORK": + + network_action_active = True + + return True, None + + +def acquire_network_owner(owner): + + with scanner_lock: + + return _acquire_network_owner_locked(owner) + + +def _transfer_network_owner_locked(current_owner, new_owner): + global network_operation_owner + + if network_operation_owner != current_owner: + return False + + network_operation_owner = new_owner + return True + + +def transfer_network_owner(current_owner, new_owner): + + with scanner_lock: + + return _transfer_network_owner_locked( + current_owner, + new_owner + ) + + +def _release_network_owner_locked(owner): + + global network_action_active + global network_operation_owner + + if network_operation_owner != owner: + + return False + + network_operation_owner = None + + if owner == "MANUAL_NETWORK": + + network_action_active = False + + return True + + +def release_network_owner(owner): + + with scanner_lock: + + return _release_network_owner_locked(owner) + + +def _wifi_verification_shared_gps_position_callback(gps): + + service = auto_wifi_verification_service + + if service is None: + return + + try: + service._gps_fix_callback(gps) + except Exception: + logger.exception( + "Failed to forward shared GPS position to Auto Verification." + ) + + +def _get_wifi_verification_shared_gps(settings): + + global wifi_verification_shared_gps_service + + with wifi_verification_shared_gps_lock: + + service = wifi_verification_shared_gps_service + + if ( + service is not None + and service.thread is not None + and service.thread.is_alive() + ): + return service + + service = AutoGPSService( + settings, + position_callback=( + _wifi_verification_shared_gps_position_callback + ) + ) + + wifi_verification_shared_gps_service = service + + return service + + +def _stop_wifi_verification_shared_gps_locked(): + + global wifi_verification_shared_gps_service + + service = wifi_verification_shared_gps_service + + if service is None: + return True + + try: + service.stop() + + thread = service.thread + + if ( + thread is not None + and thread.is_alive() + and thread is not threading.current_thread() + ): + thread.join(timeout=5) + + if thread is not None and thread.is_alive(): + logger.warning( + "Shared Wi-Fi verification GPS thread " + "did not stop within 5 seconds." + ) + return False + + wifi_verification_shared_gps_service = None + + return True + + except Exception: + logger.exception( + "Failed to stop shared Wi-Fi verification GPS service." + ) + return False + + +def acquire_wifi_verification_network_owner(owner, gps_service): + + 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) + + if not acquired: + return False, error + + try: + thread = gps_service.thread + + if thread is not None and thread.is_alive(): + return True, None + + started = gps_service.start() + + if not started: + thread = gps_service.thread + + if thread is not None and thread.is_alive(): + return True, None + + raise RuntimeError( + "Shared GPS service could not be started." + ) + + return True, None + + except Exception as error: + logger.exception( + "Failed to start shared GPS for Auto Verification." + ) + + with scanner_lock: + _release_network_owner_locked(owner) + + return False, str(error) + + +def release_wifi_verification_network_owner(owner): + + 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: + _release_network_owner_locked(owner) + + elif current_owner is not None: + return + + _stop_wifi_verification_shared_gps_locked() + + def network_actions_busy(): with scanner_lock: if ( + network_operation_owner is not None + or network_action_active or scanner_starting @@ -414,6 +762,7 @@ def network_actions_busy(): scanner_process.poll() is None ) ): + return True with gps_test_lock: @@ -426,52 +775,29 @@ def network_actions_busy(): gps_test_service.thread.is_alive() ) + def begin_network_action(): - global network_action_active - - with scanner_lock: - - if network_action_active: - - return False, "Another Wi-Fi connection operation is in progress." - - if ( - scanner_starting - or - ( - scanner_process is not None - and - scanner_process.poll() is None - ) - ): - - return False, "Wi-Fi operation is unavailable while the scanner is running." - - with gps_test_lock: - - if ( - gps_test_service is not None - and - gps_test_service.thread is not None - and - gps_test_service.thread.is_alive() - ): - - return False, "Wi-Fi operation is unavailable while the GPS test is running." - - network_action_active = True - - return True, None + return acquire_network_owner("MANUAL_NETWORK") def end_network_action(): - global network_action_active + release_network_owner("MANUAL_NETWORK") + + +def watch_gps_test(service): + + thread = service.thread + + if thread is not None: + + thread.join() with scanner_lock: - network_action_active = False + _release_network_owner_locked("GPS_TEST") + def get_scanner_status(): @@ -594,6 +920,28 @@ def read_scanner_output(process): pass + try: + + process.wait() + + except Exception as error: + + with scanner_lock: + + scanner_output.append( + f"[GUI] Scanner wait error: {error}" + ) + + while process.poll() is None: + + time.sleep(0.1) + + with scanner_lock: + + _release_network_owner_locked( + "SCANNER" + ) + def get_nm_wifi_devices(): command = [ @@ -693,7 +1041,7 @@ def get_nm_wifi_devices(): return devices, None -def get_active_wireguard_connections(): +def get_active_vpn_status(): command = [ "nmcli", @@ -701,7 +1049,7 @@ def get_active_wireguard_connections(): "--escape", "yes", "--fields", - "TYPE,DEVICE", + "TYPE", "connection", "show", "--active" @@ -722,7 +1070,7 @@ def get_active_wireguard_connections(): except Exception as error: - return [], str(error) + return False, str(error) if result.returncode != 0: @@ -732,29 +1080,16 @@ def get_active_wireguard_connections(): f"nmcli exited with code {result.returncode}" ) - return [], error + return False, error - wireguard_connections = [] + vpn_types = {"vpn", "wireguard"} - for line in result.stdout.splitlines(): + active = any( + line.strip().lower() in vpn_types + for line in result.stdout.splitlines() + ) - parts = line.split(":", 1) - - if len(parts) != 2: - continue - - connection_type, device = parts - - if connection_type == "wireguard": - - wireguard_connections.append( - { - "type": connection_type, - "device": device - } - ) - - return wireguard_connections, None + return active, None def get_wifi_interfaces(): @@ -2376,6 +2711,43 @@ def reports_trips_import(): ) + +@app.route("/access-points/auto-verification") +def auto_verification_map(): + + interfaces, interface_error = ( + get_wifi_interfaces() + ) + + return render_template( + "auto_verification_map.html", + map_style_url=get_map_style_url(), + interfaces=interfaces, + interface_error=interface_error + ) + + +@app.route("/auto-verification/assets/") +def auto_verification_map_asset(filename): + + return send_from_directory( + PROJECT_ROOT / "reports" / "static" / "maplibre", + filename + ) + + +@app.route("/api/wifi-verification/map-data") +def api_wifi_verification_map_data(): + + from reports.auto_verification_map import ( + build_auto_verification_geojson, + ) + + return jsonify( + build_auto_verification_geojson() + ) + + @app.route("/reports/session/") def reports_session(session_id): @@ -2654,58 +3026,21 @@ def gps_test_start(): with scanner_lock: - if network_action_active: + acquired, error = _acquire_network_owner_locked( + "GPS_TEST" + ) + + if not acquired: return jsonify( { "ok": False, - "error": - "A Wi-Fi connection operation is in progress." - } - ), 409 - - if ( - scanner_starting - or - ( - scanner_process is not None - and - scanner_process.poll() is None - ) - ): - - scanner_output.append( - "[GUI] GPS test cannot start " - "while scanner is running." - ) - - return jsonify( - { - "ok": False, - "error": - "GPS test cannot start " - "while scanner is running." + "error": error } ), 409 with gps_test_lock: - if ( - gps_test_service is not None - and - gps_test_service.thread is not None - and - gps_test_service.thread.is_alive() - ): - - return jsonify( - { - "ok": False, - "error": - "GPS test is already running." - } - ), 409 - try: cfg = Config() @@ -2719,21 +3054,29 @@ def gps_test_start(): gps_test_service = None + _release_network_owner_locked( + "GPS_TEST" + ) + return jsonify( { "ok": False, - "error": - "Failed to start GPS test." + "error": "Failed to start GPS test." } ), 500 + service = gps_test_service + except Exception as error: gps_test_service = None + _release_network_owner_locked( + "GPS_TEST" + ) + scanner_output.append( - f"[GUI] Failed to start GPS test: " - f"{error}" + f"[GUI] Failed to start GPS test: {error}" ) return jsonify( @@ -2743,6 +3086,35 @@ def gps_test_start(): } ), 500 + watcher = threading.Thread( + target=watch_gps_test, + args=(service,), + daemon=True + ) + + try: + + watcher.start() + + except Exception: + + # Если монитор не удалось запустить, не освобождаем + # адаптер до фактического завершения GPS-потока. + if service.thread is not None: + + service.thread.join() + + with scanner_lock: + + _release_network_owner_locked("GPS_TEST") + + return jsonify( + { + "ok": False, + "error": "Failed to monitor GPS test." + } + ), 500 + return jsonify( { "ok": True @@ -2808,6 +3180,922 @@ def api_gps_test(): get_gps_test_status() ) + + + +@app.route("/api/wifi-verification/settings", methods=["GET"]) +def api_wifi_verification_settings(): + conn = None + + try: + conn = connect_database() + + row = conn.execute( + """ + SELECT + gps_source, + gpsrelay_host, + gpsrelay_port, + radius_m, + gnss_max_age_seconds, + queue_retry_passes + FROM wifi_verification_settings + WHERE id = 1 + """ + ).fetchone() + + if row is None: + return jsonify({ + "ok": False, + "error": "Настройки проверки Wi-Fi не найдены." + }), 409 + + return jsonify({ + "ok": True, + "settings": dict(row) + }) + + except Exception: + app.logger.exception( + "Не удалось загрузить настройки проверки Wi-Fi" + ) + return jsonify({ + "ok": False, + "error": "Внутренняя ошибка при загрузке настроек." + }), 500 + + finally: + if conn is not None: + close_database(conn) + + +@app.route("/api/wifi-verification/settings", methods=["POST"]) +def api_wifi_verification_settings_save(): + conn = None + + try: + data = request.get_json(silent=True) + + if not isinstance(data, dict): + return jsonify({ + "ok": False, + "error": "Некорректные данные настроек." + }), 400 + + allowed_fields = { + "gps_source", + "gpsrelay_host", + "gpsrelay_port", + "radius_m", + "gnss_max_age_seconds", + "queue_retry_passes" + } + + if set(data) != allowed_fields: + return jsonify({ + "ok": False, + "error": "Передан неверный набор параметров." + }), 400 + + gps_source = data["gps_source"] + + if gps_source not in ("gpsd", "gpsrelay"): + return jsonify({ + "ok": False, + "error": "Выберите корректный источник GPS." + }), 400 + + if gps_source == "gpsrelay": + gpsrelay_host = data["gpsrelay_host"] + + if not isinstance(gpsrelay_host, str) or not gpsrelay_host.strip(): + return jsonify({ + "ok": False, + "error": "Укажите адрес GPSRelay." + }), 400 + + gpsrelay_host = gpsrelay_host.strip() + gpsrelay_port = data["gpsrelay_port"] + + if ( + isinstance(gpsrelay_port, bool) + or not isinstance(gpsrelay_port, int) + or not 1 <= gpsrelay_port <= 65535 + ): + return jsonify({ + "ok": False, + "error": "Порт GPSRelay должен быть от 1 до 65535." + }), 400 + + else: + gpsrelay_host = None + gpsrelay_port = None + + radius_m = data["radius_m"] + + if ( + isinstance(radius_m, bool) + or not isinstance(radius_m, int) + or radius_m not in (50, 75, 100, 125, 150, 175, 200, 250, 350, 500) + ): + return jsonify({ + "ok": False, + "error": "Выберите один из доступных радиусов проверки." + }), 400 + + gnss_max_age_seconds = data["gnss_max_age_seconds"] + + if ( + isinstance(gnss_max_age_seconds, bool) + or not isinstance(gnss_max_age_seconds, int) + or not 1 <= gnss_max_age_seconds <= 30 + ): + return jsonify({ + "ok": False, + "error": "Возраст GNSS-данных должен быть от 1 до 30 секунд." + }), 400 + + queue_retry_passes = data["queue_retry_passes"] + + if ( + isinstance(queue_retry_passes, bool) + or not isinstance(queue_retry_passes, int) + or not 0 <= queue_retry_passes <= 5 + ): + return jsonify({ + "ok": False, + "error": "Количество повторных проходов должно быть от 0 до 5." + }), 400 + + with auto_wifi_verification_lock: + + current_service = auto_wifi_verification_service + + auto_running = ( + current_service is not None + and current_service.thread is not None + and current_service.thread.is_alive() + ) + + with wifi_verification_shared_gps_lock: + + if auto_running or wifi_verification_map_monitor_enabled: + return jsonify({ + "ok": False, + "error": ( + "Нельзя изменять настройки, пока работает " + "Auto Verification или GPS-монитор карты." + ) + }), 409 + + conn = connect_database() + + conn.execute( + """ + INSERT INTO wifi_verification_settings ( + id, + gps_source, + gpsrelay_host, + gpsrelay_port, + radius_m, + gnss_max_age_seconds, + queue_retry_passes + ) + VALUES (1, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + gps_source = excluded.gps_source, + gpsrelay_host = excluded.gpsrelay_host, + gpsrelay_port = excluded.gpsrelay_port, + radius_m = excluded.radius_m, + gnss_max_age_seconds = excluded.gnss_max_age_seconds, + queue_retry_passes = excluded.queue_retry_passes, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') + """, + ( + gps_source, + gpsrelay_host, + gpsrelay_port, + radius_m, + gnss_max_age_seconds, + queue_retry_passes + ) + ) + + conn.commit() + + settings = { + "gps_source": gps_source, + "gpsrelay_host": gpsrelay_host, + "gpsrelay_port": gpsrelay_port, + "radius_m": radius_m, + "gnss_max_age_seconds": gnss_max_age_seconds, + "queue_retry_passes": queue_retry_passes + } + + return jsonify({ + "ok": True, + "settings": settings + }) + + except Exception: + if conn is not None: + conn.rollback() + + app.logger.exception( + "Не удалось сохранить настройки проверки Wi-Fi" + ) + return jsonify({ + "ok": False, + "error": "Внутренняя ошибка при сохранении настроек." + }), 500 + + finally: + if conn is not None: + close_database(conn) + +@app.route( + "/api/wifi-verification/radius", + methods=["POST"] +) +def api_wifi_verification_radius_apply(): + conn = None + + try: + data = request.get_json(silent=True) + + if not isinstance(data, dict) or set(data) != {"radius_m"}: + return jsonify({ + "ok": False, + "error": "Передан неверный набор параметров." + }), 400 + + radius_m = data["radius_m"] + + if ( + isinstance(radius_m, bool) + or not isinstance(radius_m, int) + or radius_m not in (50, 75, 100, 125, 150, 175, 200, 250, 350, 500) + ): + return jsonify({ + "ok": False, + "error": "Выберите один из доступных радиусов проверки." + }), 400 + + with auto_wifi_verification_lock: + current_service = auto_wifi_verification_service + + auto_running = ( + current_service is not None + and current_service.thread is not None + and current_service.thread.is_alive() + ) + + conn = connect_database() + + conn.execute( + """ + INSERT INTO wifi_verification_settings ( + id, + radius_m, + updated_at + ) + VALUES ( + 1, + ?, + strftime('%Y-%m-%dT%H:%M:%fZ', 'now') + ) + ON CONFLICT(id) DO UPDATE SET + radius_m = excluded.radius_m, + updated_at = excluded.updated_at + """, + (radius_m,) + ) + + conn.commit() + + if auto_running: + current_service.request_radius_update(radius_m) + + return jsonify({ + "ok": True, + "radius_m": radius_m, + "pending": auto_running + }) + + except Exception: + if conn is not None: + conn.rollback() + + app.logger.exception( + "Не удалось применить радиус проверки Wi-Fi" + ) + return jsonify({ + "ok": False, + "error": "Внутренняя ошибка при применении радиуса." + }), 500 + + finally: + if conn is not None: + close_database(conn) + + +@app.route( + "/api/wifi-verification/map-gps", + methods=["GET"] +) +def api_wifi_verification_map_gps_status(): + + connection = None + + try: + connection = connect_database() + + row = connection.execute( + """ + SELECT radius_m + FROM wifi_verification_settings + WHERE id = 1 + """ + ).fetchone() + + radius_m = ( + row["radius_m"] + if row is not None + else None + ) + + except Exception: + + logger.exception( + "Failed to load map GPS settings." + ) + + return jsonify({ + "ok": False, + "error": "Failed to load GPS settings." + }), 500 + + finally: + if connection is not None: + close_database(connection) + + with auto_wifi_verification_lock: + with wifi_verification_shared_gps_lock: + + service = wifi_verification_shared_gps_service + + gps_status = ( + service.get_status() + if service is not None + else { + "running": False, + "state": "STOPPED", + "has_fresh_fix": False, + "latitude": None, + "longitude": None, + "fix_age_seconds": None, + "max_age_seconds": None, + "error": None + } + ) + + return jsonify({ + "ok": True, + "monitor_enabled": ( + wifi_verification_map_monitor_enabled + ), + "owner": network_operation_owner, + "radius_m": radius_m, + "gps": gps_status + }) + + +@app.route( + "/api/wifi-verification/map-gps/start", + methods=["POST"] +) +def api_wifi_verification_map_gps_start(): + + global wifi_verification_map_monitor_enabled + + connection = None + service = None + started_service = False + + try: + with auto_wifi_verification_lock: + + auto_service = auto_wifi_verification_service + + auto_running = ( + auto_service is not None + and auto_service.thread is not None + and auto_service.thread.is_alive() + ) + + with wifi_verification_shared_gps_lock: + + service = wifi_verification_shared_gps_service + + if wifi_verification_map_monitor_enabled: + + if ( + service is not None + and service.thread is not None + and service.thread.is_alive() + ): + return jsonify({ + "ok": True, + "monitor_enabled": True, + "gps": service.get_status() + }) + + wifi_verification_map_monitor_enabled = False + + if auto_running: + + 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 + + return jsonify({ + "ok": True, + "monitor_enabled": True, + "gps": service.get_status() + }) + + connection = connect_database() + + 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 + + if settings is None: + return jsonify({ + "ok": False, + "error": ( + "Wi-Fi verification settings " + "are not configured." + ) + }), 409 + + if settings.get("gps_source") not in ( + "gpsd", + "gpsrelay" + ): + 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 + }), 409 + + service = _get_wifi_verification_shared_gps( + settings + ) + + already_running = ( + service.thread is not None + and service.thread.is_alive() + ) + + started_service = not already_running + + started = ( + True + if already_running + else service.start() + ) + + if not started: + cleanup_ok = True + + if started_service: + cleanup_ok = ( + _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 + + wifi_verification_map_monitor_enabled = True + + return jsonify({ + "ok": True, + "monitor_enabled": True, + "gps": service.get_status() + }) + + except Exception: + + logger.exception( + "Failed to start map GPS monitoring." + ) + + 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" + ) + + return jsonify({ + "ok": False, + "error": "Failed to start GPS monitoring." + }), 500 + + finally: + if connection is not None: + close_database(connection) + + +@app.route( + "/api/wifi-verification/map-gps/stop", + methods=["POST"] +) +def api_wifi_verification_map_gps_stop(): + + global wifi_verification_map_monitor_enabled + + try: + 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 = ( + service.get_status() + if service is not None + else None + ) + + return jsonify({ + "ok": True, + "monitor_enabled": False, + "stop_deferred": True, + "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: + + return jsonify({ + "ok": False, + "error": ( + "GPS is owned by another operation." + ), + "owner": owner, + "monitor_enabled": False + }), 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 + + return jsonify({ + "ok": True, + "monitor_enabled": False, + "stop_deferred": False + }) + + except Exception: + + logger.exception( + "Failed to stop map GPS monitoring." + ) + + return jsonify({ + "ok": False, + "error": "Failed to stop GPS monitoring." + }), 500 + + + +@app.route( + "/api/wifi-verification/status" +) +def api_wifi_verification_status(): + + with auto_wifi_verification_lock: + service = auto_wifi_verification_service + + if service is None: + return jsonify( + { + "ok": True, + "running": False, + "state": "STOPPED", + "error": None + } + ) + + return jsonify( + { + "ok": True, + **service.get_status() + } + ) + + +@app.route( + "/api/wifi-verification/start", + methods=["POST"] +) +def api_wifi_verification_start(): + + global auto_wifi_verification_service + + data = request.get_json( + silent=True + ) + + if not isinstance(data, dict): + + return jsonify( + { + "ok": False, + "error": "A JSON object is required." + } + ), 400 + + interface = data.get("interface") + + if not isinstance(interface, str) or not interface.strip(): + + return jsonify( + { + "ok": False, + "error": "Wi-Fi interface is required." + } + ), 400 + + interface = interface.strip() + + device, error, status = validate_network_interface( + interface + ) + + if error: + + return jsonify( + { + "ok": False, + "error": error + } + ), status + + try: + + with auto_wifi_verification_lock: + + connection = None + + try: + connection = connect_database() + + row = connection.execute( + """ + SELECT * + FROM wifi_verification_settings + WHERE id = 1 + """ + ).fetchone() + + settings = dict(row) if row is not None else None + + except Exception: + + logger.exception( + "Failed to load automatic Wi-Fi verification settings." + ) + + return jsonify( + { + "ok": False, + "error": "Failed to load verification settings." + } + ), 500 + + finally: + if connection is not None: + close_database(connection) + + if settings is None: + + return jsonify( + { + "ok": False, + "error": "Wi-Fi verification settings are not configured." + } + ), 409 + + if settings.get("gps_source") not in ("gpsd", "gpsrelay"): + + return jsonify( + { + "ok": False, + "error": "Select GPS source: gpsd or gpsrelay." + } + ), 409 + + 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": "Automatic Wi-Fi verification is already running.", + **current.get_status() + } + ), 409 + + shared_gps_service = ( + _get_wifi_verification_shared_gps(settings) + ) + + service = AutoWiFiVerificationService( + settings=settings, + interface=device["device"], + wifi_connection_service=wifi_connection_service, + gps_service=shared_gps_service, + acquire_network_owner=lambda owner: ( + acquire_wifi_verification_network_owner( + owner, + shared_gps_service + ) + ), + release_network_owner=( + release_wifi_verification_network_owner + ) + ) + + auto_wifi_verification_service = service + + started = service.start() + + if not started: + + return jsonify( + { + "ok": False, + "error": "Automatic Wi-Fi verification could not be started.", + **service.get_status() + } + ), 409 + + return jsonify( + { + "ok": True, + **service.get_status() + } + ) + + except ValueError as error: + + return jsonify( + { + "ok": False, + "error": str(error) + } + ), 400 + + except Exception: + + logger.exception( + "Failed to start automatic Wi-Fi verification." + ) + + return jsonify( + { + "ok": False, + "error": "An internal error occurred while starting automatic Wi-Fi verification." + } + ), 500 + + +@app.route( + "/api/wifi-verification/stop", + methods=["POST"] +) +def api_wifi_verification_stop(): + + with auto_wifi_verification_lock: + service = auto_wifi_verification_service + + if service is None: + + return jsonify( + { + "ok": True, + "running": False, + "state": "STOPPED", + "error": None + } + ) + + service.stop() + + return jsonify( + { + "ok": True, + **service.get_status() + } + ) + + @app.route( "/api/network/wifi-devices" ) @@ -2815,9 +4103,7 @@ def api_network_wifi_devices(): devices, error = get_nm_wifi_devices() - wireguard_connections, wireguard_error = ( - get_active_wireguard_connections() - ) + vpn_active, vpn_error = get_active_vpn_status() if error: @@ -2891,9 +4177,8 @@ def api_network_wifi_devices(): if not devices else None ), - "wireguard_active": bool(wireguard_connections), - "wireguard_connections": wireguard_connections, - "wireguard_error": wireguard_error + "vpn_active": vpn_active, + "vpn_error": vpn_error } ) @@ -3011,16 +4296,26 @@ def mark_network_credential_verified( close_database(conn) -def get_network_wireguard_warning(): +def get_network_vpn_warning(): - connections, error = get_active_wireguard_connections() + vpn_active, error = get_active_vpn_status() - if connections: + if vpn_active: return ( - "An active WireGuard VPN connection was detected. " - "For security and reliable local network access, " - "manually disconnect the VPN if necessary." + "Обнаружено активное VPN-подключение. " + "Для надёжной проверки пароля и подключения " + "рекомендуется временно отключить VPN. " + "Продолжить можно, но успешная работа не гарантируется." + ) + + if error: + + return ( + "Не удалось достоверно определить состояние VPN. " + "При активном VPN результат проверки пароля " + "или подключения не гарантируется. " + "Рекомендуется проверить состояние VPN вручную." ) return None @@ -3137,7 +4432,7 @@ def api_network_wifi_verify(): "bssid": result["bssid"], "ssid": result["ssid"], "verified": True, - "wireguard_warning": get_network_wireguard_warning() + "vpn_warning": get_network_vpn_warning() } ) @@ -3286,7 +4581,7 @@ def api_network_wifi_connect(): "bssid": result["bssid"], "ssid": result["ssid"], "is_open": result["is_open"], - "wireguard_warning": get_network_wireguard_warning() + "vpn_warning": get_network_vpn_warning() } ) @@ -3473,50 +4768,20 @@ def scanner_start(): with scanner_lock: - if network_action_active: + acquired, error = _acquire_network_owner_locked( + "SCANNER" + ) + + if not acquired: scanner_output.append( - "[GUI] Scanner cannot start " - "while a Wi-Fi connection operation is in progress." + f"[GUI] Scanner cannot start: {error}" ) return redirect( url_for("index") ) - if ( - scanner_starting - or - ( - scanner_process is not None - and - scanner_process.poll() is None - ) - ): - - return redirect( - url_for("index") - ) - - with gps_test_lock: - - if ( - gps_test_service is not None - and - gps_test_service.thread is not None - and - gps_test_service.thread.is_alive() - ): - - scanner_output.append( - "[GUI] Scanner cannot start " - "while GPS test is running." - ) - - return redirect( - url_for("index") - ) - scanner_starting = True interface = request.form.get( @@ -3524,13 +4789,16 @@ def scanner_start(): "" ).strip() - if not interface: with scanner_lock: scanner_starting = False + _release_network_owner_locked( + "SCANNER" + ) + scanner_output.append( "[GUI] WiFi interface was not selected." ) @@ -3539,42 +4807,29 @@ def scanner_start(): url_for("index") ) - environment = os.environ.copy() environment[ "WIFI_INTERFACE" ] = interface - command = [ - sys.executable, + sys.executable, "src/main.py" ] - try: process = subprocess.Popen( - command, - cwd=PROJECT_ROOT, - env=environment, - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - bufsize=1, - process_group=0 - ) except Exception as error: @@ -3583,6 +4838,10 @@ def scanner_start(): scanner_starting = False + _release_network_owner_locked( + "SCANNER" + ) + scanner_output.append( f"[GUI] Failed to start scanner: {error}" ) @@ -3591,15 +4850,11 @@ def scanner_start(): url_for("index") ) - with scanner_lock: scanner_process = process - scanner_starting = False - scanner_health = "ACTIVE" - scanner_stopped_at = None scanner_output.clear() @@ -3616,15 +4871,76 @@ def scanner_start(): f"[GUI] Interface: {interface}" ) - scanner_output_thread = threading.Thread( target=read_scanner_output, args=(process,), daemon=True ) - scanner_output_thread.start() + try: + scanner_output_thread.start() + + except Exception as error: + + # Поток чтения не стартовал: завершаем процесс, + # затем освобождаем владельца. + try: + + os.killpg( + process.pid, + signal.SIGKILL + ) + + except Exception: + + try: + + process.kill() + + except Exception: + + pass + + try: + + process.wait() + + except Exception: + + while process.poll() is None: + + time.sleep(0.1) + + try: + + process.stdout.close() + + except Exception: + + pass + + with scanner_lock: + + if scanner_process is process: + + scanner_process = None + + scanner_starting = False + scanner_health = "STOPPED" + scanner_stopped_at = datetime.now().isoformat() + + _release_network_owner_locked( + "SCANNER" + ) + + scanner_output.append( + f"[GUI] Failed to start scanner output reader: {error}" + ) + + return redirect( + url_for("index") + ) return redirect( url_for("index") diff --git a/gui/static/style.css b/gui/static/style.css index f21a746..2580db8 100644 --- a/gui/static/style.css +++ b/gui/static/style.css @@ -127,6 +127,30 @@ select { 0 30px; } +.report-brand { + + flex: 0 0 auto; + + display: flex; + flex-direction: column; + + justify-content: center; + + color: var(--text); + + text-decoration: none; + + white-space: nowrap; +} + + +.report-brand:hover { + color: var(--text); + + text-decoration: none; +} + + .header-actions { display: flex; @@ -516,6 +540,12 @@ main { font-size: 20px; } +/* Match Reports Capture Map title size */ +.capture-map-card > h2.session-map-title { + font-size: 21px; +} + + .panel-hint { @@ -1346,4 +1376,1446 @@ pre { margin-left: auto; text-align: right; -} \ No newline at end of file +} + + +/* ============================================================ + CAPTURE MAP PAGE STYLES + ============================================================ */ + + +.capture-map-page { + max-width: 1400px; +} + +.capture-map-page-heading { + margin-bottom: 24px; +} + +.capture-map-page-heading h1 { + margin: 5px 0 6px; + font-size: 24px; +} + +.capture-map-page-heading .panel-hint { + margin: 0; +} + +.capture-map-panel-heading { + align-items: center; +} + +.capture-map-panel-heading h2 { + margin: 0; +} + +.capture-map-toolbar { + display: flex; + align-items: center; + justify-content: flex-end; + flex-wrap: wrap; + gap: 12px; + margin-left: auto; +} + +.capture-map-toolbar > span { + color: var(--muted); + font-size: 13px; +} + +.capture-map-toolbar .button { + min-height: 38px; +} + +.capture-mode-switch { + display: inline-flex; + align-items: center; + gap: 4px; + margin-right: 8px; +} + +.capture-mode-button { + min-height: 30px; + padding: 5px 12px; + border: 1px solid var(--border); + border-radius: 5px; + background: var(--surface-light); + color: var(--muted); + font: inherit; + font-size: 11px; + font-weight: 700; + cursor: default; +} + +.capture-mode-button.active { + border-color: var(--green); + background: rgba(69, 212, 131, 0.12); + color: var(--green); +} + +.capture-mode-button:disabled { + opacity: 0.75; +} + +.capture-map-card { + margin-bottom: 22px; +} + +.capture-map-settings { + min-height: 70px; +} + +.capture-map-settings .panel-heading { + margin-bottom: 0; +} + +.capture-map-settings h2 { + margin: 0; + font-size: 20px; +} + +#capture-map { + width: 100%; + height: min(72vh, 850px); + min-height: 420px; + overflow: hidden; + border: 1px solid var(--border); + border-radius: 7px; + background: var(--terminal); +} + +.capture-map-legend { + display: flex; + flex-wrap: wrap; + gap: 12px 22px; + margin-top: 18px; + padding-top: 15px; + border-top: 1px solid var(--border); +} + +.capture-map-legend label { + display: inline-flex; + align-items: center; + gap: 8px; + margin: 0; + color: var(--muted); + font-size: 12px; + font-weight: 600; + cursor: pointer; +} + +.capture-map-legend input { + width: 14px; + height: 14px; + margin: 0; + accent-color: var(--accent); + cursor: pointer; +} + +.capture-map-dot { + display: inline-block; + width: 10px; + height: 10px; + flex-shrink: 0; + border-radius: 50%; +} + +.capture-map-dot.green { background: var(--green); } +.capture-map-dot.red { background: var(--red); } +.capture-map-dot.orange { background: var(--yellow); } +.capture-map-dot.gray { background: var(--muted); } + +/* Map title and layer controls — Reports layout */ + +.session-map-title { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 18px; +} + +.session-map-title-text { + flex: 0 0 auto; +} + +.session-map-controls { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 14px; + font-size: 13px; + font-weight: normal; +} + +.session-map-controls label { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--text); + cursor: pointer; + white-space: nowrap; +} + +.session-map-controls input { + margin: 0; +} + +.map-layer-dot { + display: inline-block; + width: 14px; + height: 14px; + flex: 0 0 14px; + box-sizing: border-box; + border: 1px solid #FFFFFF; + border-radius: 50%; +} + +.map-layer-dot-verified { + background: var(--green); +} + +.map-layer-dot-invalid-password { + background: var(--red); +} + +.map-layer-dot-technical-error { + background: var(--yellow); +} + +.map-layer-dot-not-verified { + background: var(--muted); +} + +#capture-map-message { + margin: 0 0 12px; + padding: 0; + color: var(--muted); + font-size: 13px; + overflow-wrap: anywhere; +} + +#capture-map-message:not(:empty) { + padding: 10px 12px; + background: var(--terminal); + border: 1px solid var(--border); + border-radius: 6px; +} + +.capture-map-marker { + width: 17px; + height: 17px; + border: 2px solid var(--text); + border-radius: 50%; + box-shadow: 0 1px 6px rgba(0, 0, 0, 0.65); + cursor: pointer; +} + +.capture-map-marker.green { background: var(--green); } +.capture-map-marker.red { background: var(--red); } +.capture-map-marker.orange { background: var(--yellow); } +.capture-map-marker.gray { background: var(--muted); } + +.capture-map-status { + display: inline-flex; + align-items: center; + gap: 7px; +} + +.capture-map-status-indicator { + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--muted); +} + +.capture-map-status-indicator.running { + background: var(--green); + box-shadow: 0 0 8px rgba(69, 212, 131, 0.45); +} + +.capture-map-popup .maplibregl-popup-content { + max-width: 360px; + padding: 14px 16px; + overflow-wrap: anywhere; + background: var(--surface); + color: var(--text); + border: 1px solid var(--border); + border-radius: 7px; + box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4); +} + +.capture-map-popup .maplibregl-popup-tip { + border-top-color: var(--surface); + border-bottom-color: var(--surface); +} + +.capture-map-popup .maplibregl-popup-close-button { + color: var(--muted); + font-size: 18px; +} + +.capture-map-popup .maplibregl-popup-close-button:hover { + background: var(--surface-light); + color: var(--text); +} + +#capture-map .maplibregl-ctrl-group { + overflow: hidden; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; +} + +#capture-map .maplibregl-ctrl-group button { + background-color: var(--surface); +} + +#capture-map .maplibregl-ctrl-group button + button { + border-top: 1px solid var(--border); +} + +#capture-map .auto-gps-follow-control { + overflow: hidden; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; +} + +#capture-map .auto-gps-follow-control button { + display: flex; + align-items: center; + justify-content: center; + width: 29px; + height: 29px; + padding: 0; + border: 0; + background: var(--surface); + color: var(--muted); + cursor: pointer; +} + +#capture-map .auto-gps-follow-control button.is-active { + color: #2688ff; +} + +#capture-map .auto-gps-follow-control button svg { + width: 18px; + height: 18px; + fill: currentColor; +} + + +@media (max-width: 760px) { + .capture-map-page-heading h1 { + font-size: 21px; + } + + .capture-map-card, + .capture-map-settings { + padding: 18px; + } + + .capture-map-panel-heading { + align-items: stretch; + flex-direction: column; + } + + .capture-map-toolbar { + justify-content: space-between; + margin-left: 0; + } + + .capture-map-toolbar .button { + width: auto; + } + + .capture-map-legend { + gap: 12px 16px; + } + + #capture-map { + min-height: 360px; + height: 65vh; + } +} + +@media (max-width: 480px) { + .capture-map-toolbar { + align-items: stretch; + flex-direction: column; + } + + .capture-map-toolbar .button { + width: 100%; + } + + .capture-map-legend { + align-items: flex-start; + flex-direction: column; + gap: 11px; + } +} + + +/* ============================================================ + AUTO-VERIFICATION REPORTS LAYOUT + ============================================================ */ + +.capture-map-page { + max-width: 1800px; +} + +.auto-verification-page-heading { + margin-bottom: 24px; +} + +.auto-verification-section { + color: var(--muted); + font-size: 18px; + font-weight: 600; + letter-spacing: 0.8px; + text-transform: uppercase; + margin-bottom: 8px; +} + +.auto-verification-parent { + color: var(--muted); + font-size: 13px; + font-weight: 600; + letter-spacing: 0.2px; + margin-bottom: 4px; +} + +.capture-map-page-heading h1.auto-verification-title { + margin: 0 0 8px; + font-size: 34px; + font-weight: 700; + letter-spacing: 0.2px; +} + + +.auto-verification-page-heading .panel-hint { + margin: 0; +} + +@media (max-width: 760px) { + .capture-map-page-heading h1.auto-verification-title { + font-size: 28px; + } +} + + +/* ============================================================ + Стили конфигурации автоматической проверки + ============================================================ */ + +.auto-verification-config { + margin-top: 22px; +} + +.auto-verification-top-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 28px; + align-items: start; +} + +.auto-config-gps-column { + min-width: 0; +} + +.auto-verification-relay-fields { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; + margin-top: 16px; +} + +.auto-verification-relay-fields[hidden] { + display: none; +} + +.auto-verification-config .field { + width: 100%; + max-width: none; + min-width: 0; +} + +.auto-verification-config input, +.auto-verification-config select { + width: 100%; + min-width: 0; + height: 43px; + padding: 0 13px; + background: var(--bg); + color: var(--text); + border: 1px solid var(--border); + border-radius: 6px; + font-family: inherit; +} + +.auto-verification-config input:focus, +.auto-verification-config select:focus { + border-color: var(--accent); + outline: none; +} + +.auto-verification-main-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 32px; + margin-top: 26px; +} + +.auto-verification-main-grid > .auto-config-section { + min-width: 0; + margin-top: 0; + padding-top: 22px; + border-top: 1px solid var(--border); +} + +.auto-config-section-title { + margin-bottom: 18px; + color: var(--text); + font-size: 12px; + font-weight: 700; + letter-spacing: 0.08em; +} + +.auto-verification-radius-options { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + width: 100%; + gap: 8px; +} + +.auto-verification-radius-button { + flex: 1 1 0; + min-width: 0; + height: 40px; + padding: 0 8px; + background: var(--bg); + color: var(--text); + border: 1px solid var(--border); + border-radius: 22px; + cursor: pointer; + font-family: inherit; + font-size: 13px; + font-weight: 600; + white-space: nowrap; + transition: border-color 0.15s ease, color 0.15s ease; +} + +.auto-verification-radius-button:hover { + border-color: var(--accent); +} + +.auto-verification-radius-button.active { + border-color: var(--accent); + color: var(--accent); +} + +.auto-verification-radius-actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + margin-top: 16px; +} + +.auto-verification-radius-apply { + min-width: 120px; +} + +.auto-verification-radius-status { + min-width: 0; + color: var(--muted); + font-size: 12px; + line-height: 1.5; +} + +.auto-verification-radius-status.error { + color: #ff9b9b; +} + +.auto-verification-processing-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 20px; + align-items: start; +} + +.auto-config-number-field input { + max-width: 180px; +} + +.auto-verification-config .config-help { + max-width: 390px; + margin-top: 7px; + line-height: 1.5; +} + +.auto-verification-config-actions { + justify-content: flex-end; + gap: 12px; + margin-top: 28px; +} + +.auto-verification-reset { + background: var(--bg); + color: var(--text); + border: 1px solid var(--border); +} + +@media (max-width: 900px) { + .auto-verification-top-grid, + .auto-verification-main-grid { + grid-template-columns: minmax(0, 1fr); + gap: 22px; + } + + .auto-verification-main-grid { + margin-top: 22px; + } + + .auto-verification-main-grid > .auto-config-section { + padding-top: 20px; + } + + .auto-verification-processing-grid { + gap: 24px; + } +} + +@media (max-width: 760px) { + .auto-verification-config-actions { + flex-direction: column-reverse; + } + + .auto-verification-config-actions .button { + width: 100%; + } +} + +@media (max-width: 480px) { + .auto-verification-relay-fields, + .auto-verification-processing-grid { + grid-template-columns: minmax(0, 1fr); + gap: 18px; + } + + .auto-verification-radius-options { + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 8px; + } + + .auto-verification-radius-button { + min-width: 0; + padding: 0 4px; + font-size: 12px; + } +} + + +/* ============================================================ + Auto Verification — positioning panel + ============================================================ */ + +.auto-position-panel { + margin-top: 22px; +} + +.auto-position-panel .panel-heading { + margin-bottom: 18px; +} + +.auto-position-grid { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 14px; +} + +.auto-position-item { + min-width: 0; + padding: 16px; + background: var(--bg); + border: 1px solid var(--border); + border-radius: 7px; +} + +.auto-position-label { + margin-bottom: 12px; + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: 1px; +} + +.auto-position-value { + display: flex; + align-items: center; + gap: 9px; + min-height: 26px; + color: var(--text); + font-size: 14px; + font-weight: 700; +} + +.auto-position-gps { + color: var(--red); +} + +.auto-position-mode { + color: var(--accent); +} + +.auto-position-coordinate input { + width: 100%; + height: 43px; + padding: 0 13px; + background: var(--surface); + color: var(--text); + border: 1px solid var(--border); + border-radius: 6px; + font-family: inherit; + font-size: 14px; +} + +.auto-position-coordinate input:focus { + border-color: var(--accent); + outline: none; + box-shadow: 0 0 0 2px rgba(105, 167, 255, 0.12); +} + +.auto-position-item .config-help { + margin-top: 8px; +} + +@media (max-width: 900px) { + .auto-position-grid { + grid-template-columns: minmax(0, 1fr); + } +} + +@media (max-width: 480px) { + .auto-position-grid { + grid-template-columns: minmax(0, 1fr); + } +} + + +/* Auto Verification — GPS controls */ +.auto-gps-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 7px; + margin-top: 0; +} + +.auto-gps-button { + min-height: 34px; + padding: 0 11px; + border: 1px solid var(--accent); + border-radius: 5px; + background: var(--accent); + color: #fff; + font: inherit; + font-size: 12px; + font-weight: 600; + cursor: pointer; +} + +.auto-gps-button.secondary { + border-color: var(--border); + background: var(--surface); + color: var(--text); +} + +.auto-gps-button:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.auto-position-gps.is-fixed { + color: var(--green, #35a66b); +} + +.auto-position-gps.is-searching { + color: var(--orange, #d99a36); +} + +.auto-position-gps.is-error { + color: var(--red); +} + +.capture-map-radius { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 14px; + padding-bottom: 12px; + border-bottom: 1px solid var(--border); +} + +.capture-map-radius .auto-position-label { + margin: 0; +} + +.capture-map-radius strong { + color: var(--text); + font-size: 14px; +} + +.capture-map-control-row { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 14px 22px; + margin-bottom: 16px; +} + +.capture-map-gps-controls { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 10px 14px; + min-width: 0; +} + +.capture-map-gps-controls .auto-gps-actions { + margin-top: 0; +} + +.capture-map-gps-detail { + margin: 0; + overflow-wrap: anywhere; +} + +.capture-map-control-row .session-map-controls { + flex: 1 1 420px; + justify-content: flex-end; +} + +.capture-map-toolbar { + margin-top: 14px; + margin-left: 0; + justify-content: space-between; +} + +.auto-position-gps { + white-space: nowrap; + font-size: 12px; +} + +@media (max-width: 760px) { + .capture-map-control-row { + align-items: flex-start; + flex-direction: column; + } + + .capture-map-control-row .session-map-controls { + justify-content: flex-start; + } + + .capture-map-gps-controls { + align-items: flex-start; + flex-direction: column; + } + + .auto-position-gps { + font-size: 10px; + } +} + +.auto-gps-map-marker { + width: 18px; + height: 18px; + border: 3px solid #fff; + border-radius: 50%; + background: #2688ff; + box-shadow: 0 0 0 5px rgba(38, 136, 255, 0.25); +} + + +/* Auto Verification — map top row and layers */ +.capture-map-top-row { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: nowrap; + gap: 12px 22px; + margin-bottom: 16px; +} + +.capture-map-top-row .capture-map-radius { + display: flex; + align-items: center; + gap: 10px; + flex: 0 0 auto; + margin: 0; + padding: 0; + border: 0; + white-space: nowrap; +} + +.capture-map-top-row .capture-map-gps-controls { + display: flex; + align-items: center; + justify-content: flex-end; + flex: 0 1 auto; + min-width: 0; + gap: 14px; +} + +.capture-map-top-row .capture-map-gps-detail { + white-space: nowrap; +} + +.capture-map-top-row .capture-map-scan-radius { + display: flex; + align-items: center; + flex: 0 1 auto; + min-width: 0; + gap: 7px; + white-space: nowrap; +} + +.capture-map-top-row .capture-map-scan-radius .auto-config-section-title { + margin: 0; + font-size: 11px; +} + +.capture-map-top-row .capture-map-scan-radius label { + margin: 0; + color: var(--muted); + font-size: 11px; + white-space: nowrap; +} + +.capture-map-top-row .capture-map-scan-radius select { + width: auto; + min-width: 88px; + height: 28px; + padding: 3px 22px 3px 7px; + font-size: 11px; +} + +.capture-map-top-row .capture-map-scan-radius .button { + min-width: 0; + min-height: 28px; + height: 28px; + padding: 3px 10px; + font-size: 10px; +} + +.capture-map-top-row .auto-gps-actions { + flex-wrap: nowrap; + flex: 0 0 auto; +} + +.capture-map-layers-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 14px 20px; + margin-bottom: 16px; +} + +.capture-map-layers-row .session-map-title-text { + flex: 0 0 auto; +} + +.capture-map-layers-row .session-map-controls { + flex: 1 1 420px; + justify-content: flex-end; +} + +@media (max-width: 760px) { + .capture-map-top-row { + align-items: flex-start; + flex-wrap: wrap; + } + + .capture-map-top-row .capture-map-gps-controls { + flex-wrap: wrap; + justify-content: flex-start; + } + + .capture-map-top-row .capture-map-scan-radius { + flex-wrap: wrap; + } + + .capture-map-top-row .capture-map-gps-detail { + white-space: normal; + } + + .capture-map-top-row .auto-gps-actions { + flex-wrap: wrap; + } + + .capture-map-layers-row { + align-items: flex-start; + } + + .capture-map-layers-row .session-map-controls { + justify-content: flex-start; + } +} + + +/* Координаты центра в нижней панели карты */ +.capture-map-coordinate { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; +} + +.capture-map-coordinate label { + color: var(--muted); + font-size: 12px; + white-space: nowrap; +} + +.capture-map-coordinate input { + width: 300px; + max-width: 100%; + height: 38px; + padding: 0 10px; + background: var(--surface); + color: var(--text); + border: 1px solid var(--border); + border-radius: 6px; + font-family: inherit; + font-size: 13px; +} + +.capture-map-coordinate input:focus { + border-color: var(--accent); + outline: none; + box-shadow: 0 0 0 2px rgba(105, 167, 255, 0.12); +} + +@media (max-width: 480px) { + .capture-map-coordinate { + align-items: stretch; + flex-direction: column; + width: 100%; + } + + .capture-map-coordinate input { + width: 100%; + } +} + + +/* Auto Verification — адаптивная шапка */ +@media (max-width: 1100px) { + .auto-verification-page .header-inner { + flex-wrap: wrap; + gap: 12px 24px; + } + + .auto-verification-page .header-actions { + flex: 1 1 600px; + min-width: 0; + flex-wrap: wrap; + justify-content: flex-end; + gap: 12px 18px; + } + + .auto-verification-page .header-scanner-controls { + min-width: 0; + flex-wrap: wrap; + } +} + +@media (max-width: 760px) { + .auto-verification-page .header-actions { + width: 100%; + flex: 0 1 auto; + justify-content: flex-start; + } +} + +/* ============================================================ + AUTO VERIFICATION — ENGINE MONITOR + ============================================================ */ + +.auto-verification-monitor { + margin-top: 22px; +} + +.auto-monitor-heading { + align-items: center; + margin-bottom: 20px; +} + +.auto-monitor-heading h2 { + margin: 0; +} + +.auto-monitor-demo-label { + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 5px; + color: var(--yellow); + font-size: 10px; + font-weight: 700; + letter-spacing: 1px; +} + +.auto-monitor-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 18px; +} + +.auto-monitor-column { + min-width: 0; + padding: 16px; + background: var(--surface-light, var(--surface)); + border: 1px solid var(--border); + border-radius: 8px; +} + +.auto-monitor-column-heading, +.auto-monitor-log-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 14px; +} + +.auto-monitor-column-heading h3, +.auto-monitor-log-heading h3 { + margin: 0; + color: var(--text); + font-size: 14px; + font-weight: 700; +} + +.auto-monitor-count { + color: var(--muted); + font-size: 11px; + white-space: nowrap; +} + +.auto-monitor-statistics { + display: flex; + flex-direction: column; +} + +.auto-monitor-stat-group { + display: flex; + flex-direction: column; + gap: 7px; + margin-bottom: 12px; +} + +.auto-monitor-stat-group:last-child { + margin-bottom: 0; +} + +.auto-monitor-stat-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + min-height: 38px; + padding: 8px 10px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; + font-size: 11px; +} + +.auto-monitor-stat-item span { + min-width: 0; + color: var(--text); +} + +.auto-monitor-stat-item strong { + flex: 0 0 auto; + font-size: 13px; + font-weight: 700; + font-variant-numeric: tabular-nums; +} + +.auto-monitor-stat-item.is-success strong { + color: var(--green); +} + +.auto-monitor-stat-item.is-warning strong { + color: var(--yellow); +} + +.auto-monitor-stat-item.is-error strong { + color: #e57373; +} + + +.auto-monitor-list { + display: flex; + flex-direction: column; + gap: 7px; + max-height: 280px; + overflow-y: auto; +} + +.auto-monitor-ap, +.auto-monitor-queue-item { + display: flex; + align-items: center; + gap: 10px; + min-height: 52px; + padding: 9px 10px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; +} + +.auto-monitor-signal { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 7px; + color: var(--muted); + font-size: 10px; + font-weight: 600; + white-space: nowrap; +} + +.auto-monitor-signal-icon { + display: flex; + align-items: flex-end; + gap: 2px; + width: 22px; + height: 16px; +} + +.auto-monitor-signal-icon i { + display: block; + width: 4px; + border-radius: 1px; + background: var(--border); +} + +.auto-monitor-signal-icon i:nth-child(1) { + height: 4px; +} + +.auto-monitor-signal-icon i:nth-child(2) { + height: 7px; +} + +.auto-monitor-signal-icon i:nth-child(3) { + height: 11px; +} + +.auto-monitor-signal-icon i:nth-child(4) { + height: 15px; +} + +.auto-monitor-signal.is-strong { + color: var(--green); +} + +.auto-monitor-signal.is-medium { + color: var(--orange, #d99a36); +} + +.auto-monitor-signal.is-weak { + color: var(--red); +} + +.auto-monitor-signal.is-strong .auto-monitor-signal-icon i { + background: var(--green); +} + +.auto-monitor-signal.is-medium .auto-monitor-signal-icon i:nth-child(-n+3) { + background: var(--orange, #d99a36); +} + +.auto-monitor-signal.is-weak .auto-monitor-signal-icon i:first-child { + background: var(--red); +} + +.auto-monitor-unavailable { + flex: 0 0 auto; + color: var(--red); + font-size: 23px; + font-weight: 400; + line-height: 1; +} + +.auto-monitor-ap-info { + display: flex; + flex: 1 1 auto; + flex-direction: column; + min-width: 0; + gap: 4px; +} + +.auto-monitor-ap-info strong { + overflow: hidden; + color: var(--text); + font-size: 12px; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.auto-monitor-ap-info > span { + overflow: hidden; + color: var(--muted); + font-size: 10px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.auto-monitor-queue-state { + flex: 0 0 auto; + color: var(--muted); + font-size: 10px; + white-space: nowrap; +} + +.auto-monitor-queue-number { + flex: 0 0 25px; + color: var(--muted); + font-size: 11px; + font-weight: 700; + text-align: center; +} + +.auto-monitor-queue-item.is-processing { + background: rgba(229, 192, 123, 0.10); + border-color: var(--yellow); +} + +.auto-monitor-queue-item.is-processing .auto-monitor-queue-number, +.auto-monitor-queue-item.is-processing .auto-monitor-queue-state { + color: var(--yellow); +} + +.auto-monitor-queue-item.is-processing .auto-monitor-ap-info strong { + color: var(--yellow); +} + +.auto-monitor-log { + margin-top: 20px; + padding-top: 17px; + border-top: 1px solid var(--border); +} + +.auto-monitor-log-heading { + margin-bottom: 12px; +} + +.auto-monitor-log-heading > span { + color: var(--muted); + font-size: 11px; +} + +.auto-monitor-log-list { + display: flex; + flex-direction: column; + gap: 8px; + max-height: 190px; + overflow-y: auto; +} + +.auto-monitor-log-entry { + display: grid; + grid-template-columns: 68px 58px minmax(0, 1fr); + align-items: baseline; + gap: 10px; + font-size: 11px; + line-height: 1.5; +} + +.auto-monitor-log-entry time { + color: var(--muted); + font-variant-numeric: tabular-nums; +} + +.auto-monitor-log-level { + font-size: 9px; + font-weight: 700; + letter-spacing: 0.5px; +} + +.auto-monitor-log-level.is-info { + color: var(--muted); +} + +.auto-monitor-log-level.is-success { + color: var(--green); +} + +.auto-monitor-log-level.is-warning { + color: var(--yellow); +} + +.auto-monitor-log-entry > span:last-child { + min-width: 0; + color: var(--text); + overflow-wrap: anywhere; +} + +@media (max-width: 1100px) { + .auto-monitor-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .auto-monitor-statistics { + grid-column: 1 / -1; + } +} + +@media (max-width: 900px) { + .auto-monitor-grid { + grid-template-columns: minmax(0, 1fr); + } + + .auto-monitor-statistics { + grid-column: auto; + } +} + +@media (max-width: 480px) { + .auto-verification-monitor { + padding: 16px; + } + + .auto-monitor-column { + padding: 12px; + } + + .auto-monitor-air-label, + .auto-monitor-queue-state { + font-size: 9px; + } + + .auto-monitor-log-entry { + grid-template-columns: 58px 48px minmax(0, 1fr); + gap: 7px; + font-size: 10px; + } +} + +/* AUTO VERIFICATION — monitor states */ +.auto-monitor-log-level.is-error { + color: var(--red); +} + +.auto-monitor-empty { + padding: 14px 10px; + color: var(--muted); + font-size: 11px; + text-align: center; +} diff --git a/gui/templates/auto_verification_map.html b/gui/templates/auto_verification_map.html new file mode 100644 index 0000000..62d77e5 --- /dev/null +++ b/gui/templates/auto_verification_map.html @@ -0,0 +1,1772 @@ + + + + + + 🗺 Capture Map — WiFi GPS Mapper + + + + + + + +
+ +
+ + +

+ WiFi GPS Mapper +

+ +
+ Wireless network scanner +
+
+ +
+ + + REPORTS + + + + CRACKLAB + + +
+ +
+ + + + + +
+ +
+ + +
+ +
+ + GPS ВЫКЛЮЧЕН +
+ + + + + +
+ +
+ + + + + Auto: остановлен + + +
+ +
+ +
+ +
+ +
+ +
+
REPORTS
+
Access Points
+

🛡️ Auto Verification

+

+ Географическое отображение результатов проверки паролей Wi-Fi. +

+
+ +
+
+
+
AUTO VERIFICATION ENGINE
+

MONITOR

+
+
+ Ожидание данных +
+
+ +
+
+
+

Кандидаты на проверку

+ 0 AP +
+
+
Нет данных о кандидатах
+
+
+ +
+
+

Очередь проверки

+ 0 AP +
+
+
Очередь пуста
+
+
+ +
+
+

Статистика

+ 0 +
+ +
+
+ Пароль верен + 0 +
+
+ +
+
+ Точка не обнаружена + 0 +
+
+ +
+
+ Неверный пароль + 0 +
+ +
+ Тайм-аут подключения + 0 +
+ +
+ Ошибка сети + 0 +
+ +
+ Неизвестная ошибка + 0 +
+
+
+
+ +
+
+

Журнал событий

+ Последние события +
+ +
+
Событий пока нет
+
+
+
+ + +
+
+
+ SEARCH RADIUS + — +
+ +
+ SCAN RADIUS + + + +
+ +
+

+ GPS-монитор карты остановлен +

+
+
+ +
+ 🗺 Capture Map + + + + + + + + + + +
+ +
+
+ +
+ Загрузка точек… +
+ + +
+ +
+
+ + + +
+
+
+
AUTO VERIFICATION
+

CONFIGURATION

+
+

Параметры подключения и проверки

+
+ +
+
+ + + {% if interface_error %} +
{{ interface_error }}
+ {% endif %} + {% if not interfaces and not interface_error %} +
Wi-Fi-интерфейсы не найдены.
+ {% endif %} +
+ +
+
+ + +
+ GPSD использует локальную службу gpsd и GPS-приёмник. + GPSRelay получает координаты с вашего телефона. +
+
+ + +
+
+ +
+
+
SCAN RADIUS
+ +
+ +
+ {% for radius in [50, 75, 100, 125, 150, 175, 200, 250, 350, 500] %} + + {% endfor %} +
+
+ +
+
+
+ +
+ +
+
PROCESSING
+ +
+
+ + +
+ Максимальный возраст координат GPS, которые принимает + система. Более старые координаты игнорируются. +
+
+ Допустимое значение: от 1 до 30 секунд. +
+
+ +
+ + +
+ Количество дополнительных проходов для повторной проверки + точек, проверка которых завершилась неудачно. +
+
+ Допустимое значение: от 0 до 5 проходов. +
+
+
+
+
+ +
+
+ + + + +
+
+ +
+ + + + + + + diff --git a/install.sh b/install.sh index aa3cea5..fabac21 100755 --- a/install.sh +++ b/install.sh @@ -174,7 +174,7 @@ TMPDIR="$TMP_DIR" \ "$PYTHON" - <<'PYTHON' from pathlib import Path -from database import Database +from database import Database, migrate_wifi_verification_database from cracklab.server.db.migrations import migrate_database database_path = Path("database/wifi.sqlite3") @@ -187,6 +187,8 @@ if not database_path.exists(): else: print(f"Основная база уже существует: {database_path}") print("Повторная инициализация и миграции основной схемы пропущены.") + migrate_wifi_verification_database(database_path) + print("Схема Auto Verification проверена и обновлена при необходимости.") applied = migrate_database(database_path) diff --git a/reports/access_points_page.py b/reports/access_points_page.py index 67b04b0..7ea9f7e 100644 --- a/reports/access_points_page.py +++ b/reports/access_points_page.py @@ -1505,16 +1505,20 @@ def render_wifi_connection_card(ap, credentials): ); }} - if (data.wireguard_active) {{ + if (data.vpn_active) {{ setWarning( - "Обнаружено активное соединение WireGuard. " - + "При необходимости отключите VPN вручную. " - + "Приложение не изменяет состояние WireGuard." + "Обнаружено активное VPN-подключение. " + + "Для надёжной проверки пароля и подключения " + + "рекомендуется временно отключить VPN. " + + "Продолжить можно, но успешная работа " + + "не гарантируется." ); - }} else if (data.wireguard_error) {{ + }} else if (data.vpn_error) {{ setWarning( - "Не удалось проверить состояние WireGuard: " - + data.wireguard_error + "Не удалось достоверно определить состояние VPN. " + + "При активном VPN результат операции " + + "не гарантируется. " + + "Рекомендуется проверить состояние VPN вручную." ); }} @@ -1638,8 +1642,8 @@ def render_wifi_connection_card(ap, credentials): ); }} - if (data.wireguard_warning) {{ - setWarning(data.wireguard_warning); + if (data.vpn_warning) {{ + setWarning(data.vpn_warning); }} }} catch (error) {{ diff --git a/reports/auto_verification_map.py b/reports/auto_verification_map.py new file mode 100644 index 0000000..805eab5 --- /dev/null +++ b/reports/auto_verification_map.py @@ -0,0 +1,271 @@ +""" +GeoJSON data for the Auto Wi-Fi Verification capture map. +""" + +import math +import sqlite3 +from collections import defaultdict + +from reports.database import close as close_database +from reports.database import connect as connect_database +from reports.map_popups import build_standard_popup + + +TECHNICAL_STATUSES = { + "CONNECTION_TIMEOUT", + "NETWORK_ERROR", + "UNKNOWN_ERROR", +} + + +def _valid_coordinates(latitude, longitude): + try: + latitude = float(latitude) + longitude = float(longitude) + except (TypeError, ValueError): + return None + + if not math.isfinite(latitude) or not math.isfinite(longitude): + return None + + if not -90 <= latitude <= 90: + return None + + if not -180 <= longitude <= 180: + return None + + return latitude, longitude + + +def _classify_access_point(credentials): + """ + Classify an AP using the latest attempt for each exact password. + + Priority: + green - any verified credential or successful attempt; + red - every unique password has latest status INVALID_PASSWORD; + orange - at least one latest status is a technical error; + gray - all other cases. + """ + passwords = {} + + for item in credentials: + password = item["password"] + state = passwords.setdefault( + password, + { + "verified": False, + "latest": None, + "latest_order": None, + }, + ) + + if item["verified"]: + state["verified"] = True + + if item["attempt_status"] == "SUCCESS": + state["verified"] = True + + if item["attempt_status"]: + order = ( + item["attempt_started_at"] or "", + item["attempt_id"] or 0, + ) + if state["latest_order"] is None or order > state["latest_order"]: + state["latest_order"] = order + state["latest"] = item["attempt_status"] + + if any(item["verified"] for item in passwords.values()): + return "green" + + latest_statuses = [ + item["latest"] + for item in passwords.values() + ] + + if latest_statuses and all( + status == "INVALID_PASSWORD" + for status in latest_statuses + ): + return "red" + + if any( + status in TECHNICAL_STATUSES + for status in latest_statuses + ): + return "orange" + + return "gray" + + +def build_auto_verification_geojson(): + connection = connect_database() + + try: + connection.row_factory = sqlite3.Row + + rows = connection.execute( + """ + SELECT + ap.id AS access_point_id, + ap.bssid, + ap.essid, + ap.vendor, + ap.encryption, + ap.cipher, + ap.akm, + ap.channel, + ap.last_rssi, + ap.last_seen, + ap.last_latitude, + ap.last_longitude, + + c.id AS credential_id, + c.password, + c.source, + c.verified, + + a.id AS attempt_id, + a.status AS attempt_status, + a.started_at AS attempt_started_at + + FROM access_points AS ap + + INNER JOIN credentials AS c + ON c.access_point_id = ap.id + + LEFT JOIN wifi_verification_attempts AS a + ON a.credential_id = c.id + + WHERE + c.password IS NOT NULL + AND TRIM(c.password) <> '' + AND ap.last_latitude IS NOT NULL + AND ap.last_longitude IS NOT NULL + + ORDER BY + ap.id, + c.id, + a.started_at DESC, + a.id DESC + """ + ).fetchall() + + finally: + close_database(connection) + + access_points = {} + + for row in rows: + ap_id = row["access_point_id"] + + if ap_id not in access_points: + coordinates = _valid_coordinates( + row["last_latitude"], + row["last_longitude"], + ) + if coordinates is None: + continue + + access_points[ap_id] = { + "row": row, + "credentials": {}, + } + + if ap_id not in access_points: + continue + + credential_id = row["credential_id"] + credentials = access_points[ap_id]["credentials"] + + if credential_id not in credentials: + credentials[credential_id] = { + "id": credential_id, + "password": row["password"], + "source": row["source"], + "verified": bool(row["verified"]), + "attempt_id": None, + "attempt_status": None, + "attempt_started_at": None, + } + + credential = credentials[credential_id] + + if row["attempt_id"] is not None: + order = ( + row["attempt_started_at"] or "", + row["attempt_id"], + ) + current_order = ( + credential["attempt_started_at"] or "", + credential["attempt_id"] or 0, + ) + + if credential["attempt_id"] is None or order > current_order: + credential["attempt_id"] = row["attempt_id"] + credential["attempt_status"] = row["attempt_status"] + credential["attempt_started_at"] = row["attempt_started_at"] + + features = [] + counts = { + "green": 0, + "red": 0, + "orange": 0, + "gray": 0, + } + + for item in access_points.values(): + row = item["row"] + credentials = list(item["credentials"].values()) + + if not credentials: + continue + + coordinates = _valid_coordinates( + row["last_latitude"], + row["last_longitude"], + ) + if coordinates is None: + continue + + latitude, longitude = coordinates + status = _classify_access_point(credentials) + + popup = build_standard_popup( + essid=row["essid"], + bssid=row["bssid"], + vendor=row["vendor"], + encryption=row["encryption"], + cipher=row["cipher"], + akm=row["akm"], + channel=row["channel"], + rssi=row["last_rssi"], + passwords=credentials, + handshakes=None, + observed_at=row["last_seen"], + latitude=latitude, + longitude=longitude, + ) + + features.append({ + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [longitude, latitude], + }, + "properties": { + "status": status, + "popup": popup, + "bssid": row["bssid"] or "", + "essid": row["essid"] or "", + }, + }) + + counts[status] += 1 + + return { + "type": "FeatureCollection", + "features": features, + "counts": counts, + "total": len(features), + } diff --git a/reports/wifi_connections.py b/reports/wifi_connections.py index 5539f0d..fc5d3db 100644 --- a/reports/wifi_connections.py +++ b/reports/wifi_connections.py @@ -580,11 +580,11 @@ map.on( ); if ( - data.wireguard_warning + data.vpn_warning && wifiConnectionWarning ) { wifiConnectionWarning.textContent = - data.wireguard_warning; + data.vpn_warning; wifiConnectionWarning.hidden = false; } @@ -856,16 +856,20 @@ def render_wifi_connections_page(conn, context=None): ); } - if (data.wireguard_active) { + if (data.vpn_active) { setWarning( - "Обнаружено активное соединение WireGuard. " - + "При необходимости отключите VPN вручную. " - + "Приложение не изменяет состояние WireGuard." + "Обнаружено активное VPN-подключение. " + + "Для надёжной проверки пароля и подключения " + + "рекомендуется временно отключить VPN. " + + "Продолжить можно, но успешная работа " + + "не гарантируется." ); - } else if (data.wireguard_error) { + } else if (data.vpn_error) { setWarning( - "Не удалось проверить состояние WireGuard: " - + data.wireguard_error + "Не удалось достоверно определить состояние VPN. " + + "При активном VPN результат операции " + + "не гарантируется. " + + "Рекомендуется проверить состояние VPN вручную." ); } document.dispatchEvent( diff --git a/src/auto_gps.py b/src/auto_gps.py new file mode 100644 index 0000000..eee51ad --- /dev/null +++ b/src/auto_gps.py @@ -0,0 +1,636 @@ +import logging +import re +import select +import socket +import subprocess +import threading +import time + +from datetime import datetime, timezone +from logging.handlers import RotatingFileHandler +from pathlib import Path + +from gps import GPSRelaySource, GpsdSource, parse_nmea +from logging_config import ( + LOG_DATE_FORMAT, + LOG_FORMAT, + UTCFormatter, +) + + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + +POLL_INTERVAL_SECONDS = 0.5 +RECONNECT_DELAY_SECONDS = 2.0 +CONNECT_TIMEOUT_SECONDS = 3.0 +GPSD_GREETING_MAX_BYTES = 65536 +LOG_MAX_BYTES = 5 * 1024 * 1024 +LOG_BACKUP_COUNT = 3 + + +def _create_logger(): + logger = logging.getLogger( + "wifi-gps-mapper.auto-verification" + ) + + logger.setLevel(logging.INFO) + logger.propagate = False + + if not logger.handlers: + log_dir = PROJECT_ROOT / "logs" + log_dir.mkdir( + parents=True, + exist_ok=True + ) + + handler = RotatingFileHandler( + log_dir / "auto-verification.log", + maxBytes=LOG_MAX_BYTES, + backupCount=LOG_BACKUP_COUNT, + encoding="utf-8" + ) + + handler.setFormatter( + UTCFormatter( + LOG_FORMAT, + datefmt=LOG_DATE_FORMAT + ) + ) + + logger.addHandler(handler) + + return logger + + +def _get_gpsd_port(): + """Получает IPv4 TCP-порт из активной конфигурации gpsd.socket.""" + try: + result = subprocess.run( + [ + "systemctl", + "show", + "gpsd.socket", + "--property=Listen", + "--value", + ], + check=True, + capture_output=True, + text=True, + timeout=3, + ) + except (OSError, subprocess.SubprocessError) as error: + raise RuntimeError( + f"Cannot read gpsd.socket configuration: {error}" + ) from error + + ports = set() + + for line in result.stdout.splitlines(): + endpoint = line.strip() + + if "=" in endpoint: + endpoint = endpoint.split("=", 1)[1].strip() + + match = re.fullmatch( + r"(?:127\.0\.0\.1|0\.0\.0\.0):(\d+)(?:\s+\(Stream\))?", + endpoint, + ) + + if match: + port = int(match.group(1)) + + if not 1 <= port <= 65535: + raise RuntimeError( + f"Invalid GPSD TCP port: {port}" + ) + + ports.add(port) + + if not ports: + raise RuntimeError( + "No IPv4 TCP listener found in gpsd.socket" + ) + + if len(ports) != 1: + raise RuntimeError( + "gpsd.socket has multiple different IPv4 TCP ports: " + + ", ".join(str(port) for port in sorted(ports)) + ) + + return ports.pop() + + +logger = _create_logger() + + +class AutoGPSService: + + def __init__( + self, + settings, + callback=None, + fix_callback=None, + position_callback=None + ): + self.settings = dict(settings or {}) + self.callback = callback + self.fix_callback = fix_callback + self.position_callback = position_callback + + self.gps_source = self.settings.get("gps_source") + + self.max_age_seconds = float( + self.settings.get( + "gnss_max_age_seconds", + 10 + ) + ) + + if self.max_age_seconds <= 0: + raise ValueError( + "gnss_max_age_seconds must be positive" + ) + + if self.gps_source not in ("gpsd", "gpsrelay"): + raise ValueError( + "Auto GPS source must be 'gpsd' or 'gpsrelay'" + ) + + if self.gps_source == "gpsrelay": + host = self.settings.get("gpsrelay_host") + port = self.settings.get("gpsrelay_port") + + if not isinstance(host, str) or not host.strip(): + raise ValueError( + "GPS Relay host is required" + ) + + if ( + isinstance(port, bool) + or not isinstance(port, int) + or not 1 <= port <= 65535 + ): + raise ValueError( + "GPS Relay port must be between 1 and 65535" + ) + + self.thread = None + self.stop_event = threading.Event() + + self.source = None + self.source_lock = threading.Lock() + self.state_lock = threading.Lock() + + self.running = False + self.state = "READY" + self.error = None + + self.current_fix = None + self.last_fix_monotonic = None + self.connected_monotonic = None + + def _emit( + self, + level, + code, + message + ): + event = { + "level": level, + "code": code, + "message": message, + "state": self.state, + "timestamp": datetime.now( + timezone.utc + ).isoformat() + } + + log_method = getattr( + logger, + level.lower(), + logger.info + ) + + log_method(message) + + if self.callback is not None: + try: + self.callback(event) + except Exception: + logger.exception( + "Auto GPS callback failed" + ) + + def _set_state(self, state): + with self.state_lock: + self.state = state + + def _create_source(self): + if self.gps_source == "gpsd": + return GpsdSource( + host="127.0.0.1", + port=_get_gpsd_port() + ) + + if self.gps_source == "gpsrelay": + return GPSRelaySource( + self.settings["gpsrelay_host"].strip(), + self.settings["gpsrelay_port"] + ) + + raise ValueError( + f"Unsupported Auto GPS source: {self.gps_source}" + ) + + def _open_source(self, source): + # Поддержка тестовых источников с заранее созданным сокетом. + if getattr(source, "socket", None) is not None: + stream = source.open() + return source.socket, stream, b"" + + connection = socket.create_connection( + (source.host, source.port), + timeout=CONNECT_TIMEOUT_SECONDS + ) + + # Сохраняем сокет сразу после подключения, чтобы stop() + # мог закрыть его во время дальнейшей инициализации. + source.socket = connection + connection.settimeout(CONNECT_TIMEOUT_SECONDS) + + pending = b"" + + if self.gps_source == "gpsd": + greeting = bytearray() + + handshake_deadline = ( + time.monotonic() + CONNECT_TIMEOUT_SECONDS + ) + + while b"\n" not in greeting: + if self.stop_event.is_set(): + raise ConnectionError( + "Auto GPS stopped during GPSD handshake" + ) + + remaining = ( + handshake_deadline - time.monotonic() + ) + + if remaining <= 0: + raise TimeoutError( + "GPSD handshake timed out" + ) + + connection.settimeout(remaining) + chunk = connection.recv(4096) + + if not chunk: + raise ConnectionError( + "GPSD closed the connection during handshake" + ) + + greeting.extend(chunk) + + if len(greeting) > GPSD_GREETING_MAX_BYTES: + raise ConnectionError( + "GPSD greeting exceeds the allowed size" + ) + + greeting_end = greeting.find(b"\n") + 1 + pending = bytes(greeting[greeting_end:]) + + connection.sendall( + b'?WATCH={"enable":true,"json":false,"nmea":true};\n' + ) + + connection.setblocking(False) + + return connection, None, pending + + def start(self): + if ( + self.thread is not None + and self.thread.is_alive() + ): + return False + + self.stop_event.clear() + + with self.state_lock: + self.running = True + self.state = "STARTING" + self.error = None + self.current_fix = None + self.last_fix_monotonic = None + self.connected_monotonic = None + + self.thread = threading.Thread( + target=self.worker, + name="auto-gps", + daemon=True + ) + + self.thread.start() + + self._emit( + "INFO", + "GPS_STARTED", + f"Auto GPS started with source: {self.gps_source}" + ) + + return True + + def stop(self): + self.stop_event.set() + + with self.source_lock: + source = self.source + + if source is not None: + connection = getattr( + source, + "socket", + None + ) + + if connection is not None: + try: + connection.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + try: + source.close() + except Exception: + logger.exception( + "Auto GPS source close failed" + ) + + def _set_fix(self, gps): + now = time.monotonic() + + with self.state_lock: + had_fresh_fix = ( + self.current_fix is not None + and self.last_fix_monotonic is not None + and now - self.last_fix_monotonic + <= self.max_age_seconds + ) + + self.current_fix = gps + self.last_fix_monotonic = now + self.state = "FIX" + self.error = None + + if not had_fresh_fix: + self._emit( + "INFO", + "GPS_FIX_RESTORED", + "Auto GPS has a fresh valid FIX: " + f"lat={gps.latitude:.6f}, " + f"lon={gps.longitude:.6f}" + ) + + if self.fix_callback is not None: + try: + self.fix_callback(gps) + except Exception: + logger.exception( + "Auto GPS FIX callback failed" + ) + + if self.position_callback is not None: + try: + self.position_callback(gps) + except Exception: + logger.exception( + "Auto GPS position callback failed" + ) + + def _check_fix_freshness(self): + now = time.monotonic() + + with self.state_lock: + if self.state in ("STOPPED", "RECONNECTING"): + return + + reference = ( + self.last_fix_monotonic + if self.last_fix_monotonic is not None + else self.connected_monotonic + ) + + if reference is None: + return + + age = now - reference + + if age <= self.max_age_seconds: + return + + if self.state == "NO_FIX": + return + + self.current_fix = None + self.state = "NO_FIX" + + self._emit( + "WARNING", + "GPS_FIX_LOST", + "Auto GPS has no fresh valid FIX. " + f"Last valid position age: {age:.1f} seconds." + ) + + def get_status(self): + now = time.monotonic() + + with self.state_lock: + fix = self.current_fix + last_fix = self.last_fix_monotonic + state = self.state + error = self.error + + age = ( + now - last_fix + if last_fix is not None + else None + ) + + fresh = ( + fix is not None + and age is not None + and age <= self.max_age_seconds + and state == "FIX" + ) + + return { + "running": self.running, + "source": self.gps_source, + "state": state, + "has_fresh_fix": fresh, + "latitude": ( + fix.latitude + if fresh + else None + ), + "longitude": ( + fix.longitude + if fresh + else None + ), + "fix_age_seconds": age, + "max_age_seconds": self.max_age_seconds, + "error": error + } + + def worker(self): + try: + while not self.stop_event.is_set(): + source = None + stream = None + + try: + source = self._create_source() + + with self.source_lock: + self.source = source + + if self.stop_event.is_set(): + break + + self._set_state("CONNECTING") + + logger.info( + "Connecting Auto GPS to %s", + self.gps_source + ) + + connection, stream, pending = self._open_source( + source + ) + + if self.stop_event.is_set(): + break + + with self.state_lock: + self.connected_monotonic = time.monotonic() + self.state = "CONNECTED" + self.error = None + + self._emit( + "INFO", + "GPS_CONNECTED", + f"Auto GPS connected to {self.gps_source}" + ) + + while not self.stop_event.is_set(): + # Сначала обрабатываем уже полученные строки. + # Это исключает зависимость от готовности сокета, + # когда данные остались во внутреннем буфере. + while b"\n" in pending: + line, pending = pending.split(b"\n", 1) + + gps = parse_nmea( + line.decode("ascii", errors="replace").strip(), + datetime.now(timezone.utc) + ) + + if gps is not None: + self._set_fix(gps) + else: + self._check_fix_freshness() + + if len(pending) > GPSD_GREETING_MAX_BYTES: + raise ConnectionError( + "NMEA receive buffer exceeds the allowed size" + ) + + readable, _, _ = select.select( + [connection], + [], + [], + POLL_INTERVAL_SECONDS + ) + + if not readable: + self._check_fix_freshness() + continue + + chunk = connection.recv(4096) + + if not chunk: + raise ConnectionError( + "GPS source closed the NMEA stream" + ) + + pending += chunk + + except Exception as error: + if self.stop_event.is_set(): + break + + with self.state_lock: + self.current_fix = None + self.state = "RECONNECTING" + self.error = str(error) + + self._emit( + "WARNING", + "GPS_CONNECTION_LOST", + "Auto GPS connection lost: " + f"{error}. Reconnecting to the same source." + ) + + finally: + if stream is not None: + try: + stream.close() + except Exception: + logger.exception( + "Auto GPS stream close failed" + ) + + if source is not None: + try: + source.close() + except Exception: + logger.exception( + "Auto GPS source close failed" + ) + + with self.source_lock: + if self.source is source: + self.source = None + + if not self.stop_event.is_set(): + self.stop_event.wait( + RECONNECT_DELAY_SECONDS + ) + + except Exception as error: + with self.state_lock: + self.error = str(error) + self.state = "ERROR" + + self._emit( + "ERROR", + "GPS_SERVICE_ERROR", + f"Auto GPS service error: {error}" + ) + + finally: + with self.state_lock: + self.current_fix = None + self.running = False + was_error = self.state == "ERROR" + + if not was_error: + self.state = "STOPPED" + + if not was_error: + self._emit( + "INFO", + "GPS_STOPPED", + "Auto GPS service stopped" + ) diff --git a/src/auto_wifi_verification.py b/src/auto_wifi_verification.py new file mode 100644 index 0000000..45f09b1 --- /dev/null +++ b/src/auto_wifi_verification.py @@ -0,0 +1,1685 @@ +import logging +import math +import queue +import threading +import time + +from datetime import datetime, timezone + +from reports.database import close as close_database +from reports.database import connect as connect_database + +from auto_gps import AutoGPSService +from wifi_connection import ( + APNotFoundError, + NetworkCleanupError, + NetworkCommandError, + NetworkRestoreError, + WiFiConnectionError +) + + +logger = logging.getLogger( + "wifi-gps-mapper.auto-verification" +) + + +def _utc_now(): + return datetime.now( + timezone.utc + ).isoformat(timespec="seconds") + + +def _distance_meters(lat1, lon1, lat2, lon2): + radius = 6371000.0 + + lat1 = math.radians(float(lat1)) + lon1 = math.radians(float(lon1)) + lat2 = math.radians(float(lat2)) + lon2 = math.radians(float(lon2)) + + delta_lat = lat2 - lat1 + delta_lon = lon2 - lon1 + + value = ( + math.sin(delta_lat / 2) ** 2 + + math.cos(lat1) + * math.cos(lat2) + * math.sin(delta_lon / 2) ** 2 + ) + + return radius * 2 * math.atan2( + math.sqrt(value), + math.sqrt(max(0.0, 1.0 - value)) + ) + + +def _is_invalid_password(result): + if result.get("success"): + return False + + text = " ".join( + str(result.get(key) or "") + for key in ( + "error", + "error_stdout", + "error_stderr" + ) + ).lower() + + markers = ( + "incorrect password", + "wrong password", + "password is incorrect", + "secrets were required", + "no secrets", + "secret was required", + "802-11-wireless-security.psk", + "4-way handshake", + "four-way handshake", + "authentication failed", + "invalid psk" + ) + + return any( + marker in text + for marker in markers + ) + + +class AutoWiFiVerificationService: + + def __init__( + self, + settings, + interface, + wifi_connection_service, + callback=None, + acquire_network_owner=None, + release_network_owner=None, + gps_service=None + ): + self.settings = dict(settings or {}) + self.interface = interface + self.wifi_connection_service = wifi_connection_service + self.callback = callback + self.acquire_network_owner = acquire_network_owner + self.release_network_owner = release_network_owner + self.network_owner_acquired = False + self.start_lock = threading.Lock() + + self.radius_m = int( + self.settings.get("radius_m", 500) + ) + + self.queue_retry_passes = int( + self.settings.get( + "queue_retry_passes", + 2 + ) + ) + + self._gps_fix_condition = threading.Condition() + self._gps_fix_generation = 0 + self._gps_fix_consumed_generation = 0 + + self._radius_update_lock = threading.Lock() + self._pending_radius_update = None + self._radius_update_event = threading.Event() + + self.manage_gps_service = gps_service is None + + if gps_service is None: + self.gps_service = AutoGPSService( + self.settings, + callback=self._gps_callback, + position_callback=self._gps_fix_callback + ) + else: + self.gps_service = gps_service + + self.stop_event = threading.Event() + self.thread = None + + self.lock = threading.RLock() + + self.running = False + self.state = "STOPPED" + self.error = None + + self.session_id = None + + self.access_points_total = 0 + self.attempts_total = 0 + self.success_count = 0 + self.invalid_password_count = 0 + self.technical_error_count = 0 + + self.current_bssid = None + self.current_essid = None + + self._bssid_states = {} + self._missing_scan_bssids = set() + + # Отдельные счётчики результатов попыток. + self.ap_not_found_count = 0 + self.connection_timeout_count = 0 + self.network_error_count = 0 + self.unknown_error_count = 0 + + # Только безопасные снимки для интерфейса. + self.monitor_candidates = [] + self.monitor_queue = [] + self.monitor_active = None + self.monitor_events = [] + self.monitor_event_limit = 100 + + self._notify() + + def _gps_callback(self, status): + self._notify() + + def _gps_fix_callback(self, gps): + with self._gps_fix_condition: + self._gps_fix_generation += 1 + self._gps_fix_condition.notify_all() + + def request_radius_update(self, radius_m): + if type(radius_m) is not int or radius_m not in (50, 75, 100, 125, 150, 175, 200, 250, 350, 500): + raise ValueError("Invalid verification radius.") + + with self._radius_update_lock: + with self._gps_fix_condition: + after_generation = self._gps_fix_generation + self._pending_radius_update = { + "radius_m": radius_m, + "after_generation": after_generation + } + self._radius_update_event.set() + self._gps_fix_condition.notify_all() + + return True + + def _notify(self): + if self.callback is None: + return + + try: + self.callback( + self.get_status() + ) + except Exception: + logger.exception( + "Auto Wi-Fi verification callback failed." + ) + + def _add_monitor_event(self, event, message, level="info"): + item = { + "timestamp": _utc_now(), + "event": event, + "message": message, + "level": level + } + + with self.lock: + self.monitor_events.append(item) + self.monitor_events = self.monitor_events[ + -self.monitor_event_limit: + ] + + def _update_monitor_candidates(self, candidates): + with self.lock: + strengths = { + candidate["bssid"].lower(): candidate.get("strength") + for candidate in self.monitor_candidates + } + + snapshot = [] + + for access_point in candidates: + bssid = access_point["bssid"] + + snapshot.append({ + "bssid": bssid, + "essid": access_point["essid"], + "distance": ( + round(float(access_point["distance"]), 1) + if access_point.get("distance") is not None + else None + ), + "strength": strengths.get(bssid.lower()) + }) + + self.monitor_candidates = sorted( + snapshot, + key=lambda candidate: ( + candidate["strength"] is None, + -(candidate["strength"] or 0) + ) + ) + + def _update_monitor_signal(self, scan_results): + strengths = { + access_point.bssid.lower(): getattr( + access_point, + "strength", + None + ) + for access_point in scan_results + } + + with self.lock: + for candidate in self.monitor_candidates: + strength = strengths.get( + candidate["bssid"].lower() + ) + + candidate["strength"] = ( + strength + if isinstance(strength, int) + and 0 <= strength <= 100 + else None + ) + + self.monitor_candidates.sort( + key=lambda candidate: ( + candidate["strength"] is None, + -(candidate["strength"] or 0) + ) + ) + + def _update_monitor_queue(self, work_queue): + grouped = {} + + for job in work_queue: + bssid = job[1] + key = bssid.lower() + + if key not in grouped: + grouped[key] = { + "bssid": bssid, + "essid": job[2] + } + + snapshot = list(grouped.values()) + + with self.lock: + self.monitor_queue = snapshot + + def _set_monitor_active(self, job=None): + snapshot = None + + if job is not None: + snapshot = { + "bssid": job[1], + "essid": job[2] + } + + with self.lock: + self.monitor_active = snapshot + + def get_status(self): + with self.lock: + gps_status = self.gps_service.get_status() + + return { + "running": self.running, + "state": self.state, + "error": self.error, + "session_id": self.session_id, + "interface": self.interface, + "radius_m": self.radius_m, + "gps": gps_status, + "access_points_total": self.access_points_total, + "attempts_total": self.attempts_total, + "success_count": self.success_count, + "invalid_password_count": self.invalid_password_count, + "technical_error_count": self.technical_error_count, + "monitor_statistics": { + "SUCCESS": self.success_count, + "AP_NOT_FOUND": self.ap_not_found_count, + "INVALID_PASSWORD": self.invalid_password_count, + "CONNECTION_TIMEOUT": self.connection_timeout_count, + "NETWORK_ERROR": self.network_error_count, + "UNKNOWN_ERROR": self.unknown_error_count + }, + "monitor_candidates": [ + dict(item) + for item in self.monitor_candidates + ], + "monitor_queue": [ + dict(item) + for item in self.monitor_queue + ], + "monitor_active": ( + dict(self.monitor_active) + if self.monitor_active is not None + else None + ), + "monitor_events": [ + dict(item) + for item in self.monitor_events + ], + "current_bssid": self.current_bssid, + "current_essid": self.current_essid + } + + def start(self): + with self.start_lock: + with self.lock: + if self.running: + return False + + if self.thread and self.thread.is_alive(): + return False + + if self.acquire_network_owner is not None: + acquired, error = self.acquire_network_owner( + "AUTO_WIFI_VERIFY" + ) + + if not acquired: + self._set_state("BUSY", error) + return False + + with self.lock: + self.network_owner_acquired = True + + try: + gps_generation = 0 + + if not self.manage_gps_service: + gps_status = self.gps_service.get_status() + + if ( + gps_status.get("has_fresh_fix") + and gps_status.get("latitude") is not None + and gps_status.get("longitude") is not None + ): + gps_generation = 1 + + with self._radius_update_lock: + self._pending_radius_update = None + self._radius_update_event.clear() + + with self.lock: + self.stop_event.clear() + + with self._gps_fix_condition: + self._gps_fix_generation = gps_generation + self._gps_fix_consumed_generation = 0 + + self._bssid_states.clear() + self._missing_scan_bssids.clear() + self.running = True + self.state = "WAITING_GPS" + self.error = None + + self.thread = threading.Thread( + target=self._worker, + name="auto-wifi-verification", + daemon=True + ) + + self.thread.start() + + except Exception: + try: + self._release_network_owner() + except Exception: + logger.exception( + "Failed to release AUTO_WIFI_VERIFY " + "network owner after startup error." + ) + + with self.lock: + self.running = False + self.thread = None + + raise + + self._notify() + return True + + def _release_network_owner(self): + with self.lock: + acquired = self.network_owner_acquired + + if not acquired: + return + + if self.release_network_owner is None: + raise RuntimeError( + "AUTO_WIFI_VERIFY network owner cannot be released: " + "release callback is not configured." + ) + + self.release_network_owner("AUTO_WIFI_VERIFY") + + with self.lock: + self.network_owner_acquired = False + + def stop(self, wait=True): + self.stop_event.set() + + with self._gps_fix_condition: + self._gps_fix_condition.notify_all() + + if self.manage_gps_service: + try: + self.gps_service.stop() + except Exception: + logger.exception( + "Failed to stop Auto GPS service." + ) + + thread = self.thread + + if ( + wait + and thread + and thread.is_alive() + and thread is not threading.current_thread() + ): + thread.join(timeout=15) + + self._notify() + + def _set_state(self, state, error=None): + with self.lock: + previous_state = self.state + self.state = state + self.error = error + + if previous_state != state: + self._add_monitor_event( + "STATE", + f"Состояние сервиса: {state}", + "error" if state == "ERROR" else "info" + ) + + self._notify() + + def _increment(self, field): + with self.lock: + setattr( + self, + field, + getattr(self, field) + 1 + ) + + def _create_session(self, connection): + cursor = connection.execute( + """ + INSERT INTO wifi_verification_sessions ( + started_at, + status, + radius_m, + interface_name, + access_points_total, + attempts_total, + success_count, + invalid_password_count, + technical_error_count + ) + VALUES (?, 'RUNNING', ?, ?, 0, 0, 0, 0, 0) + """, + ( + _utc_now(), + self.radius_m, + self.interface + ) + ) + + connection.commit() + + self.session_id = cursor.lastrowid + + def _update_session(self, connection, status): + if self.session_id is None: + return + + with self.lock: + values = ( + self.access_points_total, + self.attempts_total, + self.success_count, + self.invalid_password_count, + self.technical_error_count + ) + + connection.execute( + """ + UPDATE wifi_verification_sessions + SET + finished_at = ?, + status = ?, + access_points_total = ?, + attempts_total = ?, + success_count = ?, + invalid_password_count = ?, + technical_error_count = ? + WHERE id = ? + """, + ( + _utc_now(), + status, + *values, + self.session_id + ) + ) + + connection.commit() + + def _record_attempt( + self, + connection, + credential_id, + bssid, + status, + error_code=None, + error_message=None + ): + connection.execute( + """ + INSERT INTO wifi_verification_attempts ( + credential_id, + session_id, + verification_mode, + status, + started_at, + finished_at, + interface_name, + bssid, + error_code, + error_message + ) + VALUES (?, ?, 'AUTO', ?, ?, ?, ?, ?, ?, ?) + """, + ( + credential_id, + self.session_id, + status, + _utc_now(), + _utc_now(), + self.interface, + bssid, + error_code, + error_message + ) + ) + + connection.commit() + + self._increment("attempts_total") + + if status == "SUCCESS": + self._increment("success_count") + elif status == "AP_NOT_FOUND": + self._increment("ap_not_found_count") + elif status == "INVALID_PASSWORD": + self._increment("invalid_password_count") + elif status == "CONNECTION_TIMEOUT": + self._increment("technical_error_count") + self._increment("connection_timeout_count") + elif status == "NETWORK_ERROR": + self._increment("technical_error_count") + self._increment("network_error_count") + elif status == "UNKNOWN_ERROR": + self._increment("technical_error_count") + self._increment("unknown_error_count") + + self._add_monitor_event( + "ATTEMPT_RESULT", + f"Результат проверки: {status}", + "success" if status == "SUCCESS" else ( + "error" if status not in ( + "INVALID_PASSWORD", + ) else "warning" + ) + ) + + self._update_session_counters(connection) + + def _update_session_counters(self, connection): + if self.session_id is None: + return + + with self.lock: + values = ( + self.attempts_total, + self.success_count, + self.invalid_password_count, + self.technical_error_count + ) + + connection.execute( + """ + UPDATE wifi_verification_sessions + SET + attempts_total = ?, + success_count = ?, + invalid_password_count = ?, + technical_error_count = ? + WHERE id = ? + """, + ( + *values, + self.session_id + ) + ) + + connection.commit() + + def _get_gps_fix(self): + status = self.gps_service.get_status() + + if not status.get("has_fresh_fix"): + return None + + latitude = status.get("latitude") + longitude = status.get("longitude") + + if latitude is None or longitude is None: + return None + + return ( + float(latitude), + float(longitude) + ) + + def _wait_for_gps(self): + self._set_state("WAITING_GPS") + + while not self.stop_event.is_set(): + with self._gps_fix_condition: + while ( + not self.stop_event.is_set() + and self._gps_fix_generation + <= self._gps_fix_consumed_generation + ): + self._gps_fix_condition.wait() + + if self.stop_event.is_set(): + return None + + self._gps_fix_consumed_generation = ( + self._gps_fix_generation + ) + + fix = self._get_gps_fix() + + if fix is not None: + return fix + + return None + + def _get_candidates(self, connection, fix): + rows = connection.execute( + """ + SELECT + ap.id AS access_point_id, + ap.bssid, + ap.essid, + ap.last_latitude, + ap.last_longitude, + MIN(c.id) AS credential_id, + c.password + FROM access_points ap + INNER JOIN credentials c + ON c.access_point_id = ap.id + WHERE + c.password IS NOT NULL + AND c.password != '' + AND ap.last_latitude IS NOT NULL + AND ap.last_longitude IS NOT NULL + AND NOT EXISTS ( + SELECT 1 + FROM credentials verified_c + WHERE + verified_c.access_point_id = ap.id + AND verified_c.password COLLATE BINARY = + c.password COLLATE BINARY + AND verified_c.verified = 1 + ) + AND NOT EXISTS ( + SELECT 1 + FROM credentials history_c + INNER JOIN wifi_verification_attempts attempt + ON attempt.credential_id = history_c.id + WHERE + history_c.access_point_id = ap.id + AND history_c.password COLLATE BINARY = + c.password COLLATE BINARY + AND attempt.status = 'INVALID_PASSWORD' + AND attempt.id = ( + SELECT MAX(latest_attempt.id) + FROM credentials latest_c + INNER JOIN wifi_verification_attempts latest_attempt + ON latest_attempt.credential_id = latest_c.id + WHERE + latest_c.access_point_id = ap.id + AND latest_c.password COLLATE BINARY = + c.password COLLATE BINARY + ) + ) + GROUP BY + ap.id, + ap.bssid, + ap.essid, + ap.last_latitude, + ap.last_longitude, + c.password COLLATE BINARY + ORDER BY ap.id, MIN(c.id) + """ + ).fetchall() + + grouped = {} + + for row in rows: + distance = _distance_meters( + fix[0], + fix[1], + row["last_latitude"], + row["last_longitude"] + ) + + if distance > self.radius_m: + continue + + bssid = row["bssid"].lower() + + if bssid not in grouped: + grouped[bssid] = { + "access_point_id": row["access_point_id"], + "bssid": row["bssid"], + "essid": row["essid"], + "distance": distance, + "credentials": [] + } + + grouped[bssid]["credentials"].append( + { + "credential_id": row["credential_id"], + "password": row["password"] + } + ) + + return sorted( + grouped.values(), + key=lambda item: item["distance"] + ) + + def _apply_pending_radius_update(self, connection, work_queue): + while not self.stop_event.is_set(): + with self._radius_update_lock: + command = self._pending_radius_update + + if command is None: + return False + + self._set_state("WAITING_GPS") + + while not self.stop_event.is_set(): + with self._radius_update_lock: + command = self._pending_radius_update + + if command is None: + return False + + after_generation = command["after_generation"] + + with self._gps_fix_condition: + generation = self._gps_fix_generation + + if generation <= after_generation: + self._gps_fix_condition.wait() + continue + + self._gps_fix_consumed_generation = max( + self._gps_fix_consumed_generation, + generation + ) + + fix = self._get_gps_fix() + + if fix is None: + with self._radius_update_lock: + if self._pending_radius_update is command: + command["after_generation"] = generation + + continue + + with self._radius_update_lock: + if self._pending_radius_update is not command: + break + + radius_m = command["radius_m"] + + with self.lock: + self.radius_m = radius_m + + candidates = self._get_candidates( + connection, + fix + ) + + candidate_credentials = { + access_point["bssid"].lower(): { + credential["credential_id"] + for credential in access_point["credentials"] + } + for access_point in candidates + } + + queued_ids = set() + filtered_queue = [] + + for job in work_queue: + bssid_key = job[1].lower() + credential_id = job[3]["credential_id"] + state = self._bssid_states.get(bssid_key) + + if ( + bssid_key not in candidate_credentials + or state is None + or state["status"] == "VERIFIED" + or credential_id not in candidate_credentials[bssid_key] + or credential_id in state["processed_credentials"] + or (bssid_key, credential_id) in queued_ids + ): + continue + + filtered_queue.append(job) + queued_ids.add((bssid_key, credential_id)) + + work_queue[:] = filtered_queue + + for access_point in candidates: + bssid = access_point["bssid"] + bssid_key = bssid.lower() + + if bssid_key in self._missing_scan_bssids: + continue + + state = self._bssid_states.setdefault( + bssid_key, + { + "status": "NEW", + "processed_credentials": set() + } + ) + + if state["status"] == "VERIFIED": + continue + + processed_ids = state["processed_credentials"] + + for credential in access_point["credentials"]: + credential_id = credential["credential_id"] + + if credential_id in processed_ids: + continue + + if (bssid_key, credential_id) in queued_ids: + continue + + work_queue.append( + ( + access_point["access_point_id"], + bssid, + access_point["essid"], + credential, + 0 + ) + ) + + queued_ids.add((bssid_key, credential_id)) + + for bssid_key, state in self._bssid_states.items(): + if state["status"] == "VERIFIED": + continue + + has_jobs = any( + job[1].lower() == bssid_key + for job in work_queue + ) + + state["status"] = ( + "QUEUED" if has_jobs else "COMPLETED" + ) + + with self.lock: + self.access_points_total = len(candidates) + + self._update_monitor_candidates(candidates) + self._update_monitor_queue(work_queue) + + self._pending_radius_update = None + self._radius_update_event.clear() + + self._add_monitor_event( + "RADIUS_UPDATED", + ( + f"Радиус проверки обновлён: {radius_m} м; " + f"кандидатов: {len(candidates)}" + ) + ) + + return True + + if self.stop_event.is_set(): + return False + + return False + + def _verify_password( + self, + connection, + access_point, + credential + ): + credential_id = credential["credential_id"] + bssid = access_point["bssid"] + password = credential["password"] + + try: + result = self.wifi_connection_service.verify( + self.interface, + bssid, + password, + restore_connection=True, + keep_profile=False, + access_point=access_point["scan_result"] + ) + + except APNotFoundError as error: + self._record_attempt( + connection, + credential_id, + bssid, + "AP_NOT_FOUND", + "AP_NOT_FOUND", + str(error) + ) + return "AP_NOT_FOUND" + + except (NetworkRestoreError, NetworkCleanupError): + raise + + except NetworkCommandError as error: + status = ( + "CONNECTION_TIMEOUT" + if error.timed_out + else "NETWORK_ERROR" + ) + + self._record_attempt( + connection, + credential_id, + bssid, + status, + type(error).__name__, + str(error) + ) + return "TECHNICAL_ERROR" + + except WiFiConnectionError as error: + self._record_attempt( + connection, + credential_id, + bssid, + "UNKNOWN_ERROR", + type(error).__name__, + str(error) + ) + return "TECHNICAL_ERROR" + + if result.get("success"): + connection.execute( + """ + UPDATE credentials + SET verified = 0 + WHERE + access_point_id = ? + AND password COLLATE BINARY != ? COLLATE BINARY + """, + ( + access_point["access_point_id"], + password + ) + ) + connection.execute( + """ + UPDATE credentials + SET verified = 1 + WHERE + access_point_id = ? + AND password COLLATE BINARY = ? COLLATE BINARY + """, + ( + access_point["access_point_id"], + password + ) + ) + connection.commit() + + self._record_attempt( + connection, + credential_id, + bssid, + "SUCCESS" + ) + + return "SUCCESS" + + if result.get("error_type") == "APNotFoundError": + self._record_attempt( + connection, + credential_id, + bssid, + "AP_NOT_FOUND", + "AP_NOT_FOUND", + result.get("error") + ) + return "AP_NOT_FOUND" + + if _is_invalid_password(result): + self._record_attempt( + connection, + credential_id, + bssid, + "INVALID_PASSWORD", + result.get("error_type") or "INVALID_PASSWORD", + result.get("error") + ) + return "INVALID_PASSWORD" + + error_type = result.get("error_type") or "UNKNOWN_ERROR" + + status = ( + "CONNECTION_TIMEOUT" + if result.get("error_timed_out") + else "NETWORK_ERROR" + if error_type == "NetworkCommandError" + else "UNKNOWN_ERROR" + ) + + self._record_attempt( + connection, + credential_id, + bssid, + status, + error_type, + result.get("error") + ) + + return "TECHNICAL_ERROR" + + def _process_access_point( + self, + connection, + access_point, + retry_queue, + scan_result=None + ): + bssid = access_point["bssid"] + result = { + "processed_credentials": set(), + "verified": False, + "interrupted": False, + "ap_not_found": False + } + + with self.lock: + self.current_bssid = bssid + self.current_essid = access_point["essid"] + + self._notify() + + if scan_result is None: + try: + scan_result = self.wifi_connection_service.get_access_point( + self.interface, + bssid + ) + + except APNotFoundError: + retry_queue[:] = [ + job for job in retry_queue + if job[1].lower() != bssid.lower() + ] + result["ap_not_found"] = True + return result + + access_point["scan_result"] = scan_result + + for credential in access_point["credentials"]: + if self.stop_event.is_set(): + result["interrupted"] = True + return result + + outcome = self._verify_password( + connection, + access_point, + credential + ) + + result["processed_credentials"].add( + credential["credential_id"] + ) + + if outcome == "AP_NOT_FOUND": + retry_queue[:] = [ + job for job in retry_queue + if job[1].lower() != bssid.lower() + ] + result["ap_not_found"] = True + break + + if outcome == "SUCCESS": + result["verified"] = True + retry_queue[:] = [ + job for job in retry_queue + if job[1].lower() != bssid.lower() + ] + break + + if outcome in ("INVALID_PASSWORD", "TECHNICAL_ERROR"): + retry_queue.append( + ( + access_point["access_point_id"], + bssid, + access_point["essid"], + credential + ) + ) + + self._notify() + + return result + + def _process_retry( + self, + connection, + job, + retry_queue, + scan_result=None + ): + access_point_id, bssid, essid, credential = job[:4] + + result = { + "verified": False, + "interrupted": False, + "ap_not_found": False + } + + if scan_result is None: + try: + scan_result = self.wifi_connection_service.get_access_point( + self.interface, + bssid + ) + except APNotFoundError: + retry_queue[:] = [ + queued_job for queued_job in retry_queue + if queued_job[1].lower() != bssid.lower() + ] + result["ap_not_found"] = True + return result + + access_point = { + "access_point_id": access_point_id, + "bssid": bssid, + "essid": essid, + "scan_result": scan_result + } + + if self.stop_event.is_set(): + result["interrupted"] = True + return result + + outcome = self._verify_password( + connection, + access_point, + credential + ) + + if outcome == "SUCCESS": + result["verified"] = True + + elif outcome == "AP_NOT_FOUND": + result["ap_not_found"] = True + retry_queue.append(job) + + elif outcome in ("INVALID_PASSWORD", "TECHNICAL_ERROR"): + retry_queue.append(job) + + self._notify() + + return result + + def _worker(self): + connection = None + final_status = "STOPPED" + + try: + connection = connect_database() + + self._create_session( + connection + ) + + if self.manage_gps_service: + self.gps_service.start() + + # Единственная FIFO-очередь. + # Формат задания: + # (access_point_id, bssid, essid, credential, retry_count) + work_queue = [] + + self._update_monitor_queue(work_queue) + self._set_monitor_active() + self._add_monitor_event( + "SERVICE_STARTED", + "Сервис автоматической проверки запущен" + ) + + gps_refresh_deferred = False + + while not self.stop_event.is_set(): + if self._radius_update_event.is_set(): + self._apply_pending_radius_update( + connection, + work_queue + ) + continue + + gps_update = False + + # Забираем последнее необработанное GPS-поколение. + with self._gps_fix_condition: + if ( + self._gps_fix_generation + > self._gps_fix_consumed_generation + ): + self._gps_fix_consumed_generation = ( + self._gps_fix_generation + ) + gps_update = True + + # GPS FIX добавляет новые задания. + # Потеря GPS не очищает существующую очередь. + if gps_update: + fix = self._get_gps_fix() + + if fix is not None: + candidates = self._get_candidates( + connection, + fix + ) + + with self.lock: + self.access_points_total = len(candidates) + + self._update_monitor_candidates(candidates) + self._add_monitor_event( + "CANDIDATES_REFRESHED", + f"Обновлён список кандидатов: {len(candidates)}" + ) + + for access_point in candidates: + bssid = access_point["bssid"] + bssid_key = bssid.lower() + + if bssid_key in self._missing_scan_bssids: + continue + + state = self._bssid_states.setdefault( + bssid_key, + { + "status": "NEW", + "processed_credentials": set() + } + ) + + if state["status"] == "VERIFIED": + continue + + processed_ids = state[ + "processed_credentials" + ] + + queued_ids = { + job[3]["credential_id"] + for job in work_queue + if job[1].lower() == bssid_key + } + + for credential in access_point["credentials"]: + credential_id = credential["credential_id"] + + if credential_id in processed_ids: + continue + + if credential_id in queued_ids: + continue + + work_queue.append( + ( + access_point["access_point_id"], + bssid, + access_point["essid"], + credential, + 0 + ) + ) + + queued_ids.add(credential_id) + + self._update_monitor_queue(work_queue) + + if self.stop_event.is_set(): + break + + # Пустая очередь — ожидаем новый GPS FIX. + if not work_queue: + self._set_state("WAITING_GPS") + + with self._gps_fix_condition: + while ( + not self.stop_event.is_set() + and not self._radius_update_event.is_set() + and self._gps_fix_generation + <= self._gps_fix_consumed_generation + ): + self._gps_fix_condition.wait() + + continue + + self._set_state("RUNNING") + + # Одна свежая общая радиосканировка на одну попытку. + scan_results = self.wifi_connection_service.get_access_points( + self.interface + ) + + visible_access_points = { + access_point.bssid.lower(): access_point + for access_point in scan_results + } + + self._update_monitor_signal(scan_results) + + gps_update_pending = False + + with self._gps_fix_condition: + gps_update_pending = ( + self._gps_fix_generation + > self._gps_fix_consumed_generation + ) + + if gps_update_pending and not gps_refresh_deferred: + gps_refresh_deferred = True + continue + + # Удаляем задания и состояние только для отсутствующих BSSID. + missing_bssids = [ + bssid_key + for bssid_key in self._bssid_states + if bssid_key not in visible_access_points + ] + + for bssid_key in missing_bssids: + del self._bssid_states[bssid_key] + + self._missing_scan_bssids.update(missing_bssids) + self._missing_scan_bssids.difference_update( + visible_access_points + ) + + if missing_bssids: + work_queue = [ + job for job in work_queue + if job[1].lower() not in missing_bssids + ] + + self._add_monitor_event( + "AP_MISSING_FROM_SCAN", + ( + "Точки отсутствуют в радиосканировании, " + f"задания удалены: {len(missing_bssids)}" + ), + "warning" + ) + + self._update_monitor_queue(work_queue) + + if self.stop_event.is_set(): + break + + if not work_queue: + self._update_session_counters(connection) + continue + + + # Радиус имеет приоритет перед следующим заданием. + radius_update_pending = False + + with self._radius_update_lock: + if self._pending_radius_update is not None: + radius_update_pending = True + else: + job = work_queue.pop(0) + gps_refresh_deferred = False + + if radius_update_pending: + self._apply_pending_radius_update( + connection, + work_queue + ) + continue + + + self._update_monitor_queue(work_queue) + self._set_monitor_active(job) + self._add_monitor_event( + "ATTEMPT_STARTED", + "Начата проверка точки доступа" + ) + + access_point_id, bssid, essid, credential, retry_count = job + + bssid_key = bssid.lower() + credential_id = credential["credential_id"] + + state = self._bssid_states.get(bssid_key) + scan_result = visible_access_points.get(bssid_key) + + if state is None or scan_result is None: + self._set_monitor_active() + self._update_session_counters(connection) + continue + + if state["status"] == "VERIFIED": + self._set_monitor_active() + continue + + state["status"] = "CHECKING" + + if self.stop_event.is_set(): + break + + # При ошибке _process_retry добавляет исходное задание + # в конец этой же очереди. + result = self._process_retry( + connection, + job, + work_queue, + scan_result=scan_result + ) or {} + + state = self._bssid_states.get(bssid_key) + + if state is not None: + state["processed_credentials"].add(credential_id) + + if result.get("verified"): + state = self._bssid_states.get(bssid_key) + + if state is not None: + state["status"] = "VERIFIED" + + # Успех прекращает проверку остальных паролей AP. + work_queue = [ + queued_job for queued_job in work_queue + if queued_job[1].lower() != bssid_key + ] + + elif result.get("interrupted"): + break + + else: + # Пересоздаём задание со следующим номером попытки. + retry_scheduled = ( + bool(work_queue) + and work_queue[-1] == job + ) + + if retry_scheduled: + work_queue.pop() + + if retry_count < self.queue_retry_passes: + work_queue.append( + ( + access_point_id, + bssid, + essid, + credential, + retry_count + 1 + ) + ) + + state = self._bssid_states.get(bssid_key) + + if state is not None: + has_jobs = any( + queued_job[1].lower() == bssid_key + for queued_job in work_queue + ) + + state["status"] = ( + "QUEUED" if has_jobs else "COMPLETED" + ) + + self._set_monitor_active() + self._update_monitor_queue(work_queue) + + if self.stop_event.is_set(): + break + + self._update_session_counters(connection) + + final_status = "STOPPED" + + + except (NetworkRestoreError, NetworkCleanupError) as error: + final_status = "ERROR" + self._set_state( + "ERROR", + str(error) + ) + logger.exception( + "Critical Wi-Fi restoration or cleanup error." + ) + + except Exception as error: + final_status = "ERROR" + self._set_state( + "ERROR", + str(error) + ) + logger.exception( + "Auto Wi-Fi verification failed." + ) + + finally: + if self.manage_gps_service: + try: + self.gps_service.stop() + except Exception: + logger.exception( + "Failed to stop Auto GPS service." + ) + + cleanup_success = False + + try: + self.wifi_connection_service.cleanup_auto_profiles( + self.interface, + None, + [] + ) + cleanup_success = True + + except Exception as error: + final_status = "ERROR" + self._set_state( + "ERROR", + str(error) + ) + logger.exception( + "Failed to clean up Auto verification profiles." + ) + + if cleanup_success: + try: + self._release_network_owner() + + except Exception as error: + final_status = "ERROR" + self._set_state( + "ERROR", + str(error) + ) + logger.exception( + "Failed to release AUTO_WIFI_VERIFY network owner." + ) + + if connection is not None: + try: + self._update_session( + connection, + final_status + ) + except Exception: + logger.exception( + "Failed to finalize verification session." + ) + finally: + close_database(connection) + + self._set_monitor_active() + self._update_monitor_queue([]) + self._add_monitor_event( + "SERVICE_STOPPED", + ( + "Сервис завершил работу с ошибкой" + if final_status == "ERROR" + else "Сервис автоматической проверки остановлен" + ), + "error" if final_status == "ERROR" else "info" + ) + + with self.lock: + self.running = False + + if self.state != "ERROR": + self.state = "STOPPED" + + self.current_bssid = None + self.current_essid = None + self._bssid_states.clear() + self._missing_scan_bssids.clear() + + self._notify() diff --git a/src/database.py b/src/database.py index ecb5993..8a4ea88 100644 --- a/src/database.py +++ b/src/database.py @@ -7,6 +7,202 @@ from pathlib import Path from datetime import datetime, timezone +def _migrate_wifi_verification(conn): + + conn.execute(""" + CREATE TABLE IF NOT EXISTS wifi_verification_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + + radius_options TEXT NOT NULL + DEFAULT '[25,50,100,200,300]', + + radius_m INTEGER NOT NULL DEFAULT 100 + CHECK (radius_m > 0), + + gnss_max_age_seconds INTEGER NOT NULL DEFAULT 5 + CHECK (gnss_max_age_seconds > 0), + + queue_retry_passes INTEGER NOT NULL DEFAULT 1 + CHECK (queue_retry_passes >= 0), + + updated_at TEXT NOT NULL + DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) + ) + """) + + conn.execute(""" + INSERT OR IGNORE INTO wifi_verification_settings ( + id + ) + VALUES (1) + """) + + columns = { + row[1] + for row in conn.execute( + "PRAGMA table_info(wifi_verification_settings)" + ) + } + + if "retry_interval_seconds" in columns: + conn.execute(""" + ALTER TABLE wifi_verification_settings + DROP COLUMN retry_interval_seconds + """) + + if "gps_source" not in columns: + + conn.execute(""" + ALTER TABLE wifi_verification_settings + ADD COLUMN gps_source TEXT + CHECK (gps_source IN ('gpsd', 'gpsrelay')) + """) + + columns = { + row[1] + for row in conn.execute( + "PRAGMA table_info(wifi_verification_settings)" + ) + } + + if "gpsrelay_host" not in columns: + + conn.execute(""" + ALTER TABLE wifi_verification_settings + ADD COLUMN gpsrelay_host TEXT + CHECK ( + gpsrelay_host IS NULL + OR length(trim(gpsrelay_host)) > 0 + ) + """) + + if "gpsrelay_port" not in columns: + + conn.execute(""" + ALTER TABLE wifi_verification_settings + ADD COLUMN gpsrelay_port INTEGER + CHECK ( + gpsrelay_port IS NULL + OR gpsrelay_port BETWEEN 1 AND 65535 + ) + """) + + conn.execute(""" + CREATE TABLE IF NOT EXISTS wifi_verification_sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + + started_at TEXT NOT NULL, + + finished_at TEXT, + + status TEXT NOT NULL + CHECK ( + status IN ( + 'RUNNING', + 'PAUSED_GNSS', + 'PAUSED_QUEUE', + 'STOPPED', + 'ERROR' + ) + ), + + radius_m INTEGER NOT NULL, + + interface_name TEXT NOT NULL, + + access_points_total INTEGER NOT NULL DEFAULT 0, + + attempts_total INTEGER NOT NULL DEFAULT 0, + + success_count INTEGER NOT NULL DEFAULT 0, + + invalid_password_count INTEGER NOT NULL DEFAULT 0, + + technical_error_count INTEGER NOT NULL DEFAULT 0 + ) + """) + + conn.execute(""" + CREATE TABLE IF NOT EXISTS wifi_verification_attempts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + + credential_id INTEGER, + + session_id INTEGER, + + verification_mode TEXT NOT NULL + CHECK ( + verification_mode IN ('MANUAL', 'AUTO') + ), + + status TEXT NOT NULL + CHECK ( + status IN ( + 'SUCCESS', + 'INVALID_PASSWORD', + 'AP_NOT_FOUND', + 'CONNECTION_TIMEOUT', + 'NETWORK_ERROR', + 'UNKNOWN_ERROR', + 'CANCELLED' + ) + ), + + started_at TEXT NOT NULL, + + finished_at TEXT, + + interface_name TEXT, + + bssid TEXT, + + error_code TEXT, + + error_message TEXT, + + FOREIGN KEY (credential_id) + REFERENCES credentials(id) + ON DELETE SET NULL, + + FOREIGN KEY (session_id) + REFERENCES wifi_verification_sessions(id) + ON DELETE SET NULL + ) + """) + + conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_wifi_verification_sessions_started + ON wifi_verification_sessions(started_at) + """) + + conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_wifi_verification_attempts_session + ON wifi_verification_attempts(session_id, started_at) + """) + + conn.execute(""" + CREATE INDEX IF NOT EXISTS + idx_wifi_verification_attempts_credential + ON wifi_verification_attempts(credential_id, started_at) + """) + + + +def migrate_wifi_verification_database(db_path): + """Запускает только миграцию схемы Auto Verification.""" + conn = sqlite3.connect(db_path) + try: + _migrate_wifi_verification(conn) + conn.commit() + except Exception: + conn.rollback() + raise + finally: + conn.close() + + class Database: @@ -382,8 +578,15 @@ class Database: self._migrate_session_hash() + self._migrate_wifi_verification() + self.conn.commit() + def _migrate_wifi_verification(self): + + _migrate_wifi_verification(self.conn) + + def _migrate_credentials_table( self ): @@ -984,6 +1187,154 @@ class Database: return True + # ========================================================= + # Wi-Fi verification settings + # ========================================================= + + def get_wifi_verification_settings(self): + + row = self.conn.execute( + """ + SELECT * + FROM wifi_verification_settings + WHERE id=1 + """ + ).fetchone() + + if row is None: + return None + + return dict(row) + + def update_wifi_verification_settings( + self, + settings + ): + + if not isinstance(settings, dict): + raise ValueError("Настройки должны быть словарём.") + + allowed = ( + "gps_source", + "gpsrelay_host", + "gpsrelay_port", + "radius_options", + "radius_m", + "gnss_max_age_seconds", + "queue_retry_passes" + ) + + unknown = set(settings) - set(allowed) + + if unknown: + raise ValueError( + "Неизвестные настройки: " + + ", ".join(sorted(unknown)) + ) + + if not settings: + raise ValueError("Не переданы настройки для обновления.") + + values = dict(settings) + + if "gps_source" in values: + if values["gps_source"] not in (None, "gpsd", "gpsrelay"): + raise ValueError("Недопустимый источник GPS.") + + if "gpsrelay_host" in values: + host = values["gpsrelay_host"] + + if host is not None: + if not isinstance(host, str) or not host.strip(): + raise ValueError("Некорректный адрес GPS Relay.") + + values["gpsrelay_host"] = host.strip() + + if "gpsrelay_port" in values: + port = values["gpsrelay_port"] + + if port is not None: + if ( + isinstance(port, bool) + or not isinstance(port, int) + or not 1 <= port <= 65535 + ): + raise ValueError("Порт GPS Relay должен быть от 1 до 65535.") + + integer_limits = { + "radius_m": 1, + "gnss_max_age_seconds": 1, + "queue_retry_passes": 0 + } + + for name, minimum in integer_limits.items(): + if name not in values: + continue + + value = values[name] + + if ( + isinstance(value, bool) + or not isinstance(value, int) + or value < minimum + ): + raise ValueError( + f"Некорректное значение настройки {name}." + ) + + if "radius_options" in values: + options = values["radius_options"] + + if isinstance(options, str): + try: + options = json.loads(options) + except (TypeError, ValueError): + raise ValueError("radius_options должен содержать JSON-массив.") + + if ( + not isinstance(options, (list, tuple)) + or not options + or any( + isinstance(value, bool) + or not isinstance(value, int) + or value <= 0 + for value in options + ) + or len(set(options)) != len(options) + ): + raise ValueError("Некорректный список radius_options.") + + values["radius_options"] = json.dumps( + list(options), + separators=(",", ":") + ) + + assignments = [ + f"{name}=?" + for name in allowed + if name in values + ] + + parameters = [ + values[name] + for name in allowed + if name in values + ] + + self.conn.execute( + f""" + UPDATE wifi_verification_settings + SET + {", ".join(assignments)}, + updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now') + WHERE id=1 + """, + parameters + ) + + return self.get_wifi_verification_settings() + + # ========================================================= # Access points # ========================================================= diff --git a/src/lifecycle_manager.py b/src/lifecycle_manager.py index 3d45aab..13b128b 100644 --- a/src/lifecycle_manager.py +++ b/src/lifecycle_manager.py @@ -289,6 +289,63 @@ def wait_for_scanner(app_module): log("Сканер и поток чтения его вывода завершены.") +def stop_auto_gps(app_module): + with app_module.auto_gps_lock: + service = app_module.auto_gps_service + + if service is None: + return + + thread = service.thread + + if thread is None or not thread.is_alive(): + return + + log("Останавливается Auto GPS.") + + service.stop() + + if thread is not threading.current_thread(): + thread.join(timeout=5) + + if thread.is_alive(): + log( + "Предупреждение: поток Auto GPS не завершился " + "за отведённое время." + ) + else: + log("Auto GPS завершён.") + + +def stop_auto_wifi_verification(app_module): + + with app_module.auto_wifi_verification_lock: + service = app_module.auto_wifi_verification_service + + if service is None: + return + + thread = service.thread + + if thread is None or not thread.is_alive(): + return + + log("Останавливается автоматическая проверка Wi-Fi.") + + service.stop() + + if thread is not threading.current_thread(): + thread.join(timeout=5) + + if thread.is_alive(): + log( + "Предупреждение: поток автоматической проверки Wi-Fi " + "не завершился за отведённое время." + ) + else: + log("Автоматическая проверка Wi-Fi завершена.") + + def stop_gps_test(app_module): with app_module.gps_test_lock: service = app_module.gps_test_service @@ -597,6 +654,8 @@ def run_server(): log("Ожидание завершения активных HTTP-запросов.") app_module.request_lifecycle.wait_for_drain() + stop_auto_wifi_verification(app_module) + stop_auto_gps(app_module) stop_gps_test(app_module) wait_for_scanner(app_module) join_background_threads(app_module) diff --git a/src/wifi_connection.py b/src/wifi_connection.py index ea0f2a3..a5c7809 100644 --- a/src/wifi_connection.py +++ b/src/wifi_connection.py @@ -27,20 +27,44 @@ class WiFiConnectionError(RuntimeError): pass -class NetworkCommandError(WiFiConnectionError): +class APNotFoundError(WiFiConnectionError): pass +class NetworkCommandError(WiFiConnectionError): + + def __init__( + self, + message, + returncode=None, + stdout="", + stderr="", + timed_out=False + ): + super().__init__(message) + + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + self.timed_out = timed_out + + class UnsupportedSecurityError(WiFiConnectionError): pass class NetworkRestoreError(WiFiConnectionError): pass + + class NetworkCleanupError(WiFiConnectionError): pass +class PasswordFileCleanupError(WiFiConnectionError): + pass + + @dataclass(frozen=True) class AccessPoint: bssid: str @@ -49,6 +73,7 @@ class AccessPoint: wpa_flags: int rsn_flags: int key_mgmt: str | None + strength: int | None = None @property def is_open(self): @@ -125,8 +150,20 @@ class WiFiConnectionService: except subprocess.TimeoutExpired as error: + stdout = error.stdout or error.output or "" + stderr = error.stderr or "" + + if isinstance(stdout, bytes): + stdout = stdout.decode(errors="replace") + + if isinstance(stderr, bytes): + stderr = stderr.decode(errors="replace") + raise NetworkCommandError( - "NetworkManager command timed out." + "NetworkManager command timed out.", + stdout=stdout, + stderr=stderr, + timed_out=True ) from error except OSError as error: @@ -145,7 +182,12 @@ class WiFiConnectionService: f"Command exited with code {result.returncode}." ) - raise NetworkCommandError(message) + raise NetworkCommandError( + message, + returncode=result.returncode, + stdout=result.stdout, + stderr=result.stderr + ) return result.stdout.strip() @@ -320,6 +362,39 @@ class WiFiConnectionService: f"Invalid value for {property_name}." ) from error + def _get_byte_property( + self, + object_path, + property_name + ): + + parts = self._get_property( + object_path, + NM_ACCESS_POINT, + property_name + ) + + if len(parts) != 2 or parts[0] != "y": + raise WiFiConnectionError( + f"Unexpected D-Bus type for {property_name}." + ) + + try: + value = int(parts[1]) + + except ValueError as error: + + raise WiFiConnectionError( + f"Invalid value for {property_name}." + ) from error + + if not 0 <= value <= 100: + raise WiFiConnectionError( + f"Value for {property_name} is outside the valid range." + ) + + return value + def _get_ssid(self, object_path): parts = self._get_property( @@ -406,20 +481,16 @@ class WiFiConnectionService: "This access point does not advertise WPA Personal PSK or SAE security." ) - def get_access_point( + + def get_access_points( self, - interface, - bssid + interface ): self._validate_interface( interface ) - self._validate_bssid( - bssid - ) - device_path = self._device_path( interface ) @@ -460,6 +531,8 @@ class WiFiConnectionService: "Cannot parse NetworkManager access point list." ) from error + access_points = [] + for object_path in paths: ap_bssid_parts = self._get_property( @@ -477,7 +550,12 @@ class WiFiConnectionService: ap_bssid = ap_bssid_parts[1] - if ap_bssid.lower() != bssid.lower(): + try: + self._validate_bssid( + ap_bssid + ) + + except WiFiConnectionError: continue flags = self._get_integer_property( @@ -499,25 +577,60 @@ class WiFiConnectionService: object_path ) - key_mgmt = self._select_key_mgmt( - flags, - wpa_flags, - rsn_flags + try: + + key_mgmt = self._select_key_mgmt( + flags, + wpa_flags, + rsn_flags + ) + + except UnsupportedSecurityError: + key_mgmt = None + + try: + strength = self._get_byte_property( + object_path, + "Strength" + ) + + except WiFiConnectionError: + strength = None + + access_points.append( + AccessPoint( + bssid=ap_bssid.upper(), + ssid=ssid, + flags=flags, + wpa_flags=wpa_flags, + rsn_flags=rsn_flags, + key_mgmt=key_mgmt, + strength=strength + ) ) - return AccessPoint( - bssid=ap_bssid.upper(), - ssid=ssid, - flags=flags, - wpa_flags=wpa_flags, - rsn_flags=rsn_flags, - key_mgmt=key_mgmt - ) + return access_points - raise WiFiConnectionError( + def get_access_point( + self, + interface, + bssid + ): + + self._validate_bssid( + bssid + ) + + for access_point in self.get_access_points(interface): + + if access_point.bssid.lower() == bssid.lower(): + return access_point + + raise APNotFoundError( f"Access point {bssid} is not currently visible to NetworkManager." ) + def _get_active_connection_uuid(self, interface): output = self._nmcli( @@ -533,6 +646,292 @@ class WiFiConnectionService: return output + def _list_connection_profiles(self): + + output = self._nmcli( + "--terse", + "--escape", + "yes", + "--fields", + "NAME,UUID", + "connection", + "show" + ) + + profiles = [] + + for line in output.splitlines(): + + if not line: + continue + + try: + + name, profile_uuid = line.rsplit(":", 1) + + except ValueError as error: + + raise NetworkCleanupError( + "NetworkManager returned an invalid connection " + "profile entry." + ) from error + + if not name or not profile_uuid: + + raise NetworkCleanupError( + "NetworkManager returned an incomplete connection " + "profile entry." + ) + + profiles.append( + (name, profile_uuid) + ) + + return profiles + + + def _list_connection_profile_uuids(self): + + return { + profile_uuid + for _, profile_uuid in self._list_connection_profiles() + } + + + def capture_active_connection(self, interface): + + self._validate_interface( + interface + ) + + connection_uuid = self._get_active_connection_uuid( + interface + ) + + if not connection_uuid: + return None + + bssid = self._get_active_access_point_bssid( + interface + ) + + return { + "uuid": connection_uuid, + "bssid": bssid + } + + def restore_active_connection(self, interface, saved_connection): + + self._validate_interface( + interface + ) + + if saved_connection is None: + return False + + if not isinstance(saved_connection, dict): + raise WiFiConnectionError( + "Invalid saved Wi-Fi connection." + ) + + connection_uuid = saved_connection.get("uuid") + bssid = saved_connection.get("bssid") + + if not connection_uuid or not isinstance(connection_uuid, str): + raise WiFiConnectionError( + "Saved Wi-Fi connection UUID is missing." + ) + + self._validate_bssid( + bssid + ) + + try: + + self._nmcli( + "connection", + "up", + "uuid", + connection_uuid, + "ifname", + interface, + "ap", + bssid, + timeout=90 + ) + + except NetworkCommandError as error: + + raise NetworkRestoreError( + "The previous Wi-Fi connection could not be restored: " + f"{error}" + ) from error + + return True + + def cleanup_auto_profiles( + self, + interface, + saved_connection, + profile_uuids + ): + + self._validate_interface( + interface + ) + + if not isinstance(profile_uuids, (list, tuple)): + raise WiFiConnectionError( + "Invalid Auto verification profile list." + ) + + for profile_uuid in profile_uuids: + + if ( + not isinstance(profile_uuid, str) + or + not re.fullmatch( + r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-" + r"[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-" + r"[0-9a-fA-F]{12}", + profile_uuid + ) + ): + raise WiFiConnectionError( + "Invalid temporary NetworkManager profile UUID." + ) + + try: + + profiles = self._list_connection_profiles() + + except NetworkCommandError as error: + + raise NetworkCleanupError( + "NetworkManager could not inspect connection profiles: " + f"{error}" + ) from error + + auto_profiles = [ + (name, profile_uuid) + for name, profile_uuid in profiles + if name.startswith("wifi-gps-mapper-") + ] + + auto_profile_uuids = { + profile_uuid + for _, profile_uuid in auto_profiles + } + + try: + + for _ in range(len(auto_profile_uuids) + 1): + + active_uuid = self._get_active_connection_uuid( + interface + ) + + if active_uuid not in auto_profile_uuids: + break + + try: + + self._nmcli( + "connection", + "down", + "uuid", + active_uuid + ) + + except NetworkCommandError: + pass + + active_uuid_after = self._get_active_connection_uuid( + interface + ) + + if active_uuid_after == active_uuid: + + raise NetworkCleanupError( + "The active Auto verification connection " + "could not be disconnected: " + f"{active_uuid}" + ) + + if active_uuid_after not in auto_profile_uuids: + break + + else: + + raise NetworkCleanupError( + "An Auto verification connection remains active " + "on the Wi-Fi interface." + ) + + except NetworkCommandError as error: + + raise NetworkCleanupError( + "The active Wi-Fi connection state could not be verified: " + f"{error}" + ) from error + + cleanup_errors = [] + + for _, profile_uuid in auto_profiles: + + try: + + self._delete_profile( + profile_uuid + ) + + except NetworkCleanupError as error: + + cleanup_errors.append( + f"{profile_uuid}: {error}" + ) + + try: + + remaining_profiles = self._list_connection_profiles() + + except NetworkCommandError as error: + + raise NetworkCleanupError( + "The final Auto verification profile cleanup " + "could not be verified: " + f"{error}" + ) from error + + remaining_auto_profiles = [ + (name, profile_uuid) + for name, profile_uuid in remaining_profiles + if name.startswith("wifi-gps-mapper-") + ] + + if remaining_auto_profiles: + + remaining_uuids = [ + profile_uuid + for _, profile_uuid in remaining_auto_profiles + ] + + details = "; ".join(cleanup_errors) + + raise NetworkCleanupError( + "Auto verification profiles remain in NetworkManager: " + + ", ".join(remaining_uuids) + + (f". Cleanup errors: {details}" if details else "") + ) + + return { + "restored": False, + "deleted_profile_uuids": [ + profile_uuid + for _, profile_uuid in auto_profiles + ] + } + def _get_active_access_point_bssid(self, interface): device_path = self._device_path( @@ -628,6 +1027,33 @@ class WiFiConnectionService: f"{cleanup_error}" ) from creation_error + try: + + remaining_profiles = self._nmcli( + "--terse", + "--escape", + "yes", + "--fields", + "NAME", + "connection", + "show" + ) + + except NetworkCommandError as inspection_error: + + raise NetworkCleanupError( + "NetworkManager deleted the temporary profile command " + "but its absence could not be verified: " + f"{inspection_error}" + ) from creation_error + + if profile_name in remaining_profiles.splitlines(): + + raise NetworkCleanupError( + "NetworkManager still reports the temporary profile " + f"after deletion: {profile_name}" + ) from creation_error + raise creation_error def _create_temporary_profile( @@ -716,12 +1142,39 @@ class WiFiConnectionService: except NetworkCommandError as cleanup_error: - raise WiFiConnectionError( + raise NetworkCleanupError( "NetworkManager created a temporary profile, but its UUID " "could not be obtained and the profile could not be deleted: " f"{cleanup_error}" ) from error + try: + + remaining_profiles = self._nmcli( + "--terse", + "--escape", + "yes", + "--fields", + "NAME", + "connection", + "show" + ) + + except NetworkCommandError as inspection_error: + + raise NetworkCleanupError( + "NetworkManager deleted the temporary profile command " + "but its absence could not be verified: " + f"{inspection_error}" + ) from error + + if profile_name in remaining_profiles.splitlines(): + + raise NetworkCleanupError( + "NetworkManager still reports the temporary profile " + f"after deletion: {profile_name}" + ) from error + raise return output @@ -785,7 +1238,7 @@ class WiFiConnectionService: except OSError as cleanup_error: - raise NetworkCleanupError( + raise PasswordFileCleanupError( "Could not prepare the temporary password file. " "The file could not be deleted: " f"{cleanup_error}" @@ -866,14 +1319,14 @@ class WiFiConnectionService: if operation_error: - raise NetworkCleanupError( + raise PasswordFileCleanupError( "Wi-Fi activation failed: " f"{operation_error}. " "The temporary password file could not be deleted: " f"{cleanup_error}" ) from operation_error - raise NetworkCleanupError( + raise PasswordFileCleanupError( "The temporary password file could not be deleted: " f"{cleanup_error}" ) from cleanup_error @@ -886,11 +1339,59 @@ class WiFiConnectionService: if not profile_uuid: return - self._nmcli( - "connection", - "delete", - "uuid", - profile_uuid + try: + + existing_uuids = self._list_connection_profile_uuids() + + except NetworkCommandError as error: + + raise NetworkCleanupError( + "NetworkManager could not inspect connection profiles: " + f"{error}" + ) from error + + if profile_uuid not in existing_uuids: + return + + delete_error = None + + try: + + self._nmcli( + "connection", + "delete", + "uuid", + profile_uuid + ) + + except NetworkCommandError as error: + + delete_error = error + + try: + + remaining_uuids = self._list_connection_profile_uuids() + + except NetworkCommandError as error: + + raise NetworkCleanupError( + "The temporary profile deletion could not be verified: " + f"{error}" + ) from error + + if profile_uuid not in remaining_uuids: + return + + if delete_error: + + raise NetworkCleanupError( + "NetworkManager could not delete the temporary profile: " + f"{delete_error}" + ) from delete_error + + raise NetworkCleanupError( + "NetworkManager still reports the temporary profile " + f"after deletion: {profile_uuid}" ) def connect( @@ -936,7 +1437,7 @@ class WiFiConnectionService: profile_uuid ) - except NetworkCommandError as cleanup_error: + except NetworkCleanupError as cleanup_error: raise NetworkCleanupError( "Wi-Fi connection failed: " @@ -959,13 +1460,51 @@ class WiFiConnectionService: self, interface, bssid, - password + password, + restore_connection=True, + keep_profile=False, + access_point=None ): - access_point = self.get_access_point( - interface, - bssid - ) + if ( + not restore_connection + and not keep_profile + ): + raise WiFiConnectionError( + "A verification without connection restoration " + "must retain a successful temporary profile." + ) + + if ( + restore_connection + and keep_profile + ): + raise WiFiConnectionError( + "A temporary profile cannot be retained " + "when restoring the previous connection." + ) + + if access_point is None: + + access_point = self.get_access_point( + interface, + bssid + ) + + else: + + self._validate_interface(interface) + self._validate_bssid(bssid) + + if not isinstance(access_point, AccessPoint): + raise WiFiConnectionError( + "Invalid access point object." + ) + + if access_point.bssid.lower() != bssid.lower(): + raise WiFiConnectionError( + "The supplied access point does not match the requested BSSID." + ) if access_point.is_open: raise WiFiConnectionError( @@ -977,18 +1516,21 @@ class WiFiConnectionService: "Password verification is not supported for this security type." ) - previous_uuid = self._get_active_connection_uuid( - interface - ) - + previous_uuid = None previous_bssid = None - if previous_uuid: + if restore_connection: - previous_bssid = self._get_active_access_point_bssid( + previous_uuid = self._get_active_connection_uuid( interface ) + if previous_uuid: + + previous_bssid = self._get_active_access_point_bssid( + interface + ) + profile_uuid = None success = False operation_error = None @@ -1019,29 +1561,48 @@ class WiFiConnectionService: error ) + if isinstance(error, NetworkCommandError): + + try: + + self.get_access_point( + interface, + bssid + ) + + except APNotFoundError as scan_error: + + operation_error = scan_error + error_message = str( + scan_error + ) + + except Exception: + pass + finally: if profile_uuid: - try: + if restore_connection: - if previous_uuid: + try: - self._nmcli( - "connection", - "up", - "uuid", - previous_uuid, - "ifname", - interface, - "ap", - previous_bssid, - timeout=90 - ) + if previous_uuid: - else: + self._nmcli( + "connection", + "up", + "uuid", + previous_uuid, + "ifname", + interface, + "ap", + previous_bssid, + timeout=90 + ) - try: + else: self._nmcli( "connection", @@ -1050,29 +1611,28 @@ class WiFiConnectionService: profile_uuid ) - except NetworkCommandError as error: + except NetworkCommandError as error: - restore_error = str( - error - ) + restore_error = str( + error + ) - except NetworkCommandError as error: + if not ( + success + and keep_profile + ): - restore_error = str( - error - ) + try: - try: + self._delete_profile( + profile_uuid + ) - self._delete_profile( - profile_uuid - ) + except NetworkCleanupError as error: - except NetworkCommandError as error: - - cleanup_error = str( - error - ) + cleanup_error = str( + error + ) verification_error = ( f"Password verification failed: {operation_error}. " @@ -1114,5 +1674,34 @@ class WiFiConnectionService: "interface": interface, "bssid": access_point.bssid, "ssid": access_point.ssid, - "error": error_message + "error": error_message, + "error_type": ( + type(operation_error).__name__ + if operation_error else None + ), + "error_code": getattr( + operation_error, + "returncode", + None + ), + "error_timed_out": getattr( + operation_error, + "timed_out", + None + ), + "error_stdout": getattr( + operation_error, + "stdout", + None + ), + "error_stderr": getattr( + operation_error, + "stderr", + None + ), + "profile_uuid": ( + profile_uuid + if success and keep_profile + else None + ) } \ No newline at end of file