-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
527 lines (471 loc) · 11.7 KB
/
redis.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package redis
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/miekg/dns"
"github.com/coredns/coredns/plugin"
redisCon "github.com/gomodule/redigo/redis"
)
// Redis :basic redis struct
type Redis struct {
Next plugin.Handler
Pool *redisCon.Pool
redisAddress string
redisPassword string
connectTimeout int
readTimeout int
keyPrefix string
keySuffix string
Ttl uint32
Zones []string
LastZoneUpdate time.Time
}
// New :returns new redis instance
func New() *Redis {
return &Redis{
Zones: []string{"."},
redisAddress: "127.0.0.1:6379",
Pool: &redisCon.Pool{},
keyPrefix: "",
keySuffix: "",
Ttl: 300,
}
}
// LoadZones :loads zones from DB
func (redis *Redis) LoadZones() {
fmt.Println("loading zones")
var (
reply interface{}
err error
zones []string
)
conn := redis.Pool.Get()
if conn == nil {
fmt.Println("error connecting to redis")
return
}
defer conn.Close()
reply, err = conn.Do("KEYS", redis.keyPrefix+"*"+redis.keySuffix)
if err != nil {
fmt.Println(err)
return
}
zones, err = redisCon.Strings(reply, nil)
fmt.Println(zones)
for i := range zones {
fmt.Println(zones[i])
zones[i] = strings.TrimPrefix(zones[i], redis.keyPrefix)
zones[i] = strings.TrimSuffix(zones[i], redis.keySuffix)
}
redis.LastZoneUpdate = time.Now()
redis.Zones = zones
}
// A :parses A dns record
func (redis *Redis) A(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, a := range record.A {
if a.Ip == nil {
continue
}
r := new(dns.A)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeA,
Class: dns.ClassINET, Ttl: redis.minTtl(a.Ttl)}
r.A = a.Ip
answers = append(answers, r)
}
return
}
// AAAA :parses AAAA dns record
func (redis Redis) AAAA(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, aaaa := range record.AAAA {
if aaaa.Ip == nil {
continue
}
r := new(dns.AAAA)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeAAAA,
Class: dns.ClassINET, Ttl: redis.minTtl(aaaa.Ttl)}
r.AAAA = aaaa.Ip
answers = append(answers, r)
}
return
}
// CNAME :parses CNAME dns record
func (redis *Redis) CNAME(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, cname := range record.CNAME {
if len(cname.Host) == 0 {
continue
}
r := new(dns.CNAME)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeCNAME,
Class: dns.ClassINET, Ttl: redis.minTtl(cname.Ttl)}
r.Target = dns.Fqdn(cname.Host)
answers = append(answers, r)
}
return
}
// TXT :parses TXT dns record
func (redis *Redis) TXT(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, txt := range record.TXT {
if len(txt.Text) == 0 {
continue
}
r := new(dns.TXT)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeTXT,
Class: dns.ClassINET, Ttl: redis.minTtl(txt.Ttl)}
r.Txt = split255(txt.Text)
answers = append(answers, r)
}
return
}
// NS :parses NS dns record
func (redis *Redis) NS(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, ns := range record.NS {
if len(ns.Host) == 0 {
continue
}
r := new(dns.NS)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeNS,
Class: dns.ClassINET, Ttl: redis.minTtl(ns.Ttl)}
r.Ns = ns.Host
answers = append(answers, r)
extras = append(extras, redis.hosts(ns.Host, z)...)
}
return
}
// MX :parses MX dns record
func (redis *Redis) MX(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, mx := range record.MX {
if len(mx.Host) == 0 {
continue
}
r := new(dns.MX)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeMX,
Class: dns.ClassINET, Ttl: redis.minTtl(mx.Ttl)}
r.Mx = mx.Host
r.Preference = mx.Preference
answers = append(answers, r)
extras = append(extras, redis.hosts(mx.Host, z)...)
}
return
}
// SRV :parses SRV dns record
func (redis *Redis) SRV(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
for _, srv := range record.SRV {
if len(srv.Target) == 0 {
continue
}
r := new(dns.SRV)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeSRV,
Class: dns.ClassINET, Ttl: redis.minTtl(srv.Ttl)}
r.Target = srv.Target
r.Weight = srv.Weight
r.Port = srv.Port
r.Priority = srv.Priority
answers = append(answers, r)
extras = append(extras, redis.hosts(srv.Target, z)...)
}
return
}
// SOA :parses SOA dns record
func (redis *Redis) SOA(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
r := new(dns.SOA)
if record.SOA.Ns == "" {
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeSOA,
Class: dns.ClassINET, Ttl: redis.Ttl}
r.Ns = "ns1." + name
r.Mbox = "hostmaster." + name
r.Refresh = 86400
r.Retry = 7200
r.Expire = 3600
r.Minttl = redis.Ttl
} else {
r.Hdr = dns.RR_Header{Name: dns.Fqdn(z.Name), Rrtype: dns.TypeSOA,
Class: dns.ClassINET, Ttl: redis.minTtl(record.SOA.Ttl)}
r.Ns = record.SOA.Ns
r.Mbox = record.SOA.MBox
r.Refresh = record.SOA.Refresh
r.Retry = record.SOA.Retry
r.Expire = record.SOA.Expire
r.Minttl = record.SOA.MinTtl
}
r.Serial = redis.serial()
answers = append(answers, r)
return
}
// CAA :parses CAA dns record
func (redis *Redis) CAA(name string, z *Zone, record *Record) (answers, extras []dns.RR) {
if record == nil {
return
}
for _, caa := range record.CAA {
if caa.Value == "" || caa.Tag == "" {
continue
}
r := new(dns.CAA)
r.Hdr = dns.RR_Header{Name: dns.Fqdn(name), Rrtype: dns.TypeCAA, Class: dns.ClassINET}
r.Flag = caa.Flag
r.Tag = caa.Tag
r.Value = caa.Value
answers = append(answers, r)
}
return
}
// AXFR :parses AXFR dns record
func (redis *Redis) AXFR(z *Zone) (records []dns.RR) {
//soa, _ := redis.SOA(z.Name, z, record)
soa := make([]dns.RR, 0)
answers := make([]dns.RR, 0, 10)
extras := make([]dns.RR, 0, 10)
// Allocate slices for rr Records
records = append(records, soa...)
for key := range z.Locations {
if key == "@" {
location := redis.findLocation(z.Name, z)
record := redis.get(location, z)
soa, _ = redis.SOA(z.Name, z, record)
} else {
fqdnKey := dns.Fqdn(key) + z.Name
var as []dns.RR
var xs []dns.RR
location := redis.findLocation(fqdnKey, z)
record := redis.get(location, z)
// Pull all zone records
as, xs = redis.A(fqdnKey, z, record)
answers = append(answers, as...)
extras = append(extras, xs...)
as, xs = redis.AAAA(fqdnKey, z, record)
answers = append(answers, as...)
extras = append(extras, xs...)
as, xs = redis.CNAME(fqdnKey, z, record)
answers = append(answers, as...)
extras = append(extras, xs...)
as, xs = redis.MX(fqdnKey, z, record)
answers = append(answers, as...)
extras = append(extras, xs...)
as, xs = redis.SRV(fqdnKey, z, record)
answers = append(answers, as...)
extras = append(extras, xs...)
as, xs = redis.TXT(fqdnKey, z, record)
answers = append(answers, as...)
extras = append(extras, xs...)
}
}
records = soa
records = append(records, answers...)
records = append(records, extras...)
records = append(records, soa...)
fmt.Println(records)
return
}
func (redis *Redis) hosts(name string, z *Zone) []dns.RR {
var (
record *Record
answers []dns.RR
)
location := redis.findLocation(name, z)
if location == "" {
return nil
}
record = redis.get(location, z)
a, _ := redis.A(name, z, record)
answers = append(answers, a...)
aaaa, _ := redis.AAAA(name, z, record)
answers = append(answers, aaaa...)
cname, _ := redis.CNAME(name, z, record)
answers = append(answers, cname...)
return answers
}
func (redis *Redis) serial() uint32 {
return uint32(time.Now().Unix())
}
func (redis *Redis) minTtl(ttl uint32) uint32 {
if redis.Ttl == 0 && ttl == 0 {
return defaultTtl
}
if redis.Ttl == 0 {
return ttl
}
if ttl == 0 {
return redis.Ttl
}
if redis.Ttl < ttl {
return redis.Ttl
}
return ttl
}
func (redis *Redis) findLocation(query string, z *Zone) string {
var (
ok bool
closestEncloser, sourceOfSynthesis string
)
// request for zone records
if query == z.Name {
return query
}
query = strings.TrimSuffix(query, "."+z.Name)
if _, ok = z.Locations[query]; ok {
return query
}
closestEncloser, sourceOfSynthesis, ok = splitQuery(query)
for ok {
ceExists := keyMatches(closestEncloser, z) || keyExists(closestEncloser, z)
ssExists := keyExists(sourceOfSynthesis, z)
if ceExists {
if ssExists {
return sourceOfSynthesis
} else {
return ""
}
} else {
closestEncloser, sourceOfSynthesis, ok = splitQuery(closestEncloser)
}
}
return ""
}
func (redis *Redis) get(key string, z *Zone) *Record {
var (
err error
reply interface{}
val string
)
conn := redis.Pool.Get()
if conn == nil {
fmt.Println("error connecting to redis")
return nil
}
defer conn.Close()
var label string
if key == z.Name {
label = "@"
} else {
label = key
}
reply, err = conn.Do("HGET", redis.keyPrefix+z.Name+redis.keySuffix, label)
if err != nil {
return nil
}
val, err = redisCon.String(reply, nil)
if err != nil {
return nil
}
r := new(Record)
err = json.Unmarshal([]byte(val), r)
if err != nil {
fmt.Println("parse error : ", val, err)
return nil
}
return r
}
func keyExists(key string, z *Zone) bool {
_, ok := z.Locations[key]
return ok
}
func keyMatches(key string, z *Zone) bool {
for value := range z.Locations {
if strings.HasSuffix(value, key) {
return true
}
}
return false
}
func splitQuery(query string) (string, string, bool) {
if query == "" {
return "", "", false
}
var (
splits []string
closestEncloser string
sourceOfSynthesis string
)
splits = strings.SplitAfterN(query, ".", 2)
if len(splits) == 2 {
closestEncloser = splits[1]
sourceOfSynthesis = "*." + closestEncloser
} else {
closestEncloser = ""
sourceOfSynthesis = "*"
}
return closestEncloser, sourceOfSynthesis, true
}
// Connect :creates redis connection
func (redis *Redis) Connect() {
redis.Pool = &redisCon.Pool{
Dial: func() (redisCon.Conn, error) {
opts := []redisCon.DialOption{}
if redis.redisPassword != "" {
opts = append(opts, redisCon.DialPassword(redis.redisPassword))
}
if redis.connectTimeout != 0 {
opts = append(opts, redisCon.DialConnectTimeout(time.Duration(redis.connectTimeout)*time.Millisecond))
}
if redis.readTimeout != 0 {
opts = append(opts, redisCon.DialReadTimeout(time.Duration(redis.readTimeout)*time.Millisecond))
}
fmt.Println(redis.redisAddress)
return redisCon.Dial("tcp", redis.redisAddress, opts...)
},
}
}
func (redis *Redis) save(zone string, subdomain string, value string) error {
var err error
conn := redis.Pool.Get()
if conn == nil {
fmt.Println("error connecting to redis")
return nil
}
defer conn.Close()
_, err = conn.Do("HSET", redis.keyPrefix+zone+redis.keySuffix, subdomain, value)
return err
}
func (redis *Redis) load(zone string) *Zone {
var (
reply interface{}
err error
vals []string
)
conn := redis.Pool.Get()
if conn == nil {
fmt.Println("error connecting to redis")
return nil
}
defer conn.Close()
reply, err = conn.Do("HKEYS", redis.keyPrefix+zone+redis.keySuffix)
if err != nil {
return nil
}
z := new(Zone)
z.Name = zone
vals, err = redisCon.Strings(reply, nil)
if err != nil {
return nil
}
z.Locations = make(map[string]struct{})
for _, val := range vals {
z.Locations[val] = struct{}{}
}
return z
}
func split255(s string) []string {
if len(s) < 255 {
return []string{s}
}
sx := []string{}
p, i := 0, 255
for {
if i <= len(s) {
sx = append(sx, s[p:i])
} else {
sx = append(sx, s[p:])
break
}
p, i = p+255, i+255
}
return sx
}
const (
defaultTtl = 360
hostmaster = "hostmaster"
zoneUpdateTime = 10 * time.Minute
transferLength = 1000
)