RequestGroup.cc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  238. gid_, downloadContext_->getBasePath().c_str()));
  239. }
  240. } else {
  241. checkEntry.reset(new StreamCheckIntegrityEntry(this));
  242. }
  243. } else if(downloadFinishedByFileLength()) {
  244. pieceStorage_->markAllPiecesDone();
  245. #ifdef ENABLE_MESSAGE_DIGEST
  246. if(option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  247. downloadContext_->isChecksumVerificationAvailable()) {
  248. loadAndOpenFile(infoFile);
  249. ChecksumCheckIntegrityEntry* tempEntry =
  250. new ChecksumCheckIntegrityEntry(this);
  251. tempEntry->setRedownload(true);
  252. checkEntry.reset(tempEntry);
  253. } else
  254. #endif // ENABLE_MESSAGE_DIGEST
  255. {
  256. downloadContext_->setChecksumVerified(true);
  257. A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  258. gid_, 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_));
  336. btRegistry->put
  337. (gid_, SharedHandle<BtObject>
  338. (new BtObject
  339. (downloadContext_,
  340. pieceStorage_,
  341. peerStorage,
  342. btAnnounce,
  343. btRuntime,
  344. (progressInfoFile ?
  345. SharedHandle<BtProgressInfoFile>(progressInfoFile) :
  346. progressInfoFile_))));
  347. if(metadataGetMode) {
  348. if(option_->getAsBool(PREF_ENABLE_DHT) ||
  349. (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  350. option_->getAsBool(PREF_ENABLE_DHT6))) {
  351. if(option_->getAsBool(PREF_ENABLE_DHT)) {
  352. std::vector<Command*> dhtCommands;
  353. DHTSetup().setup(dhtCommands, e, AF_INET);
  354. e->addCommand(dhtCommands);
  355. }
  356. if(!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  357. option_->getAsBool(PREF_ENABLE_DHT6)) {
  358. std::vector<Command*> dhtCommands;
  359. DHTSetup().setup(dhtCommands, e, AF_INET6);
  360. e->addCommand(dhtCommands);
  361. }
  362. } else {
  363. A2_LOG_NOTICE("For BitTorrent Magnet URI, enabling DHT is strongly"
  364. " recommended. See --enable-dht option.");
  365. }
  366. SharedHandle<CheckIntegrityEntry> entry
  367. (new BtCheckIntegrityEntry(this));
  368. entry->onDownloadIncomplete(commands, e);
  369. return;
  370. }
  371. removeDefunctControlFile(progressInfoFile);
  372. {
  373. uint64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
  374. if(actualFileSize == downloadContext_->getTotalLength()) {
  375. // First, make DiskAdaptor read-only mode to allow the
  376. // program to seed file in read-only media.
  377. pieceStorage_->getDiskAdaptor()->enableReadOnly();
  378. } else {
  379. // Open file in writable mode to allow the program
  380. // truncate the file to downloadContext_->getTotalLength()
  381. A2_LOG_DEBUG
  382. (fmt("File size not match. File is opened in writable"
  383. " mode. Expected:%lld Actual:%lld",
  384. static_cast<long long int>(downloadContext_->getTotalLength()),
  385. static_cast<long long int>(actualFileSize)));
  386. }
  387. }
  388. // Call Load, Save and file allocation command here
  389. if(progressInfoFile->exists()) {
  390. // load .aria2 file if it exists.
  391. progressInfoFile->load();
  392. pieceStorage_->getDiskAdaptor()->openFile();
  393. } else {
  394. if(pieceStorage_->getDiskAdaptor()->fileExists()) {
  395. if(!option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  396. !option_->getAsBool(PREF_ALLOW_OVERWRITE) &&
  397. !option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  398. // TODO we need this->haltRequested = true?
  399. throw DOWNLOAD_FAILURE_EXCEPTION2
  400. (fmt(MSG_FILE_ALREADY_EXISTS,
  401. downloadContext_->getBasePath().c_str()),
  402. error_code::FILE_ALREADY_EXISTS);
  403. } else {
  404. pieceStorage_->getDiskAdaptor()->openFile();
  405. }
  406. if(option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  407. pieceStorage_->markAllPiecesDone();
  408. }
  409. } else {
  410. pieceStorage_->getDiskAdaptor()->openFile();
  411. }
  412. }
  413. progressInfoFile_ = progressInfoFile;
  414. if(!torrentAttrs->privateTorrent &&
  415. (option_->getAsBool(PREF_ENABLE_DHT) ||
  416. (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  417. option_->getAsBool(PREF_ENABLE_DHT6)))) {
  418. if(option_->getAsBool(PREF_ENABLE_DHT)) {
  419. std::vector<Command*> dhtCommands;
  420. DHTSetup().setup(dhtCommands, e, AF_INET);
  421. e->addCommand(dhtCommands);
  422. }
  423. if(!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  424. option_->getAsBool(PREF_ENABLE_DHT6)) {
  425. std::vector<Command*> dhtCommands;
  426. DHTSetup().setup(dhtCommands, e, AF_INET6);
  427. e->addCommand(dhtCommands);
  428. }
  429. const std::vector<std::pair<std::string, uint16_t> >& nodes =
  430. torrentAttrs->nodes;
  431. // TODO Are nodes in torrent IPv4 only?
  432. if(!nodes.empty() && DHTRegistry::isInitialized()) {
  433. DHTEntryPointNameResolveCommand* command =
  434. new DHTEntryPointNameResolveCommand(e->newCUID(), e, nodes);
  435. command->setTaskQueue(DHTRegistry::getData().taskQueue);
  436. command->setTaskFactory(DHTRegistry::getData().taskFactory);
  437. command->setRoutingTable(DHTRegistry::getData().routingTable);
  438. command->setLocalNode(DHTRegistry::getData().localNode);
  439. e->addCommand(command);
  440. }
  441. }
  442. SharedHandle<CheckIntegrityEntry> entry(new BtCheckIntegrityEntry(this));
  443. // --bt-seed-unverified=true is given and download has completed, skip
  444. // validation for piece hashes.
  445. if(option_->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  446. pieceStorage_->downloadFinished()) {
  447. entry->onDownloadFinished(commands, e);
  448. } else {
  449. processCheckIntegrityEntry(commands, entry, e);
  450. }
  451. return;
  452. }
  453. }
  454. #endif // ENABLE_BITTORRENT
  455. if(downloadContext_->getFileEntries().size() == 1) {
  456. // TODO I assume here when totallength is set to DownloadContext and it is
  457. // not 0, then filepath is also set DownloadContext correctly....
  458. if(option_->getAsBool(PREF_DRY_RUN) ||
  459. downloadContext_->getTotalLength() == 0) {
  460. createNextCommand(commands, e, 1);
  461. } else {
  462. if(e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  463. throw DOWNLOAD_FAILURE_EXCEPTION2
  464. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  465. downloadContext_->getBasePath().c_str()),
  466. error_code::DUPLICATE_DOWNLOAD);
  467. }
  468. SharedHandle<BtProgressInfoFile> progressInfoFile
  469. (new DefaultBtProgressInfoFile
  470. (downloadContext_, SharedHandle<PieceStorage>(), option_.get()));
  471. adjustFilename(progressInfoFile);
  472. initPieceStorage();
  473. SharedHandle<CheckIntegrityEntry> checkEntry =
  474. createCheckIntegrityEntry();
  475. if(checkEntry) {
  476. processCheckIntegrityEntry(commands, checkEntry, e);
  477. }
  478. }
  479. } else {
  480. // TODO --dry-run is not supported for multifile download for now.
  481. if(option_->getAsBool(PREF_DRY_RUN)) {
  482. throw DOWNLOAD_FAILURE_EXCEPTION
  483. ("--dry-run in multi-file download is not supported yet.");
  484. }
  485. // TODO file size is known in this context?
  486. // In this context, multiple FileEntry objects are in
  487. // DownloadContext.
  488. if(e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  489. throw DOWNLOAD_FAILURE_EXCEPTION2
  490. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  491. downloadContext_->getBasePath().c_str()),
  492. error_code::DUPLICATE_DOWNLOAD);
  493. }
  494. initPieceStorage();
  495. if(downloadContext_->getFileEntries().size() > 1) {
  496. pieceStorage_->setupFileFilter();
  497. }
  498. SharedHandle<DefaultBtProgressInfoFile> progressInfoFile
  499. (new DefaultBtProgressInfoFile(downloadContext_,
  500. pieceStorage_,
  501. option_.get()));
  502. removeDefunctControlFile(progressInfoFile);
  503. // Call Load, Save and file allocation command here
  504. if(progressInfoFile->exists()) {
  505. // load .aria2 file if it exists.
  506. progressInfoFile->load();
  507. pieceStorage_->getDiskAdaptor()->openFile();
  508. } else {
  509. if(pieceStorage_->getDiskAdaptor()->fileExists()) {
  510. if(!isCheckIntegrityReady() &&
  511. !option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  512. // TODO we need this->haltRequested = true?
  513. throw DOWNLOAD_FAILURE_EXCEPTION2
  514. (fmt(MSG_FILE_ALREADY_EXISTS,
  515. downloadContext_->getBasePath().c_str()),
  516. error_code::FILE_ALREADY_EXISTS);
  517. } else {
  518. pieceStorage_->getDiskAdaptor()->openFile();
  519. }
  520. } else {
  521. pieceStorage_->getDiskAdaptor()->openFile();
  522. }
  523. }
  524. progressInfoFile_ = progressInfoFile;
  525. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry
  526. (new StreamCheckIntegrityEntry(this));
  527. processCheckIntegrityEntry(commands, checkIntegrityEntry, e);
  528. }
  529. }
  530. void RequestGroup::processCheckIntegrityEntry
  531. (std::vector<Command*>& commands,
  532. const SharedHandle<CheckIntegrityEntry>& entry,
  533. DownloadEngine* e)
  534. {
  535. uint64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
  536. if(actualFileSize > downloadContext_->getTotalLength()) {
  537. entry->cutTrailingGarbage();
  538. }
  539. #ifdef ENABLE_MESSAGE_DIGEST
  540. if((option_->getAsBool(PREF_CHECK_INTEGRITY) ||
  541. downloadContext_->isChecksumVerificationNeeded()) &&
  542. entry->isValidationReady()) {
  543. entry->initValidator();
  544. // Don't save control file(.aria2 file) when user presses
  545. // control-c key while aria2 is checking hashes. If control file
  546. // doesn't exist when aria2 launched, the completed length in
  547. // saved control file will be 0 byte and this confuses user.
  548. // enableSaveControlFile() will be called after hash checking is
  549. // done. See CheckIntegrityCommand.
  550. disableSaveControlFile();
  551. e->getCheckIntegrityMan()->pushEntry(entry);
  552. } else
  553. #endif // ENABLE_MESSAGE_DIGEST
  554. {
  555. entry->onDownloadIncomplete(commands, e);
  556. }
  557. }
  558. void RequestGroup::initPieceStorage()
  559. {
  560. SharedHandle<PieceStorage> tempPieceStorage;
  561. if(downloadContext_->knowsTotalLength() &&
  562. // Following conditions are needed for chunked encoding with
  563. // content-length = 0. Google's dl server used this before.
  564. (downloadContext_->getTotalLength() > 0
  565. #ifdef ENABLE_BITTORRENT
  566. || downloadContext_->hasAttribute(bittorrent::BITTORRENT)
  567. #endif // ENABLE_BITTORRENT
  568. )) {
  569. #ifdef ENABLE_BITTORRENT
  570. DefaultPieceStorage* ps =
  571. new DefaultPieceStorage(downloadContext_, option_.get());
  572. SharedHandle<PieceStorage> psHolder(ps);
  573. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  574. if(isUriSuppliedForRequsetFileEntry
  575. (downloadContext_->getFileEntries().begin(),
  576. downloadContext_->getFileEntries().end())) {
  577. // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent
  578. // integrated downloads. Currently multi-file integrated
  579. // download is not supported.
  580. A2_LOG_DEBUG("Using LongestSequencePieceSelector");
  581. SharedHandle<PieceSelector> longestPieceSelector
  582. (new LongestSequencePieceSelector());
  583. ps->setPieceSelector(longestPieceSelector);
  584. }
  585. if(option_->defined(PREF_BT_PRIORITIZE_PIECE)) {
  586. std::vector<size_t> result;
  587. util::parsePrioritizePieceRange
  588. (result, option_->get(PREF_BT_PRIORITIZE_PIECE),
  589. downloadContext_->getFileEntries(),
  590. downloadContext_->getPieceLength());
  591. if(!result.empty()) {
  592. std::random_shuffle(result.begin(), result.end(),
  593. *(SimpleRandomizer::getInstance().get()));
  594. SharedHandle<PriorityPieceSelector> priSelector
  595. (new PriorityPieceSelector(ps->getPieceSelector()));
  596. priSelector->setPriorityPiece(result.begin(), result.end());
  597. ps->setPieceSelector(priSelector);
  598. }
  599. }
  600. }
  601. #else // !ENABLE_BITTORRENT
  602. DefaultPieceStorage* ps =
  603. new DefaultPieceStorage(downloadContext_, option_.get());
  604. SharedHandle<PieceStorage> psHolder(ps);
  605. #endif // !ENABLE_BITTORRENT
  606. if(diskWriterFactory_) {
  607. ps->setDiskWriterFactory(diskWriterFactory_);
  608. }
  609. tempPieceStorage.swap(psHolder);
  610. } else {
  611. UnknownLengthPieceStorage* ps =
  612. new UnknownLengthPieceStorage(downloadContext_, option_.get());
  613. SharedHandle<PieceStorage> psHolder(ps);
  614. if(diskWriterFactory_) {
  615. ps->setDiskWriterFactory(diskWriterFactory_);
  616. }
  617. tempPieceStorage.swap(psHolder);
  618. }
  619. tempPieceStorage->initStorage();
  620. SharedHandle<SegmentMan> tempSegmentMan
  621. (new SegmentMan(option_.get(), downloadContext_, tempPieceStorage));
  622. pieceStorage_.swap(tempPieceStorage);
  623. segmentMan_.swap(tempSegmentMan);
  624. }
  625. void RequestGroup::dropPieceStorage()
  626. {
  627. segmentMan_.reset();
  628. pieceStorage_.reset();
  629. }
  630. bool RequestGroup::downloadFinishedByFileLength()
  631. {
  632. // assuming that a control file doesn't exist.
  633. if(!isPreLocalFileCheckEnabled() ||
  634. option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  635. return false;
  636. }
  637. if(!downloadContext_->knowsTotalLength()) {
  638. return false;
  639. }
  640. File outfile(getFirstFilePath());
  641. if(outfile.exists() && downloadContext_->getTotalLength() == outfile.size()) {
  642. return true;
  643. } else {
  644. return false;
  645. }
  646. }
  647. void RequestGroup::adjustFilename
  648. (const SharedHandle<BtProgressInfoFile>& infoFile)
  649. {
  650. if(!isPreLocalFileCheckEnabled()) {
  651. // OK, no need to care about filename.
  652. return;
  653. }
  654. if(!option_->getAsBool(PREF_DRY_RUN) &&
  655. option_->getAsBool(PREF_REMOVE_CONTROL_FILE) &&
  656. infoFile->exists()) {
  657. infoFile->removeFile();
  658. A2_LOG_NOTICE(fmt("Removed control file for %s because it is requested by"
  659. " user.",
  660. infoFile->getFilename().c_str()));
  661. }
  662. if(infoFile->exists()) {
  663. // Use current filename
  664. } else if(downloadFinishedByFileLength()) {
  665. // File was downloaded already, no need to change file name.
  666. } else {
  667. File outfile(getFirstFilePath());
  668. if(outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
  669. outfile.size() <= downloadContext_->getTotalLength()) {
  670. // File exists but user decided to resume it.
  671. } else {
  672. #ifdef ENABLE_MESSAGE_DIGEST
  673. if(outfile.exists() && isCheckIntegrityReady()) {
  674. // check-integrity existing file
  675. } else {
  676. #endif // ENABLE_MESSAGE_DIGEST
  677. shouldCancelDownloadForSafety();
  678. #ifdef ENABLE_MESSAGE_DIGEST
  679. }
  680. #endif // ENABLE_MESSAGE_DIGEST
  681. }
  682. }
  683. }
  684. void RequestGroup::removeDefunctControlFile
  685. (const SharedHandle<BtProgressInfoFile>& progressInfoFile)
  686. {
  687. // Remove the control file if download file doesn't exist
  688. if(progressInfoFile->exists() &&
  689. !pieceStorage_->getDiskAdaptor()->fileExists()) {
  690. progressInfoFile->removeFile();
  691. A2_LOG_NOTICE(fmt(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  692. progressInfoFile->getFilename().c_str(),
  693. downloadContext_->getBasePath().c_str()));
  694. }
  695. }
  696. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  697. {
  698. try {
  699. if(!isPreLocalFileCheckEnabled()) {
  700. pieceStorage_->getDiskAdaptor()->initAndOpenFile();
  701. return;
  702. }
  703. removeDefunctControlFile(progressInfoFile);
  704. if(progressInfoFile->exists()) {
  705. progressInfoFile->load();
  706. pieceStorage_->getDiskAdaptor()->openExistingFile();
  707. } else {
  708. File outfile(getFirstFilePath());
  709. if(outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
  710. outfile.size() <= getTotalLength()) {
  711. pieceStorage_->getDiskAdaptor()->openExistingFile();
  712. pieceStorage_->markPiecesDone(outfile.size());
  713. } else {
  714. #ifdef ENABLE_MESSAGE_DIGEST
  715. if(outfile.exists() && isCheckIntegrityReady()) {
  716. pieceStorage_->getDiskAdaptor()->openExistingFile();
  717. } else {
  718. #endif // ENABLE_MESSAGE_DIGEST
  719. pieceStorage_->getDiskAdaptor()->initAndOpenFile();
  720. #ifdef ENABLE_MESSAGE_DIGEST
  721. }
  722. #endif // ENABLE_MESSAGE_DIGEST
  723. }
  724. }
  725. setProgressInfoFile(progressInfoFile);
  726. } catch(RecoverableException& e) {
  727. throw DOWNLOAD_FAILURE_EXCEPTION2(fmt(EX_DOWNLOAD_ABORTED), e);
  728. }
  729. }
  730. // assuming that a control file does not exist
  731. void RequestGroup::shouldCancelDownloadForSafety()
  732. {
  733. if(option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  734. return;
  735. }
  736. File outfile(getFirstFilePath());
  737. if(outfile.exists()) {
  738. if(option_->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  739. if(tryAutoFileRenaming()) {
  740. A2_LOG_NOTICE(fmt(MSG_FILE_RENAMED, getFirstFilePath().c_str()));
  741. } else {
  742. throw DOWNLOAD_FAILURE_EXCEPTION2
  743. (fmt("File renaming failed: %s", getFirstFilePath().c_str()),
  744. error_code::FILE_RENAMING_FAILED);
  745. }
  746. } else {
  747. throw DOWNLOAD_FAILURE_EXCEPTION2
  748. (fmt(MSG_FILE_ALREADY_EXISTS, getFirstFilePath().c_str()),
  749. error_code::FILE_ALREADY_EXISTS);
  750. }
  751. }
  752. }
  753. bool RequestGroup::tryAutoFileRenaming()
  754. {
  755. std::string filepath = getFirstFilePath();
  756. if(filepath.empty()) {
  757. return false;
  758. }
  759. for(unsigned int i = 1; i < 10000; ++i) {
  760. std::string newfilename = fmt("%s.%u", filepath.c_str(), i);
  761. File newfile(newfilename);
  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. static_cast<long long int>(expectedTotalLength),
  875. static_cast<long long int>(actualTotalLength)));
  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#%lld - Request queue check", gid_));
  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. btRuntime_ = 0;
  968. peerStorage_ = 0;
  969. #endif // ENABLE_BITTORRENT
  970. if(pieceStorage_) {
  971. pieceStorage_->removeAdvertisedPiece(0);
  972. }
  973. // Don't reset segmentMan_ and pieceStorage_ here to provide
  974. // progress information via RPC
  975. progressInfoFile_.reset();
  976. downloadContext_->releaseRuntimeResource();
  977. }
  978. void RequestGroup::preDownloadProcessing()
  979. {
  980. A2_LOG_DEBUG(fmt("Finding PreDownloadHandler for path %s.",
  981. getFirstFilePath().c_str()));
  982. try {
  983. for(std::vector<SharedHandle<PreDownloadHandler> >::const_iterator itr =
  984. preDownloadHandlers_.begin(), eoi = preDownloadHandlers_.end();
  985. itr != eoi; ++itr) {
  986. if((*itr)->canHandle(this)) {
  987. (*itr)->execute(this);
  988. return;
  989. }
  990. }
  991. } catch(RecoverableException& ex) {
  992. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  993. return;
  994. }
  995. A2_LOG_DEBUG("No PreDownloadHandler found.");
  996. return;
  997. }
  998. void RequestGroup::postDownloadProcessing
  999. (std::vector<SharedHandle<RequestGroup> >& groups)
  1000. {
  1001. A2_LOG_DEBUG(fmt("Finding PostDownloadHandler for path %s.",
  1002. getFirstFilePath().c_str()));
  1003. try {
  1004. for(std::vector<SharedHandle<PostDownloadHandler> >::const_iterator itr =
  1005. postDownloadHandlers_.begin(), eoi = postDownloadHandlers_.end();
  1006. itr != eoi; ++itr) {
  1007. if((*itr)->canHandle(this)) {
  1008. (*itr)->getNextRequestGroups(groups, this);
  1009. return;
  1010. }
  1011. }
  1012. } catch(RecoverableException& ex) {
  1013. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  1014. }
  1015. A2_LOG_DEBUG("No PostDownloadHandler found.");
  1016. }
  1017. void RequestGroup::initializePreDownloadHandler()
  1018. {
  1019. #ifdef ENABLE_BITTORRENT
  1020. if(option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  1021. preDownloadHandlers_.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  1022. }
  1023. #endif // ENABLE_BITTORRENT
  1024. #ifdef ENABLE_METALINK
  1025. if(option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
  1026. preDownloadHandlers_.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  1027. }
  1028. #endif // ENABLE_METALINK
  1029. }
  1030. void RequestGroup::initializePostDownloadHandler()
  1031. {
  1032. #ifdef ENABLE_BITTORRENT
  1033. if(option_->getAsBool(PREF_FOLLOW_TORRENT) ||
  1034. option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  1035. postDownloadHandlers_.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  1036. }
  1037. #endif // ENABLE_BITTORRENT
  1038. #ifdef ENABLE_METALINK
  1039. if(option_->getAsBool(PREF_FOLLOW_METALINK) ||
  1040. option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
  1041. postDownloadHandlers_.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  1042. }
  1043. #endif // ENABLE_METALINK
  1044. }
  1045. bool RequestGroup::isDependencyResolved()
  1046. {
  1047. if(!dependency_) {
  1048. return true;
  1049. }
  1050. return dependency_->resolve();
  1051. }
  1052. void RequestGroup::dependsOn(const DependencyHandle& dep)
  1053. {
  1054. dependency_ = dep;
  1055. }
  1056. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  1057. {
  1058. diskWriterFactory_ = diskWriterFactory;
  1059. }
  1060. void RequestGroup::addPostDownloadHandler
  1061. (const SharedHandle<PostDownloadHandler>& handler)
  1062. {
  1063. postDownloadHandlers_.push_back(handler);
  1064. }
  1065. void RequestGroup::addPreDownloadHandler
  1066. (const SharedHandle<PreDownloadHandler>& handler)
  1067. {
  1068. preDownloadHandlers_.push_back(handler);
  1069. }
  1070. void RequestGroup::clearPostDownloadHandler()
  1071. {
  1072. postDownloadHandlers_.clear();
  1073. }
  1074. void RequestGroup::clearPreDownloadHandler()
  1075. {
  1076. preDownloadHandlers_.clear();
  1077. }
  1078. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  1079. {
  1080. pieceStorage_ = pieceStorage;
  1081. }
  1082. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  1083. {
  1084. progressInfoFile_ = progressInfoFile;
  1085. }
  1086. bool RequestGroup::needsFileAllocation() const
  1087. {
  1088. return isFileAllocationEnabled() &&
  1089. (uint64_t)option_->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  1090. !pieceStorage_->getDiskAdaptor()->fileAllocationIterator()->finished();
  1091. }
  1092. DownloadResultHandle RequestGroup::createDownloadResult() const
  1093. {
  1094. A2_LOG_DEBUG(fmt("GID#%lld - Creating DownloadResult.", gid_));
  1095. TransferStat st = calculateStat();
  1096. SharedHandle<DownloadResult> res(new DownloadResult());
  1097. res->gid = gid_;
  1098. res->fileEntries = downloadContext_->getFileEntries();
  1099. res->inMemoryDownload = inMemoryDownload_;
  1100. res->sessionDownloadLength = st.getSessionDownloadLength();
  1101. res->sessionTime = downloadContext_->calculateSessionTime();
  1102. res->result = downloadResult();
  1103. res->followedBy = followedByGIDs_;
  1104. res->belongsTo = belongsToGID_;
  1105. res->option = option_;
  1106. res->metadataInfo = metadataInfo_;
  1107. res->totalLength = getTotalLength();
  1108. res->completedLength = getCompletedLength();
  1109. res->uploadLength = st.getAllTimeUploadLength();
  1110. if(pieceStorage_) {
  1111. if(pieceStorage_->getBitfieldLength() > 0) {
  1112. res->bitfield.assign(pieceStorage_->getBitfield(),
  1113. pieceStorage_->getBitfield()+
  1114. pieceStorage_->getBitfieldLength());
  1115. }
  1116. }
  1117. #ifdef ENABLE_BITTORRENT
  1118. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  1119. const unsigned char* p = bittorrent::getInfoHash(downloadContext_);
  1120. res->infoHash.assign(p, p+INFO_HASH_LENGTH);
  1121. }
  1122. #endif // ENABLE_BITTORRENT
  1123. res->pieceLength = downloadContext_->getPieceLength();
  1124. res->numPieces = downloadContext_->getNumPieces();
  1125. res->dir = option_->get(PREF_DIR);
  1126. return res;
  1127. }
  1128. void RequestGroup::reportDownloadFinished()
  1129. {
  1130. A2_LOG_NOTICE(fmt(MSG_FILE_DOWNLOAD_COMPLETED,
  1131. downloadContext_->getBasePath().c_str()));
  1132. uriSelector_->resetCounters();
  1133. #ifdef ENABLE_BITTORRENT
  1134. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  1135. TransferStat stat = calculateStat();
  1136. uint64_t completedLength = getCompletedLength();
  1137. double shareRatio = completedLength == 0 ? 0.0 :
  1138. 1.0*stat.getAllTimeUploadLength()/completedLength;
  1139. SharedHandle<TorrentAttribute> attrs =
  1140. bittorrent::getTorrentAttrs(downloadContext_);
  1141. if(!attrs->metadata.empty()) {
  1142. A2_LOG_NOTICE(fmt(MSG_SHARE_RATIO_REPORT,
  1143. shareRatio,
  1144. util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  1145. util::abbrevSize(completedLength).c_str()));
  1146. }
  1147. }
  1148. #endif // ENABLE_BITTORRENT
  1149. }
  1150. void RequestGroup::addAcceptType(const std::string& type)
  1151. {
  1152. if(std::find(acceptTypes_.begin(), acceptTypes_.end(), type) == acceptTypes_.end()) {
  1153. acceptTypes_.push_back(type);
  1154. }
  1155. }
  1156. void RequestGroup::removeAcceptType(const std::string& type)
  1157. {
  1158. acceptTypes_.erase(std::remove(acceptTypes_.begin(), acceptTypes_.end(), type),
  1159. acceptTypes_.end());
  1160. }
  1161. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  1162. {
  1163. uriSelector_ = uriSelector;
  1164. }
  1165. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  1166. {
  1167. if(pieceStorage_ && lastModifiedTime_.good()) {
  1168. A2_LOG_INFO(fmt("Applying Last-Modified time: %s",
  1169. lastModifiedTime_.toHTTPDate().c_str()));
  1170. size_t n =
  1171. pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_);
  1172. A2_LOG_INFO(fmt("Last-Modified attrs of %lu files were updated.",
  1173. static_cast<unsigned long>(n)));
  1174. }
  1175. }
  1176. void RequestGroup::updateLastModifiedTime(const Time& time)
  1177. {
  1178. if(time.good() && lastModifiedTime_ < time) {
  1179. lastModifiedTime_ = time;
  1180. }
  1181. }
  1182. void RequestGroup::increaseAndValidateFileNotFoundCount()
  1183. {
  1184. ++fileNotFoundCount_;
  1185. const unsigned int maxCount = option_->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  1186. if(maxCount > 0 && fileNotFoundCount_ >= maxCount &&
  1187. (!segmentMan_ ||
  1188. segmentMan_->calculateSessionDownloadLength() == 0)) {
  1189. throw DOWNLOAD_FAILURE_EXCEPTION2
  1190. (fmt("Reached max-file-not-found count=%u", maxCount),
  1191. error_code::MAX_FILE_NOT_FOUND);
  1192. }
  1193. }
  1194. void RequestGroup::markInMemoryDownload()
  1195. {
  1196. inMemoryDownload_ = true;
  1197. }
  1198. void RequestGroup::setTimeout(time_t timeout)
  1199. {
  1200. timeout_ = timeout;
  1201. }
  1202. bool RequestGroup::doesDownloadSpeedExceed()
  1203. {
  1204. return maxDownloadSpeedLimit_ > 0 &&
  1205. maxDownloadSpeedLimit_ < calculateStat().getDownloadSpeed();
  1206. }
  1207. bool RequestGroup::doesUploadSpeedExceed()
  1208. {
  1209. return maxUploadSpeedLimit_ > 0 &&
  1210. maxUploadSpeedLimit_ < calculateStat().getUploadSpeed();
  1211. }
  1212. void RequestGroup::saveControlFile() const
  1213. {
  1214. if(saveControlFile_) {
  1215. progressInfoFile_->save();
  1216. }
  1217. }
  1218. void RequestGroup::removeControlFile() const
  1219. {
  1220. progressInfoFile_->removeFile();
  1221. }
  1222. void RequestGroup::setDownloadContext
  1223. (const SharedHandle<DownloadContext>& downloadContext)
  1224. {
  1225. downloadContext_ = downloadContext;
  1226. if(downloadContext_) {
  1227. downloadContext_->setOwnerRequestGroup(this);
  1228. }
  1229. }
  1230. bool RequestGroup::p2pInvolved() const
  1231. {
  1232. #ifdef ENABLE_BITTORRENT
  1233. return downloadContext_->hasAttribute(bittorrent::BITTORRENT);
  1234. #else // !ENABLE_BITTORRENT
  1235. return false;
  1236. #endif // !ENABLE_BITTORRENT
  1237. }
  1238. a2_gid_t RequestGroup::newGID()
  1239. {
  1240. if(gidCounter_ == INT64_MAX) {
  1241. gidCounter_ = 0;
  1242. }
  1243. return ++gidCounter_;
  1244. }
  1245. } // namespace aria2