Pull request 2520: AGDNS-3360-rm-log-dnsforward

Squashed commit of the following:

commit aca896ce0eb2b2a569f9dd2d41e5f23cd349a3ba
Merge: d7feb54ff ba2fcd79a
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Tue Nov 11 14:48:53 2025 +0300

    Merge branch 'master' into AGDNS-3360-rm-log-dnsforward

commit d7feb54ff71075124c956daf688fbf29d9be2b47
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Mon Nov 10 19:06:22 2025 +0300

    dnsforward: imp log

commit cb9403cb6e04934db9ce9ba04fc1b427d6a3c88b
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Fri Nov 7 11:03:41 2025 +0300

    all: imp tests, imp docs

commit f95e541cf008bf1eb0c2c0132f85dda86225f813
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Thu Nov 6 13:07:59 2025 +0300

    all: rm accidentally added files

commit 49175747e3400244a0a893b9eb03410145433561
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Thu Nov 6 12:53:49 2025 +0300

    all: imp logs

commit 8f8f6d843da82c20e7c7d51c46fc461852b364af
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Wed Nov 5 15:34:57 2025 +0300

    dnsforward: imp log

commit 08e7fe0e01a8f688b6b63c8baa1df0ec77679841
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Wed Nov 5 15:32:33 2025 +0300

    dnsforward: fix log format

commit 4401776ff3eb85427d27234c8e50d5616dc017e6
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Wed Nov 5 15:13:21 2025 +0300

    all: imp logs

commit bf842d1d4b3d45470be34ba376b0eee7331a1a6f
Author: f.setrakov <f.setrakov@adguard.com>
Date:   Sat Nov 1 18:55:19 2025 +0300

    all: rm golibs/log
This commit is contained in:
Fedor Setrakov committed 2025-11-11 15:01:10 +03:00
1 parent ba2fcd79a3
commit d4d35186c7
15 files changed
+263 -142

No files matched your search

