nameserver.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // +build !confonly
  2. package dns
  3. import (
  4. "context"
  5. "net/url"
  6. "time"
  7. "v2ray.com/core"
  8. "v2ray.com/core/app/router"
  9. "v2ray.com/core/common/errors"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/strmatcher"
  12. "v2ray.com/core/features/routing"
  13. )
  14. // IPOption is an object for IP query options.
  15. type IPOption struct {
  16. IPv4Enable bool
  17. IPv6Enable bool
  18. }
  19. // Server is the interface for Name Server.
  20. type Server interface {
  21. // Name of the Client.
  22. Name() string
  23. // QueryIP sends IP queries to its configured server.
  24. QueryIP(ctx context.Context, domain string, clientIP net.IP, option IPOption) ([]net.IP, error)
  25. }
  26. // Client is the interface for DNS client.
  27. type Client struct {
  28. server Server
  29. clientIP net.IP
  30. domains []string
  31. expectIPs []*router.GeoIPMatcher
  32. }
  33. var errExpectedIPNonMatch = errors.New("expectIPs not match")
  34. // NewServer creates a name server object according to the network destination url.
  35. func NewServer(dest net.Destination, dispatcher routing.Dispatcher) (Server, error) {
  36. if address := dest.Address; address.Family().IsDomain() {
  37. u, err := url.Parse(address.Domain())
  38. if err != nil {
  39. return nil, err
  40. }
  41. switch {
  42. case u.String() == "localhost":
  43. return NewLocalNameServer(), nil
  44. case u.Scheme == "https": // DOH Remote mode
  45. return NewDoHNameServer(u, dispatcher)
  46. case u.Scheme == "https+local": // DOH Local mode
  47. return NewDoHLocalNameServer(u), nil
  48. case u.Scheme == "quic+local": // DNS-over-QUIC Local mode
  49. return NewQUICNameServer(u)
  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, updateDomainRule func(strmatcher.Matcher, int) 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. }
  74. // Establish domain rules
  75. var rules []string
  76. ruleCurr := 0
  77. ruleIter := 0
  78. for _, domain := range ns.PrioritizedDomain {
  79. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  80. if err != nil {
  81. return newError("failed to create prioritized domain").Base(err).AtWarning()
  82. }
  83. originalRuleIdx := ruleCurr
  84. if ruleCurr < len(ns.OriginalRules) {
  85. rule := ns.OriginalRules[ruleCurr]
  86. if ruleCurr >= len(rules) {
  87. rules = append(rules, rule.Rule)
  88. }
  89. ruleIter++
  90. if ruleIter >= int(rule.Size) {
  91. ruleIter = 0
  92. ruleCurr++
  93. }
  94. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  95. rules = append(rules, domainRule.String())
  96. ruleCurr++
  97. }
  98. err = updateDomainRule(domainRule, originalRuleIdx)
  99. if err != nil {
  100. return newError("failed to create prioritized domain").Base(err).AtWarning()
  101. }
  102. }
  103. // Establish expected IPs
  104. var matchers []*router.GeoIPMatcher
  105. for _, geoip := range ns.Geoip {
  106. matcher, err := container.Add(geoip)
  107. if err != nil {
  108. return newError("failed to create ip matcher").Base(err).AtWarning()
  109. }
  110. matchers = append(matchers, matcher)
  111. }
  112. if len(clientIP) > 0 {
  113. switch ns.Address.Address.GetAddress().(type) {
  114. case *net.IPOrDomain_Domain:
  115. newError("DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  116. case *net.IPOrDomain_Ip:
  117. newError("DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  118. }
  119. }
  120. client.server = server
  121. client.clientIP = clientIP
  122. client.domains = rules
  123. client.expectIPs = matchers
  124. return nil
  125. })
  126. return client, err
  127. }
  128. // NewSimpleClient creates a DNS client with a simple destination.
  129. func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.IP) (*Client, error) {
  130. client := &Client{}
  131. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  132. server, err := NewServer(endpoint.AsDestination(), dispatcher)
  133. if err != nil {
  134. return newError("failed to create nameserver").Base(err).AtWarning()
  135. }
  136. client.server = server
  137. client.clientIP = clientIP
  138. return nil
  139. })
  140. if len(clientIP) > 0 {
  141. switch endpoint.Address.GetAddress().(type) {
  142. case *net.IPOrDomain_Domain:
  143. newError("DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  144. case *net.IPOrDomain_Ip:
  145. newError("DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  146. }
  147. }
  148. return client, err
  149. }
  150. // Name returns the server name the client manages.
  151. func (c *Client) Name() string {
  152. return c.server.Name()
  153. }
  154. // QueryIP send DNS query to the name server with the client's IP.
  155. func (c *Client) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  156. ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
  157. ips, err := c.server.QueryIP(ctx, domain, c.clientIP, option)
  158. cancel()
  159. if err != nil {
  160. return ips, err
  161. }
  162. return c.MatchExpectedIPs(domain, ips)
  163. }
  164. // MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
  165. func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
  166. if len(c.expectIPs) == 0 {
  167. return ips, nil
  168. }
  169. newIps := []net.IP{}
  170. for _, ip := range ips {
  171. for _, matcher := range c.expectIPs {
  172. if matcher.Match(ip) {
  173. newIps = append(newIps, ip)
  174. break
  175. }
  176. }
  177. }
  178. if len(newIps) == 0 {
  179. return nil, errExpectedIPNonMatch
  180. }
  181. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog()
  182. return newIps, nil
  183. }