server.go 9.1 KB

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