diff --git a/INSTALLATION.md b/INSTALLATION.md index a31a6e9..e6f3c2d 100644 --- a/INSTALLATION.md +++ b/INSTALLATION.md @@ -60,7 +60,7 @@ wifi-gps-mapper-releases-build/ Перед установкой необходимо: 1. Подготовить компьютер под управлением Debian/Linux. -2. Скопировать на него релизную сборку WiFi GPS Mapper. +2. Клонировать на него релизную сборку WiFi GPS Mapper. 3. Убедиться, что пользователь имеет права на запись в каталог проекта. 4. Обеспечить подключение к интернету для загрузки недостающих зависимостей и данных. 5. Убедиться в наличии Python 3 и возможности создания виртуального окружения. @@ -78,7 +78,7 @@ wifi-gps-mapper-releases-build/ Перейдите в каталог релизной сборки: ```bash -cd ~/Projects/wifi-gps-mapper-releases-build +cd ~/Projects/wifi-gps-mapper-releases ``` Запустите установщик: diff --git a/gui/app.py b/gui/app.py index f1b9757..26983da 100644 --- a/gui/app.py +++ b/gui/app.py @@ -78,10 +78,15 @@ from reports.vendors import render_vendors_page from vendor_service import VendorService from sudo import SudoChecker from config import Config +from database import Database +from parser import CaptureParser +from session import Session +from reports.recovery import CAPTURES_DIR, _has_recoverable_capture from gps_test import GPSTestService from auto_gps import AutoGPSService from auto_wifi_verification import AutoWiFiVerificationService from wifi_connection import WiFiConnectionError, WiFiConnectionService +from gpsrelay_discovery import GPSRelayDiscoveryError, discover_gpsrelay from gui.timezones import get_timezone_options from logging_config import ( LOG_DATE_FORMAT, @@ -273,6 +278,8 @@ def scanner_navigation_guard(): "api_wifi_verification_stop", "api_wifi_verification_settings", "api_wifi_verification_settings_save", + "api_wifi_verification_gpsrelay_discovery_start", + "api_wifi_verification_gpsrelay_discovery_status", "api_wifi_verification_radius_apply", "static", } @@ -309,6 +316,8 @@ def scanner_navigation_guard(): "scanner_stop", "api_gps_test", "gps_test_stop", + "api_wifi_verification_gpsrelay_discovery_start", + "api_wifi_verification_gpsrelay_discovery_status", "static" } @@ -368,6 +377,10 @@ auto_wifi_verification_service = None auto_wifi_verification_lock = threading.Lock() +gpsrelay_discovery_job = None +gpsrelay_discovery_thread = None +gpsrelay_discovery_lock = threading.Lock() + # Shared GPS service for the Auto Verification map and Auto Verification worker. wifi_verification_shared_gps_service = None wifi_verification_shared_gps_lock = threading.RLock() @@ -642,35 +655,14 @@ def _stop_wifi_verification_shared_gps_locked(): def acquire_wifi_verification_network_owner(owner, gps_service): + if owner == "MANUAL_WIFI_VERIFY": + with scanner_lock: + return _acquire_network_owner_locked(owner) + if owner != "AUTO_WIFI_VERIFY": return acquire_network_owner(owner) with wifi_verification_shared_gps_lock: - - if wifi_verification_map_monitor_enabled: - - thread = gps_service.thread - - if thread is None or not thread.is_alive(): - return False, ( - "Map GPS monitor is enabled, " - "but its GPS service is not running." - ) - - with scanner_lock: - transferred = _transfer_network_owner_locked( - "MAP_GPS_MONITOR", - "AUTO_WIFI_VERIFY" - ) - - if not transferred: - return False, ( - "Unable to transfer network ownership " - "from the map GPS monitor." - ) - - return True, None - with scanner_lock: acquired, error = _acquire_network_owner_locked(owner) @@ -678,6 +670,11 @@ def acquire_wifi_verification_network_owner(owner, gps_service): return False, error try: + if gps_service is None: + raise RuntimeError( + "Shared GPS service is not configured." + ) + thread = gps_service.thread if thread is not None and thread.is_alive(): @@ -710,30 +707,19 @@ def acquire_wifi_verification_network_owner(owner, gps_service): def release_wifi_verification_network_owner(owner): + if owner == "MANUAL_WIFI_VERIFY": + with scanner_lock: + if network_operation_owner == owner: + _release_network_owner_locked(owner) + + return + if owner != "AUTO_WIFI_VERIFY": release_network_owner(owner) return with wifi_verification_shared_gps_lock: - - if wifi_verification_map_monitor_enabled: - - with scanner_lock: - transferred = _transfer_network_owner_locked( - "AUTO_WIFI_VERIFY", - "MAP_GPS_MONITOR" - ) - - if not transferred: - logger.warning( - "Could not return network ownership " - "to the map GPS monitor." - ) - - return - with scanner_lock: - current_owner = network_operation_owner if current_owner == owner: @@ -742,7 +728,8 @@ def release_wifi_verification_network_owner(owner): elif current_owner is not None: return - _stop_wifi_verification_shared_gps_locked() + if not wifi_verification_map_monitor_enabled: + _stop_wifi_verification_shared_gps_locked() def network_actions_busy(): @@ -2388,6 +2375,261 @@ def reports_trips(): ) +@app.route( + "/reports/recovery/", + methods=["POST"] +) +def reports_recovery_restore(directory_name): + + captures_root = Path( + CAPTURES_DIR + ).resolve() + + session_path = ( + captures_root / directory_name + ).resolve() + + if session_path.parent != captures_root: + abort(400) + + if not session_path.is_dir(): + abort(404) + + capture_file = ( + session_path / "capture.pcapng" + ) + + if not capture_file.is_file(): + return jsonify( + { + "error": "Capture file was not found." + } + ), 400 + + if capture_file.stat().st_size <= 0: + return jsonify( + { + "error": "Capture file is empty." + } + ), 400 + + if not _has_recoverable_capture(session_path): + return jsonify( + { + "error": ( + "Capture duration is shorter than " + "the required 5 minutes." + ) + } + ), 400 + + acquired, lock_error = acquire_network_owner( + "SESSION_RECOVERY" + ) + + if not acquired: + return jsonify( + { + "error": ( + lock_error + or "Network operation is currently busy." + ) + } + ), 409 + + db = None + + try: + + cfg = Config() + + db = Database( + cfg.database + ) + + existing_sessions = db.conn.execute( + """ + SELECT + id, + capture_file + FROM capture_sessions + """ + ).fetchall() + + for row in existing_sessions: + + stored_capture_file = row["capture_file"] + + if not stored_capture_file: + continue + + if Path( + stored_capture_file + ).resolve() == capture_file.resolve(): + + return jsonify( + { + "error": ( + "A database record already exists " + "for this capture." + ), + "session_id": row["id"], + } + ), 409 + + session = Session.from_existing( + session_path + ) + + session_id = db.create_session( + str(session.capture_file), + start_time=session.start_time + ) + + session.id = session_id + + parser = CaptureParser( + cfg, + db + ) + + parser.parse( + session, + session_id + ) + + db.flush_observations() + + event_times = [] + + timestamp_sources = ( + ("gps_track", "timestamp"), + ("access_point_observations", "observed_at"), + ("handshakes", "captured_at"), + ) + + for table, column in timestamp_sources: + + rows = db.conn.execute( + f""" + SELECT {column} + FROM {table} + WHERE session_id = ? + AND {column} IS NOT NULL + """, + (session_id,), + ).fetchall() + + for row in rows: + + try: + timestamp = datetime.fromisoformat( + str(row[0]).replace("Z", "+00:00") + ) + except ValueError: + continue + + if timestamp.tzinfo is None: + timestamp = timestamp.replace( + tzinfo=timezone.utc + ) + else: + timestamp = timestamp.astimezone( + timezone.utc + ) + + event_times.append(timestamp) + + if event_times: + + start_time = min(event_times) + + end_time = max(event_times) + + db.conn.execute( + """ + UPDATE capture_sessions + SET start_time = ?, + end_time = ? + WHERE id = ? + """, + ( + start_time.isoformat().replace("+00:00", "Z"), + end_time.isoformat().replace("+00:00", "Z"), + session_id, + ), + ) + + recovered = db.finalize_session( + session_id + ) + + db.commit() + + if not recovered: + + return jsonify( + { + "error": ( + "Parsing completed, but no GPS positions, " + "access points or handshakes were found. " + "The empty database record was removed." + ) + } + ), 422 + + logger.info( + "Interrupted capture recovered: %s (session_id=%s)", + session_path, + session_id, + ) + + return redirect( + url_for("reports_trips") + ) + + except Exception: + + if db is not None: + + try: + db.rollback() + + except Exception: + logger.exception( + "Failed to rollback session recovery." + ) + + finally: + db.observation_buffer.clear() + + logger.exception( + "Failed to recover interrupted capture: %s", + session_path, + ) + + return jsonify( + { + "error": "Failed to recover interrupted capture." + } + ), 500 + + finally: + + if db is not None: + + try: + db.close() + except Exception: + logger.exception( + "Failed to close database after session recovery." + ) + + release_network_owner( + "SESSION_RECOVERY" + ) + + @app.route("/reports/trips/preview") def reports_trips_preview(): @@ -3183,6 +3425,232 @@ def api_gps_test(): +def _run_gpsrelay_discovery(port): + global gpsrelay_discovery_job + + try: + result = discover_gpsrelay(port) + + with gpsrelay_discovery_lock: + gpsrelay_discovery_job = { + "state": "SUCCEEDED", + "running": False, + "port": port, + "result": result, + "error": None, + } + + except GPSRelayDiscoveryError as error: + + with gpsrelay_discovery_lock: + gpsrelay_discovery_job = { + "state": "FAILED", + "running": False, + "port": port, + "result": None, + "error": str(error), + } + + except Exception: + app.logger.exception( + "Unexpected GPSRelay discovery error" + ) + + with gpsrelay_discovery_lock: + gpsrelay_discovery_job = { + "state": "FAILED", + "running": False, + "port": port, + "result": None, + "error": "Unexpected GPSRelay discovery error.", + } + + finally: + try: + release_network_owner("GPSRELAY_DISCOVERY") + except Exception: + app.logger.exception( + "Could not release GPSRelay discovery network owner" + ) + + +@app.route( + "/api/wifi-verification/gpsrelay-discovery/start", + methods=["POST"] +) +def api_wifi_verification_gpsrelay_discovery_start(): + global gpsrelay_discovery_job + global gpsrelay_discovery_thread + + payload = request.get_json(silent=True) + + if payload is None: + payload = {} + + if not isinstance(payload, dict): + return jsonify( + { + "ok": False, + "error": "Invalid request body.", + } + ), 400 + + raw_port = payload.get("port", 5000) + + if raw_port is None or raw_port == "": + raw_port = 5000 + + if isinstance(raw_port, bool): + return jsonify( + { + "ok": False, + "error": "Port must be an integer between 1 and 65535.", + } + ), 400 + + if isinstance(raw_port, int): + port = raw_port + elif isinstance(raw_port, str) and raw_port.strip().isdigit(): + port = int(raw_port.strip()) + else: + return jsonify( + { + "ok": False, + "error": "Port must be an integer between 1 and 65535.", + } + ), 400 + + if not 1 <= port <= 65535: + return jsonify( + { + "ok": False, + "error": "Port must be between 1 and 65535.", + } + ), 400 + + start_error = False + + with auto_wifi_verification_lock: + + current = auto_wifi_verification_service + + if ( + current is not None + and current.thread is not None + and current.thread.is_alive() + ): + return jsonify( + { + "ok": False, + "error": "Auto Verification is running.", + } + ), 409 + + with gpsrelay_discovery_lock: + + if ( + gpsrelay_discovery_thread is not None + and gpsrelay_discovery_thread.is_alive() + ): + return jsonify( + { + "ok": False, + "error": "GPSRelay discovery is already running.", + } + ), 409 + + acquired, error = acquire_network_owner( + "GPSRELAY_DISCOVERY" + ) + + if not acquired: + return jsonify( + { + "ok": False, + "error": error or "Network interface is busy.", + } + ), 409 + + gpsrelay_discovery_job = { + "state": "RUNNING", + "running": True, + "port": port, + "result": None, + "error": None, + } + + gpsrelay_discovery_thread = threading.Thread( + target=_run_gpsrelay_discovery, + args=(port,), + daemon=True, + ) + + try: + gpsrelay_discovery_thread.start() + + except Exception: + app.logger.exception( + "Could not start GPSRelay discovery thread" + ) + + gpsrelay_discovery_thread = None + + gpsrelay_discovery_job = { + "state": "FAILED", + "running": False, + "port": port, + "result": None, + "error": "Could not start GPSRelay discovery.", + } + + start_error = True + + if start_error: + release_network_owner("GPSRELAY_DISCOVERY") + + return jsonify( + { + "ok": False, + "error": "Could not start GPSRelay discovery.", + } + ), 500 + + return jsonify( + { + "ok": True, + "state": "RUNNING", + "port": port, + } + ), 202 + + +@app.route( + "/api/wifi-verification/gpsrelay-discovery/status", + methods=["GET"] +) +def api_wifi_verification_gpsrelay_discovery_status(): + + with gpsrelay_discovery_lock: + + if gpsrelay_discovery_job is None: + job = { + "state": "IDLE", + "running": False, + "port": None, + "result": None, + "error": None, + } + else: + job = dict(gpsrelay_discovery_job) + + return jsonify( + { + "ok": True, + **job, + } + ) + + @app.route("/api/wifi-verification/settings", methods=["GET"]) def api_wifi_verification_settings(): conn = None @@ -3598,7 +4066,6 @@ def api_wifi_verification_map_gps_start(): service = wifi_verification_shared_gps_service if wifi_verification_map_monitor_enabled: - if ( service is not None and service.thread is not None @@ -3613,42 +4080,45 @@ def api_wifi_verification_map_gps_start(): wifi_verification_map_monitor_enabled = False if auto_running: + if auto_service.verification_mode == "MANUAL": + settings = auto_service.settings + else: + if ( + service is None + or service.thread is None + or not service.thread.is_alive() + ): + return jsonify({ + "ok": False, + "error": ( + "GPS service used by Auto Verification " + "is not running." + ) + }), 409 + + wifi_verification_map_monitor_enabled = True - if ( - service is None - or service.thread is None - or not service.thread.is_alive() - ): return jsonify({ - "ok": False, - "error": ( - "GPS service used by Auto Verification " - "is not running." - ) - }), 409 + "ok": True, + "monitor_enabled": True, + "gps": service.get_status() + }) - wifi_verification_map_monitor_enabled = True + else: + connection = connect_database() - return jsonify({ - "ok": True, - "monitor_enabled": True, - "gps": service.get_status() - }) + row = connection.execute( + """ + SELECT * + FROM wifi_verification_settings + WHERE id = 1 + """ + ).fetchone() - connection = connect_database() + settings = dict(row) if row is not None else None - row = connection.execute( - """ - SELECT * - FROM wifi_verification_settings - WHERE id = 1 - """ - ).fetchone() - - settings = dict(row) if row is not None else None - - close_database(connection) - connection = None + close_database(connection) + connection = None if settings is None: return jsonify({ @@ -3665,20 +4135,7 @@ def api_wifi_verification_map_gps_start(): ): return jsonify({ "ok": False, - "error": ( - "Select GPS source: gpsd or gpsrelay." - ) - }), 409 - - acquired, owner_error = acquire_network_owner( - "MAP_GPS_MONITOR" - ) - - if not acquired: - return jsonify({ - "ok": False, - "error": owner_error, - "owner": network_operation_owner + "error": "Select GPS source: gpsd or gpsrelay." }), 409 service = _get_wifi_verification_shared_gps( @@ -3699,22 +4156,16 @@ def api_wifi_verification_map_gps_start(): ) if not started: - cleanup_ok = True + thread = service.thread - if started_service: - cleanup_ok = ( + if thread is None or not thread.is_alive(): + if started_service: _stop_wifi_verification_shared_gps_locked() - ) - if cleanup_ok: - release_network_owner( - "MAP_GPS_MONITOR" - ) - - return jsonify({ - "ok": False, - "error": "GPS service could not be started." - }), 409 + return jsonify({ + "ok": False, + "error": "GPS service could not be started." + }), 409 wifi_verification_map_monitor_enabled = True @@ -3732,20 +4183,8 @@ def api_wifi_verification_map_gps_start(): with wifi_verification_shared_gps_lock: - cleanup_ok = True - if started_service and service is not None: - cleanup_ok = ( - _stop_wifi_verification_shared_gps_locked() - ) - - if ( - cleanup_ok - and network_operation_owner == "MAP_GPS_MONITOR" - ): - release_network_owner( - "MAP_GPS_MONITOR" - ) + _stop_wifi_verification_shared_gps_locked() return jsonify({ "ok": False, @@ -3769,12 +4208,9 @@ def api_wifi_verification_map_gps_stop(): with auto_wifi_verification_lock: with wifi_verification_shared_gps_lock: - wifi_verification_map_monitor_enabled = False - owner = network_operation_owner if owner == "AUTO_WIFI_VERIFY": - service = wifi_verification_shared_gps_service gps_status = ( @@ -3783,67 +4219,39 @@ def api_wifi_verification_map_gps_stop(): else None ) + wifi_verification_map_monitor_enabled = False + return jsonify({ "ok": True, "monitor_enabled": False, "stop_deferred": True, + "owner": owner, "gps": gps_status }) - if owner == "MAP_GPS_MONITOR": - - stopped = ( - _stop_wifi_verification_shared_gps_locked() - ) - - if not stopped: - return jsonify({ - "ok": False, - "error": ( - "GPS service did not stop. " - "Its state was preserved." - ), - "monitor_enabled": False - }), 409 - - release_network_owner( - "MAP_GPS_MONITOR" - ) - - elif owner is not None: + stopped = ( + _stop_wifi_verification_shared_gps_locked() + ) + if not stopped: return jsonify({ "ok": False, "error": ( - "GPS is owned by another operation." + "GPS service did not stop. " + "Its state was preserved." ), - "owner": owner, - "monitor_enabled": False + "monitor_enabled": ( + wifi_verification_map_monitor_enabled + ) }), 409 - else: - - service = wifi_verification_shared_gps_service - - if ( - service is not None - and service.thread is not None - and service.thread.is_alive() - ): - stopped = ( - _stop_wifi_verification_shared_gps_locked() - ) - - if not stopped: - return jsonify({ - "ok": False, - "error": "GPS service did not stop." - }), 409 + wifi_verification_map_monitor_enabled = False return jsonify({ "ok": True, "monitor_enabled": False, - "stop_deferred": False + "stop_deferred": False, + "owner": owner }) except Exception: @@ -3919,6 +4327,51 @@ def api_wifi_verification_start(): interface = interface.strip() + mode = data.get("mode", "AUTO") + + if not isinstance(mode, str): + return jsonify({ + "ok": False, + "error": "Invalid verification mode." + }), 400 + + mode = mode.strip().upper() + + if mode not in ("AUTO", "MANUAL"): + return jsonify({ + "ok": False, + "error": "Invalid verification mode." + }), 400 + + manual_center = None + + if mode == "MANUAL": + coordinates = data.get("manual_center") + + if ( + not isinstance(coordinates, list) + or len(coordinates) != 2 + or any(type(value) not in (int, float) for value in coordinates) + ): + return jsonify({ + "ok": False, + "error": "Manual center must contain numeric latitude and longitude." + }), 400 + + latitude = float(coordinates[0]) + longitude = float(coordinates[1]) + + if not ( + -90 <= latitude <= 90 + and -180 <= longitude <= 180 + ): + return jsonify({ + "ok": False, + "error": "Manual center coordinates are out of range." + }), 400 + + manual_center = (latitude, longitude) + device, error, status = validate_network_interface( interface ) @@ -3977,7 +4430,10 @@ def api_wifi_verification_start(): } ), 409 - if settings.get("gps_source") not in ("gpsd", "gpsrelay"): + if ( + mode == "AUTO" + and settings.get("gps_source") not in ("gpsd", "gpsrelay") + ): return jsonify( { @@ -4002,9 +4458,17 @@ def api_wifi_verification_start(): } ), 409 - shared_gps_service = ( - _get_wifi_verification_shared_gps(settings) - ) + if mode == "AUTO": + shared_gps_service = ( + _get_wifi_verification_shared_gps(settings) + ) + else: + with wifi_verification_shared_gps_lock: + shared_gps_service = ( + wifi_verification_shared_gps_service + if wifi_verification_map_monitor_enabled + else None + ) service = AutoWiFiVerificationService( settings=settings, @@ -4019,7 +4483,9 @@ def api_wifi_verification_start(): ), release_network_owner=( release_wifi_verification_network_owner - ) + ), + mode=mode, + manual_center=manual_center ) auto_wifi_verification_service = service diff --git a/gui/static/style.css b/gui/static/style.css index 2580db8..a50a3b4 100644 --- a/gui/static/style.css +++ b/gui/static/style.css @@ -1444,7 +1444,7 @@ pre { font: inherit; font-size: 11px; font-weight: 700; - cursor: default; + cursor: pointer; } .capture-mode-button.active { @@ -1835,6 +1835,24 @@ pre { display: none; } +.auto-verification-relay-discovery { + grid-column: 1 / -1; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; +} + +.auto-verification-relay-discovery .button { + min-width: 190px; +} + +#auto-gpsrelay-discovery-status { + width: 100%; + text-align: center; + overflow-wrap: anywhere; +} + .auto-verification-config .field { width: 100%; max-width: none; @@ -2238,6 +2256,21 @@ pre { box-shadow: 0 0 0 5px rgba(38, 136, 255, 0.25); } +.auto-manual-map-marker { + width: 22px; + height: 22px; + border: 3px solid #fff; + border-radius: 50%; + background: #a855f7; + box-shadow: 0 0 0 6px rgba(168, 85, 247, 0.25); + cursor: grab; +} + +.auto-manual-map-marker:active { + cursor: grabbing; +} + + /* Auto Verification — map top row and layers */ .capture-map-top-row { @@ -2819,3 +2852,27 @@ pre { font-size: 11px; text-align: center; } + +#capture-map .auto-gps-follow-control button:disabled { + opacity: 0.35; + cursor: default; +} + +#capture-map .auto-gps-follow-control .auto-manual-center-button svg { + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; +} + +#capture-map .auto-gps-follow-control .auto-gps-follow-button.is-manual { + color: #2688ff; +} + +#capture-map .auto-gps-follow-control .auto-manual-center-button { + color: #e53935; +} + +#capture-map .auto-gps-follow-control .auto-manual-center-button.active { + color: #a855f7; +} diff --git a/gui/templates/auto_verification_map.html b/gui/templates/auto_verification_map.html index 62d77e5..e49ed43 100644 --- a/gui/templates/auto_verification_map.html +++ b/gui/templates/auto_verification_map.html @@ -53,19 +53,18 @@ @@ -395,9 +394,26 @@ name="gpsrelay_port" min="1" max="65535" + value="5000" placeholder="1–65535" > + +
+ +
+
@@ -505,6 +521,12 @@ const relayFields = document.getElementById("auto-gpsrelay-fields"); const relayHost = document.getElementById("auto-gpsrelay-host"); const relayPort = document.getElementById("auto-gpsrelay-port"); + const relayDiscoverButton = document.getElementById( + "auto-gpsrelay-discover" + ); + const relayDiscoveryStatus = document.getElementById( + "auto-gpsrelay-discovery-status" + ); const gnssMaxAge = document.getElementById("auto-gnss-max-age"); const retryPasses = document.getElementById("auto-queue-retry-passes"); @@ -525,6 +547,14 @@ ); const settingsUrl = "/api/wifi-verification/settings"; + const relayDiscoveryStartUrl = + "/api/wifi-verification/gpsrelay-discovery/start"; + const relayDiscoveryStatusUrl = + "/api/wifi-verification/gpsrelay-discovery/status"; + + let relayDiscoveryTimer = null; + let relayDiscoveryActive = false; + let relayDiscoveryApplyResult = false; function updateGpsSourceFields() { const useRelay = gpsSource.value === "gpsrelay"; @@ -563,6 +593,150 @@ radiusApplyStatus.classList.toggle("error", isError); } + function showRelayDiscoveryStatus(message, isError = false) { + relayDiscoveryStatus.textContent = message; + relayDiscoveryStatus.classList.toggle("error", isError); + } + + function scheduleRelayDiscoveryPoll() { + if (relayDiscoveryTimer !== null) { + window.clearTimeout(relayDiscoveryTimer); + } + + relayDiscoveryTimer = window.setTimeout(() => { + relayDiscoveryTimer = null; + refreshRelayDiscoveryStatus(); + }, 1000); + } + + async function refreshRelayDiscoveryStatus() { + try { + const response = await fetch(relayDiscoveryStatusUrl); + const job = await response.json(); + + if (!response.ok || !job.ok) { + throw new Error( + job.error || "Не удалось получить состояние поиска." + ); + } + + if (job.state === "RUNNING") { + relayDiscoveryActive = true; + relayDiscoveryApplyResult = true; + relayDiscoverButton.disabled = true; + + showRelayDiscoveryStatus( + "Поиск GPSRelay и проверка потока NMEA…" + ); + + scheduleRelayDiscoveryPoll(); + return; + } + + relayDiscoveryActive = false; + relayDiscoverButton.disabled = false; + + if (job.state === "SUCCEEDED" && job.result) { + if (relayDiscoveryApplyResult) { + const found = job.result; + const types = Array.isArray(found.sentence_types) + ? found.sentence_types.join(", ") + : ""; + + relayHost.value = found.host || relayHost.value; + relayPort.value = found.port ?? relayPort.value; + + showRelayDiscoveryStatus( + `Найден GPSRelay: ${found.host}:${found.port}. ` + + `Интерфейс: ${found.interface}. ` + + `Корректных NMEA-предложений: ` + + `${found.valid_sentences}. ` + + `Типы: ${types}. ` + + "Для сохранения нажмите SAVE." + ); + } else { + showRelayDiscoveryStatus(""); + } + + } else if (job.state === "FAILED") { + if (relayDiscoveryApplyResult) { + showRelayDiscoveryStatus( + job.error || "GPSRelay не найден.", + true + ); + } else { + showRelayDiscoveryStatus(""); + } + + } else { + showRelayDiscoveryStatus(""); + } + + relayDiscoveryApplyResult = false; + + } catch (error) { + if (relayDiscoveryActive) { + relayDiscoverButton.disabled = true; + showRelayDiscoveryStatus( + `Не удалось обновить состояние поиска: ${error.message}` + ); + scheduleRelayDiscoveryPoll(); + } else { + relayDiscoverButton.disabled = false; + showRelayDiscoveryStatus(error.message, true); + } + } + } + + async function startRelayDiscovery() { + const rawPort = relayPort.value.trim(); + const port = rawPort === "" ? 5000 : Number(rawPort); + + if ( + !Number.isInteger(port) + || port < 1 + || port > 65535 + ) { + showRelayDiscoveryStatus( + "Укажите корректный порт от 1 до 65535.", + true + ); + return; + } + + relayDiscoverButton.disabled = true; + relayDiscoveryActive = true; + relayDiscoveryApplyResult = true; + + showRelayDiscoveryStatus("Запуск поиска GPSRelay…"); + + try { + const response = await fetch(relayDiscoveryStartUrl, { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ port: port }) + }); + + const result = await response.json(); + + if (!response.ok || !result.ok) { + throw new Error( + result.error || "Не удалось запустить поиск GPSRelay." + ); + } + + await refreshRelayDiscoveryStatus(); + + } catch (error) { + relayDiscoveryActive = false; + relayDiscoveryApplyResult = false; + relayDiscoverButton.disabled = false; + showRelayDiscoveryStatus(error.message, true); + } + } + async function applyRadius() { const radius = getSelectedRadius(); @@ -598,6 +772,11 @@ : `Радиус ${radius} м сохранён и будет использован при следующем запуске.` ); + window.dispatchEvent(new CustomEvent( + "wifi-verification-radius-applied", + { detail: { radius_m: radius } } + )); + } catch (error) { showRadiusStatus(error.message, true); @@ -611,7 +790,7 @@ gpsSource.value = settings.gps_source || ""; relayHost.value = settings.gpsrelay_host || ""; - relayPort.value = settings.gpsrelay_port ?? ""; + relayPort.value = settings.gpsrelay_port ?? "5000"; gnssMaxAge.value = settings.gnss_max_age_seconds; retryPasses.value = settings.queue_retry_passes; @@ -642,6 +821,7 @@ loadSettings(result.settings); showStatus("Настройки загружены."); + refreshRelayDiscoveryStatus(); } catch (error) { showStatus(error.message, true); @@ -724,6 +904,10 @@ }); saveButton.addEventListener("click", saveSettings); + relayDiscoverButton.addEventListener( + "click", + startRelayDiscovery + ); radiusApplyButton.addEventListener("click", applyRadius); mapRadiusApplyButton.addEventListener("click", applyRadius); @@ -734,7 +918,8 @@ gpsSource.selectedIndex = 0; relayHost.value = ""; - relayPort.value = ""; + relayPort.value = "5000"; + showRelayDiscoveryStatus(""); gnssMaxAge.value = "5"; retryPasses.value = "1"; @@ -767,6 +952,8 @@ const count = document.getElementById("capture-map-count"); const startButton = document.getElementById("auto-start"); const stopButton = document.getElementById("auto-stop"); + const autoModeButton = document.getElementById("auto-mode-button"); + const manualModeButton = document.getElementById("manual-mode-button"); const interfaceSelect = document.getElementById("auto-interface"); const statusText = document.getElementById("header-scanner-status"); const statusIndicator = document.getElementById("auto-status-indicator"); @@ -797,6 +984,8 @@ const gpsValue = document.querySelector(".auto-position-gps"); const coordinatesInput = document.getElementById("auto-position-coordinates"); const radiusText = document.getElementById("auto-position-radius"); + let manualCenterButton = null; + const mapRadiusSelect = document.getElementById("auto-map-radius-select"); const filters = { green: true, @@ -815,6 +1004,10 @@ let gpsLastRadius = null; let latestGpsPosition = null; let autoRunning = false; + let verificationMode = "AUTO"; + let manualCenter = null; + let manualMarker = null; + let manualPlacementEnabled = false; const map = new maplibregl.Map({ container: "capture-map", @@ -855,8 +1048,6 @@ const button = document.createElement("button"); button.type = "button"; button.className = "auto-gps-follow-button"; - button.title = "Вернуться к GPS"; - button.setAttribute("aria-label", "Вернуться к GPS"); button.setAttribute("aria-pressed", "true"); button.innerHTML = `
  • {} — {} байт
  • ".format( esc(item["name"]), @@ -322,9 +515,61 @@ def recovery_block(conn): for reason in candidate["reasons"] ) + recovery_html = "" + + if candidate.get("id") is None: + + directory_name = Path( + candidate["session_dir"] + ).name + + recovery_html = f""" +
    + +
    + +

    + Если восстановление не требуется, каталог можно удалить вручную: +

    + +

    + {esc(candidate["session_dir"])} + +

    + +

    + Удаление безвозвратно уничтожит файлы поездки. + Приложение автоматически файлы не удаляет. +

    +""" + html.append(f"""
    -

    Поездка #{candidate["id"]}

    +

    {esc(title)}

    Дата начала: @@ -357,6 +602,8 @@ def recovery_block(conn): Возможное дальнейшее действие: {esc(candidate["actions"])}

    + + {recovery_html}
    """) diff --git a/reports/static/report.css b/reports/static/report.css index fed37b1..91a0971 100644 --- a/reports/static/report.css +++ b/reports/static/report.css @@ -1916,3 +1916,32 @@ body .maplibregl-popup-close-button:hover { width: 100%; } } + +.recovery-directory { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.recovery-directory code { + overflow-wrap: anywhere; +} + +.recovery-copy-button { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 32px; + min-height: 32px; + padding: 4px 7px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--surface); + color: var(--text); + cursor: pointer; +} + +.recovery-copy-button:hover { + border-color: var(--accent); +} diff --git a/reports/template.py b/reports/template.py index 69a4d3e..0515865 100644 --- a/reports/template.py +++ b/reports/template.py @@ -199,6 +199,40 @@ function filterTable(id,value) }} }} +async function copyRecoveryPath(button) +{{ + const path = button.dataset.copyPath; + + if (!path) + return; + + const originalHTML = button.innerHTML; + + try + {{ + if (!navigator.clipboard || !navigator.clipboard.writeText) + throw new Error("Clipboard API unavailable"); + + await navigator.clipboard.writeText(path); + + button.textContent = "✓"; + + setTimeout(() => + {{ + button.innerHTML = originalHTML; + }}, 1500); + }} + catch (error) + {{ + button.textContent = "✕"; + + setTimeout(() => + {{ + button.innerHTML = originalHTML; + }}, 2000); + }} +}} + async function copyMapCoordinates(button) {{ const coordinates = button.dataset.coordinates; diff --git a/src/auto_gps.py b/src/auto_gps.py index eee51ad..6e7f33a 100644 --- a/src/auto_gps.py +++ b/src/auto_gps.py @@ -211,7 +211,18 @@ class AutoGPSService: logger.info ) - log_method(message) + if code in ( + "GPS_STARTED", + "GPS_CONNECTED", + "GPS_CONNECTION_LOST", + "GPS_SERVICE_ERROR", + "GPS_STOPPED", + ): + log_method( + "%s: %s", + code, + message + ) if self.callback is not None: try: diff --git a/src/auto_wifi_verification.py b/src/auto_wifi_verification.py index 45f09b1..de3898f 100644 --- a/src/auto_wifi_verification.py +++ b/src/auto_wifi_verification.py @@ -13,6 +13,7 @@ from auto_gps import AutoGPSService from wifi_connection import ( APNotFoundError, NetworkCleanupError, + NetworkCommandCancelled, NetworkCommandError, NetworkRestoreError, WiFiConnectionError @@ -23,6 +24,14 @@ logger = logging.getLogger( "wifi-gps-mapper.auto-verification" ) +LOGGED_MONITOR_EVENTS = frozenset({ + "STATE", + "RADIUS_UPDATED", + "SERVICE_STARTED", + "AP_MISSING_FROM_SCAN", + "SERVICE_STOPPED", +}) + def _utc_now(): return datetime.now( @@ -97,10 +106,47 @@ class AutoWiFiVerificationService: callback=None, acquire_network_owner=None, release_network_owner=None, - gps_service=None + gps_service=None, + mode="AUTO", + manual_center=None ): self.settings = dict(settings or {}) self.interface = interface + + self.verification_mode = str(mode or "AUTO").upper() + + if self.verification_mode not in ("AUTO", "MANUAL"): + raise ValueError("Invalid verification mode.") + + self.manual_center = None + + if self.verification_mode == "MANUAL": + if ( + not isinstance(manual_center, (tuple, list)) + or len(manual_center) != 2 + or any(type(value) is bool for value in manual_center) + ): + raise ValueError("Manual center coordinates are required.") + + try: + latitude = float(manual_center[0]) + longitude = float(manual_center[1]) + except (TypeError, ValueError): + raise ValueError("Invalid manual center coordinates.") + + if not ( + -90 <= latitude <= 90 + and -180 <= longitude <= 180 + ): + raise ValueError("Manual center coordinates are out of range.") + + self.manual_center = (latitude, longitude) + + self.network_owner = ( + "MANUAL_WIFI_VERIFY" + if self.verification_mode == "MANUAL" + else "AUTO_WIFI_VERIFY" + ) self.wifi_connection_service = wifi_connection_service self.callback = callback self.acquire_network_owner = acquire_network_owner @@ -127,9 +173,14 @@ class AutoWiFiVerificationService: self._pending_radius_update = None self._radius_update_event = threading.Event() - self.manage_gps_service = gps_service is None + self.manage_gps_service = ( + gps_service is None + and self.verification_mode == "AUTO" + ) - if gps_service is None: + if self.verification_mode == "MANUAL": + self.gps_service = None + elif gps_service is None: self.gps_service = AutoGPSService( self.settings, callback=self._gps_callback, @@ -180,6 +231,9 @@ class AutoWiFiVerificationService: self._notify() def _gps_fix_callback(self, gps): + if self.verification_mode != "AUTO": + return + with self._gps_fix_condition: self._gps_fix_generation += 1 self._gps_fix_condition.notify_all() @@ -227,6 +281,18 @@ class AutoWiFiVerificationService: -self.monitor_event_limit: ] + if event in LOGGED_MONITOR_EVENTS: + log_method = getattr( + logger, + level.lower(), + logger.info + ) + log_method( + "%s: %s", + event, + message + ) + def _update_monitor_candidates(self, candidates): with self.lock: strengths = { @@ -288,6 +354,20 @@ class AutoWiFiVerificationService: ) ) + def _sort_work_queue_by_signal(self, work_queue): + with self.lock: + strengths = { + candidate["bssid"].lower(): candidate["strength"] + for candidate in self.monitor_candidates + } + + work_queue.sort( + key=lambda job: ( + strengths.get(job[1].lower()) is None, + -(strengths.get(job[1].lower()) or 0) + ) + ) + def _update_monitor_queue(self, work_queue): grouped = {} @@ -320,7 +400,11 @@ class AutoWiFiVerificationService: def get_status(self): with self.lock: - gps_status = self.gps_service.get_status() + gps_status = ( + self.gps_service.get_status() + if self.gps_service is not None + else {} + ) return { "running": self.running, @@ -328,6 +412,8 @@ class AutoWiFiVerificationService: "error": self.error, "session_id": self.session_id, "interface": self.interface, + "verification_mode": self.verification_mode, + "manual_center": self.manual_center, "radius_m": self.radius_m, "gps": gps_status, "access_points_total": self.access_points_total, @@ -375,7 +461,7 @@ class AutoWiFiVerificationService: if self.acquire_network_owner is not None: acquired, error = self.acquire_network_owner( - "AUTO_WIFI_VERIFY" + self.network_owner ) if not acquired: @@ -386,9 +472,17 @@ class AutoWiFiVerificationService: self.network_owner_acquired = True try: + self.wifi_connection_service.disconnect_active_connection( + self.interface + ) + gps_generation = 0 - if not self.manage_gps_service: + if ( + self.verification_mode == "AUTO" + and not self.manage_gps_service + and self.gps_service is not None + ): gps_status = self.gps_service.get_status() if ( @@ -406,13 +500,23 @@ class AutoWiFiVerificationService: self.stop_event.clear() with self._gps_fix_condition: - self._gps_fix_generation = gps_generation - self._gps_fix_consumed_generation = 0 + if ( + gps_generation + and self._gps_fix_generation + <= self._gps_fix_consumed_generation + ): + self._gps_fix_generation = ( + self._gps_fix_consumed_generation + 1 + ) self._bssid_states.clear() self._missing_scan_bssids.clear() self.running = True - self.state = "WAITING_GPS" + self.state = ( + "WAITING_GPS" + if self.verification_mode == "AUTO" + else "STARTING" + ) self.error = None self.thread = threading.Thread( @@ -450,11 +554,11 @@ class AutoWiFiVerificationService: if self.release_network_owner is None: raise RuntimeError( - "AUTO_WIFI_VERIFY network owner cannot be released: " + f"{self.network_owner} network owner cannot be released: " "release callback is not configured." ) - self.release_network_owner("AUTO_WIFI_VERIFY") + self.release_network_owner(self.network_owner) with self.lock: self.network_owner_acquired = False @@ -481,7 +585,7 @@ class AutoWiFiVerificationService: and thread.is_alive() and thread is not threading.current_thread() ): - thread.join(timeout=15) + thread.join() self._notify() @@ -594,11 +698,12 @@ class AutoWiFiVerificationService: error_code, error_message ) - VALUES (?, ?, 'AUTO', ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( credential_id, self.session_id, + self.verification_mode, status, _utc_now(), _utc_now(), @@ -639,6 +744,27 @@ class AutoWiFiVerificationService: ) ) + attempt_log = ( + logger.info + if status == "SUCCESS" + else logger.warning + if status in ("INVALID_PASSWORD", "AP_NOT_FOUND") + else logger.error + ) + + attempt_log( + "Wi-Fi verification attempt: " + "session_id=%s mode=%s interface=%s " + "bssid=%s credential_id=%s status=%s error_code=%s", + self.session_id, + self.verification_mode, + self.interface, + bssid, + credential_id, + status, + error_code or "-" + ) + self._update_session_counters(connection) def _update_session_counters(self, connection): @@ -672,6 +798,9 @@ class AutoWiFiVerificationService: connection.commit() def _get_gps_fix(self): + if self.gps_service is None: + return None + status = self.gps_service.get_status() if not status.get("has_fresh_fix"): @@ -818,7 +947,11 @@ class AutoWiFiVerificationService: if command is None: return False - self._set_state("WAITING_GPS") + self._set_state( + "WAITING_GPS" + if self.verification_mode == "AUTO" + else "RUNNING" + ) while not self.stop_event.is_set(): with self._radius_update_lock: @@ -829,27 +962,31 @@ class AutoWiFiVerificationService: after_generation = command["after_generation"] - with self._gps_fix_condition: - generation = self._gps_fix_generation + if self.verification_mode == "MANUAL": + generation = after_generation + fix = self.manual_center + else: + 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 - 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 @@ -988,11 +1125,15 @@ class AutoWiFiVerificationService: self.interface, bssid, password, - restore_connection=True, + restore_connection=False, keep_profile=False, - access_point=access_point["scan_result"] + access_point=access_point["scan_result"], + cancel_event=self.stop_event ) + except NetworkCommandCancelled: + raise + except APNotFoundError as error: self._record_attempt( connection, @@ -1250,7 +1391,6 @@ class AutoWiFiVerificationService: 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) @@ -1278,11 +1418,74 @@ class AutoWiFiVerificationService: # (access_point_id, bssid, essid, credential, retry_count) work_queue = [] + if self.verification_mode == "MANUAL": + candidates = self._get_candidates( + connection, + self.manual_center + ) + + 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() + + state = self._bssid_states.setdefault( + bssid_key, + { + "status": "NEW", + "processed_credentials": set() + } + ) + + if state["status"] == "VERIFIED": + continue + + for credential in access_point["credentials"]: + credential_id = credential["credential_id"] + + if credential_id in state["processed_credentials"]: + continue + + work_queue.append( + ( + access_point["access_point_id"], + bssid, + access_point["essid"], + credential, + 0 + ) + ) + + if access_point["credentials"]: + state["status"] = "QUEUED" + + self._add_monitor_event( + "MANUAL_CENTER_SET", + ( + "Центр ручной проверки: " + f"{self.manual_center[0]:.6f}, " + f"{self.manual_center[1]:.6f}" + ) + ) + self._update_monitor_queue(work_queue) self._set_monitor_active() self._add_monitor_event( "SERVICE_STARTED", - "Сервис автоматической проверки запущен" + ( + "Сервис ручной проверки запущен" + if self.verification_mode == "MANUAL" + else "Сервис автоматической проверки запущен" + ) ) gps_refresh_deferred = False @@ -1297,16 +1500,17 @@ class AutoWiFiVerificationService: gps_update = False - # Забираем последнее необработанное GPS-поколение. - with self._gps_fix_condition: - if ( - self._gps_fix_generation - > self._gps_fix_consumed_generation - ): - self._gps_fix_consumed_generation = ( + # GPS-поколения используются только в Auto. + if self.verification_mode == "AUTO": + with self._gps_fix_condition: + if ( self._gps_fix_generation - ) - gps_update = True + > self._gps_fix_consumed_generation + ): + self._gps_fix_consumed_generation = ( + self._gps_fix_generation + ) + gps_update = True # GPS FIX добавляет новые задания. # Потеря GPS не очищает существующую очередь. @@ -1382,18 +1586,28 @@ class AutoWiFiVerificationService: if self.stop_event.is_set(): break - # Пустая очередь — ожидаем новый GPS FIX. + # Пустая очередь: Auto ждёт GPS, Manual — изменения радиуса. if not work_queue: - self._set_state("WAITING_GPS") + if self.verification_mode == "MANUAL": + self._set_state("WAITING_RADIUS") - 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() + with self._gps_fix_condition: + while ( + not self.stop_event.is_set() + and not self._radius_update_event.is_set() + ): + self._gps_fix_condition.wait() + else: + 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 @@ -1413,11 +1627,12 @@ class AutoWiFiVerificationService: gps_update_pending = False - with self._gps_fix_condition: - gps_update_pending = ( - self._gps_fix_generation - > self._gps_fix_consumed_generation - ) + if self.verification_mode == "AUTO": + 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 @@ -1453,6 +1668,7 @@ class AutoWiFiVerificationService: "warning" ) + self._sort_work_queue_by_signal(work_queue) self._update_monitor_queue(work_queue) if self.stop_event.is_set(): @@ -1583,6 +1799,19 @@ class AutoWiFiVerificationService: final_status = "STOPPED" + except NetworkCommandCancelled as error: + if self.stop_event.is_set(): + final_status = "STOPPED" + else: + final_status = "ERROR" + self._set_state( + "ERROR", + str(error) + ) + logger.exception( + "Wi-Fi verification was cancelled unexpectedly." + ) + except (NetworkRestoreError, NetworkCleanupError) as error: final_status = "ERROR" self._set_state( @@ -1600,7 +1829,8 @@ class AutoWiFiVerificationService: str(error) ) logger.exception( - "Auto Wi-Fi verification failed." + "%s Wi-Fi verification failed.", + self.verification_mode.title() ) finally: @@ -1666,7 +1896,11 @@ class AutoWiFiVerificationService: ( "Сервис завершил работу с ошибкой" if final_status == "ERROR" - else "Сервис автоматической проверки остановлен" + else ( + "Сервис ручной проверки остановлен" + if self.verification_mode == "MANUAL" + else "Сервис автоматической проверки остановлен" + ) ), "error" if final_status == "ERROR" else "info" ) diff --git a/src/database.py b/src/database.py index 04fcfc6..1db3019 100644 --- a/src/database.py +++ b/src/database.py @@ -1023,10 +1023,15 @@ class Database: def create_session( self, - capture_file + capture_file, + start_time=None ): + session_start = start_time or datetime.now( + timezone.utc + ) + cursor = self.conn.execute( """ INSERT INTO capture_sessions @@ -1039,9 +1044,7 @@ class Database: """, ( - datetime.now( - timezone.utc - ).isoformat().replace( + session_start.isoformat().replace( "+00:00", "Z" ), diff --git a/src/gpsrelay_discovery.py b/src/gpsrelay_discovery.py new file mode 100644 index 0000000..4c906ba --- /dev/null +++ b/src/gpsrelay_discovery.py @@ -0,0 +1,642 @@ + +import ipaddress +import json +import shutil +import subprocess +import xml.etree.ElementTree as ET + +from pathlib import Path + +import pynmea2 + + +DEFAULT_PORT = 5000 + +IP_TIMEOUT_SECONDS = 5 +NMAP_TIMEOUT_SECONDS = 35 +NMEA_TIMEOUT_SECONDS = 5 + +MIN_VALID_NMEA_SENTENCES = 2 + +MAX_NETWORK_PREFIX_LENGTH = 16 +MIN_NETWORK_PREFIX_LENGTH = 30 + +PRIVATE_IPV4_NETWORKS = ( + ipaddress.ip_network("10.0.0.0/8"), + ipaddress.ip_network("172.16.0.0/12"), + ipaddress.ip_network("192.168.0.0/16"), +) + +EXCLUDED_INTERFACE_PREFIXES = ( + "lo", + "docker", + "br-", + "virbr", + "veth", + "tun", + "tap", + "wg", + "tailscale", + "podman", + "cni", + "flannel", + "zt", + "vmnet", + "vboxnet", + "dummy", + "ppp", + "sit", + "gre", +) + +VALID_NMEA_TYPES = { + "GGA", + "GLL", + "GNS", + "GSA", + "GSV", + "RMC", + "VTG", + "ZDA", +} + + +class GPSRelayDiscoveryError(RuntimeError): + pass + + +def _require_tools(): + + packages = { + "ip": "iproute2", + "nmap": "nmap", + "nc": "netcat-openbsd", + } + + missing = [ + f"{tool} (пакет {package})" + for tool, package in packages.items() + if shutil.which(tool) is None + ] + + if missing: + + raise GPSRelayDiscoveryError( + "Для поиска GPSRelay необходимо установить:\n" + + "\n".join(missing) + + "\nУстановка: sudo apt install " + + " ".join( + package + for tool, package in packages.items() + if shutil.which(tool) is None + ) + ) + + +def _is_physical_interface(interface): + + device_path = ( + Path("/sys/class/net") + / interface + / "device" + ) + + return device_path.exists() + + +def _is_excluded_interface(interface): + + return interface.startswith( + EXCLUDED_INTERFACE_PREFIXES + ) + + +def _interface_priority(interface): + + if interface.startswith("enx"): + return 0 + + if interface.startswith(( + "enp", + "eno", + "eth", + )): + return 1 + + if interface.startswith(( + "wl", + "wlan", + )): + return 2 + + return 3 + + +def _get_local_networks(ip_binary): + + try: + + result = subprocess.run( + [ + ip_binary, + "-j", + "-4", + "addr", + "show" + ], + capture_output=True, + text=True, + timeout=IP_TIMEOUT_SECONDS, + check=True + ) + + except ( + subprocess.SubprocessError, + OSError + ) as error: + + raise GPSRelayDiscoveryError( + f"Не удалось получить сетевые интерфейсы: {error}" + ) from error + + try: + + interfaces = json.loads( + result.stdout + ) + + except json.JSONDecodeError as error: + + raise GPSRelayDiscoveryError( + "Команда ip вернула некорректные данные." + ) from error + + networks = {} + + for item in interfaces: + + interface = item.get("ifname", "") + + if not interface: + continue + + if _is_excluded_interface(interface): + continue + + if not _is_physical_interface(interface): + continue + + flags = item.get("flags", []) + + if "UP" not in flags: + continue + + if item.get("operstate") == "DOWN": + continue + + for address in item.get("addr_info", []): + + if address.get("family") != "inet": + continue + + if address.get("scope") != "global": + continue + + local = address.get("local") + prefixlen = address.get("prefixlen") + + try: + + network = ipaddress.ip_interface( + f"{local}/{prefixlen}" + ).network + + except ( + TypeError, + ValueError + ): + continue + + if not ( + MAX_NETWORK_PREFIX_LENGTH + <= network.prefixlen + <= MIN_NETWORK_PREFIX_LENGTH + ): + continue + + if not any( + network.subnet_of(private_network) + for private_network in PRIVATE_IPV4_NETWORKS + ): + continue + + if ( + network.network_address.is_loopback + or network.network_address.is_link_local + or network.network_address.is_multicast + ): + continue + + key = str(network) + + candidate = { + "network": key, + "interface": interface, + "priority": _interface_priority(interface) + } + + previous = networks.get(key) + + if ( + previous is None + or candidate["priority"] < previous["priority"] + ): + networks[key] = candidate + + return sorted( + networks.values(), + key=lambda item: ( + item["priority"], + item["network"] + ) + ) + + +def _scan_network( + nmap_binary, + network, + port +): + + command = [ + nmap_binary, + "--unprivileged", + "-n", + "-Pn", + "-sT", + "-T4", + "--max-retries", + "1", + "--host-timeout", + "8s", + "--open", + "-p", + str(port), + "-oX", + "-", + network + ] + + try: + + result = subprocess.run( + command, + capture_output=True, + text=True, + timeout=NMAP_TIMEOUT_SECONDS, + check=False + ) + + except subprocess.TimeoutExpired as error: + + raise GPSRelayDiscoveryError( + f"Истекло время сканирования сети {network}." + ) from error + + except OSError as error: + + raise GPSRelayDiscoveryError( + f"Не удалось запустить nmap: {error}" + ) from error + + if result.returncode != 0: + + raise GPSRelayDiscoveryError( + f"Ошибка nmap при сканировании {network}: " + f"{result.stderr.strip()}" + ) + + try: + + root = ET.fromstring( + result.stdout + ) + + except ET.ParseError as error: + + raise GPSRelayDiscoveryError( + f"Не удалось разобрать результат nmap для {network}." + ) from error + + candidates = [] + + for host in root.findall("host"): + + status = host.find("status") + + if ( + status is None + or status.get("state") != "up" + ): + continue + + ports = host.find("ports") + + if ports is None: + continue + + port_is_open = any( + item.get("portid") == str(port) + and item.find("state") is not None + and item.find("state").get("state") == "open" + for item in ports.findall("port") + ) + + if not port_is_open: + continue + + address = next( + ( + item.get("addr") + for item in host.findall("address") + if item.get("addrtype") == "ipv4" + ), + None + ) + + if address is not None: + + candidates.append( + address + ) + + return candidates + + +def _validate_nmea_stream(output): + + if isinstance(output, bytes): + output = output.decode( + "ascii", + errors="replace" + ) + + valid_types = set() + valid_count = 0 + total_count = 0 + + for line in output.splitlines(): + + line = line.strip() + + if not line.startswith("$"): + continue + + total_count += 1 + + try: + + message = pynmea2.parse( + line, + check=True + ) + + except ( + pynmea2.ParseError, + ValueError, + TypeError + ): + continue + + message_type = getattr( + message, + "sentence_type", + "" + ) + + if message_type not in VALID_NMEA_TYPES: + continue + + valid_count += 1 + valid_types.add(message_type) + + ratio = ( + valid_count / total_count + if total_count + else 0 + ) + + return { + "valid_count": valid_count, + "valid_types": valid_types, + "valid_ratio": ratio, + "total_count": total_count + } + + +def _test_candidate( + nc_binary, + host, + port +): + + try: + + result = subprocess.run( + [ + nc_binary, + "-n", + host, + str(port) + ], + capture_output=True, + timeout=NMEA_TIMEOUT_SECONDS, + check=False + ) + + output = result.stdout or b"" + + except subprocess.TimeoutExpired as error: + + output = error.stdout or b"" + + except OSError: + + return None + + quality = _validate_nmea_stream( + output + ) + + if ( + quality["valid_count"] + < MIN_VALID_NMEA_SENTENCES + ): + return None + + return quality + + +def discover_gpsrelay(port=DEFAULT_PORT): + + if isinstance(port, bool): + raise GPSRelayDiscoveryError( + "Некорректный порт GPSRelay." + ) + + try: + + port = int(port) + + except ( + TypeError, + ValueError + ) as error: + + raise GPSRelayDiscoveryError( + "Некорректный порт GPSRelay." + ) from error + + if not 1 <= port <= 65535: + + raise GPSRelayDiscoveryError( + "Порт GPSRelay должен находиться в диапазоне 1–65535." + ) + + _require_tools() + + ip_binary = shutil.which("ip") + nmap_binary = shutil.which("nmap") + nc_binary = shutil.which("nc") + + networks = _get_local_networks( + ip_binary + ) + + if not networks: + + raise GPSRelayDiscoveryError( + "Не найдены активные физические сетевые интерфейсы " + "с подходящими IPv4-подсетями." + ) + + discovered = [] + scan_errors = [] + + for network in networks: + + try: + + hosts = _scan_network( + nmap_binary, + network["network"], + port + ) + + except GPSRelayDiscoveryError as error: + + scan_errors.append( + str(error) + ) + continue + + for host in hosts: + + discovered.append({ + "host": host, + "port": port, + "interface": network["interface"], + "priority": network["priority"] + }) + + if scan_errors: + + raise GPSRelayDiscoveryError( + "Не удалось полностью просканировать все локальные сети:\n" + + "\n".join(scan_errors) + ) + + if not discovered: + + raise GPSRelayDiscoveryError( + f"Устройства с открытым TCP-портом {port} " + "в локальных сетях не найдены." + ) + + verified = [] + + for candidate in discovered: + + quality = _test_candidate( + nc_binary, + candidate["host"], + port + ) + + if quality is None: + continue + + verified.append({ + **candidate, + **quality + }) + + if not verified: + + raise GPSRelayDiscoveryError( + "Порт найден, но ни одно устройство не передаёт " + "достаточное количество корректных NMEA-предложений." + ) + + verified.sort( + key=lambda item: ( + item["priority"], + -item["valid_count"], + -len(item["valid_types"]), + -item["valid_ratio"] + ) + ) + + best = verified[0] + + best_rank = ( + best["priority"], + best["valid_count"], + len(best["valid_types"]), + best["valid_ratio"] + ) + + equally_suitable = [ + item + for item in verified + if ( + item["priority"], + item["valid_count"], + len(item["valid_types"]), + item["valid_ratio"] + ) == best_rank + ] + + if len(equally_suitable) > 1: + + hosts = ", ".join( + item["host"] + for item in equally_suitable + ) + + raise GPSRelayDiscoveryError( + "Обнаружено несколько равноценных GPSRelay: " + + hosts + + ". Автоматический выбор небезопасен." + ) + + return { + "host": best["host"], + "port": port, + "interface": best["interface"], + "valid_sentences": best["valid_count"], + "sentence_types": sorted( + best["valid_types"] + ), + "candidate_count": len(verified) + } diff --git a/src/main.py b/src/main.py index 8593a27..060eb35 100644 --- a/src/main.py +++ b/src/main.py @@ -148,6 +148,8 @@ def shutdown(signum=None, frame=None): f"WiFi stop error: {error}" ) + parser_succeeded = False + try: if parser and session: @@ -157,6 +159,8 @@ def shutdown(signum=None, frame=None): session_id ) + parser_succeeded = True + except Exception as error: @@ -179,17 +183,31 @@ def shutdown(signum=None, frame=None): + database_close_safe = True + try: if (db and session_id is not None): - db.flush_observations() + if parser_succeeded: - db.finalize_session( - session_id - ) + db.flush_observations() - db.commit() + db.finalize_session( + session_id + ) + + db.commit() + + else: + + db.observation_buffer.clear() + + db.rollback() + + logger.warning( + "Parser did not complete; session transaction rolled back" + ) except Exception as error: @@ -197,6 +215,22 @@ def shutdown(signum=None, frame=None): f"Database finalize error: {error}" ) + if db: + + try: + + db.observation_buffer.clear() + + db.rollback() + + except Exception as rollback_error: + + logger.error( + f"Database rollback error: {rollback_error}" + ) + + database_close_safe = False + try: @@ -218,7 +252,13 @@ def shutdown(signum=None, frame=None): if db: - db.close() + if database_close_safe: + + db.close() + + else: + + db.conn.close() except Exception: diff --git a/src/session.py b/src/session.py index e405299..fd04e53 100644 --- a/src/session.py +++ b/src/session.py @@ -173,12 +173,21 @@ class Session: obj = cls.__new__(cls) - obj.start_time = datetime.now( - timezone.utc - ) - obj.path = Path(path) + try: + obj.start_time = datetime.strptime( + obj.path.name, + "%Y%m%d_%H%M%S" + ).replace( + tzinfo=timezone.utc + ) + except ValueError as exc: + raise ValueError( + "Invalid session directory timestamp: " + f"{obj.path.name}" + ) from exc + obj.capture_file = ( obj.path / "capture.pcapng" diff --git a/src/wifi_connection.py b/src/wifi_connection.py index a5c7809..06959e5 100644 --- a/src/wifi_connection.py +++ b/src/wifi_connection.py @@ -49,6 +49,10 @@ class NetworkCommandError(WiFiConnectionError): self.timed_out = timed_out +class NetworkCommandCancelled(WiFiConnectionError): + pass + + class UnsupportedSecurityError(WiFiConnectionError): pass @@ -98,6 +102,7 @@ class WiFiConnectionService: or subprocess.run ) + self._use_subprocess_popen = command_runner is None self.command_timeout = command_timeout self.scan_timeout = scan_timeout @@ -128,25 +133,117 @@ class WiFiConnectionService: def _run( self, command, - timeout=None + timeout=None, + cancel_event=None ): + command_timeout = ( + timeout + or + self.command_timeout + ) + + environment = { + **os.environ, + "LC_ALL": "C" + } + try: - result = self.command_runner( - command, - capture_output=True, - text=True, - timeout=( - timeout - or - self.command_timeout - ), - env={ - **os.environ, - "LC_ALL": "C" - } - ) + if ( + cancel_event is not None + and + self._use_subprocess_popen + ): + + if cancel_event.is_set(): + raise NetworkCommandCancelled( + "Wi-Fi verification was cancelled." + ) + + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=environment + ) + + deadline = time.monotonic() + command_timeout + + while True: + + if cancel_event.is_set(): + + try: + process.terminate() + except ProcessLookupError: + pass + + try: + stdout, stderr = process.communicate( + timeout=5 + ) + + except subprocess.TimeoutExpired: + + try: + process.kill() + except ProcessLookupError: + pass + + stdout, stderr = process.communicate() + + raise NetworkCommandCancelled( + "Wi-Fi verification was cancelled." + ) + + remaining = deadline - time.monotonic() + + if remaining <= 0: + + process.kill() + stdout, stderr = process.communicate() + + raise NetworkCommandError( + "NetworkManager command timed out.", + stdout=stdout or "", + stderr=stderr or "", + timed_out=True + ) + + try: + + stdout, stderr = process.communicate( + timeout=min(0.2, remaining) + ) + + break + + except subprocess.TimeoutExpired: + continue + + if cancel_event.is_set(): + raise NetworkCommandCancelled( + "Wi-Fi verification was cancelled." + ) + + result = subprocess.CompletedProcess( + command, + process.returncode, + stdout, + stderr + ) + + else: + + result = self.command_runner( + command, + capture_output=True, + text=True, + timeout=command_timeout, + env=environment + ) except subprocess.TimeoutExpired as error: @@ -191,14 +288,20 @@ class WiFiConnectionService: return result.stdout.strip() - def _nmcli(self, *arguments, timeout=None): + def _nmcli( + self, + *arguments, + timeout=None, + cancel_event=None + ): return self._run( [ "nmcli", *arguments ], - timeout=timeout + timeout=timeout, + cancel_event=cancel_event ) def _busctl(self, *arguments): @@ -646,6 +749,44 @@ class WiFiConnectionService: return output + def disconnect_active_connection(self, interface): + + self._validate_interface(interface) + + active_uuid = self._get_active_connection_uuid( + interface + ) + + if active_uuid is None: + return False + + try: + + self._nmcli( + "connection", + "down", + "uuid", + active_uuid + ) + + except NetworkCommandError as error: + + raise NetworkCleanupError( + f"Could not disconnect active Wi-Fi connection: {error}" + ) from error + + remaining_uuid = self._get_active_connection_uuid( + interface + ) + + if remaining_uuid is not None: + + raise NetworkCleanupError( + f"Wi-Fi interface {interface} remains connected." + ) + + return True + def _list_connection_profiles(self): output = self._nmcli( @@ -1253,7 +1394,8 @@ class WiFiConnectionService: profile_uuid, interface, access_point, - password=None + password=None, + cancel_event=None ): arguments = [ @@ -1299,7 +1441,8 @@ class WiFiConnectionService: self._nmcli( *arguments, - timeout=90 + timeout=90, + cancel_event=cancel_event ) except Exception as error: @@ -1463,18 +1606,10 @@ class WiFiConnectionService: password, restore_connection=True, keep_profile=False, - access_point=None + access_point=None, + cancel_event=None ): - 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 @@ -1549,7 +1684,8 @@ class WiFiConnectionService: profile_uuid, interface, access_point, - password + password, + cancel_event=cancel_event ) success = True @@ -1617,9 +1753,38 @@ class WiFiConnectionService: error ) - if not ( - success - and keep_profile + profile_is_safe_to_delete = True + + if not restore_connection and not keep_profile: + + try: + + active_uuid = self._get_active_connection_uuid( + interface + ) + + if active_uuid == profile_uuid: + + self._nmcli( + "connection", + "down", + "uuid", + profile_uuid + ) + + except NetworkCommandError as error: + + cleanup_error = str( + error + ) + profile_is_safe_to_delete = False + + if ( + not ( + success + and keep_profile + ) + and profile_is_safe_to_delete ): try: