2020-09-17 10:48:42 +08:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/Dreamacro/clash/common/cache"
|
|
|
|
"github.com/Dreamacro/clash/component/fakeip"
|
2021-10-18 21:08:27 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2020-09-17 10:48:42 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type ResolverEnhancer struct {
|
2021-10-18 21:08:27 +08:00
|
|
|
mode C.DNSMode
|
2020-09-17 10:48:42 +08:00
|
|
|
fakePool *fakeip.Pool
|
|
|
|
mapping *cache.LruCache
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *ResolverEnhancer) FakeIPEnabled() bool {
|
2021-10-18 21:08:27 +08:00
|
|
|
return h.mode == C.DNSFakeIP
|
2020-09-17 10:48:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *ResolverEnhancer) MappingEnabled() bool {
|
2021-10-18 21:08:27 +08:00
|
|
|
return h.mode == C.DNSFakeIP || h.mode == C.DNSMapping
|
2020-09-17 10:48:42 +08:00
|
|
|
}
|
|
|
|
|
2020-10-17 12:52:43 +08:00
|
|
|
func (h *ResolverEnhancer) IsExistFakeIP(ip net.IP) bool {
|
2020-09-17 10:48:42 +08:00
|
|
|
if !h.FakeIPEnabled() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if pool := h.fakePool; pool != nil {
|
|
|
|
return pool.Exist(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-10-17 12:52:43 +08:00
|
|
|
func (h *ResolverEnhancer) IsFakeIP(ip net.IP) bool {
|
|
|
|
if !h.FakeIPEnabled() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if pool := h.fakePool; pool != nil {
|
|
|
|
return pool.IPNet().Contains(ip) && !pool.Gateway().Equal(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-09-17 10:48:42 +08:00
|
|
|
func (h *ResolverEnhancer) FindHostByIP(ip net.IP) (string, bool) {
|
|
|
|
if pool := h.fakePool; pool != nil {
|
|
|
|
if host, existed := pool.LookBack(ip); existed {
|
|
|
|
return host, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if mapping := h.mapping; mapping != nil {
|
|
|
|
if host, existed := h.mapping.Get(ip.String()); existed {
|
|
|
|
return host.(string), true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
2020-09-17 10:48:42 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewEnhancer(cfg Config) *ResolverEnhancer {
|
|
|
|
var fakePool *fakeip.Pool
|
|
|
|
var mapping *cache.LruCache
|
|
|
|
|
2021-10-18 21:08:27 +08:00
|
|
|
if cfg.EnhancedMode != C.DNSNormal {
|
2020-09-17 10:48:42 +08:00
|
|
|
fakePool = cfg.Pool
|
2022-08-17 11:43:13 +08:00
|
|
|
mapping = cache.New(cache.WithSize(4096), cache.WithStale(true))
|
2020-09-17 10:48:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return &ResolverEnhancer{
|
|
|
|
mode: cfg.EnhancedMode,
|
|
|
|
fakePool: fakePool,
|
|
|
|
mapping: mapping,
|
|
|
|
}
|
|
|
|
}
|