resolver

package
v0.7.17 Latest Latest
Warning

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

Go to latest
Published: May 28, 2026 License: MIT Imports: 21 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

This section is empty.

Variables

View Source
var DefaultDNS64Prefix = net.IPNet{
	IP:   net.ParseIP("64:ff9b::"),
	Mask: net.CIDRMask(96, 128),
}

DefaultDNS64Prefix is the well-known prefix for DNS64 (RFC 6052).

View Source
var RootServers = []NameServer{
	{Name: "a.root-servers.net", IPv4: "198.41.0.4", IPv6: "2001:503:ba3e::2:30"},
	{Name: "b.root-servers.net", IPv4: "170.247.170.2", IPv6: "2801:1b8:10::b"},
	{Name: "c.root-servers.net", IPv4: "192.33.4.12", IPv6: "2001:500:2::c"},
	{Name: "d.root-servers.net", IPv4: "199.7.91.13", IPv6: "2001:500:2d::d"},
	{Name: "e.root-servers.net", IPv4: "192.203.230.10", IPv6: "2001:500:a8::e"},
	{Name: "f.root-servers.net", IPv4: "192.5.5.241", IPv6: "2001:500:2f::f"},
	{Name: "g.root-servers.net", IPv4: "192.112.36.4", IPv6: "2001:500:12::d0d"},
	{Name: "h.root-servers.net", IPv4: "198.97.190.53", IPv6: "2001:500:1::53"},
	{Name: "i.root-servers.net", IPv4: "192.36.148.17", IPv6: "2001:7fe::53"},
	{Name: "j.root-servers.net", IPv4: "192.58.128.30", IPv6: "2001:503:c27::2:30"},
	{Name: "k.root-servers.net", IPv4: "193.0.14.129", IPv6: "2001:7fd::1"},
	{Name: "l.root-servers.net", IPv4: "199.7.83.42", IPv6: "2001:500:9f::42"},
	{Name: "m.root-servers.net", IPv4: "202.12.27.33", IPv6: "2001:dc3::35"},
}

RootServers contains the 13 root DNS servers with IPv4 and IPv6 addresses.

Functions

func ParseDNS64Prefix

func ParseDNS64Prefix(cidr string) (net.IPNet, error)

ParseDNS64Prefix parses a CIDR string into a net.IPNet suitable for DNS64. It returns an error if the prefix is not a valid IPv6 /96 network.

func SynthesizeAAAA

func SynthesizeAAAA(ipv4 net.IP, prefix net.IPNet) net.IP

SynthesizeAAAA embeds an IPv4 address into a DNS64 prefix to produce a synthesized IPv6 address. The prefix must be a /96 network. For the well-known prefix 64:ff9b::/96, the result is 64:ff9b::<ipv4 bytes>.

Types

type DelegationNS

type DelegationNS struct {
	Hostname string
	IPv4     string
	IPv6     string
	IPv4TTL  uint32
	IPv6TTL  uint32
}

DelegationNS represents a delegated nameserver with optional glue.

type ForwardTable

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

ForwardTable stores forward/stub zones and provides longest-suffix matching.

func NewForwardTable

func NewForwardTable(zones []ForwardZone) *ForwardTable

NewForwardTable creates a ForwardTable from the given zone list. Zone names are normalised to lowercase with no trailing dot.

func (*ForwardTable) Match

func (ft *ForwardTable) Match(qname string) *ForwardZone

Match finds the ForwardZone whose name is the longest suffix of qname. Returns nil if no zone matches.

type ForwardZone

type ForwardZone struct {
	Name   string   // zone name (lowercase, no trailing dot)
	Addrs  []string // upstream IP addresses
	IsStub bool     // false = forward (RD=1), true = stub (RD=0, iterative from addrs)
}

ForwardZone represents a configured forwarding or stub zone.

type InfraCache

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

InfraCache tracks nameserver performance (RTT, failures, lameness) to enable intelligent NS selection.

func NewInfraCache

func NewInfraCache() *InfraCache

NewInfraCache creates a new infrastructure cache.

func (*InfraCache) CleanStale

