dns.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // +build !confonly
  2. // Package dns is an implementation of core.DNS feature.
  3. package dns
  4. //go:generate go run v2ray.com/core/common/errors/errorgen
  5. import (
  6. "context"
  7. "fmt"
  8. "sync"
  9. "v2ray.com/core/app/router"
  10. "v2ray.com/core/common"
  11. "v2ray.com/core/common/errors"
  12. "v2ray.com/core/common/net"
  13. "v2ray.com/core/common/session"
  14. "v2ray.com/core/common/strmatcher"
  15. "v2ray.com/core/features"
  16. "v2ray.com/core/features/dns"
  17. )
  18. // DNS is a DNS rely server.
  19. type DNS struct {
  20. sync.Mutex
  21. tag string
  22. hosts *StaticHosts
  23. clients []*Client
  24. domainMatcher strmatcher.IndexMatcher
  25. matcherInfos []DomainMatcherInfo
  26. }
  27. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  28. type DomainMatcherInfo struct {
  29. clientIdx uint16
  30. domainRuleIdx uint16
  31. }
  32. // New creates a new DNS server with given configuration.
  33. func New(ctx context.Context, config *Config) (*DNS, error) {
  34. var tag string
  35. if len(config.Tag) > 0 {
  36. tag = config.Tag
  37. } else {
  38. tag = generateRandomTag()
  39. }
  40. var clientIP net.IP
  41. switch len(config.ClientIp) {
  42. case 0, net.IPv4len, net.IPv6len:
  43. clientIP = net.IP(config.ClientIp)
  44. default:
  45. return nil, newError("unexpected client IP length ", len(config.ClientIp))
  46. }
  47. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  48. if err != nil {
  49. return nil, newError("failed to create hosts").Base(err)
  50. }
  51. clients := []*Client{}
  52. domainRuleCount := 0
  53. for _, ns := range config.NameServer {
  54. domainRuleCount += len(ns.PrioritizedDomain)
  55. }
  56. // Fixes https://github.com/v2fly/v2ray-core/issues/529
  57. // Compatible with `localhost` nameserver specified in config file
  58. domainRuleCount += len(localTLDsAndDotlessDomains)
  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) 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, updateDomain)
  87. if err != nil {
  88. return nil, newError("failed to create client").Base(err)
  89. }
  90. clients = append(clients, client)
  91. }
  92. if len(clients) == 0 {
  93. clients = append(clients, NewLocalDNSClient())
  94. }
  95. return &DNS{
  96. tag: tag,
  97. hosts: hosts,
  98. clients: clients,
  99. domainMatcher: domainMatcher,
  100. matcherInfos: matcherInfos,
  101. }, nil
  102. }
  103. // Type implements common.HasType.
  104. func (*DNS) Type() interface{} {
  105. return dns.ClientType()
  106. }
  107. // Start implements common.Runnable.
  108. func (s *DNS) Start() error {
  109. return nil
  110. }
  111. // Close implements common.Closable.
  112. func (s *DNS) Close() error {
  113. return nil
  114. }
  115. // IsOwnLink implements proxy.dns.ownLinkVerifier
  116. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  117. inbound := session.InboundFromContext(ctx)
  118. return inbound != nil && inbound.Tag == s.tag
  119. }
  120. // LookupIP implements dns.Client.
  121. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  122. return s.lookupIPInternal(domain, IPOption{
  123. IPv4Enable: true,
  124. IPv6Enable: true,
  125. })
  126. }
  127. // LookupIPv4 implements dns.IPv4Lookup.
  128. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  129. return s.lookupIPInternal(domain, IPOption{
  130. IPv4Enable: true,
  131. IPv6Enable: false,
  132. })
  133. }
  134. // LookupIPv6 implements dns.IPv6Lookup.
  135. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  136. return s.lookupIPInternal(domain, IPOption{
  137. IPv4Enable: false,
  138. IPv6Enable: true,
  139. })
  140. }
  141. func (s *DNS) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  142. if domain == "" {
  143. return nil, newError("empty domain name")
  144. }
  145. // Normalize the FQDN form query
  146. if domain[len(domain)-1] == '.' {
  147. domain = domain[:len(domain)-1]
  148. }
  149. // Static host lookup
  150. switch addrs := s.hosts.Lookup(domain, option); {
  151. case addrs == nil: // Domain not recorded in static host
  152. break
  153. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  154. return nil, dns.ErrEmptyResponse
  155. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  156. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  157. domain = addrs[0].Domain()
  158. default: // Successfully found ip records in static host
  159. newError("returning ", len(addrs), " IPs for domain ", domain).WriteToLog()
  160. return toNetIP(addrs)
  161. }
  162. // Name servers lookup
  163. errs := []error{}
  164. ctx := session.ContextWithInbound(context.Background(), &session.Inbound{Tag: s.tag})
  165. for _, client := range s.sortClients(domain) {
  166. ips, err := client.QueryIP(ctx, domain, option)
  167. if len(ips) > 0 {
  168. return ips, nil
  169. }
  170. if err != nil {
  171. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  172. errs = append(errs, err)
  173. }
  174. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  175. return nil, err
  176. }
  177. }
  178. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  179. }
  180. func (s *DNS) sortClients(domain string) []*Client {
  181. clients := make([]*Client, 0, len(s.clients))
  182. clientUsed := make([]bool, len(s.clients))
  183. clientNames := make([]string, 0, len(s.clients))
  184. domainRules := []string{}
  185. // Priority domain matching
  186. for _, match := range s.domainMatcher.Match(domain) {
  187. info := s.matcherInfos[match]
  188. client := s.clients[info.clientIdx]
  189. domainRule := client.domains[info.domainRuleIdx]
  190. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  191. if clientUsed[info.clientIdx] {
  192. continue
  193. }
  194. clientUsed[info.clientIdx] = true
  195. clients = append(clients, client)
  196. clientNames = append(clientNames, client.Name())
  197. }
  198. // Default round-robin query
  199. for idx, client := range s.clients {
  200. if clientUsed[idx] {
  201. continue
  202. }
  203. clientUsed[idx] = true
  204. clients = append(clients, client)
  205. clientNames = append(clientNames, client.Name())
  206. }
  207. if len(domainRules) > 0 {
  208. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  209. }
  210. if len(clientNames) > 0 {
  211. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  212. }
  213. return clients
  214. }
  215. func init() {
  216. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  217. return New(ctx, config.(*Config))
  218. }))
  219. }