Clash.Meta/component/resolver/resolver.go

134 lines
2.4 KiB
Go
Raw Normal View History

package resolver
import (
"errors"
"net"
"strings"
"github.com/Dreamacro/clash/component/trie"
)
var (
// DefaultResolver aim to resolve ip
DefaultResolver Resolver
2020-06-18 18:11:02 +08:00
// DisableIPv6 means don't resolve ipv6 host
// default value is true
DisableIPv6 = true
// DefaultHosts aim to resolve hosts
DefaultHosts = trie.New()
)
var (
2020-06-18 18:11:02 +08:00
ErrIPNotFound = errors.New("couldn't find ip")
ErrIPVersion = errors.New("ip version error")
ErrIPv6Disabled = errors.New("ipv6 disabled")
)
type Resolver interface {
ResolveIP(host string) (ip net.IP, err error)
ResolveIPv4(host string) (ip net.IP, err error)
ResolveIPv6(host string) (ip net.IP, err error)
}
2019-09-11 17:00:55 +08:00
// ResolveIPv4 with a host, return ipv4
func ResolveIPv4(host string) (net.IP, error) {
if node := DefaultHosts.Search(host); node != nil {
if ip := node.Data.(net.IP).To4(); ip != nil {
return ip, nil
}
}
ip := net.ParseIP(host)
if ip != nil {
if !strings.Contains(host, ":") {
return ip, nil
}
return nil, ErrIPVersion
2019-09-11 17:00:55 +08:00
}
if DefaultResolver != nil {
return DefaultResolver.ResolveIPv4(host)
}
ipAddrs, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for _, ip := range ipAddrs {
2019-09-27 15:26:07 +08:00
if ip4 := ip.To4(); ip4 != nil {
return ip4, nil
2019-09-11 17:00:55 +08:00
}
}
return nil, ErrIPNotFound
2019-09-11 17:00:55 +08:00
}
// ResolveIPv6 with a host, return ipv6
func ResolveIPv6(host string) (net.IP, error) {
2020-06-18 18:11:02 +08:00
if DisableIPv6 {
return nil, ErrIPv6Disabled
}
2019-09-11 17:00:55 +08:00
if node := DefaultHosts.Search(host); node != nil {
if ip := node.Data.(net.IP).To16(); ip != nil {
return ip, nil
}
}
ip := net.ParseIP(host)
if ip != nil {
if strings.Contains(host, ":") {
return ip, nil
}
return nil, ErrIPVersion
2019-09-11 17:00:55 +08:00
}
if DefaultResolver != nil {
return DefaultResolver.ResolveIPv6(host)
}
ipAddrs, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for _, ip := range ipAddrs {
2019-09-27 15:26:07 +08:00
if ip.To4() == nil {
return ip, nil
2019-09-11 17:00:55 +08:00
}
}
return nil, ErrIPNotFound
2019-09-11 17:00:55 +08:00
}
// ResolveIP with a host, return ip
func ResolveIP(host string) (net.IP, error) {
2019-09-11 17:00:55 +08:00
if node := DefaultHosts.Search(host); node != nil {
return node.Data.(net.IP), nil
}
if DefaultResolver != nil {
2020-06-18 18:11:02 +08:00
if DisableIPv6 {
return DefaultResolver.ResolveIPv4(host)
}
return DefaultResolver.ResolveIP(host)
2020-06-18 18:11:02 +08:00
} else if DisableIPv6 {
return ResolveIPv4(host)
}
ip := net.ParseIP(host)
if ip != nil {
return ip, nil
}
ipAddr, err := net.ResolveIPAddr("ip", host)
if err != nil {
return nil, err
}
return ipAddr.IP, nil
}