2015-12-06 05:00:10 -05:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
"time"
|
2015-12-10 17:55:39 -05:00
|
|
|
|
|
|
|
"github.com/v2ray/v2ray-core/app"
|
2015-12-06 05:00:10 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type entry struct {
|
|
|
|
domain string
|
|
|
|
ip net.IP
|
|
|
|
validUntil time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func newEntry(domain string, ip net.IP) *entry {
|
|
|
|
this := &entry{
|
|
|
|
domain: domain,
|
|
|
|
ip: ip,
|
|
|
|
}
|
|
|
|
this.Extend()
|
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *entry) IsValid() bool {
|
|
|
|
return this.validUntil.After(time.Now())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *entry) Extend() {
|
|
|
|
this.validUntil = time.Now().Add(time.Hour)
|
|
|
|
}
|
|
|
|
|
|
|
|
type DnsCache struct {
|
|
|
|
sync.RWMutex
|
2015-12-10 16:08:36 -05:00
|
|
|
cache map[string]*entry
|
|
|
|
config CacheConfig
|
2015-12-06 05:00:10 -05:00
|
|
|
}
|
|
|
|
|
2015-12-10 16:08:36 -05:00
|
|
|
func NewCache(config CacheConfig) *DnsCache {
|
2015-12-06 05:00:10 -05:00
|
|
|
cache := &DnsCache{
|
2015-12-10 17:55:39 -05:00
|
|
|
cache: make(map[string]*entry),
|
|
|
|
config: config,
|
2015-12-06 05:00:10 -05:00
|
|
|
}
|
|
|
|
go cache.cleanup()
|
|
|
|
return cache
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *DnsCache) cleanup() {
|
2015-12-08 18:30:58 -05:00
|
|
|
for range time.Tick(60 * time.Second) {
|
2015-12-06 05:00:10 -05:00
|
|
|
entry2Remove := make([]*entry, 0, 128)
|
|
|
|
this.RLock()
|
|
|
|
for _, entry := range this.cache {
|
|
|
|
if !entry.IsValid() {
|
|
|
|
entry2Remove = append(entry2Remove, entry)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this.RUnlock()
|
|
|
|
|
|
|
|
for _, entry := range entry2Remove {
|
|
|
|
if !entry.IsValid() {
|
|
|
|
this.Lock()
|
|
|
|
delete(this.cache, entry.domain)
|
|
|
|
this.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-10 17:55:39 -05:00
|
|
|
func (this *DnsCache) Add(context app.Context, domain string, ip net.IP) {
|
2015-12-06 05:00:10 -05:00
|
|
|
this.RLock()
|
|
|
|
entry, found := this.cache[domain]
|
|
|
|
this.RUnlock()
|
|
|
|
if found {
|
|
|
|
entry.ip = ip
|
|
|
|
entry.Extend()
|
|
|
|
} else {
|
|
|
|
this.Lock()
|
|
|
|
this.cache[domain] = newEntry(domain, ip)
|
|
|
|
this.Unlock()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-10 17:55:39 -05:00
|
|
|
func (this *DnsCache) Get(context app.Context, domain string) net.IP {
|
2015-12-06 05:00:10 -05:00
|
|
|
this.RLock()
|
|
|
|
entry, found := this.cache[domain]
|
|
|
|
this.RUnlock()
|
|
|
|
if found {
|
|
|
|
return entry.ip
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|