dns.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // +build !confonly
  2. // Package dns is an implementation of core.DNS feature.
  3. package dns
  4. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  5. import (
  6. "context"
  7. "fmt"
  8. "strings"
  9. "sync"
  10. "github.com/v2fly/v2ray-core/v4/app/router"
  11. "github.com/v2fly/v2ray-core/v4/common"
  12. "github.com/v2fly/v2ray-core/v4/common/errors"
  13. "github.com/v2fly/v2ray-core/v4/common/net"
  14. "github.com/v2fly/v2ray-core/v4/common/session"
  15. "github.com/v2fly/v2ray-core/v4/common/strmatcher"
  16. "github.com/v2fly/v2ray-core/v4/features"
  17. "github.com/v2fly/v2ray-core/v4/features/dns"
  18. )
  19. // DNS is a DNS rely server.
  20. type DNS struct {
  21. sync.Mutex
  22. tag string
  23. disableCache bool
  24. disableFallback bool
  25. ipOption *dns.IPOption
  26. hosts *StaticHosts
  27. clients []*Client
  28. ctx context.Context
  29. domainMatcher strmatcher.IndexMatcher
  30. matcherInfos []DomainMatcherInfo
  31. }
  32. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  33. type DomainMatcherInfo struct {
  34. clientIdx uint16
  35. domainRuleIdx uint16
  36. }
  37. // New creates a new DNS server with given configuration.
  38. func New(ctx context.Context, config *Config) (*DNS, error) {
  39. var tag string
  40. if len(config.Tag) > 0 {
  41. tag = config.Tag
  42. } else {
  43. tag = generateRandomTag()
  44. }
  45. var clientIP net.IP
  46. switch len(config.ClientIp) {
  47. case 0, net.IPv4len, net.IPv6len:
  48. clientIP = net.IP(config.ClientIp)
  49. default:
  50. return nil, newError("unexpected client IP length ", len(config.ClientIp))
  51. }
  52. var ipOption *dns.IPOption
  53. switch config.QueryStrategy {
  54. case QueryStrategy_USE_IP:
  55. ipOption = &dns.IPOption{
  56. IPv4Enable: true,
  57. IPv6Enable: true,
  58. FakeEnable: false,
  59. }
  60. case QueryStrategy_USE_IP4:
  61. ipOption = &dns.IPOption{
  62. IPv4Enable: true,
  63. IPv6Enable: false,
  64. FakeEnable: false,
  65. }
  66. case QueryStrategy_USE_IP6:
  67. ipOption = &dns.IPOption{
  68. IPv4Enable: false,
  69. IPv6Enable: true,
  70. FakeEnable: false,
  71. }
  72. }
  73. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  74. if err != nil {
  75. return nil, newError("failed to create hosts").Base(err)
  76. }
  77. clients := []*Client{}
  78. domainRuleCount := 0
  79. for _, ns := range config.NameServer {
  80. domainRuleCount += len(ns.PrioritizedDomain)
  81. }
  82. // MatcherInfos is ensured to cover the maximum index domainMatcher could return, where matcher's index starts from 1
  83. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1)
  84. domainMatcher := &strmatcher.MatcherGroup{}
  85. geoipContainer := router.GeoIPMatcherContainer{}
  86. for _, endpoint := range config.NameServers {
  87. features.PrintDeprecatedFeatureWarning("simple DNS server")
  88. client, err := NewSimpleClient(ctx, endpoint, clientIP)
  89. if err != nil {
  90. return nil, newError("failed to create client").Base(err)
  91. }
  92. clients = append(clients, client)
  93. }
  94. for _, ns := range config.NameServer {
  95. clientIdx := len(clients)
  96. updateDomain := func(domainRule strmatcher.Matcher, originalRuleIdx int, matcherInfos []DomainMatcherInfo) error {
  97. midx := domainMatcher.Add(domainRule)
  98. matcherInfos[midx] = DomainMatcherInfo{
  99. clientIdx: uint16(clientIdx),
  100. domainRuleIdx: uint16(originalRuleIdx),
  101. }
  102. return nil
  103. }
  104. myClientIP := clientIP
  105. switch len(ns.ClientIp) {
  106. case net.IPv4len, net.IPv6len:
  107. myClientIP = net.IP(ns.ClientIp)
  108. }
  109. client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain)
  110. if err != nil {
  111. return nil, newError("failed to create client").Base(err)
  112. }
  113. clients = append(clients, client)
  114. }
  115. // If there is no DNS client in config, add a `localhost` DNS client
  116. if len(clients) == 0 {
  117. clients = append(clients, NewLocalDNSClient())
  118. }
  119. return &DNS{
  120. tag: tag,
  121. hosts: hosts,
  122. ipOption: ipOption,
  123. clients: clients,
  124. ctx: ctx,
  125. domainMatcher: domainMatcher,
  126. matcherInfos: matcherInfos,
  127. disableCache: config.DisableCache,
  128. disableFallback: config.DisableFallback,
  129. }, nil
  130. }
  131. // Type implements common.HasType.
  132. func (*DNS) Type() interface{} {
  133. return dns.ClientType()
  134. }
  135. // Start implements common.Runnable.
  136. func (s *DNS) Start() error {
  137. return nil
  138. }
  139. // Close implements common.Closable.
  140. func (s *DNS) Close() error {
  141. return nil
  142. }
  143. // IsOwnLink implements proxy.dns.ownLinkVerifier
  144. func (s *DNS) IsOwnLink(ctx context.Context) bool {
  145. inbound := session.InboundFromContext(ctx)
  146. return inbound != nil && inbound.Tag == s.tag
  147. }
  148. // LookupIP implements dns.Client.
  149. func (s *DNS) LookupIP(domain string) ([]net.IP, error) {
  150. return s.lookupIPInternal(domain, dns.IPOption{
  151. IPv4Enable: true,
  152. IPv6Enable: true,
  153. FakeEnable: s.ipOption.FakeEnable,
  154. })
  155. }
  156. // LookupIPv4 implements dns.IPv4Lookup.
  157. func (s *DNS) LookupIPv4(domain string) ([]net.IP, error) {
  158. return s.lookupIPInternal(domain, dns.IPOption{
  159. IPv4Enable: true,
  160. IPv6Enable: false,
  161. FakeEnable: s.ipOption.FakeEnable,
  162. })
  163. }
  164. // LookupIPv6 implements dns.IPv6Lookup.
  165. func (s *DNS) LookupIPv6(domain string) ([]net.IP, error) {
  166. return s.lookupIPInternal(domain, dns.IPOption{
  167. IPv4Enable: false,
  168. IPv6Enable: true,
  169. FakeEnable: s.ipOption.FakeEnable,
  170. })
  171. }
  172. func (s *DNS) lookupIPInternal(domain string, option dns.IPOption) ([]net.IP, error) {
  173. if domain == "" {
  174. return nil, newError("empty domain name")
  175. }
  176. // Normalize the FQDN form query
  177. if strings.HasSuffix(domain, ".") {
  178. domain = domain[:len(domain)-1]
  179. }
  180. // Static host lookup
  181. switch addrs := s.hosts.Lookup(domain, option); {
  182. case addrs == nil: // Domain not recorded in static host
  183. break
  184. case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
  185. return nil, dns.ErrEmptyResponse
  186. case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
  187. newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog()
  188. domain = addrs[0].Domain()
  189. default: // Successfully found ip records in static host
  190. newError("returning ", len(addrs), " IPs for domain ", domain).WriteToLog()
  191. return toNetIP(addrs)
  192. }
  193. // Name servers lookup
  194. errs := []error{}
  195. ctx := session.ContextWithInbound(s.ctx, &session.Inbound{Tag: s.tag})
  196. for _, client := range s.sortClients(domain) {
  197. if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") {
  198. newError("skip DNS resolution for domain ", domain, " at server ", client.Name()).AtDebug().WriteToLog()
  199. continue
  200. }
  201. ips, err := client.QueryIP(ctx, domain, option, s.disableCache)
  202. if len(ips) > 0 {
  203. return ips, nil
  204. }
  205. if err != nil {
  206. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  207. errs = append(errs, err)
  208. }
  209. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  210. return nil, err
  211. }
  212. }
  213. return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...))
  214. }
  215. // GetIPOption implements ClientWithIPOption.
  216. func (s *DNS) GetIPOption() *dns.IPOption {
  217. return s.ipOption
  218. }
  219. // SetQueryOption implements ClientWithIPOption.
  220. func (s *DNS) SetQueryOption(isIPv4Enable, isIPv6Enable bool) {
  221. s.ipOption.IPv4Enable = isIPv4Enable
  222. s.ipOption.IPv6Enable = isIPv6Enable
  223. }
  224. // SetFakeDNSOption implements ClientWithIPOption.
  225. func (s *DNS) SetFakeDNSOption(isFakeEnable bool) {
  226. s.ipOption.FakeEnable = isFakeEnable
  227. }
  228. func (s *DNS) sortClients(domain string) []*Client {
  229. clients := make([]*Client, 0, len(s.clients))
  230. clientUsed := make([]bool, len(s.clients))
  231. clientNames := make([]string, 0, len(s.clients))
  232. domainRules := []string{}
  233. // Priority domain matching
  234. for _, match := range s.domainMatcher.Match(domain) {
  235. info := s.matcherInfos[match]
  236. client := s.clients[info.clientIdx]
  237. domainRule := client.domains[info.domainRuleIdx]
  238. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", domainRule, info.clientIdx))
  239. if clientUsed[info.clientIdx] {
  240. continue
  241. }
  242. clientUsed[info.clientIdx] = true
  243. clients = append(clients, client)
  244. clientNames = append(clientNames, client.Name())
  245. }
  246. if !s.disableFallback {
  247. // Default round-robin query
  248. for idx, client := range s.clients {
  249. if clientUsed[idx] || client.skipFallback {
  250. continue
  251. }
  252. clientUsed[idx] = true
  253. clients = append(clients, client)
  254. clientNames = append(clientNames, client.Name())
  255. }
  256. }
  257. if len(domainRules) > 0 {
  258. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  259. }
  260. if len(clientNames) > 0 {
  261. newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog()
  262. }
  263. if len(clients) == 0 {
  264. clients = append(clients, s.clients[0])
  265. clientNames = append(clientNames, s.clients[0].Name())
  266. newError("domain ", domain, " will use the first DNS: ", clientNames).AtDebug().WriteToLog()
  267. }
  268. return clients
  269. }
  270. func init() {
  271. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  272. return New(ctx, config.(*Config))
  273. }))
  274. }