-
Notifications
You must be signed in to change notification settings - Fork 4
/
ratelimitedserver.go
99 lines (71 loc) · 1.8 KB
/
ratelimitedserver.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
package resolvermt
import (
"strings"
"time"
"github.com/miekg/dns"
"go.uber.org/ratelimit"
)
type rateLimitedServer struct {
limiter ratelimit.Limiter
ipAddrPort string
pool pool
}
type pool interface {
Get() (*dns.Client, *dns.Conn, error)
Return(conn *dns.Conn)
Close()
}
type server interface {
Query(query string, rrtype RRtype) (*dns.Msg, time.Duration, error)
Close()
}
func newRateLimitedServerList(ipAddrPort []string, queriesPerSecond int) []server {
list := []server{}
for i := range ipAddrPort {
server, err := newRateLimitedServer(ipAddrPort[i], queriesPerSecond)
if err != nil {
continue
}
list = append(list, server)
}
return list
}
func newRateLimitedServer(IPAddrPort string, queriesPerSecond int) (*rateLimitedServer, error) {
if !strings.Contains(IPAddrPort, ":") {
IPAddrPort += ":53"
}
server := rateLimitedServer{}
server.limiter = ratelimit.New(queriesPerSecond, ratelimit.WithoutSlack)
server.ipAddrPort = IPAddrPort
pool, err := newConnectionPool(1, queriesPerSecond, IPAddrPort)
if err != nil {
return nil, err
}
server.pool = pool
return &server, nil
}
func (s *rateLimitedServer) Query(query string, rrtype RRtype) (*dns.Msg, time.Duration, error) {
msg := new(dns.Msg)
msg.Id = s.newID()
msg.RecursionDesired = true
msg.Question = make([]dns.Question, 1)
msg.Question[0] = dns.Question{Name: query + ".", Qtype: uint16(rrtype), Qclass: dns.ClassINET}
s.limiter.Take()
client, conn, err := s.pool.Get()
if err != nil {
return nil, 0, err
}
msg, dur, err := client.ExchangeWithConn(msg, conn)
s.pool.Return(conn)
return msg, dur, err
}
func (s *rateLimitedServer) Close() {
s.pool.Close()
}
func (s *rateLimitedServer) newID() uint16 {
return uint16(randID.Int31())
}
var randID *saferand
func init() {
randID = newSafeRand(true)
}