Skip to content

Commit 3fab5cb

Browse files
committed
refactor: merge AAAA scope copies in place and let a scoped copy suppress later ones
DNSCache.async_get_address finds the cached AAAA for an address under any scope; the record manager takes its scope on the incoming record instead of building a new one, and stages a replaced unscoped copy with the other removes. The listener stores whether the processed copy was scoped next to its time instead of keying on (payload, scope), so a scoped copy also suppresses later copies from any sender.
1 parent 7dc6e79 commit 3fab5cb

16 files changed

Lines changed: 154 additions & 180 deletions

File tree

‎src/zeroconf/_cache.pxd‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ cdef class DNSCache:
3838

3939
cpdef void async_remove_records(self, object entries)
4040

41+
@cython.locals(store=cython.dict)
42+
cpdef DNSAddress async_get_address(self, DNSAddress entry)
43+
4144
@cython.locals(store=cython.dict)
4245
cpdef DNSRecord async_get_unique(self, DNSRecord entry)
4346

‎src/zeroconf/_cache.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,21 @@ def async_expire(self, now: _float) -> list[DNSRecord]:
131131
self.async_remove_records(expired)
132132
return expired
133133

134+
def async_get_address(self, entry: DNSAddress) -> DNSAddress | None:
135+
"""Look up the cached copy of an address record under any scope, or None."""
136+
store = self.cache.get(entry.key)
137+
if store is None:
138+
return None
139+
for record in store.values():
140+
if (
141+
isinstance(record, DNSAddress)
142+
and record.address == entry.address
143+
and record.type == entry.type
144+
and record.class_ == entry.class_
145+
):
146+
return record
147+
return None
148+
134149
def async_get_unique(self, entry: _UniqueRecordsType) -> DNSRecord | None:
135150
"""Look up the cached copy of a unique record, or None.
136151

‎src/zeroconf/_dns.pxd‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ cdef class DNSAddress(DNSRecord):
7878

7979
cdef bint _eq(self, DNSAddress other)
8080

81+
cdef void _set_scope_id(self, object scope_id)
82+
8183
cpdef write(self, DNSOutgoing out)
8284

8385

‎src/zeroconf/_dns.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,11 @@ def _fast_init(
310310
self.scope_id = scope_id
311311
self._hash = hash((self.key, type_, self.class_, address, scope_id))
312312

313+
def _set_scope_id(self, scope_id: _int | None) -> None:
314+
"""Replace the scope of a record that is not cached yet."""
315+
self.scope_id = scope_id
316+
self._hash = hash((self.key, self.type, self.class_, self.address, scope_id))
317+
313318

314319
class DNSHinfo(DNSRecord):
315320
"""HINFO record carrying the host's cpu and os strings."""

‎src/zeroconf/_handlers/record_manager.pxd‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import cython
33

44
from .._cache cimport DNSCache
5-
from .._dns cimport DNSQuestion, DNSRecord
5+
from .._dns cimport DNSAddress, DNSQuestion, DNSRecord
66
from .._protocol.incoming cimport DNSIncoming
77
from .._updates cimport RecordUpdateListener
88
from .._utils.time cimport current_time_millis
@@ -11,7 +11,6 @@ from .._record_update cimport RecordUpdate
1111
cdef unsigned int _DNS_PTR_MIN_TTL
1212
cdef cython.uint _TYPE_PTR
1313
cdef cython.uint _TYPE_AAAA
14-
cdef cython.uint _CLASS_UNIQUE
1514
cdef object _ADDRESS_RECORD_TYPES
1615
cdef bint TYPE_CHECKING
1716
cdef object _TYPE_PTR
@@ -40,8 +39,8 @@ cdef class RecordManager:
4039

4140
cpdef void async_remove_listener(self, RecordUpdateListener listener)
4241

43-
@cython.locals(cached=DNSRecord)
44-
cdef DNSRecord _async_merge_scope_variant(self, DNSRecord record)
42+
@cython.locals(cached=DNSAddress)
43+
cdef DNSAddress _async_merge_address(self, DNSAddress record, object removes)
4544

