RequestGroup.cc 34 KB

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