cache

package
v0.8.49 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DefaultFailureTTL uint32 = 5

DefaultFailureTTL is the typical RFC 9520 §3 "small number of seconds" negative-failure window: 5 s by default, balancing fast recovery on transient flakes against worthwhile suppression of repeat work.

View Source
const MaxFailureTTL uint32 = 30

MaxFailureTTL is the RFC 9520 §4 ceiling on resolution-failure caching. "DNS resolvers SHOULD cache resolution failures … TTL … MUST NOT exceed 5 minutes." We pick a tighter 30-second cap so transient outages clear quickly while still protecting upstream from the per-query stampede.

View Source
const MaxNSECZones = 50_000

MaxNSECZones caps the number of distinct DNSSEC-signed zones the aggressive-use NSEC index will track at once. Each entry holds the SOA + NSEC + RRSIG bytes needed to reconstruct a verifiable synth response, so per-entry memory is non-trivial (a few KB). An attacker who controls many DNSSEC-signed sibling zones — easy to arrange by registering siblings under a TLD they control, or by chaining delegations through their auth — can flood the resolver with Secure NXDOMAIN responses whose SOAs name distinct zones, growing `byZone` without bound. The per-zone interval list is already capped (256), but the zone count was not. 50k tracked zones is far above any realistic legitimate workload (the resolver would have to actively query into 50k distinct signed zones to benefit from any one of them) and small enough that the worst- case footprint stays bounded to a few hundred MB. When the cap is reached, the OLDEST-registeredAt zone (the one whose newest entry's registeredAt is oldest) is evicted to make room.

View Source
const MinSweepInterval = 10 * time.Millisecond

MinSweepInterval is the floor StartSweeper applies to its interval argument. time.NewTicker(0) panics, so a YAML cache.sweep_interval: 0 (or a /api/config/raw PUT that planted a zero value) would crash the resolver at boot. 10 ms is just above the panic threshold and well below any legitimate operator setting (the default is 60 s); kept low to avoid disturbing existing fast-tick tests that pass sub-second intervals deliberately.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache is a sharded in-memory DNS cache with TTL-based expiration.

func NewCache

func NewCache(maxEntries int, minTTL, maxTTL, negMaxTTL uint32, m *metrics.Metrics) *Cache

NewCache creates a new sharded DNS cache.

func NewCacheWithStale

func NewCacheWithStale(maxEntries int, minTTL, maxTTL, negMaxTTL uint32, serveStale bool, staleTTL uint32, m *metrics.Metrics) *Cache

NewCacheWithStale creates a cache with optional serve-stale support (RFC 8767).

func (*Cache) Delete

func (c *Cache) Delete(name string, qtype uint16, class uint16) bool

Delete removes a specific entry from the cache. Returns true if the entry was found and deleted.

func (*Cache) DetailedStats

func (c *Cache) DetailedStats() CacheStats

DetailedStats returns detailed cache statistics including positive/negative breakdowns.

func (*Cache) Flush

func (c *Cache) Flush()

Flush clears all cache entries.

func (*Cache) Get

func (c *Cache) Get(name string, qtype uint16, class uint16) (*Entry, bool)

Get retrieves an entry from the cache with TTL decay.

func (*Cache) GetStale

func (c *Cache) GetStale(name string, qtype uint16, class uint16) (*Entry, bool)

GetStale retrieves an expired entry from the cache for serve-stale (RFC 8767). Returns the entry with staleTTL if serve-stale is enabled and the entry exists but is expired.

The returned entry's DNSSECStatus is cleared: when records are served past their TTL the covering RRSIGs may also be past their signature-inception/ expiration window, so we cannot honestly carry over the original "secure" verdict. Downstream validators that care will re-verify; the AD bit on a stale serve would be a lie.

func (*Cache) GetWithECS

func (c *Cache) GetWithECS(name string, qtype uint16, class uint16, ecsPrefix string) (*Entry, bool)

GetWithECS retrieves a cache entry using an ECS-aware key. If ecsPrefix is empty, it behaves like Get.

func (*Cache) Lookup

func (c *Cache) Lookup(name string, qtype uint16, class uint16) (*Entry, bool)

Lookup retrieves an entry from the cache without deleting expired entries. Unlike Get, this is a read-only operation suitable for inspection.

func (*Cache) LookupAll

func (c *Cache) LookupAll(name string, class uint16) []*Entry

LookupAll returns all cached entries for the given name (across all types).

func (*Cache) LookupNSEC3Covers added in v0.6.21

func (c *Cache) LookupNSEC3Covers(qname string, qclass uint16) (*Entry, bool)

LookupNSEC3Covers checks whether any cached NSEC3 interval proves qname nonexistent under the interval's hash scheme. Returns either a synthesized NXDOMAIN (interval coverage, RFC 8198 §5.2) or NODATA (owner-hash match with qtype absent from the bitmap, RFC 8198 §5.4), carrying the original SOA + NSEC3 + RRSIG so a downstream validator can confirm the AD verdict.

qtype=0 disables the NODATA path (covers callers that only want NXDOMAIN). LookupNSEC3CoversTyped is the qtype-aware variant.

func (*Cache) LookupNSEC3CoversTyped added in v0.6.23

func (c *Cache) LookupNSEC3CoversTyped(qname string, qtype uint16, qclass uint16) (*Entry, bool)

LookupNSEC3CoversTyped is the qtype-aware variant that enables the RFC 8198 §5.4 NSEC3 NODATA aggressive-use path.

func (*Cache) LookupNSECCovers added in v0.6.18

func (c *Cache) LookupNSECCovers(qname string, qclass uint16) (*Entry, bool)

LookupNSECCovers checks whether any cached Secure NSEC interval proves qname nonexistent. Returns a synthesized Entry whose Authority carries the original SOA + NSEC + RRSIG so downstream validators can confirm the AD verdict, and DNSSECStatus="secure" so the server sets AD on the response. Returns ok=false when no covering interval is cached.

The lookup walks parent labels of qname to find every plausibly- authoritative zone for the name and consults that zone's interval list. Within each zone the search is linear; per-zone interval count is bounded by RegisterNSECInterval.

This function returns either:

  • NXDOMAIN entry: a cached NSEC interval STRICTLY covers qname (the classic RFC 8198 §5.2 use case);
  • NODATA entry (RFC 8198 §5.4 + qtype != 0): a cached NSEC owner EXACTLY matches qname and qtype is absent from its type bitmap.

The qtype is honoured only on the NODATA path; pass 0 to skip the NODATA check and only consider interval-coverage NXDOMAIN.

func (*Cache) LookupNSECCoversTyped added in v0.6.23

func (c *Cache) LookupNSECCoversTyped(qname string, qtype uint16, qclass uint16) (*Entry, bool)

LookupNSECCoversTyped is the qtype-aware variant for RFC 8198 §5.4 NSEC NODATA aggressive use. Pass the real qtype so a cached owner-match NSEC can prove "qname exists but not for this type."

func (*Cache) NegativeEntries

func (c *Cache) NegativeEntries(limit int) []NegativeEntryInfo

NegativeEntries returns up to limit negative cache entries across all shards.

func (*Cache) RegisterNSEC3Interval added in v0.6.21

func (c *Cache) RegisterNSEC3Interval(zone string, negTTL uint32, authority []dns.ResourceRecord)

RegisterNSEC3Interval is the NSEC3 counterpart of RegisterNSECInterval. The caller MUST have validated the response as Secure; this method does not re-validate. Opt-out NSEC3s are dropped silently because their denial guarantees do not extend to aggressive synthesis.

func (*Cache) RegisterNSECInterval added in v0.6.18

func (c *Cache) RegisterNSECInterval(zone string, negTTL uint32, authority []dns.ResourceRecord)

RegisterNSECInterval stores the NSEC intervals from a Secure NXDOMAIN response so future queries that fall in the same gap can be answered from cache. The caller MUST have verified the response as Secure; this method does not re-validate. negTTL is the negative TTL the caller already extracted (min(SOA TTL, SOA Minimum) per RFC 2308). authority is the full authority section, copied here for later replay.

func (*Cache) SetHardenBelowNX

func (c *Cache) SetHardenBelowNX(enabled bool)

SetHardenBelowNX enables or disables RFC 8020 harden-below-nxdomain.

func (*Cache) SetPrefetchEnabled

func (c *Cache) SetPrefetchEnabled(enabled bool)

SetPrefetchEnabled enables or disables proactive cache prefetching.

func (*Cache) SetPrefetchFunc

func (c *Cache) SetPrefetchFunc(fn func(name string, qtype, qclass uint16))

SetPrefetchFunc sets the callback used to re-resolve entries nearing expiry.

func (*Cache) SetStaleMaxAge added in v0.6.18

func (c *Cache) SetStaleMaxAge(seconds uint32)

SetStaleMaxAge sets the upper bound (in seconds) on how far past expiry a stale entry may be served (RFC 8767 §3.3). Setting 0 disables the cap, restoring unbounded stale-serve.

func (*Cache) StartSweeper

func (c *Cache) StartSweeper(ctx context.Context, interval time.Duration)

StartSweeper runs a background goroutine that periodically evicts expired entries. Floors interval at MinSweepInterval so a bad config never crashes the sweeper.

func (*Cache) Stats

func (c *Cache) Stats() CacheStats

Stats returns current cache statistics.

func (*Cache) Store

func (c *Cache) Store(name string, qtype uint16, class uint16, answers []dns.ResourceRecord, authority []dns.ResourceRecord)

Store caches a positive DNS result.

func (*Cache) StoreFailure added in v0.6.11

func (c *Cache) StoreFailure(name string, qtype uint16, class uint16, ttl uint32)

StoreFailure records a resolution-failure (SERVFAIL) negative entry for the (name, qtype, class) triple, with TTL clamped to [1, MaxFailureTTL]. RFC 9520 §3: "Recursive servers MUST cache resolution failures." Without this cap, a client retrying a broken name every 100 ms re-runs the full iterative chain every time — a small loop can swamp an upstream auth server with thousands of QPS. The entry stores no records and emits RCODE=SERVFAIL on cache hit, just like the upstream would have.

func (*Cache) StoreGlue added in v0.8.36

func (c *Cache) StoreGlue(name string, qtype uint16, class uint16, answers []dns.ResourceRecord)

StoreGlue caches a referral glue A/AAAA RRset for nameserver address lookups. The entry is flagged Glue so client-facing paths treat it as a miss, and it never replaces a live authoritative entry (RFC 2181 §5.4.1).

func (*Cache) StoreNegative

func (c *Cache) StoreNegative(name string, qtype uint16, class uint16, negType NegativeType, rcode uint8, authority []dns.ResourceRecord)

StoreNegative caches a negative DNS result (NXDOMAIN/NODATA) without a recorded DNSSEC verdict. Prefer StoreNegativeWithStatus so a validated (Secure) denial keeps its AD bit when served from cache.

func (*Cache) StoreNegativeWithStatus added in v0.8.32

func (c *Cache) StoreNegativeWithStatus(name string, qtype uint16, class uint16, negType NegativeType, rcode uint8, authority []dns.ResourceRecord, dnssecStatus string)

StoreNegativeWithStatus caches a negative DNS result together with the validator's DNSSEC verdict ("secure"/"insecure"/"bogus"/""). Recording the verdict is what lets a cached NXDOMAIN/NODATA be re-served with the AD bit set (buildCacheResponse gates AD on entry.DNSSECStatus == "secure"). Without it, every cached negative for a signed zone silently downgrades to AD=0 on the second and subsequent hits — a discrepancy from every mainstream validating resolver.

NXDOMAIN applies to the entire name (RFC 2308 §3) so it is stored with qtype=0 as a sentinel. NODATA is type-specific.

func (*Cache) StoreWithECS

func (c *Cache) StoreWithECS(name string, qtype uint16, class uint16, ecsPrefix string, answers []dns.ResourceRecord, authority []dns.ResourceRecord)

StoreWithECS caches a positive DNS result with an ECS prefix key. If ecsPrefix is empty, it behaves like Store.

func (*Cache) StoreWithECSStatus added in v0.6.9

func (c *Cache) StoreWithECSStatus(
	name string, qtype uint16, class uint16,
	ecsPrefix string, ecsScope uint8,
	answers []dns.ResourceRecord, authority []dns.ResourceRecord,
	dnssecStatus string,
)

StoreWithECSStatus caches a positive DNS result keyed by ECS source prefix along with the DNSSEC validator's verdict and the authoritative server's returned ECS SCOPE PREFIX-LENGTH (echoed to the client per RFC 7871 §7.2.1). ecsPrefix == "" routes to StoreWithStatus (global, all clients share).

func (*Cache) StoreWithStatus added in v0.6.3

func (c *Cache) StoreWithStatus(name string, qtype uint16, class uint16, answers []dns.ResourceRecord, authority []dns.ResourceRecord, dnssecStatus string)

StoreWithStatus caches a positive DNS result together with the validator's verdict ("secure", "insecure", "bogus", or ""). The status is consumed by the server to set the AD bit on cache-served responses without re-running DNSSEC validation per lookup.

type CacheStats

type CacheStats struct {
	Entries         int
	PositiveEntries int
	NegativeEntries int
}

CacheStats holds cache statistics.

type Entry

type Entry struct {
	Records    []dns.ResourceRecord
	Authority  []dns.ResourceRecord
	InsertedAt time.Time
	OrigTTL    uint32
	Negative   bool
	NegType    NegativeType
	SOA        *dns.ResourceRecord
	RCODE      uint8

	// DNSSECStatus records the validator's verdict on the cached records:
	// "secure", "insecure", "bogus", or "" (unknown). Used by the server
	// to set the AD bit on responses served from cache without re-running
	// validation.
	DNSSECStatus string

	// ECSScope is the SCOPE PREFIX-LENGTH the authoritative server
	// returned in its ECS option (RFC 7871 §6). Echoed back to the client
	// in the response OPT when the client itself sent ECS. Zero means the
	// answer is not subnet-scoped (global cache entry shared across all
	// clients).
	ECSScope uint8

	// Synthesized marks entries that the resolver itself constructed from
	// cached DNSSEC proofs (NSEC/NSEC3 aggressive negative caching, RFC 8198)
	// rather than being fetched from an authoritative server as-is. The server
	// uses this flag to attach RFC 8914 §4.29 EDE code 29 ("Synthesized") so
	// downstream clients know the answer was locally materialised from
	// authenticated denial records, not a direct authoritative response.
	Synthesized bool

	// Glue marks an A/AAAA RRset copied from a referral's additional
	// section. RFC 2181 §5.4.1 ranks glue below authoritative data: the
	// resolver may use it to reach a nameserver, but it is unvalidated
	// (never covered by an RRSIG) and must not be served as an answer.
	Glue bool
	// contains filtered or unexported fields
}

Entry represents a cached DNS result.

func (*Entry) Expired

func (e *Entry) Expired() bool

Expired returns true if the entry has expired.

func (*Entry) RemainingTTL

func (e *Entry) RemainingTTL() uint32

RemainingTTL returns the remaining TTL in seconds.

func (*Entry) WithDecayedTTL

func (e *Entry) WithDecayedTTL(remaining uint32) *Entry

WithDecayedTTL returns a deep copy of the entry with TTL adjusted.

type NegativeEntryInfo

type NegativeEntryInfo struct {
	Name         string               `json:"name"`
	QType        string               `json:"qtype"`
	NegType      string               `json:"neg_type"`
	RCODE        string               `json:"rcode"`
	RemainingTTL uint32               `json:"remaining_ttl"`
	Authority    []ResourceRecordInfo `json:"authority"`
}

NegativeEntryInfo holds information about a negative cache entry.

type NegativeType

type NegativeType uint8

NegativeType indicates the type of negative cache entry.

const (
	NegNone     NegativeType = 0
	NegNXDomain NegativeType = 1
	NegNoData   NegativeType = 2
	// NegServFail is the short-lived "resolution failure" cache entry
	// introduced for RFC 9520 §3. When the recursive resolver cannot
	// produce an answer (upstream timeout, all NS unreachable, broken
	// delegation, signed-zone bogus), we cache the failure for a few
	// seconds so an aggressive client cannot amplify upstream load by
	// retrying the same expensive iterative chain on every miss. TTL
	// is capped at 30 s per the RFC's recommendation.
	NegServFail NegativeType = 3
)

type ResourceRecordInfo

type ResourceRecordInfo struct {
	Name  string `json:"name"`
	Type  string `json:"type"`
	TTL   uint32 `json:"ttl"`
	RData string `json:"rdata"`
}

ResourceRecordInfo holds a human-readable representation of a DNS resource record.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL