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

50 lines
1.3 KiB
Go
Raw Permalink Normal View History

2020-11-25 14:01:53 +03:00
package dns
import (
"context"
"github.com/xtls/xray-core/common/errors"
2020-12-04 04:36:16 +03: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 14:01:53 +03: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 len(ctx.resolvedIPs) > 0 {
return ctx.resolvedIPs
}
if domain := ctx.GetTargetDomain(); len(domain) != 0 {
ips, err := ctx.dnsClient.LookupIP(domain, dns.IPOption{
IPv4Enable: true,
IPv6Enable: true,
FakeEnable: false,
})
2020-11-25 14:01:53 +03:00
if err == nil {
ctx.resolvedIPs = ips
return ips
}
errors.LogInfoInner(context.Background(), err, "resolve ip for ", domain)
2020-11-25 14:01:53 +03:00
}
2021-09-16 10:05:48 +03:00
if ips := ctx.Context.GetTargetIPs(); len(ips) != 0 {
return ips
}
2020-11-25 14:01:53 +03: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}
}