func (ic *InfraCache) CleanStale(maxIdle time.Duration)

CleanStale removes entries that have not been used for more than maxIdle.

func (*InfraCache) GetRTT

func (ic *InfraCache) GetRTT(nsIP string) time.Duration

GetRTT returns the recorded RTT for a nameserver (for testing).

func (*InfraCache) IsLame

func (ic *InfraCache) IsLame(nsIP string, zone string) bool

IsLame returns true if the nameserver is known to be lame for the given zone.

func (*InfraCache) Len

func (ic *InfraCache) Len() int

Len returns the number of entries in the infra cache (for testing).

func (*InfraCache) RecordFailure

func (ic *InfraCache) RecordFailure(nsIP string)

RecordFailure increments the fail count for a nameserver.

func (*InfraCache) RecordLame

func (ic *InfraCache) RecordLame(nsIP string, zone string)

RecordLame marks a nameserver as lame for a specific zone.

func (*InfraCache) RecordRTT

func (ic *InfraCache) RecordRTT(nsIP string, rtt time.Duration)

RecordRTT records a successful query RTT using EWMA (0.7*old + 0.3*sample).

func (*InfraCache) SortByRTT

func (ic *InfraCache) SortByRTT(entries []nsEntry) []nsEntry

SortByRTT sorts nameserver entries by their effective RTT (fastest first). Entries with failures are penalised. Unknown servers get moderate priority.

func (*InfraCache) StartCleanup

func (ic *InfraCache) StartCleanup(ctx context.Context, interval, maxIdle time.Duration)

StartCleanup runs periodic cleanup of stale infra cache entries.

type LocalRecord

type LocalRecord struct {
	Name  string
	Type  uint16
	RData []byte
	TTL   uint32
}

LocalRecord holds a single record within a local zone.

func ParseLocalRecord

func ParseLocalRecord(s string) (*LocalRecord, error)

ParseLocalRecord parses a string in "name TYPE rdata" format into a LocalRecord. Examples:

"localhost. A 127.0.0.1"
"localhost. AAAA ::1"
"example.com. CNAME www.example.com."
"example.com. TXT \"hello world\""
"example.com. MX 10 mail.example.com."
"1.0.0.127.in-addr.arpa. PTR localhost."

type LocalZone

type LocalZone struct {
	Name    string
	Type    LocalZoneType
	Records []LocalRecord
}

LocalZone represents a locally-served DNS zone.

type LocalZoneTable

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

LocalZoneTable stores local zones sorted by specificity (longest name first) for efficient longest-suffix matching.

func NewLocalZoneTable

func NewLocalZoneTable(zones []LocalZone) *LocalZoneTable

NewLocalZoneTable creates a LocalZoneTable from the given zones, sorting them so the most specific (longest name) zone comes first.

func (*LocalZoneTable) Lookup

func (t *LocalZoneTable) Lookup(name string, qtype uint16, qclass uint16) *ResolveResult

Lookup checks whether the query matches a local zone and returns the appropriate result. Returns nil if no local zone matches or if the zone type allows fall-through (e.g. LocalTransparent with no matching record).

type LocalZoneType

type LocalZoneType int

LocalZoneType controls how a local zone behaves.

const (
	// LocalStatic returns configured records or NXDOMAIN.
	LocalStatic LocalZoneType = iota
	// LocalDeny silently drops the query (returns nil response).
	LocalDeny
	// LocalRefuse returns REFUSED rcode.
	LocalRefuse
	// LocalRedirect returns configured records for any name in the zone.
	LocalRedirect
	// LocalTransparent returns configured records if found, otherwise
	// falls through to recursive resolution.
	LocalTransparent
)

func ParseLocalZoneType

func ParseLocalZoneType(s string) (LocalZoneType, bool)

ParseLocalZoneType converts a string to a LocalZoneType.

type NSInfo

type NSInfo struct {
	RTT       time.Duration // EWMA of round-trip times
	FailCount int
	LameZones map[string]struct{}
	LastUsed  time.Time
}

NSInfo holds performance data for a single nameserver IP.

type NameServer

