1
0

dns.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. // Package dns is an implementation of core.DNS feature.
  2. package dns
  3. import (
  4. "context"
  5. go_errors "errors"
  6. "fmt"
  7. "os"
  8. "runtime"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/xtls/xray-core/common"
  14. "github.com/xtls/xray-core/common/errors"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/session"
  17. "github.com/xtls/xray-core/common/strmatcher"
  18. "github.com/xtls/xray-core/features/dns"
  19. )
  20. // DNS is a DNS rely server.
  21. type DNS struct {
  22. sync.Mutex
  23. disableFallback bool
  24. disableFallbackIfMatch bool
  25. enableParallelQuery bool
  26. ipOption *dns.IPOption
  27. hosts *StaticHosts
  28. clients []*Client
  29. ctx context.Context
  30. domainMatcher strmatcher.IndexMatcher
  31. matcherInfos []*DomainMatcherInfo
  32. checkSystem bool
  33. }
  34. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  35. type DomainMatcherInfo struct {
  36. clientIdx uint16
  37. domainRuleIdx uint16
  38. }
  39. // New creates a new DNS server with given configuration.
  40. func New(ctx context.Context, config *Config) (*DNS, error) {
  41. var clientIP net.IP
  42. switch len(config.ClientIp) {
  43. case 0, net.IPv4len, net.IPv6len:
  44. clientIP = net.IP(config.ClientIp)
  45. default:
  46. return nil, errors.New("unexpected client IP length ", len(config.ClientIp))
  47. }
  48. var ipOption dns.IPOption
  49. checkSystem := false
  50. switch config.QueryStrategy {
  51. case QueryStrategy_USE_IP:
  52. ipOption = dns.IPOption{
  53. IPv4Enable: true,
  54. IPv6Enable: true,
  55. FakeEnable: false,
  56. }
  57. case QueryStrategy_USE_SYS:
  58. ipOption = dns.IPOption{
  59. IPv4Enable: true,
  60. IPv6Enable: true,
  61. FakeEnable: false,
  62. }
  63. checkSystem = true
  64. case QueryStrategy_USE_IP4:
  65. ipOption = dns.IPOption{
  66. IPv4Enable: true,
  67. IPv6Enable: false,
  68. FakeEnable: false,
  69. }
  70. case QueryStrategy_USE_IP6:
  71. ipOption = dns.IPOption{
  72. IPv4Enable: false,
  73. IPv6Enable: true,
  74. FakeEnable: false,
  75. }
  76. default:
  77. return nil, errors.New("unexpected query strategy ", config.QueryStrategy)
  78. }
  79. hosts, err := NewStaticHosts(config.StaticHosts)
  80. if err != nil {
  81. return nil, errors.New("failed to create hosts").Base(err)
  82. }
  83. var clients []*Client
  84. domainRuleCount := 0
  85. var defaultTag = config.Tag
  86. if len(config.Tag) == 0 {
  87. defaultTag = generateRandomTag()
  88. }
  89. for _, ns := range config.NameServer {
  90. domainRuleCount += len(ns.PrioritizedDomain)
  91. }
  92. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  93. matcherInfos := make([]*DomainMatcherInfo, domainRuleCount+1)
  94. domainMatcher := &strmatcher.MatcherGroup{}
  95. for _, ns := range config.NameServer {
  96. clientIdx := len(clients)
  97. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []*DomainMatcherInfo) {
  98. midx := domainMatcher.Add(domainRule)
  99. matcherInfos[midx] = &DomainMatcherInfo{
  100. clientIdx: uint16(clientIdx),
  101. domainRuleIdx: uint16(originalRuleIdx),
  102. }
  103. }
  104. myClientIP := clientIP
  105. switch len(ns.ClientIp) {
  106. case net.IPv4len, net.IPv6len:
  107. myClientIP = net.IP(ns.ClientIp)
  108. }
  109. disableCache := config.DisableCache
  110. if ns.DisableCache != nil {
  111. disableCache = *ns.DisableCache
  112. }
  113. serveStale := config.ServeStale
  114. if ns.ServeStale != nil {
  115. serveStale = *ns.ServeStale
  116. }
  117. serveExpiredTTL := config.ServeExpiredTTL
  118. if ns.ServeExpiredTTL != nil {
  119. serveExpiredTTL = *ns.ServeExpiredTTL
  120. }
  121. var tag = defaultTag
  122. if len(ns.Tag) > 0 {
  123. tag = ns.Tag
  124. }
  125. clientIPOption := ResolveIpOptionOverride(ns.QueryStrategy, ipOption)
  126. if !clientIPOption.IPv4Enable && !clientIPOption.IPv6Enable {
  127. return nil, errors.New("no QueryStrategy available for ", ns.Address)
  128. }
  129. client, err := NewClient(ctx, ns, myClientIP, disableCache, serveStale, serveExpiredTTL, tag, clientIPOption, &matcherInfos, updateDomain)
  130. if err != nil {
  131. return nil, errors.New("failed to create client").Base(err)
  132. }
  133. clients = append(clients, client)
  134. }
  135. // If there is no DNS client in config, add a `localhost` DNS client
  136. if len(clients) == 0 {
  137. clients = append(clients, NewLocalDNSClient(ipOption))
  138. }
  139. return &DNS{
  140. hosts: hosts,
  141. ipOption: &ipOption,
  142. clients: clients,
  143. ctx: ctx,
  144. domainMatcher: domainMatcher,
  145. matcherInfos: matcherInfos,
  146. disableFallback: config.DisableFallback,
  147. disableFallbackIfMatch: config.DisableFallbackIfMatch,
  148. enableParallelQuery: config.EnableParallelQuery,
  149. checkSystem: checkSystem,
  150. }, nil
  151. }
  152. // Type implements common.HasType.
  153. func (*DNS) Type() interface{} {
  154. return dns.ClientType()
  155. }
  156. // Start implements common.Runnable.
  157. func (s *DNS) Start() error {
  158. return nil
  159. }
  160. // Close implements common.Closable.
  161. func (s *DNS) Close() error {
  162. return nil
  163. }
  164. // IsOwnLink implements proxy.dns.ownLinkVerifier
  165. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  166. inbound := session.InboundFromContext(ctx)
  167. if inbound == nil {
  168. return false
  169. }
  170. for _, client := range s.clients {
  171. if client.tag == inbound.Tag {
  172. return true
  173. }
  174. }
  175. return false
  176. }
  177. // LookupIP implements dns.Client.
  178. func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  179. // Normalize the FQDN form query
  180. domain = strings.TrimSuffix(domain, ".")
  181. if domain == "" {
  182. return nil, 0, errors.New("empty domain name")
  183. }
  184. if s.checkSystem {
  185. supportIPv4, supportIPv6 := checkRoutes()
  186. option.IPv4Enable = option.IPv4Enable && supportIPv4
  187. option.IPv6Enable = option.IPv6Enable && supportIPv6
  188. } else {
  189. option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable
  190. option.IPv6Enable = option.IPv6Enable && s.ipOption.IPv6Enable
  191. }
  192. if !option.IPv4Enable && !option.IPv6Enable {
  193. return nil, 0, dns.ErrEmptyResponse
  194. }
  195. // Static host lookup
  196. switch addrs, err := s.hosts.Lookup(domain, option); {
  197. case err != nil:
  198. if go_errors.Is(err, dns.ErrEmptyResponse) {
  199. return nil, 0, dns.ErrEmptyResponse
  200. }
  201. return nil, 0, errors.New("returning nil for domain ", domain).Base(err)
  202. case addrs == nil: // Domain not recorded in static host
  203. break
  204. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  205. return nil, 0, dns.ErrEmptyResponse
  206. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  207. errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain())
  208. domain = addrs[0].Domain()
  209. default: // Successfully found ip records in static host
  210. errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs)
  211. ips, err := toNetIP(addrs)
  212. if err != nil {
  213. return nil, 0, err
  214. }
  215. return ips, 10, nil // Hosts ttl is 10
  216. }
  217. // Name servers lookup
  218. if s.enableParallelQuery {
  219. return s.parallelQuery(domain, option)
  220. } else {
  221. return s.serialQuery(domain, option)
  222. }
  223. }
  224. func (s *DNS) sortClients(domain string) []*Client {
  225. clients := make([]*Client, 0, len(s.clients))
  226. clientUsed := make([]bool, len(s.clients))
  227. clientNames := make([]string, 0, len(s.clients))
  228. domainRules := []string{}
  229. // Priority domain matching
  230. hasMatch := false
  231. MatchSlice := s.domainMatcher.Match(domain)
  232. sort.Slice(MatchSlice, func(i, j int) bool {
  233. return MatchSlice[i] < MatchSlice[j]
  234. })
  235. for _, match := range MatchSlice {
  236. info := s.matcherInfos[match]
  237. client := s.clients[info.clientIdx]
  238. domainRule := client.domains[info.domainRuleIdx]
  239. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  240. if clientUsed[info.clientIdx] {
  241. continue
  242. }
  243. clientUsed[info.clientIdx] = true
  244. clients = append(clients, client)
  245. clientNames = append(clientNames, client.Name())
  246. hasMatch = true
  247. if client.finalQuery {
  248. return clients
  249. }
  250. }
  251. if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
  252. // Default round-robin query
  253. for idx, client := range s.clients {
  254. if clientUsed[idx] || client.skipFallback {
  255. continue
  256. }
  257. clientUsed[idx] = true
  258. clients = append(clients, client)
  259. clientNames = append(clientNames, client.Name())
  260. if client.finalQuery {
  261. return clients
  262. }
  263. }
  264. }
  265. if len(domainRules) > 0 {
  266. errors.LogDebug(s.ctx, "domain ", domain, " matches following rules: ", domainRules)
  267. }
  268. if len(clientNames) > 0 {
  269. errors.LogDebug(s.ctx, "domain ", domain, " will use DNS in order: ", clientNames)
  270. }
  271. if len(clients) == 0 {
  272. if len(s.clients) > 0 {
  273. clients = append(clients, s.clients[0])
  274. clientNames = append(clientNames, s.clients[0].Name())
  275. errors.LogWarning(s.ctx, "domain ", domain, " will use the first DNS: ", clientNames)
  276. } else {
  277. errors.LogError(s.ctx, "no DNS clients available for domain ", domain, " and no default clients configured")
  278. }
  279. }
  280. return clients
  281. }
  282. func mergeQueryErrors(domain string, errs []error) error {
  283. if len(errs) == 0 {
  284. return dns.ErrEmptyResponse
  285. }
  286. var noRNF error
  287. for _, err := range errs {
  288. if go_errors.Is(err, errRecordNotFound) {
  289. continue // server no response, ignore
  290. } else if noRNF == nil {
  291. noRNF = err
  292. } else if !go_errors.Is(err, noRNF) {
  293. return errors.New("returning nil for domain ", domain).Base(errors.Combine(errs...))
  294. }
  295. }
  296. if go_errors.Is(noRNF, dns.ErrEmptyResponse) {
  297. return dns.ErrEmptyResponse
  298. }
  299. if noRNF == nil {
  300. noRNF = errRecordNotFound
  301. }
  302. return errors.New("returning nil for domain ", domain).Base(noRNF)
  303. }
  304. func (s *DNS) serialQuery(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  305. var errs []error
  306. for _, client := range s.sortClients(domain) {
  307. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  308. errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name())
  309. continue
  310. }
  311. ips, ttl, err := client.QueryIP(s.ctx, domain, option)
  312. if len(ips) > 0 {
  313. return ips, ttl, nil
  314. }
  315. errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name(), " in serial query mode")
  316. if err == nil {
  317. err = dns.ErrEmptyResponse
  318. }
  319. errs = append(errs, err)
  320. }
  321. return nil, 0, mergeQueryErrors(domain, errs)
  322. }
  323. func (s *DNS) parallelQuery(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
  324. var errs []error
  325. clients := s.sortClients(domain)
  326. resultsChan := asyncQueryAll(domain, option, clients, s.ctx)
  327. groups, groupOf := makeGroups( /*s.ctx,*/ clients)
  328. results := make([]*queryResult, len(clients))
  329. pending := make([]int, len(groups))
  330. for gi, g := range groups {
  331. pending[gi] = g.end - g.start + 1
  332. }
  333. nextGroup := 0
  334. for range clients {
  335. result := <-resultsChan
  336. results[result.index] = &result
  337. gi := groupOf[result.index]
  338. pending[gi]--
  339. for nextGroup < len(groups) {
  340. g := groups[nextGroup]
  341. // group race, minimum rtt -> return
  342. for j := g.start; j <= g.end; j++ {
  343. r := results[j]
  344. if r != nil && r.err == nil && len(r.ips) > 0 {
  345. return r.ips, r.ttl, nil
  346. }
  347. }
  348. // current group is incomplete and no one success -> continue pending
  349. if pending[nextGroup] > 0 {
  350. break
  351. }
  352. // all failed -> log and continue next group
  353. for j := g.start; j <= g.end; j++ {
  354. r := results[j]
  355. e := r.err
  356. if e == nil {
  357. e = dns.ErrEmptyResponse
  358. }
  359. errors.LogInfoInner(s.ctx, e, "failed to lookup ip for domain ", domain, " at server ", clients[j].Name(), " in parallel query mode")
  360. errs = append(errs, e)
  361. }
  362. nextGroup++
  363. }
  364. }
  365. return nil, 0, mergeQueryErrors(domain, errs)
  366. }
  367. type queryResult struct {
  368. ips []net.IP
  369. ttl uint32
  370. err error
  371. index int
  372. }
  373. func asyncQueryAll(domain string, option dns.IPOption, clients []*Client, ctx context.Context) chan queryResult {
  374. if len(clients) == 0 {
  375. ch := make(chan queryResult)
  376. close(ch)
  377. return ch
  378. }
  379. ch := make(chan queryResult, len(clients))
  380. for i, client := range clients {
  381. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  382. errors.LogDebug(ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name())
  383. ch <- queryResult{err: dns.ErrEmptyResponse, index: i}
  384. continue
  385. }
  386. go func(i int, c *Client) {
  387. qctx := ctx
  388. if !c.server.IsDisableCache() {
  389. nctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), c.timeoutMs*2)
  390. qctx = nctx
  391. defer cancel()
  392. }
  393. ips, ttl, err := c.QueryIP(qctx, domain, option)
  394. ch <- queryResult{ips: ips, ttl: ttl, err: err, index: i}
  395. }(i, client)
  396. }
  397. return ch
  398. }
  399. type group struct{ start, end int }
  400. // merge only adjacent and rule-equivalent Client into a single group
  401. func makeGroups( /*ctx context.Context,*/ clients []*Client) ([]group, []int) {
  402. n := len(clients)
  403. if n == 0 {
  404. return nil, nil
  405. }
  406. groups := make([]group, 0, n)
  407. groupOf := make([]int, n)
  408. s, e := 0, 0
  409. for i := 1; i < n; i++ {
  410. if clients[i-1].policyID == clients[i].policyID {
  411. e = i
  412. } else {
  413. for k := s; k <= e; k++ {
  414. groupOf[k] = len(groups)
  415. }
  416. groups = append(groups, group{start: s, end: e})
  417. s, e = i, i
  418. }
  419. }
  420. for k := s; k <= e; k++ {
  421. groupOf[k] = len(groups)
  422. }
  423. groups = append(groups, group{start: s, end: e})
  424. // var b strings.Builder
  425. // b.WriteString("dns grouping: total clients=")
  426. // b.WriteString(strconv.Itoa(n))
  427. // b.WriteString(", groups=")
  428. // b.WriteString(strconv.Itoa(len(groups)))
  429. // for gi, g := range groups {
  430. // b.WriteString("\n [")
  431. // b.WriteString(strconv.Itoa(g.start))
  432. // b.WriteString("..")
  433. // b.WriteString(strconv.Itoa(g.end))
  434. // b.WriteString("] gid=")
  435. // b.WriteString(strconv.Itoa(gi))
  436. // b.WriteString(" pid=")
  437. // b.WriteString(strconv.FormatUint(uint64(clients[g.start].policyID), 10))
  438. // b.WriteString(" members: ")
  439. // for i := g.start; i <= g.end; i++ {
  440. // if i > g.start {
  441. // b.WriteString(", ")
  442. // }
  443. // b.WriteString(strconv.Itoa(i))
  444. // b.WriteByte(':')
  445. // b.WriteString(clients[i].Name())
  446. // }
  447. // }
  448. // errors.LogDebug(ctx, b.String())
  449. return groups, groupOf
  450. }
  451. func init() {
  452. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  453. return New(ctx, config.(*Config))
  454. }))
  455. }
  456. func probeRoutes() (ipv4 bool, ipv6 bool) {
  457. if conn, err := net.Dial("udp4", "192.33.4.12:53"); err == nil {
  458. ipv4 = true
  459. conn.Close()
  460. }
  461. if conn, err := net.Dial("udp6", "[2001:500:2::c]:53"); err == nil {
  462. ipv6 = true
  463. conn.Close()
  464. }
  465. return
  466. }
  467. var routeCache struct {
  468. sync.Once
  469. sync.RWMutex
  470. expire time.Time
  471. ipv4, ipv6 bool
  472. }
  473. func checkRoutes() (bool, bool) {
  474. if !isGUIPlatform {
  475. routeCache.Once.Do(func() {
  476. routeCache.ipv4, routeCache.ipv6 = probeRoutes()
  477. })
  478. return routeCache.ipv4, routeCache.ipv6
  479. }
  480. routeCache.RWMutex.RLock()
  481. now := time.Now()
  482. if routeCache.expire.After(now) {
  483. routeCache.RWMutex.RUnlock()
  484. return routeCache.ipv4, routeCache.ipv6
  485. }
  486. routeCache.RWMutex.RUnlock()
  487. routeCache.RWMutex.Lock()
  488. defer routeCache.RWMutex.Unlock()
  489. now = time.Now()
  490. if routeCache.expire.After(now) { // double-check
  491. return routeCache.ipv4, routeCache.ipv6
  492. }
  493. routeCache.ipv4, routeCache.ipv6 = probeRoutes() // ~2ms
  494. routeCache.expire = now.Add(100 * time.Millisecond) // ttl
  495. return routeCache.ipv4, routeCache.ipv6
  496. }
  497. var isGUIPlatform = detectGUIPlatform()
  498. func detectGUIPlatform() bool {
  499. switch runtime.GOOS {
  500. case "android", "ios", "windows", "darwin":
  501. return true
  502. case "linux", "freebsd", "openbsd":
  503. if t := os.Getenv("XDG_SESSION_TYPE"); t == "wayland" || t == "x11" {
  504. return true
  505. }
  506. if os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != "" {
  507. return true
  508. }
  509. }
  510. return false
  511. }