nameserver.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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),
  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. errors.LogErrorInner(ctx, err, "failed to create domain matcher, ignore domain rule [type: ", domain.Type, ", domain: ", domain.Domain, "]")
  127. domainRule, _ = toStrMatcher(DomainMatchingType_Full, "hack.fix.index.for.illegal.domain.rule")
  128. }
  129. originalRuleIdx := ruleCurr
  130. if ruleCurr < len(ns.OriginalRules) {
  131. rule := ns.OriginalRules[ruleCurr]
  132. if ruleCurr >= len(rules) {
  133. rules = append(rules, rule.Rule)
  134. }
  135. ruleIter++
  136. if ruleIter >= int(rule.Size) {
  137. ruleIter = 0
  138. ruleCurr++
  139. }
  140. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  141. rules = append(rules, domainRule.String())
  142. ruleCurr++
  143. }
  144. updateDomainRule(domainRule, originalRuleIdx, *matcherInfos)
  145. }
  146. // Establish expected IPs
  147. var expectedMatcher router.GeoIPMatcher
  148. if len(ns.ExpectedGeoip) > 0 {
  149. expectedMatcher, err = router.BuildOptimizedGeoIPMatcher(ns.ExpectedGeoip...)
  150. if err != nil {
  151. return errors.New("failed to create expected ip matcher").Base(err).AtWarning()
  152. }
  153. }
  154. // Establish unexpected IPs
  155. var unexpectedMatcher router.GeoIPMatcher
  156. if len(ns.UnexpectedGeoip) > 0 {
  157. unexpectedMatcher, err = router.BuildOptimizedGeoIPMatcher(ns.UnexpectedGeoip...)
  158. if err != nil {
  159. return errors.New("failed to create unexpected ip matcher").Base(err).AtWarning()
  160. }
  161. }
  162. if len(clientIP) > 0 {
  163. switch ns.Address.Address.GetAddress().(type) {
  164. case *net.IPOrDomain_Domain:
  165. errors.LogInfo(ctx, "DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String())
  166. case *net.IPOrDomain_Ip:
  167. errors.LogInfo(ctx, "DNS: client ", net.IP(ns.Address.Address.GetIp()), " uses clientIP ", clientIP.String())
  168. }
  169. }
  170. var timeoutMs = 4000 * time.Millisecond
  171. if ns.TimeoutMs > 0 {
  172. timeoutMs = time.Duration(ns.TimeoutMs) * time.Millisecond
  173. }
  174. checkSystem := ns.QueryStrategy == QueryStrategy_USE_SYS
  175. client.server = server
  176. client.skipFallback = ns.SkipFallback
  177. client.domains = rules
  178. client.expectedIPs = expectedMatcher
  179. client.unexpectedIPs = unexpectedMatcher
  180. client.actPrior = ns.ActPrior
  181. client.actUnprior = ns.ActUnprior
  182. client.tag = tag
  183. client.timeoutMs = timeoutMs
  184. client.finalQuery = ns.FinalQuery
  185. client.ipOption = &ipOption
  186. client.checkSystem = checkSystem
  187. client.policyID = ns.PolicyID
  188. return nil
  189. })
  190. return client, err
  191. }
  192. // Name returns the server name the client manages.
  193. func (c *Client) Name() string {
  194. return c.server.Name()
  195. }
  196. // QueryIP sends DNS query to the name server with the client's IP.
  197. func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  198. if c.checkSystem {
  199. supportIPv4, supportIPv6 := checkRoutes()
  200. option.IPv4Enable = option.IPv4Enable && supportIPv4
  201. option.IPv6Enable = option.IPv6Enable && supportIPv6
  202. } else {
  203. option.IPv4Enable = option.IPv4Enable && c.ipOption.IPv4Enable
  204. option.IPv6Enable = option.IPv6Enable && c.ipOption.IPv6Enable
  205. }
  206. if !option.IPv4Enable && !option.IPv6Enable {
  207. return nil, 0, dns.ErrEmptyResponse
  208. }
  209. ctx, cancel := context.WithTimeout(ctx, c.timeoutMs)
  210. ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: c.tag})
  211. ips, ttl, err := c.server.QueryIP(ctx, domain, option)
  212. cancel()
  213. if err != nil {
  214. return nil, 0, err
  215. }
  216. if len(ips) == 0 {
  217. return nil, 0, dns.ErrEmptyResponse
  218. }
  219. if c.expectedIPs != nil && !c.actPrior {
  220. ips, _ = c.expectedIPs.FilterIPs(ips)
  221. errors.LogDebug(context.Background(), "domain ", domain, " expectedIPs ", ips, " matched at server ", c.Name())
  222. if len(ips) == 0 {
  223. return nil, 0, dns.ErrEmptyResponse
  224. }
  225. }
  226. if c.unexpectedIPs != nil && !c.actUnprior {
  227. _, ips = c.unexpectedIPs.FilterIPs(ips)
  228. errors.LogDebug(context.Background(), "domain ", domain, " unexpectedIPs ", ips, " matched at server ", c.Name())
  229. if len(ips) == 0 {
  230. return nil, 0, dns.ErrEmptyResponse
  231. }
  232. }
  233. if c.expectedIPs != nil && c.actPrior {
  234. ipsNew, _ := c.expectedIPs.FilterIPs(ips)
  235. if len(ipsNew) > 0 {
  236. ips = ipsNew
  237. errors.LogDebug(context.Background(), "domain ", domain, " priorIPs ", ips, " matched at server ", c.Name())
  238. }
  239. }
  240. if c.unexpectedIPs != nil && c.actUnprior {
  241. _, ipsNew := c.unexpectedIPs.FilterIPs(ips)
  242. if len(ipsNew) > 0 {
  243. ips = ipsNew
  244. errors.LogDebug(context.Background(), "domain ", domain, " unpriorIPs ", ips, " matched at server ", c.Name())
  245. }
  246. }
  247. return ips, ttl, nil
  248. }
  249. func ResolveIpOptionOverride(queryStrategy QueryStrategy, ipOption dns.IPOption) dns.IPOption {
  250. switch queryStrategy {
  251. case QueryStrategy_USE_IP:
  252. return ipOption
  253. case QueryStrategy_USE_SYS:
  254. return ipOption
  255. case QueryStrategy_USE_IP4:
  256. return dns.IPOption{
  257. IPv4Enable: ipOption.IPv4Enable,
  258. IPv6Enable: false,
  259. FakeEnable: false,
  260. }
  261. case QueryStrategy_USE_IP6:
  262. return dns.IPOption{
  263. IPv4Enable: false,
  264. IPv6Enable: ipOption.IPv6Enable,
  265. FakeEnable: false,
  266. }
  267. default:
  268. return ipOption
  269. }
  270. }