forked from kenshinx/godns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.go
223 lines (193 loc) · 5.18 KB
/
resolver.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
package main
import (
"bufio"
"fmt"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/miekg/dns"
)
type ResolvError struct {
qname, net string
nameservers []string
}
func (e ResolvError) Error() string {
errmsg := fmt.Sprintf("%s resolv failed on %s (%s)", e.qname, strings.Join(e.nameservers, "; "), e.net)
return errmsg
}
type RResp struct {
msg *dns.Msg
nameserver string
rtt time.Duration
}
type Resolver struct {
servers []string
domain_server *suffixTreeNode
config *ResolvSettings
}
func NewResolver(c ResolvSettings) *Resolver {
r := &Resolver{
servers: []string{},
domain_server: newSuffixTreeRoot(),
config: &c,
}
if len(c.ServerListFile) > 0 {
r.ReadServerListFile(c.ServerListFile)
}
if len(c.ResolvFile) > 0 {
clientConfig, err := dns.ClientConfigFromFile(c.ResolvFile)
if err != nil {
logger.Error(":%s is not a valid resolv.conf file\n", c.ResolvFile)
logger.Error("%s", err)
panic(err)
}
for _, server := range clientConfig.Servers {
nameserver := net.JoinHostPort(server, clientConfig.Port)
r.servers = append(r.servers, nameserver)
}
}
return r
}
func (r *Resolver) parseServerListFile(buf *os.File) {
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "server") {
continue
}
sli := strings.Split(line, "=")
if len(sli) != 2 {
continue
}
line = strings.TrimSpace(sli[1])
tokens := strings.Split(line, "/")
switch len(tokens) {
case 3:
domain := tokens[1]
ip := tokens[2]
if !isDomain(domain) || !isIP(ip) {
continue
}
r.domain_server.sinsert(strings.Split(domain, "."), ip)
case 1:
srv_port := strings.Split(line, "#")
if len(srv_port) > 2 {
continue
}
ip := ""
if ip = srv_port[0]; !isIP(ip) {
continue
}
port := "53"
if len(srv_port) == 2 {
if _, err := strconv.Atoi(srv_port[1]); err != nil {
continue
}
port = srv_port[1]
}
r.servers = append(r.servers, net.JoinHostPort(ip, port))
}
}
}
func (r *Resolver) ReadServerListFile(path string) {
files := strings.Split(path, ";")
for _, file := range files {
buf, err := os.Open(file)
if err != nil {
panic("Can't open " + file)
}
defer buf.Close()
r.parseServerListFile(buf)
}
}
// Lookup will ask each nameserver in top-to-bottom fashion, starting a new request
// in every second, and return as early as possbile (have an answer).
// It returns an error if no request has succeeded.
func (r *Resolver) Lookup(net string, req *dns.Msg) (message *dns.Msg, err error) {
c := &dns.Client{
Net: net,
ReadTimeout: r.Timeout(),
WriteTimeout: r.Timeout(),
}
if net == "udp" && settings.ResolvConfig.SetEDNS0 {
req = req.SetEdns0(65535, true)
}
qname := req.Question[0].Name
res := make(chan *RResp, 1)
var wg sync.WaitGroup
L := func(nameserver string) {
defer wg.Done()
r, rtt, err := c.Exchange(req, nameserver)
if err != nil {
logger.Warn("%s socket error on %s", qname, nameserver)
logger.Warn("error:%s", err.Error())
return
}
// If SERVFAIL happen, should return immediately and try another upstream resolver.
// However, other Error code like NXDOMAIN is an clear response stating
// that it has been verified no such domain existas and ask other resolvers
// would make no sense. See more about #20
if r != nil && r.Rcode != dns.RcodeSuccess {
logger.Warn("%s failed to get an valid answer on %s", qname, nameserver)
if r.Rcode == dns.RcodeServerFailure {
return
}
}
re := &RResp{r, nameserver, rtt}
select {
case res <- re:
default:
}
}
ticker := time.NewTicker(time.Duration(settings.ResolvConfig.Interval) * time.Millisecond)
defer ticker.Stop()
// Start lookup on each nameserver top-down, in every second
nameservers := r.Nameservers(qname)
for _, nameserver := range nameservers {
wg.Add(1)
go L(nameserver)
// but exit early, if we have an answer
select {
case re := <-res:
logger.Debug("%s resolv on %s rtt: %v", UnFqdn(qname), re.nameserver, re.rtt)
return re.msg, nil
case <-ticker.C:
continue
}
}
// wait for all the namservers to finish
wg.Wait()
select {
case re := <-res:
logger.Debug("%s resolv on %s rtt: %v", UnFqdn(qname), re.nameserver, re.rtt)
return re.msg, nil
default:
return nil, ResolvError{qname, net, nameservers}
}
}
// Namservers return the array of nameservers, with port number appended.
// '#' in the name is treated as port separator, as with dnsmasq.
func (r *Resolver) Nameservers(qname string) []string {
queryKeys := strings.Split(qname, ".")
queryKeys = queryKeys[:len(queryKeys)-1] // ignore last '.'
ns := []string{}
if v, found := r.domain_server.search(queryKeys); found {
logger.Debug("%s be found in domain server list, upstream: %v", qname, v)
server := v
nameserver := net.JoinHostPort(server, "53")
ns = append(ns, nameserver)
//Ensure query the specific upstream nameserver in async Lookup() function.
return ns
}
for _, nameserver := range r.servers {
ns = append(ns, nameserver)
}
return ns
}
func (r *Resolver) Timeout() time.Duration {
return time.Duration(r.config.Timeout) * time.Second
}