filter

package
v0.0.0-...-c1ed7b1 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2025 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Package filter contains the filter interface and its implementations along with types that combine them based on the settings in profile and filtering group.

Index

Constants

View Source
const (
	GeneralTXTSuffix       = ".sb.dns.adguard.com"
	AdultBlockingTXTSuffix = ".pc.dns.adguard.com"
)

Default safe-browsing host suffixes.

View Source
const (
	MaxIDLen = 128
	MinIDLen = 1
)

The maximum and minimum lengths of a filter ID.

View Source
const (
	MaxBlockedServiceIDLen = 64
	MinBlockedServiceIDLen = 1
)

The maximum and minimum lengths of a blocked service ID.

View Source
const (
	// MaxDayIntervalStartMinutes is the maximum value for [DayInterval.Start].
	MaxDayIntervalStartMinutes = 24*60 - 1

	// MaxDayIntervalEndMinutes is the maximum value for [DayInterval.End].
	MaxDayIntervalEndMinutes = 24 * 60
)
View Source
const MaxRuleTextRuneLen = 1024

MaxRuleTextRuneLen is the maximum length of a filter rule in runes.

View Source
const StoragePrefix = "filters/storage"

StoragePrefix is a common prefix for logging and refreshes of the filter storage.

TODO(a.garipov): Consider extracting these kinds of IDs to agdcache or some other package.

Variables

This section is empty.

Functions

This section is empty.

Types

type BlockedServiceID

type BlockedServiceID string

BlockedServiceID is the ID of a blocked service. While these are usually human-readable, clients should treat them as opaque strings.

When a request is blocked by the service blocker, this ID is used as the text of the blocking rule.

func NewBlockedServiceID

func NewBlockedServiceID(s string) (id BlockedServiceID, err error)

NewBlockedServiceID converts a simple string into a BlockedServiceID and makes sure that it's valid. This should be preferred to a simple type conversion.

type Config

type Config interface {
	// contains filtered or unexported methods
}

Config is the sum type of [Storage.ForConfig] configurations.

Acceptable implementations are:

type ConfigClient

type ConfigClient struct {
	// Custom is the configuration for identification or construction of a
	// custom filter for a client.  It must not be nil.
	Custom *ConfigCustom

	// Parental is the configuration for parental-control filtering.  It must
	// not be nil.
	Parental *ConfigParental

	// RuleList is the configuration for rule-list based filtering.  It must not
	// be nil.
	RuleList *ConfigRuleList

	// SafeBrowsing is the configuration for safe-browsing filtering.  It must
	// not be nil.
	SafeBrowsing *ConfigSafeBrowsing
}

ConfigClient is a Config for a client.

type ConfigCustom

type ConfigCustom struct {
	// Filter is the custom filter to use for this client, if any.  If
	// [ConfigCustom.Enabled] is true, Filter must not be nil.
	Filter Custom

	// Enabled shows whether the custom filters are applied at all.
	Enabled bool
}

ConfigCustom is the configuration for identification or construction of a custom filter for a client.

type ConfigGroup

type ConfigGroup struct {
	// Parental is the configuration for parental-control filtering.  It must
	// not be nil.
	Parental *ConfigParental

	// RuleList is the configuration for rule-list based filtering.  It must not
	// be nil.
	RuleList *ConfigRuleList

	// SafeBrowsing is the configuration for safe-browsing filtering.  It must
	// not be nil.
	SafeBrowsing *ConfigSafeBrowsing
}

ConfigGroup is a Config for a filtering group.

type ConfigParental

type ConfigParental struct {
	// PauseSchedule is the schedule for the pausing of the parental-control
	// filtering.  If it is nil, the parental-control filtering is never paused.
	// It is ignored if [ConfigParental.Enabled] is false.
	PauseSchedule *ConfigSchedule

	// BlockedServices are the IDs of the services blocked for this
	// parental-control configuration.  It is ignored if
	// [ConfigParental.Enabled] is false.
	BlockedServices []BlockedServiceID

	// Enabled shows whether the parental-control feature is enabled.
	Enabled bool

	// AdultBlockingEnabled shows whether the adult-blocking filtering should be
	// enforced.  It is ignored if [ConfigParental.Enabled] is false.
	AdultBlockingEnabled bool

	// SafeSearchGeneralEnabled shows whether the general safe-search filtering
	// should be enforced.  It is ignored if [ConfigParental.Enabled] is false.
	SafeSearchGeneralEnabled bool

	// SafeSearchYouTubeEnabled shows whether the YouTube safe-search filtering
	// should be enforced.  It is ignored if [ConfigParental.Enabled] is false.
	SafeSearchYouTubeEnabled bool
}

