dns.go 15 KB

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