RequestGroup.cc 32 KB

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