dns.go 6.9 KB

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