dns.go 16 KB

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