nameserver.go 7.7 KB

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