config

package
v0.32.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: Apache-2.0 Imports: 30 Imported by: 1

Documentation

Index

Constants

View Source
const UpstreamDefaultCfgName = "default"

Variables

View Source
var ErrInvalidBytesSourceType = fmt.Errorf("not a valid BytesSourceType, try [%s]", strings.Join(_BytesSourceTypeNames, ", "))
View Source
var ErrInvalidIPVersion = fmt.Errorf("not a valid IPVersion, try [%s]", strings.Join(_IPVersionNames, ", "))
View Source
var ErrInvalidInitStrategy = fmt.Errorf("not a valid InitStrategy, try [%s]", strings.Join(_InitStrategyNames, ", "))
View Source
var ErrInvalidNetProtocol = fmt.Errorf("not a valid NetProtocol, try [%s]", strings.Join(_NetProtocolNames, ", "))
View Source
var ErrInvalidProxyProtocolType = fmt.Errorf("not a valid ProxyProtocolType, try [%s]", strings.Join(_ProxyProtocolTypeNames, ", "))
View Source
var ErrInvalidQueryLogField = fmt.Errorf("not a valid QueryLogField, try [%s]", strings.Join(_QueryLogFieldNames, ", "))
View Source
var ErrInvalidQueryLogType = fmt.Errorf("not a valid QueryLogType, try [%s]", strings.Join(_QueryLogTypeNames, ", "))
View Source
var ErrInvalidTLSVersion = fmt.Errorf("not a valid TLSVersion, try [%s]", strings.Join(_TLSVersionNames, ", "))
View Source
var ErrInvalidUpstreamStrategy = fmt.Errorf("not a valid UpstreamStrategy, try [%s]", strings.Join(_UpstreamStrategyNames, ", "))

Functions

func BytesSourceTypeNames

func BytesSourceTypeNames() []string

BytesSourceTypeNames returns a list of possible string values of BytesSourceType.

func ConvertPort

func ConvertPort(in string) (uint16, error)

ConvertPort converts string representation into a valid port (0 - 65535)

func IPVersionNames

func IPVersionNames() []string

IPVersionNames returns a list of possible string values of IPVersion.

func InitStrategyNames

func InitStrategyNames() []string

InitStrategyNames returns a list of possible string values of InitStrategy.

func NetProtocolNames

func NetProtocolNames() []string

NetProtocolNames returns a list of possible string values of NetProtocol.

func ProxyProtocolTypeNames added in v0.32.0

func ProxyProtocolTypeNames() []string

ProxyProtocolTypeNames returns a list of possible string values of ProxyProtocolType.

func QueryLogFieldNames

func QueryLogFieldNames() []string

QueryLogFieldNames returns a list of possible string values of QueryLogField.

func QueryLogTypeNames

func QueryLogTypeNames() []string

QueryLogTypeNames returns a list of possible string values of QueryLogType.

func TLSVersionNames

func TLSVersionNames() []string

TLSVersionNames returns a list of possible string values of TLSVersion.

func UpstreamStrategyNames

func UpstreamStrategyNames() []string

UpstreamStrategyNames returns a list of possible string values of UpstreamStrategy.

func WithDefaults

func WithDefaults[T any]() (T, error)

Types

type Blocking

type Blocking struct {
	// Named groups of block-list sources (URLs, file paths, or inline content).
	Denylists map[string][]BytesSource `yaml:"denylists"`
	// Named groups of allow-list sources; entries here take precedence over denylists in the same group.
	Allowlists map[string][]BytesSource `yaml:"allowlists"`
	// Named time-based schedules that can gate when list groups are active.
	Schedules map[string]Schedule `yaml:"schedules"`
	// Maps each list group name to the schedule(s) that control when it is active.
	ListSchedules map[string][]string `yaml:"listSchedules"`
	// Maps client identifiers (name, IP, CIDR) to the list groups that apply to them.
	ClientGroupsBlock map[string][]string `yaml:"clientGroupsBlock"`
	// Response for blocked A/AAAA queries: zeroIP (0.0.0.0/::), nxDomain, or custom IPs; other types get NXDOMAIN.
	BlockType string `default:"ZEROIP" yaml:"blockType"`
	// TTL of blocked responses; how long clients cache the block before querying the domain again.
	BlockTTL Duration `default:"6h" yaml:"blockTTL"`
	// Controls how block/allow lists are loaded and periodically refreshed.
	Loading SourceLoading `yaml:"loading"`

	// Deprecated options
	Deprecated struct {
		BlackLists            *map[string][]BytesSource `yaml:"blackLists"`
		WhiteLists            *map[string][]BytesSource `yaml:"whiteLists"`
		DownloadTimeout       *Duration                 `yaml:"downloadTimeout"`
		DownloadAttempts      *uint                     `yaml:"downloadAttempts"`
		DownloadCooldown      *Duration                 `yaml:"downloadCooldown"`
		RefreshPeriod         *Duration                 `yaml:"refreshPeriod"`
		FailStartOnListError  *bool                     `yaml:"failStartOnListError"`
		ProcessingConcurrency *uint                     `yaml:"processingConcurrency"`
		StartStrategy         *InitStrategy             `yaml:"startStrategy"`
		MaxErrorsPerFile      *int                      `yaml:"maxErrorsPerFile"`
	} `yaml:",inline"`
}

Blocking configuration for query blocking

func (*Blocking) IsEnabled

func (c *Blocking) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*Blocking) LogConfig

func (c *Blocking) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type BootstrapDNS

type BootstrapDNS bootstrapDNS

split in two types to avoid infinite recursion. See `BootstrapDNS.UnmarshalYAML`.

func (*BootstrapDNS) IsEnabled

func (b *BootstrapDNS) IsEnabled() bool

func (*BootstrapDNS) LogConfig

func (b *BootstrapDNS) LogConfig(*logrus.Entry)

func (*BootstrapDNS) UnmarshalYAML

func (b *BootstrapDNS) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML creates BootstrapDNS from YAML

type BootstrappedUpstream

type BootstrappedUpstream bootstrappedUpstream

split in two types to avoid infinite recursion. See `BootstrappedUpstream.UnmarshalYAML`.

func (*BootstrappedUpstream) UnmarshalYAML

func (b *BootstrappedUpstream) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML creates BootstrappedUpstream from YAML

type BytesSource

type BytesSource struct {
	Type BytesSourceType
	From string
}

func NewBytesSources

func NewBytesSources(sources ...string) []BytesSource

func TextBytesSource

func TextBytesSource(lines ...string) BytesSource

func (BytesSource) String

func (s BytesSource) String() string

func (*BytesSource) UnmarshalText

func (s *BytesSource) UnmarshalText(data []byte) error

UnmarshalText implements `encoding.TextUnmarshaler`.

type BytesSourceType

type BytesSourceType uint16

BytesSourceType supported BytesSource types. ENUM( text=1 // Inline YAML block. http // HTTP(S). file // Local file. )

const (
	// BytesSourceTypeText is a BytesSourceType of type Text.
	// Inline YAML block.
	BytesSourceTypeText BytesSourceType = iota + 1
	// BytesSourceTypeHttp is a BytesSourceType of type Http.
	// HTTP(S).
	BytesSourceTypeHttp
	// BytesSourceTypeFile is a BytesSourceType of type File.
	// Local file.
	BytesSourceTypeFile
)

func BytesSourceTypeValues

func BytesSourceTypeValues() []BytesSourceType

BytesSourceTypeValues returns a list of the values for BytesSourceType

func ParseBytesSourceType

func ParseBytesSourceType(name string) (BytesSourceType, error)

ParseBytesSourceType attempts to convert a string to a BytesSourceType.

func (*BytesSourceType) AppendText added in v0.28.0

func (x *BytesSourceType) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (BytesSourceType) IsValid

func (x BytesSourceType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (BytesSourceType) MarshalText

func (x BytesSourceType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (BytesSourceType) String

func (x BytesSourceType) String() string

String implements the Stringer interface.

func (*BytesSourceType) UnmarshalText

func (x *BytesSourceType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type Caching

type Caching struct {
	// Minimum TTL for cached entries; if the response TTL is smaller, this value is used instead.
	MinCachingTime Duration `yaml:"minTime"`
	// Maximum TTL for cached entries. If <0, caching is disabled. If 0, the response TTL is used.
	MaxCachingTime Duration `yaml:"maxTime"`
	// TTL for negative responses (NXDOMAIN / empty). Use -1 to disable caching of negative results.
	CacheTimeNegative Duration `default:"30m" yaml:"cacheTimeNegative"`
	// Maximum number of cache entries (soft limit). 0 means unlimited.
	MaxItemsCount int `yaml:"maxItemsCount"`
	// If true, blocky preloads DNS results for frequently queried names before they expire.
	Prefetching bool `yaml:"prefetching"`
	// Time window used to track query frequency for prefetch eligibility.
	PrefetchExpires Duration `default:"2h" yaml:"prefetchExpires"`
	// Minimum number of queries within prefetchExpires required to trigger prefetching.
	PrefetchThreshold int `default:"5" yaml:"prefetchThreshold"`
	// Maximum number of domains tracked for prefetching (soft limit). 0 means unlimited.
	PrefetchMaxItemsCount int `yaml:"prefetchMaxItemsCount"`
	// Regex list of domains that are never cached.
	Exclude []string `yaml:"exclude"`
}

Caching configuration for domain caching

func (*Caching) EnablePrefetch

func (c *Caching) EnablePrefetch()

func (*Caching) IsEnabled

func (c *Caching) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*Caching) LogConfig

func (c *Caching) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type CertificateFingerprint added in v0.28.0

type CertificateFingerprint []byte

CertificateFingerprint represents a SHA256 fingerprint of a TLS certificate (32 bytes)

type ClientLookup

type ClientLookup struct {
	// Static map of client name to one or more IP addresses for manual client name assignment.
	ClientnameIPMapping map[string][]net.IP `yaml:"clients"`
	// Upstream DNS server used for rDNS client name lookups (typically your router).
	Upstream Upstream `yaml:"upstream"`
	// Order of preference when a router returns multiple names for a client (1-based index).
	SingleNameOrder []uint `yaml:"singleNameOrder"`
}

ClientLookup configuration for the client lookup

func (*ClientLookup) IsEnabled

func (c *ClientLookup) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*ClientLookup) LogConfig

func (c *ClientLookup) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type ConditionalUpstream

type ConditionalUpstream struct {
	RewriterConfig `yaml:",inline"`

	// Domain-to-upstream mappings; queries for each domain are forwarded to its configured resolver(s).
	Mapping ConditionalUpstreamMapping `yaml:"mapping"`
}

ConditionalUpstream conditional upstream configuration

func (*ConditionalUpstream) IsEnabled

func (c *ConditionalUpstream) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*ConditionalUpstream) LogConfig

func (c *ConditionalUpstream) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type ConditionalUpstreamMapping

type ConditionalUpstreamMapping struct {
	Upstreams map[string][]Upstream
}

ConditionalUpstreamMapping mapping for conditional configuration

func (*ConditionalUpstreamMapping) UnmarshalYAML

func (c *ConditionalUpstreamMapping) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements `yaml.Unmarshaler`.

type Config

type Config struct {
	// Upstream DNS servers and strategy configuration.
	Upstreams Upstreams `yaml:"upstreams"`
	// IP version used for outgoing connections (dual, v4, v6).
	ConnectIPVersion IPVersion `yaml:"connectIPVersion"`
	// Custom static DNS mappings and zone definitions.
	CustomDNS CustomDNS `yaml:"customDNS"`
	// Conditional upstream resolvers for specific domains.
	Conditional ConditionalUpstream `yaml:"conditional"`
	// Blocking configuration with allow/denylists and client groups.
	Blocking Blocking `yaml:"blocking"`
	// Client name lookup configuration for resolving client identifiers.
	ClientLookup ClientLookup `yaml:"clientLookup"`
	// DNS response caching settings.
	Caching Caching `yaml:"caching"`
	// Query logging configuration.
	QueryLog QueryLog `yaml:"queryLog"`
	// Prometheus metrics configuration.
	Prometheus Metrics `yaml:"prometheus"`
	// In-memory statistics subsystem (24h window), served at /api/stats.
	Statistics Statistics `yaml:"statistics"`
	// Redis configuration for cache and state synchronization between instances.
	Redis Redis `yaml:"redis"`
	// Logging configuration.
	Log log.Config `yaml:"log"`
	// Listen addresses for DNS, HTTP, HTTPS, and TLS.
	Ports Ports `yaml:"ports"`
	// Minimum TLS version the DoT and DoH servers use to serve encrypted DNS requests.
	MinTLSServeVer TLSVersion `default:"1.2" yaml:"minTlsServeVersion"`
	// Path to the TLS certificate file for DoH and DoT; if empty, a self-signed certificate is generated.
	CertFile string `yaml:"certFile"`
	// Path to the TLS key file for DoH and DoT; if empty, a self-signed certificate is generated.
	KeyFile string `yaml:"keyFile"`
	// Bootstrap DNS servers used to resolve DoH/DoT upstream hostnames.
	BootstrapDNS BootstrapDNS `yaml:"bootstrapDns"`
	// Local hosts file resolution settings.
	HostsFile HostsFile `yaml:"hostsFile"`
	// When enabled, blocky returns NXDOMAIN immediately for non-FQDN queries.
	FQDNOnly FQDNOnly `yaml:"fqdnOnly"`
	// DNS query type filtering configuration.
	Filtering Filtering `yaml:"filtering"`
	// Extended DNS Errors (RFC 8914) configuration.
	EDE EDE `yaml:"ede"`
	// EDNS Client Subnet options.
	ECS ECS `yaml:"ecs"`
	// Special Use Domain Names (SUDN) blocking configuration.
	SUDN SUDN `yaml:"specialUseDomains"`
	// DNS64 synthesis configuration for IPv6-only clients (RFC 6147).
	DNS64 DNS64 `yaml:"dns64"`
	// DNSSEC validation configuration.
	DNSSEC DNSSEC `yaml:"dnssec"`
	// HTTP/3 (DoH3) server configuration.
	HTTP3 HTTP3 `yaml:"http3"`
	// Per-client DNS query rate limiting configuration.
	RateLimit RateLimit `yaml:"rateLimit"`
	// DNS rebinding protection configuration.
	RebindingProtection RebindingProtection `yaml:"rebindingProtection"`

	// Deprecated options
	Deprecated struct {
		Upstream            *UpstreamGroups `yaml:"upstream"`
		UpstreamTimeout     *Duration       `yaml:"upstreamTimeout"`
		DisableIPv6         *bool           `yaml:"disableIPv6"`
		LogLevel            *logrus.Level   `yaml:"logLevel"`
		LogFormat           *log.FormatType `yaml:"logFormat"`
		LogPrivacy          *bool           `yaml:"logPrivacy"`
		LogTimestamp        *bool           `yaml:"logTimestamp"`
		DNSPorts            *ListenConfig   `yaml:"port"`
		HTTPPorts           *ListenConfig   `yaml:"httpPort"`
		HTTPSPorts          *ListenConfig   `yaml:"httpsPort"`
		TLSPorts            *ListenConfig   `yaml:"tlsPort"`
		StartVerifyUpstream *bool           `yaml:"startVerifyUpstream"`
		DoHUserAgent        *string         `yaml:"dohUserAgent"`
	} `yaml:",inline"`
}

Config main configuration

func LoadConfig

func LoadConfig(path string, mandatory bool) (rCfg *Config, rerr error)

LoadConfig creates new config from YAML file or a directory containing YAML files

type Configurable

type Configurable interface {
	// IsEnabled returns true when the receiver is configured.
	IsEnabled() bool

	// LogConfig logs the receiver's configuration.
	//
	// The behavior of this method is undefined when `IsEnabled` returns false.
	LogConfig(logger *logrus.Entry)
}

type CustomDNS

type CustomDNS struct {
	RewriterConfig `yaml:",inline"`

	// TTL for DNS records defined in the mapping section (does not apply to zone file records).
	CustomTTL Duration `default:"1h" yaml:"customTTL"`
	// Simple domain-to-IP mappings; multiple IPs per domain separated by commas.
	Mapping CustomDNSMapping `yaml:"mapping"`
	// DNS zone file content for more complex record definitions (A, AAAA, CNAME, TXT, SRV).
	Zone ZoneFileDNS `default:"" yaml:"zone"`
	// If true, queries for types not defined for a domain return empty; if false, they are forwarded upstream.
	FilterUnmappedTypes bool `default:"true" yaml:"filterUnmappedTypes"`
}

CustomDNS custom DNS configuration

func (*CustomDNS) IsEnabled

func (c *CustomDNS) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*CustomDNS) LogConfig

func (c *CustomDNS) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type CustomDNSEntries

type CustomDNSEntries []dns.RR

func (*CustomDNSEntries) UnmarshalYAML

func (c *CustomDNSEntries) UnmarshalYAML(unmarshal func(any) error) error

type CustomDNSMapping

type CustomDNSMapping map[string]CustomDNSEntries

type DNS64 added in v0.29.0

type DNS64 struct {
	// Enable DNS64 synthesis of AAAA records from A records for IPv6-only clients (RFC 6147).
	Enable bool `default:"false" yaml:"enable"`
	// IPv6 prefixes used for synthesis; valid lengths are /32, /40, /48, /56, /64, /96 (default: 64:ff9b::/96).
	Prefixes []netip.Prefix `yaml:"prefixes"`
	// IPv6 prefixes excluded from triggering synthesis. Overrides the default exclusion set; advanced use only.
	ExclusionSet []netip.Prefix `yaml:"exclusionSet"`
}

DNS64 is the configuration for DNS64 resolver

func (*DNS64) IsEnabled added in v0.29.0

func (c *DNS64) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*DNS64) LogConfig added in v0.29.0

func (c *DNS64) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type DNSSEC added in v0.28.0

type DNSSEC struct {
	// Enable DNSSEC validation of DNS responses.
	Validate bool `default:"false" yaml:"validate"`
	// Custom trust anchors (DNSKEY or DS records); empty uses built-in IANA root trust anchors.
	TrustAnchors []string `yaml:"trustAnchors"`
	// Maximum domain label depth for chain of trust validation (DoS protection).
	MaxChainDepth uint `default:"10" yaml:"maxChainDepth"`
	// How long to cache DNSSEC validation results, in hours.
	CacheExpirationHours uint `default:"1"   yaml:"cacheExpirationHours"`
	MaxNSEC3Iterations   uint `default:"150" yaml:"maxNSEC3Iterations"` // RFC 5155 §10.3
	// DoS protection: max upstream queries per validation
	MaxUpstreamQueries uint `default:"30" yaml:"maxUpstreamQueries"`
	// Clock skew tolerance in seconds for signature validation (default: 3600 = 1 hour)
	// Allows validation to succeed even if system clock is off by this amount.
	// Matches Unbound/BIND defaults for real-world deployments (VMs, containers, embedded systems).
	// Per RFC 6781 §4.1.2: Validators should account for clock skew in deployment environments.
	ClockSkewToleranceSec uint `default:"3600" yaml:"clockSkewToleranceSec"`
}

DNSSEC is the configuration for DNSSEC validation

func (*DNSSEC) IsEnabled added in v0.28.0

func (c *DNSSEC) IsEnabled() bool

IsEnabled returns true if DNSSEC validation is enabled

func (*DNSSEC) LogConfig added in v0.28.0

func (c *DNSSEC) LogConfig(logger *logrus.Entry)

LogConfig logs the DNSSEC configuration

type Downloader

type Downloader struct {
	// Timeout per download attempt (default: 5s).
	Timeout Duration `default:"5s" yaml:"timeout"`
	// Timeout for reading the download response body (default: 20s).
	ReadTimeout Duration `default:"20s" yaml:"readTimeout"`
	// Timeout for reading the download response headers (default: 20s).
	ReadHeaderTimeout Duration `default:"20s" yaml:"readHeaderTimeout"`
	// Timeout for writing the downloaded file (default: 20s).
	WriteTimeout Duration `default:"20s" yaml:"writeTimeout"`
	// Number of download attempts before giving up (default: 3).
	Attempts uint `default:"3" yaml:"attempts"`
	// Pause between consecutive download attempts (default: 500ms).
	Cooldown Duration `default:"500ms" yaml:"cooldown"`
	// Directory for the on-disk download cache. When empty (default), downloads are
	// fully stateless: nothing is written to disk and every source is downloaded in
	// full on every refresh. When set, blocky uses HTTP conditional requests and
	// serves unchanged/unavailable sources from this directory.
	CachePath string `yaml:"cachePath"`
}

func (*Downloader) LogConfig

func (c *Downloader) LogConfig(logger *logrus.Entry)

type Duration

type Duration time.Duration

Duration is a wrapper for time.Duration to support yaml unmarshalling

func (Duration) IsAboveZero

func (c Duration) IsAboveZero() bool

IsAboveZero returns true if duration is strictly greater than zero.

func (Duration) IsAtLeastZero

func (c Duration) IsAtLeastZero() bool

IsAtLeastZero returns true if duration is greater or equal to zero.

func (Duration) Seconds

func (c Duration) Seconds() float64

Seconds returns duration in seconds

func (Duration) SecondsU32

func (c Duration) SecondsU32() uint32

SecondsU32 returns duration in seconds as uint32

func (Duration) String

func (c Duration) String() string

String implements `fmt.Stringer`

func (Duration) ToDuration

func (c Duration) ToDuration() time.Duration

ToDuration converts Duration to time.Duration

func (*Duration) UnmarshalText

func (c *Duration) UnmarshalText(data []byte) error

UnmarshalText implements `encoding.TextUnmarshaler`.

type ECS

type ECS struct {
	// Use the ECS client subnet as the client IP when a full-prefix ECS option is present.
	UseAsClient bool `default:"false" yaml:"useAsClient"`
	// Forward the ECS option from the client request to upstream resolvers.
	Forward bool `default:"false" yaml:"forward"`
	// Subnet mask for IPv4 EDNS Client Subnet; adds ECS option when greater than zero (max 32).
	IPv4Mask ECSv4Mask `default:"0" yaml:"ipv4Mask"`
	// Subnet mask for IPv6 EDNS Client Subnet; adds ECS option when greater than zero (max 128).
	IPv6Mask ECSv6Mask `default:"0" yaml:"ipv6Mask"`
}

ECS is the configuration of the ECS resolver

func (*ECS) IsEnabled

func (c *ECS) IsEnabled() bool

IsEnabled returns true if the ECS resolver is enabled

func (*ECS) LogConfig

func (c *ECS) LogConfig(logger *logrus.Entry)

LogConfig logs the configuration

type ECSv4Mask

type ECSv4Mask uint8

ECSv4Mask is the subnet mask to be added as EDNS0 option for IPv4

func (*ECSv4Mask) UnmarshalText

func (x *ECSv4Mask) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface

type ECSv6Mask

type ECSv6Mask uint8

ECSv6Mask is the subnet mask to be added as EDNS0 option for IPv6

func (*ECSv6Mask) UnmarshalText

func (x *ECSv6Mask) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface

type EDE

type EDE = toEnable

type FQDNOnly

type FQDNOnly = toEnable

type Filtering

type Filtering struct {
	// DNS query types to drop; matching queries receive an empty answer (e.g. AAAA to block IPv6 lookups).
	QueryTypes QTypeSet `yaml:"queryTypes"`
}

func (*Filtering) IsEnabled

func (c *Filtering) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*Filtering) LogConfig

func (c *Filtering) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type HTTP3 added in v0.30.0

type HTTP3 struct {
	// Enable the HTTP/3 listener on the same addresses as ports.https (requires ports.https to be set).
	Enable bool `default:"false" yaml:"enable"`
}

HTTP3 holds DNS-over-HTTPS over HTTP/3 (DoH3) server settings.

func (*HTTP3) IsEnabled added in v0.30.0

func (c *HTTP3) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*HTTP3) LogConfig added in v0.30.0

func (c *HTTP3) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type HostsFile

type HostsFile struct {
	// Host files to load (e.g. /etc/hosts); supports local paths, URLs, and inline content.
	Sources []BytesSource `yaml:"sources"`
	// TTL for DNS records resolved from host files.
	HostsTTL Duration `default:"1h" yaml:"hostsTTL"`
	// If true, loopback addresses (127.0.0.0/8 and ::1) from host files are ignored.
	FilterLoopback bool `yaml:"filterLoopback"`
	// Controls how host files are loaded and periodically refreshed.
	Loading SourceLoading `yaml:"loading"`

	// Deprecated options
	Deprecated struct {
		RefreshPeriod *Duration    `yaml:"refreshPeriod"`
		Filepath      *BytesSource `yaml:"filePath"`
	} `yaml:",inline"`
}

func (*HostsFile) IsEnabled

func (c *HostsFile) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*HostsFile) LogConfig

func (c *HostsFile) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type IPVersion

type IPVersion uint8

IPVersion represents IP protocol version(s). ENUM( dual // Use both IPv4 and IPv6. v4 // Use IPv4 only. v6 // Use IPv6 only. )

const (
	// IPVersionDual is a IPVersion of type Dual.
	// Use both IPv4 and IPv6.
	IPVersionDual IPVersion = iota
	// IPVersionV4 is a IPVersion of type V4.
	// Use IPv4 only.
	IPVersionV4
	// IPVersionV6 is a IPVersion of type V6.
	// Use IPv6 only.
	IPVersionV6
)

func IPVersionValues

func IPVersionValues() []IPVersion

IPVersionValues returns a list of the values for IPVersion

func ParseIPVersion

func ParseIPVersion(name string) (IPVersion, error)

ParseIPVersion attempts to convert a string to a IPVersion.

func (*IPVersion) AppendText added in v0.28.0

func (x *IPVersion) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (IPVersion) EnumDescriptions added in v0.31.0

func (IPVersion) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (IPVersion) EnumValues added in v0.31.0

func (IPVersion) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (IPVersion) IsValid

func (x IPVersion) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (IPVersion) MarshalText

func (x IPVersion) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (IPVersion) Net

func (ipv IPVersion) Net() string

func (IPVersion) QTypes

func (ipv IPVersion) QTypes() []dns.Type

func (IPVersion) String

func (x IPVersion) String() string

String implements the Stringer interface.

func (*IPVersion) UnmarshalText

func (x *IPVersion) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type Init

type Init struct {
	// Startup strategy controlling how initialization failures are handled.
	Strategy InitStrategy `default:"blocking" yaml:"strategy"`
}

func (*Init) LogConfig

func (c *Init) LogConfig(logger *logrus.Entry)

type InitStrategy

type InitStrategy uint16

InitStrategy startup strategy ENUM( blocking // Initialization runs before DNS resolution starts; errors are logged but Blocky keeps running if possible. failOnError // Like blocking but Blocky exits with an error if initialization fails. fast // Blocky serves DNS immediately and runs initialization in the background. )

const (
	// InitStrategyBlocking is a InitStrategy of type Blocking.
	// Initialization runs before DNS resolution starts; errors are logged but Blocky keeps running if possible.
	InitStrategyBlocking InitStrategy = iota
	// InitStrategyFailOnError is a InitStrategy of type FailOnError.
	// Like blocking but Blocky exits with an error if initialization fails.
	InitStrategyFailOnError
	// InitStrategyFast is a InitStrategy of type Fast.
	// Blocky serves DNS immediately and runs initialization in the background.
	InitStrategyFast
)

func InitStrategyValues

func InitStrategyValues() []InitStrategy

InitStrategyValues returns a list of the values for InitStrategy

func ParseInitStrategy

func ParseInitStrategy(name string) (InitStrategy, error)

ParseInitStrategy attempts to convert a string to a InitStrategy.

func (*InitStrategy) AppendText added in v0.28.0

func (x *InitStrategy) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (InitStrategy) Do

func (s InitStrategy) Do(ctx context.Context, init func(context.Context) error, logErr func(error)) error

func (InitStrategy) EnumDescriptions added in v0.31.0

func (InitStrategy) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (InitStrategy) EnumValues added in v0.31.0

func (InitStrategy) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (InitStrategy) IsValid

func (x InitStrategy) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (InitStrategy) MarshalText

func (x InitStrategy) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (InitStrategy) String

func (x InitStrategy) String() string

String implements the Stringer interface.

func (*InitStrategy) UnmarshalText

func (x *InitStrategy) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type ListenConfig

type ListenConfig []string

ListenConfig is a list of address(es) to listen on

func (*ListenConfig) UnmarshalText

func (l *ListenConfig) UnmarshalText(data []byte) error

UnmarshalText implements `encoding.TextUnmarshaler`.

func (*ListenConfig) UnmarshalYAML added in v0.27.0

func (l *ListenConfig) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML creates a ListenConfig from YAML

type Metrics

type Metrics struct {
	// If true, enables the Prometheus metrics endpoint.
	Enable bool `default:"false" yaml:"enable"`
	// URL path under which the Prometheus metrics are served.
	Path string `default:"/metrics" yaml:"path"`
}

Metrics contains the config values for prometheus

func (*Metrics) IsEnabled

func (c *Metrics) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*Metrics) LogConfig

func (c *Metrics) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type NetProtocol

type NetProtocol uint16

NetProtocol resolver protocol ENUM( tcp+udp // TCP and UDP protocols tcp-tls // TCP-TLS protocol https // HTTPS protocol quic // DNS-over-QUIC protocol )

const (
	// NetProtocolTcpUdp is a NetProtocol of type Tcp+Udp.
	// TCP and UDP protocols
	NetProtocolTcpUdp NetProtocol = iota
	// NetProtocolTcpTls is a NetProtocol of type Tcp-Tls.
	// TCP-TLS protocol
	NetProtocolTcpTls
	// NetProtocolHttps is a NetProtocol of type Https.
	// HTTPS protocol
	NetProtocolHttps
	// NetProtocolQuic is a NetProtocol of type Quic.
	// DNS-over-QUIC protocol
	NetProtocolQuic
)

func NetProtocolValues

func NetProtocolValues() []NetProtocol

NetProtocolValues returns a list of the values for NetProtocol

func ParseNetProtocol

func ParseNetProtocol(name string) (NetProtocol, error)

ParseNetProtocol attempts to convert a string to a NetProtocol.

func (*NetProtocol) AppendText added in v0.28.0

func (x *NetProtocol) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (NetProtocol) EnumDescriptions added in v0.31.0

func (NetProtocol) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (NetProtocol) EnumValues added in v0.31.0

func (NetProtocol) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (NetProtocol) IsValid

func (x NetProtocol) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (NetProtocol) MarshalText

func (x NetProtocol) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (NetProtocol) String

func (x NetProtocol) String() string

String implements the Stringer interface.

func (*NetProtocol) UnmarshalText

func (x *NetProtocol) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type Ports

type Ports struct {
	// Listen address(es) for DNS over TCP and UDP (default: 53).
	DNS ListenConfig `default:"53" yaml:"dns"`
	// Listen address(es) for HTTP (metrics, REST API, DoH).
	HTTP ListenConfig `yaml:"http"`
	// Listen address(es) for HTTPS (metrics, REST API, DoH).
	HTTPS ListenConfig `yaml:"https"`
	// Listen address(es) for DNS-over-TLS (DoT).
	TLS ListenConfig `yaml:"tls"`
	// URL path for DoH queries.
	DOHPath string `default:"/dns-query" yaml:"dohPath"`
	// Allow binding the DNS and DoT listeners to addresses that are not yet assigned to a network
	// interface, via the Linux IP_FREEBIND socket option (e.g. for Tailscale/WireGuard/VRRP addresses
	// brought up after startup). Has no effect on wildcard binds and is ignored, with a warning, on
	// non-Linux platforms.
	FreeBind bool `default:"false" yaml:"freeBind"`
	// PROXY protocol listener families. List the TCP listeners that sit behind a trusted proxy and
	// must require a PROXY protocol header before the connection is handled, e.g. [https, tls].
	ProxyProtocol ProxyProtocolListeners `yaml:"proxyProtocol"`
}

func (*Ports) LogConfig

func (c *Ports) LogConfig(logger *logrus.Entry)

func (*Ports) PrivilegedPorts added in v0.31.0

func (p *Ports) PrivilegedPorts() []string

PrivilegedPorts returns the configured listen addresses across DNS, HTTP, HTTPS and TLS whose port is below privilegedPortCeiling.

type ProxyProtocolListeners added in v0.32.0

type ProxyProtocolListeners []ProxyProtocolType

ProxyProtocolListeners is the set of TCP listener families that require a PROXY protocol header.

func (ProxyProtocolListeners) Has added in v0.32.0

Has reports whether the given listener family requires the PROXY protocol.

type ProxyProtocolType added in v0.32.0

type ProxyProtocolType string

ProxyProtocolType is a TCP listener family that requires a PROXY protocol header. ENUM(dns,http,https,tls)

const (
	// ProxyProtocolTypeDns is a ProxyProtocolType of type dns.
	ProxyProtocolTypeDns ProxyProtocolType = "dns"
	// ProxyProtocolTypeHttp is a ProxyProtocolType of type http.
	ProxyProtocolTypeHttp ProxyProtocolType = "http"
	// ProxyProtocolTypeHttps is a ProxyProtocolType of type https.
	ProxyProtocolTypeHttps ProxyProtocolType = "https"
	// ProxyProtocolTypeTls is a ProxyProtocolType of type tls.
	ProxyProtocolTypeTls ProxyProtocolType = "tls"
)

func ParseProxyProtocolType added in v0.32.0

func ParseProxyProtocolType(name string) (ProxyProtocolType, error)

ParseProxyProtocolType attempts to convert a string to a ProxyProtocolType.

func ProxyProtocolTypeValues added in v0.32.0

func ProxyProtocolTypeValues() []ProxyProtocolType

ProxyProtocolTypeValues returns a list of the values for ProxyProtocolType

func (*ProxyProtocolType) AppendText added in v0.32.0

func (x *ProxyProtocolType) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (ProxyProtocolType) EnumDescriptions added in v0.32.0

func (ProxyProtocolType) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (ProxyProtocolType) EnumValues added in v0.32.0

func (ProxyProtocolType) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (ProxyProtocolType) IsValid added in v0.32.0

func (x ProxyProtocolType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ProxyProtocolType) MarshalText added in v0.32.0

func (x ProxyProtocolType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (ProxyProtocolType) String added in v0.32.0

func (x ProxyProtocolType) String() string

String implements the Stringer interface.

func (*ProxyProtocolType) UnmarshalText added in v0.32.0

func (x *ProxyProtocolType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type QType

type QType dns.Type

func (QType) String

func (c QType) String() string

func (*QType) UnmarshalText

func (c *QType) UnmarshalText(data []byte) error

UnmarshalText implements `encoding.TextUnmarshaler`.

type QTypeSet

type QTypeSet map[QType]struct{}

func NewQTypeSet

func NewQTypeSet(qTypes ...dns.Type) QTypeSet

func (QTypeSet) Contains

func (s QTypeSet) Contains(qType dns.Type) bool

func (*QTypeSet) Insert

func (s *QTypeSet) Insert(qType dns.Type)

func (*QTypeSet) UnmarshalYAML

func (s *QTypeSet) UnmarshalYAML(unmarshal func(any) error) error

type QUICConfig added in v0.30.0

type QUICConfig struct {
	// Maximum idle duration before the QUIC connection is closed.
	MaxIdleTimeout Duration `default:"30s" yaml:"maxIdleTimeout"`
	// Interval at which keep-alive packets are sent to maintain the QUIC connection.
	KeepAlivePeriod Duration `default:"15s" yaml:"keepAlivePeriod"`
}

QUICConfig holds QUIC-specific upstream settings.

type QueryLog

type QueryLog struct {
	// Directory for CSV log files, file path for sqlite, or database URL for mysql/postgresql/timescale.
	Target Secret `yaml:"target"`
	// Log target type: mysql, postgresql, timescale, sqlite, csv, csv-client, console, or none.
	Type QueryLogType `yaml:"type"`
	// Delete log entries older than this many days. 0 disables retention cleanup.
	LogRetentionDays uint64 `yaml:"logRetentionDays"`
	// Maximum number of attempts to create the query log writer on startup.
	CreationAttempts int `default:"3" yaml:"creationAttempts"`
	// Delay between query log writer creation attempts.
	CreationCooldown Duration `default:"2s" yaml:"creationCooldown"`
	// Which fields to include in log entries; defaults to all available fields.
	Fields []QueryLogField `yaml:"fields"`
	// Interval at which buffered log entries are flushed in bulk to the database
	// (used by the mysql, postgresql, timescale and sqlite targets).
	FlushInterval Duration `default:"30s" yaml:"flushInterval"`
	// Rules to suppress certain queries from being logged.
	Ignore QueryLogIgnore `yaml:"ignore"`
}

QueryLog configuration for the query logging

func (*QueryLog) IsEnabled

func (c *QueryLog) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*QueryLog) LogConfig

func (c *QueryLog) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

func (*QueryLog) SetDefaults

func (c *QueryLog) SetDefaults()

SetDefaults implements `defaults.Setter`.

type QueryLogField

type QueryLogField string

QueryLogField data field to be logged ENUM(clientIP,clientName,responseReason,responseAnswer,question,duration)

const (
	// QueryLogFieldClientIP is a QueryLogField of type clientIP.
	QueryLogFieldClientIP QueryLogField = "clientIP"
	// QueryLogFieldClientName is a QueryLogField of type clientName.
	QueryLogFieldClientName QueryLogField = "clientName"
	// QueryLogFieldResponseReason is a QueryLogField of type responseReason.
	QueryLogFieldResponseReason QueryLogField = "responseReason"
	// QueryLogFieldResponseAnswer is a QueryLogField of type responseAnswer.
	QueryLogFieldResponseAnswer QueryLogField = "responseAnswer"
	// QueryLogFieldQuestion is a QueryLogField of type question.
	QueryLogFieldQuestion QueryLogField = "question"
	// QueryLogFieldDuration is a QueryLogField of type duration.
	QueryLogFieldDuration QueryLogField = "duration"
)

func ParseQueryLogField

func ParseQueryLogField(name string) (QueryLogField, error)

ParseQueryLogField attempts to convert a string to a QueryLogField.

func QueryLogFieldValues

func QueryLogFieldValues() []QueryLogField

QueryLogFieldValues returns a list of the values for QueryLogField

func (*QueryLogField) AppendText added in v0.28.0

func (x *QueryLogField) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (QueryLogField) EnumDescriptions added in v0.31.0

func (QueryLogField) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (QueryLogField) EnumValues added in v0.31.0

func (QueryLogField) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (QueryLogField) IsValid

func (x QueryLogField) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (QueryLogField) MarshalText

func (x QueryLogField) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (QueryLogField) String

func (x QueryLogField) String() string

String implements the Stringer interface.

func (*QueryLogField) UnmarshalText

func (x *QueryLogField) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type QueryLogIgnore

type QueryLogIgnore struct {
	// If true, queries resolved as Special Use Domain Names (SUDN) are not logged.
	SUDN bool `default:"false" yaml:"sudn"`
	// Domains whose queries are not logged. Each entry is matched against the
	// query name as an exact domain, a *.wildcard, or a /regex/.
	Domains []string `yaml:"domains"`
}

type QueryLogType

type QueryLogType int16

QueryLogType type of the query log ENUM( console // Log to console output (used when no type is set). none // Do not log any queries. mysql // Log each query to an external MySQL or MariaDB database. postgresql // Log each query to an external PostgreSQL database. csv // Log to a CSV file (one per day). csv-client // Log to a CSV file (one per day and per client). timescale // Log each query to an external Timescale database. sqlite // Log each query to a local SQLite database file. )

const (
	// QueryLogTypeConsole is a QueryLogType of type Console.
	// Log to console output (used when no type is set).
	QueryLogTypeConsole QueryLogType = iota
	// QueryLogTypeNone is a QueryLogType of type None.
	// Do not log any queries.
	QueryLogTypeNone
	// QueryLogTypeMysql is a QueryLogType of type Mysql.
	// Log each query to an external MySQL or MariaDB database.
	QueryLogTypeMysql
	// QueryLogTypePostgresql is a QueryLogType of type Postgresql.
	// Log each query to an external PostgreSQL database.
	QueryLogTypePostgresql
	// QueryLogTypeCsv is a QueryLogType of type Csv.
	// Log to a CSV file (one per day).
	QueryLogTypeCsv
	// QueryLogTypeCsvClient is a QueryLogType of type Csv-Client.
	// Log to a CSV file (one per day and per client).
	QueryLogTypeCsvClient
	// QueryLogTypeTimescale is a QueryLogType of type Timescale.
	// Log each query to an external Timescale database.
	QueryLogTypeTimescale
	// QueryLogTypeSqlite is a QueryLogType of type Sqlite.
	// Log each query to a local SQLite database file.
	QueryLogTypeSqlite
)

func ParseQueryLogType

func ParseQueryLogType(name string) (QueryLogType, error)

ParseQueryLogType attempts to convert a string to a QueryLogType.

func QueryLogTypeValues

func QueryLogTypeValues() []QueryLogType

QueryLogTypeValues returns a list of the values for QueryLogType

func (*QueryLogType) AppendText added in v0.28.0

func (x *QueryLogType) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (QueryLogType) EnumDescriptions added in v0.31.0

func (QueryLogType) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (QueryLogType) EnumValues added in v0.31.0

func (QueryLogType) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (QueryLogType) IsValid

func (x QueryLogType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (QueryLogType) MarshalText

func (x QueryLogType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (QueryLogType) String

func (x QueryLogType) String() string

String implements the Stringer interface.

func (*QueryLogType) UnmarshalText

func (x *QueryLogType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type RateLimit added in v0.31.0

type RateLimit struct {
	// Enable per-client DNS rate limiting.
	Enable bool `default:"false" yaml:"enable"`
	// Sustained query rate limit in queries per second per client.
	Rate uint `default:"0" yaml:"rate"`
	// Token bucket capacity; queries above this burst are dropped. Defaults to rate × 2.
	Burst uint `default:"0" yaml:"burst"`
	// Prefix length used to aggregate IPv4 client addresses into a single bucket.
	IPv4Prefix uint8 `default:"32" yaml:"ipv4Prefix"`
	// Prefix length used to aggregate IPv6 client addresses into a single bucket.
	IPv6Prefix uint8 `default:"64" yaml:"ipv6Prefix"`
	// CIDRs or IPs that are never rate-limited.
	Allowlist []string `yaml:"allowlist"`
	// contains filtered or unexported fields
}

RateLimit configures per-client rate limiting at the head of the resolver chain.

func (*RateLimit) IsEnabled added in v0.31.0

func (c *RateLimit) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*RateLimit) LogConfig added in v0.31.0

func (c *RateLimit) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

func (*RateLimit) ParsedAllowlist added in v0.31.0

func (c *RateLimit) ParsedAllowlist() []*net.IPNet

ParsedAllowlist returns the parsed CIDR list populated by validate.

func (*RateLimit) ValidateForTest added in v0.31.0

func (c *RateLimit) ValidateForTest() error

ValidateForTest exposes validate for cross-package tests. Internal package callers should use the unexported validate.

type RebindingProtection added in v0.32.0

type RebindingProtection struct {
	// Enable DNS rebinding protection for answers from the general upstream resolvers.
	Enable bool `yaml:"enable"`
	// Domains (including their subdomains) that may resolve to non-public IPs (split-horizon DNS).
	AllowedDomains []string `yaml:"allowedDomains"`
	// contains filtered or unexported fields
}

RebindingProtection drops answers from the general upstream resolvers that contain private, loopback, link-local or unspecified IPs (DNS rebinding protection).

func (*RebindingProtection) IsEnabled added in v0.32.0

func (c *RebindingProtection) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*RebindingProtection) LogConfig added in v0.32.0

func (c *RebindingProtection) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

func (*RebindingProtection) NormalizedAllowedDomains added in v0.32.0

func (c *RebindingProtection) NormalizedAllowedDomains() []string

NormalizedAllowedDomains returns the allowlist entries in canonical form (lowercase, no trailing dot) — the form resolvers must match against. validate caches the result; configs that were never validated (e.g. hand-built in tests) are normalized on the fly.

type Redis

type Redis struct {
	// Server address and port (e.g. `localhost:6379`), a unix socket path (e.g. `/var/run/redis/redis.sock`),
	// or the sentinel master name when sentinel is used. An address starting with `/` is treated as a unix socket.
	Address string `yaml:"address"`
	// Redis username (if authentication is required).
	Username string `default:"" yaml:"username"`
	// Redis password (if authentication is required).
	Password Secret `default:"" yaml:"password"`
	// Redis database index to use.
	Database int `default:"0" yaml:"database"`
	// If true, blocky will not start when the Redis connection cannot be established.
	Required bool `default:"false" yaml:"required"`
	// Maximum number of connection attempts before giving up.
	ConnectionAttempts int `default:"3" yaml:"connectionAttempts"`
	// Delay between consecutive connection attempts.
	ConnectionCooldown Duration `default:"1s" yaml:"connectionCooldown"`
	// Sentinel username (if sentinel authentication is required).
	SentinelUsername string `default:"" yaml:"sentinelUsername"`
	// Sentinel password (if sentinel authentication is required).
	SentinelPassword Secret `default:"" yaml:"sentinelPassword"`
	// List of Redis Sentinel host:port addresses; enables sentinel mode when non-empty.
	SentinelAddresses []string `yaml:"sentinelAddresses"`
}

Redis configuration for the redis connection

func (*Redis) IsEnabled

func (c *Redis) IsEnabled() bool

IsEnabled implements `config.Configurable`

func (*Redis) LogConfig

func (c *Redis) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`

type RewriterConfig

type RewriterConfig struct {
	// Domain rewrite rules applied before resolution; keys are rewritten to their values.
	Rewrite map[string]string `yaml:"rewrite"`
	// If true, the original query is sent upstream when the mapped resolver returns an empty answer.
	FallbackUpstream bool `default:"false" yaml:"fallbackUpstream"`
}

RewriterConfig custom DNS configuration

func (*RewriterConfig) IsEnabled

func (c *RewriterConfig) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*RewriterConfig) LogConfig

func (c *RewriterConfig) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

func (*RewriterConfig) NormalizeRewrites added in v0.28.0

func (c *RewriterConfig) NormalizeRewrites()

NormalizeRewrites normalizes the rewrite keys to lowercase

type SUDN

type SUDN struct {
	// These are "recommended for private use" but not mandatory.
	// If a user wishes to use one, it will most likely be via conditional
	// upstream or custom DNS, which come before SUDN in the resolver chain.
	// Thus defaulting to `true` and returning NXDOMAIN here should not conflict.
	RFC6762AppendixG bool `default:"true" yaml:"rfc6762-appendixG"`
	// Set to false to completely disable Special Use Domain Name blocking (not recommended for remote upstreams).
	Enable bool `default:"true" yaml:"enable"`
}

SUDN configuration for Special Use Domain Names

func (*SUDN) IsEnabled

func (c *SUDN) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*SUDN) LogConfig

func (c *SUDN) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type Schedule added in v0.30.0

type Schedule struct {
	// Start time in HH:MM format; omit together with end for an all-day schedule.
	Start string `yaml:"start"`
	// End time in HH:MM format; if before start, the window is overnight (e.g. 22:00 to 06:00).
	End string `yaml:"end"`
	// Days of the week this schedule is active (mon, tue, wed, thu, fri, sat, sun).
	Weekdays []Weekday `yaml:"weekdays"`
	// contains filtered or unexported fields
}

Schedule defines a time-based schedule for blocking rules.

func (*Schedule) Compile added in v0.30.0

func (s *Schedule) Compile()

Compile pre-parses Start/End and builds weekdayMask. Called automatically by validate(); callers that construct a Schedule without validate() must call this before IsActive.

func (*Schedule) IsActive added in v0.30.0

func (s *Schedule) IsActive(now time.Time) bool

IsActive returns true if the schedule is active at the given time.

type Secret added in v0.31.0

type Secret string

Secret is a string config value that may be provided inline or, when prefixed with `file:` (or `file://`), read from the named file. Its String, MarshalText and MarshalYAML implementations redact the value so it can't leak through logging or config serialization.

func (Secret) MarshalText added in v0.31.0

func (s Secret) MarshalText() ([]byte, error)

MarshalText implements `encoding.TextMarshaler`, redacting the value.

func (Secret) MarshalYAML added in v0.31.0

func (s Secret) MarshalYAML() (any, error)

MarshalYAML implements `yaml.Marshaler`, redacting the value. gopkg.in/yaml honors this interface but not `encoding.TextMarshaler`, so MarshalText alone would let a `yaml.Marshal` of the config emit the raw secret.

func (Secret) Reveal added in v0.31.0

func (s Secret) Reveal() string

Reveal returns the real secret value.

func (Secret) String added in v0.31.0

func (s Secret) String() string

String implements `fmt.Stringer`, redacting the value.

func (*Secret) UnmarshalYAML added in v0.31.0

func (s *Secret) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements YAML unmarshalling with `file:`/`file://` support.

type SourceLoading

type SourceLoading struct {
	Init `yaml:",inline"`

	// Maximum number of sources downloaded and processed concurrently (default: 4).
	Concurrency uint `default:"4" yaml:"concurrency"`
	// Maximum parse errors per source before the source is considered invalid; -1 disables the limit.
	MaxErrorsPerSource int `default:"5" yaml:"maxErrorsPerSource"`
	// How often sources are reloaded; a value of 0 or less disables periodic refresh (default: 4h).
	RefreshPeriod Duration `default:"4h" yaml:"refreshPeriod"`
	// HTTP(S) download settings for remote sources.
	Downloads Downloader `yaml:"downloads"`
}

func (*SourceLoading) LogConfig

func (c *SourceLoading) LogConfig(logger *logrus.Entry)

func (*SourceLoading) StartPeriodicRefresh

func (c *SourceLoading) StartPeriodicRefresh(
	ctx context.Context, refresh func(context.Context) error, logErr func(error),
) error

type Statistics added in v0.32.0

type Statistics struct {
	// If true, enables in-memory statistics collection and the /api/stats endpoint.
	Enable bool `default:"false" yaml:"enable"`
}

Statistics contains the config for the in-memory statistics subsystem.

func (*Statistics) IsEnabled added in v0.32.0

func (c *Statistics) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*Statistics) LogConfig added in v0.32.0

func (c *Statistics) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type TLSVersion

type TLSVersion int // values MUST match `tls.VersionTLS*`

TLSVersion represents a TLS protocol version. ENUM( 1.0 = 769 1.1 1.2 1.3 )

const (
	// TLSVersion10 is a TLSVersion of type 1.0.
	TLSVersion10 TLSVersion = iota + 769
	// TLSVersion11 is a TLSVersion of type 1.1.
	TLSVersion11
	// TLSVersion12 is a TLSVersion of type 1.2.
	TLSVersion12
	// TLSVersion13 is a TLSVersion of type 1.3.
	TLSVersion13
)

func ParseTLSVersion

func ParseTLSVersion(name string) (TLSVersion, error)

ParseTLSVersion attempts to convert a string to a TLSVersion.

func TLSVersionValues

func TLSVersionValues() []TLSVersion

TLSVersionValues returns a list of the values for TLSVersion

func (*TLSVersion) AppendText added in v0.28.0

func (x *TLSVersion) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (TLSVersion) EnumDescriptions added in v0.31.0

func (TLSVersion) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (TLSVersion) EnumValues added in v0.31.0

func (TLSVersion) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (TLSVersion) IsValid

func (x TLSVersion) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (TLSVersion) MarshalText

func (x TLSVersion) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (TLSVersion) String

func (x TLSVersion) String() string

String implements the Stringer interface.

func (*TLSVersion) UnmarshalText

func (x *TLSVersion) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type Upstream

type Upstream struct {
	Net        NetProtocol
	Host       string
	Port       uint16
	Path       string
	CommonName string // Common Name to use for certificate verification; optional. "" uses .Host

	// DNS stamp metadata (optional) - only populated when parsing DNS stamps
	CertificateFingerprints []CertificateFingerprint // SHA256 fingerprints for TLS certificate pinning
	IPs                     []net.IP                 // IPs from the DNS stamp (addr + bootstrap IPs) for bootstrapping
}

Upstream is the definition of external DNS server

func ParseUpstream

func ParseUpstream(upstream string) (Upstream, error)

ParseUpstream creates new Upstream from passed string in format net:host[:port][/path][#commonname] or DNS Stamp format: sdns://...

func (*Upstream) IsDefault

func (u *Upstream) IsDefault() bool

IsDefault returns true if u is the default value

func (Upstream) String

func (u Upstream) String() string

String returns the string representation of u

func (*Upstream) UnmarshalText

func (u *Upstream) UnmarshalText(data []byte) error

UnmarshalText implements `encoding.TextUnmarshaler`.

type UpstreamGroup

type UpstreamGroup struct {
	Upstreams

	Name string // group name
}

UpstreamGroup represents the config for one group (upstream branch)

func NewUpstreamGroup

func NewUpstreamGroup(name string, cfg Upstreams, upstreams []Upstream) UpstreamGroup

NewUpstreamGroup creates an UpstreamGroup with the given name and upstreams.

The upstreams from `cfg.Groups` are ignored.

func (*UpstreamGroup) GroupUpstreams

func (c *UpstreamGroup) GroupUpstreams() []Upstream

func (*UpstreamGroup) IsEnabled

func (c *UpstreamGroup) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*UpstreamGroup) LogConfig

func (c *UpstreamGroup) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type UpstreamGroups

type UpstreamGroups map[string][]Upstream

type UpstreamStrategy

type UpstreamStrategy uint8

UpstreamStrategy upstream server usage strategy ENUM( parallel_best // Picks 2 random weighted resolvers per query and returns the fastest answer (default). strict // Queries upstreams in strict order; the next is tried only if the previous fails. random // Picks one random weighted resolver per query; another is tried on failure. )

const (
	// UpstreamStrategyParallelBest is a UpstreamStrategy of type Parallel_best.
	// Picks 2 random weighted resolvers per query and returns the fastest answer (default).
	UpstreamStrategyParallelBest UpstreamStrategy = iota
	// UpstreamStrategyStrict is a UpstreamStrategy of type Strict.
	// Queries upstreams in strict order; the next is tried only if the previous fails.
	UpstreamStrategyStrict
	// UpstreamStrategyRandom is a UpstreamStrategy of type Random.
	// Picks one random weighted resolver per query; another is tried on failure.
	UpstreamStrategyRandom
)

func ParseUpstreamStrategy

func ParseUpstreamStrategy(name string) (UpstreamStrategy, error)

ParseUpstreamStrategy attempts to convert a string to a UpstreamStrategy.

func UpstreamStrategyValues

func UpstreamStrategyValues() []UpstreamStrategy

UpstreamStrategyValues returns a list of the values for UpstreamStrategy

func (*UpstreamStrategy) AppendText added in v0.28.0

func (x *UpstreamStrategy) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (UpstreamStrategy) EnumDescriptions added in v0.31.0

func (UpstreamStrategy) EnumDescriptions() map[string]string

EnumDescriptions returns each enum value's description, taken from the `// comment` in the ENUM(...) declaration. Generated; do not edit.

func (UpstreamStrategy) EnumValues added in v0.31.0

func (UpstreamStrategy) EnumValues() []string

EnumValues returns the enum's accepted string values, used to build the JSON schema enum constraint. Generated; do not edit.

func (UpstreamStrategy) IsValid

func (x UpstreamStrategy) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (UpstreamStrategy) MarshalText

func (x UpstreamStrategy) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (UpstreamStrategy) String

func (x UpstreamStrategy) String() string

String implements the Stringer interface.

func (*UpstreamStrategy) UnmarshalText

func (x *UpstreamStrategy) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type Upstreams

type Upstreams struct {
	// Initialization strategy controlling when upstream resolvers are tested on startup.
	Init Init `yaml:"init"`
	// Timeout for upstream DNS connections; a value <= 0 is reset to the default.
	Timeout Duration `default:"2s" yaml:"timeout"`
	// Named groups of upstream DNS resolvers; the "default" group is required.
	Groups UpstreamGroups `yaml:"groups"`
	// Strategy for selecting which upstream(s) to use per query (parallel_best, random, strict).
	Strategy UpstreamStrategy `default:"parallel_best" yaml:"strategy"`
	// HTTP User-Agent header sent when connecting to DoH upstream servers.
	UserAgent string `yaml:"userAgent"`
	// QUIC-specific connection settings used when DoQ upstreams are configured.
	QUIC QUICConfig `yaml:"quic"`
}

Upstreams upstream servers configuration

func (*Upstreams) IsEnabled

func (c *Upstreams) IsEnabled() bool

IsEnabled implements `config.Configurable`.

func (*Upstreams) LogConfig

func (c *Upstreams) LogConfig(logger *logrus.Entry)

LogConfig implements `config.Configurable`.

type Weekday added in v0.30.0

type Weekday time.Weekday

Weekday represents a day of the week for schedule configuration.

func (Weekday) String added in v0.30.0

func (w Weekday) String() string

func (*Weekday) UnmarshalText added in v0.30.0

func (w *Weekday) UnmarshalText(data []byte) error

UnmarshalText implements `encoding.TextUnmarshaler`.

type ZoneFileDNS

type ZoneFileDNS struct {
	RRs CustomDNSMapping
	// contains filtered or unexported fields
}

func (*ZoneFileDNS) UnmarshalYAML

func (z *ZoneFileDNS) UnmarshalYAML(unmarshal func(any) error) error

Directories

Path Synopsis
Package migration helps with migrating deprecated config options.
Package migration helps with migrating deprecated config options.
Package schema embeds the generated config JSON schema and validates YAML config documents against it.
Package schema embeds the generated config JSON schema and validates YAML config documents against it.

Jump to

Keyboard shortcuts

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