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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
|
/***************************************************************************
* Copyright (C) 2005 by Joris Guisson *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include <util/file.h>
#include <util/log.h>
#include "downloader.h"
#include "chunkmanager.h"
#include "torrent.h"
#include "peermanager.h"
#include <util/error.h>
#include "chunkdownload.h"
#include <util/sha1hash.h>
#include <util/array.h>
#include "peer.h"
#include "piece.h"
#include "peerdownloader.h"
#include <interfaces/functions.h>
#include <interfaces/monitorinterface.h>
#include "packetwriter.h"
#include "chunkselector.h"
#include "ipblocklist.h"
#include "ktversion.h"
namespace bt
{
Downloader::Downloader(Torrent & tor,PeerManager & pman,ChunkManager & cman)
: tor(tor),pman(pman),cman(cman),downloaded(0),tmon(0)
{
chunk_selector = new ChunkSelector(cman,*this,pman);
Uint64 total = tor.getFileLength();
downloaded = (total - cman.bytesLeft());
curr_chunks_downloaded = 0;
unnecessary_data = 0;
current_chunks.setAutoDelete(true);
connect(&pman,SIGNAL(newPeer(Peer* )),this,SLOT(onNewPeer(Peer* )));
connect(&pman,SIGNAL(peerKilled(Peer* )),this,SLOT(onPeerKilled(Peer*)));
}
Downloader::~Downloader()
{
delete chunk_selector;
}
void Downloader::pieceRecieved(const Piece & p)
{
if (cman.completed())
return;
ChunkDownload* cd = 0;
for (CurChunkItr j = current_chunks.begin();j != current_chunks.end();++j)
{
if (p.getIndex() != j->first)
continue;
cd = j->second;
break;
}
if (!cd)
{
unnecessary_data += p.getLength();
Out(SYS_DIO|LOG_DEBUG) <<
"Unnecessary piece, total unnecessary data : " << kt::BytesToString(unnecessary_data) << endl;
return;
}
// if the chunk is not in memory, reload it
if (cd->getChunk()->getStatus() == Chunk::ON_DISK)
{
cman.prepareChunk(cd->getChunk(),true);
}
bool ok = false;
if (cd->piece(p,ok))
{
if (tmon)
tmon->downloadRemoved(cd);
if (ok)
downloaded += p.getLength();
if (!finished(cd))
{
// if the chunk fails don't count the bytes downloaded
if (cd->getChunk()->getSize() > downloaded)
downloaded = 0;
else
downloaded -= cd->getChunk()->getSize();
}
current_chunks.erase(p.getIndex());
update(); // run an update to assign new pieces
}
else
{
if (ok)
downloaded += p.getLength();
// save to disk again, if it is idle
if (cd->isIdle() && cd->getChunk()->getStatus() == Chunk::MMAPPED)
{
cman.saveChunk(cd->getChunk()->getIndex(),false);
}
}
if (!ok)
{
unnecessary_data += p.getLength();
Out(SYS_DIO|LOG_DEBUG) <<
"Unnecessary piece, total unnecessary data : " << kt::BytesToString(unnecessary_data) << endl;
}
}
void Downloader::update()
{
if (cman.completed())
return;
/*
Normal update should now handle all modes properly.
*/
normalUpdate();
// now see if there aren't any timed out pieces
for (Uint32 i = 0;i < pman.getNumConnectedPeers();i++)
{
Peer* p = pman.getPeer(i);
p->getPeerDownloader()->checkTimeouts();
}
}
void Downloader::normalUpdate()
{
for (CurChunkItr j = current_chunks.begin();j != current_chunks.end();++j)
{
ChunkDownload* cd = j->second;
if (cd->isIdle()) // idle chunks do not need to be in memory
{
Chunk* c = cd->getChunk();
if (c->getStatus() == Chunk::MMAPPED)
{
cman.saveChunk(cd->getChunk()->getIndex(),false);
}
}
else if (cd->isChoked())
{
cd->releaseAllPDs();
Chunk* c = cd->getChunk();
if (c->getStatus() == Chunk::MMAPPED)
{
cman.saveChunk(cd->getChunk()->getIndex(),false);
}
}
else if (cd->needsToBeUpdated())
{
cd->update();
}
}
for (Uint32 i = 0; i < pman.getNumConnectedPeers();++i)
{
PeerDownloader* pd = pman.getPeer(i)->getPeerDownloader();
if (pd->isNull())
continue;
bool ok =
(pd->getNumGrabbed() < pd->getMaxChunkDownloads() ||
pd->isNearlyDone()) &&
pd->canAddRequest();
if (ok)
{
if (!pd->isChoked())
downloadFrom(pd);
pd->setNearlyDone(false);
}
}
}
Uint32 Downloader::maxMemoryUsage()
{
Uint32 max = 1024 * 1024;
switch (mem_usage)
{
case 1: // Medium
max *= 60; // 60 MB
break;
case 2: // High
max *= 80; // 90 MB
break;
case 0: // LOW
default:
max *= 40; // 30 MB
break;
}
return max;
}
Uint32 Downloader::numNonIdle()
{
Uint32 num_non_idle = 0;
for (CurChunkItr j = current_chunks.begin();j != current_chunks.end();++j)
{
ChunkDownload* cd = j->second;
if (!cd->isIdle())
num_non_idle++;
}
return num_non_idle;
}
ChunkDownload* Downloader::selectCD(PeerDownloader* pd,Uint32 num)
{
ChunkDownload* sel = 0;
Uint32 sel_left = 0xFFFFFFFF;
for (CurChunkItr j = current_chunks.begin();j != current_chunks.end();++j)
{
ChunkDownload* cd = j->second;
if (pd->isChoked() || !pd->hasChunk(cd->getChunk()->getIndex()))
continue;
if (cd->getNumDownloaders() == num)
{
// lets favor the ones which are nearly finished
if (!sel || cd->getTotalPieces() - cd->getPiecesDownloaded() < sel_left)
{
sel = cd;
sel_left = sel->getTotalPieces() - sel->getPiecesDownloaded();
}
}
}
return sel;
}
bool Downloader::findDownloadForPD(PeerDownloader* pd,bool warmup)
{
ChunkDownload* sel = 0;
// first see if there are ChunkDownload's which need a PeerDownloader
sel = selectCD(pd,0);
if (!sel && warmup)
{
// if we couldn't find one, try to select another
// which only has one downloader
// so that during warmup, there are at the most 2 downloaders
// assigned to one peer
sel = selectCD(pd,1);
}
if (sel)
{
// if it is on disk, reload it
if (sel->getChunk()->getStatus() == Chunk::ON_DISK)
cman.prepareChunk(sel->getChunk(),true);
sel->assignPeer(pd);
return true;
}
return false;
}
ChunkDownload* Downloader::selectWorst(PeerDownloader* pd)
{
ChunkDownload* cdmin = NULL;
for (CurChunkItr j = current_chunks.begin();j != current_chunks.end();++j)
{
ChunkDownload* cd = j->second;
if (!pd->hasChunk(cd->getChunk()->getIndex()) || cd->containsPeer(pd))
continue;
if (!cdmin)
cdmin = cd;
else if (cd->getDownloadSpeed() < cdmin->getDownloadSpeed())
cdmin = cd;
else if (cd->getNumDownloaders() < cdmin->getNumDownloaders())
cdmin = cd;
}
return cdmin;
}
void Downloader::downloadFrom(PeerDownloader* pd)
{
// calculate the max memory usage
Uint32 max = maxMemoryUsage();
// calculate number of non idle chunks
Uint32 num_non_idle = numNonIdle();
// first see if we can use an existing dowload
if (findDownloadForPD(pd,cman.getNumChunks() - cman.chunksLeft() <= 4))
return;
bool limit_exceeded = num_non_idle * tor.getChunkSize() >= max;
Uint32 chunk = 0;
if (!limit_exceeded && chunk_selector->select(pd,chunk))
{
Chunk* c = cman.getChunk(chunk);
if (cman.prepareChunk(c))
{
ChunkDownload* cd = new ChunkDownload(c);
current_chunks.insert(chunk,cd);
cd->assignPeer(pd);
if (tmon)
tmon->downloadStarted(cd);
}
}
else if (pd->getNumGrabbed() == 0)
{
// If the peer hasn't got a chunk we want,
ChunkDownload *cdmin = selectWorst(pd);
if (cdmin)
{
// if it is on disk, reload it
if (cdmin->getChunk()->getStatus() == Chunk::ON_DISK)
{
cman.prepareChunk(cdmin->getChunk(),true);
}
cdmin->assignPeer(pd);
}
}
}
bool Downloader::areWeDownloading(Uint32 chunk) const
{
return current_chunks.find(chunk) != 0;
}
void Downloader::onNewPeer(Peer* peer)
{
PeerDownloader* pd = peer->getPeerDownloader();
connect(pd,SIGNAL(downloaded(const Piece& )),
this,SLOT(pieceRecieved(const Piece& )));
}
void Downloader::onPeerKilled(Peer* peer)
{
PeerDownloader* pd = peer->getPeerDownloader();
if (pd)
{
for (CurChunkItr i = current_chunks.begin();i != current_chunks.end();++i)
{
ChunkDownload* cd = i->second;
cd->peerKilled(pd);
}
}
}
bool Downloader::finished(ChunkDownload* cd)
{
Chunk* c = cd->getChunk();
// verify the data
SHA1Hash h;
if (cd->usingContinuousHashing())
h = cd->getHash();
else
h = SHA1Hash::generate(c->getData(),c->getSize());
if (tor.verifyHash(h,c->getIndex()))
{
// hash ok so save it
try
{
cman.saveChunk(c->getIndex());
Out(SYS_GEN|LOG_NOTICE) << "Chunk " << c->getIndex() << " downloaded " << endl;
// tell everybody we have the Chunk
for (Uint32 i = 0;i < pman.getNumConnectedPeers();i++)
{
pman.getPeer(i)->getPacketWriter().sendHave(c->getIndex());
}
}
catch (Error & e)
{
Out(SYS_DIO|LOG_IMPORTANT) << "Error " << e.toString() << endl;
emit ioError(e.toString());
return false;
}
}
else
{
Out(SYS_GEN|LOG_IMPORTANT) << "Hash verification error on chunk " << c->getIndex() << endl;
Out(SYS_GEN|LOG_IMPORTANT) << "Is : " << h << endl;
Out(SYS_GEN|LOG_IMPORTANT) << "Should be : " << tor.getHash(c->getIndex()) << endl;
cman.resetChunk(c->getIndex());
chunk_selector->reinsert(c->getIndex());
Uint32 pid;
if (cd->getOnlyDownloader(pid))
{
Peer* p = pman.findPeer(pid);
if (!p)
return false;
QString IP(p->getIPAddresss());
Out(SYS_GEN|LOG_NOTICE) << "Peer " << IP << " sent bad data" << endl;
IPBlocklist & ipfilter = IPBlocklist::instance();
ipfilter.insert( IP );
p->kill();
}
return false;
}
return true;
}
void Downloader::clearDownloads()
{
for (CurChunkItr i = current_chunks.begin();i != current_chunks.end();++i)
{
Uint32 ch = i->first;
Chunk* c = i->second->getChunk();
if (c->getStatus() == Chunk::MMAPPED)
cman.saveChunk(ch,false);
c->setStatus(Chunk::NOT_DOWNLOADED);
}
current_chunks.clear();
}
Uint32 Downloader::downloadRate() const
{
// sum of the download rate of each peer
Uint32 rate = 0;
for (Uint32 i = 0;i < pman.getNumConnectedPeers();i++)
{
Peer* p = pman.getPeer(i);
rate += p->getDownloadRate();
}
return rate;
}
void Downloader::setMonitor(kt::MonitorInterface* tmo)
{
tmon = tmo;
if (!tmon)
return;
for (CurChunkItr i = current_chunks.begin();i != current_chunks.end();++i)
{
ChunkDownload* cd = i->second;
tmon->downloadStarted(cd);
}
}
void Downloader::saveDownloads(const QString & file)
{
File fptr;
if (!fptr.open(file,"wb"))
return;
// Save all the current downloads to a file
CurrentChunksHeader hdr;
hdr.magic = CURRENT_CHUNK_MAGIC;
hdr.major = kt::MAJOR;
hdr.minor = kt::MINOR;
hdr.num_chunks = current_chunks.count();
fptr.write(&hdr,sizeof(CurrentChunksHeader));
// Out() << "sizeof(CurrentChunksHeader)" << sizeof(CurrentChunksHeader) << endl;
Out() << "Saving " << current_chunks.count() << " chunk downloads" << endl;
for (CurChunkItr i = current_chunks.begin();i != current_chunks.end();++i)
{
ChunkDownload* cd = i->second;
cd->save(fptr);
}
}
void Downloader::loadDownloads(const QString & file)
{
// don't load stuff if download is finished
if (cman.completed())
return;
// Load all partial downloads
File fptr;
if (!fptr.open(file,"rb"))
return;
// recalculate downloaded bytes
downloaded = (tor.getFileLength() - cman.bytesLeft());
CurrentChunksHeader chdr;
fptr.read(&chdr,sizeof(CurrentChunksHeader));
if (chdr.magic != CURRENT_CHUNK_MAGIC)
{
Out() << "Warning : current_chunks file corrupted" << endl;
return;
}
Out() << "Loading " << chdr.num_chunks << " active chunk downloads" << endl;
for (Uint32 i = 0;i < chdr.num_chunks;i++)
{
ChunkDownloadHeader hdr;
// first read header
fptr.read(&hdr,sizeof(ChunkDownloadHeader));
Out() << "Loading chunk " << hdr.index << endl;
if (hdr.index >= tor.getNumChunks())
{
Out() << "Warning : current_chunks file corrupted, invalid index " << hdr.index << endl;
return;
}
if (!cman.getChunk(hdr.index) || current_chunks.contains(hdr.index))
{
Out() << "Illegal chunk " << hdr.index << endl;
return;
}
Chunk* c = cman.getChunk(hdr.index);
if (!c->isExcluded() && cman.prepareChunk(c))
{
ChunkDownload* cd = new ChunkDownload(c);
bool ret = false;
try
{
ret = cd->load(fptr,hdr);
}
catch (...)
{
ret = false;
}
if (!ret)
{
delete cd;
}
else
{
current_chunks.insert(hdr.index,cd);
downloaded += cd->bytesDownloaded();
if (tmon)
tmon->downloadStarted(cd);
}
}
}
// reset curr_chunks_downloaded to 0
curr_chunks_downloaded = 0;
}
Uint32 Downloader::getDownloadedBytesOfCurrentChunksFile(const QString & file)
{
// Load all partial downloads
File fptr;
if (!fptr.open(file,"rb"))
return 0;
// read the number of chunks
CurrentChunksHeader chdr;
fptr.read(&chdr,sizeof(CurrentChunksHeader));
if (chdr.magic != CURRENT_CHUNK_MAGIC)
{
Out() << "Warning : current_chunks file corrupted" << endl;
return 0;
}
Uint32 num_bytes = 0;
// load all chunks and calculate how much is downloaded
for (Uint32 i = 0;i < chdr.num_chunks;i++)
{
// read the chunkdownload header
ChunkDownloadHeader hdr;
fptr.read(&hdr,sizeof(ChunkDownloadHeader));
Chunk* c = cman.getChunk(hdr.index);
if (!c)
return num_bytes;
Uint32 last_size = c->getSize() % MAX_PIECE_LEN;
if (last_size == 0)
last_size = MAX_PIECE_LEN;
// create the bitset and read it
BitSet bs(hdr.num_bits);
fptr.read(bs.getData(),bs.getNumBytes());
for (Uint32 j = 0;j < hdr.num_bits;j++)
{
if (bs.get(j))
num_bytes += j == hdr.num_bits - 1 ?
last_size : MAX_PIECE_LEN;
}
if (hdr.buffered)
fptr.seek(File::CURRENT,c->getSize());
}
curr_chunks_downloaded = num_bytes;
return num_bytes;
}
bool Downloader::isFinished() const
{
return cman.completed();
}
void Downloader::onExcluded(Uint32 from,Uint32 to)
{
for (Uint32 i = from;i <= to;i++)
{
ChunkDownload* cd = current_chunks.find(i);
// let only seed chunks finish
if (!cd || cman.getChunk(i)->getPriority() == ONLY_SEED_PRIORITY)
continue;
cd->cancelAll();
cd->releaseAllPDs();
if (tmon)
tmon->downloadRemoved(cd);
current_chunks.erase(i);
cman.resetChunk(i); // reset chunk it is not fully downloaded yet
}
}
void Downloader::onIncluded(Uint32 from,Uint32 to)
{
chunk_selector->reincluded(from,to);
}
void Downloader::corrupted(Uint32 chunk)
{
chunk_selector->reinsert(chunk);
}
Uint32 Downloader::mem_usage = 0;
void Downloader::setMemoryUsage(Uint32 m)
{
mem_usage = m;
// PeerDownloader::setMemoryUsage(m);
}
void Downloader::dataChecked(const BitSet & ok_chunks)
{
for (Uint32 i = 0;i < ok_chunks.getNumBits();i++)
{
ChunkDownload* cd = current_chunks.find(i);
if (ok_chunks.get(i) && cd)
{
// we have a chunk and we are downloading it so kill it
cd->releaseAllPDs();
if (tmon)
tmon->downloadRemoved(cd);
current_chunks.erase(i);
}
}
chunk_selector->dataChecked(ok_chunks);
}
void Downloader::recalcDownloaded()
{
Uint64 total = tor.getFileLength();
downloaded = (total - cman.bytesLeft());
}
}
#include "downloader.moc"
|