forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns.go
88 lines (77 loc) · 1.41 KB
/
dns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package dns
import (
"net"
"sync"
"time"
)
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
cache map[string]*entry
}
func NewCache() *DnsCache {
cache := &DnsCache{
cache: make(map[string]*entry),
}
go cache.cleanup()
return cache
}
func (this *DnsCache) cleanup() {
for range time.Tick(60 * time.Second) {
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()
}
}
}
}
func (this *DnsCache) Add(domain string, ip net.IP) {
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()
}
}
func (this *DnsCache) Get(domain string) net.IP {
this.RLock()
entry, found := this.cache[domain]
this.RUnlock()
if found {
return entry.ip
}
return nil
}