type NameServer struct {
	Name string
	IPv4 string
	IPv6 string
}

NameServer represents a DNS nameserver with its IP addresses.

type ResolveResult

type ResolveResult struct {
	Answers      []dns.ResourceRecord
	Authority    []dns.ResourceRecord
	Additional   []dns.ResourceRecord
	RCODE        uint8
	DNSSECStatus string // "secure", "insecure", "bogus", ""
	// DNSSECReason carries a stable token classifying the cause when
	// DNSSECStatus is "bogus" or "insecure" due to a specific RFC condition.
	// The server uses it to pick a granular RFC 8914 EDE info code
	// (signature-expired → 7, dnskey-missing → 9, etc.) instead of always
	// emitting the generic EDE 6. Empty string when no specific cause is
	// recorded. See dnssec.FailureReason.
	DNSSECReason string
	// FailureReason carries a stable token classifying a NON-DNSSEC
	// failure (RCODE=SERVFAIL paths that have nothing to do with crypto).
	// Currently used to surface "no-reachable-authority" when every NS in
	// the delegation refused or was unreachable — the server maps it to
	// EDE info code 22 (RFC 8914 §4.22) so clients and operators can tell
	// "your resolver is broken" from "the auth chain itself is broken
	// upstream of us, retry won't help". Empty when no specific cause.
	FailureReason string
	// FromFailureCache marks this result as a replay from the RFC 9520
	// resolution-failure cache rather than a fresh upstream attempt.
	// The server uses the flag to attach RFC 8914 §4.13 EDE info code
	// 13 ("Cached Error") alongside whatever EDE the original failure
	// reason mapped to, so downstream operators can tell a cache replay
	// from a live fresh failure without having to track query timing.
	FromFailureCache bool
	Error            error // underlying error if resolution failed

	// UpstreamECS is the EDNS Client Subnet option that the authoritative
	// (or forward) server included in its response, if any. The SCOPE
	// PREFIX-LENGTH field (RFC 7871 §6) determines the cache key shape: a
	// scope of 0 means the answer is global and can be shared across all
	// clients; a non-zero scope means the answer is subnet-specific and
	// must be cached under the matching ECS-keyed entry. Nil when the
	// upstream did not include ECS in its response.
	UpstreamECS *dns.ECSOption
}

ResolveResult holds the outcome of a recursive resolution.

type Resolver

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

Resolver implements recursive DNS resolution.

func NewResolver

func NewResolver(c *cache.Cache, cfg ResolverConfig, m *metrics.Metrics, logger *slog.Logger) *Resolver

NewResolver creates a new recursive resolver.

func (*Resolver) DNSSECValidator added in v0.6.42

func (r *Resolver) DNSSECValidator() *dnssec.Validator

DNSSECValidator exposes the active DNSSEC validator (or nil if DNSSEC is disabled). Used by the observability layer to surface validator counters (e.g. NTAMatches) through the metrics endpoint.

func (*Resolver) EnableDNSSEC

func (r *Resolver) EnableDNSSEC(logger *slog.Logger)

EnableDNSSEC creates the DNSSEC validator, allowing the resolver to validate signed responses. Call this after PrimeRootHints.

func (*Resolver) InfraCache

func (r *Resolver) InfraCache() *InfraCache

InfraCache returns the resolver's infrastructure cache for external use.

func (*Resolver) IsReady

func (r *Resolver) IsReady() bool

IsReady returns whether the resolver has completed root hint priming.

func (*Resolver) PrimeRootHints

func (r *Resolver) PrimeRootHints() error

PrimeRootHints queries a root server for . NS to refresh root data.

func (*Resolver) QueryDNSSEC

func (r *Resolver) QueryDNSSEC(name string, qtype uint16, qclass uint16) (*dns.Message, error)

QueryDNSSEC fetches a DNS record for DNSSEC chain validation. It satisfies the dnssec.Querier interface used by the validator to fetch DNSKEY and DS records.

The previous implementation only sent a single query to a random root server, which works only for ".", root-zone DNSKEY, and TLD DS records. For any deeper zone the root server returns a referral, not the requested records, so the validator could never assemble a chain past the TLD and fell back to Indeterminate for almost every signed zone.

