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
+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
)
}