blocklist

package
v0.8.10 Latest Latest
Warning

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

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

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

Documentation

Index

Constants

View Source
const 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

View Source
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

func ParseABP(r io.Reader) []string

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

func ParseDomainList(r io.Reader) []string

ParseDomainList parses a plain domain list with one domain per line. Blank lines and lines starting with '#' or '!' are skipped.

func ParseHostsFile

func ParseHostsFile(r io.Reader) []string

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 ListEntry

type ListEntry struct {
	URL    string
	Format string
}

ListEntry is a URL+format pair used to seed the initial list sources.

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"`
}

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

func (mgr *Manager) AddList(url, format string)

AddList adds a new list source at runtime. The list will be fetched on the next RefreshAll cycle.

func (*Manager) BlockDomain

func (mgr *Manager) BlockDomain(domain string) error

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

func (mgr *Manager) BlockedDomains() (blocks []string, allows []string)

BlockedDomains returns snapshots of custom block and allow rules.

func (*Manager) BlockingMode

func (mgr *Manager) BlockingMode() string

BlockingMode returns the active blocking mode ("nxdomain", "null_ip", or "custom_ip").

func (*Manager) CheckDomain

func (mgr *Manager) CheckDomain(domain string) bool

CheckDomain returns whether a domain is blocked without incrementing the blocked-query counter.

func (*Manager) CustomIP

func (mgr *Manager) CustomIP() string

CustomIP returns the IP address used when the blocking mode is "custom_ip".

func (*Manager) IsBlocked

func (mgr *Manager) IsBlocked(domain string) bool

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

func (mgr *Manager) RPZAction(domain string) *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

func (mgr *Manager) RemoveList(url string)

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

func (mgr *Manager) Start(ctx context.Context)

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) Stats

func (mgr *Manager) Stats() Stats

Stats returns aggregate blocklist statistics.

func (*Manager) UnblockDomain

func (mgr *Manager) UnblockDomain(domain string) error

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 NewMatcher

func NewMatcher() *Matcher

NewMatcher creates an empty Matcher ready for use.

func (*Matcher) AddExact

func (m *Matcher) AddExact(domain string)

AddExact adds an exact domain block rule.

func (*Matcher) AddWhitelist

func (m *Matcher) AddWhitelist(domain string)

AddWhitelist adds an exact whitelist rule. A whitelisted domain is never reported as blocked.

func (*Matcher) AddWildcard

func (m *Matcher) AddWildcard(domain string)

AddWildcard adds a wildcard block rule that matches the domain itself and all of its subdomains.

func (*Matcher) AddWildcardWhitelist

func (m *Matcher) AddWildcardWhitelist(domain string)

AddWildcardWhitelist adds a wildcard whitelist rule that exempts the domain and all of its subdomains from blocking.

func (*Matcher) Match

func (m *Matcher) Match(domain string) bool

Match returns true if the domain should be blocked.

The evaluation order is:

  1. Normalize the domain.
  2. Check the whitelist (exact match, then wildcard walk). If the domain is whitelisted, return false immediately.
  3. Check for an exact block match.
  4. Walk up the domain labels checking for wildcard block matches.

func (*Matcher) Remove

func (m *Matcher) Remove(domain string)

Remove removes a domain from all block lists (exact and wildcard) but does not touch the whitelist.

func (*Matcher) Reset

func (m *Matcher) Reset()

Reset clears all rules (blocks and whitelists).

func (*Matcher) Stats

func (m *Matcher) Stats() (exact, wildcards, whitelist int)

Stats returns the number of exact block rules, wildcard block rules, and whitelist rules (exact + wildcard combined).

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 NewRPZMatcher

func NewRPZMatcher() *RPZMatcher

NewRPZMatcher creates an empty RPZMatcher.

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

func ParseRPZ(r io.Reader) ([]RPZRule, error)

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.

Jump to

Keyboard shortcuts

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