forked from abh/geodns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
230 lines (180 loc) · 5.11 KB
/
serve.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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/abh/geodns/Godeps/_workspace/src/github.com/miekg/dns"
"github.com/abh/geodns/Godeps/_workspace/src/github.com/rcrowley/go-metrics"
)
func getQuestionName(z *Zone, req *dns.Msg) string {
lx := dns.SplitDomainName(req.Question[0].Name)
ql := lx[0 : len(lx)-z.LabelCount]
return strings.ToLower(strings.Join(ql, "."))
}
func serve(w dns.ResponseWriter, req *dns.Msg, z *Zone) {
qtype := req.Question[0].Qtype
logPrintf("[zone %s] incoming %s %s (id %d) from %s\n", z.Origin, req.Question[0].Name,
dns.TypeToString[qtype], req.Id, w.RemoteAddr())
// Global meter
metrics.Get("queries").(metrics.Meter).Mark(1)
// Zone meter
z.Metrics.Queries.Mark(1)
logPrintln("Got request", req)
label := getQuestionName(z, req)
z.Metrics.LabelStats.Add(label)
// IP that's talking to us (not EDNS CLIENT SUBNET)
var realIP net.IP
if addr, ok := w.RemoteAddr().(*net.UDPAddr); ok {
realIP = make(net.IP, len(addr.IP))
copy(realIP, addr.IP)
} else if addr, ok := w.RemoteAddr().(*net.TCPAddr); ok {
realIP = make(net.IP, len(addr.IP))
copy(realIP, addr.IP)
}
z.Metrics.ClientStats.Add(realIP.String())
var ip net.IP // EDNS or real IP
var edns *dns.EDNS0_SUBNET
var opt_rr *dns.OPT
for _, extra := range req.Extra {
switch extra.(type) {
case *dns.OPT:
for _, o := range extra.(*dns.OPT).Option {
opt_rr = extra.(*dns.OPT)
switch e := o.(type) {
case *dns.EDNS0_NSID:
// do stuff with e.Nsid
case *dns.EDNS0_SUBNET:
z.Metrics.EdnsQueries.Mark(1)
logPrintln("Got edns", e.Address, e.Family, e.SourceNetmask, e.SourceScope)
if e.Address != nil {
edns = e
ip = e.Address
}
}
}
}
}
if len(ip) == 0 { // no edns subnet
ip = realIP
}
targets, netmask := z.Options.Targeting.GetTargets(ip)
m := new(dns.Msg)
m.SetReply(req)
if e := m.IsEdns0(); e != nil {
m.SetEdns0(4096, e.Do())
}
m.Authoritative = true
// TODO: set scope to 0 if there are no alternate responses
if edns != nil {
if edns.Family != 0 {
if netmask < 16 {
netmask = 16
}
edns.SourceScope = uint8(netmask)
m.Extra = append(m.Extra, opt_rr)
}
}
labels, labelQtype := z.findLabels(label, targets, qTypes{dns.TypeMF, dns.TypeCNAME, qtype})
if labelQtype == 0 {
labelQtype = qtype
}
if labels == nil {
permitDebug := !*flagPrivateDebug || (realIP != nil && realIP.IsLoopback())
firstLabel := (strings.Split(label, "."))[0]
if permitDebug && firstLabel == "_status" {
if qtype == dns.TypeANY || qtype == dns.TypeTXT {
m.Answer = statusRR(label + "." + z.Origin + ".")
} else {
m.Ns = append(m.Ns, z.SoaRR())
}
m.Authoritative = true
w.WriteMsg(m)
return
}
if firstLabel == "_country" {
if qtype == dns.TypeANY || qtype == dns.TypeTXT {
h := dns.RR_Header{Ttl: 1, Class: dns.ClassINET, Rrtype: dns.TypeTXT}
h.Name = label + "." + z.Origin + "."
txt := []string{
w.RemoteAddr().String(),
ip.String(),
}
targets, netmask := z.Options.Targeting.GetTargets(ip)
txt = append(txt, strings.Join(targets, " "))
txt = append(txt, fmt.Sprintf("/%d", netmask), serverID, serverIP)
m.Answer = []dns.RR{&dns.TXT{Hdr: h,
Txt: txt,
}}
} else {
m.Ns = append(m.Ns, z.SoaRR())
}
m.Authoritative = true
w.WriteMsg(m)
return
}
// return NXDOMAIN
m.SetRcode(req, dns.RcodeNameError)
m.Authoritative = true
m.Ns = []dns.RR{z.SoaRR()}
w.WriteMsg(m)
return
}
if servers := labels.Picker(labelQtype, labels.MaxHosts); servers != nil {
var rrs []dns.RR
for _, record := range servers {
rr := dns.Copy(record.RR)
rr.Header().Name = req.Question[0].Name
rrs = append(rrs, rr)
}
m.Answer = rrs
}
if len(m.Answer) == 0 {
m.Ns = append(m.Ns, z.SoaRR())
}
logPrintln(m)
err := w.WriteMsg(m)
if err != nil {
// if Pack'ing fails the Write fails. Return SERVFAIL.
log.Println("Error writing packet", m)
dns.HandleFailed(w, req)
}
return
}
func statusRR(label string) []dns.RR {
h := dns.RR_Header{Ttl: 1, Class: dns.ClassINET, Rrtype: dns.TypeTXT}
h.Name = label
status := map[string]string{"v": VERSION, "id": serverID}
hostname, err := os.Hostname()
if err == nil {
status["h"] = hostname
}
qCounter := metrics.Get("queries").(metrics.Meter)
status["up"] = strconv.Itoa(int(time.Since(timeStarted).Seconds()))
status["qs"] = strconv.FormatInt(qCounter.Count(), 10)
status["qps1"] = fmt.Sprintf("%.4f", qCounter.Rate1())
js, err := json.Marshal(status)
return []dns.RR{&dns.TXT{Hdr: h, Txt: []string{string(js)}}}
}
func setupServerFunc(Zone *Zone) func(dns.ResponseWriter, *dns.Msg) {
return func(w dns.ResponseWriter, r *dns.Msg) {
serve(w, r, Zone)
}
}
func listenAndServe(ip string) {
prots := []string{"udp", "tcp"}
for _, prot := range prots {
go func(p string) {
server := &dns.Server{Addr: ip, Net: p}
log.Printf("Opening on %s %s", ip, p)
if err := server.ListenAndServe(); err != nil {
log.Fatalf("geodns: failed to setup %s %s: %s", ip, p, err)
}
log.Fatalf("geodns: ListenAndServe unexpectedly returned")
}(prot)
}
}