RequestGroup.cc 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroup.h"
  36. #include "PostDownloadHandler.h"
  37. #include "DownloadEngine.h"
  38. #include "DefaultSegmentManFactory.h"
  39. #include "SegmentMan.h"
  40. #include "NullProgressInfoFile.h"
  41. #include "Dependency.h"
  42. #include "prefs.h"
  43. #include "InitiateConnectionCommandFactory.h"
  44. #include "CUIDCounter.h"
  45. #include "File.h"
  46. #include "message.h"
  47. #include "Util.h"
  48. #include "BtRegistry.h"
  49. #include "LogFactory.h"
  50. #include "Logger.h"
  51. #include "DiskAdaptor.h"
  52. #include "DiskWriterFactory.h"
  53. #include "RecoverableException.h"
  54. #include "StreamCheckIntegrityEntry.h"
  55. #include "CheckIntegrityCommand.h"
  56. #include "UnknownLengthPieceStorage.h"
  57. #include "BtContext.h"
  58. #include "SingleFileDownloadContext.h"
  59. #include "DlAbortEx.h"
  60. #include "DownloadFailureException.h"
  61. #include "RequestGroupMan.h"
  62. #include "DefaultBtProgressInfoFile.h"
  63. #include "DefaultPieceStorage.h"
  64. #include "DownloadResult.h"
  65. #include "DownloadHandlerFactory.h"
  66. #include "MemoryBufferPreDownloadHandler.h"
  67. #include "DownloadHandlerConstants.h"
  68. #include "ServerHost.h"
  69. #include "Option.h"
  70. #include "FileEntry.h"
  71. #include "Request.h"
  72. #include "FileAllocationIterator.h"
  73. #include "StringFormat.h"
  74. #include "A2STR.h"
  75. #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 "PeerObject.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. #include <cassert>
  104. #include <algorithm>
  105. namespace aria2 {
  106. int32_t RequestGroup::_gidCounter = 0;
  107. const std::string RequestGroup::ACCEPT_METALINK = "application/metalink+xml";
  108. RequestGroup::RequestGroup(const Option* option,
  109. const std::deque<std::string>& uris):
  110. _gid(++_gidCounter),
  111. _uris(uris),
  112. _numConcurrentCommand(0),
  113. _numStreamConnection(0),
  114. _numCommand(0),
  115. _segmentManFactory(new DefaultSegmentManFactory(option)),
  116. _progressInfoFile(new NullProgressInfoFile()),
  117. _preLocalFileCheckEnabled(true),
  118. _haltRequested(false),
  119. _forceHaltRequested(false),
  120. _singleHostMultiConnectionEnabled(true),
  121. _uriSelector(new InOrderURISelector()),
  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. BtProgressInfoFileHandle
  189. progressInfoFile(new DefaultBtProgressInfoFile(_downloadContext,
  190. _pieceStorage,
  191. _option));
  192. BtRegistry::registerBtContext(btContext->getInfoHashAsString(), btContext);
  193. BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
  194. _pieceStorage);
  195. BtRegistry::registerBtProgressInfoFile(btContext->getInfoHashAsString(),
  196. progressInfoFile);
  197. BtRuntimeHandle btRuntime(new BtRuntime());
  198. btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT));
  199. BtRegistry::registerBtRuntime(btContext->getInfoHashAsString(), btRuntime);
  200. PeerStorageHandle peerStorage(new DefaultPeerStorage(btContext, _option));
  201. BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage);
  202. BtAnnounceHandle btAnnounce(new DefaultBtAnnounce(btContext, _option));
  203. BtRegistry::registerBtAnnounce(btContext->getInfoHashAsString(), btAnnounce);
  204. btAnnounce->shuffleAnnounce();
  205. {
  206. SharedHandle<PeerObjectCluster> po(new PeerObjectCluster());
  207. BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
  208. po);
  209. }
  210. // Remove the control file if download file doesn't exist
  211. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  212. progressInfoFile->removeFile();
  213. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  214. progressInfoFile->getFilename().c_str(),
  215. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  216. }
  217. // Call Load, Save and file allocation command here
  218. if(progressInfoFile->exists()) {
  219. // load .aria2 file if it exists.
  220. progressInfoFile->load();
  221. _pieceStorage->getDiskAdaptor()->openFile();
  222. } else {
  223. if(_pieceStorage->getDiskAdaptor()->fileExists()) {
  224. if(!_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  225. !_option->getAsBool(PREF_ALLOW_OVERWRITE) &&
  226. !_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  227. // TODO we need this->haltRequested = true?
  228. throw DownloadFailureException
  229. (StringFormat
  230. (MSG_FILE_ALREADY_EXISTS,
  231. _pieceStorage->getDiskAdaptor()->getFilePath().c_str()).str());
  232. } else {
  233. _pieceStorage->getDiskAdaptor()->openFile();
  234. }
  235. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  236. _pieceStorage->markAllPiecesDone();
  237. }
  238. } else {
  239. _pieceStorage->getDiskAdaptor()->openFile();
  240. }
  241. }
  242. _progressInfoFile = progressInfoFile;
  243. if(!btContext->isPrivate() && _option->getAsBool(PREF_ENABLE_DHT)) {
  244. std::deque<Command*> commands;
  245. DHTSetup().setup(commands, e, _option);
  246. e->addCommand(commands);
  247. if(!btContext->getNodes().empty() && DHTSetup::initialized()) {
  248. DHTEntryPointNameResolveCommand* command =
  249. new DHTEntryPointNameResolveCommand(CUIDCounterSingletonHolder::instance()->newID(), e, btContext->getNodes());
  250. command->setTaskQueue(DHTRegistry::_taskQueue);
  251. command->setTaskFactory(DHTRegistry::_taskFactory);
  252. command->setRoutingTable(DHTRegistry::_routingTable);
  253. command->setLocalNode(DHTRegistry::_localNode);
  254. e->commands.push_back(command);
  255. }
  256. }
  257. CheckIntegrityEntryHandle entry(new BtCheckIntegrityEntry(this));
  258. // --bt-seed-unverified=true is given and download has completed, skip
  259. // validation for piece hashes.
  260. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  261. _pieceStorage->downloadFinished()) {
  262. entry->onDownloadFinished(commands, e);
  263. } else {
  264. processCheckIntegrityEntry(commands, entry, e);
  265. }
  266. return;
  267. }
  268. }
  269. #endif // ENABLE_BITTORRENT
  270. // TODO I assume here when totallength is set to DownloadContext and it is
  271. // not 0, then filepath is also set DownloadContext correctly....
  272. if(_downloadContext->getTotalLength() == 0) {
  273. createNextCommand(commands, e, 1);
  274. }else {
  275. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  276. throw DownloadFailureException
  277. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  278. getFilePath().c_str()).str());
  279. }
  280. initPieceStorage();
  281. BtProgressInfoFileHandle infoFile
  282. (new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option));
  283. if(infoFile->exists() || !downloadFinishedByFileLength()) {
  284. loadAndOpenFile(infoFile);
  285. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry
  286. (new StreamCheckIntegrityEntry(SharedHandle<Request>(), this));
  287. processCheckIntegrityEntry(commands, checkIntegrityEntry, e);
  288. }
  289. }
  290. }
  291. void RequestGroup::processCheckIntegrityEntry(std::deque<Command*>& commands,
  292. const CheckIntegrityEntryHandle& entry,
  293. DownloadEngine* e)
  294. {
  295. #ifdef ENABLE_MESSAGE_DIGEST
  296. if(e->option->getAsBool(PREF_CHECK_INTEGRITY) &&
  297. entry->isValidationReady()) {
  298. entry->initValidator();
  299. CheckIntegrityCommand* command =
  300. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), this, e, entry);
  301. commands.push_back(command);
  302. } else
  303. #endif // ENABLE_MESSAGE_DIGEST
  304. {
  305. entry->onDownloadIncomplete(commands, e);
  306. }
  307. }
  308. void RequestGroup::initPieceStorage()
  309. {
  310. if(_downloadContext->getTotalLength() == 0) {
  311. UnknownLengthPieceStorageHandle ps(new UnknownLengthPieceStorage(_downloadContext, _option));
  312. if(!_diskWriterFactory.isNull()) {
  313. ps->setDiskWriterFactory(_diskWriterFactory);
  314. }
  315. _pieceStorage = ps;
  316. } else {
  317. DefaultPieceStorageHandle ps(new DefaultPieceStorage(_downloadContext, _option));
  318. if(!_diskWriterFactory.isNull()) {
  319. ps->setDiskWriterFactory(_diskWriterFactory);
  320. }
  321. _pieceStorage = ps;
  322. }
  323. _pieceStorage->initStorage();
  324. initSegmentMan();
  325. }
  326. bool RequestGroup::downloadFinishedByFileLength()
  327. {
  328. // assuming that a control file doesn't exist.
  329. if(!isPreLocalFileCheckEnabled() ||
  330. _option->getAsBool(PREF_ALLOW_OVERWRITE) ||
  331. (_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  332. !_downloadContext->getPieceHashes().empty())) {
  333. return false;
  334. }
  335. // TODO consider the case when the getFilePath() returns dir path.
  336. File outfile(getFilePath());
  337. if(outfile.exists() && getTotalLength() == outfile.size()) {
  338. _pieceStorage->markAllPiecesDone();
  339. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, _gid, getFilePath().c_str());
  340. return true;
  341. } else {
  342. return false;
  343. }
  344. }
  345. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  346. {
  347. try {
  348. if(!isPreLocalFileCheckEnabled()) {
  349. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  350. return;
  351. }
  352. // Remove the control file if download file doesn't exist
  353. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  354. progressInfoFile->removeFile();
  355. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  356. progressInfoFile->getFilename().c_str(),
  357. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  358. }
  359. while(1) {
  360. if(progressInfoFile->exists()) {
  361. progressInfoFile->load();
  362. _pieceStorage->getDiskAdaptor()->openExistingFile();
  363. } else {
  364. File outfile(getFilePath());
  365. if(outfile.exists() && _option->getAsBool(PREF_CONTINUE)) {
  366. if(getTotalLength() < outfile.size()) {
  367. throw DlAbortEx
  368. (StringFormat(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
  369. getFilePath().c_str(),
  370. Util::itos(outfile.size()).c_str(),
  371. Util::itos(getTotalLength()).c_str()).str());
  372. }
  373. _pieceStorage->getDiskAdaptor()->openExistingFile();
  374. _pieceStorage->markPiecesDone(outfile.size());
  375. } else {
  376. #ifdef ENABLE_MESSAGE_DIGEST
  377. if(outfile.exists() && _option->getAsBool(PREF_CHECK_INTEGRITY)) {
  378. _pieceStorage->getDiskAdaptor()->openExistingFile();
  379. } else {
  380. #endif // ENABLE_MESSAGE_DIGEST
  381. shouldCancelDownloadForSafety();
  382. // call updateFilename here in case when filename is renamed
  383. // by tryAutoFileRenaming()
  384. progressInfoFile->updateFilename();
  385. if(progressInfoFile->exists()) {
  386. // Close DiskAdaptor here. Renmaed file will be opened in the
  387. // next loop .
  388. _pieceStorage->getDiskAdaptor()->closeFile();
  389. continue;
  390. }
  391. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  392. #ifdef ENABLE_MESSAGE_DIGEST
  393. }
  394. #endif // ENABLE_MESSAGE_DIGEST
  395. }
  396. }
  397. setProgressInfoFile(progressInfoFile);
  398. break;
  399. }
  400. } catch(RecoverableException& e) {
  401. throw DownloadFailureException
  402. (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
  403. }
  404. }
  405. // assuming that a control file does not exist
  406. void RequestGroup::shouldCancelDownloadForSafety()
  407. {
  408. if(_option->getAsBool(PREF_ALLOW_OVERWRITE)) {
  409. return;
  410. }
  411. File outfile(getFilePath());
  412. if(outfile.exists()) {
  413. if(_option->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  414. if(tryAutoFileRenaming()) {
  415. _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
  416. } else {
  417. throw DownloadFailureException
  418. (StringFormat("File renaming failed: %s",
  419. getFilePath().c_str()).str());
  420. }
  421. } else {
  422. throw DownloadFailureException
  423. (StringFormat(MSG_FILE_ALREADY_EXISTS,
  424. getFilePath().c_str()).str());
  425. }
  426. }
  427. }
  428. bool RequestGroup::tryAutoFileRenaming()
  429. {
  430. std::string filepath = getFilePath();
  431. if(filepath.empty()) {
  432. return false;
  433. }
  434. SingleFileDownloadContextHandle ctx =
  435. dynamic_pointer_cast<SingleFileDownloadContext>(_downloadContext);
  436. // Make a copy of ctx.
  437. SingleFileDownloadContextHandle tempCtx(new SingleFileDownloadContext(*ctx.get()));
  438. DefaultBtProgressInfoFile tempInfoFile(tempCtx, SharedHandle<PieceStorage>(), 0);
  439. for(unsigned int i = 1; i < 10000; ++i) {
  440. File newfile(filepath+"."+Util::uitos(i));
  441. std::string newFilename = newfile.getBasename();
  442. tempCtx->setUFilename(newFilename);
  443. tempInfoFile.updateFilename();
  444. if(!newfile.exists() || (newfile.exists() && tempInfoFile.exists())) {
  445. ctx->setUFilename(newFilename);
  446. return true;
  447. }
  448. }
  449. return false;
  450. }
  451. void RequestGroup::createNextCommandWithAdj(std::deque<Command*>& commands,
  452. DownloadEngine* e, int numAdj)
  453. {
  454. unsigned int numCommand;
  455. if(_numConcurrentCommand == 0) {
  456. numCommand = _uris.size();
  457. } else {
  458. int n = _numConcurrentCommand+numAdj;
  459. if(n > 0) {
  460. numCommand = n;
  461. } else {
  462. return;
  463. }
  464. }
  465. createNextCommand(commands, e, numCommand, Request::METHOD_GET);
  466. }
  467. void RequestGroup::createNextCommand(std::deque<Command*>& commands,
  468. DownloadEngine* e,
  469. unsigned int numCommand,
  470. const std::string& method)
  471. {
  472. std::deque<std::string> pendingURIs;
  473. for(; !_uris.empty() && numCommand--; ) {
  474. std::string uri = _uriSelector->select(_uris);
  475. RequestHandle req(new Request());
  476. if(req->setUrl(uri)) {
  477. ServerHostHandle sv;
  478. if(!_singleHostMultiConnectionEnabled){
  479. sv = searchServerHost(req->getHost());
  480. }
  481. if(sv.isNull()) {
  482. _spentUris.push_back(uri);
  483. req->setReferer(_option->get(PREF_REFERER));
  484. req->setMethod(method);
  485. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(), req, this, e);
  486. ServerHostHandle sv(new ServerHost(command->getCuid(), req->getHost()));
  487. registerServerHost(sv);
  488. // give a chance to be executed in the next loop in DownloadEngine
  489. command->setStatus(Command::STATUS_ONESHOT_REALTIME);
  490. commands.push_back(command);
  491. } else {
  492. pendingURIs.push_back(uri);
  493. }
  494. } else {
  495. _logger->error(MSG_UNRECOGNIZED_URI, req->getUrl().c_str());
  496. }
  497. }
  498. _uris.insert(_uris.begin(), pendingURIs.begin(), pendingURIs.end());
  499. }
  500. std::string RequestGroup::getFilePath() const
  501. {
  502. assert(!_downloadContext.isNull());
  503. if(_downloadContext.isNull()) {
  504. return A2STR::NIL;
  505. } else {
  506. return _downloadContext->getActualBasePath();
  507. }
  508. }
  509. uint64_t RequestGroup::getTotalLength() const
  510. {
  511. if(_pieceStorage.isNull()) {
  512. return 0;
  513. } else {
  514. if(_pieceStorage->isSelectiveDownloadingMode()) {
  515. return _pieceStorage->getFilteredTotalLength();
  516. } else {
  517. return _pieceStorage->getTotalLength();
  518. }
  519. }
  520. }
  521. uint64_t RequestGroup::getCompletedLength() const
  522. {
  523. if(_pieceStorage.isNull()) {
  524. return 0;
  525. } else {
  526. if(_pieceStorage->isSelectiveDownloadingMode()) {
  527. return _pieceStorage->getFilteredCompletedLength();
  528. } else {
  529. return _pieceStorage->getCompletedLength();
  530. }
  531. }
  532. }
  533. void RequestGroup::validateFilename(const std::string& expectedFilename,
  534. const std::string& actualFilename) const
  535. {
  536. if(expectedFilename.empty()) {
  537. return;
  538. }
  539. if(expectedFilename != actualFilename) {
  540. throw DlAbortEx(StringFormat(EX_FILENAME_MISMATCH,
  541. expectedFilename.c_str(),
  542. actualFilename.c_str()).str());
  543. }
  544. }
  545. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  546. uint64_t actualTotalLength) const
  547. {
  548. if(expectedTotalLength <= 0) {
  549. return;
  550. }
  551. if(expectedTotalLength != actualTotalLength) {
  552. throw DlAbortEx
  553. (StringFormat(EX_SIZE_MISMATCH,
  554. Util::itos(expectedTotalLength, true).c_str(),
  555. Util::itos(actualTotalLength, true).c_str()).str());
  556. }
  557. }
  558. void RequestGroup::validateFilename(const std::string& actualFilename) const
  559. {
  560. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  561. }
  562. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  563. {
  564. validateTotalLength(getTotalLength(), actualTotalLength);
  565. }
  566. void RequestGroup::increaseStreamConnection()
  567. {
  568. ++_numStreamConnection;
  569. }
  570. void RequestGroup::decreaseStreamConnection()
  571. {
  572. --_numStreamConnection;
  573. }
  574. unsigned int RequestGroup::getNumConnection() const
  575. {
  576. unsigned int numConnection = _numStreamConnection;
  577. #ifdef ENABLE_BITTORRENT
  578. {
  579. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  580. if(!btContext.isNull()) {
  581. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  582. if(!btRuntime.isNull()) {
  583. numConnection += btRuntime->getConnections();
  584. }
  585. }
  586. }
  587. #endif // ENABLE_BITTORRENT
  588. return numConnection;
  589. }
  590. void RequestGroup::increaseNumCommand()
  591. {
  592. ++_numCommand;
  593. }
  594. void RequestGroup::decreaseNumCommand()
  595. {
  596. --_numCommand;
  597. }
  598. TransferStat RequestGroup::calculateStat()
  599. {
  600. TransferStat stat;
  601. #ifdef ENABLE_BITTORRENT
  602. {
  603. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  604. if(!btContext.isNull()) {
  605. PeerStorageHandle peerStorage = PEER_STORAGE(btContext);
  606. if(!peerStorage.isNull()) {
  607. stat = peerStorage->calculateStat();
  608. }
  609. }
  610. }
  611. #endif // ENABLE_BITTORRENT
  612. if(!_segmentMan.isNull()) {
  613. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  614. }
  615. return stat;
  616. }
  617. void RequestGroup::setHaltRequested(bool f)
  618. {
  619. _haltRequested = f;
  620. #ifdef ENABLE_BITTORRENT
  621. {
  622. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  623. if(!btContext.isNull()) {
  624. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  625. if(!btRuntime.isNull()) {
  626. btRuntime->setHalt(f);
  627. }
  628. }
  629. }
  630. #endif // ENABLE_BITTORRENT
  631. }
  632. void RequestGroup::setForceHaltRequested(bool f)
  633. {
  634. setHaltRequested(f);
  635. _forceHaltRequested = f;
  636. }
  637. void RequestGroup::releaseRuntimeResource()
  638. {
  639. #ifdef ENABLE_BITTORRENT
  640. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  641. if(!btContext.isNull()) {
  642. BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString());
  643. if(!btContextInReg.isNull() &&
  644. btContextInReg->getOwnerRequestGroup()->getGID() ==
  645. btContext->getOwnerRequestGroup()->getGID()) {
  646. BtRegistry::unregister(btContext->getInfoHashAsString());
  647. if(!DHTRegistry::_peerAnnounceStorage.isNull()) {
  648. DHTRegistry::_peerAnnounceStorage->removePeerAnnounce(btContext);
  649. }
  650. }
  651. }
  652. #endif // ENABLE_BITTORRENT
  653. if(!_pieceStorage.isNull()) {
  654. _pieceStorage->removeAdvertisedPiece(0);
  655. }
  656. }
  657. void RequestGroup::preDownloadProcessing()
  658. {
  659. _logger->debug("Finding PreDownloadHandler for path %s.", getFilePath().c_str());
  660. try {
  661. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  662. itr != _preDownloadHandlers.end(); ++itr) {
  663. if((*itr)->canHandle(this)) {
  664. (*itr)->execute(this);
  665. return;
  666. }
  667. }
  668. } catch(RecoverableException& ex) {
  669. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  670. return;
  671. }
  672. _logger->debug("No PreDownloadHandler found.");
  673. return;
  674. }
  675. void RequestGroup::postDownloadProcessing
  676. (std::deque<SharedHandle<RequestGroup> >& groups)
  677. {
  678. _logger->debug("Finding PostDownloadHandler for path %s.", getFilePath().c_str());
  679. try {
  680. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  681. itr != _postDownloadHandlers.end(); ++itr) {
  682. if((*itr)->canHandle(this)) {
  683. (*itr)->getNextRequestGroups(groups, this);
  684. return;
  685. }
  686. }
  687. } catch(RecoverableException& ex) {
  688. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  689. }
  690. _logger->debug("No PostDownloadHandler found.");
  691. }
  692. void RequestGroup::initializePreDownloadHandler()
  693. {
  694. #ifdef ENABLE_BITTORRENT
  695. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  696. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  697. }
  698. #endif // ENABLE_BITTORRENT
  699. #ifdef ENABLE_METALINK
  700. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  701. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  702. }
  703. #endif // ENABLE_METALINK
  704. }
  705. void RequestGroup::initializePostDownloadHandler()
  706. {
  707. #ifdef ENABLE_BITTORRENT
  708. if(_option->getAsBool(PREF_FOLLOW_TORRENT) ||
  709. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  710. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  711. }
  712. #endif // ENABLE_BITTORRENT
  713. #ifdef ENABLE_METALINK
  714. if(_option->getAsBool(PREF_FOLLOW_METALINK) ||
  715. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  716. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  717. }
  718. #endif // ENABLE_METALINK
  719. }
  720. void RequestGroup::getURIs(std::deque<std::string>& uris) const
  721. {
  722. uris.insert(uris.end(), _spentUris.begin(), _spentUris.end());
  723. uris.insert(uris.end(), _uris.begin(), _uris.end());
  724. }
  725. bool RequestGroup::isDependencyResolved()
  726. {
  727. if(_dependency.isNull()) {
  728. return true;
  729. }
  730. return _dependency->resolve();
  731. }
  732. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  733. {
  734. _segmentManFactory = segmentManFactory;
  735. }
  736. void RequestGroup::dependsOn(const DependencyHandle& dep)
  737. {
  738. _dependency = dep;
  739. }
  740. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  741. {
  742. _diskWriterFactory = diskWriterFactory;
  743. }
  744. DiskWriterFactoryHandle RequestGroup::getDiskWriterFactory() const
  745. {
  746. return _diskWriterFactory;
  747. }
  748. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  749. {
  750. _postDownloadHandlers.push_back(handler);
  751. }
  752. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  753. {
  754. _preDownloadHandlers.push_back(handler);
  755. }
  756. void RequestGroup::clearPostDowloadHandler()
  757. {
  758. _postDownloadHandlers.clear();
  759. }
  760. void RequestGroup::clearPreDowloadHandler()
  761. {
  762. _preDownloadHandlers.clear();
  763. }
  764. SegmentManHandle RequestGroup::getSegmentMan() const
  765. {
  766. return _segmentMan;
  767. }
  768. DownloadContextHandle RequestGroup::getDownloadContext() const
  769. {
  770. return _downloadContext;
  771. }
  772. void RequestGroup::setDownloadContext(const DownloadContextHandle& downloadContext)
  773. {
  774. _downloadContext = downloadContext;
  775. }
  776. PieceStorageHandle RequestGroup::getPieceStorage() const
  777. {
  778. return _pieceStorage;
  779. }
  780. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  781. {
  782. _pieceStorage = pieceStorage;
  783. }
  784. BtProgressInfoFileHandle RequestGroup::getProgressInfoFile() const
  785. {
  786. return _progressInfoFile;
  787. }
  788. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  789. {
  790. _progressInfoFile = progressInfoFile;
  791. }
  792. bool RequestGroup::needsFileAllocation() const
  793. {
  794. return isFileAllocationEnabled() &&
  795. (uint64_t)_option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  796. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  797. }
  798. DownloadResultHandle RequestGroup::createDownloadResult() const
  799. {
  800. std::deque<std::string> uris;
  801. getURIs(uris);
  802. return
  803. SharedHandle<DownloadResult>(new DownloadResult(_gid,
  804. getFilePath(),
  805. getTotalLength(),
  806. uris.empty() ? A2STR::NIL:uris.front(),
  807. uris.size(),
  808. downloadFinished()?
  809. DownloadResult::FINISHED :
  810. DownloadResult::NOT_YET));
  811. }
  812. void RequestGroup::registerServerHost(const ServerHostHandle& serverHost)
  813. {
  814. _serverHosts.push_back(serverHost);
  815. }
  816. class FindServerHostByCUID
  817. {
  818. private:
  819. int32_t _cuid;
  820. public:
  821. FindServerHostByCUID(int32_t cuid):_cuid(cuid) {}
  822. bool operator()(const ServerHostHandle& sv) const
  823. {
  824. return sv->getCuid() == _cuid;
  825. }
  826. };
  827. ServerHostHandle RequestGroup::searchServerHost(int32_t cuid) const
  828. {
  829. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  830. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid));
  831. if(itr == _serverHosts.end()) {
  832. return SharedHandle<ServerHost>();
  833. } else {
  834. return *itr;
  835. }
  836. }
  837. class FindServerHostByHostname
  838. {
  839. private:
  840. std::string _hostname;
  841. public:
  842. FindServerHostByHostname(const std::string& hostname):_hostname(hostname) {}
  843. bool operator()(const ServerHostHandle& sv) const
  844. {
  845. return sv->getHostname() == _hostname;
  846. }
  847. };
  848. ServerHostHandle RequestGroup::searchServerHost(const std::string& hostname) const
  849. {
  850. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  851. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByHostname(hostname));
  852. if(itr == _serverHosts.end()) {
  853. return SharedHandle<ServerHost>();
  854. } else {
  855. return *itr;
  856. }
  857. }
  858. void RequestGroup::removeServerHost(int32_t cuid)
  859. {
  860. _serverHosts.erase(std::remove_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid)), _serverHosts.end());
  861. }
  862. void RequestGroup::removeURIWhoseHostnameIs(const std::string& hostname)
  863. {
  864. std::deque<std::string> newURIs;
  865. Request req;
  866. for(std::deque<std::string>::const_iterator itr = _uris.begin(); itr != _uris.end(); ++itr) {
  867. if(((*itr).find(hostname) == std::string::npos) ||
  868. (req.setUrl(*itr) && (req.getHost() != hostname))) {
  869. newURIs.push_back(*itr);
  870. }
  871. }
  872. _logger->debug("GUID#%d - Removed %d duplicate hostname URIs",
  873. _gid, _uris.size()-newURIs.size());
  874. _uris = newURIs;
  875. }
  876. void RequestGroup::reportDownloadFinished()
  877. {
  878. _logger->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  879. getFilePath().c_str());
  880. #ifdef ENABLE_BITTORRENT
  881. TransferStat stat = calculateStat();
  882. SharedHandle<BtContext> ctx = dynamic_pointer_cast<BtContext>(_downloadContext);
  883. if(!ctx.isNull()) {
  884. double shareRatio = ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  885. _logger->notice(MSG_SHARE_RATIO_REPORT,
  886. shareRatio,
  887. Util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  888. Util::abbrevSize(getCompletedLength()).c_str());
  889. }
  890. #endif // ENABLE_BITTORRENT
  891. }
  892. const std::deque<std::string>& RequestGroup::getAcceptFeatures() const
  893. {
  894. return _acceptFeatures;
  895. }
  896. void RequestGroup::addAcceptFeatureHeader(const std::string& feature)
  897. {
  898. if(std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature) == _acceptFeatures.end()) {
  899. _acceptFeatures.push_back(feature);
  900. }
  901. }
  902. void RequestGroup::removeAcceptFeatureHeader(const std::string& feature)
  903. {
  904. std::deque<std::string>::iterator i = std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature);
  905. if(i != _acceptFeatures.end()) {
  906. _acceptFeatures.erase(i);
  907. }
  908. }
  909. const std::deque<std::string>& RequestGroup::getAcceptTypes() const
  910. {
  911. return _acceptTypes;
  912. }
  913. void RequestGroup::addAcceptType(const std::string& type)
  914. {
  915. if(std::find(_acceptTypes.begin(), _acceptTypes.end(), type) == _acceptTypes.end()) {
  916. _acceptTypes.push_back(type);
  917. }
  918. }
  919. void RequestGroup::removeAcceptType(const std::string& type)
  920. {
  921. _acceptTypes.erase(std::remove(_acceptTypes.begin(), _acceptTypes.end(), type),
  922. _acceptTypes.end());
  923. }
  924. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  925. {
  926. _uriSelector = uriSelector;
  927. }
  928. } // namespace aria2