Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/zeroconf/_history.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ from ._dns cimport DNSQuestion


cdef cython.double _DUPLICATE_QUESTION_INTERVAL
cdef unsigned int _MAX_QUESTION_HISTORY_ENTRIES

cdef class QuestionHistory:

cdef cython.dict _history
cdef public cython.dict _history

cpdef void add_question_at_time(self, DNSQuestion question, double now, cython.set known_answers)

@cython.locals(oldest=DNSQuestion, oldest_entry=cython.tuple, oldest_than=double)
cdef void _evict_to_make_room(self, double now)

@cython.locals(than=double, previous_question=cython.tuple, previous_known_answers=cython.set)
cpdef bint suppresses(self, DNSQuestion question, double now, cython.set known_answers)

Expand Down
20 changes: 19 additions & 1 deletion src/zeroconf/_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from __future__ import annotations

from ._dns import DNSQuestion, DNSRecord
from .const import _DUPLICATE_QUESTION_INTERVAL
from .const import _DUPLICATE_QUESTION_INTERVAL, _MAX_QUESTION_HISTORY_ENTRIES

# The QuestionHistory is used to implement Duplicate Question Suppression
# https://datatracker.ietf.org/doc/html/rfc6762#section-7.3
Expand All @@ -40,6 +40,8 @@ def __init__(self) -> None:

def add_question_at_time(self, question: DNSQuestion, now: _float, known_answers: set[DNSRecord]) -> None:
"""Remember a question with known answers."""
if question not in self._history and len(self._history) >= _MAX_QUESTION_HISTORY_ENTRIES:
Comment thread
bdraco marked this conversation as resolved.
self._evict_to_make_room(now)
self._history[question] = (now, known_answers)

def suppresses(self, question: DNSQuestion, now: _float, known_answers: set[DNSRecord]) -> bool:
Expand Down Expand Up @@ -75,3 +77,19 @@ def async_expire(self, now: _float) -> None:
def clear(self) -> None:
"""Clear the history."""
self._history.clear()

def _evict_to_make_room(self, now: _float) -> None:
"""Drop expired or oldest entries when the history is at cap.

Peeks at the oldest insertion (dict is ordered) — only runs the
full O(n) async_expire sweep if it could actually reclaim
something, else a sustained flood at cap turns each insert into
a wasted scan. Falls back to oldest-first eviction.
"""
oldest = next(iter(self._history))
oldest_entry = self._history[oldest]
oldest_than = oldest_entry[0]
if now - oldest_than > _DUPLICATE_QUESTION_INTERVAL:
self.async_expire(now)
while len(self._history) >= _MAX_QUESTION_HISTORY_ENTRIES:
del self._history[next(iter(self._history))]
6 changes: 6 additions & 0 deletions src/zeroconf/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@
# to retain by multicasting many unique-name records.
_MAX_CACHE_RECORDS = 10000

# Upper bound on the number of entries QuestionHistory will hold between
# the periodic 10s cache-cleanup ticks. Bounds the memory a malicious LAN
# peer can force the duplicate-question-suppression history to retain by
# flooding distinct questions (RFC 6762 §7.3, defense-in-depth).
_MAX_QUESTION_HISTORY_ENTRIES = 10000

_DNS_PACKET_HEADER_LEN = 12

_MAX_MSG_TYPICAL = 1460 # unused
Expand Down
55 changes: 55 additions & 0 deletions tests/test_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,58 @@ def test_question_expire():

# Verify the question not longer suppressed since the cache has expired
assert not history.suppresses(question, now, other_known_answers)


def test_question_history_bounded():
"""History keeps a hard cap so a LAN flood cannot grow it without bound."""
history = QuestionHistory()
now = r.current_time_millis()
answers: set[r.DNSRecord] = set()

cap = const._MAX_QUESTION_HISTORY_ENTRIES
for i in range(cap + 500):
q = r.DNSQuestion(f"_svc{i}._tcp.local.", const._TYPE_PTR, const._CLASS_IN)
history.add_question_at_time(q, now, answers)

assert len(history._history) <= cap


def test_question_history_evicts_oldest_first():
"""When at cap, the oldest insertion is dropped first."""
history = QuestionHistory()
now = r.current_time_millis()
answers: set[r.DNSRecord] = set()

cap = const._MAX_QUESTION_HISTORY_ENTRIES
first = r.DNSQuestion("_first._tcp.local.", const._TYPE_PTR, const._CLASS_IN)
history.add_question_at_time(first, now, answers)

# Add `cap` more fresh, non-expired entries — one past the cap — so the
# final insertion forces oldest-first eviction of `first`.
for i in range(cap):
q = r.DNSQuestion(f"_svc{i}._tcp.local.", const._TYPE_PTR, const._CLASS_IN)
history.add_question_at_time(q, now, answers)

assert first not in history._history
assert len(history._history) <= cap


def test_question_history_opportunistic_expire():
"""Adding past the cap first drops expired entries before evicting fresh ones."""
history = QuestionHistory()
old = r.current_time_millis()
answers: set[r.DNSRecord] = set()

cap = const._MAX_QUESTION_HISTORY_ENTRIES
for i in range(cap):
q = r.DNSQuestion(f"_stale{i}._tcp.local.", const._TYPE_PTR, const._CLASS_IN)
history.add_question_at_time(q, old, answers)

# All prior entries are now stale (>999ms old). Adding one more should
# trigger opportunistic expiry rather than evicting only the oldest one.
fresh_now = old + const._DUPLICATE_QUESTION_INTERVAL + 1
fresh = r.DNSQuestion("_fresh._tcp.local.", const._TYPE_PTR, const._CLASS_IN)
history.add_question_at_time(fresh, fresh_now, answers)

assert fresh in history._history
assert len(history._history) == 1
Loading