| 1 |
"""Connection module. |
| 2 |
|
| 3 |
This module handles the connection between the library and the router |
| 4 |
as well as all the data transfer. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import asyncio |
| 10 |
import base64 |
| 11 |
from collections.abc import Awaitable, Callable |
| 12 |
import contextlib |
| 13 |
from enum import StrEnum |
| 14 |
import json |
| 15 |
import logging |
| 16 |
import ssl |
| 17 |
from typing import Any, Self, TypeVar |
| 18 |
from urllib.parse import quote |
| 19 |
|
| 20 |
import aiohttp |
| 21 |
|
| 22 |
from asusrouter.config import ( |
| 23 |
ARConfig, |
| 24 |
ARConfigKey as ARConfKey, |
| 25 |
safe_int_config, |
| 26 |
) |
| 27 |
from asusrouter.connection_config import ( |
| 28 |
ARConnectionConfig, |
| 29 |
ARConnectionConfigKey as ARCCKey, |
| 30 |
) |
| 31 |
from asusrouter.const import ( |
| 32 |
DEFAULT_PORT_HTTP, |
| 33 |
DEFAULT_PORT_HTTPS, |
| 34 |
DEFAULT_TIMEOUT, |
| 35 |
DEFAULT_TIMEOUT_FALLBACK, |
| 36 |
USER_AGENT, |
| 37 |
HTTPStatus, |
| 38 |
RequestType, |
| 39 |
) |
| 40 |
from asusrouter.error import ( |
| 41 |
AsusRouter404Error, |
| 42 |
AsusRouterAccessError, |
| 43 |
AsusRouterConnectionError, |
| 44 |
AsusRouterError, |
| 45 |
AsusRouterFallbackError, |
| 46 |
AsusRouterFallbackForbiddenError, |
| 47 |
AsusRouterFallbackLoopError, |
| 48 |
AsusRouterLogoutError, |
| 49 |
AsusRouterNotImplementedError, |
| 50 |
AsusRouterSSLCertificateError, |
| 51 |
AsusRouterTimeoutError, |
| 52 |
) |
| 53 |
from asusrouter.modules.endpoint import ( |
| 54 |
EndpointService, |
| 55 |
EndpointType, |
| 56 |
is_sensitive_endpoint, |
| 57 |
) |
| 58 |
from asusrouter.modules.endpoint.error import handle_access_error |
| 59 |
from asusrouter.tools.connection import get_cookie_jar |
| 60 |
from asusrouter.tools.converters import clean_string, safe_float |
| 61 |
from asusrouter.tools.security import ARSecurityLevel |
| 62 |
|
| 63 |
_LOGGER = logging.getLogger(__name__) |
| 64 |
|
| 65 |
_T = TypeVar("_T") |
| 66 |
|
| 67 |
|
| 68 |
class ConnectionFallback(StrEnum): |
| 69 |
"""Connection fallback strategies.""" |
| 70 |
|
| 71 |
HTTP = "http" |
| 72 |
HTTPS = "https" |
| 73 |
HTTPS_UNSAFE = "https_unsafe" |
| 74 |
|
| 75 |
|
| 76 |
def generate_credentials( |
| 77 |
username: str, password: str |
| 78 |
) -> tuple[str, dict[str, str]]: |
| 79 |
"""Generate credentials for connection.""" |
| 80 |
|
| 81 |
auth = f"{username}:{password}".encode("ascii") |
| 82 |
logintoken = base64.b64encode(auth).decode("ascii") |
| 83 |
payload = f"login_authorization={logintoken}" |
| 84 |
headers = {"user-agent": USER_AGENT} |
| 85 |
|
| 86 |
return payload, headers |
| 87 |
|
| 88 |
|
| 89 |
def sanitize_data( |
| 90 |
value: str | None, |
| 91 |
) -> str: |
| 92 |
"""Sanitize data placeholder.""" |
| 93 |
|
| 94 |
return "[SANITIZED PLACEHOLDER]" |
| 95 |
|
| 96 |
|
| 97 |
class Connection: # pylint: disable=too-many-instance-attributes |
| 98 |
"""A connection between the library and the device.""" |
| 99 |
|
| 100 |
def __init__( # noqa: PLR0913 |
| 101 |
self, |
| 102 |
hostname: str, |
| 103 |
username: str, |
| 104 |
password: str, |
| 105 |
port: int | None = None, |
| 106 |
use_ssl: bool = False, |
| 107 |
session: aiohttp.ClientSession | None = None, |
| 108 |
timeout: int | None = DEFAULT_TIMEOUT, |
| 109 |
dumpback: Callable[..., Awaitable[None]] | None = None, |
| 110 |
config: dict[ARCCKey, Any] | None = None, |
| 111 |
): |
| 112 |
"""Initialize connection.""" |
| 113 |
|
| 114 |
_LOGGER.debug("Initializing a new connection to `%s`", hostname) |
| 115 |
|
| 116 |
# Initialize configs |
| 117 |
self._config = ARConnectionConfig() |
| 118 |
self._used_fallbacks: dict[ConnectionFallback, bool] = {} |
| 119 |
|
| 120 |
# Initialize startup configs if any provided |
| 121 |
if isinstance(config, dict): |
| 122 |
_LOGGER.debug("Using provided connection config: %s", config) |
| 123 |
for key, value in config.items(): |
| 124 |
self._config.set(key, value) |
| 125 |
|
| 126 |
# Initialize parameters for connection |
| 127 |
self._token: str | None = None |
| 128 |
self._header: dict[str, str] | None = None |
| 129 |
self._connected: bool = False |
| 130 |
self._connection_lock: asyncio.Lock = asyncio.Lock() |
| 131 |
self._timeout: int = timeout or DEFAULT_TIMEOUT |
| 132 |
|
| 133 |
# Single in-flight connect task (serialize connection attempts) |
| 134 |
self._connect_task: asyncio.Task[Any] | None = None |
| 135 |
# Lock to guard creation of the connect task |
| 136 |
self._connect_task_lock: asyncio.Lock = asyncio.Lock() |
| 137 |
|
| 138 |
# Hostname and credentials |
| 139 |
self._hostname = hostname |
| 140 |
self._username = username |
| 141 |
self._password = password |
| 142 |
|
| 143 |
# Set the port and protocol based on the input |
| 144 |
self.config.set( |
| 145 |
ARCCKey.PORT, |
| 146 |
port or (DEFAULT_PORT_HTTPS if use_ssl else DEFAULT_PORT_HTTP), |
| 147 |
) |
| 148 |
self.config.set(ARCCKey.USE_SSL, use_ssl) |
| 149 |
_LOGGER.debug( |
| 150 |
"Using `%s` and port `%s` with ssl flag `%s`", |
| 151 |
self.http, |
| 152 |
self.config.get(ARCCKey.PORT), |
| 153 |
use_ssl, |
| 154 |
) |
| 155 |
|
| 156 |
# Callback for dumping data |
| 157 |
self._dumpback = dumpback |
| 158 |
|
| 159 |
# Client session |
| 160 |
self._manage_session: bool = False |
| 161 |
if session is not None: |
| 162 |
_LOGGER.debug("Using provided session") |
| 163 |
self._session = session |
| 164 |
else: |
| 165 |
_LOGGER.debug("No session provided. Will create a new one") |
| 166 |
self._session = self._new_session() |
| 167 |
|
| 168 |
async def __aenter__(self) -> Self: |
| 169 |
"""Enter the connection.""" |
| 170 |
|
| 171 |
await self.async_connect() |
| 172 |
return self |
| 173 |
|
| 174 |
async def __aexit__( |
| 175 |
self, |
| 176 |
exc_type: object, |
| 177 |
exc_value: object, |
| 178 |
traceback: object, |
| 179 |
) -> None: |
| 180 |
"""Exit the connection.""" |
| 181 |
|
| 182 |
await self.async_close() |
| 183 |
|
| 184 |
@classmethod |
| 185 |
async def create( # noqa: PLR0913 |
| 186 |
cls, |
| 187 |
hostname: str, |
| 188 |
username: str, |
| 189 |
password: str, |
| 190 |
port: int | None = None, |
| 191 |
use_ssl: bool = False, |
| 192 |
session: aiohttp.ClientSession | None = None, |
| 193 |
timeout: int | None = DEFAULT_TIMEOUT, # noqa: ASYNC109 |
| 194 |
dumpback: Callable[..., Awaitable[None]] | None = None, |
| 195 |
config: dict[ARCCKey, Any] | None = None, |
| 196 |
) -> Connection: |
| 197 |
"""Create and initialize a connection.""" |
| 198 |
|
| 199 |
connection = cls( |
| 200 |
hostname=hostname, |
| 201 |
username=username, |
| 202 |
password=password, |
| 203 |
port=port, |
| 204 |
use_ssl=use_ssl, |
| 205 |
session=session, |
| 206 |
timeout=timeout or DEFAULT_TIMEOUT, |
| 207 |
dumpback=dumpback, |
| 208 |
config=config, |
| 209 |
) |
| 210 |
await connection.async_connect() |
| 211 |
return connection |
| 212 |
|
| 213 |
def _new_session(self) -> aiohttp.ClientSession: |
| 214 |
"""Create a new session.""" |
| 215 |
|
| 216 |
# If we create a new session, we will manage it |
| 217 |
self._manage_session = True |
| 218 |
|
| 219 |
# Timeout for the session |
| 220 |
timeout = aiohttp.ClientTimeout(total=self._timeout) |
| 221 |
|
| 222 |
# Create the session |
| 223 |
return aiohttp.ClientSession( |
| 224 |
connector=aiohttp.TCPConnector(), |
| 225 |
cookie_jar=get_cookie_jar(), |
| 226 |
timeout=timeout, |
| 227 |
) |
| 228 |
|
| 229 |
async def async_close(self) -> None: |
| 230 |
"""Close the session.""" |
| 231 |
|
| 232 |
if self._manage_session and self._session: |
| 233 |
if not self._session.closed: |
| 234 |
_LOGGER.debug("Closing the session") |
| 235 |
await self._session.close() |
| 236 |
else: |
| 237 |
_LOGGER.debug("Session already closed") |
| 238 |
else: |
| 239 |
_LOGGER.debug("No session to close or not managing the session") |
| 240 |
|
| 241 |
async def async_connect( |
| 242 |
self, |
| 243 |
lock: asyncio.Lock | None = None, |
| 244 |
t_overwrite: float | None = None, |
| 245 |
block_error: bool = False, |
| 246 |
) -> bool: |
| 247 |
"""Connect to the device and get a new auth token.""" |
| 248 |
|
| 249 |
timeout = safe_float(t_overwrite) or self._timeout |
| 250 |
|
| 251 |
# If already connected, return fast |
| 252 |
if self._connected: |
| 253 |
return True |
| 254 |
|
| 255 |
# Ensure only one connect Task is created; |
| 256 |
# reuse it for concurrent callers |
| 257 |
async with self._connect_task_lock: |
| 258 |
if self._connect_task is None or self._connect_task.done(): |
| 259 |
# start the connect attempt as a background task |
| 260 |
self._connect_task = asyncio.create_task( |
| 261 |
self._async_connect_with_lock(lock) |
| 262 |
) |
| 263 |
|
| 264 |
try: |
| 265 |
# Await the in-flight connect but don't cancel it on |
| 266 |
# outer timeout: use shield so that callers timing out |
| 267 |
# won't cancel the actual attempt. |
| 268 |
await asyncio.wait_for( |
| 269 |
asyncio.shield(self._connect_task), timeout=timeout |
| 270 |
) |
| 271 |
return True |
| 272 |
except TimeoutError: |
| 273 |
if not block_error: |
| 274 |
_LOGGER.error("Connection to %s timed out", self._hostname) |
| 275 |
# do not cancel the underlying task here; let it finish |
| 276 |
# and satisfy future callers |
| 277 |
return False |
| 278 |
except asyncio.CancelledError: |
| 279 |
# Underlying connect was cancelled (e.g. by fallback). |
| 280 |
# Treat as failed. |
| 281 |
if not block_error: |
| 282 |
_LOGGER.debug("Connection attempt was cancelled") |
| 283 |
return False |
| 284 |
finally: |
| 285 |
# If the task finished, clear it to allow future retries. |
| 286 |
if self._connect_task is not None and self._connect_task.done(): |
| 287 |
self._connect_task = None |
| 288 |
|
| 289 |
async def _async_connect_with_lock( |
| 290 |
self, |
| 291 |
lock: asyncio.Lock | None = None, |
| 292 |
) -> bool: |
| 293 |
"""Connect to the device and get a new auth token. |
| 294 |
|
| 295 |
Acquire the lock only for state checks/updates. Perform the actual |
| 296 |
network login outside the lock to avoid deadlocks when fallback |
| 297 |
triggers a nested connect attempt. |
| 298 |
""" |
| 299 |
_lock = lock or self._connection_lock |
| 300 |
|
| 301 |
# Quick check / early exit while holding the lock |
| 302 |
async with _lock: |
| 303 |
if self._connected: |
| 304 |
_LOGGER.debug("Already connected to %s", self._hostname) |
| 305 |
return True |
| 306 |
_LOGGER.debug("Initializing connection to %s", self._hostname) |
| 307 |
|
| 308 |
# Prepare auth payload and headers (no lock held) |
| 309 |
payload, headers = generate_credentials(self._username, self._password) |
| 310 |
|
| 311 |
_LOGGER.debug("Requesting authorization") |
| 312 |
try: |
| 313 |
# Do the network login outside the lock to avoid deadlocks |
| 314 |
_, _, resp_content = await self._send_request( |
| 315 |
EndpointService.LOGIN, payload, headers |
| 316 |
) |
| 317 |
_LOGGER.debug("Received authorization response") |
| 318 |
except AsusRouterSSLCertificateError as ex: |
| 319 |
raise AsusRouterAccessError( |
| 320 |
f"Cannot access {EndpointService.LOGIN}. " |
| 321 |
"due to the SSL certificate error" |
| 322 |
) from ex |
| 323 |
except AsusRouterAccessError as ex: |
| 324 |
raise AsusRouterAccessError( |
| 325 |
f"Cannot access {EndpointService.LOGIN}. " |
| 326 |
"Failed in `async_connect`" |
| 327 |
) from ex |
| 328 |
except AsusRouterError as ex: |
| 329 |
_LOGGER.debug("Connection failed with error: %s", ex) |
| 330 |
raise |
| 331 |
except Exception as ex: # pylint: disable=broad-except |
| 332 |
_LOGGER.debug( |
| 333 |
"Unexpected error while connecting to %s: %s", |
| 334 |
self._hostname, |
| 335 |
ex, |
| 336 |
) |
| 337 |
raise |
| 338 |
|
| 339 |
# Process response and update state while holding the lock |
| 340 |
content = json.loads(resp_content) |
| 341 |
token = content.get("asus_token") |
| 342 |
if not token: |
| 343 |
_LOGGER.error("No token received") |
| 344 |
return False |
| 345 |
|
| 346 |
async with _lock: |
| 347 |
# Another task may have connected while we performed |
| 348 |
# the network IO. If so, avoid overwriting state and return early. |
| 349 |
if self._connected: |
| 350 |
_LOGGER.debug( |
| 351 |
"Connection already established to %s by another task", |
| 352 |
self._hostname, |
| 353 |
) |
| 354 |
return True |
| 355 |
|
| 356 |
# Store token and header |
| 357 |
self._token = token |
| 358 |
self._header = { |
| 359 |
"user-agent": USER_AGENT, |
| 360 |
"cookie": f"asus_token={self._token}", |
| 361 |
} |
| 362 |
|
| 363 |
# Mark as connected |
| 364 |
self._connected = True |
| 365 |
_LOGGER.debug("Connected to %s", self._hostname) |
| 366 |
|
| 367 |
return True |
| 368 |
|
| 369 |
async def async_disconnect(self) -> bool: |
| 370 |
"""Disconnect from the device.""" |
| 371 |
|
| 372 |
_LOGGER.debug("Initializing disconnection from %s", self._hostname) |
| 373 |
|
| 374 |
# Check that we are connected |
| 375 |
if not self._connected: |
| 376 |
_LOGGER.debug("Not connected to %s", self._hostname) |
| 377 |
return True |
| 378 |
|
| 379 |
# Request logout |
| 380 |
try: |
| 381 |
await self._send_request(EndpointService.LOGOUT) |
| 382 |
except AsusRouterLogoutError: |
| 383 |
# Loged out successfully |
| 384 |
self.reset_connection() |
| 385 |
_LOGGER.debug("Disconnected from %s", self._hostname) |
| 386 |
return True |
| 387 |
except AsusRouterError as ex: |
| 388 |
_LOGGER.debug( |
| 389 |
"Error while disconnecting from %s: %s", self._hostname, ex |
| 390 |
) |
| 391 |
return False |
| 392 |
|
| 393 |
# Anything else would mean error when disconnecting |
| 394 |
return False |
| 395 |
|
| 396 |
def _payload_for_logging( |
| 397 |
self, security_level: Any, endpoint: EndpointType, payload: str | None |
| 398 |
) -> str | None: |
| 399 |
"""Return the payload to log if any. |
| 400 |
|
| 401 |
Rules: |
| 402 |
- STRICT: never log payload |
| 403 |
- DEFAULT: log only non-sensitive endpoints |
| 404 |
- SANITIZED: log sensitive endpoints with automatic sanitization |
| 405 |
- UNSAFE: log sensitive endpoints verbatim |
| 406 |
""" |
| 407 |
|
| 408 |
# Resolve security level safely |
| 409 |
level = ARSecurityLevel.from_value(security_level) |
| 410 |
|
| 411 |
# STRICT: never include payload | Never include |
| 412 |
# login payload at any level |
| 413 |
if ( |
| 414 |
level == ARSecurityLevel.STRICT |
| 415 |
or endpoint == EndpointService.LOGIN |
| 416 |
): |
| 417 |
return None |
| 418 |
|
| 419 |
# Clean from empty strings |
| 420 |
payload = clean_string(payload) |
| 421 |
if payload is None: |
| 422 |
return None |
| 423 |
|
| 424 |
# Sensitive endpoints: only allowed if explicitly set to |
| 425 |
# UNSAFE by user or are SANITIZED |
| 426 |
if is_sensitive_endpoint(endpoint): |
| 427 |
if ARSecurityLevel.at_least_sanitized(level): |
| 428 |
if level == ARSecurityLevel.SANITIZED: |
| 429 |
# Automatically sanitized to remove sensitive data |
| 430 |
return sanitize_data(payload) |
| 431 |
# Only UNSAFE level is above SANITIZED, meaning |
| 432 |
# Explicitly allowed as raw data by user |
| 433 |
return payload |
| 434 |
# Any other level should not log a possible sensitive payload |
| 435 |
return None |
| 436 |
|
| 437 |
# Non-sensitive endpoints: log (unless was blocked by STRICT config) |
| 438 |
return payload |
| 439 |
|
| 440 |
def _log_request( |
| 441 |
self, endpoint: EndpointType, payload: str | None |
| 442 |
) -> None: |
| 443 |
"""Log the request details.""" |
| 444 |
|
| 445 |
security_level = ARConfig.get(ARConfKey.DEBUG_PAYLOAD) |
| 446 |
|
| 447 |
# Prepare payload to log |
| 448 |
payload_to_log = self._payload_for_logging( |
| 449 |
security_level, endpoint, payload |
| 450 |
) |
| 451 |
|
| 452 |
if payload_to_log is None: |
| 453 |
_LOGGER.debug("Sending request to `%s`", endpoint) |
| 454 |
else: |
| 455 |
_LOGGER.debug( |
| 456 |
"Sending request to `%s` with payload: %s", |
| 457 |
endpoint, |
| 458 |
payload_to_log, |
| 459 |
) |
| 460 |
|
| 461 |
async def _send_request( # noqa: C901, PLR0912 |
| 462 |
self, |
| 463 |
endpoint: EndpointType, |
| 464 |
payload: str | None = None, |
| 465 |
headers: dict[str, str] | None = None, |
| 466 |
request_type: RequestType = RequestType.POST, |
| 467 |
) -> tuple[int, dict[str, str], str]: |
| 468 |
"""Send a request to the device.""" |
| 469 |
|
| 470 |
# Send request |
| 471 |
try: |
| 472 |
# Log request |
| 473 |
self._log_request(endpoint, payload) |
| 474 |
|
| 475 |
# Make the request |
| 476 |
resp_status, resp_headers, resp_content = await self._make_request( |
| 477 |
endpoint, |
| 478 |
payload, |
| 479 |
headers, |
| 480 |
request_type, |
| 481 |
) |
| 482 |
|
| 483 |
# Raise exception on 404 |
| 484 |
if resp_status == HTTPStatus.NOT_FOUND: |
| 485 |
raise AsusRouter404Error(f"Endpoint {endpoint} not found") |
| 486 |
|
| 487 |
# Raise exception on non-200 status |
| 488 |
if resp_status != HTTPStatus.OK: |
| 489 |
raise AsusRouterAccessError( |
| 490 |
f"Cannot access {endpoint}, status {resp_status}" |
| 491 |
) |
| 492 |
|
| 493 |
# Check for access errors |
| 494 |
if "error_status" in resp_content: |
| 495 |
handle_access_error( |
| 496 |
endpoint, resp_status, resp_headers, resp_content |
| 497 |
) |
| 498 |
|
| 499 |
# Reset fallback tracker if multiple fallbacks are allowed |
| 500 |
if self.config.get(ARCCKey.ALLOW_MULTIPLE_FALLBACKS): |
| 501 |
self._used_fallbacks.clear() |
| 502 |
|
| 503 |
# Return the response |
| 504 |
return (resp_status, resp_headers, resp_content) |
| 505 |
except ssl.SSLCertVerificationError as ex: |
| 506 |
if self.config.get( |
| 507 |
ARCCKey.STRICT_SSL |
| 508 |
) is False and self.config.get(ARCCKey.ALLOW_FALLBACK): |
| 509 |
_LOGGER.warning( |
| 510 |
"Cannot verify SSL certificate. Since `STRICT_SSL` " |
| 511 |
"configuration is disabled, falling back to HTTP " |
| 512 |
"with a default port" |
| 513 |
) |
| 514 |
await self._fallback() |
| 515 |
# Repeat the attempt |
| 516 |
return await self._send_request( |
| 517 |
endpoint, payload, headers, request_type |
| 518 |
) |
| 519 |
raise AsusRouterSSLCertificateError( |
| 520 |
"SSL certificate verification failed. Your configuration " |
| 521 |
"requires a strict SSL certificate verification." |
| 522 |
) from ex |
| 523 |
except aiohttp.ClientConnectorError as ex: |
| 524 |
# Are automatic fallbacks allowed? |
| 525 |
if self.config.get(ARCCKey.ALLOW_FALLBACK): |
| 526 |
return await self._async_handle_fallback( |
| 527 |
callback=self._send_request, |
| 528 |
endpoint=endpoint, |
| 529 |
payload=payload, |
| 530 |
headers=headers, |
| 531 |
request_type=request_type, |
| 532 |
) |
| 533 |
|
| 534 |
self.reset_connection() |
| 535 |
raise AsusRouterConnectionError( |
| 536 |
f"Cannot connect to `{self._hostname}` on port " |
| 537 |
f"`{self.port}`. Failed in `_send_request` with error: `{ex}`" |
| 538 |
) from ex |
| 539 |
except (aiohttp.ClientConnectionError, aiohttp.ClientOSError) as ex: |
| 540 |
raise AsusRouterConnectionError( |
| 541 |
f"Cannot connect to `{self._hostname}` on port " |
| 542 |
f"`{self.port}`. Failed in `_send_request` with error: `{ex}`" |
| 543 |
) from ex |
| 544 |
except (TimeoutError, asyncio.CancelledError) as ex: |
| 545 |
raise AsusRouterTimeoutError( |
| 546 |
f"Data cannot be retrieved due to an asyncio error. " |
| 547 |
f"Connection failed: {ex}" |
| 548 |
) from ex |
| 549 |
except Exception as ex: # pylint: disable=broad-except |
| 550 |
_LOGGER.debug( |
| 551 |
"Unexpected error sending request to %s: %s", |
| 552 |
endpoint, |
| 553 |
ex, |
| 554 |
) |
| 555 |
raise ex |
| 556 |
|
| 557 |
async def _async_handle_fallback( |
| 558 |
self, callback: Callable[..., Awaitable[_T]], **kwargs: Any |
| 559 |
) -> _T: |
| 560 |
"""Handle fallbacks on sending requests. |
| 561 |
|
| 562 |
The matrix for the automatic feedback is as follows: |
| 563 |
|
| 564 |
| Con @ Port | New @ port | Required config | |
| 565 |
| --------------- | --------------- | --------------------------- | |
| 566 |
| HTTPS @ Custom | HTTPS @ Default | | |
| 567 |
| HTTPS @ Default | HTTP @ Default | STRICT_SSL not set | |
| 568 |
| HTTP @ Custom | HTTP @ Default | | |
| 569 |
| HTTP @ Default | HTTPS @ Default | ALLOW_UPGRADE_HTTP_TO_HTTPS | |
| 570 |
""" |
| 571 |
|
| 572 |
if self.config.get(ARCCKey.USE_SSL): |
| 573 |
# From custom HTTPS to default HTTPS |
| 574 |
if self.port != DEFAULT_PORT_HTTPS: |
| 575 |
if self._used_fallbacks.get(ConnectionFallback.HTTPS): |
| 576 |
raise AsusRouterFallbackLoopError( |
| 577 |
"Fallback loop detected trying to heal HTTPS " |
| 578 |
f"connection with set port `{self.port}`" |
| 579 |
) |
| 580 |
|
| 581 |
_LOGGER.warning( |
| 582 |
"Cannot connect on the provided HTTPS port `%d`. " |
| 583 |
"Will fallback to the default port `%d`", |
| 584 |
self.port, |
| 585 |
DEFAULT_PORT_HTTPS, |
| 586 |
) |
| 587 |
await self._fallback(fallback_type=ConnectionFallback.HTTPS) |
| 588 |
# Repeat the attempt |
| 589 |
return await callback(**kwargs) |
| 590 |
|
| 591 |
# From default HTTPS to default HTTP |
| 592 |
if self.config.get(ARCCKey.STRICT_SSL): |
| 593 |
raise AsusRouterFallbackForbiddenError( |
| 594 |
"Fallback from HTTPS to HTTP connection is forbidden " |
| 595 |
"by the `STRICT_SSL` configuration option" |
| 596 |
) |
| 597 |
if self._used_fallbacks.get(ConnectionFallback.HTTP): |
| 598 |
raise AsusRouterFallbackLoopError( |
| 599 |
"Fallback loop detected trying to heal HTTPS " |
| 600 |
"by switching to HTTP" |
| 601 |
) |
| 602 |
_LOGGER.warning( |
| 603 |
"Cannot connect on the default HTTPS port `%d`. " |
| 604 |
"Will fallback to the HTTP connection " |
| 605 |
"on default port `%d`", |
| 606 |
DEFAULT_PORT_HTTPS, |
| 607 |
DEFAULT_PORT_HTTP, |
| 608 |
) |
| 609 |
await self._fallback(fallback_type=ConnectionFallback.HTTP) |
| 610 |
# Repeat the attempt |
| 611 |
return await callback(**kwargs) |
| 612 |
|
| 613 |
# From custom HTTP to default HTTP |
| 614 |
if self.port != DEFAULT_PORT_HTTP: |
| 615 |
if self._used_fallbacks.get(ConnectionFallback.HTTP): |
| 616 |
raise AsusRouterFallbackLoopError( |
| 617 |
"Fallback loop detected trying to heal HTTP " |
| 618 |
"by upgrading to HTTPS" |
| 619 |
) |
| 620 |
|
| 621 |
_LOGGER.warning( |
| 622 |
"Cannot connect on the custom HTTP port `%d`. " |
| 623 |
"Will try using the default HTTP port `%d`", |
| 624 |
self.port, |
| 625 |
DEFAULT_PORT_HTTP, |
| 626 |
) |
| 627 |
await self._fallback(fallback_type=ConnectionFallback.HTTP) |
| 628 |
# Repeat the attempt |
| 629 |
return await callback(**kwargs) |
| 630 |
|
| 631 |
# From default HTTP to default HTTPS |
| 632 |
if self.config.get(ARCCKey.ALLOW_UPGRADE_HTTP_TO_HTTPS): |
| 633 |
# Force certificate verification |
| 634 |
self.config.set(ARCCKey.VERIFY_SSL, True) |
| 635 |
if self._used_fallbacks.get(ConnectionFallback.HTTPS): |
| 636 |
raise AsusRouterFallbackLoopError( |
| 637 |
"Fallback loop detected trying to heal HTTP " |
| 638 |
"by upgrading to HTTPS" |
| 639 |
) |
| 640 |
|
| 641 |
_LOGGER.warning( |
| 642 |
"Cannot connect on the default HTTP port `%d`. " |
| 643 |
"Will try upgrading to the default HTTPS port `%d`", |
| 644 |
self.port, |
| 645 |
DEFAULT_PORT_HTTPS, |
| 646 |
) |
| 647 |
await self._fallback(fallback_type=ConnectionFallback.HTTPS) |
| 648 |
# Repeat the attempt |
| 649 |
return await callback(**kwargs) |
| 650 |
|
| 651 |
raise AsusRouterFallbackError( |
| 652 |
"Automatic fallback failed. Consider disabling it." |
| 653 |
) |
| 654 |
|
| 655 |
async def _fallback( |
| 656 |
self, fallback_type: ConnectionFallback | None = None |
| 657 |
) -> None: |
| 658 |
"""Perform connection fallback.""" |
| 659 |
|
| 660 |
if not fallback_type: |
| 661 |
fallback_type = ConnectionFallback.HTTP |
| 662 |
|
| 663 |
# Mark fallback type as used to avoid loops |
| 664 |
self._used_fallbacks[fallback_type] = True |
| 665 |
|
| 666 |
# Set fallback connection parameters |
| 667 |
match fallback_type: |
| 668 |
case ConnectionFallback.HTTP: |
| 669 |
self.config.set(ARCCKey.USE_SSL, False) |
| 670 |
self.config.set(ARCCKey.PORT, DEFAULT_PORT_HTTP) |
| 671 |
# We should not change the VERIFY_SSL setting here |
| 672 |
|
| 673 |
case ConnectionFallback.HTTPS: |
| 674 |
self.config.set(ARCCKey.USE_SSL, True) |
| 675 |
self.config.set(ARCCKey.PORT, DEFAULT_PORT_HTTPS) |
| 676 |
# We should not change the VERIFY_SSL setting here |
| 677 |
|
| 678 |
case ConnectionFallback.HTTPS_UNSAFE: |
| 679 |
self.config.set(ARCCKey.USE_SSL, True) |
| 680 |
self.config.set(ARCCKey.PORT, DEFAULT_PORT_HTTPS) |
| 681 |
self.config.set(ARCCKey.VERIFY_SSL, False) |
| 682 |
|
| 683 |
case _: |
| 684 |
raise AsusRouterNotImplementedError( |
| 685 |
f"Connection fallback not implemented: {fallback_type}" |
| 686 |
) |
| 687 |
|
| 688 |
# Reconnect with new parameters |
| 689 |
# If there is an in-flight connect task, cancel it first so the |
| 690 |
# fallback can start a fresh immediate connection attempt instead of |
| 691 |
# awaiting the old (failing) task until its timeout. |
| 692 |
old_task: asyncio.Task | None = None |
| 693 |
async with self._connect_task_lock: |
| 694 |
if ( |
| 695 |
self._connect_task is not None |
| 696 |
and not self._connect_task.done() |
| 697 |
): |
| 698 |
_LOGGER.debug( |
| 699 |
"Cancelling in-flight connect attempt to " |
| 700 |
"allow fallback reconnect" |
| 701 |
) |
| 702 |
# Capture and cancel the in-flight connect task |
| 703 |
# so we can await it later (outside the lock) |
| 704 |
# and consume any exception it raises. |
| 705 |
old_task = self._connect_task |
| 706 |
with contextlib.suppress(Exception): |
| 707 |
old_task.cancel() |
| 708 |
# Clear reference so a new connect can be started by fallback |
| 709 |
self._connect_task = None |
| 710 |
|
| 711 |
# Await the cancelled task to consume its exception (if any). |
| 712 |
# Do this outside the connect_task_lock to avoid deadlocks. |
| 713 |
if old_task is not None: |
| 714 |
try: |
| 715 |
await old_task |
| 716 |
except asyncio.CancelledError: |
| 717 |
# expected due to cancel() |
| 718 |
pass |
| 719 |
except Exception as exc: # noqa: BLE001 - consume/log other errors |
| 720 |
_LOGGER.debug( |
| 721 |
"In-flight connect task finished after cancel with: %s", |
| 722 |
exc, |
| 723 |
) |
| 724 |
|
| 725 |
# Reset connection state and perform a bounded reconnect |
| 726 |
# for the fallback. |
| 727 |
self.reset_connection() |
| 728 |
await self.async_connect( |
| 729 |
t_overwrite=DEFAULT_TIMEOUT_FALLBACK, block_error=True |
| 730 |
) |
| 731 |
|
| 732 |
async def async_query( |
| 733 |
self, |
| 734 |
endpoint: EndpointType, |
| 735 |
payload: str | None = None, |
| 736 |
headers: dict[str, str] | None = None, |
| 737 |
request_type: RequestType = RequestType.POST, |
| 738 |
) -> tuple[int, dict[str, str], str]: |
| 739 |
"""Send a request to the device.""" |
| 740 |
|
| 741 |
# If not connected, try to connect |
| 742 |
if not self._connected: |
| 743 |
_LOGGER.debug("Not connected to %s. Connecting...", self._hostname) |
| 744 |
await self.async_connect() |
| 745 |
|
| 746 |
# If still not connected, raise an error |
| 747 |
if not self._connected: |
| 748 |
raise AsusRouterTimeoutError( |
| 749 |
"Data cannot be retrieved. Connection failed" |
| 750 |
) |
| 751 |
|
| 752 |
# Send the request |
| 753 |
_LOGGER.debug( |
| 754 |
"Sending `%s` request to `%s`", request_type, self._hostname |
| 755 |
) |
| 756 |
return await self._send_request( |
| 757 |
endpoint, payload, headers, request_type |
| 758 |
) |
| 759 |
|
| 760 |
async def _make_request( |
| 761 |
self, |
| 762 |
endpoint: EndpointType, |
| 763 |
payload: str | None = None, |
| 764 |
headers: dict[str, str] | None = None, |
| 765 |
request_type: RequestType = RequestType.POST, |
| 766 |
) -> Any: |
| 767 |
"""Make a post request to the device.""" |
| 768 |
|
| 769 |
# Check if a session is available |
| 770 |
if self._session is None or self._session.closed: |
| 771 |
# If no session is available, we cannot be connected to the device |
| 772 |
_LOGGER.debug("No session available. Creating a new one") |
| 773 |
# We will create a new session and retry the request |
| 774 |
self.reset_connection() |
| 775 |
self._session = self._new_session() |
| 776 |
# Reconnect |
| 777 |
await self.async_connect() |
| 778 |
# Retry the request |
| 779 |
return await self._make_request( |
| 780 |
endpoint, payload, headers, request_type |
| 781 |
) |
| 782 |
|
| 783 |
# Check headers |
| 784 |
if not headers: |
| 785 |
headers = self._header |
| 786 |
|
| 787 |
# Generate the url |
| 788 |
url = f"{self.webpanel}/{endpoint.value}" |
| 789 |
|
| 790 |
# Add get parameters if needed |
| 791 |
if request_type == RequestType.GET and payload: |
| 792 |
url_payload = payload.replace(";", "&") |
| 793 |
url = f"{url}?{url_payload}" |
| 794 |
|
| 795 |
# Process the payload to be sent |
| 796 |
payload_to_send = quote(payload) if payload else None |
| 797 |
|
| 798 |
# Send the request |
| 799 |
async with self._session.request( |
| 800 |
request_type.value, |
| 801 |
url, |
| 802 |
data=payload_to_send if request_type == RequestType.POST else None, |
| 803 |
headers=headers, |
| 804 |
ssl=self.config.get(ARCCKey.VERIFY_SSL), |
| 805 |
) as response: |
| 806 |
# Read the status code |
| 807 |
resp_status = response.status |
| 808 |
|
| 809 |
# Read the response headers |
| 810 |
resp_headers = response.headers |
| 811 |
|
| 812 |
# Read the response |
| 813 |
try: |
| 814 |
resp_content = await response.text() |
| 815 |
except UnicodeDecodeError: |
| 816 |
_LOGGER.debug("Cannot decode response. Will ignore errors") |
| 817 |
resp_content = await response.text(errors="ignore") |
| 818 |
|
| 819 |
# Call the dumpback if available |
| 820 |
if self._dumpback is not None: |
| 821 |
await self._dumpback( |
| 822 |
endpoint, payload, resp_status, resp_headers, resp_content |
| 823 |
) |
| 824 |
|
| 825 |
# Return the response |
| 826 |
return (resp_status, resp_headers, resp_content) |
| 827 |
|
| 828 |
def reset_connection(self) -> None: |
| 829 |
"""Reset connection variables.""" |
| 830 |
|
| 831 |
if not self._connected: |
| 832 |
return |
| 833 |
|
| 834 |
_LOGGER.debug("Resetting connection to %s", self._hostname) |
| 835 |
|
| 836 |
self._connected = False |
| 837 |
self._token = None |
| 838 |
self._header = None |
| 839 |
|
| 840 |
@property |
| 841 |
def config(self) -> ARConnectionConfig: |
| 842 |
"""Return connection config.""" |
| 843 |
|
| 844 |
return self._config |
| 845 |
|
| 846 |
@property |
| 847 |
def connected(self) -> bool: |
| 848 |
"""Return connection status.""" |
| 849 |
|
| 850 |
return self._connected |
| 851 |
|
| 852 |
@property |
| 853 |
def http(self) -> str: |
| 854 |
"""Return HTTP scheme.""" |
| 855 |
|
| 856 |
return "https" if self._config.get(ARCCKey.USE_SSL) else "http" |
| 857 |
|
| 858 |
@property |
| 859 |
def port(self) -> int: |
| 860 |
"""Return port number.""" |
| 861 |
|
| 862 |
return safe_int_config(self._config.get(ARCCKey.PORT)) |
| 863 |
|
| 864 |
@property |
| 865 |
def webpanel(self) -> str: |
| 866 |
"""Return web panel URL.""" |
| 867 |
|
| 868 |
return f"{self.http}://{self._hostname}:{self.port}" |