RequestGroup.cc 35 KB

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