dns.go 8.4 KB

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