2021-10-14 16:39:21 +00:00
|
|
|
package aghnet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
|
|
|
"net"
|
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
|
|
|
"github.com/AdguardTeam/golibs/errors"
|
|
|
|
"github.com/AdguardTeam/golibs/log"
|
|
|
|
"github.com/AdguardTeam/golibs/netutil"
|
|
|
|
"github.com/AdguardTeam/golibs/stringutil"
|
|
|
|
"github.com/AdguardTeam/urlfilter"
|
|
|
|
"github.com/AdguardTeam/urlfilter/filterlist"
|
2021-11-16 13:16:38 +00:00
|
|
|
"github.com/AdguardTeam/urlfilter/rules"
|
2021-10-14 16:39:21 +00:00
|
|
|
"github.com/miekg/dns"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DefaultHostsPaths returns the slice of paths default for the operating system
|
|
|
|
// to files and directories which are containing the hosts database. The result
|
2021-11-16 13:16:38 +00:00
|
|
|
// is intended to be used within fs.FS so the initial slash is omitted.
|
2021-10-14 16:39:21 +00:00
|
|
|
func DefaultHostsPaths() (paths []string) {
|
|
|
|
return defaultHostsPaths()
|
|
|
|
}
|
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
// requestMatcher combines the logic for matching requests and translating the
|
|
|
|
// appropriate rules.
|
|
|
|
type requestMatcher struct {
|
|
|
|
// stateLock protects all the fields of requestMatcher.
|
|
|
|
stateLock *sync.RWMutex
|
|
|
|
|
|
|
|
// rulesStrg stores the rules obtained from the hosts' file.
|
|
|
|
rulesStrg *filterlist.RuleStorage
|
|
|
|
// engine serves rulesStrg.
|
|
|
|
engine *urlfilter.DNSEngine
|
|
|
|
|
|
|
|
// translator maps generated $dnsrewrite rules into hosts-syntax rules.
|
|
|
|
//
|
|
|
|
// TODO(e.burkov): Store the filename from which the rule was parsed.
|
|
|
|
translator map[string]string
|
|
|
|
}
|
|
|
|
|
|
|
|
// MatchRequest processes the request rewriting hostnames and addresses read
|
|
|
|
// from the operating system's hosts files.
|
|
|
|
//
|
|
|
|
// res is nil for any request having not an A/AAAA or PTR type. Results
|
|
|
|
// containing CNAME information may be queried again with the same question type
|
|
|
|
// and the returned CNAME for Host field of request. Results are guaranteed to
|
|
|
|
// be direct, i.e. any returned CNAME resolves into actual address like an alias
|
|
|
|
// in hosts does, see man hosts (5).
|
|
|
|
//
|
|
|
|
// It's safe for concurrent use.
|
|
|
|
func (rm *requestMatcher) MatchRequest(
|
|
|
|
req urlfilter.DNSRequest,
|
|
|
|
) (res *urlfilter.DNSResult, ok bool) {
|
|
|
|
switch req.DNSType {
|
|
|
|
case dns.TypeA, dns.TypeAAAA, dns.TypePTR:
|
|
|
|
log.Debug("%s: handling the request", hostsContainerPref)
|
|
|
|
default:
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
rm.stateLock.RLock()
|
|
|
|
defer rm.stateLock.RUnlock()
|
|
|
|
|
|
|
|
return rm.engine.MatchRequest(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Translate returns the source hosts-syntax rule for the generated dnsrewrite
|
2022-01-12 09:14:59 +00:00
|
|
|
// rule or an empty string if the last doesn't exist. The returned rules are in
|
|
|
|
// a processed format like:
|
|
|
|
//
|
|
|
|
// ip host1 host2 ...
|
|
|
|
//
|
2021-11-23 15:01:48 +00:00
|
|
|
func (rm *requestMatcher) Translate(rule string) (hostRule string) {
|
|
|
|
rm.stateLock.RLock()
|
|
|
|
defer rm.stateLock.RUnlock()
|
|
|
|
|
|
|
|
return rm.translator[rule]
|
|
|
|
}
|
|
|
|
|
|
|
|
// resetEng updates container's engine and the translation map.
|
|
|
|
func (rm *requestMatcher) resetEng(rulesStrg *filterlist.RuleStorage, tr map[string]string) {
|
|
|
|
rm.stateLock.Lock()
|
|
|
|
defer rm.stateLock.Unlock()
|
|
|
|
|
|
|
|
rm.rulesStrg = rulesStrg
|
|
|
|
rm.engine = urlfilter.NewDNSEngine(rm.rulesStrg)
|
|
|
|
|
|
|
|
rm.translator = tr
|
|
|
|
}
|
|
|
|
|
2021-10-14 16:39:21 +00:00
|
|
|
// hostsContainerPref is a prefix for logging and wrapping errors in
|
|
|
|
// HostsContainer's methods.
|
|
|
|
const hostsContainerPref = "hosts container"
|
|
|
|
|
|
|
|
// HostsContainer stores the relevant hosts database provided by the OS and
|
|
|
|
// processes both A/AAAA and PTR DNS requests for those.
|
|
|
|
type HostsContainer struct {
|
2021-11-23 15:01:48 +00:00
|
|
|
// requestMatcher matches the requests and translates the rules. It's
|
|
|
|
// embedded to implement MatchRequest and Translate for *HostsContainer.
|
2021-12-16 12:58:54 +00:00
|
|
|
//
|
|
|
|
// TODO(a.garipov, e.burkov): Consider fully merging into HostsContainer.
|
2021-11-23 15:01:48 +00:00
|
|
|
requestMatcher
|
2021-10-14 16:39:21 +00:00
|
|
|
|
2021-11-17 14:21:10 +00:00
|
|
|
// done is the channel to sign closing the container.
|
|
|
|
done chan struct{}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
// updates is the channel for receiving updated hosts.
|
2021-10-14 16:39:21 +00:00
|
|
|
updates chan *netutil.IPMap
|
2021-12-16 12:58:54 +00:00
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
// last is the set of hosts that was cached within last detected change.
|
|
|
|
last *netutil.IPMap
|
2021-10-14 16:39:21 +00:00
|
|
|
|
|
|
|
// fsys is the working file system to read hosts files from.
|
|
|
|
fsys fs.FS
|
|
|
|
|
|
|
|
// w tracks the changes in specified files and directories.
|
|
|
|
w aghos.FSWatcher
|
2021-12-16 12:58:54 +00:00
|
|
|
|
2021-10-14 16:39:21 +00:00
|
|
|
// patterns stores specified paths in the fs.Glob-compatible form.
|
|
|
|
patterns []string
|
2021-12-16 12:58:54 +00:00
|
|
|
|
|
|
|
// listID is the identifier for the list of generated rules.
|
|
|
|
listID int
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
2021-11-17 14:21:10 +00:00
|
|
|
// ErrNoHostsPaths is returned when there are no valid paths to watch passed to
|
|
|
|
// the HostsContainer.
|
|
|
|
const ErrNoHostsPaths errors.Error = "no valid paths to hosts files provided"
|
2021-10-14 16:39:21 +00:00
|
|
|
|
|
|
|
// NewHostsContainer creates a container of hosts, that watches the paths with
|
2021-11-26 15:25:43 +00:00
|
|
|
// w. listID is used as an identifier of the underlying rules list. paths
|
|
|
|
// shouldn't be empty and each of paths should locate either a file or a
|
|
|
|
// directory in fsys. fsys and w must be non-nil.
|
2021-10-14 16:39:21 +00:00
|
|
|
func NewHostsContainer(
|
2021-11-26 15:25:43 +00:00
|
|
|
listID int,
|
2021-10-14 16:39:21 +00:00
|
|
|
fsys fs.FS,
|
|
|
|
w aghos.FSWatcher,
|
|
|
|
paths ...string,
|
|
|
|
) (hc *HostsContainer, err error) {
|
|
|
|
defer func() { err = errors.Annotate(err, "%s: %w", hostsContainerPref) }()
|
|
|
|
|
|
|
|
if len(paths) == 0 {
|
2021-11-17 14:21:10 +00:00
|
|
|
return nil, ErrNoHostsPaths
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
2021-11-17 14:21:10 +00:00
|
|
|
var patterns []string
|
|
|
|
patterns, err = pathsToPatterns(fsys, paths)
|
2021-10-14 16:39:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-11-17 14:21:10 +00:00
|
|
|
} else if len(patterns) == 0 {
|
|
|
|
return nil, ErrNoHostsPaths
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
hc = &HostsContainer{
|
2021-11-23 15:01:48 +00:00
|
|
|
requestMatcher: requestMatcher{
|
|
|
|
stateLock: &sync.RWMutex{},
|
|
|
|
},
|
2021-11-26 15:25:43 +00:00
|
|
|
listID: listID,
|
2021-11-17 14:21:10 +00:00
|
|
|
done: make(chan struct{}, 1),
|
2021-10-14 16:39:21 +00:00
|
|
|
updates: make(chan *netutil.IPMap, 1),
|
|
|
|
fsys: fsys,
|
|
|
|
w: w,
|
|
|
|
patterns: patterns,
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debug("%s: starting", hostsContainerPref)
|
|
|
|
|
|
|
|
// Load initially.
|
|
|
|
if err = hc.refresh(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, p := range paths {
|
2021-11-17 14:21:10 +00:00
|
|
|
if err = w.Add(p); err != nil {
|
|
|
|
if !errors.Is(err, fs.ErrNotExist) {
|
|
|
|
return nil, fmt.Errorf("adding path: %w", err)
|
|
|
|
}
|
2021-10-14 16:39:21 +00:00
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
log.Debug("%s: %s is expected to exist but doesn't", hostsContainerPref, p)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
go hc.handleEvents()
|
|
|
|
|
|
|
|
return hc, nil
|
|
|
|
}
|
|
|
|
|
2021-11-17 14:21:10 +00:00
|
|
|
// Close implements the io.Closer interface for *HostsContainer. Close must
|
|
|
|
// only be called once. The returned err is always nil.
|
2021-10-14 16:39:21 +00:00
|
|
|
func (hc *HostsContainer) Close() (err error) {
|
2021-11-16 13:16:38 +00:00
|
|
|
log.Debug("%s: closing", hostsContainerPref)
|
2021-10-14 16:39:21 +00:00
|
|
|
|
2021-11-17 14:21:10 +00:00
|
|
|
close(hc.done)
|
|
|
|
|
|
|
|
return nil
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
// Upd returns the channel into which the updates are sent. The receivable
|
2022-01-12 09:14:59 +00:00
|
|
|
// map's values are guaranteed to be of type of *aghnet.Hosts.
|
2021-10-14 16:39:21 +00:00
|
|
|
func (hc *HostsContainer) Upd() (updates <-chan *netutil.IPMap) {
|
|
|
|
return hc.updates
|
|
|
|
}
|
|
|
|
|
|
|
|
// pathsToPatterns converts paths into patterns compatible with fs.Glob.
|
|
|
|
func pathsToPatterns(fsys fs.FS, paths []string) (patterns []string, err error) {
|
|
|
|
for i, p := range paths {
|
|
|
|
var fi fs.FileInfo
|
2021-11-17 14:21:10 +00:00
|
|
|
fi, err = fs.Stat(fsys, p)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Don't put a filename here since it's already added by fs.Stat.
|
|
|
|
return nil, fmt.Errorf("path at index %d: %w", i, err)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if fi.IsDir() {
|
|
|
|
p = path.Join(p, "*")
|
|
|
|
}
|
|
|
|
|
|
|
|
patterns = append(patterns, p)
|
|
|
|
}
|
|
|
|
|
|
|
|
return patterns, nil
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// handleEvents concurrently handles the file system events. It closes the
|
|
|
|
// update channel of HostsContainer when finishes. It's used to be called
|
|
|
|
// within a separate goroutine.
|
2021-10-14 16:39:21 +00:00
|
|
|
func (hc *HostsContainer) handleEvents() {
|
|
|
|
defer log.OnPanic(fmt.Sprintf("%s: handling events", hostsContainerPref))
|
|
|
|
|
|
|
|
defer close(hc.updates)
|
|
|
|
|
2021-11-17 14:21:10 +00:00
|
|
|
ok, eventsCh := true, hc.w.Events()
|
|
|
|
for ok {
|
|
|
|
select {
|
|
|
|
case _, ok = <-eventsCh:
|
|
|
|
if !ok {
|
|
|
|
log.Debug("%s: watcher closed the events channel", hostsContainerPref)
|
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := hc.refresh(); err != nil {
|
|
|
|
log.Error("%s: %s", hostsContainerPref, err)
|
|
|
|
}
|
|
|
|
case _, ok = <-hc.done:
|
|
|
|
// Go on.
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// ipRules is the pair of generated A/AAAA and PTR rules with related IP.
|
|
|
|
type ipRules struct {
|
|
|
|
// rule is the A/AAAA $dnsrewrite rule.
|
|
|
|
rule string
|
|
|
|
// rulePtr is the PTR $dnsrewrite rule.
|
|
|
|
rulePtr string
|
|
|
|
// ip is the IP address related to the rules.
|
|
|
|
ip net.IP
|
|
|
|
}
|
|
|
|
|
2021-10-14 16:39:21 +00:00
|
|
|
// hostsParser is a helper type to parse rules from the operating system's hosts
|
2021-11-23 15:01:48 +00:00
|
|
|
// file. It exists for only a single refreshing session.
|
2021-10-14 16:39:21 +00:00
|
|
|
type hostsParser struct {
|
2022-01-12 09:14:59 +00:00
|
|
|
// rulesBuilder builds the resulting rules list content.
|
2021-11-23 15:01:48 +00:00
|
|
|
rulesBuilder *strings.Builder
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// rules stores the rules for main hosts to generate translations.
|
|
|
|
rules []ipRules
|
2021-11-23 15:01:48 +00:00
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// cnameSet prevents duplicating cname rules, e.g. same hostname for
|
|
|
|
// different IP versions.
|
2021-11-23 15:01:48 +00:00
|
|
|
cnameSet *stringutil.Set
|
2021-10-14 16:39:21 +00:00
|
|
|
|
|
|
|
// table stores only the unique IP-hostname pairs. It's also sent to the
|
|
|
|
// updates channel afterwards.
|
|
|
|
table *netutil.IPMap
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// newHostsParser creates a new *hostsParser with buffers of size taken from the
|
|
|
|
// previous parse.
|
2021-11-16 13:16:38 +00:00
|
|
|
func (hc *HostsContainer) newHostsParser() (hp *hostsParser) {
|
2022-01-12 09:14:59 +00:00
|
|
|
lastLen := hc.last.Len()
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
return &hostsParser{
|
2021-11-23 15:01:48 +00:00
|
|
|
rulesBuilder: &strings.Builder{},
|
2022-01-12 09:14:59 +00:00
|
|
|
rules: make([]ipRules, 0, lastLen),
|
2021-11-23 15:01:48 +00:00
|
|
|
cnameSet: stringutil.NewSet(),
|
2022-01-12 09:14:59 +00:00
|
|
|
table: netutil.NewIPMap(lastLen),
|
2021-11-16 13:16:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseFile is a aghos.FileWalker for parsing the files with hosts syntax. It
|
|
|
|
// never signs to stop walking and never returns any additional patterns.
|
2021-10-14 16:39:21 +00:00
|
|
|
//
|
|
|
|
// See man hosts(5).
|
2022-01-12 09:14:59 +00:00
|
|
|
func (hp *hostsParser) parseFile(r io.Reader) (patterns []string, cont bool, err error) {
|
2021-10-14 16:39:21 +00:00
|
|
|
s := bufio.NewScanner(r)
|
|
|
|
for s.Scan() {
|
|
|
|
ip, hosts := hp.parseLine(s.Text())
|
2021-12-16 12:58:54 +00:00
|
|
|
if ip == nil || len(hosts) == 0 {
|
2021-10-14 16:39:21 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
hp.addPairs(ip, hosts)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil, true, s.Err()
|
|
|
|
}
|
|
|
|
|
|
|
|
// parseLine parses the line having the hosts syntax ignoring invalid ones.
|
2021-11-16 13:16:38 +00:00
|
|
|
func (hp *hostsParser) parseLine(line string) (ip net.IP, hosts []string) {
|
2021-10-14 16:39:21 +00:00
|
|
|
fields := strings.Fields(line)
|
|
|
|
if len(fields) < 2 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if ip = net.ParseIP(fields[0]); ip == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, f := range fields[1:] {
|
2021-12-16 12:58:54 +00:00
|
|
|
hashIdx := strings.IndexByte(f, '#')
|
|
|
|
if hashIdx == 0 {
|
|
|
|
// The rest of the fields are a part of the comment so return.
|
|
|
|
break
|
|
|
|
} else if hashIdx > 0 {
|
|
|
|
// Only a part of the field is a comment.
|
|
|
|
f = f[:hashIdx]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure that invalid hosts aren't turned into rules.
|
|
|
|
//
|
|
|
|
// See https://github.com/AdguardTeam/AdGuardHome/issues/3946.
|
|
|
|
err := netutil.ValidateDomainName(f)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("%s: host %q is invalid, ignoring", hostsContainerPref, f)
|
2021-12-09 15:26:56 +00:00
|
|
|
|
|
|
|
continue
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
2021-12-09 15:26:56 +00:00
|
|
|
|
2021-12-16 12:58:54 +00:00
|
|
|
hosts = append(hosts, f)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return ip, hosts
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// Hosts is used to contain the main host and all it's aliases.
|
|
|
|
type Hosts struct {
|
|
|
|
// Aliases contains all the aliases for Main.
|
|
|
|
Aliases *stringutil.Set
|
|
|
|
// Main is the host itself.
|
|
|
|
Main string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Equal returns true if h equals hh.
|
|
|
|
func (h *Hosts) Equal(hh *Hosts) (ok bool) {
|
|
|
|
if h == nil || hh == nil {
|
|
|
|
return h == hh
|
|
|
|
}
|
|
|
|
|
|
|
|
return h.Main == hh.Main && h.Aliases.Equal(hh.Aliases)
|
|
|
|
}
|
2021-11-23 15:01:48 +00:00
|
|
|
|
|
|
|
// add tries to add the ip-host pair. It returns:
|
|
|
|
//
|
2022-01-12 09:14:59 +00:00
|
|
|
// main host if the host is not the first one added for the ip.
|
|
|
|
// host itself if the host is the first one added for the ip.
|
|
|
|
// "" if the ip-host pair has already been added.
|
2021-11-23 15:01:48 +00:00
|
|
|
//
|
2022-01-12 09:14:59 +00:00
|
|
|
func (hp *hostsParser) add(ip net.IP, host string) (mainHost string) {
|
2021-10-14 16:39:21 +00:00
|
|
|
v, ok := hp.table.Get(ip)
|
2022-01-12 09:14:59 +00:00
|
|
|
switch h, _ := v.(*Hosts); {
|
|
|
|
case !ok:
|
|
|
|
// This is the first host for the ip.
|
|
|
|
hp.table.Set(ip, &Hosts{Main: host})
|
|
|
|
|
|
|
|
return host
|
|
|
|
case h.Main == host:
|
|
|
|
// This is a duplicate. Go on.
|
|
|
|
case h.Aliases == nil:
|
|
|
|
// This is the first alias.
|
|
|
|
h.Aliases = stringutil.NewSet(host)
|
|
|
|
|
|
|
|
return h.Main
|
|
|
|
case !h.Aliases.Has(host):
|
|
|
|
// This is a new alias.
|
|
|
|
h.Aliases.Add(host)
|
|
|
|
|
|
|
|
return h.Main
|
2021-11-16 13:16:38 +00:00
|
|
|
default:
|
2022-01-12 09:14:59 +00:00
|
|
|
// This is a duplicate. Go on.
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
2022-01-12 09:14:59 +00:00
|
|
|
|
|
|
|
return ""
|
2021-11-23 15:01:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// addPair puts the pair of ip and host to the rules builder if needed. For
|
|
|
|
// each ip the first member of hosts will become the main one.
|
|
|
|
func (hp *hostsParser) addPairs(ip net.IP, hosts []string) {
|
|
|
|
for _, host := range hosts {
|
2022-01-12 09:14:59 +00:00
|
|
|
switch mainHost := hp.add(ip, host); mainHost {
|
|
|
|
case "":
|
|
|
|
// This host is a duplicate.
|
2021-11-23 15:01:48 +00:00
|
|
|
continue
|
2022-01-12 09:14:59 +00:00
|
|
|
case host:
|
|
|
|
// This host is main.
|
|
|
|
added, addedPtr := hp.writeMainRule(host, ip)
|
|
|
|
hp.rules = append(hp.rules, ipRules{
|
|
|
|
rule: added,
|
|
|
|
rulePtr: addedPtr,
|
|
|
|
ip: ip,
|
|
|
|
})
|
|
|
|
default:
|
|
|
|
// This host is an alias.
|
2021-11-23 15:01:48 +00:00
|
|
|
pair := fmt.Sprint(host, " ", mainHost)
|
|
|
|
if hp.cnameSet.Has(pair) {
|
|
|
|
continue
|
|
|
|
}
|
2022-01-12 09:14:59 +00:00
|
|
|
hp.writeAliasRule(host, mainHost)
|
2021-11-23 15:01:48 +00:00
|
|
|
hp.cnameSet.Add(pair)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debug("%s: added ip-host pair %q-%q", hostsContainerPref, ip, host)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// writeAliasRule writes the CNAME rule for the alias-host pair into internal
|
|
|
|
// builders.
|
|
|
|
func (hp *hostsParser) writeAliasRule(alias, host string) {
|
2021-11-23 15:01:48 +00:00
|
|
|
const (
|
|
|
|
nl = "\n"
|
|
|
|
sc = ";"
|
2021-10-14 16:39:21 +00:00
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
rwSuccess = rules.MaskSeparator + "$dnsrewrite=NOERROR" + sc + "CNAME" + sc
|
2021-12-23 13:35:10 +00:00
|
|
|
constLen = len(rules.MaskPipe) + len(rwSuccess) + len(nl)
|
2021-11-23 15:01:48 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
hp.rulesBuilder.Grow(constLen + len(host) + len(alias))
|
2021-12-23 13:35:10 +00:00
|
|
|
stringutil.WriteToBuilder(hp.rulesBuilder, rules.MaskPipe, alias, rwSuccess, host, nl)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// writeMainRule writes the actual rule for the qtype and the PTR for the
|
2021-11-23 15:01:48 +00:00
|
|
|
// host-ip pair into internal builders.
|
2022-01-12 09:14:59 +00:00
|
|
|
func (hp *hostsParser) writeMainRule(host string, ip net.IP) (added, addedPtr string) {
|
2021-10-14 16:39:21 +00:00
|
|
|
arpa, err := netutil.IPToReversedAddr(ip)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
const (
|
|
|
|
nl = "\n"
|
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
rwSuccess = "^$dnsrewrite=NOERROR;"
|
|
|
|
rwSuccessPTR = "^$dnsrewrite=NOERROR;PTR;"
|
|
|
|
|
2021-12-23 13:35:10 +00:00
|
|
|
modLen = len(rules.MaskPipe) + len(rwSuccess) + len(";")
|
|
|
|
modLenPTR = len(rules.MaskPipe) + len(rwSuccessPTR)
|
2021-11-16 13:16:38 +00:00
|
|
|
)
|
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
var qtype string
|
|
|
|
// The validation of the IP address has been performed earlier so it is
|
|
|
|
// guaranteed to be either an IPv4 or an IPv6.
|
|
|
|
if ip.To4() != nil {
|
|
|
|
qtype = "A"
|
|
|
|
} else {
|
|
|
|
qtype = "AAAA"
|
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
ipStr := ip.String()
|
|
|
|
fqdn := dns.Fqdn(host)
|
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
ruleBuilder := &strings.Builder{}
|
|
|
|
ruleBuilder.Grow(modLen + len(host) + len(qtype) + len(ipStr))
|
|
|
|
stringutil.WriteToBuilder(
|
|
|
|
ruleBuilder,
|
2021-12-23 13:35:10 +00:00
|
|
|
rules.MaskPipe,
|
2021-10-14 16:39:21 +00:00
|
|
|
host,
|
2021-11-23 15:01:48 +00:00
|
|
|
rwSuccess,
|
2021-10-14 16:39:21 +00:00
|
|
|
qtype,
|
2021-11-23 15:01:48 +00:00
|
|
|
";",
|
2021-11-16 13:16:38 +00:00
|
|
|
ipStr,
|
2021-11-23 15:01:48 +00:00
|
|
|
)
|
|
|
|
added = ruleBuilder.String()
|
|
|
|
|
|
|
|
ruleBuilder.Reset()
|
2021-12-23 13:35:10 +00:00
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
ruleBuilder.Grow(modLenPTR + len(arpa) + len(fqdn))
|
2021-12-23 13:35:10 +00:00
|
|
|
stringutil.WriteToBuilder(ruleBuilder, rules.MaskPipe, arpa, rwSuccessPTR, fqdn)
|
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
addedPtr = ruleBuilder.String()
|
|
|
|
|
|
|
|
hp.rulesBuilder.Grow(len(added) + len(addedPtr) + 2*len(nl))
|
|
|
|
stringutil.WriteToBuilder(hp.rulesBuilder, added, nl, addedPtr, nl)
|
2021-10-14 16:39:21 +00:00
|
|
|
|
2021-11-23 15:01:48 +00:00
|
|
|
return added, addedPtr
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
// equalSet returns true if the internal hosts table just parsed equals target.
|
|
|
|
func (hp *hostsParser) equalSet(target *netutil.IPMap) (ok bool) {
|
2021-11-22 14:22:59 +00:00
|
|
|
if target == nil {
|
|
|
|
// hp.table shouldn't appear nil since it's initialized on each refresh.
|
|
|
|
return target == hp.table
|
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
if hp.table.Len() != target.Len() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
hp.table.Range(func(ip net.IP, b interface{}) (cont bool) {
|
2021-11-16 13:16:38 +00:00
|
|
|
// ok is set to true if the target doesn't contain ip or if the
|
2022-01-12 09:14:59 +00:00
|
|
|
// appropriate hosts set isn't equal to the checked one, i.e. the main
|
|
|
|
// hosts differ or the maps have at least one discrepancy.
|
|
|
|
if a, hasIP := target.Get(ip); !hasIP {
|
|
|
|
ok = true
|
|
|
|
} else if hosts, aok := a.(*Hosts); aok {
|
|
|
|
ok = !hosts.Equal(b.(*Hosts))
|
|
|
|
}
|
2021-11-16 13:16:38 +00:00
|
|
|
|
|
|
|
// Continue only if maps has no discrepancies.
|
|
|
|
return !ok
|
|
|
|
})
|
|
|
|
|
2021-12-27 16:40:39 +00:00
|
|
|
// Return true if every value from the IP map has no discrepancies with the
|
2021-11-16 13:16:38 +00:00
|
|
|
// appropriate one from the target.
|
|
|
|
return !ok
|
|
|
|
}
|
|
|
|
|
2021-10-14 16:39:21 +00:00
|
|
|
// sendUpd tries to send the parsed data to the ch.
|
2021-11-16 13:16:38 +00:00
|
|
|
func (hp *hostsParser) sendUpd(ch chan *netutil.IPMap) {
|
2021-10-14 16:39:21 +00:00
|
|
|
log.Debug("%s: sending upd", hostsContainerPref)
|
2021-11-16 13:16:38 +00:00
|
|
|
|
|
|
|
upd := hp.table
|
2021-10-14 16:39:21 +00:00
|
|
|
select {
|
2021-11-16 13:16:38 +00:00
|
|
|
case ch <- upd:
|
2021-10-14 16:39:21 +00:00
|
|
|
// Updates are delivered. Go on.
|
2021-11-16 13:16:38 +00:00
|
|
|
case <-ch:
|
|
|
|
ch <- upd
|
|
|
|
log.Debug("%s: replaced the last update", hostsContainerPref)
|
|
|
|
case ch <- upd:
|
|
|
|
// The previous update was just read and the next one pushed. Go on.
|
2021-10-14 16:39:21 +00:00
|
|
|
default:
|
2021-11-23 15:01:48 +00:00
|
|
|
log.Error("%s: the updates channel is broken", hostsContainerPref)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// newStrg creates a new rules storage from parsed data.
|
2021-11-26 15:25:43 +00:00
|
|
|
func (hp *hostsParser) newStrg(id int) (s *filterlist.RuleStorage, err error) {
|
2021-10-14 16:39:21 +00:00
|
|
|
return filterlist.NewRuleStorage([]filterlist.RuleList{&filterlist.StringRuleList{
|
2021-11-26 15:25:43 +00:00
|
|
|
ID: id,
|
2021-11-23 15:01:48 +00:00
|
|
|
RulesText: hp.rulesBuilder.String(),
|
2021-10-14 16:39:21 +00:00
|
|
|
IgnoreCosmetic: true,
|
|
|
|
}})
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
// translations generates the map to translate $dnsrewrite rules to
|
|
|
|
// hosts-syntax ones.
|
|
|
|
func (hp *hostsParser) translations() (trans map[string]string) {
|
|
|
|
l := len(hp.rules)
|
|
|
|
if l == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
trans = make(map[string]string, l*2)
|
|
|
|
for _, r := range hp.rules {
|
|
|
|
v, ok := hp.table.Get(r.ip)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
var hosts *Hosts
|
|
|
|
hosts, ok = v.(*Hosts)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
strs := append([]string{r.ip.String(), hosts.Main}, hosts.Aliases.Values()...)
|
|
|
|
hostsLine := strings.Join(strs, " ")
|
|
|
|
trans[r.rule], trans[r.rulePtr] = hostsLine, hostsLine
|
|
|
|
}
|
|
|
|
|
|
|
|
return trans
|
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
// refresh gets the data from specified files and propagates the updates if
|
|
|
|
// needed.
|
2021-11-17 14:21:10 +00:00
|
|
|
//
|
|
|
|
// TODO(e.burkov): Accept a parameter to specify the files to refresh.
|
2021-10-14 16:39:21 +00:00
|
|
|
func (hc *HostsContainer) refresh() (err error) {
|
|
|
|
log.Debug("%s: refreshing", hostsContainerPref)
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
hp := hc.newHostsParser()
|
|
|
|
if _, err = aghos.FileWalker(hp.parseFile).Walk(hc.fsys, hc.patterns...); err != nil {
|
|
|
|
return fmt.Errorf("refreshing : %w", err)
|
2021-10-14 16:39:21 +00:00
|
|
|
}
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
if hp.equalSet(hc.last) {
|
2022-01-12 09:14:59 +00:00
|
|
|
log.Debug("%s: no changes detected", hostsContainerPref)
|
2021-10-14 16:39:21 +00:00
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
return nil
|
|
|
|
}
|
2021-10-14 16:39:21 +00:00
|
|
|
defer hp.sendUpd(hc.updates)
|
|
|
|
|
2021-11-16 13:16:38 +00:00
|
|
|
hc.last = hp.table.ShallowClone()
|
|
|
|
|
2021-10-14 16:39:21 +00:00
|
|
|
var rulesStrg *filterlist.RuleStorage
|
2021-11-26 15:25:43 +00:00
|
|
|
if rulesStrg, err = hp.newStrg(hc.listID); err != nil {
|
2021-10-14 16:39:21 +00:00
|
|
|
return fmt.Errorf("initializing rules storage: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-01-12 09:14:59 +00:00
|
|
|
hc.resetEng(rulesStrg, hp.translations())
|
2021-10-14 16:39:21 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|