1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-28 18:25:23 +00:00
v2fly/app/dns/dns.go

63 lines
1.2 KiB
Go
Raw Normal View History

2015-12-06 10:00:10 +00:00
package dns
import (
"net"
"time"
2015-12-10 22:55:39 +00:00
"github.com/v2ray/v2ray-core/app"
2015-12-14 13:14:10 +00:00
"github.com/v2ray/v2ray-core/common/collect"
"github.com/v2ray/v2ray-core/common/serial"
2015-12-06 10:00:10 +00: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 {
2015-12-14 13:14:10 +00:00
cache *collect.ValidityMap
2015-12-10 21:08:36 +00:00
config CacheConfig
2015-12-06 10:00:10 +00:00
}
2015-12-10 21:08:36 +00:00
func NewCache(config CacheConfig) *DnsCache {
2015-12-06 10:00:10 +00:00
cache := &DnsCache{
2015-12-14 13:14:10 +00:00
cache: collect.NewValidityMap(3600),
2015-12-10 22:55:39 +00:00
config: config,
2015-12-06 10:00:10 +00:00
}
return cache
}
2015-12-10 22:55:39 +00:00
func (this *DnsCache) Add(context app.Context, domain string, ip net.IP) {
callerTag := context.CallerTag()
if !this.config.IsTrustedSource(callerTag) {
return
}
2015-12-14 13:14:10 +00:00
this.cache.Set(serial.StringLiteral(domain), newEntry(domain, ip))
2015-12-06 10:00:10 +00:00
}
2015-12-10 22:55:39 +00:00
func (this *DnsCache) Get(context app.Context, domain string) net.IP {
2015-12-14 13:14:10 +00:00
if value := this.cache.Get(serial.StringLiteral(domain)); value != nil {
return value.(*entry).ip
2015-12-06 10:00:10 +00:00
}
return nil
}