Files
wifi-gps-mapper-releases/src/wifi_connection.py
T

1707 lines
40 KiB
Python

import os
import re
import secrets
import shlex
import subprocess
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
NM_SERVICE = "org.freedesktop.NetworkManager"
NM_DEVICE_WIRELESS = "org.freedesktop.NetworkManager.Device.Wireless"
NM_ACCESS_POINT = "org.freedesktop.NetworkManager.AccessPoint"
AP_FLAGS_PRIVACY = 0x00000001
AP_SEC_KEY_MGMT_PSK = 0x00000100
AP_SEC_KEY_MGMT_802_1X = 0x00000200
AP_SEC_KEY_MGMT_SAE = 0x00000400
AP_SEC_KEY_MGMT_OWE = 0x00000800
AP_SEC_KEY_MGMT_OWE_TM = 0x00001000
AP_SEC_KEY_MGMT_EAP_SUITE_B_192 = 0x00002000
class WiFiConnectionError(RuntimeError):
pass
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
ssid: str
flags: int
wpa_flags: int
rsn_flags: int
key_mgmt: str | None
strength: int | None = None
@property
def is_open(self):
return (
not self.flags & AP_FLAGS_PRIVACY
and not self.wpa_flags
and not self.rsn_flags
)
class WiFiConnectionService:
def __init__(
self,
command_runner=None,
command_timeout=30,
scan_timeout=15,
scan_poll_interval=0.25
):
self.command_runner = (
command_runner
or
subprocess.run
)
self.command_timeout = command_timeout
self.scan_timeout = scan_timeout
self.scan_poll_interval = scan_poll_interval
@staticmethod
def _validate_interface(interface):
if not re.fullmatch(
r"[a-zA-Z0-9_.:-]{1,64}",
interface or ""
):
raise WiFiConnectionError(
"Invalid Wi-Fi interface."
)
@staticmethod
def _validate_bssid(bssid):
if not re.fullmatch(
r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}",
bssid or ""
):
raise WiFiConnectionError(
"Invalid BSSID."
)
def _run(
self,
command,
timeout=None
):
try:
result = self.command_runner(
command,
capture_output=True,
text=True,
timeout=(
timeout
or
self.command_timeout
),
env={
**os.environ,
"LC_ALL": "C"
}
)
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.",
stdout=stdout,
stderr=stderr,
timed_out=True
) from error
except OSError as error:
raise NetworkCommandError(
f"Cannot execute {command[0]}: {error}"
) from error
if result.returncode != 0:
message = (
result.stderr.strip()
or
result.stdout.strip()
or
f"Command exited with code {result.returncode}."
)
raise NetworkCommandError(
message,
returncode=result.returncode,
stdout=result.stdout,
stderr=result.stderr
)
return result.stdout.strip()
def _nmcli(self, *arguments, timeout=None):
return self._run(
[
"nmcli",
*arguments
],
timeout=timeout
)
def _busctl(self, *arguments):
return self._run(
[
"busctl",
"--system",
*arguments
]
)
def _device_path(self, interface):
self._validate_interface(
interface
)
output = self._nmcli(
"--get-values",
"GENERAL.DBUS-PATH",
"device",
"show",
interface
)
if not output.startswith("/org/freedesktop/NetworkManager/Devices/"):
raise WiFiConnectionError(
"NetworkManager did not return a valid device D-Bus path."
)
return output
def _get_property(
self,
object_path,
interface,
property_name
):
output = self._busctl(
"get-property",
NM_SERVICE,
object_path,
interface,
property_name
)
try:
parts = shlex.split(
output
)
if not parts:
raise ValueError("Empty D-Bus property.")
return parts
except ValueError as error:
raise WiFiConnectionError(
f"Cannot parse D-Bus property {property_name}."
) from error
def _get_last_scan(self, device_path):
parts = self._get_property(
device_path,
NM_DEVICE_WIRELESS,
"LastScan"
)
if len(parts) != 2 or parts[0] != "x":
raise WiFiConnectionError(
"Unexpected D-Bus type for LastScan."
)
try:
return int(parts[1])
except ValueError as error:
raise WiFiConnectionError(
"Invalid LastScan value from NetworkManager."
) from error
def _request_fresh_scan(self, device_path):
previous_scan = self._get_last_scan(
device_path
)
self._busctl(
"call",
NM_SERVICE,
device_path,
NM_DEVICE_WIRELESS,
"RequestScan",
"a{sv}",
"0"
)
deadline = (
time.monotonic()
+
self.scan_timeout
)
while True:
current_scan = self._get_last_scan(
device_path
)
if current_scan > previous_scan:
return
remaining = (
deadline
-
time.monotonic()
)
if remaining <= 0:
break
time.sleep(
min(
self.scan_poll_interval,
remaining
)
)
raise WiFiConnectionError(
"NetworkManager did not complete a fresh Wi-Fi scan in time."
)
def _get_integer_property(
self,
object_path,
property_name
):
parts = self._get_property(
object_path,
NM_ACCESS_POINT,
property_name
)
if len(parts) != 2 or parts[0] != "u":
raise WiFiConnectionError(
f"Unexpected D-Bus type for {property_name}."
)
try:
return int(parts[1])
except ValueError as error:
raise WiFiConnectionError(
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(
object_path,
NM_ACCESS_POINT,
"Ssid"
)
if not parts or parts[0] != "ay":
raise WiFiConnectionError(
"Unexpected D-Bus type for SSID."
)
try:
count = int(parts[1])
values = [
int(value)
for value in parts[2:]
]
if (
count != len(values)
or
any(value < 0 or value > 255 for value in values)
):
raise ValueError("Invalid SSID byte array.")
ssid = bytes(
values
).decode(
"utf-8",
errors="replace"
)
except (ValueError, IndexError) as error:
raise WiFiConnectionError(
"Cannot decode SSID from NetworkManager."
) from error
if not ssid:
raise WiFiConnectionError(
"The access point does not advertise its SSID."
)
return ssid
@staticmethod
def _select_key_mgmt(
flags,
wpa_flags,
rsn_flags
):
security_flags = (
wpa_flags
|
rsn_flags
)
if not flags & AP_FLAGS_PRIVACY and not security_flags:
return None
has_psk = bool(
security_flags
&
AP_SEC_KEY_MGMT_PSK
)
has_sae = bool(
security_flags
&
AP_SEC_KEY_MGMT_SAE
)
if has_psk:
return "wpa-psk"
if has_sae:
return "sae"
raise UnsupportedSecurityError(
"This access point does not advertise WPA Personal PSK or SAE security."
)
def get_access_points(
self,
interface
):
self._validate_interface(
interface
)
device_path = self._device_path(
interface
)
self._request_fresh_scan(
device_path
)
output = self._busctl(
"call",
NM_SERVICE,
device_path,
NM_DEVICE_WIRELESS,
"GetAccessPoints"
)
try:
parts = shlex.split(
output
)
if len(parts) < 2 or parts[0] != "ao":
raise ValueError("Unexpected GetAccessPoints result.")
count = int(
parts[1]
)
paths = parts[2:]
if count != len(paths):
raise ValueError("Invalid access point count.")
except ValueError as error:
raise WiFiConnectionError(
"Cannot parse NetworkManager access point list."
) from error
access_points = []
for object_path in paths:
ap_bssid_parts = self._get_property(
object_path,
NM_ACCESS_POINT,
"HwAddress"
)
if (
len(ap_bssid_parts) != 2
or
ap_bssid_parts[0] != "s"
):
continue
ap_bssid = ap_bssid_parts[1]
try:
self._validate_bssid(
ap_bssid
)
except WiFiConnectionError:
continue
flags = self._get_integer_property(
object_path,
"Flags"
)
wpa_flags = self._get_integer_property(
object_path,
"WpaFlags"
)
rsn_flags = self._get_integer_property(
object_path,
"RsnFlags"
)
ssid = self._get_ssid(
object_path
)
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 access_points
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(
"--get-values",
"GENERAL.CON-UUID",
"device",
"show",
interface
)
if not output or output == "--":
return None
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(
interface
)
parts = self._get_property(
device_path,
NM_DEVICE_WIRELESS,
"ActiveAccessPoint"
)
if len(parts) != 2 or parts[0] != "o":
raise WiFiConnectionError(
"Unexpected D-Bus type for ActiveAccessPoint."
)
object_path = parts[1]
if (
object_path == "/"
or
not object_path.startswith(
"/org/freedesktop/NetworkManager/AccessPoint/"
)
):
raise WiFiConnectionError(
"NetworkManager did not return the active access point."
)
parts = self._get_property(
object_path,
NM_ACCESS_POINT,
"HwAddress"
)
if len(parts) != 2 or parts[0] != "s":
raise WiFiConnectionError(
"Unexpected D-Bus type for the active access point BSSID."
)
bssid = parts[1]
self._validate_bssid(
bssid
)
return bssid.upper()
def _handle_failed_profile_creation(
self,
profile_name,
creation_error
):
try:
output = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME",
"connection",
"show"
)
except NetworkCommandError as inspection_error:
raise NetworkCleanupError(
"NetworkManager failed to create a temporary profile, "
"and its state could not be determined. "
f"Profile name: {profile_name}. "
f"Inspection failed: {inspection_error}"
) from creation_error
if profile_name in output.splitlines():
try:
self._nmcli(
"connection",
"delete",
"id",
profile_name
)
except NetworkCommandError as cleanup_error:
raise NetworkCleanupError(
"NetworkManager may have created a temporary profile, "
"but it could not be deleted: "
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(
self,
interface,
access_point
):
profile_name = (
"wifi-gps-mapper-"
+
secrets.token_hex(8)
)
arguments = [
"connection",
"add",
"type",
"wifi",
"ifname",
interface,
"con-name",
profile_name,
"ssid",
access_point.ssid,
"mode",
"infrastructure",
"autoconnect",
"no",
"save",
"no",
"wifi.bssid",
access_point.bssid
]
if access_point.key_mgmt:
arguments.extend(
[
"wifi-sec.key-mgmt",
access_point.key_mgmt
]
)
try:
self._nmcli(
*arguments
)
except NetworkCommandError as error:
self._handle_failed_profile_creation(
profile_name,
error
)
try:
output = self._nmcli(
"--get-values",
"connection.uuid",
"connection",
"show",
profile_name
)
if not re.fullmatch(
r"[0-9a-fA-F-]{36}",
output
):
raise WiFiConnectionError(
"NetworkManager created a profile but returned an invalid UUID."
)
except Exception as error:
try:
self._nmcli(
"connection",
"delete",
"id",
profile_name
)
except NetworkCommandError as cleanup_error:
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
@staticmethod
def _create_password_file(password):
if (
not isinstance(password, str)
or
not password
or
"\n" in password
or
"\r" in password
):
raise WiFiConnectionError(
"Invalid Wi-Fi password."
)
file_descriptor, filename = tempfile.mkstemp(
prefix="wifi-gps-mapper-",
suffix=".psk",
dir="/tmp"
)
try:
os.fchmod(
file_descriptor,
0o600
)
with os.fdopen(
file_descriptor,
"w",
encoding="utf-8"
) as password_file:
password_file.write(
"802-11-wireless-security.psk:"
+
password
+
"\n"
)
except Exception as error:
try:
os.close(
file_descriptor
)
except OSError:
pass
try:
os.unlink(
filename
)
except OSError as cleanup_error:
raise PasswordFileCleanupError(
"Could not prepare the temporary password file. "
"The file could not be deleted: "
f"{cleanup_error}"
) from error
raise
return filename
def _activate_profile(
self,
profile_uuid,
interface,
access_point,
password=None
):
arguments = [
"connection",
"up",
"uuid",
profile_uuid,
"ifname",
interface,
"ap",
access_point.bssid
]
password_file = None
operation_error = None
try:
if access_point.key_mgmt:
if password is None:
raise WiFiConnectionError(
"A password is required for this access point."
)
password_file = self._create_password_file(
password
)
arguments.extend(
[
"passwd-file",
password_file
]
)
elif password is not None:
raise WiFiConnectionError(
"An open access point does not require a password."
)
self._nmcli(
*arguments,
timeout=90
)
except Exception as error:
operation_error = error
finally:
if password_file:
try:
os.unlink(
password_file
)
except OSError as cleanup_error:
if operation_error:
raise PasswordFileCleanupError(
"Wi-Fi activation failed: "
f"{operation_error}. "
"The temporary password file could not be deleted: "
f"{cleanup_error}"
) from operation_error
raise PasswordFileCleanupError(
"The temporary password file could not be deleted: "
f"{cleanup_error}"
) from cleanup_error
if operation_error:
raise operation_error
def _delete_profile(self, profile_uuid):
if not profile_uuid:
return
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(
self,
interface,
bssid,
password=None,
access_point=None
):
if access_point is None:
access_point = self.get_access_point(
interface,
bssid
)
elif access_point.bssid.lower() != bssid.lower():
raise WiFiConnectionError(
"The supplied access point does not match the requested BSSID."
)
profile_uuid = self._create_temporary_profile(
interface,
access_point
)
try:
self._activate_profile(
profile_uuid,
interface,
access_point,
password
)
except Exception as connection_error:
try:
self._delete_profile(
profile_uuid
)
except NetworkCleanupError as cleanup_error:
raise NetworkCleanupError(
"Wi-Fi connection failed: "
f"{connection_error}. The temporary profile could not be deleted: "
f"{cleanup_error}"
) from connection_error
raise
return {
"success": True,
"interface": interface,
"bssid": access_point.bssid,
"ssid": access_point.ssid,
"profile_uuid": profile_uuid,
"is_open": access_point.is_open
}
def verify(
self,
interface,
bssid,
password,
restore_connection=True,
keep_profile=False,
access_point=None
):
if (
not restore_connection
and not keep_profile
):
raise WiFiConnectionError(
"A verification without connection restoration "
"must retain a successful temporary profile."
)
if (
restore_connection
and keep_profile
):
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(
"Open access points do not require password verification."
)
if not access_point.key_mgmt:
raise UnsupportedSecurityError(
"Password verification is not supported for this security type."
)
previous_uuid = None
previous_bssid = None
if restore_connection:
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
error_message = None
restore_error = None
cleanup_error = None
try:
profile_uuid = self._create_temporary_profile(
interface,
access_point
)
self._activate_profile(
profile_uuid,
interface,
access_point,
password
)
success = True
except Exception as error:
operation_error = error
error_message = str(
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:
if restore_connection:
try:
if previous_uuid:
self._nmcli(
"connection",
"up",
"uuid",
previous_uuid,
"ifname",
interface,
"ap",
previous_bssid,
timeout=90
)
else:
self._nmcli(
"connection",
"down",
"uuid",
profile_uuid
)
except NetworkCommandError as error:
restore_error = str(
error
)
if not (
success
and keep_profile
):
try:
self._delete_profile(
profile_uuid
)
except NetworkCleanupError as error:
cleanup_error = str(
error
)
verification_error = (
f"Password verification failed: {operation_error}. "
if operation_error else ""
)
if restore_error:
raise NetworkRestoreError(
f"{verification_error}"
"The previous Wi-Fi state could not be restored: "
f"{restore_error}. "
+ (
f"The temporary profile could not be deleted: {cleanup_error}"
if cleanup_error else ""
)
)
if cleanup_error:
raise NetworkCleanupError(
f"{verification_error}"
"The temporary Wi-Fi profile could not be deleted: "
f"{cleanup_error}"
)
if (
operation_error
and
not isinstance(
operation_error,
NetworkCommandError
)
):
raise operation_error
return {
"success": success,
"interface": interface,
"bssid": access_point.bssid,
"ssid": access_point.ssid,
"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
)
}