nameserver.go 8.3 KB

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