nameserver_local.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. }
  16. const errEmptyResponse = "No address associated with hostname"
  17. // QueryIP implements Server.
  18. func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) (ips []net.IP, err error) {
  19. start := time.Now()
  20. ips, err = s.client.LookupIP(domain, option)
  21. if err != nil && strings.HasSuffix(err.Error(), errEmptyResponse) {
  22. err = dns.ErrEmptyResponse
  23. }
  24. if len(ips) > 0 {
  25. errors.LogInfo(ctx, "Localhost got answer: ", domain, " -> ", ips)
  26. log.Record(&log.DNSLog{Server: s.Name(), Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
  27. }
  28. return
  29. }
  30. // Name implements Server.
  31. func (s *LocalNameServer) Name() string {
  32. return "localhost"
  33. }
  34. // NewLocalNameServer creates localdns server object for directly lookup in system DNS.
  35. func NewLocalNameServer() *LocalNameServer {
  36. errors.LogInfo(context.Background(), "DNS: created localhost client")
  37. return &LocalNameServer{
  38. client: localdns.New(),
  39. }
  40. }
  41. // NewLocalDNSClient creates localdns client object for directly lookup in system DNS.
  42. func NewLocalDNSClient() *Client {
  43. return &Client{server: NewLocalNameServer()}
  44. }