Clash.Meta/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-20 01:52:51 +08:00
func (h *ResolverEnhancer) IsExistFakeIP(ip netip.Addr) bool {
if !h.FakeIPEnabled() {
return false
}
if pool := h.fakePool; pool != nil {
2022-04-20 01:52:51 +08:00
return pool.Exist(ip)
}
return false
}
2022-04-20 01:52:51 +08:00
func (h *ResolverEnhancer) IsFakeIP(ip netip.Addr) bool {
if !h.FakeIPEnabled() {
return false
}
if pool := h.fakePool; pool != nil {
2022-04-20 01:52:51 +08:00
return pool.IPNet().Contains(ip) && ip != pool.Gateway() && ip != pool.Broadcast()
}
return false
}
2022-04-20 01:52:51 +08:00
func (h *ResolverEnhancer) IsFakeBroadcastIP(ip netip.Addr) bool {
if !h.FakeIPEnabled() {
return false
}
if pool := h.fakePool; pool != nil {
2022-04-20 01:52:51 +08:00
return pool.Broadcast() == ip
}
return false
}
2022-04-20 01:52:51 +08:00
func (h *ResolverEnhancer) FindHostByIP(ip netip.Addr) (string, bool) {
if pool := h.fakePool; pool != nil {
2022-04-20 01:52:51 +08:00
if host, existed := pool.LookBack(ip); existed {
return host, true
}
}
if mapping := h.mapping; mapping != nil {
2022-04-20 01:52:51 +08:00
if host, existed := h.mapping.Get(ip); existed {
2022-04-05 20:23:16 +08:00
return host, true
}
}
return "", false
}
2022-04-20 01:52:51 +08:00
func (h *ResolverEnhancer) InsertHostByIP(ip netip.Addr, host string) {
if mapping := h.mapping; mapping != nil {
2022-04-20 01:52:51 +08:00
h.mapping.Set(ip, host)
}
}
2022-04-13 05:55:08 +08: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 20:48:58 +08:00
h.fakePool.CloneFrom(o.fakePool)
}
}
2022-04-13 16:47:47 +08:00
func (h *ResolverEnhancer) StoreFakePoolState() {
2022-03-23 01:05:43 +08:00
if h.fakePool != nil {
2022-04-13 05:55:08 +08:00
h.fakePool.StoreState()
2022-03-23 01:05:43 +08: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.New(cache.WithSize[netip.Addr, string](4096))
}
return &ResolverEnhancer{
mode: cfg.EnhancedMode,
fakePool: fakePool,
mapping: mapping,
}
}