Documentation
¶
Index ¶
- Constants
- Variables
- func ParseABP(r io.Reader) []string
- func ParseDomainList(r io.Reader) []string
- func ParseHostsFile(r io.Reader) []string
- type ListEntry
- type ListSource
- type Manager
- func (mgr *Manager) AddList(url, format string)
- func (mgr *Manager) BlockDomain(domain string) error
- func (mgr *Manager) BlockedDomains() (blocks []string, allows []string)
- func (mgr *Manager) BlockingMode() string
- func (mgr *Manager) CheckDomain(domain string) bool
- func (mgr *Manager) CustomIP() string
- func (mgr *Manager) IsBlocked(domain string) bool
- func (mgr *Manager) RPZAction(domain string) *RPZAction
- func (mgr *Manager) RefreshAll()
- func (mgr *Manager) RemoveList(url string)
- func (mgr *Manager) Sources() []*ListSource
- func (mgr *Manager) Start(ctx context.Context)
- func (mgr *Manager) Stats() Stats
- func (mgr *Manager) UnblockDomain(domain string) error
- type ManagerConfig
- type Matcher
- func (m *Matcher) AddExact(domain string)
- func (m *Matcher) AddWhitelist(domain string)
- func (m *Matcher) AddWildcard(domain string)
- func (m *Matcher) AddWildcardWhitelist(domain string)
- func (m *Matcher) Match(domain string) bool
- func (m *Matcher) Remove(domain string)
- func (m *Matcher) Reset()
- func (m *Matcher) Stats() (exact, wildcards, whitelist int)
- func (m *Matcher) Whitelisted(domain string) bool
- type RPZAction
- type RPZActionType
- type RPZMatcher
- type RPZRule
- type Stats
Constants ¶
const MaxCustomBlocklistEntries = 100_000
MaxCustomBlocklistEntries caps the size of the customBlocks and customAllows maps. /api/blocklist/{block,unblock} are authenticated admin endpoints, so unbounded growth is a defence-in-depth concern rather than a directly exploitable DoS — but a runaway automation script, a misconfigured "import every domain in a 100M-row CSV" integration, or a malicious operator with valid credentials could pin gigabytes of resolver RAM by spamming unique block calls. The matcher's exact/wildcard tries already incur per-entry allocation; 100k custom entries is far above any realistic operator workload (real custom-block lists in the wild are in the low thousands) and well below the threshold at which the map alone bloats GC pressure.
Variables ¶
var ErrCustomBlocklistFull = errors.New("custom blocklist is full")
ErrCustomBlocklistFull is returned by BlockDomain / UnblockDomain when the corresponding custom-rule map has reached MaxCustomBlocklistEntries. Callers (the admin API handlers) surface this as 507 Insufficient Storage so the operator sees the cap rather than a silent no-op.
Functions ¶
func ParseABP ¶
ParseABP parses an AdBlock Plus format blocklist. It extracts domains from rules of the form "||ads.example.com^". Other ABP rule types (element hiding, exceptions, etc.) are ignored.
func ParseDomainList ¶
ParseDomainList parses a plain domain list with one domain per line. Blank lines and lines starting with '#' or '!' are skipped.
func ParseHostsFile ¶
ParseHostsFile parses a hosts-format blocklist where each line maps an IP address to a domain (e.g. "0.0.0.0 ads.example.com"). Only lines whose first field is "0.0.0.0" or "127.0.0.1" are considered. Standard local entries (localhost, broadcasthost, etc.) are skipped.
Types ¶
type ListSource ¶
type ListSource struct {
URL string `json:"url"`
Format string `json:"format"` // "hosts", "domains", "abp"
Enabled bool `json:"enabled"`
LastUpdate time.Time `json:"last_update"`
RuleCount int `json:"rule_count"`
Error string `json:"error,omitempty"`
// contains filtered or unexported fields
}
ListSource describes a single remote blocklist and its current state.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager coordinates blocklist downloads, parsing, and matching. It is safe for concurrent use.
func NewManager ¶
func NewManager(cfg ManagerConfig, logger *slog.Logger) *Manager
NewManager creates a Manager from the supplied configuration. The manager is idle until Start is called.
func (*Manager) AddList ¶
AddList adds a new list source at runtime. The list will be fetched on the next RefreshAll cycle.
func (*Manager) BlockDomain ¶
BlockDomain adds a custom exact-match block rule that persists across refreshes. Returns ErrCustomBlocklistFull when the per-map cap is reached; the matcher is left untouched in that case so a retry after removing entries works as expected.
func (*Manager) BlockedDomains ¶ added in v0.6.3
BlockedDomains returns snapshots of custom block and allow rules.
func (*Manager) BlockingMode ¶
BlockingMode returns the active blocking mode ("nxdomain", "null_ip", or "custom_ip").
func (*Manager) CheckDomain ¶
CheckDomain returns whether a domain is blocked without incrementing the blocked-query counter.
func (*Manager) CustomIP ¶
CustomIP returns the IP address used when the blocking mode is "custom_ip".
func (*Manager) IsBlocked ¶
IsBlocked checks whether domain is blocked and, if so, increments the global blocked-query counter. It checks RPZ rules first, then the traditional matcher.
func (*Manager) RPZAction ¶
RPZAction returns the RPZ action for a domain, or nil if no RPZ rule matches.
func (*Manager) RefreshAll ¶
func (mgr *Manager) RefreshAll()
RefreshAll downloads and parses every enabled list source, rebuilds the matcher, and atomically swaps it in. Errors on individual lists are logged but do not prevent other lists from loading.
func (*Manager) RemoveList ¶
RemoveList removes a list source by URL.
func (*Manager) Sources ¶
func (mgr *Manager) Sources() []*ListSource
Sources returns a snapshot of the current list sources.
func (*Manager) Start ¶
Start runs the background refresh loop. It performs an immediate refresh and then re-downloads all lists on the configured interval. It blocks until ctx is cancelled.
func (*Manager) UnblockDomain ¶
UnblockDomain adds a custom whitelist rule that persists across refreshes. Returns ErrCustomBlocklistFull when the per-map cap is reached; the existing block (if any) is left intact in that case so the operator's view of the system stays consistent.
type ManagerConfig ¶
type ManagerConfig struct {
Lists []ListEntry
Whitelist []string
BlockingMode string // "nxdomain", "null_ip", "custom_ip"
CustomIP string
RefreshInterval time.Duration
}
ManagerConfig holds the configuration for a blocklist Manager.
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher is a concurrent-safe domain matching engine that supports exact domain blocking, wildcard blocking (domain + all subdomains), and whitelist overrides. Lookups are O(1) for exact matches and O(k) for wildcard walks where k is the number of labels in the queried domain.
func (*Matcher) AddWhitelist ¶
AddWhitelist adds an exact whitelist rule. A whitelisted domain is never reported as blocked.
func (*Matcher) AddWildcard ¶
AddWildcard adds a wildcard block rule that matches the domain itself and all of its subdomains.
func (*Matcher) AddWildcardWhitelist ¶
AddWildcardWhitelist adds a wildcard whitelist rule that exempts the domain and all of its subdomains from blocking.
func (*Matcher) Match ¶
Match returns true if the domain should be blocked.
The evaluation order is:
- Normalize the domain.
- Check the whitelist (exact match, then wildcard walk). If the domain is whitelisted, return false immediately.
- Check for an exact block match.
- Walk up the domain labels checking for wildcard block matches.
func (*Matcher) Remove ¶
Remove removes a domain from all block lists (exact and wildcard) but does not touch the whitelist.
func (*Matcher) Stats ¶
Stats returns the number of exact block rules, wildcard block rules, and whitelist rules (exact + wildcard combined).
func (*Matcher) Whitelisted ¶ added in v0.8.41
Whitelisted reports whether domain is exempted by a whitelist rule (exact, or wildcard on the domain or any parent). The Manager consults it before any blocking source, RPZ included, so an operator allow always wins.
type RPZAction ¶
type RPZAction struct {
Type RPZActionType
IP net.IP // set for LocalA / LocalAAAA
}
RPZAction holds the action type and optional data (e.g., redirect IP).
type RPZActionType ¶
type RPZActionType int
RPZActionType defines the action an RPZ rule specifies.
const ( // RPZActionNXDomain returns NXDOMAIN for the matched domain. RPZActionNXDomain RPZActionType = iota // RPZActionNODATA returns NODATA (empty answer, NOERROR) for the matched domain. RPZActionNODATA // RPZActionPassthru allows the query through (whitelist). RPZActionPassthru // RPZActionDrop silently drops the query. RPZActionDrop // RPZActionLocalA redirects to a custom IPv4 address. RPZActionLocalA // RPZActionLocalAAAA redirects to a custom IPv6 address. RPZActionLocalAAAA )
type RPZMatcher ¶
type RPZMatcher struct {
// contains filtered or unexported fields
}
RPZMatcher is a concurrent-safe matcher for RPZ rules. It supports exact domain matches and wildcard (subdomain) matches. Passthru (whitelist) rules are checked first.
func (*RPZMatcher) AddRule ¶
func (m *RPZMatcher) AddRule(rule RPZRule)
AddRule adds a parsed RPZ rule to the matcher.
func (*RPZMatcher) Match ¶
func (m *RPZMatcher) Match(qname string) *RPZAction
Match checks if qname matches any RPZ rule and returns the corresponding action. Passthru rules are checked first; if the domain is whitelisted, nil is returned. Returns nil if no rule matches.
func (*RPZMatcher) Stats ¶
func (m *RPZMatcher) Stats() (exact, wildcards, passthru int)
Stats returns the number of exact rules, wildcard rules, and passthru rules.
type RPZRule ¶
type RPZRule struct {
// Name is the domain pattern (e.g., "example.com" or "*.example.com").
Name string
// IsWildcard is true if the rule applies to all subdomains of the domain.
IsWildcard bool
// Action describes what to do when the rule matches.
Action RPZAction
}
RPZRule represents a single parsed RPZ rule.
func ParseRPZ ¶
ParseRPZ parses RPZ zone file content and returns a list of rules. Each line should be in the format:
<owner> <TTL?> <CLASS?> <RRTYPE> <RDATA>
Supported rule patterns:
- `example.com CNAME .` → NXDOMAIN
- `example.com CNAME *.` → NODATA
- `example.com CNAME rpz-passthru.` → PASSTHRU (whitelist)
- `example.com CNAME rpz-drop.` → DROP
- `example.com A 10.0.0.1` → redirect to IPv4
- `example.com AAAA ::1` → redirect to IPv6
- `*.example.com CNAME .` → NXDOMAIN for all subdomains
type Stats ¶
type Stats struct {
Enabled bool `json:"enabled"`
TotalRules int `json:"total_rules"`
ListCount int `json:"list_count"`
BlockedTotal int64 `json:"blocked_total"`
CustomBlocks int `json:"custom_blocks"`
CustomAllows int `json:"custom_allows"`
BlockingMode string `json:"blocking_mode"`
}
Stats holds aggregate blocklist statistics.