| 1 |
"""Ubiquiti AirOS base class.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from abc import ABC |
| 6 |
import asyncio |
| 7 |
from collections.abc import Callable |
| 8 |
from http.cookies import SimpleCookie |
| 9 |
import json |
| 10 |
import logging |
| 11 |
from ssl import SSLError |
| 12 |
from typing import Any, Generic, TypeVar |
| 13 |
from urllib.parse import urlparse |
| 14 |
|
| 15 |
import aiohttp |
| 16 |
from mashumaro.exceptions import InvalidFieldValue, MissingField |
| 17 |
|
| 18 |
from .data import ( |
| 19 |
AirOSDataBaseClass, |
| 20 |
DerivedWirelessMode, |
| 21 |
DerivedWirelessRole, |
| 22 |
redact_data_smart, |
| 23 |
) |
| 24 |
from .exceptions import ( |
| 25 |
AirOSConnectionAuthenticationError, |
| 26 |
AirOSConnectionSetupError, |
| 27 |
AirOSDataMissingError, |
| 28 |
AirOSDeviceConnectionError, |
| 29 |
AirOSKeyDataMissingError, |
| 30 |
AirOSMultipleMatchesFoundException, |
| 31 |
AirOSTLSCompatibilityError, |
| 32 |
AirOSUrlNotFoundError, |
| 33 |
) |
| 34 |
from .model_map import UispAirOSProductMapper |
| 35 |
|
| 36 |
_LOGGER = logging.getLogger(__name__) |
| 37 |
|
| 38 |
AirOSDataModel = TypeVar("AirOSDataModel", bound=AirOSDataBaseClass) |
| 39 |
|
| 40 |
|
| 41 |
class AirOS(ABC, Generic[AirOSDataModel]): |
| 42 |
"""AirOS connection class.""" |
| 43 |
|
| 44 |
data_model: type[AirOSDataModel] |
| 45 |
|
| 46 |
def __init__( |
| 47 |
self, |
| 48 |
data_model: type[AirOSDataModel], |
| 49 |
host: str, |
| 50 |
username: str, |
| 51 |
password: str, |
| 52 |
session: aiohttp.ClientSession, |
| 53 |
use_ssl: bool = True, |
| 54 |
): |
| 55 |
"""Initialize AirOS class.""" |
| 56 |
self.data_model = data_model |
| 57 |
self.username = username |
| 58 |
self.password = password |
| 59 |
|
| 60 |
self.api_version: int = 8 |
| 61 |
|
| 62 |
parsed_host = urlparse(host) |
| 63 |
scheme = parsed_host.scheme or ("https" if use_ssl else "http") |
| 64 |
hostname = parsed_host.hostname or host |
| 65 |
|
| 66 |
self.base_url = f"{scheme}://{hostname}" |
| 67 |
|
| 68 |
self.session = session |
| 69 |
|
| 70 |
self._use_json_for_login_post = False |
| 71 |
self._auth_cookie: str | None = None |
| 72 |
self._csrf_id: str | None = None |
| 73 |
self.connected: bool = False |
| 74 |
self.current_csrf_token: str | None = None |
| 75 |
|
| 76 |
# Mostly 8.x API endpoints, login/status are the same in 6.x |
| 77 |
self._login_url = f"{self.base_url}/api/auth" |
| 78 |
self._status_cgi_url = f"{self.base_url}/status.cgi" |
| 79 |
self._reboot_cgi_url = f"{self.base_url}/reboot.cgi" |
| 80 |
|
| 81 |
# Presumed 6.x XM only endpoint |
| 82 |
self._v6_xm_login_url = f"{self.base_url}/login.cgi" |
| 83 |
self._v6_form_url = "/index.cgi" |
| 84 |
|
| 85 |
# Presumed 8.x only endpoints |
| 86 |
self._stakick_cgi_url = f"{self.base_url}/stakick.cgi" |
| 87 |
self._provmode_url = f"{self.base_url}/api/provmode" |
| 88 |
self._warnings_url = f"{self.base_url}/api/warnings" |
| 89 |
self._update_check_url = f"{self.base_url}/api/fw/update-check" |
| 90 |
self._download_url = f"{self.base_url}/api/fw/download" |
| 91 |
self._download_progress_url = f"{self.base_url}/api/fw/download-progress" |
| 92 |
self._install_url = f"{self.base_url}/fwflash.cgi" |
| 93 |
|
| 94 |
self._login_urls = [self._login_url, self._v6_xm_login_url] |
| 95 |
|
| 96 |
@staticmethod |
| 97 |
def _derived_wireless_data( |
| 98 |
derived: dict[str, Any], response: dict[str, Any] |
| 99 |
) -> dict[str, Any]: |
| 100 |
"""Add derived wireless data to the device response.""" |
| 101 |
# Access Point / Station vs PTP/PtMP |
| 102 |
wireless_mode = response.get("wireless", {}).get("mode", "") |
| 103 |
match wireless_mode: |
| 104 |
case "ap-ptmp": |
| 105 |
derived["access_point"] = True |
| 106 |
derived["ptmp"] = True |
| 107 |
derived["role"] = DerivedWirelessRole.ACCESS_POINT |
| 108 |
derived["mode"] = DerivedWirelessMode.PTMP |
| 109 |
case "sta-ptmp": |
| 110 |
derived["station"] = True |
| 111 |
derived["ptmp"] = True |
| 112 |
derived["mode"] = DerivedWirelessMode.PTMP |
| 113 |
case "ap-ptp": |
| 114 |
derived["access_point"] = True |
| 115 |
derived["ptp"] = True |
| 116 |
derived["role"] = DerivedWirelessRole.ACCESS_POINT |
| 117 |
case "sta-ptp": |
| 118 |
derived["station"] = True |
| 119 |
derived["ptp"] = True |
| 120 |
return derived |
| 121 |
|
| 122 |
@staticmethod |
| 123 |
def _derived_data_helper( |
| 124 |
response: dict[str, Any], |
| 125 |
derived_wireless_data_func: Callable[ |
| 126 |
[dict[str, Any], dict[str, Any]], dict[str, Any] |
| 127 |
], |
| 128 |
) -> dict[str, Any]: |
| 129 |
"""Add derived data to the device response.""" |
| 130 |
sku: str = "UNKNOWN" |
| 131 |
|
| 132 |
devmodel = (response.get("host") or {}).get("devmodel", "UNKNOWN") |
| 133 |
try: |
| 134 |
sku = UispAirOSProductMapper().get_sku_by_devmodel(devmodel) |
| 135 |
except KeyError: |
| 136 |
_LOGGER.warning( |
| 137 |
"Unknown SKU/Model ID for '%s'. Please report at " |
| 138 |
"https://github.com/CoMPaTech/python-airos/issues so we can add support.", |
| 139 |
devmodel, |
| 140 |
) |
| 141 |
sku = "UNKNOWN" |
| 142 |
except AirOSMultipleMatchesFoundException as err: # pragma: no cover |
| 143 |
_LOGGER.warning( |
| 144 |
"Multiple SKU/Model ID matches found for model '%s': %s. Please report at " |
| 145 |
"https://github.com/CoMPaTech/python-airos/issues so we can add support.", |
| 146 |
devmodel, |
| 147 |
err, |
| 148 |
) |
| 149 |
sku = "AMBIGUOUS" |
| 150 |
|
| 151 |
derived: dict[str, Any] = { |
| 152 |
"station": False, |
| 153 |
"access_point": False, |
| 154 |
"ptp": False, |
| 155 |
"ptmp": False, |
| 156 |
"role": DerivedWirelessRole.STATION, |
| 157 |
"mode": DerivedWirelessMode.PTP, |
| 158 |
"sku": sku, |
| 159 |
} |
| 160 |
|
| 161 |
# WIRELESS |
| 162 |
derived = derived_wireless_data_func(derived, response) |
| 163 |
|
| 164 |
# Interfaces / MAC (for unique id) |
| 165 |
interfaces = response.get("interfaces", []) |
| 166 |
# No interfaces, no mac, no usability |
| 167 |
if not interfaces: |
| 168 |
_LOGGER.error("Failed to determine interfaces from AirOS data") |
| 169 |
raise AirOSKeyDataMissingError from None |
| 170 |
|
| 171 |
derived["mac"] = AirOS.get_mac(interfaces)["mac"] |
| 172 |
derived["mac_interface"] = AirOS.get_mac(interfaces)["mac_interface"] |
| 173 |
|
| 174 |
# Firmware Major Version |
| 175 |
fwversion = (response.get("host") or {}).get("fwversion", "invalid") |
| 176 |
derived["fw_major"] = AirOS.get_fw_major(fwversion) |
| 177 |
|
| 178 |
response["derived"] = derived |
| 179 |
|
| 180 |
return response |
| 181 |
|
| 182 |
@staticmethod |
| 183 |
def get_fw_major(fwversion: str) -> int: |
| 184 |
"""Extract major firmware version from fwversion string.""" |
| 185 |
try: |
| 186 |
return int(fwversion.lstrip("v").split(".", 1)[0]) |
| 187 |
except (ValueError, AttributeError) as err: |
| 188 |
_LOGGER.error("Invalid firmware version '%s'", fwversion) |
| 189 |
raise AirOSKeyDataMissingError("invalid fwversion") from err |
| 190 |
|
| 191 |
@staticmethod |
| 192 |
def get_mac(interfaces: list[dict[str, Any]]) -> dict[str, str]: |
| 193 |
"""Extract MAC address from interfaces.""" |
| 194 |
result: dict[str, str] = {"mac": "", "mac_interface": ""} |
| 195 |
|
| 196 |
if not interfaces: |
| 197 |
return result |
| 198 |
|
| 199 |
addresses: dict[str, str] = {} |
| 200 |
interface_order = ["br0", "eth0", "ath0"] |
| 201 |
|
| 202 |
for interface in interfaces: |
| 203 |
if ( |
| 204 |
interface.get("enabled") |
| 205 |
and interface.get("hwaddr") |
| 206 |
and interface.get("ifname") |
| 207 |
): |
| 208 |
addresses[interface["ifname"]] = interface["hwaddr"] |
| 209 |
|
| 210 |
for preferred in interface_order: |
| 211 |
if preferred in addresses: |
| 212 |
result["mac"] = addresses[preferred] |
| 213 |
result["mac_interface"] = preferred |
| 214 |
break |
| 215 |
else: |
| 216 |
result["mac"] = interfaces[0].get("hwaddr", "") |
| 217 |
result["mac_interface"] = interfaces[0].get("ifname", "") |
| 218 |
|
| 219 |
return result |
| 220 |
|
| 221 |
@classmethod |
| 222 |
def derived_data(cls, response: dict[str, Any]) -> dict[str, Any]: |
| 223 |
"""Add derived data to the device response (instance method for polymorphism).""" |
| 224 |
return cls._derived_data_helper(response, cls._derived_wireless_data) |
| 225 |
|
| 226 |
def _get_authenticated_headers( |
| 227 |
self, |
| 228 |
ct_json: bool = False, |
| 229 |
ct_form: bool = False, |
| 230 |
) -> dict[str, str]: |
| 231 |
"""Construct headers for an authenticated request.""" |
| 232 |
headers = {} |
| 233 |
if ct_json: |
| 234 |
headers["Content-Type"] = "application/json" |
| 235 |
elif ct_form: |
| 236 |
headers["Content-Type"] = "application/x-www-form-urlencoded" |
| 237 |
|
| 238 |
if self._csrf_id: # pragma: no cover |
| 239 |
headers["X-CSRF-ID"] = self._csrf_id |
| 240 |
|
| 241 |
if self._auth_cookie: # pragma: no cover |
| 242 |
# headers["Cookie"] = f"AIROS_{self._auth_cookie}" |
| 243 |
headers["Cookie"] = self._auth_cookie |
| 244 |
|
| 245 |
return headers |
| 246 |
|
| 247 |
def _store_auth_data(self, response: aiohttp.ClientResponse) -> None: |
| 248 |
"""Parse the response from a successful login and store auth data.""" |
| 249 |
self._csrf_id = response.headers.get("X-CSRF-ID") |
| 250 |
|
| 251 |
# Parse all Set-Cookie headers to ensure we don't miss AIROS_* cookie |
| 252 |
cookie = SimpleCookie() |
| 253 |
for set_cookie in response.headers.getall("Set-Cookie", []): |
| 254 |
cookie.load(set_cookie) |
| 255 |
for key, morsel in cookie.items(): |
| 256 |
if key.startswith("AIROS_"): |
| 257 |
# self._auth_cookie = morsel.key[6:] + "=" + morsel.value |
| 258 |
self._auth_cookie = f"{morsel.key}={morsel.value}" |
| 259 |
break |
| 260 |
|
| 261 |
async def _request_json( |
| 262 |
self, |
| 263 |
method: str, |
| 264 |
url: str, |
| 265 |
headers: dict[str, Any] | None = None, |
| 266 |
json_data: dict[str, Any] | None = None, |
| 267 |
form_data: dict[str, Any] | None = None, |
| 268 |
authenticated: bool = False, |
| 269 |
ct_json: bool = False, |
| 270 |
ct_form: bool = False, |
| 271 |
) -> dict[str, Any] | Any: |
| 272 |
"""Make an authenticated API request and return JSON response.""" |
| 273 |
# Pass the content type flags to the header builder |
| 274 |
request_headers = ( |
| 275 |
self._get_authenticated_headers(ct_json=ct_json, ct_form=ct_form) |
| 276 |
if authenticated |
| 277 |
else {} |
| 278 |
) |
| 279 |
if headers: |
| 280 |
request_headers.update(headers) |
| 281 |
|
| 282 |
try: |
| 283 |
if url not in self._login_urls and not self.connected: |
| 284 |
_LOGGER.error("Not connected, login first") |
| 285 |
raise AirOSDeviceConnectionError from None |
| 286 |
|
| 287 |
async with self.session.request( |
| 288 |
method, |
| 289 |
url, |
| 290 |
json=json_data, |
| 291 |
data=form_data, |
| 292 |
headers=request_headers, # Pass the constructed headers |
| 293 |
) as response: |
| 294 |
response.raise_for_status() |
| 295 |
response_text = await response.text() |
| 296 |
_LOGGER.debug("Successfully fetched JSON from %s", url) |
| 297 |
|
| 298 |
# If this is the login request, we need to store the new auth data |
| 299 |
if url in self._login_urls: |
| 300 |
self._store_auth_data(response) |
| 301 |
self.connected = True |
| 302 |
|
| 303 |
return json.loads(response_text) |
| 304 |
except aiohttp.ClientResponseError as err: |
| 305 |
_LOGGER.error( |
| 306 |
"Request to %s failed with status %s: %s", url, err.status, err.message |
| 307 |
) |
| 308 |
if err.status in [401, 403]: |
| 309 |
raise AirOSConnectionAuthenticationError from err |
| 310 |
if err.status == 404: |
| 311 |
raise AirOSUrlNotFoundError from err |
| 312 |
raise AirOSConnectionSetupError from err |
| 313 |
except aiohttp.ClientConnectorSSLError as err: |
| 314 |
if _is_tls_compatibility_error(err): |
| 315 |
_LOGGER.exception("TLS compatibility error during API call to %s", url) |
| 316 |
raise AirOSTLSCompatibilityError from err |
| 317 |
raise AirOSDeviceConnectionError from err |
| 318 |
except (TimeoutError, aiohttp.ClientError) as err: |
| 319 |
_LOGGER.exception("Error during API call to %s", url) |
| 320 |
raise AirOSDeviceConnectionError from err |
| 321 |
except json.JSONDecodeError as err: |
| 322 |
_LOGGER.error("Failed to decode JSON from %s", url) |
| 323 |
raise AirOSDataMissingError from err |
| 324 |
except asyncio.CancelledError: |
| 325 |
_LOGGER.warning("Request to %s was cancelled", url) |
| 326 |
raise |
| 327 |
|
| 328 |
async def _login_v6(self) -> None: |
| 329 |
"""Login to airOS v6 (XM) devices.""" |
| 330 |
# Handle session cookie from login url |
| 331 |
async with self.session.request( |
| 332 |
"GET", |
| 333 |
self._v6_xm_login_url, |
| 334 |
allow_redirects=False, |
| 335 |
) as response: |
| 336 |
session_cookie = next( |
| 337 |
(c for n, c in response.cookies.items() if n.startswith("AIROS")), None |
| 338 |
) |
| 339 |
if not session_cookie: |
| 340 |
raise AirOSDeviceConnectionError("No session cookie received.") |
| 341 |
self._auth_cookie = f"{session_cookie.key}={session_cookie.value}" |
| 342 |
|
| 343 |
# Handle login expecting 302 redirect |
| 344 |
payload = { |
| 345 |
"username": self.username, |
| 346 |
"password": self.password, |
| 347 |
"uri": self._v6_form_url, |
| 348 |
} |
| 349 |
headers = { |
| 350 |
"Content-Type": "application/x-www-form-urlencoded", |
| 351 |
"Origin": self.base_url, |
| 352 |
"Referer": self._v6_xm_login_url, |
| 353 |
"Cookie": self._auth_cookie, |
| 354 |
} |
| 355 |
async with self.session.request( |
| 356 |
"POST", |
| 357 |
self._v6_xm_login_url, |
| 358 |
data=payload, |
| 359 |
headers=headers, |
| 360 |
allow_redirects=False, |
| 361 |
) as response: |
| 362 |
if response.status != 302: |
| 363 |
raise AirOSConnectionAuthenticationError("Login failed.") |
| 364 |
|
| 365 |
# Activate session by accessing the form URL |
| 366 |
headers = {"Referer": self._v6_xm_login_url, "Cookie": self._auth_cookie} |
| 367 |
async with self.session.request( |
| 368 |
"GET", |
| 369 |
f"{self.base_url}{self._v6_form_url}", |
| 370 |
headers=headers, |
| 371 |
allow_redirects=True, |
| 372 |
) as response: |
| 373 |
if "login.cgi" in str(response.url): |
| 374 |
raise AirOSConnectionAuthenticationError("Session activation failed.") |
| 375 |
self.connected = True |
| 376 |
self.api_version = 6 |
| 377 |
|
| 378 |
async def login(self) -> None: |
| 379 |
"""Login to AirOS device.""" |
| 380 |
payload = {"username": self.username, "password": self.password} |
| 381 |
try: |
| 382 |
await self._request_json("POST", self._login_url, json_data=payload) |
| 383 |
except AirOSUrlNotFoundError: |
| 384 |
await self._login_v6() |
| 385 |
except AirOSConnectionSetupError as err: |
| 386 |
raise AirOSConnectionSetupError("Failed to login to AirOS device") from err |
| 387 |
else: |
| 388 |
return |
| 389 |
|
| 390 |
async def raw_status(self) -> dict[str, Any]: |
| 391 |
"""Retrieve raw status from the device.""" |
| 392 |
return await self._request_json("GET", self._status_cgi_url, authenticated=True) |
| 393 |
|
| 394 |
async def status(self) -> AirOSDataModel: |
| 395 |
"""Retrieve status from the device.""" |
| 396 |
response = await self._request_json( |
| 397 |
"GET", self._status_cgi_url, authenticated=True |
| 398 |
) |
| 399 |
|
| 400 |
try: |
| 401 |
adjusted_json = self.derived_data(response) |
| 402 |
return self.data_model.from_dict(adjusted_json) |
| 403 |
except InvalidFieldValue as err: |
| 404 |
# Log with .error() as this is a specific, known type of issue |
| 405 |
redacted_data = redact_data_smart(response) |
| 406 |
_LOGGER.error( |
| 407 |
"Failed to deserialize AirOS data due to an invalid field value: %s", |
| 408 |
redacted_data, |
| 409 |
) |
| 410 |
raise AirOSKeyDataMissingError from err |
| 411 |
except MissingField as err: |
| 412 |
# Log with .exception() for a full stack trace |
| 413 |
redacted_data = redact_data_smart(response) |
| 414 |
_LOGGER.exception( |
| 415 |
"Failed to deserialize AirOS data due to a missing field: %s", |
| 416 |
redacted_data, |
| 417 |
) |
| 418 |
raise AirOSKeyDataMissingError from err |
| 419 |
|
| 420 |
async def update_check(self, force: bool = False) -> dict[str, Any]: |
| 421 |
"""Check for firmware updates.""" |
| 422 |
if force: |
| 423 |
return await self._request_json( |
| 424 |
"POST", |
| 425 |
self._update_check_url, |
| 426 |
json_data={"force": True}, |
| 427 |
authenticated=True, |
| 428 |
ct_form=True, |
| 429 |
) |
| 430 |
return await self._request_json( |
| 431 |
"POST", |
| 432 |
self._update_check_url, |
| 433 |
json_data={}, |
| 434 |
authenticated=True, |
| 435 |
ct_json=True, |
| 436 |
) |
| 437 |
|
| 438 |
async def stakick(self, mac_address: str | None = None) -> bool: |
| 439 |
"""Reconnect client station.""" |
| 440 |
if not mac_address: |
| 441 |
_LOGGER.error("Device mac-address missing") |
| 442 |
raise AirOSDataMissingError from None |
| 443 |
|
| 444 |
payload = {"staif": "ath0", "staid": mac_address.upper()} |
| 445 |
|
| 446 |
await self._request_json( |
| 447 |
"POST", |
| 448 |
self._stakick_cgi_url, |
| 449 |
form_data=payload, |
| 450 |
ct_form=True, |
| 451 |
authenticated=True, |
| 452 |
) |
| 453 |
return True |
| 454 |
|
| 455 |
async def reboot(self) -> bool: |
| 456 |
"""Reboot/restart device.""" |
| 457 |
payload = {"reboot": "yes"} |
| 458 |
|
| 459 |
result = await self._request_json( |
| 460 |
"POST", |
| 461 |
self._reboot_cgi_url, |
| 462 |
form_data=payload, |
| 463 |
ct_form=True, |
| 464 |
authenticated=True, |
| 465 |
) |
| 466 |
|
| 467 |
ok_value = result.get("ok") |
| 468 |
return ok_value is True or ok_value == "true" |
| 469 |
|
| 470 |
async def provmode(self, active: bool = False) -> bool: |
| 471 |
"""Set provisioning mode.""" |
| 472 |
action = "stop" |
| 473 |
if active: |
| 474 |
action = "start" |
| 475 |
|
| 476 |
payload = {"action": action} |
| 477 |
await self._request_json( |
| 478 |
"POST", |
| 479 |
self._provmode_url, |
| 480 |
form_data=payload, |
| 481 |
ct_form=True, |
| 482 |
authenticated=True, |
| 483 |
) |
| 484 |
return True |
| 485 |
|
| 486 |
async def warnings(self) -> dict[str, Any]: |
| 487 |
"""Get warnings.""" |
| 488 |
return await self._request_json("GET", self._warnings_url, authenticated=True) |
| 489 |
|
| 490 |
async def progress(self) -> dict[str, Any]: |
| 491 |
"""Get download progress for updates.""" |
| 492 |
payload: dict[str, Any] = {} |
| 493 |
return await self._request_json( |
| 494 |
"POST", |
| 495 |
self._download_progress_url, |
| 496 |
json_data=payload, |
| 497 |
ct_json=True, |
| 498 |
authenticated=True, |
| 499 |
) |
| 500 |
|
| 501 |
async def download(self) -> dict[str, Any]: |
| 502 |
"""Download new firmware.""" |
| 503 |
payload: dict[str, Any] = {} |
| 504 |
return await self._request_json( |
| 505 |
"POST", |
| 506 |
self._download_url, |
| 507 |
json_data=payload, |
| 508 |
ct_json=True, |
| 509 |
authenticated=True, |
| 510 |
) |
| 511 |
|
| 512 |
async def install(self) -> dict[str, Any]: |
| 513 |
"""Install new firmware.""" |
| 514 |
payload: dict[str, Any] = {"do_update": 1} |
| 515 |
return await self._request_json( |
| 516 |
"POST", |
| 517 |
self._install_url, |
| 518 |
json_data=payload, |
| 519 |
ct_json=True, |
| 520 |
authenticated=True, |
| 521 |
) |
| 522 |
|
| 523 |
|
| 524 |
def _is_tls_compatibility_error(err: aiohttp.ClientConnectorSSLError) -> bool: |
| 525 |
"""Return True for known legacy airOS TLS handshake failures.""" |
| 526 |
if "SSLV3_ALERT_HANDSHAKE_FAILURE" in str(err): |
| 527 |
return True |
| 528 |
|
| 529 |
cause = err.__cause__ |
| 530 |
if isinstance(cause, SSLError): |
| 531 |
message = str(cause).lower() |
| 532 |
return ( |
| 533 |
"handshake failure" in message or "sslv3 alert handshake failure" in message |
| 534 |
) |
| 535 |
|
| 536 |
return False |