nameserver.go 7.6 KB

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