dns.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. "strings"
  10. "sync"
  11. "github.com/v2fly/v2ray-core/v4/app/router"
  12. "github.com/v2fly/v2ray-core/v4/common"
  13. "github.com/v2fly/v2ray-core/v4/common/errors"
  14. "github.com/v2fly/v2ray-core/v4/common/net"
  15. "github.com/v2fly/v2ray-core/v4/common/platform"
  16. "github.com/v2fly/v2ray-core/v4/common/session"
  17. "github.com/v2fly/v2ray-core/v4/common/strmatcher"
  18. "github.com/v2fly/v2ray-core/v4/features"
  19. "github.com/v2fly/v2ray-core/v4/features/dns"
  20. "github.com/v2fly/v2ray-core/v4/infra/conf/cfgcommon"
  21. "github.com/v2fly/v2ray-core/v4/infra/conf/geodata"
  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.LinearIndexMatcher{}
  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, *s.ipOption)
  157. }
  158. // LookupIPv4 implements dns.IPv4Lookup.
  159. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  160. if !s.ipOption.IPv4Enable {
  161. return nil, dns.ErrEmptyResponse
  162. }
  163. o := *s.ipOption
  164. o.IPv6Enable = false
  165. return s.lookupIPInternal(domain, o)
  166. }
  167. // LookupIPv6 implements dns.IPv6Lookup.
  168. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  169. if !s.ipOption.IPv6Enable {
  170. return nil, dns.ErrEmptyResponse
  171. }
  172. o := *s.ipOption
  173. o.IPv4Enable = false
  174. return s.lookupIPInternal(domain, o)
  175. }
  176. func (s *DNS) lookupIPInternal(domain string, option dns.IPOption) ([]net.IP, error) {
  177. if domain == "" {
  178. return nil, newError("empty domain name")
  179. }
  180. // Normalize the FQDN form query
  181. domain = strings.TrimSuffix(domain, ".")
  182. // Static host lookup
  183. switch addrs := s.hosts.Lookup(domain, option); {
  184. case addrs == nil: // Domain not recorded in static host
  185. break
  186. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  187. return nil, dns.ErrEmptyResponse
  188. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  189. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  190. domain = addrs[0].Domain()
  191. default: // Successfully found ip records in static host
  192. newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog()
  193. return toNetIP(addrs)
  194. }
  195. // Name servers lookup
  196. errs := []error{}
  197. ctx := session.ContextWithInbound(s.ctx, &session.Inbound{Tag: s.tag})
  198. for _, client := range s.sortClients(domain) {
  199. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  200. newError("skip DNS resolution for domain ", domain, " at server ", client.Name()).AtDebug().WriteToLog()
  201. continue
  202. }
  203. ips, err := client.QueryIP(ctx, domain, option, s.disableCache)
  204. if len(ips) > 0 {
  205. return ips, nil
  206. }
  207. if err != nil {
  208. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  209. errs = append(errs, err)
  210. }
  211. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  212. return nil, err
  213. }
  214. }
  215. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  216. }
  217. // GetIPOption implements ClientWithIPOption.
  218. func (s *DNS) GetIPOption() *dns.IPOption {
  219. return s.ipOption
  220. }
  221. // SetQueryOption implements ClientWithIPOption.
  222. func (s *DNS) SetQueryOption(isIPv4Enable, isIPv6Enable bool) {
  223. s.ipOption.IPv4Enable = isIPv4Enable
  224. s.ipOption.IPv6Enable = isIPv6Enable
  225. }
  226. // SetFakeDNSOption implements ClientWithIPOption.
  227. func (s *DNS) SetFakeDNSOption(isFakeEnable bool) {
  228. s.ipOption.FakeEnable = isFakeEnable
  229. }
  230. func (s *DNS) sortClients(domain string) []*Client {
  231. clients := make([]*Client, 0, len(s.clients))
  232. clientUsed := make([]bool, len(s.clients))
  233. clientNames := make([]string, 0, len(s.clients))
  234. domainRules := []string{}
  235. // Priority domain matching
  236. hasMatch := false
  237. for _, match := range s.domainMatcher.Match(domain) {
  238. info := s.matcherInfos[match]
  239. client := s.clients[info.clientIdx]
  240. domainRule := client.domains[info.domainRuleIdx]
  241. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  242. if clientUsed[info.clientIdx] {
  243. continue
  244. }
  245. clientUsed[info.clientIdx] = true
  246. clients = append(clients, client)
  247. clientNames = append(clientNames, client.Name())
  248. hasMatch = true
  249. }
  250. if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
  251. // Default round-robin query
  252. for idx, client := range s.clients {
  253. if clientUsed[idx] || client.skipFallback {
  254. continue
  255. }
  256. clientUsed[idx] = true
  257. clients = append(clients, client)
  258. clientNames = append(clientNames, client.Name())
  259. }
  260. }
  261. if len(domainRules) > 0 {
  262. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  263. }
  264. if len(clientNames) > 0 {
  265. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  266. }
  267. if len(clients) == 0 {
  268. clients = append(clients, s.clients[0])
  269. clientNames = append(clientNames, s.clients[0].Name())
  270. newError("domain ", domain, " will use the first DNS: ", clientNames).AtDebug().WriteToLog()
  271. }
  272. return clients
  273. }
  274. func init() {
  275. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  276. return New(ctx, config.(*Config))
  277. }))
  278. common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  279. ctx = cfgcommon.NewConfigureLoadingContext(context.Background())
  280. geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string {
  281. return "standard"
  282. })
  283. if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil {
  284. cfgcommon.SetGeoDataLoader(ctx, loader)
  285. } else {
  286. return nil, newError("unable to create geo data loader ").Base(err)
  287. }
  288. cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx)
  289. geoLoader := cfgEnv.GetGeoLoader()
  290. simplifiedConfig := config.(*SimplifiedConfig)
  291. for _, v := range simplifiedConfig.NameServer {
  292. for _, geo := range v.Geoip {
  293. if geo.Code != "" {
  294. filepath := "geoip.dat"
  295. if geo.FilePath != "" {
  296. filepath = geo.FilePath
  297. } else {
  298. geo.CountryCode = geo.Code
  299. }
  300. var err error
  301. geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code)
  302. if err != nil {
  303. return nil, newError("unable to load geoip").Base(err)
  304. }
  305. }
  306. }
  307. }
  308. var nameservers []*NameServer
  309. for _, v := range simplifiedConfig.NameServer {
  310. nameserver := &NameServer{
  311. Address: v.Address,
  312. ClientIp: net.ParseIP(v.ClientIp),
  313. SkipFallback: v.SkipFallback,
  314. Geoip: v.Geoip,
  315. }
  316. for _, prioritizedDomain := range v.PrioritizedDomain {
  317. nameserver.PrioritizedDomain = append(nameserver.PrioritizedDomain, &NameServer_PriorityDomain{
  318. Type: prioritizedDomain.Type,
  319. Domain: prioritizedDomain.Domain,
  320. })
  321. }
  322. nameservers = append(nameservers, nameserver)
  323. }
  324. fullConfig := &Config{
  325. NameServer: nameservers,
  326. ClientIp: net.ParseIP(simplifiedConfig.ClientIp),
  327. StaticHosts: simplifiedConfig.StaticHosts,
  328. Tag: simplifiedConfig.Tag,
  329. DisableCache: simplifiedConfig.DisableCache,
  330. QueryStrategy: simplifiedConfig.QueryStrategy,
  331. DisableFallback: simplifiedConfig.DisableFallback,
  332. }
  333. return common.CreateObject(ctx, fullConfig)
  334. }))
  335. }