nameserver.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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/session"
  11. "github.com/xtls/xray-core/common/strmatcher"
  12. "github.com/xtls/xray-core/core"
  13. "github.com/xtls/xray-core/features/dns"
  14. "github.com/xtls/xray-core/features/routing"
  15. )
  16. // Server is the interface for Name Server.
  17. type Server interface {
  18. // Name of the Client.
  19. Name() string
  20. IsDisableCache() bool
  21. // QueryIP sends IP queries to its configured server.
  22. QueryIP(ctx context.Context, domain string, option dns.IPOption) ([]net.IP, uint32, error)
  23. }
  24. // Client is the interface for DNS client.
  25. type Client struct {
  26. server Server
  27. skipFallback bool
  28. domains []string
  29. expectedIPs router.GeoIPMatcher
  30. unexpectedIPs router.GeoIPMatcher
  31. actPrior bool
  32. actUnprior bool
  33. tag string
  34. timeoutMs time.Duration
  35. finalQuery bool
  36. ipOption *dns.IPOption
  37. checkSystem bool
  38. policyID uint32
  39. }
  40. // NewServer creates a name server object according to the network destination url.
  41. func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dispatcher, disableCache bool, serveStale bool, serveExpiredTTL uint32, clientIP net.IP) (Server, error) {
  42. if address := dest.Address; address.Family().IsDomain() {
  43. u, err := url.Parse(address.Domain())
  44. if err != nil {
  45. return nil, err
  46. }
  47. switch {
  48. case strings.EqualFold(u.String(), "localhost"):
  49. return NewLocalNameServer(), nil
  50. case strings.EqualFold(u.Scheme, "https"): // DNS-over-HTTPS Remote mode
  51. return NewDoHNameServer(u, dispatcher, false, disableCache, serveStale, serveExpiredTTL, clientIP), nil
  52. case strings.EqualFold(u.Scheme, "h2c"): // DNS-over-HTTPS h2c Remote mode
  53. return NewDoHNameServer(u, dispatcher, true, disableCache, serveStale, serveExpiredTTL, clientIP), nil
  54. case strings.EqualFold(u.Scheme, "https+local"): // DNS-over-HTTPS Local mode
  55. return NewDoHNameServer(u, nil, false, disableCache, serveStale, serveExpiredTTL, clientIP), nil
  56. case strings.EqualFold(u.Scheme, "h2c+local"): // DNS-over-HTTPS h2c Local mode
  57. return NewDoHNameServer(u, nil, true, disableCache, serveStale, serveExpiredTTL, clientIP), nil
  58. case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode
  59. return NewQUICNameServer(u, disableCache, serveStale, serveExpiredTTL, clientIP)
  60. case strings.EqualFold(u.Scheme, "tcp"): // DNS-over-TCP Remote mode
  61. return NewTCPNameServer(u, dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
  62. case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode
  63. return NewTCPLocalNameServer(u, disableCache, serveStale, serveExpiredTTL, clientIP)
  64. case strings.EqualFold(u.String(), "fakedns"):
  65. var fd dns.FakeDNSEngine
  66. err = core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) {
  67. fd = fdns
  68. })
  69. if err != nil {
  70. return nil, err
  71. }
  72. return NewFakeDNSServer(fd), nil
  73. }
  74. }
  75. if dest.Network == net.Network_Unknown {
  76. dest.Network = net.Network_UDP
  77. }
  78. if dest.Network == net.Network_UDP { // UDP classic DNS mode
  79. return NewClassicNameServer(dest, dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP), nil
  80. }
  81. return nil, errors.New("No available name server could be created from ", dest).AtWarning()
  82. }
  83. // NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
  84. func NewClient(
  85. ctx context.Context,
  86. ns *NameServer,
  87. clientIP net.IP,
  88. disableCache bool, serveStale bool, serveExpiredTTL uint32,
  89. tag string,
  90. ipOption dns.IPOption,
  91. matcherInfos *[]*DomainMatcherInfo,
  92. updateDomainRule func(strmatcher.Matcher, int, []*DomainMatcherInfo) error,
  93. ) (*Client, error) {
  94. client := &Client{}
  95. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  96. // Create a new server for each client for now
  97. server, err := NewServer(ctx, ns.Address.AsDestination(), dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
  98. if err != nil {
  99. return errors.New("failed to create nameserver").Base(err).AtWarning()
  100. }
  101. // Prioritize local domains with specific TLDs or those without any dot for the local DNS
  102. if _, isLocalDNS := server.(*LocalNameServer); isLocalDNS {
  103. ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
  104. ns.OriginalRules = append(ns.OriginalRules, localTLDsAndDotlessDomainsRule)
  105. // The following lines is a solution to avoid core panics(rule index out of range) when setting `localhost` DNS client in config.
  106. // Because the `localhost` DNS client will append len(localTLDsAndDotlessDomains) rules into matcherInfos to match `geosite:private` default rule.
  107. // But `matcherInfos` has no enough length to add rules, which leads to core panics (rule index out of range).
  108. // 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.
  109. // Related issues:
  110. // https://github.com/v2fly/v2ray-core/issues/529
  111. // https://github.com/v2fly/v2ray-core/issues/719
  112. for i := 0; i < len(localTLDsAndDotlessDomains); i++ {
  113. *matcherInfos = append(*matcherInfos, &DomainMatcherInfo{
  114. clientIdx: uint16(0),
  115. domainRuleIdx: uint16(0),
  116. })
  117. }
  118. }
  119. // Establish domain rules
  120. var rules []string
  121. ruleCurr := 0
  122. ruleIter := 0
  123. for _, domain := range ns.PrioritizedDomain {
  124. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  125. if err != nil {
  126. return errors.New("failed to create prioritized domain").Base(err).AtWarning()
  127. }
  128. originalRuleIdx := ruleCurr
  129. if ruleCurr < len(ns.OriginalRules) {
  130. rule := ns.OriginalRules[ruleCurr]
  131. if ruleCurr >= len(rules) {
  132. rules = append(rules, rule.Rule)
  133. }
  134. ruleIter++
  135. if ruleIter >= int(rule.Size) {
  136. ruleIter = 0
  137. ruleCurr++
  138. }
  139. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  140. rules = append(rules, domainRule.String())
  141. ruleCurr++
  142. }
  143. err = updateDomainRule(domainRule, originalRuleIdx, *matcherInfos)
  144. if err != nil {
  145. return errors.New("failed to create prioritized domain").Base(err).AtWarning()
  146. }
  147. }
  148. // Establish expected IPs
  149. var expectedMatcher router.GeoIPMatcher
  150. if len(ns.ExpectedGeoip) > 0 {
  151. expectedMatcher, err = router.BuildOptimizedGeoIPMatcher(ns.ExpectedGeoip...)
  152. if err != nil {
  153. return errors.New("failed to create expected ip matcher").Base(err).AtWarning()
  154. }
  155. }
  156. // Establish unexpected IPs
  157. var unexpectedMatcher router.GeoIPMatcher
  158. if len(ns.UnexpectedGeoip) > 0 {
  159. unexpectedMatcher, err = router.BuildOptimizedGeoIPMatcher(ns.UnexpectedGeoip...)
  160. if err != nil {
  161. return errors.New("failed to create unexpected ip matcher").Base(err).AtWarning()
  162. }
  163. }
  164. if len(clientIP) > 0 {
  165. switch ns.Address.Address.GetAddress().(type) {
  166. case *net.IPOrDomain_Domain:
  167. errors.LogInfo(ctx, "DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String())
  168. case *net.IPOrDomain_Ip:
  169. errors.LogInfo(ctx, "DNS: client ", net.IP(ns.Address.Address.GetIp()), " uses clientIP ", clientIP.String())
  170. }
  171. }
  172. var timeoutMs = 4000 * time.Millisecond
  173. if ns.TimeoutMs > 0 {
  174. timeoutMs = time.Duration(ns.TimeoutMs) * time.Millisecond
  175. }
  176. checkSystem := ns.QueryStrategy == QueryStrategy_USE_SYS
  177. client.server = server
  178. client.skipFallback = ns.SkipFallback
  179. client.domains = rules
  180. client.expectedIPs = expectedMatcher
  181. client.unexpectedIPs = unexpectedMatcher
  182. client.actPrior = ns.ActPrior
  183. client.actUnprior = ns.ActUnprior
  184. client.tag = tag
  185. client.timeoutMs = timeoutMs
  186. client.finalQuery = ns.FinalQuery
  187. client.ipOption = &ipOption
  188. client.checkSystem = checkSystem
  189. client.policyID = ns.PolicyID
  190. return nil
  191. })
  192. return client, err
  193. }
  194. // Name returns the server name the client manages.
  195. func (c *Client) Name() string {
  196. return c.server.Name()
  197. }
  198. // QueryIP sends DNS query to the name server with the client's IP.
  199. func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  200. if c.checkSystem {
  201. supportIPv4, supportIPv6 := checkRoutes()
  202. option.IPv4Enable = option.IPv4Enable && supportIPv4
  203. option.IPv6Enable = option.IPv6Enable && supportIPv6
  204. } else {
  205. option.IPv4Enable = option.IPv4Enable && c.ipOption.IPv4Enable
  206. option.IPv6Enable = option.IPv6Enable && c.ipOption.IPv6Enable
  207. }
  208. if !option.IPv4Enable && !option.IPv6Enable {
  209. return nil, 0, dns.ErrEmptyResponse
  210. }
  211. ctx, cancel := context.WithTimeout(ctx, c.timeoutMs)
  212. ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: c.tag})
  213. ips, ttl, err := c.server.QueryIP(ctx, domain, option)
  214. cancel()
  215. if err != nil {
  216. return nil, 0, err
  217. }
  218. if len(ips) == 0 {
  219. return nil, 0, dns.ErrEmptyResponse
  220. }
  221. if c.expectedIPs != nil && !c.actPrior {
  222. ips, _ = c.expectedIPs.FilterIPs(ips)
  223. errors.LogDebug(context.Background(), "domain ", domain, " expectedIPs ", ips, " matched at server ", c.Name())
  224. if len(ips) == 0 {
  225. return nil, 0, dns.ErrEmptyResponse
  226. }
  227. }
  228. if c.unexpectedIPs != nil && !c.actUnprior {
  229. _, ips = c.unexpectedIPs.FilterIPs(ips)
  230. errors.LogDebug(context.Background(), "domain ", domain, " unexpectedIPs ", ips, " matched at server ", c.Name())
  231. if len(ips) == 0 {
  232. return nil, 0, dns.ErrEmptyResponse
  233. }
  234. }
  235. if c.expectedIPs != nil && c.actPrior {
  236. ipsNew, _ := c.expectedIPs.FilterIPs(ips)
  237. if len(ipsNew) > 0 {
  238. ips = ipsNew
  239. errors.LogDebug(context.Background(), "domain ", domain, " priorIPs ", ips, " matched at server ", c.Name())
  240. }
  241. }
  242. if c.unexpectedIPs != nil && c.actUnprior {
  243. _, ipsNew := c.unexpectedIPs.FilterIPs(ips)
  244. if len(ipsNew) > 0 {
  245. ips = ipsNew
  246. errors.LogDebug(context.Background(), "domain ", domain, " unpriorIPs ", ips, " matched at server ", c.Name())
  247. }
  248. }
  249. return ips, ttl, nil
  250. }
  251. func ResolveIpOptionOverride(queryStrategy QueryStrategy, ipOption dns.IPOption) dns.IPOption {
  252. switch queryStrategy {
  253. case QueryStrategy_USE_IP:
  254. return ipOption
  255. case QueryStrategy_USE_SYS:
  256. return ipOption
  257. case QueryStrategy_USE_IP4:
  258. return dns.IPOption{
  259. IPv4Enable: ipOption.IPv4Enable,
  260. IPv6Enable: false,
  261. FakeEnable: false,
  262. }
  263. case QueryStrategy_USE_IP6:
  264. return dns.IPOption{
  265. IPv4Enable: false,
  266. IPv6Enable: ipOption.IPv6Enable,
  267. FakeEnable: false,
  268. }
  269. default:
  270. return ipOption
  271. }
  272. }