context.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package dns
  2. import (
  3. "context"
  4. "github.com/xtls/xray-core/common/errors"
  5. "github.com/xtls/xray-core/common/net"
  6. "github.com/xtls/xray-core/features/dns"
  7. "github.com/xtls/xray-core/features/routing"
  8. )
  9. // ResolvableContext is an implementation of routing.Context, with domain resolving capability.
  10. type ResolvableContext struct {
  11. routing.Context
  12. dnsClient dns.Client
  13. resolvedIPs []net.IP
  14. }
  15. // GetTargetIPs overrides original routing.Context's implementation.
  16. func (ctx *ResolvableContext) GetTargetIPs() []net.IP {
  17. if len(ctx.resolvedIPs) > 0 {
  18. return ctx.resolvedIPs
  19. }
  20. if domain := ctx.GetTargetDomain(); len(domain) != 0 {
  21. ips, err := ctx.dnsClient.LookupIP(domain, dns.IPOption{
  22. IPv4Enable: true,
  23. IPv6Enable: true,
  24. FakeEnable: false,
  25. })
  26. if err == nil {
  27. ctx.resolvedIPs = ips
  28. return ips
  29. }
  30. errors.LogInfoInner(context.Background(), err, "resolve ip for ", domain)
  31. }
  32. if ips := ctx.Context.GetTargetIPs(); len(ips) != 0 {
  33. return ips
  34. }
  35. return nil
  36. }
  37. // ContextWithDNSClient creates a new routing context with domain resolving capability.
  38. // Resolved domain IPs can be retrieved by GetTargetIPs().
  39. func ContextWithDNSClient(ctx routing.Context, client dns.Client) routing.Context {
  40. return &ResolvableContext{Context: ctx, dnsClient: client}
  41. }