diff --git a/common/dns/fakedns/middleware.go b/common/dns/fakedns/middleware.go index aae9847..01e4369 100644 --- a/common/dns/fakedns/middleware.go +++ b/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) diff --git a/common/dns/fakedns/server.go b/common/dns/fakedns/server.go index 896c3a3..5084b3c 100644 --- a/common/dns/fakedns/server.go +++ b/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{ diff --git a/common/dns/fakedns/utils.go b/common/dns/fakedns/utils.go index 5ac9ee1..b170bc0 100644 --- a/common/dns/fakedns/utils.go +++ b/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