-
Notifications
You must be signed in to change notification settings - Fork 6
/
manager.go
executable file
·370 lines (314 loc) · 7.94 KB
/
manager.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"os"
"path/filepath"
"sync"
"time"
"github.com/miekg/dns"
"github.com/Qitmeer/qitmeer/core/protocol"
)
// Node Peer
type Node struct {
IP net.IP
Services protocol.ServiceFlag
LastAttempt time.Time
LastSuccess time.Time
LastSeen time.Time
}
// Manager node mgr
type Manager struct {
mtx sync.RWMutex
nodes map[string]*Node
wg sync.WaitGroup
quit chan struct{}
peersFile string
}
const (
// defaultMaxAddresses is the maximum number of addresses to return.
defaultMaxAddresses = 16
// defaultStaleTimeout is the time in which a host is considered
// stale.
defaultStaleTimeout = time.Hour
// dumpAddressInterval is the interval used to dump the address
// cache to disk for future use.
dumpAddressInterval = time.Second * 30
// peersFilename is the name of the file.
peersFilename = "nodes.json"
// pruneAddressInterval is the interval used to run the address
// pruner.
pruneAddressInterval = time.Minute * 1
// pruneExpireTimeout is the expire time in which a node is
// considered dead.
pruneExpireTimeout = time.Hour * 8
)
var (
// rfc1918Nets specifies the IPv4 private address blocks as defined by
// by RFC1918 (10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16).
rfc1918Nets = []net.IPNet{
ipNet("10.0.0.0", 8, 32),
ipNet("172.16.0.0", 12, 32),
ipNet("192.168.0.0", 16, 32),
}
// rfc3964Net specifies the IPv6 to IPv4 encapsulation address block as
// defined by RFC3964 (2002::/16).
rfc3964Net = ipNet("2002::", 16, 128)
// rfc4380Net specifies the IPv6 teredo tunneling over UDP address block
// as defined by RFC4380 (2001::/32).
rfc4380Net = ipNet("2001::", 32, 128)
// rfc4843Net specifies the IPv6 ORCHID address block as defined by
// RFC4843 (2001:10::/28).
rfc4843Net = ipNet("2001:10::", 28, 128)
// rfc4862Net specifies the IPv6 stateless address autoconfiguration
// address block as defined by RFC4862 (FE80::/64).
rfc4862Net = ipNet("FE80::", 64, 128)
// rfc4193Net specifies the IPv6 unique local address block as defined
// by RFC4193 (FC00::/7).
rfc4193Net = ipNet("FC00::", 7, 128)
)
// ipNet returns a net.IPNet struct given the passed IP address string, number
// of one bits to include at the start of the mask, and the total number of bits
// for the mask.
func ipNet(ip string, ones, bits int) net.IPNet {
return net.IPNet{IP: net.ParseIP(ip), Mask: net.CIDRMask(ones, bits)}
}
func isRoutable(addr net.IP) bool {
for _, n := range rfc1918Nets {
if n.Contains(addr) {
return false
}
}
if rfc3964Net.Contains(addr) ||
rfc4380Net.Contains(addr) ||
rfc4843Net.Contains(addr) ||
rfc4862Net.Contains(addr) ||
rfc4193Net.Contains(addr) {
return false
}
return true
}
// NewManager make mgr
func NewManager(dataDir string) (*Manager, error) {
err := os.MkdirAll(dataDir, 0700)
if err != nil {
return nil, err
}
amgr := Manager{
nodes: make(map[string]*Node),
peersFile: filepath.Join(dataDir, peersFilename),
quit: make(chan struct{}),
}
err = amgr.deserializePeers()
if err != nil {
log.Printf("Failed to parse file %s: %v", amgr.peersFile, err)
// if it is invalid we nuke the old one unconditionally.
err = os.Remove(amgr.peersFile)
if err != nil {
log.Printf("Failed to remove corrupt peers file %s: %v",
amgr.peersFile, err)
}
}
go amgr.addressHandler()
return &amgr, nil
}
// AddAddresses add addresses
func (m *Manager) AddAddresses(addrs []net.IP) int {
var count int
m.mtx.Lock()
for _, addr := range addrs {
if !isRoutable(addr) {
continue
}
addrStr := addr.String()
_, exists := m.nodes[addrStr]
if exists {
m.nodes[addrStr].LastSeen = time.Now()
continue
}
node := Node{
IP: addr,
LastSeen: time.Now(),
Services:protocol.Full,
}
m.nodes[addrStr] = &node
count++
}
m.mtx.Unlock()
return count
}
// Addresses returns IPs that need to be tested again.
func (m *Manager) Addresses() []net.IP {
addrs := make([]net.IP, 0, defaultMaxAddresses*8)
now := time.Now()
i := defaultMaxAddresses
m.mtx.RLock()
for _, node := range m.nodes {
if i == 0 {
break
}
if (!node.LastSuccess.IsZero() && now.Sub(node.LastSuccess) < defaultStaleTimeout) ||
(!node.LastAttempt.IsZero() &&now.Sub(node.LastAttempt) < defaultStaleTimeout) {
continue
}
addrs = append(addrs, node.IP)
i--
}
m.mtx.RUnlock()
return addrs
}
// GoodAddresses returns good working IPs that match both the
// passed DNS query type and have the requested services.
func (m *Manager) GoodAddresses(qtype uint16, services protocol.ServiceFlag) []net.IP {
addrs := make([]net.IP, 0, defaultMaxAddresses)
i := defaultMaxAddresses
if qtype != dns.TypeA && qtype != dns.TypeAAAA {
return addrs
}
now := time.Now()
m.mtx.RLock()
for _, node := range m.nodes {
if i == 0 {
break
}
if qtype == dns.TypeA && node.IP.To4() == nil {
continue
} else if qtype == dns.TypeAAAA && node.IP.To4() != nil {
continue
}
if node.LastSuccess.IsZero() ||
now.Sub(node.LastSuccess) > defaultStaleTimeout {
//test
if len(m.nodes) > 5 {
continue
}
}
// Does the node have the requested services?
if node.Services&services != services {
continue
}
addrs = append(addrs, node.IP)
i--
}
m.mtx.RUnlock()
return addrs
}
// Attempt ip exist
func (m *Manager) Attempt(ip net.IP) {
m.mtx.Lock()
node, exists := m.nodes[ip.String()]
if exists {
node.LastAttempt = time.Now()
}
m.mtx.Unlock()
}
// Good add good ip
func (m *Manager) Good(ip net.IP, services protocol.ServiceFlag) {
m.mtx.Lock()
node, exists := m.nodes[ip.String()]
if exists {
node.Services = services
node.LastSuccess = time.Now()
}
m.mtx.Unlock()
}
// addressHandler is the main handler for the address manager. It must be run
// as a goroutine.
func (m *Manager) addressHandler() {
pruneAddressTicker := time.NewTicker(pruneAddressInterval)
defer pruneAddressTicker.Stop()
dumpAddressTicker := time.NewTicker(dumpAddressInterval)
defer dumpAddressTicker.Stop()
out:
for {
select {
case <-dumpAddressTicker.C:
m.savePeers()
case <-pruneAddressTicker.C:
m.prunePeers()
case <-m.quit:
break out
}
}
m.savePeers()
m.wg.Done()
}
func (m *Manager) prunePeers() {
var count int
now := time.Now()
m.mtx.Lock()
defer m.mtx.Unlock()
//debug
if len(m.nodes) < 5 {
log.Println("Pruned return: len(m.nodes) < 5", len(m.nodes))
log.Println(m.nodes)
return
}
for k, node := range m.nodes {
if now.Sub(node.LastSeen) > pruneExpireTimeout {
delete(m.nodes, k)
count++
continue
}
if !node.LastSuccess.IsZero() &&
now.Sub(node.LastSuccess) > pruneExpireTimeout {
delete(m.nodes, k)
count++
continue
}
}
l := len(m.nodes)
//m.mtx.Unlock()
log.Printf("Pruned %d addresses: %d remaining", count, l)
}
func (m *Manager) deserializePeers() error {
filePath := m.peersFile
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
return nil
}
r, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("%s error opening file: %v", filePath, err)
}
//noinspection GoUnhandledErrorResult
defer r.Close()
var nodes map[string]*Node
dec := json.NewDecoder(r)
err = dec.Decode(&nodes)
if err != nil {
return fmt.Errorf("error reading %s: %v", filePath, err)
}
l := len(nodes)
m.mtx.Lock()
m.nodes = nodes
m.mtx.Unlock()
log.Printf("%d nodes loaded", l)
return nil
}
func (m *Manager) savePeers() {
m.mtx.RLock()
defer m.mtx.RUnlock()
// Write temporary peers file and then move it into place.
tmpfile := m.peersFile + ".new"
w, err := os.Create(tmpfile)
if err != nil {
log.Printf("Error opening file %s: %v", tmpfile, err)
return
}
enc := json.NewEncoder(w)
if err := enc.Encode(&m.nodes); err != nil {
log.Printf("Failed to encode file %s: %v", tmpfile, err)
return
}
if err := w.Close(); err != nil {
log.Printf("Error closing file %s: %v", tmpfile, err)
return
}
if err := os.Rename(tmpfile, m.peersFile); err != nil {
log.Printf("Error writing file %s: %v", m.peersFile, err)
return
}
}