-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
112 lines (96 loc) · 2.04 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
package main
import (
"flag"
"os"
"os/signal"
"strings"
"syscall"
"github.com/BurntSushi/toml"
"github.com/coreos/go-log/log"
"github.com/miekg/dns"
)
// Config contains name server rules
type Config struct {
DefaultServer string
Servers map[string][]string
}
var (
defaultServer string
rules map[string]string
)
func init() {
cfgFile := flag.String("c", "", "Config file")
flag.Parse()
config := Config{}
if _, err := toml.DecodeFile(*cfgFile, &config); err != nil {
log.Fatalln(err)
return
}
if config.DefaultServer == "" {
log.Fatalln("Empty defaultServer in", *cfgFile)
}
defaultServer = config.DefaultServer
rules = map[string]string{}
for k, v := range config.Servers {
for _, domain := range v {
rules[domain+"."] = k
}
}
}
func main() {
log.Println("Starting")
tcpSrv := &dns.Server{
Addr: "127.0.0.1:53",
Net: "tcp",
Handler: dns.HandlerFunc(
func(w dns.ResponseWriter, m *dns.Msg) {
handler(w, m, &dns.Client{Net: "tcp"})
},
),
}
udpSrv := &dns.Server{
Addr: "127.0.0.1:53",
Net: "udp",
Handler: dns.HandlerFunc(
func(w dns.ResponseWriter, m *dns.Msg) {
handler(w, m, &dns.Client{Net: "udp"})
},
),
}
go func() {
if err := tcpSrv.ListenAndServe(); err != nil {
log.Fatalln(err)
}
}()
go func() {
if err := udpSrv.ListenAndServe(); err != nil {
log.Fatalln(err)
}
}()
sig := make(chan os.Signal)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
log.Println("\nStopping...")
if err := tcpSrv.Shutdown(); err != nil {
log.Error("Error while stopping tcp server:", err)
}
if err := udpSrv.Shutdown(); err != nil {
log.Error("Error while stopping udp server:", err)
}
}
func handler(w dns.ResponseWriter, m *dns.Msg, c *dns.Client) {
ip := defaultServer
for domain, newIP := range rules {
if strings.HasSuffix(m.Question[0].Name, domain) {
ip = newIP
break
}
}
log.Debugf("Lookup %s from %s\n", m.Question[0].Name, ip)
r, _, err := c.Exchange(m, ip+":53")
if err != nil {
log.Error(err)
return
}
w.WriteMsg(r)
}