Skip to content

Commit

Permalink
home: persistent client ids
Browse files Browse the repository at this point in the history
  • Loading branch information
schzhn committed Dec 29, 2023
1 parent 94d437d commit 8b295bf
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 83 deletions.
79 changes: 75 additions & 4 deletions internal/home/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@ 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/stringutil"
"github.com/google/uuid"
"golang.org/x/exp/slices"
)

// UID is the type for the unique IDs of persistent clients.
Expand Down Expand Up @@ -56,10 +62,14 @@ type persistentClient struct {

Name string

IDs []string
Tags []string
Upstreams []string

IPs []netip.Addr
Subnets []netip.Prefix
MACs []net.HardwareAddr
ClientIDs []string

// UID is the unique identifier of the persistent client.
UID UID

Expand All @@ -75,16 +85,77 @@ type persistentClient struct {
IgnoreStatistics bool
}

// ShallowClone returns a deep copy of the client, except upstreamConfig,
// parseIDs parses a list of strings into typed fields.
func (c *persistentClient) parseIDs(ids []string) (err error) {
for _, id := range ids {
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)

continue
}

var subnet netip.Prefix
if subnet, err = netip.ParsePrefix(id); err == nil {
c.Subnets = append(c.Subnets, subnet)

continue
}

var mac net.HardwareAddr
if mac, err = net.ParseMAC(id); err == nil {
c.MACs = append(c.MACs, mac)

continue
}

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.
func (c *persistentClient) ids() (ids []string) {
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...)
}

// shallowClone returns a deep copy of the client, except upstreamConfig,
// safeSearchConf, SafeSearch fields, because it's difficult to copy them.
func (c *persistentClient) ShallowClone() (sh *persistentClient) {
func (c *persistentClient) shallowClone() (sh *persistentClient) {
clone := *c

clone.BlockedServices = c.BlockedServices.Clone()
clone.IDs = stringutil.CloneSlice(c.IDs)
clone.Tags = stringutil.CloneSlice(c.Tags)
clone.Upstreams = stringutil.CloneSlice(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
}

Expand Down
79 changes: 17 additions & 62 deletions internal/home/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,6 @@ func (o *clientObject) toPersistent(
cli = &persistentClient{
Name: o.Name,

IDs: o.IDs,
Upstreams: o.Upstreams,

UID: o.UID,
Expand All @@ -235,6 +234,11 @@ func (o *clientObject) toPersistent(
UpstreamsCacheSize: o.UpstreamsCacheSize,
}

err = cli.parseIDs(o.IDs)
if err != nil {
return nil, fmt.Errorf("parsing ids: %w", err)
}

if (cli.UID == UID{}) {
cli.UID, err = NewUID()
if err != nil {
Expand Down Expand Up @@ -310,7 +314,7 @@ func (clients *clientsContainer) forConfig() (objs []*clientObject) {

BlockedServices: cli.BlockedServices.Clone(),

IDs: stringutil.CloneSlice(cli.IDs),
IDs: stringutil.CloneSlice(cli.ids()),
Tags: stringutil.CloneSlice(cli.Tags),
Upstreams: stringutil.CloneSlice(cli.Upstreams),

Expand Down Expand Up @@ -449,7 +453,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
Expand Down Expand Up @@ -534,13 +538,7 @@ func (clients *clientsContainer) findLocked(id string) (c *persistentClient, ok
}

for _, c = range clients.list {
for _, id := range c.IDs {
var subnet netip.Prefix
subnet, err = netip.ParsePrefix(id)
if err != nil {
continue
}

for _, subnet := range c.Subnets {
if subnet.Contains(ip) {
return c, true
}
Expand All @@ -560,12 +558,7 @@ func (clients *clientsContainer) findDHCP(ip netip.Addr) (c *persistentClient, o
}

for _, c = range clients.list {
for _, id := range c.IDs {
mac, err := net.ParseMAC(id)
if err != nil {
continue
}

for _, mac := range c.MACs {
if bytes.Equal(mac, foundMAC) {
return c, true
}
Expand Down Expand Up @@ -615,22 +608,12 @@ func (clients *clientsContainer) check(c *persistentClient) (err error) {
return errors.Error("client is nil")
case c.Name == "":
return errors.Error("invalid name")
case len(c.IDs) == 0:
case len(c.IPs)+len(c.Subnets)+len(c.MACs)+len(c.ClientIDs) == 0:
return errors.Error("id required")
default:
// Go on.
}

for i, id := range c.IDs {
var norm string
norm, err = normalizeClientIdentifier(id)
if err != nil {
return fmt.Errorf("client at index %d: %w", i, err)
}

c.IDs[i] = norm
}

for _, t := range c.Tags {
if !clients.allTags.Has(t) {
return fmt.Errorf("invalid tag: %q", t)
Expand All @@ -647,35 +630,6 @@ func (clients *clientsContainer) check(c *persistentClient) (err error) {
return nil
}

// normalizeClientIdentifier returns a normalized version of idStr. If idStr
// cannot be normalized, it returns an error.
func normalizeClientIdentifier(idStr string) (norm string, err error) {
if idStr == "" {
return "", errors.Error("clientid is empty")
}

var ip netip.Addr
if ip, err = netip.ParseAddr(idStr); err == nil {
return ip.String(), nil
}

var subnet netip.Prefix
if subnet, err = netip.ParsePrefix(idStr); err == nil {
return subnet.String(), nil
}

var mac net.HardwareAddr
if mac, err = net.ParseMAC(idStr); err == nil {
return mac.String(), nil
}

if err = dnsforward.ValidateClientID(idStr); err == nil {
return strings.ToLower(idStr), nil
}

return "", fmt.Errorf("bad client identifier %q", idStr)
}

// 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) {
Expand All @@ -694,7 +648,7 @@ func (clients *clientsContainer) add(c *persistentClient) (ok bool, err error) {
}

// check ID index
for _, id := range c.IDs {
for _, id := range c.ids() {
var c2 *persistentClient
c2, ok = clients.idIndex[id]
if ok {
Expand All @@ -704,7 +658,7 @@ func (clients *clientsContainer) add(c *persistentClient) (ok bool, err error) {

clients.addLocked(c)

log.Debug("clients: added %q: ID:%q [%d]", c.Name, c.IDs, len(clients.list))
log.Debug("clients: added %q: ID:%q [%d]", c.Name, c.ids(), len(clients.list))

return true, nil
}
Expand All @@ -715,7 +669,7 @@ func (clients *clientsContainer) addLocked(c *persistentClient) {
clients.list[c.Name] = c

// update ID index
for _, id := range c.IDs {
for _, id := range c.ids() {
clients.idIndex[id] = c
}
}
Expand Down Expand Up @@ -747,7 +701,7 @@ func (clients *clientsContainer) removeLocked(c *persistentClient) {
delete(clients.list, c.Name)

// Update the ID index.
for _, id := range c.IDs {
for _, id := range c.ids() {
delete(clients.idIndex, id)
}
}
Expand All @@ -772,8 +726,9 @@ func (clients *clientsContainer) update(prev, c *persistentClient) (err error) {
}

// Check the ID index.
if !slices.Equal(prev.IDs, c.IDs) {
for _, id := range c.IDs {
ids := c.ids()
if !slices.Equal(prev.ids(), ids) {
for _, id := range 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)
Expand Down
Loading

0 comments on commit 8b295bf

Please sign in to comment.