github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/features/routing/dns/context.go (about)

     1  package dns
     2  
     3  //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
     4  
     5  import (
     6  	"github.com/v2fly/v2ray-core/v5/common/net"
     7  	"github.com/v2fly/v2ray-core/v5/features/dns"
     8  	"github.com/v2fly/v2ray-core/v5/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 ips := ctx.Context.GetTargetIPs(); len(ips) != 0 {
    21  		return ips
    22  	}
    23  
    24  	if len(ctx.resolvedIPs) > 0 {
    25  		return ctx.resolvedIPs
    26  	}
    27  
    28  	if domain := ctx.GetTargetDomain(); len(domain) != 0 {
    29  		ips, err := ctx.dnsClient.LookupIP(domain)
    30  		if err == nil {
    31  			ctx.resolvedIPs = ips
    32  			return ips
    33  		}
    34  		newError("resolve ip for ", domain).Base(err).WriteToLog()
    35  	}
    36  
    37  	return nil
    38  }
    39  
    40  // ContextWithDNSClient creates a new routing context with domain resolving capability.
    41  // Resolved domain IPs can be retrieved by GetTargetIPs().
    42  func ContextWithDNSClient(ctx routing.Context, client dns.Client) routing.Context {
    43  	return &ResolvableContext{Context: ctx, dnsClient: client}
    44  }