dns.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // +build !confonly
  2. // Package dns is an implementation of core.DNS feature.
  3. package dns
  4. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  5. import (
  6. "context"
  7. "fmt"
  8. "strings"
  9. "sync"
  10. "github.com/v2fly/v2ray-core/v4/app/router"
  11. "github.com/v2fly/v2ray-core/v4/common"
  12. "github.com/v2fly/v2ray-core/v4/common/errors"
  13. "github.com/v2fly/v2ray-core/v4/common/net"
  14. "github.com/v2fly/v2ray-core/v4/common/session"
  15. "github.com/v2fly/v2ray-core/v4/common/strmatcher"
  16. "github.com/v2fly/v2ray-core/v4/features"
  17. "github.com/v2fly/v2ray-core/v4/features/dns"
  18. )
  19. // DNS is a DNS rely server.
  20. type DNS struct {
  21. sync.Mutex
  22. tag string
  23. disableCache bool
  24. hosts *StaticHosts
  25. clients []*Client
  26. ctx context.Context
  27. domainMatcher strmatcher.IndexMatcher
  28. matcherInfos []DomainMatcherInfo
  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 tag string
  38. if len(config.Tag) > 0 {
  39. tag = config.Tag
  40. } else {
  41. tag = generateRandomTag()
  42. }
  43. var clientIP net.IP
  44. switch len(config.ClientIp) {
  45. case 0, net.IPv4len, net.IPv6len:
  46. clientIP = net.IP(config.ClientIp)
  47. default:
  48. return nil, newError("unexpected client IP length ", len(config.ClientIp))
  49. }
  50. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  51. if err != nil {
  52. return nil, newError("failed to create hosts").Base(err)
  53. }
  54. clients := []*Client{}
  55. domainRuleCount := 0
  56. for _, ns := range config.NameServer {
  57. domainRuleCount += len(ns.PrioritizedDomain)
  58. }
  59. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  60. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
  61. domainMatcher := &strmatcher.MatcherGroup{}
  62. geoipContainer := router.GeoIPMatcherContainer{}
  63. for _, endpoint := range config.NameServers {
  64. features.PrintDeprecatedFeatureWarning("simple DNS server")
  65. client, err := NewSimpleClient(ctx, endpoint, clientIP)
  66. if err != nil {
  67. return nil, newError("failed to create client").Base(err)
  68. }
  69. clients = append(clients, client)
  70. }
  71. for _, ns := range config.NameServer {
  72. clientIdx := len(clients)
  73. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []DomainMatcherInfo) error {
  74. midx := domainMatcher.Add(domainRule)
  75. matcherInfos[midx] = DomainMatcherInfo{
  76. clientIdx: uint16(clientIdx),
  77. domainRuleIdx: uint16(originalRuleIdx),
  78. }
  79. return nil
  80. }
  81. myClientIP := clientIP
  82. switch len(ns.ClientIp) {
  83. case net.IPv4len, net.IPv6len:
  84. myClientIP = net.IP(ns.ClientIp)
  85. }
  86. client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain)
  87. if err != nil {
  88. return nil, newError("failed to create client").Base(err)
  89. }
  90. clients = append(clients, client)
  91. }
  92. // If there is no DNS client in config, add a `localhost` DNS client
  93. if len(clients) == 0 {
  94. clients = append(clients, NewLocalDNSClient())
  95. }
  96. return &DNS{
  97. tag: tag,
  98. hosts: hosts,
  99. clients: clients,
  100. ctx: ctx,
  101. domainMatcher: domainMatcher,
  102. matcherInfos: matcherInfos,
  103. disableCache: config.DisableCache,
  104. }, nil
  105. }
  106. // Type implements common.HasType.
  107. func (*DNS) Type() interface{} {
  108. return dns.ClientType()
  109. }
  110. // Start implements common.Runnable.
  111. func (s *DNS) Start() error {
  112. return nil
  113. }
  114. // Close implements common.Closable.
  115. func (s *DNS) Close() error {
  116. return nil
  117. }
  118. // IsOwnLink implements proxy.dns.ownLinkVerifier
  119. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  120. inbound := session.InboundFromContext(ctx)
  121. return inbound != nil && inbound.Tag == s.tag
  122. }
  123. // LookupIP implements dns.Client.
  124. func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) {
  125. if domain == "" {
  126. return nil, newError("empty domain name")
  127. }
  128. // Normalize the FQDN form query
  129. if strings.HasSuffix(domain, ".") {
  130. domain = domain[:len(domain)-1]
  131. }
  132. // Static host lookup
  133. switch addrs := s.hosts.Lookup(domain, option); {
  134. case addrs == nil: // Domain not recorded in static host
  135. break
  136. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  137. return nil, dns.ErrEmptyResponse
  138. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  139. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  140. domain = addrs[0].Domain()
  141. default: // Successfully found ip records in static host
  142. newError("returning ", len(addrs), " IPs for domain ", domain).WriteToLog()
  143. return toNetIP(addrs)
  144. }
  145. // Name servers lookup
  146. errs := []error{}
  147. ctx := session.ContextWithInbound(s.ctx, &session.Inbound{Tag: s.tag})
  148. for _, client := range s.sortClients(domain) {
  149. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  150. newError("skip DNS resolution for domain ", domain, " at server ", client.Name()).AtDebug().WriteToLog()
  151. continue
  152. }
  153. ips, err := client.QueryIP(ctx, domain, option, s.disableCache)
  154. if len(ips) > 0 {
  155. return ips, nil
  156. }
  157. if err != nil {
  158. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  159. errs = append(errs, err)
  160. }
  161. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  162. return nil, err
  163. }
  164. }
  165. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  166. }
  167. func (s *DNS) sortClients(domain string) []*Client {
  168. clients := make([]*Client, 0, len(s.clients))
  169. clientUsed := make([]bool, len(s.clients))
  170. clientNames := make([]string, 0, len(s.clients))
  171. domainRules := []string{}
  172. // Priority domain matching
  173. for _, match := range s.domainMatcher.Match(domain) {
  174. info := s.matcherInfos[match]
  175. client := s.clients[info.clientIdx]
  176. domainRule := client.domains[info.domainRuleIdx]
  177. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  178. if clientUsed[info.clientIdx] {
  179. continue
  180. }
  181. clientUsed[info.clientIdx] = true
  182. clients = append(clients, client)
  183. clientNames = append(clientNames, client.Name())
  184. }
  185. // Default round-robin query
  186. for idx, client := range s.clients {
  187. if clientUsed[idx] {
  188. continue
  189. }
  190. clientUsed[idx] = true
  191. clients = append(clients, client)
  192. clientNames = append(clientNames, client.Name())
  193. }
  194. if len(domainRules) > 0 {
  195. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  196. }
  197. if len(clientNames) > 0 {
  198. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  199. }
  200. return clients
  201. }
  202. func init() {
  203. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  204. return New(ctx, config.(*Config))
  205. }))
  206. }