Fix: dns cache behavior

This commit is contained in:
gVisor bot 2019-02-23 20:31:59 +08:00
parent 7e7b321ff9
commit b674db947b
2 changed files with 32 additions and 19 deletions

View file

@ -12,7 +12,6 @@ import (
"github.com/Dreamacro/clash/common/cache" "github.com/Dreamacro/clash/common/cache"
"github.com/Dreamacro/clash/common/picker" "github.com/Dreamacro/clash/common/picker"
C "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
D "github.com/miekg/dns" D "github.com/miekg/dns"
geoip2 "github.com/oschwald/geoip2-golang" geoip2 "github.com/oschwald/geoip2-golang"
@ -55,23 +54,17 @@ func (r *Resolver) Exchange(m *D.Msg) (msg *D.Msg, err error) {
cache, expireTime := r.cache.GetWithExpire(q.String()) cache, expireTime := r.cache.GetWithExpire(q.String())
if cache != nil { if cache != nil {
msg = cache.(*D.Msg).Copy() msg = cache.(*D.Msg).Copy()
if len(msg.Answer) > 0 { setMsgTTL(msg, uint32(expireTime.Sub(time.Now()).Seconds()))
ttl := uint32(expireTime.Sub(time.Now()).Seconds())
for _, answer := range msg.Answer {
answer.Header().Ttl = ttl
}
}
return return
} }
defer func() { defer func() {
if msg != nil { if msg == nil {
putMsgToCache(r.cache, q.String(), msg) return
if r.mapping { }
ips, err := r.msgToIP(msg)
if err != nil { putMsgToCache(r.cache, q.String(), msg)
log.Debugln("[DNS] msg to ip error: %s", err.Error()) if r.mapping {
return if ips, err := r.msgToIP(msg); err == nil {
}
for _, ip := range ips { for _, ip := range ips {
putMsgToCache(r.cache, ip.String(), msg) putMsgToCache(r.cache, ip.String(), msg)
} }

View file

@ -79,11 +79,31 @@ func (e EnhancedMode) String() string {
} }
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) { func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
if len(msg.Answer) == 0 { var ttl time.Duration
log.Debugln("[DNS] answer length is zero: %#v", msg) if len(msg.Answer) != 0 {
ttl = time.Duration(msg.Answer[0].Header().Ttl) * time.Second
} else if len(msg.Ns) != 0 {
ttl = time.Duration(msg.Ns[0].Header().Ttl) * time.Second
} else if len(msg.Extra) != 0 {
ttl = time.Duration(msg.Extra[0].Header().Ttl) * time.Second
} else {
log.Debugln("[DNS] response msg error: %#v", msg)
return return
} }
ttl := time.Duration(msg.Answer[0].Header().Ttl) * time.Second c.Put(key, msg.Copy(), ttl)
c.Put(key, msg, ttl) }
func setMsgTTL(msg *D.Msg, ttl uint32) {
for _, answer := range msg.Answer {
answer.Header().Ttl = ttl
}
for _, ns := range msg.Ns {
ns.Header().Ttl = ttl
}
for _, extra := range msg.Extra {
extra.Header().Ttl = ttl
}
} }