server.go 6.3 KB

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