dns.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package internal
  2. import (
  3. "net"
  4. "time"
  5. "github.com/v2ray/v2ray-core/app"
  6. "github.com/v2ray/v2ray-core/common/collect"
  7. "github.com/v2ray/v2ray-core/common/serial"
  8. )
  9. type entry struct {
  10. domain string
  11. ip net.IP
  12. validUntil time.Time
  13. }
  14. func newEntry(domain string, ip net.IP) *entry {
  15. this := &entry{
  16. domain: domain,
  17. ip: ip,
  18. }
  19. this.Extend()
  20. return this
  21. }
  22. func (this *entry) IsValid() bool {
  23. return this.validUntil.After(time.Now())
  24. }
  25. func (this *entry) Extend() {
  26. this.validUntil = time.Now().Add(time.Hour)
  27. }
  28. type DnsCache struct {
  29. cache *collect.ValidityMap
  30. config *CacheConfig
  31. }
  32. func NewCache(config *CacheConfig) *DnsCache {
  33. cache := &DnsCache{
  34. cache: collect.NewValidityMap(3600),
  35. config: config,
  36. }
  37. return cache
  38. }
  39. func (this *DnsCache) Add(context app.Context, domain string, ip net.IP) {
  40. callerTag := context.CallerTag()
  41. if !this.config.IsTrustedSource(serial.StringLiteral(callerTag)) {
  42. return
  43. }
  44. this.cache.Set(serial.StringLiteral(domain), newEntry(domain, ip))
  45. }
  46. func (this *DnsCache) Get(context app.Context, domain string) net.IP {
  47. if value := this.cache.Get(serial.StringLiteral(domain)); value != nil {
  48. return value.(*entry).ip
  49. }
  50. return nil
  51. }