dns

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 20 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

Overview

Package dns provides an embedded DNS server for Gopherstack that resolves synthetic AWS-style hostnames (e.g. my-cluster.abc.us-east-1.cache.amazonaws.com) back to a configured IP address (typically 127.0.0.1). It also supports per-record values for A, CNAME, and AAAA records via RegisterRecord.

Usage:

srv, err := dns.New(dns.Config{ListenAddr: ":10053", ResolveIP: "127.0.0.1"})
srv.Register("my-cluster.abc.us-east-1.cache.amazonaws.com")
srv.RegisterRecord("www.example.com", "A", []string{"1.2.3.4"})
if err := srv.Start(ctx); err != nil { ... }
defer srv.Stop()

Index

Constants

View Source
const DefaultListenAddr = ":10053"

DefaultListenAddr is the default UDP/TCP address the DNS server binds to.

View Source
const DefaultReadTimeout = 5 * time.Second

DefaultReadTimeout is the read timeout for the underlying DNS server.

View Source
const DefaultResolveIP = "127.0.0.1"

DefaultResolveIP is the IP address returned for every registered hostname.

View Source
const DefaultWriteTimeout = 5 * time.Second

DefaultWriteTimeout is the write timeout for the underlying DNS server.

Variables

View Source
var ErrBadTransfer = errors.New("dns: malformed zone transfer")

ErrBadTransfer is returned when an AXFR stream is malformed.

View Source
var ErrEphemeralBind = errors.New("dns: no ephemeral port free on both tcp and udp")

ErrEphemeralBind is returned when no port free on both TCP and UDP was found.

View Source
var ErrIPv4Required = errors.New("resolve IP must be an IPv4 address")

ErrIPv4Required is returned when the configured resolve IP is not an IPv4 address.

View Source
var ErrInvalidResolveIP = errors.New("invalid resolve IP")

ErrInvalidResolveIP is returned when the configured resolve IP cannot be parsed.

View Source
var ErrNotifyRefused = errors.New("dns: notify refused")

ErrNotifyRefused is returned when a NOTIFY is answered with an error rcode.

View Source
var ErrTransferRefused = errors.New("dns: zone transfer refused")

ErrTransferRefused is returned when the primary answers an AXFR request with an error rcode.

View Source
var ErrUnexpectedAddr = errors.New("dns: unexpected listener address type")

ErrUnexpectedAddr is returned when a listener reports a non-TCP address.

View Source
var ErrUnknownTSIGAlgorithm = errors.New("dns: unknown TSIG algorithm")

ErrUnknownTSIGAlgorithm is returned for an algorithm name that is not a TSIG HMAC algorithm.

View Source
var ErrWeakTSIGAlgorithm = errors.New(
	"dns: TSIG algorithm is not supported (only hmac-sha224, -sha256, -sha384 and -sha512)",
)

ErrWeakTSIGAlgorithm is returned for hmac-sha1 and hmac-md5 keys: only the SHA-2 family is signed or verified.

Functions

func CanonicalKeyName

func CanonicalKeyName(name string) string

CanonicalKeyName lower-cases a key name and makes it absolute.

func CanonicalTSIGAlgorithm

func CanonicalTSIGAlgorithm(alg string) string

CanonicalTSIGAlgorithm returns the absolute lower-case algorithm name miekg/dns expects.

func CheckTSIGAlgorithm

func CheckTSIGAlgorithm(alg string) error

CheckTSIGAlgorithm reports whether alg is a TSIG algorithm this package can sign and verify.

func DefaultTransparentSuffixes

func DefaultTransparentSuffixes() []string

DefaultTransparentSuffixes lists the real AWS endpoint zones answered in transparent mode.

func FetchZone

func FetchZone(ctx context.Context, addr, zone string, key *TSIGKey) ([]dns.RR, error)

FetchZone pulls zone from the primary at addr with AXFR over TCP and returns every record, the opening and closing SOA included. A non-nil key signs the request and requires every response message to verify.

func NewTSIGProvider

func NewTSIGProvider(lookup KeyLookup) dns.TsigProvider

NewTSIGProvider returns a dns.TsigProvider that resolves keys through lookup on every message, so keys created or deleted after the server started take effect at once.

func ResolvConfUpstreams

func ResolvConfUpstreams(path string) []string

ResolvConfUpstreams returns the nameservers (host:port) from a resolv.conf file.

func SendNotify

func SendNotify(ctx context.Context, addr, zone string, soa dns.RR, key *TSIGKey) error

SendNotify sends a NOTIFY (RFC 1996) for zone to addr over UDP, signed when key is non-nil.

func ServeTransfer

func ServeTransfer(w dns.ResponseWriter, req *dns.Msg, rrs []dns.RR) error

ServeTransfer streams rrs (opening SOA, records, closing SOA) to the AXFR requester in batches. TSIG is applied by the response writer when the request was signed.

