| 1 |
"""async_upnp_client.ssdp module.""" |
| 2 |
|
| 3 |
import logging |
| 4 |
import socket |
| 5 |
import sys |
| 6 |
from asyncio import BaseTransport, DatagramProtocol, DatagramTransport |
| 7 |
from asyncio.events import AbstractEventLoop |
| 8 |
from datetime import datetime |
| 9 |
from functools import lru_cache |
| 10 |
from ipaddress import IPv4Address, IPv6Address, ip_address |
| 11 |
from typing import Any, Callable, Coroutine, cast |
| 12 |
from urllib.parse import urlsplit, urlunsplit |
| 13 |
|
| 14 |
from aiohttp.http_exceptions import InvalidHeader |
| 15 |
from aiohttp.http_parser import HeadersParser |
| 16 |
from multidict import CIMultiDictProxy |
| 17 |
|
| 18 |
from async_upnp_client.const import ( |
| 19 |
AddressTupleV6Type, |
| 20 |
AddressTupleVXType, |
| 21 |
IPvXAddress, |
| 22 |
SsdpHeaders, |
| 23 |
UniqueDeviceName, |
| 24 |
) |
| 25 |
from async_upnp_client.exceptions import UpnpError |
| 26 |
from async_upnp_client.utils import CaseInsensitiveDict, lowerstr |
| 27 |
|
| 28 |
SSDP_PORT = 1900 |
| 29 |
SSDP_IP_V4 = "239.255.255.250" |
| 30 |
SSDP_IP_V6_LINK_LOCAL = "FF02::C" |
| 31 |
SSDP_IP_V6_SITE_LOCAL = "FF05::C" |
| 32 |
SSDP_IP_V6_ORGANISATION_LOCAL = "FF08::C" |
| 33 |
SSDP_IP_V6_GLOBAL = "FF0E::C" |
| 34 |
SSDP_IP_V6 = SSDP_IP_V6_LINK_LOCAL |
| 35 |
SSDP_TARGET_V4 = (SSDP_IP_V4, SSDP_PORT) |
| 36 |
SSDP_TARGET_V6 = ( |
| 37 |
SSDP_IP_V6, |
| 38 |
SSDP_PORT, |
| 39 |
0, |
| 40 |
0, |
| 41 |
) |
| 42 |
SSDP_TARGET = SSDP_TARGET_V4 |
| 43 |
SSDP_ST_ALL = "ssdp:all" |
| 44 |
SSDP_ST_ROOTDEVICE = "upnp:rootdevice" |
| 45 |
SSDP_MX = 4 |
| 46 |
SSDP_DISCOVER = '"ssdp:discover"' |
| 47 |
|
| 48 |
_LOGGER = logging.getLogger(__name__) |
| 49 |
_LOGGER_TRAFFIC_SSDP = logging.getLogger("async_upnp_client.traffic.ssdp") |
| 50 |
|
| 51 |
|
| 52 |
def get_host_string(addr: AddressTupleVXType) -> str: |
| 53 |
"""Construct host string from address tuple.""" |
| 54 |
if len(addr) == 4: |
| 55 |
if addr[3]: |
| 56 |
return f"{addr[0]}%{addr[3]}" |
| 57 |
|
| 58 |
return addr[0] |
| 59 |
|
| 60 |
|
| 61 |
def get_host_port_string(addr: AddressTupleVXType) -> str: |
| 62 |
"""Return a properly escaped host port pair.""" |
| 63 |
host = get_host_string(addr) |
| 64 |
if ":" in host: |
| 65 |
return f"[{host}]:{addr[1]}" |
| 66 |
return f"{host}:{addr[1]}" |
| 67 |
|
| 68 |
|
| 69 |
@lru_cache(maxsize=256) |
| 70 |
def get_adjusted_url(url: str, addr: AddressTupleVXType) -> str: |
| 71 |
"""Adjust a url with correction for link local scope.""" |
| 72 |
if len(addr) < 4: |
| 73 |
return url |
| 74 |
|
| 75 |
if not addr[3]: |
| 76 |
return url |
| 77 |
|
| 78 |
data = urlsplit(url) |
| 79 |
assert data.hostname |
| 80 |
try: |
| 81 |
address = ip_address(data.hostname) |
| 82 |
except ValueError: |
| 83 |
return url |
| 84 |
|
| 85 |
if not address.is_link_local: |
| 86 |
return url |
| 87 |
|
| 88 |
netloc = f"[{data.hostname}%{addr[3]}]" |
| 89 |
if data.port: |
| 90 |
netloc += f":{data.port}" |
| 91 |
return urlunsplit(data._replace(netloc=netloc)) |
| 92 |
|
| 93 |
|
| 94 |
def is_ipv4_address(addr: AddressTupleVXType) -> bool: |
| 95 |
"""Test if addr is a IPv4 tuple.""" |
| 96 |
return len(addr) == 2 |
| 97 |
|
| 98 |
|
| 99 |
def is_ipv6_address(addr: AddressTupleVXType) -> bool: |
| 100 |
"""Test if addr is a IPv6 tuple.""" |
| 101 |
return len(addr) == 4 |
| 102 |
|
| 103 |
|
| 104 |
def build_ssdp_packet(status_line: str, headers: SsdpHeaders) -> bytes: |
| 105 |
"""Construct a SSDP packet.""" |
| 106 |
headers_str = "\r\n".join([f"{key}:{value}" for key, value in headers.items()]) |
| 107 |
return f"{status_line}\r\n{headers_str}\r\n\r\n".encode() |
| 108 |
|
| 109 |
|
| 110 |
def build_ssdp_search_packet(ssdp_target: AddressTupleVXType, ssdp_mx: int, ssdp_st: str) -> bytes: |
| 111 |
"""Construct a SSDP M-SEARCH packet.""" |
| 112 |
request_line = "M-SEARCH * HTTP/1.1" |
| 113 |
headers = { |
| 114 |
"HOST": f"{get_host_port_string(ssdp_target)}", |
| 115 |
"MAN": SSDP_DISCOVER, |
| 116 |
"MX": f"{ssdp_mx}", |
| 117 |
"ST": f"{ssdp_st}", |
| 118 |
} |
| 119 |
return build_ssdp_packet(request_line, headers) |
| 120 |
|
| 121 |
|
| 122 |
@lru_cache(maxsize=128) |
| 123 |
def is_valid_ssdp_packet(data: bytes) -> bool: |
| 124 |
"""Check if data is a valid and decodable packet.""" |
| 125 |
return ( |
| 126 |
bool(data) |
| 127 |
and b"\n" in data |
| 128 |
and ( |
| 129 |
data.startswith(b"NOTIFY * HTTP/1.1") |
| 130 |
or data.startswith(b"M-SEARCH * HTTP/1.1") |
| 131 |
or data.startswith(b"HTTP/1.1 200 OK") |
| 132 |
) |
| 133 |
) |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
def udn_from_headers( |
| 138 |
headers: CIMultiDictProxy | CaseInsensitiveDict, |
| 139 |
) -> UniqueDeviceName | None: |
| 140 |
"""Get UDN from USN in headers.""" |
| 141 |
usn: str = headers.get("usn", "") |
| 142 |
return udn_from_usn(usn) |
| 143 |
|
| 144 |
|
| 145 |
@lru_cache(maxsize=128) |
| 146 |
def udn_from_usn(usn: str) -> UniqueDeviceName | None: |
| 147 |
"""Get UDN from USN in headers.""" |
| 148 |
if usn.lower().startswith("uuid:"): |
| 149 |
return usn.partition("::")[0] |
| 150 |
return None |
| 151 |
|
| 152 |
|
| 153 |
@lru_cache(maxsize=128) |
| 154 |
def _cached_header_parse( |
| 155 |
data: bytes, |
| 156 |
) -> tuple[CIMultiDictProxy[str], str, UniqueDeviceName | None]: |
| 157 |
"""Cache parsing headers. |
| 158 |
|
| 159 |
SSDP discover packets frequently end up being sent multiple |
| 160 |
times on multiple interfaces. |
| 161 |
|
| 162 |
We can avoid parsing the sames ones over and over |
| 163 |
again with a simple lru_cache. |
| 164 |
""" |
| 165 |
lines = data.replace(b"\r\n", b"\n").split(b"\n") |
| 166 |
|
| 167 |
request_line = lines[0].strip().decode() |
| 168 |
|
| 169 |
header_lines = lines[1:] if lines else [] |
| 170 |
if header_lines and header_lines[-1] != b"": |
| 171 |
header_lines.append(b"") |
| 172 |
|
| 173 |
parsed_headers, _ = HeadersParser().parse_headers(header_lines) |
| 174 |
|
| 175 |
usn = parsed_headers.get("usn") |
| 176 |
udn = udn_from_usn(usn) if usn else None |
| 177 |
|
| 178 |
return parsed_headers, request_line, udn |
| 179 |
|
| 180 |
|
| 181 |
LOWER__TIMESTAMP = lowerstr("_timestamp") |
| 182 |
LOWER__HOST = lowerstr("_host") |
| 183 |
LOWER__PORT = lowerstr("_port") |
| 184 |
LOWER__LOCAL_ADDR = lowerstr("_local_addr") |
| 185 |
LOWER__REMOTE_ADDR = lowerstr("_remote_addr") |
| 186 |
LOWER__UDN = lowerstr("_udn") |
| 187 |
LOWER__LOCATION_ORIGINAL = lowerstr("_location_original") |
| 188 |
LOWER_LOCATION = lowerstr("location") |
| 189 |
|
| 190 |
|
| 191 |
@lru_cache(maxsize=512) |
| 192 |
def _cached_decode_ssdp_packet( |
| 193 |
data: bytes, |
| 194 |
remote_addr_without_port: AddressTupleVXType, |
| 195 |
) -> tuple[str, CaseInsensitiveDict]: |
| 196 |
"""Cache decoding SSDP packets.""" |
| 197 |
parsed_headers, request_line, udn = _cached_header_parse(data) |
| 198 |
|
| 199 |
extra: dict[str, Any] = {LOWER__HOST: get_host_string(remote_addr_without_port)} |
| 200 |
if udn: |
| 201 |
extra[LOWER__UDN] = udn |
| 202 |
|
| 203 |
|
| 204 |
location = parsed_headers.get("location", "") |
| 205 |
if location.strip(): |
| 206 |
extra[LOWER__LOCATION_ORIGINAL] = location |
| 207 |
extra[LOWER_LOCATION] = get_adjusted_url(location, remote_addr_without_port) |
| 208 |
|
| 209 |
headers = CaseInsensitiveDict(parsed_headers, **extra) |
| 210 |
return request_line, headers |
| 211 |
|
| 212 |
|
| 213 |
def decode_ssdp_packet( |
| 214 |
data: bytes, |
| 215 |
local_addr: AddressTupleVXType | None, |
| 216 |
remote_addr: AddressTupleVXType, |
| 217 |
) -> tuple[str, CaseInsensitiveDict]: |
| 218 |
"""Decode a message.""" |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
if len(remote_addr) == 4: |
| 223 |
addr, port, flow, scope = remote_addr |
| 224 |
remote_addr_without_port: AddressTupleVXType = addr, 0, flow, scope |
| 225 |
else: |
| 226 |
addr, port = remote_addr |
| 227 |
remote_addr_without_port = remote_addr[0], 0 |
| 228 |
request_line, headers = _cached_decode_ssdp_packet(data, remote_addr_without_port) |
| 229 |
return request_line, headers.combine_lower_dict( |
| 230 |
{ |
| 231 |
LOWER__TIMESTAMP: datetime.now(), |
| 232 |
LOWER__REMOTE_ADDR: remote_addr, |
| 233 |
LOWER__PORT: port, |
| 234 |
LOWER__LOCAL_ADDR: local_addr, |
| 235 |
} |
| 236 |
) |
| 237 |
|
| 238 |
|
| 239 |
class SsdpProtocol(DatagramProtocol): |
| 240 |
"""SSDP Protocol.""" |
| 241 |
|
| 242 |
def __init__( |
| 243 |
self, |
| 244 |
loop: AbstractEventLoop, |
| 245 |
async_on_connect: (Callable[[DatagramTransport], Coroutine[Any, Any, None]] | None) = None, |
| 246 |
on_connect: Callable[[DatagramTransport], None] | None = None, |
| 247 |
async_on_data: (Callable[[str, CaseInsensitiveDict], Coroutine[Any, Any, None]] | None) = None, |
| 248 |
on_data: Callable[[str, CaseInsensitiveDict], None] | None = None, |
| 249 |
) -> None: |
| 250 |
"""Initialize.""" |
| 251 |
|
| 252 |
self.loop = loop |
| 253 |
self.async_on_connect = async_on_connect |
| 254 |
self.on_connect = on_connect |
| 255 |
self.async_on_data = async_on_data |
| 256 |
self.on_data = on_data |
| 257 |
|
| 258 |
self.transport: DatagramTransport | None = None |
| 259 |
self.local_addr: AddressTupleVXType | None = None |
| 260 |
|
| 261 |
def connection_made(self, transport: BaseTransport) -> None: |
| 262 |
"""Handle connection made.""" |
| 263 |
self.transport = cast(DatagramTransport, transport) |
| 264 |
sock: socket.socket | None = transport.get_extra_info("socket") |
| 265 |
self.local_addr = sock.getsockname() if sock is not None else None |
| 266 |
_LOGGER.debug( |
| 267 |
"Connection made, transport: %s, socket: %s", |
| 268 |
transport, |
| 269 |
sock, |
| 270 |
) |
| 271 |
|
| 272 |
if self.async_on_connect: |
| 273 |
coro = self.async_on_connect(self.transport) |
| 274 |
self.loop.create_task(coro) |
| 275 |
if self.on_connect: |
| 276 |
self.on_connect(self.transport) |
| 277 |
|
| 278 |
def datagram_received(self, data: bytes, addr: AddressTupleVXType) -> None: |
| 279 |
"""Handle a discovery-response.""" |
| 280 |
_LOGGER_TRAFFIC_SSDP.debug("Received packet from %s: %s", addr, data) |
| 281 |
assert self.transport |
| 282 |
|
| 283 |
if is_valid_ssdp_packet(data): |
| 284 |
try: |
| 285 |
request_line, headers = decode_ssdp_packet(data, self.local_addr, addr) |
| 286 |
except InvalidHeader as exc: |
| 287 |
_LOGGER.debug("Ignoring received packet with invalid headers: %s", exc) |
| 288 |
return |
| 289 |
|
| 290 |
if self.async_on_data: |
| 291 |
coro = self.async_on_data(request_line, headers) |
| 292 |
self.loop.create_task(coro) |
| 293 |
if self.on_data: |
| 294 |
self.on_data(request_line, headers) |
| 295 |
|
| 296 |
def error_received(self, exc: Exception) -> None: |
| 297 |
"""Handle an error.""" |
| 298 |
sock: socket.socket | None = self.transport.get_extra_info("socket") if self.transport else None |
| 299 |
_LOGGER.error("Received error: %s, transport: %s, socket: %s", exc, self.transport, sock) |
| 300 |
|
| 301 |
def connection_lost(self, exc: Exception | None) -> None: |
| 302 |
"""Handle connection lost.""" |
| 303 |
if not _LOGGER.isEnabledFor(logging.DEBUG): |
| 304 |
return |
| 305 |
assert self.transport |
| 306 |
sock: socket.socket | None = self.transport.get_extra_info("socket") |
| 307 |
_LOGGER.debug( |
| 308 |
"Lost connection, error: %s, transport: %s, socket: %s", |
| 309 |
exc, |
| 310 |
self.transport, |
| 311 |
sock, |
| 312 |
) |
| 313 |
|
| 314 |
def send_ssdp_packet(self, packet: bytes, target: AddressTupleVXType) -> None: |
| 315 |
"""Send a SSDP packet.""" |
| 316 |
assert self.transport |
| 317 |
if _LOGGER.isEnabledFor(logging.DEBUG): |
| 318 |
sock: socket.socket | None = self.transport.get_extra_info("socket") |
| 319 |
_LOGGER.debug( |
| 320 |
"Sending SSDP packet, transport: %s, socket: %s, target: %s", |
| 321 |
self.transport, |
| 322 |
sock, |
| 323 |
target, |
| 324 |
) |
| 325 |
if _LOGGER_TRAFFIC_SSDP.isEnabledFor(logging.DEBUG): |
| 326 |
_LOGGER_TRAFFIC_SSDP.debug("Sending SSDP packet, target: %s, data: %s", target, packet) |
| 327 |
self.transport.sendto(packet, target) |
| 328 |
|
| 329 |
|
| 330 |
def determine_source_target( |
| 331 |
source: AddressTupleVXType | None = None, |
| 332 |
target: AddressTupleVXType | None = None, |
| 333 |
) -> tuple[AddressTupleVXType, AddressTupleVXType]: |
| 334 |
"""Determine source and target.""" |
| 335 |
if source is None and target is None: |
| 336 |
return ("0.0.0.0", 0), (SSDP_IP_V4, SSDP_PORT) |
| 337 |
|
| 338 |
if source is not None and target is None: |
| 339 |
if len(source) == 2: |
| 340 |
return source, (SSDP_IP_V4, SSDP_PORT) |
| 341 |
|
| 342 |
return source, (SSDP_IP_V6, SSDP_PORT, 0, source[3]) |
| 343 |
|
| 344 |
if source is None and target is not None: |
| 345 |
if len(target) == 2: |
| 346 |
return ( |
| 347 |
"0.0.0.0", |
| 348 |
0, |
| 349 |
), target |
| 350 |
|
| 351 |
return ("::", 0, 0, target[3]), target |
| 352 |
|
| 353 |
if source is not None and target is not None and len(source) != len(target): |
| 354 |
raise UpnpError("Source and target do not match protocol") |
| 355 |
|
| 356 |
return cast(AddressTupleVXType, source), cast(AddressTupleVXType, target) |
| 357 |
|
| 358 |
|
| 359 |
def fix_ipv6_address_scope_id( |
| 360 |
address: AddressTupleVXType | None, |
| 361 |
) -> AddressTupleVXType | None: |
| 362 |
"""Fix scope_id for an IPv6 address, if needed.""" |
| 363 |
if address is None or is_ipv4_address(address): |
| 364 |
return address |
| 365 |
|
| 366 |
ip_str = address[0] |
| 367 |
if "%" not in ip_str: |
| 368 |
|
| 369 |
return address |
| 370 |
|
| 371 |
address = cast(AddressTupleV6Type, address) |
| 372 |
idx = ip_str.index("%") |
| 373 |
try: |
| 374 |
ip_scope_id = int(ip_str[idx + 1 :]) |
| 375 |
except ValueError: |
| 376 |
pass |
| 377 |
scope_id = address[3] |
| 378 |
new_scope_id = ip_scope_id if not scope_id and ip_scope_id else address[3] |
| 379 |
new_ip = ip_str[:idx] |
| 380 |
return ( |
| 381 |
new_ip, |
| 382 |
address[1], |
| 383 |
address[2], |
| 384 |
new_scope_id, |
| 385 |
) |
| 386 |
|
| 387 |
|
| 388 |
def ip_port_from_address_tuple( |
| 389 |
address_tuple: AddressTupleVXType, |
| 390 |
) -> tuple[IPvXAddress, int]: |
| 391 |
"""Get IPvXAddress from AddressTupleVXType.""" |
| 392 |
if len(address_tuple) == 4: |
| 393 |
if "%" in address_tuple[0]: |
| 394 |
return IPv6Address(address_tuple[0]), address_tuple[1] |
| 395 |
|
| 396 |
return IPv6Address(f"{address_tuple[0]}%{address_tuple[3]}"), address_tuple[1] |
| 397 |
|
| 398 |
return IPv4Address(address_tuple[0]), address_tuple[1] |
| 399 |
|
| 400 |
|
| 401 |
def get_ssdp_socket( |
| 402 |
source: AddressTupleVXType, |
| 403 |
target: AddressTupleVXType, |
| 404 |
) -> tuple[socket.socket, AddressTupleVXType, AddressTupleVXType]: |
| 405 |
"""Create a socket to listen on.""" |
| 406 |
|
| 407 |
if is_ipv6_address(source): |
| 408 |
source = cast(AddressTupleV6Type, source) |
| 409 |
if not source[3]: |
| 410 |
raise UpnpError(f"Source missing scope_id, source: {source}") |
| 411 |
|
| 412 |
if is_ipv6_address(target): |
| 413 |
target = cast(AddressTupleV6Type, target) |
| 414 |
if not target[3]: |
| 415 |
raise UpnpError(f"Target missing scope_id, target: {target}") |
| 416 |
|
| 417 |
target_ip, target_port = ip_port_from_address_tuple(target) |
| 418 |
target_info = socket.getaddrinfo( |
| 419 |
str(target_ip), |
| 420 |
target_port, |
| 421 |
type=socket.SOCK_DGRAM, |
| 422 |
proto=socket.IPPROTO_UDP, |
| 423 |
)[0] |
| 424 |
source_ip, source_port = ip_port_from_address_tuple(source) |
| 425 |
source_info = socket.getaddrinfo(str(source_ip), source_port, type=socket.SOCK_DGRAM, proto=socket.IPPROTO_UDP)[0] |
| 426 |
_LOGGER.debug("Creating socket, source: %s, target: %s", source_info, target_info) |
| 427 |
|
| 428 |
|
| 429 |
sock = socket.socket(source_info[0], source_info[1]) |
| 430 |
|
| 431 |
|
| 432 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 433 |
try: |
| 434 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) |
| 435 |
except AttributeError: |
| 436 |
pass |
| 437 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) |
| 438 |
|
| 439 |
|
| 440 |
if target_ip.is_multicast: |
| 441 |
if source_info[0] == socket.AF_INET6: |
| 442 |
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 2) |
| 443 |
addr = cast(AddressTupleV6Type, source_info[4]) |
| 444 |
if addr[3]: |
| 445 |
mreq = target_ip.packed + addr[3].to_bytes(4, sys.byteorder) |
| 446 |
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) |
| 447 |
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, addr[3]) |
| 448 |
else: |
| 449 |
_LOGGER.debug("Skipping setting multicast interface") |
| 450 |
else: |
| 451 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, source_ip.packed) |
| 452 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) |
| 453 |
sock.setsockopt( |
| 454 |
socket.IPPROTO_IP, |
| 455 |
socket.IP_ADD_MEMBERSHIP, |
| 456 |
target_ip.packed + source_ip.packed, |
| 457 |
) |
| 458 |
|
| 459 |
return sock, cast(AddressTupleVXType, source_info[4]), cast(AddressTupleVXType, target_info[4]) |