Skip to content

Commit a334cb0

Browse files
committed
fix: keep query dedup unscoped and scope only link-local AAAA records
Scope-aware suppression now applies only to responses, so the IPv4 and IPv6 copies of a query are still answered once (RFC 6762 sections 6, 14). The parser attaches the receiving scope only to link-local AAAA records (RFC 4007 section 6), so global addresses from differently scoped senders no longer appear as new records and fire extra Updated events. AAAA known answers cached under several scopes are written once.
1 parent c71b73e commit a334cb0

8 files changed

Lines changed: 113 additions & 4 deletions

File tree

‎src/zeroconf/_listener.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,9 @@ def _process_datagram_at_time(
235235
data: _bytes,
236236
addrs: tuple[str, int] | tuple[str, int, int, int],
237237
) -> None:
238-
sender_scope = addrs[3] if len(addrs) == 4 else 0
238+
# Only a response's records take the sender's scope (QR is the top
239+
# bit of header byte 2), so queries keep scope-independent dedup.
240+
sender_scope = addrs[3] if len(addrs) == 4 and data_len > 2 and data[2] & 0x80 else 0
239241
if (
240242
self.data == data
241243
and self.last_sender_scope == sender_scope

‎src/zeroconf/_protocol/incoming.pxd‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ cdef class DNSIncoming:
121121
name_start="unsigned int",
122122
offset="unsigned int",
123123
address_rec=DNSAddress,
124+
address=bytes,
124125
pointer_rec=DNSPointer,
125126
text_rec=DNSText,
126127
srv_rec=DNSService,

‎src/zeroconf/_protocol/incoming.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -530,14 +530,20 @@ def _read_record(
530530
)
531531
return hinfo_rec
532532
if type_ == _TYPE_AAAA:
533+
offset = self.offset
534+
address = self._read_string(16)
535+
buf = self._buf
533536
address_rec = DNSAddress.__new__(DNSAddress)
537+
# A zone index only means something for link-local fe80::/10
538+
# (RFC 4007 section 6); scoping other addresses would make
539+
# copies from differently scoped senders look like new records.
534540
address_rec._fast_init(
535541
domain,
536542
type_,
537543
class_,
538544
ttl,
539-
self._read_string(16),
540-
self.scope_id,
545+
address,
546+
self.scope_id if buf[offset] == 0xFE and (buf[offset + 1] & 0xC0) == 0x80 else None,
541547
self.now,
542548
)
543549
return address_rec

‎src/zeroconf/_services/info.pxd‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ cdef class ServiceInfo(RecordUpdateListener):
169169
@cython.locals(cache=DNSCache, history=QuestionHistory, out=DNSOutgoing, qu_question=bint)
170170
cdef DNSOutgoing _generate_request_query(self, object zc, double now, object question_type)
171171

172-
@cython.locals(question=DNSQuestion, answer=DNSRecord)
172+
@cython.locals(question=DNSQuestion, answer=DNSRecord, address_answer=DNSAddress)
173173
cdef void _add_question_with_known_answers(
174174
self,
175175
DNSOutgoing out,

‎src/zeroconf/_services/info.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,15 @@ def _add_question_with_known_answers(
594594
else:
595595
question_history.add_question_at_time(question, now, known_answers)
596596
out.add_question(question)
597+
if type_ == _TYPE_AAAA and len(known_answers) > 1:
598+
# The cache can hold an AAAA record once per scope it was
599+
# received with, but the scope is not on the wire.
600+
by_address: dict[bytes, DNSRecord] = {}
601+
for address_answer in known_answers:
602+
if TYPE_CHECKING:
603+
address_answer = cast(DNSAddress, address_answer)
604+
by_address[address_answer.address] = address_answer
605+
known_answers = set(by_address.values())
597606
for answer in known_answers:
598607
out.add_answer_at_time(answer, now)
599608

‎tests/services/test_info.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3022,3 +3022,34 @@ def test_addresses_setter_rejects_invalid_address():
30223022
info = ServiceInfo(type_, f"xxxyyy.{type_}", 80, server="spare-rig.local.")
30233023
with pytest.raises(TypeError, match="Addresses must either be"):
30243024
info.addresses = ["not an address"]
3025+
3026+
3027+
@pytest.mark.asyncio
3028+
async def test_aaaa_known_answer_sent_once_per_address() -> None:
3029+
"""An AAAA cached under several scopes is sent as one known answer."""
3030+
aiozc = AsyncZeroconf(interfaces=["127.0.0.1"])
3031+
zc = aiozc.zeroconf
3032+
now = r.current_time_millis()
3033+
address = socket.inet_pton(socket.AF_INET6, "fe80::1")
3034+
zc.cache.async_add_records(
3035+
[
3036+
r.DNSAddress(
3037+
"host.local.",
3038+
const._TYPE_AAAA,
3039+
const._CLASS_IN | const._CLASS_UNIQUE,
3040+
120,
3041+
address,
3042+
scope_id=scope,
3043+
created=now,
3044+
)
3045+
for scope in (0, 2)
3046+
]
3047+
)
3048+
sent: list[DNSOutgoing] = []
3049+
info = ServiceInfo("_test._tcp.local.", "x._test._tcp.local.", server="host.local.")
3050+
with patch.object(zc, "async_send", lambda out, *args, **kwargs: sent.append(out)):
3051+
await info.async_request(zc, timeout=200)
3052+
assert sent
3053+
for out in sent:
3054+
assert [record.type for record, _ in out.answers].count(const._TYPE_AAAA) == 1
3055+
await aiozc.async_close()

‎tests/test_listener.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,42 @@ def scopes() -> set[int | None]:
315315
assert scopes() == set()
316316

317317

318+
def test_guard_against_duplicate_queries_across_sender_scopes(zc: Zeroconf) -> None:
319+
"""The scoped copy of a query is still suppressed as a duplicate of the unscoped one."""
320+
zc.registry.async_add(
321+
ServiceInfo(
322+
"_http._tcp.local.",
323+
"Test._http._tcp.local.",
324+
server="Test._http._tcp.local.",
325+
port=4,
326+
)
327+
)
328+
handled: list[tuple[str, int]] = []
329+
330+
class SubListener(_listener.AsyncListener):
331+
def handle_query_or_defer(
332+
self,
333+
msg: DNSIncoming,
334+
addr: str,
335+
port: int,
336+
transport: _engine._WrappedTransport,
337+
v6_flow_scope: tuple[()] | tuple[int, int] = (),
338+
) -> None:
339+
handled.append((addr, port))
340+
341+
listener = SubListener(zc)
342+
listener.transport = MagicMock()
343+
344+
query = r.DNSOutgoing(const._FLAGS_QR_QUERY)
345+
query.add_question(r.DNSQuestion("peer.local.", const._TYPE_AAAA, const._CLASS_IN))
346+
packet = query.packets()[0]
347+
348+
now = current_time_millis()
349+
listener._process_datagram_at_time(False, len(packet), now, packet, ("::ffff:192.0.2.1", 5353, 0, 0))
350+
listener._process_datagram_at_time(False, len(packet), now, packet, ("fe80::2", 5353, 0, 2))
351+
assert handled == [("::ffff:192.0.2.1", 5353)]
352+
353+
318354
def test_guard_against_alternating_duplicate_packets(zc: Zeroconf) -> None:
319355
"""Alternating two distinct payloads must not bypass duplicate suppression."""
320356
zc.registry.async_add(

‎tests/test_protocol.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1497,3 +1497,27 @@ def test_hinfo_second_character_string_missing_skips_record() -> None:
14971497
parsed = r.DNSIncoming(packet)
14981498
assert parsed.valid is True
14991499
assert parsed.answers() == []
1500+
1501+
1502+
def test_aaaa_scope_only_applied_to_link_local() -> None:
1503+
"""Only link-local AAAA records take the receiving scope."""
1504+
generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE)
1505+
for address in ("fe80::1", "2001:db8::1"):
1506+
generated.add_answer_at_time(
1507+
r.DNSAddress(
1508+
"host.local.",
1509+
const._TYPE_AAAA,
1510+
const._CLASS_IN,
1511+
120,
1512+
socket.inet_pton(socket.AF_INET6, address),
1513+
),
1514+
0,
1515+
)
1516+
parsed = r.DNSIncoming(generated.packets()[0], ("fe80::2", 5353), 2)
1517+
scopes = {
1518+
socket.inet_ntop(socket.AF_INET6, cast(r.DNSAddress, answer).address): cast(
1519+
r.DNSAddress, answer
1520+
).scope_id
1521+
for answer in parsed.answers()
1522+
}
1523+
assert scopes == {"fe80::1": 2, "2001:db8::1": None}

0 commit comments

Comments
 (0)