RequestGroup.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroup.h"
  36. #include "PostDownloadHandler.h"
  37. #include "DownloadEngine.h"
  38. #include "DefaultSegmentManFactory.h"
  39. #include "NullProgressInfoFile.h"
  40. #include "SegmentManFactory.h"
  41. #include "Dependency.h"
  42. #include "prefs.h"
  43. #include "InitiateConnectionCommandFactory.h"
  44. #include "CUIDCounter.h"
  45. #include "File.h"
  46. #include "message.h"
  47. #include "Util.h"
  48. #include "BtRegistry.h"
  49. #include "LogFactory.h"
  50. #include "DiskAdaptor.h"
  51. #include "DiskWriterFactory.h"
  52. #include "RecoverableException.h"
  53. #include "StreamCheckIntegrityEntry.h"
  54. #include "CheckIntegrityCommand.h"
  55. #include "UnknownLengthPieceStorage.h"
  56. #include "SingleFileDownloadContext.h"
  57. #include "DlAbortEx.h"
  58. #include "DownloadFailureException.h"
  59. #include "RequestGroupMan.h"
  60. #include "DefaultBtProgressInfoFile.h"
  61. #include "DefaultPieceStorage.h"
  62. #include "DownloadResult.h"
  63. #include "DownloadHandlerFactory.h"
  64. #include "MemoryBufferPreDownloadHandler.h"
  65. #include "DownloadHandlerConstants.h"
  66. #include "ServerHost.h"
  67. #ifdef ENABLE_MESSAGE_DIGEST
  68. # include "CheckIntegrityCommand.h"
  69. #endif // ENABLE_MESSAGE_DIGEST
  70. #ifdef ENABLE_BITTORRENT
  71. # include "BtCheckIntegrityEntry.h"
  72. # include "DefaultPeerStorage.h"
  73. # include "DefaultBtAnnounce.h"
  74. # include "BtSetup.h"
  75. # include "BtFileAllocationEntry.h"
  76. # include "BtPostDownloadHandler.h"
  77. #endif // ENABLE_BITTORRENT
  78. #ifdef ENABLE_METALINK
  79. # include "MetalinkPostDownloadHandler.h"
  80. #endif // ENABLE_METALINK
  81. int32_t RequestGroup::_gidCounter = 0;
  82. RequestGroup::RequestGroup(const Option* option,
  83. const Strings& uris):
  84. _gid(++_gidCounter),
  85. _uris(uris),
  86. _numConcurrentCommand(0),
  87. _numStreamConnection(0),
  88. _numCommand(0),
  89. _segmentMan(0),
  90. _segmentManFactory(new DefaultSegmentManFactory(option)),
  91. _downloadContext(0),
  92. _pieceStorage(0),
  93. _progressInfoFile(new NullProgressInfoFile()),
  94. _diskWriterFactory(0),
  95. _dependency(0),
  96. _preLocalFileCheckEnabled(true),
  97. _haltRequested(false),
  98. _forceHaltRequested(false),
  99. _singleHostMultiConnectionEnabled(true),
  100. _option(option),
  101. _logger(LogFactory::getInstance())
  102. {
  103. if(_option->get(PREF_FILE_ALLOCATION) == V_PREALLOC) {
  104. _fileAllocationEnabled = true;
  105. } else {
  106. _fileAllocationEnabled = false;
  107. }
  108. initializePreDownloadHandler();
  109. initializePostDownloadHandler();
  110. }
  111. RequestGroup::~RequestGroup() {}
  112. SegmentManHandle RequestGroup::initSegmentMan()
  113. {
  114. _segmentMan = _segmentManFactory->createNewInstance(_downloadContext,
  115. _pieceStorage);
  116. return _segmentMan;
  117. }
  118. bool RequestGroup::downloadFinished() const
  119. {
  120. if(_pieceStorage.isNull()) {
  121. return false;
  122. } else {
  123. return _pieceStorage->downloadFinished();
  124. }
  125. }
  126. bool RequestGroup::allDownloadFinished() const
  127. {
  128. if(_pieceStorage.isNull()) {
  129. return false;
  130. } else {
  131. return _pieceStorage->allDownloadFinished();
  132. }
  133. }
  134. void RequestGroup::closeFile()
  135. {
  136. if(!_pieceStorage.isNull()) {
  137. _pieceStorage->getDiskAdaptor()->closeFile();
  138. }
  139. }
  140. Commands RequestGroup::createInitialCommand(DownloadEngine* e)
  141. {
  142. #ifdef ENABLE_BITTORRENT
  143. {
  144. BtContextHandle btContext = _downloadContext;
  145. if(!btContext.isNull()) {
  146. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  147. throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD,
  148. getFilePath().c_str());
  149. }
  150. initPieceStorage();
  151. if(btContext->getFileEntries().size() > 1) {
  152. // this is really multi file torrent.
  153. // clear http/ftp uris because the current implementation does not
  154. // allow integrating multi-file torrent and http/ftp.
  155. _logger->debug("Clearing http/ftp URIs because the current implementation does not allow integrating multi-file torrent and http/ftp.");
  156. _uris.clear();
  157. _pieceStorage->setFileFilter(Util::parseIntRange(_option->get(PREF_SELECT_FILE)));
  158. }
  159. BtProgressInfoFileHandle progressInfoFile =
  160. new DefaultBtProgressInfoFile(_downloadContext,
  161. _pieceStorage,
  162. _option);
  163. BtRegistry::registerBtContext(btContext->getInfoHashAsString(), btContext);
  164. BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
  165. _pieceStorage);
  166. BtRegistry::registerBtProgressInfoFile(btContext->getInfoHashAsString(),
  167. progressInfoFile);
  168. BtRuntimeHandle btRuntime = new BtRuntime();
  169. btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT));
  170. BtRegistry::registerBtRuntime(btContext->getInfoHashAsString(), btRuntime);
  171. PeerStorageHandle peerStorage = new DefaultPeerStorage(btContext, _option);
  172. BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage);
  173. BtAnnounceHandle btAnnounce = new DefaultBtAnnounce(btContext, _option);
  174. BtRegistry::registerBtAnnounce(btContext->getInfoHashAsString(), btAnnounce);
  175. btAnnounce->shuffleAnnounce();
  176. BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
  177. new PeerObjectCluster());
  178. // Remove the control file if download file doesn't exist
  179. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  180. progressInfoFile->removeFile();
  181. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  182. progressInfoFile->getFilename().c_str(),
  183. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  184. }
  185. // Call Load, Save and file allocation command here
  186. if(progressInfoFile->exists()) {
  187. // load .aria2 file if it exists.
  188. progressInfoFile->load();
  189. _pieceStorage->getDiskAdaptor()->openFile();
  190. } else {
  191. if(_pieceStorage->getDiskAdaptor()->fileExists()) {
  192. if(_option->get(PREF_CHECK_INTEGRITY) != V_TRUE &&
  193. _option->get(PREF_ALLOW_OVERWRITE) != V_TRUE) {
  194. // TODO we need this->haltRequested = true?
  195. throw new DownloadFailureException(MSG_FILE_ALREADY_EXISTS,
  196. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  197. } else {
  198. _pieceStorage->getDiskAdaptor()->openFile();
  199. }
  200. } else {
  201. _pieceStorage->getDiskAdaptor()->openFile();
  202. }
  203. }
  204. _progressInfoFile = progressInfoFile;
  205. CheckIntegrityEntryHandle entry = new BtCheckIntegrityEntry(this);
  206. return processCheckIntegrityEntry(entry, e);
  207. }
  208. }
  209. #endif // ENABLE_BITTORRENT
  210. // TODO I assume here when totallength is set to DownloadContext and it is
  211. // not 0, then filepath is also set DownloadContext correctly....
  212. if(_downloadContext->getTotalLength() == 0) {
  213. return createNextCommand(e, 1);
  214. }else {
  215. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  216. throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD,
  217. getFilePath().c_str());
  218. }
  219. initPieceStorage();
  220. BtProgressInfoFileHandle infoFile =
  221. new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option);
  222. if(!infoFile->exists() && downloadFinishedByFileLength()) {
  223. return Commands();
  224. }
  225. loadAndOpenFile(infoFile);
  226. return processCheckIntegrityEntry(new StreamCheckIntegrityEntry(0, this), e);
  227. }
  228. }
  229. Commands RequestGroup::processCheckIntegrityEntry(const CheckIntegrityEntryHandle& entry, DownloadEngine* e)
  230. {
  231. #ifdef ENABLE_MESSAGE_DIGEST
  232. if(e->option->get(PREF_CHECK_INTEGRITY) == V_TRUE &&
  233. entry->isValidationReady()) {
  234. entry->initValidator();
  235. CheckIntegrityCommand* command =
  236. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), this, e, entry);
  237. Commands commands;
  238. commands.push_back(command);
  239. return commands;
  240. } else
  241. #endif // ENABLE_MESSAGE_DIGEST
  242. {
  243. return entry->onDownloadIncomplete(e);
  244. }
  245. }
  246. void RequestGroup::initPieceStorage()
  247. {
  248. if(_downloadContext->getTotalLength() == 0) {
  249. UnknownLengthPieceStorageHandle ps = new UnknownLengthPieceStorage(_downloadContext, _option);
  250. if(!_diskWriterFactory.isNull()) {
  251. ps->setDiskWriterFactory(_diskWriterFactory);
  252. }
  253. _pieceStorage = ps;
  254. } else {
  255. DefaultPieceStorageHandle ps = new DefaultPieceStorage(_downloadContext, _option);
  256. if(!_diskWriterFactory.isNull()) {
  257. ps->setDiskWriterFactory(_diskWriterFactory);
  258. }
  259. _pieceStorage = ps;
  260. }
  261. _pieceStorage->initStorage();
  262. initSegmentMan();
  263. }
  264. bool RequestGroup::downloadFinishedByFileLength()
  265. {
  266. // assuming that a control file doesn't exist.
  267. if(!isPreLocalFileCheckEnabled() ||
  268. _option->get(PREF_ALLOW_OVERWRITE) == V_TRUE ||
  269. _option->get(PREF_CHECK_INTEGRITY) == V_TRUE &&
  270. !_downloadContext->getPieceHashes().empty()) {
  271. return false;
  272. }
  273. // TODO consider the case when the getFilePath() returns dir path.
  274. File outfile(getFilePath());
  275. if(outfile.exists() && getTotalLength() == outfile.size()) {
  276. _pieceStorage->markAllPiecesDone();
  277. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, _gid, getFilePath().c_str());
  278. return true;
  279. } else {
  280. return false;
  281. }
  282. }
  283. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  284. {
  285. try {
  286. if(!isPreLocalFileCheckEnabled()) {
  287. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  288. return;
  289. }
  290. // Remove the control file if download file doesn't exist
  291. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  292. progressInfoFile->removeFile();
  293. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  294. progressInfoFile->getFilename().c_str(),
  295. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  296. }
  297. if(progressInfoFile->exists()) {
  298. progressInfoFile->load();
  299. _pieceStorage->getDiskAdaptor()->openExistingFile();
  300. } else {
  301. File outfile(getFilePath());
  302. if(outfile.exists() && _option->get(PREF_CONTINUE) == V_TRUE) {
  303. if(getTotalLength() < outfile.size()) {
  304. throw new DlAbortEx(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
  305. getFilePath().c_str(),
  306. Util::llitos(outfile.size()).c_str(),
  307. Util::llitos(getTotalLength()).c_str());
  308. }
  309. _pieceStorage->getDiskAdaptor()->openExistingFile();
  310. _pieceStorage->markPiecesDone(outfile.size());
  311. } else {
  312. #ifdef ENABLE_MESSAGE_DIGEST
  313. if(outfile.exists() && _option->get(PREF_CHECK_INTEGRITY) == V_TRUE) {
  314. _pieceStorage->getDiskAdaptor()->openExistingFile();
  315. } else {
  316. shouldCancelDownloadForSafety();
  317. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  318. }
  319. #else // ENABLE_MESSAGE_DIGEST
  320. shouldCancelDownloadForSafety();
  321. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  322. #endif // ENABLE_MESSAGE_DIGEST
  323. }
  324. }
  325. setProgressInfoFile(progressInfoFile);
  326. } catch(RecoverableException* e) {
  327. throw new DownloadFailureException(e, EX_DOWNLOAD_ABORTED);
  328. }
  329. }
  330. // assuming that a control file does not exist
  331. void RequestGroup::shouldCancelDownloadForSafety()
  332. {
  333. if(_option->get(PREF_ALLOW_OVERWRITE) == V_TRUE) {
  334. return;
  335. }
  336. File outfile(getFilePath());
  337. if(outfile.exists()) {
  338. if(_option->get(PREF_AUTO_FILE_RENAMING) == V_TRUE) {
  339. if(tryAutoFileRenaming()) {
  340. _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
  341. } else {
  342. throw new DownloadFailureException("File renaming failed: %s",
  343. getFilePath().c_str());
  344. }
  345. } else {
  346. throw new DownloadFailureException(MSG_FILE_ALREADY_EXISTS,
  347. getFilePath().c_str());
  348. }
  349. }
  350. }
  351. bool RequestGroup::tryAutoFileRenaming()
  352. {
  353. string filepath = getFilePath();
  354. if(filepath.empty()) {
  355. return false;
  356. }
  357. for(int32_t i = 1; i < 10000; ++i) {
  358. File newfile(filepath+"."+Util::itos(i));
  359. if(!newfile.exists()) {
  360. SingleFileDownloadContextHandle(_downloadContext)->setUFilename(newfile.getBasename());
  361. return true;
  362. }
  363. }
  364. return false;
  365. }
  366. Commands RequestGroup::createNextCommandWithAdj(DownloadEngine* e, int32_t numAdj)
  367. {
  368. int32_t numCommand = _numConcurrentCommand == 0 ? _uris.size() : _numConcurrentCommand+numAdj;
  369. return createNextCommand(e, numCommand, "GET");
  370. }
  371. Commands RequestGroup::createNextCommand(DownloadEngine* e, int32_t numCommand, const string& method)
  372. {
  373. Commands commands;
  374. Strings pendingURIs;
  375. for(;!_uris.empty() && numCommand--; _uris.pop_front()) {
  376. string uri = _uris.front();
  377. RequestHandle req = new Request();
  378. if(req->setUrl(uri)) {
  379. ServerHostHandle sv = _singleHostMultiConnectionEnabled ? 0 : searchServerHost(req->getHost());
  380. if(sv.isNull()) {
  381. _spentUris.push_back(uri);
  382. req->setReferer(_option->get(PREF_REFERER));
  383. req->setMethod(method);
  384. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(), req, this, e);
  385. ServerHostHandle sv = new ServerHost(command->getCuid(), req->getHost());
  386. registerServerHost(sv);
  387. commands.push_back(command);
  388. } else {
  389. pendingURIs.push_front(uri);
  390. }
  391. } else {
  392. _logger->error(MSG_UNRECOGNIZED_URI, req->getUrl().c_str());
  393. }
  394. }
  395. copy(pendingURIs.begin(), pendingURIs.end(), front_inserter(_uris));
  396. return commands;
  397. }
  398. string RequestGroup::getFilePath() const
  399. {
  400. assert(!_downloadContext.isNull());
  401. if(_downloadContext.isNull()) {
  402. return "";
  403. } else {
  404. return _downloadContext->getActualBasePath();
  405. }
  406. }
  407. int64_t RequestGroup::getTotalLength() const
  408. {
  409. if(_pieceStorage.isNull()) {
  410. return 0;
  411. } else {
  412. if(_pieceStorage->isSelectiveDownloadingMode()) {
  413. return _pieceStorage->getFilteredTotalLength();
  414. } else {
  415. return _pieceStorage->getTotalLength();
  416. }
  417. }
  418. }
  419. int64_t RequestGroup::getCompletedLength() const
  420. {
  421. if(_pieceStorage.isNull()) {
  422. return 0;
  423. } else {
  424. if(_pieceStorage->isSelectiveDownloadingMode()) {
  425. return _pieceStorage->getFilteredCompletedLength();
  426. } else {
  427. return _pieceStorage->getCompletedLength();
  428. }
  429. }
  430. }
  431. void RequestGroup::validateFilename(const string& expectedFilename,
  432. const string& actualFilename) const
  433. {
  434. if(expectedFilename.empty()) {
  435. return;
  436. }
  437. if(expectedFilename != actualFilename) {
  438. throw new DlAbortEx(EX_FILENAME_MISMATCH,
  439. expectedFilename.c_str(),
  440. actualFilename.c_str());
  441. }
  442. }
  443. void RequestGroup::validateTotalLength(int64_t expectedTotalLength,
  444. int64_t actualTotalLength) const
  445. {
  446. if(expectedTotalLength <= 0) {
  447. return;
  448. }
  449. if(expectedTotalLength != actualTotalLength) {
  450. throw new DlAbortEx(EX_SIZE_MISMATCH,
  451. Util::llitos(expectedTotalLength, true).c_str(),
  452. Util::llitos(actualTotalLength, true).c_str());
  453. }
  454. }
  455. void RequestGroup::validateFilename(const string& actualFilename) const
  456. {
  457. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  458. }
  459. void RequestGroup::validateTotalLength(int64_t actualTotalLength) const
  460. {
  461. validateTotalLength(getTotalLength(), actualTotalLength);
  462. }
  463. void RequestGroup::increaseStreamConnection()
  464. {
  465. ++_numStreamConnection;
  466. }
  467. void RequestGroup::decreaseStreamConnection()
  468. {
  469. --_numStreamConnection;
  470. }
  471. int32_t RequestGroup::getNumConnection() const
  472. {
  473. int32_t numConnection = _numStreamConnection;
  474. #ifdef ENABLE_BITTORRENT
  475. {
  476. BtContextHandle btContext = _downloadContext;
  477. if(!btContext.isNull()) {
  478. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  479. if(!btRuntime.isNull()) {
  480. numConnection += btRuntime->getConnections();
  481. }
  482. }
  483. }
  484. #endif // ENABLE_BITTORRENT
  485. return numConnection;
  486. }
  487. void RequestGroup::increaseNumCommand()
  488. {
  489. ++_numCommand;
  490. }
  491. void RequestGroup::decreaseNumCommand()
  492. {
  493. --_numCommand;
  494. }
  495. TransferStat RequestGroup::calculateStat()
  496. {
  497. TransferStat stat;
  498. #ifdef ENABLE_BITTORRENT
  499. {
  500. BtContextHandle btContext = _downloadContext;
  501. if(!btContext.isNull()) {
  502. PeerStorageHandle peerStorage = PEER_STORAGE(btContext);
  503. if(!peerStorage.isNull()) {
  504. stat = peerStorage->calculateStat();
  505. }
  506. }
  507. }
  508. #endif // ENABLE_BITTORRENT
  509. if(!_segmentMan.isNull()) {
  510. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  511. }
  512. return stat;
  513. }
  514. void RequestGroup::setHaltRequested(bool f)
  515. {
  516. _haltRequested = f;
  517. #ifdef ENABLE_BITTORRENT
  518. {
  519. BtContextHandle btContext = _downloadContext;
  520. if(!btContext.isNull()) {
  521. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  522. if(!btRuntime.isNull()) {
  523. btRuntime->setHalt(f);
  524. }
  525. }
  526. }
  527. #endif // ENABLE_BITTORRENT
  528. }
  529. void RequestGroup::setForceHaltRequested(bool f)
  530. {
  531. setHaltRequested(f);
  532. _forceHaltRequested = f;
  533. }
  534. void RequestGroup::releaseRuntimeResource()
  535. {
  536. #ifdef ENABLE_BITTORRENT
  537. BtContextHandle btContext = _downloadContext;
  538. if(!btContext.isNull()) {
  539. BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString());
  540. if(!btContextInReg.isNull() &&
  541. btContextInReg->getOwnerRequestGroup()->getGID() ==
  542. btContext->getOwnerRequestGroup()->getGID()) {
  543. BtRegistry::unregister(btContext->getInfoHashAsString());
  544. }
  545. }
  546. #endif // ENABLE_BITTORRENT
  547. if(!_pieceStorage.isNull()) {
  548. _pieceStorage->removeAdvertisedPiece(0);
  549. }
  550. }
  551. void RequestGroup::preDownloadProcessing()
  552. {
  553. _logger->debug("Finding PreDownloadHandler for path %s.", getFilePath().c_str());
  554. try {
  555. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  556. itr != _preDownloadHandlers.end(); ++itr) {
  557. if((*itr)->canHandle(this)) {
  558. (*itr)->execute(this);
  559. return;
  560. }
  561. }
  562. } catch(RecoverableException* ex) {
  563. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  564. delete ex;
  565. return;
  566. }
  567. _logger->debug("No PreDownloadHandler found.");
  568. return;
  569. }
  570. RequestGroups RequestGroup::postDownloadProcessing()
  571. {
  572. _logger->debug("Finding PostDownloadHandler for path %s.", getFilePath().c_str());
  573. try {
  574. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  575. itr != _postDownloadHandlers.end(); ++itr) {
  576. if((*itr)->canHandle(this)) {
  577. return (*itr)->getNextRequestGroups(this);
  578. }
  579. }
  580. } catch(RecoverableException* ex) {
  581. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  582. delete ex;
  583. return RequestGroups();
  584. }
  585. _logger->debug("No PostDownloadHandler found.");
  586. return RequestGroups();
  587. }
  588. void RequestGroup::initializePreDownloadHandler()
  589. {
  590. #ifdef ENABLE_BITTORRENT
  591. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  592. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  593. }
  594. #endif // ENABLE_BITTORRENT
  595. #ifdef ENABLE_METALINK
  596. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  597. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  598. }
  599. #endif // ENABLE_METALINK
  600. }
  601. void RequestGroup::initializePostDownloadHandler()
  602. {
  603. #ifdef ENABLE_BITTORRENT
  604. if(_option->get(PREF_FOLLOW_TORRENT) == V_TRUE ||
  605. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  606. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  607. }
  608. #endif // ENABLE_BITTORRENT
  609. #ifdef ENABLE_METALINK
  610. if(_option->get(PREF_FOLLOW_METALINK) == V_TRUE ||
  611. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  612. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  613. }
  614. #endif // ENABLE_METALINK
  615. }
  616. Strings RequestGroup::getUris() const
  617. {
  618. Strings temp(_spentUris.begin(), _spentUris.end());
  619. temp.insert(temp.end(), _uris.begin(), _uris.end());
  620. return temp;
  621. }
  622. bool RequestGroup::isDependencyResolved()
  623. {
  624. if(_dependency.isNull()) {
  625. return true;
  626. }
  627. return _dependency->resolve();
  628. }
  629. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  630. {
  631. _segmentManFactory = segmentManFactory;
  632. }
  633. void RequestGroup::dependsOn(const DependencyHandle& dep)
  634. {
  635. _dependency = dep;
  636. }
  637. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  638. {
  639. _diskWriterFactory = diskWriterFactory;
  640. }
  641. DiskWriterFactoryHandle RequestGroup::getDiskWriterFactory() const
  642. {
  643. return _diskWriterFactory;
  644. }
  645. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  646. {
  647. _postDownloadHandlers.push_back(handler);
  648. }
  649. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  650. {
  651. _preDownloadHandlers.push_back(handler);
  652. }
  653. void RequestGroup::clearPostDowloadHandler()
  654. {
  655. _postDownloadHandlers.clear();
  656. }
  657. void RequestGroup::clearPreDowloadHandler()
  658. {
  659. _preDownloadHandlers.clear();
  660. }
  661. SegmentManHandle RequestGroup::getSegmentMan() const
  662. {
  663. return _segmentMan;
  664. }
  665. DownloadContextHandle RequestGroup::getDownloadContext() const
  666. {
  667. return _downloadContext;
  668. }
  669. void RequestGroup::setDownloadContext(const DownloadContextHandle& downloadContext)
  670. {
  671. _downloadContext = downloadContext;
  672. }
  673. PieceStorageHandle RequestGroup::getPieceStorage() const
  674. {
  675. return _pieceStorage;
  676. }
  677. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  678. {
  679. _pieceStorage = pieceStorage;
  680. }
  681. BtProgressInfoFileHandle RequestGroup::getProgressInfoFile() const
  682. {
  683. return _progressInfoFile;
  684. }
  685. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  686. {
  687. _progressInfoFile = progressInfoFile;
  688. }
  689. bool RequestGroup::needsFileAllocation() const
  690. {
  691. return isFileAllocationEnabled() &&
  692. _option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  693. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  694. }
  695. DownloadResultHandle RequestGroup::createDownloadResult() const
  696. {
  697. Strings uris = getUris();
  698. return new DownloadResult(_gid,
  699. getFilePath(),
  700. getTotalLength(),
  701. uris.empty() ? "":uris.front(),
  702. uris.size(),
  703. downloadFinished()?
  704. DownloadResult::FINISHED :
  705. DownloadResult::NOT_YET);
  706. }
  707. void RequestGroup::registerServerHost(const ServerHostHandle& serverHost)
  708. {
  709. _serverHosts.push_back(serverHost);
  710. }
  711. class FindServerHostByCUID
  712. {
  713. private:
  714. int32_t _cuid;
  715. public:
  716. FindServerHostByCUID(int32_t cuid):_cuid(cuid) {}
  717. bool operator()(const ServerHostHandle& sv) const
  718. {
  719. return sv->getCuid() == _cuid;
  720. }
  721. };
  722. ServerHostHandle RequestGroup::searchServerHost(int32_t cuid) const
  723. {
  724. ServerHosts::const_iterator itr = find_if(_serverHosts.begin(),
  725. _serverHosts.end(),
  726. FindServerHostByCUID(cuid));
  727. if(itr == _serverHosts.end()) {
  728. return 0;
  729. } else {
  730. return *itr;
  731. }
  732. }
  733. class FindServerHostByHostname
  734. {
  735. private:
  736. const string& _hostname;
  737. public:
  738. FindServerHostByHostname(const string& hostname):_hostname(hostname) {}
  739. bool operator()(const ServerHostHandle& sv) const
  740. {
  741. return sv->getHostname() == _hostname;
  742. }
  743. };
  744. ServerHostHandle RequestGroup::searchServerHost(const string& hostname) const
  745. {
  746. ServerHosts::const_iterator itr = find_if(_serverHosts.begin(),
  747. _serverHosts.end(),
  748. FindServerHostByHostname(hostname));
  749. if(itr == _serverHosts.end()) {
  750. return 0;
  751. } else {
  752. return *itr;
  753. }
  754. }
  755. void RequestGroup::removeServerHost(int32_t cuid)
  756. {
  757. _serverHosts.erase(remove_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid)), _serverHosts.end());
  758. }
  759. void RequestGroup::removeURIWhoseHostnameIs(const string& hostname)
  760. {
  761. Strings newURIs;
  762. Request req;
  763. for(Strings::const_iterator itr = _uris.begin(); itr != _uris.end(); ++itr) {
  764. if((*itr).find(hostname) == string::npos ||
  765. req.setUrl(*itr) && req.getHost() != hostname) {
  766. newURIs.push_back(*itr);
  767. }
  768. }
  769. _logger->debug("GUID#%d - Removed %d duplicate hostname URIs",
  770. _gid, _uris.size()-newURIs.size());
  771. _uris = newURIs;
  772. }
  773. void RequestGroup::reportDownloadFinished()
  774. {
  775. _logger->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  776. getFilePath().c_str());
  777. #ifdef ENABLE_BITTORRENT
  778. TransferStat stat = calculateStat();
  779. if(!BtContextHandle(_downloadContext).isNull()) {
  780. double shareRatio = ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  781. _logger->notice(MSG_SHARE_RATIO_REPORT,
  782. shareRatio,
  783. Util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  784. Util::abbrevSize(getCompletedLength()).c_str());
  785. }
  786. #endif // ENABLE_BITTORRENT
  787. }