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
|
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
# Written by Bram Cohen, Uoti Urpala
from random import shuffle
from BitTorrent.platform import bttime
from BitTorrent.CurrentRateMeasure import Measure
from BitTorrent.bitfield import Bitfield
class PerIPStats(object):
def __init__(self):
self.numgood = 0
self.bad = {}
self.numconnections = 0
self.lastdownload = None
self.peerid = None
class BadDataGuard(object):
def __init__(self, download):
self.download = download
self.ip = download.connection.ip
self.downloader = download.downloader
self.stats = self.downloader.perip[self.ip]
self.lastindex = None
def bad(self, index, bump = False):
self.stats.bad.setdefault(index, 0)
self.stats.bad[index] += 1
if self.ip not in self.downloader.bad_peers:
self.downloader.bad_peers[self.ip] = (False, self.stats)
if self.download is not None:
self.downloader.kick(self.download)
self.download = None
elif len(self.stats.bad) > 1 and self.stats.numconnections == 1 and \
self.stats.lastdownload is not None:
# kick new connection from same IP if previous one sent bad data,
# mainly to give the algorithm time to find other bad pieces
# in case the peer is sending a lot of bad data
self.downloader.kick(self.stats.lastdownload)
if len(self.stats.bad) >= 3 and len(self.stats.bad) > \
self.stats.numgood // 30:
self.downloader.ban(self.ip)
elif bump:
self.downloader.picker.bump(index)
def good(self, index):
# lastindex is a hack to only increase numgood for by one for each good
# piece, however many chunks came from the connection(s) from this IP
if index != self.lastindex:
self.stats.numgood += 1
self.lastindex = index
class SingleDownload(object):
def __init__(self, downloader, connection):
self.downloader = downloader
self.connection = connection
self.choked = True
self.interested = False
self.active_requests = []
self.measure = Measure(downloader.config['max_rate_period'])
self.peermeasure = Measure(max(downloader.storage.piece_size / 10000,
20))
self.have = Bitfield(downloader.numpieces)
self.last = 0
self.example_interest = None
self.backlog = 2
self.guard = BadDataGuard(self)
def _backlog(self):
backlog = 2 + int(4 * self.measure.get_rate() /
self.downloader.chunksize)
if backlog > 50:
backlog = max(50, int(.075 * backlog))
self.backlog = backlog
return backlog
def disconnected(self):
self.downloader.lost_peer(self)
for i in xrange(len(self.have)):
if self.have[i]:
self.downloader.picker.lost_have(i)
self._letgo()
self.guard.download = None
def _letgo(self):
if not self.active_requests:
return
if self.downloader.storage.endgame:
self.active_requests = []
return
lost = []
for index, begin, length in self.active_requests:
self.downloader.storage.request_lost(index, begin, length)
if index not in lost:
lost.append(index)
self.active_requests = []
ds = [d for d in self.downloader.downloads if not d.choked]
shuffle(ds)
for d in ds:
d._request_more(lost)
for d in self.downloader.downloads:
if d.choked and not d.interested:
for l in lost:
if d.have[l] and self.downloader.storage.do_I_have_requests(l):
d.interested = True
d.connection.send_interested()
break
def got_choke(self):
if not self.choked:
self.choked = True
self._letgo()
def got_unchoke(self):
if self.choked:
self.choked = False
if self.interested:
self._request_more()
def got_piece(self, index, begin, piece):
try:
self.active_requests.remove((index, begin, len(piece)))
except ValueError:
self.downloader.discarded_bytes += len(piece)
return False
if self.downloader.storage.endgame:
self.downloader.all_requests.remove((index, begin, len(piece)))
self.last = bttime()
self.measure.update_rate(len(piece))
self.downloader.measurefunc(len(piece))
self.downloader.downmeasure.update_rate(len(piece))
if not self.downloader.storage.piece_came_in(index, begin, piece,
self.guard):
if self.downloader.storage.endgame:
while self.downloader.storage.do_I_have_requests(index):
nb, nl = self.downloader.storage.new_request(index)
self.downloader.all_requests.append((index, nb, nl))
for d in self.downloader.downloads:
d.fix_download_endgame()
return False
ds = [d for d in self.downloader.downloads if not d.choked]
shuffle(ds)
for d in ds:
d._request_more([index])
return False
if self.downloader.storage.do_I_have(index):
self.downloader.picker.complete(index)
if self.downloader.storage.endgame:
for d in self.downloader.downloads:
if d is not self and d.interested:
if d.choked:
d.fix_download_endgame()
else:
try:
d.active_requests.remove((index, begin, len(piece)))
except ValueError:
continue
d.connection.send_cancel(index, begin, len(piece))
d.fix_download_endgame()
self._request_more()
if self.downloader.picker.am_I_complete():
for d in [i for i in self.downloader.downloads if i.have.numfalse == 0]:
d.connection.close()
return self.downloader.storage.do_I_have(index)
def _want(self, index):
return self.have[index] and self.downloader.storage.do_I_have_requests(index)
def _request_more(self, indices = None):
assert not self.choked
if len(self.active_requests) >= self._backlog():
return
if self.downloader.storage.endgame:
self.fix_download_endgame()
return
lost_interests = []
while len(self.active_requests) < self.backlog:
if indices is None:
interest = self.downloader.picker.next(self._want, self.have.numfalse == 0)
else:
interest = None
for i in indices:
if self.have[i] and self.downloader.storage.do_I_have_requests(i):
interest = i
break
if interest is None:
break
if not self.interested:
self.interested = True
self.connection.send_interested()
self.example_interest = interest
self.downloader.picker.requested(interest, self.have.numfalse == 0)
while len(self.active_requests) < (self.backlog-2) * 5 + 2:
begin, length = self.downloader.storage.new_request(interest)
self.active_requests.append((interest, begin, length))
self.connection.send_request(interest, begin, length)
if not self.downloader.storage.do_I_have_requests(interest):
lost_interests.append(interest)
break
if not self.active_requests and self.interested:
self.interested = False
self.connection.send_not_interested()
if lost_interests:
for d in self.downloader.downloads:
if d.active_requests or not d.interested:
continue
if d.example_interest is not None and self.downloader.storage.do_I_have_requests(d.example_interest):
continue
for lost in lost_interests:
if d.have[lost]:
break
else:
continue
interest = self.downloader.picker.next(d._want, d.have.numfalse == 0)
if interest is None:
d.interested = False
d.connection.send_not_interested()
else:
d.example_interest = interest
if self.downloader.storage.endgame:
self.downloader.all_requests = []
for d in self.downloader.downloads:
self.downloader.all_requests.extend(d.active_requests)
for d in self.downloader.downloads:
d.fix_download_endgame()
def fix_download_endgame(self):
want = [a for a in self.downloader.all_requests if self.have[a[0]] and a not in self.active_requests]
if self.interested and not self.active_requests and not want:
self.interested = False
self.connection.send_not_interested()
return
if not self.interested and want:
self.interested = True
self.connection.send_interested()
if self.choked or len(self.active_requests) >= self._backlog():
return
shuffle(want)
del want[self.backlog - len(self.active_requests):]
self.active_requests.extend(want)
for piece, begin, length in want:
self.connection.send_request(piece, begin, length)
def got_have(self, index):
if self.have[index]:
return
if index == self.downloader.numpieces-1:
self.peermeasure.update_rate(self.downloader.storage.total_length-
(self.downloader.numpieces-1)*self.downloader.storage.piece_size)
else:
self.peermeasure.update_rate(self.downloader.storage.piece_size)
self.have[index] = True
self.downloader.picker.got_have(index)
if self.downloader.picker.am_I_complete() and self.have.numfalse == 0:
self.connection.close()
return
if self.downloader.storage.endgame:
self.fix_download_endgame()
elif self.downloader.storage.do_I_have_requests(index):
if not self.choked:
self._request_more([index])
else:
if not self.interested:
self.interested = True
self.connection.send_interested()
def got_have_bitfield(self, have):
if self.downloader.picker.am_I_complete() and have.numfalse == 0:
self.connection.close()
return
self.have = have
for i in xrange(len(self.have)):
if self.have[i]:
self.downloader.picker.got_have(i)
if self.downloader.storage.endgame:
for piece, begin, length in self.downloader.all_requests:
if self.have[piece]:
self.interested = True
self.connection.send_interested()
return
for i in xrange(len(self.have)):
if self.have[i] and self.downloader.storage.do_I_have_requests(i):
self.interested = True
self.connection.send_interested()
return
def get_rate(self):
return self.measure.get_rate()
def is_snubbed(self):
return bttime() - self.last > self.downloader.snub_time
class Downloader(object):
def __init__(self, config, storage, picker, numpieces, downmeasure,
measurefunc, kickfunc, banfunc):
self.config = config
self.storage = storage
self.picker = picker
self.chunksize = config['download_slice_size']
self.downmeasure = downmeasure
self.numpieces = numpieces
self.snub_time = config['snub_time']
self.measurefunc = measurefunc
self.kickfunc = kickfunc
self.banfunc = banfunc
self.downloads = []
self.perip = {}
self.bad_peers = {}
self.discarded_bytes = 0
def make_download(self, connection):
ip = connection.ip
perip = self.perip.get(ip)
if perip is None:
perip = PerIPStats()
self.perip[ip] = perip
perip.numconnections += 1
d = SingleDownload(self, connection)
perip.lastdownload = d
perip.peerid = connection.id
self.downloads.append(d)
return d
def lost_peer(self, download):
self.downloads.remove(download)
ip = download.connection.ip
self.perip[ip].numconnections -= 1
if self.perip[ip].lastdownload == download:
self.perip[ip].lastdownload = None
def kick(self, download):
if not self.config['retaliate_to_garbled_data']:
return
ip = download.connection.ip
peerid = download.connection.id
# kickfunc will schedule connection.close() to be executed later; we
# might now be inside RawServer event loop with events from that
# connection already queued, and trying to handle them after doing
# close() now could cause problems.
self.kickfunc(download.connection)
def ban(self, ip):
if not self.config['retaliate_to_garbled_data']:
return
self.banfunc(ip)
self.bad_peers[ip] = (True, self.perip[ip])
|