forked from sipt/shuttle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdns.go
304 lines (281 loc) · 5.75 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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package shuttle
import (
"bytes"
"fmt"
"net"
"strings"
"sync"
"time"
"github.com/miekg/dns"
)
const (
DNSTypeStatic = "static"
DNSTypeDirect = "direct"
DNSTypeRemote = "remote"
DNSTypeCache = "cache"
)
type DomainHost struct {
IP net.IP
Country string
DNS net.IP
RemoteResolve bool
}
type DNS struct {
MatchType string `json:",omitempty"`
Domain string
IPs []net.IP
DNSs []net.IP
Type string `json:",omitempty"`
Country string
}
func (d *DNS) String() string {
buffer := bytes.NewBufferString(d.Domain)
buffer.WriteString(" IPs:[")
for i, v := range d.IPs {
if i > 0 {
buffer.WriteString(",")
}
buffer.WriteString(v.String())
}
buffer.WriteString("] DNSs:[")
for i, v := range d.DNSs {
if i > 0 {
buffer.WriteString(",")
}
buffer.WriteString(v.String())
}
buffer.WriteString("] Country:[" + d.Country + "]")
return buffer.String()
}
type _Reply struct {
DNS net.IP
Msg *dns.Msg
}
var (
_DNS []net.IP
_LocalDNS []*DNS
_CacheDNS IDNSCache
)
func InitDNS(dns []net.IP, localDNS []*DNS) error {
_DNS = dns
_LocalDNS = localDNS
if _CacheDNS == nil {
_CacheDNS = NewDefaultDNSCache()
}
_CacheDNS.Init()
for _, v := range _LocalDNS {
if v.Type == DNSTypeStatic {
_CacheDNS.Push(v)
}
}
return nil
}
//清除DNS缓存
func ClearDNSCache() {
_CacheDNS.Clear()
for _, v := range _LocalDNS {
if v.Type == DNSTypeStatic {
_CacheDNS.Push(v)
}
}
}
//DNS缓存列表
func DNSCacheList() []*DNS {
return _CacheDNS.List()
}
func ResolveDomain(req *Request) error {
if req.IP = net.ParseIP(req.Addr); len(req.IP) != 0 {
return nil
}
//DomainHost
temp := _LocalDNS
for _, v := range temp {
switch v.MatchType {
case RuleDomainSuffix:
if strings.HasSuffix(req.Addr, v.Domain) {
Logger.Debug("[DNS] [Local] ", v.String())
return localResolve(v, req)
}
case RuleDomain:
if req.Addr == v.Domain {
Logger.Debug("[DNS] [Local] ", v.String())
return localResolve(v, req)
}
case RuleDomainKeyword:
if strings.Index(req.Addr, v.Domain) >= 0 {
Logger.Debug("[DNS] [Local] ", v.String())
return localResolve(v, req)
}
}
}
d := _CacheDNS.Pop(req.Addr)
if d != nil {
Logger.Debug("[DNS] [Cache] ", d.String())
return localResolve(d, req)
}
return directResolve(_DNS, req)
}
func localResolve(dns *DNS, req *Request) error {
switch dns.Type {
case DNSTypeStatic, DNSTypeCache:
if len(req.IP) >= len(dns.IPs[0]) {
req.IP = req.IP[:len(dns.IPs[0])]
} else {
req.IP = make([]byte, len(dns.IPs[0]))
}
copy(req.IP, dns.IPs[0])
req.DomainHost.Country = dns.Country
if len(dns.DNSs) > 0 {
req.DomainHost.DNS = dns.DNSs[0]
}
return nil
case DNSTypeDirect:
//直连DNS解析
return directResolve(dns.DNSs, req)
case DNSTypeRemote:
//remote 到proxy-server上解析
//remoteResolve(dns, req)
Logger.Debug("[DNS] [Remote] ", req.Addr)
return nil
default:
return fmt.Errorf("not support DNSType [%s]", dns.Type)
}
}
func directResolve(servers []net.IP, req *Request) error {
reply := make(chan *_Reply, 1)
for _, v := range servers {
go func(v net.IP) {
err := resolveDomain(req, v, reply)
if err != nil {
Logger.Errorf("[DNS] [%s] failed: %v", req.Addr, err)
}
}(v)
}
r := <-reply
var (
a *dns.A
ok bool
cache = &DNS{
Domain: req.Addr,
IPs: make([]net.IP, 0),
DNSs: []net.IP{r.DNS},
Type: DNSTypeCache,
}
)
for _, v := range r.Msg.Answer {
a, ok = v.(*dns.A)
if ok {
cache.IPs = append(cache.IPs, net.ParseIP(a.A.String()))
}
}
if len(cache.IPs) == 0 {
Logger.Errorf("[DNS] resolve ip is empty")
return nil
}
req.IP = cache.IPs[0]
_CacheDNS.Push(cache)
country := GeoLookUp(req.IP)
cache.Country = country
req.DomainHost.Country = country
req.DomainHost.DNS = r.DNS
Logger.Debug("[DNS] ", cache.String())
return nil
}
func resolveDomain(req *Request, s net.IP, c chan *_Reply) (err error) {
conn, err := DirectConn(&Request{
Cmd: CmdUDP,
IP: s,
Port: 53,
})
if err != nil {
return err
}
m := &dns.Msg{}
m.SetQuestion(dns.Fqdn(req.Addr), dns.TypeA)
m.RecursionDesired = true
conn, err = RealTimeDecorate(conn)
if err != nil {
return err
}
co := &dns.Conn{Conn: conn} // c is your net.Conn
co.WriteMsg(m)
r, err := co.ReadMsg()
co.Close()
if err != nil {
return err
}
if r == nil || r.Rcode != dns.RcodeSuccess {
return fmt.Errorf("resolve domain [%s] failed", req.Addr)
}
select {
case c <- &_Reply{DNS: s, Msg: r}:
default:
}
return
}
func NewDefaultDNSCache() IDNSCache {
r := &DefaultDNSCache{}
return r
}
type IDNSCache interface {
Init()
Push(*DNS)
Pop(string) *DNS
Clear()
List() []*DNS
}
type CacheNode struct {
v *DNS
t time.Time
}
type DefaultDNSCache struct {
vs []*CacheNode
rw *sync.RWMutex
duration time.Duration
}
func (d *DefaultDNSCache) Init() {
d.rw = &sync.RWMutex{}
d.vs = make([]*CacheNode, 0, 16)
d.duration = 10 * time.Minute // DNS缓存: 60s
}
func (d *DefaultDNSCache) Push(dns *DNS) {
temp := d.Pop(dns.Domain)
if temp == nil {
d.rw.Lock()
d.vs = append(d.vs, &CacheNode{dns, time.Now().Add(d.duration)})
d.rw.Unlock()
}
}
func (d *DefaultDNSCache) Pop(domain string) *DNS {
d.rw.Lock()
defer d.rw.Unlock()
temp := d.vs
for i, v := range temp {
if v.v.Domain == domain {
if v.t.Before(time.Now()) {
if d.vs[i].v.Domain == v.v.Domain && d.vs[i].t.Before(time.Now()) {
d.vs[i] = d.vs[len(d.vs)-1]
d.vs = d.vs[:len(d.vs)-1]
}
return nil
}
return temp[i].v
}
}
return nil
}
func (d *DefaultDNSCache) Clear() {
d.rw.Lock()
d.vs = d.vs[:0]
d.rw.Unlock()
}
func (d *DefaultDNSCache) List() []*DNS {
reply := make([]*DNS, len(d.vs))
d.rw.RLock()
for i := range d.vs {
v := *(d.vs[i].v)
reply[i] = &v
}
d.rw.RUnlock()
return reply
}