Cache DNS lookups when resolving safebrowsing or parental servers, also cache replacement hostnames as well.

This commit is contained in:
Eugene Bujak 2018-10-10 19:10:38 +03:00
parent e2295c1a11
commit a5d1053520
2 changed files with 33 additions and 13 deletions

View File

@ -45,6 +45,16 @@ func init() {
}) })
} }
type cacheEntry struct {
answer []dns.RR
lastUpdated time.Time
}
var (
lookupCacheTime = time.Minute * 30
lookupCache = map[string]cacheEntry{}
)
type plugSettings struct { type plugSettings struct {
SafeBrowsingBlockHost string SafeBrowsingBlockHost string
ParentalBlockHost string ParentalBlockHost string
@ -324,20 +334,29 @@ func (p *plug) replaceHostWithValAndReply(ctx context.Context, w dns.ResponseWri
records = append(records, result) records = append(records, result)
} else { } else {
// this is a domain name, need to look it up // this is a domain name, need to look it up
req := new(dns.Msg) cacheentry := lookupCache[val]
req.SetQuestion(dns.Fqdn(val), question.Qtype) if time.Since(cacheentry.lastUpdated) > lookupCacheTime {
req.RecursionDesired = true req := new(dns.Msg)
reqstate := request.Request{W: w, Req: req, Context: ctx} req.SetQuestion(dns.Fqdn(val), question.Qtype)
result, err := p.upstream.Lookup(reqstate, dns.Fqdn(val), reqstate.QType()) req.RecursionDesired = true
if err != nil { reqstate := request.Request{W: w, Req: req, Context: ctx}
log.Printf("Got error %s\n", err) result, err := p.upstream.Lookup(reqstate, dns.Fqdn(val), reqstate.QType())
return dns.RcodeServerFailure, fmt.Errorf("plugin/dnsfilter: %s", err) if err != nil {
} log.Printf("Got error %s\n", err)
if result != nil { return dns.RcodeServerFailure, fmt.Errorf("plugin/dnsfilter: %s", err)
for _, answer := range result.Answer {
answer.Header().Name = question.Name
} }
records = result.Answer if result != nil {
for _, answer := range result.Answer {
answer.Header().Name = question.Name
}
records = result.Answer
cacheentry.answer = result.Answer
cacheentry.lastUpdated = time.Now()
lookupCache[val] = cacheentry
}
} else {
// get from cache
records = cacheentry.answer
} }
} }
m := new(dns.Msg) m := new(dns.Msg)

View File

@ -16,6 +16,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
_ "github.com/benburkert/dns/init"
"github.com/bluele/gcache" "github.com/bluele/gcache"
"golang.org/x/net/publicsuffix" "golang.org/x/net/publicsuffix"
) )