cache_controller.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package dns
  2. import (
  3. "context"
  4. go_errors "errors"
  5. "sync"
  6. "time"
  7. "github.com/xtls/xray-core/common"
  8. "github.com/xtls/xray-core/common/errors"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/signal/pubsub"
  11. "github.com/xtls/xray-core/common/task"
  12. dns_feature "github.com/xtls/xray-core/features/dns"
  13. "golang.org/x/net/dns/dnsmessage"
  14. )
  15. type CacheController struct {
  16. sync.RWMutex
  17. ips map[string]*record
  18. pub *pubsub.Service
  19. cacheCleanup *task.Periodic
  20. name string
  21. disableCache bool
  22. serveStale bool
  23. serveExpiredTTL int32
  24. }
  25. func NewCacheController(name string, disableCache bool, serveStale bool, serveExpiredTTL uint32) *CacheController {
  26. c := &CacheController{
  27. name: name,
  28. disableCache: disableCache,
  29. serveStale: serveStale,
  30. serveExpiredTTL: -int32(serveExpiredTTL),
  31. ips: make(map[string]*record),
  32. pub: pubsub.NewService(),
  33. }
  34. c.cacheCleanup = &task.Periodic{
  35. Interval: time.Minute,
  36. Execute: c.CacheCleanup,
  37. }
  38. return c
  39. }
  40. // CacheCleanup clears expired items from cache
  41. func (c *CacheController) CacheCleanup() error {
  42. now := time.Now()
  43. if c.serveStale && c.serveExpiredTTL != 0 {
  44. now = now.Add(time.Duration(c.serveExpiredTTL) * time.Second)
  45. }
  46. c.Lock()
  47. defer c.Unlock()
  48. if len(c.ips) == 0 {
  49. return errors.New("nothing to do. stopping...")
  50. }
  51. for domain, record := range c.ips {
  52. if record.A != nil && record.A.Expire.Before(now) {
  53. record.A = nil
  54. }
  55. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  56. record.AAAA = nil
  57. }
  58. if record.A == nil && record.AAAA == nil {
  59. errors.LogDebug(context.Background(), c.name, "cache cleanup ", domain)
  60. delete(c.ips, domain)
  61. } else {
  62. c.ips[domain] = record
  63. }
  64. }
  65. if len(c.ips) == 0 {
  66. c.ips = make(map[string]*record)
  67. }
  68. return nil
  69. }
  70. func (c *CacheController) updateIP(req *dnsRequest, ipRec *IPRecord) {
  71. elapsed := time.Since(req.start)
  72. c.Lock()
  73. rec, found := c.ips[req.domain]
  74. if !found {
  75. rec = &record{}
  76. }
  77. switch req.reqType {
  78. case dnsmessage.TypeA:
  79. rec.A = ipRec
  80. case dnsmessage.TypeAAAA:
  81. rec.AAAA = ipRec
  82. }
  83. errors.LogInfo(context.Background(), c.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed)
  84. c.ips[req.domain] = rec
  85. switch req.reqType {
  86. case dnsmessage.TypeA:
  87. c.pub.Publish(req.domain+"4", nil)
  88. case dnsmessage.TypeAAAA:
  89. c.pub.Publish(req.domain+"6", nil)
  90. }
  91. c.Unlock()
  92. if !c.serveStale || c.serveExpiredTTL != 0 {
  93. common.Must(c.cacheCleanup.Start())
  94. }
  95. }
  96. func (c *CacheController) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, int32, bool, bool, error) {
  97. c.RLock()
  98. record, found := c.ips[domain]
  99. c.RUnlock()
  100. if !found {
  101. return nil, 0, true, true, errRecordNotFound
  102. }
  103. var errs []error
  104. var allIPs []net.IP
  105. var rTTL int32 = dns_feature.DefaultTTL
  106. mergeReq := option.IPv4Enable && option.IPv6Enable
  107. isARecordExpired := true
  108. if option.IPv4Enable {
  109. ips, ttl, err := record.A.getIPs()
  110. if ttl > 0 {
  111. isARecordExpired = false
  112. }
  113. if !mergeReq {
  114. return ips, ttl, isARecordExpired, true, err
  115. }
  116. if ttl < rTTL {
  117. rTTL = ttl
  118. }
  119. if len(ips) > 0 {
  120. allIPs = append(allIPs, ips...)
  121. }
  122. errs = append(errs, err)
  123. }
  124. isAAAARecordExpired := true
  125. if option.IPv6Enable {
  126. ips, ttl, err := record.AAAA.getIPs()
  127. if ttl > 0 {
  128. isAAAARecordExpired = false
  129. }
  130. if !mergeReq {
  131. return ips, ttl, true, isAAAARecordExpired, err
  132. }
  133. if ttl < rTTL {
  134. rTTL = ttl
  135. }
  136. if len(ips) > 0 {
  137. allIPs = append(allIPs, ips...)
  138. }
  139. errs = append(errs, err)
  140. }
  141. if go_errors.Is(errs[0], errRecordNotFound) || go_errors.Is(errs[1], errRecordNotFound) {
  142. return nil, 0, isARecordExpired, isAAAARecordExpired, errRecordNotFound
  143. }
  144. if len(allIPs) > 0 {
  145. return allIPs, rTTL, isARecordExpired, isAAAARecordExpired, nil
  146. }
  147. if go_errors.Is(errs[0], errs[1]) {
  148. return nil, rTTL, isARecordExpired, isAAAARecordExpired, errs[0]
  149. }
  150. return nil, rTTL, isARecordExpired, isAAAARecordExpired, errors.Combine(errs...)
  151. }
  152. func (c *CacheController) registerSubscribers(domain string, option dns_feature.IPOption) (sub4 *pubsub.Subscriber, sub6 *pubsub.Subscriber) {
  153. // ipv4 and ipv6 belong to different subscription groups
  154. if option.IPv4Enable {
  155. sub4 = c.pub.Subscribe(domain + "4")
  156. }
  157. if option.IPv6Enable {
  158. sub6 = c.pub.Subscribe(domain + "6")
  159. }
  160. return
  161. }
  162. func closeSubscribers(sub4 *pubsub.Subscriber, sub6 *pubsub.Subscriber) {
  163. if sub4 != nil {
  164. sub4.Close()
  165. }
  166. if sub6 != nil {
  167. sub6.Close()
  168. }
  169. }