nameserver.go 6.4 KB

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