-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
202 lines (163 loc) · 4.11 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"log"
"math"
"net"
"net/http"
"os"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/miekg/dns"
)
var buildString string
type env struct {
cache *lru.Cache
cfg Config
client DNSClient
}
func main() {
cfgPath := flag.String("config", "config.toml", "Path to config file")
version := flag.Bool("version", false, "Version")
flag.Parse()
if *version {
fmt.Println(buildString)
os.Exit(0)
}
cfg, err := initConfig(*cfgPath)
if err != nil {
log.Fatalf("error reading config: %v", err)
}
maxCacheItems := 512
if cfg.Cache.MaxItems != 0 {
maxCacheItems = cfg.Cache.MaxItems
}
e := env{
cfg: cfg,
}
// Initialize cache
if cfg.Cache.Cache {
cache, err := lru.New(maxCacheItems)
if err != nil {
log.Fatalln("Couldn't create cache: ", err)
}
e.cache = cache
}
// Make a dialer which resolves url with bootstrap address.
dialer := &net.Dialer{
Resolver: &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: 5 * time.Second,
}
return d.DialContext(ctx, "udp", cfg.BootstrapAddress)
},
},
}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
}
var (
client DNSClient
)
switch cfg.Resolver.Type {
case "doh":
client, err = getDOHDnsClient(dialContext, cfg)
if err != nil {
log.Fatalf("Couldn't create DNS client: %v", err)
}
e.client = client
case "dot":
client, err = NewDOTClient(cfg.Resolver.Urls, dialer, cfg.Log.LogQueries)
if err != nil {
log.Fatalf("Couldn't create DNS client: %v", err)
}
e.client = client
case "dnscrypt":
client, err := NewDNSCryptClient(cfg.Resolver.Urls, cfg.Log.LogQueries)
if err != nil {
log.Fatalf("Couldn't create DNSCrypt client: %v", err)
}
e.client = client
}
// Start the DNS server.
dnsServer := &dns.Server{Addr: cfg.BindAddress, Net: "udp"}
dns.HandleFunc(".", e.handleDNS)
log.Fatalln(dnsServer.ListenAndServe())
}
func (e *env) handleDNS(w dns.ResponseWriter, r *dns.Msg) {
if len(r.Question) == 0 {
return
}
if e.cfg.Log.LogQueries {
log.Println("Got DNS query for ", r.Question[0].String())
}
cacheKey := r.Question[0].String()
// Check if we should check cache or not
if !e.cfg.Cache.Cache {
e.getAndSendResponse(w, r, cacheKey)
return
}
// Check if the key is already in cache
val, ok := e.cache.Get(cacheKey)
if !ok {
e.getAndSendResponse(w, r, cacheKey)
return
}
cResp := val.(DNSInCache)
// Check if this record is expired
ttl := minTTL(cResp.Msg)
if time.Since(cResp.CreatedAt) > ttl {
e.getAndSendResponse(w, r, cacheKey)
return
}
resp := cResp.Msg
resp.MsgHdr.Id = r.MsgHdr.Id
w.WriteMsg(adjustTTL(resp, cResp.CreatedAt))
}
func (e *env) getAndSendResponse(w dns.ResponseWriter, r *dns.Msg, cacheKey string) {
respMsg, err := e.client.GetDNSResponse(r)
if err != nil {
log.Printf("Something wrong with resp: %v", err)
return
}
// Put it in cache
if e.cfg.Cache.Cache {
dnsCache := DNSInCache{Msg: respMsg, CreatedAt: time.Now()}
e.cache.Add(cacheKey, dnsCache)
}
w.WriteMsg(respMsg)
}
func minTTL(m *dns.Msg) time.Duration {
if len(m.Answer) >= 1 {
ttl := m.Answer[0].Header().Ttl
for _, a := range m.Answer {
if a.Header().Ttl < ttl {
ttl = a.Header().Ttl
}
}
return time.Duration(ttl) * time.Second
}
return 0
}
func adjustTTL(m *dns.Msg, createdAt time.Time) *dns.Msg {
adj := *m
for i := 0; i < len(m.Answer); i++ {
expiresAt := createdAt.Add(time.Duration(m.Answer[i].Header().Ttl) * time.Second)
ttl := math.Round(time.Until(expiresAt).Seconds())
adj.Answer[i].Header().Ttl = uint32(ttl)
}
return &adj
}
func getDOHDnsClient(dialContext func(ctx context.Context, network string, addr string) (net.Conn, error), cfg Config) (DNSClient, error) {
transport := http.DefaultTransport.(*http.Transport)
transport.DialContext = dialContext
httpClient := &http.Client{
Timeout: 10 * time.Second,
Transport: transport,
}
return NewDOHClient(httpClient, cfg.Resolver.Urls, cfg.Log.LogQueries)
}