dns.go 7.0 KB

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