RequestGroup.cc 39 KB

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