RequestGroup.cc 32 KB

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