dns.go 9.0 KB

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