nameserver.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. }
  49. }
  50. if dest.Network == net.Network_Unknown {
  51. dest.Network = net.Network_UDP
  52. }
  53. if dest.Network == net.Network_UDP { // UDP classic DNS mode
  54. return NewClassicNameServer(dest, dispatcher), nil
  55. }
  56. return nil, newError("No available name server could be created from ", dest).AtWarning()
  57. }
  58. // NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
  59. func NewClient(ctx context.Context, ns *NameServer, clientIP net.IP, container router.GeoIPMatcherContainer, updateDomainRule func(strmatcher.Matcher, int) error) (*Client, error) {
  60. client := &Client{}
  61. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  62. // Create a new server for each client for now
  63. server, err := NewServer(ns.Address.AsDestination(), dispatcher)
  64. if err != nil {
  65. return newError("failed to create nameserver").Base(err).AtWarning()
  66. }
  67. // Priotize local domains with specific TLDs or without any dot to local DNS
  68. if _, isLocalDNS := server.(*LocalNameServer); isLocalDNS {
  69. ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
  70. ns.OriginalRules = append(ns.OriginalRules, localTLDsAndDotlessDomainsRule)
  71. }
  72. // Establish domain rules
  73. var rules []string
  74. ruleCurr := 0
  75. ruleIter := 0
  76. for _, domain := range ns.PrioritizedDomain {
  77. domainRule, err := toStrMatcher(domain.Type, domain.Domain)
  78. if err != nil {
  79. return newError("failed to create prioritized domain").Base(err).AtWarning()
  80. }
  81. originalRuleIdx := ruleCurr
  82. if ruleCurr < len(ns.OriginalRules) {
  83. rule := ns.OriginalRules[ruleCurr]
  84. if ruleCurr >= len(rules) {
  85. rules = append(rules, rule.Rule)
  86. }
  87. ruleIter++
  88. if ruleIter >= int(rule.Size) {
  89. ruleIter = 0
  90. ruleCurr++
  91. }
  92. } else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
  93. rules = append(rules, domainRule.String())
  94. ruleCurr++
  95. }
  96. err = updateDomainRule(domainRule, originalRuleIdx)
  97. if err != nil {
  98. return newError("failed to create prioritized domain").Base(err).AtWarning()
  99. }
  100. }
  101. // Establish expected IPs
  102. var matchers []*router.GeoIPMatcher
  103. for _, geoip := range ns.Geoip {
  104. matcher, err := container.Add(geoip)
  105. if err != nil {
  106. return newError("failed to create ip matcher").Base(err).AtWarning()
  107. }
  108. matchers = append(matchers, matcher)
  109. }
  110. if len(clientIP) > 0 {
  111. switch ns.Address.Address.GetAddress().(type) {
  112. case *net.IPOrDomain_Domain:
  113. newError("DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  114. case *net.IPOrDomain_Ip:
  115. newError("DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  116. }
  117. }
  118. client.server = server
  119. client.clientIP = clientIP
  120. client.domains = rules
  121. client.expectIPs = matchers
  122. return nil
  123. })
  124. return client, err
  125. }
  126. // NewSimpleClient creates a DNS client with a simple destination.
  127. func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.IP) (*Client, error) {
  128. client := &Client{}
  129. err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
  130. server, err := NewServer(endpoint.AsDestination(), dispatcher)
  131. if err != nil {
  132. return newError("failed to create nameserver").Base(err).AtWarning()
  133. }
  134. client.server = server
  135. client.clientIP = clientIP
  136. return nil
  137. })
  138. if len(clientIP) > 0 {
  139. switch endpoint.Address.GetAddress().(type) {
  140. case *net.IPOrDomain_Domain:
  141. newError("DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  142. case *net.IPOrDomain_Ip:
  143. newError("DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
  144. }
  145. }
  146. return client, err
  147. }
  148. // Name returns the server name the client manages.
  149. func (c *Client) Name() string {
  150. return c.server.Name()
  151. }
  152. // QueryIP send DNS query to the name server with the client's IP.
  153. func (c *Client) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  154. ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
  155. ips, err := c.server.QueryIP(ctx, domain, c.clientIP, option)
  156. cancel()
  157. if err != nil {
  158. return ips, err
  159. }
  160. return c.MatchExpectedIPs(domain, ips)
  161. }
  162. // MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
  163. func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
  164. if len(c.expectIPs) == 0 {
  165. return ips, nil
  166. }
  167. newIps := []net.IP{}
  168. for _, ip := range ips {
  169. for _, matcher := range c.expectIPs {
  170. if matcher.Match(ip) {
  171. newIps = append(newIps, ip)
  172. break
  173. }
  174. }
  175. }
  176. if len(newIps) == 0 {
  177. return nil, errExpectedIPNonMatch
  178. }
  179. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog()
  180. return newIps, nil
  181. }