| 1 |
"""async_upnp_client.aiohttp module.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import logging |
| 5 |
from asyncio.events import AbstractEventLoop, AbstractServer |
| 6 |
from ipaddress import ip_address |
| 7 |
from typing import Mapping |
| 8 |
from urllib.parse import urlparse |
| 9 |
|
| 10 |
import aiohttp.web |
| 11 |
from aiohttp import ( |
| 12 |
ClientConnectionError, |
| 13 |
ClientError, |
| 14 |
ClientResponseError, |
| 15 |
ClientSession, |
| 16 |
ClientTimeout, |
| 17 |
) |
| 18 |
|
| 19 |
from async_upnp_client.client import UpnpRequester |
| 20 |
from async_upnp_client.const import ( |
| 21 |
AddressTupleVXType, |
| 22 |
HttpRequest, |
| 23 |
HttpResponse, |
| 24 |
IPvXAddress, |
| 25 |
) |
| 26 |
from async_upnp_client.event_handler import UpnpEventHandler, UpnpNotifyServer |
| 27 |
from async_upnp_client.exceptions import ( |
| 28 |
UpnpClientResponseError, |
| 29 |
UpnpCommunicationError, |
| 30 |
UpnpConnectionError, |
| 31 |
UpnpConnectionTimeoutError, |
| 32 |
UpnpServerOSError, |
| 33 |
) |
| 34 |
|
| 35 |
_LOGGER = logging.getLogger(__name__) |
| 36 |
_LOGGER_TRAFFIC_UPNP = logging.getLogger("async_upnp_client.traffic.upnp") |
| 37 |
|
| 38 |
|
| 39 |
def _fixed_host_header(url: str) -> dict[str, str]: |
| 40 |
"""Strip scope_id from IPv6 host, if needed.""" |
| 41 |
if "%" not in url: |
| 42 |
return {} |
| 43 |
|
| 44 |
url_parts = urlparse(url) |
| 45 |
if url_parts.hostname and "%" in url_parts.hostname: |
| 46 |
idx = url_parts.hostname.rindex("%") |
| 47 |
fixed_hostname = url_parts.hostname[:idx] |
| 48 |
if ":" in fixed_hostname: |
| 49 |
fixed_hostname = f"[{fixed_hostname}]" |
| 50 |
host = f"{fixed_hostname}:{url_parts.port}" if url_parts.port else fixed_hostname |
| 51 |
return {"Host": host} |
| 52 |
|
| 53 |
return {} |
| 54 |
|
| 55 |
|
| 56 |
class AiohttpRequester(UpnpRequester): |
| 57 |
"""Standard AioHttpUpnpRequester, to be used with UpnpFactory.""" |
| 58 |
|
| 59 |
# pylint: disable=too-few-public-methods |
| 60 |
|
| 61 |
def __init__(self, timeout: int = 5, http_headers: Mapping[str, str] | None = None) -> None: |
| 62 |
"""Initialize.""" |
| 63 |
self._timeout = ClientTimeout(total=float(timeout)) |
| 64 |
self._http_headers = http_headers or {} |
| 65 |
|
| 66 |
async def async_http_request( |
| 67 |
self, |
| 68 |
http_request: HttpRequest, |
| 69 |
) -> HttpResponse: |
| 70 |
"""Do a HTTP request.""" |
| 71 |
req_headers = { |
| 72 |
**_fixed_host_header(http_request.url), |
| 73 |
**self._http_headers, |
| 74 |
**(http_request.headers or {}), |
| 75 |
} |
| 76 |
|
| 77 |
log_traffic = _LOGGER_TRAFFIC_UPNP.isEnabledFor(logging.DEBUG) |
| 78 |
if log_traffic: # pragma: no branch |
| 79 |
_LOGGER_TRAFFIC_UPNP.debug( |
| 80 |
"Sending request:\n%s %s\n%s\n%s\n", |
| 81 |
http_request.method, |
| 82 |
http_request.url, |
| 83 |
"\n".join([key + ": " + value for key, value in (req_headers or {}).items()]), |
| 84 |
http_request.body or "", |
| 85 |
) |
| 86 |
|
| 87 |
try: |
| 88 |
async with ClientSession() as session: |
| 89 |
async with session.request( |
| 90 |
http_request.method, |
| 91 |
http_request.url, |
| 92 |
headers=req_headers, |
| 93 |
data=http_request.body, |
| 94 |
timeout=self._timeout, |
| 95 |
) as response: |
| 96 |
status = response.status |
| 97 |
resp_headers: Mapping = response.headers or {} |
| 98 |
resp_body = await response.read() |
| 99 |
|
| 100 |
if log_traffic: # pragma: no branch |
| 101 |
_LOGGER_TRAFFIC_UPNP.debug( |
| 102 |
"Got response from %s %s:\n%s\n%s\n\n%s", |
| 103 |
http_request.method, |
| 104 |
http_request.url, |
| 105 |
status, |
| 106 |
"\n".join([key + ": " + value for key, value in resp_headers.items()]), |
| 107 |
resp_body, |
| 108 |
) |
| 109 |
|
| 110 |
resp_body_text = await response.text() |
| 111 |
except asyncio.TimeoutError as err: |
| 112 |
raise UpnpConnectionTimeoutError(repr(err)) from err |
| 113 |
except ClientConnectionError as err: |
| 114 |
raise UpnpConnectionError(repr(err)) from err |
| 115 |
except ClientResponseError as err: |
| 116 |
raise UpnpClientResponseError( |
| 117 |
request_info=err.request_info, |
| 118 |
history=err.history, |
| 119 |
status=err.status, |
| 120 |
message=err.message, |
| 121 |
headers=err.headers, |
| 122 |
) from err |
| 123 |
except ClientError as err: |
| 124 |
raise UpnpCommunicationError(repr(err)) from err |
| 125 |
except UnicodeDecodeError as err: |
| 126 |
raise UpnpCommunicationError(repr(err)) from err |
| 127 |
|
| 128 |
return HttpResponse(status, resp_headers, resp_body_text) |
| 129 |
|
| 130 |
|
| 131 |
class AiohttpSessionRequester(UpnpRequester): |
| 132 |
""" |
| 133 |
Standard AiohttpSessionRequester, to be used with UpnpFactory. |
| 134 |
|
| 135 |
With pluggable session. |
| 136 |
""" |
| 137 |
|
| 138 |
# pylint: disable=too-few-public-methods |
| 139 |
|
| 140 |
def __init__( |
| 141 |
self, |
| 142 |
session: ClientSession, |
| 143 |
with_sleep: bool = False, |
| 144 |
timeout: int = 5, |
| 145 |
http_headers: Mapping[str, str] | None = None, |
| 146 |
) -> None: |
| 147 |
"""Initialize.""" |
| 148 |
self._session = session |
| 149 |
self._with_sleep = with_sleep |
| 150 |
self._timeout = ClientTimeout(total=float(timeout)) |
| 151 |
self._http_headers = http_headers or {} |
| 152 |
|
| 153 |
async def async_http_request( |
| 154 |
self, |
| 155 |
http_request: HttpRequest, |
| 156 |
) -> HttpResponse: |
| 157 |
"""Do a HTTP request with a retry on ServerDisconnectedError. |
| 158 |
|
| 159 |
The HTTP/1.1 spec allows the server to disconnect at any time. |
| 160 |
We want to retry the request in this event. |
| 161 |
""" |
| 162 |
for _ in range(2): |
| 163 |
try: |
| 164 |
return await self._async_http_request(http_request) |
| 165 |
except ClientConnectionError as err: |
| 166 |
_LOGGER.debug( |
| 167 |
"%r during request %s %s; retrying", |
| 168 |
err, |
| 169 |
http_request.method, |
| 170 |
http_request.url, |
| 171 |
) |
| 172 |
try: |
| 173 |
return await self._async_http_request(http_request) |
| 174 |
except ClientConnectionError as err: |
| 175 |
raise UpnpConnectionError(repr(err)) from err |
| 176 |
|
| 177 |
async def _async_http_request( |
| 178 |
self, |
| 179 |
http_request: HttpRequest, |
| 180 |
) -> HttpResponse: |
| 181 |
"""Do a HTTP request.""" |
| 182 |
# pylint: disable=too-many-arguments |
| 183 |
req_headers = { |
| 184 |
**_fixed_host_header(http_request.url), |
| 185 |
**self._http_headers, |
| 186 |
**(http_request.headers or {}), |
| 187 |
} |
| 188 |
|
| 189 |
log_traffic = _LOGGER_TRAFFIC_UPNP.isEnabledFor(logging.DEBUG) |
| 190 |
if log_traffic: # pragma: no branch |
| 191 |
_LOGGER_TRAFFIC_UPNP.debug( |
| 192 |
"Sending request:\n%s %s\n%s\n%s\n", |
| 193 |
http_request.method, |
| 194 |
http_request.url, |
| 195 |
"\n".join([key + ": " + value for key, value in (req_headers or {}).items()]), |
| 196 |
http_request.body or "", |
| 197 |
) |
| 198 |
|
| 199 |
if self._with_sleep: |
| 200 |
await asyncio.sleep(0) |
| 201 |
|
| 202 |
try: |
| 203 |
async with self._session.request( |
| 204 |
http_request.method, |
| 205 |
http_request.url, |
| 206 |
headers=req_headers, |
| 207 |
data=http_request.body, |
| 208 |
timeout=self._timeout, |
| 209 |
) as response: |
| 210 |
status = response.status |
| 211 |
resp_headers: Mapping = response.headers or {} |
| 212 |
resp_body = await response.read() |
| 213 |
|
| 214 |
if log_traffic: # pragma: no branch |
| 215 |
_LOGGER_TRAFFIC_UPNP.debug( |
| 216 |
"Got response from %s %s:\n%s\n%s\n\n%s", |
| 217 |
http_request.method, |
| 218 |
http_request.url, |
| 219 |
status, |
| 220 |
"\n".join([key + ": " + value for key, value in resp_headers.items()]), |
| 221 |
resp_body, |
| 222 |
) |
| 223 |
|
| 224 |
resp_body_text = await response.text() |
| 225 |
except asyncio.TimeoutError as err: |
| 226 |
raise UpnpConnectionTimeoutError(repr(err)) from err |
| 227 |
except ClientConnectionError: |
| 228 |
raise |
| 229 |
except ClientResponseError as err: |
| 230 |
raise UpnpClientResponseError( |
| 231 |
request_info=err.request_info, |
| 232 |
history=err.history, |
| 233 |
status=err.status, |
| 234 |
message=err.message, |
| 235 |
headers=err.headers, |
| 236 |
) from err |
| 237 |
except ClientError as err: |
| 238 |
raise UpnpCommunicationError(repr(err)) from err |
| 239 |
except UnicodeDecodeError as err: |
| 240 |
raise UpnpCommunicationError(repr(err)) from err |
| 241 |
|
| 242 |
return HttpResponse(status, resp_headers, resp_body_text) |
| 243 |
|
| 244 |
|
| 245 |
class AiohttpNotifyServer(UpnpNotifyServer): |
| 246 |
""" |
| 247 |
Aio HTTP Server to handle incoming events. |
| 248 |
|
| 249 |
It is advisable to use one AiohttpNotifyServer per listening IP, |
| 250 |
UpnpDevices can share a AiohttpNotifyServer/UpnpEventHandler. |
| 251 |
""" |
| 252 |
|
| 253 |
def __init__( |
| 254 |
self, |
| 255 |
requester: UpnpRequester, |
| 256 |
source: AddressTupleVXType, |
| 257 |
callback_url: str | None = None, |
| 258 |
loop: AbstractEventLoop | None = None, |
| 259 |
) -> None: |
| 260 |
"""Initialize.""" |
| 261 |
self._source = source |
| 262 |
self._callback_url = callback_url |
| 263 |
self._loop = loop or asyncio.get_event_loop() |
| 264 |
|
| 265 |
self._aiohttp_server: aiohttp.web.Server | None = None |
| 266 |
self._server: AbstractServer | None = None |
| 267 |
|
| 268 |
self.event_handler = UpnpEventHandler(self, requester) |
| 269 |
|
| 270 |
async def async_start_server(self) -> None: |
| 271 |
"""Start the HTTP server.""" |
| 272 |
self._aiohttp_server = aiohttp.web.Server(self._handle_request) |
| 273 |
|
| 274 |
try: |
| 275 |
self._server = await self._loop.create_server(self._aiohttp_server, self._source[0], self._source[1]) |
| 276 |
except OSError as err: |
| 277 |
_LOGGER.error( |
| 278 |
"Failed to create HTTP server at %s:%d: %s", |
| 279 |
self._source[0], |
| 280 |
self._source[1], |
| 281 |
err, |
| 282 |
) |
| 283 |
raise UpnpServerOSError( |
| 284 |
errno=err.errno, |
| 285 |
strerror=err.strerror, |
| 286 |
) from err |
| 287 |
|
| 288 |
# Get listening port. |
| 289 |
socks = self._server.sockets |
| 290 |
assert socks and len(socks) == 1 |
| 291 |
sock = socks[0] |
| 292 |
self._source = sock.getsockname() |
| 293 |
_LOGGER.debug("New source for UpnpNotifyServer: %s", self._source) |
| 294 |
|
| 295 |
async def async_stop_server(self) -> None: |
| 296 |
"""Stop the HTTP server.""" |
| 297 |
await self.event_handler.async_unsubscribe_all() |
| 298 |
|
| 299 |
if self._aiohttp_server: |
| 300 |
await self._aiohttp_server.shutdown(10) |
| 301 |
self._aiohttp_server = None |
| 302 |
|
| 303 |
if self._server: |
| 304 |
self._server.close() |
| 305 |
self._server = None |
| 306 |
|
| 307 |
async def _handle_request(self, request: aiohttp.web.BaseRequest) -> aiohttp.web.Response: |
| 308 |
"""Handle incoming requests.""" |
| 309 |
_LOGGER.debug("Received request: %s", request) |
| 310 |
log_traffic = _LOGGER_TRAFFIC_UPNP.isEnabledFor(logging.DEBUG) |
| 311 |
|
| 312 |
headers = request.headers |
| 313 |
body = await request.text() |
| 314 |
if log_traffic: |
| 315 |
_LOGGER_TRAFFIC_UPNP.debug( |
| 316 |
"Incoming request:\nNOTIFY\n%s\n\n%s", |
| 317 |
"\n".join([key + ": " + value for key, value in headers.items()]), |
| 318 |
body, |
| 319 |
) |
| 320 |
|
| 321 |
if request.method != "NOTIFY": |
| 322 |
_LOGGER.debug("Not notify") |
| 323 |
return aiohttp.web.Response(status=405) |
| 324 |
|
| 325 |
http_request = HttpRequest(request.method, self.callback_url, request.headers, body) |
| 326 |
status = await self.event_handler.handle_notify(http_request) |
| 327 |
_LOGGER.debug("NOTIFY response status: %s", status) |
| 328 |
if log_traffic: |
| 329 |
_LOGGER_TRAFFIC_UPNP.debug("Sending response: %s", status) |
| 330 |
|
| 331 |
return aiohttp.web.Response(status=status) |
| 332 |
|
| 333 |
@property |
| 334 |
def listen_ip(self) -> IPvXAddress: |
| 335 |
"""Get listening IP Address.""" |
| 336 |
return ip_address(self._source[0]) |
| 337 |
|
| 338 |
@property |
| 339 |
def listen_host(self) -> str: |
| 340 |
"""Get listening host.""" |
| 341 |
return str(self.listen_ip) |
| 342 |
|
| 343 |
@property |
| 344 |
def listen_port(self) -> int: |
| 345 |
"""Get the listening port.""" |
| 346 |
return self._source[1] |
| 347 |
|
| 348 |
@property |
| 349 |
def callback_url(self) -> str: |
| 350 |
"""Return callback URL on which we are callable.""" |
| 351 |
listen_ip = self.listen_ip |
| 352 |
return self._callback_url or ( |
| 353 |
self._callback_url or f"http://{self.listen_host}:{self.listen_port}/notify" |
| 354 |
if listen_ip.version == 4 |
| 355 |
else f"http://[{self.listen_host}]:{self.listen_port}/notify" |
| 356 |
) |