dns.go 6.8 KB

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