-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghandler.go
104 lines (92 loc) · 1.87 KB
/
ghandler.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
package ghandler
import (
"fmt"
"log"
"sync"
"time"
"github.com/miekg/dns"
"github.com/mlctrez/googledns"
)
func New() *DnsServer {
d := &DnsServer{
gdns: googledns.New(),
cache: make(map[string]*CachedQuery),
cacheMutex: &sync.Mutex{},
}
go d.purgeCache()
return d
}
type CachedQuery struct {
Expires time.Time
Answers []dns.RR
}
type DnsServer struct {
gdns *googledns.Gdns
cache map[string]*CachedQuery
cacheMutex *sync.Mutex
}
func lowestTtl(ans []dns.RR) time.Duration {
var lowest uint32
for _, a := range ans {
if lowest == 0 || a.Header().Ttl < lowest {
lowest = a.Header().Ttl
}
}
return time.Duration(lowest)
}
func (d *DnsServer) purgeCache() {
ticker := time.NewTicker(time.Second * 10)
for range ticker.C {
for k, v := range d.cache {
if v.Expires.Before(time.Now()) {
d.cacheMutex.Lock()
delete(d.cache, k)
d.cacheMutex.Unlock()
}
}
}
}
func (d *DnsServer) cacheAnswer(query string, ans []dns.RR) (result []dns.RR) {
if len(ans) > 0 {
d.cacheMutex.Lock()
defer d.cacheMutex.Unlock()
loTtl := lowestTtl(ans)
if loTtl < 10 {
loTtl = 10
}
for _, a := range ans {
a.Header().Ttl = uint32(loTtl)
}
d.cache[query] = &CachedQuery{
Expires: time.Now().Add(loTtl * time.Second),
Answers: ans,
}
return ans
}
return ans
}
func (d *DnsServer) Handler(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
m.Answer = make([]dns.RR, 0)
for _, q := range r.Question {
cr := d.cache[q.String()]
if cr != nil {
if cr.Expires.After(time.Now()) {
m.Answer = append(m.Answer, cr.Answers...)
continue
}
delete(d.cache, q.String())
}
ans, err := d.gdns.Query(q)
if err == nil {
m.Answer = append(m.Answer, d.cacheAnswer(q.String(), ans)...)
} else {
fmt.Println(err)
}
}
err := w.WriteMsg(m)
if err != nil {
log.Println("error", err)
}
}