Release WiFi GPS Mapper v2.1.0

This commit is contained in:
2026-11-30 00:24:44 +03:00
parent cb2e659a57
commit 08bb7f5c45
13 changed files with 8454 additions and 276 deletions
+636
View File
@@ -0,0 +1,636 @@
import logging
import re
import select
import socket
import subprocess
import threading
import time
from datetime import datetime, timezone
from logging.handlers import RotatingFileHandler
from pathlib import Path
from gps import GPSRelaySource, GpsdSource, parse_nmea
from logging_config import (
LOG_DATE_FORMAT,
LOG_FORMAT,
UTCFormatter,
)
PROJECT_ROOT = Path(__file__).resolve().parent.parent
POLL_INTERVAL_SECONDS = 0.5
RECONNECT_DELAY_SECONDS = 2.0
CONNECT_TIMEOUT_SECONDS = 3.0
GPSD_GREETING_MAX_BYTES = 65536
LOG_MAX_BYTES = 5 * 1024 * 1024
LOG_BACKUP_COUNT = 3
def _create_logger():
logger = logging.getLogger(
"wifi-gps-mapper.auto-verification"
)
logger.setLevel(logging.INFO)
logger.propagate = False
if not logger.handlers:
log_dir = PROJECT_ROOT / "logs"
log_dir.mkdir(
parents=True,
exist_ok=True
)
handler = RotatingFileHandler(
log_dir / "auto-verification.log",
maxBytes=LOG_MAX_BYTES,
backupCount=LOG_BACKUP_COUNT,
encoding="utf-8"
)
handler.setFormatter(
UTCFormatter(
LOG_FORMAT,
datefmt=LOG_DATE_FORMAT
)
)
logger.addHandler(handler)
return logger
def _get_gpsd_port():
"""Получает IPv4 TCP-порт из активной конфигурации gpsd.socket."""
try:
result = subprocess.run(
[
"systemctl",
"show",
"gpsd.socket",
"--property=Listen",
"--value",
],
check=True,
capture_output=True,
text=True,
timeout=3,
)
except (OSError, subprocess.SubprocessError) as error:
raise RuntimeError(
f"Cannot read gpsd.socket configuration: {error}"
) from error
ports = set()
for line in result.stdout.splitlines():
endpoint = line.strip()
if "=" in endpoint:
endpoint = endpoint.split("=", 1)[1].strip()
match = re.fullmatch(
r"(?:127\.0\.0\.1|0\.0\.0\.0):(\d+)(?:\s+\(Stream\))?",
endpoint,
)
if match:
port = int(match.group(1))
if not 1 <= port <= 65535:
raise RuntimeError(
f"Invalid GPSD TCP port: {port}"
)
ports.add(port)
if not ports:
raise RuntimeError(
"No IPv4 TCP listener found in gpsd.socket"
)
if len(ports) != 1:
raise RuntimeError(
"gpsd.socket has multiple different IPv4 TCP ports: "
+ ", ".join(str(port) for port in sorted(ports))
)
return ports.pop()
logger = _create_logger()
class AutoGPSService:
def __init__(
self,
settings,
callback=None,
fix_callback=None,
position_callback=None
):
self.settings = dict(settings or {})
self.callback = callback
self.fix_callback = fix_callback
self.position_callback = position_callback
self.gps_source = self.settings.get("gps_source")
self.max_age_seconds = float(
self.settings.get(
"gnss_max_age_seconds",
10
)
)
if self.max_age_seconds <= 0:
raise ValueError(
"gnss_max_age_seconds must be positive"
)
if self.gps_source not in ("gpsd", "gpsrelay"):
raise ValueError(
"Auto GPS source must be 'gpsd' or 'gpsrelay'"
)
if self.gps_source == "gpsrelay":
host = self.settings.get("gpsrelay_host")
port = self.settings.get("gpsrelay_port")
if not isinstance(host, str) or not host.strip():
raise ValueError(
"GPS Relay host is required"
)
if (
isinstance(port, bool)
or not isinstance(port, int)
or not 1 <= port <= 65535
):
raise ValueError(
"GPS Relay port must be between 1 and 65535"
)
self.thread = None
self.stop_event = threading.Event()
self.source = None
self.source_lock = threading.Lock()
self.state_lock = threading.Lock()
self.running = False
self.state = "READY"
self.error = None
self.current_fix = None
self.last_fix_monotonic = None
self.connected_monotonic = None
def _emit(
self,
level,
code,
message
):
event = {
"level": level,
"code": code,
"message": message,
"state": self.state,
"timestamp": datetime.now(
timezone.utc
).isoformat()
}
log_method = getattr(
logger,
level.lower(),
logger.info
)
log_method(message)
if self.callback is not None:
try:
self.callback(event)
except Exception:
logger.exception(
"Auto GPS callback failed"
)
def _set_state(self, state):
with self.state_lock:
self.state = state
def _create_source(self):
if self.gps_source == "gpsd":
return GpsdSource(
host="127.0.0.1",
port=_get_gpsd_port()
)
if self.gps_source == "gpsrelay":
return GPSRelaySource(
self.settings["gpsrelay_host"].strip(),
self.settings["gpsrelay_port"]
)
raise ValueError(
f"Unsupported Auto GPS source: {self.gps_source}"
)
def _open_source(self, source):
# Поддержка тестовых источников с заранее созданным сокетом.
if getattr(source, "socket", None) is not None:
stream = source.open()
return source.socket, stream, b""
connection = socket.create_connection(
(source.host, source.port),
timeout=CONNECT_TIMEOUT_SECONDS
)
# Сохраняем сокет сразу после подключения, чтобы stop()
# мог закрыть его во время дальнейшей инициализации.
source.socket = connection
connection.settimeout(CONNECT_TIMEOUT_SECONDS)
pending = b""
if self.gps_source == "gpsd":
greeting = bytearray()
handshake_deadline = (
time.monotonic() + CONNECT_TIMEOUT_SECONDS
)
while b"\n" not in greeting:
if self.stop_event.is_set():
raise ConnectionError(
"Auto GPS stopped during GPSD handshake"
)
remaining = (
handshake_deadline - time.monotonic()
)
if remaining <= 0:
raise TimeoutError(
"GPSD handshake timed out"
)
connection.settimeout(remaining)
chunk = connection.recv(4096)
if not chunk:
raise ConnectionError(
"GPSD closed the connection during handshake"
)
greeting.extend(chunk)
if len(greeting) > GPSD_GREETING_MAX_BYTES:
raise ConnectionError(
"GPSD greeting exceeds the allowed size"
)
greeting_end = greeting.find(b"\n") + 1
pending = bytes(greeting[greeting_end:])
connection.sendall(
b'?WATCH={"enable":true,"json":false,"nmea":true};\n'
)
connection.setblocking(False)
return connection, None, pending
def start(self):
if (
self.thread is not None
and self.thread.is_alive()
):
return False
self.stop_event.clear()
with self.state_lock:
self.running = True
self.state = "STARTING"
self.error = None
self.current_fix = None
self.last_fix_monotonic = None
self.connected_monotonic = None
self.thread = threading.Thread(
target=self.worker,
name="auto-gps",
daemon=True
)
self.thread.start()
self._emit(
"INFO",
"GPS_STARTED",
f"Auto GPS started with source: {self.gps_source}"
)
return True
def stop(self):
self.stop_event.set()
with self.source_lock:
source = self.source
if source is not None:
connection = getattr(
source,
"socket",
None
)
if connection is not None:
try:
connection.shutdown(socket.SHUT_RDWR)
except OSError:
pass
try:
source.close()
except Exception:
logger.exception(
"Auto GPS source close failed"
)
def _set_fix(self, gps):
now = time.monotonic()
with self.state_lock:
had_fresh_fix = (
self.current_fix is not None
and self.last_fix_monotonic is not None
and now - self.last_fix_monotonic
<= self.max_age_seconds
)
self.current_fix = gps
self.last_fix_monotonic = now
self.state = "FIX"
self.error = None
if not had_fresh_fix:
self._emit(
"INFO",
"GPS_FIX_RESTORED",
"Auto GPS has a fresh valid FIX: "
f"lat={gps.latitude:.6f}, "
f"lon={gps.longitude:.6f}"
)
if self.fix_callback is not None:
try:
self.fix_callback(gps)
except Exception:
logger.exception(
"Auto GPS FIX callback failed"
)
if self.position_callback is not None:
try:
self.position_callback(gps)
except Exception:
logger.exception(
"Auto GPS position callback failed"
)
def _check_fix_freshness(self):
now = time.monotonic()
with self.state_lock:
if self.state in ("STOPPED", "RECONNECTING"):
return
reference = (
self.last_fix_monotonic
if self.last_fix_monotonic is not None
else self.connected_monotonic
)
if reference is None:
return
age = now - reference
if age <= self.max_age_seconds:
return
if self.state == "NO_FIX":
return
self.current_fix = None
self.state = "NO_FIX"
self._emit(
"WARNING",
"GPS_FIX_LOST",
"Auto GPS has no fresh valid FIX. "
f"Last valid position age: {age:.1f} seconds."
)
def get_status(self):
now = time.monotonic()
with self.state_lock:
fix = self.current_fix
last_fix = self.last_fix_monotonic
state = self.state
error = self.error
age = (
now - last_fix
if last_fix is not None
else None
)
fresh = (
fix is not None
and age is not None
and age <= self.max_age_seconds
and state == "FIX"
)
return {
"running": self.running,
"source": self.gps_source,
"state": state,
"has_fresh_fix": fresh,
"latitude": (
fix.latitude
if fresh
else None
),
"longitude": (
fix.longitude
if fresh
else None
),
"fix_age_seconds": age,
"max_age_seconds": self.max_age_seconds,
"error": error
}
def worker(self):
try:
while not self.stop_event.is_set():
source = None
stream = None
try:
source = self._create_source()
with self.source_lock:
self.source = source
if self.stop_event.is_set():
break
self._set_state("CONNECTING")
logger.info(
"Connecting Auto GPS to %s",
self.gps_source
)
connection, stream, pending = self._open_source(
source
)
if self.stop_event.is_set():
break
with self.state_lock:
self.connected_monotonic = time.monotonic()
self.state = "CONNECTED"
self.error = None
self._emit(
"INFO",
"GPS_CONNECTED",
f"Auto GPS connected to {self.gps_source}"
)
while not self.stop_event.is_set():
# Сначала обрабатываем уже полученные строки.
# Это исключает зависимость от готовности сокета,
# когда данные остались во внутреннем буфере.
while b"\n" in pending:
line, pending = pending.split(b"\n", 1)
gps = parse_nmea(
line.decode("ascii", errors="replace").strip(),
datetime.now(timezone.utc)
)
if gps is not None:
self._set_fix(gps)
else:
self._check_fix_freshness()
if len(pending) > GPSD_GREETING_MAX_BYTES:
raise ConnectionError(
"NMEA receive buffer exceeds the allowed size"
)
readable, _, _ = select.select(
[connection],
[],
[],
POLL_INTERVAL_SECONDS
)
if not readable:
self._check_fix_freshness()
continue
chunk = connection.recv(4096)
if not chunk:
raise ConnectionError(
"GPS source closed the NMEA stream"
)
pending += chunk
except Exception as error:
if self.stop_event.is_set():
break
with self.state_lock:
self.current_fix = None
self.state = "RECONNECTING"
self.error = str(error)
self._emit(
"WARNING",
"GPS_CONNECTION_LOST",
"Auto GPS connection lost: "
f"{error}. Reconnecting to the same source."
)
finally:
if stream is not None:
try:
stream.close()
except Exception:
logger.exception(
"Auto GPS stream close failed"
)
if source is not None:
try:
source.close()
except Exception:
logger.exception(
"Auto GPS source close failed"
)
with self.source_lock:
if self.source is source:
self.source = None
if not self.stop_event.is_set():
self.stop_event.wait(
RECONNECT_DELAY_SECONDS
)
except Exception as error:
with self.state_lock:
self.error = str(error)
self.state = "ERROR"
self._emit(
"ERROR",
"GPS_SERVICE_ERROR",
f"Auto GPS service error: {error}"
)
finally:
with self.state_lock:
self.current_fix = None
self.running = False
was_error = self.state == "ERROR"
if not was_error:
self.state = "STOPPED"
if not was_error:
self._emit(
"INFO",
"GPS_STOPPED",
"Auto GPS service stopped"
)
File diff suppressed because it is too large Load Diff
+351
View File
@@ -7,6 +7,202 @@ from pathlib import Path
from datetime import datetime, timezone
def _migrate_wifi_verification(conn):
conn.execute("""
CREATE TABLE IF NOT EXISTS wifi_verification_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
radius_options TEXT NOT NULL
DEFAULT '[25,50,100,200,300]',
radius_m INTEGER NOT NULL DEFAULT 100
CHECK (radius_m > 0),
gnss_max_age_seconds INTEGER NOT NULL DEFAULT 5
CHECK (gnss_max_age_seconds > 0),
queue_retry_passes INTEGER NOT NULL DEFAULT 1
CHECK (queue_retry_passes >= 0),
updated_at TEXT NOT NULL
DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
)
""")
conn.execute("""
INSERT OR IGNORE INTO wifi_verification_settings (
id
)
VALUES (1)
""")
columns = {
row[1]
for row in conn.execute(
"PRAGMA table_info(wifi_verification_settings)"
)
}
if "retry_interval_seconds" in columns:
conn.execute("""
ALTER TABLE wifi_verification_settings
DROP COLUMN retry_interval_seconds
""")
if "gps_source" not in columns:
conn.execute("""
ALTER TABLE wifi_verification_settings
ADD COLUMN gps_source TEXT
CHECK (gps_source IN ('gpsd', 'gpsrelay'))
""")
columns = {
row[1]
for row in conn.execute(
"PRAGMA table_info(wifi_verification_settings)"
)
}
if "gpsrelay_host" not in columns:
conn.execute("""
ALTER TABLE wifi_verification_settings
ADD COLUMN gpsrelay_host TEXT
CHECK (
gpsrelay_host IS NULL
OR length(trim(gpsrelay_host)) > 0
)
""")
if "gpsrelay_port" not in columns:
conn.execute("""
ALTER TABLE wifi_verification_settings
ADD COLUMN gpsrelay_port INTEGER
CHECK (
gpsrelay_port IS NULL
OR gpsrelay_port BETWEEN 1 AND 65535
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS wifi_verification_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
started_at TEXT NOT NULL,
finished_at TEXT,
status TEXT NOT NULL
CHECK (
status IN (
'RUNNING',
'PAUSED_GNSS',
'PAUSED_QUEUE',
'STOPPED',
'ERROR'
)
),
radius_m INTEGER NOT NULL,
interface_name TEXT NOT NULL,
access_points_total INTEGER NOT NULL DEFAULT 0,
attempts_total INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
invalid_password_count INTEGER NOT NULL DEFAULT 0,
technical_error_count INTEGER NOT NULL DEFAULT 0
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS wifi_verification_attempts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
credential_id INTEGER,
session_id INTEGER,
verification_mode TEXT NOT NULL
CHECK (
verification_mode IN ('MANUAL', 'AUTO')
),
status TEXT NOT NULL
CHECK (
status IN (
'SUCCESS',
'INVALID_PASSWORD',
'AP_NOT_FOUND',
'CONNECTION_TIMEOUT',
'NETWORK_ERROR',
'UNKNOWN_ERROR',
'CANCELLED'
)
),
started_at TEXT NOT NULL,
finished_at TEXT,
interface_name TEXT,
bssid TEXT,
error_code TEXT,
error_message TEXT,
FOREIGN KEY (credential_id)
REFERENCES credentials(id)
ON DELETE SET NULL,
FOREIGN KEY (session_id)
REFERENCES wifi_verification_sessions(id)
ON DELETE SET NULL
)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS
idx_wifi_verification_sessions_started
ON wifi_verification_sessions(started_at)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS
idx_wifi_verification_attempts_session
ON wifi_verification_attempts(session_id, started_at)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS
idx_wifi_verification_attempts_credential
ON wifi_verification_attempts(credential_id, started_at)
""")
def migrate_wifi_verification_database(db_path):
"""Запускает только миграцию схемы Auto Verification."""
conn = sqlite3.connect(db_path)
try:
_migrate_wifi_verification(conn)
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
class Database:
@@ -382,8 +578,15 @@ class Database:
self._migrate_session_hash()
self._migrate_wifi_verification()
self.conn.commit()
def _migrate_wifi_verification(self):
_migrate_wifi_verification(self.conn)
def _migrate_credentials_table(
self
):
@@ -984,6 +1187,154 @@ class Database:
return True
# =========================================================
# Wi-Fi verification settings
# =========================================================
def get_wifi_verification_settings(self):
row = self.conn.execute(
"""
SELECT *
FROM wifi_verification_settings
WHERE id=1
"""
).fetchone()
if row is None:
return None
return dict(row)
def update_wifi_verification_settings(
self,
settings
):
if not isinstance(settings, dict):
raise ValueError("Настройки должны быть словарём.")
allowed = (
"gps_source",
"gpsrelay_host",
"gpsrelay_port",
"radius_options",
"radius_m",
"gnss_max_age_seconds",
"queue_retry_passes"
)
unknown = set(settings) - set(allowed)
if unknown:
raise ValueError(
"Неизвестные настройки: "
+ ", ".join(sorted(unknown))
)
if not settings:
raise ValueError("Не переданы настройки для обновления.")
values = dict(settings)
if "gps_source" in values:
if values["gps_source"] not in (None, "gpsd", "gpsrelay"):
raise ValueError("Недопустимый источник GPS.")
if "gpsrelay_host" in values:
host = values["gpsrelay_host"]
if host is not None:
if not isinstance(host, str) or not host.strip():
raise ValueError("Некорректный адрес GPS Relay.")
values["gpsrelay_host"] = host.strip()
if "gpsrelay_port" in values:
port = values["gpsrelay_port"]
if port is not None:
if (
isinstance(port, bool)
or not isinstance(port, int)
or not 1 <= port <= 65535
):
raise ValueError("Порт GPS Relay должен быть от 1 до 65535.")
integer_limits = {
"radius_m": 1,
"gnss_max_age_seconds": 1,
"queue_retry_passes": 0
}
for name, minimum in integer_limits.items():
if name not in values:
continue
value = values[name]
if (
isinstance(value, bool)
or not isinstance(value, int)
or value < minimum
):
raise ValueError(
f"Некорректное значение настройки {name}."
)
if "radius_options" in values:
options = values["radius_options"]
if isinstance(options, str):
try:
options = json.loads(options)
except (TypeError, ValueError):
raise ValueError("radius_options должен содержать JSON-массив.")
if (
not isinstance(options, (list, tuple))
or not options
or any(
isinstance(value, bool)
or not isinstance(value, int)
or value <= 0
for value in options
)
or len(set(options)) != len(options)
):
raise ValueError("Некорректный список radius_options.")
values["radius_options"] = json.dumps(
list(options),
separators=(",", ":")
)
assignments = [
f"{name}=?"
for name in allowed
if name in values
]
parameters = [
values[name]
for name in allowed
if name in values
]
self.conn.execute(
f"""
UPDATE wifi_verification_settings
SET
{", ".join(assignments)},
updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
WHERE id=1
""",
parameters
)
return self.get_wifi_verification_settings()
# =========================================================
# Access points
# =========================================================
+59
View File
@@ -289,6 +289,63 @@ def wait_for_scanner(app_module):
log("Сканер и поток чтения его вывода завершены.")
def stop_auto_gps(app_module):
with app_module.auto_gps_lock:
service = app_module.auto_gps_service
if service is None:
return
thread = service.thread
if thread is None or not thread.is_alive():
return
log("Останавливается Auto GPS.")
service.stop()
if thread is not threading.current_thread():
thread.join(timeout=5)
if thread.is_alive():
log(
"Предупреждение: поток Auto GPS не завершился "
"за отведённое время."
)
else:
log("Auto GPS завершён.")
def stop_auto_wifi_verification(app_module):
with app_module.auto_wifi_verification_lock:
service = app_module.auto_wifi_verification_service
if service is None:
return
thread = service.thread
if thread is None or not thread.is_alive():
return
log("Останавливается автоматическая проверка Wi-Fi.")
service.stop()
if thread is not threading.current_thread():
thread.join(timeout=5)
if thread.is_alive():
log(
"Предупреждение: поток автоматической проверки Wi-Fi "
"не завершился за отведённое время."
)
else:
log("Автоматическая проверка Wi-Fi завершена.")
def stop_gps_test(app_module):
with app_module.gps_test_lock:
service = app_module.gps_test_service
@@ -597,6 +654,8 @@ def run_server():
log("Ожидание завершения активных HTTP-запросов.")
app_module.request_lifecycle.wait_for_drain()
stop_auto_wifi_verification(app_module)
stop_auto_gps(app_module)
stop_gps_test(app_module)
wait_for_scanner(app_module)
join_background_threads(app_module)
+667 -78
View File
@@ -27,20 +27,44 @@ class WiFiConnectionError(RuntimeError):
pass
class NetworkCommandError(WiFiConnectionError):
class APNotFoundError(WiFiConnectionError):
pass
class NetworkCommandError(WiFiConnectionError):
def __init__(
self,
message,
returncode=None,
stdout="",
stderr="",
timed_out=False
):
super().__init__(message)
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
self.timed_out = timed_out
class UnsupportedSecurityError(WiFiConnectionError):
pass
class NetworkRestoreError(WiFiConnectionError):
pass
class NetworkCleanupError(WiFiConnectionError):
pass
class PasswordFileCleanupError(WiFiConnectionError):
pass
@dataclass(frozen=True)
class AccessPoint:
bssid: str
@@ -49,6 +73,7 @@ class AccessPoint:
wpa_flags: int
rsn_flags: int
key_mgmt: str | None
strength: int | None = None
@property
def is_open(self):
@@ -125,8 +150,20 @@ class WiFiConnectionService:
except subprocess.TimeoutExpired as error:
stdout = error.stdout or error.output or ""
stderr = error.stderr or ""
if isinstance(stdout, bytes):
stdout = stdout.decode(errors="replace")
if isinstance(stderr, bytes):
stderr = stderr.decode(errors="replace")
raise NetworkCommandError(
"NetworkManager command timed out."
"NetworkManager command timed out.",
stdout=stdout,
stderr=stderr,
timed_out=True
) from error
except OSError as error:
@@ -145,7 +182,12 @@ class WiFiConnectionService:
f"Command exited with code {result.returncode}."
)
raise NetworkCommandError(message)
raise NetworkCommandError(
message,
returncode=result.returncode,
stdout=result.stdout,
stderr=result.stderr
)
return result.stdout.strip()
@@ -320,6 +362,39 @@ class WiFiConnectionService:
f"Invalid value for {property_name}."
) from error
def _get_byte_property(
self,
object_path,
property_name
):
parts = self._get_property(
object_path,
NM_ACCESS_POINT,
property_name
)
if len(parts) != 2 or parts[0] != "y":
raise WiFiConnectionError(
f"Unexpected D-Bus type for {property_name}."
)
try:
value = int(parts[1])
except ValueError as error:
raise WiFiConnectionError(
f"Invalid value for {property_name}."
) from error
if not 0 <= value <= 100:
raise WiFiConnectionError(
f"Value for {property_name} is outside the valid range."
)
return value
def _get_ssid(self, object_path):
parts = self._get_property(
@@ -406,20 +481,16 @@ class WiFiConnectionService:
"This access point does not advertise WPA Personal PSK or SAE security."
)
def get_access_point(
def get_access_points(
self,
interface,
bssid
interface
):
self._validate_interface(
interface
)
self._validate_bssid(
bssid
)
device_path = self._device_path(
interface
)
@@ -460,6 +531,8 @@ class WiFiConnectionService:
"Cannot parse NetworkManager access point list."
) from error
access_points = []
for object_path in paths:
ap_bssid_parts = self._get_property(
@@ -477,7 +550,12 @@ class WiFiConnectionService:
ap_bssid = ap_bssid_parts[1]
if ap_bssid.lower() != bssid.lower():
try:
self._validate_bssid(
ap_bssid
)
except WiFiConnectionError:
continue
flags = self._get_integer_property(
@@ -499,25 +577,60 @@ class WiFiConnectionService:
object_path
)
key_mgmt = self._select_key_mgmt(
flags,
wpa_flags,
rsn_flags
try:
key_mgmt = self._select_key_mgmt(
flags,
wpa_flags,
rsn_flags
)
except UnsupportedSecurityError:
key_mgmt = None
try:
strength = self._get_byte_property(
object_path,
"Strength"
)
except WiFiConnectionError:
strength = None
access_points.append(
AccessPoint(
bssid=ap_bssid.upper(),
ssid=ssid,
flags=flags,
wpa_flags=wpa_flags,
rsn_flags=rsn_flags,
key_mgmt=key_mgmt,
strength=strength
)
)
return AccessPoint(
bssid=ap_bssid.upper(),
ssid=ssid,
flags=flags,
wpa_flags=wpa_flags,
rsn_flags=rsn_flags,
key_mgmt=key_mgmt
)
return access_points
raise WiFiConnectionError(
def get_access_point(
self,
interface,
bssid
):
self._validate_bssid(
bssid
)
for access_point in self.get_access_points(interface):
if access_point.bssid.lower() == bssid.lower():
return access_point
raise APNotFoundError(
f"Access point {bssid} is not currently visible to NetworkManager."
)
def _get_active_connection_uuid(self, interface):
output = self._nmcli(
@@ -533,6 +646,292 @@ class WiFiConnectionService:
return output
def _list_connection_profiles(self):
output = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME,UUID",
"connection",
"show"
)
profiles = []
for line in output.splitlines():
if not line:
continue
try:
name, profile_uuid = line.rsplit(":", 1)
except ValueError as error:
raise NetworkCleanupError(
"NetworkManager returned an invalid connection "
"profile entry."
) from error
if not name or not profile_uuid:
raise NetworkCleanupError(
"NetworkManager returned an incomplete connection "
"profile entry."
)
profiles.append(
(name, profile_uuid)
)
return profiles
def _list_connection_profile_uuids(self):
return {
profile_uuid
for _, profile_uuid in self._list_connection_profiles()
}
def capture_active_connection(self, interface):
self._validate_interface(
interface
)
connection_uuid = self._get_active_connection_uuid(
interface
)
if not connection_uuid:
return None
bssid = self._get_active_access_point_bssid(
interface
)
return {
"uuid": connection_uuid,
"bssid": bssid
}
def restore_active_connection(self, interface, saved_connection):
self._validate_interface(
interface
)
if saved_connection is None:
return False
if not isinstance(saved_connection, dict):
raise WiFiConnectionError(
"Invalid saved Wi-Fi connection."
)
connection_uuid = saved_connection.get("uuid")
bssid = saved_connection.get("bssid")
if not connection_uuid or not isinstance(connection_uuid, str):
raise WiFiConnectionError(
"Saved Wi-Fi connection UUID is missing."
)
self._validate_bssid(
bssid
)
try:
self._nmcli(
"connection",
"up",
"uuid",
connection_uuid,
"ifname",
interface,
"ap",
bssid,
timeout=90
)
except NetworkCommandError as error:
raise NetworkRestoreError(
"The previous Wi-Fi connection could not be restored: "
f"{error}"
) from error
return True
def cleanup_auto_profiles(
self,
interface,
saved_connection,
profile_uuids
):
self._validate_interface(
interface
)
if not isinstance(profile_uuids, (list, tuple)):
raise WiFiConnectionError(
"Invalid Auto verification profile list."
)
for profile_uuid in profile_uuids:
if (
not isinstance(profile_uuid, str)
or
not re.fullmatch(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-"
r"[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
r"[0-9a-fA-F]{12}",
profile_uuid
)
):
raise WiFiConnectionError(
"Invalid temporary NetworkManager profile UUID."
)
try:
profiles = self._list_connection_profiles()
except NetworkCommandError as error:
raise NetworkCleanupError(
"NetworkManager could not inspect connection profiles: "
f"{error}"
) from error
auto_profiles = [
(name, profile_uuid)
for name, profile_uuid in profiles
if name.startswith("wifi-gps-mapper-")
]
auto_profile_uuids = {
profile_uuid
for _, profile_uuid in auto_profiles
}
try:
for _ in range(len(auto_profile_uuids) + 1):
active_uuid = self._get_active_connection_uuid(
interface
)
if active_uuid not in auto_profile_uuids:
break
try:
self._nmcli(
"connection",
"down",
"uuid",
active_uuid
)
except NetworkCommandError:
pass
active_uuid_after = self._get_active_connection_uuid(
interface
)
if active_uuid_after == active_uuid:
raise NetworkCleanupError(
"The active Auto verification connection "
"could not be disconnected: "
f"{active_uuid}"
)
if active_uuid_after not in auto_profile_uuids:
break
else:
raise NetworkCleanupError(
"An Auto verification connection remains active "
"on the Wi-Fi interface."
)
except NetworkCommandError as error:
raise NetworkCleanupError(
"The active Wi-Fi connection state could not be verified: "
f"{error}"
) from error
cleanup_errors = []
for _, profile_uuid in auto_profiles:
try:
self._delete_profile(
profile_uuid
)
except NetworkCleanupError as error:
cleanup_errors.append(
f"{profile_uuid}: {error}"
)
try:
remaining_profiles = self._list_connection_profiles()
except NetworkCommandError as error:
raise NetworkCleanupError(
"The final Auto verification profile cleanup "
"could not be verified: "
f"{error}"
) from error
remaining_auto_profiles = [
(name, profile_uuid)
for name, profile_uuid in remaining_profiles
if name.startswith("wifi-gps-mapper-")
]
if remaining_auto_profiles:
remaining_uuids = [
profile_uuid
for _, profile_uuid in remaining_auto_profiles
]
details = "; ".join(cleanup_errors)
raise NetworkCleanupError(
"Auto verification profiles remain in NetworkManager: "
+ ", ".join(remaining_uuids)
+ (f". Cleanup errors: {details}" if details else "")
)
return {
"restored": False,
"deleted_profile_uuids": [
profile_uuid
for _, profile_uuid in auto_profiles
]
}
def _get_active_access_point_bssid(self, interface):
device_path = self._device_path(
@@ -628,6 +1027,33 @@ class WiFiConnectionService:
f"{cleanup_error}"
) from creation_error
try:
remaining_profiles = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME",
"connection",
"show"
)
except NetworkCommandError as inspection_error:
raise NetworkCleanupError(
"NetworkManager deleted the temporary profile command "
"but its absence could not be verified: "
f"{inspection_error}"
) from creation_error
if profile_name in remaining_profiles.splitlines():
raise NetworkCleanupError(
"NetworkManager still reports the temporary profile "
f"after deletion: {profile_name}"
) from creation_error
raise creation_error
def _create_temporary_profile(
@@ -716,12 +1142,39 @@ class WiFiConnectionService:
except NetworkCommandError as cleanup_error:
raise WiFiConnectionError(
raise NetworkCleanupError(
"NetworkManager created a temporary profile, but its UUID "
"could not be obtained and the profile could not be deleted: "
f"{cleanup_error}"
) from error
try:
remaining_profiles = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME",
"connection",
"show"
)
except NetworkCommandError as inspection_error:
raise NetworkCleanupError(
"NetworkManager deleted the temporary profile command "
"but its absence could not be verified: "
f"{inspection_error}"
) from error
if profile_name in remaining_profiles.splitlines():
raise NetworkCleanupError(
"NetworkManager still reports the temporary profile "
f"after deletion: {profile_name}"
) from error
raise
return output
@@ -785,7 +1238,7 @@ class WiFiConnectionService:
except OSError as cleanup_error:
raise NetworkCleanupError(
raise PasswordFileCleanupError(
"Could not prepare the temporary password file. "
"The file could not be deleted: "
f"{cleanup_error}"
@@ -866,14 +1319,14 @@ class WiFiConnectionService:
if operation_error:
raise NetworkCleanupError(
raise PasswordFileCleanupError(
"Wi-Fi activation failed: "
f"{operation_error}. "
"The temporary password file could not be deleted: "
f"{cleanup_error}"
) from operation_error
raise NetworkCleanupError(
raise PasswordFileCleanupError(
"The temporary password file could not be deleted: "
f"{cleanup_error}"
) from cleanup_error
@@ -886,11 +1339,59 @@ class WiFiConnectionService:
if not profile_uuid:
return
self._nmcli(
"connection",
"delete",
"uuid",
profile_uuid
try:
existing_uuids = self._list_connection_profile_uuids()
except NetworkCommandError as error:
raise NetworkCleanupError(
"NetworkManager could not inspect connection profiles: "
f"{error}"
) from error
if profile_uuid not in existing_uuids:
return
delete_error = None
try:
self._nmcli(
"connection",
"delete",
"uuid",
profile_uuid
)
except NetworkCommandError as error:
delete_error = error
try:
remaining_uuids = self._list_connection_profile_uuids()
except NetworkCommandError as error:
raise NetworkCleanupError(
"The temporary profile deletion could not be verified: "
f"{error}"
) from error
if profile_uuid not in remaining_uuids:
return
if delete_error:
raise NetworkCleanupError(
"NetworkManager could not delete the temporary profile: "
f"{delete_error}"
) from delete_error
raise NetworkCleanupError(
"NetworkManager still reports the temporary profile "
f"after deletion: {profile_uuid}"
)
def connect(
@@ -936,7 +1437,7 @@ class WiFiConnectionService:
profile_uuid
)
except NetworkCommandError as cleanup_error:
except NetworkCleanupError as cleanup_error:
raise NetworkCleanupError(
"Wi-Fi connection failed: "
@@ -959,13 +1460,51 @@ class WiFiConnectionService:
self,
interface,
bssid,
password
password,
restore_connection=True,
keep_profile=False,
access_point=None
):
access_point = self.get_access_point(
interface,
bssid
)
if (
not restore_connection
and not keep_profile
):
raise WiFiConnectionError(
"A verification without connection restoration "
"must retain a successful temporary profile."
)
if (
restore_connection
and keep_profile
):
raise WiFiConnectionError(
"A temporary profile cannot be retained "
"when restoring the previous connection."
)
if access_point is None:
access_point = self.get_access_point(
interface,
bssid
)
else:
self._validate_interface(interface)
self._validate_bssid(bssid)
if not isinstance(access_point, AccessPoint):
raise WiFiConnectionError(
"Invalid access point object."
)
if access_point.bssid.lower() != bssid.lower():
raise WiFiConnectionError(
"The supplied access point does not match the requested BSSID."
)
if access_point.is_open:
raise WiFiConnectionError(
@@ -977,18 +1516,21 @@ class WiFiConnectionService:
"Password verification is not supported for this security type."
)
previous_uuid = self._get_active_connection_uuid(
interface
)
previous_uuid = None
previous_bssid = None
if previous_uuid:
if restore_connection:
previous_bssid = self._get_active_access_point_bssid(
previous_uuid = self._get_active_connection_uuid(
interface
)
if previous_uuid:
previous_bssid = self._get_active_access_point_bssid(
interface
)
profile_uuid = None
success = False
operation_error = None
@@ -1019,29 +1561,48 @@ class WiFiConnectionService:
error
)
if isinstance(error, NetworkCommandError):
try:
self.get_access_point(
interface,
bssid
)
except APNotFoundError as scan_error:
operation_error = scan_error
error_message = str(
scan_error
)
except Exception:
pass
finally:
if profile_uuid:
try:
if restore_connection:
if previous_uuid:
try:
self._nmcli(
"connection",
"up",
"uuid",
previous_uuid,
"ifname",
interface,
"ap",
previous_bssid,
timeout=90
)
if previous_uuid:
else:
self._nmcli(
"connection",
"up",
"uuid",
previous_uuid,
"ifname",
interface,
"ap",
previous_bssid,
timeout=90
)
try:
else:
self._nmcli(
"connection",
@@ -1050,29 +1611,28 @@ class WiFiConnectionService:
profile_uuid
)
except NetworkCommandError as error:
except NetworkCommandError as error:
restore_error = str(
error
)
restore_error = str(
error
)
except NetworkCommandError as error:
if not (
success
and keep_profile
):
restore_error = str(
error
)
try:
try:
self._delete_profile(
profile_uuid
)
self._delete_profile(
profile_uuid
)
except NetworkCleanupError as error:
except NetworkCommandError as error:
cleanup_error = str(
error
)
cleanup_error = str(
error
)
verification_error = (
f"Password verification failed: {operation_error}. "
@@ -1114,5 +1674,34 @@ class WiFiConnectionService:
"interface": interface,
"bssid": access_point.bssid,
"ssid": access_point.ssid,
"error": error_message
"error": error_message,
"error_type": (
type(operation_error).__name__
if operation_error else None
),
"error_code": getattr(
operation_error,
"returncode",
None
),
"error_timed_out": getattr(
operation_error,
"timed_out",
None
),
"error_stdout": getattr(
operation_error,
"stdout",
None
),
"error_stderr": getattr(
operation_error,
"stderr",
None
),
"profile_uuid": (
profile_uuid
if success and keep_profile
else None
)
}