RequestGroup.cc 41 KB

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