nameserver_fakedns.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //go:build !confonly
  2. // +build !confonly
  3. package dns
  4. import (
  5. "context"
  6. core "github.com/v2fly/v2ray-core/v5"
  7. "github.com/v2fly/v2ray-core/v5/common/net"
  8. "github.com/v2fly/v2ray-core/v5/features/dns"
  9. )
  10. type FakeDNSServer struct {
  11. fakeDNSEngine dns.FakeDNSEngine
  12. }
  13. func NewFakeDNSServer(fakeDNSEngine dns.FakeDNSEngine) *FakeDNSServer {
  14. return &FakeDNSServer{fakeDNSEngine: fakeDNSEngine}
  15. }
  16. func (FakeDNSServer) Name() string {
  17. return "fakedns"
  18. }
  19. func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, opt dns.IPOption, _ bool) ([]net.IP, error) {
  20. if !opt.FakeEnable {
  21. return nil, nil // Returning empty ip record with no error will continue DNS lookup, effectively indicating that this server is disabled.
  22. }
  23. if f.fakeDNSEngine == nil {
  24. if err := core.RequireFeatures(ctx, func(fd dns.FakeDNSEngine) {
  25. f.fakeDNSEngine = fd
  26. }); err != nil {
  27. return nil, newError("Unable to locate a fake DNS Engine").Base(err).AtError()
  28. }
  29. }
  30. var ips []net.Address
  31. if fkr0, ok := f.fakeDNSEngine.(dns.FakeDNSEngineRev0); ok {
  32. ips = fkr0.GetFakeIPForDomain3(domain, opt.IPv4Enable, opt.IPv6Enable)
  33. } else {
  34. ips = filterIP(f.fakeDNSEngine.GetFakeIPForDomain(domain), opt)
  35. }
  36. netIP, err := toNetIP(ips)
  37. if err != nil {
  38. return nil, newError("Unable to convert IP to net ip").Base(err).AtError()
  39. }
  40. newError(f.Name(), " got answer: ", domain, " -> ", ips).AtInfo().WriteToLog()
  41. if len(netIP) > 0 {
  42. return netIP, nil
  43. }
  44. return nil, dns.ErrEmptyResponse
  45. }
  46. func isFakeDNS(server Server) bool {
  47. _, ok := server.(*FakeDNSServer)
  48. return ok
  49. }