nameserver.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // +build !confonly
  2. package dns
  3. import (
  4. "context"
  5. "net/url"
  6. "strings"
  7. "time"
  8. core "github.com/v2fly/v2ray-core/v4"
  9. "github.com/v2fly/v2ray-core/v4/app/router"
  10. "github.com/v2fly/v2ray-core/v4/common/errors"
  11. "github.com/v2fly/v2ray-core/v4/common/net"
  12. "github.com/v2fly/v2ray-core/v4/common/strmatcher"
  13. "github.com/v2fly/v2ray-core/v4/features/dns"
  14. "github.com/v2fly/v2ray-core/v4/features/routing"
  15. )
  16. // Server is the interface for Name Server.
  17. type Server interface {
  18. // Name of the Client.
  19. Name() string
  20. // QueryIP sends IP queries to its configured server.
  21. QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns.IPOption, disableCache bool) ([]net.IP, error)
  22. }
  23. // Client is the interface for DNS client.
  24. type Client struct {
  25. server Server
  26. clientIP net.IP
  27. skipFallback bool
  28. domains []string
  29. expectIPs []*router.GeoIPMatcher
  30. }
  31. var errExpectedIPNonMatch = errors.New("expectIPs not match")
  32. // NewServer creates a name server object according to the network destination url.
  33. func NewServer(dest net.Destination, dispatcher routing.Dispatcher) (Server, error) {
  34. if address := dest.Address; address.Family().IsDomain() {
  35. u, err := url.Parse(address.Domain())
  36. if err != nil {
  37. return nil, err
  38. }
  39. switch {
  40. case strings.EqualFold(u.String(), "localhost"):
  41. return NewLocalNameServer(), nil
  42. case strings.EqualFold(u.Scheme, "https"): // DOH Remote mode
  43. return NewDoHNameServer(u, dispatcher)
  44. case strings.EqualFold(u.Scheme, "https+local"): // DOH Local mode
  45. return NewDoHLocalNameServer(u), nil
  46. case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode
  47. return NewQUICNameServer(u)
  48. case strings.EqualFold(u.String(), "fakedns"):
  49. return NewFakeDNSServer(), nil
  50. }
  51. }
  52. if dest.Network == net.Network_Unknown {
  53. dest.Network = net.Network_UDP
  54. }
  55. if dest.Network == net.Network_UDP { // UDP classic DNS mode
  56. return NewClassicNameServer(dest, dispatcher), nil
  57. }
  58. return nil, newError("No available name server could be created from ", dest).AtWarning()
  59. }
  60. // NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
  61. func NewClient(ctx context.Context, ns *NameServer, clientIP net.IP, container router.GeoIPMatcherContainer, matcherInfos *[]DomainMatcherInfo, updateDomainRule func(strmatcher.Matcher, int, []DomainMatcherInfo) error) (*Client, error) {
  62. client := &Client{}
  63. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  64. // Create a new server for each client for now
  65. server, err := NewServer(ns.Address.AsDestination(), dispatcher)
  66. if err != nil {
  67. return newError("failed to create nameserver").Base(err).AtWarning()
  68. }
  69. // Priotize local domains with specific TLDs or without any dot to local DNS
  70. if _, isLocalDNS := server.(*LocalNameServer); isLocalDNS {
  71. ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
  72. ns.OriginalRules = append(ns.OriginalRules, localTLDsAndDotlessDomainsRule)
  73. // The following lines is a solution to avoid core panics(rule index out of range) when setting `localhost` DNS client in config.
  74. // Because the `localhost` DNS client will apend len(localTLDsAndDotlessDomains) rules into matcherInfos to match `geosite:private` default rule.
  75. // But `matcherInfos` has no enough length to add rules, which leads to core panics (rule index out of range).
  76. // To avoid this, the length of `matcherInfos` must be equal to the expected, so manually append it with Golang default zero value first for later modification.
  77. // Related issues:
  78. // https://github.com/v2fly/v2ray-core/issues/529
  79. // https://github.com/v2fly/v2ray-core/issues/719
  80. for i := 0; i < len(localTLDsAndDotlessDomains); i++ {
  81. *matcherInfos = append(*matcherInfos, DomainMatcherInfo{
  82. clientIdx: uint16(0),
  83. domainRuleIdx: uint16(0),
  84. })
  85. }
  86. }
  87. // Establish domain rules
  88. var rules []string
  89. ruleCurr := 0
  90. ruleIter := 0
  91. for _, domain := range ns.PrioritizedDomain {
  92. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  93. if err != nil {
  94. return newError("failed to create prioritized domain").Base(err).AtWarning()
  95. }
  96. originalRuleIdx := ruleCurr
  97. if ruleCurr < len(ns.OriginalRules) {
  98. rule := ns.OriginalRules[ruleCurr]
  99. if ruleCurr >= len(rules) {
  100. rules = append(rules, rule.Rule)
  101. }
  102. ruleIter++
  103. if ruleIter >= int(rule.Size) {
  104. ruleIter = 0
  105. ruleCurr++
  106. }
  107. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  108. rules = append(rules, domainRule.String())
  109. ruleCurr++
  110. }
  111. err = updateDomainRule(domainRule, originalRuleIdx, *matcherInfos)
  112. if err != nil {
  113. return newError("failed to create prioritized domain").Base(err).AtWarning()
  114. }
  115. }
  116. // Establish expected IPs
  117. var matchers []*router.GeoIPMatcher
  118. for _, geoip := range ns.Geoip {
  119. matcher, err := container.Add(geoip)
  120. if err != nil {
  121. return newError("failed to create ip matcher").Base(err).AtWarning()
  122. }
  123. matchers = append(matchers, matcher)
  124. }
  125. if len(clientIP) > 0 {
  126. switch ns.Address.Address.GetAddress().(type) {
  127. case *net.IPOrDomain_Domain:
  128. newError("DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  129. case *net.IPOrDomain_Ip:
  130. newError("DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  131. }
  132. }
  133. client.server = server
  134. client.clientIP = clientIP
  135. client.skipFallback = ns.SkipFallback
  136. client.domains = rules
  137. client.expectIPs = matchers
  138. return nil
  139. })
  140. return client, err
  141. }
  142. // NewSimpleClient creates a DNS client with a simple destination.
  143. func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.IP) (*Client, error) {
  144. client := &Client{}
  145. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  146. server, err := NewServer(endpoint.AsDestination(), dispatcher)
  147. if err != nil {
  148. return newError("failed to create nameserver").Base(err).AtWarning()
  149. }
  150. client.server = server
  151. client.clientIP = clientIP
  152. return nil
  153. })
  154. if len(clientIP) > 0 {
  155. switch endpoint.Address.GetAddress().(type) {
  156. case *net.IPOrDomain_Domain:
  157. newError("DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  158. case *net.IPOrDomain_Ip:
  159. newError("DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  160. }
  161. }
  162. return client, err
  163. }
  164. // Name returns the server name the client manages.
  165. func (c *Client) Name() string {
  166. return c.server.Name()
  167. }
  168. // QueryIP send DNS query to the name server with the client's IP.
  169. func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption, disableCache bool) ([]net.IP, error) {
  170. ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
  171. ips, err := c.server.QueryIP(ctx, domain, c.clientIP, option, disableCache)
  172. cancel()
  173. if err != nil {
  174. return ips, err
  175. }
  176. return c.MatchExpectedIPs(domain, ips)
  177. }
  178. // MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
  179. func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
  180. if len(c.expectIPs) == 0 {
  181. return ips, nil
  182. }
  183. newIps := []net.IP{}
  184. for _, ip := range ips {
  185. for _, matcher := range c.expectIPs {
  186. if matcher.Match(ip) {
  187. newIps = append(newIps, ip)
  188. break
  189. }
  190. }
  191. }
  192. if len(newIps) == 0 {
  193. return nil, errExpectedIPNonMatch
  194. }
  195. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog()
  196. return newIps, nil
  197. }