This implementation does proper iterative resolution from the roots, reusing the standard resolver pipeline but bypassing the resolver's own DNSSEC validator on the result. The validator is bypassed because this method is called from within the validator itself — running it again would recurse infinitely. The validator performs its own signature verification on the records this method returns, which is the only correctness guarantee that matters.

func (*Resolver) Resolve

func (r *Resolver) Resolve(name string, qtype uint16, qclass uint16) (*ResolveResult, error)

Resolve performs recursive resolution for the given query. Concurrent requests for the same name+type are coalesced. This wrapper retains the legacy signature for callers (and the broad test suite) that do not carry client subnet context.

func (*Resolver) ResolveWithECS added in v0.6.9

func (r *Resolver) ResolveWithECS(name string, qtype uint16, qclass uint16, clientECS *dns.ECSOption) (*ResolveResult, error)

ResolveWithECS performs recursive resolution while carrying the client's EDNS Client Subnet option (RFC 7871) end-to-end. clientECS is propagated to every authoritative or forward upstream query so the upstream may geo-tailor its response, and the upstream's returned scope is surfaced in ResolveResult.UpstreamECS so the caller can pick the appropriate cache key. Pass nil for clientECS to disable ECS for this resolution (equivalent to Resolve).

Note: ECS is intentionally NOT propagated through the in-flight coalescer key. A coalescer that mixes subnets would serve client A's geo-tailored answer to client B; the coalescer therefore only fires for the no-ECS path. ECS-bearing queries always run independently — correctness over dedup throughput.

func (*Resolver) ResolveWithECSAndCD added in v0.6.25

func (r *Resolver) ResolveWithECSAndCD(name string, qtype uint16, qclass uint16, clientECS *dns.ECSOption, cd bool) (*ResolveResult, error)

ResolveWithECSAndCD is the CD-bit-aware entry point used by the server when the client's query carried CD=1 (RFC 4035 §3.2.2, RFC 6840 §5.9 — "Checking Disabled"). On the iterative path CD is irrelevant (authoritative servers ignore it), but on the forward path we MUST propagate it so a downstream-validating client does not get its verdict silently rewritten by an intermediate cache that chose to validate on its own. Existing ResolveWithECS callers keep cd=false.

func (*Resolver) SetDNSSECAllowSHA1 added in v0.6.2

func (r *Resolver) SetDNSSECAllowSHA1(allow bool)

SetDNSSECAllowSHA1 toggles acceptance of weak SHA1-based DNSSEC primitives (RSASHA1 RRSIGs and SHA1 DS digests) on the active validator. Default is false, matching modern resolver behavior. No-op if DNSSEC is not enabled.

func (*Resolver) SetDNSSECNegativeTrustAnchors added in v0.6.42

func (r *Resolver) SetDNSSECNegativeTrustAnchors(entries []string) []string

SetDNSSECNegativeTrustAnchors installs the operator-configured RFC 7646 NTA list onto the active validator. Each entry is "<zone>|<RFC3339-expiry>|<reason>". Returns the list of entries that failed to parse (caller logs them); the validator still receives the entries that did parse. No-op if DNSSEC is not enabled.

func (*Resolver) SetForwardTable

func (r *Resolver) SetForwardTable(ft *ForwardTable)

SetForwardTable configures forward and stub zones for the resolver.

func (*Resolver) SetLocalZones

func (r *Resolver) SetLocalZones(lz *LocalZoneTable)

SetLocalZones configures the resolver's local zone table. Queries matching a local zone are answered immediately without recursion.

func (*Resolver) StartRootRefresh

func (r *Resolver) StartRootRefresh(ctx context.Context, interval time.Duration)

StartRootRefresh runs a background goroutine that re-primes root hints at the given interval (RFC 8109). Call this after the initial PrimeRootHints.

func (*Resolver) Trace added in v0.6.7

func (r *Resolver) Trace(
	ctx context.Context,
	name string,
	qtype uint16,
	qclass uint16,
	opts TraceOptions,
	events chan<- TraceEvent,
) (*ResolveResult, error)

