server.go 10 KB

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