From 6ac63cf8a81ff8cf7cf55096d280c7a54b39d7b2 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:09:03 +0100 Subject: [PATCH] Resolve mDNS candidates of a WebRTC answer with the driver's Zeroconf The media transport created and closed its own AsyncZeroconf to resolve .local candidates. In Home Assistant that closes the shared instance and all of its services. The WebRTC delegate now resolves them with the driver's instance before it applies the answer, waiting at most 2 s, and names that do not resolve are ignored. Adds StreamSession.camera. --- docs/source/media/camera.rst | 10 + pyhap/camera_stream.py | 6 + pyhap/media/_mdns.py | 199 ++++++++++++++ pyhap/media/ice.py | 35 +-- pyhap/media/sender.py | 14 +- pyhap/media/transport.py | 98 +++---- pyhap/media/webrtc_delegate.py | 20 +- tests/test_camera_stream.py | 12 + tests/test_media_mdns.py | 387 ++++++++++++++++++++++++++++ tests/test_media_sender.py | 20 +- tests/test_media_transport.py | 204 +++++++++++---- tests/test_media_webrtc_delegate.py | 63 +++++ 12 files changed, 926 insertions(+), 142 deletions(-) create mode 100644 pyhap/media/_mdns.py create mode 100644 tests/test_media_mdns.py diff --git a/docs/source/media/camera.rst b/docs/source/media/camera.rst index 9c709eb3..687f29ba 100644 --- a/docs/source/media/camera.rst +++ b/docs/source/media/camera.rst @@ -301,6 +301,16 @@ controller answers. It needs the ``WebRTC`` extra Pass ``on_audio`` to receive the controller's talkback as Opus packets. +A controller may name itself by an mDNS ``.local`` name in its answer. The +delegate resolves such names with the Zeroconf instance of the camera's +driver: the one it advertises with, or the ``async_zeroconf_instance`` the +application gave it, which has to run on the driver's loop. It asks for at +most four names and waits up to two seconds for them, at most a quarter of +the ``hook_timeout`` the answer has: with a short one, an answer that takes +more than a second is missed. Without an instance, and for a name that does +not resolve, the controller is only reached when its own connectivity checks +get to the camera. + Talkback ======== diff --git a/pyhap/camera_stream.py b/pyhap/camera_stream.py index 847a155b..cdf0b4e1 100644 --- a/pyhap/camera_stream.py +++ b/pyhap/camera_stream.py @@ -122,6 +122,12 @@ class StreamSession: def sensor_uuid(self) -> UUID: return self.sensor.sensor_uuid + @property + def camera(self) -> Camera | None: + """The camera of the session, None for one outside a stream service.""" + controller = self._controller + return None if controller is None else controller.camera + @property def ended(self) -> bool: return self.state is SessionState.ENDED diff --git a/pyhap/media/_mdns.py b/pyhap/media/_mdns.py new file mode 100644 index 00000000..cc0f531e --- /dev/null +++ b/pyhap/media/_mdns.py @@ -0,0 +1,199 @@ +"""Resolve the mDNS names of a WebRTC answer's candidates. + +A controller may name itself by an mDNS ``.local`` name instead of an IP +address. The names are resolved here, on the caller's loop, with the Zeroconf +instance of the camera's driver: the media transport must not create one. A +worker has no instance of its own, and where an application makes every new +instance its shared one, closing the new one would close that. + +Names that do not resolve stay as they are; the transport ignores them and +such a peer is then only found by its own checks. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Mapping, Sequence +import dataclasses +import ipaddress +import logging +import re +from typing import TYPE_CHECKING + +from . import sdp as sdp_module +from .ice import Candidate + +if TYPE_CHECKING: + from zeroconf.asyncio import AsyncZeroconf + + from pyhap import hksv3 + +logger = logging.getLogger(__name__) + +# Seconds all names of an answer get, in parallel: the answer waits for them. +# Zeroconf first asks for a unicast answer, which can get lost where several +# mDNS stacks share the port; the answer to its next question then came after +# about 1.3 seconds. +MDNS_TIMEOUT = 2.0 +# Names resolved per answer; each costs a query. +MAX_MDNS_NAMES = 4 +MAX_MDNS_NAME = 253 +# The SDP parser splits on line feeds and reads a candidate after this. +_SDP_PREFIX = "a=candidate:" +# Where the connection address of a candidate is, the fifth field (RFC 8839). +_HOST = re.compile(r"\s*(?:a=)?(?:candidate:)?\s*(?:\S+\s+){4}(?P\S+)") + + +def _mdns_host(candidate: str) -> str | None: + """The mDNS name of a candidate the transport uses once it has an address. + + Read as the transport reads it: a UDP candidate of component 1 with a + valid port. Others must not use up the names an answer has resolved. + """ + try: + parsed = Candidate.from_sdp(sdp_module.candidate_value(candidate)) + except ValueError: + return None + host = parsed.host + if ( + parsed.component == 1 + and parsed.transport.lower() == "udp" + and 0 < parsed.port < 65536 + and host.lower().endswith(".local") + and len(".local") < len(host) <= MAX_MDNS_NAME + ): + return host + return None + + +def _with_address(candidate: str, addresses: Mapping[str, str]) -> str: + """The candidate with its mDNS name replaced by the resolved address.""" + host = _mdns_host(candidate) + address = addresses.get(host.lower()) if host else None + match = _HOST.match(candidate) if address else None + if match is None: + return candidate + start, end = match.span("host") + return f"{candidate[:start]}{address}{candidate[end:]}" + + +def _usable(address: str) -> bool: + """Whether an mDNS answer names a peer: a unicast address, not loopback.""" + try: + parsed = ipaddress.ip_address(address) + except ValueError: + return False + if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped: + parsed = parsed.ipv4_mapped + return not ( + parsed.is_unspecified + or parsed.is_multicast + or parsed.is_loopback + or parsed == ipaddress.IPv4Address("255.255.255.255") + ) + + +async def _lookup( + zeroconf: AsyncZeroconf, names: Sequence[str], timeout: float +) -> dict[str, str]: + """Ask for every name at once; a name without an answer is left out. + + Returns after ``timeout`` seconds at the latest. + """ + try: + from zeroconf import AddressResolver # noqa: PLC0415 - rarely needed + except ImportError: + logger.debug("This zeroconf cannot resolve mDNS candidates") + return {} + instance = zeroconf.zeroconf + if not names: + return {} + if instance.loop is not None and instance.loop is not asyncio.get_running_loop(): + logger.debug("The Zeroconf instance runs on another loop, names stay") + return {} + if not instance.started: + # A request would wait for the start, and giving up on the request + # would cancel that start for everyone. + logger.debug("The Zeroconf instance has not started, names stay") + return {} + + async def resolve(name: str) -> str | None: + try: + resolver = AddressResolver(f"{name}.") + if not await resolver.async_request(instance, int(timeout * 1000)): + return None + addresses = resolver.parsed_scoped_addresses() + except Exception as err: # noqa: BLE001 - e.g. an instance that stopped + logger.debug("mDNS name %r not resolved: %r", name, err) + return None + return addresses[0] if addresses else None + + tasks = {name: asyncio.ensure_future(resolve(name)) for name in names} + try: + done, _ = await asyncio.wait(tasks.values(), timeout=timeout) + finally: + for task in tasks.values(): + task.cancel() + return { + name: address + for name, task in tasks.items() + if task in done and (address := task.result()) is not None + } + + +async def resolve_answer( + zeroconf: AsyncZeroconf | None, + sdp: str, + candidates: Sequence[hksv3.IceCandidate], + timeout: float = MDNS_TIMEOUT, +) -> tuple[str, list[hksv3.IceCandidate]]: + """The answer with the mDNS names of its candidates resolved. + + Covers the candidates HAP carries next to the SDP and those inside it, + as far as the sender uses them. At most :data:`MAX_MDNS_NAMES` names are + asked for, within ``timeout`` seconds. Without a Zeroconf instance that + runs on this loop nothing is resolved. + """ + try: + answer = sdp_module.parse(sdp_module.merge_candidates(sdp, candidates)) + transport = answer.transport() + except sdp_module.SdpError: + # The sender refuses this answer. + return sdp, list(candidates) + if not transport.ice_ufrag or not transport.ice_pwd or not transport.fingerprints: + # It refuses this one too, without waiting for names first. + return sdp, list(candidates) + lines = sdp.split("\n") + written = [ + *(line[len(_SDP_PREFIX) :] for line in lines if line.startswith(_SDP_PREFIX)), + *(c.candidate for c in candidates), + ] + # A name is asked for when the sender uses a candidate with it and it can + # be replaced where it is written. + replaceable = {host.lower() for text in written if (host := _mdns_host(text))} + hosts = [_mdns_host(text) for text in answer.candidates] + names = list( + dict.fromkeys( + host.lower() for host in hosts if host and host.lower() in replaceable + ) + ) + if not names: + return sdp, list(candidates) + if zeroconf is None: + logger.debug("No Zeroconf instance to resolve %d mDNS candidates", len(names)) + return sdp, list(candidates) + if len(names) > MAX_MDNS_NAMES: + logger.debug("Resolving only %d of the mDNS candidates", MAX_MDNS_NAMES) + answers = await _lookup(zeroconf, names[:MAX_MDNS_NAMES], timeout) + addresses = {name: answer for name, answer in answers.items() if _usable(answer)} + logger.debug("Resolved %d of %d mDNS candidates", len(addresses), len(names)) + resolved_sdp = "\n".join( + f"{_SDP_PREFIX}{_with_address(line[len(_SDP_PREFIX) :], addresses)}" + if line.startswith(_SDP_PREFIX) + else line + for line in lines + ) + return resolved_sdp, [ + dataclasses.replace(c, candidate=_with_address(c.candidate, addresses)) + for c in candidates + ] diff --git a/pyhap/media/ice.py b/pyhap/media/ice.py index b1f4e12b..570a2b0f 100644 --- a/pyhap/media/ice.py +++ b/pyhap/media/ice.py @@ -10,7 +10,9 @@ No STUN or TURN server is used: HomeKit controllers reach the accessory through a relay of their own (remote) or on the LAN, and the accessory's outgoing check opens its NAT towards the relay. A request from an unknown -address with a valid MESSAGE-INTEGRITY becomes a peer-reflexive pair. +address with a valid MESSAGE-INTEGRITY becomes a peer-reflexive pair; that is +also how a peer is found whose candidates are mDNS names, which the transport +does not resolve. After selection, consent freshness (RFC 7675) sends a check on the selected pair every few seconds; without an authenticated response for @@ -647,34 +649,3 @@ def _close_sockets(self) -> None: sockets, self._sockets = self._sockets, [] for sock in sockets: sock.close() - - -async def resolve_mdns(names: Iterable[str], timeout: float) -> dict[str, str | None]: - """Resolve mDNS ``.local`` host names to IP addresses, all at once. - - One zeroconf instance asks for every name in parallel; a name that does - not resolve within ``timeout`` seconds maps to None. - """ - from zeroconf import AddressResolver # noqa: PLC0415 - rarely needed - from zeroconf.asyncio import AsyncZeroconf # noqa: PLC0415 - - zeroconf = AsyncZeroconf() - - async def resolve(name: str) -> str | None: - resolver = AddressResolver(name if name.endswith(".") else f"{name}.") - if not await resolver.async_request(zeroconf.zeroconf, int(timeout * 1000)): - return None - addresses = resolver.parsed_scoped_addresses() - return addresses[0] if addresses else None - - try: - unique = list(dict.fromkeys(names)) - results = await asyncio.gather( - *(resolve(name) for name in unique), return_exceptions=True - ) - finally: - await zeroconf.async_close() - return { - name: result if isinstance(result, str) else None - for name, result in zip(unique, results, strict=True) - } diff --git a/pyhap/media/sender.py b/pyhap/media/sender.py index f39417dd..21f614eb 100644 --- a/pyhap/media/sender.py +++ b/pyhap/media/sender.py @@ -388,6 +388,9 @@ async def apply_answer( """Accept the controller's answer and connect in the background. ``candidates`` are answer candidates HAP carried next to the SDP. + mDNS ``.local`` names among them and in the SDP are not resolved + here but ignored; :class:`~pyhap.media.webrtc_delegate.WebRTCMediaDelegate` + resolves them before it applies an answer. """ if self._state != "offered": raise MediaError("No offer is waiting for an answer") @@ -413,9 +416,7 @@ async def apply_answer( self._remote_ice = (media.ice_ufrag, media.ice_pwd) self._remote_fingerprints = list(media.fingerprints) self._dtls_role = DtlsRole.from_remote_setup(media.setup) - self._start( - self._expire("answered", self._negotiation_timeout, "negotiation timed out") - ) + self._start(self._expire_negotiation()) self._start( self._connect( media.ice_ufrag, @@ -605,6 +606,13 @@ async def _expire(self, state: str, timeout: float, reason: str) -> None: if self._state == state: await self._close(reason) + async def _expire_negotiation(self) -> None: + await asyncio.sleep(self._negotiation_timeout) + if self._state == "answered": + # Ends the connect too, so its own error never gets to say it. + hint = self._transport.ice_failure_hint + await self._close(f"negotiation timed out{hint}") + async def _writer(self) -> None: try: while True: diff --git a/pyhap/media/transport.py b/pyhap/media/transport.py index e23b0910..4e2fbd82 100644 --- a/pyhap/media/transport.py +++ b/pyhap/media/transport.py @@ -46,7 +46,6 @@ import asyncio from collections.abc import Callable, Iterable, Sequence import contextlib -import dataclasses from dataclasses import dataclass import datetime import enum @@ -70,7 +69,7 @@ from pyhap import util -from .ice import Candidate, IceAgent, resolve_mdns +from .ice import Candidate, IceAgent logger = logging.getLogger(__name__) @@ -79,12 +78,8 @@ SRTP_EXPORTER_LABEL = b"EXTRACTOR-dtls_srtp" DEFAULT_CONNECT_TIMEOUT = 20.0 MAX_REMOTE_CANDIDATES = 32 -MAX_MDNS_NAME = 253 -MDNS_TIMEOUT = 2.0 # The DTLS 1.2 protocol version, which pyOpenSSL has no constant for. DTLS1_2_VERSION = 0xFEFD -# mDNS names resolved per connection; each costs a zeroconf query. -MAX_MDNS_CANDIDATES = 4 FINGERPRINT_ALGORITHMS = { "sha-256": hashes.SHA256(), "sha-384": hashes.SHA384(), @@ -291,6 +286,7 @@ def __init__( self._handshake_done = False self._connected = False self._closed = False + self._mdns_ignored = 0 @property def local_username(self) -> str: @@ -313,6 +309,17 @@ def connected(self) -> bool: """Whether SRTP is ready.""" return self._connected and not self._closed + @property + def ice_failure_hint(self) -> str: + """What a failure adds to its reason while ICE has selected no pair. + + Names the ignored mDNS candidates: the peer had to get through with + its own checks. + """ + if not self._mdns_ignored or self._ice.selected_pair is not None: + return "" + return f" (mDNS candidates ignored: {self._mdns_ignored})" + @property def closed(self) -> bool: """Whether the transport was closed.""" @@ -358,9 +365,15 @@ async def connect( """Run ICE and the DTLS handshake, then start receiving. At most :data:`MAX_REMOTE_CANDIDATES` distinct UDP candidates of - component 1 are used; adding them (which may resolve mDNS names) - counts against ``timeout``. Raises :class:`TransportError` when - either step fails, times out or the transport is closed meanwhile. + component 1 are used. mDNS ``.local`` candidates are not resolved + here; the WebRTC delegate resolves them before, with the driver's + Zeroconf instance. Where a name is left, its peer is found when its + own checks reach this side, as a peer-reflexive pair; with other + candidates in the answer, a pair with one of those may be selected + first. An ICE lite peer, or one whose checks are filtered on the way, + is not found by a name; the error then ends with + :attr:`ice_failure_hint`. Raises :class:`TransportError` when either + step fails, times out or the transport is closed meanwhile. """ if self._closed: raise TransportError("Transport is closed") @@ -368,17 +381,19 @@ async def connect( self._ice.remote_username = remote_username self._ice.remote_password = remote_password self._ice.remote_is_lite = ice_lite - candidates = _remote_candidates(remote_candidates) + candidates, self._mdns_ignored = _remote_candidates(remote_candidates) try: await asyncio.wait_for( self._connect(candidates, remote_fingerprints), timeout ) except TimeoutError as err: - raise TransportError("WebRTC connection timed out") from err + reason = f"WebRTC connection timed out{self.ice_failure_hint}" + raise TransportError(reason) from err except (ConnectionError, SSL.Error) as err: - raise TransportError(f"WebRTC connection failed: {err}") from err + reason = f"WebRTC connection failed: {err}{self.ice_failure_hint}" + raise TransportError(reason) from err except Exception as err: - # For example an mDNS socket that cannot bind, or an SRTP error. + # For example an SRTP error. raise TransportError(f"WebRTC connection failed: {err!r}") from err if self._closed: raise TransportError("Transport is closed") @@ -390,7 +405,7 @@ async def _connect( candidates: list[Candidate], remote_fingerprints: Sequence[tuple[str, str]], ) -> None: - await self._ice.connect(await _resolve_candidates(candidates)) + await self._ice.connect(candidates) self._ssl = SSL.Connection(self.certificate.ssl_context()) if self.role is DtlsRole.SERVER: self._ssl.set_accept_state() @@ -594,14 +609,12 @@ async def _close(self, reason: str) -> None: def _usable_remote_address(host: str, port: int) -> bool: - """Whether a remote candidate has a valid port and a unicast or mDNS host. + """Whether a remote candidate has a valid port and a unicast IP address. Unspecified, multicast and broadcast addresses are not usable peers. """ if not 0 < port < 65536: return False - if host.lower().endswith(".local"): - return len(host) > len(".local") and len(host) <= MAX_MDNS_NAME try: address = ipaddress.ip_address(host) except ValueError: @@ -616,51 +629,16 @@ def _usable_remote_address(host: str, port: int) -> bool: ) -async def _resolve_candidates(candidates: list[Candidate]) -> list[Candidate]: - """Replace mDNS host names by their address; unresolved ones are dropped. - - At most :data:`MAX_MDNS_CANDIDATES` names are resolved, in parallel, and - an address a name resolves to must be a usable unicast address too. - """ - names = [c.host for c in candidates if c.host.lower().endswith(".local")] - if len(set(names)) > MAX_MDNS_CANDIDATES: - logger.debug("Resolving only %d of the mDNS candidates", MAX_MDNS_CANDIDATES) - wanted = list(dict.fromkeys(names))[:MAX_MDNS_CANDIDATES] - addresses: dict[str, str | None] = {} - if wanted: - try: - addresses = await resolve_mdns(wanted, MDNS_TIMEOUT) - except OSError as err: - logger.debug("Cannot resolve mDNS candidates: %s", err) - resolved = [] - for candidate in candidates: - if not candidate.host.lower().endswith(".local"): - resolved.append(candidate) - continue - address = addresses.get(candidate.host) - if address is None or not _usable_resolved_address(address, candidate.port): - logger.debug("Ignoring unresolved candidate %s", candidate.host) - continue - resolved.append(dataclasses.replace(candidate, host=address)) - return resolved - - -def _usable_resolved_address(address: str, port: int) -> bool: - """Whether an mDNS answer names a usable peer: unicast, not loopback.""" - if address.lower().endswith(".local") or not _usable_remote_address(address, port): - return False - return not ipaddress.ip_address(address.split("%", 1)[0]).is_loopback - - -def _remote_candidates(values: Iterable[str]) -> list[Candidate]: +def _remote_candidates(values: Iterable[str]) -> tuple[list[Candidate], int]: """Parse distinct UDP candidates of component 1, at most the cap. Candidates whose port is out of range, whose address is unspecified, - multicast or broadcast, or whose host is neither an IP address nor an - mDNS ``.local`` name are dropped. + multicast or broadcast, or whose host is not an IP address are dropped. + Also returns how many of them were mDNS ``.local`` names. """ seen: set[str] = set() candidates = [] + mdns = 0 for value in values: text = value.strip().removeprefix("a=").removeprefix("candidate:") if text in seen: @@ -671,6 +649,10 @@ def _remote_candidates(values: Iterable[str]) -> list[Candidate]: except ValueError: logger.debug("Ignoring unparsable candidate %r", value) continue + if parsed.host.lower().endswith(".local"): + if parsed.component == 1 and parsed.transport.lower() == "udp": + mdns += 1 + continue if not _usable_remote_address(parsed.host, parsed.port): logger.debug("Ignoring candidate with an unusable address %r", value) continue @@ -678,4 +660,6 @@ def _remote_candidates(values: Iterable[str]) -> list[Candidate]: candidates.append(parsed) if len(candidates) == MAX_REMOTE_CANDIDATES: break - return candidates + if mdns: + logger.debug("mDNS candidates ignored, they are not resolved: %d", mdns) + return candidates, mdns diff --git a/pyhap/media/webrtc_delegate.py b/pyhap/media/webrtc_delegate.py index e5b07b2b..3f3ddefb 100644 --- a/pyhap/media/webrtc_delegate.py +++ b/pyhap/media/webrtc_delegate.py @@ -43,6 +43,7 @@ from pyhap.camera_stream import StreamError from . import MediaError +from ._mdns import MDNS_TIMEOUT, resolve_answer from .pool import SourceLease, WebRTCMediaSender from .sdp import AudioParams, VideoParams @@ -171,8 +172,25 @@ async def handle_answer( sdp: str, candidates: list[hksv3.IceCandidate], ) -> None: - """Apply the answer and pull the channel while ICE and DTLS connect.""" + """Apply the answer and pull the channel while ICE and DTLS connect. + + mDNS names of the answer's candidates are resolved first, with the + Zeroconf instance of the camera's driver, which has to run on this + loop. A name that does not resolve costs up to two seconds of the + hook's time, at most a quarter of its ``hook_timeout``; the pull + starts after that. Without an instance, and for names that do not + resolve, the peer is only found by its own checks. + """ sender, lease, media = self._get(session) + camera = session.camera + if camera is not None: + hook_timeout = camera.webrtc_controllers[session.sensor_uuid].hook_timeout + sdp, candidates = await resolve_answer( + camera.driver.advertiser, + sdp, + candidates, + min(MDNS_TIMEOUT, hook_timeout / 4), + ) try: await sender.apply_answer(sdp, candidates) except MediaError as err: diff --git a/tests/test_camera_stream.py b/tests/test_camera_stream.py index 14ca3257..76f4e1fb 100644 --- a/tests/test_camera_stream.py +++ b/tests/test_camera_stream.py @@ -410,6 +410,18 @@ async def test_session_end( session_release.assert_awaited_once_with(session) +async def test_session_names_its_camera( + session_controller: StreamController[StreamSession], + add_session: Callable[..., StreamSession], + stream_sensor: hksv3.SensorConfiguration, +) -> None: + """Test a session of a stream service knows its camera, another does not.""" + lone = StreamSession(id=uuid4(), sensor=stream_sensor, client_addr=CLIENT) + + assert add_session(CLIENT).camera is session_controller.camera + assert lone.camera is None + + def test_session_end_without_controller( stream_sensor: hksv3.SensorConfiguration, ) -> None: diff --git a/tests/test_media_mdns.py b/tests/test_media_mdns.py new file mode 100644 index 00000000..6e960bb1 --- /dev/null +++ b/tests/test_media_mdns.py @@ -0,0 +1,387 @@ +"""Tests for pyhap.media._mdns, the mDNS names of answer candidates.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Sequence +import sys +from types import SimpleNamespace +from typing import Any, cast + +import pytest +import zeroconf + +from pyhap import hksv3 +from pyhap.camera_stream import MAX_HOOK_TIMEOUT +from pyhap.media import _mdns, sdp + +pytestmark = pytest.mark.timeout(5) + +ZEROCONF = cast(Any, object()) +NAME = "0a1b2c3d-4e5f.local" +ADDRESS = "192.168.1.20" +CREDENTIALS = ( + "a=ice-ufrag:abcd\r\n" + "a=ice-pwd:0123456789abcdef012345\r\n" + f"a=fingerprint:sha-256 {':'.join(['AB'] * 32)}\r\n" +) +ANSWER = ( + "v=0\r\n" + "o=- 1 2 IN IP4 127.0.0.1\r\n" + "s=-\r\n" + "t=0 0\r\n" + "a=group:BUNDLE 0\r\n" + f"{CREDENTIALS}" + "m=video 9 UDP/TLS/RTP/SAVPF 99\r\n" + "c=IN IP4 0.0.0.0\r\n" + "a=mid:0\r\n" +) + + +def _hap(candidate: str) -> hksv3.IceCandidate: + return hksv3.IceCandidate(candidate, "0", 0) + + +def _candidate(host: str, number: int = 1) -> hksv3.IceCandidate: + return _hap(f"candidate:{number} 1 udp 2122260223 {host} 5000 typ host") + + +def _answers( + monkeypatch: pytest.MonkeyPatch, answers: dict[str, str] +) -> list[tuple[list[str], float]]: + """Answer lookups from a table and return what was asked.""" + asked: list[tuple[list[str], float]] = [] + + async def lookup(_zeroconf: Any, names: Sequence[str], timeout: float) -> Any: + asked.append((list(names), timeout)) + return {name: answers[name] for name in names if name in answers} + + monkeypatch.setattr(_mdns, "_lookup", lookup) + return asked + + +def _instance( + loop: asyncio.AbstractEventLoop | None = None, started: bool = True +) -> Any: + """Stand in for an AsyncZeroconf whose instance runs on ``loop``.""" + return SimpleNamespace(zeroconf=SimpleNamespace(loop=loop, started=started)) + + +async def test_names_are_resolved_in_the_sdp_and_the_hap_candidates( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify a resolved name is replaced everywhere, however it is written.""" + asked = _answers(monkeypatch, {NAME: ADDRESS}) + answer = ( + ANSWER + + f"a=candidate:7 1 udp 1 {NAME.upper()} 5000 typ host\r\n" + + "a=candidate:8 1 udp 1 10.0.0.9 5000 typ host\r\n" + ) + + resolved_sdp, resolved = await _mdns.resolve_answer( + ZEROCONF, answer, [_candidate(NAME), _candidate("10.0.0.1", 2)] + ) + + assert asked == [([NAME], _mdns.MDNS_TIMEOUT)] + assert resolved_sdp == answer.replace(NAME.upper(), ADDRESS) + assert resolved == [_candidate(ADDRESS), _candidate("10.0.0.1", 2)] + + +async def test_only_the_address_of_a_candidate_is_replaced( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify the name is replaced where it is the address, other bytes stay.""" + asked = _answers(monkeypatch, {NAME: ADDRESS}) + line = "a=candidate:{0} 1\tUDP 1 {0} 5000 typ host raddr {0} rport 9" + answer = ANSWER.replace("\r\n", "\n") + line.format(NAME) + "\na=x" + + resolved_sdp, resolved = await _mdns.resolve_answer(ZEROCONF, answer, [], 0.5) + + assert asked == [([NAME], 0.5)] + assert resolved_sdp == ( + ANSWER.replace("\r\n", "\n") + + f"a=candidate:{NAME} 1\tUDP 1 {ADDRESS} 5000 typ host raddr {NAME} rport 9" + + "\na=x" + ) + assert resolved == [] + + +@pytest.mark.parametrize( + "address", + [ + "127.0.0.1", + "::1", + "::ffff:127.0.0.1", + "224.0.0.251", + "ff02::fb", + "0.0.0.0", + "255.255.255.255", + "::ffff:255.255.255.255", + "x", + ], + ids=[ + "loopback", + "loopback-v6", + "loopback-mapped", + "multicast", + "multicast-v6", + "unspecified", + "broadcast", + "broadcast-mapped", + "no-address", + ], +) +async def test_answers_that_name_no_peer_are_not_taken( + monkeypatch: pytest.MonkeyPatch, address: str +) -> None: + """Verify a name stays when its answer is not a unicast peer address.""" + _answers(monkeypatch, {NAME: address}) + + _, resolved = await _mdns.resolve_answer(ZEROCONF, ANSWER, [_candidate(NAME)]) + + assert resolved == [_candidate(NAME)] + + +async def test_candidates_are_read_as_the_transport_reads_them( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify only candidates the transport uses have their names asked for.""" + used = [ + _hap("candidate: 1 1 udp 1 spaced.local 5000 typ host"), + _hap(" a=candidate:2 01 UDP 1 prefixed.local 5000 typ host"), + _hap(" candidate: 3 1 udp 1 led.local 5000 typ host"), + _hap("a=candidate: 4 1 udp 1 both.local 5000 typ host"), + ] + unused = [ + _hap("candidate:5 1 tcp 1 tcp.local 5000 typ host"), + _hap("candidate:6 2 udp 1 rtcp.local 5000 typ host"), + _hap("candidate:7 1 udp 1 port.local 0 typ host"), + _hap("candidate:8 1 udp 1 short.local 5000"), + # The transport reads it, but its name cannot be replaced in place. + _hap("candidate:candidate: 9 1 udp 1 twice.local 5000 typ host"), + ] + session_level = "a=candidate:10 1 udp 1 session.local 5000 typ host\r\n" + answer = ANSWER.replace("m=video", f"{session_level}m=video") + names = ["spaced.local", "prefixed.local", "led.local", "both.local"] + extra = ["tcp.local", "rtcp.local", "port.local", "twice.local", "session.local"] + asked = _answers(monkeypatch, dict.fromkeys([*names, *extra], ADDRESS)) + + resolved_sdp, resolved = await _mdns.resolve_answer( + ZEROCONF, answer, [*unused, *used] + ) + + assert asked == [(names, _mdns.MDNS_TIMEOUT)] + assert resolved_sdp == answer + assert resolved[: len(unused)] == unused + assert [c.candidate for c in resolved[len(unused) :]] == [ + "candidate: 1 1 udp 1 192.168.1.20 5000 typ host", + " a=candidate:2 01 UDP 1 192.168.1.20 5000 typ host", + " candidate: 3 1 udp 1 192.168.1.20 5000 typ host", + "a=candidate: 4 1 udp 1 192.168.1.20 5000 typ host", + ] + + +@pytest.mark.parametrize( + ("length", "asked"), + [(253, 1), (254, 0), (len(".local"), 0)], + ids=["longest-dns-name", "too-long", "no-label"], +) +async def test_names_of_a_length_dns_has_are_asked_for( + monkeypatch: pytest.MonkeyPatch, length: int, asked: int +) -> None: + """Verify an over-long name, or none before the suffix, is not asked for.""" + name = f"{'a' * (length - len('.local'))}.local" + requests = _answers(monkeypatch, {name: ADDRESS}) + + await _mdns.resolve_answer(ZEROCONF, ANSWER, [_candidate(name)]) + + assert len(requests) == asked + + +def test_default_timeout_covers_a_lost_first_answer() -> None: + """Verify the wait reaches the answer to zeroconf's second question. + + That one came after about 1.3 seconds where the first answer got lost. + The wait also has to leave the answer hook most of its time. + """ + assert 1.5 <= _mdns.MDNS_TIMEOUT <= MAX_HOOK_TIMEOUT / 4 + + +async def test_few_names_are_asked_for(monkeypatch: pytest.MonkeyPatch) -> None: + """Verify an answer cannot make the camera ask for many names.""" + names = [f"host-{number}.local" for number in range(6)] + asked = _answers(monkeypatch, dict.fromkeys(names, ADDRESS)) + + _, resolved = await _mdns.resolve_answer( + ZEROCONF, ANSWER, [_candidate(name) for name in [*names, names[0].upper()]] + ) + + assert asked == [(names[: _mdns.MAX_MDNS_NAMES], _mdns.MDNS_TIMEOUT)] + assert [c.candidate.split()[4] for c in resolved] == [ + *[ADDRESS] * 4, + *names[4:], + ADDRESS, + ] + + +@pytest.mark.parametrize( + ("instance", "answer", "candidates"), + [ + (None, ANSWER, [_candidate(NAME)]), + (ZEROCONF, ANSWER, [_candidate("10.0.0.1")]), + (ZEROCONF, ANSWER + "a=x\r\n" * sdp.MAX_SDP_SIZE, [_candidate(NAME)]), + (ZEROCONF, ANSWER.replace(CREDENTIALS, ""), [_candidate(NAME)]), + ], + ids=["no-instance", "no-names", "too-large", "no-credentials"], +) +async def test_nothing_is_asked( + monkeypatch: pytest.MonkeyPatch, + instance: Any, + answer: str, + candidates: list[hksv3.IceCandidate], +) -> None: + """Verify an answer is kept as it is when there is nothing to resolve.""" + asked = _answers(monkeypatch, {NAME: ADDRESS}) + + assert await _mdns.resolve_answer(instance, answer, candidates) == ( + answer, + candidates, + ) + assert asked == [] + + +def _new_instances(monkeypatch: pytest.MonkeyPatch) -> list[object]: + """Record the Zeroconf instances that get created, and refuse them.""" + created: list[object] = [] + + def refuse(instance: object, *_args: object, **_kwargs: object) -> None: + created.append(instance) + raise AssertionError("A lookup must not create a Zeroconf instance") + + # Patched on the classes: zeroconf.asyncio holds its own name for Zeroconf. + monkeypatch.setattr("zeroconf.Zeroconf.__init__", refuse) + monkeypatch.setattr("zeroconf.asyncio.AsyncZeroconf.__init__", refuse) + return created + + +class _Resolver: + """Stand in for zeroconf.AddressResolver: answers after a delay, if any.""" + + delays: dict[str, float] + requests: list[tuple[str, Any, int]] + cancelled: list[str] + + def __init__(self, name: str) -> None: + self.name = name + + async def async_request(self, instance: Any, timeout: int) -> bool: + self.requests.append((self.name, instance, timeout)) + delay = self.delays.get(self.name) + try: + await asyncio.sleep(9 if delay is None else delay) + except asyncio.CancelledError: + self.cancelled.append(self.name) + raise + return delay is not None + + def parsed_scoped_addresses(self) -> list[str]: + return [ADDRESS, "fe80::1%eth0"] + + +@pytest.fixture +def resolver(monkeypatch: pytest.MonkeyPatch) -> type[_Resolver]: + """Replace zeroconf's resolver by one with a table of answer delays.""" + _Resolver.delays, _Resolver.requests, _Resolver.cancelled = {}, [], [] + monkeypatch.setattr(zeroconf, "AddressResolver", _Resolver) + return _Resolver + + +async def test_lookup_uses_the_given_instance(monkeypatch: pytest.MonkeyPatch) -> None: + """Verify every name is asked on the instance; failures leave a name out.""" + table: dict[str, list[str]] = { + "a.local.": [ADDRESS, "fe80::1%eth0"], + "b.local.": [], + } + requests: list[tuple[str, Any, int]] = [] + + class Resolver: + def __init__(self, name: str) -> None: + self.name = name + + async def async_request(self, instance: Any, timeout: int) -> bool: + requests.append((self.name, instance, timeout)) + if self.name == "c.local.": + raise OSError("no route") + return self.name in table + + def parsed_scoped_addresses(self) -> list[str]: + return table[self.name] + + created = _new_instances(monkeypatch) + monkeypatch.setattr(zeroconf, "AddressResolver", Resolver) + instance = _instance(asyncio.get_running_loop()) + + found = await _mdns._lookup( + instance, ["a.local", "b.local", "c.local", "d.local"], 1.5 + ) + + assert found == {"a.local": ADDRESS} + assert requests == [(f"{name}.local.", instance.zeroconf, 1500) for name in "abcd"] + assert created == [] + + +async def test_lookup_takes_what_arrived_in_time(resolver: type[_Resolver]) -> None: + """Verify answers count as they come, a late one is given up.""" + resolver.delays = {"first.local.": 0.05, "second.local.": 0.4} + loop = asyncio.get_running_loop() + started = loop.time() + + found = await _mdns._lookup( + _instance(loop), ["first.local", "second.local", "never.local"], 0.6 + ) + await asyncio.sleep(0) + + assert found == {"first.local": ADDRESS, "second.local": ADDRESS} + assert loop.time() - started < 1.0 + assert resolver.cancelled == ["never.local."] + + +async def test_lookup_is_given_up_with_its_caller(resolver: type[_Resolver]) -> None: + """Verify the requests end when the caller is cancelled, e.g. its hook.""" + lookup = asyncio.ensure_future( + _mdns._lookup(_instance(asyncio.get_running_loop()), ["never.local"], 3) + ) + await asyncio.sleep(0.05) + + lookup.cancel() + await asyncio.wait([lookup]) + await asyncio.sleep(0) + + assert lookup.cancelled() + assert resolver.cancelled == ["never.local."] + + +@pytest.mark.parametrize( + "case", ["other-loop", "not-started", "old-zeroconf", "no-names"] +) +async def test_lookup_without_a_usable_zeroconf( + monkeypatch: pytest.MonkeyPatch, resolver: type[_Resolver], case: str +) -> None: + """Verify nothing is asked where a request could not work or do harm.""" + loop = asyncio.get_running_loop() + other = asyncio.new_event_loop() + instance = { + "other-loop": _instance(other), + # Giving up on a request would cancel the start of the instance. + "not-started": _instance(loop, started=False), + "old-zeroconf": _instance(loop), + "no-names": _instance(loop), + }[case] + monkeypatch.setitem( + sys.modules, "zeroconf", None if case == "old-zeroconf" else zeroconf + ) + + names = [] if case == "no-names" else ["a.local"] + assert await _mdns._lookup(instance, names, 0.2) == {} + assert resolver.requests == [] + other.close() diff --git a/tests/test_media_sender.py b/tests/test_media_sender.py index 2418f92e..a1c68a69 100644 --- a/tests/test_media_sender.py +++ b/tests/test_media_sender.py @@ -50,7 +50,7 @@ video_count, wait_until, ) -from .webrtc_helpers import SFrameKey # noqa: E402 +from .webrtc_helpers import IceCandidate, SFrameKey # noqa: E402 pytestmark = pytest.mark.timeout(5) @@ -441,11 +441,27 @@ async def test_negotiation_timeout_counts_from_answer() -> None: answer, candidates = await controller.answer(offer) started = time.monotonic() await sender.apply_answer(answer, candidates) - assert "timed out" in await asyncio.wait_for(closed.get(), 3) + assert await asyncio.wait_for(closed.get(), 3) == "negotiation timed out" assert time.monotonic() - started >= 0.25 await controller.close() +async def test_negotiation_timeout_names_ignored_mdns_candidates() -> None: + """Verify the end reason says a peer was known by mDNS names alone.""" + sender = make_sender(negotiation_timeout=0.3) + closed: asyncio.Queue[str] = asyncio.Queue() + sender.on_closed = closed.put_nowait + controller = Controller() + try: + answer, _ = await controller.answer(await sender.create_offer()) + mdns = "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 9 typ host" + await sender.apply_answer(answer, [IceCandidate(mdns, "0", 0)]) + reason = await asyncio.wait_for(closed.get(), 3) + assert reason == "negotiation timed out (mDNS candidates ignored: 1)" + finally: + await controller.close() + + async def test_close_during_create_offer() -> None: """Verify closing while the offer is made leaks no socket or task.""" sender = make_sender() diff --git a/tests/test_media_transport.py b/tests/test_media_transport.py index 405ad840..ed593ef4 100644 --- a/tests/test_media_transport.py +++ b/tests/test_media_transport.py @@ -198,43 +198,11 @@ async def test_unusable_fingerprints_are_refused( await answerer.close() -async def test_mdns_candidates_are_bounded_and_checked( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Verify few mDNS names are resolved at once and bad answers are dropped.""" - asked: list[list[str]] = [] - answers = { - "a.local": "192.168.1.20", - "b.local": "127.0.0.1", - "c.local": "224.0.0.251", - "d.local": None, - "e.local": "192.168.1.21", - } - - async def resolve(names: list[str], _timeout: float) -> dict[str, str | None]: - asked.append(list(names)) - return {name: answers[name] for name in names} - - monkeypatch.setattr(transport, "resolve_mdns", resolve) - candidates = transport._remote_candidates( - [ - f"candidate:{i} 1 udp {100 - i} {name} 5000 typ host" - for i, name in enumerate(answers) - ] - + ["candidate:9 1 udp 1 192.168.1.30 5000 typ host"] - ) - - resolved = await transport._resolve_candidates(candidates) - - assert asked == [["a.local", "b.local", "c.local", "d.local"]] - assert [c.host for c in resolved] == ["192.168.1.20", "192.168.1.30"] - - async def test_connect_timeout() -> None: """Verify ICE without a reachable peer times out.""" lone = make_transport(True) await lone.gather() - with pytest.raises(TransportError, match="timed out"): + with pytest.raises(TransportError, match=r"^WebRTC connection timed out$"): await lone.connect( remote_username="user", remote_password="password0123456789abcd", @@ -363,7 +331,7 @@ def test_remote_candidates_capped_and_deduplicated() -> None: "garbage", *numbered_candidates(40), ] - parsed = transport._remote_candidates(values) + parsed, _ = transport._remote_candidates(values) assert len(parsed) == transport.MAX_REMOTE_CANDIDATES assert parsed[0].port == 1000 assert parsed[1].port == 2000 @@ -376,8 +344,7 @@ def test_remote_candidates_capped_and_deduplicated() -> None: "candidate:1 1 udp 1 10.0.0.1 65536 typ host", "candidate:1 1 udp 1 example.com 1000 typ host", "candidate:1 1 udp 1 10.0.0.1x 1000 typ host", - f"candidate:1 1 udp 1 {'a' * 250}.local 1000 typ host", - "candidate:1 1 udp 1 .local 1000 typ host", + "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 1000 typ host", "candidate:1 1 udp 1 0.0.0.0 1000 typ host", "candidate:1 1 udp 1 :: 1000 typ host", "candidate:1 1 udp 1 224.0.0.251 1000 typ host", @@ -391,8 +358,7 @@ def test_remote_candidates_capped_and_deduplicated() -> None: "port-high", "dns-name", "bad-ip", - "long-mdns", - "empty-mdns", + "mdns", "unspecified-v4", "unspecified-v6", "multicast-v4", @@ -403,8 +369,8 @@ def test_remote_candidates_capped_and_deduplicated() -> None: ], ) def test_remote_candidates_drop_unusable_addresses(value: str) -> None: - """Verify bad ports, non-unicast IPs and hosts other than IP or mDNS drop.""" - assert transport._remote_candidates([value]) == [] + """Verify bad ports, non-unicast IPs and hosts other than an IP drop.""" + assert transport._remote_candidates([value])[0] == [] @pytest.mark.parametrize( @@ -412,13 +378,157 @@ def test_remote_candidates_drop_unusable_addresses(value: str) -> None: [ "candidate:1 1 udp 1 10.0.0.1 65535 typ host", "candidate:1 1 udp 1 fe80::1%en0 1000 typ host", - "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 1000 typ host", ], - ids=["ipv4", "ipv6-zone", "mdns"], + ids=["ipv4", "ipv6-zone"], ) def test_remote_candidates_keep_usable_addresses(value: str) -> None: - """Verify IP addresses and mDNS names with a valid port are kept.""" - assert len(transport._remote_candidates([value])) == 1 + """Verify IP addresses with a valid port are kept.""" + assert len(transport._remote_candidates([value])[0]) == 1 + + +def test_remote_candidates_drop_mdns_names(caplog: pytest.LogCaptureFixture) -> None: + """Verify mDNS names are dropped and counted, other candidates stay.""" + caplog.set_level("DEBUG", logger=transport.__name__) + parsed, mdns = transport._remote_candidates( + [ + "candidate:1 1 udp 3 0a1b2c3d-4e5f.local 1000 typ host", + "candidate:2 1 udp 2 10.0.0.1 1000 typ host", + "candidate:3 1 UDP 1 6f7a8b9c-0d1e.LOCAL 1000 typ host", + "candidate:4 2 udp 1 7a8b9c0d-1e2f.local 1000 typ host", + "candidate:5 1 tcp 1 8b9c0d1e-2f3a.local 1000 typ host", + ] + ) + assert [c.host for c in parsed] == ["10.0.0.1"] + assert mdns == 2 + assert caplog.messages == ["mDNS candidates ignored, they are not resolved: 2"] + + +async def test_failed_connect_names_the_ignored_mdns_candidates() -> None: + """Verify a peer that never checks fails with a hint to its mDNS names.""" + lone = make_transport(True) + await lone.gather() + try: + with pytest.raises( + TransportError, + match=r"^WebRTC connection timed out \(mDNS candidates ignored: 1\)$", + ): + await lone.connect( + remote_username="u", + remote_password="p", + remote_candidates=[ + "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 9 typ host" + ], + remote_fingerprints=[], + role=DtlsRole.CLIENT, + timeout=0.2, + ) + finally: + await lone.close() + + +async def test_failed_checks_name_the_ignored_mdns_candidates() -> None: + """Verify failed ICE checks come with the hint to the peer's mDNS names.""" + + async def fail(_candidates: object) -> None: + raise ConnectionError("ICE checks failed") + + lone = make_transport(True) + setattr(lone._ice, "connect", fail) # noqa: B010 - replaces a method + try: + with pytest.raises( + TransportError, + match=r"failed: ICE checks failed \(mDNS candidates ignored: 1\)$", + ): + await lone.connect( + remote_username="u", + remote_password="p", + remote_candidates=[ + "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 9 typ host" + ], + remote_fingerprints=[], + role=DtlsRole.CLIENT, + ) + finally: + await lone.close() + + +async def test_failure_after_ice_does_not_name_mdns_candidates() -> None: + """Verify a stalled DTLS handshake is not blamed on ignored mDNS names.""" + offerer, answerer = make_transport(True), make_transport(False) + try: + offer_candidates = await offerer.gather() + answer_candidates = await answerer.gather() + # Both wait for the other's first handshake message. + results = await asyncio.gather( + offerer.connect( + remote_username=answerer.local_username, + remote_password=answerer.local_password, + remote_candidates=[ + *answer_candidates, + "candidate:9 1 udp 1 0a1b2c3d-4e5f.local 9 typ host", + ], + remote_fingerprints=[("sha-256", answerer.certificate.fingerprint)], + role=DtlsRole.SERVER, + timeout=1, + ), + answerer.connect( + remote_username=offerer.local_username, + remote_password=offerer.local_password, + remote_candidates=offer_candidates, + remote_fingerprints=[("sha-256", offerer.certificate.fingerprint)], + role=DtlsRole.SERVER, + timeout=1, + ), + return_exceptions=True, + ) + assert offerer._ice.selected_pair is not None + assert str(results[0]) == "WebRTC connection timed out" + finally: + await offerer.close() + await answerer.close() + + +async def test_peer_with_only_an_mdns_candidate_connects( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify a peer known by an mDNS name alone is found by its own checks.""" + + def refuse(*_args: object, **_kwargs: object) -> None: + raise AssertionError("The transport must not create a Zeroconf instance") + + # Patched on the classes: zeroconf.asyncio holds its own name for Zeroconf. + monkeypatch.setattr("zeroconf.Zeroconf.__init__", refuse) + monkeypatch.setattr("zeroconf.asyncio.AsyncZeroconf.__init__", refuse) + offerer, answerer = make_transport(True), make_transport(False) + try: + offer_candidates = await offerer.gather() + await answerer.gather() + await asyncio.gather( + offerer.connect( + remote_username=answerer.local_username, + remote_password=answerer.local_password, + remote_candidates=[ + "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 9 typ host" + ], + remote_fingerprints=[("sha-256", answerer.certificate.fingerprint)], + role=DtlsRole.CLIENT, + timeout=5, + ), + answerer.connect( + remote_username=offerer.local_username, + remote_password=offerer.local_password, + remote_candidates=offer_candidates, + remote_fingerprints=[("sha-256", offerer.certificate.fingerprint)], + role=DtlsRole.SERVER, + timeout=5, + ), + ) + answer_rtp, _ = collect(answerer) + await offerer.send_rtp(RTP) + assert await asyncio.wait_for(answer_rtp.get(), 2) == RTP + finally: + await offerer.close() + await answerer.close() def numbered_candidates(count: int) -> list[str]: @@ -484,7 +594,7 @@ async def test_unexpected_connect_error_is_a_transport_error() -> None: """Verify any failure while connecting comes out as TransportError.""" lone = make_transport(True) setattr(lone, "_connect", fail_connect) # noqa: B010 - replaces a method - with pytest.raises(TransportError, match="mdns"): + with pytest.raises(TransportError, match="socket"): await lone.connect( remote_username="u", remote_password="p", @@ -496,8 +606,8 @@ async def test_unexpected_connect_error_is_a_transport_error() -> None: async def fail_connect(*_args: object) -> None: - """Fail like an mDNS socket that cannot bind.""" - raise OSError("mdns port in use") + """Fail like a socket that cannot be used.""" + raise OSError("socket failed") async def test_close_waits_for_a_close_under_way( diff --git a/tests/test_media_webrtc_delegate.py b/tests/test_media_webrtc_delegate.py index 8c0dfa09..328ff064 100644 --- a/tests/test_media_webrtc_delegate.py +++ b/tests/test_media_webrtc_delegate.py @@ -138,6 +138,69 @@ async def test_keys_differ_per_session( assert first.sframe != second.sframe +MDNS_CANDIDATE = "candidate:1 1 udp 1 0a1b2c3d-4e5f.local 9 typ host" +ANSWER = ( + "v=0\r\n" + "o=- 1 2 IN IP4 127.0.0.1\r\n" + "s=-\r\n" + "t=0 0\r\n" + "a=ice-ufrag:abcd\r\n" + "a=ice-pwd:0123456789abcdef012345\r\n" + f"a=fingerprint:sha-256 {':'.join(['AB'] * 32)}\r\n" + "m=video 9 UDP/TLS/RTP/SAVPF 99\r\n" + "a=mid:0\r\n" + f"a={MDNS_CANDIDATE.replace(' 9 ', ' 10 ')}\r\n" +) + + +@pytest.mark.parametrize( + ("advertiser", "hook_timeout", "asked", "host"), + [ + (object(), 8.0, [2.0], "192.168.1.20"), + (object(), 2.0, [0.5], "192.168.1.20"), + (None, 8.0, [], "0a1b2c3d-4e5f.local"), + ], + ids=["driver-instance", "short-hook", "no-instance"], +) +async def test_answer_resolves_mdns_candidates_with_the_drivers_zeroconf( + monkeypatch: pytest.MonkeyPatch, + media_delegate: WebRTCMediaDelegate, + webrtc_session: Callable[..., WebRTCSession], + advertiser: object, + hook_timeout: float, + asked: list[float], + host: str, +) -> None: + """Verify names are resolved on the driver's instance, in part of the hook.""" + timeouts: list[float] = [] + + async def lookup(instance: object, names: list[str], timeout: float) -> Any: + assert instance is advertiser + timeouts.append(timeout) + return dict.fromkeys(names, "192.168.1.20") + + monkeypatch.setattr("pyhap.media._mdns._lookup", lookup) + session = webrtc_session() + session._controller = cast(Any, MagicMock()) + session._controller.camera.driver.advertiser = advertiser + session._controller.camera.webrtc_controllers = { + session.sensor_uuid: MagicMock(hook_timeout=hook_timeout) + } + + await offer(media_delegate, session) + await media_delegate.handle_answer( + session, ANSWER, [hksv3.IceCandidate(MDNS_CANDIDATE, "0", 0)] + ) + + name = "0a1b2c3d-4e5f.local" + assert timeouts == asked + assert sender_of(media_delegate, session).calls[1] == ( + "answer", + ANSWER.replace(name, host), + [hksv3.IceCandidate(MDNS_CANDIDATE.replace(name, host), "0", 0)], + ) + + async def test_answer_starts_the_pull( media_delegate: WebRTCMediaDelegate, webrtc_session: Callable[..., WebRTCSession],