Browse Source

hope fix lru cache bugs

pull/15/head
Jason 5 years ago
parent
commit
6949363adb
  1. 2
      common/dns/fakedns/middleware.go
  2. 18
      common/dns/fakedns/server.go
  3. 12
      common/dns/fakedns/utils.go

2
common/dns/fakedns/middleware.go

@ -34,7 +34,7 @@ func withFakeIP(cache *cache.Cache, pool *fakeip.Pool) handler {
msg.Answer = []D.RR{rr}
putMsgToCache(cache, "fakeip:"+q.String(), msg)
putMsgToMap(ipToHost, ip.String(), msg)
putMsgToCache(cache, ip.String(), msg)
setMsgTTL(msg, dnsFakeTTL)
_ = w.WriteMsg(msg)

18
common/dns/fakedns/server.go

@ -4,7 +4,6 @@ import (
"errors"
"net"
"strings"
"sync"
D "github.com/miekg/dns"
"github.com/xjasonlyu/tun2socks/common/fakeip"
@ -16,10 +15,6 @@ const (
dnsDefaultTTL uint32 = 600
)
var (
ipToHost sync.Map
)
// var cacheDuration = time.Duration(dnsDefaultTTL) * time.Second
type Server struct {
@ -62,7 +57,7 @@ func (s *Server) StartServer(addr string) error {
}
func (s *Server) IPToHost(ip net.IP) (string, bool) {
c, ok := ipToHost.Load(ip.String())
c, ok := s.c.Peek(ip.String())
if !ok {
return "", false
}
@ -80,8 +75,17 @@ func NewServer(fakeIPRange, hostsLine string, size int) (*Server, error) {
return nil, err
}
var cacheItem *cache.Cache
evictCallback := func(_ interface{}, value interface{}) {
msg := value.(*D.Msg).Copy()
q := msg.Question[0]
ip := msg.Answer[0].(*D.A).A
cacheItem.Remove("fakeip:" + q.String())
cacheItem.Remove(ip.String())
}
cacheItem = cache.New(size, evictCallback)
hosts := lineToHosts(hostsLine)
cacheItem := cache.New(size, evictCallback)
handler := newHandler(hosts, cacheItem, pool)
return &Server{

12
common/dns/fakedns/utils.go

@ -1,26 +1,14 @@
package fakedns
import (
"sync"
D "github.com/miekg/dns"
cache "github.com/xjasonlyu/tun2socks/common/lru-cache"
)
func putMsgToMap(m sync.Map, key string, msg *D.Msg) {
m.Store(key, msg.Copy())
}
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
c.Add(key, msg.Copy())
}
func evictCallback(_ interface{}, value interface{}) {
msg := value.(*D.Msg).Copy()
ip := msg.Answer[0].(*D.A).A
ipToHost.Delete(ip.String())
}
func setMsgTTL(msg *D.Msg, ttl uint32) {
for _, answer := range msg.Answer {
answer.Header().Ttl = ttl

Loading…
Cancel
Save