Trace performs a diagnostic resolution that emits one TraceEvent per pipeline stage. The function returns when the channel reader has consumed all events or ctx is cancelled. Events are guaranteed to be ordered by Seq. The caller is expected to read events promptly — the channel is unbuffered to give back-pressure when the UI cannot keep up. Trace closes `events` before it returns.

Trace does NOT use the inflight coalescer (so each call is independent of concurrent production resolutions for the same name) and bypasses the answer cache when opts.BypassCache is set. It still reads glue and delegation cache to avoid hammering the roots on every diagnostic.

type ResolverConfig

type ResolverConfig struct {
	MaxDepth        int
	MaxCNAMEDepth   int
	UpstreamTimeout time.Duration
	UpstreamRetries int
	QMinEnabled     bool
	Caps0x20Enabled bool // DNS 0x20 case randomization (RFC 5452)
	PreferIPv4      bool
	DNSSECEnabled   bool
	// UpstreamPort overrides the DNS port for upstream queries (default "53").
	// Used for testing with mock DNS servers.
	UpstreamPort string
	// DNS64Enabled enables DNS64 synthesis (RFC 6147).
	DNS64Enabled bool
	// DNS64Prefix is the IPv6 prefix used for DNS64 synthesis (must be /96).
	DNS64Prefix net.IPNet
	// ECSEnabled enables forwarding of EDNS Client Subnet options.
	ECSEnabled bool
	// ECSMaxPrefix is the maximum source prefix length for ECS (default 24).
	ECSMaxPrefix int
	// FallbackResolvers is a list of backup recursive DNS servers (e.g. 8.8.8.8, 1.1.1.1).
	// When primary resolution returns SERVFAIL, one randomly-picked fallback is tried once.
	FallbackResolvers []string
	// UpstreamUDPBufferSize is the EDNS0 UDP payload size advertised in
	// outgoing OPT records. RFC 9018 / DNS Flag Day 2020 recommends 1232
	// to avoid IP fragmentation, which closes the off-path fragment-
	// injection cache-poisoning vector. 0 means "use the safe default".
	UpstreamUDPBufferSize int
}

ResolverConfig holds configuration for the recursive resolver.

type TraceEvent added in v0.6.7

type TraceEvent struct {
	Seq       uint64         `json:"seq"`
	Stage     string         `json:"stage"`
	Status    TraceStatus    `json:"status"`
	Time      time.Time      `json:"time"`
	ElapsedMs int64          `json:"elapsed_ms"`
	Message   string         `json:"message"`
	Details   map[string]any `json:"details,omitempty"`
}

TraceEvent is a single point of progress emitted by Trace.

Stage names are stable and form the "pipeline" the UI renders:

start, local-zones, forward-zones, cache, iterative-step,
upstream, classify, cname, dname, delegation, dnssec, fallback, finish.

Details is free-form per-stage context (e.g. NS IP, response counts).

type TraceOptions added in v0.6.7

type TraceOptions struct {
	// BypassCache makes the trace ignore the resolver cache for the queried
	// name. Glue / DNSKEY caching is unaffected so the trace stays fast.
	BypassCache bool
	// SkipDNSSEC turns off the DNSSEC validator for this trace even if the
	// resolver has it enabled. Useful when diagnosing whether a SERVFAIL is
	// upstream-related or validation-related.
	SkipDNSSEC bool
	// MaxDepth caps the number of iterative steps; 0 falls back to resolver
	// MaxDepth.
	MaxDepth int
	// MaxCNAMEDepth caps CNAME chasing; 0 falls back to resolver setting.
	MaxCNAMEDepth int
}

TraceOptions controls Trace behaviour.

type TraceStatus added in v0.6.7

type TraceStatus string

TraceStatus classifies an emitted event for UI rendering.

const (
	TraceStatusInfo  TraceStatus = "info"
	TraceStatusOK    TraceStatus = "ok"
	TraceStatusWarn  TraceStatus = "warn"
	TraceStatusError TraceStatus = "error"
)

Jump to

Keyboard shortcuts

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