Files
T

3718 lines
76 KiB
Python

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 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 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():
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
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()
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 network_actions_busy():
with scanner_lock:
if (
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():
global network_action_active
with scanner_lock:
if network_action_active:
return False, "Another Wi-Fi connection operation is in progress."
if (
scanner_starting
or
(
scanner_process is not None
and
scanner_process.poll() is None
)
):
return False, "Wi-Fi operation is unavailable while the scanner is running."
with gps_test_lock:
if (
gps_test_service is not None
and
gps_test_service.thread is not None
and
gps_test_service.thread.is_alive()
):
return False, "Wi-Fi operation is unavailable while the GPS test is running."
network_action_active = True
return True, None
def end_network_action():
global network_action_active
with scanner_lock:
network_action_active = False
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
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_wireguard_connections():
command = [
"nmcli",
"--terse",
"--escape",
"yes",
"--fields",
"TYPE,DEVICE",
"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 [], str(error)
if result.returncode != 0:
error = (
result.stderr.strip()
or
f"nmcli exited with code {result.returncode}"
)
return [], error
wireguard_connections = []
for line in result.stdout.splitlines():
parts = line.split(":", 1)
if len(parts) != 2:
continue
connection_type, device = parts
if connection_type == "wireguard":
wireguard_connections.append(
{
"type": connection_type,
"device": device
}
)
return wireguard_connections, None
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/<job_id>"
)
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/<job_id>"
)
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("/reports/session/<int:session_id>")
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/<bssid>")
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/<path:filename>")
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:
if network_action_active:
return jsonify(
{
"ok": False,
"error":
"A Wi-Fi connection operation is in progress."
}
), 409
if (
scanner_starting
or
(
scanner_process is not None
and
scanner_process.poll() is None
)
):
scanner_output.append(
"[GUI] GPS test cannot start "
"while scanner is running."
)
return jsonify(
{
"ok": False,
"error":
"GPS test cannot start "
"while scanner is running."
}
), 409
with gps_test_lock:
if (
gps_test_service is not None
and
gps_test_service.thread is not None
and
gps_test_service.thread.is_alive()
):
return jsonify(
{
"ok": False,
"error":
"GPS test is already running."
}
), 409
try:
cfg = Config()
gps_test_service = GPSTestService(
cfg,
callback=gps_test_output
)
if not gps_test_service.start():
gps_test_service = None
return jsonify(
{
"ok": False,
"error":
"Failed to start GPS test."
}
), 500
except Exception as error:
gps_test_service = None
scanner_output.append(
f"[GUI] Failed to start GPS test: "
f"{error}"
)
return jsonify(
{
"ok": False,
"error": str(error)
}
), 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/network/wifi-devices"
)
def api_network_wifi_devices():
devices, error = get_nm_wifi_devices()
wireguard_connections, wireguard_error = (
get_active_wireguard_connections()
)
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
),
"wireguard_active": bool(wireguard_connections),
"wireguard_connections": wireguard_connections,
"wireguard_error": wireguard_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_wireguard_warning():
connections, error = get_active_wireguard_connections()
if connections:
return (
"An active WireGuard VPN connection was detected. "
"For security and reliable local network access, "
"manually disconnect the VPN if necessary."
)
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,
"wireguard_warning": get_network_wireguard_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"],
"wireguard_warning": get_network_wireguard_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:
if network_action_active:
scanner_output.append(
"[GUI] Scanner cannot start "
"while a Wi-Fi connection operation is in progress."
)
return redirect(
url_for("index")
)
if (
scanner_starting
or
(
scanner_process is not None
and
scanner_process.poll() is None
)
):
return redirect(
url_for("index")
)
with gps_test_lock:
if (
gps_test_service is not None
and
gps_test_service.thread is not None
and
gps_test_service.thread.is_alive()
):
scanner_output.append(
"[GUI] Scanner cannot start "
"while GPS test is running."
)
return redirect(
url_for("index")
)
scanner_starting = True
interface = request.form.get(
"interface",
""
).strip()
if not interface:
with scanner_lock:
scanner_starting = False
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
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
)
scanner_output_thread.start()
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
)