import os import sys import signal import subprocess import threading import logging from logging.handlers import RotatingFileHandler import secrets import time import tempfile from collections import deque from datetime import datetime, timezone from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parent.parent sys.path.insert( 0, str(PROJECT_ROOT / "src") ) from flask import ( Flask, abort, Response, jsonify, redirect, render_template, request, send_file, send_from_directory, url_for, ) 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, generate_dashboard, ) from cracklab.server.web import cracklab_bp from cracklab.server.db.connection import ( connect_database as connect_cracklab_database, ) from cracklab.server.services.search_context import SearchContextService from reports.search import ( build_search_data, load_handshakes, normalize_criteria, render_search_page, search_access_points, ) from reports.hashcat import ( build_all_hash_export, build_export_filename, import_hashcat_show, ) from reports.trips_page import render_trips_page from reports.wifitrip import ( WifitripError, export_wifitrip, import_wifitrip, select_wifitrip_session_ids, validate_wifitrip, ) from reports.session_page import render_session_page from reports.access_points import render_access_points_page from reports.wifi_connections import render_wifi_connections_page from reports.access_points_page import render_access_point_page from reports.template import ReportContext from reports.utils import format_datetime as format_report_datetime from reports.vendors import render_vendors_page 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 ( LOG_DATE_FORMAT, LOG_FORMAT, UTCFormatter, ) from request_lifecycle import RequestLifecycleMiddleware app = Flask( __name__, template_folder=str( PROJECT_ROOT / "gui" / "templates" ), static_folder=str( PROJECT_ROOT / "gui" / "static" ) ) request_lifecycle = RequestLifecycleMiddleware( app.wsgi_app ) app.wsgi_app = request_lifecycle app.add_template_filter( format_report_datetime, "local_datetime" ) logger = logging.getLogger("wifi-gps-mapper.gui") 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 / "gui.log", maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8" ) handler.setFormatter( UTCFormatter( LOG_FORMAT, datefmt=LOG_DATE_FORMAT, ) ) logger.addHandler(handler) app.register_blueprint( cracklab_bp ) def wants_json_error(): return ( request.path.startswith(( "/api/", "/gps-test/", "/config/", "/scanner/" )) or request.path in { "/reports/vendors/update", "/reports/vendors/recalculate", "/reports/search/data", "/reports/search/cracklab", } or request.path.startswith( "/reports/vendors/recalculate/status/" ) ) def render_http_error(status_code, title, message): if wants_json_error(): return jsonify({ "error": message }), status_code return render_template( "error.html", status_code=status_code, title=title, message=message ), status_code @app.errorhandler(404) def page_not_found(error): logger.warning( "HTTP 404 method=%s path=%s", request.method, request.path ) return render_http_error( 404, "Страница не найдена", "Запрошенная страница не существует или была перемещена." ) @app.errorhandler(403) def access_forbidden(error): logger.warning( "HTTP 403 method=%s path=%s", request.method, request.path ) return render_http_error( 403, "Доступ запрещён", "У вас нет разрешения на выполнение этого действия." ) @app.errorhandler(405) def method_not_allowed(error): logger.warning( "HTTP 405 method=%s path=%s", request.method, request.path ) return render_http_error( 405, "Действие недоступно", "Этот способ обращения к странице не поддерживается." ) @app.errorhandler(500) def internal_server_error(error): original_exception = getattr( error, "original_exception", None ) if original_exception is not None: logger.error( "Unhandled exception method=%s path=%s", request.method, request.path, exc_info=( type(original_exception), original_exception, original_exception.__traceback__ ) ) else: logger.error( "HTTP 500 method=%s path=%s", request.method, request.path ) return render_http_error( 500, "Что-то пошло не так", "Во время обработки запроса произошла ошибка. Попробуйте позже." ) @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() if not status["running"]: return None if request.endpoint is None: return None if ( request.endpoint is not None and request.endpoint.startswith("cracklab.") ): return None allowed_endpoints = { "index", "api_status", "api_network_wifi_devices", "api_network_wifi_verify", "api_network_wifi_connect", "scanner_stop", "api_gps_test", "gps_test_stop", "static" } if request.endpoint in allowed_endpoints: return None return redirect( url_for("index") ) scanner_process = None scanner_starting = False network_action_active = False network_operation_owner = None scanner_health = "READY" scanner_stopped_at = None scanner_output = deque( maxlen=500 ) scanner_lock = threading.Lock() scanner_output_thread = None vendor_previews = {} vendor_preview_lock = threading.Lock() vendor_update_job = None vendor_update_thread = None vendor_update_lock = threading.Lock() vendor_operation_lock = threading.Lock() vendor_recalc_job = None vendor_recalc_thread = None vendor_recalc_lock = threading.Lock() 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 wifi_connection_service = WiFiConnectionService() def check_sudo(): try: result = subprocess.run( [ "sudo", "-n", "-v" ], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) except KeyboardInterrupt: return False except Exception: return False return result.returncode == 0 def sudo_keepalive(stop_event): checker = SudoChecker() while not stop_event.wait(60): checker.refresh() def gps_test_output(message): with scanner_lock: scanner_output.append( message ) def get_gps_test_status(): with gps_test_lock: service = gps_test_service if service is None: return { "running": False, "state": "READY", "nmea_received": False, "fix_received": False, "nmea_count": 0, "fix_count": 0, "latitude": None, "longitude": None, "error": None } return { "running": service.running, "state": service.state, "nmea_received": service.nmea_received, "fix_received": service.fix_received, "nmea_count": service.nmea_count, "fix_count": service.fix_count, "latitude": service.latitude, "longitude": service.longitude, "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 or ( scanner_process is not None and scanner_process.poll() is None ) ): return True with gps_test_lock: return ( gps_test_service is not None and gps_test_service.thread is not None and gps_test_service.thread.is_alive() ) def begin_network_action(): return acquire_network_owner("MANUAL_NETWORK") def end_network_action(): release_network_owner("MANUAL_NETWORK") def watch_gps_test(service): thread = service.thread if thread is not None: thread.join() with scanner_lock: _release_network_owner_locked("GPS_TEST") def get_scanner_status(): global scanner_health global scanner_stopped_at global scanner_process with scanner_lock: process = scanner_process if ( scanner_health == "STOPPED" and scanner_stopped_at is not None and time.time() - scanner_stopped_at >= 5 ): scanner_health = "READY" scanner_stopped_at = None if process is None: return { "running": False, "pid": None, "health": scanner_health } return_code = process.poll() if return_code is None: return { "running": True, "pid": process.pid, "health": scanner_health } scanner_process = None scanner_health = "STOPPED" scanner_stopped_at = time.time() scanner_output.append( f"[GUI] Scanner process exited with code {return_code}." ) return { "running": False, "pid": process.pid, "health": scanner_health, "return_code": return_code } def read_scanner_output(process): global scanner_health try: for line in iter( process.stdout.readline, "" ): line = line.rstrip() if line.startswith( "ScannerState:" ): state = line.split( ":", 1 )[1].strip() if state in { "READY", "ACTIVE", "WARNING", "STOPPED" }: if ( state != "STOPPED" or process.poll() is not None ): with scanner_lock: scanner_health = state continue if line: with scanner_lock: scanner_output.append( line ) except Exception as error: with scanner_lock: scanner_output.append( f"[GUI] Output reader error: {error}" ) finally: try: process.stdout.close() except Exception: 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 = [ "nmcli", "--terse", "--escape", "yes", "--fields", "DEVICE,TYPE,STATE", "device", "status" ] try: result = subprocess.run( command, capture_output=True, text=True, timeout=10, env={ **os.environ, "LC_ALL": "C" } ) except Exception as error: return [], f"NetworkManager query failed: {error}" if result.returncode != 0: error = ( result.stderr.strip() or f"nmcli exited with code {result.returncode}" ) return [], error devices = [] for line in result.stdout.splitlines(): parts = line.split(":", 2) if len(parts) != 3: continue device, device_type, state = parts if device_type != "wifi": continue devices.append( { "device": device, "state": state, "managed": None } ) for device in devices: try: managed_result = subprocess.run( [ "nmcli", "--get-values", "GENERAL.NM-MANAGED", "device", "show", device["device"] ], capture_output=True, text=True, timeout=10, env={ **os.environ, "LC_ALL": "C" } ) if managed_result.returncode == 0: value = managed_result.stdout.strip().lower() if value == "yes": device["managed"] = True elif value == "no": device["managed"] = False except Exception: pass return devices, None def get_active_vpn_status(): command = [ "nmcli", "--terse", "--escape", "yes", "--fields", "TYPE", "connection", "show", "--active" ] try: result = subprocess.run( command, capture_output=True, text=True, timeout=10, env={ **os.environ, "LC_ALL": "C" } ) except Exception as error: return False, str(error) if result.returncode != 0: error = ( result.stderr.strip() or f"nmcli exited with code {result.returncode}" ) return False, error vpn_types = {"vpn", "wireguard"} active = any( line.strip().lower() in vpn_types for line in result.stdout.splitlines() ) return active, None def get_wifi_interfaces(): try: result = subprocess.run( [ "sudo", "-n", "iw", "dev" ], cwd=PROJECT_ROOT, capture_output=True, text=True, timeout=10 ) except Exception as error: return [], str(error) if result.returncode != 0: error = ( result.stderr.strip() or f"iw exited with code {result.returncode}" ) return [], error interfaces = [] current = None for line in result.stdout.splitlines(): line = line.strip() if line.startswith("Interface"): parts = line.split() if len(parts) >= 2: current = parts[1] interfaces.append(current) return interfaces, None def get_wifi_channels(interface): try: result = subprocess.run( [ "sudo", "-n", str( PROJECT_ROOT / "bin" / "hcxdumptool" ), "-I", interface ], cwd=PROJECT_ROOT, capture_output=True, text=True, timeout=30 ) except Exception as error: return { "2.4": [], "5": [], "6": [], "error": str(error) } output = ( result.stdout + "\n" + result.stderr ) if result.returncode != 0: error = ( result.stderr.strip() or result.stdout.strip() or f"hcxdumptool exited with code " f"{result.returncode}" ) return { "2.4": [], "5": [], "6": [], "error": error } import re channels = { "2.4": [], "5": [], "6": [] } pattern = re.compile( r"(\d{4,5})\s+" r"\[\s*(\d+)\s*\]" r"(?:\s+(disabled))?" ) seen = { "2.4": set(), "5": set(), "6": set() } for line in output.splitlines(): matches = pattern.findall(line) for frequency, channel, disabled in matches: frequency = int(frequency) channel = int(channel) if 2400 <= frequency < 2500: band = "2.4" suffix = "a" elif 5000 <= frequency < 5925: band = "5" suffix = "b" elif 5925 <= frequency <= 7125: band = "6" suffix = "c" else: continue key = ( channel, frequency ) if key in seen[band]: continue seen[band].add(key) channels[band].append( { "channel": channel, "frequency": frequency, "value": f"{channel}{suffix}", "available": not bool(disabled) } ) for band in channels: channels[band].sort( key=lambda item: ( item["channel"], item["frequency"] ) ) return { "2.4": channels["2.4"], "5": channels["5"], "6": channels["6"], "error": None } def read_config(): import yaml config_file = ( PROJECT_ROOT / "config" / "config.yaml" ) try: with open( config_file, "r" ) as file: data = yaml.safe_load(file) gps = data["gps"] if "source" not in gps: data["gps"] = { "source": "gpsrelay", "gpsrelay": { "host": gps["host"], "port": gps["port"], }, "gnss": { "handler": "direct", "direct": { "device": "/dev/serial/by-id/" "usb-u-blox_AG_-_www.u-blox.com_" "u-blox_GNSS_receiver-if00", }, "gpsd": {}, "modem": { "device": "/dev/serial/by-id/" "usb-Quectel_EM160R-GL_718c89b2-if01-port0", "at_device": "/dev/serial/by-id/" "usb-Quectel_EM160R-GL_718c89b2-if03-port0", }, }, } elif "gnss" in gps and "direct" not in gps["gnss"]: old_gnss = gps["gnss"] data["gps"]["gnss"] = { "handler": old_gnss.get( "handler", "direct" ), "direct": { "device": old_gnss.get( "device", "/dev/serial/by-id/" "usb-u-blox_AG_-_www.u-blox.com_" "u-blox_GNSS_receiver-if00" ) }, "gpsd": {}, "modem": { "device": "/dev/serial/by-id/" "usb-Quectel_EM160R-GL_718c89b2-if01-port0", "at_device": old_gnss.get( "at_device", "/dev/serial/by-id/" "usb-Quectel_EM160R-GL_718c89b2-if03-port0" ), }, } return data except Exception as error: return { "_error": str(error) } def save_config(data): import re import yaml config_file = ( PROJECT_ROOT / "config" / "config.yaml" ) with open( config_file, "r" ) as file: text = file.read() def yaml_string(value): import json return json.dumps( str(value), ensure_ascii=False ) from zoneinfo import ZoneInfo timezone_name = str( data["timezone"] ).strip() if not timezone_name: raise RuntimeError( "Timezone cannot be empty." ) try: ZoneInfo(timezone_name) except Exception as error: raise RuntimeError( f"Invalid timezone: {timezone_name}" ) from error values = { "database": { "file": yaml_string( data["database"]["file"] ), }, "vendor": { "database": yaml_string( data["vendor"]["database"] ), }, "wifi": { "enable_2_4ghz": ( "true" if data["wifi"]["enable_2_4ghz"] else "false" ), "channels_2_4ghz": yaml_string( data["wifi"]["channels_2_4ghz"] ), "enable_5ghz": ( "true" if data["wifi"]["enable_5ghz"] else "false" ), "channels_5ghz": yaml_string( data["wifi"]["channels_5ghz"] ), "enable_6ghz": ( "true" if data["wifi"]["enable_6ghz"] else "false" ), "channels_6ghz": yaml_string( data["wifi"]["channels_6ghz"] ), "filtermode": str( data["wifi"]["filtermode"] ), "extra_args": yaml_string( data["wifi"]["extra_args"] ), }, "captures": { "directory": yaml_string( data["captures"]["directory"] ), }, "reports": { "recent_sessions_limit": str( data["reports"]["recent_sessions_limit"] ), }, "logging": { "level": yaml_string( data["logging"]["level"] ), }, "status": { "interval": str( data["status"]["interval"] ), }, } timezone_pattern = ( r"(^timezone:[ \t]*)" r"([^#\n]*?)" r"([ \t]*#.*)?$" ) text, count = re.subn( timezone_pattern, lambda item: ( item.group(1) + yaml_string( timezone_name ) + ( item.group(3) if item.group(3) else "" ) ), text, count=1, flags=re.MULTILINE ) if count != 1: raise RuntimeError( "Configuration key not found: timezone" ) gps_pattern = ( r"(^gps:[ \t]*\n)" r"(.*?)(?=^[A-Za-z_][A-Za-z0-9_]*:[ \t]*$|\Z)" ) gps_match = re.search( gps_pattern, text, flags=re.MULTILINE | re.DOTALL ) if not gps_match: raise RuntimeError( "Configuration section not found: gps" ) gps_text = ( " source: " + yaml_string( data["gps"]["source"] ) + "\n" " gpsrelay:\n" " host: " + yaml_string( data["gps"]["gpsrelay"]["host"] ) + "\n" " port: " + str( data["gps"]["gpsrelay"]["port"] ) + "\n" " gnss:\n" " handler: " + yaml_string( data["gps"]["gnss"]["handler"] ) + "\n" " direct:\n" " device: " + yaml_string( data["gps"]["gnss"]["direct"]["device"] ) + "\n" " gpsd: {}\n" " modem:\n" " device: " + yaml_string( data["gps"]["gnss"]["modem"]["device"] ) + "\n" " at_device: " + yaml_string( data["gps"]["gnss"]["modem"]["at_device"] ) + "\n" ) text = ( text[:gps_match.start(2)] + gps_text + text[gps_match.end(2):] ) for section, section_values in values.items(): section_pattern = ( r"(^" + re.escape(section) + r":[ \t]*\n)" r"(.*?)(?=^[A-Za-z_][A-Za-z0-9_]*:[ \t]*$|\Z)" ) match = re.search( section_pattern, text, flags=re.MULTILINE | re.DOTALL ) if not match: raise RuntimeError( f"Configuration section not found: {section}" ) section_text = match.group(2) for key, value in section_values.items(): pattern = ( r"(^[ \t]+" + re.escape(key) + r":[ \t]*)" + r"([^#\n]*?)" + r"([ \t]*#.*)?$" ) section_text, count = re.subn( pattern, lambda item: ( item.group(1) + value + ( item.group(3) if item.group(3) else "" ) ), section_text, count=1, flags=re.MULTILINE ) if count != 1: raise RuntimeError( f"Configuration key not found: " f"{section}.{key}" ) text = ( text[:match.start(2)] + section_text + text[match.end(2):] ) with open( config_file, "w" ) as file: file.write(text) def render_report( render_function, *args, **kwargs ): conn = connect_database() try: context = ReportContext( mode="server" ) html = render_function( conn, *args, context=context, **kwargs ) return Response( html, mimetype="text/html" ) finally: close_database(conn) @app.route("/reports/wifi-connections/") def reports_wifi_connections(): return render_report( render_wifi_connections_page ) @app.route("/reports/vendors/") def reports_vendors(): config = read_config() if "_error" in config: return jsonify( { "error": config["_error"] } ), 500 vendor_config = config.get( "vendor", {} ) database_config = config.get( "database", {} ) service = VendorService( PROJECT_ROOT / vendor_config["database"], PROJECT_ROOT / database_config["file"], vendor_config["sources"], vendor_config.get( "mirrors", {} ) ) job_id = request.args.get( "job_id" ) job = None preview = None token = None recalc_job = None recalc_job_id = request.args.get( "recalc_job_id" ) if recalc_job_id: with vendor_recalc_lock: if ( vendor_recalc_job is not None and vendor_recalc_job["id"] == recalc_job_id ): recalc_job = dict( vendor_recalc_job ) if job_id: with vendor_update_lock: if ( vendor_update_job is not None and vendor_update_job["id"] == job_id ): job = dict( vendor_update_job ) service = job["service"] if job is not None: token = job.get( "preview_token" ) if token: with vendor_preview_lock: preview = vendor_previews.get( token ) return render_report( render_vendors_page, service, preview, token, job=job, recalc_job=recalc_job ) def _run_vendor_update( job_id, service ): global vendor_update_job def progress_callback( stage, source=None, message=None ): with vendor_update_lock: if ( vendor_update_job is None or vendor_update_job["id"] != job_id ): return vendor_update_job["stage"] = stage vendor_update_job["source"] = source vendor_update_job["message"] = message try: preview = service.prepare_update( progress_callback=progress_callback ) token = secrets.token_urlsafe( 32 ) with vendor_preview_lock: while len(vendor_previews) >= 5: old_token, old_preview = ( next( iter( vendor_previews.items() ) ) ) del vendor_previews[ old_token ] service._cleanup_preview( old_preview ) vendor_previews[ token ] = preview with vendor_update_lock: if ( vendor_update_job is not None and vendor_update_job["id"] == job_id ): vendor_update_job["status"] = "ready" vendor_update_job["stage"] = "ready" vendor_update_job["source"] = None vendor_update_job["message"] = ( "Обновление готово к применению" ) vendor_update_job["preview_token"] = token vendor_update_job["error"] = None except Exception as error: with vendor_update_lock: if ( vendor_update_job is not None and vendor_update_job["id"] == job_id ): vendor_update_job["status"] = "error" vendor_update_job["stage"] = "error" vendor_update_job["message"] = None vendor_update_job["error"] = str( error ) @app.route( "/reports/vendors/update", methods=["POST"] ) def reports_vendors_update(): global vendor_update_job global vendor_update_thread config = read_config() if "_error" in config: return jsonify( { "error": config["_error"] } ), 500 vendor_config = config.get( "vendor", {} ) database_config = config.get( "database", {} ) service = VendorService( PROJECT_ROOT / vendor_config["database"], PROJECT_ROOT / database_config["file"], vendor_config["sources"], vendor_config.get( "mirrors", {} ) ) with vendor_update_lock: if ( vendor_update_job is not None and vendor_update_job["status"] == "running" ): job = dict( vendor_update_job ) return render_report( render_vendors_page, job["service"], job=job ) job_id = secrets.token_urlsafe( 16 ) vendor_update_job = { "id": job_id, "status": "running", "stage": "starting", "source": None, "message": "Подготовка обновления", "error": None, "preview_token": None, "service": service } try: vendor_update_thread = threading.Thread( target=_run_vendor_update, args=( job_id, service ), daemon=True ) vendor_update_thread.start() except Exception as error: vendor_update_job["status"] = "error" vendor_update_job["stage"] = "error" vendor_update_job["source"] = None vendor_update_job["message"] = None vendor_update_job["error"] = str( error ) job = dict( vendor_update_job ) return render_report( render_vendors_page, service, job=job ) @app.route( "/reports/vendors/update/status/" ) def reports_vendors_update_status( job_id ): with vendor_update_lock: if ( vendor_update_job is None or vendor_update_job["id"] != job_id ): return jsonify( { "status": "missing", "error": "Vendor update job is missing." } ), 404 job = dict( vendor_update_job ) return jsonify( { "status": job["status"], "stage": job["stage"], "source": job["source"], "message": job["message"], "error": job["error"], "preview_ready": job["preview_token"] is not None } ) def _run_vendor_recalculation( job_id, service ): global vendor_recalc_job def progress_callback( stage, source=None, message=None ): with vendor_recalc_lock: if ( vendor_recalc_job is None or vendor_recalc_job["id"] != job_id ): return vendor_recalc_job["stage"] = stage vendor_recalc_job["message"] = message try: with vendor_operation_lock: progress_callback( "scanning", message="Пересчёт производителей точек доступа" ) result = service.recalculate_ap_vendors( progress_callback=progress_callback ) with vendor_recalc_lock: if ( vendor_recalc_job is not None and vendor_recalc_job["id"] == job_id ): vendor_recalc_job["status"] = "ready" vendor_recalc_job["stage"] = "ready" vendor_recalc_job["message"] = ( "Пересчёт производителей завершён" ) vendor_recalc_job["result"] = result vendor_recalc_job["error"] = None except Exception as error: with vendor_recalc_lock: if ( vendor_recalc_job is not None and vendor_recalc_job["id"] == job_id ): vendor_recalc_job["status"] = "error" vendor_recalc_job["stage"] = "error" vendor_recalc_job["message"] = None vendor_recalc_job["error"] = str(error) @app.route( "/reports/vendors/recalculate", methods=["POST"] ) def reports_vendors_recalculate(): global vendor_recalc_job global vendor_recalc_thread config = read_config() if "_error" in config: return jsonify( { "error": config["_error"] } ), 500 vendor_config = config.get( "vendor", {} ) database_config = config.get( "database", {} ) service = VendorService( PROJECT_ROOT / vendor_config["database"], PROJECT_ROOT / database_config["file"], sources={} ) with vendor_recalc_lock: if ( vendor_recalc_job is not None and vendor_recalc_job["status"] == "running" ): job = dict( vendor_recalc_job ) else: job_id = secrets.token_urlsafe( 16 ) vendor_recalc_job = { "id": job_id, "status": "running", "stage": "waiting", "message": "Ожидание доступа к базам данных", "error": None, "result": None } try: vendor_recalc_thread = threading.Thread( target=_run_vendor_recalculation, args=( job_id, service ), daemon=True ) vendor_recalc_thread.start() except Exception as error: vendor_recalc_job["status"] = "error" vendor_recalc_job["stage"] = "error" vendor_recalc_job["message"] = None vendor_recalc_job["error"] = str(error) job = dict( vendor_recalc_job ) return render_report( render_vendors_page, service, recalc_job=job ) @app.route( "/reports/vendors/recalculate/status/" ) def reports_vendors_recalculate_status( job_id ): with vendor_recalc_lock: if ( vendor_recalc_job is None or vendor_recalc_job["id"] != job_id ): return jsonify( { "status": "missing", "error": "Vendor recalculation job is missing." } ), 404 job = dict( vendor_recalc_job ) return jsonify( { "status": job["status"], "stage": job["stage"], "message": job["message"], "error": job["error"] } ) @app.route( "/reports/vendors/apply", methods=["POST"] ) def reports_vendors_apply(): config = read_config() if "_error" in config: return jsonify( { "error": config["_error"] } ), 500 vendor_config = config.get( "vendor", {} ) database_config = config.get( "database", {} ) service = VendorService( PROJECT_ROOT / vendor_config["database"], PROJECT_ROOT / database_config["file"], vendor_config["sources"], vendor_config.get( "mirrors", {} ) ) if not vendor_operation_lock.acquire( blocking=False ): return jsonify( { "error": "Another vendor database operation is running. " "Please try again later." } ), 409 try: token = request.form.get( "token", "" ) with vendor_preview_lock: preview = vendor_previews.pop( token, None ) if preview is None: return jsonify( { "error": "Vendor preview is missing or expired." } ), 400 try: result = service.apply( preview ) except Exception as error: return render_report( render_vendors_page, service, message={ "type": "error", "text": str(error) } ) return render_report( render_vendors_page, service, message={ "type": "success", "text": ( "OUI update completed. " f"OUI updated: " f"{'yes' if result['oui_updated'] else 'no'}." ) } ) finally: vendor_operation_lock.release() @app.route("/reports/") def reports_dashboard(): return render_report( generate_dashboard ) @app.route("/reports/sessions/") def reports_capture_sessions(): return render_report( generate_capture_sessions, sessions_page_limit=request.args.get("limit"), ) @app.route("/reports/trips/") def reports_trips(): return render_report( render_trips_page ) @app.route("/reports/trips/preview") def reports_trips_preview(): conn = connect_database() try: session_ids = select_wifitrip_session_ids( conn, mode=request.args.get("mode", "all"), limit=request.args.get("limit", "1"), date_from=request.args.get("date_from"), date_to=request.args.get("date_to"), ) available_count = conn.execute( "SELECT COUNT(*) FROM capture_sessions" ).fetchone()[0] except WifitripError as exc: return jsonify( { "error": str(exc), } ), 400 finally: close_database(conn) return jsonify( { "count": len(session_ids), "available_count": available_count, } ) @app.route("/reports/trips/export") def reports_trips_export(): conn = connect_database() output_path = None try: session_ids = select_wifitrip_session_ids( conn, mode=request.args.get("mode", "all"), limit=request.args.get("limit", "1"), date_from=request.args.get("date_from"), date_to=request.args.get("date_to"), ) if not session_ids: return jsonify( { "error": "No capture sessions match the selected criteria.", } ), 400 filename = ( "wifi-gps-mapper-" f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}.wifitrip" ) temp_file = tempfile.NamedTemporaryFile( prefix="wifitrip-", suffix=".tmp", delete=False, ) temp_path = Path( temp_file.name ) temp_file.close() output_path = temp_path.with_name( filename ) temp_path.unlink( missing_ok=True ) result = export_wifitrip( conn, output_path=output_path, session_ids=session_ids, ) except WifitripError as exc: if output_path is not None: output_path.unlink( missing_ok=True ) return jsonify( { "error": str(exc), } ), 400 except Exception: if output_path is not None: output_path.unlink( missing_ok=True ) raise finally: close_database(conn) response = send_file( output_path, as_attachment=True, download_name=output_path.name, mimetype="application/zip", ) response.headers[ "X-Wifitrip-Sessions" ] = str(result["sessions"]) response.headers[ "X-Wifitrip-Size" ] = str(result["size"]) response.headers[ "X-Wifitrip-Duration" ] = str(result["duration"]) response.call_on_close( lambda: output_path.unlink( missing_ok=True ) ) return response @app.route( "/reports/trips/preflight", methods=["POST"] ) def reports_trips_preflight(): uploaded_file = request.files.get( "wifitrip_file" ) if uploaded_file is None: return jsonify( { "valid": False, "error": "Wifitrip package is required." } ), 400 temp_file = tempfile.NamedTemporaryFile( suffix=".wifitrip", delete=False, ) package_path = Path( temp_file.name ) try: uploaded_file.save( temp_file ) temp_file.close() result = validate_wifitrip( package_path ) return jsonify( result ) except Exception as error: return jsonify( { "valid": False, "error": str(error), } ), 400 finally: if not temp_file.closed: temp_file.close() package_path.unlink( missing_ok=True ) @app.route( "/reports/trips/import", methods=["POST"] ) def reports_trips_import(): uploaded_file = request.files.get( "wifitrip_file" ) if uploaded_file is None: return render_report( render_trips_page, message={ "type": "error", "text": "Wifitrip package is required.", } ), 400 temp_file = tempfile.NamedTemporaryFile( suffix=".wifitrip", delete=False, ) package_path = Path( temp_file.name ) try: uploaded_file.save( temp_file ) temp_file.close() validation = validate_wifitrip( package_path ) if not validation.get("valid"): return render_report( render_trips_page, validation=validation, message={ "type": "error", "text": ( "Import was rejected. " "The package is invalid and " "no sessions were imported." ), } ), 400 conn = connect_database() try: result = import_wifitrip( conn, package_path, ) finally: close_database(conn) if result["failed"]: return render_report( render_trips_page, import_result=result, validation=validation, message={ "type": "error", "text": ( "Import completed with " "failed sessions." ), } ), 400 return render_report( render_trips_page, import_result=result, validation=validation, message={ "type": "success", "text": ( "Import completed successfully." ), } ) except Exception as error: return render_report( render_trips_page, message={ "type": "error", "text": ( "Import failed: " f"{error}" ), } ), 500 finally: if not temp_file.closed: temp_file.close() package_path.unlink( missing_ok=True ) @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): return render_report( render_session_page, session_id ) @app.route("/reports/access-points/") def reports_access_points(): return render_report( render_access_points_page ) @app.route("/reports/access-points/") def reports_access_point(bssid): return render_report( render_access_point_page, bssid ) @app.route("/reports/hashcat/", methods=["GET", "POST"]) @app.route("/reports/hashcat/export", methods=["GET", "POST"]) @app.route("/reports/hashcat/preflight", methods=["GET", "POST"]) @app.route("/reports/hashcat/import", methods=["GET", "POST"]) def reports_hashcat_gone(): abort(404) @app.route("/reports/search/") def reports_search(): return render_report( render_search_page ) @app.route("/reports/search/data") def reports_search_data(): criteria = normalize_criteria( vendor=request.args.get( "vendor", "" ), essid=request.args.get( "essid", "" ), bssid=request.args.get( "bssid", "" ) ) if not criteria: return jsonify( { "error": "At least one search criterion is required." } ), 400 conn = connect_database() try: data = build_search_data( conn, criteria ) return jsonify( data ) except Exception as error: return jsonify( { "error": str(error) } ), 500 finally: close_database(conn) @app.route( "/reports/search/cracklab", methods=["POST"], ) def reports_search_cracklab(): criteria = normalize_criteria( vendor=request.form.get( "vendor", "" ), essid=request.form.get( "essid", "" ), bssid=request.form.get( "bssid", "" ) ) if not criteria: return jsonify( { "error": "At least one search criterion is required." } ), 400 reports_conn = connect_database() cracklab_conn = None try: reports_conn.execute("BEGIN") access_points = search_access_points( reports_conn, criteria ) handshakes = load_handshakes( reports_conn, criteria ) handshake_ids = [ int(handshake["id"]) for items in handshakes.values() for handshake in items ] reports_conn.rollback() if not handshake_ids: return jsonify( { "error": "Search results contain no handshakes or PMKID records." } ), 400 cracklab_conn = connect_cracklab_database() context = SearchContextService( cracklab_conn ).create_context( criteria=criteria, handshake_ids=handshake_ids, matched_access_point_count=len(access_points), ) return jsonify( { "redirect_url": url_for( "cracklab.jobs_page", search_context_token=context["token"], ), "matched_access_point_count": context["matched_access_point_count"], "handshake_count": context["handshake_count"], "expires_at": context["expires_at"], } ) except Exception as error: logger.exception( "Failed to create CrackLab search context." ) return jsonify( { "error": "Unable to create CrackLab search context. " "Please try again later." } ), 500 finally: close_database(reports_conn) if cracklab_conn is not None: cracklab_conn.close() @app.route("/reports/static/") def reports_static(filename): return send_from_directory( PROJECT_ROOT / "reports" / "static", filename ) @app.route("/") def index(): config = read_config() timezone_options = get_timezone_options( config.get("timezone", "Etc/UTC") ) interfaces, interface_error = ( get_wifi_interfaces() ) status = get_scanner_status() gps_test = get_gps_test_status() with scanner_lock: output = list( scanner_output ) return render_template( "index.html", config=config, timezone_options=timezone_options, interfaces=interfaces, interface_error=interface_error, status=status, gps_test=gps_test, output=output ) @app.route( "/api/status" ) def api_status(): status = get_scanner_status() gps_test = get_gps_test_status() busy = network_actions_busy() with scanner_lock: output = list( scanner_output ) return jsonify( { "status": status, "gps_test": gps_test, "network_actions_busy": busy, "output": output } ) @app.route( "/gps-test/start", methods=["POST"] ) def gps_test_start(): global gps_test_service with scanner_lock: acquired, error = _acquire_network_owner_locked( "GPS_TEST" ) if not acquired: return jsonify( { "ok": False, "error": error } ), 409 with gps_test_lock: try: cfg = Config() gps_test_service = GPSTestService( cfg, callback=gps_test_output ) if not gps_test_service.start(): gps_test_service = None _release_network_owner_locked( "GPS_TEST" ) return jsonify( { "ok": False, "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: {error}" ) return jsonify( { "ok": False, "error": str(error) } ), 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 } ) @app.route( "/gps-test/stop", methods=["POST"] ) def gps_test_stop(): with gps_test_lock: service = gps_test_service if ( service is None or not service.running ): return jsonify( { "ok": False, "error": "GPS test is not running." } ), 409 service.stop() if ( service.thread is not None and service.thread is not threading.current_thread() ): service.thread.join( timeout=2 ) with scanner_lock: scanner_output.append( "[GUI] GPS test stop requested." ) return jsonify( { "ok": True } ) @app.route( "/api/gps-test" ) def api_gps_test(): return jsonify( 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" ) def api_network_wifi_devices(): devices, error = get_nm_wifi_devices() vpn_active, vpn_error = get_active_vpn_status() if error: return jsonify( { "ok": False, "devices": [], "selected_device": None, "error": error } ), 503 for device in devices: state = device["state"] managed = device["managed"] device["available"] = False device["reason"] = None if managed is False: device["reason"] = ( "NetworkManager is not managing this device." ) elif managed is None: device["reason"] = ( "Could not determine whether " "NetworkManager manages this device." ) elif state == "unavailable": device["reason"] = ( "Wi-Fi device is unavailable. " "Check hardware switch, rfkill or driver." ) elif state == "unmanaged": device["reason"] = ( "Wi-Fi device is unmanaged." ) elif state not in ("connected", "disconnected"): device["reason"] = ( f"Wi-Fi device is not ready. State: {state}" ) else: device["available"] = True selected_device = None if len(devices) == 1: selected_device = devices[0]["device"] return jsonify( { "ok": True, "devices": devices, "selected_device": selected_device, "selection_required": len(devices) > 1, "error": ( "No Wi-Fi interfaces found." if not devices else None ), "vpn_active": vpn_active, "vpn_error": vpn_error } ) def validate_network_interface(interface): devices, error = get_nm_wifi_devices() if error: return None, error, 503 if not devices: return None, "No Wi-Fi interfaces found.", 400 device = next( ( item for item in devices if item["device"] == interface ), None ) if device is None: return None, "The selected Wi-Fi interface was not found.", 400 if device["managed"] is not True: return None, "NetworkManager is not managing this Wi-Fi interface.", 409 if device["state"] == "unavailable": return None, "Wi-Fi interface is unavailable. Check hardware switch, rfkill or driver.", 409 if device["state"] == "unmanaged": return None, "Wi-Fi interface is unmanaged.", 409 if device["state"] not in ("connected", "disconnected"): return None, f"Wi-Fi interface is not ready. State: {device['state']}", 409 return device, None, None def get_network_credential( bssid, password, verified_only=False ): conn = connect_database() try: query = """ SELECT ap.id AS access_point_id, c.id AS credential_id FROM access_points AS ap JOIN credentials AS c ON c.access_point_id = ap.id WHERE lower(ap.bssid) = lower(?) AND c.password = ? """ if verified_only: query += " AND c.verified = 1" query += " LIMIT 1" return conn.execute( query, ( bssid, password ) ).fetchone() finally: close_database(conn) def mark_network_credential_verified( access_point_id, password ): conn = connect_database() try: cursor = conn.execute( """ UPDATE credentials SET verified = 1 WHERE access_point_id = ? AND password = ? """, ( access_point_id, password ) ) if cursor.rowcount == 0: raise WiFiConnectionError( "The credential no longer exists in the database." ) conn.commit() except Exception: conn.rollback() raise finally: close_database(conn) def get_network_vpn_warning(): vpn_active, error = get_active_vpn_status() if vpn_active: return ( "Обнаружено активное VPN-подключение. " "Для надёжной проверки пароля и подключения " "рекомендуется временно отключить VPN. " "Продолжить можно, но успешная работа не гарантируется." ) if error: return ( "Не удалось достоверно определить состояние VPN. " "При активном VPN результат проверки пароля " "или подключения не гарантируется. " "Рекомендуется проверить состояние VPN вручную." ) return None @app.route( "/api/network/verify", methods=["POST"] ) def api_network_wifi_verify(): 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") bssid = data.get("bssid") password = data.get("password") if ( not isinstance(interface, str) or not interface.strip() or not isinstance(bssid, str) or not bssid.strip() or not isinstance(password, str) or not password ): return jsonify( { "ok": False, "error": "Interface, BSSID and password are required." } ), 400 interface = interface.strip() bssid = bssid.strip() acquired, error = begin_network_action() if not acquired: return jsonify( { "ok": False, "error": error } ), 409 try: device, error, status = validate_network_interface( interface ) if error: return jsonify( { "ok": False, "error": error } ), status credential = get_network_credential( bssid, password ) if credential is None: return jsonify( { "ok": False, "error": "The specified password was not found for this access point." } ), 404 result = wifi_connection_service.verify( interface, bssid, password ) if not result.get("success"): return jsonify( { "ok": False, "success": False, "error": result.get("error") or "Wi-Fi verification failed." } ), 401 mark_network_credential_verified( credential["access_point_id"], password ) return jsonify( { "ok": True, "success": True, "interface": result["interface"], "bssid": result["bssid"], "ssid": result["ssid"], "verified": True, "vpn_warning": get_network_vpn_warning() } ) except WiFiConnectionError as error: return jsonify( { "ok": False, "error": str(error) } ), 502 except Exception: logger.exception( "Wi-Fi password verification API failed." ) return jsonify( { "ok": False, "error": "An internal error occurred during Wi-Fi verification." } ), 500 finally: end_network_action() @app.route( "/api/network/connect", methods=["POST"] ) def api_network_wifi_connect(): 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") bssid = data.get("bssid") password = data.get("password") if ( not isinstance(interface, str) or not interface.strip() or not isinstance(bssid, str) or not bssid.strip() or ( password is not None and not isinstance(password, str) ) ): return jsonify( { "ok": False, "error": "A valid interface and BSSID are required." } ), 400 interface = interface.strip() bssid = bssid.strip() acquired, error = begin_network_action() if not acquired: return jsonify( { "ok": False, "error": error } ), 409 try: device, error, status = validate_network_interface( interface ) if error: return jsonify( { "ok": False, "error": error } ), status access_point = wifi_connection_service.get_access_point( interface, bssid ) if not access_point.is_open: if not isinstance(password, str) or not password: return jsonify( { "ok": False, "error": "A password is required for this secured access point." } ), 400 credential = get_network_credential( bssid, password, verified_only=True ) if credential is None: return jsonify( { "ok": False, "error": "This password has not been successfully verified for this access point." } ), 403 else: password = None result = wifi_connection_service.connect( interface, bssid, password, access_point=access_point ) return jsonify( { "ok": True, "success": True, "interface": result["interface"], "bssid": result["bssid"], "ssid": result["ssid"], "is_open": result["is_open"], "vpn_warning": get_network_vpn_warning() } ) except WiFiConnectionError as error: return jsonify( { "ok": False, "error": str(error) } ), 502 except Exception: logger.exception( "Wi-Fi connection API failed." ) return jsonify( { "ok": False, "error": "An internal error occurred during Wi-Fi connection." } ), 500 finally: end_network_action() @app.route( "/api/wifi/channels" ) def api_wifi_channels(): interface = request.args.get( "interface", "" ).strip() if not interface: return jsonify( { "2.4": [], "5": [], "6": [], "error": "WiFi interface was not selected." } ), 400 interfaces, interface_error = ( get_wifi_interfaces() ) if interface_error: return jsonify( { "2.4": [], "5": [], "6": [], "error": interface_error } ), 500 if interface not in interfaces: return jsonify( { "2.4": [], "5": [], "6": [], "error": "Invalid WiFi interface." } ), 400 return jsonify( get_wifi_channels(interface) ) @app.route( "/config/save", methods=["POST"] ) def config_save(): if get_scanner_status()["running"]: with scanner_lock: scanner_output.append( "[GUI] Configuration cannot be " "saved while scanner is running." ) return jsonify( { "ok": False, "error": "Configuration cannot be saved " "while scanner is running." } ), 409 if get_gps_test_status()["running"]: with scanner_lock: scanner_output.append( "[GUI] Configuration cannot be " "saved while GPS test is running." ) return jsonify( { "ok": False, "error": "Configuration cannot be saved " "while GPS test is running." } ), 409 try: data = request.get_json( silent=True ) if not data: raise RuntimeError( "No configuration data received." ) save_config(data) with scanner_lock: scanner_output.append( "[GUI] Configuration saved." ) return jsonify( { "ok": True, "message": "Configuration saved successfully." } ) except Exception as error: with scanner_lock: scanner_output.append( f"[GUI] Failed to save configuration: " f"{error}" ) return jsonify( { "ok": False, "error": str(error) } ), 500 @app.route( "/scanner/start", methods=["POST"] ) def scanner_start(): global scanner_process global scanner_output_thread global scanner_health global scanner_stopped_at global scanner_starting with scanner_lock: acquired, error = _acquire_network_owner_locked( "SCANNER" ) if not acquired: scanner_output.append( f"[GUI] Scanner cannot start: {error}" ) return redirect( url_for("index") ) scanner_starting = True interface = request.form.get( "interface", "" ).strip() if not interface: with scanner_lock: scanner_starting = False _release_network_owner_locked( "SCANNER" ) scanner_output.append( "[GUI] WiFi interface was not selected." ) return redirect( url_for("index") ) environment = os.environ.copy() environment[ "WIFI_INTERFACE" ] = interface command = [ 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: with scanner_lock: scanner_starting = False _release_network_owner_locked( "SCANNER" ) scanner_output.append( f"[GUI] Failed to start scanner: {error}" ) return redirect( url_for("index") ) with scanner_lock: scanner_process = process scanner_starting = False scanner_health = "ACTIVE" scanner_stopped_at = None scanner_output.clear() scanner_output.append( "[GUI] Scanner started." ) scanner_output.append( f"[GUI] PID: {process.pid}" ) scanner_output.append( f"[GUI] Interface: {interface}" ) scanner_output_thread = threading.Thread( target=read_scanner_output, args=(process,), daemon=True ) 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") ) @app.route( "/scanner/stop", methods=["POST"] ) def scanner_stop(): global scanner_health with scanner_lock: process = scanner_process if ( process is None or process.poll() is not None ): return redirect( url_for("index") ) scanner_health = "STOPPING" scanner_output.append( "[GUI] SIGINT sent to scanner." ) try: os.killpg( process.pid, signal.SIGINT ) except Exception as error: with scanner_lock: scanner_health = "ACTIVE" scanner_output.append( f"[GUI] Failed to stop scanner: {error}" ) return redirect( url_for("index") ) if __name__ == "__main__": print( "Checking sudo privileges..." ) if not check_sudo(): print( "sudo authentication failed." ) raise SystemExit(1) print( "sudo: OK" ) sudo_keepalive_thread = threading.Thread( target=sudo_keepalive, args=(sudo_keepalive_stop_event,), daemon=True ) sudo_keepalive_thread.start() logging.getLogger("werkzeug").disabled = True app.run( host="127.0.0.1", port=5000, debug=False )