RequestGroup.cc 36 KB

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