server.go 9.8 KB

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