nameserver_local.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package dns
  2. import (
  3. "context"
  4. "strings"
  5. "time"
  6. "github.com/xtls/xray-core/common/errors"
  7. "github.com/xtls/xray-core/common/log"
  8. "github.com/xtls/xray-core/common/net"
  9. "github.com/xtls/xray-core/features/dns"
  10. "github.com/xtls/xray-core/features/dns/localdns"
  11. )
  12. // LocalNameServer is an wrapper over local DNS feature.
  13. type LocalNameServer struct {
  14. client *localdns.Client
  15. queryStrategy QueryStrategy
  16. }
  17. const errEmptyResponse = "No address associated with hostname"
  18. // QueryIP implements Server.
  19. func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) (ips []net.IP, err error) {
  20. option = ResolveIpOptionOverride(s.queryStrategy, option)
  21. if !option.IPv4Enable && !option.IPv6Enable {
  22. return nil, dns.ErrEmptyResponse
  23. }
  24. start := time.Now()
  25. ips, err = s.client.LookupIP(domain, option)
  26. if err != nil && strings.HasSuffix(err.Error(), errEmptyResponse) {
  27. err = dns.ErrEmptyResponse
  28. }
  29. if len(ips) > 0 {
  30. errors.LogInfo(ctx, "Localhost got answer: ", domain, " -> ", ips)
  31. log.Record(&log.DNSLog{Server: s.Name(), Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
  32. }
  33. return
  34. }
  35. // Name implements Server.
  36. func (s *LocalNameServer) Name() string {
  37. return "localhost"
  38. }
  39. // NewLocalNameServer creates localdns server object for directly lookup in system DNS.
  40. func NewLocalNameServer(queryStrategy QueryStrategy) *LocalNameServer {
  41. errors.LogInfo(context.Background(), "DNS: created localhost client")
  42. return &LocalNameServer{
  43. queryStrategy: queryStrategy,
  44. client: localdns.New(),
  45. }
  46. }
  47. // NewLocalDNSClient creates localdns client object for directly lookup in system DNS.
  48. func NewLocalDNSClient() *Client {
  49. return &Client{server: NewLocalNameServer(QueryStrategy_USE_IP)}
  50. }