Browse Source

optimize fakeip cache

pull/15/head
Jason 5 years ago
parent
commit
76a93f67ea
  1. 4
      common/dns/fakedns/middleware.go
  2. 8
      common/dns/fakedns/server.go
  3. 12
      common/dns/fakedns/utils.go

4
common/dns/fakedns/middleware.go

@ -17,9 +17,7 @@ func withFakeIP(cache *cache.Cache, pool *fakeip.Pool) handler {
return func(w D.ResponseWriter, r *D.Msg) {
q := r.Question[0]
cacheItem := cache.Get("fakeip:" + q.String())
if cacheItem != nil {
msg := cacheItem.(*D.Msg).Copy()
if msg := getMsgFromCache(cache, "fakeip:"+q.String()); msg != nil {
setMsgTTL(msg, dnsFakeTTL)
msg.SetReply(r)
_ = w.WriteMsg(msg)

8
common/dns/fakedns/server.go

@ -58,11 +58,11 @@ func (s *Server) StartServer(addr string) error {
}
func (s *Server) IPToHost(ip net.IP) (string, bool) {
c := s.c.Get(ip.String())
if c == nil {
msg := getMsgFromCache(s.c, ip.String())
if msg == nil {
return "", false
}
fqdn := c.(*D.Msg).Question[0].Name
fqdn := msg.Question[0].Name
return strings.TrimRight(fqdn, "."), true
}
@ -76,8 +76,8 @@ func NewServer(fakeIPRange, hostsLine string) (*Server, error) {
return nil, err
}
cacheItem := cache.New(cacheDuration)
hosts := lineToHosts(hostsLine)
cacheItem := cache.New(cacheDuration)
handler := newHandler(hosts, cacheItem, pool)
return &Server{

12
common/dns/fakedns/utils.go

@ -13,11 +13,21 @@ func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
if strings.HasPrefix(key, "fakeip:") {
ttl = time.Duration(dnsDefaultTTL) * time.Second
} else {
ttl = 6 * time.Duration(dnsDefaultTTL) * time.Second
ttl = 3 * time.Duration(dnsDefaultTTL) * time.Second
}
c.Put(key, msg.Copy(), ttl)
}
func getMsgFromCache(c *cache.Cache, key string) (msg *D.Msg) {
item := c.Get(key)
if item == nil {
return
}
msg = item.(*D.Msg).Copy()
putMsgToCache(c, key, msg)
return
}
func setMsgTTL(msg *D.Msg, ttl uint32) {
for _, answer := range msg.Answer {
answer.Header().Ttl = ttl

Loading…
Cancel
Save