ConfigParental is the configuration for parental-control filtering.

type ConfigRuleList

type ConfigRuleList struct {
	// IDs are the IDs of the filtering rule lists used for this filtering
	// configuration.  They are ignored if [ConfigRuleList.Enabled] is false.
	IDs []ID

	// Enabled shows whether the rule-list based filtering is enabled.
	Enabled bool
}

ConfigRuleList is the configuration for rule-list based filtering.

type ConfigSafeBrowsing

type ConfigSafeBrowsing struct {
	// Enabled shows whether the safe-browsing hashprefix-based filtering should
	// is enabled.
	Enabled bool

	// DangerousDomainsEnabled shows whether the dangerous-domains safe-browsing
	// filtering should be enforced.  It is ignored if
	// [ConfigSafeBrowsing.Enabled] is false.
	DangerousDomainsEnabled bool

	// NewlyRegisteredDomainsEnabled shows whether the newly-registered domains
	// safe-browsing filtering should be enforced.  It is ignored if
	// [ConfigSafeBrowsing.Enabled] is false.
	NewlyRegisteredDomainsEnabled bool
}

ConfigSafeBrowsing is the configuration for safe-browsing filtering.

type ConfigSchedule

type ConfigSchedule struct {
	// Week is the parental protection schedule for every day of the week.  It
	// must not be nil.
	Week *WeeklySchedule

	// TimeZone is the profile's time zone.  It must not be nil.
	TimeZone *agdtime.Location
}

ConfigSchedule is the schedule of a client's parental protection. All fields must not be nil.

func (*ConfigSchedule) Contains

func (s *ConfigSchedule) Contains(t time.Time) (ok bool)

Contains returns true if t is within the allowed schedule.

type Custom

type Custom interface {
	// DNSResult returns the result of applying the urlfilter DNS filtering
	// engine.  If the request is not filtered, DNSResult returns nil.
	DNSResult(
		ctx context.Context,
		clientIP netip.Addr,
		clientName string,
		host string,
		rrType dnsmsg.RRType,
		isAns bool,
	) (res *urlfilter.DNSResult)

	// Rules returns the rules used to create the filter.  rules must not be
	// modified.
	Rules() (rules []RuleText)
}

Custom is a custom filter for a client.

type DayInterval

type DayInterval struct {
	// Start is the inclusive start of the interval in minutes.  It must be
	// within the range from 00:00:00 (0) to 23:59:59
	// ([MaxDayIntervalStartMinutes]).
	Start uint16

	// End is the exclusive end of the interval in minutes.  It must be within
	// the range from 00:00:00 (0) to 00:00:00 of the next day
	// ([MaxDayIntervalEndMinutes]).
	End uint16
}

DayInterval is an interval within a single day. The interval is exclusive at the end. An empty DayInterval is zero-length.

func (*DayInterval) Validate

func (r *DayInterval) Validate() (err error)

Validate returns the day range validation errors, if any. A nil DayInterval is considered valid.

type Empty

type Empty struct{}

Empty is an Interface implementation that always returns nil.

func (Empty) FilterRequest

func (Empty) FilterRequest(_ context.Context, _ *Request) (r Result, err error)

FilterRequest implements the Interface interface for Empty.

func (Empty) FilterResponse

func (Empty) FilterResponse(_ context.Context, _ *Response) (r Result, err error)

FilterResponse implements the Interface interface for Empty.

type EmptyMetrics

type EmptyMetrics struct{}

EmptyMetrics is the implementation of the Metrics interface that does nothing.

func (EmptyMetrics) SetFilterStatus

func (EmptyMetrics) SetFilterStatus(_ context.Context, _ string, _ time.Time, _ int, _ error)

SetFilterStatus implements the Metrics interface for EmptyMetrics.

type HashMatcher

type HashMatcher interface {
	MatchByPrefix(ctx context.Context, host string) (hashes []string, matched bool, err error)
}

HashMatcher is the interface for a safe-browsing and adult-blocking hash matcher, which is used to respond to a TXT query based on the domain name.

type ID

type ID string

