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