+6 -3
View File
@@ -113,15 +113,18 @@ func (p *AddressUpdater) UpdateAddress(
// Exchanger is a fake [rdns.Exchanger] implementation for tests. // Exchanger is a fake [rdns.Exchanger] implementation for tests.
type Exchanger struct { type Exchanger struct {
OnExchange func(ip netip.Addr) (host string, ttl time.Duration, err error) OnExchange func(ctx context.Context, ip netip.Addr) (host string, ttl time.Duration, err error)
} }
// type check // type check
var _ rdns.Exchanger = (*Exchanger)(nil) var _ rdns.Exchanger = (*Exchanger)(nil)
// Exchange implements [rdns.Exchanger] interface for *Exchanger. // Exchange implements [rdns.Exchanger] interface for *Exchanger.
func (e *Exchanger) Exchange(ip netip.Addr) (host string, ttl time.Duration, err error) { func (e *Exchanger) Exchange(
return e.OnExchange(ip) ctx context.Context,
ip netip.Addr,
) (host string, ttl time.Duration, err error) {
return e.OnExchange(ctx, ip)
} }
// UpstreamMock is a fake [upstream.Upstream] implementation for tests. // UpstreamMock is a fake [upstream.Upstream] implementation for tests.
+21 -8
View File
@@ -99,16 +99,24 @@ func TestDefaultAddrProc_Process_rDNS(t *testing.T) {
updIPCh := make(chan netip.Addr, 1) updIPCh := make(chan netip.Addr, 1)
updHostCh := make(chan string, 1) updHostCh := make(chan string, 1)
updInfoCh := make(chan *whois.Info, 1) updInfoCh := make(chan *whois.Info, 1)
onExchange := func(
_ context.Context,
ip netip.Addr,
) (host string, ttl time.Duration, err error) {
return tc.host, 0, tc.rdnsErr
}
p := client.NewDefaultAddrProc(&client.DefaultAddrProcConfig{ p := client.NewDefaultAddrProc(&client.DefaultAddrProcConfig{
BaseLogger: slogutil.NewDiscardLogger(), BaseLogger: slogutil.NewDiscardLogger(),
DialContext: func(_ context.Context, _, _ string) (conn net.Conn, err error) { DialContext: func(
panic("not implemented") ctx context.Context,
network,
addr string,
) (conn net.Conn, err error) {
panic(testutil.UnexpectedCall(ctx, network, addr))
}, },
Exchanger: &aghtest.Exchanger{ Exchanger: &aghtest.Exchanger{
OnExchange: func(ip netip.Addr) (host string, ttl time.Duration, err error) { OnExchange: onExchange,
return tc.host, 0, tc.rdnsErr
},
}, },
PrivateSubnets: netutil.SubnetSetFunc(netutil.IsLocallyServed), PrivateSubnets: netutil.SubnetSetFunc(netutil.IsLocallyServed),
AddressUpdater: &aghtest.AddressUpdater{ AddressUpdater: &aghtest.AddressUpdater{
@@ -211,15 +219,20 @@ func TestDefaultAddrProc_Process_WHOIS(t *testing.T) {
updHostCh := make(chan string, 1) updHostCh := make(chan string, 1)
updInfoCh := make(chan *whois.Info, 1) updInfoCh := make(chan *whois.Info, 1)
onExchange := func(
ctx context.Context,
addr netip.Addr,
) (_ string, _ time.Duration, _ error) {
panic(testutil.UnexpectedCall(ctx, addr))
}
p := client.NewDefaultAddrProc(&client.DefaultAddrProcConfig{ p := client.NewDefaultAddrProc(&client.DefaultAddrProcConfig{
BaseLogger: slogutil.NewDiscardLogger(), BaseLogger: slogutil.NewDiscardLogger(),
DialContext: func(_ context.Context, _, _ string) (conn net.Conn, err error) { DialContext: func(_ context.Context, _, _ string) (conn net.Conn, err error) {
return whoisConn, nil return whoisConn, nil
}, },
Exchanger: &aghtest.Exchanger{ Exchanger: &aghtest.Exchanger{
OnExchange: func(_ netip.Addr) (_ string, _ time.Duration, _ error) { OnExchange: onExchange,
panic("not implemented")
},
}, },
PrivateSubnets: netutil.SubnetSetFunc(netutil.IsLocallyServed), PrivateSubnets: netutil.SubnetSetFunc(netutil.IsLocallyServed),
AddressUpdater: &aghtest.AddressUpdater{ AddressUpdater: &aghtest.AddressUpdater{
+8 -3
View File
@@ -23,7 +23,9 @@ func (s *Server) HandleBefore(
_ *proxy.Proxy, _ *proxy.Proxy,
pctx *proxy.DNSContext, pctx *proxy.DNSContext,
) (err error) { ) (err error) {
clientID, err := s.clientIDFromDNSContext(pctx) // TODO(f.setrakov): Obtain context from arguments.
ctx := context.TODO()
clientID, err := s.clientIDFromDNSContext(ctx, pctx)
if err != nil { if err != nil {
return &proxy.BeforeRequestError{ return &proxy.BeforeRequestError{
Err: fmt.Errorf("getting clientid: %w", err), Err: fmt.Errorf("getting clientid: %w", err),
@@ -65,7 +67,10 @@ func (s *Server) HandleBefore(
// clientIDFromDNSContext extracts the client's ID from the server name of the // clientIDFromDNSContext extracts the client's ID from the server name of the
// client's DoT or DoQ request or the path of the client's DoH. If the protocol // client's DoT or DoQ request or the path of the client's DoH. If the protocol
// is not one of these, clientID is an empty string and err is nil. // is not one of these, clientID is an empty string and err is nil.
func (s *Server) clientIDFromDNSContext(pctx *proxy.DNSContext) (clientID string, err error) { func (s *Server) clientIDFromDNSContext(
ctx context.Context,
pctx *proxy.DNSContext,
) (clientID string, err error) {
proto := pctx.Proto proto := pctx.Proto
if proto == proxy.ProtoHTTPS { if proto == proxy.ProtoHTTPS {
clientID, err = clientIDFromDNSContextHTTPS(pctx) clientID, err = clientIDFromDNSContextHTTPS(pctx)
@@ -85,7 +90,7 @@ func (s *Server) clientIDFromDNSContext(pctx *proxy.DNSContext) (clientID string
return "", nil return "", nil
} }
cliSrvName, err := clientServerName(pctx, proto) cliSrvName, err := clientServerName(ctx, s.logger, pctx, proto)
if err != nil { if err != nil {
return "", fmt.Errorf("getting client server-name: %w", err) return "", fmt.Errorf("getting client server-name: %w", err)
} }
+10 -4
View File
@@ -1,15 +1,16 @@
package dnsforward package dnsforward
import ( import (
"context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"log/slog"
"net/http" "net/http"
"path" "path"
"strings" "strings"
"github.com/AdguardTeam/AdGuardHome/internal/client" "github.com/AdguardTeam/AdGuardHome/internal/client"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil"
) )
@@ -94,8 +95,13 @@ type tlsConn interface {
// clientServerName returns the TLS server name based on the protocol. For // clientServerName returns the TLS server name based on the protocol. For
// DNS-over-HTTPS requests, it will return the hostname part of the Host header // DNS-over-HTTPS requests, it will return the hostname part of the Host header
// if there is one. // if there is one. l and pctx must not be nil.
func clientServerName(pctx *proxy.DNSContext, proto proxy.Proto) (srvName string, err error) { func clientServerName(
ctx context.Context,
l *slog.Logger,
pctx *proxy.DNSContext,
proto proxy.Proto,
) (srvName string, err error) {
from := "tls conn" from := "tls conn"
switch proto { switch proto {
@@ -121,7 +127,7 @@ func clientServerName(pctx *proxy.DNSContext, proto proxy.Proto) (srvName string
srvName = tc.ConnectionState().ServerName srvName = tc.ConnectionState().ServerName
} }
log.Debug("dnsforward: got client server name %q from %s", srvName, from) l.DebugContext(ctx, "got client server name", "name", srvName, "from", from)
return srvName, nil return srvName, nil
} }
@@ -228,7 +228,8 @@ func TestServer_clientIDFromDNSContext(t *testing.T) {
HTTPRequest: httpReq, HTTPRequest: httpReq,
} }
clientID, err := srv.clientIDFromDNSContext(pctx) ctx := testutil.ContextWithTimeout(t, testTimeout)
clientID, err := srv.clientIDFromDNSContext(ctx, pctx)
assert.Equal(t, tc.wantClientID, clientID) assert.Equal(t, tc.wantClientID, clientID)
testutil.AssertErrorMsg(t, tc.wantErrMsg, err) testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
+17 -9
View File
@@ -5,6 +5,7 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"log/slog"
"net" "net"
"net/netip" "net/netip"
"os" "os"
@@ -22,7 +23,6 @@ import (
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/container" "github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/stringutil" "github.com/AdguardTeam/golibs/stringutil"
@@ -480,8 +480,11 @@ func (s *Server) prepareIpsetListSettings(ctx context.Context) (ipsets []string,
} }
// loadUpstreams parses upstream DNS servers from the configured file or from // loadUpstreams parses upstream DNS servers from the configured file or from
// the configuration itself. // the configuration itself. l must not be nil.
func (conf *ServerConfig) loadUpstreams() (upstreams []string, err error) { func (conf *ServerConfig) loadUpstreams(
ctx context.Context,
l *slog.Logger,
) (upstreams []string, err error) {
if conf.UpstreamDNSFileName == "" { if conf.UpstreamDNSFileName == "" {
return stringutil.FilterOut(conf.UpstreamDNS, aghnet.IsCommentOrEmpty), nil return stringutil.FilterOut(conf.UpstreamDNS, aghnet.IsCommentOrEmpty), nil
} }
@@ -494,7 +497,7 @@ func (conf *ServerConfig) loadUpstreams() (upstreams []string, err error) {
upstreams = stringutil.SplitTrimmed(string(data), "\n") upstreams = stringutil.SplitTrimmed(string(data), "\n")
log.Debug("dnsforward: got %d upstreams in %q", len(upstreams), conf.UpstreamDNSFileName) l.DebugContext(ctx, "got upstreams", "number", len(upstreams), "filename", conf.UpstreamDNSFileName)
return stringutil.FilterOut(upstreams, aghnet.IsCommentOrEmpty), nil return stringutil.FilterOut(upstreams, aghnet.IsCommentOrEmpty), nil
} }
@@ -601,16 +604,16 @@ func filterOutAddrs(upsConf *proxy.UpstreamConfig, set addrPortSet) (err error)
} }
// ourAddrsSet returns an addrPortSet that contains all the configured listening // ourAddrsSet returns an addrPortSet that contains all the configured listening
// addresses. // addresses. l must not be nil.
func (conf *ServerConfig) ourAddrsSet() (m addrPortSet, err error) { func (conf *ServerConfig) ourAddrsSet(ctx context.Context, l *slog.Logger) (m addrPortSet, err error) {
addrs, unspecPorts := conf.collectDNSAddrs() addrs, unspecPorts := conf.collectDNSAddrs()
switch { switch {
case addrs.Len() == 0: case addrs.Len() == 0:
log.Debug("dnsforward: no listen addresses") l.DebugContext(ctx, "no listen addresses")
return emptyAddrPortSet{}, nil return emptyAddrPortSet{}, nil
case unspecPorts.Len() == 0: case unspecPorts.Len() == 0:
log.Debug("dnsforward: filtering out addresses %s", addrs) l.DebugContext(ctx, "filtering out addresses", "addresses", addrs)
return addrs, nil return addrs, nil
default: default:
@@ -621,7 +624,12 @@ func (conf *ServerConfig) ourAddrsSet() (m addrPortSet, err error) {
return nil, err return nil, err
} }
log.Debug("dnsforward: filtering out addresses %s on ports %d", ifaceAddrs, unspecPorts) l.DebugContext(
ctx,
"filtering out addresses",
"addresses", ifaceAddrs,
"ports", unspecPorts,
)
return &combinedAddrPortSet{ return &combinedAddrPortSet{
ports: unspecPorts, ports: unspecPorts,
+60 -34
View File
@@ -1,13 +1,15 @@
package dnsforward package dnsforward
import ( import (
"context"
"fmt" "fmt"
"log/slog"
"sync" "sync"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@@ -58,6 +60,7 @@ type parseResult struct {
// validator for it. cv already contains the parsed upstreams along with errors // validator for it. cv already contains the parsed upstreams along with errors
// related. // related.
func newUpstreamConfigValidator( func newUpstreamConfigValidator(
ctx context.Context,
general []string, general []string,
fallback []string, fallback []string,
private []string, private []string,
@@ -70,15 +73,15 @@ func newUpstreamConfigValidator(
} }
conf, err := proxy.ParseUpstreamsConfig(general, opts) conf, err := proxy.ParseUpstreamsConfig(general, opts)
cv.generalParseResults = collectErrResults(general, err) cv.generalParseResults = collectErrResults(ctx, opts.Logger, general, err)
insertConfResults(conf, cv.generalUpstreamResults) insertConfResults(conf, cv.generalUpstreamResults)
conf, err = proxy.ParseUpstreamsConfig(fallback, opts) conf, err = proxy.ParseUpstreamsConfig(fallback, opts)
cv.fallbackParseResults = collectErrResults(fallback, err) cv.fallbackParseResults = collectErrResults(ctx, opts.Logger, fallback, err)
insertConfResults(conf, cv.fallbackUpstreamResults) insertConfResults(conf, cv.fallbackUpstreamResults)
conf, err = proxy.ParseUpstreamsConfig(private, opts) conf, err = proxy.ParseUpstreamsConfig(private, opts)
cv.privateParseResults = collectErrResults(private, err) cv.privateParseResults = collectErrResults(ctx, opts.Logger, private, err)
insertConfResults(conf, cv.privateUpstreamResults) insertConfResults(conf, cv.privateUpstreamResults)
return cv return cv
@@ -86,8 +89,8 @@ func newUpstreamConfigValidator(
// collectErrResults parses err and returns parsing results containing the // collectErrResults parses err and returns parsing results containing the
// original upstream configuration line and the corresponding error. err can be // original upstream configuration line and the corresponding error. err can be
// nil. // nil. l must not be nil.
func collectErrResults(lines []string, err error) (results []*parseResult) { func collectErrResults(ctx context.Context, l *slog.Logger, lines []string, err error) (results []*parseResult) {
if err == nil { if err == nil {
return nil return nil
} }
@@ -97,7 +100,7 @@ func collectErrResults(lines []string, err error) (results []*parseResult) {
wrapper, ok := err.(errors.WrapperSlice) wrapper, ok := err.(errors.WrapperSlice)
if !ok { if !ok {
log.Debug("dnsforward: configvalidator: unwrapping: %s", err) l.DebugContext(ctx, "unwrapping", slogutil.KeyError, err)
return nil return nil
} }
@@ -107,7 +110,7 @@ func collectErrResults(lines []string, err error) (results []*parseResult) {
for i, e := range errs { for i, e := range errs {
var parseErr *proxy.ParseError var parseErr *proxy.ParseError
if !errors.As(e, &parseErr) { if !errors.As(e, &parseErr) {
log.Debug("dnsforward: configvalidator: inserting unexpected error %d: %s", i, err) l.DebugContext(ctx, "inserting unexpected error", "index", i, slogutil.KeyError, err)
continue continue
} }
@@ -162,8 +165,8 @@ func insertListResults(ups []upstream.Upstream, results map[string]*upstreamResu
// check tries to exchange with each successfully parsed upstream and enriches // check tries to exchange with each successfully parsed upstream and enriches
// the results with the healthcheck errors. It should not be called after the // the results with the healthcheck errors. It should not be called after the
// [upsConfValidator.close] method, since it makes no sense to check the closed // [upsConfValidator.close] method, since it makes no sense to check the closed
// upstreams. // upstreams. l must not be nil.
func (cv *upstreamConfigValidator) check() { func (cv *upstreamConfigValidator) check(ctx context.Context, l *slog.Logger) {
const ( const (
// testTLD is the special-use fully-qualified domain name for testing // testTLD is the special-use fully-qualified domain name for testing
// the DNS server reachability. // the DNS server reachability.
@@ -193,22 +196,23 @@ func (cv *upstreamConfigValidator) check() {
wg := &sync.WaitGroup{} wg := &sync.WaitGroup{}
for _, res := range cv.generalUpstreamResults { for _, res := range cv.generalUpstreamResults {
wg.Go(func() { checkSrv(res, commonChecker) }) wg.Go(func() { checkSrv(ctx, l, res, commonChecker) })
} }
for _, res := range cv.fallbackUpstreamResults { for _, res := range cv.fallbackUpstreamResults {
wg.Go(func() { checkSrv(res, commonChecker) }) wg.Go(func() { checkSrv(ctx, l, res, commonChecker) })
} }
for _, res := range cv.privateUpstreamResults { for _, res := range cv.privateUpstreamResults {
wg.Go(func() { checkSrv(res, arpaChecker) }) wg.Go(func() { checkSrv(ctx, l, res, arpaChecker) })
} }
wg.Wait() wg.Wait()
} }
// checkSrv runs hc on the server from res, if any, and stores any occurred // checkSrv runs hc on the server from res, if any, and stores any occurred
// error in res. It is used to be run in a separate goroutine. // error in res. It is used to be run in a separate goroutine. l must not be
func checkSrv(res *upstreamResult, hc *healthchecker) { // nil.
defer log.OnPanic(fmt.Sprintf("dnsforward: checking upstream %s", res.server.Address())) func checkSrv(ctx context.Context, l *slog.Logger, res *upstreamResult, hc *healthchecker) {
defer slogutil.RecoverAndLog(ctx, l)
res.err = hc.check(res.server) res.err = hc.check(res.server)
if res.err != nil && res.isSpecific { if res.err != nil && res.isSpecific {
@@ -247,8 +251,11 @@ const (
// status returns all the data collected during parsing, healthcheck, and // status returns all the data collected during parsing, healthcheck, and
// closing of the upstreams. The returned map is keyed by the original upstream // closing of the upstreams. The returned map is keyed by the original upstream
// configuration piece and contains the corresponding error or "OK" if there was // configuration piece and contains the corresponding error or "OK" if there was
// no error. // no error. l must not be nil.
func (cv *upstreamConfigValidator) status() (results map[string]string) { func (cv *upstreamConfigValidator) status(
ctx context.Context,
l *slog.Logger,
) (results map[string]string) {
// Names of the upstream configuration sections for logging. // Names of the upstream configuration sections for logging.
const ( const (
generalSection = "general" generalSection = "general"
@@ -259,30 +266,39 @@ func (cv *upstreamConfigValidator) status() (results map[string]string) {
results = map[string]string{} results = map[string]string{}
for original, res := range cv.generalUpstreamResults { for original, res := range cv.generalUpstreamResults {
upstreamResultToStatus(generalSection, string(original), res, results) upstreamResultToStatus(ctx, l, generalSection, string(original), res, results)
} }
for original, res := range cv.fallbackUpstreamResults { for original, res := range cv.fallbackUpstreamResults {
upstreamResultToStatus(fallbackSection, string(original), res, results) upstreamResultToStatus(ctx, l, fallbackSection, string(original), res, results)
} }
for original, res := range cv.privateUpstreamResults { for original, res := range cv.privateUpstreamResults {
upstreamResultToStatus(privateSection, string(original), res, results) upstreamResultToStatus(ctx, l, privateSection, string(original), res, results)
} }
parseResultToStatus(generalTextLabel, generalSection, cv.generalParseResults, results) parseResultToStatus(ctx, l, generalTextLabel, generalSection, cv.generalParseResults, results)
parseResultToStatus(fallbackTextLabel, fallbackSection, cv.fallbackParseResults, results) parseResultToStatus(
parseResultToStatus(privateTextLabel, privateSection, cv.privateParseResults, results) ctx,
l,
fallbackTextLabel,
fallbackSection,
cv.fallbackParseResults,
results,
)
parseResultToStatus(ctx, l, privateTextLabel, privateSection, cv.privateParseResults, results)
return results return results
} }
// upstreamResultToStatus puts "OK" or an error message from res into resMap. // upstreamResultToStatus puts "OK" or an error message from res into resMap.
// section is the name of the upstream configuration section, i.e. "general", // section is the name of the upstream configuration section, i.e. "general",
// "fallback", or "private", and only used for logging. // "fallback", or "private", and only used for logging. l must not be nil.
// //
// TODO(e.burkov): Currently, the HTTP handler expects that all the results are // TODO(e.burkov): Currently, the HTTP handler expects that all the results are
// put together in a single map, which may lead to collisions, see AG-27539. // put together in a single map, which may lead to collisions, see AG-27539.
// Improve the results compilation. // Improve the results compilation.
func upstreamResultToStatus( func upstreamResultToStatus(
ctx context.Context,
l *slog.Logger,
section string, section string,
original string, original string,
res *upstreamResult, res *upstreamResult,
@@ -298,21 +314,22 @@ func upstreamResultToStatus(
case "": case "":
resMap[original] = val resMap[original] = val
case val: case val:
log.Debug("dnsforward: duplicating %s config line %q", section, original) l.DebugContext(ctx, "duplicating config line", "section", section, "address", original)
default: default:
log.Debug( l.WarnContext(
"dnsforward: warning: %s config line %q (%v) had different result %v", ctx,
section, "config line had different result",
val, "section", section,
original, "result", val,
prevVal, "original", original,
"previous", prevVal,
) )
} }
} }
// parseResultToStatus puts parsing error messages from results into resMap. // parseResultToStatus puts parsing error messages from results into resMap.
// section is the name of the upstream configuration section, i.e. "general", // section is the name of the upstream configuration section, i.e. "general",
// "fallback", or "private", and only used for logging. // "fallback", or "private", and only used for logging. l must not be nil.
// //
// Parsing error message has the following format: // Parsing error message has the following format:
// //
@@ -321,6 +338,8 @@ func upstreamResultToStatus(
// Where sectionTextLabel is a section text label of a localization and line is // Where sectionTextLabel is a section text label of a localization and line is
// a line number. // a line number.
func parseResultToStatus( func parseResultToStatus(
ctx context.Context,
l *slog.Logger,
textLabel string, textLabel string,
section string, section string,
results []*parseResult, results []*parseResult,
@@ -330,7 +349,14 @@ func parseResultToStatus(
original := res.original original := res.original
_, ok := resMap[original] _, ok := resMap[original]
if ok { if ok {
log.Debug("dnsforward: duplicating %s parsing error %q", section, original) l.DebugContext(
ctx,
"duplicating parsing error",
"section",
section,
"original",
original,
)
continue continue
} }
+30 -22
View File
@@ -28,7 +28,6 @@ import (
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" "github.com/AdguardTeam/golibs/cache"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/netutil/sysresolv" "github.com/AdguardTeam/golibs/netutil/sysresolv"
@@ -375,7 +374,10 @@ const (
var _ rdns.Exchanger = (*Server)(nil) var _ rdns.Exchanger = (*Server)(nil)
// Exchange implements the [rdns.Exchanger] interface for *Server. // Exchange implements the [rdns.Exchanger] interface for *Server.
func (s *Server) Exchange(ip netip.Addr) (host string, ttl time.Duration, err error) { func (s *Server) Exchange(
ctx context.Context,
ip netip.Addr,
) (host string, ttl time.Duration, err error) {
s.serverLock.RLock() s.serverLock.RLock()
defer s.serverLock.RUnlock() defer s.serverLock.RUnlock()
@@ -420,11 +422,16 @@ func (s *Server) Exchange(ip netip.Addr) (host string, ttl time.Duration, err er
return "", 0, fmt.Errorf(errMsg, err) return "", 0, fmt.Errorf(errMsg, err)
} }
return hostFromPTR(dctx.Res) return hostFromPTR(ctx, s.logger, dctx.Res)
} }
// hostFromPTR returns domain name from the PTR response or error. // hostFromPTR returns domain name from the PTR response or error. l must not
func hostFromPTR(resp *dns.Msg) (host string, ttl time.Duration, err error) { // be nil.
func hostFromPTR(
ctx context.Context,
l *slog.Logger,
resp *dns.Msg,
) (host string, ttl time.Duration, err error) {
// Distinguish between NODATA response and a failed request. // Distinguish between NODATA response and a failed request.
if resp.Rcode != dns.RcodeSuccess && resp.Rcode != dns.RcodeNameError { if resp.Rcode != dns.RcodeSuccess && resp.Rcode != dns.RcodeNameError {
return "", 0, fmt.Errorf( return "", 0, fmt.Errorf(
@@ -436,7 +443,8 @@ func hostFromPTR(resp *dns.Msg) (host string, ttl time.Duration, err error) {
var ttlSec uint32 var ttlSec uint32
log.Debug("dnsforward: resolving ptr, received %d answers", len(resp.Answer)) l.DebugContext(ctx, "resolving ptr", "num_answers", len(resp.Answer))
for _, ans := range resp.Answer { for _, ans := range resp.Answer {
ptr, ok := ans.(*dns.PTR) ptr, ok := ans.(*dns.PTR)
if !ok { if !ok {
@@ -542,23 +550,23 @@ func (s *Server) Prepare(ctx context.Context, conf *ServerConfig) (err error) {
} }
// prepareUpstreamSettings sets upstream DNS server settings. // prepareUpstreamSettings sets upstream DNS server settings.
func (s *Server) prepareUpstreamSettings(boot upstream.Resolver) (err error) { func (s *Server) prepareUpstreamSettings(ctx context.Context, boot upstream.Resolver) (err error) {
// Load upstreams either from the file, or from the settings // Load upstreams either from the file, or from the settings
var upstreams []string var upstreams []string
upstreams, err = s.conf.loadUpstreams() upstreams, err = s.conf.loadUpstreams(ctx, s.logger)
if err != nil { if err != nil {
return fmt.Errorf("loading upstreams: %w", err) return fmt.Errorf("loading upstreams: %w", err)
} }
uc, err := newUpstreamConfig(upstreams, defaultDNS, &upstream.Options{ uc, err := newUpstreamConfig(ctx, s.logger, upstreams, defaultDNS, &upstream.Options{
Logger: aghslog.NewForUpstream(s.baseLogger, aghslog.UpstreamTypeMain), Logger: aghslog.NewForUpstream(s.baseLogger, aghslog.UpstreamTypeMain),
Bootstrap: boot, Bootstrap: boot,
Timeout: s.conf.UpstreamTimeout, Timeout: s.conf.UpstreamTimeout,
HTTPVersions: aghnet.UpstreamHTTPVersions(s.conf.UseHTTP3Upstreams), HTTPVersions: aghnet.UpstreamHTTPVersions(s.conf.UseHTTP3Upstreams),
PreferIPv6: s.conf.BootstrapPreferIPv6, PreferIPv6: s.conf.BootstrapPreferIPv6,
// Use a customized set of RootCAs, because Go's default mechanism of // Use a customized set of RootCAs, because Go's default mechanism of
// loading TLS roots does not always work properly on some routers so we're // loading TLS roots does not always work properly on some routers so
// loading roots manually and pass it here. // we're loading roots manually and pass it here.
// //
// See [aghtls.SystemRootCAs]. // See [aghtls.SystemRootCAs].
// //
@@ -605,13 +613,13 @@ func (e *PrivateRDNSError) Unwrap() (err error) {
// prepareLocalResolvers initializes the private RDNS upstream configuration // prepareLocalResolvers initializes the private RDNS upstream configuration
// according to the server's settings. It assumes s.serverLock is locked or the // according to the server's settings. It assumes s.serverLock is locked or the
// Server not running. // Server not running.
func (s *Server) prepareLocalResolvers() (uc *proxy.UpstreamConfig, err error) { func (s *Server) prepareLocalResolvers(ctx context.Context) (uc *proxy.UpstreamConfig, err error) {
if !s.conf.UsePrivateRDNS { if !s.conf.UsePrivateRDNS {
return nil, nil return nil, nil
} }
var ownAddrs addrPortSet var ownAddrs addrPortSet
ownAddrs, err = s.conf.ourAddrsSet() ownAddrs, err = s.conf.ourAddrsSet(ctx, s.logger)
if err != nil { if err != nil {
// Don't wrap the error, because it's informative enough as is. // Don't wrap the error, because it's informative enough as is.
return nil, err return nil, err
@@ -626,7 +634,7 @@ func (s *Server) prepareLocalResolvers() (uc *proxy.UpstreamConfig, err error) {
} }
addrs := s.conf.LocalPTRResolvers addrs := s.conf.LocalPTRResolvers
uc, err = newPrivateConfig(addrs, ownAddrs, s.sysResolvers, s.privateNets, opts) uc, err = newPrivateConfig(ctx, s.logger, addrs, ownAddrs, s.sysResolvers, s.privateNets, opts)
if err != nil { if err != nil {
return nil, fmt.Errorf("preparing resolvers: %w", err) return nil, fmt.Errorf("preparing resolvers: %w", err)
} }
@@ -662,13 +670,13 @@ func (s *Server) prepareInternalDNS(ctx context.Context) (err error) {
return err return err
} }
err = s.prepareUpstreamSettings(s.bootstrap) err = s.prepareUpstreamSettings(ctx, s.bootstrap)
if err != nil { if err != nil {
// Don't wrap the error, because it's informative enough as is. // Don't wrap the error, because it's informative enough as is.
return err return err
} }
s.conf.PrivateRDNSUpstreamConfig, err = s.prepareLocalResolvers() s.conf.PrivateRDNSUpstreamConfig, err = s.prepareLocalResolvers(ctx)
if err != nil { if err != nil {
return err return err
} }
@@ -807,21 +815,21 @@ func (s *Server) stopLocked(ctx context.Context) {
} }
for _, b := range s.bootResolvers { for _, b := range s.bootResolvers {
logCloserErr(b, "dnsforward: closing bootstrap %s: %s", b.Address()) logCloserErr(ctx, b, "closing bootstrap", s.logger.With("address", b.Address()))
} }
s.isRunning = false s.isRunning = false
} }
// logCloserErr logs the error returned by c, if any. // logCloserErr logs the error returned by c, if any. l and c must not be nil.
func logCloserErr(c io.Closer, format string, args ...any) { func logCloserErr(ctx context.Context, c io.Closer, msg string, l *slog.Logger) {
if c == nil { if c == nil {
return return
} }
err := c.Close() err := c.Close()
if err != nil { if err != nil {
log.Error(format, append(args, err)...) l.ErrorContext(ctx, msg, slogutil.KeyError, err)
} }
} }
@@ -860,8 +868,8 @@ func (s *Server) Reconfigure(ctx context.Context, conf *ServerConfig) error {
s.stopLocked(ctx) s.stopLocked(ctx)
// It seems that net.Listener.Close() doesn't close file descriptors right away. // It seems that net.Listener.Close() doesn't close file descriptors right
// We wait for some time and hope that this fd will be closed. // away. We wait for some time and hope that this fd will be closed.
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
if s.addrProc != nil { if s.addrProc != nil {
@@ -1840,7 +1840,8 @@ func TestServer_Exchange(t *testing.T) {
ServePlainDNS: true, ServePlainDNS: true,
}) })
host, ttl, eerr := srv.Exchange(tc.req) ctx := testutil.ContextWithTimeout(t, testTimeout)
host, ttl, eerr := srv.Exchange(ctx, tc.req)
require.ErrorIs(t, eerr, tc.wantErr) require.ErrorIs(t, eerr, tc.wantErr)
assert.Equal(t, tc.want, host) assert.Equal(t, tc.want, host)
@@ -1863,7 +1864,8 @@ func TestServer_Exchange(t *testing.T) {
ServePlainDNS: true, ServePlainDNS: true,
}) })
host, _, eerr := srv.Exchange(localIP) ctx := testutil.ContextWithTimeout(t, testTimeout)
host, _, eerr := srv.Exchange(ctx, localIP)
require.NoError(t, eerr) require.NoError(t, eerr)
assert.Empty(t, host) assert.Empty(t, host)
+35 -18
View File
@@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log/slog"
"net/http" "net/http"
"net/netip" "net/netip"
"slices" "slices"
@@ -186,7 +187,7 @@ func (s *Server) getDNSConfig(ctx context.Context) (c *jsonDNSConfig) {
upstreamMode = jsonUpstreamModeFastestAddr upstreamMode = jsonUpstreamModeFastestAddr
} }
defPTRUps, err := s.defaultLocalPTRUpstreams() defPTRUps, err := s.defaultLocalPTRUpstreams(ctx)
if err != nil { if err != nil {
s.logger.ErrorContext(ctx, "getting local ptr upstreams", slogutil.KeyError, err) s.logger.ErrorContext(ctx, "getting local ptr upstreams", slogutil.KeyError, err)
} }
@@ -227,8 +228,8 @@ func (s *Server) getDNSConfig(ctx context.Context) (c *jsonDNSConfig) {
// defaultLocalPTRUpstreams returns the list of default local PTR resolvers // defaultLocalPTRUpstreams returns the list of default local PTR resolvers
// filtered of AdGuard Home's own DNS server addresses. It may appear empty. // filtered of AdGuard Home's own DNS server addresses. It may appear empty.
func (s *Server) defaultLocalPTRUpstreams() (ups []string, err error) { func (s *Server) defaultLocalPTRUpstreams(ctx context.Context) (ups []string, err error) {
matcher, err := s.conf.ourAddrsSet() matcher, err := s.conf.ourAddrsSet(ctx, s.logger)
if err != nil { if err != nil {
// Don't wrap the error because it's informative enough as is. // Don't wrap the error because it's informative enough as is.
return nil, err return nil, err
@@ -278,10 +279,13 @@ func (req *jsonDNSConfig) checkUpstreamMode() (err error) {
} }
} }
// validate returns an error if any field of req is invalid. // validate returns an error if any field of req is invalid. l, ownAddrs,
// sysResolvers and privateNets must not be nil.
// //
// TODO(s.chzhen): Parse, don't validate. // TODO(s.chzhen): Parse, don't validate.
func (req *jsonDNSConfig) validate( func (req *jsonDNSConfig) validate(
ctx context.Context,
l *slog.Logger,
ownAddrs addrPortSet, ownAddrs addrPortSet,
sysResolvers SystemResolvers, sysResolvers SystemResolvers,
privateNets netutil.SubnetSet, privateNets netutil.SubnetSet,
@@ -289,7 +293,7 @@ func (req *jsonDNSConfig) validate(
) (err error) { ) (err error) {
defer func() { err = errors.Annotate(err, "validating dns config: %w") }() defer func() { err = errors.Annotate(err, "validating dns config: %w") }()
err = req.validateUpstreamDNSServers(ownAddrs, sysResolvers, privateNets) err = req.validateUpstreamDNSServers(ctx, l, ownAddrs, sysResolvers, privateNets)
if err != nil { if err != nil {
// Don't wrap the error since it's informative enough as is. // Don't wrap the error since it's informative enough as is.
return err return err
@@ -364,8 +368,10 @@ func (req *jsonDNSConfig) containsPrivateRDNS() (ok bool) {
} }
// checkPrivateRDNS returns an error if the configuration of the private RDNS is // checkPrivateRDNS returns an error if the configuration of the private RDNS is
// not valid. // not valid. l must not be nil.
func (req *jsonDNSConfig) checkPrivateRDNS( func (req *jsonDNSConfig) checkPrivateRDNS(
ctx context.Context,
l *slog.Logger,
ownAddrs addrPortSet, ownAddrs addrPortSet,
sysResolvers SystemResolvers, sysResolvers SystemResolvers,
privateNets netutil.SubnetSet, privateNets netutil.SubnetSet,
@@ -376,9 +382,16 @@ func (req *jsonDNSConfig) checkPrivateRDNS(
addrs := cmp.Or(req.LocalPTRUpstreams, &[]string{}) addrs := cmp.Or(req.LocalPTRUpstreams, &[]string{})
uc, err := newPrivateConfig(*addrs, ownAddrs, sysResolvers, privateNets, &upstream.Options{ uc, err := newPrivateConfig(
Logger: slogutil.NewDiscardLogger(), ctx,
}) l,
*addrs,
ownAddrs,
sysResolvers,
privateNets,
&upstream.Options{
Logger: slogutil.NewDiscardLogger(),
})
err = errors.WithDeferred(err, uc.Close()) err = errors.WithDeferred(err, uc.Close())
if err != nil { if err != nil {
return fmt.Errorf("private upstream servers: %w", err) return fmt.Errorf("private upstream servers: %w", err)
@@ -388,7 +401,10 @@ func (req *jsonDNSConfig) checkPrivateRDNS(
} }
// validateUpstreamDNSServers returns an error if any field of req is invalid. // validateUpstreamDNSServers returns an error if any field of req is invalid.
// l, ownAddrs, sysResolvers and privateNets must not be nil.
func (req *jsonDNSConfig) validateUpstreamDNSServers( func (req *jsonDNSConfig) validateUpstreamDNSServers(
ctx context.Context,
l *slog.Logger,
ownAddrs addrPortSet, ownAddrs addrPortSet,
sysResolvers SystemResolvers, sysResolvers SystemResolvers,
privateNets netutil.SubnetSet, privateNets netutil.SubnetSet,
@@ -406,7 +422,7 @@ func (req *jsonDNSConfig) validateUpstreamDNSServers(
} }
} }
err = req.checkPrivateRDNS(ownAddrs, sysResolvers, privateNets) err = req.checkPrivateRDNS(ctx, l, ownAddrs, sysResolvers, privateNets)
if err != nil { if err != nil {
// Don't wrap the error since it's informative enough as is. // Don't wrap the error since it's informative enough as is.
return err return err
@@ -533,7 +549,7 @@ func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) {
} }
// TODO(e.burkov): Consider prebuilding this set on startup. // TODO(e.burkov): Consider prebuilding this set on startup.
ourAddrs, err := s.conf.ourAddrsSet() ourAddrs, err := s.conf.ourAddrsSet(ctx, s.logger)
if err != nil { if err != nil {
// TODO(e.burkov): Put into openapi. // TODO(e.burkov): Put into openapi.
aghhttp.ErrorAndLog( aghhttp.ErrorAndLog(
@@ -549,7 +565,7 @@ func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) {
return return
} }
err = req.validate(ourAddrs, s.sysResolvers, s.privateNets, s.conf.CacheSize) err = req.validate(ctx, s.logger, ourAddrs, s.sysResolvers, s.privateNets, s.conf.CacheSize)
if err != nil { if err != nil {
aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusBadRequest, "%s", err) aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusBadRequest, "%s", err)
@@ -684,9 +700,10 @@ type upstreamJSON struct {
} }
// closeBoots closes all the provided bootstrap servers and logs errors if any. // closeBoots closes all the provided bootstrap servers and logs errors if any.
func closeBoots(boots []*upstream.UpstreamResolver) { // l must not be nil.
func closeBoots(ctx context.Context, l *slog.Logger, boots []*upstream.UpstreamResolver) {
for _, c := range boots { for _, c := range boots {
logCloserErr(c, "dnsforward: closing bootstrap %s: %s", c.Address()) logCloserErr(ctx, c, "closing bootstrap", l.With("address", c.Address()))
} }
} }
@@ -735,13 +752,13 @@ func (s *Server) handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
return return
} }
defer closeBoots(boots) defer closeBoots(ctx, s.logger, boots)
cv := newUpstreamConfigValidator(req.Upstreams, req.FallbackDNS, req.PrivateUpstreams, opts) cv := newUpstreamConfigValidator(ctx, req.Upstreams, req.FallbackDNS, req.PrivateUpstreams, opts)
cv.check() cv.check(ctx, s.logger)
cv.close() cv.close()
aghhttp.WriteJSONResponseOK(ctx, l, w, r, cv.status()) aghhttp.WriteJSONResponseOK(ctx, l, w, r, cv.status(ctx, l))
} }
// handleCacheClear is the handler for the POST /control/cache_clear HTTP API. // handleCacheClear is the handler for the POST /control/cache_clear HTTP API.
+27 -21
View File
@@ -3,10 +3,11 @@ package dnsforward
import ( import (
"context" "context"
"encoding/base64" "encoding/base64"
"log/slog"
"net" "net"
"strconv" "strconv"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/urlfilter/rules" "github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@@ -45,21 +46,25 @@ var strToSVCBKey = map[string]dns.SVCBKey{
"echconfig": dns.SVCB_ECHCONFIG, "echconfig": dns.SVCB_ECHCONFIG,
} }
// svcbKeyHandler is a handler for one SVCB parameter key. // svcbKeyHandler is a handler for one SVCB parameter key. l must not be nil.
type svcbKeyHandler func(valStr string) (val dns.SVCBKeyValue) type svcbKeyHandler func(
ctx context.Context,
l *slog.Logger,
valStr string,
) (val dns.SVCBKeyValue)
// svcbKeyHandlers are the supported SVCB parameters handlers. // svcbKeyHandlers are the supported SVCB parameters handlers.
var svcbKeyHandlers = map[string]svcbKeyHandler{ var svcbKeyHandlers = map[string]svcbKeyHandler{
"alpn": func(valStr string) (val dns.SVCBKeyValue) { "alpn": func(_ context.Context, _ *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
return &dns.SVCBAlpn{ return &dns.SVCBAlpn{
Alpn: []string{valStr}, Alpn: []string{valStr},
} }
}, },
"ech": func(valStr string) (val dns.SVCBKeyValue) { "ech": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
ech, err := base64.StdEncoding.DecodeString(valStr) ech, err := base64.StdEncoding.DecodeString(valStr)
if err != nil { if err != nil {
log.Debug("can't parse svcb/https ech: %s; ignoring", err) l.DebugContext(ctx, "can't parse svcb/https ech, ignoring", slogutil.KeyError, err)
return nil return nil
} }
@@ -69,10 +74,10 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{
} }
}, },
"ipv4hint": func(valStr string) (val dns.SVCBKeyValue) { "ipv4hint": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
ip := net.ParseIP(valStr) ip := net.ParseIP(valStr)
if ip4 := ip.To4(); ip == nil || ip4 == nil { if ip4 := ip.To4(); ip == nil || ip4 == nil {
log.Debug("can't parse svcb/https ipv4 hint %q; ignoring", valStr) l.DebugContext(ctx, "can't parse svcb/https ipv4 hint, ignoring", "value", valStr)
return nil return nil
} }
@@ -82,10 +87,10 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{
} }
}, },
"ipv6hint": func(valStr string) (val dns.SVCBKeyValue) { "ipv6hint": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
ip := net.ParseIP(valStr) ip := net.ParseIP(valStr)
if ip == nil { if ip == nil {
log.Debug("can't parse svcb/https ipv6 hint %q; ignoring", valStr) l.DebugContext(ctx, "can't parse svcb/https ipv6 hint, ignoring", "value", valStr)
return nil return nil
} }
@@ -95,10 +100,10 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{
} }
}, },
"mandatory": func(valStr string) (val dns.SVCBKeyValue) { "mandatory": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
code, ok := strToSVCBKey[valStr] code, ok := strToSVCBKey[valStr]
if !ok { if !ok {
log.Debug("unknown svcb/https mandatory key %q, ignoring", valStr) l.DebugContext(ctx, "unknown svcb/https mandatory key, ignoring", "value", valStr)
return nil return nil
} }
@@ -108,14 +113,14 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{
} }
}, },
"no-default-alpn": func(_ string) (val dns.SVCBKeyValue) { "no-default-alpn": func(_ context.Context, _ *slog.Logger, _ string) (val dns.SVCBKeyValue) {
return &dns.SVCBNoDefaultAlpn{} return &dns.SVCBNoDefaultAlpn{}
}, },
"port": func(valStr string) (val dns.SVCBKeyValue) { "port": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
port64, err := strconv.ParseUint(valStr, 10, 16) port64, err := strconv.ParseUint(valStr, 10, 16)
if err != nil { if err != nil {
log.Debug("can't parse svcb/https port: %s; ignoring", err) l.DebugContext(ctx, "can't parse svcb/https port; ignoring", slogutil.KeyError, err)
return nil return nil
} }
@@ -127,15 +132,16 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{
// TODO(a.garipov): This is the previous name for the parameter that has // TODO(a.garipov): This is the previous name for the parameter that has
// since been changed. Remove this in v0.109.0. // since been changed. Remove this in v0.109.0.
"echconfig": func(valStr string) (val dns.SVCBKeyValue) { "echconfig": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
log.Info( l.WarnContext(
`warning: svcb/https record parameter name "echconfig" is deprecated; ` + ctx,
`svcb/https record parameter name "echconfig" is deprecated; `+
`use "ech" instead`, `use "ech" instead`,
) )
ech, err := base64.StdEncoding.DecodeString(valStr) ech, err := base64.StdEncoding.DecodeString(valStr)
if err != nil { if err != nil {
log.Debug("can't parse svcb/https ech: %s; ignoring", err) l.DebugContext(ctx, "can't parse svcb/https ech; ignoring", slogutil.KeyError, err)
return nil return nil
} }
@@ -145,7 +151,7 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{
} }
}, },
"dohpath": func(valStr string) (val dns.SVCBKeyValue) { "dohpath": func(_ context.Context, _ *slog.Logger, valStr string) (val dns.SVCBKeyValue) {
return &dns.SVCBDoHPath{ return &dns.SVCBDoHPath{
Template: valStr, Template: valStr,
} }
@@ -187,7 +193,7 @@ func (s *Server) genAnswerSVCB(
continue continue
} }
val := handler(valStr) val := handler(ctx, s.logger, valStr)
if val == nil { if val == nil {
continue continue
} }
+16 -5
View File
@@ -1,14 +1,15 @@
package dnsforward package dnsforward
import ( import (
"context"
"fmt" "fmt"
"log/slog"
"slices" "slices"
"time" "time"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/stringutil" "github.com/AdguardTeam/golibs/stringutil"
) )
@@ -55,8 +56,10 @@ func newBootstrap(
// newUpstreamConfig returns the upstream configuration based on upstreams. If // newUpstreamConfig returns the upstream configuration based on upstreams. If
// upstreams slice specifies no default upstreams, defaultUpstreams are used to // upstreams slice specifies no default upstreams, defaultUpstreams are used to
// create upstreams with no domain specifications. opts are used when creating // create upstreams with no domain specifications. opts are used when creating
// upstream configuration. // upstream configuration. l must not be nil.
func newUpstreamConfig( func newUpstreamConfig(
ctx context.Context,
l *slog.Logger,
upstreams []string, upstreams []string,
defaultUpstreams []string, defaultUpstreams []string,
opts *upstream.Options, opts *upstream.Options,
@@ -67,7 +70,12 @@ func newUpstreamConfig(
} }
if len(uc.Upstreams) == 0 && len(defaultUpstreams) > 0 { if len(uc.Upstreams) == 0 && len(defaultUpstreams) > 0 {
log.Info("dnsforward: warning: no default upstreams specified, using %v", defaultUpstreams) l.WarnContext(
ctx,
"no default upstreams specified",
"default_upstreams",
defaultUpstreams,
)
var defaultUpstreamConfig *proxy.UpstreamConfig var defaultUpstreamConfig *proxy.UpstreamConfig
defaultUpstreamConfig, err = proxy.ParseUpstreamsConfig(defaultUpstreams, opts) defaultUpstreamConfig, err = proxy.ParseUpstreamsConfig(defaultUpstreams, opts)
@@ -84,8 +92,11 @@ func newUpstreamConfig(
// newPrivateConfig creates an upstream configuration for resolving PTR records // newPrivateConfig creates an upstream configuration for resolving PTR records
// for local addresses. The configuration is built either from the provided // for local addresses. The configuration is built either from the provided
// addresses or from the system resolvers. unwanted filters the resulting // addresses or from the system resolvers. unwanted filters the resulting
// upstream configuration. // upstream configuration. l, unwanted, sysResolvers, privateNets and opts must
// not be nil.
func newPrivateConfig( func newPrivateConfig(
ctx context.Context,
l *slog.Logger,
addrs []string, addrs []string,
unwanted addrPortSet, unwanted addrPortSet,
sysResolvers SystemResolvers, sysResolvers SystemResolvers,
@@ -103,7 +114,7 @@ func newPrivateConfig(
} }
} }
log.Debug("dnsforward: private-use upstreams: %v", addrs) l.DebugContext(ctx, "private-use upstreams", "addrs", addrs)
uc, err = proxy.ParseUpstreamsConfig(addrs, opts) uc, err = proxy.ParseUpstreamsConfig(addrs, opts)
if err != nil { if err != nil {
+12 -7
View File
@@ -143,15 +143,19 @@ func TestUpstreamConfigValidator(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
cv := newUpstreamConfigValidator(tc.general, tc.fallback, tc.private, &upstream.Options{ ctx := testutil.ContextWithTimeout(t, testTimeout)
opts := &upstream.Options{
Logger: testLogger, Logger: testLogger,
Timeout: upsTimeout, Timeout: upsTimeout,
Bootstrap: net.DefaultResolver, Bootstrap: net.DefaultResolver,
}) }
cv.check()
cv := newUpstreamConfigValidator(ctx, tc.general, tc.fallback, tc.private, opts)
cv.check(ctx, testLogger)
cv.close() cv.close()
assert.Equal(t, tc.want, cv.status()) assert.Equal(t, tc.want, cv.status(ctx, testLogger))
}) })
} }
} }
@@ -195,13 +199,14 @@ func TestUpstreamConfigValidator_Check_once(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
cv := newUpstreamConfigValidator(tc.ups, nil, nil, &upstream.Options{ ctx := testutil.ContextWithTimeout(t, testTimeout)
cv := newUpstreamConfigValidator(ctx, tc.ups, nil, nil, &upstream.Options{
Logger: testLogger, Logger: testLogger,
Timeout: testTimeout, Timeout: testTimeout,
}) })
go func() { go func() {
cv.check() cv.check(ctx, testLogger)
testutil.RequireSend(testutil.PanicT{}, reqCh, signal{}, testTimeout) testutil.RequireSend(testutil.PanicT{}, reqCh, signal{}, testTimeout)
}() }()
@@ -212,7 +217,7 @@ func TestUpstreamConfigValidator_Check_once(t *testing.T) {
testutil.RequireReceive(t, reqCh, testTimeout) testutil.RequireReceive(t, reqCh, testTimeout)
cv.close() cv.close()
require.Equal(t, wantStatus, cv.status()) require.Equal(t, wantStatus, cv.status(ctx, testLogger))
}) })
} }
} }
+2 -2
View File
@@ -34,7 +34,7 @@ func (Empty) Process(_ context.Context, _ netip.Addr) (host string, changed bool
type Exchanger interface { type Exchanger interface {
// Exchange tries to resolve the ip in a suitable way, i.e. either as local // Exchange tries to resolve the ip in a suitable way, i.e. either as local
// or as external. // or as external.
Exchange(ip netip.Addr) (host string, ttl time.Duration, err error) Exchange(ctx context.Context, ip netip.Addr) (host string, ttl time.Duration, err error)
} }
// Config is the configuration structure for Default. // Config is the configuration structure for Default.
@@ -93,7 +93,7 @@ func (r *Default) Process(ctx context.Context, ip netip.Addr) (host string, chan
return fromCache, false return fromCache, false
} }
host, ttl, err := r.exchanger.Exchange(ip) host, ttl, err := r.exchanger.Exchange(ctx, ip)
if err != nil { if err != nil {
r.logger.DebugContext(ctx, "resolving", "ip", ip, slogutil.KeyError, err) r.logger.DebugContext(ctx, "resolving", "ip", ip, slogutil.KeyError, err)
} }
+13 -3
View File
@@ -1,6 +1,7 @@
package rdns_test package rdns_test
import ( import (
"context"
"net/netip" "net/netip"
"testing" "testing"
"time" "time"
@@ -54,7 +55,10 @@ func TestDefault_Process(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
hit := 0 hit := 0
onExchange := func(ip netip.Addr) (host string, ttl time.Duration, err error) { onExchange := func(
_ context.Context,
ip netip.Addr,
) (host string, ttl time.Duration, err error) {
hit++ hit++
switch ip { switch ip {
@@ -94,7 +98,10 @@ func TestDefault_Process(t *testing.T) {
const cacheTTL = time.Second / 2 const cacheTTL = time.Second / 2
zeroTTLExchanger := &aghtest.Exchanger{ zeroTTLExchanger := &aghtest.Exchanger{
OnExchange: func(ip netip.Addr) (host string, ttl time.Duration, err error) { OnExchange: func(
_ context.Context,
ip netip.Addr,
) (host string, ttl time.Duration, err error) {
return revAddr1, 0, nil return revAddr1, 0, nil
}, },
} }
@@ -109,7 +116,10 @@ func TestDefault_Process(t *testing.T) {
require.True(t, changed) require.True(t, changed)
assert.Equal(t, revAddr1, got) assert.Equal(t, revAddr1, got)
zeroTTLExchanger.OnExchange = func(ip netip.Addr) (host string, ttl time.Duration, err error) { zeroTTLExchanger.OnExchange = func(
_ context.Context,
ip netip.Addr,
) (host string, ttl time.Duration, err error) {
return revAddr2, time.Hour, nil return revAddr2, time.Hour, nil
} }