func SingleKeyProvider

func SingleKeyProvider(key TSIGKey) dns.TsigProvider

SingleKeyProvider returns a dns.TsigProvider that knows only key.

func SyntheticHostname

func SyntheticHostname(resourceID, randomSuffix, region, serviceType string) string

SyntheticHostname generates an AWS-style synthetic hostname for a resource. serviceType is one of: "cache", "rds", "redshift", "es".

Types

type Config

type Config struct {
	// Logger is an optional structured logger.
	Logger *slog.Logger
	// TsigProvider, when set, verifies signed requests and signs their responses (RFC 8945).
	TsigProvider dns.TsigProvider
	// ListenAddr is the host:port to bind (default ":10053").
	ListenAddr string
	// ResolveIP is the IP address returned for every registered name (default "127.0.0.1").
	ResolveIP string
	// Transparent enables real-AWS-endpoint interception and upstream forwarding.
	Transparent TransparentConfig
}

Config holds the configuration for the embedded DNS server.

type Interceptor

type Interceptor interface {
	Intercept(src net.Addr, req *dns.Msg, local func() *dns.Msg) *dns.Msg
}

Interceptor sees every query before the static records do. local computes the static answer; returning nil falls back to it.

type KeyLookup

type KeyLookup func(canonicalName string) (TSIGKey, bool)

KeyLookup finds a key by its canonical name.

type Server

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

Server is an embedded DNS server that answers A queries for registered synthetic hostnames with a fixed IP address.

func New

func New(cfg Config) (*Server, error)

New creates a new Server with the given config. Zero-value Config fields are filled with defaults.

func (*Server) Deregister

func (s *Server) Deregister(hostname string)

Deregister removes a hostname from the set the server will resolve. It clears both simple registrations (Register) and typed records (RegisterRecord). Calls are safe for concurrent use.

func (*Server) IsRegistered

func (s *Server) IsRegistered(hostname string) bool

IsRegistered reports whether the hostname is registered.

func (*Server) Owns

func (s *Server) Owns(hostname string) bool

Owns reports whether hostname has a static registration of any kind.

func (*Server) Port

func (s *Server) Port() int

Port returns the TCP/UDP port the server is bound to, or 0 before Start binds an ephemeral port.

func (*Server) Register

func (s *Server) Register(hostname string)

Register adds a hostname to the set of names the server will resolve. The trailing dot required by DNS is added automatically. Hostnames are stored in lower-case so lookups are case-insensitive. Calls are safe for concurrent use.

func (*Server) RegisterRecord

func (s *Server) RegisterRecord(hostname, recordType string, values []string)

RegisterRecord stores per-record typed values for a hostname. recordType must be one of "A", "CNAME", "AAAA", or "ALIAS". Multiple calls with the same hostname and recordType append values. Calls are safe for concurrent use.

func (*Server) SetInterceptor

func (s *Server) SetInterceptor(i Interceptor)

SetInterceptor installs (or, with nil, removes) the query interceptor.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start launches the DNS server in the background. It returns once both the UDP and TCP servers are ready to accept queries. Call Stop or cancel ctx to shut down.

func (*Server) Stop

func (s *Server) Stop() error

Stop shuts down both the UDP and TCP servers and waits for their serve goroutines to exit. It is safe to call more than once, and after a failed Start.

type StreamInterceptor

type StreamInterceptor interface {
	InterceptStream(w dns.ResponseWriter, req *dns.Msg) bool
}

StreamInterceptor is an optional Interceptor extension for exchanges that need the response writer: it writes any number of messages and reports true, or reports false to let the query take the single-message path.

type TSIGKey

type TSIGKey struct {
	// Name is the key name, an absolute domain name once canonicalised.
	Name string
	// Algorithm is the algorithm name, with or without the trailing dot (hmac-sha256).
	Algorithm string
	// Secret is the base64 encoded shared secret.
	Secret string
}

TSIGKey is a shared secret that signs DNS messages between two servers (RFC 8945).

type TransparentConfig

type TransparentConfig struct {
	// Suffixes are zones whose names resolve to ResolveIP; empty disables the mode.
	Suffixes []string
	// Skip lists names (or zones) that always resolve upstream, e.g. "sts.amazonaws.com".
	Skip []string
	// SkipPatterns are regexes (RE2, matched against the whole lowercase name without the
	// trailing dot) whose matches resolve upstream like Skip entries.
	SkipPatterns []string
	// Upstreams are host:port resolvers; empty means /etc/resolv.conf.
	Upstreams []string
}

TransparentConfig makes the server answer real AWS endpoint names with ResolveIP and forward every other unowned name to an upstream resolver.

Directories

Path Synopsis
Package dnstest starts embedded pkgs/dns servers on free ports for tests.
Package dnstest starts embedded pkgs/dns servers on free ports for tests.

Jump to

Keyboard shortcuts

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