2020-11-25 13:01:53 +02:00
package dns
import (
"context"
2021-10-16 16:02:51 +03:00
"net/url"
"strings"
"time"
2020-11-25 13:01:53 +02:00
2021-10-16 16:02:51 +03:00
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/errors"
2020-12-04 03:36:16 +02:00
"github.com/xtls/xray-core/common/net"
2021-10-16 16:02:51 +03:00
"github.com/xtls/xray-core/common/strmatcher"
"github.com/xtls/xray-core/core"
2021-03-07 06:39:50 +02:00
"github.com/xtls/xray-core/features/dns"
2021-10-16 16:02:51 +03:00
"github.com/xtls/xray-core/features/routing"
2020-11-25 13:01:53 +02:00
)
2021-10-16 16:02:51 +03:00
// Server is the interface for Name Server.
type Server interface {
2020-11-25 13:01:53 +02:00
// Name of the Client.
Name ( ) string
// QueryIP sends IP queries to its configured server.
2021-10-16 16:02:51 +03:00
QueryIP ( ctx context . Context , domain string , clientIP net . IP , option dns . IPOption , disableCache bool ) ( [ ] net . IP , error )
}
// Client is the interface for DNS client.
type Client struct {
server Server
clientIP net . IP
skipFallback bool
domains [ ] string
expectIPs [ ] * router . GeoIPMatcher
}
var errExpectedIPNonMatch = errors . New ( "expectIPs not match" )
// NewServer creates a name server object according to the network destination url.
2024-12-11 03:07:52 +02:00
func NewServer ( dest net . Destination , dispatcher routing . Dispatcher , queryStrategy QueryStrategy , fd dns . FakeDNSEngine ) ( Server , error ) {
2021-10-16 16:02:51 +03:00
if address := dest . Address ; address . Family ( ) . IsDomain ( ) {
u , err := url . Parse ( address . Domain ( ) )
if err != nil {
return nil , err
}
switch {
case strings . EqualFold ( u . String ( ) , "localhost" ) :
return NewLocalNameServer ( ) , nil
case strings . EqualFold ( u . Scheme , "https" ) : // DOH Remote mode
2023-09-20 00:03:19 +03:00
return NewDoHNameServer ( u , dispatcher , queryStrategy )
2021-10-16 16:02:51 +03:00
case strings . EqualFold ( u . Scheme , "https+local" ) : // DOH Local mode
2023-09-20 00:03:19 +03:00
return NewDoHLocalNameServer ( u , queryStrategy ) , nil
2021-10-16 16:02:51 +03:00
case strings . EqualFold ( u . Scheme , "quic+local" ) : // DNS-over-QUIC Local mode
2023-09-20 00:03:19 +03:00
return NewQUICNameServer ( u , queryStrategy )
2021-10-16 16:02:51 +03:00
case strings . EqualFold ( u . Scheme , "tcp" ) : // DNS-over-TCP Remote mode
2023-09-20 00:03:19 +03:00
return NewTCPNameServer ( u , dispatcher , queryStrategy )
2021-10-16 16:02:51 +03:00
case strings . EqualFold ( u . Scheme , "tcp+local" ) : // DNS-over-TCP Local mode
2023-09-20 00:03:19 +03:00
return NewTCPLocalNameServer ( u , queryStrategy )
2021-10-16 16:02:51 +03:00
case strings . EqualFold ( u . String ( ) , "fakedns" ) :
2024-12-11 03:07:52 +02:00
return NewFakeDNSServer ( fd ) , nil
2021-10-16 16:02:51 +03:00
}
}
if dest . Network == net . Network_Unknown {
dest . Network = net . Network_UDP
}
if dest . Network == net . Network_UDP { // UDP classic DNS mode
2024-08-27 17:19:33 +03:00
return NewClassicNameServer ( dest , dispatcher , queryStrategy ) , nil
2021-10-16 16:02:51 +03:00
}
2024-06-29 21:32:57 +03:00
return nil , errors . New ( "No available name server could be created from " , dest ) . AtWarning ( )
2020-11-25 13:01:53 +02:00
}
2021-10-16 16:02:51 +03:00
// NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
2023-09-20 00:03:19 +03:00
func NewClient (
ctx context . Context ,
ns * NameServer ,
clientIP net . IP ,
container router . GeoIPMatcherContainer ,
matcherInfos * [ ] * DomainMatcherInfo ,
updateDomainRule func ( strmatcher . Matcher , int , [ ] * DomainMatcherInfo ) error ,
) ( * Client , error ) {
2021-10-16 16:02:51 +03:00
client := & Client { }
2024-12-11 03:07:52 +02:00
var fd dns . FakeDNSEngine
2021-10-16 16:02:51 +03:00
err := core . RequireFeatures ( ctx , func ( dispatcher routing . Dispatcher ) error {
2024-12-11 03:07:52 +02:00
core . RequireFeatures ( ctx , func ( fdns dns . FakeDNSEngine ) { // FakeDNSEngine is optional
fd = fdns
} )
2021-10-16 16:02:51 +03:00
// Create a new server for each client for now
2024-12-11 03:07:52 +02:00
server , err := NewServer ( ns . Address . AsDestination ( ) , dispatcher , ns . GetQueryStrategy ( ) , fd )
2021-10-16 16:02:51 +03:00
if err != nil {
2024-06-29 21:32:57 +03:00
return errors . New ( "failed to create nameserver" ) . Base ( err ) . AtWarning ( )
2021-10-16 16:02:51 +03:00
}
2024-07-12 01:20:06 +03:00
// Prioritize local domains with specific TLDs or those without any dot for the local DNS
2021-10-16 16:02:51 +03:00
if _ , isLocalDNS := server . ( * LocalNameServer ) ; isLocalDNS {
ns . PrioritizedDomain = append ( ns . PrioritizedDomain , localTLDsAndDotlessDomains ... )
ns . OriginalRules = append ( ns . OriginalRules , localTLDsAndDotlessDomainsRule )
// The following lines is a solution to avoid core panics( rule index out of range) when setting `localhost` DNS client in config.
2024-08-22 12:32:38 +03:00
// Because the `localhost` DNS client will append len(localTLDsAndDotlessDomains) rules into matcherInfos to match `geosite:private` default rule.
2021-10-16 16:02:51 +03:00
// But `matcherInfos` has no enough length to add rules, which leads to core panics (rule index out of range).
// To avoid this, the length of `matcherInfos` must be equal to the expected, so manually append it with Golang default zero value first for later modification.
// Related issues:
// https://github.com/v2fly/v2ray-core/issues/529
// https://github.com/v2fly/v2ray-core/issues/719
for i := 0 ; i < len ( localTLDsAndDotlessDomains ) ; i ++ {
* matcherInfos = append ( * matcherInfos , & DomainMatcherInfo {
clientIdx : uint16 ( 0 ) ,
domainRuleIdx : uint16 ( 0 ) ,
} )
}
}
// Establish domain rules
var rules [ ] string
ruleCurr := 0
ruleIter := 0
for _ , domain := range ns . PrioritizedDomain {
domainRule , err := toStrMatcher ( domain . Type , domain . Domain )
if err != nil {
2024-06-29 21:32:57 +03:00
return errors . New ( "failed to create prioritized domain" ) . Base ( err ) . AtWarning ( )
2021-10-16 16:02:51 +03:00
}
originalRuleIdx := ruleCurr
if ruleCurr < len ( ns . OriginalRules ) {
rule := ns . OriginalRules [ ruleCurr ]
if ruleCurr >= len ( rules ) {
rules = append ( rules , rule . Rule )
}
ruleIter ++
if ruleIter >= int ( rule . Size ) {
ruleIter = 0
ruleCurr ++
}
} else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
rules = append ( rules , domainRule . String ( ) )
ruleCurr ++
}
err = updateDomainRule ( domainRule , originalRuleIdx , * matcherInfos )
if err != nil {
2024-06-29 21:32:57 +03:00
return errors . New ( "failed to create prioritized domain" ) . Base ( err ) . AtWarning ( )
2021-10-16 16:02:51 +03:00
}
}
// Establish expected IPs
var matchers [ ] * router . GeoIPMatcher
for _ , geoip := range ns . Geoip {
matcher , err := container . Add ( geoip )
if err != nil {
2024-06-29 21:32:57 +03:00
return errors . New ( "failed to create ip matcher" ) . Base ( err ) . AtWarning ( )
2021-10-16 16:02:51 +03:00
}
matchers = append ( matchers , matcher )
}
if len ( clientIP ) > 0 {
switch ns . Address . Address . GetAddress ( ) . ( type ) {
case * net . IPOrDomain_Domain :
2024-06-29 21:32:57 +03:00
errors . LogInfo ( ctx , "DNS: client " , ns . Address . Address . GetDomain ( ) , " uses clientIP " , clientIP . String ( ) )
2021-10-16 16:02:51 +03:00
case * net . IPOrDomain_Ip :
2024-06-29 21:32:57 +03:00
errors . LogInfo ( ctx , "DNS: client " , ns . Address . Address . GetIp ( ) , " uses clientIP " , clientIP . String ( ) )
2021-10-16 16:02:51 +03:00
}
}
client . server = server
client . clientIP = clientIP
client . skipFallback = ns . SkipFallback
client . domains = rules
client . expectIPs = matchers
return nil
} )
return client , err
2020-11-25 13:01:53 +02:00
}
2021-10-16 16:02:51 +03:00
// Name returns the server name the client manages.
func ( c * Client ) Name ( ) string {
return c . server . Name ( )
2020-11-25 13:01:53 +02:00
}
2022-01-11 06:39:58 +02:00
// QueryIP sends DNS query to the name server with the client's IP.
2021-10-16 16:02:51 +03:00
func ( c * Client ) QueryIP ( ctx context . Context , domain string , option dns . IPOption , disableCache bool ) ( [ ] net . IP , error ) {
ctx , cancel := context . WithTimeout ( ctx , 4 * time . Second )
ips , err := c . server . QueryIP ( ctx , domain , c . clientIP , option , disableCache )
cancel ( )
if err != nil {
return ips , err
}
return c . MatchExpectedIPs ( domain , ips )
}
// MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
func ( c * Client ) MatchExpectedIPs ( domain string , ips [ ] net . IP ) ( [ ] net . IP , error ) {
if len ( c . expectIPs ) == 0 {
return ips , nil
}
newIps := [ ] net . IP { }
for _ , ip := range ips {
for _ , matcher := range c . expectIPs {
if matcher . Match ( ip ) {
newIps = append ( newIps , ip )
break
}
}
}
if len ( newIps ) == 0 {
return nil , errExpectedIPNonMatch
2020-11-25 13:01:53 +02:00
}
2024-06-29 21:32:57 +03:00
errors . LogDebug ( context . Background ( ) , "domain " , domain , " expectIPs " , newIps , " matched at server " , c . Name ( ) )
2021-10-16 16:02:51 +03:00
return newIps , nil
2020-11-25 13:01:53 +02:00
}
2023-09-20 00:03:19 +03:00
func ResolveIpOptionOverride ( queryStrategy QueryStrategy , ipOption dns . IPOption ) dns . IPOption {
switch queryStrategy {
case QueryStrategy_USE_IP :
return ipOption
case QueryStrategy_USE_IP4 :
return dns . IPOption {
IPv4Enable : ipOption . IPv4Enable ,
IPv6Enable : false ,
FakeEnable : false ,
}
case QueryStrategy_USE_IP6 :
return dns . IPOption {
IPv4Enable : false ,
IPv6Enable : ipOption . IPv6Enable ,
FakeEnable : false ,
}
default :
return ipOption
}
}