dns.go 11 KB

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