forked from anacrolix/dht
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathannounce.go
235 lines (213 loc) · 5.5 KB
/
announce.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
package dht
// get_peers and announce_peers.
import (
"time"
"github.com/anacrolix/sync"
"github.com/anacrolix/torrent/logonce"
"github.com/willf/bloom"
"github.com/anacrolix/dht/krpc"
)
// Maintains state for an ongoing Announce operation. An Announce is started
// by calling Server.Announce.
type Announce struct {
mu sync.Mutex
Peers chan PeersValues
// Inner chan is set to nil when on close.
values chan PeersValues
stop chan struct{}
triedAddrs *bloom.BloomFilter
// True when contact with all starting addrs has been initiated. This
// prevents a race where the first transaction finishes before the rest
// have been opened, sees no other transactions are pending and ends the
// announce.
contactedStartAddrs bool
// How many transactions are still ongoing.
pending int
server *Server
infoHash int160
// Count of (probably) distinct addresses we've sent get_peers requests
// to.
numContacted int
// The torrent port that we're announcing.
announcePort int
// The torrent port should be determined by the receiver in case we're
// being NATed.
announcePortImplied bool
}
// Returns the number of distinct remote addresses the announce has queried.
func (a *Announce) NumContacted() int {
a.mu.Lock()
defer a.mu.Unlock()
return a.numContacted
}
func newBloomFilterForTraversal() *bloom.BloomFilter {
return bloom.NewWithEstimates(1000, 0.5)
}
// This is kind of the main thing you want to do with DHT. It traverses the
// graph toward nodes that store peers for the infohash, streaming them to the
// caller, and announcing the local node to each node if allowed and
// specified.
func (s *Server) Announce(infoHash [20]byte, port int, impliedPort bool) (*Announce, error) {
s.mu.Lock()
defer s.mu.Unlock()
startAddrs, err := s.traversalStartingAddrs()
if err != nil {
return nil, err
}
disc := &Announce{
Peers: make(chan PeersValues, 100),
stop: make(chan struct{}),
values: make(chan PeersValues),
triedAddrs: newBloomFilterForTraversal(),
server: s,
infoHash: int160FromByteArray(infoHash),
announcePort: port,
announcePortImplied: impliedPort,
}
// Function ferries from values to Values until discovery is halted.
go func() {
defer close(disc.Peers)
for {
select {
case psv := <-disc.values:
select {
case disc.Peers <- psv:
case <-disc.stop:
return
}
case <-disc.stop:
return
}
}
}()
go func() {
disc.mu.Lock()
defer disc.mu.Unlock()
for i, addr := range startAddrs {
if i != 0 {
disc.mu.Unlock()
time.Sleep(time.Millisecond)
disc.mu.Lock()
}
disc.contact(addr)
}
disc.contactedStartAddrs = true
// If we failed to contact any of the starting addrs, no transactions
// will complete triggering a check that there are no pending
// responses.
disc.maybeClose()
}()
return disc, nil
}
func validNodeAddr(addr Addr) bool {
ua := addr.UDPAddr()
if ua.Port == 0 {
return false
}
if ip4 := ua.IP.To4(); ip4 != nil && ip4[0] == 0 {
return false
}
return true
}
// TODO: Merge this with maybeGetPeersFromAddr.
func (a *Announce) gotNodeAddr(addr Addr) {
if !validNodeAddr(addr) {
return
}
if a.triedAddrs.Test([]byte(addr.String())) {
return
}
if a.server.ipBlocked(addr.UDPAddr().IP) {
return
}
a.contact(addr)
}
// TODO: Merge this with maybeGetPeersFromAddr.
func (a *Announce) contact(addr Addr) {
a.numContacted++
a.triedAddrs.Add([]byte(addr.String()))
if err := a.getPeers(addr); err != nil {
return
}
a.pending++
}
func (a *Announce) maybeClose() {
if a.contactedStartAddrs && a.pending == 0 {
a.close()
}
}
func (a *Announce) transactionClosed() {
a.pending--
a.maybeClose()
}
func (a *Announce) responseNode(node krpc.NodeInfo) {
a.gotNodeAddr(NewAddr(node.Addr))
}
// Announce to a peer, if appropriate.
func (a *Announce) maybeAnnouncePeer(to Addr, token string, peerId [20]byte) {
if !a.server.config.NoSecurity && !NodeIdSecure(peerId, to.UDPAddr().IP) {
return
}
a.server.mu.Lock()
defer a.server.mu.Unlock()
err := a.server.announcePeer(to, a.infoHash, a.announcePort, token, a.announcePortImplied, nil)
if err != nil {
logonce.Stderr.Printf("error announcing peer: %s", err)
}
}
func (a *Announce) getPeers(addr Addr) error {
a.server.mu.Lock()
defer a.server.mu.Unlock()
return a.server.getPeers(addr, a.infoHash, func(m krpc.Msg, err error) {
// Register suggested nodes closer to the target info-hash.
if m.R != nil {
a.mu.Lock()
for _, n := range m.R.Nodes {
a.responseNode(n)
}
a.mu.Unlock()
if vs := m.R.Values; len(vs) != 0 {
nodeInfo := krpc.NodeInfo{
Addr: addr.UDPAddr(),
ID: *m.SenderID(),
}
select {
case a.values <- PeersValues{
Peers: func() (ret []Peer) {
for _, cp := range vs {
ret = append(ret, Peer(cp))
}
return
}(),
NodeInfo: nodeInfo,
}:
case <-a.stop:
}
}
a.maybeAnnouncePeer(addr, m.R.Token, *m.SenderID())
}
a.mu.Lock()
a.transactionClosed()
a.mu.Unlock()
})
}
// Corresponds to the "values" key in a get_peers KRPC response. A list of
// peers that a node has reported as being in the swarm for a queried info
// hash.
type PeersValues struct {
Peers []Peer // Peers given in get_peers response.
krpc.NodeInfo // The node that gave the response.
}
// Stop the announce.
func (a *Announce) Close() {
a.mu.Lock()
defer a.mu.Unlock()
a.close()
}
func (a *Announce) close() {
select {
case <-a.stop:
default:
close(a.stop)
}
}