dns.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. var domainMatcher strmatcher.IndexMatcher
  100. switch config.DomainMatcher {
  101. case "mph", "hybrid":
  102. newError("using mph domain matcher").AtDebug().WriteToLog()
  103. domainMatcher = strmatcher.NewMphIndexMatcher()
  104. case "linear":
  105. fallthrough
  106. default:
  107. newError("using default domain matcher").AtDebug().WriteToLog()
  108. domainMatcher = strmatcher.NewLinearIndexMatcher()
  109. }
  110. for nsIdx, ns := range config.NameServer {
  111. clientIdx := nsClientMap[nsIdx]
  112. var rules []string
  113. ruleCurr := 0
  114. ruleIter := 0
  115. for _, domain := range ns.PrioritizedDomain {
  116. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  117. if err != nil {
  118. return nil, nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  119. }
  120. originalRuleIdx := ruleCurr
  121. if ruleCurr < len(ns.OriginalRules) {
  122. rule := ns.OriginalRules[ruleCurr]
  123. if ruleCurr >= len(rules) {
  124. rules = append(rules, rule.Rule)
  125. }
  126. ruleIter++
  127. if ruleIter >= int(rule.Size) {
  128. ruleIter = 0
  129. ruleCurr++
  130. }
  131. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  132. rules = append(rules, domainRule.String())
  133. ruleCurr++
  134. }
  135. midx := domainMatcher.Add(domainRule)
  136. matcherInfos[midx] = DomainMatcherInfo{
  137. clientIdx: uint16(clientIdx),
  138. domainRuleIdx: uint16(originalRuleIdx),
  139. }
  140. if err != nil {
  141. return nil, nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  142. }
  143. }
  144. clients[clientIdx].domains = rules
  145. }
  146. if err := domainMatcher.Build(); err != nil {
  147. return nil, nil, err
  148. }
  149. return domainMatcher, matcherInfos, nil
  150. }
  151. func establishExpectedIPs(config *Config, clients []*Client, nsClientMap map[int]int) error {
  152. geoipContainer := router.GeoIPMatcherContainer{}
  153. for nsIdx, ns := range config.NameServer {
  154. clientIdx := nsClientMap[nsIdx]
  155. var matchers []*router.GeoIPMatcher
  156. for _, geoip := range ns.Geoip {
  157. matcher, err := geoipContainer.Add(geoip)
  158. if err != nil {
  159. return newError("failed to create ip matcher").Base(err).AtWarning()
  160. }
  161. matchers = append(matchers, matcher)
  162. }
  163. clients[clientIdx].expectIPs = matchers
  164. }
  165. return nil
  166. }
  167. // Type implements common.HasType.
  168. func (*DNS) Type() interface{} {
  169. return dns.ClientType()
  170. }
  171. // Start implements common.Runnable.
  172. func (s *DNS) Start() error {
  173. return nil
  174. }
  175. // Close implements common.Closable.
  176. func (s *DNS) Close() error {
  177. return nil
  178. }
  179. // IsOwnLink implements proxy.dns.ownLinkVerifier
  180. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  181. inbound := session.InboundFromContext(ctx)
  182. return inbound != nil && s.clientTags[inbound.Tag]
  183. }
  184. // LookupIP implements dns.Client.
  185. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  186. return s.lookupIPInternal(domain, s.ipOption)
  187. }
  188. // LookupIPv4 implements dns.IPv4Lookup.
  189. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  190. if option := s.ipOption.With(dns.IPOption{IPv4Enable: true}); option.IsValid() {
  191. return s.lookupIPInternal(domain, option)
  192. }
  193. return nil, dns.ErrEmptyResponse
  194. }
  195. // LookupIPv6 implements dns.IPv6Lookup.
  196. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  197. if option := s.ipOption.With(dns.IPOption{IPv6Enable: true}); option.IsValid() {
  198. return s.lookupIPInternal(domain, option)
  199. }
  200. return nil, dns.ErrEmptyResponse
  201. }
  202. func (s *DNS) lookupIPInternal(domain string, option dns.IPOption) ([]net.IP, error) {
  203. if domain == "" {
  204. return nil, newError("empty domain name")
  205. }
  206. // Normalize the FQDN form query
  207. domain = strings.TrimSuffix(domain, ".")
  208. // Static host lookup
  209. switch addrs := s.hosts.Lookup(domain, option); {
  210. case addrs == nil: // Domain not recorded in static host
  211. break
  212. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  213. return nil, dns.ErrEmptyResponse
  214. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  215. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  216. domain = addrs[0].Domain()
  217. default: // Successfully found ip records in static host
  218. newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog()
  219. return toNetIP(addrs)
  220. }
  221. // Name servers lookup
  222. errs := []error{}
  223. for _, client := range s.sortClients(domain, option) {
  224. ips, err := client.QueryIP(s.ctx, domain, option)
  225. if len(ips) > 0 {
  226. return ips, nil
  227. }
  228. if err != nil {
  229. errs = append(errs, err)
  230. }
  231. if err != dns.ErrEmptyResponse { // ErrEmptyResponse is not seen as failure, so no failed log
  232. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  233. }
  234. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  235. return nil, err // Continues lookup for certain errors
  236. }
  237. }
  238. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  239. }
  240. // GetIPOption implements ClientWithIPOption.
  241. func (s *DNS) GetIPOption() *dns.IPOption {
  242. return &s.ipOption
  243. }
  244. // SetQueryOption implements ClientWithIPOption.
  245. func (s *DNS) SetQueryOption(isIPv4Enable, isIPv6Enable bool) {
  246. s.ipOption.IPv4Enable = isIPv4Enable
  247. s.ipOption.IPv6Enable = isIPv6Enable
  248. }
  249. // SetFakeDNSOption implements ClientWithIPOption.
  250. func (s *DNS) SetFakeDNSOption(isFakeEnable bool) {
  251. s.ipOption.FakeEnable = isFakeEnable
  252. }
  253. func (s *DNS) sortClients(domain string, option dns.IPOption) []*Client {
  254. clients := make([]*Client, 0, len(s.clients))
  255. clientUsed := make([]bool, len(s.clients))
  256. clientNames := make([]string, 0, len(s.clients))
  257. domainRules := []string{}
  258. // Priority domain matching
  259. for _, match := range s.domainMatcher.Match(domain) {
  260. info := s.matcherInfos[match]
  261. client := s.clients[info.clientIdx]
  262. domainRule := client.domains[info.domainRuleIdx]
  263. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  264. switch {
  265. case clientUsed[info.clientIdx]:
  266. continue
  267. case !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS"):
  268. continue
  269. }
  270. clientUsed[info.clientIdx] = true
  271. clients = append(clients, client)
  272. clientNames = append(clientNames, client.Name())
  273. }
  274. // Default round-robin query
  275. hasDomainMatch := len(clients) > 0
  276. for idx, client := range s.clients {
  277. switch {
  278. case clientUsed[idx]:
  279. continue
  280. case !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS"):
  281. continue
  282. case client.fallbackStrategy == FallbackStrategy_Disabled:
  283. continue
  284. case client.fallbackStrategy == FallbackStrategy_DisabledIfAnyMatch && hasDomainMatch:
  285. continue
  286. }
  287. clientUsed[idx] = true
  288. clients = append(clients, client)
  289. clientNames = append(clientNames, client.Name())
  290. }
  291. if len(domainRules) > 0 {
  292. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  293. }
  294. if len(clientNames) > 0 {
  295. newError("domain ", domain, " will use DNS in order: ", clientNames, " ", toReqTypes(option)).AtDebug().WriteToLog()
  296. }
  297. return clients
  298. }
  299. func init() {
  300. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  301. return New(ctx, config.(*Config))
  302. }))
  303. common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  304. ctx = cfgcommon.NewConfigureLoadingContext(ctx)
  305. geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string {
  306. return "standard"
  307. })
  308. if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil {
  309. cfgcommon.SetGeoDataLoader(ctx, loader)
  310. } else {
  311. return nil, newError("unable to create geo data loader ").Base(err)
  312. }
  313. cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx)
  314. geoLoader := cfgEnv.GetGeoLoader()
  315. simplifiedConfig := config.(*SimplifiedConfig)
  316. for _, v := range simplifiedConfig.NameServer {
  317. for _, geo := range v.Geoip {
  318. if geo.Code != "" {
  319. filepath := "geoip.dat"
  320. if geo.FilePath != "" {
  321. filepath = geo.FilePath
  322. } else {
  323. geo.CountryCode = geo.Code
  324. }
  325. var err error
  326. geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code)
  327. if err != nil {
  328. return nil, newError("unable to load geoip").Base(err)
  329. }
  330. }
  331. }
  332. }
  333. var nameservers []*NameServer
  334. for _, v := range simplifiedConfig.NameServer {
  335. nameserver := &NameServer{
  336. Address: v.Address,
  337. ClientIp: net.ParseIP(v.ClientIp),
  338. Tag: v.Tag,
  339. QueryStrategy: v.QueryStrategy,
  340. CacheStrategy: v.CacheStrategy,
  341. FallbackStrategy: v.FallbackStrategy,
  342. SkipFallback: v.SkipFallback,
  343. Geoip: v.Geoip,
  344. }
  345. for _, prioritizedDomain := range v.PrioritizedDomain {
  346. nameserver.PrioritizedDomain = append(nameserver.PrioritizedDomain, &NameServer_PriorityDomain{
  347. Type: prioritizedDomain.Type,
  348. Domain: prioritizedDomain.Domain,
  349. })
  350. }
  351. nameservers = append(nameservers, nameserver)
  352. }
  353. fullConfig := &Config{
  354. StaticHosts: simplifiedConfig.StaticHosts,
  355. NameServer: nameservers,
  356. ClientIp: net.ParseIP(simplifiedConfig.ClientIp),
  357. Tag: simplifiedConfig.Tag,
  358. QueryStrategy: simplifiedConfig.QueryStrategy,
  359. CacheStrategy: simplifiedConfig.CacheStrategy,
  360. FallbackStrategy: simplifiedConfig.FallbackStrategy,
  361. // Deprecated flags
  362. DisableCache: simplifiedConfig.DisableCache,
  363. DisableFallback: simplifiedConfig.DisableFallback,
  364. DisableFallbackIfMatch: simplifiedConfig.DisableFallbackIfMatch,
  365. }
  366. return common.CreateObject(ctx, fullConfig)
  367. }))
  368. }