server.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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/app/router"
  10. "v2ray.com/core/common"
  11. "v2ray.com/core/common/errors"
  12. "v2ray.com/core/common/net"
  13. "v2ray.com/core/common/session"
  14. "v2ray.com/core/common/strmatcher"
  15. "v2ray.com/core/common/uuid"
  16. "v2ray.com/core/features"
  17. "v2ray.com/core/features/dns"
  18. "v2ray.com/core/features/routing"
  19. )
  20. // Server is a DNS rely server.
  21. type Server struct {
  22. sync.Mutex
  23. hosts *StaticHosts
  24. clients []Client
  25. clientIP net.IP
  26. domainMatcher strmatcher.IndexMatcher
  27. domainIndexMap map[uint32]uint32
  28. ipIndexMap map[uint32]*MultiGeoIPMatcher
  29. tag string
  30. }
  31. // MultiGeoIPMatcher for match
  32. type MultiGeoIPMatcher struct {
  33. matchers []*router.GeoIPMatcher
  34. }
  35. var errExpectedIPNonMatch = errors.New("expected ip not match")
  36. // Match check ip match
  37. func (c *MultiGeoIPMatcher) Match(ip net.IP) bool {
  38. for _, matcher := range c.matchers {
  39. if matcher.Match(ip) {
  40. return true
  41. }
  42. }
  43. return false
  44. }
  45. // HasMatcher check has matcher
  46. func (c *MultiGeoIPMatcher) HasMatcher() bool {
  47. if len(c.matchers) > 0 {
  48. return true
  49. }
  50. return false
  51. }
  52. func generateRandomTag() string {
  53. id := uuid.New()
  54. return "v2ray.system." + id.String()
  55. }
  56. // New creates a new DNS server with given configuration.
  57. func New(ctx context.Context, config *Config) (*Server, error) {
  58. server := &Server{
  59. clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
  60. tag: config.Tag,
  61. }
  62. if server.tag == "" {
  63. server.tag = generateRandomTag()
  64. }
  65. if len(config.ClientIp) > 0 {
  66. if len(config.ClientIp) != 4 && len(config.ClientIp) != 16 {
  67. return nil, newError("unexpected IP length", len(config.ClientIp))
  68. }
  69. server.clientIP = net.IP(config.ClientIp)
  70. }
  71. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  72. if err != nil {
  73. return nil, newError("failed to create hosts").Base(err)
  74. }
  75. server.hosts = hosts
  76. addNameServer := func(endpoint *net.Endpoint) int {
  77. address := endpoint.Address.AsAddress()
  78. if address.Family().IsDomain() && address.Domain() == "localhost" {
  79. server.clients = append(server.clients, NewLocalNameServer())
  80. } else {
  81. dest := endpoint.AsDestination()
  82. if dest.Network == net.Network_Unknown {
  83. dest.Network = net.Network_UDP
  84. }
  85. if dest.Network == net.Network_UDP {
  86. idx := len(server.clients)
  87. server.clients = append(server.clients, nil)
  88. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  89. server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
  90. }))
  91. }
  92. }
  93. return len(server.clients) - 1
  94. }
  95. if len(config.NameServers) > 0 {
  96. features.PrintDeprecatedFeatureWarning("simple DNS server")
  97. }
  98. for _, destPB := range config.NameServers {
  99. addNameServer(destPB)
  100. }
  101. var geoIPMatcherContainer router.GeoIPMatcherContainer
  102. if len(config.NameServer) > 0 {
  103. domainMatcher := &strmatcher.MatcherGroup{}
  104. domainIndexMap := make(map[uint32]uint32)
  105. ipIndexMap := make(map[uint32]*MultiGeoIPMatcher)
  106. for _, ns := range config.NameServer {
  107. idx := addNameServer(ns.Address)
  108. for _, domain := range ns.PrioritizedDomain {
  109. matcher, err := toStrMatcher(domain.Type, domain.Domain)
  110. if err != nil {
  111. return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  112. }
  113. midx := domainMatcher.Add(matcher)
  114. domainIndexMap[midx] = uint32(idx)
  115. }
  116. var matchers []*router.GeoIPMatcher
  117. for _, geoip := range ns.Geoip {
  118. matcher, err := geoIPMatcherContainer.Add(geoip)
  119. if err != nil {
  120. return nil, newError("failed to create ip matcher").Base(err).AtWarning()
  121. }
  122. matchers = append(matchers, matcher)
  123. }
  124. matcher := &MultiGeoIPMatcher{matchers: matchers}
  125. ipIndexMap[uint32(idx)] = matcher
  126. }
  127. server.domainMatcher = domainMatcher
  128. server.domainIndexMap = domainIndexMap
  129. server.ipIndexMap = ipIndexMap
  130. }
  131. if len(server.clients) == 0 {
  132. server.clients = append(server.clients, NewLocalNameServer())
  133. }
  134. return server, nil
  135. }
  136. // Type implements common.HasType.
  137. func (*Server) Type() interface{} {
  138. return dns.ClientType()
  139. }
  140. // Start implements common.Runnable.
  141. func (s *Server) Start() error {
  142. return nil
  143. }
  144. // Close implements common.Closable.
  145. func (s *Server) Close() error {
  146. return nil
  147. }
  148. func (s *Server) IsOwnLink(ctx context.Context) bool {
  149. inbound := session.InboundFromContext(ctx)
  150. return inbound != nil && inbound.Tag == s.tag
  151. }
  152. // Match check dns ip match geoip
  153. func (s *Server) Match(idx uint32, client Client, domain string, ips []net.IP) ([]net.IP, error) {
  154. matcher, exist := s.ipIndexMap[idx]
  155. if exist == false {
  156. newError("domain ", domain, " server not in ipIndexMap: ", client.Name(), " idx:", idx, " just return").AtDebug().WriteToLog()
  157. return ips, nil
  158. }
  159. if matcher.HasMatcher() == false {
  160. newError("domain ", domain, " server has not valid matcher: ", client.Name(), " idx:", idx, " just return").AtDebug().WriteToLog()
  161. return ips, nil
  162. }
  163. newIps := []net.IP{}
  164. for _, ip := range ips {
  165. if matcher.Match(ip) {
  166. newIps = append(newIps, ip)
  167. newError("domain ", domain, " ip ", ip, " is match at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  168. } else {
  169. newError("domain ", domain, " ip ", ip, " is not match at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  170. }
  171. }
  172. if len(newIps) == 0 {
  173. return nil, errExpectedIPNonMatch
  174. }
  175. return newIps, nil
  176. }
  177. func (s *Server) queryIPTimeout(idx uint32, client Client, domain string, option IPOption) ([]net.IP, error) {
  178. ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
  179. if len(s.tag) > 0 {
  180. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  181. Tag: s.tag,
  182. })
  183. }
  184. ips, err := client.QueryIP(ctx, domain, option)
  185. cancel()
  186. if err != nil {
  187. return ips, err
  188. }
  189. ips, err = s.Match(idx, client, domain, ips)
  190. return ips, err
  191. }
  192. // LookupIP implements dns.Client.
  193. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  194. return s.lookupIPInternal(domain, IPOption{
  195. IPv4Enable: true,
  196. IPv6Enable: true,
  197. })
  198. }
  199. // LookupIPv4 implements dns.IPv4Lookup.
  200. func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
  201. return s.lookupIPInternal(domain, IPOption{
  202. IPv4Enable: true,
  203. IPv6Enable: false,
  204. })
  205. }
  206. // LookupIPv6 implements dns.IPv6Lookup.
  207. func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
  208. return s.lookupIPInternal(domain, IPOption{
  209. IPv4Enable: false,
  210. IPv6Enable: true,
  211. })
  212. }
  213. func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
  214. ips := s.hosts.LookupIP(domain, option)
  215. if ips == nil {
  216. return nil
  217. }
  218. if ips[0].Family().IsDomain() && depth < 5 {
  219. if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
  220. return newIPs
  221. }
  222. }
  223. return ips
  224. }
  225. func toNetIP(ips []net.Address) []net.IP {
  226. if len(ips) == 0 {
  227. return nil
  228. }
  229. netips := make([]net.IP, 0, len(ips))
  230. for _, ip := range ips {
  231. netips = append(netips, ip.IP())
  232. }
  233. return netips
  234. }
  235. func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  236. if domain == "" {
  237. return nil, newError("empty domain name")
  238. }
  239. if domain[len(domain)-1] == '.' {
  240. domain = domain[:len(domain)-1]
  241. }
  242. ips := s.lookupStatic(domain, option, 0)
  243. if ips != nil && ips[0].Family().IsIP() {
  244. newError("returning ", len(ips), " IPs for domain ", domain).WriteToLog()
  245. return toNetIP(ips), nil
  246. }
  247. if ips != nil && ips[0].Family().IsDomain() {
  248. newdomain := ips[0].Domain()
  249. newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
  250. domain = newdomain
  251. }
  252. var lastErr error
  253. var matchedClient Client
  254. if s.domainMatcher != nil {
  255. idx := s.domainMatcher.Match(domain)
  256. if idx > 0 {
  257. matchedClient = s.clients[s.domainIndexMap[idx]]
  258. newError("domain matched, direct lookup ip for domain ", domain, " at ", matchedClient.Name()).WriteToLog()
  259. ips, err := s.queryIPTimeout(s.domainIndexMap[idx], matchedClient, domain, option)
  260. if len(ips) > 0 {
  261. return ips, nil
  262. }
  263. if err == dns.ErrEmptyResponse {
  264. return nil, err
  265. }
  266. if err != nil {
  267. newError("failed to lookup ip for domain ", domain, " at server ", matchedClient.Name()).Base(err).WriteToLog()
  268. lastErr = err
  269. }
  270. }
  271. }
  272. for idx, client := range s.clients {
  273. if client == matchedClient {
  274. newError("domain ", domain, " at server ", client.Name(), " idx:", idx, " already lookup failed, just ignore").AtDebug().WriteToLog()
  275. continue
  276. }
  277. newError("try to lookup ip for domain ", domain, " at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  278. ips, err := s.queryIPTimeout(uint32(idx), client, domain, option)
  279. if len(ips) > 0 {
  280. newError("lookup ip for domain ", domain, " success: ", ips, " at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  281. return ips, nil
  282. }
  283. if err != nil {
  284. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  285. lastErr = err
  286. }
  287. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  288. return nil, err
  289. }
  290. }
  291. return nil, newError("returning nil for domain ", domain).Base(lastErr)
  292. }
  293. func init() {
  294. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  295. return New(ctx, config.(*Config))
  296. }))
  297. }