1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-04 17:27:23 -05:00
v2fly/app/dns/dns.go

63 lines
1.2 KiB
Go
Raw Normal View History

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