text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
pprof:
enabled: true
port: 6060
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
parental_sensitivity: 0
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filtering:
filtering_enabled: true
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
protection_enabled: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
blocked_response_ttl: 10
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 26
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
log:
file: ""
max_backups: 0
max_size: 100
max_age: 3
compress: true
local_time: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v26/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 765 |
```go
//go:build !linux
package ipset
import (
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
)
func newManager(_ []string) (mgr Manager, err error) {
return nil, aghos.Unsupported("ipset")
}
``` | /content/code_sandbox/internal/ipset/ipset_others.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 58 |
```go
//go:build linux
package ipset
import (
"net"
"strings"
"testing"
"github.com/AdguardTeam/golibs/errors"
"github.com/digineo/go-ipset/v2"
"github.com/mdlayher/netlink"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ti-mo/netfilter"
)
// fakeConn is a fake ipsetConn for tests.
type fakeConn struct {
ipv4Header *ipset.HeaderPolicy
ipv4Entries *[]*ipset.Entry
ipv6Header *ipset.HeaderPolicy
ipv6Entries *[]*ipset.Entry
sets []props
}
// type check
var _ ipsetConn = (*fakeConn)(nil)
// Add implements the [ipsetConn] interface for *fakeConn.
func (c *fakeConn) Add(name string, entries ...*ipset.Entry) (err error) {
if strings.Contains(name, "ipv4") {
*c.ipv4Entries = append(*c.ipv4Entries, entries...)
return nil
} else if strings.Contains(name, "ipv6") {
*c.ipv6Entries = append(*c.ipv6Entries, entries...)
return nil
}
return errors.Error("test: ipset not found")
}
// Close implements the [ipsetConn] interface for *fakeConn.
func (c *fakeConn) Close() (err error) {
return nil
}
// Header implements the [ipsetConn] interface for *fakeConn.
func (c *fakeConn) Header(_ string) (_ *ipset.HeaderPolicy, _ error) {
return nil, nil
}
// listAll implements the [ipsetConn] interface for *fakeConn.
func (c *fakeConn) listAll() (sets []props, err error) {
return c.sets, nil
}
func TestManager_Add(t *testing.T) {
ipsetConf := []string{
"example.com,example.net/ipv4set",
"example.org,example.biz/ipv6set",
}
var ipv4Entries []*ipset.Entry
var ipv6Entries []*ipset.Entry
fakeDial := func(
pf netfilter.ProtoFamily,
conf *netlink.Config,
) (conn ipsetConn, err error) {
return &fakeConn{
ipv4Header: &ipset.HeaderPolicy{
Family: ipset.NewUInt8Box(uint8(netfilter.ProtoIPv4)),
},
ipv4Entries: &ipv4Entries,
ipv6Header: &ipset.HeaderPolicy{
Family: ipset.NewUInt8Box(uint8(netfilter.ProtoIPv6)),
},
ipv6Entries: &ipv6Entries,
sets: []props{{
name: "ipv4set",
family: netfilter.ProtoIPv4,
}, {
name: "ipv6set",
family: netfilter.ProtoIPv6,
}},
}, nil
}
m, err := newManagerWithDialer(ipsetConf, fakeDial)
require.NoError(t, err)
ip4 := net.IP{1, 2, 3, 4}
ip6 := net.IP{
0x12, 0x34, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x56, 0x78,
}
n, err := m.Add("example.net", []net.IP{ip4}, nil)
require.NoError(t, err)
assert.Equal(t, 1, n)
require.Len(t, ipv4Entries, 1)
gotIP4 := ipv4Entries[0].IP.Value
assert.Equal(t, ip4, gotIP4)
n, err = m.Add("example.biz", nil, []net.IP{ip6})
require.NoError(t, err)
assert.Equal(t, 1, n)
require.Len(t, ipv6Entries, 1)
gotIP6 := ipv6Entries[0].IP.Value
assert.Equal(t, ip6, gotIP6)
err = m.Close()
assert.NoError(t, err)
}
// ipsetPropsSink is the typed sink for benchmark results.
var ipsetPropsSink []props
func BenchmarkManager_LookupHost(b *testing.B) {
propsLong := []props{{
name: "example.com",
family: netfilter.ProtoIPv4,
}}
propsShort := []props{{
name: "example.net",
family: netfilter.ProtoIPv4,
}}
m := &manager{
domainToIpsets: map[string][]props{
"": propsLong,
"example.net": propsShort,
},
}
b.Run("long", func(b *testing.B) {
const name = "a.very.long.domain.name.inside.the.domain.example.com"
for range b.N {
ipsetPropsSink = m.lookupHost(name)
}
require.Equal(b, propsLong, ipsetPropsSink)
})
b.Run("short", func(b *testing.B) {
const name = "example.net"
for range b.N {
ipsetPropsSink = m.lookupHost(name)
}
require.Equal(b, propsShort, ipsetPropsSink)
})
}
``` | /content/code_sandbox/internal/ipset/ipset_linux_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,190 |
```go
package filtering
// SafeSearch interface describes a service for search engines hosts rewrites.
type SafeSearch interface {
// CheckHost checks host with safe search filter. CheckHost must be safe
// for concurrent use. qtype must be either [dns.TypeA] or [dns.TypeAAAA].
CheckHost(host string, qtype uint16) (res Result, err error)
// Update updates the configuration of the safe search filter. Update must
// be safe for concurrent use. An implementation of Update may ignore some
// fields, but it must document which.
Update(conf SafeSearchConfig) (err error)
}
// SafeSearchConfig is a struct with safe search related settings.
type SafeSearchConfig struct {
// Enabled indicates if safe search is enabled entirely.
Enabled bool `yaml:"enabled" json:"enabled"`
// Services flags. Each flag indicates if the corresponding service is
// enabled or disabled.
Bing bool `yaml:"bing" json:"bing"`
DuckDuckGo bool `yaml:"duckduckgo" json:"duckduckgo"`
Ecosia bool `yaml:"ecosia" json:"ecosia"`
Google bool `yaml:"google" json:"google"`
Pixabay bool `yaml:"pixabay" json:"pixabay"`
Yandex bool `yaml:"yandex" json:"yandex"`
YouTube bool `yaml:"youtube" json:"youtube"`
}
// checkSafeSearch checks host with safe search engine. Matches
// [hostChecker.check].
func (d *DNSFilter) checkSafeSearch(
host string,
qtype uint16,
setts *Settings,
) (res Result, err error) {
if d.safeSearch == nil || !setts.ProtectionEnabled || !setts.SafeSearchEnabled {
return Result{}, nil
}
clientSafeSearch := setts.ClientSafeSearch
if clientSafeSearch != nil {
return clientSafeSearch.CheckHost(host, qtype)
}
return d.safeSearch.CheckHost(host, qtype)
}
``` | /content/code_sandbox/internal/filtering/safesearch.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 432 |
```go
//go:build linux
package ipset
import (
"bytes"
"fmt"
"net"
"strings"
"sync"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/digineo/go-ipset/v2"
"github.com/mdlayher/netlink"
"github.com/ti-mo/netfilter"
"golang.org/x/sys/unix"
)
// How to test on a real Linux machine:
//
// 1. Run "sudo ipset create example_set hash:ip family ipv4".
//
// 2. Run "sudo ipset list example_set". The Members field should be empty.
//
// 3. Add the line "example.com/example_set" to your AdGuardHome.yaml.
//
// 4. Start AdGuardHome.
//
// 5. Make requests to example.com and its subdomains.
//
// 6. Run "sudo ipset list example_set". The Members field should contain the
// resolved IP addresses.
// newManager returns a new Linux ipset manager.
func newManager(ipsetConf []string) (set Manager, err error) {
return newManagerWithDialer(ipsetConf, defaultDial)
}
// defaultDial is the default netfilter dialing function.
func defaultDial(pf netfilter.ProtoFamily, conf *netlink.Config) (conn ipsetConn, err error) {
c, err := ipset.Dial(pf, conf)
if err != nil {
return nil, err
}
return &queryConn{c}, nil
}
// queryConn is the [ipsetConn] implementation with listAll method, which
// returns the list of properties of all available ipsets.
type queryConn struct {
*ipset.Conn
}
// type check
var _ ipsetConn = (*queryConn)(nil)
// listAll returns the list of properties of all available ipsets.
//
// TODO(s.chzhen): Use path_to_url
func (qc *queryConn) listAll() (sets []props, err error) {
msg, err := netfilter.MarshalNetlink(
netfilter.Header{
// The family doesn't seem to matter. See TODO on parseIpsetConfig.
Family: qc.Conn.Family,
SubsystemID: netfilter.NFSubsysIPSet,
MessageType: netfilter.MessageType(ipset.CmdList),
Flags: netlink.Request | netlink.Dump,
},
[]netfilter.Attribute{{
Type: uint16(ipset.AttrProtocol),
Data: []byte{ipset.Protocol},
}},
)
if err != nil {
return nil, fmt.Errorf("marshaling netlink msg: %w", err)
}
// We assume it's OK to call a method of an unexported type
// [ipset.connector], since there is no negative effects.
ms, err := qc.Conn.Conn.Query(msg)
if err != nil {
return nil, fmt.Errorf("querying netlink msg: %w", err)
}
for i, s := range ms {
p := props{}
err = p.unmarshalMessage(s)
if err != nil {
return nil, fmt.Errorf("unmarshaling netlink msg at index %d: %w", i, err)
}
sets = append(sets, p)
}
return sets, nil
}
// ipsetConn is the ipset conn interface.
type ipsetConn interface {
Add(name string, entries ...*ipset.Entry) (err error)
Close() (err error)
Header(name string) (p *ipset.HeaderPolicy, err error)
listAll() (sets []props, err error)
}
// dialer creates an ipsetConn.
type dialer func(pf netfilter.ProtoFamily, conf *netlink.Config) (conn ipsetConn, err error)
// props contains one Linux Netfilter ipset properties.
type props struct {
// name of the ipset.
name string
// typeName of the ipset.
typeName string
// family of the IP addresses in the ipset.
family netfilter.ProtoFamily
// isPersistent indicates that ipset has no timeout parameter and all
// entries are added permanently.
isPersistent bool
}
// unmarshalMessage unmarshals netlink message and sets the properties of the
// ipset.
func (p *props) unmarshalMessage(msg netlink.Message) (err error) {
_, attrs, err := netfilter.UnmarshalNetlink(msg)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// By default ipset has no timeout parameter.
p.isPersistent = true
for _, a := range attrs {
p.parseAttribute(a)
}
return nil
}
// parseAttribute parses netfilter attribute and sets the name and family of
// the ipset.
func (p *props) parseAttribute(a netfilter.Attribute) {
switch ipset.AttributeType(a.Type) {
case ipset.AttrData:
p.parseAttrData(a)
case ipset.AttrSetName:
// Trim the null character.
p.name = string(bytes.Trim(a.Data, "\x00"))
case ipset.AttrTypeName:
p.typeName = string(bytes.Trim(a.Data, "\x00"))
case ipset.AttrFamily:
p.family = netfilter.ProtoFamily(a.Data[0])
default:
// Go on.
}
}
// parseAttrData parses attribute data and sets the timeout of the ipset.
func (p *props) parseAttrData(a netfilter.Attribute) {
for _, a := range a.Children {
switch ipset.AttributeType(a.Type) {
case ipset.AttrTimeout:
timeout := a.Uint32()
p.isPersistent = timeout == 0
default:
// Go on.
}
}
}
// manager is the Linux Netfilter ipset manager.
type manager struct {
nameToIpset map[string]props
domainToIpsets map[string][]props
dial dialer
// mu protects all properties below.
mu *sync.Mutex
// TODO(a.garipov): Currently, the ipset list is static, and we don't read
// the IPs already in sets, so we can assume that all incoming IPs are
// either added to all corresponding ipsets or not. When that stops being
// the case, for example if we add dynamic reconfiguration of ipsets, this
// map will need to become a per-ipset-name one.
addedIPs *container.MapSet[ipInIpsetEntry]
ipv4Conn ipsetConn
ipv6Conn ipsetConn
}
// ipInIpsetEntry is the type for entries in [manager.addIPs].
type ipInIpsetEntry struct {
ipsetName string
// TODO(schzen): Use netip.Addr.
ipArr [net.IPv6len]byte
}
// dialNetfilter establishes connections to Linux's netfilter module.
func (m *manager) dialNetfilter(conf *netlink.Config) (err error) {
// The kernel API does not actually require two sockets but package
// github.com/digineo/go-ipset does.
//
// TODO(a.garipov): Perhaps we can ditch package ipset altogether and just
// use packages netfilter and netlink.
m.ipv4Conn, err = m.dial(netfilter.ProtoIPv4, conf)
if err != nil {
return fmt.Errorf("dialing v4: %w", err)
}
m.ipv6Conn, err = m.dial(netfilter.ProtoIPv6, conf)
if err != nil {
return fmt.Errorf("dialing v6: %w", err)
}
return nil
}
// parseIpsetConfigLine parses one ipset configuration line.
func parseIpsetConfigLine(confStr string) (hosts, ipsetNames []string, err error) {
confStr = strings.TrimSpace(confStr)
hostsAndNames := strings.Split(confStr, "/")
if len(hostsAndNames) != 2 {
return nil, nil, fmt.Errorf("invalid value %q: expected one slash", confStr)
}
hosts = strings.Split(hostsAndNames[0], ",")
ipsetNames = strings.Split(hostsAndNames[1], ",")
if len(ipsetNames) == 0 {
return nil, nil, nil
}
for i := range ipsetNames {
ipsetNames[i] = strings.TrimSpace(ipsetNames[i])
if len(ipsetNames[i]) == 0 {
return nil, nil, fmt.Errorf("invalid value %q: empty ipset name", confStr)
}
}
for i := range hosts {
hosts[i] = strings.ToLower(strings.TrimSpace(hosts[i]))
}
return hosts, ipsetNames, nil
}
// parseIpsetConfig parses the ipset configuration and stores ipsets. It
// returns an error if the configuration can't be used.
func (m *manager) parseIpsetConfig(ipsetConf []string) (err error) {
// The family doesn't seem to matter when we use a header query, so query
// only the IPv4 one.
//
// TODO(a.garipov): Find out if this is a bug or a feature.
all, err := m.ipv4Conn.listAll()
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
currentlyKnown := map[string]props{}
for _, p := range all {
currentlyKnown[p.name] = p
}
for i, confStr := range ipsetConf {
var hosts, ipsetNames []string
hosts, ipsetNames, err = parseIpsetConfigLine(confStr)
if err != nil {
return fmt.Errorf("config line at idx %d: %w", i, err)
}
var ipsets []props
ipsets, err = m.ipsets(ipsetNames, currentlyKnown)
if err != nil {
return fmt.Errorf("getting ipsets from config line at idx %d: %w", i, err)
}
for _, host := range hosts {
m.domainToIpsets[host] = append(m.domainToIpsets[host], ipsets...)
}
}
return nil
}
// ipsetProps returns the properties of an ipset with the given name.
//
// Additional header data query. See path_to_url
//
// TODO(s.chzhen): Use *props.
func (m *manager) ipsetProps(name string) (p props, err error) {
// The family doesn't seem to matter when we use a header query, so
// query only the IPv4 one.
//
// TODO(a.garipov): Find out if this is a bug or a feature.
var res *ipset.HeaderPolicy
res, err = m.ipv4Conn.Header(name)
if err != nil {
return props{}, err
}
if res == nil || res.Family == nil {
return props{}, errors.Error("empty response or no family data")
}
family := netfilter.ProtoFamily(res.Family.Value)
if family != netfilter.ProtoIPv4 && family != netfilter.ProtoIPv6 {
return props{}, fmt.Errorf("unexpected ipset family %q", family)
}
typeName := res.TypeName.Get()
return props{
name: name,
typeName: typeName,
family: family,
isPersistent: false,
}, nil
}
// ipsets returns ipset properties of currently known ipsets. It also makes an
// additional ipset header data query if needed.
func (m *manager) ipsets(names []string, currentlyKnown map[string]props) (sets []props, err error) {
for _, n := range names {
p, ok := currentlyKnown[n]
if !ok {
return nil, fmt.Errorf("unknown ipset %q", n)
}
if p.family != netfilter.ProtoIPv4 && p.family != netfilter.ProtoIPv6 {
log.Debug("ipset: getting properties: %q %q unexpected ipset family %q",
p.name,
p.typeName,
p.family,
)
p, err = m.ipsetProps(n)
if err != nil {
return nil, fmt.Errorf("%q %q making header query: %w", p.name, p.typeName, err)
}
}
m.nameToIpset[n] = p
sets = append(sets, p)
}
return sets, nil
}
// newManagerWithDialer returns a new Linux ipset manager using the provided
// dialer.
func newManagerWithDialer(ipsetConf []string, dial dialer) (mgr Manager, err error) {
defer func() { err = errors.Annotate(err, "ipset: %w") }()
m := &manager{
mu: &sync.Mutex{},
nameToIpset: make(map[string]props),
domainToIpsets: make(map[string][]props),
dial: dial,
addedIPs: container.NewMapSet[ipInIpsetEntry](),
}
err = m.dialNetfilter(&netlink.Config{})
if err != nil {
if errors.Is(err, unix.EPROTONOSUPPORT) {
// The implementation doesn't support this protocol version. Just
// issue a warning.
log.Info("ipset: dialing netfilter: warning: %s", err)
return nil, nil
}
return nil, fmt.Errorf("dialing netfilter: %w", err)
}
err = m.parseIpsetConfig(ipsetConf)
if err != nil {
return nil, fmt.Errorf("getting ipsets: %w", err)
}
log.Debug("ipset: initialized")
return m, nil
}
// lookupHost find the ipsets for the host, taking subdomain wildcards into
// account.
func (m *manager) lookupHost(host string) (sets []props) {
// Search for matching ipset hosts starting with most specific domain.
// We could use a trie here but the simple, inefficient solution isn't
// that expensive: ~10 ns for TLD + SLD vs. ~140 ns for 10 subdomains on
// an AMD Ryzen 7 PRO 4750U CPU; ~120 ns vs. ~ 1500 ns on a Raspberry
// Pi's ARMv7 rev 4 CPU.
for i := 0; ; i++ {
host = host[i:]
sets = m.domainToIpsets[host]
if sets != nil {
return sets
}
i = strings.Index(host, ".")
if i == -1 {
break
}
}
// Check the root catch-all one.
return m.domainToIpsets[""]
}
// addIPs adds the IP addresses for the host to the ipset. set must be same
// family as set's family.
func (m *manager) addIPs(host string, set props, ips []net.IP) (n int, err error) {
if len(ips) == 0 {
return 0, nil
}
var entries []*ipset.Entry
var newAddedEntries []ipInIpsetEntry
for _, ip := range ips {
e := ipInIpsetEntry{
ipsetName: set.name,
}
copy(e.ipArr[:], ip.To16())
if m.addedIPs.Has(e) {
continue
}
entries = append(entries, ipset.NewEntry(ipset.EntryIP(ip)))
newAddedEntries = append(newAddedEntries, e)
}
n = len(entries)
if n == 0 {
return 0, nil
}
var conn ipsetConn
switch set.family {
case netfilter.ProtoIPv4:
conn = m.ipv4Conn
case netfilter.ProtoIPv6:
conn = m.ipv6Conn
default:
return 0, fmt.Errorf("unexpected family %s for ipset %q", set.family, set.name)
}
err = conn.Add(set.name, entries...)
if err != nil {
return 0, fmt.Errorf("adding %q%s to %q %q: %w", host, ips, set.name, set.typeName, err)
}
// Only add these to the cache once we're sure that all of them were
// actually sent to the ipset.
for _, e := range newAddedEntries {
s := m.nameToIpset[e.ipsetName]
if s.isPersistent {
m.addedIPs.Add(e)
}
}
return n, nil
}
// addToSets adds the IP addresses to the corresponding ipset.
func (m *manager) addToSets(
host string,
ip4s []net.IP,
ip6s []net.IP,
sets []props,
) (n int, err error) {
for _, set := range sets {
var nn int
switch set.family {
case netfilter.ProtoIPv4:
nn, err = m.addIPs(host, set, ip4s)
if err != nil {
return n, err
}
case netfilter.ProtoIPv6:
nn, err = m.addIPs(host, set, ip6s)
if err != nil {
return n, err
}
default:
return n, fmt.Errorf("%q %q unexpected family %q", set.name, set.typeName, set.family)
}
log.Debug("ipset: added %d ips to set %q %q", nn, set.name, set.typeName)
n += nn
}
return n, nil
}
// Add implements the [Manager] interface for *manager.
func (m *manager) Add(host string, ip4s, ip6s []net.IP) (n int, err error) {
m.mu.Lock()
defer m.mu.Unlock()
sets := m.lookupHost(host)
if len(sets) == 0 {
return 0, nil
}
log.Debug("ipset: found %d sets", len(sets))
return m.addToSets(host, ip4s, ip6s, sets)
}
// Close implements the [Manager] interface for *manager.
func (m *manager) Close() (err error) {
m.mu.Lock()
defer m.mu.Unlock()
var errs []error
// Close both and collect errors so that the errors from closing one
// don't interfere with closing the other.
err = m.ipv4Conn.Close()
if err != nil {
errs = append(errs, err)
}
err = m.ipv6Conn.Close()
if err != nil {
errs = append(errs, err)
}
return errors.Annotate(errors.Join(errs...), "closing ipsets: %w")
}
``` | /content/code_sandbox/internal/ipset/ipset_linux.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 4,106 |
```go
package filtering
import (
"encoding/json"
"net/http"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
)
// handleSafeSearchEnable is the handler for POST /control/safesearch/enable
// HTTP API.
//
// Deprecated: Use handleSafeSearchSettings.
func (d *DNSFilter) handleSafeSearchEnable(w http.ResponseWriter, r *http.Request) {
setProtectedBool(d.confMu, &d.conf.SafeSearchConf.Enabled, true)
d.conf.ConfigModified()
}
// handleSafeSearchDisable is the handler for POST /control/safesearch/disable
// HTTP API.
//
// Deprecated: Use handleSafeSearchSettings.
func (d *DNSFilter) handleSafeSearchDisable(w http.ResponseWriter, r *http.Request) {
setProtectedBool(d.confMu, &d.conf.SafeSearchConf.Enabled, false)
d.conf.ConfigModified()
}
// handleSafeSearchStatus is the handler for GET /control/safesearch/status
// HTTP API.
func (d *DNSFilter) handleSafeSearchStatus(w http.ResponseWriter, r *http.Request) {
var resp SafeSearchConfig
func() {
d.confMu.RLock()
defer d.confMu.RUnlock()
resp = d.conf.SafeSearchConf
}()
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// handleSafeSearchSettings is the handler for PUT /control/safesearch/settings
// HTTP API.
func (d *DNSFilter) handleSafeSearchSettings(w http.ResponseWriter, r *http.Request) {
req := &SafeSearchConfig{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
return
}
conf := *req
err = d.safeSearch.Update(conf)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "updating: %s", err)
return
}
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.SafeSearchConf = conf
}()
d.conf.ConfigModified()
aghhttp.OK(w)
}
``` | /content/code_sandbox/internal/filtering/safesearchhttp.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 450 |
```go
package filtering
import (
"fmt"
"net/netip"
"slices"
"strings"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// Legacy DNS rewrites
// LegacyRewrite is a single legacy DNS rewrite record.
//
// Instances of *LegacyRewrite must never be nil.
type LegacyRewrite struct {
// Domain is the domain pattern for which this rewrite should work.
Domain string `yaml:"domain"`
// Answer is the IP address, canonical name, or one of the special
// values: "A" or "AAAA".
Answer string `yaml:"answer"`
// IP is the IP address that should be used in the response if Type is
// dns.TypeA or dns.TypeAAAA.
IP netip.Addr `yaml:"-"`
// Type is the DNS record type: A, AAAA, or CNAME.
Type uint16 `yaml:"-"`
}
// equal returns true if the rw is equal to the other.
func (rw *LegacyRewrite) equal(other *LegacyRewrite) (ok bool) {
return rw.Domain == other.Domain && rw.Answer == other.Answer
}
// matchesQType returns true if the entry matches the question type qt.
func (rw *LegacyRewrite) matchesQType(qt uint16) (ok bool) {
// Add CNAMEs, since they match for all types requests.
if rw.Type == dns.TypeCNAME {
return true
}
// Reject types other than A and AAAA.
if qt != dns.TypeA && qt != dns.TypeAAAA {
return false
}
// If the types match or the entry is set to allow only the other type,
// include them.
return rw.Type == qt || rw.IP == netip.Addr{}
}
// normalize makes sure that the new or decoded entry is normalized with regards
// to domain name case, IP length, and so on.
//
// If rw is nil, it returns an errors.
func (rw *LegacyRewrite) normalize() (err error) {
if rw == nil {
return errors.Error("nil rewrite entry")
}
// TODO(a.garipov): Write a case-agnostic version of strings.HasSuffix and
// use it in matchDomainWildcard instead of using strings.ToLower
// everywhere.
rw.Domain = strings.ToLower(rw.Domain)
switch rw.Answer {
case "AAAA":
rw.IP = netip.Addr{}
rw.Type = dns.TypeAAAA
return nil
case "A":
rw.IP = netip.Addr{}
rw.Type = dns.TypeA
return nil
default:
// Go on.
}
ip, err := netip.ParseAddr(rw.Answer)
if err != nil {
log.Debug("normalizing legacy rewrite: %s", err)
rw.Type = dns.TypeCNAME
return nil
}
rw.IP = ip
if ip.Is4() {
rw.Type = dns.TypeA
} else {
rw.Type = dns.TypeAAAA
}
return nil
}
// isWildcard returns true if pat is a wildcard domain pattern.
func isWildcard(pat string) bool {
return len(pat) > 1 && pat[0] == '*' && pat[1] == '.'
}
// matchDomainWildcard returns true if host matches the wildcard pattern.
func matchDomainWildcard(host, wildcard string) (ok bool) {
return isWildcard(wildcard) && strings.HasSuffix(host, wildcard[1:])
}
// Compare is used to sort rewrites according to the following priority:
//
// 1. A and AAAA > CNAME;
// 2. wildcard > exact;
// 3. lower level wildcard > higher level wildcard;
func (rw *LegacyRewrite) Compare(b *LegacyRewrite) (res int) {
if rw.Type == dns.TypeCNAME {
if b.Type != dns.TypeCNAME {
return -1
}
} else if b.Type == dns.TypeCNAME {
return 1
}
if aIsWld, bIsWld := isWildcard(rw.Domain), isWildcard(b.Domain); aIsWld == bIsWld {
// Both are either wildcards or both aren't.
return len(b.Domain) - len(rw.Domain)
} else if aIsWld {
return 1
} else {
return -1
}
}
// prepareRewrites normalizes and validates all legacy DNS rewrites.
func (d *DNSFilter) prepareRewrites() (err error) {
for i, r := range d.conf.Rewrites {
err = r.normalize()
if err != nil {
return fmt.Errorf("at index %d: %w", i, err)
}
}
return nil
}
// findRewrites returns the list of matched rewrite entries. If rewrites are
// empty, but matched is true, the domain is found among the rewrite rules but
// not for this question type.
//
// The result priority is: CNAME, then A and AAAA; exact, then wildcard. If the
// host is matched exactly, wildcard entries aren't returned. If the host
// matched by wildcards, return the most specific for the question type.
func findRewrites(
entries []*LegacyRewrite,
host string,
qtype uint16,
) (rewrites []*LegacyRewrite, matched bool) {
for _, e := range entries {
if e.Domain != host && !matchDomainWildcard(host, e.Domain) {
continue
}
matched = true
if e.matchesQType(qtype) {
rewrites = append(rewrites, e)
}
}
if len(rewrites) == 0 {
return nil, matched
}
slices.SortFunc(rewrites, (*LegacyRewrite).Compare)
for i, r := range rewrites {
if isWildcard(r.Domain) {
// Don't use rewrites[:0], because we need to return at least one
// item here.
rewrites = rewrites[:max(1, i)]
break
}
}
return rewrites, matched
}
// setRewriteResult sets the Reason or IPList of res if necessary. res must not
// be nil.
func setRewriteResult(res *Result, host string, rewrites []*LegacyRewrite, qtype uint16) {
for _, rw := range rewrites {
if rw.Type == qtype && (qtype == dns.TypeA || qtype == dns.TypeAAAA) {
if rw.IP == (netip.Addr{}) {
// "A"/"AAAA" exception: allow getting from upstream.
res.Reason = NotFilteredNotFound
return
}
res.IPList = append(res.IPList, rw.IP)
log.Debug("rewrite: a/aaaa for %s is %s", host, rw.IP)
}
}
}
// cloneRewrites returns a deep copy of entries.
func cloneRewrites(entries []*LegacyRewrite) (clone []*LegacyRewrite) {
clone = make([]*LegacyRewrite, len(entries))
for i, rw := range entries {
clone[i] = &LegacyRewrite{
Domain: rw.Domain,
Answer: rw.Answer,
IP: rw.IP,
Type: rw.Type,
}
}
return clone
}
``` | /content/code_sandbox/internal/filtering/rewrites.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,602 |
```go
package filtering
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghrenameio"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
)
// filterDir is the subdirectory of a data directory to store downloaded
// filters.
const filterDir = "filters"
// FilterYAML represents a filter list in the configuration file.
//
// TODO(e.burkov): Investigate if the field ordering is important.
type FilterYAML struct {
Enabled bool
URL string // URL or a file path
Name string `yaml:"name"`
RulesCount int `yaml:"-"`
LastUpdated time.Time `yaml:"-"`
checksum uint32 // checksum of the file data
white bool
Filter `yaml:",inline"`
}
// Clear filter rules
func (filter *FilterYAML) unload() {
filter.RulesCount = 0
filter.checksum = 0
}
// Path to the filter contents
func (filter *FilterYAML) Path(dataDir string) string {
return filepath.Join(
dataDir,
filterDir,
strconv.FormatInt(int64(filter.ID), 10)+".txt")
}
// ensureName sets provided title or default name for the filter if it doesn't
// have name already.
func (filter *FilterYAML) ensureName(title string) {
if filter.Name != "" {
return
}
if title != "" {
filter.Name = title
return
}
filter.Name = fmt.Sprintf("List %d", filter.ID)
}
const (
// errFilterNotExist is returned from [filterSetProperties] when there are
// no lists with the desired URL to update.
//
// TODO(e.burkov): Use wherever the same error is needed.
errFilterNotExist errors.Error = "url doesn't exist"
// errFilterExists is returned from [filterSetProperties] when there is
// another filter having the same URL as the one updated.
//
// TODO(e.burkov): Use wherever the same error is needed.
errFilterExists errors.Error = "url already exists"
)
// filterSetProperties searches for the particular filter list by url and sets
// the values of newList to it, updating afterwards if needed. It returns true
// if the update was performed and the filtering engine restart is required.
func (d *DNSFilter) filterSetProperties(
listURL string,
newList FilterYAML,
isAllowlist bool,
) (shouldRestart bool, err error) {
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
filters := d.conf.Filters
if isAllowlist {
filters = d.conf.WhitelistFilters
}
i := slices.IndexFunc(filters, func(flt FilterYAML) bool { return flt.URL == listURL })
if i == -1 {
return false, errFilterNotExist
}
flt := &filters[i]
log.Debug(
"filtering: set name to %q, url to %s, enabled to %t for filter %s",
newList.Name,
newList.URL,
newList.Enabled,
flt.URL,
)
defer func(oldURL, oldName string, oldEnabled bool, oldUpdated time.Time, oldRulesCount int) {
if err != nil {
flt.URL = oldURL
flt.Name = oldName
flt.Enabled = oldEnabled
flt.LastUpdated = oldUpdated
flt.RulesCount = oldRulesCount
}
}(flt.URL, flt.Name, flt.Enabled, flt.LastUpdated, flt.RulesCount)
flt.Name = newList.Name
if flt.URL != newList.URL {
if d.filterExistsLocked(newList.URL) {
return false, errFilterExists
}
shouldRestart = true
flt.URL = newList.URL
flt.LastUpdated = time.Time{}
flt.unload()
}
if flt.Enabled != newList.Enabled {
flt.Enabled = newList.Enabled
shouldRestart = true
}
if flt.Enabled {
if shouldRestart {
// Download the filter contents.
shouldRestart, err = d.update(flt)
}
} else {
// TODO(e.burkov): The validation of the contents of the new URL is
// currently skipped if the rule list is disabled. This makes it
// possible to set a bad rules source, but the validation should still
// kick in when the filter is enabled. Consider changing this behavior
// to be stricter.
flt.unload()
}
return shouldRestart, err
}
// filterExists returns true if a filter with the same url exists in d. It's
// safe for concurrent use.
func (d *DNSFilter) filterExists(url string) (ok bool) {
d.conf.filtersMu.RLock()
defer d.conf.filtersMu.RUnlock()
r := d.filterExistsLocked(url)
return r
}
// filterExistsLocked returns true if d contains the filter with the same url.
// d.filtersMu is expected to be locked.
func (d *DNSFilter) filterExistsLocked(url string) (ok bool) {
for _, f := range d.conf.Filters {
if f.URL == url {
return true
}
}
for _, f := range d.conf.WhitelistFilters {
if f.URL == url {
return true
}
}
return false
}
// Add a filter
// Return FALSE if a filter with this URL exists
func (d *DNSFilter) filterAdd(flt FilterYAML) (err error) {
// Defer annotating to unlock sooner.
defer func() { err = errors.Annotate(err, "adding filter: %w") }()
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
// Check for duplicates.
if d.filterExistsLocked(flt.URL) {
return errFilterExists
}
if flt.white {
d.conf.WhitelistFilters = append(d.conf.WhitelistFilters, flt)
} else {
d.conf.Filters = append(d.conf.Filters, flt)
}
return nil
}
// Load filters from the disk
// And if any filter has zero ID, assign a new one
func (d *DNSFilter) loadFilters(array []FilterYAML) {
for i := range array {
filter := &array[i] // otherwise we're operating on a copy
if filter.ID == 0 {
newID := d.idGen.next()
log.Info("filtering: warning: filter at index %d has no id; assigning to %d", i, newID)
filter.ID = newID
}
if !filter.Enabled {
// No need to load a filter that is not enabled
continue
}
err := d.load(filter)
if err != nil {
log.Error("filtering: loading filter %d: %s", filter.ID, err)
}
}
}
func deduplicateFilters(filters []FilterYAML) (deduplicated []FilterYAML) {
urls := container.NewMapSet[string]()
lastIdx := 0
for _, filter := range filters {
if !urls.Has(filter.URL) {
urls.Add(filter.URL)
filters[lastIdx] = filter
lastIdx++
}
}
return filters[:lastIdx]
}
// tryRefreshFilters is like [refreshFilters], but backs down if the update is
// already going on.
//
// TODO(e.burkov): Get rid of the concurrency pattern which requires the
// [sync.Mutex.TryLock].
func (d *DNSFilter) tryRefreshFilters(block, allow, force bool) (updated int, isNetworkErr, ok bool) {
if ok = d.refreshLock.TryLock(); !ok {
return 0, false, false
}
defer d.refreshLock.Unlock()
updated, isNetworkErr = d.refreshFiltersIntl(block, allow, force)
return updated, isNetworkErr, ok
}
// listsToUpdate returns the slice of filter lists that could be updated.
func (d *DNSFilter) listsToUpdate(filters *[]FilterYAML, force bool) (toUpd []FilterYAML) {
now := time.Now()
d.conf.filtersMu.RLock()
defer d.conf.filtersMu.RUnlock()
for i := range *filters {
flt := &(*filters)[i] // otherwise we will be operating on a copy
if !flt.Enabled {
continue
}
if !force {
exp := flt.LastUpdated.Add(time.Duration(d.conf.FiltersUpdateIntervalHours) * time.Hour)
if now.Before(exp) {
continue
}
}
toUpd = append(toUpd, FilterYAML{
Filter: Filter{
ID: flt.ID,
},
URL: flt.URL,
Name: flt.Name,
checksum: flt.checksum,
})
}
return toUpd
}
func (d *DNSFilter) refreshFiltersArray(filters *[]FilterYAML, force bool) (int, []FilterYAML, []bool, bool) {
var updateFlags []bool // 'true' if filter data has changed
updateFilters := d.listsToUpdate(filters, force)
if len(updateFilters) == 0 {
return 0, nil, nil, false
}
failNum := 0
for i := range updateFilters {
uf := &updateFilters[i]
updated, err := d.update(uf)
updateFlags = append(updateFlags, updated)
if err != nil {
failNum++
log.Error("filtering: updating filter from url %q: %s\n", uf.URL, err)
continue
}
}
if failNum == len(updateFilters) {
return 0, nil, nil, true
}
updateCount := 0
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
for i := range updateFilters {
uf := &updateFilters[i]
updated := updateFlags[i]
for k := range *filters {
f := &(*filters)[k]
if f.ID != uf.ID || f.URL != uf.URL {
continue
}
f.LastUpdated = uf.LastUpdated
if !updated {
continue
}
log.Info(
"filtering: updated filter %d; rule count: %d (was %d)",
f.ID,
uf.RulesCount,
f.RulesCount,
)
f.Name = uf.Name
f.RulesCount = uf.RulesCount
f.checksum = uf.checksum
updateCount++
}
}
return updateCount, updateFilters, updateFlags, false
}
// refreshFiltersIntl checks filters and updates them if necessary. If force is
// true, it ignores the filter.LastUpdated field value.
//
// Algorithm:
//
// 1. Get the list of filters to be updated. For each filter, run the download
// and checksum check operation. Store downloaded data in a temporary file
// inside data/filters directory
//
// 2. For each filter, if filter data hasn't changed, just set new update time
// on file. Otherwise, rename the temporary file (<temp> -> 1.txt). Note
// that this method works only on Unix systems. On Windows, don't pass
// files to filtering, pass the whole data.
//
// refreshFiltersIntl returns the number of updated filters. It also returns
// true if there was a network error and nothing could be updated.
//
// TODO(a.garipov, e.burkov): What the hell?
func (d *DNSFilter) refreshFiltersIntl(block, allow, force bool) (int, bool) {
updNum := 0
log.Debug("filtering: starting updating")
defer func() { log.Debug("filtering: finished updating, %d updated", updNum) }()
var lists []FilterYAML
var toUpd []bool
isNetErr := false
if block {
updNum, lists, toUpd, isNetErr = d.refreshFiltersArray(&d.conf.Filters, force)
}
if allow {
updNumAl, listsAl, toUpdAl, isNetErrAl := d.refreshFiltersArray(&d.conf.WhitelistFilters, force)
updNum += updNumAl
lists = append(lists, listsAl...)
toUpd = append(toUpd, toUpdAl...)
isNetErr = isNetErr || isNetErrAl
}
if isNetErr {
return 0, true
}
if updNum != 0 {
d.EnableFilters(false)
for i := range lists {
uf := &lists[i]
updated := toUpd[i]
if !updated {
continue
}
p := uf.Path(d.conf.DataDir)
err := os.Remove(p + ".old")
if err != nil {
log.Debug("filtering: removing old filter file %q: %s", p, err)
}
}
}
return updNum, false
}
// update refreshes filter's content and a/mtimes of it's file.
func (d *DNSFilter) update(filter *FilterYAML) (b bool, err error) {
b, err = d.updateIntl(filter)
filter.LastUpdated = time.Now()
if !b {
chErr := os.Chtimes(
filter.Path(d.conf.DataDir),
filter.LastUpdated,
filter.LastUpdated,
)
if chErr != nil {
log.Error("filtering: os.Chtimes(): %s", chErr)
}
}
return b, err
}
// updateIntl updates the flt rewriting it's actual file. It returns true if
// the actual update has been performed.
func (d *DNSFilter) updateIntl(flt *FilterYAML) (ok bool, err error) {
log.Debug("filtering: downloading update for filter %d from %q", flt.ID, flt.URL)
var res *rulelist.ParseResult
// Change the default 0o600 permission to something more acceptable by end
// users.
//
// See path_to_url
tmpFile, err := aghrenameio.NewPendingFile(flt.Path(d.conf.DataDir), 0o644)
if err != nil {
return false, err
}
defer func() { err = d.finalizeUpdate(tmpFile, flt, res, err, ok) }()
r, err := d.reader(flt.URL)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return false, err
}
defer func() { err = errors.WithDeferred(err, r.Close()) }()
bufPtr := d.bufPool.Get()
defer d.bufPool.Put(bufPtr)
p := rulelist.NewParser()
res, err = p.Parse(tmpFile, r, *bufPtr)
return res.Checksum != flt.checksum && err == nil, err
}
// finalizeUpdate closes and gets rid of temporary file f with filter's content
// according to updated. It also saves new values of flt's name, rules number
// and checksum if succeeded.
func (d *DNSFilter) finalizeUpdate(
file aghrenameio.PendingFile,
flt *FilterYAML,
res *rulelist.ParseResult,
returned error,
updated bool,
) (err error) {
id := flt.ID
if !updated {
if returned == nil {
log.Debug("filtering: filter %d from url %q has no changes, skipping", id, flt.URL)
}
return errors.WithDeferred(returned, file.Cleanup())
}
log.Info("filtering: saving contents of filter %d into %q", id, flt.Path(d.conf.DataDir))
err = file.CloseReplace()
if err != nil {
return fmt.Errorf("finalizing update: %w", err)
}
rulesCount := res.RulesCount
log.Info("filtering: updated filter %d: %d bytes, %d rules", id, res.BytesWritten, rulesCount)
flt.ensureName(res.Title)
flt.checksum = res.Checksum
flt.RulesCount = rulesCount
return nil
}
// reader returns an io.ReadCloser reading filtering-rule list data form either
// a file on the filesystem or the filter's HTTP URL.
func (d *DNSFilter) reader(fltURL string) (r io.ReadCloser, err error) {
if !filepath.IsAbs(fltURL) {
r, err = d.readerFromURL(fltURL)
if err != nil {
return nil, fmt.Errorf("reading from url: %w", err)
}
return r, nil
}
r, err = os.Open(fltURL)
if err != nil {
return nil, fmt.Errorf("opening file: %w", err)
}
return r, nil
}
// readerFromURL returns an io.ReadCloser reading filtering-rule list data form
// the filter's URL.
func (d *DNSFilter) readerFromURL(fltURL string) (r io.ReadCloser, err error) {
resp, err := d.conf.HTTPClient.Get(fltURL)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("got status code %d, want %d", resp.StatusCode, http.StatusOK)
}
return resp.Body, nil
}
// loads filter contents from the file in dataDir
func (d *DNSFilter) load(flt *FilterYAML) (err error) {
fileName := flt.Path(d.conf.DataDir)
log.Debug("filtering: loading filter %d from %q", flt.ID, fileName)
file, err := os.Open(fileName)
if errors.Is(err, os.ErrNotExist) {
// Do nothing, file doesn't exist.
return nil
} else if err != nil {
return fmt.Errorf("opening filter file: %w", err)
}
defer func() { err = errors.WithDeferred(err, file.Close()) }()
st, err := file.Stat()
if err != nil {
return fmt.Errorf("getting filter file stat: %w", err)
}
log.Debug("filtering: file %q, id %d, length %d", fileName, flt.ID, st.Size())
bufPtr := d.bufPool.Get()
defer d.bufPool.Put(bufPtr)
p := rulelist.NewParser()
res, err := p.Parse(io.Discard, file, *bufPtr)
if err != nil {
return fmt.Errorf("parsing filter file: %w", err)
}
flt.ensureName(res.Title)
flt.RulesCount, flt.checksum, flt.LastUpdated = res.RulesCount, res.Checksum, st.ModTime()
return nil
}
func (d *DNSFilter) EnableFilters(async bool) {
d.conf.filtersMu.RLock()
defer d.conf.filtersMu.RUnlock()
d.enableFiltersLocked(async)
}
func (d *DNSFilter) enableFiltersLocked(async bool) {
filters := make([]Filter, 1, len(d.conf.Filters)+len(d.conf.WhitelistFilters)+1)
filters[0] = Filter{
ID: rulelist.URLFilterIDCustom,
Data: []byte(strings.Join(d.conf.UserRules, "\n")),
}
for _, filter := range d.conf.Filters {
if !filter.Enabled {
continue
}
filters = append(filters, Filter{
ID: filter.ID,
FilePath: filter.Path(d.conf.DataDir),
})
}
var allowFilters []Filter
for _, filter := range d.conf.WhitelistFilters {
if !filter.Enabled {
continue
}
allowFilters = append(allowFilters, Filter{
ID: filter.ID,
FilePath: filter.Path(d.conf.DataDir),
})
}
err := d.setFilters(filters, allowFilters, async)
if err != nil {
log.Error("filtering: enabling filters: %s", err)
}
d.SetEnabled(d.conf.FilteringEnabled)
}
``` | /content/code_sandbox/internal/filtering/filter.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 4,412 |
```go
package filtering
import (
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// DNSRewriteResult is the result of application of $dnsrewrite rules.
type DNSRewriteResult struct {
Response DNSRewriteResultResponse `json:",omitempty"`
RCode rules.RCode `json:",omitempty"`
}
// DNSRewriteResultResponse is the collection of DNS response records
// the server returns.
type DNSRewriteResultResponse map[rules.RRType][]rules.RRValue
// processDNSRewrites processes DNS rewrite rules in dnsr. It returns an empty
// result if dnsr is empty. Otherwise, the result will have either CanonName or
// DNSRewriteResult set. dnsr is expected to be non-empty.
func (d *DNSFilter) processDNSRewrites(dnsr []*rules.NetworkRule) (res Result) {
var rules []*ResultRule
dnsrr := &DNSRewriteResult{
Response: DNSRewriteResultResponse{},
}
for _, nr := range dnsr {
dr := nr.DNSRewrite
if dr.NewCNAME != "" {
// NewCNAME rules have a higher priority than other rules.
rules = []*ResultRule{{
FilterListID: nr.GetFilterListID(),
Text: nr.RuleText,
}}
return Result{
Rules: rules,
Reason: RewrittenRule,
CanonName: dr.NewCNAME,
}
}
switch dr.RCode {
case dns.RcodeSuccess:
dnsrr.RCode = dr.RCode
dnsrr.Response[dr.RRType] = append(dnsrr.Response[dr.RRType], dr.Value)
rules = append(rules, &ResultRule{
FilterListID: nr.GetFilterListID(),
Text: nr.RuleText,
})
default:
// RcodeRefused and other such codes have higher priority. Return
// immediately.
rules = []*ResultRule{{
FilterListID: nr.GetFilterListID(),
Text: nr.RuleText,
}}
dnsrr = &DNSRewriteResult{
RCode: dr.RCode,
}
return Result{
DNSRewriteResult: dnsrr,
Rules: rules,
Reason: RewrittenRule,
}
}
}
return Result{
DNSRewriteResult: dnsrr,
Rules: rules,
Reason: RewrittenRule,
}
}
// processDNSResultRewrites returns an empty Result if there are no dnsrewrite
// rules in dnsres. Otherwise, it returns the processed Result.
func (d *DNSFilter) processDNSResultRewrites(
dnsres *urlfilter.DNSResult,
host string,
) (dnsRWRes Result) {
dnsr := dnsres.DNSRewrites()
if len(dnsr) == 0 {
return Result{}
}
res := d.processDNSRewrites(dnsr)
if res.Reason == RewrittenRule && res.CanonName == host {
// A rewrite of a host to itself. Go on and try matching other things.
return Result{}
}
return res
}
``` | /content/code_sandbox/internal/filtering/dnsrewrite.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 722 |
```go
package filtering
import (
"fmt"
"sync/atomic"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/log"
)
// idGenerator generates filtering-list IDs in a way broadly compatible with the
// legacy approach of AdGuard Home.
//
// TODO(a.garipov): Get rid of this once we switch completely to the new
// rule-list architecture.
type idGenerator struct {
current *atomic.Int32
}
// newIDGenerator returns a new ID generator initialized with the given seed
// value.
func newIDGenerator(seed int32) (g *idGenerator) {
g = &idGenerator{
current: &atomic.Int32{},
}
g.current.Store(seed)
return g
}
// next returns the next ID from the generator. It is safe for concurrent use.
func (g *idGenerator) next() (id rulelist.URLFilterID) {
id32 := g.current.Add(1)
if id32 < 0 {
panic(fmt.Errorf("invalid current id value %d", id32))
}
return rulelist.URLFilterID(id32)
}
// fix ensures that flts all have unique IDs.
func (g *idGenerator) fix(flts []FilterYAML) {
set := container.NewMapSet[rulelist.URLFilterID]()
for i, f := range flts {
id := f.ID
if id == 0 {
id = g.next()
flts[i].ID = id
}
if !set.Has(id) {
set.Add(id)
continue
}
newID := g.next()
for set.Has(newID) {
newID = g.next()
}
log.Info(
"filtering: warning: filter at index %d has duplicate id %d; reassigning to %d",
i,
id,
newID,
)
flts[i].ID = newID
set.Add(newID)
}
}
``` | /content/code_sandbox/internal/filtering/idgenerator.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 443 |
```go
package filtering
import (
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/stretchr/testify/assert"
)
func TestIDGenerator_Fix(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
in []FilterYAML
}{{
name: "nil",
in: nil,
}, {
name: "empty",
in: []FilterYAML{},
}, {
name: "one_zero",
in: []FilterYAML{{}},
}, {
name: "two_zeros",
in: []FilterYAML{{}, {}},
}, {
name: "many_good",
in: []FilterYAML{{
Filter: Filter{
ID: 1,
},
}, {
Filter: Filter{
ID: 2,
},
}, {
Filter: Filter{
ID: 3,
},
}},
}, {
name: "two_dups",
in: []FilterYAML{{
Filter: Filter{
ID: 1,
},
}, {
Filter: Filter{
ID: 3,
},
}, {
Filter: Filter{
ID: 1,
},
}, {
Filter: Filter{
ID: 2,
},
}},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
g := newIDGenerator(1)
g.fix(tc.in)
assertUniqueIDs(t, tc.in)
})
}
}
// assertUniqueIDs is a test helper that asserts that the IDs of filters are
// unique.
func assertUniqueIDs(t testing.TB, flts []FilterYAML) {
t.Helper()
uc := aghalg.UniqChecker[rulelist.URLFilterID]{}
for _, f := range flts {
uc.Add(f.ID)
}
assert.NoError(t, uc.Validate())
}
``` | /content/code_sandbox/internal/filtering/idgenerator_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 465 |
```go
package filtering_test
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TODO(d.kolyshev): Use [rewrite.Item] instead.
type rewriteJSON struct {
Domain string `json:"domain"`
Answer string `json:"answer"`
}
type rewriteUpdateJSON struct {
Target rewriteJSON `json:"target"`
Update rewriteJSON `json:"update"`
}
const (
// testTimeout is the common timeout for tests.
testTimeout = 100 * time.Millisecond
listURL = "/control/rewrite/list"
addURL = "/control/rewrite/add"
deleteURL = "/control/rewrite/delete"
updateURL = "/control/rewrite/update"
decodeErrorMsg = "json.Decode: json: cannot unmarshal string into Go value of type" +
" filtering.rewriteEntryJSON\n"
)
func TestDNSFilter_handleRewriteHTTP(t *testing.T) {
confModCh := make(chan struct{})
reqCh := make(chan struct{})
testRewrites := []*rewriteJSON{
{Domain: "example.local", Answer: "example.rewrite"},
{Domain: "one.local", Answer: "one.rewrite"},
}
testRewritesJSON, mErr := json.Marshal(testRewrites)
require.NoError(t, mErr)
testCases := []struct {
reqData any
name string
url string
method string
wantList []*rewriteJSON
wantBody string
wantConfMod bool
wantStatus int
}{{
name: "list",
url: listURL,
method: http.MethodGet,
reqData: nil,
wantConfMod: false,
wantStatus: http.StatusOK,
wantBody: string(testRewritesJSON) + "\n",
wantList: testRewrites,
}, {
name: "add",
url: addURL,
method: http.MethodPost,
reqData: rewriteJSON{Domain: "add.local", Answer: "add.rewrite"},
wantConfMod: true,
wantStatus: http.StatusOK,
wantBody: "",
wantList: append(
testRewrites,
&rewriteJSON{Domain: "add.local", Answer: "add.rewrite"},
),
}, {
name: "add_error",
url: addURL,
method: http.MethodPost,
reqData: "invalid_json",
wantConfMod: false,
wantStatus: http.StatusBadRequest,
wantBody: decodeErrorMsg,
wantList: testRewrites,
}, {
name: "delete",
url: deleteURL,
method: http.MethodPost,
reqData: rewriteJSON{Domain: "one.local", Answer: "one.rewrite"},
wantConfMod: true,
wantStatus: http.StatusOK,
wantBody: "",
wantList: []*rewriteJSON{{Domain: "example.local", Answer: "example.rewrite"}},
}, {
name: "delete_error",
url: deleteURL,
method: http.MethodPost,
reqData: "invalid_json",
wantConfMod: false,
wantStatus: http.StatusBadRequest,
wantBody: decodeErrorMsg,
wantList: testRewrites,
}, {
name: "update",
url: updateURL,
method: http.MethodPut,
reqData: rewriteUpdateJSON{
Target: rewriteJSON{Domain: "one.local", Answer: "one.rewrite"},
Update: rewriteJSON{Domain: "upd.local", Answer: "upd.rewrite"},
},
wantConfMod: true,
wantStatus: http.StatusOK,
wantBody: "",
wantList: []*rewriteJSON{
{Domain: "example.local", Answer: "example.rewrite"},
{Domain: "upd.local", Answer: "upd.rewrite"},
},
}, {
name: "update_error",
url: updateURL,
method: http.MethodPut,
reqData: "invalid_json",
wantConfMod: false,
wantStatus: http.StatusBadRequest,
wantBody: "json.Decode: json: cannot unmarshal string into Go value of type" +
" filtering.rewriteUpdateJSON\n",
wantList: testRewrites,
}, {
name: "update_error_target",
url: updateURL,
method: http.MethodPut,
reqData: rewriteUpdateJSON{
Target: rewriteJSON{Domain: "inv.local", Answer: "inv.rewrite"},
Update: rewriteJSON{Domain: "upd.local", Answer: "upd.rewrite"},
},
wantConfMod: false,
wantStatus: http.StatusBadRequest,
wantBody: "target rule not found\n",
wantList: testRewrites,
}}
for _, tc := range testCases {
onConfModified := func() {
if !tc.wantConfMod {
panic("config modified has been fired")
}
testutil.RequireSend(testutil.PanicT{}, confModCh, struct{}{}, testTimeout)
}
t.Run(tc.name, func(t *testing.T) {
handlers := make(map[string]http.Handler)
d, err := filtering.New(&filtering.Config{
ConfigModified: onConfModified,
HTTPRegister: func(_, url string, handler http.HandlerFunc) {
handlers[url] = handler
},
Rewrites: rewriteEntriesToLegacyRewrites(testRewrites),
}, nil)
require.NoError(t, err)
t.Cleanup(d.Close)
d.RegisterFilteringHandlers()
require.NotEmpty(t, handlers)
require.Contains(t, handlers, listURL)
require.Contains(t, handlers, tc.url)
var body io.Reader
if tc.reqData != nil {
data, rErr := json.Marshal(tc.reqData)
require.NoError(t, rErr)
body = bytes.NewReader(data)
}
r := httptest.NewRequest(tc.method, tc.url, body)
w := httptest.NewRecorder()
go func() {
handlers[tc.url].ServeHTTP(w, r)
testutil.RequireSend(testutil.PanicT{}, reqCh, struct{}{}, testTimeout)
}()
if tc.wantConfMod {
testutil.RequireReceive(t, confModCh, testTimeout)
}
testutil.RequireReceive(t, reqCh, testTimeout)
assert.Equal(t, tc.wantStatus, w.Code)
respBody, err := io.ReadAll(w.Body)
require.NoError(t, err)
assert.Equal(t, []byte(tc.wantBody), respBody)
assertRewritesList(t, handlers[listURL], tc.wantList)
})
}
}
// assertRewritesList checks if rewrites list equals the list received from the
// handler by listURL.
func assertRewritesList(t *testing.T, handler http.Handler, wantList []*rewriteJSON) {
t.Helper()
r := httptest.NewRequest(http.MethodGet, listURL, nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
require.Equal(t, http.StatusOK, w.Code)
var actual []*rewriteJSON
err := json.NewDecoder(w.Body).Decode(&actual)
require.NoError(t, err)
assert.Equal(t, wantList, actual)
}
// rewriteEntriesToLegacyRewrites gets legacy rewrites from json entries.
func rewriteEntriesToLegacyRewrites(entries []*rewriteJSON) (rw []*filtering.LegacyRewrite) {
for _, entry := range entries {
rw = append(rw, &filtering.LegacyRewrite{
Domain: entry.Domain,
Answer: entry.Answer,
})
}
return rw
}
``` | /content/code_sandbox/internal/filtering/rewritehttp_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,728 |
```go
package filtering
import (
"bytes"
"fmt"
"net/netip"
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/aghtest"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/hashprefix"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMain(m *testing.M) {
testutil.DiscardLogOutput(m)
}
const (
sbBlocked = "wmconvirus.narod.ru"
pcBlocked = "pornhub.com"
)
// Helpers.
func newForTest(t testing.TB, c *Config, filters []Filter) (f *DNSFilter, setts *Settings) {
setts = &Settings{
ProtectionEnabled: true,
FilteringEnabled: true,
}
if c != nil {
c.SafeBrowsingCacheSize = 10000
c.ParentalCacheSize = 10000
c.SafeSearchCacheSize = 1000
c.CacheTime = 30
setts.SafeSearchEnabled = c.SafeSearchConf.Enabled
setts.SafeBrowsingEnabled = c.SafeBrowsingEnabled
setts.ParentalEnabled = c.ParentalEnabled
} else {
// It must not be nil.
c = &Config{}
}
f, err := New(c, filters)
require.NoError(t, err)
return f, setts
}
func newChecker(host string) Checker {
return hashprefix.New(&hashprefix.Config{
CacheTime: 10,
CacheSize: 100000,
Upstream: aghtest.NewBlockUpstream(host, true),
})
}
func (d *DNSFilter) checkMatch(t *testing.T, hostname string, setts *Settings) {
t.Helper()
res, err := d.CheckHost(hostname, dns.TypeA, setts)
require.NoErrorf(t, err, "host %q", hostname)
assert.Truef(t, res.IsFiltered, "host %q", hostname)
}
func (d *DNSFilter) checkMatchIP(t *testing.T, hostname, ip string, qtype uint16, setts *Settings) {
t.Helper()
res, err := d.CheckHost(hostname, qtype, setts)
require.NoErrorf(t, err, "host %q", hostname, err)
require.NotEmpty(t, res.Rules, "host %q", hostname)
assert.Truef(t, res.IsFiltered, "host %q", hostname)
r := res.Rules[0]
require.NotNilf(t, r.IP, "Expected ip %s to match, actual: %v", ip, r.IP)
assert.Equalf(t, ip, r.IP.String(), "host %q", hostname)
}
func (d *DNSFilter) checkMatchEmpty(t *testing.T, hostname string, setts *Settings) {
t.Helper()
res, err := d.CheckHost(hostname, dns.TypeA, setts)
require.NoErrorf(t, err, "host %q", hostname)
assert.Falsef(t, res.IsFiltered, "host %q", hostname)
}
func TestDNSFilter_CheckHost_hostRules(t *testing.T) {
addr := "216.239.38.120"
addr6 := "::1"
text := fmt.Sprintf(` %s google.com www.google.com # enforce google's safesearch
%s ipv6.com
0.0.0.0 block.com
0.0.0.1 host2
0.0.0.2 host2
::1 host2
`,
addr, addr6)
filters := []Filter{{
ID: 0, Data: []byte(text),
}}
d, setts := newForTest(t, nil, filters)
t.Cleanup(d.Close)
d.checkMatchIP(t, "google.com", addr, dns.TypeA, setts)
d.checkMatchIP(t, "www.google.com", addr, dns.TypeA, setts)
d.checkMatchEmpty(t, "subdomain.google.com", setts)
d.checkMatchEmpty(t, "example.org", setts)
// IPv4 match.
d.checkMatchIP(t, "block.com", "0.0.0.0", dns.TypeA, setts)
// Empty IPv6.
res, err := d.CheckHost("block.com", dns.TypeAAAA, setts)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
require.Len(t, res.Rules, 1)
assert.Equal(t, "0.0.0.0 block.com", res.Rules[0].Text)
assert.Empty(t, res.Rules[0].IP)
// IPv6 match.
d.checkMatchIP(t, "ipv6.com", addr6, dns.TypeAAAA, setts)
// Empty IPv4.
res, err = d.CheckHost("ipv6.com", dns.TypeA, setts)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
require.Len(t, res.Rules, 1)
assert.Equal(t, "::1 ipv6.com", res.Rules[0].Text)
assert.Empty(t, res.Rules[0].IP)
// Two IPv4, both must be returned.
res, err = d.CheckHost("host2", dns.TypeA, setts)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
require.Len(t, res.Rules, 2)
assert.Equal(t, res.Rules[0].IP, netip.AddrFrom4([4]byte{0, 0, 0, 1}))
assert.Equal(t, res.Rules[1].IP, netip.AddrFrom4([4]byte{0, 0, 0, 2}))
// One IPv6 address.
res, err = d.CheckHost("host2", dns.TypeAAAA, setts)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
require.Len(t, res.Rules, 1)
assert.Equal(t, res.Rules[0].IP, netutil.IPv6Localhost())
}
// Safe Browsing.
func TestSafeBrowsing(t *testing.T) {
logOutput := &bytes.Buffer{}
aghtest.ReplaceLogWriter(t, logOutput)
aghtest.ReplaceLogLevel(t, log.DEBUG)
sbChecker := newChecker(sbBlocked)
d, setts := newForTest(t, &Config{
SafeBrowsingEnabled: true,
SafeBrowsingChecker: sbChecker,
}, nil)
t.Cleanup(d.Close)
d.checkMatch(t, sbBlocked, setts)
require.Contains(t, logOutput.String(), fmt.Sprintf("safebrowsing lookup for %q", sbBlocked))
d.checkMatch(t, "test."+sbBlocked, setts)
d.checkMatchEmpty(t, "yandex.ru", setts)
d.checkMatchEmpty(t, pcBlocked, setts)
// Cached result.
d.checkMatch(t, sbBlocked, setts)
d.checkMatchEmpty(t, pcBlocked, setts)
}
func TestParallelSB(t *testing.T) {
d, setts := newForTest(t, &Config{
SafeBrowsingEnabled: true,
SafeBrowsingChecker: newChecker(sbBlocked),
}, nil)
t.Cleanup(d.Close)
t.Run("group", func(t *testing.T) {
for i := range 100 {
t.Run(fmt.Sprintf("aaa%d", i), func(t *testing.T) {
t.Parallel()
d.checkMatch(t, sbBlocked, setts)
d.checkMatch(t, "test."+sbBlocked, setts)
d.checkMatchEmpty(t, "yandex.ru", setts)
d.checkMatchEmpty(t, pcBlocked, setts)
})
}
})
}
// Parental.
func TestParentalControl(t *testing.T) {
logOutput := &bytes.Buffer{}
aghtest.ReplaceLogWriter(t, logOutput)
aghtest.ReplaceLogLevel(t, log.DEBUG)
d, setts := newForTest(t, &Config{
ParentalEnabled: true,
ParentalControlChecker: newChecker(pcBlocked),
}, nil)
t.Cleanup(d.Close)
d.checkMatch(t, pcBlocked, setts)
require.Contains(t, logOutput.String(), fmt.Sprintf("parental lookup for %q", pcBlocked))
d.checkMatch(t, "www."+pcBlocked, setts)
d.checkMatchEmpty(t, "www.yandex.ru", setts)
d.checkMatchEmpty(t, "yandex.ru", setts)
d.checkMatchEmpty(t, "api.jquery.com", setts)
// Test cached result.
d.checkMatch(t, pcBlocked, setts)
d.checkMatchEmpty(t, "yandex.ru", setts)
}
// Filtering.
func TestMatching(t *testing.T) {
const nl = "\n"
const (
blockingRules = `||example.org^` + nl
allowlistRules = `||example.org^` + nl + `@@||test.example.org` + nl
importantRules = `@@||example.org^` + nl + `||test.example.org^$important` + nl
regexRules = `/example\.org/` + nl + `@@||test.example.org^` + nl
maskRules = `test*.example.org^` + nl + `exam*.com` + nl
dnstypeRules = `||example.org^$dnstype=AAAA` + nl + `@@||test.example.org^` + nl
)
testCases := []struct {
name string
rules string
host string
wantReason Reason
wantIsFiltered bool
wantDNSType uint16
}{{
name: "sanity",
rules: "||doubleclick.net^",
host: "www.doubleclick.net",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "sanity",
rules: "||doubleclick.net^",
host: "nodoubleclick.net",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "sanity",
rules: "||doubleclick.net^",
host: "doubleclick.net.ru",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "sanity",
rules: "||doubleclick.net^",
host: sbBlocked,
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "blocking",
rules: blockingRules,
host: "example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "blocking",
rules: blockingRules,
host: "test.example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "blocking",
rules: blockingRules,
host: "test.test.example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "blocking",
rules: blockingRules,
host: "testexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "blocking",
rules: blockingRules,
host: "onemoreexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "allowlist",
rules: allowlistRules,
host: "example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "allowlist",
rules: allowlistRules,
host: "test.example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeA,
}, {
name: "allowlist",
rules: allowlistRules,
host: "test.test.example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeA,
}, {
name: "allowlist",
rules: allowlistRules,
host: "testexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "allowlist",
rules: allowlistRules,
host: "onemoreexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "important",
rules: importantRules,
host: "example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeA,
}, {
name: "important",
rules: importantRules,
host: "test.example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "important",
rules: importantRules,
host: "test.test.example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "important",
rules: importantRules,
host: "testexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "important",
rules: importantRules,
host: "onemoreexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "regex",
rules: regexRules,
host: "example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "regex",
rules: regexRules,
host: "test.example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeA,
}, {
name: "regex",
rules: regexRules,
host: "test.test.example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeA,
}, {
name: "regex",
rules: regexRules,
host: "testexample.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "regex",
rules: regexRules,
host: "onemoreexample.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "test.example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "test2.example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "example.com",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "exampleeee.com",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "onemoreexamsite.com",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "example.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "testexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "mask",
rules: maskRules,
host: "example.co.uk",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "dnstype",
rules: dnstypeRules,
host: "onemoreexample.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "dnstype",
rules: dnstypeRules,
host: "example.org",
wantIsFiltered: false,
wantReason: NotFilteredNotFound,
wantDNSType: dns.TypeA,
}, {
name: "dnstype",
rules: dnstypeRules,
host: "example.org",
wantIsFiltered: true,
wantReason: FilteredBlockList,
wantDNSType: dns.TypeAAAA,
}, {
name: "dnstype",
rules: dnstypeRules,
host: "test.example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeA,
}, {
name: "dnstype",
rules: dnstypeRules,
host: "test.example.org",
wantIsFiltered: false,
wantReason: NotFilteredAllowList,
wantDNSType: dns.TypeAAAA,
}}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s-%s", tc.name, tc.host), func(t *testing.T) {
filters := []Filter{{ID: 0, Data: []byte(tc.rules)}}
d, setts := newForTest(t, nil, filters)
t.Cleanup(d.Close)
res, err := d.CheckHost(tc.host, tc.wantDNSType, setts)
require.NoError(t, err)
assert.Equalf(t, tc.wantIsFiltered, res.IsFiltered, "Hostname %s has wrong result (%v must be %v)", tc.host, res.IsFiltered, tc.wantIsFiltered)
assert.Equalf(t, tc.wantReason, res.Reason, "Hostname %s has wrong reason (%v must be %v)", tc.host, res.Reason, tc.wantReason)
})
}
}
func TestWhitelist(t *testing.T) {
rules := `||host1^
||host2^
`
filters := []Filter{{
ID: 0, Data: []byte(rules),
}}
whiteRules := `||host1^
||host3^
`
whiteFilters := []Filter{{
ID: 0, Data: []byte(whiteRules),
}}
d, setts := newForTest(t, nil, filters)
err := d.setFilters(filters, whiteFilters, false)
require.NoError(t, err)
t.Cleanup(d.Close)
// Matched by white filter.
res, err := d.CheckHost("host1", dns.TypeA, setts)
require.NoError(t, err)
assert.False(t, res.IsFiltered)
assert.Equal(t, res.Reason, NotFilteredAllowList)
require.Len(t, res.Rules, 1)
assert.Equal(t, "||host1^", res.Rules[0].Text)
// Not matched by white filter, but matched by block filter.
res, err = d.CheckHost("host2", dns.TypeA, setts)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
assert.Equal(t, res.Reason, FilteredBlockList)
require.Len(t, res.Rules, 1)
assert.Equal(t, "||host2^", res.Rules[0].Text)
}
// Client Settings.
func applyClientSettings(setts *Settings) {
setts.FilteringEnabled = false
setts.ParentalEnabled = false
setts.SafeBrowsingEnabled = true
rule, _ := rules.NewNetworkRule("||facebook.com^", 0)
s := ServiceEntry{}
s.Name = "facebook"
s.Rules = []*rules.NetworkRule{rule}
setts.ServicesRules = append(setts.ServicesRules, s)
}
func TestClientSettings(t *testing.T) {
d, setts := newForTest(t,
&Config{
ParentalEnabled: true,
SafeBrowsingEnabled: false,
SafeBrowsingChecker: newChecker(sbBlocked),
ParentalControlChecker: newChecker(pcBlocked),
},
[]Filter{{
ID: 0, Data: []byte("||example.org^\n"),
}},
)
t.Cleanup(d.Close)
type testCase struct {
name string
host string
before bool
wantReason Reason
}
testCases := []testCase{{
name: "filters",
host: "example.org",
before: true,
wantReason: FilteredBlockList,
}, {
name: "parental",
host: pcBlocked,
before: true,
wantReason: FilteredParental,
}, {
name: "safebrowsing",
host: sbBlocked,
before: false,
wantReason: FilteredSafeBrowsing,
}, {
name: "additional_rules",
host: "facebook.com",
before: false,
wantReason: FilteredBlockedService,
}}
makeTester := func(tc testCase, before bool) func(t *testing.T) {
return func(t *testing.T) {
t.Helper()
r, err := d.CheckHost(tc.host, dns.TypeA, setts)
require.NoError(t, err)
if before {
assert.True(t, r.IsFiltered)
assert.Equal(t, tc.wantReason, r.Reason)
} else {
assert.False(t, r.IsFiltered)
}
}
}
// Check behaviour without any per-client settings, then apply per-client
// settings and check behavior once again.
for _, tc := range testCases {
t.Run(tc.name, makeTester(tc, tc.before))
}
applyClientSettings(setts)
for _, tc := range testCases {
t.Run(tc.name, makeTester(tc, !tc.before))
}
}
// Benchmarks.
func BenchmarkSafeBrowsing(b *testing.B) {
d, setts := newForTest(b, &Config{
SafeBrowsingEnabled: true,
SafeBrowsingChecker: newChecker(sbBlocked),
}, nil)
b.Cleanup(d.Close)
for range b.N {
res, err := d.CheckHost(sbBlocked, dns.TypeA, setts)
require.NoError(b, err)
assert.Truef(b, res.IsFiltered, "expected hostname %q to match", sbBlocked)
}
}
func BenchmarkSafeBrowsingParallel(b *testing.B) {
d, setts := newForTest(b, &Config{
SafeBrowsingEnabled: true,
SafeBrowsingChecker: newChecker(sbBlocked),
}, nil)
b.Cleanup(d.Close)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
res, err := d.CheckHost(sbBlocked, dns.TypeA, setts)
require.NoError(b, err)
assert.Truef(b, res.IsFiltered, "expected hostname %q to match", sbBlocked)
}
})
}
``` | /content/code_sandbox/internal/filtering/filtering_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 5,451 |
```go
package filtering
import (
"fmt"
"net/netip"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/hostsfile"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// matchSysHosts tries to match the host against the operating system's hosts
// database. err is always nil.
func (d *DNSFilter) matchSysHosts(
host string,
qtype uint16,
setts *Settings,
) (res Result, err error) {
// TODO(e.burkov): Where else is this checked?
if !setts.FilteringEnabled || d.conf.EtcHosts == nil {
return Result{}, nil
}
vals, rs, matched := hostsRewrites(qtype, host, d.conf.EtcHosts)
if !matched {
return Result{}, nil
}
return Result{
DNSRewriteResult: &DNSRewriteResult{
Response: DNSRewriteResultResponse{
qtype: vals,
},
RCode: dns.RcodeSuccess,
},
Rules: rs,
Reason: RewrittenAutoHosts,
}, nil
}
// hostsRewrites returns values and rules matched by qt and host within hs.
func hostsRewrites(
qtype uint16,
host string,
hs hostsfile.Storage,
) (vals []rules.RRValue, rls []*ResultRule, matched bool) {
var isValidProto func(netip.Addr) (ok bool)
switch qtype {
case dns.TypeA:
isValidProto = netip.Addr.Is4
case dns.TypeAAAA:
isValidProto = netip.Addr.Is6
case dns.TypePTR:
addr, err := netutil.IPFromReversedAddr(host)
if err != nil {
log.Debug("filtering: failed to parse PTR record %q: %s", host, err)
return nil, nil, false
}
names := hs.ByAddr(addr)
for _, name := range names {
vals = append(vals, name)
rls = append(rls, &ResultRule{
Text: fmt.Sprintf("%s %s", addr, name),
FilterListID: rulelist.URLFilterIDEtcHosts,
})
}
return vals, rls, len(names) > 0
default:
log.Debug("filtering: unsupported qtype %d", qtype)
return nil, nil, false
}
addrs := hs.ByName(host)
for _, addr := range addrs {
if isValidProto(addr) {
vals = append(vals, addr)
}
rls = append(rls, &ResultRule{
Text: fmt.Sprintf("%s %s", addr, host),
FilterListID: rulelist.URLFilterIDEtcHosts,
})
}
return vals, rls, len(addrs) > 0
}
``` | /content/code_sandbox/internal/filtering/hosts.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 669 |
```go
package filtering
import (
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// testTimeout is the common timeout for tests.
const testTimeout = 5 * time.Second
// serveHTTPLocally starts a new HTTP server, that handles its index with h. It
// also gracefully closes the listener when the test under t finishes.
func serveHTTPLocally(t *testing.T, h http.Handler) (urlStr string) {
t.Helper()
l, err := net.Listen("tcp", ":0")
require.NoError(t, err)
go func() { _ = http.Serve(l, h) }()
testutil.CleanupAndRequireSuccess(t, l.Close)
addr := l.Addr()
require.IsType(t, (*net.TCPAddr)(nil), addr)
return (&url.URL{
Scheme: aghhttp.SchemeHTTP,
Host: addr.String(),
}).String()
}
// serveFiltersLocally is a helper that concurrently listens on a free port to
// respond with fltContent.
func serveFiltersLocally(t *testing.T, fltContent []byte) (urlStr string) {
t.Helper()
return serveHTTPLocally(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
pt := testutil.PanicT{}
n, werr := w.Write(fltContent)
require.NoError(pt, werr)
require.Equal(pt, len(fltContent), n)
}))
}
// updateAndAssert loads filter content from its URL and then asserts rules
// count.
func updateAndAssert(
t *testing.T,
dnsFilter *DNSFilter,
f *FilterYAML,
wantUpd require.BoolAssertionFunc,
wantRulesCount int,
) {
t.Helper()
ok, err := dnsFilter.update(f)
require.NoError(t, err)
wantUpd(t, ok)
assert.Equal(t, wantRulesCount, f.RulesCount)
dir, err := os.ReadDir(filepath.Join(dnsFilter.conf.DataDir, filterDir))
require.NoError(t, err)
require.FileExists(t, f.Path(dnsFilter.conf.DataDir))
assert.Len(t, dir, 1)
err = dnsFilter.load(f)
require.NoError(t, err)
}
// newDNSFilter returns a new properly initialized DNS filter instance.
func newDNSFilter(t *testing.T) (d *DNSFilter) {
t.Helper()
dnsFilter, err := New(&Config{
DataDir: t.TempDir(),
HTTPClient: &http.Client{
Timeout: testTimeout,
},
}, nil)
require.NoError(t, err)
return dnsFilter
}
func TestDNSFilter_Update(t *testing.T) {
const content = `||example.org^$third-party
# Inline comment example
||example.com^$third-party
0.0.0.0 example.com
`
fltContent := []byte(content)
addr := serveFiltersLocally(t, fltContent)
f := &FilterYAML{
URL: addr,
Name: "test-filter",
}
dnsFilter := newDNSFilter(t)
t.Run("download", func(t *testing.T) {
updateAndAssert(t, dnsFilter, f, require.True, 3)
})
t.Run("refresh_idle", func(t *testing.T) {
updateAndAssert(t, dnsFilter, f, require.False, 3)
})
t.Run("refresh_actually", func(t *testing.T) {
anotherContent := []byte(`||example.com^`)
oldURL := f.URL
f.URL = serveFiltersLocally(t, anotherContent)
t.Cleanup(func() { f.URL = oldURL })
updateAndAssert(t, dnsFilter, f, require.True, 1)
})
t.Run("load_unload", func(t *testing.T) {
err := dnsFilter.load(f)
require.NoError(t, err)
f.unload()
})
}
func TestFilterYAML_EnsureName(t *testing.T) {
dnsFilter := newDNSFilter(t)
t.Run("title_custom", func(t *testing.T) {
content := []byte("! Title: src-title\n||example.com^")
f := &FilterYAML{
URL: serveFiltersLocally(t, content),
Name: "user-custom",
}
updateAndAssert(t, dnsFilter, f, require.True, 1)
assert.Equal(t, "user-custom", f.Name)
})
t.Run("title_from_src", func(t *testing.T) {
content := []byte("! Title: src-title\n||example.com^")
f := &FilterYAML{
URL: serveFiltersLocally(t, content),
}
updateAndAssert(t, dnsFilter, f, require.True, 1)
assert.Equal(t, "src-title", f.Name)
})
t.Run("title_default", func(t *testing.T) {
content := []byte("||example.com^")
f := &FilterYAML{
URL: serveFiltersLocally(t, content),
}
updateAndAssert(t, dnsFilter, f, require.True, 1)
assert.Equal(t, "List 0", f.Name)
})
}
``` | /content/code_sandbox/internal/filtering/filter_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,155 |
```go
package filtering
import (
"fmt"
"net/netip"
"testing"
"testing/fstest"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/aghtest"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDNSFilter_CheckHost_hostsContainer(t *testing.T) {
addrv4 := netip.MustParseAddr("1.2.3.4")
addrv6 := netip.MustParseAddr("::1")
addrMapped := netip.MustParseAddr("::ffff:1.2.3.4")
addrv4Dup := netip.MustParseAddr("4.3.2.1")
data := fmt.Sprintf(
""+
"%[1]s v4.host.example\n"+
"%[2]s v6.host.example\n"+
"%[3]s mapped.host.example\n"+
"%[4]s v4.host.with-dup\n"+
"%[4]s v4.host.with-dup\n",
addrv4,
addrv6,
addrMapped,
addrv4Dup,
)
files := fstest.MapFS{
"hosts": &fstest.MapFile{
Data: []byte(data),
},
}
watcher := &aghtest.FSWatcher{
OnStart: func() (_ error) { panic("not implemented") },
OnEvents: func() (e <-chan struct{}) { return nil },
OnAdd: func(name string) (err error) { return nil },
OnClose: func() (err error) { return nil },
}
hc, err := aghnet.NewHostsContainer(files, watcher, "hosts")
require.NoError(t, err)
testutil.CleanupAndRequireSuccess(t, hc.Close)
conf := &Config{
EtcHosts: hc,
}
f, err := New(conf, nil)
require.NoError(t, err)
setts := &Settings{
FilteringEnabled: true,
}
testCases := []struct {
name string
host string
wantRules []*ResultRule
wantResps []rules.RRValue
dtyp uint16
}{{
name: "v4",
host: "v4.host.example",
dtyp: dns.TypeA,
wantRules: []*ResultRule{{
Text: "1.2.3.4 v4.host.example",
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: []rules.RRValue{addrv4},
}, {
name: "v6",
host: "v6.host.example",
dtyp: dns.TypeAAAA,
wantRules: []*ResultRule{{
Text: "::1 v6.host.example",
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: []rules.RRValue{addrv6},
}, {
name: "mapped",
host: "mapped.host.example",
dtyp: dns.TypeAAAA,
wantRules: []*ResultRule{{
Text: "::ffff:1.2.3.4 mapped.host.example",
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: []rules.RRValue{addrMapped},
}, {
name: "ptr",
host: "4.3.2.1.in-addr.arpa",
dtyp: dns.TypePTR,
wantRules: []*ResultRule{{
Text: "1.2.3.4 v4.host.example",
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: []rules.RRValue{"v4.host.example"},
}, {
name: "ptr-mapped",
host: "4.0.3.0.2.0.1.0.f.f.f.f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa",
dtyp: dns.TypePTR,
wantRules: []*ResultRule{{
Text: "::ffff:1.2.3.4 mapped.host.example",
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: []rules.RRValue{"mapped.host.example"},
}, {
name: "not_found_v4",
host: "non.existent.example",
dtyp: dns.TypeA,
wantRules: nil,
wantResps: nil,
}, {
name: "not_found_v6",
host: "non.existent.example",
dtyp: dns.TypeAAAA,
wantRules: nil,
wantResps: nil,
}, {
name: "not_found_ptr",
host: "4.3.2.2.in-addr.arpa",
dtyp: dns.TypePTR,
wantRules: nil,
wantResps: nil,
}, {
name: "v4_mismatch",
host: "v4.host.example",
dtyp: dns.TypeAAAA,
wantRules: []*ResultRule{{
Text: fmt.Sprintf("%s v4.host.example", addrv4),
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: nil,
}, {
name: "v6_mismatch",
host: "v6.host.example",
dtyp: dns.TypeA,
wantRules: []*ResultRule{{
Text: fmt.Sprintf("%s v6.host.example", addrv6),
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: nil,
}, {
name: "wrong_ptr",
host: "4.3.2.1.ip6.arpa",
dtyp: dns.TypePTR,
wantRules: nil,
wantResps: nil,
}, {
name: "unsupported_type",
host: "v4.host.example",
dtyp: dns.TypeCNAME,
wantRules: nil,
wantResps: nil,
}, {
name: "v4_dup",
host: "v4.host.with-dup",
dtyp: dns.TypeA,
wantRules: []*ResultRule{{
Text: "4.3.2.1 v4.host.with-dup",
FilterListID: rulelist.URLFilterIDEtcHosts,
}},
wantResps: []rules.RRValue{addrv4Dup},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var res Result
res, err = f.CheckHost(tc.host, tc.dtyp, setts)
require.NoError(t, err)
if len(tc.wantRules) == 0 {
assert.Empty(t, res.Rules)
assert.Nil(t, res.DNSRewriteResult)
return
}
require.NotNil(t, res.DNSRewriteResult)
require.Contains(t, res.DNSRewriteResult.Response, tc.dtyp)
assert.Equal(t, tc.wantResps, res.DNSRewriteResult.Response[tc.dtyp])
assert.Equal(t, tc.wantRules, res.Rules)
})
}
}
``` | /content/code_sandbox/internal/filtering/hosts_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,676 |
```go
package filtering
import (
"encoding/json"
"fmt"
"net/http"
"net/netip"
"net/url"
"os"
"path/filepath"
"slices"
"sync"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// validateFilterURL validates the filter list URL or file name.
func validateFilterURL(urlStr string) (err error) {
defer func() { err = errors.Annotate(err, "checking filter: %w") }()
if filepath.IsAbs(urlStr) {
_, err = os.Stat(urlStr)
// Don't wrap the error since it's informative enough as is.
return err
}
u, err := url.ParseRequestURI(urlStr)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
if s := u.Scheme; s != aghhttp.SchemeHTTP && s != aghhttp.SchemeHTTPS {
return &url.Error{
Op: "Check scheme",
URL: urlStr,
Err: fmt.Errorf("only %v allowed", []string{
aghhttp.SchemeHTTP,
aghhttp.SchemeHTTPS,
}),
}
}
return nil
}
type filterAddJSON struct {
Name string `json:"name"`
URL string `json:"url"`
Whitelist bool `json:"whitelist"`
}
func (d *DNSFilter) handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
fj := filterAddJSON{}
err := json.NewDecoder(r.Body).Decode(&fj)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "Failed to parse request body json: %s", err)
return
}
err = validateFilterURL(fj.URL)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
// Check for duplicates
if d.filterExists(fj.URL) {
err = errFilterExists
aghhttp.Error(r, w, http.StatusBadRequest, "Filter with URL %q: %s", fj.URL, err)
return
}
// Set necessary properties
filt := FilterYAML{
Enabled: true,
URL: fj.URL,
Name: fj.Name,
white: fj.Whitelist,
Filter: Filter{
ID: d.idGen.next(),
},
}
// Download the filter contents
ok, err := d.update(&filt)
if err != nil {
aghhttp.Error(
r,
w,
http.StatusBadRequest,
"Couldn't fetch filter from URL %q: %s",
filt.URL,
err,
)
return
}
if !ok {
aghhttp.Error(
r,
w,
http.StatusBadRequest,
"Filter with URL %q is invalid (maybe it points to blank page?)",
filt.URL,
)
return
}
// URL is assumed valid so append it to filters, update config, write new
// file and reload it to engines.
err = d.filterAdd(filt)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "Filter with URL %q: %s", filt.URL, err)
return
}
d.conf.ConfigModified()
d.EnableFilters(true)
_, err = fmt.Fprintf(w, "OK %d rules\n", filt.RulesCount)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write body: %s", err)
}
}
func (d *DNSFilter) handleFilteringRemoveURL(w http.ResponseWriter, r *http.Request) {
type request struct {
URL string `json:"url"`
Whitelist bool `json:"whitelist"`
}
req := request{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "failed to parse request body json: %s", err)
return
}
var deleted FilterYAML
func() {
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
filters := &d.conf.Filters
if req.Whitelist {
filters = &d.conf.WhitelistFilters
}
delIdx := slices.IndexFunc(*filters, func(flt FilterYAML) bool {
return flt.URL == req.URL
})
if delIdx == -1 {
log.Error("deleting filter with url %q: %s", req.URL, errFilterNotExist)
return
}
deleted = (*filters)[delIdx]
p := deleted.Path(d.conf.DataDir)
err = os.Rename(p, p+".old")
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Error("deleting filter %d: renaming file %q: %s", deleted.ID, p, err)
return
}
*filters = slices.Delete(*filters, delIdx, delIdx+1)
log.Info("deleted filter %d", deleted.ID)
}()
d.conf.ConfigModified()
d.EnableFilters(true)
// NOTE: The old files "filter.txt.old" aren't deleted. It's not really
// necessary, but will require the additional complicated code to run
// after enableFilters is done.
//
// TODO(a.garipov): Make sure the above comment is true.
_, err = fmt.Fprintf(w, "OK %d rules\n", deleted.RulesCount)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "couldn't write body: %s", err)
}
}
type filterURLReqData struct {
Name string `json:"name"`
URL string `json:"url"`
Enabled bool `json:"enabled"`
}
type filterURLReq struct {
Data *filterURLReqData `json:"data"`
URL string `json:"url"`
Whitelist bool `json:"whitelist"`
}
func (d *DNSFilter) handleFilteringSetURL(w http.ResponseWriter, r *http.Request) {
fj := filterURLReq{}
err := json.NewDecoder(r.Body).Decode(&fj)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "decoding request: %s", err)
return
}
if fj.Data == nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", errors.Error("data is absent"))
return
}
err = validateFilterURL(fj.Data.URL)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "invalid url: %s", err)
return
}
filt := FilterYAML{
Enabled: fj.Data.Enabled,
Name: fj.Data.Name,
URL: fj.Data.URL,
}
restart, err := d.filterSetProperties(fj.URL, filt, fj.Whitelist)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, err.Error())
return
}
d.conf.ConfigModified()
if restart {
d.EnableFilters(true)
}
}
// filteringRulesReq is the JSON structure for settings custom filtering rules.
type filteringRulesReq struct {
Rules []string `json:"rules"`
}
func (d *DNSFilter) handleFilteringSetRules(w http.ResponseWriter, r *http.Request) {
if aghhttp.WriteTextPlainDeprecated(w, r) {
return
}
req := &filteringRulesReq{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
return
}
d.conf.UserRules = req.Rules
d.conf.ConfigModified()
d.EnableFilters(true)
}
func (d *DNSFilter) handleFilteringRefresh(w http.ResponseWriter, r *http.Request) {
type Req struct {
White bool `json:"whitelist"`
}
var err error
req := Req{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
return
}
var ok bool
resp := struct {
Updated int `json:"updated"`
}{}
resp.Updated, _, ok = d.tryRefreshFilters(!req.White, req.White, true)
if !ok {
aghhttp.Error(
r,
w,
http.StatusInternalServerError,
"filters update procedure is already running",
)
return
}
aghhttp.WriteJSONResponseOK(w, r, resp)
}
type filterJSON struct {
URL string `json:"url"`
Name string `json:"name"`
LastUpdated string `json:"last_updated,omitempty"`
ID rulelist.URLFilterID `json:"id"`
RulesCount uint32 `json:"rules_count"`
Enabled bool `json:"enabled"`
}
type filteringConfig struct {
Filters []filterJSON `json:"filters"`
WhitelistFilters []filterJSON `json:"whitelist_filters"`
UserRules []string `json:"user_rules"`
Interval uint32 `json:"interval"` // in hours
Enabled bool `json:"enabled"`
}
func filterToJSON(f FilterYAML) filterJSON {
fj := filterJSON{
ID: f.ID,
Enabled: f.Enabled,
URL: f.URL,
Name: f.Name,
RulesCount: uint32(f.RulesCount),
}
if !f.LastUpdated.IsZero() {
fj.LastUpdated = f.LastUpdated.Format(time.RFC3339)
}
return fj
}
// Get filtering configuration
func (d *DNSFilter) handleFilteringStatus(w http.ResponseWriter, r *http.Request) {
resp := filteringConfig{}
d.conf.filtersMu.RLock()
resp.Enabled = d.conf.FilteringEnabled
resp.Interval = d.conf.FiltersUpdateIntervalHours
for _, f := range d.conf.Filters {
fj := filterToJSON(f)
resp.Filters = append(resp.Filters, fj)
}
for _, f := range d.conf.WhitelistFilters {
fj := filterToJSON(f)
resp.WhitelistFilters = append(resp.WhitelistFilters, fj)
}
resp.UserRules = d.conf.UserRules
d.conf.filtersMu.RUnlock()
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// Set filtering configuration
func (d *DNSFilter) handleFilteringConfig(w http.ResponseWriter, r *http.Request) {
req := filteringConfig{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
return
}
if !ValidateUpdateIvl(req.Interval) {
aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval")
return
}
func() {
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
d.conf.FilteringEnabled = req.Enabled
d.conf.FiltersUpdateIntervalHours = req.Interval
}()
d.conf.ConfigModified()
d.EnableFilters(true)
}
type checkHostRespRule struct {
Text string `json:"text"`
FilterListID rulelist.URLFilterID `json:"filter_list_id"`
}
type checkHostResp struct {
Reason string `json:"reason"`
// Rule is the text of the matched rule.
//
// Deprecated: Use Rules[*].Text.
Rule string `json:"rule"`
Rules []*checkHostRespRule `json:"rules"`
// for FilteredBlockedService:
SvcName string `json:"service_name"`
// for Rewrite:
CanonName string `json:"cname"` // CNAME value
IPList []netip.Addr `json:"ip_addrs"` // list of IP addresses
// FilterID is the ID of the rule's filter list.
//
// Deprecated: Use Rules[*].FilterListID.
FilterID rulelist.URLFilterID `json:"filter_id"`
}
func (d *DNSFilter) handleCheckHost(w http.ResponseWriter, r *http.Request) {
host := r.URL.Query().Get("name")
setts := d.Settings()
setts.FilteringEnabled = true
setts.ProtectionEnabled = true
d.ApplyBlockedServices(setts)
result, err := d.CheckHost(host, dns.TypeA, setts)
if err != nil {
aghhttp.Error(
r,
w,
http.StatusInternalServerError,
"couldn't apply filtering: %s: %s",
host,
err,
)
return
}
rulesLen := len(result.Rules)
resp := checkHostResp{
Reason: result.Reason.String(),
SvcName: result.ServiceName,
CanonName: result.CanonName,
IPList: result.IPList,
Rules: make([]*checkHostRespRule, len(result.Rules)),
}
if rulesLen > 0 {
resp.FilterID = result.Rules[0].FilterListID
resp.Rule = result.Rules[0].Text
}
for i, r := range result.Rules {
resp.Rules[i] = &checkHostRespRule{
FilterListID: r.FilterListID,
Text: r.Text,
}
}
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// setProtectedBool sets the value of a boolean pointer under a lock. l must
// protect the value under ptr.
//
// TODO(e.burkov): Make it generic?
func setProtectedBool(mu *sync.RWMutex, ptr *bool, val bool) {
mu.Lock()
defer mu.Unlock()
*ptr = val
}
// protectedBool gets the value of a boolean pointer under a read lock. l must
// protect the value under ptr.
//
// TODO(e.burkov): Make it generic?
func protectedBool(mu *sync.RWMutex, ptr *bool) (val bool) {
mu.RLock()
defer mu.RUnlock()
return *ptr
}
// handleSafeBrowsingEnable is the handler for the POST
// /control/safebrowsing/enable HTTP API.
func (d *DNSFilter) handleSafeBrowsingEnable(w http.ResponseWriter, r *http.Request) {
setProtectedBool(d.confMu, &d.conf.SafeBrowsingEnabled, true)
d.conf.ConfigModified()
}
// handleSafeBrowsingDisable is the handler for the POST
// /control/safebrowsing/disable HTTP API.
func (d *DNSFilter) handleSafeBrowsingDisable(w http.ResponseWriter, r *http.Request) {
setProtectedBool(d.confMu, &d.conf.SafeBrowsingEnabled, false)
d.conf.ConfigModified()
}
// handleSafeBrowsingStatus is the handler for the GET
// /control/safebrowsing/status HTTP API.
func (d *DNSFilter) handleSafeBrowsingStatus(w http.ResponseWriter, r *http.Request) {
resp := &struct {
Enabled bool `json:"enabled"`
}{
Enabled: protectedBool(d.confMu, &d.conf.SafeBrowsingEnabled),
}
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// handleParentalEnable is the handler for the POST /control/parental/enable
// HTTP API.
func (d *DNSFilter) handleParentalEnable(w http.ResponseWriter, r *http.Request) {
setProtectedBool(d.confMu, &d.conf.ParentalEnabled, true)
d.conf.ConfigModified()
}
// handleParentalDisable is the handler for the POST /control/parental/disable
// HTTP API.
func (d *DNSFilter) handleParentalDisable(w http.ResponseWriter, r *http.Request) {
setProtectedBool(d.confMu, &d.conf.ParentalEnabled, false)
d.conf.ConfigModified()
}
// handleParentalStatus is the handler for the GET /control/parental/status
// HTTP API.
func (d *DNSFilter) handleParentalStatus(w http.ResponseWriter, r *http.Request) {
resp := &struct {
Enabled bool `json:"enabled"`
}{
Enabled: protectedBool(d.confMu, &d.conf.ParentalEnabled),
}
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// RegisterFilteringHandlers - register handlers
func (d *DNSFilter) RegisterFilteringHandlers() {
registerHTTP := d.conf.HTTPRegister
if registerHTTP == nil {
return
}
registerHTTP(http.MethodPost, "/control/safebrowsing/enable", d.handleSafeBrowsingEnable)
registerHTTP(http.MethodPost, "/control/safebrowsing/disable", d.handleSafeBrowsingDisable)
registerHTTP(http.MethodGet, "/control/safebrowsing/status", d.handleSafeBrowsingStatus)
registerHTTP(http.MethodPost, "/control/parental/enable", d.handleParentalEnable)
registerHTTP(http.MethodPost, "/control/parental/disable", d.handleParentalDisable)
registerHTTP(http.MethodGet, "/control/parental/status", d.handleParentalStatus)
registerHTTP(http.MethodPost, "/control/safesearch/enable", d.handleSafeSearchEnable)
registerHTTP(http.MethodPost, "/control/safesearch/disable", d.handleSafeSearchDisable)
registerHTTP(http.MethodGet, "/control/safesearch/status", d.handleSafeSearchStatus)
registerHTTP(http.MethodPut, "/control/safesearch/settings", d.handleSafeSearchSettings)
registerHTTP(http.MethodGet, "/control/rewrite/list", d.handleRewriteList)
registerHTTP(http.MethodPost, "/control/rewrite/add", d.handleRewriteAdd)
registerHTTP(http.MethodPut, "/control/rewrite/update", d.handleRewriteUpdate)
registerHTTP(http.MethodPost, "/control/rewrite/delete", d.handleRewriteDelete)
registerHTTP(http.MethodGet, "/control/blocked_services/services", d.handleBlockedServicesIDs)
registerHTTP(http.MethodGet, "/control/blocked_services/all", d.handleBlockedServicesAll)
// Deprecated handlers.
registerHTTP(http.MethodGet, "/control/blocked_services/list", d.handleBlockedServicesList)
registerHTTP(http.MethodPost, "/control/blocked_services/set", d.handleBlockedServicesSet)
registerHTTP(http.MethodGet, "/control/blocked_services/get", d.handleBlockedServicesGet)
registerHTTP(http.MethodPut, "/control/blocked_services/update", d.handleBlockedServicesUpdate)
registerHTTP(http.MethodGet, "/control/filtering/status", d.handleFilteringStatus)
registerHTTP(http.MethodPost, "/control/filtering/config", d.handleFilteringConfig)
registerHTTP(http.MethodPost, "/control/filtering/add_url", d.handleFilteringAddURL)
registerHTTP(http.MethodPost, "/control/filtering/remove_url", d.handleFilteringRemoveURL)
registerHTTP(http.MethodPost, "/control/filtering/set_url", d.handleFilteringSetURL)
registerHTTP(http.MethodPost, "/control/filtering/refresh", d.handleFilteringRefresh)
registerHTTP(http.MethodPost, "/control/filtering/set_rules", d.handleFilteringSetRules)
registerHTTP(http.MethodGet, "/control/filtering/check_host", d.handleCheckHost)
}
// ValidateUpdateIvl returns false if i is not a valid filters update interval.
func ValidateUpdateIvl(i uint32) bool {
return i == 0 || i == 1 || i == 12 || i == 1*24 || i == 3*24 || i == 7*24
}
``` | /content/code_sandbox/internal/filtering/http.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 4,212 |
```go
// Package filtering implements a DNS request and response filter.
package filtering
import (
"context"
"fmt"
"io/fs"
"net"
"net/http"
"net/netip"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/hostsfile"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/mathutil"
"github.com/AdguardTeam/golibs/syncutil"
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/filterlist"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// ServiceEntry - blocked service array element
type ServiceEntry struct {
Name string
Rules []*rules.NetworkRule
}
// Settings are custom filtering settings for a client.
type Settings struct {
ClientName string
ClientIP netip.Addr
ClientTags []string
ServicesRules []ServiceEntry
ProtectionEnabled bool
FilteringEnabled bool
SafeSearchEnabled bool
SafeBrowsingEnabled bool
ParentalEnabled bool
// ClientSafeSearch is a client configured safe search.
ClientSafeSearch SafeSearch
}
// Resolver is the interface for net.Resolver to simplify testing.
type Resolver interface {
LookupIP(ctx context.Context, network, host string) (ips []net.IP, err error)
}
// Config allows you to configure DNS filtering with New() or just change variables directly.
type Config struct {
// BlockingIPv4 is the IP address to be returned for a blocked A request.
BlockingIPv4 netip.Addr `yaml:"blocking_ipv4"`
// BlockingIPv6 is the IP address to be returned for a blocked AAAA request.
BlockingIPv6 netip.Addr `yaml:"blocking_ipv6"`
// SafeBrowsingChecker is the safe browsing hash-prefix checker.
SafeBrowsingChecker Checker `yaml:"-"`
// ParentControl is the parental control hash-prefix checker.
ParentalControlChecker Checker `yaml:"-"`
SafeSearch SafeSearch `yaml:"-"`
// BlockedServices is the configuration of blocked services.
// Per-client settings can override this configuration.
BlockedServices *BlockedServices `yaml:"blocked_services"`
// EtcHosts is a container of IP-hostname pairs taken from the operating
// system configuration files (e.g. /etc/hosts).
//
// TODO(e.burkov): Move it to dnsforward entirely.
EtcHosts hostsfile.Storage `yaml:"-"`
// Called when the configuration is changed by HTTP request
ConfigModified func() `yaml:"-"`
// Register an HTTP handler
HTTPRegister aghhttp.RegisterFunc `yaml:"-"`
// HTTPClient is the client to use for updating the remote filters.
HTTPClient *http.Client `yaml:"-"`
// filtersMu protects filter lists.
filtersMu *sync.RWMutex
// ProtectionDisabledUntil is the timestamp until when the protection is
// disabled.
ProtectionDisabledUntil *time.Time `yaml:"protection_disabled_until"`
SafeSearchConf SafeSearchConfig `yaml:"safe_search"`
// DataDir is used to store filters' contents.
DataDir string `yaml:"-"`
// BlockingMode defines the way how blocked responses are constructed.
BlockingMode BlockingMode `yaml:"blocking_mode"`
// ParentalBlockHost is the IP (or domain name) which is used to respond to
// DNS requests blocked by parental control.
ParentalBlockHost string `yaml:"parental_block_host"`
// SafeBrowsingBlockHost is the IP (or domain name) which is used to respond
// to DNS requests blocked by safe-browsing.
SafeBrowsingBlockHost string `yaml:"safebrowsing_block_host"`
Rewrites []*LegacyRewrite `yaml:"rewrites"`
// Filters are the blocking filter lists.
Filters []FilterYAML `yaml:"-"`
// WhitelistFilters are the allowing filter lists.
WhitelistFilters []FilterYAML `yaml:"-"`
// UserRules is the global list of custom rules.
UserRules []string `yaml:"-"`
SafeBrowsingCacheSize uint `yaml:"safebrowsing_cache_size"` // (in bytes)
SafeSearchCacheSize uint `yaml:"safesearch_cache_size"` // (in bytes)
ParentalCacheSize uint `yaml:"parental_cache_size"` // (in bytes)
// TODO(a.garipov): Use timeutil.Duration
CacheTime uint `yaml:"cache_time"` // Element's TTL (in minutes)
// enabled is used to be returned within Settings.
//
// It is of type uint32 to be accessed by atomic.
//
// TODO(e.burkov): Use atomic.Bool in Go 1.19.
enabled uint32
// FiltersUpdateIntervalHours is the time period to update filters
// (in hours).
FiltersUpdateIntervalHours uint32 `yaml:"filters_update_interval"`
// BlockedResponseTTL is the time-to-live value for blocked responses. If
// 0, then default value is used (3600).
BlockedResponseTTL uint32 `yaml:"blocked_response_ttl"`
// FilteringEnabled indicates whether or not use filter lists.
FilteringEnabled bool `yaml:"filtering_enabled"`
ParentalEnabled bool `yaml:"parental_enabled"`
SafeBrowsingEnabled bool `yaml:"safebrowsing_enabled"`
// ProtectionEnabled defines whether or not use any of filtering features.
ProtectionEnabled bool `yaml:"protection_enabled"`
}
// BlockingMode is an enum of all allowed blocking modes.
type BlockingMode string
// Allowed blocking modes.
const (
// BlockingModeCustomIP means respond with a custom IP address.
BlockingModeCustomIP BlockingMode = "custom_ip"
// BlockingModeDefault is the same as BlockingModeNullIP for
// Adblock-style rules, but responds with the IP address specified in
// the rule when blocked by an `/etc/hosts`-style rule.
BlockingModeDefault BlockingMode = "default"
// BlockingModeNullIP means respond with a zero IP address: "0.0.0.0"
// for A requests and "::" for AAAA ones.
BlockingModeNullIP BlockingMode = "null_ip"
// BlockingModeNXDOMAIN means respond with the NXDOMAIN code.
BlockingModeNXDOMAIN BlockingMode = "nxdomain"
// BlockingModeREFUSED means respond with the REFUSED code.
BlockingModeREFUSED BlockingMode = "refused"
)
// LookupStats store stats collected during safebrowsing or parental checks
type LookupStats struct {
Requests uint64 // number of HTTP requests that were sent
CacheHits uint64 // number of lookups that didn't need HTTP requests
Pending int64 // number of currently pending HTTP requests
PendingMax int64 // maximum number of pending HTTP requests
}
// Stats store LookupStats for safebrowsing, parental and safesearch
type Stats struct {
Safebrowsing LookupStats
Parental LookupStats
Safesearch LookupStats
}
// Parameters to pass to filters-initializer goroutine
type filtersInitializerParams struct {
allowFilters []Filter
blockFilters []Filter
}
type hostChecker struct {
check func(host string, qtype uint16, setts *Settings) (res Result, err error)
name string
}
// Checker is used for safe browsing or parental control hash-prefix filtering.
type Checker interface {
// Check returns true if request for the host should be blocked.
Check(host string) (block bool, err error)
}
// DNSFilter matches hostnames and DNS requests against filtering rules.
type DNSFilter struct {
// idGen is used to generate IDs for package urlfilter.
idGen *idGenerator
// bufPool is a pool of buffers used for filtering-rule list parsing.
bufPool *syncutil.Pool[[]byte]
rulesStorage *filterlist.RuleStorage
filteringEngine *urlfilter.DNSEngine
rulesStorageAllow *filterlist.RuleStorage
filteringEngineAllow *urlfilter.DNSEngine
safeSearch SafeSearch
// safeBrowsingChecker is the safe browsing hash-prefix checker.
safeBrowsingChecker Checker
// parentalControl is the parental control hash-prefix checker.
parentalControlChecker Checker
engineLock sync.RWMutex
// confMu protects conf.
confMu *sync.RWMutex
// conf contains filtering parameters.
conf *Config
// done is the channel to signal to stop running filters updates loop.
done chan struct{}
// Channel for passing data to filters-initializer goroutine
filtersInitializerChan chan filtersInitializerParams
filtersInitializerLock sync.Mutex
refreshLock *sync.Mutex
hostCheckers []hostChecker
}
// Filter represents a filter list
type Filter struct {
// FilePath is the path to a filtering rules list file.
FilePath string `yaml:"-"`
// Data is the content of the file.
Data []byte `yaml:"-"`
// ID is automatically assigned when filter is added using nextFilterID.
ID rulelist.URLFilterID `yaml:"id"`
}
// Reason holds an enum detailing why it was filtered or not filtered
type Reason int
const (
// reasons for not filtering
// NotFilteredNotFound - host was not find in any checks, default value for result
NotFilteredNotFound Reason = iota
// NotFilteredAllowList - the host is explicitly allowed
NotFilteredAllowList
// NotFilteredError is returned when there was an error during
// checking. Reserved, currently unused.
NotFilteredError
// reasons for filtering
// FilteredBlockList - the host was matched to be advertising host
FilteredBlockList
// FilteredSafeBrowsing - the host was matched to be malicious/phishing
FilteredSafeBrowsing
// FilteredParental - the host was matched to be outside of parental control settings
FilteredParental
// FilteredInvalid - the request was invalid and was not processed
FilteredInvalid
// FilteredSafeSearch - the host was replaced with safesearch variant
FilteredSafeSearch
// FilteredBlockedService - the host is blocked by "blocked services" settings
FilteredBlockedService
// Rewritten is returned when there was a rewrite by a legacy DNS rewrite
// rule.
Rewritten
// RewrittenAutoHosts is returned when there was a rewrite by autohosts
// rules (/etc/hosts and so on).
RewrittenAutoHosts
// RewrittenRule is returned when a $dnsrewrite filter rule was applied.
//
// TODO(a.garipov): Remove Rewritten and RewrittenAutoHosts by merging their
// functionality into RewrittenRule.
//
// See path_to_url
RewrittenRule
)
// TODO(a.garipov): Resync with actual code names or replace completely
// in HTTP API v1.
var reasonNames = []string{
NotFilteredNotFound: "NotFilteredNotFound",
NotFilteredAllowList: "NotFilteredWhiteList",
NotFilteredError: "NotFilteredError",
FilteredBlockList: "FilteredBlackList",
FilteredSafeBrowsing: "FilteredSafeBrowsing",
FilteredParental: "FilteredParental",
FilteredInvalid: "FilteredInvalid",
FilteredSafeSearch: "FilteredSafeSearch",
FilteredBlockedService: "FilteredBlockedService",
Rewritten: "Rewrite",
RewrittenAutoHosts: "RewriteEtcHosts",
RewrittenRule: "RewriteRule",
}
func (r Reason) String() string {
if r < 0 || int(r) >= len(reasonNames) {
return ""
}
return reasonNames[r]
}
// In returns true if reasons include r.
func (r Reason) In(reasons ...Reason) (ok bool) { return slices.Contains(reasons, r) }
// SetEnabled sets the status of the *DNSFilter.
func (d *DNSFilter) SetEnabled(enabled bool) {
atomic.StoreUint32(&d.conf.enabled, mathutil.BoolToNumber[uint32](enabled))
}
// Settings returns filtering settings.
func (d *DNSFilter) Settings() (s *Settings) {
d.confMu.RLock()
defer d.confMu.RUnlock()
return &Settings{
FilteringEnabled: atomic.LoadUint32(&d.conf.enabled) != 0,
SafeSearchEnabled: d.conf.SafeSearchConf.Enabled,
SafeBrowsingEnabled: d.conf.SafeBrowsingEnabled,
ParentalEnabled: d.conf.ParentalEnabled,
}
}
// WriteDiskConfig - write configuration
func (d *DNSFilter) WriteDiskConfig(c *Config) {
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
*c = *d.conf
c.Rewrites = cloneRewrites(c.Rewrites)
}()
d.conf.filtersMu.RLock()
defer d.conf.filtersMu.RUnlock()
c.Filters = slices.Clone(d.conf.Filters)
c.WhitelistFilters = slices.Clone(d.conf.WhitelistFilters)
c.UserRules = slices.Clone(d.conf.UserRules)
}
// setFilters sets new filters, synchronously or asynchronously. When filters
// are set asynchronously, the old filters continue working until the new
// filters are ready.
//
// In this case the caller must ensure that the old filter files are intact.
func (d *DNSFilter) setFilters(blockFilters, allowFilters []Filter, async bool) error {
if async {
params := filtersInitializerParams{
allowFilters: allowFilters,
blockFilters: blockFilters,
}
d.filtersInitializerLock.Lock()
defer d.filtersInitializerLock.Unlock()
// Remove all pending tasks.
removeLoop:
for {
select {
case <-d.filtersInitializerChan:
// Continue removing.
default:
break removeLoop
}
}
d.filtersInitializerChan <- params
return nil
}
return d.initFiltering(allowFilters, blockFilters)
}
// Close - close the object
func (d *DNSFilter) Close() {
d.engineLock.Lock()
defer d.engineLock.Unlock()
if d.done != nil {
d.done <- struct{}{}
}
d.reset()
}
func (d *DNSFilter) reset() {
if d.rulesStorage != nil {
if err := d.rulesStorage.Close(); err != nil {
log.Error("filtering: rulesStorage.Close: %s", err)
}
}
if d.rulesStorageAllow != nil {
if err := d.rulesStorageAllow.Close(); err != nil {
log.Error("filtering: rulesStorageAllow.Close: %s", err)
}
}
}
// ProtectionStatus returns the status of protection and time until it's
// disabled if so.
func (d *DNSFilter) ProtectionStatus() (status bool, disabledUntil *time.Time) {
d.confMu.RLock()
defer d.confMu.RUnlock()
return d.conf.ProtectionEnabled, d.conf.ProtectionDisabledUntil
}
// SetProtectionStatus updates the status of protection and time until it's
// disabled.
func (d *DNSFilter) SetProtectionStatus(status bool, disabledUntil *time.Time) {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.ProtectionEnabled = status
d.conf.ProtectionDisabledUntil = disabledUntil
}
// SetProtectionEnabled updates the status of protection.
func (d *DNSFilter) SetProtectionEnabled(status bool) {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.ProtectionEnabled = status
}
// SetBlockingMode sets blocking mode properties.
func (d *DNSFilter) SetBlockingMode(mode BlockingMode, bIPv4, bIPv6 netip.Addr) {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.BlockingMode = mode
if mode == BlockingModeCustomIP {
d.conf.BlockingIPv4 = bIPv4
d.conf.BlockingIPv6 = bIPv6
}
}
// BlockingMode returns blocking mode properties.
func (d *DNSFilter) BlockingMode() (mode BlockingMode, bIPv4, bIPv6 netip.Addr) {
d.confMu.RLock()
defer d.confMu.RUnlock()
return d.conf.BlockingMode, d.conf.BlockingIPv4, d.conf.BlockingIPv6
}
// SetBlockedResponseTTL sets TTL for blocked responses.
func (d *DNSFilter) SetBlockedResponseTTL(ttl uint32) {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.BlockedResponseTTL = ttl
}
// BlockedResponseTTL returns TTL for blocked responses.
func (d *DNSFilter) BlockedResponseTTL() (ttl uint32) {
d.confMu.Lock()
defer d.confMu.Unlock()
return d.conf.BlockedResponseTTL
}
// SafeBrowsingBlockHost returns a host for safe browsing blocked responses.
func (d *DNSFilter) SafeBrowsingBlockHost() (host string) {
return d.conf.SafeBrowsingBlockHost
}
// ParentalBlockHost returns a host for parental protection blocked responses.
func (d *DNSFilter) ParentalBlockHost() (host string) {
return d.conf.ParentalBlockHost
}
// ResultRule contains information about applied rules.
type ResultRule struct {
// Text is the text of the rule.
Text string `json:",omitempty"`
// IP is the host IP. It is nil unless the rule uses the
// /etc/hosts syntax or the reason is FilteredSafeSearch.
IP netip.Addr `json:",omitempty"`
// FilterListID is the ID of the rule's filter list.
FilterListID rulelist.URLFilterID `json:",omitempty"`
}
// Result contains the result of a request check.
//
// All fields transitively have omitempty tags so that the query log doesn't
// become too large.
//
// TODO(a.garipov): Clarify relationships between fields. Perhaps replace with
// a sum type or an interface?
type Result struct {
// DNSRewriteResult is the $dnsrewrite filter rule result.
DNSRewriteResult *DNSRewriteResult `json:",omitempty"`
// CanonName is the CNAME value from the lookup rewrite result. It is empty
// unless Reason is set to Rewritten or RewrittenRule.
CanonName string `json:",omitempty"`
// ServiceName is the name of the blocked service. It is empty unless
// Reason is set to FilteredBlockedService.
ServiceName string `json:",omitempty"`
// IPList is the lookup rewrite result. It is empty unless Reason is set to
// Rewritten.
IPList []netip.Addr `json:",omitempty"`
// Rules are applied rules. If Rules are not empty, each rule is not nil.
Rules []*ResultRule `json:",omitempty"`
// Reason is the reason for blocking or unblocking the request.
Reason Reason `json:",omitempty"`
// IsFiltered is true if the request is filtered.
//
// TODO(d.kolyshev): Get rid of this flag.
IsFiltered bool `json:",omitempty"`
}
// Matched returns true if any match at all was found regardless of
// whether it was filtered or not.
func (r Reason) Matched() bool {
return r != NotFilteredNotFound
}
// CheckHostRules tries to match the host against filtering rules only.
func (d *DNSFilter) CheckHostRules(host string, rrtype uint16, setts *Settings) (Result, error) {
return d.matchHost(strings.ToLower(host), rrtype, setts)
}
// CheckHost tries to match the host against filtering rules, then safebrowsing
// and parental control rules, if they are enabled.
func (d *DNSFilter) CheckHost(
host string,
qtype uint16,
setts *Settings,
) (res Result, err error) {
// Sometimes clients try to resolve ".", which is a request to get root
// servers.
if host == "" {
return Result{}, nil
}
host = strings.ToLower(host)
if setts.FilteringEnabled {
res = d.processRewrites(host, qtype)
if res.Reason == Rewritten {
return res, nil
}
}
for _, hc := range d.hostCheckers {
res, err = hc.check(host, qtype, setts)
if err != nil {
return Result{}, fmt.Errorf("%s: %w", hc.name, err)
}
if res.Reason.Matched() {
return res, nil
}
}
return Result{}, nil
}
// processRewrites performs filtering based on the legacy rewrite records.
//
// Firstly, it finds CNAME rewrites for host. If the CNAME is the same as host,
// this query isn't filtered. If it's different, repeat the process for the new
// CNAME, breaking loops in the process.
//
// Secondly, it finds A or AAAA rewrites for host and, if found, sets res.IPList
// accordingly. If the found rewrite has a special value of "A" or "AAAA", the
// result is an exception.
func (d *DNSFilter) processRewrites(host string, qtype uint16) (res Result) {
d.confMu.RLock()
defer d.confMu.RUnlock()
rewrites, matched := findRewrites(d.conf.Rewrites, host, qtype)
if !matched {
return Result{}
}
res.Reason = Rewritten
cnames := container.NewMapSet[string]()
origHost := host
for matched && len(rewrites) > 0 && rewrites[0].Type == dns.TypeCNAME {
rw := rewrites[0]
rwPat := rw.Domain
rwAns := rw.Answer
log.Debug("rewrite: cname for %s is %s", host, rwAns)
if origHost == rwAns || rwPat == rwAns {
// Either a request for the hostname itself or a rewrite of
// a pattern onto itself, both of which are an exception rules.
// Return a not filtered result.
return Result{}
} else if host == rwAns && isWildcard(rwPat) {
// An "*.example.com sub.example.com" rewrite matching in a loop.
//
// See path_to_url
res.CanonName = host
break
}
host = rwAns
if cnames.Has(host) {
log.Info("rewrite: cname loop for %q on %q", origHost, host)
return res
}
cnames.Add(host)
res.CanonName = host
rewrites, matched = findRewrites(d.conf.Rewrites, host, qtype)
}
setRewriteResult(&res, host, rewrites, qtype)
return res
}
// matchBlockedServicesRules checks the host against the blocked services rules
// in settings, if any. The err is always nil, it is only there to make this
// a valid hostChecker function.
func matchBlockedServicesRules(
host string,
_ uint16,
setts *Settings,
) (res Result, err error) {
if !setts.ProtectionEnabled {
return Result{}, nil
}
svcs := setts.ServicesRules
if len(svcs) == 0 {
return Result{}, nil
}
req := rules.NewRequestForHostname(host)
for _, s := range svcs {
for _, rule := range s.Rules {
if rule.Match(req) {
res.Reason = FilteredBlockedService
res.IsFiltered = true
res.ServiceName = s.Name
ruleText := rule.Text()
res.Rules = []*ResultRule{{
FilterListID: rule.GetFilterListID(),
Text: ruleText,
}}
log.Debug("blocked services: matched rule: %s host: %s service: %s",
ruleText, host, s.Name)
return res, nil
}
}
}
return res, nil
}
//
// Adding rule and matching against the rules
//
func newRuleStorage(filters []Filter) (rs *filterlist.RuleStorage, err error) {
lists := make([]filterlist.RuleList, 0, len(filters))
for _, f := range filters {
switch id := int(f.ID); {
case len(f.Data) != 0:
lists = append(lists, &filterlist.StringRuleList{
ID: id,
RulesText: string(f.Data),
IgnoreCosmetic: true,
})
case f.FilePath == "":
continue
case runtime.GOOS == "windows":
// On Windows we don't pass a file to urlfilter because it's
// difficult to update this file while it's being used.
var data []byte
data, err = os.ReadFile(f.FilePath)
if errors.Is(err, fs.ErrNotExist) {
continue
} else if err != nil {
return nil, fmt.Errorf("reading filter content: %w", err)
}
lists = append(lists, &filterlist.StringRuleList{
ID: id,
RulesText: string(data),
IgnoreCosmetic: true,
})
default:
var list *filterlist.FileRuleList
list, err = filterlist.NewFileRuleList(id, f.FilePath, true)
if errors.Is(err, fs.ErrNotExist) {
continue
} else if err != nil {
return nil, fmt.Errorf("creating file rule list with %q: %w", f.FilePath, err)
}
lists = append(lists, list)
}
}
rs, err = filterlist.NewRuleStorage(lists)
if err != nil {
return nil, fmt.Errorf("creating rule storage: %w", err)
}
return rs, nil
}
// Initialize urlfilter objects.
func (d *DNSFilter) initFiltering(allowFilters, blockFilters []Filter) (err error) {
rulesStorage, err := newRuleStorage(blockFilters)
if err != nil {
return err
}
rulesStorageAllow, err := newRuleStorage(allowFilters)
if err != nil {
return err
}
filteringEngine := urlfilter.NewDNSEngine(rulesStorage)
filteringEngineAllow := urlfilter.NewDNSEngine(rulesStorageAllow)
func() {
d.engineLock.Lock()
defer d.engineLock.Unlock()
d.reset()
d.rulesStorage = rulesStorage
d.filteringEngine = filteringEngine
d.rulesStorageAllow = rulesStorageAllow
d.filteringEngineAllow = filteringEngineAllow
}()
// Make sure that the OS reclaims memory as soon as possible.
debug.FreeOSMemory()
log.Debug("filtering: initialized filtering engine")
return nil
}
// hostRules is a helper that converts a slice of host rules into a slice of the
// rules.Rule interface values.
func hostRulesToRules(netRules []*rules.HostRule) (res []rules.Rule) {
if netRules == nil {
return nil
}
res = make([]rules.Rule, len(netRules))
for i, nr := range netRules {
res[i] = nr
}
return res
}
// matchHostProcessAllowList processes the allowlist logic of host matching.
func (d *DNSFilter) matchHostProcessAllowList(
host string,
dnsres *urlfilter.DNSResult,
) (res Result, err error) {
var matchedRules []rules.Rule
if dnsres.NetworkRule != nil {
matchedRules = []rules.Rule{dnsres.NetworkRule}
} else if len(dnsres.HostRulesV4) > 0 {
matchedRules = hostRulesToRules(dnsres.HostRulesV4)
} else if len(dnsres.HostRulesV6) > 0 {
matchedRules = hostRulesToRules(dnsres.HostRulesV6)
}
if len(matchedRules) == 0 {
return Result{}, fmt.Errorf("invalid dns result: rules are empty")
}
log.Debug("filtering: allowlist rules for host %q: %+v", host, matchedRules)
return makeResult(matchedRules, NotFilteredAllowList), nil
}
// matchHostProcessDNSResult processes the matched DNS filtering result.
func (d *DNSFilter) matchHostProcessDNSResult(
qtype uint16,
dnsres *urlfilter.DNSResult,
) (res Result) {
if dnsres.NetworkRule != nil {
reason := FilteredBlockList
if dnsres.NetworkRule.Whitelist {
reason = NotFilteredAllowList
}
return makeResult([]rules.Rule{dnsres.NetworkRule}, reason)
}
switch qtype {
case dns.TypeA:
if dnsres.HostRulesV4 != nil {
res = makeResult(hostRulesToRules(dnsres.HostRulesV4), FilteredBlockList)
for i, hr := range dnsres.HostRulesV4 {
res.Rules[i].IP = hr.IP
}
return res
}
case dns.TypeAAAA:
if dnsres.HostRulesV6 != nil {
res = makeResult(hostRulesToRules(dnsres.HostRulesV6), FilteredBlockList)
for i, hr := range dnsres.HostRulesV6 {
res.Rules[i].IP = hr.IP
}
return res
}
default:
// Go on.
}
return hostResultForOtherQType(dnsres)
}
// hostResultForOtherQType returns a result based on the host rules in dnsres,
// if any. dnsres.HostRulesV4 take precedence over dnsres.HostRulesV6.
func hostResultForOtherQType(dnsres *urlfilter.DNSResult) (res Result) {
if len(dnsres.HostRulesV4) != 0 {
return makeResult([]rules.Rule{dnsres.HostRulesV4[0]}, FilteredBlockList)
}
if len(dnsres.HostRulesV6) != 0 {
return makeResult([]rules.Rule{dnsres.HostRulesV6[0]}, FilteredBlockList)
}
return Result{}
}
// matchHost is a low-level way to check only if host is filtered by rules,
// skipping expensive safebrowsing and parental lookups.
func (d *DNSFilter) matchHost(
host string,
rrtype uint16,
setts *Settings,
) (res Result, err error) {
if !setts.FilteringEnabled {
return Result{}, nil
}
ufReq := &urlfilter.DNSRequest{
Hostname: host,
SortedClientTags: setts.ClientTags,
// TODO(e.burkov): Wait for urlfilter update to pass net.IP.
ClientIP: setts.ClientIP,
ClientName: setts.ClientName,
DNSType: rrtype,
}
d.engineLock.RLock()
// Keep in mind that this lock must be held no just when calling Match() but
// also while using the rules returned by it.
//
// TODO(e.burkov): Inspect if the above is true.
defer d.engineLock.RUnlock()
if setts.ProtectionEnabled && d.filteringEngineAllow != nil {
dnsres, ok := d.filteringEngineAllow.MatchRequest(ufReq)
if ok {
return d.matchHostProcessAllowList(host, dnsres)
}
}
if d.filteringEngine == nil {
return Result{}, nil
}
dnsres, matchedEngine := d.filteringEngine.MatchRequest(ufReq)
// Check DNS rewrites first, because the API there is a bit awkward.
dnsRWRes := d.processDNSResultRewrites(dnsres, host)
if dnsRWRes.Reason != NotFilteredNotFound {
return dnsRWRes, nil
} else if !matchedEngine {
return Result{}, nil
}
if !setts.ProtectionEnabled {
// Don't check non-dnsrewrite filtering results.
return Result{}, nil
}
res = d.matchHostProcessDNSResult(rrtype, dnsres)
for _, r := range res.Rules {
log.Debug(
"filtering: found rule %q for host %q, filter list id: %d",
r.Text,
host,
r.FilterListID,
)
}
return res, nil
}
// makeResult returns a properly constructed Result.
func makeResult(matchedRules []rules.Rule, reason Reason) (res Result) {
resRules := make([]*ResultRule, len(matchedRules))
for i, mr := range matchedRules {
resRules[i] = &ResultRule{
FilterListID: mr.GetFilterListID(),
Text: mr.Text(),
}
}
return Result{
Rules: resRules,
Reason: reason,
IsFiltered: reason == FilteredBlockList,
}
}
// InitModule manually initializes blocked services map.
func InitModule() {
initBlockedServices()
}
// New creates properly initialized DNS Filter that is ready to be used. c must
// be non-nil.
func New(c *Config, blockFilters []Filter) (d *DNSFilter, err error) {
d = &DNSFilter{
idGen: newIDGenerator(int32(time.Now().Unix())),
bufPool: syncutil.NewSlicePool[byte](rulelist.DefaultRuleBufSize),
refreshLock: &sync.Mutex{},
safeBrowsingChecker: c.SafeBrowsingChecker,
parentalControlChecker: c.ParentalControlChecker,
confMu: &sync.RWMutex{},
}
d.safeSearch = c.SafeSearch
d.hostCheckers = []hostChecker{{
check: d.matchSysHosts,
name: "hosts container",
}, {
check: d.matchHost,
name: "filtering",
}, {
check: matchBlockedServicesRules,
name: "blocked services",
}, {
check: d.checkSafeBrowsing,
name: "safe browsing",
}, {
check: d.checkParental,
name: "parental",
}, {
check: d.checkSafeSearch,
name: "safe search",
}}
defer func() { err = errors.Annotate(err, "filtering: %w") }()
d.conf = c
d.conf.filtersMu = &sync.RWMutex{}
err = d.prepareRewrites()
if err != nil {
return nil, fmt.Errorf("rewrites: preparing: %s", err)
}
if d.conf.BlockedServices != nil {
err = d.conf.BlockedServices.Validate()
if err != nil {
return nil, fmt.Errorf("filtering: %w", err)
}
}
if blockFilters != nil {
err = d.initFiltering(nil, blockFilters)
if err != nil {
d.Close()
return nil, fmt.Errorf("initializing filtering subsystem: %s", err)
}
}
_ = os.MkdirAll(filepath.Join(d.conf.DataDir, filterDir), 0o755)
d.loadFilters(d.conf.Filters)
d.loadFilters(d.conf.WhitelistFilters)
d.conf.Filters = deduplicateFilters(d.conf.Filters)
d.conf.WhitelistFilters = deduplicateFilters(d.conf.WhitelistFilters)
d.idGen.fix(d.conf.Filters)
d.idGen.fix(d.conf.WhitelistFilters)
return d, nil
}
// Start registers web handlers and starts filters updates loop.
func (d *DNSFilter) Start() {
d.filtersInitializerChan = make(chan filtersInitializerParams, 1)
d.done = make(chan struct{}, 1)
d.RegisterFilteringHandlers()
go d.updatesLoop()
}
// updatesLoop initializes new filters and checks for filters updates in a loop.
func (d *DNSFilter) updatesLoop() {
defer log.OnPanic("filtering: updates loop")
ivl := time.Second * 5
t := time.NewTimer(ivl)
for {
select {
case params := <-d.filtersInitializerChan:
err := d.initFiltering(params.allowFilters, params.blockFilters)
if err != nil {
log.Error("filtering: initializing: %s", err)
continue
}
case <-t.C:
ivl = d.periodicallyRefreshFilters(ivl)
t.Reset(ivl)
case <-d.done:
t.Stop()
return
}
}
}
// periodicallyRefreshFilters checks for filters updates and returns time
// interval for the next update.
func (d *DNSFilter) periodicallyRefreshFilters(ivl time.Duration) (nextIvl time.Duration) {
const maxInterval = time.Hour
if d.conf.FiltersUpdateIntervalHours == 0 {
return ivl
}
isNetErr, ok := false, false
_, isNetErr, ok = d.tryRefreshFilters(true, true, false)
if ok && !isNetErr {
ivl = maxInterval
} else if isNetErr {
ivl *= 2
ivl = max(ivl, maxInterval)
}
return ivl
}
// Safe browsing and parental control methods.
// TODO(a.garipov): Unify with checkParental.
func (d *DNSFilter) checkSafeBrowsing(
host string,
_ uint16,
setts *Settings,
) (res Result, err error) {
if !setts.ProtectionEnabled || !setts.SafeBrowsingEnabled {
return Result{}, nil
}
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("filtering: safebrowsing lookup for %q", host)
}
res = Result{
Rules: []*ResultRule{{
Text: "adguard-malware-shavar",
FilterListID: rulelist.URLFilterIDSafeBrowsing,
}},
Reason: FilteredSafeBrowsing,
IsFiltered: true,
}
block, err := d.safeBrowsingChecker.Check(host)
if !block || err != nil {
return Result{}, err
}
return res, nil
}
// TODO(a.garipov): Unify with checkSafeBrowsing.
func (d *DNSFilter) checkParental(
host string,
_ uint16,
setts *Settings,
) (res Result, err error) {
if !setts.ProtectionEnabled || !setts.ParentalEnabled {
return Result{}, nil
}
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("filtering: parental lookup for %q", host)
}
res = Result{
Rules: []*ResultRule{{
Text: "parental CATEGORY_BLACKLISTED",
FilterListID: rulelist.URLFilterIDParentalControl,
}},
Reason: FilteredParental,
IsFiltered: true,
}
block, err := d.parentalControlChecker.Check(host)
if !block || err != nil {
return Result{}, err
}
return res, nil
}
``` | /content/code_sandbox/internal/filtering/filtering.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 8,472 |
```go
package filtering
import (
"net/netip"
"path"
"testing"
"github.com/AdguardTeam/golibs/netutil"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDNSFilter_CheckHostRules_dnsrewrite(t *testing.T) {
const text = `
|cname^$dnsrewrite=new-cname
|a-record^$dnsrewrite=127.0.0.1
|aaaa-record^$dnsrewrite=::1
|txt-record^$dnsrewrite=NOERROR;TXT;hello-world
|refused^$dnsrewrite=REFUSED
|mapped^$dnsrewrite=NOERROR;AAAA;::ffff:127.0.0.1
|a-records^$dnsrewrite=127.0.0.1
|a-records^$dnsrewrite=127.0.0.2
|aaaa-records^$dnsrewrite=::1
|aaaa-records^$dnsrewrite=::2
|disable-one^$dnsrewrite=127.0.0.1
|disable-one^$dnsrewrite=127.0.0.2
@@||disable-one^$dnsrewrite=127.0.0.1
|disable-cname^$dnsrewrite=127.0.0.1
|disable-cname^$dnsrewrite=new-cname
@@||disable-cname^$dnsrewrite=new-cname
|disable-cname-many^$dnsrewrite=127.0.0.1
|disable-cname-many^$dnsrewrite=new-cname-1
|disable-cname-many^$dnsrewrite=new-cname-2
@@||disable-cname-many^$dnsrewrite=new-cname-1
|disable-all^$dnsrewrite=127.0.0.1
|disable-all^$dnsrewrite=127.0.0.2
@@||disable-all^$dnsrewrite
|1.2.3.4.in-addr.arpa^$dnsrewrite=NOERROR;PTR;new-ptr
|1.2.3.5.in-addr.arpa^$dnsrewrite=NOERROR;PTR;new-ptr-with-dot.
`
f, _ := newForTest(t, nil, []Filter{{ID: 0, Data: []byte(text)}})
setts := &Settings{
FilteringEnabled: true,
}
ipv4p1 := netutil.IPv4Localhost()
ipv4p2 := ipv4p1.Next()
ipv6p1 := netutil.IPv6Localhost()
ipv6p2 := ipv6p1.Next()
mapped := netip.AddrFrom16(ipv4p1.As16())
testCasesA := []struct {
name string
want []any
rcode int
dtyp uint16
}{{
name: "a-record",
rcode: dns.RcodeSuccess,
want: []any{ipv4p1},
dtyp: dns.TypeA,
}, {
name: "aaaa-record",
want: []any{ipv6p1},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeAAAA,
}, {
name: "txt-record",
want: []any{"hello-world"},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeTXT,
}, {
name: "refused",
want: nil,
rcode: dns.RcodeRefused,
dtyp: 0,
}, {
name: "a-records",
want: []any{ipv4p1, ipv4p2},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeA,
}, {
name: "aaaa-records",
want: []any{ipv6p1, ipv6p2},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeAAAA,
}, {
name: "disable-one",
want: []any{ipv4p2},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeA,
}, {
name: "disable-cname",
want: []any{ipv4p1},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeA,
}, {
name: "mapped",
want: []any{mapped},
rcode: dns.RcodeSuccess,
dtyp: dns.TypeAAAA,
}}
for _, tc := range testCasesA {
t.Run(tc.name, func(t *testing.T) {
host := path.Base(tc.name)
res, err := f.CheckHostRules(host, tc.dtyp, setts)
require.NoError(t, err)
dnsrr := res.DNSRewriteResult
require.NotNil(t, dnsrr)
assert.Equal(t, tc.rcode, dnsrr.RCode)
if tc.rcode == dns.RcodeRefused {
return
}
ipVals := dnsrr.Response[tc.dtyp]
require.Len(t, ipVals, len(tc.want))
for i, val := range tc.want {
require.Equal(t, val, ipVals[i])
}
})
}
t.Run("cname", func(t *testing.T) {
dtyp := dns.TypeA
host := path.Base(t.Name())
res, err := f.CheckHostRules(host, dtyp, setts)
require.NoError(t, err)
assert.Equal(t, "new-cname", res.CanonName)
})
t.Run("disable-cname-many", func(t *testing.T) {
dtyp := dns.TypeA
host := path.Base(t.Name())
res, err := f.CheckHostRules(host, dtyp, setts)
require.NoError(t, err)
assert.Equal(t, "new-cname-2", res.CanonName)
assert.Nil(t, res.DNSRewriteResult)
})
t.Run("disable-all", func(t *testing.T) {
dtyp := dns.TypeA
host := path.Base(t.Name())
res, err := f.CheckHostRules(host, dtyp, setts)
require.NoError(t, err)
assert.Empty(t, res.CanonName)
assert.Empty(t, res.Rules)
})
t.Run("1.2.3.4.in-addr.arpa", func(t *testing.T) {
dtyp := dns.TypePTR
host := path.Base(t.Name())
res, err := f.CheckHostRules(host, dtyp, setts)
require.NoError(t, err)
require.NotNil(t, res.DNSRewriteResult)
rr := res.DNSRewriteResult
require.NotEmpty(t, rr.Response)
resps := rr.Response[dtyp]
require.Len(t, resps, 1)
ptr, ok := resps[0].(string)
require.True(t, ok)
assert.Equal(t, "new-ptr.", ptr)
})
t.Run("1.2.3.5.in-addr.arpa", func(t *testing.T) {
dtyp := dns.TypePTR
host := path.Base(t.Name())
res, err := f.CheckHostRules(host, dtyp, setts)
require.NoError(t, err)
require.NotNil(t, res.DNSRewriteResult)
rr := res.DNSRewriteResult
require.NotEmpty(t, rr.Response)
resps := rr.Response[dtyp]
require.Len(t, resps, 1)
ptr, ok := resps[0].(string)
require.True(t, ok)
assert.Equal(t, "new-ptr-with-dot.", ptr)
})
}
``` | /content/code_sandbox/internal/filtering/dnsrewrite_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,674 |
```go
package filtering
import (
"encoding/json"
"net/http"
"slices"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/log"
)
// TODO(d.kolyshev): Use [rewrite.Item] instead.
type rewriteEntryJSON struct {
Domain string `json:"domain"`
Answer string `json:"answer"`
}
// handleRewriteList is the handler for the GET /control/rewrite/list HTTP API.
func (d *DNSFilter) handleRewriteList(w http.ResponseWriter, r *http.Request) {
arr := []*rewriteEntryJSON{}
func() {
d.confMu.RLock()
defer d.confMu.RUnlock()
for _, ent := range d.conf.Rewrites {
jsonEnt := rewriteEntryJSON{
Domain: ent.Domain,
Answer: ent.Answer,
}
arr = append(arr, &jsonEnt)
}
}()
aghhttp.WriteJSONResponseOK(w, r, arr)
}
// handleRewriteAdd is the handler for the POST /control/rewrite/add HTTP API.
func (d *DNSFilter) handleRewriteAdd(w http.ResponseWriter, r *http.Request) {
rwJSON := rewriteEntryJSON{}
err := json.NewDecoder(r.Body).Decode(&rwJSON)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json.Decode: %s", err)
return
}
rw := &LegacyRewrite{
Domain: rwJSON.Domain,
Answer: rwJSON.Answer,
}
err = rw.normalize()
if err != nil {
// Shouldn't happen currently, since normalize only returns a non-nil
// error when a rewrite is nil, but be change-proof.
aghhttp.Error(r, w, http.StatusBadRequest, "normalizing: %s", err)
return
}
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.Rewrites = append(d.conf.Rewrites, rw)
log.Debug(
"rewrite: added element: %s -> %s [%d]",
rw.Domain,
rw.Answer,
len(d.conf.Rewrites),
)
}()
d.conf.ConfigModified()
}
// handleRewriteDelete is the handler for the POST /control/rewrite/delete HTTP
// API.
func (d *DNSFilter) handleRewriteDelete(w http.ResponseWriter, r *http.Request) {
jsent := rewriteEntryJSON{}
err := json.NewDecoder(r.Body).Decode(&jsent)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json.Decode: %s", err)
return
}
entDel := &LegacyRewrite{
Domain: jsent.Domain,
Answer: jsent.Answer,
}
arr := []*LegacyRewrite{}
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
for _, ent := range d.conf.Rewrites {
if ent.equal(entDel) {
log.Debug("rewrite: removed element: %s -> %s", ent.Domain, ent.Answer)
continue
}
arr = append(arr, ent)
}
d.conf.Rewrites = arr
}()
d.conf.ConfigModified()
}
// rewriteUpdateJSON is a struct for JSON object with rewrite rule update info.
type rewriteUpdateJSON struct {
Target rewriteEntryJSON `json:"target"`
Update rewriteEntryJSON `json:"update"`
}
// handleRewriteUpdate is the handler for the PUT /control/rewrite/update HTTP
// API.
func (d *DNSFilter) handleRewriteUpdate(w http.ResponseWriter, r *http.Request) {
updateJSON := rewriteUpdateJSON{}
err := json.NewDecoder(r.Body).Decode(&updateJSON)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json.Decode: %s", err)
return
}
rwDel := &LegacyRewrite{
Domain: updateJSON.Target.Domain,
Answer: updateJSON.Target.Answer,
}
rwAdd := &LegacyRewrite{
Domain: updateJSON.Update.Domain,
Answer: updateJSON.Update.Answer,
}
err = rwAdd.normalize()
if err != nil {
// Shouldn't happen currently, since normalize only returns a non-nil
// error when a rewrite is nil, but be change-proof.
aghhttp.Error(r, w, http.StatusBadRequest, "normalizing: %s", err)
return
}
index := -1
defer func() {
if index >= 0 {
d.conf.ConfigModified()
}
}()
d.confMu.Lock()
defer d.confMu.Unlock()
index = slices.IndexFunc(d.conf.Rewrites, rwDel.equal)
if index == -1 {
aghhttp.Error(r, w, http.StatusBadRequest, "target rule not found")
return
}
d.conf.Rewrites = slices.Replace(d.conf.Rewrites, index, index+1, rwAdd)
log.Debug("rewrite: removed element: %s -> %s", rwDel.Domain, rwDel.Answer)
log.Debug("rewrite: added element: %s -> %s", rwAdd.Domain, rwAdd.Answer)
}
``` | /content/code_sandbox/internal/filtering/rewritehttp.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,121 |
```go
package filtering
import (
"encoding/json"
"fmt"
"net/http"
"slices"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/AdGuardHome/internal/schedule"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/urlfilter/rules"
)
// serviceRules maps a service ID to its filtering rules.
var serviceRules map[string][]*rules.NetworkRule
// serviceIDs contains service IDs sorted alphabetically.
var serviceIDs []string
// initBlockedServices initializes package-level blocked service data.
func initBlockedServices() {
l := len(blockedServices)
serviceIDs = make([]string, l)
serviceRules = make(map[string][]*rules.NetworkRule, l)
for i, s := range blockedServices {
netRules := make([]*rules.NetworkRule, 0, len(s.Rules))
for _, text := range s.Rules {
rule, err := rules.NewNetworkRule(text, rulelist.URLFilterIDBlockedService)
if err != nil {
log.Error("parsing blocked service %q rule %q: %s", s.ID, text, err)
continue
}
netRules = append(netRules, rule)
}
serviceIDs[i] = s.ID
serviceRules[s.ID] = netRules
}
slices.Sort(serviceIDs)
log.Debug("filtering: initialized %d services", l)
}
// BlockedServices is the configuration of blocked services.
type BlockedServices struct {
// Schedule is blocked services schedule for every day of the week.
Schedule *schedule.Weekly `json:"schedule" yaml:"schedule"`
// IDs is the names of blocked services.
IDs []string `json:"ids" yaml:"ids"`
}
// Clone returns a deep copy of blocked services.
func (s *BlockedServices) Clone() (c *BlockedServices) {
if s == nil {
return nil
}
return &BlockedServices{
Schedule: s.Schedule.Clone(),
IDs: slices.Clone(s.IDs),
}
}
// Validate returns an error if blocked services contain unknown service ID. s
// must not be nil.
func (s *BlockedServices) Validate() (err error) {
for _, id := range s.IDs {
_, ok := serviceRules[id]
if !ok {
return fmt.Errorf("unknown blocked-service %q", id)
}
}
return nil
}
// ApplyBlockedServices - set blocked services settings for this DNS request
func (d *DNSFilter) ApplyBlockedServices(setts *Settings) {
d.confMu.RLock()
defer d.confMu.RUnlock()
setts.ServicesRules = []ServiceEntry{}
bsvc := d.conf.BlockedServices
// TODO(s.chzhen): Use startTime from [dnsforward.dnsContext].
if !bsvc.Schedule.Contains(time.Now()) {
d.ApplyBlockedServicesList(setts, bsvc.IDs)
}
}
// ApplyBlockedServicesList appends filtering rules to the settings.
func (d *DNSFilter) ApplyBlockedServicesList(setts *Settings, list []string) {
for _, name := range list {
rules, ok := serviceRules[name]
if !ok {
log.Error("unknown service name: %s", name)
continue
}
setts.ServicesRules = append(setts.ServicesRules, ServiceEntry{
Name: name,
Rules: rules,
})
}
}
func (d *DNSFilter) handleBlockedServicesIDs(w http.ResponseWriter, r *http.Request) {
aghhttp.WriteJSONResponseOK(w, r, serviceIDs)
}
func (d *DNSFilter) handleBlockedServicesAll(w http.ResponseWriter, r *http.Request) {
aghhttp.WriteJSONResponseOK(w, r, struct {
BlockedServices []blockedService `json:"blocked_services"`
}{
BlockedServices: blockedServices,
})
}
// handleBlockedServicesList is the handler for the GET
// /control/blocked_services/list HTTP API.
//
// Deprecated: Use handleBlockedServicesGet.
func (d *DNSFilter) handleBlockedServicesList(w http.ResponseWriter, r *http.Request) {
var list []string
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
list = d.conf.BlockedServices.IDs
}()
aghhttp.WriteJSONResponseOK(w, r, list)
}
// handleBlockedServicesSet is the handler for the POST
// /control/blocked_services/set HTTP API.
//
// Deprecated: Use handleBlockedServicesUpdate.
func (d *DNSFilter) handleBlockedServicesSet(w http.ResponseWriter, r *http.Request) {
list := []string{}
err := json.NewDecoder(r.Body).Decode(&list)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json.Decode: %s", err)
return
}
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.BlockedServices.IDs = list
log.Debug("Updated blocked services list: %d", len(list))
}()
d.conf.ConfigModified()
}
// handleBlockedServicesGet is the handler for the GET
// /control/blocked_services/get HTTP API.
func (d *DNSFilter) handleBlockedServicesGet(w http.ResponseWriter, r *http.Request) {
var bsvc *BlockedServices
func() {
d.confMu.RLock()
defer d.confMu.RUnlock()
bsvc = d.conf.BlockedServices.Clone()
}()
aghhttp.WriteJSONResponseOK(w, r, bsvc)
}
// handleBlockedServicesUpdate is the handler for the PUT
// /control/blocked_services/update HTTP API.
func (d *DNSFilter) handleBlockedServicesUpdate(w http.ResponseWriter, r *http.Request) {
bsvc := &BlockedServices{}
err := json.NewDecoder(r.Body).Decode(bsvc)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json.Decode: %s", err)
return
}
err = bsvc.Validate()
if err != nil {
aghhttp.Error(r, w, http.StatusUnprocessableEntity, "validating: %s", err)
return
}
if bsvc.Schedule == nil {
bsvc.Schedule = schedule.EmptyWeekly()
}
func() {
d.confMu.Lock()
defer d.confMu.Unlock()
d.conf.BlockedServices = bsvc
}()
log.Debug("updated blocked services schedule: %d", len(bsvc.IDs))
d.conf.ConfigModified()
}
``` | /content/code_sandbox/internal/filtering/blocked.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,407 |
```go
package filtering
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDNSFilter_handleFilteringSetURL(t *testing.T) {
filtersDir := t.TempDir()
var goodRulesEndpoint, anotherGoodRulesEndpoint, badRulesEndpoint string
for _, rulesSource := range []struct {
endpoint *string
content []byte
}{{
endpoint: &goodRulesEndpoint,
content: []byte(`||example.org^`),
}, {
endpoint: &anotherGoodRulesEndpoint,
content: []byte(`||example.com^`),
}, {
endpoint: &badRulesEndpoint,
content: []byte(`<html></html>`),
}} {
*rulesSource.endpoint = serveFiltersLocally(t, rulesSource.content)
}
testCases := []struct {
name string
wantBody string
oldURL string
newName string
newURL string
initial []FilterYAML
}{{
name: "success",
wantBody: "",
oldURL: goodRulesEndpoint,
newName: "default_one",
newURL: anotherGoodRulesEndpoint,
initial: []FilterYAML{{
Enabled: true,
URL: goodRulesEndpoint,
Name: "default_one",
white: false,
}},
}, {
name: "non-existing",
wantBody: "url doesn't exist\n",
oldURL: anotherGoodRulesEndpoint,
newName: "default_one",
newURL: goodRulesEndpoint,
initial: []FilterYAML{{
Enabled: true,
URL: goodRulesEndpoint,
Name: "default_one",
white: false,
}},
}, {
name: "existing",
wantBody: "url already exists\n",
oldURL: goodRulesEndpoint,
newName: "default_one",
newURL: anotherGoodRulesEndpoint,
initial: []FilterYAML{{
Enabled: true,
URL: goodRulesEndpoint,
Name: "default_one",
white: false,
}, {
Enabled: true,
URL: anotherGoodRulesEndpoint,
Name: "another_default_one",
white: false,
}},
}, {
name: "bad_rules",
wantBody: "data is HTML, not plain text\n",
oldURL: goodRulesEndpoint,
newName: "default_one",
newURL: badRulesEndpoint,
initial: []FilterYAML{{
Enabled: true,
URL: goodRulesEndpoint,
Name: "default_one",
white: false,
}},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
confModifiedCalled := false
d, err := New(&Config{
FilteringEnabled: true,
Filters: tc.initial,
HTTPClient: &http.Client{
Timeout: 5 * time.Second,
},
ConfigModified: func() { confModifiedCalled = true },
DataDir: filtersDir,
}, nil)
require.NoError(t, err)
t.Cleanup(d.Close)
d.Start()
reqData := &filterURLReq{
Data: &filterURLReqData{
// Leave the name of an existing list.
Name: tc.newName,
URL: tc.newURL,
Enabled: true,
},
URL: tc.oldURL,
Whitelist: false,
}
data, err := json.Marshal(reqData)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodPost, "path_to_url", bytes.NewReader(data))
w := httptest.NewRecorder()
d.handleFilteringSetURL(w, r)
assert.Equal(t, tc.wantBody, w.Body.String())
// For the moment the non-empty response body only contains occurred
// error, so the configuration shouldn't be written.
assert.Equal(t, tc.wantBody == "", confModifiedCalled)
})
}
}
func TestDNSFilter_handleSafeBrowsingStatus(t *testing.T) {
const (
testTimeout = time.Second
statusURL = "/control/safebrowsing/status"
)
confModCh := make(chan struct{})
filtersDir := t.TempDir()
testCases := []struct {
name string
url string
enabled bool
wantStatus assert.BoolAssertionFunc
}{{
name: "enable_off",
url: "/control/safebrowsing/enable",
enabled: false,
wantStatus: assert.True,
}, {
name: "enable_on",
url: "/control/safebrowsing/enable",
enabled: true,
wantStatus: assert.True,
}, {
name: "disable_on",
url: "/control/safebrowsing/disable",
enabled: true,
wantStatus: assert.False,
}, {
name: "disable_off",
url: "/control/safebrowsing/disable",
enabled: false,
wantStatus: assert.False,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
handlers := make(map[string]http.Handler)
d, err := New(&Config{
ConfigModified: func() {
testutil.RequireSend(testutil.PanicT{}, confModCh, struct{}{}, testTimeout)
},
DataDir: filtersDir,
HTTPRegister: func(_, url string, handler http.HandlerFunc) {
handlers[url] = handler
},
SafeBrowsingEnabled: tc.enabled,
}, nil)
require.NoError(t, err)
t.Cleanup(d.Close)
d.RegisterFilteringHandlers()
require.NotEmpty(t, handlers)
require.Contains(t, handlers, statusURL)
r := httptest.NewRequest(http.MethodPost, tc.url, nil)
w := httptest.NewRecorder()
go handlers[tc.url].ServeHTTP(w, r)
testutil.RequireReceive(t, confModCh, testTimeout)
r = httptest.NewRequest(http.MethodGet, statusURL, nil)
w = httptest.NewRecorder()
handlers[statusURL].ServeHTTP(w, r)
require.Equal(t, http.StatusOK, w.Code)
status := struct {
Enabled bool `json:"enabled"`
}{
Enabled: false,
}
err = json.NewDecoder(w.Body).Decode(&status)
require.NoError(t, err)
tc.wantStatus(t, status.Enabled)
})
}
}
func TestDNSFilter_handleParentalStatus(t *testing.T) {
const (
testTimeout = time.Second
statusURL = "/control/parental/status"
)
confModCh := make(chan struct{})
filtersDir := t.TempDir()
testCases := []struct {
name string
url string
enabled bool
wantStatus assert.BoolAssertionFunc
}{{
name: "enable_off",
url: "/control/parental/enable",
enabled: false,
wantStatus: assert.True,
}, {
name: "enable_on",
url: "/control/parental/enable",
enabled: true,
wantStatus: assert.True,
}, {
name: "disable_on",
url: "/control/parental/disable",
enabled: true,
wantStatus: assert.False,
}, {
name: "disable_off",
url: "/control/parental/disable",
enabled: false,
wantStatus: assert.False,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
handlers := make(map[string]http.Handler)
d, err := New(&Config{
ConfigModified: func() {
testutil.RequireSend(testutil.PanicT{}, confModCh, struct{}{}, testTimeout)
},
DataDir: filtersDir,
HTTPRegister: func(_, url string, handler http.HandlerFunc) {
handlers[url] = handler
},
ParentalEnabled: tc.enabled,
}, nil)
require.NoError(t, err)
t.Cleanup(d.Close)
d.RegisterFilteringHandlers()
require.NotEmpty(t, handlers)
require.Contains(t, handlers, statusURL)
r := httptest.NewRequest(http.MethodPost, tc.url, nil)
w := httptest.NewRecorder()
go handlers[tc.url].ServeHTTP(w, r)
testutil.RequireReceive(t, confModCh, testTimeout)
r = httptest.NewRequest(http.MethodGet, statusURL, nil)
w = httptest.NewRecorder()
handlers[statusURL].ServeHTTP(w, r)
require.Equal(t, http.StatusOK, w.Code)
status := struct {
Enabled bool `json:"enabled"`
}{
Enabled: false,
}
err = json.NewDecoder(w.Body).Decode(&status)
require.NoError(t, err)
tc.wantStatus(t, status.Enabled)
})
}
}
``` | /content/code_sandbox/internal/filtering/http_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,063 |
```go
package filtering
import (
"net"
"net/netip"
"testing"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TODO(e.burkov): All the tests in this file may and should me merged together.
func TestRewrites(t *testing.T) {
d, _ := newForTest(t, nil, nil)
t.Cleanup(d.Close)
var (
addr1v4 = netip.AddrFrom4([4]byte{1, 2, 3, 4})
addr2v4 = netip.AddrFrom4([4]byte{1, 2, 3, 5})
addr3v4 = netip.AddrFrom4([4]byte{1, 2, 3, 6})
addr4v4 = netip.AddrFrom4([4]byte{1, 2, 3, 7})
addr1v6 = netip.MustParseAddr("1:2:3::4")
addr2v6 = netip.MustParseAddr("1234::5678")
)
d.conf.Rewrites = []*LegacyRewrite{{
// This one and below are about CNAME, A and AAAA.
Domain: "somecname",
Answer: "somehost.com",
}, {
Domain: "somehost.com",
Answer: netip.IPv4Unspecified().String(),
}, {
Domain: "host.com",
Answer: addr1v4.String(),
}, {
Domain: "host.com",
Answer: addr2v4.String(),
}, {
Domain: "host.com",
Answer: addr1v6.String(),
}, {
Domain: "www.host.com",
Answer: "host.com",
}, {
// This one is a wildcard.
Domain: "*.host.com",
Answer: addr2v4.String(),
}, {
// This one and below are about wildcard overriding.
Domain: "a.host.com",
Answer: addr1v4.String(),
}, {
// This one is about CNAME and wildcard interacting.
Domain: "*.host2.com",
Answer: "host.com",
}, {
// This one and below are about 2 level CNAME.
Domain: "b.host.com",
Answer: "somecname",
}, {
// This one and below are about 2 level CNAME and wildcard.
Domain: "b.host3.com",
Answer: "a.host3.com",
}, {
Domain: "a.host3.com",
Answer: "x.host.com",
}, {
Domain: "*.hostboth.com",
Answer: addr3v4.String(),
}, {
Domain: "*.hostboth.com",
Answer: addr2v6.String(),
}, {
Domain: "BIGHOST.COM",
Answer: addr4v4.String(),
}, {
Domain: "*.issue4016.com",
Answer: "sub.issue4016.com",
}, {
Domain: "*.sub.issue6226.com",
Answer: addr2v4.String(),
}, {
Domain: "*.issue6226.com",
Answer: addr1v4.String(),
}}
require.NoError(t, d.prepareRewrites())
testCases := []struct {
name string
host string
wantCName string
wantIPs []netip.Addr
wantReason Reason
dtyp uint16
}{{
name: "not_filtered_not_found",
host: "hoost.com",
wantCName: "",
wantIPs: nil,
wantReason: NotFilteredNotFound,
dtyp: dns.TypeA,
}, {
name: "rewritten_a",
host: "www.host.com",
wantCName: "host.com",
wantIPs: []netip.Addr{addr1v4, addr2v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "rewritten_aaaa",
host: "www.host.com",
wantCName: "host.com",
wantIPs: []netip.Addr{addr1v6},
wantReason: Rewritten,
dtyp: dns.TypeAAAA,
}, {
name: "wildcard_match",
host: "abc.host.com",
wantCName: "",
wantIPs: []netip.Addr{addr2v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "wildcard_override",
host: "a.host.com",
wantCName: "",
wantIPs: []netip.Addr{addr1v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "wildcard_cname_interaction",
host: "www.host2.com",
wantCName: "host.com",
wantIPs: []netip.Addr{addr1v4, addr2v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "two_cnames",
host: "b.host.com",
wantCName: "somehost.com",
wantIPs: []netip.Addr{netip.IPv4Unspecified()},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "two_cnames_and_wildcard",
host: "b.host3.com",
wantCName: "x.host.com",
wantIPs: []netip.Addr{addr2v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "issue3343",
host: "www.hostboth.com",
wantCName: "",
wantIPs: []netip.Addr{addr2v6},
wantReason: Rewritten,
dtyp: dns.TypeAAAA,
}, {
name: "issue3351",
host: "bighost.com",
wantCName: "",
wantIPs: []netip.Addr{addr4v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "issue4008",
host: "somehost.com",
wantCName: "",
wantIPs: nil,
wantReason: Rewritten,
dtyp: dns.TypeHTTPS,
}, {
name: "issue4016",
host: "www.issue4016.com",
wantCName: "sub.issue4016.com",
wantIPs: nil,
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "issue4016_self",
host: "sub.issue4016.com",
wantCName: "",
wantIPs: nil,
wantReason: NotFilteredNotFound,
dtyp: dns.TypeA,
}, {
name: "issue6226",
host: "www.issue6226.com",
wantCName: "",
wantIPs: []netip.Addr{addr1v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}, {
name: "issue6226_sub",
host: "www.sub.issue6226.com",
wantCName: "",
wantIPs: []netip.Addr{addr2v4},
wantReason: Rewritten,
dtyp: dns.TypeA,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := d.processRewrites(tc.host, tc.dtyp)
require.Equalf(t, tc.wantReason, r.Reason, "got %s", r.Reason)
if tc.wantCName != "" {
assert.Equal(t, tc.wantCName, r.CanonName)
}
assert.Equal(t, tc.wantIPs, r.IPList)
})
}
}
func TestRewritesLevels(t *testing.T) {
d, _ := newForTest(t, nil, nil)
t.Cleanup(d.Close)
// Exact host, wildcard L2, wildcard L3.
d.conf.Rewrites = []*LegacyRewrite{{
Domain: "host.com",
Answer: "1.1.1.1",
Type: dns.TypeA,
}, {
Domain: "*.host.com",
Answer: "2.2.2.2",
Type: dns.TypeA,
}, {
Domain: "*.sub.host.com",
Answer: "3.3.3.3",
Type: dns.TypeA,
}}
require.NoError(t, d.prepareRewrites())
testCases := []struct {
name string
host string
want net.IP
}{{
name: "exact_match",
host: "host.com",
want: net.IP{1, 1, 1, 1},
}, {
name: "l2_match",
host: "sub.host.com",
want: net.IP{2, 2, 2, 2},
}, {
name: "l3_match",
host: "my.sub.host.com",
want: net.IP{3, 3, 3, 3},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := d.processRewrites(tc.host, dns.TypeA)
assert.Equal(t, Rewritten, r.Reason)
require.Len(t, r.IPList, 1)
})
}
}
func TestRewritesExceptionCNAME(t *testing.T) {
d, _ := newForTest(t, nil, nil)
t.Cleanup(d.Close)
// Wildcard and exception for a sub-domain.
d.conf.Rewrites = []*LegacyRewrite{{
Domain: "*.host.com",
Answer: "2.2.2.2",
}, {
Domain: "sub.host.com",
Answer: "sub.host.com",
}, {
Domain: "*.sub.host.com",
Answer: "*.sub.host.com",
}}
require.NoError(t, d.prepareRewrites())
testCases := []struct {
name string
host string
want netip.Addr
}{{
name: "match_subdomain",
host: "my.host.com",
want: netip.AddrFrom4([4]byte{2, 2, 2, 2}),
}, {
name: "exception_cname",
host: "sub.host.com",
want: netip.Addr{},
}, {
name: "exception_wildcard",
host: "my.sub.host.com",
want: netip.Addr{},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := d.processRewrites(tc.host, dns.TypeA)
if tc.want == (netip.Addr{}) {
assert.Equal(t, NotFilteredNotFound, r.Reason, "got %s", r.Reason)
return
}
assert.Equal(t, Rewritten, r.Reason)
require.Len(t, r.IPList, 1)
assert.Equal(t, tc.want, r.IPList[0])
})
}
}
func TestRewritesExceptionIP(t *testing.T) {
d, _ := newForTest(t, nil, nil)
t.Cleanup(d.Close)
// Exception for AAAA record.
d.conf.Rewrites = []*LegacyRewrite{{
Domain: "host.com",
Answer: "1.2.3.4",
Type: dns.TypeA,
}, {
Domain: "host.com",
Answer: "AAAA",
Type: dns.TypeAAAA,
}, {
Domain: "host2.com",
Answer: "::1",
Type: dns.TypeAAAA,
}, {
Domain: "host2.com",
Answer: "A",
Type: dns.TypeA,
}, {
Domain: "host3.com",
Answer: "A",
Type: dns.TypeA,
}}
require.NoError(t, d.prepareRewrites())
testCases := []struct {
name string
host string
want []netip.Addr
dtyp uint16
wantReason Reason
}{{
name: "match_A",
host: "host.com",
want: []netip.Addr{netip.AddrFrom4([4]byte{1, 2, 3, 4})},
dtyp: dns.TypeA,
wantReason: Rewritten,
}, {
name: "exception_AAAA_host.com",
host: "host.com",
want: nil,
dtyp: dns.TypeAAAA,
wantReason: NotFilteredNotFound,
}, {
name: "exception_A_host2.com",
host: "host2.com",
want: nil,
dtyp: dns.TypeA,
wantReason: NotFilteredNotFound,
}, {
name: "match_AAAA_host2.com",
host: "host2.com",
want: []netip.Addr{netip.MustParseAddr("::1")},
dtyp: dns.TypeAAAA,
wantReason: Rewritten,
}, {
name: "exception_A_host3.com",
host: "host3.com",
want: nil,
dtyp: dns.TypeA,
wantReason: NotFilteredNotFound,
}, {
name: "match_AAAA_host3.com",
host: "host3.com",
want: nil,
dtyp: dns.TypeAAAA,
wantReason: Rewritten,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if tc.name != "match_AAAA_host3.com" {
t.SkipNow()
}
r := d.processRewrites(tc.host, tc.dtyp)
assert.Equal(t, tc.want, r.IPList)
assert.Equal(t, tc.wantReason, r.Reason)
})
}
}
``` | /content/code_sandbox/internal/filtering/rewrites_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,164 |
```go
// Package hashprefix used for safe browsing and parent control.
package hashprefix
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"slices"
"strings"
"time"
"github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/stringutil"
"github.com/miekg/dns"
"golang.org/x/net/publicsuffix"
)
const (
// prefixLen is the length of the hash prefix of the filtered hostname.
prefixLen = 2
// hashSize is the size of hashed hostname.
hashSize = sha256.Size
// hexSize is the size of hexadecimal representation of hashed hostname.
hexSize = hashSize * 2
)
// prefix is the type of the SHA256 hash prefix used to match against the
// domain-name database.
type prefix [prefixLen]byte
// hostnameHash is the hashed hostname.
//
// TODO(s.chzhen): Split into prefix and suffix.
type hostnameHash [hashSize]byte
// findMatch returns true if one of the a hostnames matches one of the b.
func findMatch(a, b []hostnameHash) (matched bool) {
for _, hash := range a {
if slices.Contains(b, hash) {
return true
}
}
return false
}
// Config is the configuration structure for safe browsing and parental
// control.
type Config struct {
// Upstream is the upstream DNS server.
Upstream upstream.Upstream
// ServiceName is the name of the service.
ServiceName string
// TXTSuffix is the TXT suffix for DNS request.
TXTSuffix string
// CacheTime is the time period to store hash.
CacheTime time.Duration
// CacheSize is the maximum size of the cache. If it's zero, cache size is
// unlimited.
CacheSize uint
}
type Checker struct {
// upstream is the upstream DNS server.
upstream upstream.Upstream
// cache stores hostname hashes.
cache cache.Cache
// svc is the name of the service.
svc string
// txtSuffix is the TXT suffix for DNS request.
txtSuffix string
// cacheTime is the time period to store hash.
cacheTime time.Duration
}
// New returns Checker.
func New(conf *Config) (c *Checker) {
return &Checker{
upstream: conf.Upstream,
cache: cache.New(cache.Config{
EnableLRU: true,
MaxSize: conf.CacheSize,
}),
svc: conf.ServiceName,
txtSuffix: conf.TXTSuffix,
cacheTime: conf.CacheTime,
}
}
// Check returns true if request for the host should be blocked.
func (c *Checker) Check(host string) (ok bool, err error) {
hashes := hostnameToHashes(host)
found, blocked, hashesToRequest := c.findInCache(hashes)
if found {
log.Debug("%s: found %q in cache, blocked: %t", c.svc, host, blocked)
return blocked, nil
}
question := c.getQuestion(hashesToRequest)
log.Debug("%s: checking %s: %s", c.svc, host, question)
req := (&dns.Msg{}).SetQuestion(question, dns.TypeTXT)
resp, err := c.upstream.Exchange(req)
if err != nil {
return false, fmt.Errorf("getting hashes: %w", err)
}
matched, receivedHashes := c.processAnswer(hashesToRequest, resp, host)
c.storeInCache(hashesToRequest, receivedHashes)
return matched, nil
}
// hostnameToHashes returns hashes that should be checked by the hash prefix
// filter.
func hostnameToHashes(host string) (hashes []hostnameHash) {
// subDomainNum defines how many labels should be hashed to match against a
// hash prefix filter.
const subDomainNum = 4
pubSuf, icann := publicsuffix.PublicSuffix(host)
if !icann {
// Check the full private domain space.
pubSuf = ""
}
nDots := 0
i := strings.LastIndexFunc(host, func(r rune) (ok bool) {
if r == '.' {
nDots++
}
return nDots == subDomainNum
})
if i != -1 {
host = host[i+1:]
}
sub := netutil.Subdomains(host)
for _, s := range sub {
if s == pubSuf {
break
}
sum := sha256.Sum256([]byte(s))
hashes = append(hashes, sum)
}
return hashes
}
// getQuestion combines hexadecimal encoded prefixes of hashed hostnames into
// string.
func (c *Checker) getQuestion(hashes []hostnameHash) (q string) {
b := &strings.Builder{}
for _, hash := range hashes {
stringutil.WriteToBuilder(b, hex.EncodeToString(hash[:prefixLen]), ".")
}
stringutil.WriteToBuilder(b, c.txtSuffix)
return b.String()
}
// processAnswer returns true if DNS response matches the hash, and received
// hashed hostnames from the upstream.
func (c *Checker) processAnswer(
hashesToRequest []hostnameHash,
resp *dns.Msg,
host string,
) (matched bool, receivedHashes []hostnameHash) {
txtCount := 0
for _, a := range resp.Answer {
txt, ok := a.(*dns.TXT)
if !ok {
continue
}
txtCount++
receivedHashes = c.appendHashesFromTXT(receivedHashes, txt, host)
}
log.Debug("%s: received answer for %s with %d TXT count", c.svc, host, txtCount)
matched = findMatch(hashesToRequest, receivedHashes)
if matched {
log.Debug("%s: matched %s", c.svc, host)
return true, receivedHashes
}
return false, receivedHashes
}
// appendHashesFromTXT appends received hashed hostnames.
func (c *Checker) appendHashesFromTXT(
hashes []hostnameHash,
txt *dns.TXT,
host string,
) (receivedHashes []hostnameHash) {
log.Debug("%s: received hashes for %s: %v", c.svc, host, txt.Txt)
for _, t := range txt.Txt {
if len(t) != hexSize {
log.Debug("%s: wrong hex size %d for %s %s", c.svc, len(t), host, t)
continue
}
buf, err := hex.DecodeString(t)
if err != nil {
log.Debug("%s: decoding hex string %s: %s", c.svc, t, err)
continue
}
var hash hostnameHash
copy(hash[:], buf)
hashes = append(hashes, hash)
}
return hashes
}
``` | /content/code_sandbox/internal/filtering/hashprefix/hashprefix.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,509 |
```go
package hashprefix
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestCacheItem(t *testing.T) {
item := &cacheItem{
expiry: time.Unix(0x01_23_45_67_89_AB_CD_EF, 0),
hashes: []hostnameHash{{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
}, {
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
}},
}
wantData := []byte{
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
0x01, 0x03, 0x05, 0x07, 0x02, 0x04, 0x06, 0x08,
}
gotData := fromCacheItem(item)
assert.Equal(t, wantData, gotData)
newItem := toCacheItem(gotData)
gotData = fromCacheItem(newItem)
assert.Equal(t, wantData, gotData)
}
``` | /content/code_sandbox/internal/filtering/hashprefix/cache_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 834 |
```go
package hashprefix
import (
"crypto/sha256"
"encoding/hex"
"slices"
"strings"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghtest"
"github.com/AdguardTeam/golibs/cache"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
cacheTime = 10 * time.Minute
cacheSize = 10000
)
func TestChcker_getQuestion(t *testing.T) {
const suf = "sb.dns.adguard.com."
// test hostnameToHashes()
hashes := hostnameToHashes("1.2.3.sub.host.com")
assert.Len(t, hashes, 3)
hash := hostnameHash(sha256.Sum256([]byte("3.sub.host.com")))
hexPref1 := hex.EncodeToString(hash[:prefixLen])
assert.True(t, slices.Contains(hashes, hash))
hash = sha256.Sum256([]byte("sub.host.com"))
hexPref2 := hex.EncodeToString(hash[:prefixLen])
assert.True(t, slices.Contains(hashes, hash))
hash = sha256.Sum256([]byte("host.com"))
hexPref3 := hex.EncodeToString(hash[:prefixLen])
assert.True(t, slices.Contains(hashes, hash))
hash = sha256.Sum256([]byte("com"))
assert.False(t, slices.Contains(hashes, hash))
c := &Checker{
svc: "SafeBrowsing",
txtSuffix: suf,
}
q := c.getQuestion(hashes)
assert.Contains(t, q, hexPref1)
assert.Contains(t, q, hexPref2)
assert.Contains(t, q, hexPref3)
assert.True(t, strings.HasSuffix(q, suf))
}
func TestHostnameToHashes(t *testing.T) {
testCases := []struct {
name string
host string
wantLen int
}{{
name: "basic",
host: "example.com",
wantLen: 1,
}, {
name: "sub_basic",
host: "www.example.com",
wantLen: 2,
}, {
name: "private_domain",
host: "foo.co.uk",
wantLen: 1,
}, {
name: "sub_private_domain",
host: "bar.foo.co.uk",
wantLen: 2,
}, {
name: "private_domain_v2",
host: "foo.blogspot.co.uk",
wantLen: 4,
}, {
name: "sub_private_domain_v2",
host: "bar.foo.blogspot.co.uk",
wantLen: 4,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
hashes := hostnameToHashes(tc.host)
assert.Len(t, hashes, tc.wantLen)
})
}
}
func TestChecker_storeInCache(t *testing.T) {
c := &Checker{
svc: "SafeBrowsing",
cacheTime: cacheTime,
}
conf := cache.Config{}
c.cache = cache.New(conf)
// store in cache hashes for "3.sub.host.com" and "host.com"
// and empty data for hash-prefix for "sub.host.com"
hashes := []hostnameHash{}
hash := hostnameHash(sha256.Sum256([]byte("sub.host.com")))
hashes = append(hashes, hash)
var hashesArray []hostnameHash
hash4 := sha256.Sum256([]byte("3.sub.host.com"))
hashesArray = append(hashesArray, hash4)
hash2 := sha256.Sum256([]byte("host.com"))
hashesArray = append(hashesArray, hash2)
c.storeInCache(hashes, hashesArray)
// match "3.sub.host.com" or "host.com" from cache
hashes = []hostnameHash{}
hash = sha256.Sum256([]byte("3.sub.host.com"))
hashes = append(hashes, hash)
hash = sha256.Sum256([]byte("sub.host.com"))
hashes = append(hashes, hash)
hash = sha256.Sum256([]byte("host.com"))
hashes = append(hashes, hash)
found, blocked, _ := c.findInCache(hashes)
assert.True(t, found)
assert.True(t, blocked)
// match "sub.host.com" from cache
hashes = []hostnameHash{}
hash = sha256.Sum256([]byte("sub.host.com"))
hashes = append(hashes, hash)
found, blocked, _ = c.findInCache(hashes)
assert.True(t, found)
assert.False(t, blocked)
// Match "sub.host.com" from cache. Another hash for "host.example" is not
// in the cache, so get data for it from the server.
hashes = []hostnameHash{}
hash = sha256.Sum256([]byte("sub.host.com"))
hashes = append(hashes, hash)
hash = sha256.Sum256([]byte("host.example"))
hashes = append(hashes, hash)
found, _, hashesToRequest := c.findInCache(hashes)
assert.False(t, found)
hash = sha256.Sum256([]byte("sub.host.com"))
ok := slices.Contains(hashesToRequest, hash)
assert.False(t, ok)
hash = sha256.Sum256([]byte("host.example"))
ok = slices.Contains(hashesToRequest, hash)
assert.True(t, ok)
c = &Checker{
svc: "SafeBrowsing",
cacheTime: cacheTime,
}
c.cache = cache.New(cache.Config{})
hashes = []hostnameHash{}
hash = sha256.Sum256([]byte("sub.host.com"))
hashes = append(hashes, hash)
c.cache.Set(hash[:prefixLen], make([]byte, expirySize+hashSize))
found, _, _ = c.findInCache(hashes)
assert.False(t, found)
}
func TestChecker_Check(t *testing.T) {
const hostname = "example.org"
testCases := []struct {
name string
wantBlock bool
}{{
name: "sb_no_block",
wantBlock: false,
}, {
name: "sb_block",
wantBlock: true,
}, {
name: "pc_no_block",
wantBlock: false,
}, {
name: "pc_block",
wantBlock: true,
}}
for _, tc := range testCases {
c := New(&Config{
CacheTime: cacheTime,
CacheSize: cacheSize,
})
// Prepare the upstream.
ups := aghtest.NewBlockUpstream(hostname, tc.wantBlock)
var numReq int
onExchange := ups.OnExchange
ups.OnExchange = func(req *dns.Msg) (resp *dns.Msg, err error) {
numReq++
return onExchange(req)
}
c.upstream = ups
t.Run(tc.name, func(t *testing.T) {
// Firstly, check the request blocking.
hits := 0
res := false
res, err := c.Check(hostname)
require.NoError(t, err)
if tc.wantBlock {
assert.True(t, res)
hits++
} else {
require.False(t, res)
}
// Check the cache state, check the response is now cached.
assert.Equal(t, 1, c.cache.Stats().Count)
assert.Equal(t, hits, c.cache.Stats().Hit)
// There was one request to an upstream.
assert.Equal(t, 1, numReq)
// Now make the same request to check the cache was used.
res, err = c.Check(hostname)
require.NoError(t, err)
if tc.wantBlock {
assert.True(t, res)
} else {
require.False(t, res)
}
// Check the cache state, it should've been used.
assert.Equal(t, 1, c.cache.Stats().Count)
assert.Equal(t, hits+1, c.cache.Stats().Hit)
// Check that there were no additional requests.
assert.Equal(t, 1, numReq)
})
}
}
``` | /content/code_sandbox/internal/filtering/hashprefix/hashprefix_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,750 |
```go
package hashprefix
import (
"encoding/binary"
"time"
"github.com/AdguardTeam/golibs/log"
)
// expirySize is the size of expiry in cacheItem.
const expirySize = 8
// cacheItem represents an item that we will store in the cache.
type cacheItem struct {
// expiry is the time when cacheItem will expire.
expiry time.Time
// hashes is the hashed hostnames.
hashes []hostnameHash
}
// toCacheItem decodes cacheItem from data. data must be at least equal to
// expiry size.
func toCacheItem(data []byte) *cacheItem {
t := time.Unix(int64(binary.BigEndian.Uint64(data)), 0)
data = data[expirySize:]
hashes := make([]hostnameHash, 0, len(data)/hashSize)
for i := 0; i < len(data); i += hashSize {
var hash hostnameHash
copy(hash[:], data[i:i+hashSize])
hashes = append(hashes, hash)
}
return &cacheItem{
expiry: t,
hashes: hashes,
}
}
// fromCacheItem encodes cacheItem into data.
func fromCacheItem(item *cacheItem) (data []byte) {
data = make([]byte, 0, len(item.hashes)*hashSize+expirySize)
expiry := item.expiry.Unix()
data = binary.BigEndian.AppendUint64(data, uint64(expiry))
for _, v := range item.hashes {
data = append(data, v[:]...)
}
return data
}
// findInCache finds hashes in the cache. If nothing found returns list of
// hashes, prefixes of which will be sent to upstream.
func (c *Checker) findInCache(
hashes []hostnameHash,
) (found, blocked bool, hashesToRequest []hostnameHash) {
now := time.Now()
i := 0
for _, hash := range hashes {
data := c.cache.Get(hash[:prefixLen])
if data == nil {
hashes[i] = hash
i++
continue
}
item := toCacheItem(data)
if now.After(item.expiry) {
hashes[i] = hash
i++
continue
}
if ok := findMatch(hashes, item.hashes); ok {
return true, true, nil
}
}
if i == 0 {
return true, false, nil
}
return false, false, hashes[:i]
}
// storeInCache caches hashes.
func (c *Checker) storeInCache(hashesToRequest, respHashes []hostnameHash) {
hashToStore := make(map[prefix][]hostnameHash)
for _, hash := range respHashes {
var pref prefix
copy(pref[:], hash[:])
hashToStore[pref] = append(hashToStore[pref], hash)
}
for pref, hash := range hashToStore {
c.setCache(pref, hash)
}
for _, hash := range hashesToRequest {
val := c.cache.Get(hash[:prefixLen])
if val == nil {
var pref prefix
copy(pref[:], hash[:])
c.setCache(pref, nil)
}
}
}
// setCache stores hash in cache.
func (c *Checker) setCache(pref prefix, hashes []hostnameHash) {
item := &cacheItem{
expiry: time.Now().Add(c.cacheTime),
hashes: hashes,
}
c.cache.Set(pref[:], fromCacheItem(item))
log.Debug("%s: stored in cache: %v", c.svc, pref)
}
``` | /content/code_sandbox/internal/filtering/hashprefix/cache.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 772 |
```go
package rulelist
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghrenameio"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/urlfilter/filterlist"
"github.com/c2h5oh/datasize"
)
// Filter contains information about a single rule-list filter.
//
// TODO(a.garipov): Use.
type Filter struct {
// url is the URL of this rule list. Supported schemes are:
// - http
// - https
// - file
url *url.URL
// ruleList is the last successfully compiled [filterlist.RuleList].
ruleList filterlist.RuleList
// updated is the time of the last successful update.
updated time.Time
// name is the human-readable name of this rule-list filter.
name string
// uid is the unique ID of this rule-list filter.
uid UID
// urlFilterID is used for working with package urlfilter.
urlFilterID URLFilterID
// rulesCount contains the number of rules in this rule-list filter.
rulesCount int
// checksum is a CRC32 hash used to quickly check if the rules within a list
// file have changed.
checksum uint32
// enabled, if true, means that this rule-list filter is used for filtering.
enabled bool
}
// FilterConfig contains the configuration for a [Filter].
type FilterConfig struct {
// URL is the URL of this rule-list filter. Supported schemes are:
// - http
// - https
// - file
URL *url.URL
// Name is the human-readable name of this rule-list filter. If not set, it
// is either taken from the rule-list data or generated synthetically from
// the UID.
Name string
// UID is the unique ID of this rule-list filter.
UID UID
// URLFilterID is used for working with package urlfilter.
URLFilterID URLFilterID
// Enabled, if true, means that this rule-list filter is used for filtering.
Enabled bool
}
// NewFilter creates a new rule-list filter. The filter is not refreshed, so a
// refresh should be performed before use.
func NewFilter(c *FilterConfig) (f *Filter, err error) {
if c.URL == nil {
return nil, errors.Error("no url")
}
switch s := c.URL.Scheme; s {
case "http", "https", "file":
// Go on.
default:
return nil, fmt.Errorf("bad url scheme: %q", s)
}
return &Filter{
url: c.URL,
name: c.Name,
uid: c.UID,
urlFilterID: c.URLFilterID,
enabled: c.Enabled,
}, nil
}
// Refresh updates the data in the rule-list filter. parseBuf is the initial
// buffer used to parse information from the data. cli and maxSize are only
// used when f is a URL-based list.
//
// TODO(a.garipov): Unexport and test in an internal test or through enigne
// tests.
//
// TODO(a.garipov): Consider not returning parseRes.
func (f *Filter) Refresh(
ctx context.Context,
parseBuf []byte,
cli *http.Client,
cacheDir string,
maxSize datasize.ByteSize,
) (parseRes *ParseResult, err error) {
cachePath := filepath.Join(cacheDir, f.uid.String()+".txt")
switch s := f.url.Scheme; s {
case "http", "https":
parseRes, err = f.setFromHTTP(ctx, parseBuf, cli, cachePath, maxSize.Bytes())
case "file":
parseRes, err = f.setFromFile(parseBuf, f.url.Path, cachePath)
default:
// Since the URL has been prevalidated in New, consider this a
// programmer error.
panic(fmt.Errorf("bad url scheme: %q", s))
}
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return nil, err
}
if f.checksum != parseRes.Checksum {
f.checksum = parseRes.Checksum
f.rulesCount = parseRes.RulesCount
f.setName(parseRes.Title)
f.updated = time.Now()
}
return parseRes, nil
}
// setFromHTTP sets the rule-list filter's data from its URL. It also caches
// the data into a file.
func (f *Filter) setFromHTTP(
ctx context.Context,
parseBuf []byte,
cli *http.Client,
cachePath string,
maxSize uint64,
) (parseRes *ParseResult, err error) {
defer func() { err = errors.Annotate(err, "setting from http: %w") }()
text, parseRes, err := f.readFromHTTP(ctx, parseBuf, cli, cachePath, maxSize)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return nil, err
}
// TODO(a.garipov): Add filterlist.BytesRuleList.
f.ruleList = &filterlist.StringRuleList{
ID: f.urlFilterID,
RulesText: text,
IgnoreCosmetic: true,
}
return parseRes, nil
}
// readFromHTTP reads the data from the rule-list filter's URL into the cache
// file as well as returns it as a string. The data is filtered through a
// parser and so is free from comments, unnecessary whitespace, etc.
func (f *Filter) readFromHTTP(
ctx context.Context,
parseBuf []byte,
cli *http.Client,
cachePath string,
maxSize uint64,
) (text string, parseRes *ParseResult, err error) {
urlStr := f.url.String()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, urlStr, nil)
if err != nil {
return "", nil, fmt.Errorf("making request for http url %q: %w", urlStr, err)
}
resp, err := cli.Do(req)
if err != nil {
return "", nil, fmt.Errorf("requesting from http url: %w", err)
}
defer func() { err = errors.WithDeferred(err, resp.Body.Close()) }()
// TODO(a.garipov): Use [agdhttp.CheckStatus] when it's moved to golibs.
if resp.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("got status code %d, want %d", resp.StatusCode, http.StatusOK)
}
fltFile, err := aghrenameio.NewPendingFile(cachePath, 0o644)
if err != nil {
return "", nil, fmt.Errorf("creating temp file: %w", err)
}
defer func() { err = aghrenameio.WithDeferredCleanup(err, fltFile) }()
buf := &bytes.Buffer{}
mw := io.MultiWriter(buf, fltFile)
parser := NewParser()
httpBody := ioutil.LimitReader(resp.Body, maxSize)
parseRes, err = parser.Parse(mw, httpBody, parseBuf)
if err != nil {
return "", nil, fmt.Errorf("parsing response from http url %q: %w", urlStr, err)
}
return buf.String(), parseRes, nil
}
// setName sets the title using either the already-present name, the given title
// from the rule-list data, or a synthetic name.
func (f *Filter) setName(title string) {
if f.name != "" {
return
}
if title != "" {
f.name = title
return
}
f.name = fmt.Sprintf("List %s", f.uid)
}
// setFromFile sets the rule-list filter's data from a file path. It also
// caches the data into a file.
//
// TODO(a.garipov): Retest on Windows once rule-list updater is committed. See
// if calling Close is necessary here.
func (f *Filter) setFromFile(
parseBuf []byte,
filePath string,
cachePath string,
) (parseRes *ParseResult, err error) {
defer func() { err = errors.Annotate(err, "setting from file: %w") }()
parseRes, err = parseIntoCache(parseBuf, filePath, cachePath)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return nil, err
}
err = f.Close()
if err != nil {
return nil, fmt.Errorf("closing old rule list: %w", err)
}
rl, err := filterlist.NewFileRuleList(f.urlFilterID, cachePath, true)
if err != nil {
return nil, fmt.Errorf("opening new rule list: %w", err)
}
f.ruleList = rl
return parseRes, nil
}
// parseIntoCache copies the relevant the data from filePath into cachePath
// while also parsing it.
func parseIntoCache(
parseBuf []byte,
filePath string,
cachePath string,
) (parseRes *ParseResult, err error) {
tmpFile, err := aghrenameio.NewPendingFile(cachePath, 0o644)
if err != nil {
return nil, fmt.Errorf("creating temp file: %w", err)
}
defer func() { err = aghrenameio.WithDeferredCleanup(err, tmpFile) }()
// #nosec G304 -- Assume that cachePath is always cacheDir joined with a
// uid using [filepath.Join].
f, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("opening src file: %w", err)
}
defer func() { err = errors.WithDeferred(err, f.Close()) }()
parser := NewParser()
parseRes, err = parser.Parse(tmpFile, f, parseBuf)
if err != nil {
return nil, fmt.Errorf("copying src file: %w", err)
}
return parseRes, nil
}
// Close closes the underlying rule list.
func (f *Filter) Close() (err error) {
if f.ruleList == nil {
return nil
}
return f.ruleList.Close()
}
``` | /content/code_sandbox/internal/filtering/rulelist/filter.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,228 |
```go
package rulelist
import "github.com/AdguardTeam/golibs/errors"
// ErrHTML is returned by [Parser.Parse] if the data is likely to be HTML.
//
// TODO(a.garipov): This error is currently returned to the UI. Stop that and
// make it all-lowercase.
const ErrHTML errors.Error = "data is HTML, not plain text"
``` | /content/code_sandbox/internal/filtering/rulelist/error.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 83 |
```go
package rulelist
import (
"context"
"fmt"
"net/http"
"sync"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/filterlist"
"github.com/c2h5oh/datasize"
)
// Engine is a single DNS filter based on one or more rule lists. This
// structure contains the filtering engine combining several rule lists.
//
// TODO(a.garipov): Merge with [TextEngine] in some way?
type Engine struct {
// mu protects engine and storage.
//
// TODO(a.garipov): See if anything else should be protected.
mu *sync.RWMutex
// engine is the filtering engine.
engine *urlfilter.DNSEngine
// storage is the filtering-rule storage. It is saved here to close it.
storage *filterlist.RuleStorage
// name is the human-readable name of the engine, like "allowed", "blocked",
// or "custom".
name string
// filters is the data about rule filters in this engine.
filters []*Filter
}
// EngineConfig is the configuration for rule-list filtering engines created by
// combining refreshable filters.
type EngineConfig struct {
// Name is the human-readable name of this engine, like "allowed",
// "blocked", or "custom".
Name string
// Filters is the data about rule lists in this engine. There must be no
// other references to the elements of this slice.
Filters []*Filter
}
// NewEngine returns a new rule-list filtering engine. The engine is not
// refreshed, so a refresh should be performed before use.
func NewEngine(c *EngineConfig) (e *Engine) {
return &Engine{
mu: &sync.RWMutex{},
name: c.Name,
filters: c.Filters,
}
}
// Close closes the underlying rule-list engine as well as the rule lists.
func (e *Engine) Close() (err error) {
e.mu.Lock()
defer e.mu.Unlock()
if e.storage == nil {
return nil
}
err = e.storage.Close()
if err != nil {
return fmt.Errorf("closing engine %q: %w", e.name, err)
}
return nil
}
// FilterRequest returns the result of filtering req using the DNS filtering
// engine.
func (e *Engine) FilterRequest(
req *urlfilter.DNSRequest,
) (res *urlfilter.DNSResult, hasMatched bool) {
return e.currentEngine().MatchRequest(req)
}
// currentEngine returns the current filtering engine.
func (e *Engine) currentEngine() (enging *urlfilter.DNSEngine) {
e.mu.RLock()
defer e.mu.RUnlock()
return e.engine
}
// Refresh updates all rule lists in e. ctx is used for cancellation.
// parseBuf, cli, cacheDir, and maxSize are used for updates of rule-list
// filters; see [Filter.Refresh].
//
// TODO(a.garipov): Unexport and test in an internal test or through enigne
// tests.
func (e *Engine) Refresh(
ctx context.Context,
parseBuf []byte,
cli *http.Client,
cacheDir string,
maxSize datasize.ByteSize,
) (err error) {
defer func() { err = errors.Annotate(err, "updating engine %q: %w", e.name) }()
var filtersToRefresh []*Filter
for _, f := range e.filters {
if f.enabled {
filtersToRefresh = append(filtersToRefresh, f)
}
}
if len(filtersToRefresh) == 0 {
log.Info("filtering: updating engine %q: no rule-list filters", e.name)
return nil
}
engRefr := &engineRefresh{
httpCli: cli,
cacheDir: cacheDir,
engineName: e.name,
parseBuf: parseBuf,
maxSize: maxSize,
}
ruleLists, errs := engRefr.process(ctx, e.filters)
if isOneTimeoutError(errs) {
// Don't wrap the error since it's informative enough as is.
return err
}
storage, err := filterlist.NewRuleStorage(ruleLists)
if err != nil {
errs = append(errs, fmt.Errorf("creating rule storage: %w", err))
return errors.Join(errs...)
}
e.resetStorage(storage)
return errors.Join(errs...)
}
// resetStorage sets e.storage and e.engine and closes the previous storage.
// Errors from closing the previous storage are logged.
func (e *Engine) resetStorage(storage *filterlist.RuleStorage) {
e.mu.Lock()
defer e.mu.Unlock()
prevStorage := e.storage
e.storage, e.engine = storage, urlfilter.NewDNSEngine(storage)
if prevStorage == nil {
return
}
err := prevStorage.Close()
if err != nil {
log.Error("filtering: engine %q: closing old storage: %s", e.name, err)
}
}
// isOneTimeoutError returns true if the sole error in errs is either
// [context.Canceled] or [context.DeadlineExceeded].
func isOneTimeoutError(errs []error) (ok bool) {
if len(errs) != 1 {
return false
}
err := errs[0]
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
// engineRefresh represents a single ongoing engine refresh.
type engineRefresh struct {
httpCli *http.Client
cacheDir string
engineName string
parseBuf []byte
maxSize datasize.ByteSize
}
// process runs updates of all given rule-list filters. All errors are logged
// as they appear, since the update can take a significant amount of time.
// errs contains all errors that happened during the update, unless the context
// is canceled or its deadline is reached, in which case errs will only contain
// a single timeout error.
//
// TODO(a.garipov): Think of a better way to communicate the timeout condition?
func (r *engineRefresh) process(
ctx context.Context,
filters []*Filter,
) (ruleLists []filterlist.RuleList, errs []error) {
ruleLists = make([]filterlist.RuleList, 0, len(filters))
for i, f := range filters {
select {
case <-ctx.Done():
return nil, []error{fmt.Errorf("timeout after updating %d filters: %w", i, ctx.Err())}
default:
// Go on.
}
err := r.processFilter(ctx, f)
if err == nil {
ruleLists = append(ruleLists, f.ruleList)
continue
}
errs = append(errs, err)
// Also log immediately, since the update can take a lot of time.
log.Error(
"filtering: updating engine %q: rule list %s from url %q: %s\n",
r.engineName,
f.uid,
f.url,
err,
)
}
return ruleLists, errs
}
// processFilter runs an update of a single rule-list filter.
func (r *engineRefresh) processFilter(ctx context.Context, f *Filter) (err error) {
prevChecksum := f.checksum
parseRes, err := f.Refresh(ctx, r.parseBuf, r.httpCli, r.cacheDir, r.maxSize)
if err != nil {
return fmt.Errorf("updating %s: %w", f.uid, err)
}
if prevChecksum == parseRes.Checksum {
log.Info("filtering: engine %q: filter %q: no change", r.engineName, f.uid)
return nil
}
log.Info(
"filtering: updated engine %q: filter %q: %d bytes, %d rules",
r.engineName,
f.uid,
parseRes.BytesWritten,
parseRes.RulesCount,
)
return nil
}
``` | /content/code_sandbox/internal/filtering/rulelist/engine.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,722 |
```go
package rulelist_test
import (
"bufio"
"bytes"
"strings"
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/golibs/testutil/fakeio"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParser_Parse(t *testing.T) {
t.Parallel()
longRule := strings.Repeat("a", rulelist.DefaultRuleBufSize+1) + "\n"
tooLongRule := strings.Repeat("a", bufio.MaxScanTokenSize+1) + "\n"
testCases := []struct {
name string
in string
wantDst string
wantErrMsg string
wantTitle string
wantRulesNum int
wantWritten int
}{{
name: "empty",
in: "",
wantDst: "",
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 0,
wantWritten: 0,
}, {
name: "html",
in: testRuleTextHTML,
wantErrMsg: rulelist.ErrHTML.Error(),
wantTitle: "",
wantRulesNum: 0,
wantWritten: 0,
}, {
name: "comments",
in: "# Comment 1\n" +
"! Comment 2\n",
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 0,
wantWritten: 0,
}, {}, {
name: "rule",
in: testRuleTextBlocked,
wantDst: testRuleTextBlocked,
wantErrMsg: "",
wantRulesNum: 1,
wantTitle: "",
wantWritten: len(testRuleTextBlocked),
}, {
name: "html_in_rule",
in: testRuleTextBlocked + testRuleTextHTML,
wantDst: testRuleTextBlocked + testRuleTextHTML,
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 2,
wantWritten: len(testRuleTextBlocked) + len(testRuleTextHTML),
}, {
name: "title",
in: testRuleTextTitle +
"! Title: Bad, Ignored Title\n" +
testRuleTextBlocked,
wantDst: testRuleTextBlocked,
wantErrMsg: "",
wantTitle: testTitle,
wantRulesNum: 1,
wantWritten: len(testRuleTextBlocked),
}, {
name: "cosmetic_with_zwnj",
in: testRuleTextCosmetic,
wantDst: testRuleTextCosmetic,
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 1,
wantWritten: len(testRuleTextCosmetic),
}, {
name: "bad_char",
in: testRuleTextTitle +
testRuleTextBlocked +
">>>\x7F<<<",
wantDst: testRuleTextBlocked,
wantErrMsg: "line 3: " +
"character 4: " +
"likely binary character '\\x7f'",
wantTitle: testTitle,
wantRulesNum: 1,
wantWritten: len(testRuleTextBlocked),
}, {
name: "too_long",
in: tooLongRule,
wantDst: "",
wantErrMsg: "scanning filter contents: bufio.Scanner: token too long",
wantTitle: "",
wantRulesNum: 0,
wantWritten: 0,
}, {
name: "longer_than_default",
in: longRule,
wantDst: longRule,
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 1,
wantWritten: len(longRule),
}, {
name: "bad_tab_and_comment",
in: testRuleTextBadTab,
wantDst: testRuleTextBadTab,
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 1,
wantWritten: len(testRuleTextBadTab),
}, {
name: "etc_hosts_tab_and_comment",
in: testRuleTextEtcHostsTab,
wantDst: testRuleTextEtcHostsTab,
wantErrMsg: "",
wantTitle: "",
wantRulesNum: 1,
wantWritten: len(testRuleTextEtcHostsTab),
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
dst := &bytes.Buffer{}
buf := make([]byte, rulelist.DefaultRuleBufSize)
p := rulelist.NewParser()
r, err := p.Parse(dst, strings.NewReader(tc.in), buf)
require.NotNil(t, r)
testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
assert.Equal(t, tc.wantDst, dst.String())
assert.Equal(t, tc.wantTitle, r.Title)
assert.Equal(t, tc.wantRulesNum, r.RulesCount)
assert.Equal(t, tc.wantWritten, r.BytesWritten)
if tc.wantWritten > 0 {
assert.NotZero(t, r.Checksum)
}
})
}
}
func TestParser_Parse_writeError(t *testing.T) {
t.Parallel()
dst := &fakeio.Writer{
OnWrite: func(b []byte) (n int, err error) {
return 1, errors.Error("test error")
},
}
buf := make([]byte, rulelist.DefaultRuleBufSize)
p := rulelist.NewParser()
r, err := p.Parse(dst, strings.NewReader(testRuleTextBlocked), buf)
require.NotNil(t, r)
testutil.AssertErrorMsg(t, "writing rule line: test error", err)
assert.Equal(t, 1, r.BytesWritten)
}
func TestParser_Parse_checksums(t *testing.T) {
t.Parallel()
const (
withoutComments = testRuleTextBlocked
withComments = "! Some comment.\n" +
" " + testRuleTextBlocked +
"# Another comment.\n"
)
buf := make([]byte, rulelist.DefaultRuleBufSize)
p := rulelist.NewParser()
r, err := p.Parse(&bytes.Buffer{}, strings.NewReader(withoutComments), buf)
require.NotNil(t, r)
require.NoError(t, err)
gotWithoutComments := r.Checksum
p = rulelist.NewParser()
r, err = p.Parse(&bytes.Buffer{}, strings.NewReader(withComments), buf)
require.NotNil(t, r)
require.NoError(t, err)
gotWithComments := r.Checksum
assert.Equal(t, gotWithoutComments, gotWithComments)
}
var (
resSink *rulelist.ParseResult
errSink error
)
func BenchmarkParser_Parse(b *testing.B) {
dst := &bytes.Buffer{}
src := strings.NewReader(strings.Repeat(testRuleTextBlocked, 1000))
buf := make([]byte, rulelist.DefaultRuleBufSize)
p := rulelist.NewParser()
b.ReportAllocs()
b.ResetTimer()
for range b.N {
resSink, errSink = p.Parse(dst, src, buf)
dst.Reset()
}
require.NoError(b, errSink)
require.NotNil(b, resSink)
// Most recent result, on a ThinkPad X13 with a Ryzen Pro 7 CPU:
//
// goos: linux
// goarch: amd64
// pkg: github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist
// cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
// BenchmarkParser_Parse-16 100000000 128.0 ns/op 48 B/op 1 allocs/op
}
func FuzzParser_Parse(f *testing.F) {
const n = 64
testCases := []string{
"",
"# Comment",
"! Comment",
"! Title ",
"! Title XXX",
testRuleTextBadTab,
testRuleTextBlocked,
testRuleTextCosmetic,
testRuleTextEtcHostsTab,
testRuleTextHTML,
"1.2.3.4",
"1.2.3.4 etc-hosts.example",
">>>\x00<<<",
">>>\x7F<<<",
strings.Repeat("a", rulelist.DefaultRuleBufSize+1),
strings.Repeat("a", bufio.MaxScanTokenSize+1),
}
for _, tc := range testCases {
f.Add(tc)
}
buf := make([]byte, n)
f.Fuzz(func(t *testing.T, input string) {
require.Eventually(t, func() (ok bool) {
dst := &bytes.Buffer{}
src := strings.NewReader(input)
p := rulelist.NewParser()
r, _ := p.Parse(dst, src, buf)
require.NotNil(t, r)
return true
}, testTimeout, testTimeout/100)
})
}
``` | /content/code_sandbox/internal/filtering/rulelist/parser_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,989 |
```go
package rulelist_test
import (
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFilter_Refresh(t *testing.T) {
cacheDir := t.TempDir()
uid := rulelist.MustNewUID()
const fltData = testRuleTextTitle + testRuleTextBlocked
fileURL, srvURL := newFilterLocations(t, cacheDir, fltData, fltData)
testCases := []struct {
url *url.URL
name string
wantNewErrMsg string
}{{
url: nil,
name: "nil_url",
wantNewErrMsg: "no url",
}, {
url: &url.URL{
Scheme: "ftp",
},
name: "bad_scheme",
wantNewErrMsg: `bad url scheme: "ftp"`,
}, {
name: "file",
url: &url.URL{
Scheme: "file",
Path: fileURL.Path,
},
wantNewErrMsg: "",
}, {
name: "http",
url: srvURL,
wantNewErrMsg: "",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
f, err := rulelist.NewFilter(&rulelist.FilterConfig{
URL: tc.url,
Name: tc.name,
UID: uid,
URLFilterID: testURLFilterID,
Enabled: true,
})
if tc.wantNewErrMsg != "" {
assert.EqualError(t, err, tc.wantNewErrMsg)
return
}
testutil.CleanupAndRequireSuccess(t, f.Close)
require.NotNil(t, f)
buf := make([]byte, rulelist.DefaultRuleBufSize)
cli := &http.Client{
Timeout: testTimeout,
}
ctx := testutil.ContextWithTimeout(t, testTimeout)
res, err := f.Refresh(ctx, buf, cli, cacheDir, rulelist.DefaultMaxRuleListSize)
require.NoError(t, err)
assert.Equal(t, testTitle, res.Title)
assert.Equal(t, len(testRuleTextBlocked), res.BytesWritten)
assert.Equal(t, 1, res.RulesCount)
// Check that the cached file exists.
_, err = os.Stat(filepath.Join(cacheDir, uid.String()+".txt"))
require.NoError(t, err)
})
}
}
``` | /content/code_sandbox/internal/filtering/rulelist/filter_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 574 |
```go
package rulelist
import (
"fmt"
"strings"
"sync"
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/filterlist"
)
// TextEngine is a single DNS filter based on a list of rules in text form.
type TextEngine struct {
// mu protects engine and storage.
mu *sync.RWMutex
// engine is the filtering engine.
engine *urlfilter.DNSEngine
// storage is the filtering-rule storage. It is saved here to close it.
storage *filterlist.RuleStorage
// name is the human-readable name of the engine, like "custom".
name string
}
// TextEngineConfig is the configuration for a rule-list filtering engine
// created from a filtering rule text.
type TextEngineConfig struct {
// Name is the human-readable name of this engine, like "allowed",
// "blocked", or "custom".
Name string
// Rules is the text of the filtering rules for this engine.
Rules []string
// ID is the ID to use inside a URL-filter engine.
ID URLFilterID
}
// NewTextEngine returns a new rule-list filtering engine that uses rules
// directly. The engine is ready to use and should not be refreshed.
func NewTextEngine(c *TextEngineConfig) (e *TextEngine, err error) {
text := strings.Join(c.Rules, "\n")
storage, err := filterlist.NewRuleStorage([]filterlist.RuleList{
&filterlist.StringRuleList{
RulesText: text,
ID: c.ID,
IgnoreCosmetic: true,
},
})
if err != nil {
return nil, fmt.Errorf("creating rule storage: %w", err)
}
engine := urlfilter.NewDNSEngine(storage)
return &TextEngine{
mu: &sync.RWMutex{},
engine: engine,
storage: storage,
name: c.Name,
}, nil
}
// FilterRequest returns the result of filtering req using the DNS filtering
// engine.
func (e *TextEngine) FilterRequest(
req *urlfilter.DNSRequest,
) (res *urlfilter.DNSResult, hasMatched bool) {
var engine *urlfilter.DNSEngine
func() {
e.mu.RLock()
defer e.mu.RUnlock()
engine = e.engine
}()
return engine.MatchRequest(req)
}
// Close closes the underlying rule list engine as well as the rule lists.
func (e *TextEngine) Close() (err error) {
e.mu.Lock()
defer e.mu.Unlock()
if e.storage == nil {
return nil
}
err = e.storage.Close()
if err != nil {
return fmt.Errorf("closing text engine %q: %w", e.name, err)
}
return nil
}
``` | /content/code_sandbox/internal/filtering/rulelist/textengine.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 600 |
```go
package rulelist_test
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/require"
)
func TestMain(m *testing.M) {
testutil.DiscardLogOutput(m)
}
// testTimeout is the common timeout for tests.
const testTimeout = 1 * time.Second
// testURLFilterID is the common [rulelist.URLFilterID] for tests.
const testURLFilterID rulelist.URLFilterID = 1
// testTitle is the common title for tests.
const testTitle = "Test Title"
// Common rule texts for tests.
const (
testRuleTextBadTab = "||bad-tab-and-comment.example^\t# A comment.\n"
testRuleTextBlocked = "||blocked.example^\n"
testRuleTextBlocked2 = "||blocked-2.example^\n"
testRuleTextEtcHostsTab = "0.0.0.0 tab..example^\t# A comment.\n"
testRuleTextHTML = "<!DOCTYPE html>\n"
testRuleTextTitle = "! Title: " + testTitle + " \n"
// testRuleTextCosmetic is a cosmetic rule with a zero-width non-joiner.
//
// See path_to_url
testRuleTextCosmetic = "||cosmetic.example## :has-text(/\u200c/i)\n"
)
// urlFilterIDCounter is the atomic integer used to create unique filter IDs.
var urlFilterIDCounter = &atomic.Int32{}
// newURLFilterID returns a new unique URLFilterID.
func newURLFilterID() (id rulelist.URLFilterID) {
return rulelist.URLFilterID(urlFilterIDCounter.Add(1))
}
// newFilter is a helper for creating new filters in tests. It does not
// register the closing of the filter using t.Cleanup; callers must do that
// either directly or by using the filter in an engine.
func newFilter(t testing.TB, u *url.URL, name string) (f *rulelist.Filter) {
t.Helper()
f, err := rulelist.NewFilter(&rulelist.FilterConfig{
URL: u,
Name: name,
UID: rulelist.MustNewUID(),
URLFilterID: newURLFilterID(),
Enabled: true,
})
require.NoError(t, err)
return f
}
// newFilterLocations is a test helper that sets up both the filtering-rule list
// file and the HTTP-server. It also registers file removal and server stopping
// using t.Cleanup.
func newFilterLocations(
t testing.TB,
cacheDir string,
fileData string,
httpData string,
) (fileURL, srvURL *url.URL) {
filePath := filepath.Join(cacheDir, "initial.txt")
err := os.WriteFile(filePath, []byte(fileData), 0o644)
require.NoError(t, err)
testutil.CleanupAndRequireSuccess(t, func() (err error) {
return os.Remove(filePath)
})
fileURL = &url.URL{
Scheme: "file",
Path: filePath,
}
srv := newStringHTTPServer(httpData)
t.Cleanup(srv.Close)
srvURL, err = url.Parse(srv.URL)
require.NoError(t, err)
return fileURL, srvURL
}
// newStringHTTPServer returns a new HTTP server that serves s.
func newStringHTTPServer(s string) (srv *httptest.Server) {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
pt := testutil.PanicT{}
_, err := io.WriteString(w, s)
require.NoError(pt, err)
}))
}
``` | /content/code_sandbox/internal/filtering/rulelist/rulelist_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 831 |
```go
package rulelist
import (
"bufio"
"bytes"
"fmt"
"hash/crc32"
"io"
"slices"
"github.com/AdguardTeam/golibs/errors"
)
// Parser is a filtering-rule parser that collects data, such as the checksum
// and the title, as well as counts rules and removes comments.
type Parser struct {
title string
rulesCount int
written int
checksum uint32
titleFound bool
}
// NewParser returns a new filtering-rule parser.
func NewParser() (p *Parser) {
return &Parser{}
}
// ParseResult contains information about the results of parsing a
// filtering-rule list by [Parser.Parse].
type ParseResult struct {
// Title is the title contained within the filtering-rule list, if any.
Title string
// RulesCount is the number of rules in the list. It excludes empty lines
// and comments.
RulesCount int
// BytesWritten is the number of bytes written to dst.
BytesWritten int
// Checksum is the CRC-32 checksum of the rules content. That is, excluding
// empty lines and comments.
Checksum uint32
}
// Parse parses data from src into dst using buf during parsing. r is never
// nil.
func (p *Parser) Parse(dst io.Writer, src io.Reader, buf []byte) (r *ParseResult, err error) {
s := bufio.NewScanner(src)
// Don't use [DefaultRuleBufSize] as the maximum size, since some
// filtering-rule lists compressed by e.g. HostlistsCompiler can have very
// large lines. The buffer optimization still works for the more common
// case of reasonably-sized lines.
//
// See path_to_url
s.Buffer(buf, bufio.MaxScanTokenSize)
// Use a one-based index for lines and columns, since these errors end up in
// the frontend, and users are more familiar with one-based line and column
// indexes.
lineNum := 1
for s.Scan() {
var n int
n, err = p.processLine(dst, s.Bytes(), lineNum)
p.written += n
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return p.result(), err
}
lineNum++
}
r = p.result()
err = s.Err()
return r, errors.Annotate(err, "scanning filter contents: %w")
}
// result returns the current parsing result.
func (p *Parser) result() (r *ParseResult) {
return &ParseResult{
Title: p.title,
RulesCount: p.rulesCount,
BytesWritten: p.written,
Checksum: p.checksum,
}
}
// processLine processes a single line. It may write to dst, and if it does, n
// is the number of bytes written.
func (p *Parser) processLine(dst io.Writer, line []byte, lineNum int) (n int, err error) {
trimmed := bytes.TrimSpace(line)
if p.written == 0 && isHTMLLine(trimmed) {
return 0, ErrHTML
}
badIdx, isRule := 0, false
if p.titleFound {
badIdx, isRule = parseLine(trimmed)
} else {
badIdx, isRule = p.parseLineTitle(trimmed)
}
if badIdx != -1 {
return 0, fmt.Errorf(
"line %d: character %d: likely binary character %q",
lineNum,
badIdx+bytes.Index(line, trimmed)+1,
trimmed[badIdx],
)
}
if !isRule {
return 0, nil
}
p.rulesCount++
p.checksum = crc32.Update(p.checksum, crc32.IEEETable, trimmed)
// Assume that there is generally enough space in the buffer to add a
// newline.
n, err = dst.Write(append(trimmed, '\n'))
return n, errors.Annotate(err, "writing rule line: %w")
}
// isHTMLLine returns true if line is likely an HTML line. line is assumed to
// be trimmed of whitespace characters.
func isHTMLLine(line []byte) (isHTML bool) {
return hasPrefixFold(line, []byte("<html")) || hasPrefixFold(line, []byte("<!doctype"))
}
// hasPrefixFold is a simple, best-effort prefix matcher. It may return
// incorrect results for some non-ASCII characters.
func hasPrefixFold(b, prefix []byte) (ok bool) {
l := len(prefix)
return len(b) >= l && bytes.EqualFold(b[:l], prefix)
}
// parseLine returns true if the parsed line is a filtering rule. line is
// assumed to be trimmed of whitespace characters. badIdx is the index of the
// first character that may indicate that this is a binary file, or -1 if none.
//
// A line is considered a rule if it's not empty, not a comment, and contains
// only printable characters.
func parseLine(line []byte) (badIdx int, isRule bool) {
if len(line) == 0 || line[0] == '#' || line[0] == '!' {
return -1, false
}
badIdx = slices.IndexFunc(line, likelyBinary)
return badIdx, badIdx == -1
}
// likelyBinary returns true if b is likely to be a byte from a binary file.
func likelyBinary(b byte) (ok bool) {
return (b < ' ' || b == 0x7f) && b != '\n' && b != '\r' && b != '\t'
}
// parseLineTitle is like [parseLine] but additionally looks for a title. line
// is assumed to be trimmed of whitespace characters.
func (p *Parser) parseLineTitle(line []byte) (badIdx int, isRule bool) {
if len(line) == 0 || line[0] == '#' {
return -1, false
}
if line[0] != '!' {
badIdx = slices.IndexFunc(line, likelyBinary)
return badIdx, badIdx == -1
}
const titlePattern = "! Title: "
if !bytes.HasPrefix(line, []byte(titlePattern)) {
return -1, false
}
title := bytes.TrimSpace(line[len(titlePattern):])
if title != nil {
// Note that title can be a non-nil empty slice. Consider that normal
// and just stop looking for other titles.
p.title = string(title)
p.titleFound = true
}
return -1, false
}
``` | /content/code_sandbox/internal/filtering/rulelist/parser.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,451 |
```go
package rulelist_test
import (
"net/http"
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/urlfilter"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEngine_Refresh(t *testing.T) {
cacheDir := t.TempDir()
fileURL, srvURL := newFilterLocations(t, cacheDir, testRuleTextBlocked, testRuleTextBlocked2)
fileFlt := newFilter(t, fileURL, "File Filter")
httpFlt := newFilter(t, srvURL, "HTTP Filter")
eng := rulelist.NewEngine(&rulelist.EngineConfig{
Name: "Engine",
Filters: []*rulelist.Filter{fileFlt, httpFlt},
})
require.NotNil(t, eng)
testutil.CleanupAndRequireSuccess(t, eng.Close)
buf := make([]byte, rulelist.DefaultRuleBufSize)
cli := &http.Client{
Timeout: testTimeout,
}
ctx := testutil.ContextWithTimeout(t, testTimeout)
err := eng.Refresh(ctx, buf, cli, cacheDir, rulelist.DefaultMaxRuleListSize)
require.NoError(t, err)
fltReq := &urlfilter.DNSRequest{
Hostname: "blocked.example",
Answer: false,
DNSType: dns.TypeA,
}
fltRes, hasMatched := eng.FilterRequest(fltReq)
assert.True(t, hasMatched)
require.NotNil(t, fltRes)
fltReq = &urlfilter.DNSRequest{
Hostname: "blocked-2.example",
Answer: false,
DNSType: dns.TypeA,
}
fltRes, hasMatched = eng.FilterRequest(fltReq)
assert.True(t, hasMatched)
require.NotNil(t, fltRes)
}
``` | /content/code_sandbox/internal/filtering/rulelist/engine_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 419 |
```go
package rulelist_test
import (
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/urlfilter"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewTextEngine(t *testing.T) {
eng, err := rulelist.NewTextEngine(&rulelist.TextEngineConfig{
Name: "RulesEngine",
Rules: []string{
testRuleTextTitle,
testRuleTextBlocked,
},
ID: testURLFilterID,
})
require.NoError(t, err)
require.NotNil(t, eng)
testutil.CleanupAndRequireSuccess(t, eng.Close)
fltReq := &urlfilter.DNSRequest{
Hostname: "blocked.example",
Answer: false,
DNSType: dns.TypeA,
}
fltRes, hasMatched := eng.FilterRequest(fltReq)
assert.True(t, hasMatched)
require.NotNil(t, fltRes)
require.NotNil(t, fltRes.NetworkRule)
assert.Equal(t, fltRes.NetworkRule.FilterListID, testURLFilterID)
}
``` | /content/code_sandbox/internal/filtering/rulelist/textengine_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 266 |
```go
// Package rulelist contains the implementation of the standard rule-list
// filter that wraps an urlfilter filtering-engine.
//
// TODO(a.garipov): Add a new update worker.
package rulelist
import (
"fmt"
"github.com/c2h5oh/datasize"
"github.com/google/uuid"
)
// DefaultRuleBufSize is the default length of a buffer used to read a line with
// a filtering rule, in bytes.
//
// TODO(a.garipov): Consider using [datasize.ByteSize]. It is currently only
// used as an int.
const DefaultRuleBufSize = 1024
// DefaultMaxRuleListSize is the default maximum filtering-rule list size.
const DefaultMaxRuleListSize = 64 * datasize.MB
// URLFilterID is a semantic type-alias for IDs used for working with package
// urlfilter.
type URLFilterID = int
// The IDs of built-in filter lists.
//
// NOTE: Do not change without the need for it and keep in sync with
// client/src/helpers/constants.ts.
//
// TODO(a.garipov): Add type [URLFilterID] once it is used consistently in
// package filtering.
//
// TODO(d.kolyshev): Add URLFilterIDLegacyRewrite here and to the UI.
const (
URLFilterIDCustom URLFilterID = 0
URLFilterIDEtcHosts URLFilterID = -1
URLFilterIDBlockedService URLFilterID = -2
URLFilterIDParentalControl URLFilterID = -3
URLFilterIDSafeBrowsing URLFilterID = -4
URLFilterIDSafeSearch URLFilterID = -5
)
// UID is the type for the unique IDs of filtering-rule lists.
type UID uuid.UUID
// NewUID returns a new filtering-rule list UID. Any error returned is an error
// from the cryptographic randomness reader.
func NewUID() (uid UID, err error) {
uuidv7, err := uuid.NewV7()
return UID(uuidv7), err
}
// MustNewUID is a wrapper around [NewUID] that panics if there is an error.
func MustNewUID() (uid UID) {
uid, err := NewUID()
if err != nil {
panic(fmt.Errorf("unexpected uuidv7 error: %w", err))
}
return uid
}
// type check
var _ fmt.Stringer = UID{}
// String implements the [fmt.Stringer] interface for UID.
func (id UID) String() (s string) {
return uuid.UUID(id).String()
}
``` | /content/code_sandbox/internal/filtering/rulelist/rulelist.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 547 |
```go
package rewrite
import (
"net/netip"
"testing"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewDefaultStorage(t *testing.T) {
items := []*Item{{
Domain: "example.com",
Answer: "answer.com",
}}
s, err := NewDefaultStorage(-1, items)
require.NoError(t, err)
require.Len(t, s.List(), 1)
}
func TestDefaultStorage_CRUD(t *testing.T) {
var items []*Item
s, err := NewDefaultStorage(-1, items)
require.NoError(t, err)
require.Len(t, s.List(), 0)
item := &Item{Domain: "example.com", Answer: "answer.com"}
err = s.Add(item)
require.NoError(t, err)
list := s.List()
require.Len(t, list, 1)
require.True(t, item.equal(list[0]))
err = s.Remove(item)
require.NoError(t, err)
require.Len(t, s.List(), 0)
}
func TestDefaultStorage_MatchRequest(t *testing.T) {
var (
addr1v4 = netip.AddrFrom4([4]byte{1, 2, 3, 4})
addr2v4 = netip.AddrFrom4([4]byte{1, 2, 3, 5})
addr3v4 = netip.AddrFrom4([4]byte{1, 2, 3, 6})
addr4v4 = netip.AddrFrom4([4]byte{1, 2, 3, 7})
addr1v6 = netip.MustParseAddr("1:2:3::4")
addr2v6 = netip.MustParseAddr("1234::5678")
)
items := []*Item{{
// This one and below are about CNAME, A and AAAA.
Domain: "somecname",
Answer: "somehost.com",
}, {
Domain: "somehost.com",
Answer: netip.IPv4Unspecified().String(),
}, {
Domain: "host.com",
Answer: addr1v4.String(),
}, {
Domain: "host.com",
Answer: addr2v4.String(),
}, {
Domain: "host.com",
Answer: addr1v6.String(),
}, {
Domain: "www.host.com",
Answer: "host.com",
}, {
// This one is a wildcard.
Domain: "*.host.com",
Answer: addr2v4.String(),
}, {
// This one and below are about wildcard overriding.
Domain: "a.host.com",
Answer: addr1v4.String(),
}, {
// This one is about CNAME and wildcard interacting.
Domain: "*.host2.com",
Answer: "host.com",
}, {
// This one and below are about 2 level CNAME.
Domain: "b.host.com",
Answer: "somecname",
}, {
// This one and below are about 2 level CNAME and wildcard.
Domain: "b.host3.com",
Answer: "a.host3.com",
}, {
Domain: "a.host3.com",
Answer: "x.host.com",
}, {
Domain: "*.hostboth.com",
Answer: addr3v4.String(),
}, {
Domain: "*.hostboth.com",
Answer: addr2v6.String(),
}, {
Domain: "BIGHOST.COM",
Answer: addr4v4.String(),
}, {
Domain: "*.issue4016.com",
Answer: "sub.issue4016.com",
}}
s, err := NewDefaultStorage(-1, items)
require.NoError(t, err)
testCases := []struct {
name string
host string
wantDNSRewrites []*rules.DNSRewrite
dtyp uint16
}{{
name: "not_filtered_not_found",
host: "hoost.com",
wantDNSRewrites: nil,
dtyp: dns.TypeA,
}, {
name: "not_filtered_qtype",
host: "www.host.com",
wantDNSRewrites: nil,
dtyp: dns.TypeMX,
}, {
name: "rewritten_a",
host: "www.host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr1v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}, {
Value: addr2v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "rewritten_aaaa",
host: "www.host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr1v6,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeAAAA,
}},
dtyp: dns.TypeAAAA,
}, {
name: "wildcard_match",
host: "abc.host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr2v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
//}, {
// TODO(d.kolyshev): This is about matching in urlfilter.
// name: "wildcard_override",
// host: "a.host.com",
// wantDNSRewrites: []*rules.DNSRewrite{{
// Value: net.IP{1, 2, 3, 4}.To16(),
// NewCNAME: "",
// RCode: dns.RcodeSuccess,
// RRType: dns.TypeA,
// }},
// dtyp: dns.TypeA,
}, {
name: "wildcard_cname_interaction",
host: "www.host2.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr1v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}, {
Value: addr2v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "two_cnames",
host: "b.host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: netip.IPv4Unspecified(),
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "two_cnames_and_wildcard",
host: "b.host3.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr2v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "issue3343",
host: "www.hostboth.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr2v6,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeAAAA,
}},
dtyp: dns.TypeAAAA,
}, {
name: "issue3351",
host: "bighost.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr4v4,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "issue4008",
host: "somehost.com",
wantDNSRewrites: nil,
dtyp: dns.TypeHTTPS,
}, {
name: "issue4016",
host: "www.issue4016.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: nil,
NewCNAME: "sub.issue4016.com",
RCode: dns.RcodeSuccess,
RRType: dns.TypeNone,
}},
dtyp: dns.TypeA,
}, {
name: "issue4016_self",
host: "sub.issue4016.com",
wantDNSRewrites: nil,
dtyp: dns.TypeA,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
dnsRewrites := s.MatchRequest(&urlfilter.DNSRequest{
Hostname: tc.host,
DNSType: tc.dtyp,
})
assert.Equal(t, tc.wantDNSRewrites, dnsRewrites)
})
}
}
func TestDefaultStorage_MatchRequest_Levels(t *testing.T) {
var (
addr1 = netip.AddrFrom4([4]byte{1, 1, 1, 1})
addr2 = netip.AddrFrom4([4]byte{2, 2, 2, 2})
addr3 = netip.AddrFrom4([4]byte{3, 3, 3, 3})
)
// Exact host, wildcard L2, wildcard L3.
items := []*Item{{
Domain: "host.com",
Answer: addr1.String(),
}, {
Domain: "*.host.com",
Answer: addr2.String(),
}, {
Domain: "*.sub.host.com",
Answer: addr3.String(),
}}
s, err := NewDefaultStorage(-1, items)
require.NoError(t, err)
testCases := []struct {
name string
host string
wantDNSRewrites []*rules.DNSRewrite
dtyp uint16
}{{
name: "exact_match",
host: "host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr1,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "l2_match",
host: "sub.host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr2,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
//}, {
// TODO(d.kolyshev): This is about matching in urlfilter.
// name: "l3_match",
// host: "my.sub.host.com",
// wantDNSRewrites: []*rules.DNSRewrite{{
// Value: addr3,
// NewCNAME: "",
// RCode: dns.RcodeSuccess,
// RRType: dns.TypeA,
// }},
// dtyp: dns.TypeA,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
dnsRewrites := s.MatchRequest(&urlfilter.DNSRequest{
Hostname: tc.host,
DNSType: tc.dtyp,
})
assert.Equal(t, tc.wantDNSRewrites, dnsRewrites)
})
}
}
func TestDefaultStorage_MatchRequest_ExceptionCNAME(t *testing.T) {
addr := netip.AddrFrom4([4]byte{2, 2, 2, 2})
// Wildcard and exception for a sub-domain.
items := []*Item{{
Domain: "*.host.com",
Answer: addr.String(),
}, {
Domain: "sub.host.com",
Answer: "sub.host.com",
}, {
Domain: "*.sub.host.com",
Answer: "*.sub.host.com",
}}
s, err := NewDefaultStorage(-1, items)
require.NoError(t, err)
testCases := []struct {
name string
host string
wantDNSRewrites []*rules.DNSRewrite
dtyp uint16
}{{
name: "match_subdomain",
host: "my.host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "exception_cname",
host: "sub.host.com",
wantDNSRewrites: nil,
dtyp: dns.TypeA,
//}, {
// TODO(d.kolyshev): This is about matching in urlfilter.
// name: "exception_wildcard",
// host: "my.sub.host.com",
// wantDNSRewrites: nil,
// dtyp: dns.TypeA,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
dnsRewrites := s.MatchRequest(&urlfilter.DNSRequest{
Hostname: tc.host,
DNSType: tc.dtyp,
})
assert.Equal(t, tc.wantDNSRewrites, dnsRewrites)
})
}
}
func TestDefaultStorage_MatchRequest_ExceptionIP(t *testing.T) {
addr := netip.AddrFrom4([4]byte{1, 2, 3, 4})
// Exception for AAAA record.
items := []*Item{{
Domain: "host.com",
Answer: addr.String(),
}, {
Domain: "host.com",
Answer: "AAAA",
}, {
Domain: "host2.com",
Answer: netutil.IPv6Localhost().String(),
}, {
Domain: "host2.com",
Answer: "A",
}, {
Domain: "host3.com",
Answer: "A",
}}
s, err := NewDefaultStorage(-1, items)
require.NoError(t, err)
testCases := []struct {
name string
host string
wantDNSRewrites []*rules.DNSRewrite
dtyp uint16
}{{
name: "match_A",
host: "host.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: addr,
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeA,
}},
dtyp: dns.TypeA,
}, {
name: "exception_AAAA_host.com",
host: "host.com",
wantDNSRewrites: nil,
dtyp: dns.TypeAAAA,
}, {
name: "exception_A_host2.com",
host: "host2.com",
wantDNSRewrites: nil,
dtyp: dns.TypeA,
}, {
name: "match_AAAA_host2.com",
host: "host2.com",
wantDNSRewrites: []*rules.DNSRewrite{{
Value: netutil.IPv6Localhost(),
NewCNAME: "",
RCode: dns.RcodeSuccess,
RRType: dns.TypeAAAA,
}},
dtyp: dns.TypeAAAA,
}, {
name: "exception_A_host3.com",
host: "host3.com",
wantDNSRewrites: nil,
dtyp: dns.TypeA,
}, {
name: "match_AAAA_host3.com",
host: "host3.com",
wantDNSRewrites: nil,
dtyp: dns.TypeAAAA,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
dnsRewrites := s.MatchRequest(&urlfilter.DNSRequest{
Hostname: tc.host,
DNSType: tc.dtyp,
})
assert.Equal(t, tc.wantDNSRewrites, dnsRewrites)
})
}
}
``` | /content/code_sandbox/internal/filtering/rewrite/storage_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,705 |
```go
// Package rewrite implements DNS Rewrites storage and request matching.
package rewrite
import (
"fmt"
"slices"
"strings"
"sync"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/filterlist"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// Storage is a storage for rewrite rules.
type Storage interface {
// MatchRequest returns matching dnsrewrites for the specified request.
MatchRequest(dReq *urlfilter.DNSRequest) (rws []*rules.DNSRewrite)
// Add adds item to the storage.
Add(item *Item) (err error)
// Remove deletes item from the storage.
Remove(item *Item) (err error)
// List returns all items from the storage.
List() (items []*Item)
}
// DefaultStorage is the default storage for rewrite rules.
type DefaultStorage struct {
// mu protects items.
mu *sync.RWMutex
// engine is the DNS filtering engine.
engine *urlfilter.DNSEngine
// ruleList is the filtering rule ruleList used by the engine.
ruleList filterlist.RuleList
// rewrites stores the rewrite entries from configuration.
rewrites []*Item
// urlFilterID is the synthetic integer identifier for the urlfilter engine.
//
// TODO(a.garipov): Change the type to a string in module urlfilter and
// remove this crutch.
urlFilterID int
}
// NewDefaultStorage returns new rewrites storage. listID is used as an
// identifier of the underlying rules list. rewrites must not be nil.
func NewDefaultStorage(listID int, rewrites []*Item) (s *DefaultStorage, err error) {
s = &DefaultStorage{
mu: &sync.RWMutex{},
urlFilterID: listID,
rewrites: rewrites,
}
s.mu.Lock()
defer s.mu.Unlock()
err = s.resetRules()
if err != nil {
return nil, err
}
return s, nil
}
// type check
var _ Storage = (*DefaultStorage)(nil)
// MatchRequest implements the [Storage] interface for *DefaultStorage.
func (s *DefaultStorage) MatchRequest(dReq *urlfilter.DNSRequest) (rws []*rules.DNSRewrite) {
s.mu.RLock()
defer s.mu.RUnlock()
rrules := s.rewriteRulesForReq(dReq)
if len(rrules) == 0 {
return nil
}
// TODO(a.garipov): Check cnames for cycles on initialization.
cnames := container.NewMapSet[string]()
host := dReq.Hostname
for len(rrules) > 0 && rrules[0].DNSRewrite != nil && rrules[0].DNSRewrite.NewCNAME != "" {
rule := rrules[0]
rwAns := rule.DNSRewrite.NewCNAME
log.Debug("rewrite: cname for %s is %s", host, rwAns)
if dReq.Hostname == rwAns {
// A request for the hostname itself is an exception rule.
// TODO(d.kolyshev): Check rewrite of a pattern onto itself.
return nil
}
if host == rwAns && isWildcard(rule.RuleText) {
// An "*.example.com sub.example.com" rewrite matching in a loop.
//
// See path_to_url
return []*rules.DNSRewrite{rule.DNSRewrite}
}
if cnames.Has(rwAns) {
log.Info("rewrite: cname loop for %q on %q", dReq.Hostname, rwAns)
return nil
}
cnames.Add(rwAns)
drules := s.rewriteRulesForReq(&urlfilter.DNSRequest{
Hostname: rwAns,
DNSType: dReq.DNSType,
})
if drules != nil {
rrules = drules
}
host = rwAns
}
return s.collectDNSRewrites(rrules, dReq.DNSType)
}
// collectDNSRewrites filters DNSRewrite by question type.
func (s *DefaultStorage) collectDNSRewrites(
rewrites []*rules.NetworkRule,
qtyp uint16,
) (rws []*rules.DNSRewrite) {
for _, rewrite := range rewrites {
dnsRewrite := rewrite.DNSRewrite
if matchesQType(dnsRewrite, qtyp) {
rws = append(rws, dnsRewrite)
}
}
return rws
}
// rewriteRulesForReq returns matching dnsrewrite rules.
func (s *DefaultStorage) rewriteRulesForReq(dReq *urlfilter.DNSRequest) (rules []*rules.NetworkRule) {
res, _ := s.engine.MatchRequest(dReq)
return res.DNSRewrites()
}
// Add implements the [Storage] interface for *DefaultStorage.
func (s *DefaultStorage) Add(item *Item) (err error) {
s.mu.Lock()
defer s.mu.Unlock()
// TODO(d.kolyshev): Handle duplicate items.
s.rewrites = append(s.rewrites, item)
return s.resetRules()
}
// Remove implements the [Storage] interface for *DefaultStorage.
func (s *DefaultStorage) Remove(item *Item) (err error) {
s.mu.Lock()
defer s.mu.Unlock()
arr := []*Item{}
// TODO(d.kolyshev): Use slices.IndexFunc + slices.Delete?
for _, ent := range s.rewrites {
if ent.equal(item) {
log.Debug("rewrite: removed element: %s -> %s", ent.Domain, ent.Answer)
continue
}
arr = append(arr, ent)
}
s.rewrites = arr
return s.resetRules()
}
// List implements the [Storage] interface for *DefaultStorage.
func (s *DefaultStorage) List() (items []*Item) {
s.mu.RLock()
defer s.mu.RUnlock()
return slices.Clone(s.rewrites)
}
// resetRules resets the filtering rules.
func (s *DefaultStorage) resetRules() (err error) {
// TODO(a.garipov): Use strings.Builder.
var rulesText []string
for _, rewrite := range s.rewrites {
rulesText = append(rulesText, rewrite.toRule())
}
strList := &filterlist.StringRuleList{
ID: s.urlFilterID,
RulesText: strings.Join(rulesText, "\n"),
IgnoreCosmetic: true,
}
rs, err := filterlist.NewRuleStorage([]filterlist.RuleList{strList})
if err != nil {
return fmt.Errorf("creating list storage: %w", err)
}
s.ruleList = strList
s.engine = urlfilter.NewDNSEngine(rs)
log.Info("rewrite: filter %d: reset %d rules", s.urlFilterID, s.engine.RulesCount)
return nil
}
// matchesQType returns true if dnsrewrite matches the question type qt.
func matchesQType(dnsrr *rules.DNSRewrite, qt uint16) (ok bool) {
// Add CNAMEs, since they match for all types requests.
if dnsrr.RRType == dns.TypeCNAME {
return true
}
// Reject types other than A and AAAA.
if qt != dns.TypeA && qt != dns.TypeAAAA {
return false
}
return dnsrr.RRType == qt
}
// isWildcard returns true if pat is a wildcard domain pattern.
func isWildcard(pat string) (res bool) {
return strings.HasPrefix(pat, "|*.")
}
``` | /content/code_sandbox/internal/filtering/rewrite/storage.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,658 |
```go
package rewrite
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestItem_equal(t *testing.T) {
const (
testDomain = "example.org"
testAnswer = "1.1.1.1"
)
testItem := &Item{
Domain: testDomain,
Answer: testAnswer,
}
testCases := []struct {
left *Item
right *Item
name string
want bool
}{{
name: "nil_left",
left: nil,
right: testItem,
want: false,
}, {
name: "nil_right",
left: testItem,
right: nil,
want: false,
}, {
name: "nils",
left: nil,
right: nil,
want: true,
}, {
name: "equal",
left: testItem,
right: testItem,
want: true,
}, {
name: "distinct",
left: testItem,
right: &Item{
Domain: "other",
Answer: "other",
},
want: false,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
res := tc.left.equal(tc.right)
assert.Equal(t, tc.want, res)
})
}
}
func TestItem_toRule(t *testing.T) {
const testDomain = "example.org"
testCases := []struct {
name string
item *Item
want string
}{{
name: "nil",
item: nil,
want: "",
}, {
name: "a_rule",
item: &Item{
Domain: testDomain,
Answer: "1.1.1.1",
},
want: "|example.org^$dnsrewrite=NOERROR;A;1.1.1.1",
}, {
name: "aaaa_rule",
item: &Item{
Domain: testDomain,
Answer: "1:2:3::4",
},
want: "|example.org^$dnsrewrite=NOERROR;AAAA;1:2:3::4",
}, {
name: "cname_rule",
item: &Item{
Domain: testDomain,
Answer: "other.org",
},
want: "|example.org^$dnsrewrite=NOERROR;CNAME;other.org",
}, {
name: "wildcard_rule",
item: &Item{
Domain: "*.example.org",
Answer: "other.org",
},
want: "|*.example.org^$dnsrewrite=NOERROR;CNAME;other.org",
}, {
name: "aaaa_exception",
item: &Item{
Domain: testDomain,
Answer: "A",
},
want: "@@||example.org^$dnstype=A,dnsrewrite",
}, {
name: "aaaa_exception",
item: &Item{
Domain: testDomain,
Answer: "AAAA",
},
want: "@@||example.org^$dnstype=AAAA,dnsrewrite",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
res := tc.item.toRule()
assert.Equal(t, tc.want, res)
})
}
}
``` | /content/code_sandbox/internal/filtering/rewrite/item_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 748 |
```go
package rewrite
import (
"fmt"
"net/netip"
"strings"
"github.com/miekg/dns"
)
// Item is a single DNS rewrite record.
type Item struct {
// Domain is the domain pattern for which this rewrite should work.
Domain string `yaml:"domain"`
// Answer is the IP address, canonical name, or one of the special
// values: "A" or "AAAA".
Answer string `yaml:"answer"`
}
// equal returns true if rw is equal to other.
func (rw *Item) equal(other *Item) (ok bool) {
if rw == nil {
return other == nil
} else if other == nil {
return false
}
return *rw == *other
}
// toRule converts rw to a filter rule.
func (rw *Item) toRule() (res string) {
if rw == nil {
return ""
}
domain := strings.ToLower(rw.Domain)
dType, exception := rw.rewriteParams()
dTypeKey := dns.TypeToString[dType]
if exception {
return fmt.Sprintf("@@||%s^$dnstype=%s,dnsrewrite", domain, dTypeKey)
}
return fmt.Sprintf("|%s^$dnsrewrite=NOERROR;%s;%s", domain, dTypeKey, rw.Answer)
}
// rewriteParams returns dns request type and exception flag for rw.
func (rw *Item) rewriteParams() (dType uint16, exception bool) {
switch rw.Answer {
case "AAAA":
return dns.TypeAAAA, true
case "A":
return dns.TypeA, true
default:
// Go on.
}
addr, err := netip.ParseAddr(rw.Answer)
if err != nil {
// TODO(d.kolyshev): Validate rw.Answer as a domain name.
return dns.TypeCNAME, false
}
if addr.Is4() {
dType = dns.TypeA
} else {
dType = dns.TypeAAAA
}
return dType, false
}
``` | /content/code_sandbox/internal/filtering/rewrite/item.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 435 |
```go
// Package safesearch implements safesearch host matching.
package safesearch
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"net/netip"
"strings"
"sync"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/cache"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/urlfilter"
"github.com/AdguardTeam/urlfilter/filterlist"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// Service is a enum with service names used as search providers.
type Service string
// Service enum members.
const (
Bing Service = "bing"
DuckDuckGo Service = "duckduckgo"
Ecosia Service = "ecosia"
Google Service = "google"
Pixabay Service = "pixabay"
Yandex Service = "yandex"
YouTube Service = "youtube"
)
// isServiceProtected returns true if the service safe search is active.
func isServiceProtected(s filtering.SafeSearchConfig, service Service) (ok bool) {
switch service {
case Bing:
return s.Bing
case DuckDuckGo:
return s.DuckDuckGo
case Ecosia:
return s.Ecosia
case Google:
return s.Google
case Pixabay:
return s.Pixabay
case Yandex:
return s.Yandex
case YouTube:
return s.YouTube
default:
panic(fmt.Errorf("safesearch: invalid sources: not found service %q", service))
}
}
// Default is the default safe search filter that uses filtering rules with the
// dnsrewrite modifier.
type Default struct {
// mu protects engine.
mu *sync.RWMutex
// engine is the filtering engine that contains the DNS rewrite rules.
// engine may be nil, which means that this safe search filter is disabled.
engine *urlfilter.DNSEngine
cache cache.Cache
logPrefix string
cacheTTL time.Duration
}
// NewDefault returns an initialized default safe search filter. name is used
// for logging.
func NewDefault(
conf filtering.SafeSearchConfig,
name string,
cacheSize uint,
cacheTTL time.Duration,
) (ss *Default, err error) {
ss = &Default{
mu: &sync.RWMutex{},
cache: cache.New(cache.Config{
EnableLRU: true,
MaxSize: cacheSize,
}),
// Use %s, because the client safe-search names already contain double
// quotes.
logPrefix: fmt.Sprintf("safesearch %s: ", name),
cacheTTL: cacheTTL,
}
err = ss.resetEngine(rulelist.URLFilterIDSafeSearch, conf)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return nil, err
}
return ss, nil
}
// log is a helper for logging that includes the name of the safe search
// filter. level must be one of [log.DEBUG], [log.INFO], and [log.ERROR].
func (ss *Default) log(level log.Level, msg string, args ...any) {
switch level {
case log.DEBUG:
log.Debug(ss.logPrefix+msg, args...)
case log.INFO:
log.Info(ss.logPrefix+msg, args...)
case log.ERROR:
log.Error(ss.logPrefix+msg, args...)
default:
panic(fmt.Errorf("safesearch: unsupported logging level %d", level))
}
}
// resetEngine creates new engine for provided safe search configuration and
// sets it in ss.
func (ss *Default) resetEngine(
listID int,
conf filtering.SafeSearchConfig,
) (err error) {
if !conf.Enabled {
ss.log(log.INFO, "disabled")
return nil
}
var sb strings.Builder
for service, serviceRules := range safeSearchRules {
if isServiceProtected(conf, service) {
sb.WriteString(serviceRules)
}
}
strList := &filterlist.StringRuleList{
ID: listID,
RulesText: sb.String(),
IgnoreCosmetic: true,
}
rs, err := filterlist.NewRuleStorage([]filterlist.RuleList{strList})
if err != nil {
return fmt.Errorf("creating rule storage: %w", err)
}
ss.engine = urlfilter.NewDNSEngine(rs)
ss.log(log.INFO, "reset %d rules", ss.engine.RulesCount)
return nil
}
// type check
var _ filtering.SafeSearch = (*Default)(nil)
// CheckHost implements the [filtering.SafeSearch] interface for *Default.
func (ss *Default) CheckHost(host string, qtype rules.RRType) (res filtering.Result, err error) {
start := time.Now()
defer func() {
ss.log(log.DEBUG, "lookup for %q finished in %s", host, time.Since(start))
}()
switch qtype {
case dns.TypeA, dns.TypeAAAA, dns.TypeHTTPS:
// Go on.
default:
return filtering.Result{}, nil
}
// Check cache. Return cached result if it was found
cachedValue, isFound := ss.getCachedResult(host, qtype)
if isFound {
ss.log(log.DEBUG, "found in cache: %q", host)
return cachedValue, nil
}
rewrite := ss.searchHost(host, qtype)
if rewrite == nil {
return filtering.Result{}, nil
}
fltRes, err := ss.newResult(rewrite, qtype)
if err != nil {
ss.log(log.DEBUG, "looking up addresses for %q: %s", host, err)
return filtering.Result{}, err
}
res = *fltRes
// TODO(a.garipov): Consider switch back to resolving CNAME records IPs and
// saving results to cache.
ss.setCacheResult(host, qtype, res)
return res, nil
}
// searchHost looks up DNS rewrites in the internal DNS filtering engine.
func (ss *Default) searchHost(host string, qtype rules.RRType) (res *rules.DNSRewrite) {
ss.mu.RLock()
defer ss.mu.RUnlock()
if ss.engine == nil {
return nil
}
r, _ := ss.engine.MatchRequest(&urlfilter.DNSRequest{
Hostname: strings.ToLower(host),
DNSType: qtype,
})
rewritesRules := r.DNSRewrites()
if len(rewritesRules) > 0 {
return rewritesRules[0].DNSRewrite
}
return nil
}
// newResult creates Result object from rewrite rule. qtype must be either
// [dns.TypeA] or [dns.TypeAAAA], or [dns.TypeHTTPS]. If err is nil, res is
// never nil, so that the empty result is converted into a NODATA response.
func (ss *Default) newResult(
rewrite *rules.DNSRewrite,
qtype rules.RRType,
) (res *filtering.Result, err error) {
res = &filtering.Result{
Reason: filtering.FilteredSafeSearch,
IsFiltered: true,
}
if rewrite.RRType == qtype {
ip, ok := rewrite.Value.(netip.Addr)
if !ok || ip == (netip.Addr{}) {
return nil, fmt.Errorf("expected ip rewrite value, got %T(%[1]v)", rewrite.Value)
}
res.Rules = []*filtering.ResultRule{{
FilterListID: rulelist.URLFilterIDSafeSearch,
IP: ip,
}}
return res, nil
}
res.CanonName = rewrite.NewCNAME
return res, nil
}
// setCacheResult stores data in cache for host. qtype is expected to be either
// [dns.TypeA] or [dns.TypeAAAA].
func (ss *Default) setCacheResult(host string, qtype rules.RRType, res filtering.Result) {
expire := uint32(time.Now().Add(ss.cacheTTL).Unix())
exp := make([]byte, 4)
binary.BigEndian.PutUint32(exp, expire)
buf := bytes.NewBuffer(exp)
err := gob.NewEncoder(buf).Encode(res)
if err != nil {
ss.log(log.ERROR, "cache encoding: %s", err)
return
}
val := buf.Bytes()
_ = ss.cache.Set([]byte(dns.Type(qtype).String()+" "+host), val)
ss.log(log.DEBUG, "stored in cache: %q, %d bytes", host, len(val))
}
// getCachedResult returns stored data from cache for host. qtype is expected
// to be either [dns.TypeA] or [dns.TypeAAAA].
func (ss *Default) getCachedResult(
host string,
qtype rules.RRType,
) (res filtering.Result, ok bool) {
res = filtering.Result{}
data := ss.cache.Get([]byte(dns.Type(qtype).String() + " " + host))
if data == nil {
return res, false
}
exp := binary.BigEndian.Uint32(data[:4])
if exp <= uint32(time.Now().Unix()) {
ss.cache.Del([]byte(host))
return res, false
}
buf := bytes.NewBuffer(data[4:])
err := gob.NewDecoder(buf).Decode(&res)
if err != nil {
ss.log(log.ERROR, "cache decoding: %s", err)
return filtering.Result{}, false
}
return res, true
}
// Update implements the [filtering.SafeSearch] interface for *Default. Update
// ignores the CustomResolver and Enabled fields.
func (ss *Default) Update(conf filtering.SafeSearchConfig) (err error) {
ss.mu.Lock()
defer ss.mu.Unlock()
err = ss.resetEngine(rulelist.URLFilterIDSafeSearch, conf)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return err
}
ss.cache.Clear()
return nil
}
``` | /content/code_sandbox/internal/filtering/safesearch/safesearch.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,186 |
```go
package safesearch
import (
"net/netip"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TODO(a.garipov): Move as much of this as possible into proper external tests.
const (
// TODO(a.garipov): Add IPv6 tests.
testQType = dns.TypeA
testCacheSize = 5000
testCacheTTL = 30 * time.Minute
)
var defaultSafeSearchConf = filtering.SafeSearchConfig{
Enabled: true,
Bing: true,
DuckDuckGo: true,
Ecosia: true,
Google: true,
Pixabay: true,
Yandex: true,
YouTube: true,
}
var yandexIP = netip.AddrFrom4([4]byte{213, 180, 193, 56})
func newForTest(t testing.TB, ssConf filtering.SafeSearchConfig) (ss *Default) {
ss, err := NewDefault(ssConf, "", testCacheSize, testCacheTTL)
require.NoError(t, err)
return ss
}
func TestSafeSearch(t *testing.T) {
ss := newForTest(t, defaultSafeSearchConf)
val := ss.searchHost("www.google.com", testQType)
assert.Equal(t, &rules.DNSRewrite{NewCNAME: "forcesafesearch.google.com"}, val)
}
func TestSafeSearchCacheYandex(t *testing.T) {
const domain = "yandex.ru"
ss := newForTest(t, filtering.SafeSearchConfig{Enabled: false})
// Check host with disabled safesearch.
res, err := ss.CheckHost(domain, testQType)
require.NoError(t, err)
assert.False(t, res.IsFiltered)
assert.Empty(t, res.Rules)
ss = newForTest(t, defaultSafeSearchConf)
res, err = ss.CheckHost(domain, testQType)
require.NoError(t, err)
// For yandex we already know valid IP.
require.Len(t, res.Rules, 1)
assert.Equal(t, res.Rules[0].IP, yandexIP)
// Check cache.
cachedValue, isFound := ss.getCachedResult(domain, testQType)
require.True(t, isFound)
require.Len(t, cachedValue.Rules, 1)
assert.Equal(t, cachedValue.Rules[0].IP, yandexIP)
}
const googleHost = "www.google.com"
var dnsRewriteSink *rules.DNSRewrite
func BenchmarkSafeSearch(b *testing.B) {
ss := newForTest(b, defaultSafeSearchConf)
for range b.N {
dnsRewriteSink = ss.searchHost(googleHost, testQType)
}
assert.Equal(b, "forcesafesearch.google.com", dnsRewriteSink.NewCNAME)
}
``` | /content/code_sandbox/internal/filtering/safesearch/safesearch_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 637 |
```go
package safesearch_test
import (
"context"
"net"
"net/netip"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/AdGuardHome/internal/filtering/safesearch"
"github.com/AdguardTeam/golibs/testutil"
"github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMain(m *testing.M) {
testutil.DiscardLogOutput(m)
}
// Common test constants.
const (
// TODO(a.garipov): Add IPv6 tests.
testQType = dns.TypeA
testCacheSize = 5000
testCacheTTL = 30 * time.Minute
)
// testConf is the default safe search configuration for tests.
var testConf = filtering.SafeSearchConfig{
Enabled: true,
Bing: true,
DuckDuckGo: true,
Ecosia: true,
Google: true,
Pixabay: true,
Yandex: true,
YouTube: true,
}
// yandexIP is the expected IP address of Yandex safe search results. Keep in
// sync with the rules data.
var yandexIP = netip.AddrFrom4([4]byte{213, 180, 193, 56})
func TestDefault_CheckHost_yandex(t *testing.T) {
conf := testConf
ss, err := safesearch.NewDefault(conf, "", testCacheSize, testCacheTTL)
require.NoError(t, err)
hosts := []string{
"yandex.ru",
"yAndeX.ru",
"YANdex.COM",
"yandex.by",
"yandex.kz",
"www.yandex.com",
}
testCases := []struct {
want netip.Addr
name string
qt uint16
}{{
want: yandexIP,
name: "a",
qt: dns.TypeA,
}, {
want: netip.Addr{},
name: "aaaa",
qt: dns.TypeAAAA,
}, {
want: netip.Addr{},
name: "https",
qt: dns.TypeHTTPS,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
for _, host := range hosts {
// Check host for each domain.
var res filtering.Result
res, err = ss.CheckHost(host, tc.qt)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
assert.Equal(t, filtering.FilteredSafeSearch, res.Reason)
if tc.want == (netip.Addr{}) {
assert.Empty(t, res.Rules)
} else {
require.Len(t, res.Rules, 1)
rule := res.Rules[0]
assert.Equal(t, tc.want, rule.IP)
assert.Equal(t, rulelist.URLFilterIDSafeSearch, rule.FilterListID)
}
}
})
}
}
func TestDefault_CheckHost_google(t *testing.T) {
ss, err := safesearch.NewDefault(testConf, "", testCacheSize, testCacheTTL)
require.NoError(t, err)
// Check host for each domain.
for _, host := range []string{
"www.google.com",
"www.google.im",
"www.google.co.in",
"www.google.iq",
"www.google.is",
"www.google.it",
"www.google.je",
} {
t.Run(host, func(t *testing.T) {
var res filtering.Result
res, err = ss.CheckHost(host, testQType)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
assert.Equal(t, filtering.FilteredSafeSearch, res.Reason)
assert.Equal(t, "forcesafesearch.google.com", res.CanonName)
assert.Empty(t, res.Rules)
})
}
}
// testResolver is a [filtering.Resolver] for tests.
//
// TODO(a.garipov): Move to aghtest and use everywhere.
type testResolver struct {
OnLookupIP func(ctx context.Context, network, host string) (ips []net.IP, err error)
}
// type check
var _ filtering.Resolver = (*testResolver)(nil)
// LookupIP implements the [filtering.Resolver] interface for *testResolver.
func (r *testResolver) LookupIP(
ctx context.Context,
network string,
host string,
) (ips []net.IP, err error) {
return r.OnLookupIP(ctx, network, host)
}
func TestDefault_CheckHost_duckduckgoAAAA(t *testing.T) {
ss, err := safesearch.NewDefault(testConf, "", testCacheSize, testCacheTTL)
require.NoError(t, err)
// The DuckDuckGo safe-search addresses are resolved through CNAMEs, but
// DuckDuckGo doesn't have a safe-search IPv6 address. The result should be
// the same as the one for Yandex IPv6. That is, a NODATA response.
res, err := ss.CheckHost("www.duckduckgo.com", dns.TypeAAAA)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
assert.Equal(t, filtering.FilteredSafeSearch, res.Reason)
assert.Equal(t, "safe.duckduckgo.com", res.CanonName)
assert.Empty(t, res.Rules)
}
func TestDefault_Update(t *testing.T) {
conf := testConf
ss, err := safesearch.NewDefault(conf, "", testCacheSize, testCacheTTL)
require.NoError(t, err)
res, err := ss.CheckHost("www.yandex.com", testQType)
require.NoError(t, err)
assert.True(t, res.IsFiltered)
err = ss.Update(filtering.SafeSearchConfig{
Enabled: true,
Google: false,
})
require.NoError(t, err)
res, err = ss.CheckHost("www.yandex.com", testQType)
require.NoError(t, err)
assert.False(t, res.IsFiltered)
err = ss.Update(filtering.SafeSearchConfig{
Enabled: false,
Google: true,
})
require.NoError(t, err)
res, err = ss.CheckHost("www.yandex.com", testQType)
require.NoError(t, err)
assert.False(t, res.IsFiltered)
}
``` | /content/code_sandbox/internal/filtering/safesearch/safesearch_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,409 |
```go
package safesearch
import _ "embed"
//go:embed rules/bing.txt
var bing string
//go:embed rules/google.txt
var google string
//go:embed rules/pixabay.txt
var pixabay string
//go:embed rules/duckduckgo.txt
var duckduckgo string
//go:embed rules/ecosia.txt
var ecosia string
//go:embed rules/yandex.txt
var yandex string
//go:embed rules/youtube.txt
var youtube string
// safeSearchRules is a map with rules texts grouped by search providers.
// Source rules downloaded from:
// path_to_url
// path_to_url
var safeSearchRules = map[Service]string{
Bing: bing,
DuckDuckGo: duckduckgo,
Ecosia: ecosia,
Google: google,
Pixabay: pixabay,
Yandex: yandex,
YouTube: youtube,
}
``` | /content/code_sandbox/internal/filtering/safesearch/rules.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 207 |
```go
//go:build darwin || openbsd
package aghos
import (
"os"
"syscall"
)
func setRlimit(val uint64) (err error) {
var rlim syscall.Rlimit
rlim.Max = val
rlim.Cur = val
return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlim)
}
func haveAdminRights() (bool, error) {
return os.Getuid() == 0, nil
}
func isOpenWrt() (ok bool) {
return false
}
``` | /content/code_sandbox/internal/aghos/os_bsd.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 115 |
```go
package aghos
// PreCheckActionStart performs the service start action pre-check.
func PreCheckActionStart() (err error) {
return preCheckActionStart()
}
``` | /content/code_sandbox/internal/aghos/service.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 37 |
```go
package aghos
// ConfigureSyslog reroutes standard logger output to syslog.
func ConfigureSyslog(serviceName string) (err error) {
return configureSyslog(serviceName)
}
``` | /content/code_sandbox/internal/aghos/syslog.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 39 |
```go
//go:build windows
package aghos
import (
"strings"
"github.com/AdguardTeam/golibs/log"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc/eventlog"
)
type eventLogWriter struct {
el *eventlog.Log
}
// Write implements io.Writer interface for eventLogWriter.
func (w *eventLogWriter) Write(b []byte) (int, error) {
return len(b), w.el.Info(1, string(b))
}
// configureSyslog sets standard log output to event log.
func configureSyslog(serviceName string) (err error) {
// Note that the eventlog src is the same as the service name, otherwise we
// will get "the description for event id cannot be found" warning in every
// log record.
// Continue if we receive "registry key already exists" or if we get
// ERROR_ACCESS_DENIED so that we can log without administrative permissions
// for pre-existing eventlog sources.
err = eventlog.InstallAsEventCreate(serviceName, eventlog.Info|eventlog.Warning|eventlog.Error)
if err != nil &&
!strings.Contains(err.Error(), "registry key already exists") &&
err != windows.ERROR_ACCESS_DENIED {
// Don't wrap the error, because it's informative enough as is.
return err
}
el, err := eventlog.Open(serviceName)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return err
}
log.SetOutput(&eventLogWriter{el: el})
return nil
}
``` | /content/code_sandbox/internal/aghos/syslog_windows.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 343 |
```go
//go:build freebsd
package aghos
import (
"os"
"syscall"
)
func setRlimit(val uint64) (err error) {
var rlim syscall.Rlimit
rlim.Max = int64(val)
rlim.Cur = int64(val)
return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlim)
}
func haveAdminRights() (bool, error) {
return os.Getuid() == 0, nil
}
func isOpenWrt() (ok bool) {
return false
}
``` | /content/code_sandbox/internal/aghos/os_freebsd.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 116 |
```go
//go:build !darwin
package aghos
// preCheckActionStart performs the service start action pre-check.
func preCheckActionStart() (err error) {
return nil
}
``` | /content/code_sandbox/internal/aghos/service_others.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 41 |
```go
//go:build windows
package aghos
import (
"os"
"os/signal"
"golang.org/x/sys/windows"
)
func setRlimit(val uint64) (err error) {
return Unsupported("setrlimit")
}
func haveAdminRights() (bool, error) {
var token windows.Token
h := windows.CurrentProcess()
err := windows.OpenProcessToken(h, windows.TOKEN_QUERY, &token)
if err != nil {
return false, err
}
info := make([]byte, 4)
var returnedLen uint32
err = windows.GetTokenInformation(token, windows.TokenElevation, &info[0], uint32(len(info)), &returnedLen)
token.Close()
if err != nil {
return false, err
}
if info[0] == 0 {
return false, nil
}
return true, nil
}
func isOpenWrt() (ok bool) {
return false
}
func notifyReconfigureSignal(c chan<- os.Signal) {
signal.Notify(c, windows.SIGHUP)
}
func isReconfigureSignal(sig os.Signal) (ok bool) {
return sig == windows.SIGHUP
}
func sendShutdownSignal(c chan<- os.Signal) {
c <- os.Interrupt
}
``` | /content/code_sandbox/internal/aghos/os_windows.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 261 |
```go
// Package aghos contains utilities for functions requiring system calls and
// other OS-specific APIs. OS-specific network handling should go to aghnet
// instead.
package aghos
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"path"
"runtime"
"slices"
"strconv"
"strings"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
)
// Unsupported is a helper that returns a wrapped [errors.ErrUnsupported].
func Unsupported(op string) (err error) {
return fmt.Errorf("%s: not supported on %s: %w", op, runtime.GOOS, errors.ErrUnsupported)
}
// SetRlimit sets user-specified limit of how many fd's we can use.
//
// See path_to_url
func SetRlimit(val uint64) (err error) {
return setRlimit(val)
}
// HaveAdminRights checks if the current user has root (administrator) rights.
func HaveAdminRights() (bool, error) {
return haveAdminRights()
}
// MaxCmdOutputSize is the maximum length of performed shell command output in
// bytes.
const MaxCmdOutputSize = 64 * 1024
// RunCommand runs shell command.
func RunCommand(command string, arguments ...string) (code int, output []byte, err error) {
cmd := exec.Command(command, arguments...)
out, err := cmd.Output()
out = out[:min(len(out), MaxCmdOutputSize)]
if err != nil {
if eerr := new(exec.ExitError); errors.As(err, &eerr) {
return eerr.ExitCode(), eerr.Stderr, nil
}
return 1, nil, fmt.Errorf("command %q failed: %w: %s", command, err, out)
}
return cmd.ProcessState.ExitCode(), out, nil
}
// PIDByCommand searches for process named command and returns its PID ignoring
// the PIDs from except. If no processes found, the error returned.
func PIDByCommand(command string, except ...int) (pid int, err error) {
// Don't use -C flag here since it's a feature of linux's ps
// implementation. Use POSIX-compatible flags instead.
//
// See path_to_url
cmd := exec.Command("ps", "-A", "-o", "pid=", "-o", "comm=")
var stdout io.ReadCloser
if stdout, err = cmd.StdoutPipe(); err != nil {
return 0, fmt.Errorf("getting the command's stdout pipe: %w", err)
}
if err = cmd.Start(); err != nil {
return 0, fmt.Errorf("start command executing: %w", err)
}
var instNum int
pid, instNum, err = parsePSOutput(stdout, command, except)
if err != nil {
return 0, err
}
if err = cmd.Wait(); err != nil {
return 0, fmt.Errorf("executing the command: %w", err)
}
switch instNum {
case 0:
// TODO(e.burkov): Use constant error.
return 0, fmt.Errorf("no %s instances found", command)
case 1:
// Go on.
default:
log.Info("warning: %d %s instances found", instNum, command)
}
if code := cmd.ProcessState.ExitCode(); code != 0 {
return 0, fmt.Errorf("ps finished with code %d", code)
}
return pid, nil
}
// parsePSOutput scans the output of ps searching the largest PID of the process
// associated with cmdName ignoring PIDs from ignore. A valid line from r
// should look like these:
//
// 123 ./example-cmd
// 1230 some/base/path/example-cmd
// 3210 example-cmd
func parsePSOutput(r io.Reader, cmdName string, ignore []int) (largest, instNum int, err error) {
s := bufio.NewScanner(r)
for s.Scan() {
fields := strings.Fields(s.Text())
if len(fields) != 2 || path.Base(fields[1]) != cmdName {
continue
}
cur, aerr := strconv.Atoi(fields[0])
if aerr != nil || cur < 0 || slices.Contains(ignore, cur) {
continue
}
instNum++
largest = max(largest, cur)
}
if err = s.Err(); err != nil {
return 0, 0, fmt.Errorf("scanning stdout: %w", err)
}
return largest, instNum, nil
}
// IsOpenWrt returns true if host OS is OpenWrt.
func IsOpenWrt() (ok bool) {
return isOpenWrt()
}
// NotifyReconfigureSignal notifies c on receiving reconfigure signals.
func NotifyReconfigureSignal(c chan<- os.Signal) {
notifyReconfigureSignal(c)
}
// IsReconfigureSignal returns true if sig is a reconfigure signal.
func IsReconfigureSignal(sig os.Signal) (ok bool) {
return isReconfigureSignal(sig)
}
// SendShutdownSignal sends the shutdown signal to the channel.
func SendShutdownSignal(c chan<- os.Signal) {
sendShutdownSignal(c)
}
``` | /content/code_sandbox/internal/aghos/os.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,126 |
```go
//go:build !windows
package aghos
import (
"log/syslog"
"github.com/AdguardTeam/golibs/log"
)
// configureSyslog sets standard log output to syslog.
func configureSyslog(serviceName string) (err error) {
w, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_USER, serviceName)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return err
}
log.SetOutput(w)
return nil
}
``` | /content/code_sandbox/internal/aghos/syslog_others.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 112 |
```go
package aghos
import (
"fmt"
"io"
"io/fs"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors"
)
// FileWalker is the signature of a function called for files in the file tree.
// As opposed to filepath.Walk it only walk the files (not directories) matching
// the provided pattern and those returned by function itself. All patterns
// should be valid for fs.Glob. If FileWalker returns false for cont then
// walking terminates. Prefer using bufio.Scanner to read the r since the input
// is not limited.
//
// TODO(e.burkov, a.garipov): Move into another package like aghfs.
//
// TODO(e.burkov): Think about passing filename or any additional data.
type FileWalker func(r io.Reader) (patterns []string, cont bool, err error)
// checkFile tries to open and process a single file located on sourcePath in
// the specified fsys. The path is skipped if it's a directory.
func checkFile(
fsys fs.FS,
c FileWalker,
sourcePath string,
) (patterns []string, cont bool, err error) {
var f fs.File
f, err = fsys.Open(sourcePath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// Ignore non-existing files since this may only happen when the
// file was removed after filepath.Glob matched it.
return nil, true, nil
}
return nil, false, err
}
defer func() { err = errors.WithDeferred(err, f.Close()) }()
var fi fs.FileInfo
if fi, err = f.Stat(); err != nil {
return nil, true, err
} else if fi.IsDir() {
// Skip the directories.
return nil, true, nil
}
return c(f)
}
// handlePatterns parses the patterns in fsys and ignores duplicates using
// srcSet. srcSet must be non-nil.
func handlePatterns(
fsys fs.FS,
srcSet *container.MapSet[string],
patterns ...string,
) (sub []string, err error) {
sub = make([]string, 0, len(patterns))
for _, p := range patterns {
var matches []string
matches, err = fs.Glob(fsys, p)
if err != nil {
// Enrich error with the pattern because filepath.Glob
// doesn't do it.
return nil, fmt.Errorf("invalid pattern %q: %w", p, err)
}
for _, m := range matches {
if srcSet.Has(m) {
continue
}
srcSet.Add(m)
sub = append(sub, m)
}
}
return sub, nil
}
// Walk starts walking the files in fsys defined by patterns from initial.
// It only returns true if fw signed to stop walking.
func (fw FileWalker) Walk(fsys fs.FS, initial ...string) (ok bool, err error) {
// The slice of sources keeps the order in which the files are walked since
// srcSet.Values() returns strings in undefined order.
srcSet := container.NewMapSet[string]()
var src []string
src, err = handlePatterns(fsys, srcSet, initial...)
if err != nil {
return false, err
}
var filename string
defer func() { err = errors.Annotate(err, "checking %q: %w", filename) }()
// TODO(e.burkov): Redo this loop, as it modifies the very same slice it
// iterates over.
for i := 0; i < len(src); i++ {
var patterns []string
var cont bool
filename = src[i]
patterns, cont, err = checkFile(fsys, fw, src[i])
if err != nil {
return false, err
}
if !cont {
return true, nil
}
var subsrc []string
subsrc, err = handlePatterns(fsys, srcSet, patterns...)
if err != nil {
return false, err
}
src = append(src, subsrc...)
}
return false, nil
}
``` | /content/code_sandbox/internal/aghos/filewalker.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 923 |
```go
//go:build linux
package aghos
import (
"io"
"os"
"syscall"
"github.com/AdguardTeam/golibs/osutil"
"github.com/AdguardTeam/golibs/stringutil"
)
func setRlimit(val uint64) (err error) {
var rlim syscall.Rlimit
rlim.Max = val
rlim.Cur = val
return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlim)
}
func haveAdminRights() (bool, error) {
// The error is nil because the platform-independent function signature
// requires returning an error.
return os.Getuid() == 0, nil
}
func isOpenWrt() (ok bool) {
const etcReleasePattern = "etc/*release*"
var err error
ok, err = FileWalker(func(r io.Reader) (_ []string, cont bool, err error) {
const osNameData = "openwrt"
// This use of ReadAll is now safe, because FileWalker's Walk()
// have limited r.
var data []byte
data, err = io.ReadAll(r)
if err != nil {
return nil, false, err
}
return nil, !stringutil.ContainsFold(string(data), osNameData), nil
}).Walk(osutil.RootDirFS(), etcReleasePattern)
return err == nil && ok
}
``` | /content/code_sandbox/internal/aghos/os_linux.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 300 |
```go
package aghos
import (
"io/fs"
"path"
"testing"
"testing/fstest"
"github.com/AdguardTeam/golibs/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// errFS is an fs.FS implementation, method Open of which always returns
// errFSOpen.
type errFS struct{}
// errFSOpen is returned from errFS.Open.
const errFSOpen errors.Error = "test open error"
// Open implements the fs.FS interface for *errFS. fsys is always nil and err
// is always errFSOpen.
func (efs *errFS) Open(name string) (fsys fs.File, err error) {
return nil, errFSOpen
}
func TestWalkerFunc_CheckFile(t *testing.T) {
emptyFS := fstest.MapFS{}
t.Run("non-existing", func(t *testing.T) {
_, ok, err := checkFile(emptyFS, nil, "lol")
require.NoError(t, err)
assert.True(t, ok)
})
t.Run("invalid_argument", func(t *testing.T) {
_, ok, err := checkFile(&errFS{}, nil, "")
require.ErrorIs(t, err, errFSOpen)
assert.False(t, ok)
})
t.Run("ignore_dirs", func(t *testing.T) {
const dirName = "dir"
testFS := fstest.MapFS{
path.Join(dirName, "file"): &fstest.MapFile{Data: []byte{}},
}
patterns, ok, err := checkFile(testFS, nil, dirName)
require.NoError(t, err)
assert.Empty(t, patterns)
assert.True(t, ok)
})
}
``` | /content/code_sandbox/internal/aghos/filewalker_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 374 |
```go
package aghos
import (
"fmt"
"io"
"io/fs"
"path/filepath"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/osutil"
"github.com/fsnotify/fsnotify"
)
// event is a convenient alias for an empty struct to signal that watching
// event happened.
type event = struct{}
// FSWatcher tracks all the fyle system events and notifies about those.
//
// TODO(e.burkov, a.garipov): Move into another package like aghfs.
//
// TODO(e.burkov): Add tests.
type FSWatcher interface {
// Start starts watching the added files.
Start() (err error)
// Close stops watching the files and closes an update channel.
io.Closer
// Events returns the channel to notify about the file system events.
Events() (e <-chan event)
// Add starts tracking the file. It returns an error if the file can't be
// tracked. It must not be called after Start.
Add(name string) (err error)
}
// osWatcher tracks the file system provided by the OS.
type osWatcher struct {
// watcher is the actual notifier that is handled by osWatcher.
watcher *fsnotify.Watcher
// events is the channel to notify.
events chan event
// files is the set of tracked files.
files *container.MapSet[string]
}
// osWatcherPref is a prefix for logging and wrapping errors in osWathcer's
// methods.
const osWatcherPref = "os watcher"
// NewOSWritesWatcher creates FSWatcher that tracks the real file system of the
// OS and notifies only about writing events.
func NewOSWritesWatcher() (w FSWatcher, err error) {
defer func() { err = errors.Annotate(err, "%s: %w", osWatcherPref) }()
var watcher *fsnotify.Watcher
watcher, err = fsnotify.NewWatcher()
if err != nil {
return nil, fmt.Errorf("creating watcher: %w", err)
}
return &osWatcher{
watcher: watcher,
events: make(chan event, 1),
files: container.NewMapSet[string](),
}, nil
}
// type check
var _ FSWatcher = (*osWatcher)(nil)
// Start implements the FSWatcher interface for *osWatcher.
func (w *osWatcher) Start() (err error) {
go w.handleErrors()
go w.handleEvents()
return nil
}
// Close implements the FSWatcher interface for *osWatcher.
func (w *osWatcher) Close() (err error) {
return w.watcher.Close()
}
// Events implements the FSWatcher interface for *osWatcher.
func (w *osWatcher) Events() (e <-chan event) {
return w.events
}
// Add implements the [FSWatcher] interface for *osWatcher.
//
// TODO(e.burkov): Make it accept non-existing files to detect it's creating.
func (w *osWatcher) Add(name string) (err error) {
defer func() { err = errors.Annotate(err, "%s: %w", osWatcherPref) }()
fi, err := fs.Stat(osutil.RootDirFS(), name)
if err != nil {
return fmt.Errorf("checking file %q: %w", name, err)
}
name = filepath.Join("/", name)
w.files.Add(name)
// Watch the directory and filter the events by the file name, since the
// common recomendation to the fsnotify package is to watch the directory
// instead of the file itself.
//
// See path_to_url#readme-watching-a-file-doesn-t-work-well.
if !fi.IsDir() {
name = filepath.Dir(name)
}
return w.watcher.Add(name)
}
// handleEvents notifies about the received file system's event if needed. It
// is intended to be used as a goroutine.
func (w *osWatcher) handleEvents() {
defer log.OnPanic(fmt.Sprintf("%s: handling events", osWatcherPref))
defer close(w.events)
ch := w.watcher.Events
for e := range ch {
if e.Op&fsnotify.Write == 0 || !w.files.Has(e.Name) {
continue
}
// Skip the following events assuming that sometimes the same event
// occurs several times.
for ok := true; ok; {
select {
case _, ok = <-ch:
// Go on.
default:
ok = false
}
}
select {
case w.events <- event{}:
// Go on.
default:
log.Debug("%s: events buffer is full", osWatcherPref)
}
}
}
// handleErrors handles accompanying errors. It used to be called in a separate
// goroutine.
func (w *osWatcher) handleErrors() {
defer log.OnPanic(fmt.Sprintf("%s: handling errors", osWatcherPref))
for err := range w.watcher.Errors {
log.Error("%s: %s", osWatcherPref, err)
}
}
// EmptyFSWatcher is a no-op implementation of the [FSWatcher] interface. It
// may be used on systems not supporting filesystem events.
type EmptyFSWatcher struct{}
// type check
var _ FSWatcher = EmptyFSWatcher{}
// Start implements the [FSWatcher] interface for EmptyFSWatcher. It always
// returns nil error.
func (EmptyFSWatcher) Start() (err error) {
return nil
}
// Close implements the [FSWatcher] interface for EmptyFSWatcher. It always
// returns nil error.
func (EmptyFSWatcher) Close() (err error) {
return nil
}
// Events implements the [FSWatcher] interface for EmptyFSWatcher. It always
// returns nil channel.
func (EmptyFSWatcher) Events() (e <-chan event) {
return nil
}
// Add implements the [FSWatcher] interface for EmptyFSWatcher. It always
// returns nil error.
func (EmptyFSWatcher) Add(_ string) (err error) {
return nil
}
``` | /content/code_sandbox/internal/aghos/fswatcher.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,326 |
```go
//go:build darwin || freebsd || linux || openbsd
package aghos
import (
"fmt"
"os/user"
"strconv"
"syscall"
)
func setGroup(groupName string) (err error) {
g, err := user.LookupGroup(groupName)
if err != nil {
return fmt.Errorf("looking up group: %w", err)
}
gid, err := strconv.Atoi(g.Gid)
if err != nil {
return fmt.Errorf("parsing gid: %w", err)
}
err = syscall.Setgid(gid)
if err != nil {
return fmt.Errorf("setting gid: %w", err)
}
return nil
}
func setUser(userName string) (err error) {
u, err := user.Lookup(userName)
if err != nil {
return fmt.Errorf("looking up user: %w", err)
}
uid, err := strconv.Atoi(u.Uid)
if err != nil {
return fmt.Errorf("parsing uid: %w", err)
}
err = syscall.Setuid(uid)
if err != nil {
return fmt.Errorf("setting uid: %w", err)
}
return nil
}
``` | /content/code_sandbox/internal/aghos/user_unix.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 247 |
```go
//go:build darwin
package aghos
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/AdguardTeam/golibs/log"
)
// preCheckActionStart performs the service start action pre-check. It warns
// user that the service should be installed into Applications directory.
func preCheckActionStart() (err error) {
exe, err := os.Executable()
if err != nil {
return fmt.Errorf("getting executable path: %v", err)
}
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
return fmt.Errorf("evaluating executable symlinks: %v", err)
}
if !strings.HasPrefix(exe, "/Applications/") {
log.Info("warning: service must be started from within the /Applications directory")
}
return err
}
``` | /content/code_sandbox/internal/aghos/service_darwin.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 183 |
```go
package aghos
import (
"bytes"
"testing"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLargestLabeled(t *testing.T) {
const (
comm = `command-name`
nl = "\n"
)
testCases := []struct {
name string
data []byte
wantPID int
wantInstNum int
}{{
name: "success",
data: []byte(nl +
` 123 not-a-` + comm + nl +
` 321 ` + comm + nl,
),
wantPID: 321,
wantInstNum: 1,
}, {
name: "several",
data: []byte(nl +
`1 ` + comm + nl +
`5 /` + comm + nl +
`2 /some/path/` + comm + nl +
`4 ./` + comm + nl +
`3 ` + comm + nl +
`10 .` + comm + nl,
),
wantPID: 5,
wantInstNum: 5,
}, {
name: "no_any",
data: []byte(nl +
`1 ` + `not-a-` + comm + nl +
`2 ` + `not-a-` + comm + nl +
`3 ` + `not-a-` + comm + nl,
),
wantPID: 0,
wantInstNum: 0,
}, {
name: "weird_input",
data: []byte(nl +
`abc ` + comm + nl +
`-1 ` + comm + nl,
),
wantPID: 0,
wantInstNum: 0,
}}
for _, tc := range testCases {
r := bytes.NewReader(tc.data)
t.Run(tc.name, func(t *testing.T) {
pid, instNum, err := parsePSOutput(r, comm, nil)
require.NoError(t, err)
assert.Equal(t, tc.wantPID, pid)
assert.Equal(t, tc.wantInstNum, instNum)
})
}
t.Run("scanner_fail", func(t *testing.T) {
lr := ioutil.LimitReader(bytes.NewReader([]byte{1, 2, 3}), 0)
target := &ioutil.LimitError{}
_, _, err := parsePSOutput(lr, "", nil)
require.ErrorAs(t, err, &target)
assert.EqualValues(t, 0, target.Limit)
})
t.Run("ignore", func(t *testing.T) {
r := bytes.NewReader([]byte(nl +
`1 ` + comm + nl +
`2 ` + comm + nl +
`3` + comm + nl,
))
pid, instances, err := parsePSOutput(r, comm, []int{1, 3})
require.NoError(t, err)
assert.Equal(t, 2, pid)
assert.Equal(t, 1, instances)
})
}
``` | /content/code_sandbox/internal/aghos/os_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 696 |
```go
//go:build windows
package aghos
// TODO(a.garipov): Think of a way to implement these. Perhaps by using
// syscall.CreateProcessAsUser or something from the golang.org/x/sys module.
func setGroup(_ string) (err error) {
return Unsupported("setgid")
}
func setUser(_ string) (err error) {
return Unsupported("setuid")
}
``` | /content/code_sandbox/internal/aghos/user_windows.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 85 |
```go
package aghos
// SetGroup sets the effective group ID of the calling process.
func SetGroup(groupName string) (err error) {
return setGroup(groupName)
}
// SetUser sets the effective user ID of the calling process.
func SetUser(userName string) (err error) {
return setUser(userName)
}
``` | /content/code_sandbox/internal/aghos/user.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 67 |
```go
package aghos_test
import (
"testing"
"github.com/AdguardTeam/golibs/testutil"
)
func TestMain(m *testing.M) {
testutil.DiscardLogOutput(m)
}
``` | /content/code_sandbox/internal/aghos/aghos_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 44 |
```go
package aghos_test
import (
"bufio"
"io"
"path"
"testing"
"testing/fstest"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFileWalker_Walk(t *testing.T) {
const attribute = `000`
makeFileWalker := func(_ string) (fw aghos.FileWalker) {
return func(r io.Reader) (patterns []string, cont bool, err error) {
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
if line == attribute {
return nil, false, nil
}
if len(line) != 0 {
patterns = append(patterns, path.Join(".", line))
}
}
return patterns, true, s.Err()
}
}
const nl = "\n"
testCases := []struct {
testFS fstest.MapFS
want assert.BoolAssertionFunc
initPattern string
name string
}{{
name: "simple",
testFS: fstest.MapFS{
"simple_0001.txt": &fstest.MapFile{Data: []byte(attribute + nl)},
},
initPattern: "simple_0001.txt",
want: assert.True,
}, {
name: "chain",
testFS: fstest.MapFS{
"chain_0001.txt": &fstest.MapFile{Data: []byte(`chain_0002.txt` + nl)},
"chain_0002.txt": &fstest.MapFile{Data: []byte(`chain_0003.txt` + nl)},
"chain_0003.txt": &fstest.MapFile{Data: []byte(attribute + nl)},
},
initPattern: "chain_0001.txt",
want: assert.True,
}, {
name: "several",
testFS: fstest.MapFS{
"several_0001.txt": &fstest.MapFile{Data: []byte(`several_*` + nl)},
"several_0002.txt": &fstest.MapFile{Data: []byte(`several_0001.txt` + nl)},
"several_0003.txt": &fstest.MapFile{Data: []byte(attribute + nl)},
},
initPattern: "several_0001.txt",
want: assert.True,
}, {
name: "no",
testFS: fstest.MapFS{
"no_0001.txt": &fstest.MapFile{Data: []byte(nl)},
"no_0002.txt": &fstest.MapFile{Data: []byte(nl)},
"no_0003.txt": &fstest.MapFile{Data: []byte(nl)},
},
initPattern: "no_*",
want: assert.False,
}, {
name: "subdirectory",
testFS: fstest.MapFS{
path.Join("dir", "subdir_0002.txt"): &fstest.MapFile{
Data: []byte(attribute + nl),
},
"subdir_0001.txt": &fstest.MapFile{Data: []byte(`dir/*`)},
},
initPattern: "subdir_0001.txt",
want: assert.True,
}}
for _, tc := range testCases {
fw := makeFileWalker("")
t.Run(tc.name, func(t *testing.T) {
ok, err := fw.Walk(tc.testFS, tc.initPattern)
require.NoError(t, err)
tc.want(t, ok)
})
}
t.Run("pattern_malformed", func(t *testing.T) {
f := fstest.MapFS{}
ok, err := makeFileWalker("").Walk(f, "[]")
require.Error(t, err)
assert.False(t, ok)
assert.ErrorIs(t, err, path.ErrBadPattern)
})
t.Run("bad_filename", func(t *testing.T) {
const filename = "bad_filename.txt"
f := fstest.MapFS{
filename: &fstest.MapFile{Data: []byte("[]")},
}
ok, err := aghos.FileWalker(func(r io.Reader) (patterns []string, cont bool, err error) {
s := bufio.NewScanner(r)
for s.Scan() {
patterns = append(patterns, s.Text())
}
return patterns, true, s.Err()
}).Walk(f, filename)
require.Error(t, err)
assert.False(t, ok)
assert.ErrorIs(t, err, path.ErrBadPattern)
})
t.Run("itself_error", func(t *testing.T) {
const rerr errors.Error = "returned error"
f := fstest.MapFS{
"mockfile.txt": &fstest.MapFile{Data: []byte(`mockdata`)},
}
ok, err := aghos.FileWalker(func(r io.Reader) (patterns []string, ok bool, err error) {
return nil, true, rerr
}).Walk(f, "*")
require.ErrorIs(t, err, rerr)
assert.False(t, ok)
})
}
``` | /content/code_sandbox/internal/aghos/filewalker_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,159 |
```go
//go:build darwin || freebsd || linux || openbsd
package aghos
import (
"os"
"os/signal"
"golang.org/x/sys/unix"
)
func notifyReconfigureSignal(c chan<- os.Signal) {
signal.Notify(c, unix.SIGHUP)
}
func isReconfigureSignal(sig os.Signal) (ok bool) {
return sig == unix.SIGHUP
}
func sendShutdownSignal(_ chan<- os.Signal) {
// On Unix we are already notified by the system.
}
``` | /content/code_sandbox/internal/aghos/os_unix.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 110 |
```yaml
---
!include release.yaml
---
!include snapcraft.yaml
---
!include test.yaml
``` | /content/code_sandbox/bamboo-specs/bamboo.yaml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 20 |
```yaml
---
'version': 2
'plan':
'project-key': 'AGH'
'key': 'AGHBSNAPSPECS'
'name': 'AdGuard Home - Build and publish release'
# Make sure to sync any changes with the branch overrides below.
'variables':
'channel': 'edge'
'dockerFrontend': 'adguard/home-js-builder:2.0'
'dockerGo': 'adguard/go-builder:1.22.6--1'
'stages':
- 'Build frontend':
'manual': false
'final': false
'jobs':
- 'Build frontend'
- 'Make release':
'manual': false
'final': false
'jobs':
- 'Make release'
- 'Make and publish docker':
'manual': false
'final': false
'jobs':
- 'Make and publish docker'
- 'Publish to static storage':
'manual': false
'final': false
'jobs':
- 'Publish to static storage'
- 'Publish to GitHub Releases':
'manual': false
'final': false
'jobs':
- 'Publish to GitHub Releases'
'Build frontend':
'artifacts':
- 'name': 'AdGuardHome frontend'
'pattern': 'build/**'
'shared': true
'required': true
'docker':
'image': '${bamboo.dockerFrontend}'
'volumes':
'${system.YARN_DIR}': '${bamboo.cacheYarn}'
'key': 'BF'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
make\
VERBOSE=1\
js-deps js-build
'requirements':
- 'adg-docker': 'true'
'Make release':
'artifact-subscriptions':
- 'artifact': 'AdGuardHome frontend'
# TODO(a.garipov): Use more fine-grained artifact rules.
'artifacts':
- 'name': 'AdGuardHome dists'
'pattern': 'dist/**'
'shared': true
'required': true
'docker':
'image': '${bamboo.dockerGo}'
'volumes':
'${system.GO_CACHE_DIR}': '${bamboo.cacheGo}'
'${system.GO_PKG_CACHE_DIR}': '${bamboo.cacheGoPkg}'
'key': 'MR'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
# Run the build with the specified channel.
echo "${bamboo.gpgSecretKeyPart1}${bamboo.gpgSecretKeyPart2}"\
| awk '{ gsub(/\\n/, "\n"); print; }'\
| gpg --import --batch --yes
make\
CHANNEL=${bamboo.channel}\
GPG_KEY_PASSPHRASE=${bamboo.gpgPassword}\
FRONTEND_PREBUILT=1\
PARALLELISM=1\
VERBOSE=2\
build-release
'requirements':
- 'adg-docker': 'true'
'Make and publish docker':
'key': 'MPD'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
# Install Qemu, create builder.
docker version -f '{{ .Server.Experimental }}'
docker buildx rm buildx-builder || :
docker buildx create --name buildx-builder --driver docker-container\
--use
docker buildx inspect --bootstrap
# Login to DockerHub.
docker login -u="${bamboo.dockerHubUsername}"\
-p="${bamboo.dockerHubPassword}"
# Boot the builder.
docker buildx inspect --bootstrap
# Print Docker info.
docker info
# Prepare and push the build.
env\
CHANNEL="${bamboo.channel}"\
COMMIT="${bamboo.repository.revision.number}"\
DIST_DIR='dist'\
DOCKER_IMAGE_NAME='adguard/adguardhome'\
DOCKER_OUTPUT="type=image,name=adguard/adguardhome,push=true"\
VERBOSE='1'\
sh ./scripts/make/build-docker.sh
'environment':
DOCKER_CLI_EXPERIMENTAL=enabled
'final-tasks':
- 'clean'
'requirements':
- 'adg-docker': 'true'
'Publish to static storage':
'key': 'PUB'
'other':
'clean-working-dir': true
'tasks':
- 'clean'
- 'checkout':
'repository': 'bamboo-deploy-publisher'
'path': 'bamboo-deploy-publisher'
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
cd ./dist/
CHANNEL="${bamboo.channel}"
export CHANNEL
../bamboo-deploy-publisher/deploy.sh adguard-home-"$CHANNEL"
'final-tasks':
- 'clean'
'requirements':
- 'adg-docker': 'true'
'Publish to GitHub Releases':
'key': 'PTGR'
'other':
'clean-working-dir': true
'tasks':
- 'clean'
- 'checkout':
'repository': 'bamboo-deploy-publisher'
'path': 'bamboo-deploy-publisher'
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
channel="${bamboo.channel}"
readonly channel
if [ "$channel" != 'release' ] && [ "${channel}" != 'beta' ]
then
echo "don't publish to GitHub Releases for this channel"
exit 0
fi
cd ./dist/
env\
GITHUB_TOKEN="${bamboo.githubPublicRepoPassword}"\
../bamboo-deploy-publisher/deploy.sh adguard-home-github
'final-tasks':
- 'clean'
'requirements':
- 'adg-docker': 'true'
'triggers':
# Don't use minute values that end with a zero or a five as these are often
# used in CI and so resources during these minutes can be quite busy.
- 'cron': '0 42 13 ? * MON-FRI *'
'branches':
'create': 'manually'
'delete':
'after-deleted-days': 1
'after-inactive-days': 30
'integration':
'push-on-success': false
'merge-from': 'AdGuard Home - Build and publish release'
'link-to-jira': true
'notifications':
- 'events':
- 'plan-completed'
'recipients':
- 'webhook':
'name': 'Build webhook'
'url': 'path_to_url
'labels': []
'other':
'concurrent-build-plugin': 'system-default'
'branch-overrides':
# beta-vX.Y branches are the branches into which the commits that are needed
# to release a new patch version are initially cherry-picked.
- '^beta-v[0-9]+\.[0-9]+':
# Build betas on release branches manually.
'triggers': []
# Set the default release channel on the release branch to beta, as we may
# need to build a few of these.
'variables':
'channel': 'beta'
'dockerFrontend': 'adguard/home-js-builder:2.0'
'dockerGo': 'adguard/go-builder:1.22.6--1'
# release-vX.Y.Z branches are the branches from which the actual final
# release is built.
- '^release-v[0-9]+\.[0-9]+\.[0-9]+':
# Disable integration branches for release branches.
'branch-config':
'integration':
'push-on-success': false
'merge-from': 'beta-v0.107'
# Build final releases on release branches manually.
'triggers': []
# Set the default release channel on the final branch to release, as these
# are the ones that actually get released.
'variables':
'channel': 'release'
'dockerFrontend': 'adguard/home-js-builder:2.0'
'dockerGo': 'adguard/go-builder:1.22.6--1'
``` | /content/code_sandbox/bamboo-specs/release.yaml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,989 |
```yaml
---
'version': 2
'plan':
'project-key': 'AGH'
'key': 'AHBRTSPECS'
'name': 'AdGuard Home - Build and run tests'
'variables':
'dockerFrontend': 'adguard/home-js-builder:2.0'
'dockerGo': 'adguard/go-builder:1.22.6--1'
'channel': 'development'
'stages':
- 'Tests':
'manual': false
'final': false
'jobs':
- 'Test frontend'
- 'Test backend'
- 'Frontend':
manual: false
final: false
jobs:
- 'Build frontend'
- 'Artifact':
manual: false
final: false
jobs:
- 'Artifact'
'Test frontend':
'docker':
'image': '${bamboo.dockerFrontend}'
'volumes':
'${system.YARN_DIR}': '${bamboo.cacheYarn}'
'key': 'JSTEST'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
make VERBOSE=1 js-deps js-lint js-test
'final-tasks':
- 'clean'
'requirements':
- 'adg-docker': 'true'
# TODO(e.burkov): Add the linting stage for markdown docs and shell scripts.
'Test backend':
'docker':
'image': '${bamboo.dockerGo}'
'volumes':
'${system.GO_CACHE_DIR}': '${bamboo.cacheGo}'
'${system.GO_PKG_CACHE_DIR}': '${bamboo.cacheGoPkg}'
'key': 'GOTEST'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
make\
GOMAXPROCS=1\
VERBOSE=1\
go-deps go-tools go-lint
make\
VERBOSE=1\
go-test
'final-tasks':
- 'clean'
'requirements':
- 'adg-docker': 'true'
'Build frontend':
'artifacts':
- 'name': 'AdGuardHome frontend'
'pattern': 'build/**'
'shared': true
'required': true
'docker':
'image': '${bamboo.dockerFrontend}'
'volumes':
'${system.YARN_DIR}': '${bamboo.cacheYarn}'
'key': 'BF'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |-
#!/bin/sh
set -e -f -u -x
make\
VERBOSE=1\
js-deps js-build
'requirements':
- 'adg-docker': 'true'
'Artifact':
'artifact-subscriptions':
- 'artifact': 'AdGuardHome frontend'
'artifacts':
- 'name': 'AdGuardHome_windows_amd64'
'pattern': 'dist/AdGuardHome_windows_amd64.zip'
'shared': true
'required': true
- 'name': 'AdGuardHome_darwin_amd64'
'pattern': 'dist/AdGuardHome_darwin_amd64.zip'
'shared': true
'required': true
- 'name': 'AdGuardHome_linux_amd64'
'pattern': 'dist/AdGuardHome_linux_amd64.tar.gz'
'shared': true
'required': true
'docker':
'image': '${bamboo.dockerGo}'
'volumes':
'${system.GO_CACHE_DIR}': '${bamboo.cacheGo}'
'${system.GO_PKG_CACHE_DIR}': '${bamboo.cacheGoPkg}'
'key': 'ART'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |-
#!/bin/sh
set -e -f -u -x
make\
ARCH="amd64"\
CHANNEL=${bamboo.channel}\
FRONTEND_PREBUILT=1\
OS="windows darwin linux"\
PARALLELISM=1\
SIGN=0\
VERBOSE=2\
build-release
'requirements':
- 'adg-docker': 'true'
'branches':
'create': 'for-pull-request'
'delete':
'after-deleted-days': 1
'after-inactive-days': 5
'integration':
'push-on-success': false
'merge-from': 'AdGuard Home - Build and run tests'
'link-to-jira': true
'notifications':
- 'events':
- 'plan-status-changed'
'recipients':
- 'webhook':
'name': 'Build webhook'
'url': 'path_to_url
'labels': []
'other':
'concurrent-build-plugin': 'system-default'
'branch-overrides':
# rc-vX.Y.Z branches are the release candidate branches. They are created
# from the release branch and are used to build the release candidate
# images.
- '^rc-v[0-9]+\.[0-9]+\.[0-9]+':
# Set the default release channel on the release branch to beta, as we
# may need to build a few of these.
'variables':
'dockerFrontend': 'adguard/home-js-builder:2.0'
'dockerGo': 'adguard/go-builder:1.22.6--1'
'channel': 'candidate'
``` | /content/code_sandbox/bamboo-specs/test.yaml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,348 |
```yaml
---
# This part of the release build is separate from the one described in
# release.yaml, because the Snapcraft infrastructure is brittle, and timeouts
# during logins and uploads often lead to release blocking.
'version': 2
'plan':
'project-key': 'AGH'
'key': 'AGHSNAP'
'name': 'AdGuard Home - Build and publish Snapcraft release'
# Make sure to sync any changes with the branch overrides below.
'variables':
'channel': 'edge'
'dockerSnap': 'adguard/snap-builder:1.1'
'snapcraftChannel': 'edge'
'stages':
- 'Download release':
'manual': false
'final': false
'jobs':
- 'Download release'
- 'Build packages':
'manual': false
'final': false
'jobs':
- 'Build packages'
- 'Publish to Snapstore':
'manual': false
'final': false
'jobs':
- 'Publish to Snapstore'
# TODO(a.garipov): Consider using the Artifact Downloader Task if it ever learns
# about plan branches.
'Download release':
'artifacts':
- 'name': 'i386_binary'
'pattern': 'AdGuardHome_i386'
'shared': true
'required': true
- 'name': 'amd64_binary'
'pattern': 'AdGuardHome_amd64'
'shared': true
'required': true
- 'name': 'armhf_binary'
'pattern': 'AdGuardHome_armhf'
'shared': true
'required': true
- 'name': 'arm64_binary'
'pattern': 'AdGuardHome_arm64'
'shared': true
'required': true
'docker':
'image': '${bamboo.dockerSnap}'
'key': 'DR'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
env\
CHANNEL="${bamboo.channel}"\
VERBOSE='1'\
sh ./scripts/snap/download.sh
'requirements':
- 'adg-docker': 'true'
'Build packages':
'artifact-subscriptions':
- 'artifact': 'i386_binary'
- 'artifact': 'amd64_binary'
- 'artifact': 'armhf_binary'
- 'artifact': 'arm64_binary'
'artifacts':
- 'name': 'i386_snap'
'pattern': 'AdGuardHome_i386.snap'
'shared': true
'required': true
- 'name': 'amd64_snap'
'pattern': 'AdGuardHome_amd64.snap'
'shared': true
'required': true
- 'name': 'armhf_snap'
'pattern': 'AdGuardHome_armhf.snap'
'shared': true
'required': true
- 'name': 'arm64_snap'
'pattern': 'AdGuardHome_arm64.snap'
'shared': true
'required': true
'docker':
'image': '${bamboo.dockerSnap}'
'key': 'BP'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
env\
VERBOSE='1'\
sh ./scripts/snap/build.sh
'requirements':
- 'adg-docker': 'true'
'Publish to Snapstore':
'artifact-subscriptions':
- 'artifact': 'i386_snap'
- 'artifact': 'amd64_snap'
- 'artifact': 'armhf_snap'
- 'artifact': 'arm64_snap'
'docker':
'image': '${bamboo.dockerSnap}'
'key': 'PTS'
'other':
'clean-working-dir': true
'tasks':
- 'checkout':
'force-clean-build': true
- 'script':
'interpreter': 'SHELL'
'scripts':
- |
#!/bin/sh
set -e -f -u -x
env\
SNAPCRAFT_CHANNEL="${bamboo.snapcraftChannel}"\
SNAPCRAFT_STORE_CREDENTIALS="${bamboo.snapcraftMacaroonPassword}"\
VERBOSE='1'\
sh ./scripts/snap/upload.sh
'final-tasks':
- 'clean'
'requirements':
- 'adg-docker': 'true'
'triggers':
# Don't use minute values that end with a zero or a five as these are often
# used in CI and so resources during these minutes can be quite busy.
#
# NOTE: The time is chosen to be exactly one hour after the main release
# build as defined as in release.yaml.
- 'cron': '0 42 14 ? * MON-FRI *'
'branches':
'create': 'manually'
'delete':
'after-deleted-days': 1
'after-inactive-days': 30
'integration':
'push-on-success': false
'merge-from': 'AdGuard Home - Build and publish Snapcraft release'
'link-to-jira': true
'notifications':
- 'events':
- 'plan-completed'
'recipients':
- 'webhook':
'name': 'Build webhook'
'url': 'path_to_url
'labels': []
'other':
'concurrent-build-plugin': 'system-default'
'branch-overrides':
# beta-vX.Y branches are the branches into which the commits that are needed
# to release a new patch version are initially cherry-picked.
- '^beta-v[0-9]+\.[0-9]+':
# Build betas on release branches manually.
'triggers': []
# Set the default release channel on the release branch to beta, as we may
# need to build a few of these.
'variables':
'channel': 'beta'
'dockerSnap': 'adguard/snap-builder:1.1'
'snapcraftChannel': 'beta'
# release-vX.Y.Z branches are the branches from which the actual final
# release is built.
- '^release-v[0-9]+\.[0-9]+\.[0-9]+':
# Disable integration branches for release branches.
'branch-config':
'integration':
'push-on-success': false
'merge-from': 'beta-v0.107'
# Build final releases on release branches manually.
'triggers': []
# Set the default release channel on the final branch to release, as these
# are the ones that actually get released.
'variables':
'channel': 'release'
'dockerSnap': 'adguard/snap-builder:1.1'
'snapcraftChannel': 'candidate'
``` | /content/code_sandbox/bamboo-specs/snapcraft.yaml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,567 |
```shell
#!/bin/sh
# AdGuard Home Installation Script
# Exit the script if a pipeline fails (-e), prevent accidental filename
# expansion (-f), and consider undefined variables as errors (-u).
set -e -f -u
# Function log is an echo wrapper that writes to stderr if the caller
# requested verbosity level greater than 0. Otherwise, it does nothing.
log() {
if [ "$verbose" -gt '0' ]
then
echo "$1" 1>&2
fi
}
# Function error_exit is an echo wrapper that writes to stderr and stops the
# script execution with code 1.
error_exit() {
echo "$1" 1>&2
exit 1
}
# Function usage prints the note about how to use the script.
#
# TODO(e.burkov): Document each option.
usage() {
echo 'install.sh: usage: [-c channel] [-C cpu_type] [-h] [-O os] [-o output_dir]'\
'[-r|-R] [-u|-U] [-v|-V]' 1>&2
exit 2
}
# Function maybe_sudo runs passed command with root privileges if use_sudo isn't
# equal to 0.
#
# TODO(e.burkov): Use everywhere the sudo_cmd isn't quoted.
maybe_sudo() {
if [ "$use_sudo" -eq 0 ]
then
"$@"
else
"$sudo_cmd" "$@"
fi
}
# Function is_command checks if the command exists on the machine.
is_command() {
command -v "$1" >/dev/null 2>&1
}
# Function is_little_endian checks if the CPU is little-endian.
#
# See path_to_url
is_little_endian() {
# The ASCII character "I" has the octal code of 111. In the two-byte octal
# display mode (-o), hexdump will print it either as "000111" on a little
# endian system or as a "111000" on a big endian one. Return the sixth
# character to compare it against the number '1'.
#
# Do not use echo -n, because its behavior in the presence of the -n flag is
# explicitly implementation-defined in POSIX. Use hexdump instead of od,
# because OpenWrt and its derivatives have the former but not the latter.
is_little_endian_result="$(
printf 'I'\
| hexdump -o\
| awk '{ print substr($2, 6, 1); exit; }'
)"
readonly is_little_endian_result
[ "$is_little_endian_result" -eq '1' ]
}
# Function check_required checks if the required software is available on the
# machine. The required software:
#
# unzip (macOS) / tar (other unixes)
#
# curl/wget are checked in function configure.
check_required() {
required_darwin="unzip"
required_unix="tar"
readonly required_darwin required_unix
case "$os"
in
('freebsd'|'linux'|'openbsd')
required="$required_unix"
;;
('darwin')
required="$required_darwin"
;;
(*)
# Generally shouldn't happen, since the OS has already been validated.
error_exit "unsupported operating system: '$os'"
;;
esac
readonly required
# Don't use quotes to get word splitting.
for cmd in $required
do
log "checking $cmd"
if ! is_command "$cmd"
then
log "the full list of required software: [$required]"
error_exit "$cmd is required to install AdGuard Home via this script"
fi
done
}
# Function check_out_dir requires the output directory to be set and exist.
check_out_dir() {
if [ "$out_dir" = '' ]
then
error_exit 'output directory should be presented'
fi
if ! [ -d "$out_dir" ]
then
log "$out_dir directory will be created"
fi
}
# Function parse_opts parses the options list and validates it's combinations.
parse_opts() {
while getopts "C:c:hO:o:rRuUvV" opt "$@"
do
case "$opt"
in
(C)
cpu="$OPTARG"
;;
(c)
channel="$OPTARG"
;;
(h)
usage
;;
(O)
os="$OPTARG"
;;
(o)
out_dir="$OPTARG"
;;
(R)
reinstall='0'
;;
(U)
uninstall='0'
;;
(r)
reinstall='1'
;;
(u)
uninstall='1'
;;
(V)
verbose='0'
;;
(v)
verbose='1'
;;
(*)
log "bad option $OPTARG"
usage
;;
esac
done
if [ "$uninstall" -eq '1' ] && [ "$reinstall" -eq '1' ]
then
error_exit 'the -r and -u options are mutually exclusive'
fi
}
# Function set_channel sets the channel if needed and validates the value.
set_channel() {
# Validate.
case "$channel"
in
('development'|'edge'|'beta'|'release')
# All is well, go on.
;;
(*)
error_exit \
"invalid channel '$channel'
supported values are 'development', 'edge', 'beta', and 'release'"
;;
esac
# Log.
log "channel: $channel"
}
# Function set_os sets the os if needed and validates the value.
set_os() {
# Set if needed.
if [ "$os" = '' ]
then
os="$( uname -s )"
case "$os"
in
('Darwin')
os='darwin'
;;
('FreeBSD')
os='freebsd'
;;
('Linux')
os='linux'
;;
('OpenBSD')
os='openbsd'
;;
(*)
error_exit "unsupported operating system: '$os'"
;;
esac
fi
# Validate.
case "$os"
in
('darwin'|'freebsd'|'linux'|'openbsd')
# All right, go on.
;;
(*)
error_exit "unsupported operating system: '$os'"
;;
esac
# Log.
log "operating system: $os"
}
# Function set_cpu sets the cpu if needed and validates the value.
set_cpu() {
# Set if needed.
if [ "$cpu" = '' ]
then
cpu="$( uname -m )"
case "$cpu"
in
('x86_64'|'x86-64'|'x64'|'amd64')
cpu='amd64'
;;
('i386'|'i486'|'i686'|'i786'|'x86')
cpu='386'
;;
('armv5l')
cpu='armv5'
;;
('armv6l')
cpu='armv6'
;;
('armv7l' | 'armv8l')
cpu='armv7'
;;
('aarch64'|'arm64')
cpu='arm64'
;;
('mips'|'mips64')
if is_little_endian
then
cpu="${cpu}le"
fi
cpu="${cpu}_softfloat"
;;
(*)
error_exit "unsupported cpu type: $cpu"
;;
esac
fi
# Validate.
case "$cpu"
in
('amd64'|'386'|'armv5'|'armv6'|'armv7'|'arm64')
# All right, go on.
;;
('mips64le_softfloat'|'mips64_softfloat'|'mipsle_softfloat'|'mips_softfloat')
# That's right too.
;;
(*)
error_exit "unsupported cpu type: $cpu"
;;
esac
# Log.
log "cpu type: $cpu"
}
# Function fix_darwin performs some configuration changes for macOS if needed.
#
# TODO(a.garipov): Remove after the final v0.107.0 release.
#
# See path_to_url
fix_darwin() {
if [ "$os" != 'darwin' ]
then
return 0
fi
# Set the package extension.
pkg_ext='zip'
# It is important to install AdGuard Home into the /Applications directory
# on macOS. Otherwise, it may grant not enough privileges to the AdGuard
# Home.
out_dir='/Applications'
}
# Function fix_freebsd performs some fixes to make it work on FreeBSD.
fix_freebsd() {
if ! [ "$os" = 'freebsd' ]
then
return 0
fi
rcd='/usr/local/etc/rc.d'
readonly rcd
if ! [ -d "$rcd" ]
then
mkdir "$rcd"
fi
}
# download_curl uses curl(1) to download a file. The first argument is the URL.
# The second argument is optional and is the output file.
download_curl() {
curl_output="${2:-}"
if [ "$curl_output" = '' ]
then
curl -L -S -s "$1"
else
curl -L -S -o "$curl_output" -s "$1"
fi
}
# download_wget uses wget(1) to download a file. The first argument is the URL.
# The second argument is optional and is the output file.
download_wget() {
wget_output="${2:--}"
wget --no-verbose -O "$wget_output" "$1"
}
# download_fetch uses fetch(1) to download a file. The first argument is the
# URL. The second argument is optional and is the output file.
download_fetch() {
fetch_output="${2:-}"
if [ "$fetch_output" = '' ]
then
fetch -o '-' "$1"
else
fetch -o "$fetch_output" "$1"
fi
}
# Function set_download_func sets the appropriate function for downloading
# files.
set_download_func() {
if is_command 'curl'
then
# Go on and use the default, download_curl.
return 0
elif is_command 'wget'
then
download_func='download_wget'
elif is_command 'fetch'
then
download_func='download_fetch'
else
error_exit "either curl or wget is required to install AdGuard Home via this script"
fi
}
# Function set_sudo_cmd sets the appropriate command to run a command under
# superuser privileges.
set_sudo_cmd() {
case "$os"
in
('openbsd')
sudo_cmd='doas'
;;
('darwin'|'freebsd'|'linux')
# Go on and use the default, sudo.
;;
(*)
error_exit "unsupported operating system: '$os'"
;;
esac
}
# Function configure sets the script's configuration.
configure() {
set_channel
set_os
set_cpu
fix_darwin
set_download_func
set_sudo_cmd
check_out_dir
pkg_name="AdGuardHome_${os}_${cpu}.${pkg_ext}"
url="path_to_url{channel}/${pkg_name}"
agh_dir="${out_dir}/AdGuardHome"
readonly pkg_name url agh_dir
log "AdGuard Home will be installed into $agh_dir"
}
# Function is_root checks for root privileges to be granted.
is_root() {
if [ "$( id -u )" -eq '0' ]
then
log 'script is executed with root privileges'
return 0
fi
if is_command "$sudo_cmd"
then
log 'note that AdGuard Home requires root privileges to install using this script'
return 1
fi
error_exit \
'root privileges are required to install AdGuard Home using this script
please, restart it with root privileges'
}
# Function rerun_with_root downloads the script, runs it with root privileges,
# and exits the current script. It passes the necessary configuration of the
# current script to the child script.
#
# TODO(e.burkov): Try to avoid restarting.
rerun_with_root() {
script_url=\
'path_to_url
readonly script_url
r='-R'
if [ "$reinstall" -eq '1' ]
then
r='-r'
fi
u='-U'
if [ "$uninstall" -eq '1' ]
then
u='-u'
fi
v='-V'
if [ "$verbose" -eq '1' ]
then
v='-v'
fi
readonly r u v
log 'restarting with root privileges'
# Group curl/wget together with an echo, so that if the former fails before
# producing any output, the latter prints an exit command for the following
# shell to execute to prevent it from getting an empty input and exiting
# with a zero code in that case.
{ "$download_func" "$script_url" || echo 'exit 1'; }\
| $sudo_cmd sh -s -- -c "$channel" -C "$cpu" -O "$os" -o "$out_dir" "$r" "$u" "$v"
# Exit the script. Since if the code of the previous pipeline is non-zero,
# the execution won't reach this point thanks to set -e, exit with zero.
exit 0
}
# Function download downloads the file from the URL and saves it to the
# specified filepath.
download() {
log "downloading package from $url -> $pkg_name"
if ! "$download_func" "$url" "$pkg_name"
then
error_exit "cannot download the package from $url into $pkg_name"
fi
log "successfully downloaded $pkg_name"
}
# Function unpack unpacks the passed archive depending on it's extension.
unpack() {
log "unpacking package from $pkg_name into $out_dir"
if ! mkdir -p "$out_dir"
then
error_exit "cannot create directory $out_dir"
fi
case "$pkg_ext"
in
('zip')
unzip "$pkg_name" -d "$out_dir"
;;
('tar.gz')
tar -C "$out_dir" -f "$pkg_name" -x -z
;;
(*)
error_exit "unexpected package extension: '$pkg_ext'"
;;
esac
log "successfully unpacked, contents: $( echo; ls -l -A "$agh_dir" )"
rm "$pkg_name"
}
# Function handle_existing detects the existing AGH installation and takes care
# of removing it if needed.
handle_existing() {
if ! [ -d "$agh_dir" ]
then
log 'no need to uninstall'
if [ "$uninstall" -eq '1' ]
then
exit 0
fi
return 0
fi
if [ "$( ls -1 -A "$agh_dir" )" != '' ]
then
log 'the existing AdGuard Home installation is detected'
if [ "$reinstall" -ne '1' ] && [ "$uninstall" -ne '1' ]
then
error_exit \
"to reinstall/uninstall the AdGuard Home using this script specify one of the '-r' or '-u' flags"
fi
# TODO(e.burkov): Remove the stop once v0.107.1 released.
if ( cd "$agh_dir" && ! ./AdGuardHome -s stop || ! ./AdGuardHome -s uninstall )
then
# It doesn't terminate the script since it is possible
# that AGH just not installed as service but appearing
# in the directory.
log "cannot uninstall AdGuard Home from $agh_dir"
fi
rm -r "$agh_dir"
log 'AdGuard Home was successfully uninstalled'
fi
if [ "$uninstall" -eq '1' ]
then
exit 0
fi
}
# Function install_service tries to install AGH as service.
install_service() {
# Installing the service as root is required at least on FreeBSD.
use_sudo='0'
if [ "$os" = 'freebsd' ]
then
use_sudo='1'
fi
if ( cd "$agh_dir" && maybe_sudo ./AdGuardHome -s install )
then
return 0
fi
log "installation failed, removing $agh_dir"
rm -r "$agh_dir"
# Some devices detected to have armv7 CPU face the compatibility
# issues with actual armv7 builds. We should try to install the
# armv5 binary instead.
#
# See path_to_url
if [ "$cpu" = 'armv7' ]
then
cpu='armv5'
reinstall='1'
log "trying to use $cpu cpu"
rerun_with_root
fi
error_exit 'cannot install AdGuardHome as a service'
}
# Entrypoint
# Set default values of configuration variables.
channel='release'
reinstall='0'
uninstall='0'
verbose='0'
cpu=''
os=''
out_dir='/opt'
pkg_ext='tar.gz'
download_func='download_curl'
sudo_cmd='sudo'
parse_opts "$@"
echo 'starting AdGuard Home installation script'
configure
check_required
if ! is_root
then
rerun_with_root
fi
# Needs rights.
fix_freebsd
handle_existing
download
unpack
install_service
echo "\
AdGuard Home is now installed and running
you can control the service status with the following commands:
$sudo_cmd ${agh_dir}/AdGuardHome -s start|stop|restart|status|install|uninstall"
``` | /content/code_sandbox/scripts/install.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,895 |
```go
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"path/filepath"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/httphdr"
"github.com/AdguardTeam/golibs/mapsutil"
)
// upload base translation.
func (c *twoskyClient) upload() (err error) {
defer func() { err = errors.Annotate(err, "upload: %w") }()
uploadURI := c.uri.JoinPath("upload")
basePath := filepath.Join(localesDir, defaultBaseFile)
formData := map[string]string{
"format": "json",
"language": string(c.baseLang),
"filename": defaultBaseFile,
"project": c.projectID,
}
buf, cType, err := prepareMultipartMsg(formData, basePath)
if err != nil {
return fmt.Errorf("preparing multipart msg: %w", err)
}
err = send(uploadURI.String(), cType, buf)
if err != nil {
return fmt.Errorf("sending multipart msg: %w", err)
}
return nil
}
// prepareMultipartMsg prepares translation data for upload.
func prepareMultipartMsg(
formData map[string]string,
basePath string,
) (buf *bytes.Buffer, cType string, err error) {
buf = &bytes.Buffer{}
w := multipart.NewWriter(buf)
var fw io.Writer
err = mapsutil.SortedRangeError(formData, w.WriteField)
if err != nil {
return nil, "", fmt.Errorf("writing field: %w", err)
}
file, err := os.Open(basePath)
if err != nil {
return nil, "", fmt.Errorf("opening file: %w", err)
}
defer func() {
err = errors.WithDeferred(err, file.Close())
}()
h := make(textproto.MIMEHeader)
h.Set(httphdr.ContentType, aghhttp.HdrValApplicationJSON)
d := fmt.Sprintf("form-data; name=%q; filename=%q", "file", defaultBaseFile)
h.Set(httphdr.ContentDisposition, d)
fw, err = w.CreatePart(h)
if err != nil {
return nil, "", fmt.Errorf("creating part: %w", err)
}
_, err = io.Copy(fw, file)
if err != nil {
return nil, "", fmt.Errorf("copying: %w", err)
}
err = w.Close()
if err != nil {
return nil, "", fmt.Errorf("closing writer: %w", err)
}
return buf, w.FormDataContentType(), nil
}
// send POST request to uriStr.
func send(uriStr, cType string, buf *bytes.Buffer) (err error) {
client := http.Client{
Timeout: uploadTimeout,
}
req, err := http.NewRequest(http.MethodPost, uriStr, buf)
if err != nil {
return fmt.Errorf("bad request: %w", err)
}
req.Header.Set(httphdr.ContentType, cType)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("client post form: %w", err)
}
defer func() {
err = errors.WithDeferred(err, resp.Body.Close())
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status code is not ok: %q", http.StatusText(resp.StatusCode))
}
return nil
}
``` | /content/code_sandbox/scripts/translations/upload.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 760 |
```go
package main
import (
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/golibs/log"
)
// download and save all translations.
func (c *twoskyClient) download() (err error) {
var numWorker int
flagSet := flag.NewFlagSet("download", flag.ExitOnError)
flagSet.Usage = func() {
usage("download command error")
}
flagSet.IntVar(&numWorker, "n", 1, "number of concurrent downloads")
err = flagSet.Parse(os.Args[2:])
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
if numWorker < 1 {
usage("count must be positive")
}
downloadURI := c.uri.JoinPath("download")
client := &http.Client{
Timeout: 10 * time.Second,
}
wg := &sync.WaitGroup{}
failed := &sync.Map{}
uriCh := make(chan *url.URL, len(c.langs))
for range numWorker {
wg.Add(1)
go downloadWorker(wg, failed, client, uriCh)
}
for _, lang := range c.langs {
uri := translationURL(downloadURI, defaultBaseFile, c.projectID, lang)
uriCh <- uri
}
close(uriCh)
wg.Wait()
printFailedLocales(failed)
return nil
}
// printFailedLocales prints sorted list of failed downloads, if any.
func printFailedLocales(failed *sync.Map) {
keys := []string{}
failed.Range(func(k, _ any) bool {
s, ok := k.(string)
if !ok {
panic("unexpected type")
}
keys = append(keys, s)
return true
})
if len(keys) == 0 {
return
}
slices.Sort(keys)
log.Info("failed locales: %s", strings.Join(keys, " "))
}
// downloadWorker downloads translations by received urls and saves them.
// Where failed is a map for storing failed downloads.
func downloadWorker(
wg *sync.WaitGroup,
failed *sync.Map,
client *http.Client,
uriCh <-chan *url.URL,
) {
defer wg.Done()
for uri := range uriCh {
q := uri.Query()
code := q.Get("language")
err := saveToFile(client, uri, code)
if err != nil {
log.Error("download: worker: %s", err)
failed.Store(code, struct{}{})
}
}
}
// saveToFile downloads translation by url and saves it to a file, or returns
// error.
func saveToFile(client *http.Client, uri *url.URL, code string) (err error) {
data, err := getTranslation(client, uri.String())
if err != nil {
log.Info("%s", data)
return fmt.Errorf("getting translation: %s", err)
}
name := filepath.Join(localesDir, code+".json")
err = os.WriteFile(name, data, 0o664)
if err != nil {
return fmt.Errorf("writing file: %s", err)
}
fmt.Println(name)
return nil
}
// getTranslation returns received translation data and error. If err is not
// nil, data may contain a response from server for inspection.
func getTranslation(client *http.Client, url string) (data []byte, err error) {
resp, err := client.Get(url)
if err != nil {
return nil, fmt.Errorf("requesting: %w", err)
}
defer log.OnCloserError(resp.Body, log.ERROR)
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("url: %q; status code: %s", url, http.StatusText(resp.StatusCode))
// Go on and download the body for inspection.
}
limitReader := ioutil.LimitReader(resp.Body, readLimit)
data, readErr := io.ReadAll(limitReader)
return data, errors.WithDeferred(err, readErr)
}
// translationURL returns a new url.URL with provided query parameters.
func translationURL(oldURL *url.URL, baseFile, projectID string, lang langCode) (uri *url.URL) {
uri = &url.URL{}
*uri = *oldURL
q := uri.Query()
q.Set("format", "json")
q.Set("filename", baseFile)
q.Set("project", projectID)
q.Set("language", string(lang))
uri.RawQuery = q.Encode()
return uri
}
``` | /content/code_sandbox/scripts/translations/download.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,003 |
```go
// translations downloads translations, uploads translations, prints summary
// for translations, prints unused strings.
package main
import (
"bufio"
"bytes"
"cmp"
"encoding/json"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"golang.org/x/exp/maps"
)
const (
twoskyConfFile = "./.twosky.json"
localesDir = "./client/src/__locales"
defaultBaseFile = "en.json"
defaultProjectID = "home"
srcDir = "./client/src"
twoskyURI = "path_to_url"
readLimit = 1 * 1024 * 1024
uploadTimeout = 20 * time.Second
)
// blockerLangCodes is the codes of languages which need to be fully translated.
var blockerLangCodes = []langCode{
"de",
"en",
"es",
"fr",
"it",
"ja",
"ko",
"pt-br",
"pt-pt",
"ru",
"zh-cn",
"zh-tw",
}
// langCode is a language code.
type langCode string
// languages is a map, where key is language code and value is display name.
type languages map[langCode]string
// textlabel is a text label of localization.
type textLabel string
// locales is a map, where key is text label and value is translation.
type locales map[textLabel]string
func main() {
if len(os.Args) == 1 {
usage("need a command")
}
if os.Args[1] == "help" {
usage("")
}
conf, err := readTwoskyConfig()
check(err)
var cli *twoskyClient
switch os.Args[1] {
case "summary":
err = summary(conf.Languages)
case "download":
cli, err = conf.toClient()
check(err)
err = cli.download()
case "unused":
err = unused(conf.LocalizableFiles[0])
case "upload":
cli, err = conf.toClient()
check(err)
err = cli.upload()
case "auto-add":
err = autoAdd(conf.LocalizableFiles[0])
default:
usage("unknown command")
}
check(err)
}
// check is a simple error-checking helper for scripts.
func check(err error) {
if err != nil {
panic(err)
}
}
// usage prints usage. If addStr is not empty print addStr and exit with code
// 1, otherwise exit with code 0.
func usage(addStr string) {
const usageStr = `Usage: go run main.go <command> [<args>]
Commands:
help
Print usage.
summary
Print summary.
download [-n <count>]
Download translations. count is a number of concurrent downloads.
unused
Print unused strings.
upload
Upload translations.
auto-add
Add locales with additions to the git and restore locales with
deletions.`
if addStr != "" {
fmt.Printf("%s\n%s\n", addStr, usageStr)
os.Exit(1)
}
fmt.Println(usageStr)
os.Exit(0)
}
// twoskyConfig is the configuration structure for localization.
type twoskyConfig struct {
Languages languages `json:"languages"`
ProjectID string `json:"project_id"`
BaseLangcode langCode `json:"base_locale"`
LocalizableFiles []string `json:"localizable_files"`
}
// readTwoskyConfig returns twosky configuration.
func readTwoskyConfig() (t *twoskyConfig, err error) {
defer func() { err = errors.Annotate(err, "parsing twosky config: %w") }()
b, err := os.ReadFile(twoskyConfFile)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
var tsc []twoskyConfig
err = json.Unmarshal(b, &tsc)
if err != nil {
err = fmt.Errorf("unmarshalling %q: %w", twoskyConfFile, err)
return nil, err
}
if len(tsc) == 0 {
err = fmt.Errorf("%q is empty", twoskyConfFile)
return nil, err
}
conf := tsc[0]
for _, lang := range conf.Languages {
if lang == "" {
return nil, errors.Error("language is empty")
}
}
if len(conf.LocalizableFiles) == 0 {
return nil, errors.Error("no localizable files specified")
}
return &conf, nil
}
// twoskyClient is the twosky client with methods for download and upload
// translations.
type twoskyClient struct {
// uri is the base URL.
uri *url.URL
// projectID is the name of the project.
projectID string
// baseLang is the base language code.
baseLang langCode
// langs is the list of codes of languages to download.
langs []langCode
}
// toClient reads values from environment variables or defaults, validates
// them, and returns the twosky client.
func (t *twoskyConfig) toClient() (cli *twoskyClient, err error) {
defer func() { err = errors.Annotate(err, "filling config: %w") }()
uriStr := cmp.Or(os.Getenv("TWOSKY_URI"), twoskyURI)
uri, err := url.Parse(uriStr)
if err != nil {
return nil, err
}
projectID := cmp.Or(os.Getenv("TWOSKY_PROJECT_ID"), defaultProjectID)
baseLang := t.BaseLangcode
uLangStr := os.Getenv("UPLOAD_LANGUAGE")
if uLangStr != "" {
baseLang = langCode(uLangStr)
}
langs := maps.Keys(t.Languages)
dlLangStr := os.Getenv("DOWNLOAD_LANGUAGES")
if dlLangStr == "blocker" {
langs = blockerLangCodes
} else if dlLangStr != "" {
var dlLangs []langCode
dlLangs, err = validateLanguageStr(dlLangStr, t.Languages)
if err != nil {
return nil, err
}
langs = dlLangs
}
return &twoskyClient{
uri: uri,
projectID: projectID,
baseLang: baseLang,
langs: langs,
}, nil
}
// validateLanguageStr validates languages codes that contain in the str and
// returns them or error.
func validateLanguageStr(str string, all languages) (langs []langCode, err error) {
codes := strings.Fields(str)
langs = make([]langCode, 0, len(codes))
for _, k := range codes {
lc := langCode(k)
_, ok := all[lc]
if !ok {
return nil, fmt.Errorf("validating languages: unexpected language code %q", k)
}
langs = append(langs, lc)
}
return langs, nil
}
// readLocales reads file with name fn and returns a map, where key is text
// label and value is localization.
func readLocales(fn string) (loc locales, err error) {
b, err := os.ReadFile(fn)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
loc = make(locales)
err = json.Unmarshal(b, &loc)
if err != nil {
err = fmt.Errorf("unmarshalling %q: %w", fn, err)
return nil, err
}
return loc, nil
}
// summary prints summary for translations.
func summary(langs languages) (err error) {
basePath := filepath.Join(localesDir, defaultBaseFile)
baseLoc, err := readLocales(basePath)
if err != nil {
return fmt.Errorf("summary: %w", err)
}
size := float64(len(baseLoc))
keys := maps.Keys(langs)
slices.Sort(keys)
for _, lang := range keys {
name := filepath.Join(localesDir, string(lang)+".json")
if name == basePath {
continue
}
var loc locales
loc, err = readLocales(name)
if err != nil {
return fmt.Errorf("summary: reading locales: %w", err)
}
f := float64(len(loc)) * 100 / size
blocker := ""
// N is small enough to not raise performance questions.
ok := slices.Contains(blockerLangCodes, lang)
if ok {
blocker = " (blocker)"
}
fmt.Printf("%s\t %6.2f %%%s\n", lang, f, blocker)
}
return nil
}
// unused prints unused text labels.
func unused(basePath string) (err error) {
defer func() { err = errors.Annotate(err, "unused: %w") }()
baseLoc, err := readLocales(basePath)
if err != nil {
return err
}
locDir := filepath.Clean(localesDir)
js, err := findJS(locDir)
if err != nil {
return err
}
return findUnused(js, baseLoc)
}
// findJS returns list of JavaScript and JSON files or error.
func findJS(locDir string) (fileNames []string, err error) {
walkFn := func(name string, _ os.FileInfo, err error) error {
if err != nil {
log.Info("warning: accessing a path %q: %s", name, err)
return nil
}
if strings.HasPrefix(name, locDir) {
return nil
}
ext := filepath.Ext(name)
if ext == ".js" || ext == ".json" {
fileNames = append(fileNames, name)
}
return nil
}
err = filepath.Walk(srcDir, walkFn)
if err != nil {
return nil, fmt.Errorf("filepath walking %q: %w", srcDir, err)
}
return fileNames, nil
}
// findUnused prints unused text labels from fileNames.
func findUnused(fileNames []string, loc locales) (err error) {
knownUsed := []textLabel{
"blocking_mode_refused",
"blocking_mode_nxdomain",
"blocking_mode_custom_ip",
}
for _, v := range knownUsed {
delete(loc, v)
}
for _, fn := range fileNames {
var buf []byte
buf, err = os.ReadFile(fn)
if err != nil {
return fmt.Errorf("finding unused: %w", err)
}
for k := range loc {
if bytes.Contains(buf, []byte(k)) {
delete(loc, k)
}
}
}
keys := maps.Keys(loc)
slices.Sort(keys)
for _, v := range keys {
fmt.Println(v)
}
return nil
}
// autoAdd adds locales with additions to the git and restores locales with
// deletions.
func autoAdd(basePath string) (err error) {
defer func() { err = errors.Annotate(err, "auto add: %w") }()
adds, dels, err := changedLocales()
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
if slices.Contains(dels, basePath) {
return errors.Error("base locale contains deletions")
}
err = handleAdds(adds)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil
}
err = handleDels(dels)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil
}
return nil
}
// handleAdds adds locales with additions to the git.
func handleAdds(locales []string) (err error) {
if len(locales) == 0 {
return nil
}
args := append([]string{"add"}, locales...)
code, out, err := aghos.RunCommand("git", args...)
if err != nil || code != 0 {
return fmt.Errorf("git add exited with code %d output %q: %w", code, out, err)
}
return nil
}
// handleDels restores locales with deletions.
func handleDels(locales []string) (err error) {
if len(locales) == 0 {
return nil
}
args := append([]string{"restore"}, locales...)
code, out, err := aghos.RunCommand("git", args...)
if err != nil || code != 0 {
return fmt.Errorf("git restore exited with code %d output %q: %w", code, out, err)
}
return nil
}
// changedLocales returns cleaned paths of locales with changes or error. adds
// is the list of locales with only additions. dels is the list of locales
// with only deletions.
func changedLocales() (adds, dels []string, err error) {
defer func() { err = errors.Annotate(err, "getting changes: %w") }()
cmd := exec.Command("git", "diff", "--numstat", localesDir)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, fmt.Errorf("piping: %w", err)
}
err = cmd.Start()
if err != nil {
return nil, nil, fmt.Errorf("starting: %w", err)
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 3 {
return nil, nil, fmt.Errorf("invalid input: %q", line)
}
path := fields[2]
if fields[0] == "0" {
dels = append(dels, path)
} else if fields[1] == "0" {
adds = append(adds, path)
}
}
err = scanner.Err()
if err != nil {
return nil, nil, fmt.Errorf("scanning: %w", err)
}
err = cmd.Wait()
if err != nil {
return nil, nil, fmt.Errorf("waiting: %w", err)
}
return adds, dels, nil
}
``` | /content/code_sandbox/scripts/translations/main.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,163 |
```javascript
const fs = require('fs');
const readline = require('readline');
const dnsPacket = require('dns-packet')
const processLineByLine = async (source, callback) => {
const fileStream = fs.createReadStream(source);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
await callback(line);
}
}
const anonDomain = (domain) => {
// Replace all question domain letters with a
return domain.replace(/[a-z]/g, 'a');
}
const anonIP = (ip) => {
// Replace all numbers with '1'
return ip.replace(/[0-9]/g, '1');
}
const anonAnswer = (answer) => {
const answerData = Buffer.from(answer, 'base64');
const packet = dnsPacket.decode(answerData, 0);
packet.questions.forEach((q) => {
q.name = anonDomain(q.name);
});
packet.answers.forEach((q) => {
q.name = anonDomain(q.name);
if (q.type === 'A' || q.type === 'AAAA') {
q.data = anonIP(q.data);
} else if (typeof q.data === 'string') {
q.data = anonDomain(q.data);
}
});
const anonData = dnsPacket.encode(packet);
return anonData.toString('base64');
}
const anonLine = (line) => {
if (!line) {
return null;
}
try {
const logItem = JSON.parse(line);
// Replace all numbers with '1'
logItem['IP'] = logItem['IP'].replace(/[0-9]/g, '1');
// Replace all question domain letters with a
logItem['QH'] = logItem['QH'].replace(/[a-z]/g, 'a');
// Anonymize "Answer" and "OrigAnswer" fields
if (logItem['Answer']) {
logItem['Answer'] = anonAnswer(logItem['Answer']);
}
if (logItem['OrigAnswer']) {
logItem['OrigAnswer'] = anonAnswer(logItem['OrigAnswer']);
}
// If Result is set, anonymize the "Rule" field
if (logItem['Result'] && logItem['Result']['Rule']) {
logItem['Result']['Rule'] = anonDomain(logItem['Result']['Rule']);
}
return JSON.stringify(logItem);
} catch (ex) {
console.error(`Failed to parse ${line}: ${ex} ${ex.stack}`);
return null;
}
}
const anon = async (source, dest) => {
const out = fs.createWriteStream(dest, {
flags: 'w',
});
await processLineByLine(source, async (line) => {
const newLine = anonLine(line);
if (!newLine) {
return;
}
out.write(`${newLine}\n`);
});
}
const main = async () => {
console.log('Start query log anonymization');
const source = process.argv[2];
const dest = process.argv[3];
console.log(`Source: ${source}`);
console.log(`Destination: ${dest}`);
if (!fs.existsSync(source)) {
throw new Error(`${source} not found`);
}
try {
await anon(source, dest);
} catch (ex) {
console.error(ex);
}
console.log('Finished query log anonymization')
}
main();
``` | /content/code_sandbox/scripts/querylog/anonymize.js | javascript | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 746 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a significant change is made to this script.
#
# AdGuard-Project-Version: 8
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '0' ]
then
set -x
fi
# Set $EXIT_ON_ERROR to zero to see all errors.
if [ "${EXIT_ON_ERROR:-1}" -eq '0' ]
then
set +e
else
set -e
fi
set -f -u
# Source the common helpers, including not_found and run_linter.
. ./scripts/make/helper.sh
# Simple analyzers
# blocklist_imports is a simple check against unwanted packages. The following
# packages are banned:
#
# * Package errors is replaced by our own package in the
# github.com/AdguardTeam/golibs module.
#
# * Packages golang.org/x/exp/slices and golang.org/x/net/context have been
# moved into stdlib.
#
# * Package io/ioutil is soft-deprecated.
#
# * Package reflect is often an overkill, and for deep comparisons there are
# much better functions in module github.com/google/go-cmp. Which is
# already our indirect dependency and which may or may not enter the stdlib
# at some point.
#
# See path_to_url
#
# * Package sort is replaced by package slices.
#
# * Package unsafe is unsafe.
#
# Currently, the only standard exception are files generated from protobuf
# schemas, which use package reflect. If your project needs more exceptions,
# add and document them.
#
# TODO(a.garipov): Add golibs/log.
#
# TODO(a.garipov): Add deprecated package golang.org/x/exp/maps once all
# projects switch to Go 1.23.
blocklist_imports() {
git grep\
-e '[[:space:]]"errors"$'\
-e '[[:space:]]"golang.org/x/exp/slices"$'\
-e '[[:space:]]"golang.org/x/net/context"$'\
-e '[[:space:]]"io/ioutil"$'\
-e '[[:space:]]"log"$'\
-e '[[:space:]]"reflect"$'\
-e '[[:space:]]"sort"$'\
-e '[[:space:]]"unsafe"$'\
-n\
-- '*.go'\
':!*.pb.go'\
| sed -e 's/^\([^[:space:]]\+\)\(.*\)$/\1 blocked import:\2/'\
|| exit 0
}
# method_const is a simple check against the usage of some raw strings and
# numbers where one should use named constants.
method_const() {
git grep -F\
-e '"DELETE"'\
-e '"GET"'\
-e '"PATCH"'\
-e '"POST"'\
-e '"PUT"'\
-n\
-- '*.go'\
| sed -e 's/^\([^[:space:]]\+\)\(.*\)$/\1 http method literal:\2/'\
|| exit 0
}
# underscores is a simple check against Go filenames with underscores. Add new
# build tags and OS as you go. The main goal of this check is to discourage the
# use of filenames like client_manager.go.
underscores() {
underscore_files="$(
git ls-files '*_*.go'\
| grep -F\
-e '_bsd.go'\
-e '_darwin.go'\
-e '_freebsd.go'\
-e '_generate.go'\
-e '_linux.go'\
-e '_next.go'\
-e '_openbsd.go'\
-e '_others.go'\
-e '_test.go'\
-e '_unix.go'\
-e '_windows.go'\
-v\
| sed -e 's/./\t\0/'
)"
readonly underscore_files
if [ "$underscore_files" != '' ]
then
echo 'found file names with underscores:'
echo "$underscore_files"
fi
}
# TODO(a.garipov): Add an analyzer to look for `fallthrough`, `goto`, and `new`?
# Checks
run_linter -e blocklist_imports
run_linter -e method_const
run_linter -e underscores
run_linter -e gofumpt --extra -e -l .
# TODO(a.garipov): golint is deprecated, find a suitable replacement.
run_linter "${GO:-go}" vet ./...
run_linter govulncheck ./...
run_linter gocyclo --over 10 .
# TODO(a.garipov): Enable 10 for all.
run_linter gocognit --over='20'\
./internal/querylog/\
;
run_linter gocognit --over='19'\
./internal/home/\
;
run_linter gocognit --over='18'\
./internal/aghtls/\
;
run_linter gocognit --over='15'\
./internal/aghos/\
./internal/filtering/\
;
run_linter gocognit --over='14'\
./internal/dhcpd\
;
run_linter gocognit --over='13'\
./internal/aghnet/\
;
run_linter gocognit --over='12'\
./internal/filtering/rewrite/\
;
run_linter gocognit --over='11'\
./internal/updater/\
;
run_linter gocognit --over='10'\
./internal/aghalg/\
./internal/aghhttp/\
./internal/aghrenameio/\
./internal/aghtest/\
./internal/arpdb/\
./internal/client/\
./internal/configmigrate/\
./internal/dhcpsvc\
./internal/dnsforward/\
./internal/filtering/hashprefix/\
./internal/filtering/rulelist/\
./internal/filtering/safesearch/\
./internal/ipset\
./internal/next/\
./internal/rdns/\
./internal/schedule/\
./internal/stats/\
./internal/tools/\
./internal/version/\
./internal/whois/\
./scripts/\
;
run_linter ineffassign ./...
run_linter unparam ./...
git ls-files -- 'Makefile' '*.conf' '*.go' '*.mod' '*.sh' '*.yaml' '*.yml'\
| xargs misspell --error\
| sed -e 's/^/misspell: /'
run_linter nilness ./...
# TODO(a.garipov): Enable for all.
run_linter fieldalignment \
./internal/aghalg/\
./internal/aghhttp/\
./internal/aghos/\
./internal/aghrenameio/\
./internal/aghtest/\
./internal/aghtls/\
./internal/arpdb/\
./internal/client/\
./internal/configmigrate/\
./internal/dhcpsvc/\
./internal/filtering/hashprefix/\
./internal/filtering/rewrite/\
./internal/filtering/rulelist/\
./internal/filtering/safesearch/\
./internal/ipset/\
./internal/next/...\
./internal/querylog/\
./internal/rdns/\
./internal/schedule/\
./internal/stats/\
./internal/updater/\
./internal/version/\
./internal/whois/\
;
run_linter -e shadow --strict ./...
# TODO(a.garipov): Enable for all.
run_linter gosec --quiet\
./internal/aghalg/\
./internal/aghchan/\
./internal/aghhttp/\
./internal/aghnet/\
./internal/aghos/\
./internal/aghrenameio/\
./internal/aghtest/\
./internal/arpdb/\
./internal/client/\
./internal/configmigrate/\
./internal/dhcpd/\
./internal/dhcpsvc/\
./internal/dnsforward/\
./internal/filtering/hashprefix/\
./internal/filtering/rewrite/\
./internal/filtering/rulelist/\
./internal/filtering/safesearch/\
./internal/ipset/\
./internal/next/\
./internal/rdns/\
./internal/schedule/\
./internal/stats/\
./internal/tools/\
./internal/version/\
./internal/whois/\
;
run_linter errcheck ./...
staticcheck_matrix='
darwin: GOOS=darwin
freebsd: GOOS=freebsd
linux: GOOS=linux
openbsd: GOOS=openbsd
windows: GOOS=windows
'
readonly staticcheck_matrix
echo "$staticcheck_matrix" | run_linter staticcheck --matrix ./...
``` | /content/code_sandbox/scripts/make/go-lint.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,012 |
```shell
#!/bin/sh
# AdGuard Home Version Generation Script
#
# This script generates versions based on the current git tree state. The valid
# output formats are:
#
# * For release versions, "v0.123.4". This version should be the one in the
# current tag, and the script merely checks, that the current commit is
# properly tagged.
#
# * For prerelease beta versions, "v0.123.4-b.5". This version should be the
# one in the current tag, and the script merely checks, that the current
# commit is properly tagged.
#
# * For prerelease alpha versions (aka snapshots), "v0.123.4-a.6+a1b2c3d4".
#
# BUG(a.garipov): The script currently can't differentiate between beta tags and
# release tags if they are on the same commit, so the beta tag **must** be
# pushed and built **before** the release tag is pushed.
#
# TODO(a.garipov): The script currently doesn't handle release branches, so it
# must be modified once we have those.
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '0' ]
then
set -x
fi
set -e -f -u
# bump_minor is an awk program that reads a minor release version, increments
# the minor part of it, and prints the next version.
#
# shellcheck disable=SC2016
bump_minor='/^v[0-9]+\.[0-9]+\.0$/ {
print($1 "." $2 + 1 ".0");
next;
}
{
printf("invalid minor release version: \"%s\"\n", $0);
exit 1;
}'
readonly bump_minor
# get_last_minor_zero returns the last new minor release.
get_last_minor_zero() {
# List all tags. Then, select those that fit the pattern of a new minor
# release: a semver version with the patch part set to zero.
#
# Then, sort them first by the first field ("1"), starting with the
# second character to skip the "v" prefix (".2"), and only spanning the
# first field (",1"). The sort is numeric and reverse ("nr").
#
# Then, sort them by the second field ("2"), and only spanning the
# second field (",2"). The sort is also numeric and reverse ("nr").
#
# Finally, get the top (that is, most recent) version.
git tag\
| grep -e 'v[0-9]\+\.[0-9]\+\.0$'\
| sort -k 1.2,1nr -k 2,2nr -t '.'\
| head -n 1
}
channel="${CHANNEL:?please set CHANNEL}"
readonly channel
case "$channel"
in
('development')
# commit_number is the number of current commit within the branch.
commit_number="$( git rev-list --count master..HEAD )"
readonly commit_number
# The development builds are described with a combination of unset semantic
# version, the commit's number within the branch, and the commit hash, e.g.:
#
# v0.0.0-dev.5-a1b2c3d4
#
version="v0.0.0-dev.${commit_number}+$( git rev-parse --short HEAD )"
;;
('edge')
# last_minor_zero is the last new minor release.
last_minor_zero="$( get_last_minor_zero )"
readonly last_minor_zero
# num_commits_since_minor is the number of commits since the last new
# minor release. If the current commit is the new minor release,
# num_commits_since_minor is zero.
num_commits_since_minor="$( git rev-list --count "${last_minor_zero}..HEAD" )"
readonly num_commits_since_minor
# next_minor is the next minor release version.
next_minor="$( echo "$last_minor_zero" | awk -F '.' "$bump_minor" )"
readonly next_minor
# Make this commit a prerelease version for the next minor release. For
# example, if the last minor release was v0.123.0, and the current
# commit is the fifth since then, the version will look something like:
#
# v0.124.0-a.5+a1b2c3d4
#
version="${next_minor}-a.${num_commits_since_minor}+$( git rev-parse --short HEAD )"
;;
('beta'|'release')
# current_desc is the description of the current git commit. If the
# current commit is tagged, git describe will show the tag.
current_desc="$( git describe )"
readonly current_desc
# last_tag is the most recent git tag.
last_tag="$( git describe --abbrev=0 )"
readonly last_tag
# Require an actual tag for the beta and final releases.
if [ "$current_desc" != "$last_tag" ]
then
echo 'need a tag' 1>&2
exit 1
fi
version="$last_tag"
;;
('candidate')
# This pseudo-channel is used to set a proper versions into release
# candidate builds.
# last_tag is expected to be the latest release tag.
last_tag="$( git describe --abbrev=0 )"
readonly last_tag
# current_branch is the name of the branch currently checked out.
current_branch="$( git rev-parse --abbrev-ref HEAD )"
readonly current_branch
# The branch should be named like:
#
# rc-v12.34.56
#
if ! echo "$current_branch" | grep -E -e '^rc-v[0-9]+\.[0-9]+\.[0-9]+$' -q
then
echo "invalid release candidate branch name '$current_branch'" 1>&2
exit 1
fi
version="${current_branch#rc-}-rc.$( git rev-list --count "$last_tag"..HEAD )"
;;
(*)
echo "invalid channel '$channel', supported values are\
'development', 'edge', 'beta', 'release' and 'candidate'" 1>&2
exit 1
;;
esac
# Finally, make sure that we don't output invalid versions.
if ! echo "$version" | grep -E -e '^v[0-9]+\.[0-9]+\.[0-9]+(-(a|b|dev|rc)\.[0-9]+)?(\+[[:xdigit:]]+)?$' -q
then
echo "generated an invalid version '$version'" 1>&2
exit 1
fi
echo "$version"
``` | /content/code_sandbox/scripts/make/version.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,468 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '0' ]
then
set -x
fi
set -e -f -u
dist_dir="${DIST_DIR:?please set DIST_DIR}"
sudo_cmd="${SUDO:-}"
readonly dist_dir sudo_cmd
$sudo_cmd rm -f\
./AdGuardHome\
./AdGuardHome.exe\
./coverage.txt\
;
$sudo_cmd rm -f -r\
./bin/\
./build/static/\
./client/node_modules/\
./data/\
"./${dist_dir}/"\
;
``` | /content/code_sandbox/scripts/make/clean.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 133 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a significant change is made to this script.
#
# AdGuard-Project-Version: 1
verbose="${VERBOSE:-0}"
readonly verbose
# Verbosity levels:
# 0 = Don't print anything except for errors.
# 1 = Print commands, but not nested commands.
# 2 = Print everything.
if [ "$verbose" -gt '1' ]
then
set -x
v_flags='-v=1'
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
v_flags='-v=1'
x_flags='-x=0'
else
set +x
v_flags='-v=0'
x_flags='-x=0'
fi
readonly v_flags x_flags
set -e -f -u
if [ "${RACE:-1}" -eq '0' ]
then
race_flags='--race=0'
else
race_flags='--race=1'
fi
readonly race_flags
go="${GO:-go}"
readonly go
count_flags='--count=1'
cover_flags='--coverprofile=./coverage.txt'
shuffle_flags='--shuffle=on'
timeout_flags="${TIMEOUT_FLAGS:---timeout=90s}"
readonly count_flags cover_flags shuffle_flags timeout_flags
"$go" test\
"$count_flags"\
"$cover_flags"\
"$race_flags"\
"$shuffle_flags"\
"$timeout_flags"\
"$v_flags"\
"$x_flags"\
./...
``` | /content/code_sandbox/scripts/make/go-test.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 337 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a significant change is made to this script.
#
# AdGuard-Project-Version: 4
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '1' ]
then
set -x
v_flags='-v=1'
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
v_flags='-v=1'
x_flags='-x=0'
else
set +x
v_flags='-v=0'
x_flags='-x=0'
fi
readonly v_flags x_flags
set -e -f -u
go="${GO:-go}"
readonly go
# Remove only the actual binaries in the bin/ directory, as developers may add
# their own scripts there. Most commonly, a script named go for tools that
# call the go binary and need a particular version.
rm -f\
bin/errcheck\
bin/fieldalignment\
bin/gocognit\
bin/gocyclo\
bin/gofumpt\
bin/gosec\
bin/govulncheck\
bin/ineffassign\
bin/misspell\
bin/nilness\
bin/shadow\
bin/staticcheck\
bin/unparam\
;
# Reset GOARCH and GOOS to make sure we install the tools for the native
# architecture even when we're cross-compiling the main binary, and also to
# prevent the "cannot install cross-compiled binaries when GOBIN is set" error.
env\
GOARCH=""\
GOBIN="${PWD}/bin"\
GOOS=""\
GOWORK='off'\
"$go" install\
--modfile=./internal/tools/go.mod\
"$v_flags"\
"$x_flags"\
github.com/fzipp/gocyclo/cmd/gocyclo\
github.com/golangci/misspell/cmd/misspell\
github.com/gordonklaus/ineffassign\
github.com/kisielk/errcheck\
github.com/securego/gosec/v2/cmd/gosec\
github.com/uudashr/gocognit/cmd/gocognit\
golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment\
golang.org/x/tools/go/analysis/passes/nilness/cmd/nilness\
golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow\
golang.org/x/vuln/cmd/govulncheck\
honnef.co/go/tools/cmd/staticcheck\
mvdan.cc/gofumpt\
mvdan.cc/unparam\
;
``` | /content/code_sandbox/scripts/make/go-tools.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 581 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
readonly verbose
# Verbosity levels:
# 0 = Don't print anything except for errors.
# 1 = Print commands, but not nested commands.
# 2 = Print everything.
if [ "$verbose" -gt '1' ]
then
set -x
v_flags='-v=1'
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
v_flags='-v=1'
x_flags='-x=0'
else
set +x
v_flags='-v=0'
x_flags='-x=0'
fi
readonly v_flags x_flags
set -e -f -u
if [ "${RACE:-1}" -eq '0' ]
then
race_flags='--race=0'
else
race_flags='--race=1'
fi
readonly race_flags
go="${GO:-go}"
count_flags='--count=1'
shuffle_flags='--shuffle=on'
timeout_flags="${TIMEOUT_FLAGS:---timeout=30s}"
fuzztime_flags="${FUZZTIME_FLAGS:---fuzztime=20s}"
readonly go count_flags shuffle_flags timeout_flags fuzztime_flags
# TODO(a.garipov): File an issue about using --fuzz with multiple packages.
"$go" test\
"$count_flags"\
"$shuffle_flags"\
"$race_flags"\
"$timeout_flags"\
"$x_flags"\
"$v_flags"\
"$fuzztime_flags"\
--fuzz='.'\
--run='^$'\
./internal/filtering/rulelist/\
;
``` | /content/code_sandbox/scripts/make/go-fuzz.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 347 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a remarkable change is made to this script.
#
# AdGuard-Project-Version: 2
verbose="${VERBOSE:-0}"
readonly verbose
# Don't use -f, because we use globs in this script.
set -e -u
if [ "$verbose" -gt '0' ]
then
set -x
fi
# NOTE: Adjust for your project.
#
# TODO(e.burkov): Add build-docker.sh, build-release.sh and install.sh.
shellcheck -e 'SC2250' -f 'gcc' -o 'all' -x --\
./scripts/hooks/*\
./scripts/snap/*\
./scripts/make/clean.sh\
./scripts/make/go-bench.sh\
./scripts/make/go-build.sh\
./scripts/make/go-deps.sh\
./scripts/make/go-fuzz.sh\
./scripts/make/go-lint.sh\
./scripts/make/go-test.sh\
./scripts/make/go-tools.sh\
./scripts/make/go-upd-tools.sh\
./scripts/make/helper.sh\
./scripts/make/md-lint.sh\
./scripts/make/sh-lint.sh\
./scripts/make/txt-lint.sh\
./scripts/make/version.sh\
;
``` | /content/code_sandbox/scripts/make/sh-lint.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 300 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a remarkable change is made to this script.
#
# AdGuard-Project-Version: 2
verbose="${VERBOSE:-0}"
readonly verbose
set -e -f -u
if [ "$verbose" -gt '0' ]
then
set -x
fi
# NOTE: Adjust for your project.
# markdownlint\
# ./README.md\
# ;
# TODO(e.burkov): Lint markdown documents within this project.
``` | /content/code_sandbox/scripts/make/md-lint.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 123 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
if [ "$verbose" -gt '0' ]
then
set -x
debug_flags='--debug=1'
else
set +x
debug_flags='--debug=0'
fi
readonly debug_flags
set -e -f -u
# Require these to be set. The channel value is validated later.
channel="${CHANNEL:?please set CHANNEL}"
commit="${COMMIT:?please set COMMIT}"
dist_dir="${DIST_DIR:?please set DIST_DIR}"
readonly channel commit dist_dir
if [ "${VERSION:-}" = 'v0.0.0' ] || [ "${VERSION:-}" = '' ]
then
version="$( sh ./scripts/make/version.sh )"
else
version="$VERSION"
fi
readonly version
# Allow users to use sudo.
sudo_cmd="${SUDO:-}"
readonly sudo_cmd
docker_platforms="\
linux/386,\
linux/amd64,\
linux/arm/v6,\
linux/arm/v7,\
linux/arm64,\
linux/ppc64le"
readonly docker_platforms
build_date="$( date -u +'%Y-%m-%dT%H:%M:%SZ' )"
readonly build_date
# Set DOCKER_IMAGE_NAME to 'adguard/adguard-home' if you want (and are allowed)
# to push to DockerHub.
docker_image_name="${DOCKER_IMAGE_NAME:-adguardhome-dev}"
readonly docker_image_name
# Set DOCKER_OUTPUT to 'type=image,name=adguard/adguard-home,push=true' if you
# want (and are allowed) to push to DockerHub.
#
# If you want to inspect the resulting image using commands like "docker image
# ls", change type to docker and also set docker_platforms to a single platform.
#
# See path_to_url
docker_output="${DOCKER_OUTPUT:-type=image,name=${docker_image_name},push=false}"
readonly docker_output
case "$channel"
in
('release')
docker_version_tag="--tag=${docker_image_name}:${version}"
docker_channel_tag="--tag=${docker_image_name}:latest"
;;
('beta')
docker_version_tag="--tag=${docker_image_name}:${version}"
docker_channel_tag="--tag=${docker_image_name}:beta"
;;
('edge')
# Set the version tag to an empty string when pushing to the edge channel.
docker_version_tag=''
docker_channel_tag="--tag=${docker_image_name}:edge"
;;
('development')
# Set both tags to an empty string for development builds.
docker_version_tag=''
docker_channel_tag=''
;;
(*)
echo "invalid channel '$channel', supported values are\
'development', 'edge', 'beta', and 'release'" 1>&2
exit 1
;;
esac
readonly docker_version_tag docker_channel_tag
# Copy the binaries into a new directory under new names, so that it's easier to
# COPY them later. DO NOT remove the trailing underscores. See file
# docker/Dockerfile.
dist_docker="${dist_dir}/docker"
readonly dist_docker
mkdir -p "$dist_docker"
cp "${dist_dir}/AdGuardHome_linux_386/AdGuardHome/AdGuardHome"\
"${dist_docker}/AdGuardHome_linux_386_"
cp "${dist_dir}/AdGuardHome_linux_amd64/AdGuardHome/AdGuardHome"\
"${dist_docker}/AdGuardHome_linux_amd64_"
cp "${dist_dir}/AdGuardHome_linux_arm64/AdGuardHome/AdGuardHome"\
"${dist_docker}/AdGuardHome_linux_arm64_"
cp "${dist_dir}/AdGuardHome_linux_arm_6/AdGuardHome/AdGuardHome"\
"${dist_docker}/AdGuardHome_linux_arm_v6"
cp "${dist_dir}/AdGuardHome_linux_arm_7/AdGuardHome/AdGuardHome"\
"${dist_docker}/AdGuardHome_linux_arm_v7"
cp "${dist_dir}/AdGuardHome_linux_ppc64le/AdGuardHome/AdGuardHome"\
"${dist_docker}/AdGuardHome_linux_ppc64le_"
# Don't use quotes with $docker_version_tag and $docker_channel_tag, because we
# want word splitting and or an empty space if tags are empty.
#
# TODO(a.garipov): Once flag --tag of docker buildx build supports commas, use
# them instead.
$sudo_cmd docker\
"$debug_flags"\
buildx build\
--build-arg BUILD_DATE="$build_date"\
--build-arg DIST_DIR="$dist_dir"\
--build-arg VCS_REF="$commit"\
--build-arg VERSION="$version"\
--output "$docker_output"\
--platform "$docker_platforms"\
$docker_version_tag\
$docker_channel_tag\
-f ./docker/Dockerfile\
.
``` | /content/code_sandbox/scripts/make/build-docker.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,006 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
readonly verbose
# Verbosity levels:
# 0 = Don't print anything except for errors.
# 1 = Print commands, but not nested commands.
# 2 = Print everything.
if [ "$verbose" -gt '1' ]
then
set -x
v_flags='-v=1'
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
v_flags='-v=1'
x_flags='-x=0'
else
set +x
v_flags='-v=0'
x_flags='-x=0'
fi
readonly v_flags x_flags
set -e -f -u
if [ "${RACE:-1}" -eq '0' ]
then
race_flags='--race=0'
else
race_flags='--race=1'
fi
readonly race_flags
go="${GO:-go}"
count_flags='--count=1'
shuffle_flags='--shuffle=on'
timeout_flags="${TIMEOUT_FLAGS:---timeout=30s}"
readonly go count_flags shuffle_flags timeout_flags
"$go" test\
"$count_flags"\
"$shuffle_flags"\
"$race_flags"\
"$timeout_flags"\
"$x_flags"\
"$v_flags"\
--bench='.'\
--benchmem\
--benchtime=1s\
--run='^$'\
./...
``` | /content/code_sandbox/scripts/make/go-bench.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 302 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a significant change is made to this script.
#
# AdGuard-Project-Version: 1
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '1' ]
then
env
set -x
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
x_flags='-x=0'
else
set +x
x_flags='-x=0'
fi
readonly x_flags
set -e -f -u
go="${GO:-go}"
readonly go
"$go" mod download "$x_flags"
``` | /content/code_sandbox/scripts/make/go-deps.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 152 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a remarkable change is made to this script.
#
# AdGuard-Project-Version: 5
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '0' ]
then
set -x
fi
# Set $EXIT_ON_ERROR to zero to see all errors.
if [ "${EXIT_ON_ERROR:-1}" -eq '0' ]
then
set +e
else
set -e
fi
# We don't need glob expansions and we want to see errors about unset variables.
set -f -u
# Source the common helpers, including not_found.
. ./scripts/make/helper.sh
# Simple analyzers
# trailing_newlines is a simple check that makes sure that all plain-text files
# have a trailing newlines to make sure that all tools work correctly with them.
trailing_newlines() (
nl="$( printf "\n" )"
readonly nl
# NOTE: Adjust for your project.
git ls-files\
':!*.png'\
':!*.tar.gz'\
':!*.zip'\
| while read -r f
do
final_byte="$( tail -c -1 "$f" )"
if [ "$final_byte" != "$nl" ]
then
printf '%s: must have a trailing newline\n' "$f"
fi
done
)
# trailing_whitespace is a simple check that makes sure that there are no
# trailing whitespace in plain-text files.
trailing_whitespace() {
# NOTE: Adjust for your project.
git ls-files\
':!*.bmp'\
':!*.jpg'\
':!*.mmdb'\
':!*.png'\
':!*.svg'\
':!*.tar.gz'\
':!*.webp'\
':!*.zip'\
| while read -r f
do
grep -e '[[:space:]]$' -n -- "$f"\
| sed -e "s:^:${f}\::" -e 's/ \+$/>>>&<<</'
done
}
run_linter -e trailing_newlines
run_linter -e trailing_whitespace
git ls-files -- '*.conf' '*.md' '*.txt' '*.yaml' '*.yml'\
'client/src/__locales/en.json'\
| xargs misspell --error\
| sed -e 's/^/misspell: /'
``` | /content/code_sandbox/scripts/make/txt-lint.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 558 |
```shell
#!/bin/sh
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a significant change is made to this script.
#
# AdGuard-Project-Version: 2
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '1' ]
then
env
set -x
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
x_flags='-x=0'
else
set +x
x_flags='-x=0'
fi
readonly x_flags
set -e -f -u
go="${GO:-go}"
readonly go
cd ./internal/tools/
"$go" get -u "$x_flags"
"$go" mod tidy
``` | /content/code_sandbox/scripts/make/go-upd-tools.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 164 |
```shell
#!/bin/sh
# Common script helpers
#
# This file contains common script helpers. It should be sourced in scripts
# right after the initial environment processing.
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a remarkable change is made to this script.
#
# AdGuard-Project-Version: 3
# Deferred helpers
not_found_msg='
looks like a binary not found error.
make sure you have installed the linter binaries using:
$ make go-tools
'
readonly not_found_msg
not_found() {
if [ "$?" -eq '127' ]
then
# Code 127 is the exit status a shell uses when a command or a file is
# not found, according to the Bash Hackers wiki.
#
# See path_to_url
echo "$not_found_msg" 1>&2
fi
}
trap not_found EXIT
# Helpers
# run_linter runs the given linter with two additions:
#
# 1. If the first argument is "-e", run_linter exits with a nonzero exit code
# if there is anything in the command's combined output.
#
# 2. In any case, run_linter adds the program's name to its combined output.
run_linter() (
set +e
if [ "${VERBOSE:-0}" -lt '2' ]
then
set +x
fi
cmd="${1:?run_linter: provide a command}"
shift
exit_on_output='0'
if [ "$cmd" = '-e' ]
then
exit_on_output='1'
cmd="${1:?run_linter: provide a command}"
shift
fi
readonly cmd
output="$( "$cmd" "$@" )"
exitcode="$?"
readonly output
if [ "$output" != '' ]
then
echo "$output" | sed -e "s/^/${cmd}: /"
if [ "$exitcode" -eq '0' ] && [ "$exit_on_output" -eq '1' ]
then
exitcode='1'
fi
fi
return "$exitcode"
)
``` | /content/code_sandbox/scripts/make/helper.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 460 |
```shell
#!/bin/sh
# AdGuard Home Release Script
#
# The commentary in this file is written with the assumption that the reader
# only has superficial knowledge of the POSIX shell language and alike.
# Experienced readers may find it overly verbose.
# The default verbosity level is 0. Show log messages if the caller requested
# verbosity level greater than 0. Show the environment and every command that
# is run if the verbosity level is greater than 1. Otherwise, print nothing.
#
# The level of verbosity for the build script is the same minus one level. See
# below in build().
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '1' ]
then
env
set -x
fi
# By default, sign the packages, but allow users to skip that step.
sign="${SIGN:-1}"
readonly sign
# Exit the script if a pipeline fails (-e), prevent accidental filename
# expansion (-f), and consider undefined variables as errors (-u).
set -e -f -u
# Function log is an echo wrapper that writes to stderr if the caller requested
# verbosity level greater than 0. Otherwise, it does nothing.
log() {
if [ "$verbose" -gt '0' ]
then
# Don't use quotes to get word splitting.
echo "$1" 1>&2
fi
}
log 'starting to build AdGuard Home release'
# Require the channel to be set. Additional validation is performed later by
# go-build.sh.
channel="${CHANNEL:?please set CHANNEL}"
readonly channel
# Check VERSION against the default value from the Makefile. If it is that, use
# the version calculation script.
version="${VERSION:-}"
if [ "$version" = 'v0.0.0' ] || [ "$version" = '' ]
then
version="$( sh ./scripts/make/version.sh )"
fi
readonly version
log "channel '$channel'"
log "version '$version'"
# Check architecture and OS limiters. Add spaces to the local versions for
# better pattern matching.
if [ "${ARCH:-}" != '' ]
then
log "arches: '$ARCH'"
arches=" $ARCH "
else
arches=''
fi
readonly arches
if [ "${OS:-}" != '' ]
then
log "oses: '$OS'"
oses=" $OS "
else
oses=''
fi
readonly oses
# Require the gpg key and passphrase to be set if the signing is required.
if [ "$sign" -eq '1' ]
then
gpg_key_passphrase="${GPG_KEY_PASSPHRASE:?please set GPG_KEY_PASSPHRASE or unset SIGN}"
gpg_key="${GPG_KEY:?please set GPG_KEY or unset SIGN}"
else
gpg_key_passphrase=''
gpg_key=''
fi
readonly gpg_key_passphrase gpg_key
# The default distribution files directory is dist.
dist="${DIST_DIR:-dist}"
readonly dist
log "checking tools"
# Make sure we fail gracefully if one of the tools we need is missing. Use
# alternatives when available.
use_shasum='0'
for tool in gpg gzip sed sha256sum tar zip
do
if ! command -v "$tool" > /dev/null
then
if [ "$tool" = 'sha256sum' ] && command -v 'shasum' > /dev/null
then
# macOS doesn't have sha256sum installed by default, but it does
# have shasum.
log 'replacing sha256sum with shasum -a 256'
use_shasum='1'
else
log "pieces don't fit, '$tool' not found"
exit 1
fi
fi
done
readonly use_shasum
# Data section. Arrange data into space-separated tables for read -r to read.
# Use a hyphen for missing values.
# os arch arm mips
platforms="\
darwin amd64 - -
darwin arm64 - -
freebsd 386 - -
freebsd amd64 - -
freebsd arm 5 -
freebsd arm 6 -
freebsd arm 7 -
freebsd arm64 - -
linux 386 - -
linux amd64 - -
linux arm 5 -
linux arm 6 -
linux arm 7 -
linux arm64 - -
linux mips - softfloat
linux mips64 - softfloat
linux mips64le - softfloat
linux mipsle - softfloat
linux ppc64le - -
linux riscv64 - -
openbsd amd64 - -
openbsd arm64 - -
windows 386 - -
windows amd64 - -
windows arm64 - -"
readonly platforms
# Function build builds the release for one platform. It builds a binary and an
# archive.
build() {
# Get the arguments. Here and below, use the "build_" prefix for all
# variables local to function build.
build_dir="${dist}/${1}/AdGuardHome"\
build_ar="$2"\
build_os="$3"\
build_arch="$4"\
build_arm="$5"\
build_mips="$6"\
;
# Use the ".exe" filename extension if we build a Windows release.
if [ "$build_os" = 'windows' ]
then
build_output="./${build_dir}/AdGuardHome.exe"
else
build_output="./${build_dir}/AdGuardHome"
fi
mkdir -p "./${build_dir}"
# Build the binary.
#
# Set GOARM and GOMIPS to an empty string if $build_arm and $build_mips are
# the zero value by removing the hyphen as if it's a prefix.
env\
GOARCH="$build_arch"\
GOARM="${build_arm#-}"\
GOMIPS="${build_mips#-}"\
GOOS="$os"\
VERBOSE="$(( verbose - 1 ))"\
VERSION="$version"\
OUT="$build_output"\
sh ./scripts/make/go-build.sh\
;
log "$build_output"
if [ "$sign" -eq '1' ]
then
gpg\
--default-key "$gpg_key"\
--detach-sig\
--passphrase "$gpg_key_passphrase"\
--pinentry-mode loopback\
-q\
"$build_output"\
;
fi
# Prepare the build directory for archiving.
cp ./CHANGELOG.md ./LICENSE.txt ./README.md "$build_dir"
# Make archives. Windows and macOS prefer ZIP archives; the rest,
# gzipped tarballs.
case "$build_os"
in
('darwin'|'windows')
build_archive="./${dist}/${build_ar}.zip"
# TODO(a.garipov): Find an option similar to the -C option of tar for
# zip.
( cd "${dist}/${1}" && zip -9 -q -r "../../${build_archive}" "./AdGuardHome" )
;;
(*)
build_archive="./${dist}/${build_ar}.tar.gz"
tar -C "./${dist}/${1}" -c -f - "./AdGuardHome" | gzip -9 - > "$build_archive"
;;
esac
log "$build_archive"
}
log "starting builds"
# Go over all platforms defined in the space-separated table above, tweak the
# values where necessary, and feed to build.
echo "$platforms" | while read -r os arch arm mips
do
# See if the architecture or the OS is in the allowlist. To do so, try
# removing everything that matches the pattern (well, a prefix, but that
# doesn't matter here) containing the arch or the OS.
#
# For example, when $arches is " amd64 arm64 " and $arch is "amd64",
# then the pattern to remove is "* amd64 *", so the whole string becomes
# empty. On the other hand, if $arch is "windows", then the pattern is
# "* windows *", which doesn't match, so nothing is removed.
#
# See path_to_url
if [ "${arches##* $arch *}" != '' ]
then
log "$arch excluded, continuing"
continue
elif [ "${oses##* $os *}" != '' ]
then
log "$os excluded, continuing"
continue
fi
case "$arch"
in
(arm)
dir="AdGuardHome_${os}_${arch}_${arm}"
ar="AdGuardHome_${os}_${arch}v${arm}"
;;
(mips*)
dir="AdGuardHome_${os}_${arch}_${mips}"
ar="$dir"
;;
(*)
dir="AdGuardHome_${os}_${arch}"
ar="$dir"
;;
esac
build "$dir" "$ar" "$os" "$arch" "$arm" "$mips"
done
log "packing frontend"
build_archive="./${dist}/AdGuardHome_frontend.tar.gz"
tar -c -f - ./build | gzip -9 - > "$build_archive"
log "$build_archive"
log "calculating checksums"
# calculate_checksums uses the previously detected SHA-256 tool to calculate
# checksums. Do not use find with -exec, since shasum requires arguments.
calculate_checksums() {
if [ "$use_shasum" -eq '0' ]
then
sha256sum "$@"
else
shasum -a 256 "$@"
fi
}
# Calculate the checksums of the files in a subshell with a different working
# directory. Don't use ls, because files matching one of the patterns may be
# absent, which will make ls return with a non-zero status code.
#
# TODO(a.garipov): Consider calculating these as the build goes.
(
set +f
cd "./${dist}"
: > ./checksums.txt
for archive in ./*.zip ./*.tar.gz
do
# Make sure that we don't try to calculate a checksum for a glob pattern
# that matched no files.
if [ ! -f "$archive" ]
then
continue
fi
calculate_checksums "$archive" >> ./checksums.txt
done
)
log "writing versions"
echo "version=$version" > "./${dist}/version.txt"
# Create the version.json file.
version_download_url="path_to_url{channel}"
version_json="./${dist}/version.json"
readonly version_download_url version_json
# If the channel is edge, point users to the "Platforms" page on the Wiki,
# because the direct links to the edge packages are listed there.
if [ "$channel" = 'edge' ]
then
announcement_url='path_to_url
else
announcement_url="path_to_url{version}"
fi
readonly announcement_url
# TODO(a.garipov): Remove "selfupdate_min_version" in future versions.
rm -f "$version_json"
echo "{
\"version\": \"${version}\",
\"announcement\": \"AdGuard Home ${version} is now available!\",
\"announcement_url\": \"${announcement_url}\",
\"selfupdate_min_version\": \"0.0\",
" >> "$version_json"
# Add the MIPS* object keys without the "softfloat" part to mitigate the
# consequences of #5373.
#
# TODO(a.garipov): Remove this around fall 2023.
echo "
\"download_linux_mips64\": \"${version_download_url}/AdGuardHome_linux_mips64_softfloat.tar.gz\",
\"download_linux_mips64le\": \"${version_download_url}/AdGuardHome_linux_mips64le_softfloat.tar.gz\",
\"download_linux_mipsle\": \"${version_download_url}/AdGuardHome_linux_mipsle_softfloat.tar.gz\",
" >> "$version_json"
# Same as with checksums above, don't use ls, because files matching one of the
# patterns may be absent.
ar_files="$( find "./${dist}/" ! -name "${dist}" -prune \( -name '*.tar.gz' -o -name '*.zip' \) )"
ar_files_len="$( echo "$ar_files" | wc -l )"
readonly ar_files ar_files_len
i='1'
# Don't use quotes to get word splitting.
for f in $ar_files
do
platform="$f"
# Remove the prefix.
platform="${platform#"./${dist}/AdGuardHome_"}"
# Remove the filename extensions.
platform="${platform%.zip}"
platform="${platform%.tar.gz}"
# Use the filename's base path.
filename="${f#"./${dist}/"}"
if [ "$i" -eq "$ar_files_len" ]
then
echo " \"download_${platform}\": \"${version_download_url}/${filename}\"" >> "$version_json"
else
echo " \"download_${platform}\": \"${version_download_url}/${filename}\"," >> "$version_json"
fi
i="$(( i + 1 ))"
done
echo '}' >> "$version_json"
log "finished"
``` | /content/code_sandbox/scripts/make/build-release.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,889 |
```shell
#!/bin/sh
# AdGuard Home Build Script
#
# The commentary in this file is written with the assumption that the reader
# only has superficial knowledge of the POSIX shell language and alike.
# Experienced readers may find it overly verbose.
# This comment is used to simplify checking local copies of the script. Bump
# this number every time a significant change is made to this script.
#
# AdGuard-Project-Version: 1
# The default verbosity level is 0. Show every command that is run and every
# package that is processed if the caller requested verbosity level greater than
# 0. Also show subcommands if the requested verbosity level is greater than 1.
# Otherwise, do nothing.
verbose="${VERBOSE:-0}"
readonly verbose
if [ "$verbose" -gt '1' ]
then
env
set -x
v_flags='-v=1'
x_flags='-x=1'
elif [ "$verbose" -gt '0' ]
then
set -x
v_flags='-v=1'
x_flags='-x=0'
else
set +x
v_flags='-v=0'
x_flags='-x=0'
fi
readonly x_flags v_flags
# Exit the script if a pipeline fails (-e), prevent accidental filename
# expansion (-f), and consider undefined variables as errors (-u).
set -e -f -u
# Allow users to override the go command from environment. For example, to
# build two releases with two different Go versions and test the difference.
go="${GO:-go}"
readonly go
# Require the channel to be set and validate the value.
channel="${CHANNEL:?please set CHANNEL}"
readonly channel
case "$channel"
in
('development'|'edge'|'beta'|'release'|'candidate')
# All is well, go on.
;;
(*)
echo "invalid channel '$channel', supported values are\
'development', 'edge', 'beta', 'release', and 'candidate'" 1>&2
exit 1
;;
esac
# Check VERSION against the default value from the Makefile. If it is that, use
# the version calculation script.
version="${VERSION:-}"
if [ "$version" = 'v0.0.0' ] || [ "$version" = '' ]
then
version="$( sh ./scripts/make/version.sh )"
fi
readonly version
# Set date and time of the latest commit unless already set.
committime="${SOURCE_DATE_EPOCH:-$( git log -1 --pretty=%ct )}"
readonly committime
# Set the linker flags accordingly: set the release channel and the current
# version as well as goarm and gomips variable values, if the variables are set
# and are not empty.
version_pkg='github.com/AdguardTeam/AdGuardHome/internal/version'
readonly version_pkg
ldflags="-s -w"
ldflags="${ldflags} -X ${version_pkg}.version=${version}"
ldflags="${ldflags} -X ${version_pkg}.channel=${channel}"
ldflags="${ldflags} -X ${version_pkg}.committime=${committime}"
if [ "${GOARM:-}" != '' ]
then
ldflags="${ldflags} -X ${version_pkg}.goarm=${GOARM}"
elif [ "${GOMIPS:-}" != '' ]
then
ldflags="${ldflags} -X ${version_pkg}.gomips=${GOMIPS}"
fi
readonly ldflags
# Allow users to limit the build's parallelism.
parallelism="${PARALLELISM:-}"
readonly parallelism
# Use GOFLAGS for -p, because -p=0 simply disables the build instead of leaving
# the default value.
if [ "${parallelism}" != '' ]
then
GOFLAGS="${GOFLAGS:-} -p=${parallelism}"
fi
readonly GOFLAGS
export GOFLAGS
# Allow users to specify a different output name.
out="${OUT:-AdGuardHome}"
readonly out
o_flags="-o=${out}"
readonly o_flags
# Allow users to enable the race detector. Unfortunately, that means that cgo
# must be enabled.
if [ "${RACE:-0}" -eq '0' ]
then
CGO_ENABLED='0'
race_flags='--race=0'
else
CGO_ENABLED='1'
race_flags='--race=1'
fi
readonly CGO_ENABLED race_flags
export CGO_ENABLED
GO111MODULE='on'
export GO111MODULE
# Build the new binary if requested.
if [ "${NEXTAPI:-0}" -eq '0' ]
then
tags_flags='--tags='
else
tags_flags='--tags=next'
fi
readonly tags_flags
if [ "$verbose" -gt '0' ]
then
"$go" env
fi
"$go" build\
--ldflags="$ldflags"\
"$race_flags"\
"$tags_flags"\
--trimpath\
"$o_flags"\
"$v_flags"\
"$x_flags"
``` | /content/code_sandbox/scripts/make/go-build.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,056 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
if [ "$verbose" -gt '0' ]
then
set -x
fi
set -e -f -u
# Function log is an echo wrapper that writes to stderr if the caller requested
# verbosity level greater than 0. Otherwise, it does nothing.
log() {
if [ "$verbose" -gt '0' ]
then
# Don't use quotes to get word splitting.
echo "$1" 1>&2
fi
}
# Do not set a new lowercase variable, because the snapcraft tool expects the
# uppercase form.
if [ "${SNAPCRAFT_STORE_CREDENTIALS:-}" = '' ]
then
log 'please set SNAPCRAFT_STORE_CREDENTIALS'
exit 1
fi
export SNAPCRAFT_STORE_CREDENTIALS
snapcraft_channel="${SNAPCRAFT_CHANNEL:?please set SNAPCRAFT_CHANNEL}"
readonly snapcraft_channel
# Allow developers to overwrite the command, e.g. for testing.
snapcraft_cmd="${SNAPCRAFT_CMD:-snapcraft}"
readonly snapcraft_cmd
default_timeout='90s'
kill_timeout='120s'
readonly default_timeout kill_timeout
for arch in\
'i386'\
'amd64'\
'armhf'\
'arm64'
do
snap_file="./AdGuardHome_${arch}.snap"
# Catch the exit code and the combined output to later inspect it.
set +e
snapcraft_output="$(
# Use timeout(1) to force snapcraft to quit after a certain time. There
# seems to be no environment variable or flag to force this behavior.
timeout\
--preserve-status\
-k "$kill_timeout"\
-v "$default_timeout"\
"$snapcraft_cmd" upload\
--release="${snapcraft_channel}"\
--quiet\
"${snap_file}"\
2>&1
)"
snapcraft_exit_code="$?"
set -e
if [ "$snapcraft_exit_code" -eq '0' ]
then
log "successful upload: ${snapcraft_output}"
continue
fi
# Skip the ones that were failed by a duplicate upload error.
case "$snapcraft_output"
in
(*'A file with this exact same content has already been uploaded'*|\
*'Error checking upload uniqueness'*)
log "warning: duplicate upload, skipping"
log "snapcraft upload error: ${snapcraft_output}"
continue
;;
(*)
echo "unexpected snapcraft upload error: ${snapcraft_output}"
return "$snapcraft_exit_code"
;;
esac
done
``` | /content/code_sandbox/scripts/snap/upload.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 566 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
if [ "$verbose" -gt '0' ]
then
set -x
fi
set -e -f -u
channel="${CHANNEL:?please set CHANNEL}"
readonly channel
printf '%s %s\n'\
'386' 'i386'\
'amd64' 'amd64'\
'armv7' 'armhf'\
'arm64' 'arm64' \
| while read -r arch snap_arch
do
release_url="path_to_url{channel}/AdGuardHome_linux_${arch}.tar.gz"
output="./AdGuardHome_linux_${arch}.tar.gz"
curl -o "$output" -v "$release_url"
tar -f "$output" -v -x -z
cp ./AdGuardHome/AdGuardHome "./AdGuardHome_${snap_arch}"
rm -f -r "$output" ./AdGuardHome
done
``` | /content/code_sandbox/scripts/snap/download.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 199 |
```shell
#!/bin/sh
verbose="${VERBOSE:-0}"
if [ "$verbose" -gt '0' ]
then
set -x
fi
set -e -f -u
# Function log is an echo wrapper that writes to stderr if the caller requested
# verbosity level greater than 0. Otherwise, it does nothing.
#
# TODO(a.garipov): Add to helpers.sh and use more actively in scripts.
log() {
if [ "$verbose" -gt '0' ]
then
# Don't use quotes to get word splitting.
echo "$1" 1>&2
fi
}
version="$( ./AdGuardHome_amd64 --version | cut -d ' ' -f 4 )"
if [ "$version" = '' ]
then
log 'empty version from ./AdGuardHome_amd64'
exit 1
fi
readonly version
log "version '$version'"
for arch in\
'i386'\
'amd64'\
'armhf'\
'arm64'
do
build_output="./AdGuardHome_${arch}"
snap_output="./AdGuardHome_${arch}.snap"
snap_dir="${snap_output}.dir"
# Create the meta subdirectory and copy files there.
mkdir -p "${snap_dir}/meta"
cp "$build_output" "${snap_dir}/AdGuardHome"
cp './snap/local/adguard-home-web.sh' "$snap_dir"
cp -r './snap/gui' "${snap_dir}/meta/"
# Create a snap.yaml file, setting the values.
sed\
-e 's/%VERSION%/'"$version"'/'\
-e 's/%ARCH%/'"$arch"'/'\
./snap/snap.tmpl.yaml\
> "${snap_dir}/meta/snap.yaml"
# TODO(a.garipov): The snapcraft tool will *always* write everything,
# including errors, to stdout. And there doesn't seem to be a way to change
# that. So, save the combined output, but only show it when snapcraft
# actually fails.
set +e
snapcraft_output="$(
snapcraft pack "$snap_dir" --output "$snap_output" 2>&1
)"
snapcraft_exit_code="$?"
set -e
if [ "$snapcraft_exit_code" -ne '0' ]
then
log "$snapcraft_output"
exit "$snapcraft_exit_code"
fi
log "$snap_output"
rm -f -r "$snap_dir"
done
``` | /content/code_sandbox/scripts/snap/build.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 534 |
```go
// vetted-filters fetches the most recent Hostlists Registry filtering rule list
// index and transforms the filters from it to AdGuard Home's format.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"time"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/google/renameio/v2/maybe"
)
func main() {
ctx := context.Background()
l := slogutil.New(nil)
urlStr := "path_to_url"
if v, ok := os.LookupEnv("URL"); ok {
urlStr = v
}
// Validate the URL.
_, err := url.Parse(urlStr)
check(err)
c := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := c.Get(urlStr)
check(err)
defer slogutil.CloseAndLog(ctx, l, resp.Body, slog.LevelError)
if resp.StatusCode != http.StatusOK {
panic(fmt.Errorf("expected code %d, got %d", http.StatusOK, resp.StatusCode))
}
hlFlt := &hlFilters{}
err = json.NewDecoder(resp.Body).Decode(hlFlt)
check(err)
aghFlt := &aghFilters{
Categories: map[string]*aghFiltersCategory{
"general": {
Name: "filter_category_general",
Description: "filter_category_general_desc",
},
"other": {
Name: "filter_category_other",
Description: "filter_category_other_desc",
},
"regional": {
Name: "filter_category_regional",
Description: "filter_category_regional_desc",
},
"security": {
Name: "filter_category_security",
Description: "filter_category_security_desc",
},
},
Filters: map[string]*aghFiltersFilter{},
}
for i, f := range hlFlt.Filters {
key := f.FilterKey
cat := f.category()
if cat == "" {
l.WarnContext(ctx, "no fitting category for filter", "key", key, "idx", i)
}
aghFlt.Filters[key] = &aghFiltersFilter{
Name: f.Name,
CategoryID: cat,
Homepage: f.Homepage,
// NOTE: The source URL in filters.json is not guaranteed to contain
// the URL of the filtering rule list. So, use our mirror for the
// vetted blocklists, which are mostly guaranteed to be valid and
// available lists.
Source: f.DownloadURL,
}
}
buf := &bytes.Buffer{}
_, _ = buf.WriteString(jsHeader)
enc := json.NewEncoder(buf)
enc.SetIndent("", " ")
err = enc.Encode(aghFlt)
check(err)
err = maybe.WriteFile("client/src/helpers/filters/filters.ts", buf.Bytes(), 0o644)
check(err)
}
// jsHeader is the header for the generated JavaScript file. It informs the
// reader that the file is generated and disables some style-related eslint
// checks.
const jsHeader = `// Code generated by go run ./scripts/vetted-filters/main.go; DO NOT EDIT.
/* eslint quote-props: 'off', quotes: 'off', comma-dangle: 'off', semi: 'off' */
export default `
// check is a simple error-checking helper for scripts.
func check(err error) {
if err != nil {
panic(err)
}
}
// hlFilters is the JSON structure for the Hostlists Registry rule list index.
type hlFilters struct {
Filters []*hlFiltersFilter `json:"filters"`
}
// hlFiltersFilter is the JSON structure for a filter in the Hostlists Registry.
type hlFiltersFilter struct {
DownloadURL string `json:"downloadUrl"`
FilterKey string `json:"filterKey"`
Homepage string `json:"homepage"`
Name string `json:"name"`
Tags []int `json:"tags"`
}
// Known tag IDs. Keep in sync with tags/metadata.json in the source repo.
const (
tagIDGeneral = 1
tagIDSecurity = 2
tagIDRegional = 3
tagIDOther = 4
)
// category returns the AdGuard Home category for this filter. If there is no
// fitting category, cat is empty.
func (f *hlFiltersFilter) category() (cat string) {
for _, t := range f.Tags {
switch t {
case tagIDGeneral:
return "general"
case tagIDSecurity:
return "security"
case tagIDRegional:
return "regional"
case tagIDOther:
return "other"
}
}
return ""
}
// aghFilters is the JSON structure for AdGuard Home's list of vetted filtering
// rule list in file client/src/helpers/filters/filters.ts.
type aghFilters struct {
Categories map[string]*aghFiltersCategory `json:"categories"`
Filters map[string]*aghFiltersFilter `json:"filters"`
}
// aghFiltersCategory is the JSON structure for a category in the vetted
// filtering rule list file.
type aghFiltersCategory struct {
Name string `json:"name"`
Description string `json:"description"`
}
// aghFiltersFilter is the JSON structure for a filter in the vetted filtering
// rule list file.
type aghFiltersFilter struct {
Name string `json:"name"`
CategoryID string `json:"categoryId"`
Homepage string `json:"homepage"`
Source string `json:"source"`
}
``` | /content/code_sandbox/scripts/vetted-filters/main.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,211 |
```go
// blocked services fetches the most recent Hostlists Registry blocked service
// index and transforms the filters from it to AdGuard Home's data and code
// formats.
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"slices"
"strings"
"text/template"
"time"
"github.com/AdguardTeam/golibs/log"
)
func main() {
urlStr := "path_to_url"
if v, ok := os.LookupEnv("URL"); ok {
urlStr = v
}
// Validate the URL.
_, err := url.Parse(urlStr)
check(err)
c := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := c.Get(urlStr)
check(err)
defer log.OnCloserError(resp.Body, log.ERROR)
if resp.StatusCode != http.StatusOK {
panic(fmt.Errorf("expected code %d, got %d", http.StatusOK, resp.StatusCode))
}
hlSvcs := &hlServices{}
err = json.NewDecoder(resp.Body).Decode(hlSvcs)
check(err)
// Sort all services and rules to make the output more predictable.
slices.SortStableFunc(hlSvcs.BlockedServices, func(a, b *hlServicesService) (res int) {
return strings.Compare(a.ID, b.ID)
})
for _, s := range hlSvcs.BlockedServices {
slices.Sort(s.Rules)
}
// Use another set of delimiters to prevent them interfering with the Go
// code.
tmpl, err := template.New("main").Delims("<%", "%>").Funcs(template.FuncMap{
"isnotlast": func(idx, sliceLen int) (ok bool) { return idx != sliceLen-1 },
}).Parse(tmplStr)
check(err)
f, err := os.OpenFile(
"./internal/filtering/servicelist.go",
os.O_CREATE|os.O_TRUNC|os.O_WRONLY,
0o644,
)
check(err)
defer log.OnCloserError(f, log.ERROR)
err = tmpl.Execute(f, hlSvcs)
check(err)
}
// tmplStr is the template for the Go source file with the services.
const tmplStr = `// Code generated by go run ./scripts/blocked-services/main.go; DO NOT EDIT.
package filtering
// blockedService represents a single blocked service.
type blockedService struct {
ID string ` + "`" + `json:"id"` + "`" + `
Name string ` + "`" + `json:"name"` + "`" + `
IconSVG []byte ` + "`" + `json:"icon_svg"` + "`" + `
Rules []string ` + "`" + `json:"rules"` + "`" + `
}
// blockedServices contains raw blocked service data.
var blockedServices = []blockedService{<% $l := len .BlockedServices %>
<%- range $i, $s := .BlockedServices %>{
ID: <% printf "%q" $s.ID %>,
Name: <% printf "%q" $s.Name %>,
IconSVG: []byte(<% printf "%q" $s.IconSVG %>),
Rules: []string{<% range $s.Rules %>
<% printf "%q" . %>,<% end %>
},
}<% if isnotlast $i $l %>, <% end %><% end %>}
`
// check is a simple error-checking helper for scripts.
func check(err error) {
if err != nil {
panic(err)
}
}
// hlServices is the JSON structure for the Hostlists Registry blocked service
// index.
type hlServices struct {
BlockedServices []*hlServicesService `json:"blocked_services"`
}
// hlServicesService is the JSON structure for a service in the Hostlists
// Registry.
type hlServicesService struct {
ID string `json:"id"`
Name string `json:"name"`
IconSVG string `json:"icon_svg"`
Rules []string `json:"rules"`
}
``` | /content/code_sandbox/scripts/blocked-services/main.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 870 |
```shell
#!/bin/sh
set -e -f -u -x
# This script syncs companies DB that we bundle with AdGuard Home. The source
# for this database is path_to_url
#
trackers_url='path_to_url
output='./client/src/helpers/trackers/trackers.json'
readonly trackers_url output
curl -o "$output" -v "$trackers_url"
``` | /content/code_sandbox/scripts/companiesdb/download.sh | shell | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 83 |
```yaml
# The %VARIABLES% are be replaced by actual values by the build script.
'name': 'adguard-home'
'base': 'core22'
'version': '%VERSION%'
'summary': Network-wide ads & trackers blocking DNS server
'description': |
AdGuard Home is a network-wide software for blocking ads & tracking. After
you set it up, it'll cover ALL your home devices, and you don't need any
client-side software for that.
It operates as a DNS server that re-routes tracking domains to a "black hole,"
thus preventing your devices from connecting to those servers. It's based
on software we use for our public AdGuard DNS servers -- both share a lot
of common code.
'grade': 'stable'
'confinement': 'strict'
'architectures':
- '%ARCH%'
'apps':
'adguard-home':
'command': 'AdGuardHome --no-check-update -w $SNAP_DATA'
'plugs':
# Add the "network-bind" plug to bind to interfaces.
- 'network-bind'
# Add the "network-observe" plug to be able to bind to ports below 1024
# (cap_net_bind_service) and also to bind to a particular interface using
# SO_BINDTODEVICE (cap_net_raw).
- 'network-observe'
# Add the "network-control" plug to be able to use raw sockets in the DHCP
# server.
#
# TODO(a.garipov): If this works, request auto-connect of this plug.
- 'network-control'
'daemon': 'simple'
'restart-condition': 'always'
'adguard-home-web':
'command': 'adguard-home-web.sh'
'plugs':
- 'desktop'
``` | /content/code_sandbox/snap/snap.tmpl.yaml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 390 |
```desktop
[Desktop Entry]
Type=Application
Encoding=UTF-8
Name=AdGuard Home
Comment=Network-wide ads & trackers blocking DNS server
Exec=adguard-home.adguard-home-web
Icon=${SNAP}/meta/gui/adguard-home-web.png
Terminal=false
``` | /content/code_sandbox/snap/gui/adguard-home-web.desktop | desktop | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.