RequestGroup.cc 42 KB

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