dns.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // Package dns is an implementation of core.DNS feature.
  2. package dns
  3. import (
  4. "context"
  5. "fmt"
  6. "strings"
  7. "sync"
  8. "github.com/xtls/xray-core/app/router"
  9. "github.com/xtls/xray-core/common"
  10. "github.com/xtls/xray-core/common/errors"
  11. "github.com/xtls/xray-core/common/net"
  12. "github.com/xtls/xray-core/common/session"
  13. "github.com/xtls/xray-core/common/strmatcher"
  14. "github.com/xtls/xray-core/features/dns"
  15. )
  16. // DNS is a DNS rely server.
  17. type DNS struct {
  18. sync.Mutex
  19. tag string
  20. disableCache bool
  21. disableFallback bool
  22. disableFallbackIfMatch bool
  23. ipOption *dns.IPOption
  24. hosts *StaticHosts
  25. clients []*Client
  26. ctx context.Context
  27. domainMatcher strmatcher.IndexMatcher
  28. matcherInfos []*DomainMatcherInfo
  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 tag string
  38. if len(config.Tag) > 0 {
  39. tag = config.Tag
  40. } else {
  41. tag = generateRandomTag()
  42. }
  43. var clientIP net.IP
  44. switch len(config.ClientIp) {
  45. case 0, net.IPv4len, net.IPv6len:
  46. clientIP = net.IP(config.ClientIp)
  47. default:
  48. return nil, errors.New("unexpected client IP length ", len(config.ClientIp))
  49. }
  50. var ipOption *dns.IPOption
  51. switch config.QueryStrategy {
  52. case QueryStrategy_USE_IP:
  53. ipOption = &dns.IPOption{
  54. IPv4Enable: true,
  55. IPv6Enable: true,
  56. FakeEnable: false,
  57. }
  58. case QueryStrategy_USE_IP4:
  59. ipOption = &dns.IPOption{
  60. IPv4Enable: true,
  61. IPv6Enable: false,
  62. FakeEnable: false,
  63. }
  64. case QueryStrategy_USE_IP6:
  65. ipOption = &dns.IPOption{
  66. IPv4Enable: false,
  67. IPv6Enable: true,
  68. FakeEnable: false,
  69. }
  70. }
  71. hosts, err := NewStaticHosts(config.StaticHosts)
  72. if err != nil {
  73. return nil, errors.New("failed to create hosts").Base(err)
  74. }
  75. clients := []*Client{}
  76. domainRuleCount := 0
  77. for _, ns := range config.NameServer {
  78. domainRuleCount += len(ns.PrioritizedDomain)
  79. }
  80. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  81. matcherInfos := make([]*DomainMatcherInfo, domainRuleCount+1)
  82. domainMatcher := &strmatcher.MatcherGroup{}
  83. geoipContainer := router.GeoIPMatcherContainer{}
  84. for _, ns := range config.NameServer {
  85. clientIdx := len(clients)
  86. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []*DomainMatcherInfo) error {
  87. midx := domainMatcher.Add(domainRule)
  88. matcherInfos[midx] = &DomainMatcherInfo{
  89. clientIdx: uint16(clientIdx),
  90. domainRuleIdx: uint16(originalRuleIdx),
  91. }
  92. return nil
  93. }
  94. myClientIP := clientIP
  95. switch len(ns.ClientIp) {
  96. case net.IPv4len, net.IPv6len:
  97. myClientIP = net.IP(ns.ClientIp)
  98. }
  99. client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain)
  100. if err != nil {
  101. return nil, errors.New("failed to create client").Base(err)
  102. }
  103. clients = append(clients, client)
  104. }
  105. // If there is no DNS client in config, add a `localhost` DNS client
  106. if len(clients) == 0 {
  107. clients = append(clients, NewLocalDNSClient())
  108. }
  109. return &DNS{
  110. tag: tag,
  111. hosts: hosts,
  112. ipOption: ipOption,
  113. clients: clients,
  114. ctx: ctx,
  115. domainMatcher: domainMatcher,
  116. matcherInfos: matcherInfos,
  117. disableCache: config.DisableCache,
  118. disableFallback: config.DisableFallback,
  119. disableFallbackIfMatch: config.DisableFallbackIfMatch,
  120. }, nil
  121. }
  122. // Type implements common.HasType.
  123. func (*DNS) Type() interface{} {
  124. return dns.ClientType()
  125. }
  126. // Start implements common.Runnable.
  127. func (s *DNS) Start() error {
  128. return nil
  129. }
  130. // Close implements common.Closable.
  131. func (s *DNS) Close() error {
  132. return nil
  133. }
  134. // IsOwnLink implements proxy.dns.ownLinkVerifier
  135. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  136. inbound := session.InboundFromContext(ctx)
  137. return inbound != nil && inbound.Tag == s.tag
  138. }
  139. // LookupIP implements dns.Client.
  140. func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) {
  141. if domain == "" {
  142. return nil, errors.New("empty domain name")
  143. }
  144. option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable
  145. option.IPv6Enable = option.IPv6Enable && s.ipOption.IPv6Enable
  146. if !option.IPv4Enable && !option.IPv6Enable {
  147. return nil, dns.ErrEmptyResponse
  148. }
  149. // Normalize the FQDN form query
  150. domain = strings.TrimSuffix(domain, ".")
  151. // Static host lookup
  152. switch addrs := s.hosts.Lookup(domain, option); {
  153. case addrs == nil: // Domain not recorded in static host
  154. break
  155. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  156. return nil, dns.ErrEmptyResponse
  157. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  158. errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain())
  159. domain = addrs[0].Domain()
  160. default: // Successfully found ip records in static host
  161. errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs)
  162. return toNetIP(addrs)
  163. }
  164. // Name servers lookup
  165. errs := []error{}
  166. ctx := session.ContextWithInbound(s.ctx, &session.Inbound{Tag: s.tag})
  167. for _, client := range s.sortClients(domain) {
  168. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  169. errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name())
  170. continue
  171. }
  172. ips, err := client.QueryIP(ctx, domain, option, s.disableCache)
  173. if len(ips) > 0 {
  174. return ips, nil
  175. }
  176. if err != nil {
  177. errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name())
  178. errs = append(errs, err)
  179. }
  180. // 5 for RcodeRefused in miekg/dns, hardcode to reduce binary size
  181. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch && err != dns.ErrEmptyResponse && dns.RCodeFromError(err) != 5 {
  182. return nil, err
  183. }
  184. }
  185. return nil, errors.New("returning nil for domain ", domain).Base(errors.Combine(errs...))
  186. }
  187. // LookupHosts implements dns.HostsLookup.
  188. func (s *DNS) LookupHosts(domain string) *net.Address {
  189. domain = strings.TrimSuffix(domain, ".")
  190. if domain == "" {
  191. return nil
  192. }
  193. // Normalize the FQDN form query
  194. addrs := s.hosts.Lookup(domain, *s.ipOption)
  195. if len(addrs) > 0 {
  196. errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].String())
  197. return &addrs[0]
  198. }
  199. return nil
  200. }
  201. // GetIPOption implements ClientWithIPOption.
  202. func (s *DNS) GetIPOption() *dns.IPOption {
  203. return s.ipOption
  204. }
  205. // SetQueryOption implements ClientWithIPOption.
  206. func (s *DNS) SetQueryOption(isIPv4Enable, isIPv6Enable bool) {
  207. s.ipOption.IPv4Enable = isIPv4Enable
  208. s.ipOption.IPv6Enable = isIPv6Enable
  209. }
  210. // SetFakeDNSOption implements ClientWithIPOption.
  211. func (s *DNS) SetFakeDNSOption(isFakeEnable bool) {
  212. s.ipOption.FakeEnable = isFakeEnable
  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. for _, match := range s.domainMatcher.Match(domain) {
  222. info := s.matcherInfos[match]
  223. client := s.clients[info.clientIdx]
  224. domainRule := client.domains[info.domainRuleIdx]
  225. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  226. if clientUsed[info.clientIdx] {
  227. continue
  228. }
  229. clientUsed[info.clientIdx] = true
  230. clients = append(clients, client)
  231. clientNames = append(clientNames, client.Name())
  232. hasMatch = true
  233. }
  234. if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
  235. // Default round-robin query
  236. for idx, client := range s.clients {
  237. if clientUsed[idx] || client.skipFallback {
  238. continue
  239. }
  240. clientUsed[idx] = true
  241. clients = append(clients, client)
  242. clientNames = append(clientNames, client.Name())
  243. }
  244. }
  245. if len(domainRules) > 0 {
  246. errors.LogDebug(s.ctx, "domain ", domain, " matches following rules: ", domainRules)
  247. }
  248. if len(clientNames) > 0 {
  249. errors.LogDebug(s.ctx, "domain ", domain, " will use DNS in order: ", clientNames)
  250. }
  251. if len(clients) == 0 {
  252. clients = append(clients, s.clients[0])
  253. clientNames = append(clientNames, s.clients[0].Name())
  254. errors.LogDebug(s.ctx, "domain ", domain, " will use the first DNS: ", clientNames)
  255. }
  256. return clients
  257. }
  258. func init() {
  259. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  260. return New(ctx, config.(*Config))
  261. }))
  262. }