RequestGroup.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 "CreateRequestCommand.h"
  46. #include "File.h"
  47. #include "message.h"
  48. #include "util.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 "DownloadContext.h"
  58. #include "DlAbortEx.h"
  59. #include "DownloadFailureException.h"
  60. #include "RequestGroupMan.h"
  61. #include "DefaultBtProgressInfoFile.h"
  62. #include "DefaultPieceStorage.h"
  63. #include "DownloadHandlerFactory.h"
  64. #include "MemoryBufferPreDownloadHandler.h"
  65. #include "DownloadHandlerConstants.h"
  66. #include "Option.h"
  67. #include "FileEntry.h"
  68. #include "Request.h"
  69. #include "FileAllocationIterator.h"
  70. #include "StringFormat.h"
  71. #include "A2STR.h"
  72. #include "URISelector.h"
  73. #include "InOrderURISelector.h"
  74. #include "PieceSelector.h"
  75. #include "a2functional.h"
  76. #include "SocketCore.h"
  77. #ifdef ENABLE_MESSAGE_DIGEST
  78. # include "CheckIntegrityCommand.h"
  79. #endif // ENABLE_MESSAGE_DIGEST
  80. #ifdef ENABLE_BITTORRENT
  81. # include "bittorrent_helper.h"
  82. # include "BtRegistry.h"
  83. # include "BtCheckIntegrityEntry.h"
  84. # include "DefaultPeerStorage.h"
  85. # include "DefaultBtAnnounce.h"
  86. # include "BtRuntime.h"
  87. # include "BtSetup.h"
  88. # include "BtFileAllocationEntry.h"
  89. # include "BtPostDownloadHandler.h"
  90. # include "DHTSetup.h"
  91. # include "DHTRegistry.h"
  92. # include "BtMessageFactory.h"
  93. # include "BtRequestFactory.h"
  94. # include "BtMessageDispatcher.h"
  95. # include "BtMessageReceiver.h"
  96. # include "PeerConnection.h"
  97. # include "ExtensionMessageFactory.h"
  98. # include "DHTPeerAnnounceStorage.h"
  99. # include "DHTEntryPointNameResolveCommand.h"
  100. # include "LongestSequencePieceSelector.h"
  101. #endif // ENABLE_BITTORRENT
  102. #ifdef ENABLE_METALINK
  103. # include "MetalinkPostDownloadHandler.h"
  104. #endif // ENABLE_METALINK
  105. namespace aria2 {
  106. int32_t RequestGroup::_gidCounter = 0;
  107. const std::string RequestGroup::ACCEPT_METALINK = "application/metalink+xml";
  108. RequestGroup::RequestGroup(const SharedHandle<Option>& option):
  109. _gid(++_gidCounter),
  110. _option(new Option(*option.get())),
  111. _numConcurrentCommand(option->getAsInt(PREF_SPLIT)),
  112. _numStreamConnection(0),
  113. _numCommand(0),
  114. _segmentManFactory(new DefaultSegmentManFactory(_option.get())),
  115. _saveControlFile(true),
  116. _progressInfoFile(new NullProgressInfoFile()),
  117. _preLocalFileCheckEnabled(true),
  118. _haltRequested(false),
  119. _forceHaltRequested(false),
  120. _haltReason(RequestGroup::NONE),
  121. _uriSelector(new InOrderURISelector()),
  122. _lastModifiedTime(Time::null()),
  123. _fileNotFoundCount(0),
  124. _timeout(option->getAsInt(PREF_TIMEOUT)),
  125. _inMemoryDownload(false),
  126. _maxDownloadSpeedLimit(option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT)),
  127. _maxUploadSpeedLimit(option->getAsInt(PREF_MAX_UPLOAD_LIMIT)),
  128. _logger(LogFactory::getInstance())
  129. {
  130. _fileAllocationEnabled = _option->get(PREF_FILE_ALLOCATION) != V_NONE;
  131. // Add types to be sent as a Accept header value here.
  132. // It would be good to put this value in Option so that user can tweak
  133. // and add this list.
  134. // ACCEPT_METALINK is used for `transparent metalink'.
  135. addAcceptType(ACCEPT_METALINK);
  136. if(!_option->getAsBool(PREF_DRY_RUN)) {
  137. initializePreDownloadHandler();
  138. initializePostDownloadHandler();
  139. }
  140. }
  141. RequestGroup::~RequestGroup() {}
  142. const SegmentManHandle& RequestGroup::initSegmentMan()
  143. {
  144. _segmentMan = _segmentManFactory->createNewInstance(_downloadContext,
  145. _pieceStorage);
  146. return _segmentMan;
  147. }
  148. bool RequestGroup::downloadFinished() const
  149. {
  150. if(_pieceStorage.isNull()) {
  151. return false;
  152. } else {
  153. return _pieceStorage->downloadFinished();
  154. }
  155. }
  156. bool RequestGroup::allDownloadFinished() const
  157. {
  158. if(_pieceStorage.isNull()) {
  159. return false;
  160. } else {
  161. return _pieceStorage->allDownloadFinished();
  162. }
  163. }
  164. downloadresultcode::RESULT RequestGroup::downloadResult() const
  165. {
  166. if (downloadFinished())
  167. return downloadresultcode::FINISHED;
  168. else {
  169. if (_lastUriResult.isNull()) {
  170. if(_haltReason == RequestGroup::USER_REQUEST) {
  171. return downloadresultcode::IN_PROGRESS;
  172. } else {
  173. return downloadresultcode::UNKNOWN_ERROR;
  174. }
  175. } else {
  176. return _lastUriResult->getResult();
  177. }
  178. }
  179. }
  180. void RequestGroup::closeFile()
  181. {
  182. if(!_pieceStorage.isNull()) {
  183. _pieceStorage->getDiskAdaptor()->closeFile();
  184. }
  185. }
  186. void RequestGroup::createInitialCommand
  187. (std::deque<Command*>& commands, DownloadEngine* e)
  188. {
  189. #ifdef ENABLE_BITTORRENT
  190. {
  191. if(_downloadContext->hasAttribute(bittorrent::BITTORRENT)) {
  192. const BDE& torrentAttrs =
  193. _downloadContext->getAttribute(bittorrent::BITTORRENT);
  194. bool metadataGetMode = !torrentAttrs.containsKey(bittorrent::METADATA);
  195. if(_option->getAsBool(PREF_DRY_RUN)) {
  196. throw DOWNLOAD_FAILURE_EXCEPTION
  197. ("Cancel BitTorrent download in dry-run context.");
  198. }
  199. SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
  200. if(!btRegistry->getDownloadContext
  201. (torrentAttrs[bittorrent::INFO_HASH].s()).isNull()) {
  202. throw DOWNLOAD_FAILURE_EXCEPTION
  203. (StringFormat
  204. ("InfoHash %s is already registered.",
  205. bittorrent::getInfoHashString(_downloadContext).c_str()).str());
  206. }
  207. if(metadataGetMode) {
  208. // Use UnknownLengthPieceStorage.
  209. initPieceStorage();
  210. } else {
  211. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  212. throw DOWNLOAD_FAILURE_EXCEPTION
  213. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  214. _downloadContext->getBasePath().c_str()).str());
  215. }
  216. initPieceStorage();
  217. if(_downloadContext->getFileEntries().size() > 1) {
  218. _pieceStorage->setupFileFilter();
  219. }
  220. }
  221. SharedHandle<DefaultBtProgressInfoFile> progressInfoFile;
  222. if(!metadataGetMode) {
  223. progressInfoFile.reset(new DefaultBtProgressInfoFile(_downloadContext,
  224. _pieceStorage,
  225. _option.get()));
  226. }
  227. BtRuntimeHandle btRuntime(new BtRuntime());
  228. btRuntime->setMaxPeers(_option->getAsInt(PREF_BT_MAX_PEERS));
  229. _btRuntime = btRuntime;
  230. if(!progressInfoFile.isNull()) {
  231. progressInfoFile->setBtRuntime(btRuntime);
  232. }
  233. SharedHandle<DefaultPeerStorage> peerStorage
  234. (new DefaultPeerStorage(_option.get()));
  235. peerStorage->setBtRuntime(btRuntime);
  236. peerStorage->setPieceStorage(_pieceStorage);
  237. _peerStorage = peerStorage;
  238. if(!progressInfoFile.isNull()) {
  239. progressInfoFile->setPeerStorage(peerStorage);
  240. }
  241. SharedHandle<DefaultBtAnnounce> btAnnounce
  242. (new DefaultBtAnnounce(_downloadContext, _option.get()));
  243. btAnnounce->setBtRuntime(btRuntime);
  244. btAnnounce->setPieceStorage(_pieceStorage);
  245. btAnnounce->setPeerStorage(peerStorage);
  246. btAnnounce->setUserDefinedInterval
  247. (_option->getAsInt(PREF_BT_TRACKER_INTERVAL));
  248. btAnnounce->shuffleAnnounce();
  249. btRegistry->put(_gid,
  250. BtObject(_downloadContext,
  251. _pieceStorage,
  252. peerStorage,
  253. btAnnounce,
  254. btRuntime,
  255. (progressInfoFile.isNull()?
  256. _progressInfoFile:
  257. SharedHandle<BtProgressInfoFile>
  258. (progressInfoFile))));
  259. if(metadataGetMode) {
  260. std::deque<Command*> dhtCommands;
  261. DHTSetup().setup(dhtCommands, e, _option.get());
  262. e->addCommand(dhtCommands);
  263. SharedHandle<CheckIntegrityEntry> entry
  264. (new BtCheckIntegrityEntry(this));
  265. entry->onDownloadIncomplete(commands, e);
  266. return;
  267. }
  268. // Remove the control file if download file doesn't exist
  269. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  270. progressInfoFile->removeFile();
  271. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  272. progressInfoFile->getFilename().c_str(),
  273. _downloadContext->getBasePath().c_str());
  274. }
  275. {
  276. uint64_t actualFileSize = _pieceStorage->getDiskAdaptor()->size();
  277. if(actualFileSize == _downloadContext->getTotalLength()) {
  278. // First, make DiskAdaptor read-only mode to allow the
  279. // program to seed file in read-only media.
  280. _pieceStorage->getDiskAdaptor()->enableReadOnly();
  281. } else {
  282. // Open file in writable mode to allow the program
  283. // truncate the file to _downloadContext->getTotalLength()
  284. _logger->debug("File size not match. File is opened in writable mode."
  285. " Expected:%s Actual:%s",
  286. util::uitos(_downloadContext->getTotalLength()).c_str(),
  287. util::uitos(actualFileSize).c_str());
  288. }
  289. }
  290. // Call Load, Save and file allocation command here
  291. if(progressInfoFile->exists()) {
  292. // load .aria2 file if it exists.
  293. progressInfoFile->load();
  294. _pieceStorage->getDiskAdaptor()->openFile();
  295. } else {
  296. if(_pieceStorage->getDiskAdaptor()->fileExists()) {
  297. if(!_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  298. !_option->getAsBool(PREF_ALLOW_OVERWRITE) &&
  299. !_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  300. // TODO we need this->haltRequested = true?
  301. throw DOWNLOAD_FAILURE_EXCEPTION
  302. (StringFormat
  303. (MSG_FILE_ALREADY_EXISTS,
  304. _downloadContext->getBasePath().c_str()).str());
  305. } else {
  306. _pieceStorage->getDiskAdaptor()->openFile();
  307. }
  308. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  309. _pieceStorage->markAllPiecesDone();
  310. }
  311. } else {
  312. _pieceStorage->getDiskAdaptor()->openFile();
  313. }
  314. }
  315. _progressInfoFile = progressInfoFile;
  316. if(torrentAttrs[bittorrent::PRIVATE].i() == 0 &&
  317. _option->getAsBool(PREF_ENABLE_DHT)) {
  318. std::deque<Command*> commands;
  319. DHTSetup().setup(commands, e, _option.get());
  320. e->addCommand(commands);
  321. if(!torrentAttrs[bittorrent::NODES].empty() && DHTSetup::initialized()) {
  322. std::deque<std::pair<std::string, uint16_t> > entryPoints;
  323. const BDE& nodes = torrentAttrs[bittorrent::NODES];
  324. for(BDE::List::const_iterator i = nodes.listBegin();
  325. i != nodes.listEnd(); ++i) {
  326. std::pair<std::string, uint16_t> addr
  327. ((*i)[bittorrent::HOSTNAME].s(), (*i)[bittorrent::PORT].i());
  328. entryPoints.push_back(addr);
  329. }
  330. DHTEntryPointNameResolveCommand* command =
  331. new DHTEntryPointNameResolveCommand(e->newCUID(), e, entryPoints);
  332. command->setTaskQueue(DHTRegistry::_taskQueue);
  333. command->setTaskFactory(DHTRegistry::_taskFactory);
  334. command->setRoutingTable(DHTRegistry::_routingTable);
  335. command->setLocalNode(DHTRegistry::_localNode);
  336. e->commands.push_back(command);
  337. }
  338. }
  339. CheckIntegrityEntryHandle entry(new BtCheckIntegrityEntry(this));
  340. // --bt-seed-unverified=true is given and download has completed, skip
  341. // validation for piece hashes.
  342. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  343. _pieceStorage->downloadFinished()) {
  344. entry->onDownloadFinished(commands, e);
  345. } else {
  346. processCheckIntegrityEntry(commands, entry, e);
  347. }
  348. return;
  349. }
  350. }
  351. #endif // ENABLE_BITTORRENT
  352. // TODO Currently, BitTorrent+WEB-Seeding is only way to download
  353. // multiple files in one RequestGroup. In this context, we don't
  354. // have BitTorrent, so add assertion here. This situation will be
  355. // changed if Metalink spec is formalized to support multi-file
  356. // torrent.
  357. assert(_downloadContext->getFileEntries().size() == 1);
  358. // TODO I assume here when totallength is set to DownloadContext and it is
  359. // not 0, then filepath is also set DownloadContext correctly....
  360. if(_option->getAsBool(PREF_DRY_RUN) ||
  361. _downloadContext->getTotalLength() == 0) {
  362. createNextCommand(commands, e, 1);
  363. }else {
  364. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  365. throw DOWNLOAD_FAILURE_EXCEPTION
  366. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  367. _downloadContext->getBasePath().c_str()).str());
  368. }
  369. adjustFilename
  370. (SharedHandle<BtProgressInfoFile>(new DefaultBtProgressInfoFile
  371. (_downloadContext,
  372. SharedHandle<PieceStorage>(),
  373. _option.get())));
  374. initPieceStorage();
  375. BtProgressInfoFileHandle infoFile
  376. (new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage,
  377. _option.get()));
  378. if(!infoFile->exists() && downloadFinishedByFileLength()) {
  379. _pieceStorage->markAllPiecesDone();
  380. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  381. _gid, _downloadContext->getBasePath().c_str());
  382. } else {
  383. loadAndOpenFile(infoFile);
  384. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry
  385. (new StreamCheckIntegrityEntry(this));
  386. processCheckIntegrityEntry(commands, checkIntegrityEntry, e);
  387. }
  388. }
  389. }
  390. void RequestGroup::processCheckIntegrityEntry(std::deque<Command*>& commands,
  391. const CheckIntegrityEntryHandle& entry,
  392. DownloadEngine* e)
  393. {
  394. #ifdef ENABLE_MESSAGE_DIGEST
  395. if(_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  396. entry->isValidationReady()) {
  397. entry->initValidator();
  398. entry->cutTrailingGarbage();
  399. // Don't save control file(.aria2 file) when user presses
  400. // control-c key while aria2 is checking hashes. If control file
  401. // doesn't exist when aria2 launched, the completed length in
  402. // saved control file will be 0 byte and this confuses user.
  403. // enableSaveControlFile() will be called after hash checking is
  404. // done. See CheckIntegrityCommand.
  405. disableSaveControlFile();
  406. e->_checkIntegrityMan->pushEntry(entry);
  407. } else
  408. #endif // ENABLE_MESSAGE_DIGEST
  409. {
  410. entry->onDownloadIncomplete(commands, e);
  411. }
  412. }
  413. void RequestGroup::initPieceStorage()
  414. {
  415. if(_downloadContext->knowsTotalLength()) {
  416. #ifdef ENABLE_BITTORRENT
  417. SharedHandle<DefaultPieceStorage> ps
  418. (new DefaultPieceStorage(_downloadContext, _option.get()));
  419. // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent integrated
  420. // downloads. Currently multi-file integrated download is not supported.
  421. if(_downloadContext->hasAttribute(bittorrent::BITTORRENT) &&
  422. isUriSuppliedForRequsetFileEntry
  423. (_downloadContext->getFileEntries().begin(),
  424. _downloadContext->getFileEntries().end())) {
  425. _logger->debug("Using LongestSequencePieceSelector");
  426. ps->setPieceSelector
  427. (SharedHandle<PieceSelector>(new LongestSequencePieceSelector()));
  428. }
  429. #else // !ENABLE_BITTORRENT
  430. SharedHandle<DefaultPieceStorage> ps
  431. (new DefaultPieceStorage(_downloadContext, _option.get()));
  432. #endif // !ENABLE_BITTORRENT
  433. if(!_diskWriterFactory.isNull()) {
  434. ps->setDiskWriterFactory(_diskWriterFactory);
  435. }
  436. _pieceStorage = ps;
  437. } else {
  438. UnknownLengthPieceStorageHandle ps
  439. (new UnknownLengthPieceStorage(_downloadContext, _option.get()));
  440. if(!_diskWriterFactory.isNull()) {
  441. ps->setDiskWriterFactory(_diskWriterFactory);
  442. }
  443. _pieceStorage = ps;
  444. }
  445. _pieceStorage->initStorage();
  446. initSegmentMan();
  447. }
  448. bool RequestGroup::downloadFinishedByFileLength()
  449. {
  450. // assuming that a control file doesn't exist.
  451. if(!isPreLocalFileCheckEnabled() ||
  452. _option->getAsBool(PREF_ALLOW_OVERWRITE) ||
  453. (_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  454. !_downloadContext->getPieceHashes().empty())) {
  455. return false;
  456. }
  457. if(!_downloadContext->knowsTotalLength()) {
  458. return false;
  459. }
  460. File outfile(getFirstFilePath());
  461. if(outfile.exists() && _downloadContext->getTotalLength() == outfile.size()) {
  462. return true;
  463. } else {
  464. return false;
  465. }
  466. }
  467. void RequestGroup::adjustFilename
  468. (const SharedHandle<BtProgressInfoFile>& infoFile)
  469. {
  470. if(!isPreLocalFileCheckEnabled()) {
  471. // OK, no need to care about filename.
  472. } else if(infoFile->exists()) {
  473. // Use current filename
  474. } else if(downloadFinishedByFileLength()) {
  475. // File was downloaded already, no need to change file name.
  476. } else {
  477. File outfile(getFirstFilePath());
  478. if(outfile.exists() && _option->getAsBool(PREF_CONTINUE) &&
  479. outfile.size() <= _downloadContext->getTotalLength()) {
  480. // File exists but user decided to resume it.
  481. } else {
  482. #ifdef ENABLE_MESSAGE_DIGEST
  483. if(outfile.exists() && _option->getAsBool(PREF_CHECK_INTEGRITY)) {
  484. // check-integrity existing file
  485. } else {
  486. #endif // ENABLE_MESSAGE_DIGEST
  487. shouldCancelDownloadForSafety();
  488. #ifdef ENABLE_MESSAGE_DIGEST
  489. }
  490. #endif // ENABLE_MESSAGE_DIGEST
  491. }
  492. }
  493. }
  494. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  495. {
  496. try {
  497. if(!isPreLocalFileCheckEnabled()) {
  498. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  499. return;
  500. }
  501. // Remove the control file if download file doesn't exist
  502. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  503. progressInfoFile->removeFile();
  504. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  505. progressInfoFile->getFilename().c_str(),
  506. _downloadContext->getBasePath().c_str());
  507. }
  508. if(progressInfoFile->exists()) {
  509. progressInfoFile->load();
  510. _pieceStorage->getDiskAdaptor()->openExistingFile();
  511. } else {
  512. File outfile(getFirstFilePath());
  513. if(outfile.exists() && _option->getAsBool(PREF_CONTINUE) &&
  514. outfile.size() <= getTotalLength()) {
  515. _pieceStorage->getDiskAdaptor()->openExistingFile();
  516. _pieceStorage->markPiecesDone(outfile.size());
  517. } else {
  518. #ifdef ENABLE_MESSAGE_DIGEST
  519. if(outfile.exists() && _option->getAsBool(PREF_CHECK_INTEGRITY)) {
  520. _pieceStorage->getDiskAdaptor()->openExistingFile();
  521. } else {
  522. #endif // ENABLE_MESSAGE_DIGEST
  523. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  524. #ifdef ENABLE_MESSAGE_DIGEST
  525. }
  526. #endif // ENABLE_MESSAGE_DIGEST
  527. }
  528. }
  529. setProgressInfoFile(progressInfoFile);
  530. } catch(RecoverableException& e) {
  531. throw DOWNLOAD_FAILURE_EXCEPTION2
  532. (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
  533. }
  534. }
  535. // assuming that a control file does not exist
  536. void RequestGroup::shouldCancelDownloadForSafety()
  537. {
  538. if(_option->getAsBool(PREF_ALLOW_OVERWRITE)) {
  539. return;
  540. }
  541. File outfile(getFirstFilePath());
  542. if(outfile.exists()) {
  543. if(_option->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  544. if(tryAutoFileRenaming()) {
  545. _logger->notice(MSG_FILE_RENAMED, getFirstFilePath().c_str());
  546. } else {
  547. throw DOWNLOAD_FAILURE_EXCEPTION
  548. (StringFormat("File renaming failed: %s",
  549. getFirstFilePath().c_str()).str());
  550. }
  551. } else {
  552. throw DOWNLOAD_FAILURE_EXCEPTION
  553. (StringFormat(MSG_FILE_ALREADY_EXISTS,
  554. getFirstFilePath().c_str()).str());
  555. }
  556. }
  557. }
  558. bool RequestGroup::tryAutoFileRenaming()
  559. {
  560. std::string filepath = getFirstFilePath();
  561. if(filepath.empty()) {
  562. return false;
  563. }
  564. for(unsigned int i = 1; i < 10000; ++i) {
  565. File newfile(strconcat(filepath, ".", util::uitos(i)));
  566. File ctrlfile(newfile.getPath()+DefaultBtProgressInfoFile::getSuffix());
  567. if(!newfile.exists() || (newfile.exists() && ctrlfile.exists())) {
  568. _downloadContext->getFirstFileEntry()->setPath(newfile.getPath());
  569. return true;
  570. }
  571. }
  572. return false;
  573. }
  574. void RequestGroup::createNextCommandWithAdj(std::deque<Command*>& commands,
  575. DownloadEngine* e, int numAdj)
  576. {
  577. int numCommand;
  578. if(getTotalLength() == 0) {
  579. numCommand = 1+numAdj;
  580. } else {
  581. numCommand = std::min(_downloadContext->getNumPieces(),
  582. _numConcurrentCommand);
  583. numCommand += numAdj;
  584. }
  585. if(numCommand > 0) {
  586. createNextCommand(commands, e, numCommand);
  587. }
  588. }
  589. void RequestGroup::createNextCommand(std::deque<Command*>& commands,
  590. DownloadEngine* e,
  591. unsigned int numCommand)
  592. {
  593. for(; numCommand--; ) {
  594. Command* command = new CreateRequestCommand(e->newCUID(), this, e);
  595. commands.push_back(command);
  596. }
  597. if(!commands.empty()) {
  598. e->setNoWait(true);
  599. }
  600. }
  601. std::string RequestGroup::getFirstFilePath() const
  602. {
  603. assert(!_downloadContext.isNull());
  604. if(inMemoryDownload()) {
  605. static const std::string DIR_MEMORY("[MEMORY]");
  606. return DIR_MEMORY+File(_downloadContext->getFirstFileEntry()->getPath()).getBasename();
  607. } else {
  608. return _downloadContext->getFirstFileEntry()->getPath();
  609. }
  610. }
  611. uint64_t RequestGroup::getTotalLength() const
  612. {
  613. if(_pieceStorage.isNull()) {
  614. return 0;
  615. } else {
  616. if(_pieceStorage->isSelectiveDownloadingMode()) {
  617. return _pieceStorage->getFilteredTotalLength();
  618. } else {
  619. return _pieceStorage->getTotalLength();
  620. }
  621. }
  622. }
  623. uint64_t RequestGroup::getCompletedLength() const
  624. {
  625. if(_pieceStorage.isNull()) {
  626. return 0;
  627. } else {
  628. if(_pieceStorage->isSelectiveDownloadingMode()) {
  629. return _pieceStorage->getFilteredCompletedLength();
  630. } else {
  631. return _pieceStorage->getCompletedLength();
  632. }
  633. }
  634. }
  635. void RequestGroup::validateFilename(const std::string& expectedFilename,
  636. const std::string& actualFilename) const
  637. {
  638. if(expectedFilename.empty()) {
  639. return;
  640. }
  641. if(expectedFilename != actualFilename) {
  642. throw DL_ABORT_EX(StringFormat(EX_FILENAME_MISMATCH,
  643. expectedFilename.c_str(),
  644. actualFilename.c_str()).str());
  645. }
  646. }
  647. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  648. uint64_t actualTotalLength) const
  649. {
  650. if(expectedTotalLength <= 0) {
  651. return;
  652. }
  653. if(expectedTotalLength != actualTotalLength) {
  654. throw DL_ABORT_EX
  655. (StringFormat(EX_SIZE_MISMATCH,
  656. util::itos(expectedTotalLength, true).c_str(),
  657. util::itos(actualTotalLength, true).c_str()).str());
  658. }
  659. }
  660. void RequestGroup::validateFilename(const std::string& actualFilename) const
  661. {
  662. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  663. }
  664. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  665. {
  666. validateTotalLength(getTotalLength(), actualTotalLength);
  667. }
  668. void RequestGroup::increaseStreamConnection()
  669. {
  670. ++_numStreamConnection;
  671. }
  672. void RequestGroup::decreaseStreamConnection()
  673. {
  674. --_numStreamConnection;
  675. }
  676. unsigned int RequestGroup::getNumConnection() const
  677. {
  678. unsigned int numConnection = _numStreamConnection;
  679. #ifdef ENABLE_BITTORRENT
  680. if(!_btRuntime.isNull()) {
  681. numConnection += _btRuntime->getConnections();
  682. }
  683. #endif // ENABLE_BITTORRENT
  684. return numConnection;
  685. }
  686. void RequestGroup::increaseNumCommand()
  687. {
  688. ++_numCommand;
  689. }
  690. void RequestGroup::decreaseNumCommand()
  691. {
  692. --_numCommand;
  693. }
  694. TransferStat RequestGroup::calculateStat()
  695. {
  696. TransferStat stat;
  697. #ifdef ENABLE_BITTORRENT
  698. if(!_peerStorage.isNull()) {
  699. stat = _peerStorage->calculateStat();
  700. }
  701. #endif // ENABLE_BITTORRENT
  702. if(!_segmentMan.isNull()) {
  703. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  704. }
  705. return stat;
  706. }
  707. void RequestGroup::setHaltRequested(bool f, HaltReason haltReason)
  708. {
  709. _haltRequested = f;
  710. if(_haltRequested) {
  711. _haltReason = haltReason;
  712. }
  713. #ifdef ENABLE_BITTORRENT
  714. if(!_btRuntime.isNull()) {
  715. _btRuntime->setHalt(f);
  716. }
  717. #endif // ENABLE_BITTORRENT
  718. }
  719. void RequestGroup::setForceHaltRequested(bool f, HaltReason haltReason)
  720. {
  721. setHaltRequested(f, haltReason);
  722. _forceHaltRequested = f;
  723. }
  724. void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
  725. {
  726. #ifdef ENABLE_BITTORRENT
  727. if(_downloadContext->hasAttribute(bittorrent::BITTORRENT)) {
  728. e->getBtRegistry()->remove(_gid);
  729. }
  730. #endif // ENABLE_BITTORRENT
  731. if(!_pieceStorage.isNull()) {
  732. _pieceStorage->removeAdvertisedPiece(0);
  733. }
  734. _downloadContext->releaseRuntimeResource();
  735. }
  736. void RequestGroup::preDownloadProcessing()
  737. {
  738. _logger->debug("Finding PreDownloadHandler for path %s.",
  739. getFirstFilePath().c_str());
  740. try {
  741. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  742. itr != _preDownloadHandlers.end(); ++itr) {
  743. if((*itr)->canHandle(this)) {
  744. (*itr)->execute(this);
  745. return;
  746. }
  747. }
  748. } catch(RecoverableException& ex) {
  749. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  750. return;
  751. }
  752. _logger->debug("No PreDownloadHandler found.");
  753. return;
  754. }
  755. void RequestGroup::postDownloadProcessing
  756. (std::deque<SharedHandle<RequestGroup> >& groups)
  757. {
  758. _logger->debug("Finding PostDownloadHandler for path %s.",
  759. getFirstFilePath().c_str());
  760. try {
  761. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  762. itr != _postDownloadHandlers.end(); ++itr) {
  763. if((*itr)->canHandle(this)) {
  764. (*itr)->getNextRequestGroups(groups, this);
  765. return;
  766. }
  767. }
  768. } catch(RecoverableException& ex) {
  769. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  770. }
  771. _logger->debug("No PostDownloadHandler found.");
  772. }
  773. void RequestGroup::initializePreDownloadHandler()
  774. {
  775. #ifdef ENABLE_BITTORRENT
  776. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  777. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  778. }
  779. #endif // ENABLE_BITTORRENT
  780. #ifdef ENABLE_METALINK
  781. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  782. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  783. }
  784. #endif // ENABLE_METALINK
  785. }
  786. void RequestGroup::initializePostDownloadHandler()
  787. {
  788. #ifdef ENABLE_BITTORRENT
  789. if(_option->getAsBool(PREF_FOLLOW_TORRENT) ||
  790. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  791. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  792. }
  793. #endif // ENABLE_BITTORRENT
  794. #ifdef ENABLE_METALINK
  795. if(_option->getAsBool(PREF_FOLLOW_METALINK) ||
  796. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  797. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  798. }
  799. #endif // ENABLE_METALINK
  800. }
  801. bool RequestGroup::isDependencyResolved()
  802. {
  803. if(_dependency.isNull()) {
  804. return true;
  805. }
  806. return _dependency->resolve();
  807. }
  808. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  809. {
  810. _segmentManFactory = segmentManFactory;
  811. }
  812. void RequestGroup::dependsOn(const DependencyHandle& dep)
  813. {
  814. _dependency = dep;
  815. }
  816. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  817. {
  818. _diskWriterFactory = diskWriterFactory;
  819. }
  820. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  821. {
  822. _postDownloadHandlers.push_back(handler);
  823. }
  824. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  825. {
  826. _preDownloadHandlers.push_back(handler);
  827. }
  828. void RequestGroup::clearPostDownloadHandler()
  829. {
  830. _postDownloadHandlers.clear();
  831. }
  832. void RequestGroup::clearPreDownloadHandler()
  833. {
  834. _preDownloadHandlers.clear();
  835. }
  836. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  837. {
  838. _pieceStorage = pieceStorage;
  839. }
  840. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  841. {
  842. _progressInfoFile = progressInfoFile;
  843. }
  844. bool RequestGroup::needsFileAllocation() const
  845. {
  846. return isFileAllocationEnabled() &&
  847. (uint64_t)_option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  848. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  849. }
  850. DownloadResultHandle RequestGroup::createDownloadResult() const
  851. {
  852. uint64_t sessionDownloadLength = 0;
  853. #ifdef ENABLE_BITTORRENT
  854. if(!_peerStorage.isNull()) {
  855. sessionDownloadLength +=
  856. _peerStorage->calculateStat().getSessionDownloadLength();
  857. }
  858. #endif // ENABLE_BITTORRENT
  859. if(!_segmentMan.isNull()) {
  860. sessionDownloadLength +=
  861. _segmentMan->calculateSessionDownloadLength();
  862. }
  863. return
  864. SharedHandle<DownloadResult>
  865. (new DownloadResult(_gid,
  866. _downloadContext->getFileEntries(),
  867. _inMemoryDownload,
  868. sessionDownloadLength,
  869. _downloadContext->calculateSessionTime(),
  870. downloadResult()));
  871. }
  872. void RequestGroup::reportDownloadFinished()
  873. {
  874. _logger->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  875. _downloadContext->getBasePath().c_str());
  876. _uriSelector->resetCounters();
  877. #ifdef ENABLE_BITTORRENT
  878. if(_downloadContext->hasAttribute(bittorrent::BITTORRENT)) {
  879. TransferStat stat = calculateStat();
  880. double shareRatio =
  881. ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  882. const BDE& attrs = _downloadContext->getAttribute(bittorrent::BITTORRENT);
  883. if(attrs.containsKey(bittorrent::METADATA)) {
  884. _logger->notice(MSG_SHARE_RATIO_REPORT,
  885. shareRatio,
  886. util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  887. util::abbrevSize(getCompletedLength()).c_str());
  888. }
  889. }
  890. #endif // ENABLE_BITTORRENT
  891. }
  892. void RequestGroup::addAcceptType(const std::string& type)
  893. {
  894. if(std::find(_acceptTypes.begin(), _acceptTypes.end(), type) == _acceptTypes.end()) {
  895. _acceptTypes.push_back(type);
  896. }
  897. }
  898. void RequestGroup::removeAcceptType(const std::string& type)
  899. {
  900. _acceptTypes.erase(std::remove(_acceptTypes.begin(), _acceptTypes.end(), type),
  901. _acceptTypes.end());
  902. }
  903. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  904. {
  905. _uriSelector = uriSelector;
  906. }
  907. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  908. {
  909. if(!_pieceStorage.isNull() && _lastModifiedTime.good()) {
  910. time_t t = _lastModifiedTime.getTime();
  911. _logger->info("Applying Last-Modified time: %s in local time zone",
  912. ctime(&t));
  913. size_t n =
  914. _pieceStorage->getDiskAdaptor()->utime(Time(), _lastModifiedTime);
  915. _logger->info("Last-Modified attrs of %lu files were updated.",
  916. static_cast<unsigned long>(n));
  917. }
  918. }
  919. void RequestGroup::updateLastModifiedTime(const Time& time)
  920. {
  921. if(time.good() && _lastModifiedTime < time) {
  922. _lastModifiedTime = time;
  923. }
  924. }
  925. void RequestGroup::increaseAndValidateFileNotFoundCount()
  926. {
  927. ++_fileNotFoundCount;
  928. const unsigned int maxCount = _option->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  929. if(maxCount > 0 && _fileNotFoundCount >= maxCount &&
  930. _segmentMan->calculateSessionDownloadLength() == 0) {
  931. throw DOWNLOAD_FAILURE_EXCEPTION2
  932. (StringFormat("Reached max-file-not-found count=%u", maxCount).str(),
  933. downloadresultcode::MAX_FILE_NOT_FOUND);
  934. }
  935. }
  936. void RequestGroup::markInMemoryDownload()
  937. {
  938. _inMemoryDownload = true;
  939. }
  940. void RequestGroup::setTimeout(time_t timeout)
  941. {
  942. _timeout = timeout;
  943. }
  944. bool RequestGroup::doesDownloadSpeedExceed()
  945. {
  946. return _maxDownloadSpeedLimit > 0 &&
  947. _maxDownloadSpeedLimit < calculateStat().getDownloadSpeed();
  948. }
  949. bool RequestGroup::doesUploadSpeedExceed()
  950. {
  951. return _maxUploadSpeedLimit > 0 &&
  952. _maxUploadSpeedLimit < calculateStat().getUploadSpeed();
  953. }
  954. void RequestGroup::setLastUriResult
  955. (const std::string uri, downloadresultcode::RESULT result)
  956. {
  957. _lastUriResult.reset(new URIResult(uri, result));
  958. }
  959. void RequestGroup::saveControlFile() const
  960. {
  961. if(_saveControlFile) {
  962. _progressInfoFile->save();
  963. }
  964. }
  965. void RequestGroup::removeControlFile() const
  966. {
  967. _progressInfoFile->removeFile();
  968. }
  969. } // namespace aria2