nameserver.go 7.8 KB

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