server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // +build !confonly
  2. package dns
  3. //go:generate errorgen
  4. import (
  5. "context"
  6. "fmt"
  7. "log"
  8. "net/url"
  9. "strings"
  10. "sync"
  11. "time"
  12. "v2ray.com/core"
  13. "v2ray.com/core/app/router"
  14. "v2ray.com/core/common"
  15. "v2ray.com/core/common/errors"
  16. "v2ray.com/core/common/net"
  17. "v2ray.com/core/common/session"
  18. "v2ray.com/core/common/strmatcher"
  19. "v2ray.com/core/common/uuid"
  20. "v2ray.com/core/features"
  21. "v2ray.com/core/features/dns"
  22. "v2ray.com/core/features/routing"
  23. )
  24. // Server is a DNS rely server.
  25. type Server struct {
  26. sync.Mutex
  27. hosts *StaticHosts
  28. clientIP net.IP
  29. clients []Client // clientIdx -> Client
  30. ipIndexMap []*MultiGeoIPMatcher // clientIdx -> *MultiGeoIPMatcher
  31. domainRules [][]string // clientIdx -> domainRuleIdx -> DomainRule
  32. domainMatcher strmatcher.IndexMatcher
  33. matcherInfos []DomainMatcherInfo // matcherIdx -> DomainMatcherInfo
  34. tag string
  35. }
  36. // DomainMatcherInfo contains information attached to index returned by Server.domainMatcher
  37. type DomainMatcherInfo struct {
  38. clientIdx uint16
  39. domainRuleIdx uint16
  40. }
  41. // MultiGeoIPMatcher for match
  42. type MultiGeoIPMatcher struct {
  43. matchers []*router.GeoIPMatcher
  44. }
  45. var errExpectedIPNonMatch = errors.New("expectIPs not match")
  46. // Match check ip match
  47. func (c *MultiGeoIPMatcher) Match(ip net.IP) bool {
  48. for _, matcher := range c.matchers {
  49. if matcher.Match(ip) {
  50. return true
  51. }
  52. }
  53. return false
  54. }
  55. // HasMatcher check has matcher
  56. func (c *MultiGeoIPMatcher) HasMatcher() bool {
  57. return len(c.matchers) > 0
  58. }
  59. func generateRandomTag() string {
  60. id := uuid.New()
  61. return "v2ray.system." + id.String()
  62. }
  63. // New creates a new DNS server with given configuration.
  64. func New(ctx context.Context, config *Config) (*Server, error) {
  65. server := &Server{
  66. clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
  67. tag: config.Tag,
  68. }
  69. if server.tag == "" {
  70. server.tag = generateRandomTag()
  71. }
  72. if len(config.ClientIp) > 0 {
  73. if len(config.ClientIp) != net.IPv4len && len(config.ClientIp) != net.IPv6len {
  74. return nil, newError("unexpected IP length", len(config.ClientIp))
  75. }
  76. server.clientIP = net.IP(config.ClientIp)
  77. }
  78. hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
  79. if err != nil {
  80. return nil, newError("failed to create hosts").Base(err)
  81. }
  82. server.hosts = hosts
  83. addNameServer := func(ns *NameServer) int {
  84. endpoint := ns.Address
  85. address := endpoint.Address.AsAddress()
  86. if address.Family().IsDomain() && address.Domain() == "localhost" {
  87. server.clients = append(server.clients, NewLocalNameServer())
  88. if len(ns.PrioritizedDomain) == 0 { // Priotize local domain with .local domain or without any dot to local DNS
  89. ns.PrioritizedDomain = []*NameServer_PriorityDomain{
  90. {Type: DomainMatchingType_Regex, Domain: "^[^.]*$"}, // This will only match domain without any dot
  91. {Type: DomainMatchingType_Subdomain, Domain: "local"},
  92. {Type: DomainMatchingType_Subdomain, Domain: "localdomain"},
  93. }
  94. }
  95. } else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https+local://") {
  96. // URI schemed string treated as domain
  97. // DOH Local mode
  98. u, err := url.Parse(address.Domain())
  99. if err != nil {
  100. log.Fatalln(newError("DNS config error").Base(err))
  101. }
  102. server.clients = append(server.clients, NewDoHLocalNameServer(u, server.clientIP))
  103. } else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https://") {
  104. // DOH Remote mode
  105. u, err := url.Parse(address.Domain())
  106. if err != nil {
  107. log.Fatalln(newError("DNS config error").Base(err))
  108. }
  109. idx := len(server.clients)
  110. server.clients = append(server.clients, nil)
  111. // need the core dispatcher, register DOHClient at callback
  112. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  113. c, err := NewDoHNameServer(u, d, server.clientIP)
  114. if err != nil {
  115. log.Fatalln(newError("DNS config error").Base(err))
  116. }
  117. server.clients[idx] = c
  118. }))
  119. } else {
  120. // UDP classic DNS mode
  121. dest := endpoint.AsDestination()
  122. if dest.Network == net.Network_Unknown {
  123. dest.Network = net.Network_UDP
  124. }
  125. if dest.Network == net.Network_UDP {
  126. idx := len(server.clients)
  127. server.clients = append(server.clients, nil)
  128. common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
  129. server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
  130. }))
  131. }
  132. }
  133. server.ipIndexMap = append(server.ipIndexMap, nil)
  134. return len(server.clients) - 1
  135. }
  136. if len(config.NameServers) > 0 {
  137. features.PrintDeprecatedFeatureWarning("simple DNS server")
  138. for _, destPB := range config.NameServers {
  139. addNameServer(&NameServer{Address: destPB})
  140. }
  141. }
  142. if len(config.NameServer) > 0 {
  143. clientIndices := []int{}
  144. domainRuleCount := 0
  145. for _, ns := range config.NameServer {
  146. idx := addNameServer(ns)
  147. clientIndices = append(clientIndices, idx)
  148. domainRuleCount += len(ns.PrioritizedDomain)
  149. }
  150. domainRules := make([][]string, len(server.clients))
  151. domainMatcher := &strmatcher.MatcherGroup{}
  152. matcherInfos := make([]DomainMatcherInfo, domainRuleCount+1) // matcher index starts from 1
  153. var geoIPMatcherContainer router.GeoIPMatcherContainer
  154. for nidx, ns := range config.NameServer {
  155. idx := clientIndices[nidx]
  156. // Establish domain rule matcher
  157. rules := []string{}
  158. ruleCurr := 0
  159. ruleIter := 0
  160. for _, domain := range ns.PrioritizedDomain {
  161. matcher, err := toStrMatcher(domain.Type, domain.Domain)
  162. if err != nil {
  163. return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
  164. }
  165. midx := domainMatcher.Add(matcher)
  166. if midx >= uint32(len(matcherInfos)) { // This rarely happens according to current matcher's implementation
  167. newError("expanding domain matcher info array to size ", midx, " when adding ", matcher).AtDebug().WriteToLog()
  168. matcherInfos = append(matcherInfos, make([]DomainMatcherInfo, midx-uint32(len(matcherInfos))+1)...)
  169. }
  170. info := &matcherInfos[midx]
  171. info.clientIdx = uint16(idx)
  172. if ruleCurr < len(ns.OriginalRules) {
  173. info.domainRuleIdx = uint16(ruleCurr)
  174. rule := ns.OriginalRules[ruleCurr]
  175. if ruleCurr >= len(rules) {
  176. rules = append(rules, rule.Rule)
  177. }
  178. ruleIter++
  179. if ruleIter >= int(rule.Size) {
  180. ruleIter = 0
  181. ruleCurr++
  182. }
  183. } else { // No original rule, generate one according to current domain matcher (majorly for compability with tests)
  184. info.domainRuleIdx = uint16(len(rules))
  185. rules = append(rules, matcher.String())
  186. }
  187. }
  188. domainRules[idx] = rules
  189. // only add to ipIndexMap if GeoIP is configured
  190. if len(ns.Geoip) > 0 {
  191. var matchers []*router.GeoIPMatcher
  192. for _, geoip := range ns.Geoip {
  193. matcher, err := geoIPMatcherContainer.Add(geoip)
  194. if err != nil {
  195. return nil, newError("failed to create ip matcher").Base(err).AtWarning()
  196. }
  197. matchers = append(matchers, matcher)
  198. }
  199. matcher := &MultiGeoIPMatcher{matchers: matchers}
  200. server.ipIndexMap[idx] = matcher
  201. }
  202. }
  203. server.domainRules = domainRules
  204. server.domainMatcher = domainMatcher
  205. server.matcherInfos = matcherInfos
  206. }
  207. if len(server.clients) == 0 {
  208. server.clients = append(server.clients, NewLocalNameServer())
  209. server.ipIndexMap = append(server.ipIndexMap, nil)
  210. }
  211. return server, nil
  212. }
  213. // Type implements common.HasType.
  214. func (*Server) Type() interface{} {
  215. return dns.ClientType()
  216. }
  217. // Start implements common.Runnable.
  218. func (s *Server) Start() error {
  219. return nil
  220. }
  221. // Close implements common.Closable.
  222. func (s *Server) Close() error {
  223. return nil
  224. }
  225. func (s *Server) IsOwnLink(ctx context.Context) bool {
  226. inbound := session.InboundFromContext(ctx)
  227. return inbound != nil && inbound.Tag == s.tag
  228. }
  229. // Match check dns ip match geoip
  230. func (s *Server) Match(idx int, client Client, domain string, ips []net.IP) ([]net.IP, error) {
  231. var matcher *MultiGeoIPMatcher
  232. if idx < len(s.ipIndexMap) {
  233. matcher = s.ipIndexMap[idx]
  234. }
  235. if matcher == nil {
  236. return ips, nil
  237. }
  238. if !matcher.HasMatcher() {
  239. newError("domain ", domain, " server has no valid matcher: ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  240. return ips, nil
  241. }
  242. newIps := []net.IP{}
  243. for _, ip := range ips {
  244. if matcher.Match(ip) {
  245. newIps = append(newIps, ip)
  246. }
  247. }
  248. if len(newIps) == 0 {
  249. return nil, errExpectedIPNonMatch
  250. }
  251. newError("domain ", domain, " expectIPs ", newIps, " matched at server ", client.Name(), " idx:", idx).AtDebug().WriteToLog()
  252. return newIps, nil
  253. }
  254. func (s *Server) queryIPTimeout(idx int, client Client, domain string, option IPOption) ([]net.IP, error) {
  255. ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
  256. if len(s.tag) > 0 {
  257. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  258. Tag: s.tag,
  259. })
  260. }
  261. ips, err := client.QueryIP(ctx, domain, option)
  262. cancel()
  263. if err != nil {
  264. return ips, err
  265. }
  266. ips, err = s.Match(idx, client, domain, ips)
  267. return ips, err
  268. }
  269. // LookupIP implements dns.Client.
  270. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  271. return s.lookupIPInternal(domain, IPOption{
  272. IPv4Enable: true,
  273. IPv6Enable: true,
  274. })
  275. }
  276. // LookupIPv4 implements dns.IPv4Lookup.
  277. func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
  278. return s.lookupIPInternal(domain, IPOption{
  279. IPv4Enable: true,
  280. IPv6Enable: false,
  281. })
  282. }
  283. // LookupIPv6 implements dns.IPv6Lookup.
  284. func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
  285. return s.lookupIPInternal(domain, IPOption{
  286. IPv4Enable: false,
  287. IPv6Enable: true,
  288. })
  289. }
  290. func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
  291. ips := s.hosts.LookupIP(domain, option)
  292. if ips == nil {
  293. return nil
  294. }
  295. if ips[0].Family().IsDomain() && depth < 5 {
  296. if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
  297. return newIPs
  298. }
  299. }
  300. return ips
  301. }
  302. func toNetIP(ips []net.Address) []net.IP {
  303. if len(ips) == 0 {
  304. return nil
  305. }
  306. netips := make([]net.IP, 0, len(ips))
  307. for _, ip := range ips {
  308. netips = append(netips, ip.IP())
  309. }
  310. return netips
  311. }
  312. func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
  313. if domain == "" {
  314. return nil, newError("empty domain name")
  315. }
  316. // normalize the FQDN form query
  317. if domain[len(domain)-1] == '.' {
  318. domain = domain[:len(domain)-1]
  319. }
  320. ips := s.lookupStatic(domain, option, 0)
  321. if ips != nil && ips[0].Family().IsIP() {
  322. newError("returning ", len(ips), " IPs for domain ", domain).WriteToLog()
  323. return toNetIP(ips), nil
  324. }
  325. if ips != nil && ips[0].Family().IsDomain() {
  326. newdomain := ips[0].Domain()
  327. newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
  328. domain = newdomain
  329. }
  330. var lastErr error
  331. var matchedClient Client
  332. if s.domainMatcher != nil {
  333. indices := s.domainMatcher.Match(domain)
  334. domainRules := []string{}
  335. matchingDNS := []string{}
  336. for _, idx := range indices {
  337. info := s.matcherInfos[idx]
  338. rule := s.domainRules[info.clientIdx][info.domainRuleIdx]
  339. domainRules = append(domainRules, fmt.Sprintf("%s(DNS idx:%d)", rule, info.clientIdx))
  340. matchingDNS = append(matchingDNS, s.clients[info.clientIdx].Name())
  341. }
  342. if len(domainRules) > 0 {
  343. newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog()
  344. }
  345. if len(matchingDNS) > 0 {
  346. newError("domain ", domain, " uses following DNS first: ", matchingDNS).AtDebug().WriteToLog()
  347. }
  348. for _, idx := range indices {
  349. clientIdx := int(s.matcherInfos[idx].clientIdx)
  350. matchedClient = s.clients[clientIdx]
  351. ips, err := s.queryIPTimeout(clientIdx, matchedClient, domain, option)
  352. if len(ips) > 0 {
  353. return ips, nil
  354. }
  355. if err == dns.ErrEmptyResponse {
  356. return nil, err
  357. }
  358. if err != nil {
  359. newError("failed to lookup ip for domain ", domain, " at server ", matchedClient.Name()).Base(err).WriteToLog()
  360. lastErr = err
  361. }
  362. }
  363. }
  364. for idx, client := range s.clients {
  365. if client == matchedClient {
  366. newError("domain ", domain, " at server ", client.Name(), " idx:", idx, " already lookup failed, just ignore").AtDebug().WriteToLog()
  367. continue
  368. }
  369. ips, err := s.queryIPTimeout(idx, client, domain, option)
  370. if len(ips) > 0 {
  371. return ips, nil
  372. }
  373. if err != nil {
  374. newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
  375. lastErr = err
  376. }
  377. if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch {
  378. return nil, err
  379. }
  380. }
  381. return nil, newError("returning nil for domain ", domain).Base(lastErr)
  382. }
  383. func init() {
  384. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  385. return New(ctx, config.(*Config))
  386. }))
  387. }