server.go 9.6 KB

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