-
Notifications
You must be signed in to change notification settings - Fork 69
/
cache.go
316 lines (271 loc) · 6.44 KB
/
cache.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main
import (
"crypto/md5"
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/miekg/dns"
"github.com/ryanuber/go-glob"
)
const globChars = "*?"
// KeyNotFound type
type KeyNotFound struct {
key string
}
// Error formats an error for the KeyNotFound type
func (e KeyNotFound) Error() string {
return e.key + " " + "not found"
}
// KeyExpired type
type KeyExpired struct {
Key string
}
// Error formats an error for the KeyExpired type
func (e KeyExpired) Error() string {
return e.Key + " " + "expired"
}
// CacheIsFull type
type CacheIsFull struct {
}
// Error formats an error for the CacheIsFull type
func (e CacheIsFull) Error() string {
return "Cache is Full"
}
// Mesg represents a cache entry
type Mesg struct {
Msg *dns.Msg
Blocked bool
LastUpdateTime time.Time
}
// Cache interface
type Cache interface {
Get(key string) (Msg *dns.Msg, blocked bool, err error)
Set(key string, Msg *dns.Msg, blocked bool) error
Exists(key string) bool
Remove(key string)
Length() int
}
// MemoryCache type
type MemoryCache struct {
Backend map[string]*Mesg
Maxcount int
mu sync.RWMutex
}
// MemoryBlockCache type
type MemoryBlockCache struct {
Backend map[string]bool
Special map[string]*regexp.Regexp
mu sync.RWMutex
}
// MemoryQuestionCache type
type MemoryQuestionCache struct {
Backend []QuestionCacheEntry `json:"entry"`
Maxcount int
mu sync.RWMutex
}
// Get returns the entry for a key or an error
func (c *MemoryCache) Get(key string) (*dns.Msg, bool, error) {
key = strings.ToLower(key)
//Truncate time to the second, so that subsecond queries won't keep moving
//forward the last update time without touching the TTL
now := WallClock.Now().Truncate(time.Second)
expired := false
c.mu.Lock()
mesg, ok := c.Backend[key]
if ok && mesg.Msg == nil {
ok = false
logger.Warningf("Cache: key %s returned nil entry", key)
c.removeNoLock(key)
}
if ok {
elapsed := uint32(now.Sub(mesg.LastUpdateTime).Seconds())
for _, answer := range mesg.Msg.Answer {
if elapsed > answer.Header().Ttl {
logger.Debugf("Cache: Key expired %s", key)
c.removeNoLock(key)
expired = true
}
answer.Header().Ttl -= elapsed
}
}
c.mu.Unlock()
if !ok {
logger.Debugf("Cache: Cannot find key %s\n", key)
return nil, false, KeyNotFound{key}
}
if expired {
return nil, false, KeyExpired{key}
}
mesg.LastUpdateTime = now
return mesg.Msg, mesg.Blocked, nil
}
// Set sets a keys value to a Mesg
func (c *MemoryCache) Set(key string, msg *dns.Msg, blocked bool) error {
key = strings.ToLower(key)
if c.Full() && !c.Exists(key) {
return CacheIsFull{}
}
if msg == nil {
logger.Debugf("Setting an empty value for key %s", key)
}
c.mu.Lock()
c.Backend[key] = &Mesg{msg, blocked, WallClock.Now().Truncate(time.Second)}
c.mu.Unlock()
return nil
}
// Remove removes an entry from the cache
func (c *MemoryCache) removeNoLock(key string) {
key = strings.ToLower(key)
delete(c.Backend, key)
}
// Remove removes an entry from the cache
func (c *MemoryCache) Remove(key string) {
c.mu.Lock()
c.removeNoLock(key)
c.mu.Unlock()
}
// Exists returns whether a key exists in the cache
func (c *MemoryCache) Exists(key string) bool {
key = strings.ToLower(key)
c.mu.RLock()
_, ok := c.Backend[key]
c.mu.RUnlock()
return ok
}
// Length returns the caches length
func (c *MemoryCache) Length() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.Backend)
}
// Full returns whether the cache is full
func (c *MemoryCache) Full() bool {
if c.Maxcount == 0 {
return false
}
return c.Length() >= c.Maxcount
}
// KeyGen generates a key for the hash from a question
func KeyGen(q Question) string {
h := md5.New()
h.Write([]byte(q.String()))
x := h.Sum(nil)
key := fmt.Sprintf("%x", x)
logger.Debugf("KeyGen: %s %s", q.String(), key)
return key
}
// Get returns the entry for a key or an error
func (c *MemoryBlockCache) Get(key string) (bool, error) {
var ok, val bool
c.mu.RLock()
if strings.HasPrefix(key, "~") {
_, ok = c.Special[key]
val = true
} else if strings.ContainsAny(key, globChars) {
key = strings.ToLower(key)
_, ok = c.Special[key]
val = true
} else {
key = strings.ToLower(key)
val, ok = c.Backend[key]
}
c.mu.RUnlock()
if !ok {
return false, KeyNotFound{key}
}
return val, nil
}
// Remove removes an entry from the cache
func (c *MemoryBlockCache) Remove(key string) {
c.mu.Lock()
if strings.HasPrefix(key, "~") {
delete(c.Special, key)
} else if strings.ContainsAny(key, globChars) {
delete(c.Special, strings.ToLower(key))
} else {
delete(c.Backend, strings.ToLower(key))
}
c.mu.Unlock()
}
// Set sets a value in the BlockCache
func (c *MemoryBlockCache) Set(key string, value bool) error {
c.mu.Lock()
if strings.HasPrefix(key, "~") {
// get rid of the ~ prefix
runes := []rune(key)
ex := string(runes[1:])
re, err := regexp.Compile(ex)
if err != nil {
logger.Errorf("Invalid regexp entry: `%s` %v", key, err)
} else {
c.Special[key] = re
}
} else if strings.ContainsAny(key, globChars) {
c.Special[strings.ToLower(key)] = nil
} else {
c.Backend[strings.ToLower(key)] = value
}
c.mu.Unlock()
return nil
}
// Exists returns whether a key exists in the cache
func (c *MemoryBlockCache) Exists(key string) bool {
key = strings.ToLower(key)
c.mu.RLock()
_, ok := c.Backend[key]
if !ok {
for data, regex := range c.Special {
if regex != nil {
if regex.MatchString(key) {
ok = true
}
} else {
if glob.Glob(data, key) {
ok = true
}
}
}
}
c.mu.RUnlock()
return ok
}
// Length returns the caches length
func (c *MemoryBlockCache) Length() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.Backend)
}
// Add adds a question to the cache
func (c *MemoryQuestionCache) Add(q QuestionCacheEntry) {
c.mu.Lock()
if c.Maxcount != 0 && len(c.Backend) >= c.Maxcount {
c.Backend = nil
}
c.Backend = append(c.Backend, q)
c.mu.Unlock()
}
// Clear clears the contents of the cache
func (c *MemoryQuestionCache) Clear() {
c.mu.Lock()
c.Backend = make([]QuestionCacheEntry, 0, 0)
c.mu.Unlock()
}
// Length returns the caches length
func (c *MemoryQuestionCache) Length() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.Backend)
}
// GetOlder eturns a slice of the entries older than `time`
func (c *MemoryQuestionCache) GetOlder(time int64) []QuestionCacheEntry {
c.mu.RLock()
defer c.mu.RUnlock()
for i, e := range c.Backend {
if e.Date > time {
return c.Backend[i:]
}
}
return []QuestionCacheEntry{}
}