dns.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. ipOption *dns.IPOption
  30. hosts *StaticHosts
  31. clients []*Client
  32. ctx context.Context
  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. var tag string
  44. if len(config.Tag) > 0 {
  45. tag = config.Tag
  46. } else {
  47. tag = generateRandomTag()
  48. }
  49. var clientIP net.IP
  50. switch len(config.ClientIp) {
  51. case 0, net.IPv4len, net.IPv6len:
  52. clientIP = net.IP(config.ClientIp)
  53. default:
  54. return nil, newError("unexpected client IP length ", len(config.ClientIp))
  55. }
  56. var ipOption *dns.IPOption
  57. switch config.QueryStrategy {
  58. case QueryStrategy_USE_IP:
  59. ipOption = &dns.IPOption{
  60. IPv4Enable: true,
  61. IPv6Enable: true,
  62. FakeEnable: false,
  63. }
  64. case QueryStrategy_USE_IP4:
  65. ipOption = &dns.IPOption{
  66. IPv4Enable: true,
  67. IPv6Enable: false,
  68. FakeEnable: false,
  69. }
  70. case QueryStrategy_USE_IP6:
  71. ipOption = &dns.IPOption{
  72. IPv4Enable: false,
  73. IPv6Enable: true,
  74. FakeEnable: false,
  75. }
  76. }
  77. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  78. if err != nil {
  79. return nil, newError("failed to create hosts").Base(err)
  80. }
  81. clients := []*Client{}
  82. domainRuleCount := 0
  83. for _, ns := range config.NameServer {
  84. domainRuleCount += len(ns.PrioritizedDomain)
  85. }
  86. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  87. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
  88. domainMatcher := &strmatcher.MatcherGroup{}
  89. geoipContainer := router.GeoIPMatcherContainer{}
  90. for _, endpoint := range config.NameServers {
  91. features.PrintDeprecatedFeatureWarning("simple DNS server")
  92. client, err := NewSimpleClient(ctx, endpoint, clientIP)
  93. if err != nil {
  94. return nil, newError("failed to create client").Base(err)
  95. }
  96. clients = append(clients, client)
  97. }
  98. for _, ns := range config.NameServer {
  99. clientIdx := len(clients)
  100. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []DomainMatcherInfo) error {
  101. midx := domainMatcher.Add(domainRule)
  102. matcherInfos[midx] = DomainMatcherInfo{
  103. clientIdx: uint16(clientIdx),
  104. domainRuleIdx: uint16(originalRuleIdx),
  105. }
  106. return nil
  107. }
  108. myClientIP := clientIP
  109. switch len(ns.ClientIp) {
  110. case net.IPv4len, net.IPv6len:
  111. myClientIP = net.IP(ns.ClientIp)
  112. }
  113. client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain)
  114. if err != nil {
  115. return nil, newError("failed to create client").Base(err)
  116. }
  117. clients = append(clients, client)
  118. }
  119. // If there is no DNS client in config, add a `localhost` DNS client
  120. if len(clients) == 0 {
  121. clients = append(clients, NewLocalDNSClient())
  122. }
  123. return &DNS{
  124. tag: tag,
  125. hosts: hosts,
  126. ipOption: ipOption,
  127. clients: clients,
  128. ctx: ctx,
  129. domainMatcher: domainMatcher,
  130. matcherInfos: matcherInfos,
  131. disableCache: config.DisableCache,
  132. disableFallback: config.DisableFallback,
  133. }, nil
  134. }
  135. // Type implements common.HasType.
  136. func (*DNS) Type() interface{} {
  137. return dns.ClientType()
  138. }
  139. // Start implements common.Runnable.
  140. func (s *DNS) Start() error {
  141. return nil
  142. }
  143. // Close implements common.Closable.
  144. func (s *DNS) Close() error {
  145. return nil
  146. }
  147. // IsOwnLink implements proxy.dns.ownLinkVerifier
  148. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  149. inbound := session.InboundFromContext(ctx)
  150. return inbound != nil && inbound.Tag == s.tag
  151. }
  152. // LookupIP implements dns.Client.
  153. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  154. return s.lookupIPInternal(domain, dns.IPOption{
  155. IPv4Enable: true,
  156. IPv6Enable: true,
  157. FakeEnable: s.ipOption.FakeEnable,
  158. })
  159. }
  160. // LookupIPv4 implements dns.IPv4Lookup.
  161. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  162. return s.lookupIPInternal(domain, dns.IPOption{
  163. IPv4Enable: true,
  164. IPv6Enable: false,
  165. FakeEnable: s.ipOption.FakeEnable,
  166. })
  167. }
  168. // LookupIPv6 implements dns.IPv6Lookup.
  169. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  170. return s.lookupIPInternal(domain, dns.IPOption{
  171. IPv4Enable: false,
  172. IPv6Enable: true,
  173. FakeEnable: s.ipOption.FakeEnable,
  174. })
  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. for _, match := range s.domainMatcher.Match(domain) {
  237. info := s.matcherInfos[match]
  238. client := s.clients[info.clientIdx]
  239. domainRule := client.domains[info.domainRuleIdx]
  240. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  241. if clientUsed[info.clientIdx] {
  242. continue
  243. }
  244. clientUsed[info.clientIdx] = true
  245. clients = append(clients, client)
  246. clientNames = append(clientNames, client.Name())
  247. }
  248. if !s.disableFallback {
  249. // Default round-robin query
  250. for idx, client := range s.clients {
  251. if clientUsed[idx] || client.skipFallback {
  252. continue
  253. }
  254. clientUsed[idx] = true
  255. clients = append(clients, client)
  256. clientNames = append(clientNames, client.Name())
  257. }
  258. }
  259. if len(domainRules) > 0 {
  260. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  261. }
  262. if len(clientNames) > 0 {
  263. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  264. }
  265. if len(clients) == 0 {
  266. clients = append(clients, s.clients[0])
  267. clientNames = append(clientNames, s.clients[0].Name())
  268. newError("domain ", domain, " will use the first DNS: ", clientNames).AtDebug().WriteToLog()
  269. }
  270. return clients
  271. }
  272. func init() {
  273. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  274. return New(ctx, config.(*Config))
  275. }))
  276. common.Must(common.RegisterConfig((*SimplifiedConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  277. ctx = cfgcommon.NewConfigureLoadingContext(context.Background())
  278. geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string {
  279. return "standard"
  280. })
  281. if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil {
  282. cfgcommon.SetGeoDataLoader(ctx, loader)
  283. } else {
  284. return nil, newError("unable to create geo data loader ").Base(err)
  285. }
  286. cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(ctx)
  287. geoLoader := cfgEnv.GetGeoLoader()
  288. simplifiedConfig := config.(*SimplifiedConfig)
  289. for _, v := range simplifiedConfig.NameServer {
  290. for _, geo := range v.Geoip {
  291. if geo.Code != "" {
  292. filepath := "geoip.dat"
  293. if geo.FilePath != "" {
  294. filepath = geo.FilePath
  295. } else {
  296. geo.CountryCode = geo.Code
  297. }
  298. var err error
  299. geo.Cidr, err = geoLoader.LoadIP(filepath, geo.Code)
  300. if err != nil {
  301. return nil, newError("unable to load geoip").Base(err)
  302. }
  303. }
  304. }
  305. }
  306. fullConfig := &Config{
  307. NameServer: simplifiedConfig.NameServer,
  308. ClientIp: simplifiedConfig.ClientIp,
  309. StaticHosts: simplifiedConfig.StaticHosts,
  310. Tag: simplifiedConfig.Tag,
  311. DisableCache: simplifiedConfig.DisableCache,
  312. QueryStrategy: simplifiedConfig.QueryStrategy,
  313. DisableFallback: simplifiedConfig.DisableFallback,
  314. }
  315. return common.CreateObject(ctx, fullConfig)
  316. }))
  317. }