dns.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. ipOption *dns.IPOption
  27. hosts *StaticHosts
  28. clients []*Client
  29. ctx context.Context
  30. domainMatcher strmatcher.IndexMatcher
  31. matcherInfos []DomainMatcherInfo
  32. }
  33. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  34. type DomainMatcherInfo struct {
  35. clientIdx uint16
  36. domainRuleIdx uint16
  37. }
  38. // New creates a new DNS server with given configuration.
  39. func New(ctx context.Context, config *Config) (*DNS, error) {
  40. var tag string
  41. if len(config.Tag) > 0 {
  42. tag = config.Tag
  43. } else {
  44. tag = generateRandomTag()
  45. }
  46. var clientIP net.IP
  47. switch len(config.ClientIp) {
  48. case 0, net.IPv4len, net.IPv6len:
  49. clientIP = net.IP(config.ClientIp)
  50. default:
  51. return nil, newError("unexpected client IP length ", len(config.ClientIp))
  52. }
  53. var ipOption *dns.IPOption
  54. switch config.QueryStrategy {
  55. case QueryStrategy_USE_IP:
  56. ipOption = &dns.IPOption{
  57. IPv4Enable: true,
  58. IPv6Enable: true,
  59. FakeEnable: false,
  60. }
  61. case QueryStrategy_USE_IP4:
  62. ipOption = &dns.IPOption{
  63. IPv4Enable: true,
  64. IPv6Enable: false,
  65. FakeEnable: false,
  66. }
  67. case QueryStrategy_USE_IP6:
  68. ipOption = &dns.IPOption{
  69. IPv4Enable: false,
  70. IPv6Enable: true,
  71. FakeEnable: false,
  72. }
  73. }
  74. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  75. if err != nil {
  76. return nil, newError("failed to create hosts").Base(err)
  77. }
  78. clients := []*Client{}
  79. domainRuleCount := 0
  80. for _, ns := range config.NameServer {
  81. domainRuleCount += len(ns.PrioritizedDomain)
  82. }
  83. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  84. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
  85. domainMatcher := &strmatcher.MatcherGroup{}
  86. geoipContainer := router.GeoIPMatcherContainer{}
  87. for _, endpoint := range config.NameServers {
  88. features.PrintDeprecatedFeatureWarning("simple DNS server")
  89. client, err := NewSimpleClient(ctx, endpoint, clientIP)
  90. if err != nil {
  91. return nil, newError("failed to create client").Base(err)
  92. }
  93. clients = append(clients, client)
  94. }
  95. for _, ns := range config.NameServer {
  96. clientIdx := len(clients)
  97. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []DomainMatcherInfo) error {
  98. midx := domainMatcher.Add(domainRule)
  99. matcherInfos[midx] = DomainMatcherInfo{
  100. clientIdx: uint16(clientIdx),
  101. domainRuleIdx: uint16(originalRuleIdx),
  102. }
  103. return nil
  104. }
  105. myClientIP := clientIP
  106. switch len(ns.ClientIp) {
  107. case net.IPv4len, net.IPv6len:
  108. myClientIP = net.IP(ns.ClientIp)
  109. }
  110. client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain)
  111. if err != nil {
  112. return nil, newError("failed to create client").Base(err)
  113. }
  114. clients = append(clients, client)
  115. }
  116. // If there is no DNS client in config, add a `localhost` DNS client
  117. if len(clients) == 0 {
  118. clients = append(clients, NewLocalDNSClient())
  119. }
  120. return &DNS{
  121. tag: tag,
  122. hosts: hosts,
  123. ipOption: ipOption,
  124. clients: clients,
  125. ctx: ctx,
  126. domainMatcher: domainMatcher,
  127. matcherInfos: matcherInfos,
  128. disableCache: config.DisableCache,
  129. disableFallback: config.DisableFallback,
  130. }, nil
  131. }
  132. // Type implements common.HasType.
  133. func (*DNS) Type() interface{} {
  134. return dns.ClientType()
  135. }
  136. // Start implements common.Runnable.
  137. func (s *DNS) Start() error {
  138. return nil
  139. }
  140. // Close implements common.Closable.
  141. func (s *DNS) Close() error {
  142. return nil
  143. }
  144. // IsOwnLink implements proxy.dns.ownLinkVerifier
  145. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  146. inbound := session.InboundFromContext(ctx)
  147. return inbound != nil && inbound.Tag == s.tag
  148. }
  149. // LookupIP implements dns.Client.
  150. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  151. return s.lookupIPInternal(domain, dns.IPOption{
  152. IPv4Enable: true,
  153. IPv6Enable: true,
  154. FakeEnable: s.ipOption.FakeEnable,
  155. })
  156. }
  157. // LookupIPv4 implements dns.IPv4Lookup.
  158. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  159. return s.lookupIPInternal(domain, dns.IPOption{
  160. IPv4Enable: true,
  161. IPv6Enable: false,
  162. FakeEnable: s.ipOption.FakeEnable,
  163. })
  164. }
  165. // LookupIPv6 implements dns.IPv6Lookup.
  166. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  167. return s.lookupIPInternal(domain, dns.IPOption{
  168. IPv4Enable: false,
  169. IPv6Enable: true,
  170. FakeEnable: s.ipOption.FakeEnable,
  171. })
  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. for _, match := range s.domainMatcher.Match(domain) {
  234. info := s.matcherInfos[match]
  235. client := s.clients[info.clientIdx]
  236. domainRule := client.domains[info.domainRuleIdx]
  237. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  238. if clientUsed[info.clientIdx] {
  239. continue
  240. }
  241. clientUsed[info.clientIdx] = true
  242. clients = append(clients, client)
  243. clientNames = append(clientNames, client.Name())
  244. }
  245. if !s.disableFallback {
  246. // Default round-robin query
  247. for idx, client := range s.clients {
  248. if clientUsed[idx] || client.skipFallback {
  249. continue
  250. }
  251. clientUsed[idx] = true
  252. clients = append(clients, client)
  253. clientNames = append(clientNames, client.Name())
  254. }
  255. }
  256. if len(domainRules) > 0 {
  257. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  258. }
  259. if len(clientNames) > 0 {
  260. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  261. }
  262. if len(clients) == 0 {
  263. clients = append(clients, s.clients[0])
  264. clientNames = append(clientNames, s.clients[0].Name())
  265. newError("domain ", domain, " will use the first DNS: ", clientNames).AtDebug().WriteToLog()
  266. }
  267. return clients
  268. }
  269. func init() {
  270. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  271. return New(ctx, config.(*Config))
  272. }))
  273. }