dns.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Package dns is an implementation of core.DNS feature.
  2. package dns
  3. import (
  4. "context"
  5. go_errors "errors"
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "github.com/xtls/xray-core/common"
  11. "github.com/xtls/xray-core/common/errors"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/session"
  14. "github.com/xtls/xray-core/common/strmatcher"
  15. "github.com/xtls/xray-core/features/dns"
  16. )
  17. // DNS is a DNS rely server.
  18. type DNS struct {
  19. sync.Mutex
  20. disableFallback bool
  21. disableFallbackIfMatch bool
  22. ipOption *dns.IPOption
  23. hosts *StaticHosts
  24. clients []*Client
  25. ctx context.Context
  26. domainMatcher strmatcher.IndexMatcher
  27. matcherInfos []*DomainMatcherInfo
  28. checkSystem bool
  29. }
  30. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  31. type DomainMatcherInfo struct {
  32. clientIdx uint16
  33. domainRuleIdx uint16
  34. }
  35. // New creates a new DNS server with given configuration.
  36. func New(ctx context.Context, config *Config) (*DNS, error) {
  37. var clientIP net.IP
  38. switch len(config.ClientIp) {
  39. case 0, net.IPv4len, net.IPv6len:
  40. clientIP = net.IP(config.ClientIp)
  41. default:
  42. return nil, errors.New("unexpected client IP length ", len(config.ClientIp))
  43. }
  44. var ipOption dns.IPOption
  45. checkSystem := false
  46. switch config.QueryStrategy {
  47. case QueryStrategy_USE_IP:
  48. ipOption = dns.IPOption{
  49. IPv4Enable: true,
  50. IPv6Enable: true,
  51. FakeEnable: false,
  52. }
  53. case QueryStrategy_USE_SYS:
  54. ipOption = dns.IPOption{
  55. IPv4Enable: true,
  56. IPv6Enable: true,
  57. FakeEnable: false,
  58. }
  59. checkSystem = true
  60. case QueryStrategy_USE_IP4:
  61. ipOption = dns.IPOption{
  62. IPv4Enable: true,
  63. IPv6Enable: false,
  64. FakeEnable: false,
  65. }
  66. case QueryStrategy_USE_IP6:
  67. ipOption = dns.IPOption{
  68. IPv4Enable: false,
  69. IPv6Enable: true,
  70. FakeEnable: false,
  71. }
  72. default:
  73. return nil, errors.New("unexpected query strategy ", config.QueryStrategy)
  74. }
  75. hosts, err := NewStaticHosts(config.StaticHosts)
  76. if err != nil {
  77. return nil, errors.New("failed to create hosts").Base(err)
  78. }
  79. var clients []*Client
  80. domainRuleCount := 0
  81. var defaultTag = config.Tag
  82. if len(config.Tag) == 0 {
  83. defaultTag = generateRandomTag()
  84. }
  85. for _, ns := range config.NameServer {
  86. domainRuleCount += len(ns.PrioritizedDomain)
  87. }
  88. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  89. matcherInfos := make([]*DomainMatcherInfo, domainRuleCount+1)
  90. domainMatcher := &strmatcher.MatcherGroup{}
  91. for _, ns := range config.NameServer {
  92. clientIdx := len(clients)
  93. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []*DomainMatcherInfo) error {
  94. midx := domainMatcher.Add(domainRule)
  95. matcherInfos[midx] = &DomainMatcherInfo{
  96. clientIdx: uint16(clientIdx),
  97. domainRuleIdx: uint16(originalRuleIdx),
  98. }
  99. return nil
  100. }
  101. myClientIP := clientIP
  102. switch len(ns.ClientIp) {
  103. case net.IPv4len, net.IPv6len:
  104. myClientIP = net.IP(ns.ClientIp)
  105. }
  106. disableCache := config.DisableCache || ns.DisableCache
  107. var tag = defaultTag
  108. if len(ns.Tag) > 0 {
  109. tag = ns.Tag
  110. }
  111. clientIPOption := ResolveIpOptionOverride(ns.QueryStrategy, ipOption)
  112. if !clientIPOption.IPv4Enable && !clientIPOption.IPv6Enable {
  113. return nil, errors.New("no QueryStrategy available for ", ns.Address)
  114. }
  115. client, err := NewClient(ctx, ns, myClientIP, disableCache, tag, clientIPOption, &matcherInfos, updateDomain)
  116. if err != nil {
  117. return nil, errors.New("failed to create client").Base(err)
  118. }
  119. clients = append(clients, client)
  120. }
  121. // If there is no DNS client in config, add a `localhost` DNS client
  122. if len(clients) == 0 {
  123. clients = append(clients, NewLocalDNSClient(ipOption))
  124. }
  125. return &DNS{
  126. hosts: hosts,
  127. ipOption: &ipOption,
  128. clients: clients,
  129. ctx: ctx,
  130. domainMatcher: domainMatcher,
  131. matcherInfos: matcherInfos,
  132. disableFallback: config.DisableFallback,
  133. disableFallbackIfMatch: config.DisableFallbackIfMatch,
  134. checkSystem: checkSystem,
  135. }, nil
  136. }
  137. // Type implements common.HasType.
  138. func (*DNS) Type() interface{} {
  139. return dns.ClientType()
  140. }
  141. // Start implements common.Runnable.
  142. func (s *DNS) Start() error {
  143. return nil
  144. }
  145. // Close implements common.Closable.
  146. func (s *DNS) Close() error {
  147. return nil
  148. }
  149. // IsOwnLink implements proxy.dns.ownLinkVerifier
  150. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  151. inbound := session.InboundFromContext(ctx)
  152. if inbound == nil {
  153. return false
  154. }
  155. for _, client := range s.clients {
  156. if client.tag == inbound.Tag {
  157. return true
  158. }
  159. }
  160. return false
  161. }
  162. // LookupIP implements dns.Client.
  163. func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  164. // Normalize the FQDN form query
  165. domain = strings.TrimSuffix(domain, ".")
  166. if domain == "" {
  167. return nil, 0, errors.New("empty domain name")
  168. }
  169. if s.checkSystem {
  170. supportIPv4, supportIPv6 := checkSystemNetwork()
  171. option.IPv4Enable = option.IPv4Enable && supportIPv4
  172. option.IPv6Enable = option.IPv6Enable && supportIPv6
  173. } else {
  174. option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable
  175. option.IPv6Enable = option.IPv6Enable && s.ipOption.IPv6Enable
  176. }
  177. if !option.IPv4Enable && !option.IPv6Enable {
  178. return nil, 0, dns.ErrEmptyResponse
  179. }
  180. // Static host lookup
  181. switch addrs, err := s.hosts.Lookup(domain, option); {
  182. case err != nil:
  183. if go_errors.Is(err, dns.ErrEmptyResponse) {
  184. return nil, 0, dns.ErrEmptyResponse
  185. }
  186. return nil, 0, errors.New("returning nil for domain ", domain).Base(err)
  187. case addrs == nil: // Domain not recorded in static host
  188. break
  189. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  190. return nil, 0, dns.ErrEmptyResponse
  191. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  192. errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain())
  193. domain = addrs[0].Domain()
  194. default: // Successfully found ip records in static host
  195. errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs)
  196. ips, err := toNetIP(addrs)
  197. if err != nil {
  198. return nil, 0, err
  199. }
  200. return ips, 10, nil // Hosts ttl is 10
  201. }
  202. // Name servers lookup
  203. var errs []error
  204. for _, client := range s.sortClients(domain) {
  205. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  206. errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name())
  207. continue
  208. }
  209. ips, ttl, err := client.QueryIP(s.ctx, domain, option)
  210. if len(ips) > 0 {
  211. if ttl == 0 {
  212. ttl = 1
  213. }
  214. return ips, ttl, nil
  215. }
  216. errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name())
  217. if err == nil {
  218. err = dns.ErrEmptyResponse
  219. }
  220. errs = append(errs, err)
  221. if client.IsFinalQuery() {
  222. break
  223. }
  224. }
  225. if len(errs) > 0 {
  226. allErrs := errors.Combine(errs...)
  227. err0 := errs[0]
  228. if errors.AllEqual(err0, allErrs) {
  229. if go_errors.Is(err0, dns.ErrEmptyResponse) {
  230. return nil, 0, dns.ErrEmptyResponse
  231. }
  232. return nil, 0, errors.New("returning nil for domain ", domain).Base(err0)
  233. }
  234. return nil, 0, errors.New("returning nil for domain ", domain).Base(allErrs)
  235. }
  236. return nil, 0, dns.ErrEmptyResponse
  237. }
  238. func (s *DNS) sortClients(domain string) []*Client {
  239. clients := make([]*Client, 0, len(s.clients))
  240. clientUsed := make([]bool, len(s.clients))
  241. clientNames := make([]string, 0, len(s.clients))
  242. domainRules := []string{}
  243. // Priority domain matching
  244. hasMatch := false
  245. MatchSlice := s.domainMatcher.Match(domain)
  246. sort.Slice(MatchSlice, func(i, j int) bool {
  247. return MatchSlice[i] < MatchSlice[j]
  248. })
  249. for _, match := range MatchSlice {
  250. info := s.matcherInfos[match]
  251. client := s.clients[info.clientIdx]
  252. domainRule := client.domains[info.domainRuleIdx]
  253. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  254. if clientUsed[info.clientIdx] {
  255. continue
  256. }
  257. clientUsed[info.clientIdx] = true
  258. clients = append(clients, client)
  259. clientNames = append(clientNames, client.Name())
  260. hasMatch = true
  261. }
  262. if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
  263. // Default round-robin query
  264. for idx, client := range s.clients {
  265. if clientUsed[idx] || client.skipFallback {
  266. continue
  267. }
  268. clientUsed[idx] = true
  269. clients = append(clients, client)
  270. clientNames = append(clientNames, client.Name())
  271. }
  272. }
  273. if len(domainRules) > 0 {
  274. errors.LogDebug(s.ctx, "domain ", domain, " matches following rules: ", domainRules)
  275. }
  276. if len(clientNames) > 0 {
  277. errors.LogDebug(s.ctx, "domain ", domain, " will use DNS in order: ", clientNames)
  278. }
  279. if len(clients) == 0 {
  280. clients = append(clients, s.clients[0])
  281. clientNames = append(clientNames, s.clients[0].Name())
  282. errors.LogDebug(s.ctx, "domain ", domain, " will use the first DNS: ", clientNames)
  283. }
  284. return clients
  285. }
  286. func init() {
  287. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  288. return New(ctx, config.(*Config))
  289. }))
  290. }
  291. func checkSystemNetwork() (supportIPv4 bool, supportIPv6 bool) {
  292. conn4, err4 := net.Dial("udp4", "8.8.8.8:53")
  293. if err4 != nil {
  294. supportIPv4 = false
  295. } else {
  296. supportIPv4 = true
  297. conn4.Close()
  298. }
  299. conn6, err6 := net.Dial("udp6", "[2001:4860:4860::8888]:53")
  300. if err6 != nil {
  301. supportIPv6 = false
  302. } else {
  303. supportIPv6 = true
  304. conn6.Close()
  305. }
  306. return
  307. }