clash/dns/enhancer.go

121 lines
2.4 KiB
Go
Raw Normal View History

package dns
import (
"net/netip"
"github.com/Dreamacro/clash/common/cache"
"github.com/Dreamacro/clash/component/fakeip"
C "github.com/Dreamacro/clash/constant"
)
type ResolverEnhancer struct {
mode C.DNSMode
fakePool *fakeip.Pool
mapping *cache.LruCache[netip.Addr, string]
}
func (h *ResolverEnhancer) FakeIPEnabled() bool {
return h.mode == C.DNSFakeIP
}
func (h *ResolverEnhancer) MappingEnabled() bool {
return h.mode == C.DNSFakeIP || h.mode == C.DNSMapping
}
2022-04-19 17:52:51 +00:00
func (h *ResolverEnhancer) IsExistFakeIP(ip netip.Addr) bool {
if !h.FakeIPEnabled() {
return false
}
if pool := h.fakePool; pool != nil {
2022-04-19 17:52:51 +00:00
return pool.Exist(ip)
}
return false
}
2022-04-19 17:52:51 +00:00
func (h *ResolverEnhancer) IsFakeIP(ip netip.Addr) bool {
if !h.FakeIPEnabled() {
return false
}
if pool := h.fakePool; pool != nil {
2022-04-19 17:52:51 +00:00
return pool.IPNet().Contains(ip) && ip != pool.Gateway() && ip != pool.Broadcast()
}
return false
}
2022-04-19 17:52:51 +00:00
func (h *ResolverEnhancer) IsFakeBroadcastIP(ip netip.Addr) bool {
if !h.FakeIPEnabled() {
return false
}
if pool := h.fakePool; pool != nil {
2022-04-19 17:52:51 +00:00
return pool.Broadcast() == ip
}
return false
}
2022-04-19 17:52:51 +00:00
func (h *ResolverEnhancer) FindHostByIP(ip netip.Addr) (string, bool) {
if pool := h.fakePool; pool != nil {
2022-04-19 17:52:51 +00:00
if host, existed := pool.LookBack(ip); existed {
return host, true
}
}
if mapping := h.mapping; mapping != nil {
2022-04-19 17:52:51 +00:00
if host, existed := h.mapping.Get(ip); existed {
2022-04-05 12:23:16 +00:00
return host, true
}
}
return "", false
}
2022-04-19 17:52:51 +00:00
func (h *ResolverEnhancer) InsertHostByIP(ip netip.Addr, host string) {
if mapping := h.mapping; mapping != nil {
2022-04-19 17:52:51 +00:00
h.mapping.Set(ip, host)
}
}
2022-04-12 21:55:08 +00:00
func (h *ResolverEnhancer) FlushFakeIP() error {
if h.fakePool != nil {
return h.fakePool.FlushFakeIP()
}
return nil
}
func (h *ResolverEnhancer) PatchFrom(o *ResolverEnhancer) {
if h.mapping != nil && o.mapping != nil {
o.mapping.CloneTo(h.mapping)
}
if h.fakePool != nil && o.fakePool != nil {
2021-10-11 12:48:58 +00:00
h.fakePool.CloneFrom(o.fakePool)
}
}
2022-04-13 08:47:47 +00:00
func (h *ResolverEnhancer) StoreFakePoolState() {
2022-03-22 17:05:43 +00:00
if h.fakePool != nil {
2022-04-12 21:55:08 +00:00
h.fakePool.StoreState()
2022-03-22 17:05:43 +00:00
}
}
func NewEnhancer(cfg Config) *ResolverEnhancer {
var fakePool *fakeip.Pool
var mapping *cache.LruCache[netip.Addr, string]
if cfg.EnhancedMode != C.DNSNormal {
fakePool = cfg.Pool
mapping = cache.NewLRUCache[netip.Addr, string](cache.WithSize[netip.Addr, string](4096), cache.WithStale[netip.Addr, string](true))
}
return &ResolverEnhancer{
mode: cfg.EnhancedMode,
fakePool: fakePool,
mapping: mapping,
}
}