RequestGroup.cc 29 KB

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