-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdns.go
64 lines (56 loc) · 1.39 KB
/
dns.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
package main
import (
"flag"
"fmt"
"log"
"strings"
"github.com/miekg/dns"
)
func rr(name, qtype, value string) dns.RR {
r, _ := dns.NewRR(fmt.Sprintf("%s 1 %s %s", name, strings.ToUpper(qtype), value))
return r
}
func main() {
port := flag.String("p", "53", "bind to [addr:]port")
zone := flag.String("z", ".", "zone")
flag.Parse()
records := map[string][]dns.RR{}
for _, v := range flag.Args() {
r := strings.SplitN(v, ":", 3)
if len(r) == 3 { // name:type:value
if !strings.HasSuffix(r[0], ".") {
r[0] = r[0] + "." + *zone
}
records[r[0]] = append(records[r[0]], rr(r[0], r[1], r[2]))
} else {
log.Printf("unknown record %s", v)
}
}
dns.HandleFunc(*zone, func(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
switch r.Opcode {
case dns.OpcodeQuery:
for _, q := range m.Question {
log.Printf("query %s %d\n", q.Name, q.Qtype)
for _, rr := range records[strings.ToLower(q.Name)] {
if rr.Header().Rrtype == q.Qtype {
log.Printf("RR %v\n", rr)
m.Answer = append(m.Answer, rr)
}
}
}
}
w.WriteMsg(m)
})
if ! strings.Contains(*port, ":") {
*port = ":" + *port
}
server := &dns.Server{Addr: *port, Net: "udp"}
log.Printf("Start DNS Server at %s %v\n", *port, records)
err := server.ListenAndServe()
defer server.Shutdown()
if err != nil {
log.Fatalf("Failed to start server: %s", err.Error())
}
}