ID is the ID of a filter list. It is an opaque string.

const (
	// IDNone means that no filter were applied at all.
	IDNone ID = ""

	// IDAdGuardDNS is the special filter ID of the main AdGuard DNS
	// filtering-rule list.  For this list, rule statistics are collected.
	IDAdGuardDNS ID = "adguard_dns_filter"

	// IDAdultBlocking is the special shared filter ID used when a request was
	// filtered by the adult content blocking filter.
	IDAdultBlocking ID = "adult_blocking"

	// IDBlockedService is the shared filter ID used when a request was blocked
	// by the service blocker.
	IDBlockedService ID = "blocked_service"

	// IDCustom is the special shared filter ID used when a request was filtered
	// by a custom profile rule.
	IDCustom ID = "custom"

	// IDGeneralSafeSearch is the shared filter ID used when a request was
	// modified by the general safe search filter.
	IDGeneralSafeSearch ID = "general_safe_search"

	// IDNewRegDomains is the special shared filter ID used when a request was
	// filtered by the newly registered domains filter.
	IDNewRegDomains ID = "newly_registered_domains"

	// IDSafeBrowsing is the special shared filter ID used when a request was
	// filtered by the safe browsing filter.
	IDSafeBrowsing ID = "safe_browsing"

	// IDYoutubeSafeSearch is the special shared filter ID used when a request
	// was modified by the YouTube safe search filter.
	IDYoutubeSafeSearch ID = "youtube_safe_search"
)

Special ID values shared across the AdGuard DNS system.

NOTE: DO NOT change these as other parts of the system depend on these values.

TODO(a.garipov): Consider removing those that aren't used outside of the filter subpackages.

func NewID

func NewID(s string) (id ID, err error)

NewID converts a simple string into an ID and makes sure that it's valid. This should be preferred to a simple type conversion.

type Interface

type Interface interface {
	// FilterRequest filters a DNS request based on the information provided
	// about the request.  req must be valid.
	FilterRequest(ctx context.Context, req *Request) (r Result, err error)

	// FilterResponse filters a DNS response based on the information provided
	// about the response.  resp must be valid.
	FilterResponse(ctx context.Context, resp *Response) (r Result, err error)
}

Interface is the DNS request and response filter interface.

type Metrics

type Metrics interface {
	// SetFilterStatus sets the status of a filter by its id.  If err is not
	// nil, updTime and ruleCount are ignored.
	SetFilterStatus(
		ctx context.Context,
		id string,
		updTime time.Time,
		ruleCount int,
		err error,
	)
}

Metrics is the interface for metrics of filters.

type Request

type Request struct {
	// DNS is the original DNS request used to create filtered responses.  It
	// must not be nil and must have exactly one question.
	DNS *dns.Msg

	// Messages is used to create filtered responses for this request.  It must
	// not be nil.
	Messages *dnsmsg.Constructor

	// RemoteIP is the remote IP address of the client.
	RemoteIP netip.Addr

	// ClientName is the client name for rule-list filtering.
	ClientName string

	// Host is the lowercased, non-FQDN version of the hostname from the
	// question of the request.
	Host string

	// QType is the type of question for this request.
	QType dnsmsg.RRType

	// QClass is the class of question for this request.
	QClass dnsmsg.Class
}

Request contains information about a request being filtered.

type Response

type Response struct {
	// DNS is the original DNS response used to create filtered responses.  It
	// must not be nil and must have exactly one question.
	DNS *dns.Msg

	// RemoteIP is the remote IP address of the client.
	RemoteIP netip.Addr

	// ClientName is the client name for rule-list filtering.
	ClientName string
}

Response contains information about a response being filtered.

type Result

type Result interface {
	// MatchedRule returns data about the matched rule and its rule list.
	MatchedRule() (id ID, text RuleText)
	// contains filtered or unexported methods
}

Result is a sum type of all possible filtering actions. See the following types as implementations:

type ResultAllowed

type ResultAllowed struct {
	List ID
	Rule RuleText
}

ResultAllowed means that this request or response was allowed by an allowlist rule within the given filter list.

func (*ResultAllowed) MatchedRule

func (a *ResultAllowed) MatchedRule() (id ID, text RuleText)

MatchedRule implements the Result interface for *ResultAllowed.

type ResultBlocked

type ResultBlocked struct {
	List ID
	Rule RuleText
}

ResultBlocked means that this request or response was blocked by a blocklist rule within the given filter list.

