-
Notifications
You must be signed in to change notification settings - Fork 907
/
dht.go
387 lines (325 loc) · 6.9 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
package main
import (
"bytes"
"container/list"
"crypto/rand"
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"net"
"strconv"
"sync"
"time"
"github.com/marksamman/bencode"
"golang.org/x/time/rate"
)
var seeds = []string{
"router.bittorrent.com:6881",
"dht.transmissionbt.com:6881",
"router.utorrent.com:6881",
}
type nodeID []byte
type node struct {
addr string
id string
}
type announcements struct {
mu sync.RWMutex
ll *list.List
limit int
input chan struct{}
}
func (a *announcements) get() *announcement {
a.mu.Lock()
defer a.mu.Unlock()
if elem := a.ll.Front(); elem != nil {
ac := elem.Value.(*announcement)
a.ll.Remove(elem)
return ac
}
return nil
}
func (a *announcements) put(ac *announcement) {
a.mu.Lock()
defer a.mu.Unlock()
if a.ll.Len() >= a.limit {
return
}
a.ll.PushBack(ac)
select {
case a.input <- struct{}{}:
default:
}
}
func (a *announcements) wait() <-chan struct{} {
return a.input
}
func (a *announcements) len() int {
a.mu.RLock()
defer a.mu.RUnlock()
return a.ll.Len()
}
func (a *announcements) full() bool {
return a.len() >= a.limit
}
type announcement struct {
raw map[string]interface{}
from net.UDPAddr
peer net.Addr
infohash []byte
infohashHex string
}
func randBytes(n int) []byte {
b := make([]byte, n)
rand.Read(b)
return b
}
func neighborID(target nodeID, local nodeID) nodeID {
const closeness = 15
id := make([]byte, 20)
copy(id[:closeness], target[:closeness])
copy(id[closeness:], local[closeness:])
return id
}
func makeQuery(tid string, q string, a map[string]interface{}) map[string]interface{} {
return map[string]interface{}{
"t": tid,
"y": "q",
"q": q,
"a": a,
}
}
func makeReply(tid string, r map[string]interface{}) map[string]interface{} {
return map[string]interface{}{
"t": tid,
"y": "r",
"r": r,
}
}
func decodeNodes(s string) (nodes []*node) {
length := len(s)
if length%26 != 0 {
return
}
for i := 0; i < length; i += 26 {
id := s[i : i+20]
ip := net.IP([]byte(s[i+20 : i+24])).String()
port := binary.BigEndian.Uint16([]byte(s[i+24 : i+26]))
addr := ip + ":" + strconv.Itoa(int(port))
nodes = append(nodes, &node{id: id, addr: addr})
}
return
}
func per(events int, duration time.Duration) rate.Limit {
return rate.Every(duration / time.Duration(events))
}
type dht struct {
mu sync.Mutex
announcements *announcements
chNode chan *node
die chan struct{}
errDie error
localID nodeID
conn *net.UDPConn
queryTypes map[string]func(map[string]interface{}, net.UDPAddr)
friendsLimiter *rate.Limiter
secret []byte
seeds []string
}
func newDHT(laddr string, maxFriendsPerSec int) (*dht, error) {
conn, err := net.ListenPacket("udp", laddr)
if err != nil {
return nil, err
}
d := &dht{
announcements: &announcements{
ll: list.New(),
limit: maxFriendsPerSec * 10,
input: make(chan struct{}, 1),
},
localID: randBytes(20),
conn: conn.(*net.UDPConn),
chNode: make(chan *node),
die: make(chan struct{}),
secret: randBytes(20),
}
d.friendsLimiter = rate.NewLimiter(per(maxFriendsPerSec, time.Second), maxFriendsPerSec)
d.queryTypes = map[string]func(map[string]interface{}, net.UDPAddr){
"get_peers": d.onGetPeersQuery,
"announce_peer": d.onAnnouncePeerQuery,
}
return d, nil
}
func (d *dht) run() {
go d.listen()
go d.join()
go d.makeFriends()
}
func (d *dht) listen() {
buf := make([]byte, 2048)
for {
n, addr, err := d.conn.ReadFromUDP(buf)
if err == nil {
d.onMessage(buf[:n], *addr)
} else {
d.errDie = err
close(d.die)
break
}
}
}
func (d *dht) join() {
const timesForSure = 3
for i := 0; i < timesForSure; i++ {
for _, addr := range seeds {
select {
case d.chNode <- &node{
addr: addr,
id: string(randBytes(20)),
}:
case <-d.die:
return
}
}
}
}
func (d *dht) onMessage(data []byte, from net.UDPAddr) {
dict, err := bencode.Decode(bytes.NewBuffer(data))
if err != nil {
return
}
y, ok := dict["y"].(string)
if !ok {
return
}
switch y {
case "q":
d.onQuery(dict, from)
case "r", "e":
d.onReply(dict, from)
}
}
func (d *dht) onQuery(dict map[string]interface{}, from net.UDPAddr) {
_, ok := dict["t"].(string)
if !ok {
return
}
q, ok := dict["q"].(string)
if !ok {
return
}
if handle, ok := d.queryTypes[q]; ok {
handle(dict, from)
}
}
func (d *dht) onReply(dict map[string]interface{}, from net.UDPAddr) {
r, ok := dict["r"].(map[string]interface{})
if !ok {
return
}
nodes, ok := r["nodes"].(string)
if !ok {
return
}
for _, node := range decodeNodes(nodes) {
if !d.friendsLimiter.Allow() {
continue
}
d.chNode <- node
}
}
func (d *dht) findNode(to string, target nodeID) {
q := makeQuery(string(randBytes(2)), "find_node", map[string]interface{}{
"id": string(neighborID(target, d.localID)),
"target": string(randBytes(20)),
})
addr, err := net.ResolveUDPAddr("udp", to)
if err != nil {
return
}
d.send(q, *addr)
}
func (d *dht) onGetPeersQuery(dict map[string]interface{}, from net.UDPAddr) {
tid, ok := dict["t"].(string)
if !ok {
return
}
a, ok := dict["a"].(map[string]interface{})
if !ok {
return
}
id, ok := a["id"].(string)
if !ok {
return
}
r := makeReply(tid, map[string]interface{}{
"id": string(neighborID([]byte(id), d.localID)),
"nodes": "",
"token": d.makeToken(from),
})
d.send(r, from)
}
func (d *dht) onAnnouncePeerQuery(dict map[string]interface{}, from net.UDPAddr) {
if d.announcements.full() {
return
}
a, ok := dict["a"].(map[string]interface{})
if !ok {
return
}
token, ok := a["token"].(string)
if !ok || !d.validateToken(token, from) {
return
}
if ac := d.summarize(dict, from); ac != nil {
d.announcements.put(ac)
}
}
func (d *dht) summarize(dict map[string]interface{}, from net.UDPAddr) *announcement {
a, ok := dict["a"].(map[string]interface{})
if !ok {
return nil
}
infohash, ok := a["info_hash"].(string)
if !ok {
return nil
}
port := int64(from.Port)
if impliedPort, ok := a["implied_port"].(int64); ok && impliedPort == 0 {
if p, ok := a["port"].(int64); ok {
port = p
}
}
return &announcement{
raw: dict,
from: from,
infohash: []byte(infohash),
infohashHex: hex.EncodeToString([]byte(infohash)),
peer: &net.TCPAddr{IP: from.IP, Port: int(port)},
}
}
func (d *dht) send(dict map[string]interface{}, to net.UDPAddr) error {
d.mu.Lock()
defer d.mu.Unlock()
d.conn.WriteToUDP(bencode.Encode(dict), &to)
return nil
}
func (d *dht) makeFriends() {
for {
select {
case node := <-d.chNode:
d.findNode(node.addr, []byte(node.id))
case <-d.die:
return
}
}
}
func (d *dht) makeToken(from net.UDPAddr) string {
s := sha1.New()
s.Write([]byte(from.String()))
s.Write(d.secret)
return string(s.Sum(nil))
}
func (d *dht) validateToken(token string, from net.UDPAddr) bool {
return token == d.makeToken(from)
}