RequestGroup.cc 42 KB

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