From 45c10a17a6ca5bae17f0b63c79d590bc62185a17 Mon Sep 17 00:00:00 2001 From: Jiahao Lu Date: Thu, 24 Aug 2023 23:28:04 +0800 Subject: [PATCH] Fix: DNS NCACHE TTL and OPT RRs (#2900) * Fix: DNS NCACHE TTL and OPT RRs 1. DNS NCACHE was not correctly implemented. 2. OPT RRs must not be cached or forwarded. Closes #2889. --- dns/resolver.go | 6 +++++- dns/util.go | 28 +++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/dns/resolver.go b/dns/resolver.go index 75c907c..6342e0a 100644 --- a/dns/resolver.go +++ b/dns/resolver.go @@ -16,6 +16,7 @@ import ( C "github.com/Dreamacro/clash/constant" D "github.com/miekg/dns" + "github.com/samber/lo" "golang.org/x/sync/singleflight" ) @@ -166,7 +167,10 @@ func (r *Resolver) exchangeWithoutCache(ctx context.Context, m *D.Msg) (msg *D.M } msg := result.(*D.Msg) - + // OPT RRs MUST NOT be cached, forwarded, or stored in or loaded from master files. + msg.Extra = lo.Filter(msg.Extra, func(rr D.RR, index int) bool { + return rr.Header().Rrtype != D.TypeOPT + }) putMsgToCache(r.lruCache, q.String(), q, msg) }() diff --git a/dns/util.go b/dns/util.go index fea2f65..64a941a 100644 --- a/dns/util.go +++ b/dns/util.go @@ -6,22 +6,27 @@ import ( "errors" "fmt" "net" + "strings" "time" "github.com/Dreamacro/clash/common/cache" "github.com/Dreamacro/clash/common/picker" + "github.com/Dreamacro/clash/log" D "github.com/miekg/dns" "github.com/samber/lo" ) +const serverFailureCacheTTL uint32 = 5 + func minimalTTL(records []D.RR) uint32 { - if len(records) == 0 { + rr := lo.MinBy(records, func(r1 D.RR, r2 D.RR) bool { + return r1.Header().Ttl < r2.Header().Ttl + }) + if rr == nil { return 0 } - return lo.MinBy(records, func(r1 D.RR, r2 D.RR) bool { - return r1.Header().Ttl < r2.Header().Ttl - }).Header().Ttl + return rr.Header().Ttl } func updateTTL(records []D.RR, ttl uint32) { @@ -35,7 +40,20 @@ func updateTTL(records []D.RR, ttl uint32) { } func putMsgToCache(c *cache.LruCache, key string, q D.Question, msg *D.Msg) { - ttl := minimalTTL(msg.Answer) + // skip dns cache for acme challenge + if q.Qtype == D.TypeTXT && strings.HasPrefix(q.Name, "_acme-challenge.") { + log.Debugln("[DNS] dns cache ignored because of acme challenge for: %s", q.Name) + return + } + + var ttl uint32 + if msg.Rcode == D.RcodeServerFailure { + // [...] a resolver MAY cache a server failure response. + // If it does so it MUST NOT cache it for longer than five (5) minutes [...] + ttl = serverFailureCacheTTL + } else { + ttl = minimalTTL(append(append(msg.Answer, msg.Ns...), msg.Extra...)) + } if ttl == 0 { return }