Skip to content

Commit f0090e4

Browse files
committed
fix: don't degrade or crash on a listen-socket rebuild failure
The Default dual-use conversion demoted the socket from senders before the fallible rebuild, so a rebuild failure left it pulled from senders but not replaced (instance stops responding) and propagated into the caller's handler. The explicit demote was redundant; the rebuild removes the old transport from senders itself, but only after the new socket succeeds. Drop the pre-demote (keep only the diff-view pop) so a failed rebuild leaves senders intact, and catch the rebuild failure as a logged no-op to honor the best-effort contract.
1 parent 55ca5ea commit f0090e4

2 files changed

Lines changed: 59 additions & 17 deletions

File tree

‎src/zeroconf/_engine.py‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -237,25 +237,32 @@ async def async_update_interfaces(
237237

238238
# A Default single-family instance shares the listen socket as its only
239239
# sender (the dual-use socket). Moving it to an explicit interface set
240-
# abandons that optimization: demote the socket so it stops responding
241-
# (otherwise it would double every announcement on the overlapping
242-
# interface) and rebuild it as a pure listener (its existing group
243-
# memberships would otherwise collide with the new per-interface joins).
244-
# Once demoted it no longer counts as a per-interface sender, so the
245-
# interface it served gets a fresh responder like any other. The no-arg
246-
# refresh of a Default instance leaves desired == {its interface} and so
247-
# neither demotes nor rebuilds.
240+
# abandons that optimization: rebuild it as a pure listener (its existing
241+
# group memberships would otherwise collide with the new per-interface
242+
# joins), which also stops it responding so it can't double-announce on
243+
# the overlapping interface. Drop it from the diff's view so the desired
244+
# interfaces are added fresh; the actual sender removal is done by the
245+
# rebuild once it succeeds (so a failed rebuild leaves senders intact).
246+
# The no-arg refresh of a Default instance leaves desired == {its
247+
# interface} and so neither converts nor rebuilds.
248248
if listen_transport is not None and any(
249249
wrapped.transport is listen_transport.transport for wrapped in self.senders
250250
):
251251
listen_key = listen_transport.interface_key
252252
if any(key != listen_key for key in desired):
253-
self.senders = _without_transport(self.senders, listen_transport.transport)
254253
current.pop(listen_key, None)
255254
needs_rebuild = True
256255

257256
if needs_rebuild:
258-
await self._async_rebuild_listen_socket(apple_p2p, desired, current)
257+
try:
258+
await self._async_rebuild_listen_socket(apple_p2p, desired, current)
259+
except (OSError, RuntimeError) as exc:
260+
# A fresh wildcard bind / endpoint creation can transiently fail
261+
# during adapter churn. The rebuild raises before tearing down
262+
# the old listen socket, so state is unchanged; log and no-op
263+
# rather than crash the caller's handler (best-effort contract).
264+
log.warning("Skipping interface update; listen socket rebuild failed: %s", exc)
265+
return False
259266
listen_transport = self._listen_transport
260267
listen_socket = listen_transport.sock if listen_transport is not None else None
261268

‎tests/test_interface_update.py‎

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -704,16 +704,50 @@ async def fake_wrap(sock: object, is_sender: bool) -> _WrappedTransport:
704704

705705

706706
@pytest.mark.asyncio
707-
async def test_update_interfaces_rebuild_failure_raises(aiozc_loopback: AsyncZeroconf) -> None:
708-
"""If the replacement listen socket can't be created, the rebuild raises."""
707+
async def test_update_interfaces_rebuild_failure_is_noop(
708+
aiozc_loopback: AsyncZeroconf, caplog: pytest.LogCaptureFixture
709+
) -> None:
710+
"""If the replacement listen socket can't be created, the rescan logs and no-ops."""
709711
engine = aiozc_loopback.zeroconf.engine
710712
await aiozc_loopback.zeroconf.async_wait_for_start()
713+
old_listen = engine._listen_transport
714+
before = (list(engine.senders), list(engine.readers))
711715
with (
712716
patch.object(_engine, "normalize_interface_choice", return_value=[(("fe80::1", 0, 0), 1)]),
713717
patch.object(_engine, "new_listen_socket", return_value=None),
714-
pytest.raises(RuntimeError, match="listen socket"),
718+
caplog.at_level(logging.WARNING),
715719
):
716-
await engine.async_update_interfaces(["unused"], IPVersion.V6Only, False)
720+
added = await engine.async_update_interfaces(["unused"], IPVersion.V6Only, False)
721+
722+
# Best-effort: no raise into the caller, state left untouched.
723+
assert added is False
724+
assert "listen socket rebuild failed" in caplog.text
725+
assert engine._listen_transport is old_listen
726+
assert (list(engine.senders), list(engine.readers)) == before
727+
728+
729+
@pytest.mark.asyncio
730+
async def test_update_interfaces_default_rebuild_failure_keeps_dual_use(
731+
aiozc_loopback: AsyncZeroconf,
732+
) -> None:
733+
"""A failed rebuild during a dual-use conversion leaves the dual-use sender intact."""
734+
engine = aiozc_loopback.zeroconf.engine
735+
await aiozc_loopback.zeroconf.async_wait_for_start()
736+
listen = engine._listen_transport
737+
assert listen is not None
738+
# Simulate a Default single-family instance: the listen socket is the sole sender.
739+
engine.senders = [listen]
740+
with (
741+
patch.object(_engine, "normalize_interface_choice", return_value=["192.168.1.5"]),
742+
patch.object(_engine, "new_listen_socket", return_value=None),
743+
):
744+
added = await engine.async_update_interfaces(["unused"], IPVersion.V4Only, False)
745+
746+
# The dual-use socket was not demoted before the (failed) rebuild, so the
747+
# instance still responds on its interface rather than going silent.
748+
assert added is False
749+
assert engine.senders == [listen]
750+
assert engine._listen_transport is listen
717751

718752

719753
@pytest.mark.asyncio
@@ -732,11 +766,12 @@ async def test_update_interfaces_rebuild_closes_socket_on_wrap_failure(
732766
patch.object(_engine, "new_listen_socket", return_value=new_listen_sock),
733767
patch.object(_engine, "add_multicast_member", return_value=True),
734768
patch.object(_engine.AsyncEngine, "_async_wrap_socket", new=AsyncMock(side_effect=OSError("boom"))),
735-
pytest.raises(OSError),
736769
):
737-
await engine.async_update_interfaces(["unused"], IPVersion.V6Only, False)
770+
added = await engine.async_update_interfaces(["unused"], IPVersion.V6Only, False)
738771

739-
# The unadopted socket was closed, and the old listen socket is untouched.
772+
# Best-effort no-op: the unadopted socket was closed (not leaked) and the
773+
# old listen socket is untouched.
774+
assert added is False
740775
new_listen_sock.close.assert_called_once()
741776
assert engine._listen_transport is old_listen
742777

0 commit comments

Comments
 (0)