RequestGroup.cc 26 KB

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