server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // +build !confonly
  2. package dns
  3. //go:generate errorgen
  4. import (
  5. "context"
  6. "sync"
  7. "time"
  8. "v2ray.com/core"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/session"
  12. "v2ray.com/core/common/strmatcher"
  13. "v2ray.com/core/features"
  14. "v2ray.com/core/features/dns"
  15. "v2ray.com/core/features/routing"
  16. )
  17. // Server is a DNS rely server.
  18. type Server struct {
  19. sync.Mutex
  20. hosts *StaticHosts
  21. clients []Client
  22. clientIP net.IP
  23. domainMatcher strmatcher.IndexMatcher
  24. domainIndexMap map[uint32]uint32
  25. tag string
  26. }
  27. // New creates a new DNS server with given configuration.
  28. func New(ctx context.Context, config *Config) (*Server, error) {
  29. server := &Server{
  30. clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
  31. tag: config.Tag,
  32. }
  33. if len(config.ClientIp) > 0 {
  34. if len(config.ClientIp) != 4 && len(config.ClientIp) != 16 {
  35. return nil, newError("unexpected IP length", len(config.ClientIp))
  36. }
  37. server.clientIP = net.IP(config.ClientIp)
  38. }
  39. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  40. if err != nil {
  41. return nil, newError("failed to create hosts").Base(err)
  42. }
  43. server.hosts = hosts
  44. addNameServer := func(endpoint *net.Endpoint) int {
  45. address := endpoint.Address.AsAddress()
  46. if address.Family().IsDomain() && address.Domain() == "localhost" {
  47. server.clients = append(server.clients, NewLocalNameServer())
  48. } else {
  49. dest := endpoint.AsDestination()
  50. if dest.Network == net.Network_Unknown {
  51. dest.Network = net.Network_UDP
  52. }
  53. if dest.Network == net.Network_UDP {
  54. idx := len(server.clients)
  55. server.clients = append(server.clients, nil)
  56. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  57. server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
  58. }))
  59. }
  60. }
  61. return len(server.clients) - 1
  62. }
  63. if len(config.NameServers) > 0 {
  64. features.PrintDeprecatedFeatureWarning("simple DNS server")
  65. }
  66. for _, destPB := range config.NameServers {
  67. addNameServer(destPB)
  68. }
  69. if len(config.NameServer) > 0 {
  70. domainMatcher := &strmatcher.MatcherGroup{}
  71. domainIndexMap := make(map[uint32]uint32)
  72. for _, ns := range config.NameServer {
  73. idx := addNameServer(ns.Address)
  74. for _, domain := range ns.PrioritizedDomain {
  75. matcher, err := toStrMatcher(domain.Type, domain.Domain)
  76. if err != nil {
  77. return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  78. }
  79. midx := domainMatcher.Add(matcher)
  80. domainIndexMap[midx] = uint32(idx)
  81. }
  82. }
  83. server.domainMatcher = domainMatcher
  84. server.domainIndexMap = domainIndexMap
  85. }
  86. if len(server.clients) == 0 {
  87. server.clients = append(server.clients, NewLocalNameServer())
  88. }
  89. return server, nil
  90. }
  91. // Type implements common.HasType.
  92. func (*Server) Type() interface{} {
  93. return dns.ClientType()
  94. }
  95. // Start implements common.Runnable.
  96. func (s *Server) Start() error {
  97. return nil
  98. }
  99. // Close implements common.Closable.
  100. func (s *Server) Close() error {
  101. return nil
  102. }
  103. func (s *Server) queryIPTimeout(client Client, domain string, option IPOption) ([]net.IP, error) {
  104. ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
  105. if len(s.tag) > 0 {
  106. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  107. Tag: s.tag,
  108. })
  109. }
  110. ips, err := client.QueryIP(ctx, domain, option)
  111. cancel()
  112. return ips, err
  113. }
  114. // LookupIP implements dns.Client.
  115. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  116. return s.lookupIPInternal(domain, IPOption{
  117. IPv4Enable: true,
  118. IPv6Enable: true,
  119. })
  120. }
  121. // LookupIPv4 implements dns.IPv4Lookup.
  122. func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
  123. return s.lookupIPInternal(domain, IPOption{
  124. IPv4Enable: true,
  125. IPv6Enable: false,
  126. })
  127. }
  128. // LookupIPv6 implements dns.IPv6Lookup.
  129. func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
  130. return s.lookupIPInternal(domain, IPOption{
  131. IPv4Enable: false,
  132. IPv6Enable: true,
  133. })
  134. }
  135. func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
  136. ips := s.hosts.LookupIP(domain, option)
  137. if ips == nil {
  138. return nil
  139. }
  140. if ips[0].Family().IsDomain() && depth < 5 {
  141. if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
  142. return newIPs
  143. }
  144. }
  145. return ips
  146. }
  147. func toNetIP(ips []net.Address) []net.IP {
  148. if len(ips) == 0 {
  149. return nil
  150. }
  151. netips := make([]net.IP, 0, len(ips))
  152. for _, ip := range ips {
  153. netips = append(netips, ip.IP())
  154. }
  155. return netips
  156. }
  157. func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  158. ips := s.lookupStatic(domain, option, 0)
  159. if ips != nil && ips[0].Family().IsIP() {
  160. return toNetIP(ips), nil
  161. }
  162. if ips != nil && ips[0].Family().IsDomain() {
  163. newdomain := ips[0].Domain()
  164. newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
  165. domain = newdomain
  166. }
  167. var lastErr error
  168. if s.domainMatcher != nil {
  169. idx := s.domainMatcher.Match(domain)
  170. if idx > 0 {
  171. ns := s.clients[s.domainIndexMap[idx]]
  172. ips, err := s.queryIPTimeout(ns, domain, option)
  173. if len(ips) > 0 {
  174. return ips, nil
  175. }
  176. if err != nil {
  177. newError("failed to lookup ip for domain ", domain, " at server ", ns.Name()).Base(err).WriteToLog()
  178. lastErr = err
  179. }
  180. }
  181. }
  182. for _, client := range s.clients {
  183. ips, err := s.queryIPTimeout(client, domain, option)
  184. if len(ips) > 0 {
  185. return ips, nil
  186. }
  187. if err != nil {
  188. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  189. lastErr = err
  190. }
  191. }
  192. return nil, newError("returning nil for domain ", domain).Base(lastErr)
  193. }
  194. func init() {
  195. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  196. return New(ctx, config.(*Config))
  197. }))
  198. }