Xray-core/features/routing/dns/context.go

45 lines
1.2 KiB
Go
Raw Normal View History

2020-11-25 11:01:53 +00:00
package dns
2020-12-04 01:36:16 +00:00
//go:generate go run github.com/xtls/xray-core/common/errors/errorgen
2020-11-25 11:01:53 +00:00
import (
2020-12-04 01:36:16 +00:00
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/features/dns"
"github.com/xtls/xray-core/features/routing"
2020-11-25 11:01:53 +00:00
)
// ResolvableContext is an implementation of routing.Context, with domain resolving capability.
type ResolvableContext struct {
routing.Context
dnsClient dns.Client
resolvedIPs []net.IP
}
// GetTargetIPs overrides original routing.Context's implementation.
func (ctx *ResolvableContext) GetTargetIPs() []net.IP {
if ips := ctx.Context.GetTargetIPs(); len(ips) != 0 {
return ips
}
if len(ctx.resolvedIPs) > 0 {
return ctx.resolvedIPs
}
if domain := ctx.GetTargetDomain(); len(domain) != 0 {
2021-04-09 15:36:36 +00:00
ips, err := ctx.dnsClient.LookupIP(domain)
2020-11-25 11:01:53 +00:00
if err == nil {
ctx.resolvedIPs = ips
return ips
}
2021-04-09 15:36:36 +00:00
newError("failed to resolve ip for ", domain).Base(err).WriteToLog()
2020-11-25 11:01:53 +00:00
}
return nil
}
// ContextWithDNSClient creates a new routing context with domain resolving capability.
// Resolved domain IPs can be retrieved by GetTargetIPs().
func ContextWithDNSClient(ctx routing.Context, client dns.Client) routing.Context {
return &ResolvableContext{Context: ctx, dnsClient: client}
}