Debian Codegraph @

async_upnp_client/client_factory.py

raw
1 """async_upnp_client.client_factory module."""
2
3 import logging
4 import urllib.parse
5 from typing import Any, Callable, Mapping, Sequence
6 from xml.etree import ElementTree as ET
7
8 import defusedxml.ElementTree as DET
9 import voluptuous as vol
10
11 from async_upnp_client.client import (
12 UpnpAction,
13 UpnpDevice,
14 UpnpError,
15 UpnpRequester,
16 UpnpService,
17 UpnpStateVariable,
18 default_on_post_call_action,
19 default_on_post_receive_device_spec,
20 default_on_post_receive_service_spec,
21 default_on_pre_call_action,
22 default_on_pre_receive_device_spec,
23 default_on_pre_receive_service_spec,
24 )
25 from async_upnp_client.const import (
26 NS,
27 STATE_VARIABLE_TYPE_MAPPING,
28 ActionArgumentInfo,
29 ActionInfo,
30 DeviceIcon,
31 DeviceInfo,
32 HttpRequest,
33 HttpResponse,
34 ServiceInfo,
35 StateVariableInfo,
36 StateVariableTypeInfo,
37 )
38 from async_upnp_client.exceptions import (
39 UpnpResponseError,
40 UpnpXmlContentError,
41 UpnpXmlParseError,
42 )
43 from async_upnp_client.utils import absolute_url
44
45 _LOGGER = logging.getLogger(__name__)
46
47
48 def _ipv6_hosts_match(base_host: str | None, resolved_host: str | None) -> bool:
49 """Check whether two hostnames refer to the same IPv6 address.
50
51 SSDP discovery adds zone IDs to link-local device URLs (e.g. fe80::1%2),
52 but devices omit them from absolute service URLs in their XML. A plain
53 string comparison rejects these as different hosts. This function handles
54 the mismatch: if only one side carries a zone ID, compare the bare
55 addresses. If both carry zone IDs, require them to match. Non-IPv6
56 hostnames are not touched (returns False so the caller falls through
57 to normal comparison).
58 """
59 if base_host is None or resolved_host is None:
60 return False
61 if ":" not in base_host or ":" not in resolved_host:
62 return False
63
64 base_parts = base_host.split("%", 1)
65 resolved_parts = resolved_host.split("%", 1)
66
67 if base_parts[0] != resolved_parts[0]:
68 return False
69
70 base_zone = base_parts[1] if len(base_parts) > 1 else None
71 resolved_zone = resolved_parts[1] if len(resolved_parts) > 1 else None
72
73 if base_zone is not None and resolved_zone is not None:
74 return base_zone == resolved_zone
75
76 if base_zone is None and resolved_zone is not None:
77 return False
78
79 return True
80
81
82 class UpnpFactory:
83 """
84 Factory for UpnpService and friends.
85
86 Use UpnpFactory.async_create_device() to instantiate a UpnpDevice from a description URL. The
87 description URL can be retrieved by searching for the UPnP device on the network, or by
88 listening for advertisements.
89 """
90
91 # pylint: disable=too-few-public-methods,too-many-instance-attributes
92
93 def __init__(
94 self,
95 requester: UpnpRequester,
96 non_strict: bool = False,
97 on_pre_receive_device_spec: Callable[[HttpRequest], HttpRequest] = default_on_pre_receive_device_spec,
98 on_post_receive_device_spec: Callable[[HttpResponse], HttpResponse] = default_on_post_receive_device_spec,
99 on_pre_receive_service_spec: Callable[[HttpRequest], HttpRequest] = default_on_pre_receive_service_spec,
100 on_post_receive_service_spec: Callable[[HttpResponse], HttpResponse] = default_on_post_receive_service_spec,
101 on_pre_call_action: Callable[
102 [UpnpAction, Mapping[str, Any], HttpRequest], HttpRequest
103 ] = default_on_pre_call_action,
104 on_post_call_action: Callable[[UpnpAction, HttpResponse], HttpResponse] = default_on_post_call_action,
105 ) -> None:
106 """Initialize."""
107 # pylint: disable=too-many-arguments,too-many-positional-arguments
108 self.requester = requester
109 self._non_strict = non_strict
110 self._on_pre_receive_device_spec = on_pre_receive_device_spec
111 self._on_post_receive_device_spec = on_post_receive_device_spec
112 self._on_pre_receive_service_spec = on_pre_receive_service_spec
113 self._on_post_receive_service_spec = on_post_receive_service_spec
114 self._on_pre_call_action = on_pre_call_action
115 self._on_post_call_action = on_post_call_action
116
117 async def async_create_device(
118 self,
119 description_url: str,
120 ) -> UpnpDevice:
121 """Create a UpnpDevice, with all of it UpnpServices."""
122 _LOGGER.debug("Creating device, description_url: %s", description_url)
123 root_el = await self._async_get_device_spec(description_url)
124
125 # get root device
126 device_el = root_el.find("./device:device", NS)
127 if device_el is None:
128 raise UpnpXmlContentError("Could not find device element")
129
130 return await self._async_create_device(device_el, description_url)
131
132 async def _async_create_device(self, device_el: ET.Element, description_url: str) -> UpnpDevice:
133 """Create a device."""
134 device_info = self._parse_device_el(device_el, description_url)
135
136 # get services
137 services = []
138 for service_desc_el in device_el.findall("./device:serviceList/device:service", NS):
139 service = await self._async_create_service(service_desc_el, description_url)
140 if service is not None:
141 services.append(service)
142
143 embedded_devices = []
144 for embedded_device_el in device_el.findall("./device:deviceList/device:device", NS):
145 embedded_device = await self._async_create_device(embedded_device_el, description_url)
146 embedded_devices.append(embedded_device)
147
148 return UpnpDevice(
149 self.requester,
150 device_info,
151 services,
152 embedded_devices,
153 self._on_pre_receive_device_spec,
154 self._on_post_receive_device_spec,
155 )
156
157 def _parse_device_el(self, device_desc_el: ET.Element, description_url: str) -> DeviceInfo:
158 """Parse device description XML."""
159 icons = []
160 for icon_el in device_desc_el.iterfind("./device:iconList/device:icon", NS):
161 icon_url = icon_el.findtext("./device:url", "", NS)
162 icon_url = absolute_url(description_url, icon_url)
163 icon = DeviceIcon(
164 mimetype=icon_el.findtext("./device:mimetype", "", NS),
165 width=int(icon_el.findtext("./device:width", 0, NS)),
166 height=int(icon_el.findtext("./device:height", 0, NS)),
167 depth=int(icon_el.findtext("./device:depth", 0, NS)),
168 url=icon_url,
169 )
170 icons.append(icon)
171
172 return DeviceInfo(
173 device_type=device_desc_el.findtext("./device:deviceType", "", NS),
174 friendly_name=device_desc_el.findtext("./device:friendlyName", "", NS),
175 manufacturer=device_desc_el.findtext("./device:manufacturer", "", NS),
176 manufacturer_url=device_desc_el.findtext("./device:manufacturerURL", "", NS),
177 model_description=device_desc_el.findtext("./device:modelDescription", None, NS),
178 model_name=device_desc_el.findtext("./device:modelName", "", NS),
179 model_number=device_desc_el.findtext("./device:modelNumber", None, NS),
180 model_url=device_desc_el.findtext("./device:modelURL", None, NS),
181 serial_number=device_desc_el.findtext("./device:serialNumber", None, NS),
182 udn=device_desc_el.findtext("./device:UDN", "", NS),
183 upc=device_desc_el.findtext("./device:UPC", "", NS),
184 presentation_url=device_desc_el.findtext("./device:presentationURL", "", NS),
185 url=description_url,
186 icons=icons,
187 xml=device_desc_el,
188 )
189
190 async def _async_create_service(self, service_description_el: ET.Element, base_url: str) -> UpnpService | None:
191 """Retrieve the SCPD for a service and create a UpnpService from it.
192
193 Returns None if the service is skipped (non-strict mode) because one of
194 its URLs is malformed or resolves to a different host than the device.
195 """
196 if not self._service_urls_valid(service_description_el, base_url):
197 return None
198
199 scpd_url = service_description_el.findtext("device:SCPDURL", None, NS)
200 scpd_url = urllib.parse.urljoin(base_url, scpd_url)
201
202 try:
203 scpd_el = await self._async_get_service_spec(scpd_url)
204 except UpnpXmlParseError as err:
205 if not self._non_strict:
206 raise
207 _LOGGER.debug("Ignoring bad XML document from URL %s: %s", scpd_url, err)
208 scpd_el = ET.Element(f"{{{NS['service']}}}scpd")
209
210 if not self._non_strict and scpd_el.tag != f"{{{NS['service']}}}scpd":
211 raise UpnpXmlContentError(f"Invalid document root: {scpd_el.tag}")
212
213 service_info = self._parse_service_el(service_description_el)
214 state_vars = self._create_state_variables(scpd_el)
215 actions = self._create_actions(scpd_el, state_vars)
216 return UpnpService(
217 self.requester,
218 service_info,
219 state_vars,
220 actions,
221 self._on_pre_call_action,
222 self._on_post_call_action,
223 )
224
225 def _service_urls_valid(self, service_description_el: ET.Element, base_url: str) -> bool:
226 """Validate that a service's URLs resolve to the device's own host.
227
228 Per UDA 1.1/2.0 the SCPDURL/controlURL/eventSubURL elements MUST be
229 relative to the device description URL, so a conformant device never
230 points them at another host. An absolute URL to a different host is a
231 potential SSRF vector (e.g. cloud-metadata or loopback endpoints) and is
232 refused in strict mode or skipped (with a warning) in non-strict mode.
233 """
234 base_host = urllib.parse.urlparse(base_url).hostname
235 for tag in ("SCPDURL", "controlURL", "eventSubURL"):
236 ref = service_description_el.findtext(f"device:{tag}", "", NS)
237 if not ref:
238 continue
239 # A malformed URL (e.g. an unbalanced IPv6 bracket) makes urljoin or
240 # urlparse raise; fail closed and treat it as a refused host.
241 try:
242 resolved = urllib.parse.urljoin(base_url, ref)
243 resolved_host = urllib.parse.urlparse(resolved).hostname
244 except ValueError:
245 resolved_host = None
246 if resolved_host != base_host and not _ipv6_hosts_match(base_host, resolved_host):
247 reason = (
248 "is malformed"
249 if resolved_host is None
250 else f"resolves to a different host than the device URL {base_url!r}"
251 )
252 message = f"Service {tag} {ref!r} {reason}; refusing as potential SSRF"
253 if not self._non_strict:
254 raise UpnpError(message)
255
256 _LOGGER.warning("%s; skipping service", message)
257 return False
258 return True
259
260 def _parse_service_el(self, service_description_el: ET.Element) -> ServiceInfo:
261 """Parse service description XML."""
262 return ServiceInfo(
263 service_id=service_description_el.findtext("device:serviceId", "", NS),
264 service_type=service_description_el.findtext("device:serviceType", "", NS),
265 control_url=service_description_el.findtext("device:controlURL", "", NS),
266 event_sub_url=service_description_el.findtext("device:eventSubURL", "", NS),
267 scpd_url=service_description_el.findtext("device:SCPDURL", "", NS),
268 xml=service_description_el,
269 )
270
271 def _create_state_variables(self, scpd_el: ET.Element) -> list[UpnpStateVariable]:
272 """Create UpnpStateVariables from scpd_el."""
273 service_state_table_el = scpd_el.find("./service:serviceStateTable", NS)
274 if service_state_table_el is None:
275 if self._non_strict:
276 _LOGGER.debug("Could not find service state table element")
277 return []
278 raise UpnpXmlContentError("Could not find service state table element")
279
280 state_vars = []
281 for state_var_el in service_state_table_el.findall("./service:stateVariable", NS):
282 state_var = self._create_state_variable(state_var_el)
283 state_vars.append(state_var)
284 return state_vars
285
286 def _create_state_variable(self, state_variable_el: ET.Element) -> UpnpStateVariable:
287 """Create UpnpStateVariable from state_variable_el."""
288 state_variable_info = self._parse_state_variable_el(state_variable_el)
289 type_info = state_variable_info.type_info
290 schema = self._state_variable_create_schema(type_info)
291 return UpnpStateVariable(state_variable_info, schema)
292
293 def _parse_state_variable_el(self, state_variable_el: ET.Element) -> StateVariableInfo:
294 """Parse XML for state variable."""
295 # send events
296 send_events = False
297 if "sendEvents" in state_variable_el.attrib:
298 send_events = state_variable_el.attrib["sendEvents"] == "yes"
299 elif state_variable_el.find("service:sendEventsAttribute", NS) is not None:
300 send_events = state_variable_el.findtext("service:sendEventsAttribute", None, NS) == "yes"
301 else:
302 _LOGGER.debug(
303 "Invalid XML for state variable/send events: %s",
304 ET.tostring(state_variable_el, encoding="unicode"),
305 )
306
307 # data type
308 data_type = state_variable_el.findtext("service:dataType", None, NS)
309 if data_type is None:
310 raise UpnpXmlContentError(f"Invalid or missing data type: {data_type}")
311
312 if self._non_strict and data_type not in STATE_VARIABLE_TYPE_MAPPING:
313 # Do some effort to fix the data type.
314 data_type = data_type.lower()
315 if data_type == "datetime":
316 data_type = "dateTime"
317 elif data_type == "datetime.tz":
318 data_type = "dateTime.tz"
319
320 if data_type not in STATE_VARIABLE_TYPE_MAPPING:
321 raise UpnpError(f"Unsupported data type: {data_type}")
322
323 data_type_mapping = STATE_VARIABLE_TYPE_MAPPING[data_type]
324
325 # default value
326 default_value = state_variable_el.findtext("service:defaultValue", None, NS)
327
328 # allowed value ranges
329 allowed_value_range: dict[str, str | None] = {}
330 allowed_value_range_el = state_variable_el.find("service:allowedValueRange", NS)
331 if allowed_value_range_el is not None:
332 allowed_value_range = {
333 "min": allowed_value_range_el.findtext("service:minimum", None, NS),
334 "max": allowed_value_range_el.findtext("service:maximum", None, NS),
335 "step": allowed_value_range_el.findtext("service:step", None, NS),
336 }
337
338 # allowed value list
339 allowed_values: list[str] | None = None
340 allowed_value_list_el = state_variable_el.find("service:allowedValueList", NS)
341 if allowed_value_list_el is not None:
342 allowed_values = [
343 v.text for v in allowed_value_list_el.findall("service:allowedValue", NS) if v.text is not None
344 ]
345
346 type_info = StateVariableTypeInfo(
347 data_type=data_type,
348 data_type_mapping=data_type_mapping,
349 default_value=default_value,
350 allowed_value_range=allowed_value_range,
351 allowed_values=allowed_values,
352 xml=state_variable_el,
353 )
354 name = state_variable_el.findtext("service:name", "", NS).strip()
355 return StateVariableInfo(
356 name=name,
357 send_events=send_events,
358 type_info=type_info,
359 xml=state_variable_el,
360 )
361
362 def _state_variable_create_schema(self, type_info: StateVariableTypeInfo) -> vol.Schema:
363 """Create schema."""
364 # construct validators
365 validators = []
366
367 data_type_upnp = type_info.data_type
368 data_type_mapping = STATE_VARIABLE_TYPE_MAPPING[data_type_upnp]
369 data_type = data_type_mapping["type"]
370 validators.append(data_type)
371
372 data_type_validator = data_type_mapping.get("validator")
373 if data_type_validator:
374 validators.append(data_type_validator)
375
376 if not self._non_strict:
377 in_coercer = data_type_mapping["in"]
378 if type_info.allowed_values:
379 allowed_values = [in_coercer(allowed_value) for allowed_value in type_info.allowed_values]
380 in_ = vol.In(allowed_values)
381 validators.append(in_)
382
383 if type_info.allowed_value_range:
384 min_ = type_info.allowed_value_range.get("min", None)
385 max_ = type_info.allowed_value_range.get("max", None)
386 min_ = in_coercer(min_) if min_ else None
387 max_ = in_coercer(max_) if max_ else None
388 if min_ is not None or max_ is not None:
389 range_ = vol.Range(min=min_, max=max_)
390 validators.append(range_)
391
392 # construct key
393 key = vol.Required("value")
394
395 if type_info.default_value is not None and type_info.default_value != "":
396 default_value: Any = type_info.default_value
397 if data_type is bool:
398 default_value = default_value == "1"
399 else:
400 default_value = data_type(default_value)
401 key.default = default_value
402
403 return vol.Schema(vol.All(*validators))
404
405 def _create_actions(self, scpd_el: ET.Element, state_variables: Sequence[UpnpStateVariable]) -> list[UpnpAction]:
406 """Create UpnpActions from scpd_el."""
407 action_list_el = scpd_el.find("./service:actionList", NS)
408 if action_list_el is None:
409 return []
410
411 actions = []
412 for action_el in action_list_el.findall("./service:action", NS):
413 action = self._create_action(action_el, state_variables)
414 actions.append(action)
415 return actions
416
417 def _create_action(self, action_el: ET.Element, state_variables: Sequence[UpnpStateVariable]) -> UpnpAction:
418 """Create a UpnpAction from action_el."""
419 action_info = self._parse_action_el(action_el)
420 svs = {sv.name: sv for sv in state_variables}
421 arguments = [
422 UpnpAction.Argument(arg_info, svs[arg_info.state_variable_name]) for arg_info in action_info.arguments
423 ]
424 return UpnpAction(action_info, arguments, non_strict=self._non_strict)
425
426 def _parse_action_el(self, action_el: ET.Element) -> ActionInfo:
427 """Parse XML for action."""
428 # build arguments
429 args: list[ActionArgumentInfo] = []
430 for argument_el in action_el.findall("./service:argumentList/service:argument", NS):
431 argument_name = argument_el.findtext("service:name", None, NS)
432 if argument_name is None:
433 _LOGGER.debug("Caught Action Argument without a name, ignoring")
434 continue
435
436 direction = argument_el.findtext("service:direction", None, NS)
437 if direction is None:
438 _LOGGER.debug("Caught Action Argument without a direction, ignoring")
439 continue
440
441 state_variable_name = argument_el.findtext("service:relatedStateVariable", None, NS)
442 if state_variable_name is None:
443 _LOGGER.debug("Caught Action Argument without a State Variable name, ignoring")
444 continue
445
446 argument_info = ActionArgumentInfo(
447 name=argument_name,
448 direction=direction,
449 state_variable_name=state_variable_name,
450 xml=argument_el,
451 )
452 args.append(argument_info)
453
454 action_name = action_el.findtext("service:name", None, NS)
455 if action_name is None:
456 _LOGGER.debug('Caught Action without a name, using default "nameless"')
457 action_name = "nameless"
458
459 return ActionInfo(name=action_name, arguments=args, xml=action_el)
460
461 async def _async_get_device_spec(self, url: str) -> ET.Element:
462 """Get a url."""
463 bare_request = HttpRequest("GET", url, {}, None)
464 request = self._on_pre_receive_device_spec(bare_request)
465 bare_response = await self.requester.async_http_request(request)
466 response = self._on_post_receive_device_spec(bare_response)
467 return self._read_spec_from_reponse(response)
468
469 async def _async_get_service_spec(self, url: str) -> ET.Element:
470 """Get a url."""
471 bare_request = HttpRequest("GET", url, {}, None)
472 request = self._on_pre_receive_service_spec(bare_request)
473 bare_response = await self.requester.async_http_request(request)
474 response = self._on_post_receive_service_spec(bare_response)
475 return self._read_spec_from_reponse(response)
476
477 def _read_spec_from_reponse(self, response: HttpResponse) -> ET.Element:
478 """Read XML specification from response."""
479 if response.status_code != 200:
480 raise UpnpResponseError(status=response.status_code, headers=response.headers)
481
482 description: str = response.body or ""
483 try:
484 element: ET.Element = DET.fromstring(description)
485 return element
486 except ET.ParseError as err:
487 _LOGGER.debug("Unable to parse XML: %s\nXML:\n%s", err, description)
488 raise UpnpXmlParseError(err) from err