dns.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. serveStale := config.ServeStale || ns.ServeStale
  108. serveExpiredTTL := config.ServeExpiredTTL
  109. if ns.ServeExpiredTTL != nil {
  110. serveExpiredTTL = *ns.ServeExpiredTTL
  111. }
  112. var tag = defaultTag
  113. if len(ns.Tag) > 0 {
  114. tag = ns.Tag
  115. }
  116. clientIPOption := ResolveIpOptionOverride(ns.QueryStrategy, ipOption)
  117. if !clientIPOption.IPv4Enable && !clientIPOption.IPv6Enable {
  118. return nil, errors.New("no QueryStrategy available for ", ns.Address)
  119. }
  120. client, err := NewClient(ctx, ns, myClientIP, disableCache, serveStale, serveExpiredTTL, tag, clientIPOption, &matcherInfos, updateDomain)
  121. if err != nil {
  122. return nil, errors.New("failed to create client").Base(err)
  123. }
  124. clients = append(clients, client)
  125. }
  126. // If there is no DNS client in config, add a `localhost` DNS client
  127. if len(clients) == 0 {
  128. clients = append(clients, NewLocalDNSClient(ipOption))
  129. }
  130. return &DNS{
  131. hosts: hosts,
  132. ipOption: &ipOption,
  133. clients: clients,
  134. ctx: ctx,
  135. domainMatcher: domainMatcher,
  136. matcherInfos: matcherInfos,
  137. disableFallback: config.DisableFallback,
  138. disableFallbackIfMatch: config.DisableFallbackIfMatch,
  139. checkSystem: checkSystem,
  140. }, nil
  141. }
  142. // Type implements common.HasType.
  143. func (*DNS) Type() interface{} {
  144. return dns.ClientType()
  145. }
  146. // Start implements common.Runnable.
  147. func (s *DNS) Start() error {
  148. return nil
  149. }
  150. // Close implements common.Closable.
  151. func (s *DNS) Close() error {
  152. return nil
  153. }
  154. // IsOwnLink implements proxy.dns.ownLinkVerifier
  155. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  156. inbound := session.InboundFromContext(ctx)
  157. if inbound == nil {
  158. return false
  159. }
  160. for _, client := range s.clients {
  161. if client.tag == inbound.Tag {
  162. return true
  163. }
  164. }
  165. return false
  166. }
  167. // LookupIP implements dns.Client.
  168. func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  169. // Normalize the FQDN form query
  170. domain = strings.TrimSuffix(domain, ".")
  171. if domain == "" {
  172. return nil, 0, errors.New("empty domain name")
  173. }
  174. if s.checkSystem {
  175. supportIPv4, supportIPv6 := checkSystemNetwork()
  176. option.IPv4Enable = option.IPv4Enable && supportIPv4
  177. option.IPv6Enable = option.IPv6Enable && supportIPv6
  178. } else {
  179. option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable
  180. option.IPv6Enable = option.IPv6Enable && s.ipOption.IPv6Enable
  181. }
  182. if !option.IPv4Enable && !option.IPv6Enable {
  183. return nil, 0, dns.ErrEmptyResponse
  184. }
  185. // Static host lookup
  186. switch addrs, err := s.hosts.Lookup(domain, option); {
  187. case err != nil:
  188. if go_errors.Is(err, dns.ErrEmptyResponse) {
  189. return nil, 0, dns.ErrEmptyResponse
  190. }
  191. return nil, 0, errors.New("returning nil for domain ", domain).Base(err)
  192. case addrs == nil: // Domain not recorded in static host
  193. break
  194. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  195. return nil, 0, dns.ErrEmptyResponse
  196. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  197. errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain())
  198. domain = addrs[0].Domain()
  199. default: // Successfully found ip records in static host
  200. errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs)
  201. ips, err := toNetIP(addrs)
  202. if err != nil {
  203. return nil, 0, err
  204. }
  205. return ips, 10, nil // Hosts ttl is 10
  206. }
  207. // Name servers lookup
  208. var errs []error
  209. for _, client := range s.sortClients(domain) {
  210. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  211. errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name())
  212. continue
  213. }
  214. ips, ttl, err := client.QueryIP(s.ctx, domain, option)
  215. if len(ips) > 0 {
  216. if ttl == 0 {
  217. ttl = 1
  218. }
  219. return ips, ttl, nil
  220. }
  221. errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name())
  222. if err == nil {
  223. err = dns.ErrEmptyResponse
  224. }
  225. errs = append(errs, err)
  226. if client.IsFinalQuery() {
  227. break
  228. }
  229. }
  230. if len(errs) > 0 {
  231. allErrs := errors.Combine(errs...)
  232. err0 := errs[0]
  233. if errors.AllEqual(err0, allErrs) {
  234. if go_errors.Is(err0, dns.ErrEmptyResponse) {
  235. return nil, 0, dns.ErrEmptyResponse
  236. }
  237. return nil, 0, errors.New("returning nil for domain ", domain).Base(err0)
  238. }
  239. return nil, 0, errors.New("returning nil for domain ", domain).Base(allErrs)
  240. }
  241. return nil, 0, dns.ErrEmptyResponse
  242. }
  243. func (s *DNS) sortClients(domain string) []*Client {
  244. clients := make([]*Client, 0, len(s.clients))
  245. clientUsed := make([]bool, len(s.clients))
  246. clientNames := make([]string, 0, len(s.clients))
  247. domainRules := []string{}
  248. // Priority domain matching
  249. hasMatch := false
  250. MatchSlice := s.domainMatcher.Match(domain)
  251. sort.Slice(MatchSlice, func(i, j int) bool {
  252. return MatchSlice[i] < MatchSlice[j]
  253. })
  254. for _, match := range MatchSlice {
  255. info := s.matcherInfos[match]
  256. client := s.clients[info.clientIdx]
  257. domainRule := client.domains[info.domainRuleIdx]
  258. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  259. if clientUsed[info.clientIdx] {
  260. continue
  261. }
  262. clientUsed[info.clientIdx] = true
  263. clients = append(clients, client)
  264. clientNames = append(clientNames, client.Name())
  265. hasMatch = true
  266. }
  267. if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
  268. // Default round-robin query
  269. for idx, client := range s.clients {
  270. if clientUsed[idx] || client.skipFallback {
  271. continue
  272. }
  273. clientUsed[idx] = true
  274. clients = append(clients, client)
  275. clientNames = append(clientNames, client.Name())
  276. }
  277. }
  278. if len(domainRules) > 0 {
  279. errors.LogDebug(s.ctx, "domain ", domain, " matches following rules: ", domainRules)
  280. }
  281. if len(clientNames) > 0 {
  282. errors.LogDebug(s.ctx, "domain ", domain, " will use DNS in order: ", clientNames)
  283. }
  284. if len(clients) == 0 {
  285. clients = append(clients, s.clients[0])
  286. clientNames = append(clientNames, s.clients[0].Name())
  287. errors.LogDebug(s.ctx, "domain ", domain, " will use the first DNS: ", clientNames)
  288. }
  289. return clients
  290. }
  291. func init() {
  292. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  293. return New(ctx, config.(*Config))
  294. }))
  295. }
  296. func checkSystemNetwork() (supportIPv4 bool, supportIPv6 bool) {
  297. conn4, err4 := net.Dial("udp4", "192.33.4.12:53")
  298. if err4 != nil {
  299. supportIPv4 = false
  300. } else {
  301. supportIPv4 = true
  302. conn4.Close()
  303. }
  304. conn6, err6 := net.Dial("udp6", "[2001:500:2::c]:53")
  305. if err6 != nil {
  306. supportIPv6 = false
  307. } else {
  308. supportIPv6 = true
  309. conn6.Close()
  310. }
  311. return
  312. }