4645
@cython.locals(question=DNSQuestion, record=DNSRecord)
4746
cdef void _async_update_matching_records(self, RecordUpdateListener listener, cython.list questions)

‎src/zeroconf/_handlers/record_manager.py‎

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616
from .._record_update import RecordUpdate
1717
from .._updates import RecordUpdateListener
1818
from .._utils.time import current_time_millis
19-
from ..const import _ADDRESS_RECORD_TYPES, _CLASS_UNIQUE, _DNS_PTR_MIN_TTL, _TYPE_AAAA, _TYPE_PTR
19+
from ..const import _ADDRESS_RECORD_TYPES, _DNS_PTR_MIN_TTL, _TYPE_AAAA, _TYPE_PTR
2020

2121
if TYPE_CHECKING:
2222
from .._core import Zeroconf
2323

2424
_float = float
2525
_RecordUpdate = RecordUpdate
26+
_DNSRecordSet = set[DNSRecord]
2627
_DNSQuestion = DNSQuestion
2728

2829

@@ -119,8 +120,9 @@ def async_updates_from_response(self, msg: DNSIncoming) -> None:
119120

120121
maybe_entry = cache.async_get_unique(record)
121122
if maybe_entry is None and record_type == _TYPE_AAAA:
122-
record = self._async_merge_scope_variant(record) # noqa: PLW2901
123-
maybe_entry = cache.async_get_unique(record)
123+
if TYPE_CHECKING:
124+
assert isinstance(record, DNSAddress)
125+
maybe_entry = self._async_merge_address(record, removes)
124126

125127
if not record.is_expired(now):
126128
if record_type in _ADDRESS_RECORD_TYPES:
@@ -171,33 +173,16 @@ def async_updates_from_response(self, msg: DNSIncoming) -> None:
171173
if updates:
172174
self.async_updates_complete(new)
173175

174-
def _async_merge_scope_variant(self, record: DNSRecord) -> DNSAddress:
175-
"""Return the AAAA record to cache, merged with any cached copy under another scope.
176-
177-
The cache keeps one AAAA per address since the scope is not on the
178-
wire: a scoped copy replaces an unscoped one, otherwise the cached
179-
scope is kept.
180-
"""
181-
if TYPE_CHECKING:
182-
record = cast(DNSAddress, record)
183-
for cached in self.cache.async_all_by_details(record.name, _TYPE_AAAA, record.class_):
184-
if TYPE_CHECKING:
185-
cached = cast(DNSAddress, cached)
186-
if cached.address != record.address:
187-
continue
188-
if record.scope_id and not cached.scope_id:
189-
self.cache.async_remove_records((cached,))
190-
return record
191-
return DNSAddress(
192-
record.name,
193-
_TYPE_AAAA,
194-
(record.class_ | _CLASS_UNIQUE) if record.unique else record.class_,
195-
record.ttl,
196-
record.address,
197-
cached.scope_id,
198-
record.created,
199-
)
200-
return record
176+
def _async_merge_address(self, record: DNSAddress, removes: _DNSRecordSet) -> DNSAddress | None:
177+
"""Return the cached copy of the AAAA, keeping one per address and preferring a scoped one."""
178+
cached = self.cache.async_get_address(record)
179+
if cached is None:
180+
return None
181+
if record.scope_id and not cached.scope_id:
182+
removes.add(cached)
183+
return None
184+
record._set_scope_id(cached.scope_id)
185+
return cached
201186

