dns.go 9.0 KB

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