nameserver.go 6.5 KB

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