dns.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. core "github.com/v2fly/v2ray-core/v5"
  12. "github.com/v2fly/v2ray-core/v5/app/dns/fakedns"
  13. "github.com/v2fly/v2ray-core/v5/app/router"
  14. "github.com/v2fly/v2ray-core/v5/common"
  15. "github.com/v2fly/v2ray-core/v5/common/errors"
  16. "github.com/v2fly/v2ray-core/v5/common/net"
  17. "github.com/v2fly/v2ray-core/v5/common/platform"
  18. "github.com/v2fly/v2ray-core/v5/common/session"
  19. "github.com/v2fly/v2ray-core/v5/common/strmatcher"
  20. "github.com/v2fly/v2ray-core/v5/features"
  21. "github.com/v2fly/v2ray-core/v5/features/dns"
  22. "github.com/v2fly/v2ray-core/v5/infra/conf/cfgcommon"
  23. "github.com/v2fly/v2ray-core/v5/infra/conf/geodata"
  24. )
  25. // DNS is a DNS rely server.
  26. type DNS struct {
  27. sync.Mutex
  28. hosts *StaticHosts
  29. clients []*Client
  30. ctx context.Context
  31. clientTags map[string]bool
  32. fakeDNSEngine *FakeDNSEngine
  33. domainMatcher strmatcher.IndexMatcher
  34. matcherInfos []DomainMatcherInfo
  35. }
  36. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  37. type DomainMatcherInfo struct {
  38. clientIdx uint16
  39. domainRuleIdx uint16
  40. }
  41. // New creates a new DNS server with given configuration.
  42. func New(ctx context.Context, config *Config) (*DNS, error) {
  43. // Create static hosts
  44. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  45. if err != nil {
  46. return nil, newError("failed to create hosts").Base(err)
  47. }
  48. // Create name servers from legacy configs
  49. clients := []*Client{}
  50. for _, endpoint := range config.NameServers {
  51. features.PrintDeprecatedFeatureWarning("simple DNS server")
  52. client, err := NewClient(ctx, &NameServer{Address: endpoint}, config)
  53. if err != nil {
  54. return nil, newError("failed to create client").Base(err)
  55. }
  56. clients = append(clients, client)
  57. }
  58. // Create name servers
  59. nsClientMap := map[int]int{}
  60. for nsIdx, ns := range config.NameServer {
  61. client, err := NewClient(ctx, ns, config)
  62. if err != nil {
  63. return nil, newError("failed to create client").Base(err)
  64. }
  65. nsClientMap[nsIdx] = len(clients)
  66. clients = append(clients, client)
  67. }
  68. // If there is no DNS client in config, add a `localhost` DNS client
  69. if len(clients) == 0 {
  70. clients = append(clients, NewLocalDNSClient())
  71. }
  72. s := &DNS{
  73. hosts: hosts,
  74. clients: clients,
  75. ctx: ctx,
  76. }
  77. // Establish members related to global DNS state
  78. s.clientTags = make(map[string]bool)
  79. for _, client := range clients {
  80. s.clientTags[client.tag] = true
  81. }
  82. if err := establishDomainRules(s, config, nsClientMap); err != nil {
  83. return nil, err
  84. }
  85. if err := establishExpectedIPs(s, config, nsClientMap); err != nil {
  86. return nil, err
  87. }
  88. if err := establishFakeDNS(s, config, nsClientMap); err != nil {
  89. return nil, err
  90. }
  91. return s, nil
  92. }
  93. func establishDomainRules(s *DNS, config *Config, nsClientMap map[int]int) error {
  94. domainRuleCount := 0
  95. for _, ns := range config.NameServer {
  96. domainRuleCount += len(ns.PrioritizedDomain)
  97. }
  98. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  99. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
  100. var domainMatcher strmatcher.IndexMatcher
  101. switch config.DomainMatcher {
  102. case "mph", "hybrid":
  103. newError("using mph domain matcher").AtDebug().WriteToLog()
  104. domainMatcher = strmatcher.NewMphIndexMatcher()
  105. case "linear":
  106. fallthrough
  107. default:
  108. newError("using default domain matcher").AtDebug().WriteToLog()
  109. domainMatcher = strmatcher.NewLinearIndexMatcher()
  110. }
  111. for nsIdx, ns := range config.NameServer {
  112. clientIdx := nsClientMap[nsIdx]
  113. var rules []string
  114. ruleCurr := 0
  115. ruleIter := 0
  116. for _, domain := range ns.PrioritizedDomain {
  117. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  118. if err != nil {
  119. return newError("failed to create prioritized domain").Base(err).AtWarning()
  120. }
  121. originalRuleIdx := ruleCurr
  122. if ruleCurr < len(ns.OriginalRules) {
  123. rule := ns.OriginalRules[ruleCurr]
  124. if ruleCurr >= len(rules) {
  125. rules = append(rules, rule.Rule)
  126. }
  127. ruleIter++
  128. if ruleIter >= int(rule.Size) {
  129. ruleIter = 0
  130. ruleCurr++
  131. }
  132. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  133. rules = append(rules, domainRule.String())
  134. ruleCurr++
  135. }
  136. midx := domainMatcher.Add(domainRule)
  137. matcherInfos[midx] = DomainMatcherInfo{
  138. clientIdx: uint16(clientIdx),
  139. domainRuleIdx: uint16(originalRuleIdx),
  140. }
  141. if err != nil {
  142. return newError("failed to create prioritized domain").Base(err).AtWarning()
  143. }
  144. }
  145. s.clients[clientIdx].domains = rules
  146. }
  147. if err := domainMatcher.Build(); err != nil {
  148. return err
  149. }
  150. s.domainMatcher = domainMatcher
  151. s.matcherInfos = matcherInfos
  152. return nil
  153. }
  154. func establishExpectedIPs(s *DNS, config *Config, nsClientMap map[int]int) error {
  155. geoipContainer := router.GeoIPMatcherContainer{}
  156. for nsIdx, ns := range config.NameServer {
  157. clientIdx := nsClientMap[nsIdx]
  158. var matchers []*router.GeoIPMatcher
  159. for _, geoip := range ns.Geoip {
  160. matcher, err := geoipContainer.Add(geoip)
  161. if err != nil {
  162. return newError("failed to create ip matcher").Base(err).AtWarning()
  163. }
  164. matchers = append(matchers, matcher)
  165. }
  166. s.clients[clientIdx].expectIPs = matchers
  167. }
  168. return nil
  169. }
  170. func establishFakeDNS(s *DNS, config *Config, nsClientMap map[int]int) error {
  171. fakeHolders := &fakedns.HolderMulti{}
  172. fakeDefault := (*fakedns.HolderMulti)(nil)
  173. if config.FakeDns != nil {
  174. defaultEngine, err := fakeHolders.AddPoolMulti(config.FakeDns)
  175. if err != nil {
  176. return newError("fail to create fake dns").Base(err).AtWarning()
  177. }
  178. fakeDefault = defaultEngine
  179. }
  180. for nsIdx, ns := range config.NameServer {
  181. clientIdx := nsClientMap[nsIdx]
  182. if ns.FakeDns == nil {
  183. continue
  184. }
  185. engine, err := fakeHolders.AddPoolMulti(ns.FakeDns)
  186. if err != nil {
  187. return newError("fail to create fake dns").Base(err).AtWarning()
  188. }
  189. s.clients[clientIdx].fakeDNS = NewFakeDNSServer(engine)
  190. s.clients[clientIdx].queryStrategy.FakeEnable = true
  191. }
  192. // Do not create FakeDNSEngine feature if no FakeDNS server is configured
  193. if fakeHolders.IsEmpty() {
  194. return nil
  195. }
  196. // Add FakeDNSEngine feature when DNS feature is added for the first time
  197. s.fakeDNSEngine = &FakeDNSEngine{dns: s, fakeHolders: fakeHolders, fakeDefault: fakeDefault}
  198. return core.RequireFeatures(s.ctx, func(client dns.Client) error {
  199. v := core.MustFromContext(s.ctx)
  200. if v.GetFeature(dns.FakeDNSEngineType()) != nil {
  201. return nil
  202. }
  203. if client, ok := client.(dns.ClientWithFakeDNS); ok {
  204. return v.AddFeature(client.AsFakeDNSEngine())
  205. }
  206. return nil
  207. })
  208. }
  209. // Type implements common.HasType.
  210. func (*DNS) Type() interface{} {
  211. return dns.ClientType()
  212. }
  213. // Start implements common.Runnable.
  214. func (s *DNS) Start() error {
  215. return nil
  216. }
  217. // Close implements common.Closable.
  218. func (s *DNS) Close() error {
  219. return nil
  220. }
  221. // IsOwnLink implements proxy.dns.ownLinkVerifier
  222. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  223. inbound := session.InboundFromContext(ctx)
  224. return inbound != nil && s.clientTags[inbound.Tag]
  225. }
  226. // AsFakeDNSClient implements dns.ClientWithFakeDNS.
  227. func (s *DNS) AsFakeDNSClient() dns.Client {
  228. return &FakeDNSClient{DNS: s}
  229. }
  230. // AsFakeDNSEngine implements dns.ClientWithFakeDNS.
  231. func (s *DNS) AsFakeDNSEngine() dns.FakeDNSEngine {
  232. return s.fakeDNSEngine
  233. }
  234. // LookupIP implements dns.Client.
  235. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  236. return s.lookupIPInternal(domain, dns.IPOption{IPv4Enable: true, IPv6Enable: true, FakeEnable: false})
  237. }
  238. // LookupIPv4 implements dns.IPv4Lookup.
  239. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  240. return s.lookupIPInternal(domain, dns.IPOption{IPv4Enable: true, FakeEnable: false})
  241. }
  242. // LookupIPv6 implements dns.IPv6Lookup.
  243. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  244. return s.lookupIPInternal(domain, dns.IPOption{IPv6Enable: true, FakeEnable: false})
  245. }
  246. func (s *DNS) lookupIPInternal(domain string, option dns.IPOption) ([]net.IP, error) {
  247. if domain == "" {
  248. return nil, newError("empty domain name")
  249. }
  250. // Normalize the FQDN form query
  251. domain = strings.TrimSuffix(domain, ".")
  252. // Static host lookup
  253. switch addrs := s.hosts.Lookup(domain, option); {
  254. case addrs == nil: // Domain not recorded in static host
  255. break
  256. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  257. return nil, dns.ErrEmptyResponse
  258. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  259. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  260. domain = addrs[0].Domain()
  261. default: // Successfully found ip records in static host
  262. newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog()
  263. return toNetIP(addrs)
  264. }
  265. // Name servers lookup
  266. errs := []error{}
  267. for _, client := range s.sortClients(domain, option) {
  268. ips, err := client.QueryIP(s.ctx, domain, option)
  269. if len(ips) > 0 {
  270. return ips, nil
  271. }
  272. if err != nil {
  273. errs = append(errs, err)
  274. }
  275. if err != dns.ErrEmptyResponse { // ErrEmptyResponse is not seen as failure, so no failed log
  276. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  277. }
  278. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  279. return nil, err // Only continue lookup for certain errors
  280. }
  281. }
  282. if len(errs) == 0 {
  283. return nil, dns.ErrEmptyResponse
  284. }
  285. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  286. }
  287. func (s *DNS) sortClients(domain string, option dns.IPOption) []*Client {
  288. clients := make([]*Client, 0, len(s.clients))
  289. clientUsed := make([]bool, len(s.clients))
  290. clientIdxs := make([]int, 0, len(s.clients))
  291. domainRules := []string{}
  292. // Priority domain matching
  293. for _, match := range s.domainMatcher.Match(domain) {
  294. info := s.matcherInfos[match]
  295. client := s.clients[info.clientIdx]
  296. domainRule := client.domains[info.domainRuleIdx]
  297. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  298. switch {
  299. case clientUsed[info.clientIdx]:
  300. continue
  301. case !option.FakeEnable && isFakeDNS(client.server):
  302. continue
  303. }
  304. clientUsed[info.clientIdx] = true
  305. clients = append(clients, client)
  306. clientIdxs = append(clientIdxs, int(info.clientIdx))
  307. }
  308. // Default round-robin query
  309. hasDomainMatch := len(clients) > 0
  310. for idx, client := range s.clients {
  311. switch {
  312. case clientUsed[idx]:
  313. continue
  314. case !option.FakeEnable && isFakeDNS(client.server):
  315. continue
  316. case client.fallbackStrategy == FallbackStrategy_Disabled:
  317. continue
  318. case client.fallbackStrategy == FallbackStrategy_DisabledIfAnyMatch && hasDomainMatch:
  319. continue
  320. }
  321. clientUsed[idx] = true
  322. clients = append(clients, client)
  323. clientIdxs = append(clientIdxs, idx)
  324. }
  325. if len(domainRules) > 0 {
  326. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  327. }
  328. if len(clientIdxs) > 0 {
  329. newError("domain ", domain, " will use DNS in order: ", s.formatClientNames(clientIdxs, option), " ", toReqTypes(option)).AtDebug().WriteToLog()
  330. }
  331. return clients
  332. }
  333. func (s *DNS) formatClientNames(clientIdxs []int, option dns.IPOption) []string {
  334. clientNames := make([]string, 0, len(clientIdxs))
  335. counter := make(map[string]uint, len(clientIdxs))
  336. for _, clientIdx := range clientIdxs {
  337. client := s.clients[clientIdx]
  338. var name string
  339. if option.With(client.queryStrategy).FakeEnable {
  340. name = fmt.Sprintf("%s(DNS idx:%d)", client.fakeDNS.Name(), clientIdx)
  341. } else {
  342. name = client.Name()
  343. }
  344. counter[name]++
  345. clientNames = append(clientNames, name)
  346. }
  347. for idx, clientIdx := range clientIdxs {
  348. name := clientNames[idx]
  349. if counter[name] > 1 {
  350. clientNames[idx] = fmt.Sprintf("%s(DNS idx:%d)", name, clientIdx)
  351. }
  352. }
  353. return clientNames
  354. }
  355. func init() {
  356. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  357. return New(ctx, config.(*Config))
  358. }))
  359. common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  360. ctx = cfgcommon.NewConfigureLoadingContext(ctx)
  361. geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string {
  362. return "standard"
  363. })
  364. if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil {
  365. cfgcommon.SetGeoDataLoader(ctx, loader)
  366. } else {
  367. return nil, newError("unable to create geo data loader ").Base(err)
  368. }
  369. cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx)
  370. geoLoader := cfgEnv.GetGeoLoader()
  371. simplifiedConfig := config.(*SimplifiedConfig)
  372. for _, v := range simplifiedConfig.NameServer {
  373. for _, geo := range v.Geoip {
  374. if geo.Code != "" {
  375. filepath := "geoip.dat"
  376. if geo.FilePath != "" {
  377. filepath = geo.FilePath
  378. } else {
  379. geo.CountryCode = geo.Code
  380. }
  381. var err error
  382. geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code)
  383. if err != nil {
  384. return nil, newError("unable to load geoip").Base(err)
  385. }
  386. }
  387. }
  388. }
  389. var nameservers []*NameServer
  390. for _, v := range simplifiedConfig.NameServer {
  391. nameserver := &NameServer{
  392. Address: v.Address,
  393. ClientIp: net.ParseIP(v.ClientIp),
  394. Tag: v.Tag,
  395. QueryStrategy: v.QueryStrategy,
  396. CacheStrategy: v.CacheStrategy,
  397. FallbackStrategy: v.FallbackStrategy,
  398. SkipFallback: v.SkipFallback,
  399. Geoip: v.Geoip,
  400. }
  401. for _, prioritizedDomain := range v.PrioritizedDomain {
  402. nameserver.PrioritizedDomain = append(nameserver.PrioritizedDomain, &NameServer_PriorityDomain{
  403. Type: prioritizedDomain.Type,
  404. Domain: prioritizedDomain.Domain,
  405. })
  406. }
  407. nameservers = append(nameservers, nameserver)
  408. }
  409. var statichosts []*HostMapping
  410. for _, v := range simplifiedConfig.StaticHosts {
  411. statichost := &HostMapping{
  412. Type: v.Type,
  413. Domain: v.Domain,
  414. ProxiedDomain: v.ProxiedDomain,
  415. }
  416. for _, ip := range v.Ip {
  417. statichost.Ip = append(statichost.Ip, net.ParseIP(ip))
  418. }
  419. statichosts = append(statichosts, statichost)
  420. }
  421. fullConfig := &Config{
  422. StaticHosts: statichosts,
  423. NameServer: nameservers,
  424. ClientIp: net.ParseIP(simplifiedConfig.ClientIp),
  425. Tag: simplifiedConfig.Tag,
  426. DomainMatcher: simplifiedConfig.DomainMatcher,
  427. QueryStrategy: simplifiedConfig.QueryStrategy,
  428. CacheStrategy: simplifiedConfig.CacheStrategy,
  429. FallbackStrategy: simplifiedConfig.FallbackStrategy,
  430. // Deprecated flags
  431. DisableCache: simplifiedConfig.DisableCache,
  432. DisableFallback: simplifiedConfig.DisableFallback,
  433. DisableFallbackIfMatch: simplifiedConfig.DisableFallbackIfMatch,
  434. }
  435. return common.CreateObject(ctx, fullConfig)
  436. }))
  437. }