RequestGroup.cc 32 KB

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