all: sync with master
This commit is contained in:
@@ -1,261 +0,0 @@
|
||||
package home
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/filtering/safesearch"
|
||||
"github.com/AdguardTeam/dnsproxy/proxy"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/stringutil"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
// UID is the type for the unique IDs of persistent clients.
|
||||
type UID uuid.UUID
|
||||
|
||||
// NewUID returns a new persistent client 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
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ encoding.TextMarshaler = UID{}
|
||||
|
||||
// MarshalText implements the [encoding.TextMarshaler] for UID.
|
||||
func (uid UID) MarshalText() ([]byte, error) {
|
||||
return uuid.UUID(uid).MarshalText()
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ encoding.TextUnmarshaler = (*UID)(nil)
|
||||
|
||||
// UnmarshalText implements the [encoding.TextUnmarshaler] interface for UID.
|
||||
func (uid *UID) UnmarshalText(data []byte) error {
|
||||
return (*uuid.UUID)(uid).UnmarshalText(data)
|
||||
}
|
||||
|
||||
// persistentClient contains information about persistent clients.
|
||||
type persistentClient struct {
|
||||
// upstreamConfig is the custom upstream configuration for this client. If
|
||||
// it's nil, it has not been initialized yet. If it's non-nil and empty,
|
||||
// there are no valid upstreams. If it's non-nil and non-empty, these
|
||||
// upstream must be used.
|
||||
upstreamConfig *proxy.CustomUpstreamConfig
|
||||
|
||||
// TODO(d.kolyshev): Make safeSearchConf a pointer.
|
||||
safeSearchConf filtering.SafeSearchConfig
|
||||
SafeSearch filtering.SafeSearch
|
||||
|
||||
// BlockedServices is the configuration of blocked services of a client.
|
||||
BlockedServices *filtering.BlockedServices
|
||||
|
||||
Name string
|
||||
|
||||
Tags []string
|
||||
Upstreams []string
|
||||
|
||||
IPs []netip.Addr
|
||||
// TODO(s.chzhen): Use netutil.Prefix.
|
||||
Subnets []netip.Prefix
|
||||
MACs []net.HardwareAddr
|
||||
ClientIDs []string
|
||||
|
||||
// UID is the unique identifier of the persistent client.
|
||||
UID UID
|
||||
|
||||
UpstreamsCacheSize uint32
|
||||
UpstreamsCacheEnabled bool
|
||||
|
||||
UseOwnSettings bool
|
||||
FilteringEnabled bool
|
||||
SafeBrowsingEnabled bool
|
||||
ParentalEnabled bool
|
||||
UseOwnBlockedServices bool
|
||||
IgnoreQueryLog bool
|
||||
IgnoreStatistics bool
|
||||
}
|
||||
|
||||
// setTags sets the tags if they are known, otherwise logs an unknown tag.
|
||||
func (c *persistentClient) setTags(tags []string, known *stringutil.Set) {
|
||||
for _, t := range tags {
|
||||
if !known.Has(t) {
|
||||
log.Info("skipping unknown tag %q", t)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
c.Tags = append(c.Tags, t)
|
||||
}
|
||||
|
||||
slices.Sort(c.Tags)
|
||||
}
|
||||
|
||||
// setIDs parses a list of strings into typed fields and returns an error if
|
||||
// there is one.
|
||||
func (c *persistentClient) setIDs(ids []string) (err error) {
|
||||
for _, id := range ids {
|
||||
err = c.setID(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
slices.SortFunc(c.IPs, netip.Addr.Compare)
|
||||
|
||||
// TODO(s.chzhen): Use netip.PrefixCompare in Go 1.23.
|
||||
slices.SortFunc(c.Subnets, subnetCompare)
|
||||
slices.SortFunc(c.MACs, slices.Compare[net.HardwareAddr])
|
||||
slices.Sort(c.ClientIDs)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// subnetCompare is a comparison function for the two subnets. It returns -1 if
|
||||
// x sorts before y, 1 if x sorts after y, and 0 if their relative sorting
|
||||
// position is the same.
|
||||
func subnetCompare(x, y netip.Prefix) (cmp int) {
|
||||
if x == y {
|
||||
return 0
|
||||
}
|
||||
|
||||
xAddr, xBits := x.Addr(), x.Bits()
|
||||
yAddr, yBits := y.Addr(), y.Bits()
|
||||
if xBits == yBits {
|
||||
return xAddr.Compare(yAddr)
|
||||
}
|
||||
|
||||
if xBits > yBits {
|
||||
return -1
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
// setID parses id into typed field if there is no error.
|
||||
func (c *persistentClient) setID(id string) (err error) {
|
||||
if id == "" {
|
||||
return errors.Error("clientid is empty")
|
||||
}
|
||||
|
||||
var ip netip.Addr
|
||||
if ip, err = netip.ParseAddr(id); err == nil {
|
||||
c.IPs = append(c.IPs, ip)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var subnet netip.Prefix
|
||||
if subnet, err = netip.ParsePrefix(id); err == nil {
|
||||
c.Subnets = append(c.Subnets, subnet)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var mac net.HardwareAddr
|
||||
if mac, err = net.ParseMAC(id); err == nil {
|
||||
c.MACs = append(c.MACs, mac)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
err = dnsforward.ValidateClientID(id)
|
||||
if err != nil {
|
||||
// Don't wrap the error, because it's informative enough as is.
|
||||
return err
|
||||
}
|
||||
|
||||
c.ClientIDs = append(c.ClientIDs, strings.ToLower(id))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ids returns a list of client ids containing at least one element.
|
||||
func (c *persistentClient) ids() (ids []string) {
|
||||
ids = make([]string, 0, c.idsLen())
|
||||
|
||||
for _, ip := range c.IPs {
|
||||
ids = append(ids, ip.String())
|
||||
}
|
||||
|
||||
for _, subnet := range c.Subnets {
|
||||
ids = append(ids, subnet.String())
|
||||
}
|
||||
|
||||
for _, mac := range c.MACs {
|
||||
ids = append(ids, mac.String())
|
||||
}
|
||||
|
||||
return append(ids, c.ClientIDs...)
|
||||
}
|
||||
|
||||
// idsLen returns a length of client ids.
|
||||
func (c *persistentClient) idsLen() (n int) {
|
||||
return len(c.IPs) + len(c.Subnets) + len(c.MACs) + len(c.ClientIDs)
|
||||
}
|
||||
|
||||
// equalIDs returns true if the ids of the current and previous clients are the
|
||||
// same.
|
||||
func (c *persistentClient) equalIDs(prev *persistentClient) (equal bool) {
|
||||
return slices.Equal(c.IPs, prev.IPs) &&
|
||||
slices.Equal(c.Subnets, prev.Subnets) &&
|
||||
slices.EqualFunc(c.MACs, prev.MACs, slices.Equal[net.HardwareAddr]) &&
|
||||
slices.Equal(c.ClientIDs, prev.ClientIDs)
|
||||
}
|
||||
|
||||
// shallowClone returns a deep copy of the client, except upstreamConfig,
|
||||
// safeSearchConf, SafeSearch fields, because it's difficult to copy them.
|
||||
func (c *persistentClient) shallowClone() (clone *persistentClient) {
|
||||
clone = &persistentClient{}
|
||||
*clone = *c
|
||||
|
||||
clone.BlockedServices = c.BlockedServices.Clone()
|
||||
clone.Tags = slices.Clone(c.Tags)
|
||||
clone.Upstreams = slices.Clone(c.Upstreams)
|
||||
|
||||
clone.IPs = slices.Clone(c.IPs)
|
||||
clone.Subnets = slices.Clone(c.Subnets)
|
||||
clone.MACs = slices.Clone(c.MACs)
|
||||
clone.ClientIDs = slices.Clone(c.ClientIDs)
|
||||
|
||||
return clone
|
||||
}
|
||||
|
||||
// closeUpstreams closes the client-specific upstream config of c if any.
|
||||
func (c *persistentClient) closeUpstreams() (err error) {
|
||||
if c.upstreamConfig != nil {
|
||||
if err = c.upstreamConfig.Close(); err != nil {
|
||||
return fmt.Errorf("closing upstreams of client %q: %w", c.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// setSafeSearch initializes and sets the safe search filter for this client.
|
||||
func (c *persistentClient) setSafeSearch(
|
||||
conf filtering.SafeSearchConfig,
|
||||
cacheSize uint,
|
||||
cacheTTL time.Duration,
|
||||
) (err error) {
|
||||
ss, err := safesearch.NewDefault(conf, fmt.Sprintf("client %q", c.Name), cacheSize, cacheTTL)
|
||||
if err != nil {
|
||||
// Don't wrap the error, because it's informative enough as is.
|
||||
return err
|
||||
}
|
||||
|
||||
c.SafeSearch = ss
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
package home
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPersistentClient_EqualIDs(t *testing.T) {
|
||||
const (
|
||||
ip = "0.0.0.0"
|
||||
ip1 = "1.1.1.1"
|
||||
ip2 = "2.2.2.2"
|
||||
|
||||
cidr = "0.0.0.0/0"
|
||||
cidr1 = "1.1.1.1/11"
|
||||
cidr2 = "2.2.2.2/22"
|
||||
|
||||
mac = "00-00-00-00-00-00"
|
||||
mac1 = "11-11-11-11-11-11"
|
||||
mac2 = "22-22-22-22-22-22"
|
||||
|
||||
cli = "client0"
|
||||
cli1 = "client1"
|
||||
cli2 = "client2"
|
||||
)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
ids []string
|
||||
prevIDs []string
|
||||
want assert.BoolAssertionFunc
|
||||
}{{
|
||||
name: "single_ip",
|
||||
ids: []string{ip1},
|
||||
prevIDs: []string{ip1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "single_ip_not_equal",
|
||||
ids: []string{ip1},
|
||||
prevIDs: []string{ip2},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "ips_not_equal",
|
||||
ids: []string{ip1, ip2},
|
||||
prevIDs: []string{ip1, ip},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "ips_mixed_equal",
|
||||
ids: []string{ip1, ip2},
|
||||
prevIDs: []string{ip2, ip1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "single_subnet",
|
||||
ids: []string{cidr1},
|
||||
prevIDs: []string{cidr1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "subnets_not_equal",
|
||||
ids: []string{ip1, ip2, cidr1, cidr2},
|
||||
prevIDs: []string{ip1, ip2, cidr1, cidr},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "subnets_mixed_equal",
|
||||
ids: []string{ip1, ip2, cidr1, cidr2},
|
||||
prevIDs: []string{cidr2, cidr1, ip2, ip1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "single_mac",
|
||||
ids: []string{mac1},
|
||||
prevIDs: []string{mac1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "single_mac_not_equal",
|
||||
ids: []string{mac1},
|
||||
prevIDs: []string{mac2},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "macs_not_equal",
|
||||
ids: []string{ip1, ip2, cidr1, cidr2, mac1, mac2},
|
||||
prevIDs: []string{ip1, ip2, cidr1, cidr2, mac1, mac},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "macs_mixed_equal",
|
||||
ids: []string{ip1, ip2, cidr1, cidr2, mac1, mac2},
|
||||
prevIDs: []string{mac2, mac1, cidr2, cidr1, ip2, ip1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "single_client_id",
|
||||
ids: []string{cli1},
|
||||
prevIDs: []string{cli1},
|
||||
want: assert.True,
|
||||
}, {
|
||||
name: "single_client_id_not_equal",
|
||||
ids: []string{cli1},
|
||||
prevIDs: []string{cli2},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "client_ids_not_equal",
|
||||
ids: []string{ip1, ip2, cidr1, cidr2, mac1, mac2, cli1, cli2},
|
||||
prevIDs: []string{ip1, ip2, cidr1, cidr2, mac1, mac2, cli1, cli},
|
||||
want: assert.False,
|
||||
}, {
|
||||
name: "client_ids_mixed_equal",
|
||||
ids: []string{ip1, ip2, cidr1, cidr2, mac1, mac2, cli1, cli2},
|
||||
prevIDs: []string{cli2, cli1, mac2, mac1, cidr2, cidr1, ip2, ip1},
|
||||
want: assert.True,
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := &persistentClient{}
|
||||
err := c.setIDs(tc.ids)
|
||||
require.NoError(t, err)
|
||||
|
||||
prev := &persistentClient{}
|
||||
err = prev.setIDs(tc.prevIDs)
|
||||
require.NoError(t, err)
|
||||
|
||||
tc.want(t, c.equalIDs(prev))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -23,7 +24,6 @@ import (
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/stringutil"
|
||||
"golang.org/x/exp/maps"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
// DHCP is an interface for accessing DHCP lease data the [clientsContainer]
|
||||
@@ -47,8 +47,9 @@ type DHCP interface {
|
||||
type clientsContainer struct {
|
||||
// TODO(a.garipov): Perhaps use a number of separate indices for different
|
||||
// types (string, netip.Addr, and so on).
|
||||
list map[string]*persistentClient // name -> client
|
||||
idIndex map[string]*persistentClient // ID -> client
|
||||
list map[string]*client.Persistent // name -> client
|
||||
|
||||
clientIndex *client.Index
|
||||
|
||||
// ipToRC maps IP addresses to runtime client information.
|
||||
ipToRC map[netip.Addr]*client.Runtime
|
||||
@@ -102,10 +103,11 @@ func (clients *clientsContainer) Init(
|
||||
log.Fatal("clients.list != nil")
|
||||
}
|
||||
|
||||
clients.list = map[string]*persistentClient{}
|
||||
clients.idIndex = map[string]*persistentClient{}
|
||||
clients.list = map[string]*client.Persistent{}
|
||||
clients.ipToRC = map[netip.Addr]*client.Runtime{}
|
||||
|
||||
clients.clientIndex = client.NewIndex()
|
||||
|
||||
clients.allTags = stringutil.NewSet(clientTags...)
|
||||
|
||||
// TODO(e.burkov): Use [dhcpsvc] implementation when it's ready.
|
||||
@@ -140,8 +142,7 @@ func (clients *clientsContainer) Init(
|
||||
}
|
||||
|
||||
// handleHostsUpdates receives the updates from the hosts container and adds
|
||||
// them to the clients container. It's used to be called in a separate
|
||||
// goroutine.
|
||||
// them to the clients container. It is intended to be used as a goroutine.
|
||||
func (clients *clientsContainer) handleHostsUpdates() {
|
||||
for upd := range clients.etcHosts.Upd() {
|
||||
clients.addFromHostsFile(upd)
|
||||
@@ -189,7 +190,7 @@ type clientObject struct {
|
||||
Upstreams []string `yaml:"upstreams"`
|
||||
|
||||
// UID is the unique identifier of the persistent client.
|
||||
UID UID `yaml:"uid"`
|
||||
UID client.UID `yaml:"uid"`
|
||||
|
||||
// UpstreamsCacheSize is the DNS cache size (in bytes).
|
||||
//
|
||||
@@ -213,8 +214,8 @@ type clientObject struct {
|
||||
func (o *clientObject) toPersistent(
|
||||
filteringConf *filtering.Config,
|
||||
allTags *stringutil.Set,
|
||||
) (cli *persistentClient, err error) {
|
||||
cli = &persistentClient{
|
||||
) (cli *client.Persistent, err error) {
|
||||
cli = &client.Persistent{
|
||||
Name: o.Name,
|
||||
|
||||
Upstreams: o.Upstreams,
|
||||
@@ -224,7 +225,7 @@ func (o *clientObject) toPersistent(
|
||||
UseOwnSettings: !o.UseGlobalSettings,
|
||||
FilteringEnabled: o.FilteringEnabled,
|
||||
ParentalEnabled: o.ParentalEnabled,
|
||||
safeSearchConf: o.SafeSearchConf,
|
||||
SafeSearchConf: o.SafeSearchConf,
|
||||
SafeBrowsingEnabled: o.SafeBrowsingEnabled,
|
||||
UseOwnBlockedServices: !o.UseGlobalBlockedServices,
|
||||
IgnoreQueryLog: o.IgnoreQueryLog,
|
||||
@@ -233,13 +234,13 @@ func (o *clientObject) toPersistent(
|
||||
UpstreamsCacheSize: o.UpstreamsCacheSize,
|
||||
}
|
||||
|
||||
err = cli.setIDs(o.IDs)
|
||||
err = cli.SetIDs(o.IDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing ids: %w", err)
|
||||
}
|
||||
|
||||
if (cli.UID == UID{}) {
|
||||
cli.UID, err = NewUID()
|
||||
if (cli.UID == client.UID{}) {
|
||||
cli.UID, err = client.NewUID()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generating uid: %w", err)
|
||||
}
|
||||
@@ -248,7 +249,7 @@ func (o *clientObject) toPersistent(
|
||||
if o.SafeSearchConf.Enabled {
|
||||
o.SafeSearchConf.CustomResolver = safeSearchResolver{}
|
||||
|
||||
err = cli.setSafeSearch(
|
||||
err = cli.SetSafeSearch(
|
||||
o.SafeSearchConf,
|
||||
filteringConf.SafeSearchCacheSize,
|
||||
time.Minute*time.Duration(filteringConf.CacheTime),
|
||||
@@ -265,7 +266,7 @@ func (o *clientObject) toPersistent(
|
||||
|
||||
cli.BlockedServices = o.BlockedServices.Clone()
|
||||
|
||||
cli.setTags(o.Tags, allTags)
|
||||
cli.SetTags(o.Tags, allTags)
|
||||
|
||||
return cli, nil
|
||||
}
|
||||
@@ -277,7 +278,7 @@ func (clients *clientsContainer) addFromConfig(
|
||||
filteringConf *filtering.Config,
|
||||
) (err error) {
|
||||
for i, o := range objects {
|
||||
var cli *persistentClient
|
||||
var cli *client.Persistent
|
||||
cli, err = o.toPersistent(filteringConf, clients.allTags)
|
||||
if err != nil {
|
||||
return fmt.Errorf("clients: init persistent client at index %d: %w", i, err)
|
||||
@@ -305,7 +306,7 @@ func (clients *clientsContainer) forConfig() (objs []*clientObject) {
|
||||
|
||||
BlockedServices: cli.BlockedServices.Clone(),
|
||||
|
||||
IDs: cli.ids(),
|
||||
IDs: cli.IDs(),
|
||||
Tags: stringutil.CloneSlice(cli.Tags),
|
||||
Upstreams: stringutil.CloneSlice(cli.Upstreams),
|
||||
|
||||
@@ -314,7 +315,7 @@ func (clients *clientsContainer) forConfig() (objs []*clientObject) {
|
||||
UseGlobalSettings: !cli.UseOwnSettings,
|
||||
FilteringEnabled: cli.FilteringEnabled,
|
||||
ParentalEnabled: cli.ParentalEnabled,
|
||||
SafeSearchConf: cli.safeSearchConf,
|
||||
SafeSearchConf: cli.SafeSearchConf,
|
||||
SafeBrowsingEnabled: cli.SafeBrowsingEnabled,
|
||||
UseGlobalBlockedServices: !cli.UseOwnBlockedServices,
|
||||
IgnoreQueryLog: cli.IgnoreQueryLog,
|
||||
@@ -435,7 +436,7 @@ func (clients *clientsContainer) clientOrArtificial(
|
||||
}
|
||||
|
||||
// find returns a shallow copy of the client if there is one found.
|
||||
func (clients *clientsContainer) find(id string) (c *persistentClient, ok bool) {
|
||||
func (clients *clientsContainer) find(id string) (c *client.Persistent, ok bool) {
|
||||
clients.lock.Lock()
|
||||
defer clients.lock.Unlock()
|
||||
|
||||
@@ -444,7 +445,7 @@ func (clients *clientsContainer) find(id string) (c *persistentClient, ok bool)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return c.shallowClone(), true
|
||||
return c.ShallowClone(), true
|
||||
}
|
||||
|
||||
// shouldCountClient is a wrapper around [clientsContainer.find] to make it a
|
||||
@@ -480,8 +481,8 @@ func (clients *clientsContainer) UpstreamConfigByID(
|
||||
c, ok := clients.findLocked(id)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
} else if c.upstreamConfig != nil {
|
||||
return c.upstreamConfig, nil
|
||||
} else if c.UpstreamConfig != nil {
|
||||
return c.UpstreamConfig, nil
|
||||
}
|
||||
|
||||
upstreams := stringutil.FilterOut(c.Upstreams, dnsforward.IsCommentOrEmpty)
|
||||
@@ -510,15 +511,15 @@ func (clients *clientsContainer) UpstreamConfigByID(
|
||||
int(c.UpstreamsCacheSize),
|
||||
config.DNS.EDNSClientSubnet.Enabled,
|
||||
)
|
||||
c.upstreamConfig = conf
|
||||
c.UpstreamConfig = conf
|
||||
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
// findLocked searches for a client by its ID. clients.lock is expected to be
|
||||
// locked.
|
||||
func (clients *clientsContainer) findLocked(id string) (c *persistentClient, ok bool) {
|
||||
c, ok = clients.idIndex[id]
|
||||
func (clients *clientsContainer) findLocked(id string) (c *client.Persistent, ok bool) {
|
||||
c, ok = clients.clientIndex.Find(id)
|
||||
if ok {
|
||||
return c, true
|
||||
}
|
||||
@@ -528,21 +529,13 @@ func (clients *clientsContainer) findLocked(id string) (c *persistentClient, ok
|
||||
return nil, false
|
||||
}
|
||||
|
||||
for _, c = range clients.list {
|
||||
for _, subnet := range c.Subnets {
|
||||
if subnet.Contains(ip) {
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(e.burkov): Iterate through clients.list only once.
|
||||
return clients.findDHCP(ip)
|
||||
}
|
||||
|
||||
// findDHCP searches for a client by its MAC, if the DHCP server is active and
|
||||
// there is such client. clients.lock is expected to be locked.
|
||||
func (clients *clientsContainer) findDHCP(ip netip.Addr) (c *persistentClient, ok bool) {
|
||||
func (clients *clientsContainer) findDHCP(ip netip.Addr) (c *client.Persistent, ok bool) {
|
||||
foundMAC := clients.dhcp.MACByIP(ip)
|
||||
if foundMAC == nil {
|
||||
return nil, false
|
||||
@@ -592,13 +585,13 @@ func (clients *clientsContainer) findRuntimeClient(ip netip.Addr) (rc *client.Ru
|
||||
}
|
||||
|
||||
// check validates the client. It also sorts the client tags.
|
||||
func (clients *clientsContainer) check(c *persistentClient) (err error) {
|
||||
func (clients *clientsContainer) check(c *client.Persistent) (err error) {
|
||||
switch {
|
||||
case c == nil:
|
||||
return errors.Error("client is nil")
|
||||
case c.Name == "":
|
||||
return errors.Error("invalid name")
|
||||
case c.idsLen() == 0:
|
||||
case c.IDsLen() == 0:
|
||||
return errors.Error("id required")
|
||||
default:
|
||||
// Go on.
|
||||
@@ -613,7 +606,7 @@ func (clients *clientsContainer) check(c *persistentClient) (err error) {
|
||||
// TODO(s.chzhen): Move to the constructor.
|
||||
slices.Sort(c.Tags)
|
||||
|
||||
err = dnsforward.ValidateUpstreams(c.Upstreams)
|
||||
_, err = proxy.ParseUpstreamsConfig(c.Upstreams, &upstream.Options{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid upstream servers: %w", err)
|
||||
}
|
||||
@@ -623,7 +616,7 @@ func (clients *clientsContainer) check(c *persistentClient) (err error) {
|
||||
|
||||
// add adds a new client object. ok is false if such client already exists or
|
||||
// if an error occurred.
|
||||
func (clients *clientsContainer) add(c *persistentClient) (ok bool, err error) {
|
||||
func (clients *clientsContainer) add(c *client.Persistent) (ok bool, err error) {
|
||||
err = clients.check(c)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -639,31 +632,26 @@ func (clients *clientsContainer) add(c *persistentClient) (ok bool, err error) {
|
||||
}
|
||||
|
||||
// check ID index
|
||||
ids := c.ids()
|
||||
for _, id := range ids {
|
||||
var c2 *persistentClient
|
||||
c2, ok = clients.idIndex[id]
|
||||
if ok {
|
||||
return false, fmt.Errorf("another client uses the same ID (%q): %q", id, c2.Name)
|
||||
}
|
||||
err = clients.clientIndex.Clashes(c)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
return false, err
|
||||
}
|
||||
|
||||
clients.addLocked(c)
|
||||
|
||||
log.Debug("clients: added %q: ID:%q [%d]", c.Name, ids, len(clients.list))
|
||||
log.Debug("clients: added %q: ID:%q [%d]", c.Name, c.IDs(), len(clients.list))
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// addLocked c to the indexes. clients.lock is expected to be locked.
|
||||
func (clients *clientsContainer) addLocked(c *persistentClient) {
|
||||
func (clients *clientsContainer) addLocked(c *client.Persistent) {
|
||||
// update Name index
|
||||
clients.list[c.Name] = c
|
||||
|
||||
// update ID index
|
||||
for _, id := range c.ids() {
|
||||
clients.idIndex[id] = c
|
||||
}
|
||||
clients.clientIndex.Add(c)
|
||||
}
|
||||
|
||||
// remove removes a client. ok is false if there is no such client.
|
||||
@@ -671,7 +659,7 @@ func (clients *clientsContainer) remove(name string) (ok bool) {
|
||||
clients.lock.Lock()
|
||||
defer clients.lock.Unlock()
|
||||
|
||||
var c *persistentClient
|
||||
var c *client.Persistent
|
||||
c, ok = clients.list[name]
|
||||
if !ok {
|
||||
return false
|
||||
@@ -684,8 +672,8 @@ func (clients *clientsContainer) remove(name string) (ok bool) {
|
||||
|
||||
// removeLocked removes c from the indexes. clients.lock is expected to be
|
||||
// locked.
|
||||
func (clients *clientsContainer) removeLocked(c *persistentClient) {
|
||||
if err := c.closeUpstreams(); err != nil {
|
||||
func (clients *clientsContainer) removeLocked(c *client.Persistent) {
|
||||
if err := c.CloseUpstreams(); err != nil {
|
||||
log.Error("client container: removing client %s: %s", c.Name, err)
|
||||
}
|
||||
|
||||
@@ -693,13 +681,11 @@ func (clients *clientsContainer) removeLocked(c *persistentClient) {
|
||||
delete(clients.list, c.Name)
|
||||
|
||||
// Update the ID index.
|
||||
for _, id := range c.ids() {
|
||||
delete(clients.idIndex, id)
|
||||
}
|
||||
clients.clientIndex.Delete(c)
|
||||
}
|
||||
|
||||
// update updates a client by its name.
|
||||
func (clients *clientsContainer) update(prev, c *persistentClient) (err error) {
|
||||
func (clients *clientsContainer) update(prev, c *client.Persistent) (err error) {
|
||||
err = clients.check(c)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
@@ -717,7 +703,7 @@ func (clients *clientsContainer) update(prev, c *persistentClient) (err error) {
|
||||
}
|
||||
}
|
||||
|
||||
if c.equalIDs(prev) {
|
||||
if c.EqualIDs(prev) {
|
||||
clients.removeLocked(prev)
|
||||
clients.addLocked(c)
|
||||
|
||||
@@ -725,11 +711,10 @@ func (clients *clientsContainer) update(prev, c *persistentClient) (err error) {
|
||||
}
|
||||
|
||||
// Check the ID index.
|
||||
for _, id := range c.ids() {
|
||||
existing, ok := clients.idIndex[id]
|
||||
if ok && existing != prev {
|
||||
return fmt.Errorf("id %q is used by client with name %q", id, existing.Name)
|
||||
}
|
||||
err = clients.clientIndex.Clashes(c)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
return err
|
||||
}
|
||||
|
||||
clients.removeLocked(prev)
|
||||
@@ -906,14 +891,14 @@ func (clients *clientsContainer) addFromSystemARP() {
|
||||
// the persistent clients.
|
||||
func (clients *clientsContainer) close() (err error) {
|
||||
persistent := maps.Values(clients.list)
|
||||
slices.SortFunc(persistent, func(a, b *persistentClient) (res int) {
|
||||
slices.SortFunc(persistent, func(a, b *client.Persistent) (res int) {
|
||||
return strings.Compare(a.Name, b.Name)
|
||||
})
|
||||
|
||||
var errs []error
|
||||
|
||||
for _, cli := range persistent {
|
||||
if err = cli.closeUpstreams(); err != nil {
|
||||
if err = cli.CloseUpstreams(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,8 +66,9 @@ func TestClients(t *testing.T) {
|
||||
cliIPv6 = netip.MustParseAddr("1:2:3::4")
|
||||
)
|
||||
|
||||
c := &persistentClient{
|
||||
c := &client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{cli1IP, cliIPv6},
|
||||
}
|
||||
|
||||
@@ -76,8 +77,9 @@ func TestClients(t *testing.T) {
|
||||
|
||||
assert.True(t, ok)
|
||||
|
||||
c = &persistentClient{
|
||||
c = &client.Persistent{
|
||||
Name: "client2",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{cli2IP},
|
||||
}
|
||||
|
||||
@@ -109,8 +111,9 @@ func TestClients(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("add_fail_name", func(t *testing.T) {
|
||||
ok, err := clients.add(&persistentClient{
|
||||
ok, err := clients.add(&client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{netip.MustParseAddr("1.2.3.5")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -118,16 +121,18 @@ func TestClients(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("add_fail_ip", func(t *testing.T) {
|
||||
ok, err := clients.add(&persistentClient{
|
||||
ok, err := clients.add(&client.Persistent{
|
||||
Name: "client3",
|
||||
UID: client.MustNewUID(),
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("update_fail_ip", func(t *testing.T) {
|
||||
err := clients.update(&persistentClient{Name: "client1"}, &persistentClient{
|
||||
err := clients.update(&client.Persistent{Name: "client1"}, &client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
@@ -143,8 +148,9 @@ func TestClients(t *testing.T) {
|
||||
prev, ok := clients.list["client1"]
|
||||
require.True(t, ok)
|
||||
|
||||
err := clients.update(prev, &persistentClient{
|
||||
err := clients.update(prev, &client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{cliNewIP},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -157,8 +163,9 @@ func TestClients(t *testing.T) {
|
||||
prev, ok = clients.list["client1"]
|
||||
require.True(t, ok)
|
||||
|
||||
err = clients.update(prev, &persistentClient{
|
||||
err = clients.update(prev, &client.Persistent{
|
||||
Name: "client1-renamed",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{cliNewIP},
|
||||
UseOwnSettings: true,
|
||||
})
|
||||
@@ -175,7 +182,7 @@ func TestClients(t *testing.T) {
|
||||
|
||||
assert.Nil(t, nilCli)
|
||||
|
||||
require.Len(t, c.ids(), 1)
|
||||
require.Len(t, c.IDs(), 1)
|
||||
|
||||
assert.Equal(t, cliNewIP, c.IPs[0])
|
||||
})
|
||||
@@ -258,8 +265,9 @@ func TestClientsWHOIS(t *testing.T) {
|
||||
t.Run("can't_set_manually-added", func(t *testing.T) {
|
||||
ip := netip.MustParseAddr("1.1.1.2")
|
||||
|
||||
ok, err := clients.add(&persistentClient{
|
||||
ok, err := clients.add(&client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{netip.MustParseAddr("1.1.1.2")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -280,8 +288,9 @@ func TestClientsAddExisting(t *testing.T) {
|
||||
ip := netip.MustParseAddr("1.1.1.1")
|
||||
|
||||
// Add a client.
|
||||
ok, err := clients.add(&persistentClient{
|
||||
ok, err := clients.add(&client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{ip, netip.MustParseAddr("1:2:3::4")},
|
||||
Subnets: []netip.Prefix{netip.MustParsePrefix("2.2.2.0/24")},
|
||||
MACs: []net.HardwareAddr{{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}},
|
||||
@@ -330,16 +339,18 @@ func TestClientsAddExisting(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// Add a new client with the same IP as for a client with MAC.
|
||||
ok, err := clients.add(&persistentClient{
|
||||
ok, err := clients.add(&client.Persistent{
|
||||
Name: "client2",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{ip},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ok)
|
||||
|
||||
// Add a new client with the IP from the first client's IP range.
|
||||
ok, err = clients.add(&persistentClient{
|
||||
ok, err = clients.add(&client.Persistent{
|
||||
Name: "client3",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{netip.MustParseAddr("2.2.2.2")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -351,8 +362,9 @@ func TestClientsCustomUpstream(t *testing.T) {
|
||||
clients := newClientsContainer(t)
|
||||
|
||||
// Add client with upstreams.
|
||||
ok, err := clients.add(&persistentClient{
|
||||
ok, err := clients.add(&client.Persistent{
|
||||
Name: "client1",
|
||||
UID: client.MustNewUID(),
|
||||
IPs: []netip.Addr{netip.MustParseAddr("1.1.1.1"), netip.MustParseAddr("1:2:3::4")},
|
||||
Upstreams: []string{
|
||||
"1.1.1.1",
|
||||
|
||||
@@ -131,9 +131,9 @@ func (clients *clientsContainer) handleGetClients(w http.ResponseWriter, r *http
|
||||
|
||||
// initPrev initializes the persistent client with the default or previous
|
||||
// client properties.
|
||||
func initPrev(cj clientJSON, prev *persistentClient) (c *persistentClient, err error) {
|
||||
func initPrev(cj clientJSON, prev *client.Persistent) (c *client.Persistent, err error) {
|
||||
var (
|
||||
uid UID
|
||||
uid client.UID
|
||||
ignoreQueryLog bool
|
||||
ignoreStatistics bool
|
||||
upsCacheEnabled bool
|
||||
@@ -166,14 +166,14 @@ func initPrev(cj clientJSON, prev *persistentClient) (c *persistentClient, err e
|
||||
return nil, fmt.Errorf("invalid blocked services: %w", err)
|
||||
}
|
||||
|
||||
if (uid == UID{}) {
|
||||
uid, err = NewUID()
|
||||
if (uid == client.UID{}) {
|
||||
uid, err = client.NewUID()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generating uid: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &persistentClient{
|
||||
return &client.Persistent{
|
||||
BlockedServices: svcs,
|
||||
UID: uid,
|
||||
IgnoreQueryLog: ignoreQueryLog,
|
||||
@@ -187,21 +187,21 @@ func initPrev(cj clientJSON, prev *persistentClient) (c *persistentClient, err e
|
||||
// errors.
|
||||
func (clients *clientsContainer) jsonToClient(
|
||||
cj clientJSON,
|
||||
prev *persistentClient,
|
||||
) (c *persistentClient, err error) {
|
||||
prev *client.Persistent,
|
||||
) (c *client.Persistent, err error) {
|
||||
c, err = initPrev(cj, prev)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.setIDs(cj.IDs)
|
||||
err = c.SetIDs(cj.IDs)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.safeSearchConf = copySafeSearch(cj.SafeSearchConf, cj.SafeSearchEnabled)
|
||||
c.SafeSearchConf = copySafeSearch(cj.SafeSearchConf, cj.SafeSearchEnabled)
|
||||
c.Name = cj.Name
|
||||
c.Tags = cj.Tags
|
||||
c.Upstreams = cj.Upstreams
|
||||
@@ -211,9 +211,9 @@ func (clients *clientsContainer) jsonToClient(
|
||||
c.SafeBrowsingEnabled = cj.SafeBrowsingEnabled
|
||||
c.UseOwnBlockedServices = !cj.UseGlobalBlockedServices
|
||||
|
||||
if c.safeSearchConf.Enabled {
|
||||
err = c.setSafeSearch(
|
||||
c.safeSearchConf,
|
||||
if c.SafeSearchConf.Enabled {
|
||||
err = c.SetSafeSearch(
|
||||
c.SafeSearchConf,
|
||||
clients.safeSearchCacheSize,
|
||||
clients.safeSearchCacheTTL,
|
||||
)
|
||||
@@ -258,7 +258,7 @@ func copySafeSearch(
|
||||
func copyBlockedServices(
|
||||
sch *schedule.Weekly,
|
||||
svcStrs []string,
|
||||
prev *persistentClient,
|
||||
prev *client.Persistent,
|
||||
) (svcs *filtering.BlockedServices, err error) {
|
||||
var weekly *schedule.Weekly
|
||||
if sch != nil {
|
||||
@@ -283,15 +283,15 @@ func copyBlockedServices(
|
||||
}
|
||||
|
||||
// clientToJSON converts persistent client object to JSON object.
|
||||
func clientToJSON(c *persistentClient) (cj *clientJSON) {
|
||||
func clientToJSON(c *client.Persistent) (cj *clientJSON) {
|
||||
// TODO(d.kolyshev): Remove after cleaning the deprecated
|
||||
// [clientJSON.SafeSearchEnabled] field.
|
||||
cloneVal := c.safeSearchConf
|
||||
cloneVal := c.SafeSearchConf
|
||||
safeSearchConf := &cloneVal
|
||||
|
||||
return &clientJSON{
|
||||
Name: c.Name,
|
||||
IDs: c.ids(),
|
||||
IDs: c.IDs(),
|
||||
Tags: c.Tags,
|
||||
UseGlobalSettings: !c.UseOwnSettings,
|
||||
FilteringEnabled: c.FilteringEnabled,
|
||||
@@ -397,7 +397,7 @@ func (clients *clientsContainer) handleUpdateClient(w http.ResponseWriter, r *ht
|
||||
return
|
||||
}
|
||||
|
||||
var prev *persistentClient
|
||||
var prev *client.Persistent
|
||||
var ok bool
|
||||
|
||||
func() {
|
||||
|
||||
@@ -232,6 +232,10 @@ type dnsConfig struct {
|
||||
|
||||
// ServePlainDNS defines if plain DNS is allowed for incoming requests.
|
||||
ServePlainDNS bool `yaml:"serve_plain_dns"`
|
||||
|
||||
// HostsFileEnabled defines whether to use information from the system hosts
|
||||
// file to resolve queries.
|
||||
HostsFileEnabled bool `yaml:"hostsfile_enabled"`
|
||||
}
|
||||
|
||||
type tlsConfigSettings struct {
|
||||
@@ -259,6 +263,10 @@ type tlsConfigSettings struct {
|
||||
}
|
||||
|
||||
type queryLogConfig struct {
|
||||
// DirPath is the custom directory for logs. If it's empty the default
|
||||
// directory will be used. See [homeContext.getDataDir].
|
||||
DirPath string `yaml:"dir_path"`
|
||||
|
||||
// Ignored is the list of host names, which should not be written to log.
|
||||
// "." is considered to be the root domain.
|
||||
Ignored []string `yaml:"ignored"`
|
||||
@@ -278,6 +286,10 @@ type queryLogConfig struct {
|
||||
}
|
||||
|
||||
type statsConfig struct {
|
||||
// DirPath is the custom directory for statistics. If it's empty the
|
||||
// default directory is used. See [homeContext.getDataDir].
|
||||
DirPath string `yaml:"dir_path"`
|
||||
|
||||
// Ignored is the list of host names, which should not be counted.
|
||||
Ignored []string `yaml:"ignored"`
|
||||
|
||||
@@ -341,9 +353,10 @@ var config = &configuration{
|
||||
// was later increased to 300 due to https://github.com/AdguardTeam/AdGuardHome/issues/2257
|
||||
MaxGoroutines: 300,
|
||||
},
|
||||
UpstreamTimeout: timeutil.Duration{Duration: dnsforward.DefaultTimeout},
|
||||
UsePrivateRDNS: true,
|
||||
ServePlainDNS: true,
|
||||
UpstreamTimeout: timeutil.Duration{Duration: dnsforward.DefaultTimeout},
|
||||
UsePrivateRDNS: true,
|
||||
ServePlainDNS: true,
|
||||
HostsFileEnabled: true,
|
||||
},
|
||||
TLS: tlsConfigSettings{
|
||||
PortHTTPS: defaultPortHTTPS,
|
||||
@@ -443,20 +456,25 @@ var config = &configuration{
|
||||
Theme: ThemeAuto,
|
||||
}
|
||||
|
||||
// getConfigFilename returns path to the current config file
|
||||
func (c *configuration) getConfigFilename() string {
|
||||
configFile, err := filepath.EvalSymlinks(Context.configFilename)
|
||||
// configFilePath returns the absolute path to the symlink-evaluated path to the
|
||||
// current config file.
|
||||
func configFilePath() (confPath string) {
|
||||
confPath, err := filepath.EvalSymlinks(Context.confFilePath)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
log.Error("unexpected error while config file path evaluation: %s", err)
|
||||
confPath = Context.confFilePath
|
||||
logFunc := log.Error
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
logFunc = log.Debug
|
||||
}
|
||||
configFile = Context.configFilename
|
||||
}
|
||||
if !filepath.IsAbs(configFile) {
|
||||
configFile = filepath.Join(Context.workDir, configFile)
|
||||
|
||||
logFunc("evaluating config path: %s; using %q", err, confPath)
|
||||
}
|
||||
|
||||
return configFile
|
||||
if !filepath.IsAbs(confPath) {
|
||||
confPath = filepath.Join(Context.workDir, confPath)
|
||||
}
|
||||
|
||||
return confPath
|
||||
}
|
||||
|
||||
// validateBindHosts returns error if any of binding hosts from configuration is
|
||||
@@ -497,7 +515,10 @@ func parseConfig() (err error) {
|
||||
// Don't wrap the error, because it's informative enough as is.
|
||||
return err
|
||||
} else if upgraded {
|
||||
err = maybe.WriteFile(config.getConfigFilename(), config.fileData, 0o644)
|
||||
confPath := configFilePath()
|
||||
log.Debug("writing config file %q after config upgrade", confPath)
|
||||
|
||||
err = maybe.WriteFile(confPath, config.fileData, 0o644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("writing new config: %w", err)
|
||||
}
|
||||
@@ -518,12 +539,8 @@ func parseConfig() (err error) {
|
||||
config.DNS.UpstreamTimeout = timeutil.Duration{Duration: dnsforward.DefaultTimeout}
|
||||
}
|
||||
|
||||
err = setContextTLSCipherIDs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
// Do not wrap the error because it's informative enough as is.
|
||||
return setContextTLSCipherIDs()
|
||||
}
|
||||
|
||||
// validateConfig returns error if the configuration is invalid.
|
||||
@@ -587,11 +604,11 @@ func readConfigFile() (fileData []byte, err error) {
|
||||
return config.fileData, nil
|
||||
}
|
||||
|
||||
name := config.getConfigFilename()
|
||||
log.Debug("reading config file: %s", name)
|
||||
confPath := configFilePath()
|
||||
log.Debug("reading config file %q", confPath)
|
||||
|
||||
// Do not wrap the error because it's informative enough as is.
|
||||
return os.ReadFile(name)
|
||||
return os.ReadFile(confPath)
|
||||
}
|
||||
|
||||
// Saves configuration to the YAML file and also saves the user filter contents to a file
|
||||
@@ -655,8 +672,8 @@ func (c *configuration) write() (err error) {
|
||||
|
||||
config.Clients.Persistent = Context.clients.forConfig()
|
||||
|
||||
configFile := config.getConfigFilename()
|
||||
log.Debug("writing config file %q", configFile)
|
||||
confPath := configFilePath()
|
||||
log.Debug("writing config file %q", confPath)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
enc := yaml.NewEncoder(buf)
|
||||
@@ -667,7 +684,7 @@ func (c *configuration) write() (err error) {
|
||||
return fmt.Errorf("generating config file: %w", err)
|
||||
}
|
||||
|
||||
err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
|
||||
err = maybe.WriteFile(confPath, buf.Bytes(), 0o644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("writing config file: %w", err)
|
||||
}
|
||||
|
||||
@@ -144,10 +144,7 @@ func handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
// Make sure that we don't send negative numbers to the frontend,
|
||||
// since enough time might have passed to make the difference less
|
||||
// than zero.
|
||||
protectionDisabledDuration = max(
|
||||
0,
|
||||
time.Until(*protectionDisabledUntil).Milliseconds(),
|
||||
)
|
||||
protectionDisabledDuration = max(0, time.Until(*protectionDisabledUntil).Milliseconds())
|
||||
}
|
||||
|
||||
resp = statusResponse{
|
||||
|
||||
@@ -46,12 +46,15 @@ func onConfigModified() {
|
||||
// server and initializes it at last. It also must not be called unless
|
||||
// [config] and [Context] are initialized.
|
||||
func initDNS() (err error) {
|
||||
baseDir := Context.getDataDir()
|
||||
|
||||
anonymizer := config.anonymizer()
|
||||
|
||||
statsDir, querylogDir, err := checkStatsAndQuerylogDirs(&Context, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
statsConf := stats.Config{
|
||||
Filename: filepath.Join(baseDir, "stats.db"),
|
||||
Filename: filepath.Join(statsDir, "stats.db"),
|
||||
Limit: config.Stats.Interval.Duration,
|
||||
ConfigModified: onConfigModified,
|
||||
HTTPRegister: httpRegister,
|
||||
@@ -75,7 +78,7 @@ func initDNS() (err error) {
|
||||
ConfigModified: onConfigModified,
|
||||
HTTPRegister: httpRegister,
|
||||
FindClient: Context.clients.findMultiple,
|
||||
BaseDir: baseDir,
|
||||
BaseDir: querylogDir,
|
||||
AnonymizeClientIP: config.DNS.AnonymizeClientIP,
|
||||
RotationIvl: config.QueryLog.Interval.Duration,
|
||||
MemSize: config.QueryLog.MemSize,
|
||||
@@ -424,7 +427,7 @@ func applyAdditionalFiltering(clientIP netip.Addr, clientID string, setts *filte
|
||||
}
|
||||
|
||||
setts.FilteringEnabled = c.FilteringEnabled
|
||||
setts.SafeSearchEnabled = c.safeSearchConf.Enabled
|
||||
setts.SafeSearchEnabled = c.SafeSearchConf.Enabled
|
||||
setts.ClientSafeSearch = c.SafeSearch
|
||||
setts.SafeBrowsingEnabled = c.SafeBrowsingEnabled
|
||||
setts.ParentalEnabled = c.ParentalEnabled
|
||||
@@ -545,3 +548,50 @@ func (r safeSearchResolver) LookupIP(
|
||||
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
// checkStatsAndQuerylogDirs checks and returns directory paths to store
|
||||
// statistics and query log.
|
||||
func checkStatsAndQuerylogDirs(
|
||||
ctx *homeContext,
|
||||
conf *configuration,
|
||||
) (statsDir, querylogDir string, err error) {
|
||||
baseDir := ctx.getDataDir()
|
||||
|
||||
statsDir = conf.Stats.DirPath
|
||||
if statsDir == "" {
|
||||
statsDir = baseDir
|
||||
} else {
|
||||
err = checkDir(statsDir)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("statistics: custom directory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
querylogDir = conf.QueryLog.DirPath
|
||||
if querylogDir == "" {
|
||||
querylogDir = baseDir
|
||||
} else {
|
||||
err = checkDir(querylogDir)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("querylog: custom directory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return statsDir, querylogDir, nil
|
||||
}
|
||||
|
||||
// checkDir checks if the path is a directory. It's used to check for
|
||||
// misconfiguration at startup.
|
||||
func checkDir(path string) (err error) {
|
||||
var fi os.FileInfo
|
||||
if fi, err = os.Stat(path); err != nil {
|
||||
// Don't wrap the error, since it's informative enough as is.
|
||||
return err
|
||||
}
|
||||
|
||||
if !fi.IsDir() {
|
||||
return fmt.Errorf("%q is not a directory", path)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/client"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/schedule"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -12,6 +13,19 @@ import (
|
||||
|
||||
var testIPv4 = netip.AddrFrom4([4]byte{1, 2, 3, 4})
|
||||
|
||||
// newIDIndex is a helper function that returns a client index filled with
|
||||
// persistent clients from the m. It also generates a UID for each client.
|
||||
func newIDIndex(m []*client.Persistent) (ci *client.Index) {
|
||||
ci = client.NewIndex()
|
||||
|
||||
for _, c := range m {
|
||||
c.UID = client.MustNewUID()
|
||||
ci.Add(c)
|
||||
}
|
||||
|
||||
return ci
|
||||
}
|
||||
|
||||
func TestApplyAdditionalFiltering(t *testing.T) {
|
||||
var err error
|
||||
|
||||
@@ -22,29 +36,28 @@ func TestApplyAdditionalFiltering(t *testing.T) {
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
Context.clients.idIndex = map[string]*persistentClient{
|
||||
"default": {
|
||||
UseOwnSettings: false,
|
||||
safeSearchConf: filtering.SafeSearchConfig{Enabled: false},
|
||||
FilteringEnabled: false,
|
||||
SafeBrowsingEnabled: false,
|
||||
ParentalEnabled: false,
|
||||
},
|
||||
"custom_filtering": {
|
||||
UseOwnSettings: true,
|
||||
safeSearchConf: filtering.SafeSearchConfig{Enabled: true},
|
||||
FilteringEnabled: true,
|
||||
SafeBrowsingEnabled: true,
|
||||
ParentalEnabled: true,
|
||||
},
|
||||
"partial_custom_filtering": {
|
||||
UseOwnSettings: true,
|
||||
safeSearchConf: filtering.SafeSearchConfig{Enabled: true},
|
||||
FilteringEnabled: true,
|
||||
SafeBrowsingEnabled: false,
|
||||
ParentalEnabled: false,
|
||||
},
|
||||
}
|
||||
Context.clients.clientIndex = newIDIndex([]*client.Persistent{{
|
||||
ClientIDs: []string{"default"},
|
||||
UseOwnSettings: false,
|
||||
SafeSearchConf: filtering.SafeSearchConfig{Enabled: false},
|
||||
FilteringEnabled: false,
|
||||
SafeBrowsingEnabled: false,
|
||||
ParentalEnabled: false,
|
||||
}, {
|
||||
ClientIDs: []string{"custom_filtering"},
|
||||
UseOwnSettings: true,
|
||||
SafeSearchConf: filtering.SafeSearchConfig{Enabled: true},
|
||||
FilteringEnabled: true,
|
||||
SafeBrowsingEnabled: true,
|
||||
ParentalEnabled: true,
|
||||
}, {
|
||||
ClientIDs: []string{"partial_custom_filtering"},
|
||||
UseOwnSettings: true,
|
||||
SafeSearchConf: filtering.SafeSearchConfig{Enabled: true},
|
||||
FilteringEnabled: true,
|
||||
SafeBrowsingEnabled: false,
|
||||
ParentalEnabled: false,
|
||||
}})
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -108,38 +121,37 @@ func TestApplyAdditionalFiltering_blockedServices(t *testing.T) {
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
Context.clients.idIndex = map[string]*persistentClient{
|
||||
"default": {
|
||||
UseOwnBlockedServices: false,
|
||||
Context.clients.clientIndex = newIDIndex([]*client.Persistent{{
|
||||
ClientIDs: []string{"default"},
|
||||
UseOwnBlockedServices: false,
|
||||
}, {
|
||||
ClientIDs: []string{"no_services"},
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.EmptyWeekly(),
|
||||
},
|
||||
"no_services": {
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.EmptyWeekly(),
|
||||
},
|
||||
UseOwnBlockedServices: true,
|
||||
UseOwnBlockedServices: true,
|
||||
}, {
|
||||
ClientIDs: []string{"services"},
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.EmptyWeekly(),
|
||||
IDs: clientBlockedServices,
|
||||
},
|
||||
"services": {
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.EmptyWeekly(),
|
||||
IDs: clientBlockedServices,
|
||||
},
|
||||
UseOwnBlockedServices: true,
|
||||
UseOwnBlockedServices: true,
|
||||
}, {
|
||||
ClientIDs: []string{"invalid_services"},
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.EmptyWeekly(),
|
||||
IDs: invalidBlockedServices,
|
||||
},
|
||||
"invalid_services": {
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.EmptyWeekly(),
|
||||
IDs: invalidBlockedServices,
|
||||
},
|
||||
UseOwnBlockedServices: true,
|
||||
UseOwnBlockedServices: true,
|
||||
}, {
|
||||
ClientIDs: []string{"allow_all"},
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.FullWeekly(),
|
||||
IDs: clientBlockedServices,
|
||||
},
|
||||
"allow_all": {
|
||||
BlockedServices: &filtering.BlockedServices{
|
||||
Schedule: schedule.FullWeekly(),
|
||||
IDs: clientBlockedServices,
|
||||
},
|
||||
UseOwnBlockedServices: true,
|
||||
},
|
||||
}
|
||||
UseOwnBlockedServices: true,
|
||||
}})
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
@@ -39,8 +40,6 @@ import (
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/netutil"
|
||||
"github.com/AdguardTeam/golibs/osutil"
|
||||
"github.com/AdguardTeam/golibs/stringutil"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
// Global context
|
||||
@@ -68,11 +67,14 @@ type homeContext struct {
|
||||
// Runtime properties
|
||||
// --
|
||||
|
||||
configFilename string // Config filename (can be overridden via the command line arguments)
|
||||
workDir string // Location of our directory, used to protect against CWD being somewhere else
|
||||
pidFileName string // PID file name. Empty if no PID file was created.
|
||||
controlLock sync.Mutex
|
||||
tlsRoots *x509.CertPool // list of root CAs for TLSv1.2
|
||||
// confFilePath is the configuration file path as set by default or from the
|
||||
// command-line options.
|
||||
confFilePath string
|
||||
|
||||
workDir string // Location of our directory, used to protect against CWD being somewhere else
|
||||
pidFileName string // PID file name. Empty if no PID file was created.
|
||||
controlLock sync.Mutex
|
||||
tlsRoots *x509.CertPool // list of root CAs for TLSv1.2
|
||||
|
||||
// tlsCipherIDs are the ID of the cipher suites that AdGuard Home must use.
|
||||
tlsCipherIDs []uint16
|
||||
@@ -250,7 +252,7 @@ func setupHostsContainer() (err error) {
|
||||
return errors.Join(fmt.Errorf("initializing hosts container: %w", err), closeErr)
|
||||
}
|
||||
|
||||
return nil
|
||||
return hostsWatcher.Start()
|
||||
}
|
||||
|
||||
// setupOpts sets up command-line options.
|
||||
@@ -361,7 +363,7 @@ func setupDNSFilteringConf(conf *filtering.Config) (err error) {
|
||||
|
||||
conf.EtcHosts = Context.etcHosts
|
||||
// TODO(s.chzhen): Use empty interface.
|
||||
if Context.etcHosts == nil {
|
||||
if Context.etcHosts == nil || !config.DNS.HostsFileEnabled {
|
||||
conf.EtcHosts = nil
|
||||
}
|
||||
|
||||
@@ -575,6 +577,9 @@ func run(opts options, clientBuildFS fs.FS, done chan struct{}) {
|
||||
Path: path.Join("adguardhome", version.Channel(), "version.json"),
|
||||
}
|
||||
|
||||
confPath := configFilePath()
|
||||
log.Debug("using config path %q for updater", confPath)
|
||||
|
||||
upd := updater.NewUpdater(&updater.Config{
|
||||
Client: config.Filtering.HTTPClient,
|
||||
Version: version.Version(),
|
||||
@@ -584,7 +589,7 @@ func run(opts options, clientBuildFS fs.FS, done chan struct{}) {
|
||||
GOARM: version.GOARM(),
|
||||
GOMIPS: version.GOMIPS(),
|
||||
WorkDir: Context.workDir,
|
||||
ConfName: config.getConfigFilename(),
|
||||
ConfName: confPath,
|
||||
ExecPath: execPath,
|
||||
VersionCheckURL: u.String(),
|
||||
})
|
||||
@@ -748,7 +753,16 @@ func writePIDFile(fn string) bool {
|
||||
// initConfigFilename sets up context config file path. This file path can be
|
||||
// overridden by command-line arguments, or is set to default.
|
||||
func initConfigFilename(opts options) {
|
||||
Context.configFilename = stringutil.Coalesce(opts.confFilename, "AdGuardHome.yaml")
|
||||
confPath := opts.confFilename
|
||||
if confPath == "" {
|
||||
Context.confFilePath = "AdGuardHome.yaml"
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Debug("config path overridden to %q from cmdline", confPath)
|
||||
|
||||
Context.confFilePath = confPath
|
||||
}
|
||||
|
||||
// initWorkingDir initializes the workDir. If no command-line arguments are
|
||||
@@ -906,16 +920,23 @@ func printHTTPAddresses(proto string) {
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------
|
||||
// first run / install
|
||||
// -------------------
|
||||
func detectFirstRun() bool {
|
||||
configfile := Context.configFilename
|
||||
if !filepath.IsAbs(configfile) {
|
||||
configfile = filepath.Join(Context.workDir, Context.configFilename)
|
||||
// detectFirstRun returns true if this is the first run of AdGuard Home.
|
||||
func detectFirstRun() (ok bool) {
|
||||
confPath := Context.confFilePath
|
||||
if !filepath.IsAbs(confPath) {
|
||||
confPath = filepath.Join(Context.workDir, Context.confFilePath)
|
||||
}
|
||||
_, err := os.Stat(configfile)
|
||||
return errors.Is(err, os.ErrNotExist)
|
||||
|
||||
_, err := os.Stat(confPath)
|
||||
if err == nil {
|
||||
return false
|
||||
} else if errors.Is(err, os.ErrNotExist) {
|
||||
return true
|
||||
}
|
||||
|
||||
log.Error("detecting first run: %s; considering first run", err)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// jsonError is a generic JSON error response.
|
||||
|
||||
@@ -75,6 +75,8 @@ func getLogSettings(opts options) (ls *logSettings) {
|
||||
if opts.verbose {
|
||||
ls.Verbose = true
|
||||
}
|
||||
|
||||
// TODO(a.garipov): Use cmp.Or in Go 1.22.
|
||||
ls.File = stringutil.Coalesce(opts.logFile, ls.File)
|
||||
|
||||
if opts.runningAsService && ls.File == "" && runtime.GOOS == "windows" {
|
||||
|
||||
@@ -270,15 +270,17 @@ var cmdLineOpts = []cmdLineOpt{{
|
||||
log.Info(
|
||||
"warning: --no-etc-hosts flag is deprecated " +
|
||||
"and will be removed in the future versions; " +
|
||||
"set clients.runtime_sources.hosts in the configuration file to false instead",
|
||||
"set clients.runtime_sources.hosts and dns.hostsfile_enabled " +
|
||||
"in the configuration file to false instead",
|
||||
)
|
||||
|
||||
return nil, nil
|
||||
},
|
||||
serialize: func(o options) (val string, ok bool) { return "", o.noEtcHosts },
|
||||
description: "Deprecated: use clients.runtime_sources.hosts instead. Do not use the OS-provided hosts.",
|
||||
longName: "no-etc-hosts",
|
||||
shortName: "",
|
||||
serialize: func(o options) (val string, ok bool) { return "", o.noEtcHosts },
|
||||
description: "Deprecated: use clients.runtime_sources.hosts and dns.hostsfile_enabled " +
|
||||
"instead. Do not use the OS-provided hosts.",
|
||||
longName: "no-etc-hosts",
|
||||
shortName: "",
|
||||
}, {
|
||||
updateWithValue: nil,
|
||||
updateNoValue: func(o options) (options, error) { o.localFrontend = true; return o, nil },
|
||||
|
||||
@@ -227,12 +227,15 @@ func handleServiceControlAction(
|
||||
runOpts := opts
|
||||
runOpts.serviceControlAction = "run"
|
||||
|
||||
args := optsToArgs(runOpts)
|
||||
log.Debug("service: using args %q", args)
|
||||
|
||||
svcConfig := &service.Config{
|
||||
Name: serviceName,
|
||||
DisplayName: serviceDisplayName,
|
||||
Description: serviceDescription,
|
||||
WorkingDirectory: pwd,
|
||||
Arguments: optsToArgs(runOpts),
|
||||
Arguments: args,
|
||||
}
|
||||
configureService(svcConfig)
|
||||
|
||||
|
||||
@@ -704,9 +704,9 @@ const (
|
||||
keyTypeRSA = "RSA"
|
||||
)
|
||||
|
||||
// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
|
||||
// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
|
||||
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
|
||||
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
|
||||
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
|
||||
//
|
||||
// TODO(a.garipov): Find out if this version of parsePrivateKey from the stdlib
|
||||
// is actually necessary.
|
||||
|
||||
Reference in New Issue
Block a user