RequestGroup.cc 40 KB

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