From d4d35186c7fab9ad97056ff4372c9dd37b264972 Mon Sep 17 00:00:00 2001 From: Fedor Setrakov Date: Tue, 11 Nov 2025 15:01:10 +0300 Subject: [PATCH] Pull request 2520: AGDNS-3360-rm-log-dnsforward Squashed commit of the following: commit aca896ce0eb2b2a569f9dd2d41e5f23cd349a3ba Merge: d7feb54ff ba2fcd79a Author: f.setrakov Date: Tue Nov 11 14:48:53 2025 +0300 Merge branch 'master' into AGDNS-3360-rm-log-dnsforward commit d7feb54ff71075124c956daf688fbf29d9be2b47 Author: f.setrakov Date: Mon Nov 10 19:06:22 2025 +0300 dnsforward: imp log commit cb9403cb6e04934db9ce9ba04fc1b427d6a3c88b Author: f.setrakov Date: Fri Nov 7 11:03:41 2025 +0300 all: imp tests, imp docs commit f95e541cf008bf1eb0c2c0132f85dda86225f813 Author: f.setrakov Date: Thu Nov 6 13:07:59 2025 +0300 all: rm accidentally added files commit 49175747e3400244a0a893b9eb03410145433561 Author: f.setrakov Date: Thu Nov 6 12:53:49 2025 +0300 all: imp logs commit 8f8f6d843da82c20e7c7d51c46fc461852b364af Author: f.setrakov Date: Wed Nov 5 15:34:57 2025 +0300 dnsforward: imp log commit 08e7fe0e01a8f688b6b63c8baa1df0ec77679841 Author: f.setrakov Date: Wed Nov 5 15:32:33 2025 +0300 dnsforward: fix log format commit 4401776ff3eb85427d27234c8e50d5616dc017e6 Author: f.setrakov Date: Wed Nov 5 15:13:21 2025 +0300 all: imp logs commit bf842d1d4b3d45470be34ba376b0eee7331a1a6f Author: f.setrakov Date: Sat Nov 1 18:55:19 2025 +0300 all: rm golibs/log --- internal/aghtest/interface.go | 9 +- internal/client/addrproc_test.go | 29 ++++-- internal/dnsforward/beforerequest.go | 11 ++- internal/dnsforward/clientid.go | 14 ++- internal/dnsforward/clientid_internal_test.go | 3 +- internal/dnsforward/config.go | 26 +++-- internal/dnsforward/configvalidator.go | 94 ++++++++++++------- internal/dnsforward/dnsforward.go | 52 +++++----- .../dnsforward/dnsforward_internal_test.go | 6 +- internal/dnsforward/http.go | 53 +++++++---- internal/dnsforward/svcbmsg.go | 48 +++++----- internal/dnsforward/upstreams.go | 21 ++++- .../dnsforward/upstreams_internal_test.go | 19 ++-- internal/rdns/rdns.go | 4 +- internal/rdns/rdns_test.go | 16 +++- 15 files changed, 263 insertions(+), 142 deletions(-) diff --git a/internal/aghtest/interface.go b/internal/aghtest/interface.go index fb6841c87..2a570a1f5 100644 --- a/internal/aghtest/interface.go +++ b/internal/aghtest/interface.go @@ -113,15 +113,18 @@ func (p *AddressUpdater) UpdateAddress( // Exchanger is a fake [rdns.Exchanger] implementation for tests. 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 var _ rdns.Exchanger = (*Exchanger)(nil) // Exchange implements [rdns.Exchanger] interface for *Exchanger. -func (e *Exchanger) Exchange(ip netip.Addr) (host string, ttl time.Duration, err error) { - return e.OnExchange(ip) +func (e *Exchanger) Exchange( + 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. diff --git a/internal/client/addrproc_test.go b/internal/client/addrproc_test.go index 265ebd0d3..d2eb92ad9 100644 --- a/internal/client/addrproc_test.go +++ b/internal/client/addrproc_test.go @@ -99,16 +99,24 @@ func TestDefaultAddrProc_Process_rDNS(t *testing.T) { updIPCh := make(chan netip.Addr, 1) updHostCh := make(chan string, 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{ BaseLogger: slogutil.NewDiscardLogger(), - DialContext: func(_ context.Context, _, _ string) (conn net.Conn, err error) { - panic("not implemented") + DialContext: func( + ctx context.Context, + network, + addr string, + ) (conn net.Conn, err error) { + panic(testutil.UnexpectedCall(ctx, network, addr)) }, Exchanger: &aghtest.Exchanger{ - OnExchange: func(ip netip.Addr) (host string, ttl time.Duration, err error) { - return tc.host, 0, tc.rdnsErr - }, + OnExchange: onExchange, }, PrivateSubnets: netutil.SubnetSetFunc(netutil.IsLocallyServed), AddressUpdater: &aghtest.AddressUpdater{ @@ -211,15 +219,20 @@ func TestDefaultAddrProc_Process_WHOIS(t *testing.T) { updHostCh := make(chan string, 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{ BaseLogger: slogutil.NewDiscardLogger(), DialContext: func(_ context.Context, _, _ string) (conn net.Conn, err error) { return whoisConn, nil }, Exchanger: &aghtest.Exchanger{ - OnExchange: func(_ netip.Addr) (_ string, _ time.Duration, _ error) { - panic("not implemented") - }, + OnExchange: onExchange, }, PrivateSubnets: netutil.SubnetSetFunc(netutil.IsLocallyServed), AddressUpdater: &aghtest.AddressUpdater{ diff --git a/internal/dnsforward/beforerequest.go b/internal/dnsforward/beforerequest.go index 1d0a138ef..339775796 100644 --- a/internal/dnsforward/beforerequest.go +++ b/internal/dnsforward/beforerequest.go @@ -23,7 +23,9 @@ func (s *Server) HandleBefore( _ *proxy.Proxy, pctx *proxy.DNSContext, ) (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 { return &proxy.BeforeRequestError{ 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 // 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. -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 if proto == proxy.ProtoHTTPS { clientID, err = clientIDFromDNSContextHTTPS(pctx) @@ -85,7 +90,7 @@ func (s *Server) clientIDFromDNSContext(pctx *proxy.DNSContext) (clientID string return "", nil } - cliSrvName, err := clientServerName(pctx, proto) + cliSrvName, err := clientServerName(ctx, s.logger, pctx, proto) if err != nil { return "", fmt.Errorf("getting client server-name: %w", err) } diff --git a/internal/dnsforward/clientid.go b/internal/dnsforward/clientid.go index b648b8ef2..eab3e9324 100644 --- a/internal/dnsforward/clientid.go +++ b/internal/dnsforward/clientid.go @@ -1,15 +1,16 @@ package dnsforward import ( + "context" "crypto/tls" "fmt" + "log/slog" "net/http" "path" "strings" "github.com/AdguardTeam/AdGuardHome/internal/client" "github.com/AdguardTeam/dnsproxy/proxy" - "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" ) @@ -94,8 +95,13 @@ type tlsConn interface { // 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 -// if there is one. -func clientServerName(pctx *proxy.DNSContext, proto proxy.Proto) (srvName string, err error) { +// if there is one. l and pctx must not be nil. +func clientServerName( + ctx context.Context, + l *slog.Logger, + pctx *proxy.DNSContext, + proto proxy.Proto, +) (srvName string, err error) { from := "tls conn" switch proto { @@ -121,7 +127,7 @@ func clientServerName(pctx *proxy.DNSContext, proto proxy.Proto) (srvName string 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 } diff --git a/internal/dnsforward/clientid_internal_test.go b/internal/dnsforward/clientid_internal_test.go index f095c4484..5720d4ba9 100644 --- a/internal/dnsforward/clientid_internal_test.go +++ b/internal/dnsforward/clientid_internal_test.go @@ -228,7 +228,8 @@ func TestServer_clientIDFromDNSContext(t *testing.T) { HTTPRequest: httpReq, } - clientID, err := srv.clientIDFromDNSContext(pctx) + ctx := testutil.ContextWithTimeout(t, testTimeout) + clientID, err := srv.clientIDFromDNSContext(ctx, pctx) assert.Equal(t, tc.wantClientID, clientID) testutil.AssertErrorMsg(t, tc.wantErrMsg, err) diff --git a/internal/dnsforward/config.go b/internal/dnsforward/config.go index 94360ab69..4e3411aaa 100644 --- a/internal/dnsforward/config.go +++ b/internal/dnsforward/config.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "crypto/x509" "fmt" + "log/slog" "net" "net/netip" "os" @@ -22,7 +23,6 @@ import ( "github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/golibs/container" "github.com/AdguardTeam/golibs/errors" - "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/golibs/netutil" "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 -// the configuration itself. -func (conf *ServerConfig) loadUpstreams() (upstreams []string, err error) { +// the configuration itself. l must not be nil. +func (conf *ServerConfig) loadUpstreams( + ctx context.Context, + l *slog.Logger, +) (upstreams []string, err error) { if conf.UpstreamDNSFileName == "" { 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") - 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 } @@ -601,16 +604,16 @@ func filterOutAddrs(upsConf *proxy.UpstreamConfig, set addrPortSet) (err error) } // ourAddrsSet returns an addrPortSet that contains all the configured listening -// addresses. -func (conf *ServerConfig) ourAddrsSet() (m addrPortSet, err error) { +// addresses. l must not be nil. +func (conf *ServerConfig) ourAddrsSet(ctx context.Context, l *slog.Logger) (m addrPortSet, err error) { addrs, unspecPorts := conf.collectDNSAddrs() switch { case addrs.Len() == 0: - log.Debug("dnsforward: no listen addresses") + l.DebugContext(ctx, "no listen addresses") return emptyAddrPortSet{}, nil case unspecPorts.Len() == 0: - log.Debug("dnsforward: filtering out addresses %s", addrs) + l.DebugContext(ctx, "filtering out addresses", "addresses", addrs) return addrs, nil default: @@ -621,7 +624,12 @@ func (conf *ServerConfig) ourAddrsSet() (m addrPortSet, err error) { 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{ ports: unspecPorts, diff --git a/internal/dnsforward/configvalidator.go b/internal/dnsforward/configvalidator.go index 61ef89003..5d6e30bad 100644 --- a/internal/dnsforward/configvalidator.go +++ b/internal/dnsforward/configvalidator.go @@ -1,13 +1,15 @@ package dnsforward import ( + "context" "fmt" + "log/slog" "sync" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/golibs/errors" - "github.com/AdguardTeam/golibs/log" + "github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/miekg/dns" ) @@ -58,6 +60,7 @@ type parseResult struct { // validator for it. cv already contains the parsed upstreams along with errors // related. func newUpstreamConfigValidator( + ctx context.Context, general []string, fallback []string, private []string, @@ -70,15 +73,15 @@ func newUpstreamConfigValidator( } conf, err := proxy.ParseUpstreamsConfig(general, opts) - cv.generalParseResults = collectErrResults(general, err) + cv.generalParseResults = collectErrResults(ctx, opts.Logger, general, err) insertConfResults(conf, cv.generalUpstreamResults) conf, err = proxy.ParseUpstreamsConfig(fallback, opts) - cv.fallbackParseResults = collectErrResults(fallback, err) + cv.fallbackParseResults = collectErrResults(ctx, opts.Logger, fallback, err) insertConfResults(conf, cv.fallbackUpstreamResults) conf, err = proxy.ParseUpstreamsConfig(private, opts) - cv.privateParseResults = collectErrResults(private, err) + cv.privateParseResults = collectErrResults(ctx, opts.Logger, private, err) insertConfResults(conf, cv.privateUpstreamResults) return cv @@ -86,8 +89,8 @@ func newUpstreamConfigValidator( // collectErrResults parses err and returns parsing results containing the // original upstream configuration line and the corresponding error. err can be -// nil. -func collectErrResults(lines []string, err error) (results []*parseResult) { +// nil. l must not be nil. +func collectErrResults(ctx context.Context, l *slog.Logger, lines []string, err error) (results []*parseResult) { if err == nil { return nil } @@ -97,7 +100,7 @@ func collectErrResults(lines []string, err error) (results []*parseResult) { wrapper, ok := err.(errors.WrapperSlice) if !ok { - log.Debug("dnsforward: configvalidator: unwrapping: %s", err) + l.DebugContext(ctx, "unwrapping", slogutil.KeyError, err) return nil } @@ -107,7 +110,7 @@ func collectErrResults(lines []string, err error) (results []*parseResult) { for i, e := range errs { var parseErr *proxy.ParseError 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 } @@ -162,8 +165,8 @@ func insertListResults(ups []upstream.Upstream, results map[string]*upstreamResu // check tries to exchange with each successfully parsed upstream and enriches // 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 -// upstreams. -func (cv *upstreamConfigValidator) check() { +// upstreams. l must not be nil. +func (cv *upstreamConfigValidator) check(ctx context.Context, l *slog.Logger) { const ( // testTLD is the special-use fully-qualified domain name for testing // the DNS server reachability. @@ -193,22 +196,23 @@ func (cv *upstreamConfigValidator) check() { wg := &sync.WaitGroup{} for _, res := range cv.generalUpstreamResults { - wg.Go(func() { checkSrv(res, commonChecker) }) + wg.Go(func() { checkSrv(ctx, l, res, commonChecker) }) } for _, res := range cv.fallbackUpstreamResults { - wg.Go(func() { checkSrv(res, commonChecker) }) + wg.Go(func() { checkSrv(ctx, l, res, commonChecker) }) } for _, res := range cv.privateUpstreamResults { - wg.Go(func() { checkSrv(res, arpaChecker) }) + wg.Go(func() { checkSrv(ctx, l, res, arpaChecker) }) } wg.Wait() } // 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. -func checkSrv(res *upstreamResult, hc *healthchecker) { - defer log.OnPanic(fmt.Sprintf("dnsforward: checking upstream %s", res.server.Address())) +// error in res. It is used to be run in a separate goroutine. l must not be +// nil. +func checkSrv(ctx context.Context, l *slog.Logger, res *upstreamResult, hc *healthchecker) { + defer slogutil.RecoverAndLog(ctx, l) res.err = hc.check(res.server) if res.err != nil && res.isSpecific { @@ -247,8 +251,11 @@ const ( // status returns all the data collected during parsing, healthcheck, and // 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 -// no error. -func (cv *upstreamConfigValidator) status() (results map[string]string) { +// no error. l must not be nil. +func (cv *upstreamConfigValidator) status( + ctx context.Context, + l *slog.Logger, +) (results map[string]string) { // Names of the upstream configuration sections for logging. const ( generalSection = "general" @@ -259,30 +266,39 @@ func (cv *upstreamConfigValidator) status() (results map[string]string) { results = map[string]string{} 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 { - upstreamResultToStatus(fallbackSection, string(original), res, results) + upstreamResultToStatus(ctx, l, fallbackSection, string(original), res, results) } 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(fallbackTextLabel, fallbackSection, cv.fallbackParseResults, results) - parseResultToStatus(privateTextLabel, privateSection, cv.privateParseResults, results) + parseResultToStatus(ctx, l, generalTextLabel, generalSection, cv.generalParseResults, results) + parseResultToStatus( + ctx, + l, + fallbackTextLabel, + fallbackSection, + cv.fallbackParseResults, + results, + ) + parseResultToStatus(ctx, l, privateTextLabel, privateSection, cv.privateParseResults, results) return results } // upstreamResultToStatus puts "OK" or an error message from res into resMap. // 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 // put together in a single map, which may lead to collisions, see AG-27539. // Improve the results compilation. func upstreamResultToStatus( + ctx context.Context, + l *slog.Logger, section string, original string, res *upstreamResult, @@ -298,21 +314,22 @@ func upstreamResultToStatus( case "": resMap[original] = val case val: - log.Debug("dnsforward: duplicating %s config line %q", section, original) + l.DebugContext(ctx, "duplicating config line", "section", section, "address", original) default: - log.Debug( - "dnsforward: warning: %s config line %q (%v) had different result %v", - section, - val, - original, - prevVal, + l.WarnContext( + ctx, + "config line had different result", + "section", section, + "result", val, + "original", original, + "previous", prevVal, ) } } // parseResultToStatus puts parsing error messages from results into resMap. // 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: // @@ -321,6 +338,8 @@ func upstreamResultToStatus( // Where sectionTextLabel is a section text label of a localization and line is // a line number. func parseResultToStatus( + ctx context.Context, + l *slog.Logger, textLabel string, section string, results []*parseResult, @@ -330,7 +349,14 @@ func parseResultToStatus( original := res.original _, ok := resMap[original] if ok { - log.Debug("dnsforward: duplicating %s parsing error %q", section, original) + l.DebugContext( + ctx, + "duplicating parsing error", + "section", + section, + "original", + original, + ) continue } diff --git a/internal/dnsforward/dnsforward.go b/internal/dnsforward/dnsforward.go index 9b2e91f6f..44ad1e9d1 100644 --- a/internal/dnsforward/dnsforward.go +++ b/internal/dnsforward/dnsforward.go @@ -28,7 +28,6 @@ import ( "github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/golibs/cache" "github.com/AdguardTeam/golibs/errors" - "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil/sysresolv" @@ -375,7 +374,10 @@ const ( var _ rdns.Exchanger = (*Server)(nil) // 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() 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 hostFromPTR(dctx.Res) + return hostFromPTR(ctx, s.logger, dctx.Res) } -// hostFromPTR returns domain name from the PTR response or error. -func hostFromPTR(resp *dns.Msg) (host string, ttl time.Duration, err error) { +// hostFromPTR returns domain name from the PTR response or error. l must not +// 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. if resp.Rcode != dns.RcodeSuccess && resp.Rcode != dns.RcodeNameError { return "", 0, fmt.Errorf( @@ -436,7 +443,8 @@ func hostFromPTR(resp *dns.Msg) (host string, ttl time.Duration, err error) { 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 { ptr, ok := ans.(*dns.PTR) if !ok { @@ -542,23 +550,23 @@ func (s *Server) Prepare(ctx context.Context, conf *ServerConfig) (err error) { } // 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 var upstreams []string - upstreams, err = s.conf.loadUpstreams() + upstreams, err = s.conf.loadUpstreams(ctx, s.logger) if err != nil { 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), Bootstrap: boot, Timeout: s.conf.UpstreamTimeout, HTTPVersions: aghnet.UpstreamHTTPVersions(s.conf.UseHTTP3Upstreams), PreferIPv6: s.conf.BootstrapPreferIPv6, // 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 roots manually and pass it here. + // loading TLS roots does not always work properly on some routers so + // we're loading roots manually and pass it here. // // See [aghtls.SystemRootCAs]. // @@ -605,13 +613,13 @@ func (e *PrivateRDNSError) Unwrap() (err error) { // prepareLocalResolvers initializes the private RDNS upstream configuration // according to the server's settings. It assumes s.serverLock is locked or the // 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 { return nil, nil } var ownAddrs addrPortSet - ownAddrs, err = s.conf.ourAddrsSet() + ownAddrs, err = s.conf.ourAddrsSet(ctx, s.logger) if err != nil { // Don't wrap the error, because it's informative enough as is. return nil, err @@ -626,7 +634,7 @@ func (s *Server) prepareLocalResolvers() (uc *proxy.UpstreamConfig, err error) { } 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 { return nil, fmt.Errorf("preparing resolvers: %w", err) } @@ -662,13 +670,13 @@ func (s *Server) prepareInternalDNS(ctx context.Context) (err error) { return err } - err = s.prepareUpstreamSettings(s.bootstrap) + err = s.prepareUpstreamSettings(ctx, s.bootstrap) if err != nil { // Don't wrap the error, because it's informative enough as is. return err } - s.conf.PrivateRDNSUpstreamConfig, err = s.prepareLocalResolvers() + s.conf.PrivateRDNSUpstreamConfig, err = s.prepareLocalResolvers(ctx) if err != nil { return err } @@ -807,21 +815,21 @@ func (s *Server) stopLocked(ctx context.Context) { } 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 } -// logCloserErr logs the error returned by c, if any. -func logCloserErr(c io.Closer, format string, args ...any) { +// logCloserErr logs the error returned by c, if any. l and c must not be nil. +func logCloserErr(ctx context.Context, c io.Closer, msg string, l *slog.Logger) { if c == nil { return } err := c.Close() 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) - // It seems that net.Listener.Close() doesn't close file descriptors right away. - // We wait for some time and hope that this fd will be closed. + // It seems that net.Listener.Close() doesn't close file descriptors right + // away. We wait for some time and hope that this fd will be closed. time.Sleep(100 * time.Millisecond) if s.addrProc != nil { diff --git a/internal/dnsforward/dnsforward_internal_test.go b/internal/dnsforward/dnsforward_internal_test.go index b76f648af..ba762d62e 100644 --- a/internal/dnsforward/dnsforward_internal_test.go +++ b/internal/dnsforward/dnsforward_internal_test.go @@ -1840,7 +1840,8 @@ func TestServer_Exchange(t *testing.T) { 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) assert.Equal(t, tc.want, host) @@ -1863,7 +1864,8 @@ func TestServer_Exchange(t *testing.T) { ServePlainDNS: true, }) - host, _, eerr := srv.Exchange(localIP) + ctx := testutil.ContextWithTimeout(t, testTimeout) + host, _, eerr := srv.Exchange(ctx, localIP) require.NoError(t, eerr) assert.Empty(t, host) diff --git a/internal/dnsforward/http.go b/internal/dnsforward/http.go index 07b6245bf..29411a551 100644 --- a/internal/dnsforward/http.go +++ b/internal/dnsforward/http.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "log/slog" "net/http" "net/netip" "slices" @@ -186,7 +187,7 @@ func (s *Server) getDNSConfig(ctx context.Context) (c *jsonDNSConfig) { upstreamMode = jsonUpstreamModeFastestAddr } - defPTRUps, err := s.defaultLocalPTRUpstreams() + defPTRUps, err := s.defaultLocalPTRUpstreams(ctx) if err != nil { 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 // filtered of AdGuard Home's own DNS server addresses. It may appear empty. -func (s *Server) defaultLocalPTRUpstreams() (ups []string, err error) { - matcher, err := s.conf.ourAddrsSet() +func (s *Server) defaultLocalPTRUpstreams(ctx context.Context) (ups []string, err error) { + matcher, err := s.conf.ourAddrsSet(ctx, s.logger) if err != nil { // Don't wrap the error because it's informative enough as is. 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. func (req *jsonDNSConfig) validate( + ctx context.Context, + l *slog.Logger, ownAddrs addrPortSet, sysResolvers SystemResolvers, privateNets netutil.SubnetSet, @@ -289,7 +293,7 @@ func (req *jsonDNSConfig) validate( ) (err error) { 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 { // Don't wrap the error since it's informative enough as is. return err @@ -364,8 +368,10 @@ func (req *jsonDNSConfig) containsPrivateRDNS() (ok bool) { } // 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( + ctx context.Context, + l *slog.Logger, ownAddrs addrPortSet, sysResolvers SystemResolvers, privateNets netutil.SubnetSet, @@ -376,9 +382,16 @@ func (req *jsonDNSConfig) checkPrivateRDNS( addrs := cmp.Or(req.LocalPTRUpstreams, &[]string{}) - uc, err := newPrivateConfig(*addrs, ownAddrs, sysResolvers, privateNets, &upstream.Options{ - Logger: slogutil.NewDiscardLogger(), - }) + uc, err := newPrivateConfig( + ctx, + l, + *addrs, + ownAddrs, + sysResolvers, + privateNets, + &upstream.Options{ + Logger: slogutil.NewDiscardLogger(), + }) err = errors.WithDeferred(err, uc.Close()) if err != nil { 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. +// l, ownAddrs, sysResolvers and privateNets must not be nil. func (req *jsonDNSConfig) validateUpstreamDNSServers( + ctx context.Context, + l *slog.Logger, ownAddrs addrPortSet, sysResolvers SystemResolvers, 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 { // Don't wrap the error since it's informative enough as is. 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. - ourAddrs, err := s.conf.ourAddrsSet() + ourAddrs, err := s.conf.ourAddrsSet(ctx, s.logger) if err != nil { // TODO(e.burkov): Put into openapi. aghhttp.ErrorAndLog( @@ -549,7 +565,7 @@ func (s *Server) handleSetConfig(w http.ResponseWriter, r *http.Request) { 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 { 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. -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 { - 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 } - defer closeBoots(boots) + defer closeBoots(ctx, s.logger, boots) - cv := newUpstreamConfigValidator(req.Upstreams, req.FallbackDNS, req.PrivateUpstreams, opts) - cv.check() + cv := newUpstreamConfigValidator(ctx, req.Upstreams, req.FallbackDNS, req.PrivateUpstreams, opts) + cv.check(ctx, s.logger) 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. diff --git a/internal/dnsforward/svcbmsg.go b/internal/dnsforward/svcbmsg.go index 07c171aad..e143c0960 100644 --- a/internal/dnsforward/svcbmsg.go +++ b/internal/dnsforward/svcbmsg.go @@ -3,10 +3,11 @@ package dnsforward import ( "context" "encoding/base64" + "log/slog" "net" "strconv" - "github.com/AdguardTeam/golibs/log" + "github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/urlfilter/rules" "github.com/miekg/dns" ) @@ -45,21 +46,25 @@ var strToSVCBKey = map[string]dns.SVCBKey{ "echconfig": dns.SVCB_ECHCONFIG, } -// svcbKeyHandler is a handler for one SVCB parameter key. -type svcbKeyHandler func(valStr string) (val dns.SVCBKeyValue) +// svcbKeyHandler is a handler for one SVCB parameter key. l must not be nil. +type svcbKeyHandler func( + ctx context.Context, + l *slog.Logger, + valStr string, +) (val dns.SVCBKeyValue) // svcbKeyHandlers are the supported SVCB parameters handlers. 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{ 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) 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 } @@ -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) 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 } @@ -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) 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 } @@ -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] 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 } @@ -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{} }, - "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) 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 } @@ -127,15 +132,16 @@ var svcbKeyHandlers = map[string]svcbKeyHandler{ // TODO(a.garipov): This is the previous name for the parameter that has // since been changed. Remove this in v0.109.0. - "echconfig": func(valStr string) (val dns.SVCBKeyValue) { - log.Info( - `warning: svcb/https record parameter name "echconfig" is deprecated; ` + + "echconfig": func(ctx context.Context, l *slog.Logger, valStr string) (val dns.SVCBKeyValue) { + l.WarnContext( + ctx, + `svcb/https record parameter name "echconfig" is deprecated; `+ `use "ech" instead`, ) ech, err := base64.StdEncoding.DecodeString(valStr) 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 } @@ -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{ Template: valStr, } @@ -187,7 +193,7 @@ func (s *Server) genAnswerSVCB( continue } - val := handler(valStr) + val := handler(ctx, s.logger, valStr) if val == nil { continue } diff --git a/internal/dnsforward/upstreams.go b/internal/dnsforward/upstreams.go index 618601bd1..5bf7dcedc 100644 --- a/internal/dnsforward/upstreams.go +++ b/internal/dnsforward/upstreams.go @@ -1,14 +1,15 @@ package dnsforward import ( + "context" "fmt" + "log/slog" "slices" "time" "github.com/AdguardTeam/AdGuardHome/internal/aghnet" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/upstream" - "github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/stringutil" ) @@ -55,8 +56,10 @@ func newBootstrap( // newUpstreamConfig returns the upstream configuration based on upstreams. If // upstreams slice specifies no default upstreams, defaultUpstreams are used to // create upstreams with no domain specifications. opts are used when creating -// upstream configuration. +// upstream configuration. l must not be nil. func newUpstreamConfig( + ctx context.Context, + l *slog.Logger, upstreams []string, defaultUpstreams []string, opts *upstream.Options, @@ -67,7 +70,12 @@ func newUpstreamConfig( } 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 defaultUpstreamConfig, err = proxy.ParseUpstreamsConfig(defaultUpstreams, opts) @@ -84,8 +92,11 @@ func newUpstreamConfig( // newPrivateConfig creates an upstream configuration for resolving PTR records // for local addresses. The configuration is built either from the provided // 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( + ctx context.Context, + l *slog.Logger, addrs []string, unwanted addrPortSet, 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) if err != nil { diff --git a/internal/dnsforward/upstreams_internal_test.go b/internal/dnsforward/upstreams_internal_test.go index 4dbd289aa..06c340525 100644 --- a/internal/dnsforward/upstreams_internal_test.go +++ b/internal/dnsforward/upstreams_internal_test.go @@ -143,15 +143,19 @@ func TestUpstreamConfigValidator(t *testing.T) { for _, tc := range testCases { 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, Timeout: upsTimeout, Bootstrap: net.DefaultResolver, - }) - cv.check() + } + + cv := newUpstreamConfigValidator(ctx, tc.general, tc.fallback, tc.private, opts) + + cv.check(ctx, testLogger) 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 { 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, Timeout: testTimeout, }) go func() { - cv.check() + cv.check(ctx, testLogger) testutil.RequireSend(testutil.PanicT{}, reqCh, signal{}, testTimeout) }() @@ -212,7 +217,7 @@ func TestUpstreamConfigValidator_Check_once(t *testing.T) { testutil.RequireReceive(t, reqCh, testTimeout) cv.close() - require.Equal(t, wantStatus, cv.status()) + require.Equal(t, wantStatus, cv.status(ctx, testLogger)) }) } } diff --git a/internal/rdns/rdns.go b/internal/rdns/rdns.go index de84243cd..af5b9ec86 100644 --- a/internal/rdns/rdns.go +++ b/internal/rdns/rdns.go @@ -34,7 +34,7 @@ func (Empty) Process(_ context.Context, _ netip.Addr) (host string, changed bool type Exchanger interface { // Exchange tries to resolve the ip in a suitable way, i.e. either as local // 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. @@ -93,7 +93,7 @@ func (r *Default) Process(ctx context.Context, ip netip.Addr) (host string, chan return fromCache, false } - host, ttl, err := r.exchanger.Exchange(ip) + host, ttl, err := r.exchanger.Exchange(ctx, ip) if err != nil { r.logger.DebugContext(ctx, "resolving", "ip", ip, slogutil.KeyError, err) } diff --git a/internal/rdns/rdns_test.go b/internal/rdns/rdns_test.go index f0b27ed87..6226f5880 100644 --- a/internal/rdns/rdns_test.go +++ b/internal/rdns/rdns_test.go @@ -1,6 +1,7 @@ package rdns_test import ( + "context" "net/netip" "testing" "time" @@ -54,7 +55,10 @@ func TestDefault_Process(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { 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++ switch ip { @@ -94,7 +98,10 @@ func TestDefault_Process(t *testing.T) { const cacheTTL = time.Second / 2 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 }, } @@ -109,7 +116,10 @@ func TestDefault_Process(t *testing.T) { require.True(t, changed) 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 }