dns.go 8.7 KB

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