Xray-core/features/dns/localdns/client.go

87 lines
1.8 KiB
Go
Raw Normal View History

2020-11-25 11:01:53 +00:00
package localdns
import (
2020-12-04 01:36:16 +00:00
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/features/dns"
2020-11-25 11:01:53 +00:00
)
// Client is an implementation of dns.Client, which queries localhost for DNS.
type Client struct{}
// Type implements common.HasType.
func (*Client) Type() interface{} {
return dns.ClientType()
}
// Start implements common.Runnable.
func (*Client) Start() error { return nil }
// Close implements common.Closable.
func (*Client) Close() error { return nil }
// LookupIP implements Client.
2021-03-19 15:33:07 +00:00
func (*Client) LookupIP(host string) ([]net.IP, error) {
2020-11-25 11:01:53 +00:00
ips, err := net.LookupIP(host)
if err != nil {
return nil, err
}
parsedIPs := make([]net.IP, 0, len(ips))
for _, ip := range ips {
parsed := net.IPAddress(ip)
if parsed != nil {
parsedIPs = append(parsedIPs, parsed.IP())
}
2021-03-19 15:33:07 +00:00
}
if len(parsedIPs) == 0 {
return nil, dns.ErrEmptyResponse
}
return parsedIPs, nil
}
2021-04-09 15:36:36 +00:00
// LookupOptions implements Client.
2021-04-10 03:36:58 +00:00
func (c *Client) LookupOptions(host string, _ ...dns.Option) ([]net.IP, error) {
2021-04-09 15:36:36 +00:00
return c.LookupIP(host)
}
2021-03-19 15:33:07 +00:00
// LookupIPv4 implements IPv4Lookup.
func (c *Client) LookupIPv4(host string) ([]net.IP, error) {
ips, err := c.LookupIP(host)
if err != nil {
return nil, err
}
ipv4 := make([]net.IP, 0, len(ips))
for _, ip := range ips {
2020-11-25 11:01:53 +00:00
if len(ip) == net.IPv4len {
ipv4 = append(ipv4, ip)
}
2021-03-19 15:33:07 +00:00
}
if len(ipv4) == 0 {
return nil, dns.ErrEmptyResponse
}
return ipv4, nil
}
// LookupIPv6 implements IPv6Lookup.
func (c *Client) LookupIPv6(host string) ([]net.IP, error) {
ips, err := c.LookupIP(host)
if err != nil {
return nil, err
}
ipv6 := make([]net.IP, 0, len(ips))
for _, ip := range ips {
2020-11-25 11:01:53 +00:00
if len(ip) == net.IPv6len {
ipv6 = append(ipv6, ip)
}
}
2021-03-19 15:33:07 +00:00
if len(ipv6) == 0 {
return nil, dns.ErrEmptyResponse
2020-11-25 11:01:53 +00:00
}
2021-03-19 15:33:07 +00:00
return ipv6, nil
2020-11-25 11:01:53 +00:00
}
// New create a new dns.Client that queries localhost for DNS.
func New() *Client {
return &Client{}
}