-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
90 lines (85 loc) · 1.9 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
package main
import (
"fmt"
"log"
"os"
"github.com/miekg/dns"
)
func parseQuery(m *dns.Msg, qdns *QuickDNSResolver) {
for _, q := range m.Question {
println("Query: ", q.Name, q.Qtype, q.Qclass)
switch q.Qtype {
case dns.TypeNone:
fallthrough
case dns.TypeANY:
fallthrough
case dns.TypeNS:
{
// ns1.swiftwave.xyz and ns2.swiftwave.xyz
rr, err := dns.NewRR(fmt.Sprintf("%s NS ns1.swiftwave.xyz", q.Name))
if err == nil {
m.Answer = append(m.Answer, rr)
}
rr, err = dns.NewRR(fmt.Sprintf("%s NS ns2.swiftwave.xyz", q.Name))
if err == nil {
m.Answer = append(m.Answer, rr)
}
}
case dns.TypeA:
{
isQDNS, ip := qdns.ResolveARecord(q.Name)
if isQDNS {
rr, err := dns.NewRR(fmt.Sprintf("%s A %s", q.Name, ip))
if err == nil {
m.Answer = append(m.Answer, rr)
}
}
}
}
}
}
func handleDnsRequest(w dns.ResponseWriter, r *dns.Msg, qdns *QuickDNSResolver) {
m := new(dns.Msg)
m.SetReply(r)
m.Compress = false
switch r.Opcode {
case dns.OpcodeQuery:
parseQuery(m, qdns)
}
_ = w.WriteMsg(m)
}
func main() {
// create quick dns resolver
qdns, err := NewQuickDNSResolver()
if err != nil {
panic(err)
}
// attach request handler func
dns.HandleFunc(".", func(w dns.ResponseWriter, m *dns.Msg) {
handleDnsRequest(w, m, qdns)
})
// start server
address := os.Getenv("ADDRESS")
if address == "" {
address = "0.0.0.0"
log.Printf("Defaulting to address %s", address)
}
port := os.Getenv("PORT")
if port == "" {
port = "53"
log.Printf("Defaulting to port %s", port)
}
server := &dns.Server{Addr: ":" + port, Net: "udp"}
log.Printf("Starting at %s\n", port)
err = server.ListenAndServe()
if err != nil {
log.Fatalf("Failed to start server: %s\n ", err.Error())
}
// defer shutdown
defer func() {
err := server.Shutdown()
if err != nil {
log.Fatalf("Failed to shutdown server: %s\n ", err.Error())
}
}()
}