dns.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. cacheStrategy CacheStrategy
  23. disableFallback 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, newError("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, config.Hosts)
  73. if err != nil {
  74. return nil, newError("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 _, endpoint := range config.NameServers {
  86. features.PrintDeprecatedFeatureWarning("simple DNS server")
  87. client, err := NewSimpleClient(ctx, endpoint, clientIP)
  88. if err != nil {
  89. return nil, newError("failed to create client").Base(err)
  90. }
  91. clients = append(clients, client)
  92. }
  93. for _, ns := range config.NameServer {
  94. clientIdx := len(clients)
  95. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []DomainMatcherInfo) error {
  96. midx := domainMatcher.Add(domainRule)
  97. matcherInfos[midx] = DomainMatcherInfo{
  98. clientIdx: uint16(clientIdx),
  99. domainRuleIdx: uint16(originalRuleIdx),
  100. }
  101. return nil
  102. }
  103. myClientIP := clientIP
  104. switch len(ns.ClientIp) {
  105. case net.IPv4len, net.IPv6len:
  106. myClientIP = net.IP(ns.ClientIp)
  107. }
  108. client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain)
  109. if err != nil {
  110. return nil, newError("failed to create client").Base(err)
  111. }
  112. clients = append(clients, client)
  113. }
  114. // If there is no DNS client in config, add a `localhost` DNS client
  115. if len(clients) == 0 {
  116. clients = append(clients, NewLocalDNSClient())
  117. }
  118. return &DNS{
  119. tag: tag,
  120. hosts: hosts,
  121. ipOption: ipOption,
  122. clients: clients,
  123. ctx: ctx,
  124. domainMatcher: domainMatcher,
  125. matcherInfos: matcherInfos,
  126. cacheStrategy: config.CacheStrategy,
  127. disableFallback: config.DisableFallback,
  128. }, nil
  129. }
  130. // Type implements common.HasType.
  131. func (*DNS) Type() interface{} {
  132. return dns.ClientType()
  133. }
  134. // Start implements common.Runnable.
  135. func (s *DNS) Start() error {
  136. return nil
  137. }
  138. // Close implements common.Closable.
  139. func (s *DNS) Close() error {
  140. return nil
  141. }
  142. // IsOwnLink implements proxy.dns.ownLinkVerifier
  143. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  144. inbound := session.InboundFromContext(ctx)
  145. return inbound != nil && inbound.Tag == s.tag
  146. }
  147. // LookupIP implements dns.Client.
  148. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  149. return s.lookupIPInternal(domain, s.ipOption.Copy())
  150. }
  151. // LookupOptions implements dns.Client.
  152. func (s *DNS) LookupOptions(domain string, opts ...dns.Option) ([]net.IP, error) {
  153. opt := s.ipOption.Copy()
  154. for _, o := range opts {
  155. if o != nil {
  156. o(opt)
  157. }
  158. }
  159. return s.lookupIPInternal(domain, opt)
  160. }
  161. // LookupIPv4 implements dns.IPv4Lookup.
  162. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  163. return s.lookupIPInternal(domain, &dns.IPOption{
  164. IPv4Enable: true,
  165. })
  166. }
  167. // LookupIPv6 implements dns.IPv6Lookup.
  168. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  169. return s.lookupIPInternal(domain, &dns.IPOption{
  170. IPv6Enable: true,
  171. })
  172. }
  173. func (s *DNS) lookupIPInternal(domain string, option *dns.IPOption) ([]net.IP, error) {
  174. if domain == "" {
  175. return nil, newError("empty domain name")
  176. }
  177. if isQuery(option) {
  178. return nil, newError("empty option: Impossible.").AtWarning()
  179. }
  180. // Normalize the FQDN form query
  181. if strings.HasSuffix(domain, ".") {
  182. domain = domain[:len(domain)-1]
  183. }
  184. // Static host lookup
  185. switch addrs := s.hosts.Lookup(domain, option); {
  186. case addrs == nil: // Domain not recorded in static host
  187. break
  188. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  189. return nil, dns.ErrEmptyResponse
  190. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  191. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  192. domain = addrs[0].Domain()
  193. default:
  194. // Successfully found ip records in static host.
  195. // Skip hosts mapping result in FakeDNS query.
  196. if isIPQuery(option) {
  197. newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog()
  198. return toNetIP(addrs)
  199. }
  200. }
  201. // Name servers lookup
  202. errs := []error{}
  203. ctx := session.ContextWithInbound(s.ctx, &session.Inbound{Tag: s.tag})
  204. for _, client := range s.sortClients(domain, option) {
  205. ips, err := client.QueryIP(ctx, domain, *option, s.cacheStrategy)
  206. if len(ips) > 0 {
  207. return ips, nil
  208. }
  209. if err != nil {
  210. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  211. errs = append(errs, err)
  212. }
  213. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  214. return nil, err
  215. }
  216. }
  217. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  218. }
  219. func (s *DNS) sortClients(domain string, option *dns.IPOption) []*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. defer func() {
  225. if len(domainRules) > 0 {
  226. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  227. }
  228. if len(clientNames) > 0 {
  229. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  230. }
  231. if len(clients) == 0 {
  232. clients = append(clients, s.clients[0])
  233. clientNames = append(clientNames, s.clients[0].Name())
  234. newError("domain ", domain, " will use the first DNS: ", clientNames).AtDebug().WriteToLog()
  235. }
  236. }()
  237. // Priority domain matching
  238. for _, match := range s.domainMatcher.Match(domain) {
  239. info := s.matcherInfos[match]
  240. client := s.clients[info.clientIdx]
  241. domainRule := client.domains[info.domainRuleIdx]
  242. if !canQueryOnClient(option, client) {
  243. newError("skipping the client " + client.Name()).AtDebug().WriteToLog()
  244. continue
  245. }
  246. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  247. if clientUsed[info.clientIdx] {
  248. continue
  249. }
  250. clientUsed[info.clientIdx] = true
  251. clients = append(clients, client)
  252. clientNames = append(clientNames, client.Name())
  253. }
  254. if !s.disableFallback {
  255. // Default round-robin query
  256. for idx, client := range s.clients {
  257. if clientUsed[idx] || client.skipFallback {
  258. continue
  259. }
  260. if !canQueryOnClient(option, client) {
  261. newError("skipping the client " + client.Name()).AtDebug().WriteToLog()
  262. continue
  263. }
  264. clientUsed[idx] = true
  265. clients = append(clients, client)
  266. clientNames = append(clientNames, client.Name())
  267. }
  268. }
  269. return clients
  270. }
  271. func init() {
  272. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  273. return New(ctx, config.(*Config))
  274. }))
  275. }