TorrentMan.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - a simple utility for downloading files faster
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. */
  21. /* copyright --> */
  22. #include "TorrentMan.h"
  23. #include "Dictionary.h"
  24. #include "List.h"
  25. #include "ShaVisitor.h"
  26. #include "Util.h"
  27. #include "MetaFileUtil.h"
  28. #include "DlAbortEx.h"
  29. #include "File.h"
  30. #include "message.h"
  31. #include "PreAllocationDiskWriter.h"
  32. #include "DefaultDiskWriter.h"
  33. #include "MultiDiskWriter.h"
  34. #include "prefs.h"
  35. #include "CopyDiskAdaptor.h"
  36. #include "DirectDiskAdaptor.h"
  37. #include "MultiDiskAdaptor.h"
  38. #include "LogFactory.h"
  39. #include <errno.h>
  40. #include <libgen.h>
  41. #include <string.h>
  42. TorrentMan::TorrentMan():bitfield(NULL),
  43. peerEntryIdCounter(0), cuidCounter(0),
  44. downloadLength(0), uploadLength(0),
  45. preDownloadLength(0), preUploadLength(0),
  46. deltaDownloadLength(0), deltaUploadLength(0),
  47. storeDir("."),
  48. setupComplete(false),
  49. interval(DEFAULT_ANNOUNCE_INTERVAL),
  50. minInterval(DEFAULT_ANNOUNCE_MIN_INTERVAL),
  51. complete(0), incomplete(0),
  52. connections(0), diskAdaptor(NULL) {
  53. logger = LogFactory::getInstance();
  54. }
  55. TorrentMan::~TorrentMan() {
  56. if(bitfield != NULL) {
  57. delete bitfield;
  58. }
  59. for(Peers::iterator itr = peers.begin(); itr != peers.end(); itr++) {
  60. delete *itr;
  61. }
  62. if(diskAdaptor != NULL) {
  63. delete diskAdaptor;
  64. }
  65. }
  66. // TODO do not use this method in application code
  67. void TorrentMan::updatePeers(const Peers& peers) {
  68. this->peers = peers;
  69. }
  70. bool TorrentMan::addPeer(Peer* peer, bool duplicate) {
  71. if(duplicate) {
  72. for(Peers::iterator itr = peers.begin(); itr != peers.end(); itr++) {
  73. Peer* p = *itr;
  74. if(p->ipaddr == peer->ipaddr && p->port == peer->port && p->error > 0) {
  75. return false;
  76. }
  77. }
  78. } else {
  79. deleteOldErrorPeers(MAX_PEER_LIST_SIZE);
  80. for(Peers::iterator itr = peers.begin(); itr != peers.end(); itr++) {
  81. Peer* p = *itr;
  82. if(p->ipaddr == peer->ipaddr && p->port == peer->port) {
  83. return false;
  84. }
  85. }
  86. }
  87. ++peerEntryIdCounter;
  88. peer->entryId = peerEntryIdCounter;
  89. peers.push_back(peer);
  90. return true;
  91. }
  92. /*
  93. void TorrentMan::updatePeer(const Peer& peer) {
  94. for(Peers::iterator itr = peers.begin(); itr != peers.end(); itr++) {
  95. Peer& p = *itr;
  96. if(p.eid == peer.eid) {
  97. p = peer;
  98. break;
  99. }
  100. }
  101. }
  102. */
  103. bool TorrentMan::isPeerAvailable() const {
  104. return getPeer() != Peer::nullPeer;
  105. }
  106. int TorrentMan::deleteOldErrorPeers(int maxNum) {
  107. int counter = 0;
  108. for(Peers::iterator itr = peers.begin(); itr != peers.end();) {
  109. Peer* p = *itr;
  110. if(p->error >= MAX_PEER_ERROR && p->cuid == 0) {
  111. delete p;
  112. itr = peers.erase(itr);
  113. counter++;
  114. if(maxNum <= counter) {
  115. break;
  116. }
  117. } else {
  118. itr++;
  119. }
  120. }
  121. return counter;
  122. }
  123. Peer* TorrentMan::getPeer() const {
  124. for(Peers::const_iterator itr = peers.begin(); itr != peers.end(); itr++) {
  125. Peer* p = *itr;
  126. if(p->cuid == 0 && p->error < MAX_PEER_ERROR) {
  127. return p;
  128. }
  129. }
  130. return Peer::nullPeer;
  131. }
  132. bool TorrentMan::isEndGame() const {
  133. return bitfield->countMissingBlock() <= END_GAME_PIECE_NUM;
  134. }
  135. Piece TorrentMan::getMissingPiece(const Peer* peer) {
  136. int index = -1;
  137. if(isEndGame()) {
  138. index = bitfield->getMissingIndex(peer->getBitfield(), peer->getBitfieldLength());
  139. } else {
  140. index = bitfield->getMissingUnusedIndex(peer->getBitfield(), peer->getBitfieldLength());
  141. }
  142. if(index == -1) {
  143. return Piece::nullPiece;
  144. }
  145. bitfield->setUseBit(index);
  146. Piece piece = findUsedPiece(index);
  147. if(Piece::isNull(piece)) {
  148. Piece piece(index, bitfield->getBlockLength(index));
  149. addUsedPiece(piece);
  150. return piece;
  151. } else {
  152. return piece;
  153. }
  154. }
  155. int TorrentMan::deleteUsedPiecesByFillRate(int fillRate, int toDelete) {
  156. int deleted = 0;
  157. for(UsedPieces::iterator itr = usedPieces.begin();
  158. itr != usedPieces.end() && deleted < toDelete;) {
  159. Piece& piece = *itr;
  160. if(!bitfield->isUseBitSet(piece.getIndex()) &&
  161. piece.countCompleteBlock() <= piece.countBlock()*(fillRate/100.0)) {
  162. logger->debug("deleting used piece index=%d, fillRate(%%)=%d<=%d",
  163. piece.getIndex(),
  164. (piece.countCompleteBlock()*100)/piece.countBlock(),
  165. fillRate);
  166. itr = usedPieces.erase(itr);
  167. deleted++;
  168. } else {
  169. itr++;
  170. }
  171. }
  172. return deleted;
  173. }
  174. void TorrentMan::reduceUsedPieces(int max) {
  175. int toDelete = usedPieces.size()-max;
  176. if(toDelete <= 0) {
  177. return;
  178. }
  179. int fillRate = 10;
  180. while(fillRate < 50) {
  181. int deleted = deleteUsedPiecesByFillRate(fillRate, toDelete);
  182. if(deleted == 0) {
  183. break;
  184. }
  185. toDelete -= deleted;
  186. fillRate += 10;
  187. }
  188. }
  189. void TorrentMan::addUsedPiece(const Piece& piece) {
  190. usedPieces.push_back(piece);
  191. }
  192. Piece TorrentMan::findUsedPiece(int index) const {
  193. for(UsedPieces::const_iterator itr = usedPieces.begin(); itr != usedPieces.end(); itr++) {
  194. const Piece& piece = *itr;
  195. if(piece.getIndex() == index) {
  196. return piece;
  197. }
  198. }
  199. return Piece::nullPiece;
  200. }
  201. void TorrentMan::deleteUsedPiece(const Piece& piece) {
  202. if(Piece::isNull(piece)) {
  203. return;
  204. }
  205. for(UsedPieces::iterator itr = usedPieces.begin(); itr != usedPieces.end(); itr++) {
  206. if(itr->getIndex() == piece.getIndex()) {
  207. usedPieces.erase(itr);
  208. break;
  209. }
  210. }
  211. }
  212. void TorrentMan::completePiece(const Piece& piece) {
  213. if(Piece::isNull(piece)) {
  214. return;
  215. }
  216. if(!hasPiece(piece.getIndex())) {
  217. addDownloadLength(piece.getLength());
  218. }
  219. bitfield->setBit(piece.getIndex());
  220. bitfield->unsetUseBit(piece.getIndex());
  221. deleteUsedPiece(piece);
  222. if(!isEndGame()) {
  223. reduceUsedPieces(100);
  224. }
  225. }
  226. void TorrentMan::cancelPiece(const Piece& piece) {
  227. if(Piece::isNull(piece)) {
  228. return;
  229. }
  230. bitfield->unsetUseBit(piece.getIndex());
  231. if(!isEndGame()) {
  232. if(piece.countCompleteBlock() == 0) {
  233. deleteUsedPiece(piece);
  234. }
  235. }
  236. }
  237. void TorrentMan::updatePiece(const Piece& piece) {
  238. if(Piece::isNull(piece)) {
  239. return;
  240. }
  241. for(UsedPieces::iterator itr = usedPieces.begin(); itr != usedPieces.end(); itr++) {
  242. if(itr->getIndex() == piece.getIndex()) {
  243. *itr = piece;
  244. break;
  245. }
  246. }
  247. }
  248. void TorrentMan::syncPiece(Piece& piece) {
  249. if(Piece::isNull(piece)) {
  250. return;
  251. }
  252. for(UsedPieces::iterator itr = usedPieces.begin(); itr != usedPieces.end(); itr++) {
  253. if(itr->getIndex() == piece.getIndex()) {
  254. piece = *itr;
  255. return;
  256. }
  257. }
  258. // hasPiece(piece.getIndex()) is true, then set all bit of
  259. // piece.bitfield to 1
  260. if(hasPiece(piece.getIndex())) {
  261. piece.setAllBlock();
  262. }
  263. }
  264. void TorrentMan::initBitfield() {
  265. if(bitfield != NULL) {
  266. delete bitfield;
  267. }
  268. bitfield = new BitfieldMan(pieceLength, totalLength);
  269. }
  270. void TorrentMan::setBitfield(unsigned char* bitfield, int bitfieldLength) {
  271. if(this->bitfield == NULL) {
  272. initBitfield();
  273. }
  274. this->bitfield->setBitfield(bitfield, bitfieldLength);
  275. }
  276. bool TorrentMan::downloadComplete() const {
  277. return bitfield->isAllBitSet();
  278. }
  279. void TorrentMan::readFileEntry(FileEntries& fileEntries, Directory** pTopDir, const Dictionary* infoDic, const string& defaultName) {
  280. Data* topName = (Data*)infoDic->get("name");
  281. if(topName != NULL) {
  282. name = topName->toString();
  283. } else {
  284. char* basec = strdup(defaultName.c_str());
  285. name = string(basename(basec))+".file";
  286. free(basec);
  287. }
  288. List* files = (List*)infoDic->get("files");
  289. if(files == NULL) {
  290. // single-file mode;
  291. setFileMode(SINGLE);
  292. Data* length = (Data*)infoDic->get("length");
  293. totalLength = length->toLLInt();
  294. FileEntry fileEntry(name, totalLength, 0);
  295. fileEntries.push_back(fileEntry);
  296. } else {
  297. long long int length = 0;
  298. long long int offset = 0;
  299. // multi-file mode
  300. setFileMode(MULTI);
  301. *pTopDir = new Directory(name);
  302. const MetaList& metaList = files->getList();
  303. for(MetaList::const_iterator itr = metaList.begin(); itr != metaList.end();
  304. itr++) {
  305. Dictionary* fileDic = (Dictionary*)(*itr);
  306. Data* lengthData = (Data*)fileDic->get("length");
  307. length += lengthData->toLLInt();
  308. List* path = (List*)fileDic->get("path");
  309. const MetaList& paths = path->getList();
  310. Directory* parentDir = *pTopDir;
  311. string filePath = name;
  312. for(int i = 0; i < (int)paths.size()-1; i++) {
  313. Data* subpath = (Data*)paths.at(i);
  314. Directory* dir = new Directory(subpath->toString());
  315. parentDir->addFile(dir);
  316. parentDir = dir;
  317. filePath.append("/").append(subpath->toString());
  318. }
  319. Data* lastpath = (Data*)paths.back();
  320. filePath.append("/").append(lastpath->toString());
  321. FileEntry fileEntry(filePath, lengthData->toLLInt(), offset);
  322. fileEntries.push_back(fileEntry);
  323. offset += fileEntry.length;
  324. }
  325. totalLength = length;
  326. }
  327. }
  328. void TorrentMan::setup(string metaInfoFile, const Strings& targetFilePaths) {
  329. peerId = "-A2****-";
  330. for(int i = 0; i < 12; i++) {
  331. peerId += Util::itos((int)(((double)10)*random()/(RAND_MAX+1.0)));
  332. }
  333. uploadLength = 0;
  334. downloadLength = 0;
  335. Dictionary* topDic = (Dictionary*)MetaFileUtil::parseMetaFile(metaInfoFile);
  336. const Dictionary* infoDic = (const Dictionary*)topDic->get("info");
  337. ShaVisitor v;
  338. infoDic->accept(&v);
  339. unsigned char md[20];
  340. int len;
  341. v.getHash(md, len);
  342. setInfoHash(md);
  343. FileEntries fileEntries;
  344. Directory* topDir = NULL;
  345. readFileEntry(fileEntries, &topDir, infoDic, metaInfoFile);
  346. announce = ((Data*)topDic->get("announce"))->toString();
  347. pieceLength = ((Data*)infoDic->get("piece length"))->toInt();
  348. pieces = totalLength/pieceLength+(totalLength%pieceLength ? 1 : 0);
  349. Data* piecesHashData = (Data*)infoDic->get("pieces");
  350. if(piecesHashData->getLen() != pieces*20) {
  351. throw new DlAbortEx("the number of pieces is wrong.");
  352. }
  353. for(int index = 0; index < pieces; index++) {
  354. string hex = Util::toHex((unsigned char*)&piecesHashData->getData()[index*20], 20);
  355. pieceHashes.push_back(hex);
  356. logger->debug("piece #%d, hash:%s", index, hex.c_str());
  357. }
  358. initBitfield();
  359. delete topDic;
  360. if(option->get(PREF_DIRECT_FILE_MAPPING) == V_TRUE) {
  361. if(fileMode == SINGLE) {
  362. diskAdaptor = new DirectDiskAdaptor(new DefaultDiskWriter(totalLength));
  363. } else {
  364. diskAdaptor = new MultiDiskAdaptor(new MultiDiskWriter(pieceLength));
  365. }
  366. } else {
  367. diskAdaptor = new CopyDiskAdaptor(new DefaultDiskWriter(totalLength));
  368. ((CopyDiskAdaptor*)diskAdaptor)->setTempFilename(name+".a2tmp");
  369. }
  370. diskAdaptor->setStoreDir(storeDir);
  371. diskAdaptor->setTopDir(topDir);
  372. diskAdaptor->setFileEntries(fileEntries);
  373. setFileFilter(targetFilePaths);
  374. if(segmentFileExists()) {
  375. load();
  376. diskAdaptor->openExistingFile();
  377. } else {
  378. diskAdaptor->initAndOpenFile();
  379. }
  380. setupComplete = true;
  381. }
  382. void TorrentMan::setFileFilter(const Strings& filePaths) {
  383. if(fileMode != MULTI || filePaths.empty()) {
  384. return;
  385. }
  386. diskAdaptor->removeAllDownloadEntry();
  387. for(Strings::const_iterator pitr = filePaths.begin();
  388. pitr != filePaths.end(); pitr++) {
  389. if(!diskAdaptor->addDownloadEntry(*pitr)) {
  390. throw new DlAbortEx("no such file entry <%s>", (*pitr).c_str());
  391. }
  392. FileEntry fileEntry = diskAdaptor->getFileEntryFromPath(*pitr);
  393. bitfield->addFilter(fileEntry.offset, fileEntry.length);
  394. }
  395. bitfield->enableFilter();
  396. }
  397. FileEntries TorrentMan::readFileEntryFromMetaInfoFile(const string& metaInfoFile) {
  398. Dictionary* topDic = (Dictionary*)MetaFileUtil::parseMetaFile(metaInfoFile);
  399. const Dictionary* infoDic = (const Dictionary*)topDic->get("info");
  400. FileEntries fileEntries;
  401. Directory* topDir = NULL;
  402. readFileEntry(fileEntries, &topDir, infoDic, metaInfoFile);
  403. if(topDir != NULL) {
  404. delete topDir;
  405. }
  406. return fileEntries;
  407. }
  408. string TorrentMan::getName() const {
  409. return name;
  410. }
  411. bool TorrentMan::hasPiece(int index) const {
  412. return bitfield->isBitSet(index);
  413. }
  414. string TorrentMan::getPieceHash(int index) const {
  415. return pieceHashes.at(index);
  416. }
  417. string TorrentMan::getSegmentFilePath() const {
  418. return storeDir+"/"+name+".aria2";
  419. }
  420. bool TorrentMan::segmentFileExists() const {
  421. string segFilename = getSegmentFilePath();
  422. File f(segFilename);
  423. if(f.isFile()) {
  424. logger->info(MSG_SEGMENT_FILE_EXISTS, segFilename.c_str());
  425. return true;
  426. } else {
  427. logger->info(MSG_SEGMENT_FILE_DOES_NOT_EXIST, segFilename.c_str());
  428. return false;
  429. }
  430. }
  431. FILE* TorrentMan::openSegFile(string segFilename, string mode) const {
  432. FILE* segFile = fopen(segFilename.c_str(), mode.c_str());
  433. if(segFile == NULL) {
  434. throw new DlAbortEx(strerror(errno));
  435. }
  436. return segFile;
  437. }
  438. void TorrentMan::load() {
  439. string segFilename = getSegmentFilePath();
  440. logger->info(MSG_LOADING_SEGMENT_FILE, segFilename.c_str());
  441. FILE* segFile = openSegFile(segFilename, "r+");
  442. read(segFile);
  443. fclose(segFile);
  444. logger->info(MSG_LOADED_SEGMENT_FILE);
  445. }
  446. void TorrentMan::read(FILE* file) {
  447. assert(file != NULL);
  448. unsigned char savedInfoHash[INFO_HASH_LENGTH];
  449. if(fread(savedInfoHash, INFO_HASH_LENGTH, 1, file) < 1) {
  450. throw new DlAbortEx(strerror(errno));
  451. }
  452. if(Util::toHex(savedInfoHash, INFO_HASH_LENGTH) != Util::toHex(infoHash, INFO_HASH_LENGTH)) {
  453. throw new DlAbortEx("info hash mismatch");
  454. }
  455. unsigned char* savedBitfield = new unsigned char[bitfield->getBitfieldLength()];
  456. try {
  457. if(fread(savedBitfield, bitfield->getBitfieldLength(), 1, file) < 1) {
  458. throw new DlAbortEx(strerror(errno));
  459. }
  460. setBitfield(savedBitfield, bitfield->getBitfieldLength());
  461. if(fread(&downloadLength, sizeof(downloadLength), 1, file) < 1) {
  462. throw new DlAbortEx(strerror(errno));
  463. }
  464. if(fread(&uploadLength, sizeof(uploadLength), 1, file) < 1) {
  465. throw new DlAbortEx(strerror(errno));
  466. }
  467. preDownloadLength = downloadLength;
  468. preUploadLength = uploadLength;
  469. delete [] savedBitfield;
  470. } catch(Exception* ex) {
  471. delete [] savedBitfield;
  472. throw;
  473. }
  474. }
  475. void TorrentMan::save() const {
  476. if(!setupComplete) {
  477. return;
  478. }
  479. string segFilename = getSegmentFilePath();
  480. logger->info(MSG_SAVING_SEGMENT_FILE, segFilename.c_str());
  481. FILE* file = openSegFile(segFilename, "w");
  482. if(fwrite(infoHash, INFO_HASH_LENGTH, 1, file) < 1) {
  483. throw new DlAbortEx(strerror(errno));
  484. }
  485. if(fwrite(bitfield->getBitfield(), bitfield->getBitfieldLength(), 1, file) < 1) {
  486. throw new DlAbortEx(strerror(errno));
  487. }
  488. if(fwrite(&downloadLength, sizeof(downloadLength), 1, file) < 1) {
  489. throw new DlAbortEx(strerror(errno));
  490. }
  491. if(fwrite(&uploadLength, sizeof(uploadLength), 1, file) < 1) {
  492. throw new DlAbortEx(strerror(errno));
  493. }
  494. fclose(file);
  495. logger->info(MSG_SAVED_SEGMENT_FILE);
  496. }
  497. void TorrentMan::remove() const {
  498. if(segmentFileExists()) {
  499. File f(getSegmentFilePath());
  500. f.remove();
  501. }
  502. }
  503. bool TorrentMan::isSelectiveDownloadingMode() const {
  504. return bitfield->isFilterEnabled();
  505. }
  506. void TorrentMan::finishSelectiveDownloadingMode() {
  507. bitfield->clearFilter();
  508. diskAdaptor->addAllDownloadEntry();
  509. }
  510. long long int TorrentMan::getCompletedLength() const {
  511. return bitfield->getCompletedLength();
  512. }
  513. long long int TorrentMan::getSelectedTotalLength() const {
  514. return bitfield->getFilteredTotalLength();
  515. }
  516. void TorrentMan::onDownloadComplete() {
  517. save();
  518. diskAdaptor->onDownloadComplete();
  519. if(isSelectiveDownloadingMode()) {
  520. finishSelectiveDownloadingMode();
  521. }
  522. }