func (*ResultBlocked) MatchedRule

func (b *ResultBlocked) MatchedRule() (id ID, text RuleText)

MatchedRule implements the Result interface for *ResultBlocked.

type ResultModifiedRequest

type ResultModifiedRequest struct {
	// Msg is the new, rewritten or modified request.
	Msg *dns.Msg

	// List is the ID of the filter list.
	List ID

	// Rule is the filtering rule that triggered the rewrite.
	Rule RuleText
}

ResultModifiedRequest means that this request was rewritten or modified by a rewrite rule within the given filter list.

func (*ResultModifiedRequest) Clone

Clone returns a deep clone of m with a new ID.

func (*ResultModifiedRequest) MatchedRule

func (m *ResultModifiedRequest) MatchedRule() (id ID, text RuleText)

MatchedRule implements the Result interface for *ResultModifiedRequest.

type ResultModifiedResponse

type ResultModifiedResponse struct {
	// Msg is the new, rewritten or modified response.
	Msg *dns.Msg

	// List is the ID of the filter list.
	List ID

	// Rule is the filtering rule that triggered the rewrite.
	Rule RuleText
}

ResultModifiedResponse means that this response was rewritten or modified by a rewrite rule within the given filter list.

func (*ResultModifiedResponse) Clone

Clone returns a deep clone of m.

func (*ResultModifiedResponse) CloneForReq

func (m *ResultModifiedResponse) CloneForReq(
	c *dnsmsg.Cloner,
	req *dns.Msg,
) (clone *ResultModifiedResponse)

CloneForReq returns a deep clone of m with Msg set as a reply to req, if any.

func (*ResultModifiedResponse) MatchedRule

func (m *ResultModifiedResponse) MatchedRule() (id ID, text RuleText)

MatchedRule implements the Result interface for *ResultModifiedResponse.

type RuleText

type RuleText string

RuleText is the text of a single rule within a rule-list filter.

func NewRuleText

func NewRuleText(s string) (t RuleText, err error)

NewRuleText converts a simple string into a RuleText and makes sure that it's valid. This should be preferred to a simple type conversion.

type Storage

type Storage interface {
	// ForConfig returns a filter created from the configuration.  If c is nil,
	// f is [filter.Empty].
	ForConfig(ctx context.Context, c Config) (f Interface)

	// HasListID returns true if id is known to the storage.
	HasListID(id ID) (ok bool)
}

Storage is the interface for filter storages that can build a filter based on a configuration.

type WeeklySchedule

type WeeklySchedule [7]*DayInterval

WeeklySchedule is a schedule for one week. The index is the same as time.Weekday values. That is, 0 is Sunday, 1 is Monday, etc. A nil DayInterval means that there is no schedule for this day.

Directories

Path Synopsis
Package custom contains filters made from custom filtering rules of clients.
Package custom contains filters made from custom filtering rules of clients.
Package filterstorage defines an interface for a storage of filters as well as the default implementation and the filter configuration.
Package filterstorage defines an interface for a storage of filters as well as the default implementation and the filter configuration.
Package hashprefix defines a storage of hashes of domain names used for filtering and serving TXT records with domain-name hashes.
Package hashprefix defines a storage of hashes of domain names used for filtering and serving TXT records with domain-name hashes.
internal
composite
Package composite implements a composite filter based on several types of filters and the logic of the filter application.
Package composite implements a composite filter based on several types of filters and the logic of the filter application.
filtertest
Package filtertest contains common constants and utilities for the internal filtering packages.
Package filtertest contains common constants and utilities for the internal filtering packages.
refreshable
Package refreshable defines the refreshable part of filters and indexes.
Package refreshable defines the refreshable part of filters and indexes.
rulelist
Package rulelist contains the implementation of the standard rule-list filter that wraps an urlfilter filtering-engine.
Package rulelist contains the implementation of the standard rule-list filter that wraps an urlfilter filtering-engine.
safesearch
Package safesearch contains the implementation of the safe-search filter that uses lists of DNS rewrite rules to enforce safe search.
Package safesearch contains the implementation of the safe-search filter that uses lists of DNS rewrite rules to enforce safe search.
serviceblock
Package serviceblock contains an implementation of a filter that blocks services using rule lists.
Package serviceblock contains an implementation of a filter that blocks services using rule lists.

Jump to

Keyboard shortcuts

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