dns.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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/v5/common/errors/errorgen
  6. import (
  7. "context"
  8. "fmt"
  9. "strings"
  10. "sync"
  11. "github.com/v2fly/v2ray-core/v5/app/router"
  12. "github.com/v2fly/v2ray-core/v5/common"
  13. "github.com/v2fly/v2ray-core/v5/common/errors"
  14. "github.com/v2fly/v2ray-core/v5/common/net"
  15. "github.com/v2fly/v2ray-core/v5/common/platform"
  16. "github.com/v2fly/v2ray-core/v5/common/session"
  17. "github.com/v2fly/v2ray-core/v5/common/strmatcher"
  18. "github.com/v2fly/v2ray-core/v5/features"
  19. "github.com/v2fly/v2ray-core/v5/features/dns"
  20. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon"
  21. "github.com/v2fly/v2ray-core/v5/infra/conf/geodata"
  22. )
  23. // DNS is a DNS rely server.
  24. type DNS struct {
  25. sync.Mutex
  26. ipOption dns.IPOption
  27. hosts *StaticHosts
  28. clients []*Client
  29. ctx context.Context
  30. clientTags map[string]bool
  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. // Create static hosts
  42. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  43. if err != nil {
  44. return nil, newError("failed to create hosts").Base(err)
  45. }
  46. // Create name servers from legacy configs
  47. clients := []*Client{}
  48. for _, endpoint := range config.NameServers {
  49. features.PrintDeprecatedFeatureWarning("simple DNS server")
  50. client, err := NewClient(ctx, &NameServer{Address: endpoint}, config)
  51. if err != nil {
  52. return nil, newError("failed to create client").Base(err)
  53. }
  54. clients = append(clients, client)
  55. }
  56. // Create name servers
  57. nsClientMap := map[int]int{}
  58. for nsIdx, ns := range config.NameServer {
  59. client, err := NewClient(ctx, ns, config)
  60. if err != nil {
  61. return nil, newError("failed to create client").Base(err)
  62. }
  63. nsClientMap[nsIdx] = len(clients)
  64. clients = append(clients, client)
  65. }
  66. // If there is no DNS client in config, add a `localhost` DNS client
  67. if len(clients) == 0 {
  68. clients = append(clients, NewLocalDNSClient())
  69. }
  70. // Establish members related to global DNS state
  71. domainMatcher, matcherInfos, err := establishDomainRules(config, clients, nsClientMap)
  72. if err != nil {
  73. return nil, err
  74. }
  75. if err := establishExpectedIPs(config, clients, nsClientMap); err != nil {
  76. return nil, err
  77. }
  78. clientTags := make(map[string]bool)
  79. for _, client := range clients {
  80. clientTags[client.tag] = true
  81. }
  82. return &DNS{
  83. ipOption: toIPOption(config.QueryStrategy),
  84. hosts: hosts,
  85. clients: clients,
  86. ctx: ctx,
  87. clientTags: clientTags,
  88. domainMatcher: domainMatcher,
  89. matcherInfos: matcherInfos,
  90. }, nil
  91. }
  92. func establishDomainRules(config *Config, clients []*Client, nsClientMap map[int]int) (strmatcher.IndexMatcher, []DomainMatcherInfo, error) {
  93. domainRuleCount := 0
  94. for _, ns := range config.NameServer {
  95. domainRuleCount += len(ns.PrioritizedDomain)
  96. }
  97. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  98. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
  99. domainMatcher := &strmatcher.LinearIndexMatcher{}
  100. for nsIdx, ns := range config.NameServer {
  101. clientIdx := nsClientMap[nsIdx]
  102. var rules []string
  103. ruleCurr := 0
  104. ruleIter := 0
  105. for _, domain := range ns.PrioritizedDomain {
  106. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  107. if err != nil {
  108. return nil, nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  109. }
  110. originalRuleIdx := ruleCurr
  111. if ruleCurr < len(ns.OriginalRules) {
  112. rule := ns.OriginalRules[ruleCurr]
  113. if ruleCurr >= len(rules) {
  114. rules = append(rules, rule.Rule)
  115. }
  116. ruleIter++
  117. if ruleIter >= int(rule.Size) {
  118. ruleIter = 0
  119. ruleCurr++
  120. }
  121. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  122. rules = append(rules, domainRule.String())
  123. ruleCurr++
  124. }
  125. midx := domainMatcher.Add(domainRule)
  126. matcherInfos[midx] = DomainMatcherInfo{
  127. clientIdx: uint16(clientIdx),
  128. domainRuleIdx: uint16(originalRuleIdx),
  129. }
  130. if err != nil {
  131. return nil, nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  132. }
  133. }
  134. clients[clientIdx].domains = rules
  135. }
  136. return domainMatcher, matcherInfos, nil
  137. }
  138. func establishExpectedIPs(config *Config, clients []*Client, nsClientMap map[int]int) error {
  139. geoipContainer := router.GeoIPMatcherContainer{}
  140. for nsIdx, ns := range config.NameServer {
  141. clientIdx := nsClientMap[nsIdx]
  142. var matchers []*router.GeoIPMatcher
  143. for _, geoip := range ns.Geoip {
  144. matcher, err := geoipContainer.Add(geoip)
  145. if err != nil {
  146. return newError("failed to create ip matcher").Base(err).AtWarning()
  147. }
  148. matchers = append(matchers, matcher)
  149. }
  150. clients[clientIdx].expectIPs = matchers
  151. }
  152. return nil
  153. }
  154. // Type implements common.HasType.
  155. func (*DNS) Type() interface{} {
  156. return dns.ClientType()
  157. }
  158. // Start implements common.Runnable.
  159. func (s *DNS) Start() error {
  160. return nil
  161. }
  162. // Close implements common.Closable.
  163. func (s *DNS) Close() error {
  164. return nil
  165. }
  166. // IsOwnLink implements proxy.dns.ownLinkVerifier
  167. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  168. inbound := session.InboundFromContext(ctx)
  169. return inbound != nil && s.clientTags[inbound.Tag]
  170. }
  171. // LookupIP implements dns.Client.
  172. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  173. return s.lookupIPInternal(domain, s.ipOption)
  174. }
  175. // LookupIPv4 implements dns.IPv4Lookup.
  176. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  177. if option := s.ipOption.With(dns.IPOption{IPv4Enable: true}); option.IsValid() {
  178. return s.lookupIPInternal(domain, option)
  179. }
  180. return nil, dns.ErrEmptyResponse
  181. }
  182. // LookupIPv6 implements dns.IPv6Lookup.
  183. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  184. if option := s.ipOption.With(dns.IPOption{IPv6Enable: true}); option.IsValid() {
  185. return s.lookupIPInternal(domain, option)
  186. }
  187. return nil, dns.ErrEmptyResponse
  188. }
  189. func (s *DNS) lookupIPInternal(domain string, option dns.IPOption) ([]net.IP, error) {
  190. if domain == "" {
  191. return nil, newError("empty domain name")
  192. }
  193. // Normalize the FQDN form query
  194. domain = strings.TrimSuffix(domain, ".")
  195. // Static host lookup
  196. switch addrs := s.hosts.Lookup(domain, option); {
  197. case addrs == nil: // Domain not recorded in static host
  198. break
  199. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  200. return nil, dns.ErrEmptyResponse
  201. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  202. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  203. domain = addrs[0].Domain()
  204. default: // Successfully found ip records in static host
  205. newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog()
  206. return toNetIP(addrs)
  207. }
  208. // Name servers lookup
  209. errs := []error{}
  210. for _, client := range s.sortClients(domain, option) {
  211. ips, err := client.QueryIP(s.ctx, domain, option)
  212. if len(ips) > 0 {
  213. return ips, nil
  214. }
  215. if err != nil {
  216. errs = append(errs, err)
  217. }
  218. if err != dns.ErrEmptyResponse { // ErrEmptyResponse is not seen as failure, so no failed log
  219. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  220. }
  221. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  222. return nil, err // Continues lookup for certain errors
  223. }
  224. }
  225. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  226. }
  227. // GetIPOption implements ClientWithIPOption.
  228. func (s *DNS) GetIPOption() *dns.IPOption {
  229. return &s.ipOption
  230. }
  231. // SetQueryOption implements ClientWithIPOption.
  232. func (s *DNS) SetQueryOption(isIPv4Enable, isIPv6Enable bool) {
  233. s.ipOption.IPv4Enable = isIPv4Enable
  234. s.ipOption.IPv6Enable = isIPv6Enable
  235. }
  236. // SetFakeDNSOption implements ClientWithIPOption.
  237. func (s *DNS) SetFakeDNSOption(isFakeEnable bool) {
  238. s.ipOption.FakeEnable = isFakeEnable
  239. }
  240. func (s *DNS) sortClients(domain string, option dns.IPOption) []*Client {
  241. clients := make([]*Client, 0, len(s.clients))
  242. clientUsed := make([]bool, len(s.clients))
  243. clientNames := make([]string, 0, len(s.clients))
  244. domainRules := []string{}
  245. // Priority domain matching
  246. for _, match := range s.domainMatcher.Match(domain) {
  247. info := s.matcherInfos[match]
  248. client := s.clients[info.clientIdx]
  249. domainRule := client.domains[info.domainRuleIdx]
  250. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  251. switch {
  252. case clientUsed[info.clientIdx]:
  253. continue
  254. case !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS"):
  255. continue
  256. }
  257. clientUsed[info.clientIdx] = true
  258. clients = append(clients, client)
  259. clientNames = append(clientNames, client.Name())
  260. }
  261. // Default round-robin query
  262. hasDomainMatch := len(clients) > 0
  263. for idx, client := range s.clients {
  264. switch {
  265. case clientUsed[idx]:
  266. continue
  267. case !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS"):
  268. continue
  269. case client.fallbackStrategy == FallbackStrategy_Disabled:
  270. continue
  271. case client.fallbackStrategy == FallbackStrategy_DisabledIfAnyMatch && hasDomainMatch:
  272. continue
  273. }
  274. clientUsed[idx] = true
  275. clients = append(clients, client)
  276. clientNames = append(clientNames, client.Name())
  277. }
  278. if len(domainRules) > 0 {
  279. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  280. }
  281. if len(clientNames) > 0 {
  282. newError("domain ", domain, " will use DNS in order: ", clientNames, " ", toReqTypes(option)).AtDebug().WriteToLog()
  283. }
  284. return clients
  285. }
  286. func init() {
  287. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  288. return New(ctx, config.(*Config))
  289. }))
  290. common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  291. ctx = cfgcommon.NewConfigureLoadingContext(ctx)
  292. geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string {
  293. return "standard"
  294. })
  295. if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil {
  296. cfgcommon.SetGeoDataLoader(ctx, loader)
  297. } else {
  298. return nil, newError("unable to create geo data loader ").Base(err)
  299. }
  300. cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx)
  301. geoLoader := cfgEnv.GetGeoLoader()
  302. simplifiedConfig := config.(*SimplifiedConfig)
  303. for _, v := range simplifiedConfig.NameServer {
  304. for _, geo := range v.Geoip {
  305. if geo.Code != "" {
  306. filepath := "geoip.dat"
  307. if geo.FilePath != "" {
  308. filepath = geo.FilePath
  309. } else {
  310. geo.CountryCode = geo.Code
  311. }
  312. var err error
  313. geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code)
  314. if err != nil {
  315. return nil, newError("unable to load geoip").Base(err)
  316. }
  317. }
  318. }
  319. }
  320. var nameservers []*NameServer
  321. for _, v := range simplifiedConfig.NameServer {
  322. nameserver := &NameServer{
  323. Address: v.Address,
  324. ClientIp: net.ParseIP(v.ClientIp),
  325. Tag: v.Tag,
  326. QueryStrategy: v.QueryStrategy,
  327. CacheStrategy: v.CacheStrategy,
  328. FallbackStrategy: v.FallbackStrategy,
  329. SkipFallback: v.SkipFallback,
  330. Geoip: v.Geoip,
  331. }
  332. for _, prioritizedDomain := range v.PrioritizedDomain {
  333. nameserver.PrioritizedDomain = append(nameserver.PrioritizedDomain, &NameServer_PriorityDomain{
  334. Type: prioritizedDomain.Type,
  335. Domain: prioritizedDomain.Domain,
  336. })
  337. }
  338. nameservers = append(nameservers, nameserver)
  339. }
  340. fullConfig := &Config{
  341. StaticHosts: simplifiedConfig.StaticHosts,
  342. NameServer: nameservers,
  343. ClientIp: net.ParseIP(simplifiedConfig.ClientIp),
  344. Tag: simplifiedConfig.Tag,
  345. QueryStrategy: simplifiedConfig.QueryStrategy,
  346. CacheStrategy: simplifiedConfig.CacheStrategy,
  347. FallbackStrategy: simplifiedConfig.FallbackStrategy,
  348. // Deprecated flags
  349. DisableCache: simplifiedConfig.DisableCache,
  350. DisableFallback: simplifiedConfig.DisableFallback,
  351. DisableFallbackIfMatch: simplifiedConfig.DisableFallbackIfMatch,
  352. }
  353. return common.CreateObject(ctx, fullConfig)
  354. }))
  355. }