nameserver.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package dns
  2. import (
  3. "context"
  4. "net/url"
  5. "strings"
  6. "time"
  7. "github.com/xtls/xray-core/app/router"
  8. "github.com/xtls/xray-core/common/errors"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/strmatcher"
  11. core "github.com/xtls/xray-core/core"
  12. "github.com/xtls/xray-core/features/dns"
  13. "github.com/xtls/xray-core/features/routing"
  14. )
  15. // Server is the interface for Name Server.
  16. type Server interface {
  17. // Name of the Client.
  18. Name() string
  19. // QueryIP sends IP queries to its configured server.
  20. QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns.IPOption, cs CacheStrategy) ([]net.IP, error)
  21. }
  22. // Client is the interface for DNS client.
  23. type Client struct {
  24. server Server
  25. clientIP net.IP
  26. domains []string
  27. expectIPs []*router.GeoIPMatcher
  28. }
  29. var errExpectedIPNonMatch = errors.New("expectIPs not match")
  30. // NewServer creates a name server object according to the network destination url.
  31. func NewServer(dest net.Destination, dispatcher routing.Dispatcher) (Server, error) {
  32. if address := dest.Address; address.Family().IsDomain() {
  33. u, err := url.Parse(address.Domain())
  34. if err != nil {
  35. return nil, err
  36. }
  37. switch {
  38. case strings.EqualFold(u.String(), "localhost"):
  39. return NewLocalNameServer(), nil
  40. case strings.EqualFold(u.Scheme, "https"): // DOH Remote mode
  41. return NewDoHNameServer(u, dispatcher)
  42. case strings.EqualFold(u.Scheme, "https+local"): // DOH Local mode
  43. return NewDoHLocalNameServer(u), nil
  44. case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode
  45. return NewQUICNameServer(u)
  46. case strings.EqualFold(u.String(), "fakedns"):
  47. return NewFakeDNSServer(), nil
  48. }
  49. }
  50. if dest.Network == net.Network_Unknown {
  51. dest.Network = net.Network_UDP
  52. }
  53. if dest.Network == net.Network_UDP { // UDP classic DNS mode
  54. return NewClassicNameServer(dest, dispatcher), nil
  55. }
  56. return nil, newError("No available name server could be created from ", dest).AtWarning()
  57. }
  58. // NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
  59. func NewClient(ctx context.Context, ns *NameServer, clientIP net.IP, container router.GeoIPMatcherContainer, matcherInfos *[]DomainMatcherInfo, updateDomainRule func(strmatcher.Matcher, int, []DomainMatcherInfo) error) (*Client, error) {
  60. client := &Client{}
  61. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  62. // Create a new server for each client for now
  63. server, err := NewServer(ns.Address.AsDestination(), dispatcher)
  64. if err != nil {
  65. return newError("failed to create nameserver").Base(err).AtWarning()
  66. }
  67. // Priotize local domains with specific TLDs or without any dot to local DNS
  68. if _, isLocalDNS := server.(*LocalNameServer); isLocalDNS {
  69. ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
  70. ns.OriginalRules = append(ns.OriginalRules, localTLDsAndDotlessDomainsRule)
  71. // The following lines is a solution to avoid core panics(rule index out of range) when setting `localhost` DNS client in config.
  72. // Because the `localhost` DNS client will apend len(localTLDsAndDotlessDomains) rules into matcherInfos to match `geosite:private` default rule.
  73. // But `matcherInfos` has no enough length to add rules, which leads to core panics (rule index out of range).
  74. // 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.
  75. for i := 0; i < len(localTLDsAndDotlessDomains); i++ {
  76. *matcherInfos = append(*matcherInfos, DomainMatcherInfo{
  77. clientIdx: uint16(0),
  78. domainRuleIdx: uint16(0),
  79. })
  80. }
  81. }
  82. // Establish domain rules
  83. var rules []string
  84. ruleCurr := 0
  85. ruleIter := 0
  86. for _, domain := range ns.PrioritizedDomain {
  87. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  88. if err != nil {
  89. return newError("failed to create prioritized domain").Base(err).AtWarning()
  90. }
  91. originalRuleIdx := ruleCurr
  92. if ruleCurr < len(ns.OriginalRules) {
  93. rule := ns.OriginalRules[ruleCurr]
  94. if ruleCurr >= len(rules) {
  95. rules = append(rules, rule.Rule)
  96. }
  97. ruleIter++
  98. if ruleIter >= int(rule.Size) {
  99. ruleIter = 0
  100. ruleCurr++
  101. }
  102. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  103. rules = append(rules, domainRule.String())
  104. ruleCurr++
  105. }
  106. err = updateDomainRule(domainRule, originalRuleIdx, *matcherInfos)
  107. if err != nil {
  108. return newError("failed to create prioritized domain").Base(err).AtWarning()
  109. }
  110. }
  111. // Establish expected IPs
  112. var matchers []*router.GeoIPMatcher
  113. for _, geoip := range ns.Geoip {
  114. matcher, err := container.Add(geoip)
  115. if err != nil {
  116. return newError("failed to create ip matcher").Base(err).AtWarning()
  117. }
  118. matchers = append(matchers, matcher)
  119. }
  120. if len(clientIP) > 0 {
  121. switch ns.Address.Address.GetAddress().(type) {
  122. case *net.IPOrDomain_Domain:
  123. newError("DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  124. case *net.IPOrDomain_Ip:
  125. newError("DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  126. }
  127. }
  128. client.server = server
  129. client.clientIP = clientIP
  130. client.domains = rules
  131. client.expectIPs = matchers
  132. return nil
  133. })
  134. return client, err
  135. }
  136. // NewSimpleClient creates a DNS client with a simple destination.
  137. func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.IP) (*Client, error) {
  138. client := &Client{}
  139. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  140. server, err := NewServer(endpoint.AsDestination(), dispatcher)
  141. if err != nil {
  142. return newError("failed to create nameserver").Base(err).AtWarning()
  143. }
  144. client.server = server
  145. client.clientIP = clientIP
  146. return nil
  147. })
  148. if len(clientIP) > 0 {
  149. switch endpoint.Address.GetAddress().(type) {
  150. case *net.IPOrDomain_Domain:
  151. newError("DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  152. case *net.IPOrDomain_Ip:
  153. newError("DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  154. }
  155. }
  156. return client, err
  157. }
  158. // Name returns the server name the client manages.
  159. func (c *Client) Name() string {
  160. return c.server.Name()
  161. }
  162. // QueryIP send DNS query to the name server with the client's IP.
  163. func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption, cs CacheStrategy) ([]net.IP, error) {
  164. ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
  165. ips, err := c.server.QueryIP(ctx, domain, c.clientIP, option, cs)
  166. cancel()
  167. if err != nil {
  168. return ips, err
  169. }
  170. return c.MatchExpectedIPs(domain, ips)
  171. }
  172. // MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
  173. func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
  174. if len(c.expectIPs) == 0 {
  175. return ips, nil
  176. }
  177. newIps := []net.IP{}
  178. for _, ip := range ips {
  179. for _, matcher := range c.expectIPs {
  180. if matcher.Match(ip) {
  181. newIps = append(newIps, ip)
  182. break
  183. }
  184. }
  185. }
  186. if len(newIps) == 0 {
  187. return nil, errExpectedIPNonMatch
  188. }
  189. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog()
  190. return newIps, nil
  191. }