dns.go 8.3 KB

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