202187
def _async_update_matching_records(
203188
self, listener: RecordUpdateListener, questions: list[_DNSQuestion]

‎src/zeroconf/_listener.pxd‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ cdef cython.uint _DUPLICATE_PACKET_SUPPRESSION_INTERVAL
1717
cdef cython.uint _RECENT_PACKETS_MAX
1818
cdef cython.uint _MAX_DEFERRED_ADDRS
1919
cdef cython.uint _MAX_DEFERRED_PER_ADDR
20+
cdef tuple _NOT_SEEN
2021

2122

2223
cdef class AsyncListener:
@@ -27,7 +28,7 @@ cdef class AsyncListener:
2728
cdef QueryHandler _query_handler
2829
cdef public cython.bytes data
2930
cdef public double last_time
30-
cdef public cython.uint last_sender_scope
31+
cdef bint _last_scoped
3132
cdef public DNSIncoming last_message
3233
cdef public object transport
3334
cdef public object sock_description
@@ -39,7 +40,7 @@ cdef class AsyncListener:
3940
@cython.locals(now=double, debug=cython.bint)
4041
cpdef datagram_received(self, cython.bytes bytes, cython.tuple addrs)
4142

42-
@cython.locals(msg=DNSIncoming, recent_time=double, sender_scope=cython.uint, key=object)
43+
@cython.locals(msg=DNSIncoming, recent=tuple, recent_time=double, scoped=bint)
4344
cpdef _process_datagram_at_time(self, bint debug, cython.uint data_len, double now, bytes data, cython.tuple addrs)
4445

4546
cdef _cancel_any_timers_for_addr(self, object addr)

‎src/zeroconf/_listener.py‎

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838

3939
DEBUG_ENABLED = partial(log.isEnabledFor, logging.DEBUG)
4040

41+
_NOT_SEEN = (-1e30, True)
42+
4143

4244
class AsyncListener:
4345
"""Asyncio datagram protocol that receives mDNS packets and feeds them
@@ -46,14 +48,14 @@ class AsyncListener:
4648
__slots__ = (
4749
"_deferred",
4850
"_deferred_deadlines",
51+
"_last_scoped",
4952
"_query_handler",
5053
"_recent_packets",
5154
"_record_manager",
5255
"_registry",
5356
"_timers",
5457
"data",
5558
"last_message",
56-
"last_sender_scope",
5759
"last_time",
5860
"sock_description",
5961
"transport",
@@ -68,7 +70,7 @@ def __init__(self, zc: Zeroconf) -> None:
6870
self.data: bytes | None = None
6971
self.last_time: float = 0
7072
self.last_message: DNSIncoming | None = None
71-
self.last_sender_scope = 0
73+
self._last_scoped = False
7274
self.transport: _WrappedTransport | None = None
7375
self.sock_description: str | None = None
7476
self._deferred: dict[str, list[DNSIncoming]] = {}
@@ -78,13 +80,10 @@ def __init__(self, zc: Zeroconf) -> None:
7880
# flood cannot defeat single-slot dedup; relies on dict insertion
7981
# order so the oldest entry is evicted first. Only payloads
8082
# without a QU question are cached so unicast replies still go
81-
# out on every receipt.
82-
#
83-
# A dual-stack socket receives a responder's IPv4 and IPv6 copies
84-
# of the same message (RFC 6762 section 20), and only a copy from
85-
# a link-local sender gives its link-local AAAA records a scope,
86-
# so a copy from a scoped sender is keyed with its scope.
87-
self._recent_packets: dict[bytes | tuple[bytes, int], float] = {}
83+
# out on every receipt. Each entry records whether the copy came
84+
# from a scoped sender: only that copy scopes link-local AAAA
85+
# records, so it is not suppressed by an unscoped one.
86+
self._recent_packets: dict[bytes, tuple[float, bool]] = {}
8887
super().__init__()
8988

9089
def cancel_pending_timers(self) -> None:
@@ -236,11 +235,11 @@ def _process_datagram_at_time(
236235
addrs: tuple[str, int] | tuple[str, int, int, int],
237236
) -> None:
238237
# 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
238+
# bit of header byte 2).
239+
scoped = len(addrs) == 4 and addrs[3] != 0 and data_len > 2 and (data[2] & 0x80) != 0
241240
if (
242241
self.data == data
243-
and self.last_sender_scope == sender_scope
242+
and (self._last_scoped or not scoped)
244243
and (now - _DUPLICATE_PACKET_SUPPRESSION_INTERVAL) < self.last_time
245244
and self.last_message is not None
246245
and not self.last_message.has_qu_question()
@@ -257,17 +256,17 @@ def _process_datagram_at_time(
257256
)
258257
return
259258

260-
# `get(data, -1e30)` keeps the suppression compare a single C
259+
# `get(data, _NOT_SEEN)` keeps the suppression compare a single C
261260
# double compare; the sentinel is far below any real `now -
262261
# _DUPLICATE_PACKET_SUPPRESSION_INTERVAL` so a cache miss never
263262
# triggers the branch even when `now` is small (time.monotonic
264263
# is allowed to start near zero, leaving `now - INTERVAL`
265264
# negative for the first ~1s after boot). Only non-QU payloads
266265
# are cached, so any hit here is safe to suppress without re-
267266
# checking has_qu_question.
268-
key = (data, sender_scope) if sender_scope else data
269-
recent_time = self._recent_packets.get(key, -1e30)
270-
if (now - _DUPLICATE_PACKET_SUPPRESSION_INTERVAL) < recent_time:
267+
recent = self._recent_packets.get(data, _NOT_SEEN)
268+
recent_time = recent[0]
269+
if (now - _DUPLICATE_PACKET_SUPPRESSION_INTERVAL) < recent_time and (recent[1] or not scoped):
271270
# No timestamp refresh on hit so the suppression window
272271
# ends at first-observation + interval; one parse-and-
273272
# dispatch fires per payload per interval, capping the
@@ -303,16 +302,16 @@ def _process_datagram_at_time(
303302
self.data = data
304303
self.last_time = now
305304
self.last_message = msg
306-
self.last_sender_scope = sender_scope
305+
self._last_scoped = scoped
307306
if not msg.has_qu_question():
308307
# Refresh LRU position when an entry exists but the
309308
# suppression window has expired; otherwise evict the oldest
310309
# entry once the window is full.
311-
if key in self._recent_packets:
312-
del self._recent_packets[key]
310+
if recent is not _NOT_SEEN:
311+
del self._recent_packets[data]
313312
elif len(self._recent_packets) >= _RECENT_PACKETS_MAX:
314313
del self._recent_packets[next(iter(self._recent_packets))]
315-
self._recent_packets[key] = now
314+
self._recent_packets[data] = (now, scoped)
316315
if msg.valid is True:
317316
if debug:
318317
log.debug(

‎src/zeroconf/_protocol/incoming.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -530,20 +530,16 @@ def _read_record(
530530
)
531531
return hinfo_rec
532532
if type_ == _TYPE_AAAA:
533-
offset = self.offset
534533
address = self._read_string(16)
535-
buf = self._buf
536534
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.
535+
# Zone indexes only apply to link-local fe80::/10 (RFC 4007 section 6).
540536
address_rec._fast_init(
541537
domain,
542538
type_,
543539
class_,
544540
ttl,
545541
address,
546-
self.scope_id if buf[offset] == 0xFE and (buf[offset + 1] & 0xC0) == 0x80 else None,
542+
self.scope_id if address[0] == 0xFE and (address[1] & 0xC0) == 0x80 else None,
547543
self.now,
548544
)
549545
return address_rec

‎src/zeroconf/_services/info.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -783,9 +783,9 @@ def _get_ip_addresses_from_cache_lifo(
783783
ip_addr = get_ip_address_object_from_record(record)
784784
if ip_addr is None:
785785
continue
786-
# The cache keeps scoped and unscoped link-local AAAA
787-
# records as separate entries because DNSAddress equality
788-
# includes scope_id. Collapse them here so each address
786+
# Records added to the cache directly, not through the
787+
# record manager, can hold scoped and unscoped copies of a
788+
# link-local AAAA. Collapse them here so each address
789789
# appears once; the scoped variant wins so callers of
790790
# parsed_scoped_addresses() get a %<interface_index>-
791791
# qualified link-local address when one was observed.

0 commit comments

Comments
 (0)