-
Notifications
You must be signed in to change notification settings - Fork 8
/
dht.go
485 lines (361 loc) · 8.89 KB
/
dht.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package dht
import (
"encoding/hex"
"errors"
"math/rand"
"net"
"os"
"sync"
"time"
"github.com/vmihailenco/msgpack"
"github.com/golang/protobuf/proto"
logging "github.com/op/go-logging"
)
type Dht struct {
sync.RWMutex
routing *Routing
options DhtOptions
hash []byte
running bool
store map[string][]byte
commandQueue map[string]CallbackChan
logger *logging.Logger
server net.PacketConn
gotBroadcast [][]byte
messageChunks map[string]WaitingPartMsg
sentMsgs map[string][]Packet
}
type DhtOptions struct {
NoRepublishOnExit bool
ListenAddr string
BootstrapAddr string
Verbose int
Cluster int
Stats bool
Interactif bool
OnStore func(Packet) bool
OnCustomCmd func(Packet) interface{}
OnBroadcast func(Packet) interface{}
MaxStorageSize int
MaxItemSize int
}
type WaitingPartMsg struct {
timer *time.Timer
timeout *time.Timer
hash []byte
addr net.Addr
total int32
parts [][]byte
}
func New(options DhtOptions) *Dht {
if options.MaxStorageSize == 0 {
options.MaxStorageSize = 500000000 // ~500Mo
}
if options.MaxItemSize == 0 {
options.MaxItemSize = 5000000 // ~5Mo
}
res := &Dht{
routing: NewRouting(),
options: options,
running: false,
store: make(map[string][]byte),
commandQueue: make(map[string]CallbackChan),
messageChunks: make(map[string]WaitingPartMsg),
sentMsgs: make(map[string][]Packet),
logger: logging.MustGetLogger("dht"),
}
initLogger(res)
res.routing.dht = res
res.logger.Debug("DHT version 0.0.1")
r := rand.Intn(60) - 60
timer := time.NewTicker(time.Minute*10 + (time.Second * time.Duration(r)))
go func() {
for range timer.C {
res.republish()
}
}()
return res
}
func initLogger(dht *Dht) {
var format = logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
backend := logging.NewLogBackend(os.Stderr, "", 0)
var logLevel logging.Level
switch dht.options.Verbose {
case 0:
logLevel = logging.CRITICAL
case 1:
logLevel = logging.ERROR
case 2:
logLevel = logging.WARNING
case 3:
logLevel = logging.NOTICE
case 4:
logLevel = logging.INFO
case 5:
logLevel = logging.DEBUG
default:
logLevel = 2
}
backendFormatter := logging.NewBackendFormatter(backend, format)
backendLeveled := logging.AddModuleLevel(backendFormatter)
backendLeveled.SetLevel(logLevel, "")
logging.SetBackend(backendLeveled)
}
func (this *Dht) republish() {
for k, v := range this.store {
h, _ := hex.DecodeString(k)
this.StoreAt(h, v)
}
this.logger.Debug("Republished", len(this.store))
}
func (this *Dht) Store(value []byte) (Hash, int, error) {
return this.StoreAt(NewHash(value), value)
}
func (this *Dht) StoreAt(hash Hash, value []byte) (Hash, int, error) {
if len(value) > this.options.MaxItemSize {
return []byte{}, 0, errors.New("Store: Exceeds max limit")
}
bucket := this.fetchNodes(hash)
if len(bucket) == 0 {
return []byte{}, 0, errors.New("No nodes found")
}
fn := func(node *Node) chan interface{} {
return node.Store(hash, value)
}
query := NewQuery(hash, fn, this)
res, ok := query.Run().([]bool)
if !ok || len(res) == 0 {
return []byte{}, 0, errors.New("No answers from nodes")
}
storedOkNb := 0
for _, stored := range res {
if stored {
storedOkNb++
}
}
if storedOkNb == 0 {
return []byte{}, 0, errors.New(hex.EncodeToString(hash) + ": The key might be existing already")
}
return hash, storedOkNb, nil
}
func (this *Dht) Fetch(hash Hash) ([]byte, error) {
fn := func(node *Node) chan interface{} {
return node.Fetch(hash)
}
query := NewQuery(hash, fn, this)
res := query.Run()
switch res.(type) {
case []*Node:
return nil, errors.New("Not found")
case *Found:
found := res.(*Found)
return found.Header.Data, nil
default:
}
return nil, errors.New("Unknown fetched data")
}
func (this *Dht) fetchNodes(hash Hash) []*Node {
fn := func(node *Node) chan interface{} {
return node.FetchNodes(hash)
}
query := NewQuery(hash, fn, this)
return query.Run().([]*Node)
}
func (this *Dht) bootstrap() error {
this.logger.Debug("Connecting to bootstrap node", this.options.BootstrapAddr)
addr, err := net.ResolveUDPAddr("udp", this.options.BootstrapAddr)
if err != nil {
return err
}
bootstrapNode := NewNode(this, addr, []byte{})
// this.routing.AddNode(bootstrapNode.contact)
if err, hasErr := (<-bootstrapNode.Ping()).(error); hasErr {
return err
}
_ = this.fetchNodes(this.hash)
for i, bucket := range this.routing.buckets {
if len(bucket) != 0 {
continue
}
h := NewRandomHash()
h = this.routing.nCopy(h, this.hash, i)
_ = this.fetchNodes(h)
}
this.logger.Info("Ready...")
if this.options.Interactif {
go this.Cli()
}
return nil
}
func (this *Dht) Start() error {
if this.running {
return errors.New("Already started")
}
this.hash = NewRandomHash()
this.logger.Info("Own hash", hex.EncodeToString(this.hash))
l, err := net.ListenPacket("udp", this.options.ListenAddr)
if err != nil {
return errors.New("Error listening:" + err.Error())
}
this.server = l
go func() {
this.logger.Info("Listening on " + this.options.ListenAddr)
if err := this.loop(); err != nil {
this.running = false
this.logger.Error("Main loop: " + err.Error())
}
}()
this.running = true
if len(this.options.BootstrapAddr) > 0 {
if err := this.bootstrap(); err != nil {
this.Stop()
return errors.New("Bootstrap: " + err.Error())
}
} else {
if this.options.Interactif {
go this.Cli()
}
}
return nil
}
const BUFFER_SIZE = 1024 * 4
func (this *Dht) loop() error {
this.running = true
defer this.server.Close()
// msgs := make(map[string][]UDPWrapper)
for this.running {
var message [BUFFER_SIZE]byte
n, addr, err := this.server.ReadFrom(message[0:])
if err != nil {
if this.running == false {
return nil
}
return errors.New("Error reading:" + err.Error())
}
go this.handleInPacket(addr, message[:n])
}
return nil
}
func (this *Dht) Stop() {
if !this.running {
return
}
if !this.options.NoRepublishOnExit {
this.republish()
}
this.running = false
this.server.Close()
}
func (this *Dht) handleInPacket(addr net.Addr, blob []byte) {
var packet Packet
if err := proto.Unmarshal(blob, &packet); err != nil {
this.logger.Warning("Invalid packet", err)
return
}
var node *Node
addr, err := net.ResolveUDPAddr("udp", packet.Header.Sender.Addr)
if err != nil {
this.logger.Warning("Cannot resolve udp address")
return
}
node = NewNodeContact(this, addr, *packet.Header.Sender)
// this.logger.Info("Got packet", packet.Header.Sender.Addr)
this.routing.AddNode(*packet.Header.Sender)
node.HandleInPacket(packet)
}
func (this *Dht) Logger() *logging.Logger {
return this.logger
}
func (this *Dht) CustomCmd(data interface{}) {
bucket := this.routing.FindNode(this.hash)
for _, contact := range bucket {
addr, _ := net.ResolveUDPAddr("udp", contact.Addr)
node := NewNodeContact(this, addr, contact)
<-node.Custom(data)
}
}
func (this *Dht) hasBroadcast(hash []byte) bool {
for _, h := range this.gotBroadcast {
if compare(h, hash) == 0 {
return true
}
}
return false
}
func compare(hash1, hash2 []byte) int {
if len(hash1) != len(hash2) {
return len(hash1) - len(hash2)
}
for i, v := range hash1 {
if v != hash2[i] {
return int(v) - int(hash2[i])
}
}
return 0
}
func (this *Dht) Broadcast(data interface{}) {
bucket := this.routing.FindNode(this.hash)
var packet Packet
switch data.(type) {
case Packet_Broadcast:
packet = data.(Packet)
case Packet:
packet = data.(Packet)
default:
// Fixme
h, err := msgpack.Marshal(data)
if err != nil {
this.logger.Error("Cannot broadcast")
return
}
packet = NewPacket(this, Command_BROADCAST, []byte{}, &Packet_Broadcast{&Broadcast{h}})
}
for _, contact := range bucket {
addr, _ := net.ResolveUDPAddr("udp", contact.Addr)
node := NewNodeContact(this, addr, contact)
node.Broadcast(packet)
}
}
func (this *Dht) Running() bool {
return this.running
}
func (this *Dht) Wait() {
for this.running {
time.Sleep(time.Second)
}
}
func (this *Dht) onCustomCmd(packet Packet) interface{} {
if this.options.OnCustomCmd != nil {
return this.options.OnCustomCmd(packet)
}
return nil
}
func (this *Dht) onBroadcast(packet Packet) interface{} {
if this.options.OnBroadcast != nil {
return this.options.OnBroadcast(packet)
}
return nil
}
func (this *Dht) onStore(packet Packet) bool {
if this.options.OnStore != nil {
return this.options.OnStore(packet)
}
return true
}
func (this *Dht) GetConnectedNumber() int {
return this.routing.Size()
}
func (this *Dht) StoredKeys() int {
return len(this.store)
}
func (this *Dht) StorageSize() int {
this.RLock()
defer this.RUnlock()
size := 0
for k, v := range this.store {
size += len(k) + len(v)
}
return size
}