RequestGroup.cc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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 "fmt.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. #include "Segment.h"
  78. #include "SocketRecvBuffer.h"
  79. #ifdef ENABLE_MESSAGE_DIGEST
  80. # include "CheckIntegrityCommand.h"
  81. # include "ChecksumCheckIntegrityEntry.h"
  82. #endif // ENABLE_MESSAGE_DIGEST
  83. #ifdef ENABLE_BITTORRENT
  84. # include "bittorrent_helper.h"
  85. # include "BtRegistry.h"
  86. # include "BtCheckIntegrityEntry.h"
  87. # include "DefaultPeerStorage.h"
  88. # include "DefaultBtAnnounce.h"
  89. # include "BtRuntime.h"
  90. # include "BtSetup.h"
  91. # include "BtPostDownloadHandler.h"
  92. # include "DHTSetup.h"
  93. # include "DHTRegistry.h"
  94. # include "DHTNode.h"
  95. # include "DHTRoutingTable.h"
  96. # include "DHTTaskQueue.h"
  97. # include "DHTTaskFactory.h"
  98. # include "DHTTokenTracker.h"
  99. # include "DHTMessageDispatcher.h"
  100. # include "DHTMessageReceiver.h"
  101. # include "DHTMessageFactory.h"
  102. # include "DHTMessageCallback.h"
  103. # include "BtMessageFactory.h"
  104. # include "BtRequestFactory.h"
  105. # include "BtMessageDispatcher.h"
  106. # include "BtMessageReceiver.h"
  107. # include "PeerConnection.h"
  108. # include "ExtensionMessageFactory.h"
  109. # include "DHTPeerAnnounceStorage.h"
  110. # include "DHTEntryPointNameResolveCommand.h"
  111. # include "LongestSequencePieceSelector.h"
  112. # include "PriorityPieceSelector.h"
  113. # include "bittorrent_helper.h"
  114. #endif // ENABLE_BITTORRENT
  115. #ifdef ENABLE_METALINK
  116. # include "MetalinkPostDownloadHandler.h"
  117. #endif // ENABLE_METALINK
  118. namespace aria2 {
  119. a2_gid_t RequestGroup::gidCounter_ = 0;
  120. RequestGroup::RequestGroup(const SharedHandle<Option>& option)
  121. : gid_(newGID()),
  122. option_(option),
  123. numConcurrentCommand_(option->getAsInt(PREF_SPLIT)),
  124. numStreamConnection_(0),
  125. numStreamCommand_(0),
  126. numCommand_(0),
  127. saveControlFile_(true),
  128. progressInfoFile_(new NullProgressInfoFile()),
  129. preLocalFileCheckEnabled_(true),
  130. haltRequested_(false),
  131. forceHaltRequested_(false),
  132. haltReason_(RequestGroup::NONE),
  133. pauseRequested_(false),
  134. uriSelector_(new InorderURISelector()),
  135. lastModifiedTime_(Time::null()),
  136. fileNotFoundCount_(0),
  137. timeout_(option->getAsInt(PREF_TIMEOUT)),
  138. #ifdef ENABLE_BITTORRENT
  139. btRuntime_(0),
  140. peerStorage_(0),
  141. #endif // ENABLE_BITTORRENT
  142. inMemoryDownload_(false),
  143. maxDownloadSpeedLimit_(option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT)),
  144. maxUploadSpeedLimit_(option->getAsInt(PREF_MAX_UPLOAD_LIMIT)),
  145. lastErrorCode_(error_code::UNDEFINED),
  146. belongsToGID_(0),
  147. requestGroupMan_(0),
  148. resumeFailureCount_(0)
  149. {
  150. fileAllocationEnabled_ = option_->get(PREF_FILE_ALLOCATION) != V_NONE;
  151. // Add types to be sent as a Accept header value here.
  152. // It would be good to put this value in Option so that user can tweak
  153. // and add this list.
  154. // The mime types of Metalink is used for `transparent metalink'.
  155. addAcceptType(DownloadHandlerConstants::getMetalinkContentTypes().begin(),
  156. DownloadHandlerConstants::getMetalinkContentTypes().end());
  157. if(!option_->getAsBool(PREF_DRY_RUN)) {
  158. initializePreDownloadHandler();
  159. initializePostDownloadHandler();
  160. }
  161. }
  162. RequestGroup::~RequestGroup() {}
  163. bool RequestGroup::isCheckIntegrityReady() const
  164. {
  165. return option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  166. (downloadContext_->isChecksumVerificationAvailable() ||
  167. downloadContext_->isPieceHashVerificationAvailable());
  168. }
  169. bool RequestGroup::downloadFinished() const
  170. {
  171. if(!pieceStorage_) {
  172. return false;
  173. } else {
  174. return pieceStorage_->downloadFinished();
  175. }
  176. }
  177. bool RequestGroup::allDownloadFinished() const
  178. {
  179. if(!pieceStorage_) {
  180. return false;
  181. } else {
  182. return pieceStorage_->allDownloadFinished();
  183. }
  184. }
  185. error_code::Value RequestGroup::downloadResult() const
  186. {
  187. if(downloadFinished() && !downloadContext_->isChecksumVerificationNeeded())
  188. return error_code::FINISHED;
  189. else {
  190. if(haltReason_ == RequestGroup::USER_REQUEST) {
  191. return error_code::REMOVED;
  192. } else if(lastErrorCode_ == error_code::UNDEFINED) {
  193. if(haltReason_ == RequestGroup::SHUTDOWN_SIGNAL) {
  194. return error_code::IN_PROGRESS;
  195. } else {
  196. return error_code::UNKNOWN_ERROR;
  197. }
  198. } else {
  199. return lastErrorCode_;
  200. }
  201. }
  202. }
  203. void RequestGroup::closeFile()
  204. {
  205. if(pieceStorage_) {
  206. pieceStorage_->getDiskAdaptor()->closeFile();
  207. }
  208. }
  209. // TODO The function name is not intuitive at all.. it does not convey
  210. // that this function open file.
  211. SharedHandle<CheckIntegrityEntry> RequestGroup::createCheckIntegrityEntry()
  212. {
  213. BtProgressInfoFileHandle infoFile
  214. (new DefaultBtProgressInfoFile(downloadContext_, pieceStorage_,
  215. option_.get()));
  216. SharedHandle<CheckIntegrityEntry> checkEntry;
  217. if(option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  218. downloadContext_->isPieceHashVerificationAvailable()) {
  219. // When checking piece hash, we don't care file is downloaded and
  220. // infoFile exists.
  221. loadAndOpenFile(infoFile);
  222. checkEntry.reset(new StreamCheckIntegrityEntry(this));
  223. } else if(infoFile->exists()) {
  224. loadAndOpenFile(infoFile);
  225. if(downloadFinished()) {
  226. #ifdef ENABLE_MESSAGE_DIGEST
  227. if(downloadContext_->isChecksumVerificationNeeded()) {
  228. A2_LOG_INFO(MSG_HASH_CHECK_NOT_DONE);
  229. ChecksumCheckIntegrityEntry* tempEntry =
  230. new ChecksumCheckIntegrityEntry(this);
  231. tempEntry->setRedownload(true);
  232. checkEntry.reset(tempEntry);
  233. } else
  234. #endif // ENABLE_MESSAGE_DIGEST
  235. {
  236. downloadContext_->setChecksumVerified(true);
  237. A2_LOG_NOTICE
  238. (fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  239. util::itos(gid_).c_str(),
  240. downloadContext_->getBasePath().c_str()));
  241. }
  242. } else {
  243. checkEntry.reset(new StreamCheckIntegrityEntry(this));
  244. }
  245. } else if(downloadFinishedByFileLength()) {
  246. pieceStorage_->markAllPiecesDone();
  247. #ifdef ENABLE_MESSAGE_DIGEST
  248. if(option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  249. downloadContext_->isChecksumVerificationAvailable()) {
  250. loadAndOpenFile(infoFile);
  251. ChecksumCheckIntegrityEntry* tempEntry =
  252. new ChecksumCheckIntegrityEntry(this);
  253. tempEntry->setRedownload(true);
  254. checkEntry.reset(tempEntry);
  255. } else
  256. #endif // ENABLE_MESSAGE_DIGEST
  257. {
  258. downloadContext_->setChecksumVerified(true);
  259. A2_LOG_NOTICE
  260. (fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  261. util::itos(gid_).c_str(),
  262. downloadContext_->getBasePath().c_str()));
  263. }
  264. } else {
  265. loadAndOpenFile(infoFile);
  266. checkEntry.reset(new StreamCheckIntegrityEntry(this));
  267. }
  268. return checkEntry;
  269. }
  270. void RequestGroup::createInitialCommand
  271. (std::vector<Command*>& commands, DownloadEngine* e)
  272. {
  273. // Start session timer here. When file size becomes known, it will
  274. // be reset again in *FileAllocationEntry, because hash check and
  275. // file allocation takes a time. For downloads in which file size
  276. // is unknown, session timer will not be reset.
  277. downloadContext_->resetDownloadStartTime();
  278. #ifdef ENABLE_BITTORRENT
  279. {
  280. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  281. SharedHandle<TorrentAttribute> torrentAttrs =
  282. bittorrent::getTorrentAttrs(downloadContext_);
  283. bool metadataGetMode = torrentAttrs->metadata.empty();
  284. if(option_->getAsBool(PREF_DRY_RUN)) {
  285. throw DOWNLOAD_FAILURE_EXCEPTION
  286. ("Cancel BitTorrent download in dry-run context.");
  287. }
  288. SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
  289. if(btRegistry->getDownloadContext(torrentAttrs->infoHash)) {
  290. // TODO If metadataGetMode == false and each FileEntry has
  291. // URI, then go without BT.
  292. throw DOWNLOAD_FAILURE_EXCEPTION2
  293. (fmt("InfoHash %s is already registered.",
  294. bittorrent::getInfoHashString(downloadContext_).c_str()),
  295. error_code::DUPLICATE_INFO_HASH);
  296. }
  297. if(metadataGetMode) {
  298. // Use UnknownLengthPieceStorage.
  299. initPieceStorage();
  300. } else {
  301. if(e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  302. throw DOWNLOAD_FAILURE_EXCEPTION2
  303. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  304. downloadContext_->getBasePath().c_str()),
  305. error_code::DUPLICATE_DOWNLOAD);
  306. }
  307. initPieceStorage();
  308. if(downloadContext_->getFileEntries().size() > 1) {
  309. pieceStorage_->setupFileFilter();
  310. }
  311. }
  312. SharedHandle<DefaultBtProgressInfoFile> progressInfoFile;
  313. if(!metadataGetMode) {
  314. progressInfoFile.reset(new DefaultBtProgressInfoFile(downloadContext_,
  315. pieceStorage_,
  316. option_.get()));
  317. }
  318. BtRuntimeHandle btRuntime(new BtRuntime());
  319. btRuntime->setMaxPeers(option_->getAsInt(PREF_BT_MAX_PEERS));
  320. btRuntime_ = btRuntime.get();
  321. if(progressInfoFile) {
  322. progressInfoFile->setBtRuntime(btRuntime);
  323. }
  324. SharedHandle<DefaultPeerStorage> peerStorage(new DefaultPeerStorage());
  325. peerStorage->setBtRuntime(btRuntime);
  326. peerStorage->setPieceStorage(pieceStorage_);
  327. peerStorage_ = peerStorage.get();
  328. if(progressInfoFile) {
  329. progressInfoFile->setPeerStorage(peerStorage);
  330. }
  331. SharedHandle<DefaultBtAnnounce> btAnnounce
  332. (new DefaultBtAnnounce(downloadContext_, option_.get()));
  333. btAnnounce->setBtRuntime(btRuntime);
  334. btAnnounce->setPieceStorage(pieceStorage_);
  335. btAnnounce->setPeerStorage(peerStorage);
  336. btAnnounce->setUserDefinedInterval
  337. (option_->getAsInt(PREF_BT_TRACKER_INTERVAL));
  338. btAnnounce->shuffleAnnounce();
  339. assert(btRegistry->get(gid_).isNull());
  340. btRegistry->put
  341. (gid_, BtObject
  342. (downloadContext_,
  343. pieceStorage_,
  344. peerStorage,
  345. btAnnounce,
  346. btRuntime,
  347. (progressInfoFile ?
  348. SharedHandle<BtProgressInfoFile>(progressInfoFile) :
  349. progressInfoFile_)));
  350. if(metadataGetMode) {
  351. if(option_->getAsBool(PREF_ENABLE_DHT) ||
  352. (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  353. option_->getAsBool(PREF_ENABLE_DHT6))) {
  354. if(option_->getAsBool(PREF_ENABLE_DHT)) {
  355. std::vector<Command*> dhtCommands;
  356. DHTSetup().setup(dhtCommands, e, AF_INET);
  357. e->addCommand(dhtCommands);
  358. }
  359. if(!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  360. option_->getAsBool(PREF_ENABLE_DHT6)) {
  361. std::vector<Command*> dhtCommands;
  362. DHTSetup().setup(dhtCommands, e, AF_INET6);
  363. e->addCommand(dhtCommands);
  364. }
  365. } else {
  366. A2_LOG_NOTICE("For BitTorrent Magnet URI, enabling DHT is strongly"
  367. " recommended. See --enable-dht option.");
  368. }
  369. SharedHandle<CheckIntegrityEntry> entry
  370. (new BtCheckIntegrityEntry(this));
  371. entry->onDownloadIncomplete(commands, e);
  372. return;
  373. }
  374. removeDefunctControlFile(progressInfoFile);
  375. {
  376. uint64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
  377. if(actualFileSize == downloadContext_->getTotalLength()) {
  378. // First, make DiskAdaptor read-only mode to allow the
  379. // program to seed file in read-only media.
  380. pieceStorage_->getDiskAdaptor()->enableReadOnly();
  381. } else {
  382. // Open file in writable mode to allow the program
  383. // truncate the file to downloadContext_->getTotalLength()
  384. A2_LOG_DEBUG
  385. (fmt("File size not match. File is opened in writable"
  386. " mode. Expected:%s Actual:%s",
  387. util::uitos(downloadContext_->getTotalLength()).c_str(),
  388. util::uitos(actualFileSize).c_str()));
  389. }
  390. }
  391. // Call Load, Save and file allocation command here
  392. if(progressInfoFile->exists()) {
  393. // load .aria2 file if it exists.
  394. progressInfoFile->load();
  395. pieceStorage_->getDiskAdaptor()->openFile();
  396. } else {
  397. if(pieceStorage_->getDiskAdaptor()->fileExists()) {
  398. if(!option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  399. !option_->getAsBool(PREF_ALLOW_OVERWRITE) &&
  400. !option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  401. // TODO we need this->haltRequested = true?
  402. throw DOWNLOAD_FAILURE_EXCEPTION2
  403. (fmt(MSG_FILE_ALREADY_EXISTS,
  404. downloadContext_->getBasePath().c_str()),
  405. error_code::FILE_ALREADY_EXISTS);
  406. } else {
  407. pieceStorage_->getDiskAdaptor()->openFile();
  408. }
  409. if(option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  410. pieceStorage_->markAllPiecesDone();
  411. }
  412. } else {
  413. pieceStorage_->getDiskAdaptor()->openFile();
  414. }
  415. }
  416. progressInfoFile_ = progressInfoFile;
  417. if(!torrentAttrs->privateTorrent &&
  418. (option_->getAsBool(PREF_ENABLE_DHT) ||
  419. (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  420. option_->getAsBool(PREF_ENABLE_DHT6)))) {
  421. if(option_->getAsBool(PREF_ENABLE_DHT)) {
  422. std::vector<Command*> dhtCommands;
  423. DHTSetup().setup(dhtCommands, e, AF_INET);
  424. e->addCommand(dhtCommands);
  425. }
  426. if(!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  427. option_->getAsBool(PREF_ENABLE_DHT6)) {
  428. std::vector<Command*> dhtCommands;
  429. DHTSetup().setup(dhtCommands, e, AF_INET6);
  430. e->addCommand(dhtCommands);
  431. }
  432. const std::vector<std::pair<std::string, uint16_t> >& nodes =
  433. torrentAttrs->nodes;
  434. // TODO Are nodes in torrent IPv4 only?
  435. if(!nodes.empty() && DHTRegistry::isInitialized()) {
  436. DHTEntryPointNameResolveCommand* command =
  437. new DHTEntryPointNameResolveCommand(e->newCUID(), e, nodes);
  438. command->setTaskQueue(DHTRegistry::getData().taskQueue);
  439. command->setTaskFactory(DHTRegistry::getData().taskFactory);
  440. command->setRoutingTable(DHTRegistry::getData().routingTable);
  441. command->setLocalNode(DHTRegistry::getData().localNode);
  442. e->addCommand(command);
  443. }
  444. }
  445. SharedHandle<CheckIntegrityEntry> entry(new BtCheckIntegrityEntry(this));
  446. // --bt-seed-unverified=true is given and download has completed, skip
  447. // validation for piece hashes.
  448. if(option_->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  449. pieceStorage_->downloadFinished()) {
  450. entry->onDownloadFinished(commands, e);
  451. } else {
  452. processCheckIntegrityEntry(commands, entry, e);
  453. }
  454. return;
  455. }
  456. }
  457. #endif // ENABLE_BITTORRENT
  458. if(downloadContext_->getFileEntries().size() == 1) {
  459. // TODO I assume here when totallength is set to DownloadContext and it is
  460. // not 0, then filepath is also set DownloadContext correctly....
  461. if(option_->getAsBool(PREF_DRY_RUN) ||
  462. downloadContext_->getTotalLength() == 0) {
  463. createNextCommand(commands, e, 1);
  464. } else {
  465. if(e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  466. throw DOWNLOAD_FAILURE_EXCEPTION2
  467. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  468. downloadContext_->getBasePath().c_str()),
  469. error_code::DUPLICATE_DOWNLOAD);
  470. }
  471. SharedHandle<BtProgressInfoFile> progressInfoFile
  472. (new DefaultBtProgressInfoFile
  473. (downloadContext_, SharedHandle<PieceStorage>(), option_.get()));
  474. adjustFilename(progressInfoFile);
  475. initPieceStorage();
  476. SharedHandle<CheckIntegrityEntry> checkEntry =
  477. createCheckIntegrityEntry();
  478. if(checkEntry) {
  479. processCheckIntegrityEntry(commands, checkEntry, e);
  480. }
  481. }
  482. } else {
  483. // TODO --dry-run is not supported for multifile download for now.
  484. if(option_->getAsBool(PREF_DRY_RUN)) {
  485. throw DOWNLOAD_FAILURE_EXCEPTION
  486. ("--dry-run in multi-file download is not supported yet.");
  487. }
  488. // TODO file size is known in this context?
  489. // In this context, multiple FileEntry objects are in
  490. // DownloadContext.
  491. if(e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  492. throw DOWNLOAD_FAILURE_EXCEPTION2
  493. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  494. downloadContext_->getBasePath().c_str()),
  495. error_code::DUPLICATE_DOWNLOAD);
  496. }
  497. initPieceStorage();
  498. if(downloadContext_->getFileEntries().size() > 1) {
  499. pieceStorage_->setupFileFilter();
  500. }
  501. SharedHandle<DefaultBtProgressInfoFile> progressInfoFile
  502. (new DefaultBtProgressInfoFile(downloadContext_,
  503. pieceStorage_,
  504. option_.get()));
  505. removeDefunctControlFile(progressInfoFile);
  506. // Call Load, Save and file allocation command here
  507. if(progressInfoFile->exists()) {
  508. // load .aria2 file if it exists.
  509. progressInfoFile->load();
  510. pieceStorage_->getDiskAdaptor()->openFile();
  511. } else {
  512. if(pieceStorage_->getDiskAdaptor()->fileExists()) {
  513. if(!isCheckIntegrityReady() &&
  514. !option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  515. // TODO we need this->haltRequested = true?
  516. throw DOWNLOAD_FAILURE_EXCEPTION2
  517. (fmt(MSG_FILE_ALREADY_EXISTS,
  518. downloadContext_->getBasePath().c_str()),
  519. error_code::FILE_ALREADY_EXISTS);
  520. } else {
  521. pieceStorage_->getDiskAdaptor()->openFile();
  522. }
  523. } else {
  524. pieceStorage_->getDiskAdaptor()->openFile();
  525. }
  526. }
  527. progressInfoFile_ = progressInfoFile;
  528. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry
  529. (new StreamCheckIntegrityEntry(this));
  530. processCheckIntegrityEntry(commands, checkIntegrityEntry, e);
  531. }
  532. }
  533. void RequestGroup::processCheckIntegrityEntry
  534. (std::vector<Command*>& commands,
  535. const SharedHandle<CheckIntegrityEntry>& entry,
  536. DownloadEngine* e)
  537. {
  538. uint64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
  539. if(actualFileSize > downloadContext_->getTotalLength()) {
  540. entry->cutTrailingGarbage();
  541. }
  542. #ifdef ENABLE_MESSAGE_DIGEST
  543. if((option_->getAsBool(PREF_CHECK_INTEGRITY) ||
  544. downloadContext_->isChecksumVerificationNeeded()) &&
  545. entry->isValidationReady()) {
  546. entry->initValidator();
  547. // Don't save control file(.aria2 file) when user presses
  548. // control-c key while aria2 is checking hashes. If control file
  549. // doesn't exist when aria2 launched, the completed length in
  550. // saved control file will be 0 byte and this confuses user.
  551. // enableSaveControlFile() will be called after hash checking is
  552. // done. See CheckIntegrityCommand.
  553. disableSaveControlFile();
  554. e->getCheckIntegrityMan()->pushEntry(entry);
  555. } else
  556. #endif // ENABLE_MESSAGE_DIGEST
  557. {
  558. entry->onDownloadIncomplete(commands, e);
  559. }
  560. }
  561. void RequestGroup::initPieceStorage()
  562. {
  563. SharedHandle<PieceStorage> tempPieceStorage;
  564. if(downloadContext_->knowsTotalLength() &&
  565. // Following conditions are needed for chunked encoding with
  566. // content-length = 0. Google's dl server used this before.
  567. (downloadContext_->getTotalLength() > 0
  568. #ifdef ENABLE_BITTORRENT
  569. || downloadContext_->hasAttribute(bittorrent::BITTORRENT)
  570. #endif // ENABLE_BITTORRENT
  571. )) {
  572. #ifdef ENABLE_BITTORRENT
  573. DefaultPieceStorage* ps =
  574. new DefaultPieceStorage(downloadContext_, option_.get());
  575. SharedHandle<PieceStorage> psHolder(ps);
  576. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  577. if(isUriSuppliedForRequsetFileEntry
  578. (downloadContext_->getFileEntries().begin(),
  579. downloadContext_->getFileEntries().end())) {
  580. // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent
  581. // integrated downloads. Currently multi-file integrated
  582. // download is not supported.
  583. A2_LOG_DEBUG("Using LongestSequencePieceSelector");
  584. SharedHandle<PieceSelector> longestPieceSelector
  585. (new LongestSequencePieceSelector());
  586. ps->setPieceSelector(longestPieceSelector);
  587. }
  588. if(option_->defined(PREF_BT_PRIORITIZE_PIECE)) {
  589. std::vector<size_t> result;
  590. util::parsePrioritizePieceRange
  591. (result, option_->get(PREF_BT_PRIORITIZE_PIECE),
  592. downloadContext_->getFileEntries(),
  593. downloadContext_->getPieceLength());
  594. if(!result.empty()) {
  595. std::random_shuffle(result.begin(), result.end(),
  596. *(SimpleRandomizer::getInstance().get()));
  597. SharedHandle<PriorityPieceSelector> priSelector
  598. (new PriorityPieceSelector(ps->getPieceSelector()));
  599. priSelector->setPriorityPiece(result.begin(), result.end());
  600. ps->setPieceSelector(priSelector);
  601. }
  602. }
  603. }
  604. #else // !ENABLE_BITTORRENT
  605. DefaultPieceStorage* ps =
  606. new DefaultPieceStorage(downloadContext_, option_.get());
  607. SharedHandle<PieceStorage> psHolder(ps);
  608. #endif // !ENABLE_BITTORRENT
  609. if(diskWriterFactory_) {
  610. ps->setDiskWriterFactory(diskWriterFactory_);
  611. }
  612. tempPieceStorage.swap(psHolder);
  613. } else {
  614. UnknownLengthPieceStorage* ps =
  615. new UnknownLengthPieceStorage(downloadContext_, option_.get());
  616. SharedHandle<PieceStorage> psHolder(ps);
  617. if(diskWriterFactory_) {
  618. ps->setDiskWriterFactory(diskWriterFactory_);
  619. }
  620. tempPieceStorage.swap(psHolder);
  621. }
  622. tempPieceStorage->initStorage();
  623. SharedHandle<SegmentMan> tempSegmentMan
  624. (new SegmentMan(option_.get(), downloadContext_, tempPieceStorage));
  625. pieceStorage_.swap(tempPieceStorage);
  626. segmentMan_.swap(tempSegmentMan);
  627. }
  628. void RequestGroup::dropPieceStorage()
  629. {
  630. segmentMan_.reset();
  631. pieceStorage_.reset();
  632. }
  633. bool RequestGroup::downloadFinishedByFileLength()
  634. {
  635. // assuming that a control file doesn't exist.
  636. if(!isPreLocalFileCheckEnabled() ||
  637. option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  638. return false;
  639. }
  640. if(!downloadContext_->knowsTotalLength()) {
  641. return false;
  642. }
  643. File outfile(getFirstFilePath());
  644. if(outfile.exists() && downloadContext_->getTotalLength() == outfile.size()) {
  645. return true;
  646. } else {
  647. return false;
  648. }
  649. }
  650. void RequestGroup::adjustFilename
  651. (const SharedHandle<BtProgressInfoFile>& infoFile)
  652. {
  653. if(!isPreLocalFileCheckEnabled()) {
  654. // OK, no need to care about filename.
  655. return;
  656. }
  657. if(!option_->getAsBool(PREF_DRY_RUN) &&
  658. option_->getAsBool(PREF_REMOVE_CONTROL_FILE) &&
  659. infoFile->exists()) {
  660. infoFile->removeFile();
  661. A2_LOG_NOTICE(fmt("Removed control file for %s because it is requested by"
  662. " user.",
  663. infoFile->getFilename().c_str()));
  664. }
  665. if(infoFile->exists()) {
  666. // Use current filename
  667. } else if(downloadFinishedByFileLength()) {
  668. // File was downloaded already, no need to change file name.
  669. } else {
  670. File outfile(getFirstFilePath());
  671. if(outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
  672. outfile.size() <= downloadContext_->getTotalLength()) {
  673. // File exists but user decided to resume it.
  674. } else {
  675. #ifdef ENABLE_MESSAGE_DIGEST
  676. if(outfile.exists() && isCheckIntegrityReady()) {
  677. // check-integrity existing file
  678. } else {
  679. #endif // ENABLE_MESSAGE_DIGEST
  680. shouldCancelDownloadForSafety();
  681. #ifdef ENABLE_MESSAGE_DIGEST
  682. }
  683. #endif // ENABLE_MESSAGE_DIGEST
  684. }
  685. }
  686. }
  687. void RequestGroup::removeDefunctControlFile
  688. (const SharedHandle<BtProgressInfoFile>& progressInfoFile)
  689. {
  690. // Remove the control file if download file doesn't exist
  691. if(progressInfoFile->exists() &&
  692. !pieceStorage_->getDiskAdaptor()->fileExists()) {
  693. progressInfoFile->removeFile();
  694. A2_LOG_NOTICE(fmt(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  695. progressInfoFile->getFilename().c_str(),
  696. downloadContext_->getBasePath().c_str()));
  697. }
  698. }
  699. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  700. {
  701. try {
  702. if(!isPreLocalFileCheckEnabled()) {
  703. pieceStorage_->getDiskAdaptor()->initAndOpenFile();
  704. return;
  705. }
  706. removeDefunctControlFile(progressInfoFile);
  707. if(progressInfoFile->exists()) {
  708. progressInfoFile->load();
  709. pieceStorage_->getDiskAdaptor()->openExistingFile();
  710. } else {
  711. File outfile(getFirstFilePath());
  712. if(outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
  713. outfile.size() <= getTotalLength()) {
  714. pieceStorage_->getDiskAdaptor()->openExistingFile();
  715. pieceStorage_->markPiecesDone(outfile.size());
  716. } else {
  717. #ifdef ENABLE_MESSAGE_DIGEST
  718. if(outfile.exists() && isCheckIntegrityReady()) {
  719. pieceStorage_->getDiskAdaptor()->openExistingFile();
  720. } else {
  721. #endif // ENABLE_MESSAGE_DIGEST
  722. pieceStorage_->getDiskAdaptor()->initAndOpenFile();
  723. #ifdef ENABLE_MESSAGE_DIGEST
  724. }
  725. #endif // ENABLE_MESSAGE_DIGEST
  726. }
  727. }
  728. setProgressInfoFile(progressInfoFile);
  729. } catch(RecoverableException& e) {
  730. throw DOWNLOAD_FAILURE_EXCEPTION2(fmt(EX_DOWNLOAD_ABORTED), e);
  731. }
  732. }
  733. // assuming that a control file does not exist
  734. void RequestGroup::shouldCancelDownloadForSafety()
  735. {
  736. if(option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  737. return;
  738. }
  739. File outfile(getFirstFilePath());
  740. if(outfile.exists()) {
  741. if(option_->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  742. if(tryAutoFileRenaming()) {
  743. A2_LOG_NOTICE(fmt(MSG_FILE_RENAMED, getFirstFilePath().c_str()));
  744. } else {
  745. throw DOWNLOAD_FAILURE_EXCEPTION2
  746. (fmt("File renaming failed: %s", getFirstFilePath().c_str()),
  747. error_code::FILE_RENAMING_FAILED);
  748. }
  749. } else {
  750. throw DOWNLOAD_FAILURE_EXCEPTION2
  751. (fmt(MSG_FILE_ALREADY_EXISTS, getFirstFilePath().c_str()),
  752. error_code::FILE_ALREADY_EXISTS);
  753. }
  754. }
  755. }
  756. bool RequestGroup::tryAutoFileRenaming()
  757. {
  758. std::string filepath = getFirstFilePath();
  759. if(filepath.empty()) {
  760. return false;
  761. }
  762. for(unsigned int i = 1; i < 10000; ++i) {
  763. File newfile(strconcat(filepath, A2STR::DOT_C, util::uitos(i)));
  764. File ctrlfile(newfile.getPath()+DefaultBtProgressInfoFile::getSuffix());
  765. if(!newfile.exists() || (newfile.exists() && ctrlfile.exists())) {
  766. downloadContext_->getFirstFileEntry()->setPath(newfile.getPath());
  767. return true;
  768. }
  769. }
  770. return false;
  771. }
  772. void RequestGroup::createNextCommandWithAdj(std::vector<Command*>& commands,
  773. DownloadEngine* e, int numAdj)
  774. {
  775. int numCommand;
  776. if(getTotalLength() == 0) {
  777. numCommand = 1+numAdj;
  778. } else {
  779. numCommand = std::min(downloadContext_->getNumPieces(),
  780. numConcurrentCommand_);
  781. numCommand += numAdj;
  782. }
  783. if(numCommand > 0) {
  784. createNextCommand(commands, e, numCommand);
  785. }
  786. }
  787. void RequestGroup::createNextCommand(std::vector<Command*>& commands,
  788. DownloadEngine* e)
  789. {
  790. int numCommand;
  791. if(getTotalLength() == 0) {
  792. if(numStreamCommand_ > 0) {
  793. numCommand = 0;
  794. } else {
  795. numCommand = 1;
  796. }
  797. } else {
  798. if(numStreamCommand_ >= numConcurrentCommand_) {
  799. numCommand = 0;
  800. } else {
  801. numCommand = std::min(downloadContext_->getNumPieces(),
  802. numConcurrentCommand_-numStreamCommand_);
  803. }
  804. }
  805. if(numCommand > 0) {
  806. createNextCommand(commands, e, numCommand);
  807. }
  808. }
  809. void RequestGroup::createNextCommand(std::vector<Command*>& commands,
  810. DownloadEngine* e,
  811. unsigned int numCommand)
  812. {
  813. for(; numCommand--; ) {
  814. Command* command = new CreateRequestCommand(e->newCUID(), this, e);
  815. commands.push_back(command);
  816. }
  817. if(!commands.empty()) {
  818. e->setNoWait(true);
  819. }
  820. }
  821. std::string RequestGroup::getFirstFilePath() const
  822. {
  823. assert(downloadContext_);
  824. if(inMemoryDownload()) {
  825. static const std::string DIR_MEMORY("[MEMORY]");
  826. return DIR_MEMORY+File(downloadContext_->getFirstFileEntry()->getPath()).getBasename();
  827. } else {
  828. return downloadContext_->getFirstFileEntry()->getPath();
  829. }
  830. }
  831. uint64_t RequestGroup::getTotalLength() const
  832. {
  833. if(!pieceStorage_) {
  834. return 0;
  835. } else {
  836. if(pieceStorage_->isSelectiveDownloadingMode()) {
  837. return pieceStorage_->getFilteredTotalLength();
  838. } else {
  839. return pieceStorage_->getTotalLength();
  840. }
  841. }
  842. }
  843. uint64_t RequestGroup::getCompletedLength() const
  844. {
  845. if(!pieceStorage_) {
  846. return 0;
  847. } else {
  848. if(pieceStorage_->isSelectiveDownloadingMode()) {
  849. return pieceStorage_->getFilteredCompletedLength();
  850. } else {
  851. return pieceStorage_->getCompletedLength();
  852. }
  853. }
  854. }
  855. void RequestGroup::validateFilename(const std::string& expectedFilename,
  856. const std::string& actualFilename) const
  857. {
  858. if(expectedFilename.empty()) {
  859. return;
  860. }
  861. if(expectedFilename != actualFilename) {
  862. throw DL_ABORT_EX(fmt(EX_FILENAME_MISMATCH,
  863. expectedFilename.c_str(),
  864. actualFilename.c_str()));
  865. }
  866. }
  867. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  868. uint64_t actualTotalLength) const
  869. {
  870. if(expectedTotalLength <= 0) {
  871. return;
  872. }
  873. if(expectedTotalLength != actualTotalLength) {
  874. throw DL_ABORT_EX
  875. (fmt(EX_SIZE_MISMATCH,
  876. util::itos(expectedTotalLength, true).c_str(),
  877. util::itos(actualTotalLength, true).c_str()));
  878. }
  879. }
  880. void RequestGroup::validateFilename(const std::string& actualFilename) const
  881. {
  882. validateFilename(downloadContext_->getFileEntries().front()->getBasename(), actualFilename);
  883. }
  884. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  885. {
  886. validateTotalLength(getTotalLength(), actualTotalLength);
  887. }
  888. void RequestGroup::increaseStreamCommand()
  889. {
  890. ++numStreamCommand_;
  891. }
  892. void RequestGroup::decreaseStreamCommand()
  893. {
  894. --numStreamCommand_;
  895. }
  896. void RequestGroup::increaseStreamConnection()
  897. {
  898. ++numStreamConnection_;
  899. }
  900. void RequestGroup::decreaseStreamConnection()
  901. {
  902. --numStreamConnection_;
  903. }
  904. unsigned int RequestGroup::getNumConnection() const
  905. {
  906. unsigned int numConnection = numStreamConnection_;
  907. #ifdef ENABLE_BITTORRENT
  908. if(btRuntime_) {
  909. numConnection += btRuntime_->getConnections();
  910. }
  911. #endif // ENABLE_BITTORRENT
  912. return numConnection;
  913. }
  914. void RequestGroup::increaseNumCommand()
  915. {
  916. ++numCommand_;
  917. }
  918. void RequestGroup::decreaseNumCommand()
  919. {
  920. --numCommand_;
  921. if(!numCommand_ && requestGroupMan_) {
  922. A2_LOG_DEBUG(fmt("GID#%s - Request queue check", util::itos(gid_).c_str()));
  923. requestGroupMan_->requestQueueCheck();
  924. }
  925. }
  926. TransferStat RequestGroup::calculateStat() const
  927. {
  928. TransferStat stat;
  929. #ifdef ENABLE_BITTORRENT
  930. if(peerStorage_) {
  931. stat = peerStorage_->calculateStat();
  932. }
  933. #endif // ENABLE_BITTORRENT
  934. if(segmentMan_) {
  935. stat.setDownloadSpeed
  936. (stat.getDownloadSpeed()+segmentMan_->calculateDownloadSpeed());
  937. stat.setSessionDownloadLength
  938. (stat.getSessionDownloadLength()+
  939. segmentMan_->calculateSessionDownloadLength());
  940. }
  941. return stat;
  942. }
  943. void RequestGroup::setHaltRequested(bool f, HaltReason haltReason)
  944. {
  945. haltRequested_ = f;
  946. if(haltRequested_) {
  947. pauseRequested_ = false;
  948. haltReason_ = haltReason;
  949. }
  950. #ifdef ENABLE_BITTORRENT
  951. if(btRuntime_) {
  952. btRuntime_->setHalt(f);
  953. }
  954. #endif // ENABLE_BITTORRENT
  955. }
  956. void RequestGroup::setForceHaltRequested(bool f, HaltReason haltReason)
  957. {
  958. setHaltRequested(f, haltReason);
  959. forceHaltRequested_ = f;
  960. }
  961. void RequestGroup::setPauseRequested(bool f)
  962. {
  963. pauseRequested_ = f;
  964. }
  965. void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
  966. {
  967. #ifdef ENABLE_BITTORRENT
  968. e->getBtRegistry()->remove(gid_);
  969. btRuntime_ = 0;
  970. peerStorage_ = 0;
  971. #endif // ENABLE_BITTORRENT
  972. if(pieceStorage_) {
  973. pieceStorage_->removeAdvertisedPiece(0);
  974. }
  975. // Don't reset segmentMan_ and pieceStorage_ here to provide
  976. // progress information via RPC
  977. progressInfoFile_.reset();
  978. downloadContext_->releaseRuntimeResource();
  979. }
  980. void RequestGroup::preDownloadProcessing()
  981. {
  982. A2_LOG_DEBUG(fmt("Finding PreDownloadHandler for path %s.",
  983. getFirstFilePath().c_str()));
  984. try {
  985. for(std::vector<SharedHandle<PreDownloadHandler> >::const_iterator itr =
  986. preDownloadHandlers_.begin(), eoi = preDownloadHandlers_.end();
  987. itr != eoi; ++itr) {
  988. if((*itr)->canHandle(this)) {
  989. (*itr)->execute(this);
  990. return;
  991. }
  992. }
  993. } catch(RecoverableException& ex) {
  994. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  995. return;
  996. }
  997. A2_LOG_DEBUG("No PreDownloadHandler found.");
  998. return;
  999. }
  1000. void RequestGroup::postDownloadProcessing
  1001. (std::vector<SharedHandle<RequestGroup> >& groups)
  1002. {
  1003. A2_LOG_DEBUG(fmt("Finding PostDownloadHandler for path %s.",
  1004. getFirstFilePath().c_str()));
  1005. try {
  1006. for(std::vector<SharedHandle<PostDownloadHandler> >::const_iterator itr =
  1007. postDownloadHandlers_.begin(), eoi = postDownloadHandlers_.end();
  1008. itr != eoi; ++itr) {
  1009. if((*itr)->canHandle(this)) {
  1010. (*itr)->getNextRequestGroups(groups, this);
  1011. return;
  1012. }
  1013. }
  1014. } catch(RecoverableException& ex) {
  1015. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  1016. }
  1017. A2_LOG_DEBUG("No PostDownloadHandler found.");
  1018. }
  1019. void RequestGroup::initializePreDownloadHandler()
  1020. {
  1021. #ifdef ENABLE_BITTORRENT
  1022. if(option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  1023. preDownloadHandlers_.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  1024. }
  1025. #endif // ENABLE_BITTORRENT
  1026. #ifdef ENABLE_METALINK
  1027. if(option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
  1028. preDownloadHandlers_.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  1029. }
  1030. #endif // ENABLE_METALINK
  1031. }
  1032. void RequestGroup::initializePostDownloadHandler()
  1033. {
  1034. #ifdef ENABLE_BITTORRENT
  1035. if(option_->getAsBool(PREF_FOLLOW_TORRENT) ||
  1036. option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  1037. postDownloadHandlers_.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  1038. }
  1039. #endif // ENABLE_BITTORRENT
  1040. #ifdef ENABLE_METALINK
  1041. if(option_->getAsBool(PREF_FOLLOW_METALINK) ||
  1042. option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
  1043. postDownloadHandlers_.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  1044. }
  1045. #endif // ENABLE_METALINK
  1046. }
  1047. bool RequestGroup::isDependencyResolved()
  1048. {
  1049. if(!dependency_) {
  1050. return true;
  1051. }
  1052. return dependency_->resolve();
  1053. }
  1054. void RequestGroup::dependsOn(const DependencyHandle& dep)
  1055. {
  1056. dependency_ = dep;
  1057. }
  1058. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  1059. {
  1060. diskWriterFactory_ = diskWriterFactory;
  1061. }
  1062. void RequestGroup::addPostDownloadHandler
  1063. (const SharedHandle<PostDownloadHandler>& handler)
  1064. {
  1065. postDownloadHandlers_.push_back(handler);
  1066. }
  1067. void RequestGroup::addPreDownloadHandler
  1068. (const SharedHandle<PreDownloadHandler>& handler)
  1069. {
  1070. preDownloadHandlers_.push_back(handler);
  1071. }
  1072. void RequestGroup::clearPostDownloadHandler()
  1073. {
  1074. postDownloadHandlers_.clear();
  1075. }
  1076. void RequestGroup::clearPreDownloadHandler()
  1077. {
  1078. preDownloadHandlers_.clear();
  1079. }
  1080. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  1081. {
  1082. pieceStorage_ = pieceStorage;
  1083. }
  1084. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  1085. {
  1086. progressInfoFile_ = progressInfoFile;
  1087. }
  1088. bool RequestGroup::needsFileAllocation() const
  1089. {
  1090. return isFileAllocationEnabled() &&
  1091. (uint64_t)option_->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  1092. !pieceStorage_->getDiskAdaptor()->fileAllocationIterator()->finished();
  1093. }
  1094. DownloadResultHandle RequestGroup::createDownloadResult() const
  1095. {
  1096. A2_LOG_DEBUG(fmt("GID#%s - Creating DownloadResult.",
  1097. util::itos(gid_).c_str()));
  1098. TransferStat st = calculateStat();
  1099. SharedHandle<DownloadResult> res(new DownloadResult());
  1100. res->gid = gid_;
  1101. res->fileEntries = downloadContext_->getFileEntries();
  1102. res->inMemoryDownload = inMemoryDownload_;
  1103. res->sessionDownloadLength = st.getSessionDownloadLength();
  1104. res->sessionTime = downloadContext_->calculateSessionTime();
  1105. res->result = downloadResult();
  1106. res->followedBy = followedByGIDs_;
  1107. res->belongsTo = belongsToGID_;
  1108. res->option = option_;
  1109. res->metadataInfo = metadataInfo_;
  1110. res->totalLength = getTotalLength();
  1111. res->completedLength = getCompletedLength();
  1112. res->uploadLength = st.getAllTimeUploadLength();
  1113. if(pieceStorage_) {
  1114. if(pieceStorage_->getBitfieldLength() > 0) {
  1115. res->bitfield = std::string(pieceStorage_->getBitfield(),
  1116. pieceStorage_->getBitfield()+
  1117. pieceStorage_->getBitfieldLength());
  1118. }
  1119. }
  1120. #ifdef ENABLE_BITTORRENT
  1121. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  1122. const unsigned char* p = bittorrent::getInfoHash(downloadContext_);
  1123. res->infoHash = std::string(p, p+INFO_HASH_LENGTH);
  1124. }
  1125. #endif // ENABLE_BITTORRENT
  1126. res->pieceLength = downloadContext_->getPieceLength();
  1127. res->numPieces = downloadContext_->getNumPieces();
  1128. res->dir = option_->get(PREF_DIR);
  1129. return res;
  1130. }
  1131. void RequestGroup::reportDownloadFinished()
  1132. {
  1133. A2_LOG_NOTICE(fmt(MSG_FILE_DOWNLOAD_COMPLETED,
  1134. downloadContext_->getBasePath().c_str()));
  1135. uriSelector_->resetCounters();
  1136. #ifdef ENABLE_BITTORRENT
  1137. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  1138. TransferStat stat = calculateStat();
  1139. uint64_t completedLength = getCompletedLength();
  1140. double shareRatio = completedLength == 0 ? 0.0 :
  1141. 1.0*stat.getAllTimeUploadLength()/completedLength;
  1142. SharedHandle<TorrentAttribute> attrs =
  1143. bittorrent::getTorrentAttrs(downloadContext_);
  1144. if(!attrs->metadata.empty()) {
  1145. A2_LOG_NOTICE(fmt(MSG_SHARE_RATIO_REPORT,
  1146. shareRatio,
  1147. util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  1148. util::abbrevSize(completedLength).c_str()));
  1149. }
  1150. }
  1151. #endif // ENABLE_BITTORRENT
  1152. }
  1153. void RequestGroup::addAcceptType(const std::string& type)
  1154. {
  1155. if(std::find(acceptTypes_.begin(), acceptTypes_.end(), type) == acceptTypes_.end()) {
  1156. acceptTypes_.push_back(type);
  1157. }
  1158. }
  1159. void RequestGroup::removeAcceptType(const std::string& type)
  1160. {
  1161. acceptTypes_.erase(std::remove(acceptTypes_.begin(), acceptTypes_.end(), type),
  1162. acceptTypes_.end());
  1163. }
  1164. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  1165. {
  1166. uriSelector_ = uriSelector;
  1167. }
  1168. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  1169. {
  1170. if(pieceStorage_ && lastModifiedTime_.good()) {
  1171. A2_LOG_INFO(fmt("Applying Last-Modified time: %s",
  1172. lastModifiedTime_.toHTTPDate().c_str()));
  1173. size_t n =
  1174. pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_);
  1175. A2_LOG_INFO(fmt("Last-Modified attrs of %lu files were updated.",
  1176. static_cast<unsigned long>(n)));
  1177. }
  1178. }
  1179. void RequestGroup::updateLastModifiedTime(const Time& time)
  1180. {
  1181. if(time.good() && lastModifiedTime_ < time) {
  1182. lastModifiedTime_ = time;
  1183. }
  1184. }
  1185. void RequestGroup::increaseAndValidateFileNotFoundCount()
  1186. {
  1187. ++fileNotFoundCount_;
  1188. const unsigned int maxCount = option_->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  1189. if(maxCount > 0 && fileNotFoundCount_ >= maxCount &&
  1190. (!segmentMan_ ||
  1191. segmentMan_->calculateSessionDownloadLength() == 0)) {
  1192. throw DOWNLOAD_FAILURE_EXCEPTION2
  1193. (fmt("Reached max-file-not-found count=%u", maxCount),
  1194. error_code::MAX_FILE_NOT_FOUND);
  1195. }
  1196. }
  1197. void RequestGroup::markInMemoryDownload()
  1198. {
  1199. inMemoryDownload_ = true;
  1200. }
  1201. void RequestGroup::setTimeout(time_t timeout)
  1202. {
  1203. timeout_ = timeout;
  1204. }
  1205. bool RequestGroup::doesDownloadSpeedExceed()
  1206. {
  1207. return maxDownloadSpeedLimit_ > 0 &&
  1208. maxDownloadSpeedLimit_ < calculateStat().getDownloadSpeed();
  1209. }
  1210. bool RequestGroup::doesUploadSpeedExceed()
  1211. {
  1212. return maxUploadSpeedLimit_ > 0 &&
  1213. maxUploadSpeedLimit_ < calculateStat().getUploadSpeed();
  1214. }
  1215. void RequestGroup::saveControlFile() const
  1216. {
  1217. if(saveControlFile_) {
  1218. progressInfoFile_->save();
  1219. }
  1220. }
  1221. void RequestGroup::removeControlFile() const
  1222. {
  1223. progressInfoFile_->removeFile();
  1224. }
  1225. void RequestGroup::setDownloadContext
  1226. (const SharedHandle<DownloadContext>& downloadContext)
  1227. {
  1228. downloadContext_ = downloadContext;
  1229. if(downloadContext_) {
  1230. downloadContext_->setOwnerRequestGroup(this);
  1231. }
  1232. }
  1233. bool RequestGroup::p2pInvolved() const
  1234. {
  1235. #ifdef ENABLE_BITTORRENT
  1236. return downloadContext_->hasAttribute(bittorrent::BITTORRENT);
  1237. #else // !ENABLE_BITTORRENT
  1238. return false;
  1239. #endif // !ENABLE_BITTORRENT
  1240. }
  1241. a2_gid_t RequestGroup::newGID()
  1242. {
  1243. if(gidCounter_ == INT64_MAX) {
  1244. gidCounter_ = 0;
  1245. }
  1246. return ++gidCounter_;
  1247. }
  1248. } // namespace aria2