RequestGroup.cc 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroup.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include "PostDownloadHandler.h"
  39. #include "DownloadEngine.h"
  40. #include "SegmentMan.h"
  41. #include "NullProgressInfoFile.h"
  42. #include "Dependency.h"
  43. #include "prefs.h"
  44. #include "CreateRequestCommand.h"
  45. #include "File.h"
  46. #include "message.h"
  47. #include "util.h"
  48. #include "LogFactory.h"
  49. #include "Logger.h"
  50. #include "DiskAdaptor.h"
  51. #include "DiskWriterFactory.h"
  52. #include "RecoverableException.h"
  53. #include "StreamCheckIntegrityEntry.h"
  54. #include "CheckIntegrityCommand.h"
  55. #include "UnknownLengthPieceStorage.h"
  56. #include "DownloadContext.h"
  57. #include "DlAbortEx.h"
  58. #include "DownloadFailureException.h"
  59. #include "RequestGroupMan.h"
  60. #include "DefaultBtProgressInfoFile.h"
  61. #include "DefaultPieceStorage.h"
  62. #include "download_handlers.h"
  63. #include "MemoryBufferPreDownloadHandler.h"
  64. #include "DownloadHandlerConstants.h"
  65. #include "Option.h"
  66. #include "FileEntry.h"
  67. #include "Request.h"
  68. #include "FileAllocationIterator.h"
  69. #include "fmt.h"
  70. #include "A2STR.h"
  71. #include "URISelector.h"
  72. #include "InorderURISelector.h"
  73. #include "PieceSelector.h"
  74. #include "a2functional.h"
  75. #include "SocketCore.h"
  76. #include "SimpleRandomizer.h"
  77. #include "Segment.h"
  78. #include "SocketRecvBuffer.h"
  79. #include "RequestGroupCriteria.h"
  80. #include "CheckIntegrityCommand.h"
  81. #include "ChecksumCheckIntegrityEntry.h"
  82. #ifdef ENABLE_BITTORRENT
  83. #include "bittorrent_helper.h"
  84. #include "BtRegistry.h"
  85. #include "BtCheckIntegrityEntry.h"
  86. #include "DefaultPeerStorage.h"
  87. #include "DefaultBtAnnounce.h"
  88. #include "BtRuntime.h"
  89. #include "BtSetup.h"
  90. #include "BtPostDownloadHandler.h"
  91. #include "DHTSetup.h"
  92. #include "DHTRegistry.h"
  93. #include "DHTNode.h"
  94. #include "DHTRoutingTable.h"
  95. #include "DHTTaskQueue.h"
  96. #include "DHTTaskFactory.h"
  97. #include "DHTTokenTracker.h"
  98. #include "DHTMessageDispatcher.h"
  99. #include "DHTMessageReceiver.h"
  100. #include "DHTMessageFactory.h"
  101. #include "DHTMessageCallback.h"
  102. #include "BtMessageFactory.h"
  103. #include "BtRequestFactory.h"
  104. #include "BtMessageDispatcher.h"
  105. #include "BtMessageReceiver.h"
  106. #include "PeerConnection.h"
  107. #include "ExtensionMessageFactory.h"
  108. #include "DHTPeerAnnounceStorage.h"
  109. #include "DHTEntryPointNameResolveCommand.h"
  110. #include "LongestSequencePieceSelector.h"
  111. #include "PriorityPieceSelector.h"
  112. #include "bittorrent_helper.h"
  113. #endif // ENABLE_BITTORRENT
  114. #ifdef ENABLE_METALINK
  115. #include "MetalinkPostDownloadHandler.h"
  116. #endif // ENABLE_METALINK
  117. namespace aria2 {
  118. RequestGroup::RequestGroup(const std::shared_ptr<GroupId>& gid,
  119. const std::shared_ptr<Option>& option)
  120. : belongsToGID_(0),
  121. gid_(gid),
  122. option_(option),
  123. progressInfoFile_(std::make_shared<NullProgressInfoFile>()),
  124. uriSelector_(make_unique<InorderURISelector>()),
  125. requestGroupMan_(nullptr),
  126. #ifdef ENABLE_BITTORRENT
  127. btRuntime_(nullptr),
  128. peerStorage_(nullptr),
  129. #endif // ENABLE_BITTORRENT
  130. followingGID_(0),
  131. lastModifiedTime_(Time::null()),
  132. timeout_(option->getAsInt(PREF_TIMEOUT)),
  133. state_(STATE_WAITING),
  134. numConcurrentCommand_(option->getAsInt(PREF_SPLIT)),
  135. numStreamConnection_(0),
  136. numStreamCommand_(0),
  137. numCommand_(0),
  138. fileNotFoundCount_(0),
  139. maxDownloadSpeedLimit_(option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT)),
  140. maxUploadSpeedLimit_(option->getAsInt(PREF_MAX_UPLOAD_LIMIT)),
  141. resumeFailureCount_(0),
  142. haltReason_(RequestGroup::NONE),
  143. lastErrorCode_(error_code::UNDEFINED),
  144. saveControlFile_(true),
  145. preLocalFileCheckEnabled_(true),
  146. haltRequested_(false),
  147. forceHaltRequested_(false),
  148. pauseRequested_(false),
  149. inMemoryDownload_(false),
  150. seedOnly_(false)
  151. {
  152. fileAllocationEnabled_ = option_->get(PREF_FILE_ALLOCATION) != V_NONE;
  153. if (!option_->getAsBool(PREF_DRY_RUN)) {
  154. initializePreDownloadHandler();
  155. initializePostDownloadHandler();
  156. }
  157. }
  158. RequestGroup::~RequestGroup() {}
  159. bool RequestGroup::isCheckIntegrityReady()
  160. {
  161. return option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  162. ((downloadContext_->isChecksumVerificationAvailable() &&
  163. downloadFinishedByFileLength()) ||
  164. downloadContext_->isPieceHashVerificationAvailable());
  165. }
  166. bool RequestGroup::downloadFinished() const
  167. {
  168. if (!pieceStorage_) {
  169. return false;
  170. }
  171. return pieceStorage_->downloadFinished();
  172. }
  173. bool RequestGroup::allDownloadFinished() const
  174. {
  175. if (!pieceStorage_) {
  176. return false;
  177. }
  178. return pieceStorage_->allDownloadFinished();
  179. }
  180. std::pair<error_code::Value, std::string> RequestGroup::downloadResult() const
  181. {
  182. if (downloadFinished() && !downloadContext_->isChecksumVerificationNeeded()) {
  183. return std::make_pair(error_code::FINISHED, "");
  184. }
  185. if (haltReason_ == RequestGroup::USER_REQUEST) {
  186. return std::make_pair(error_code::REMOVED, "");
  187. }
  188. if (lastErrorCode_ == error_code::UNDEFINED) {
  189. if (haltReason_ == RequestGroup::SHUTDOWN_SIGNAL) {
  190. return std::make_pair(error_code::IN_PROGRESS, "");
  191. }
  192. return std::make_pair(error_code::UNKNOWN_ERROR, "");
  193. }
  194. return std::make_pair(lastErrorCode_, lastErrorMessage_);
  195. }
  196. void RequestGroup::closeFile()
  197. {
  198. if (pieceStorage_) {
  199. pieceStorage_->flushWrDiskCacheEntry();
  200. pieceStorage_->getDiskAdaptor()->closeFile();
  201. }
  202. }
  203. // TODO The function name is not intuitive at all.. it does not convey
  204. // that this function open file.
  205. std::unique_ptr<CheckIntegrityEntry> RequestGroup::createCheckIntegrityEntry()
  206. {
  207. auto infoFile = std::make_shared<DefaultBtProgressInfoFile>(
  208. downloadContext_, pieceStorage_, option_.get());
  209. if (option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  210. downloadContext_->isPieceHashVerificationAvailable()) {
  211. // When checking piece hash, we don't care file is downloaded and
  212. // infoFile exists.
  213. loadAndOpenFile(infoFile);
  214. return make_unique<StreamCheckIntegrityEntry>(this);
  215. }
  216. if (isPreLocalFileCheckEnabled() &&
  217. (infoFile->exists() || (File(getFirstFilePath()).exists() &&
  218. option_->getAsBool(PREF_CONTINUE)))) {
  219. // If infoFile exists or -c option is given, we need to check
  220. // download has been completed (which is determined after
  221. // loadAndOpenFile()). If so, use ChecksumCheckIntegrityEntry when
  222. // verification is enabled, because CreateRequestCommand does not
  223. // issue checksum verification and download fails without it.
  224. loadAndOpenFile(infoFile);
  225. if (downloadFinished()) {
  226. if (downloadContext_->isChecksumVerificationNeeded()) {
  227. A2_LOG_INFO(MSG_HASH_CHECK_NOT_DONE);
  228. auto tempEntry = make_unique<ChecksumCheckIntegrityEntry>(this);
  229. tempEntry->setRedownload(true);
  230. return std::move(tempEntry);
  231. }
  232. downloadContext_->setChecksumVerified(true);
  233. A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED, gid_->toHex().c_str(),
  234. downloadContext_->getBasePath().c_str()));
  235. return nullptr;
  236. }
  237. return make_unique<StreamCheckIntegrityEntry>(this);
  238. }
  239. if (downloadFinishedByFileLength() &&
  240. downloadContext_->isChecksumVerificationAvailable()) {
  241. pieceStorage_->markAllPiecesDone();
  242. loadAndOpenFile(infoFile);
  243. auto tempEntry = make_unique<ChecksumCheckIntegrityEntry>(this);
  244. tempEntry->setRedownload(true);
  245. return std::move(tempEntry);
  246. }
  247. loadAndOpenFile(infoFile);
  248. return make_unique<StreamCheckIntegrityEntry>(this);
  249. }
  250. void RequestGroup::createInitialCommand(
  251. std::vector<std::unique_ptr<Command>>& commands, DownloadEngine* e)
  252. {
  253. // Start session timer here. When file size becomes known, it will
  254. // be reset again in *FileAllocationEntry, because hash check and
  255. // file allocation takes a time. For downloads in which file size
  256. // is unknown, session timer will not be reset.
  257. downloadContext_->resetDownloadStartTime();
  258. #ifdef ENABLE_BITTORRENT
  259. if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  260. auto torrentAttrs = bittorrent::getTorrentAttrs(downloadContext_);
  261. bool metadataGetMode = torrentAttrs->metadata.empty();
  262. if (option_->getAsBool(PREF_DRY_RUN)) {
  263. throw DOWNLOAD_FAILURE_EXCEPTION(
  264. "Cancel BitTorrent download in dry-run context.");
  265. }
  266. auto& btRegistry = e->getBtRegistry();
  267. if (btRegistry->getDownloadContext(torrentAttrs->infoHash)) {
  268. // TODO If metadataGetMode == false and each FileEntry has
  269. // URI, then go without BT.
  270. throw DOWNLOAD_FAILURE_EXCEPTION2(
  271. fmt("InfoHash %s is already registered.",
  272. bittorrent::getInfoHashString(downloadContext_).c_str()),
  273. error_code::DUPLICATE_INFO_HASH);
  274. }
  275. if (metadataGetMode) {
  276. // Use UnknownLengthPieceStorage.
  277. initPieceStorage();
  278. }
  279. else if (e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  280. throw DOWNLOAD_FAILURE_EXCEPTION2(
  281. fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  282. downloadContext_->getBasePath().c_str()),
  283. error_code::DUPLICATE_DOWNLOAD);
  284. }
  285. else {
  286. initPieceStorage();
  287. if (downloadContext_->getFileEntries().size() > 1) {
  288. pieceStorage_->setupFileFilter();
  289. }
  290. }
  291. std::shared_ptr<DefaultBtProgressInfoFile> progressInfoFile;
  292. if (!metadataGetMode) {
  293. progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>(
  294. downloadContext_, pieceStorage_, option_.get());
  295. }
  296. auto btRuntime = std::make_shared<BtRuntime>();
  297. btRuntime->setMaxPeers(option_->getAsInt(PREF_BT_MAX_PEERS));
  298. btRuntime_ = btRuntime.get();
  299. if (progressInfoFile) {
  300. progressInfoFile->setBtRuntime(btRuntime);
  301. }
  302. auto peerStorage = std::make_shared<DefaultPeerStorage>();
  303. peerStorage->setBtRuntime(btRuntime);
  304. peerStorage->setPieceStorage(pieceStorage_);
  305. peerStorage_ = peerStorage.get();
  306. if (progressInfoFile) {
  307. progressInfoFile->setPeerStorage(peerStorage);
  308. }
  309. auto btAnnounce = std::make_shared<DefaultBtAnnounce>(
  310. downloadContext_.get(), option_.get());
  311. btAnnounce->setBtRuntime(btRuntime);
  312. btAnnounce->setPieceStorage(pieceStorage_);
  313. btAnnounce->setPeerStorage(peerStorage);
  314. btAnnounce->setUserDefinedInterval(
  315. std::chrono::seconds(option_->getAsInt(PREF_BT_TRACKER_INTERVAL)));
  316. btAnnounce->shuffleAnnounce();
  317. assert(!btRegistry->get(gid_->getNumericId()));
  318. btRegistry->put(
  319. gid_->getNumericId(),
  320. make_unique<BtObject>(
  321. downloadContext_, pieceStorage_, peerStorage, btAnnounce, btRuntime,
  322. (progressInfoFile ? progressInfoFile : progressInfoFile_)));
  323. if (option_->getAsBool(PREF_ENABLE_DHT) ||
  324. (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  325. option_->getAsBool(PREF_ENABLE_DHT6))) {
  326. if (option_->getAsBool(PREF_ENABLE_DHT)) {
  327. std::vector<std::unique_ptr<Command>> c, rc;
  328. std::tie(c, rc) = DHTSetup().setup(e, AF_INET);
  329. e->addCommand(std::move(c));
  330. for (auto& a : rc) {
  331. e->addRoutineCommand(std::move(a));
  332. }
  333. }
  334. if (!e->getOption()->getAsBool(PREF_DISABLE_IPV6) &&
  335. option_->getAsBool(PREF_ENABLE_DHT6)) {
  336. std::vector<std::unique_ptr<Command>> c, rc;
  337. std::tie(c, rc) = DHTSetup().setup(e, AF_INET6);
  338. e->addCommand(std::move(c));
  339. for (auto& a : rc) {
  340. e->addRoutineCommand(std::move(a));
  341. }
  342. }
  343. const auto& nodes = torrentAttrs->nodes;
  344. // TODO Are nodes in torrent IPv4 only?
  345. if (!torrentAttrs->privateTorrent && !nodes.empty() &&
  346. DHTRegistry::isInitialized()) {
  347. auto command = make_unique<DHTEntryPointNameResolveCommand>(
  348. e->newCUID(), e, nodes);
  349. command->setTaskQueue(DHTRegistry::getData().taskQueue.get());
  350. command->setTaskFactory(DHTRegistry::getData().taskFactory.get());
  351. command->setRoutingTable(DHTRegistry::getData().routingTable.get());
  352. command->setLocalNode(DHTRegistry::getData().localNode);
  353. e->addCommand(std::move(command));
  354. }
  355. }
  356. else if (metadataGetMode) {
  357. A2_LOG_NOTICE(_("For BitTorrent Magnet URI, enabling DHT is strongly"
  358. " recommended. See --enable-dht option."));
  359. }
  360. if (metadataGetMode) {
  361. BtCheckIntegrityEntry{this}.onDownloadIncomplete(commands, e);
  362. return;
  363. }
  364. removeDefunctControlFile(progressInfoFile);
  365. {
  366. int64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
  367. if (actualFileSize == downloadContext_->getTotalLength()) {
  368. // First, make DiskAdaptor read-only mode to allow the
  369. // program to seed file in read-only media.
  370. pieceStorage_->getDiskAdaptor()->enableReadOnly();
  371. }
  372. else {
  373. // Open file in writable mode to allow the program
  374. // truncate the file to downloadContext_->getTotalLength()
  375. A2_LOG_DEBUG(fmt("File size not match. File is opened in writable"
  376. " mode. Expected:%" PRId64 " Actual:%" PRId64 "",
  377. downloadContext_->getTotalLength(), actualFileSize));
  378. }
  379. }
  380. // Call Load, Save and file allocation command here
  381. if (progressInfoFile->exists()) {
  382. // load .aria2 file if it exists.
  383. progressInfoFile->load();
  384. pieceStorage_->getDiskAdaptor()->openFile();
  385. }
  386. else if (pieceStorage_->getDiskAdaptor()->fileExists()) {
  387. if (!option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  388. !option_->getAsBool(PREF_ALLOW_OVERWRITE) &&
  389. !option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  390. // TODO we need this->haltRequested = true?
  391. throw DOWNLOAD_FAILURE_EXCEPTION2(
  392. fmt(MSG_FILE_ALREADY_EXISTS,
  393. downloadContext_->getBasePath().c_str()),
  394. error_code::FILE_ALREADY_EXISTS);
  395. }
  396. pieceStorage_->getDiskAdaptor()->openFile();
  397. if (option_->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  398. pieceStorage_->markAllPiecesDone();
  399. }
  400. }
  401. else {
  402. pieceStorage_->getDiskAdaptor()->openFile();
  403. }
  404. progressInfoFile_ = progressInfoFile;
  405. auto entry = make_unique<BtCheckIntegrityEntry>(this);
  406. // --bt-seed-unverified=true is given and download has completed, skip
  407. // validation for piece hashes.
  408. if (option_->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  409. pieceStorage_->downloadFinished()) {
  410. entry->onDownloadFinished(commands, e);
  411. }
  412. else {
  413. processCheckIntegrityEntry(commands, std::move(entry), e);
  414. }
  415. return;
  416. }
  417. #endif // ENABLE_BITTORRENT
  418. if (downloadContext_->getFileEntries().size() == 1) {
  419. // TODO I assume here when totallength is set to DownloadContext and it is
  420. // not 0, then filepath is also set DownloadContext correctly....
  421. if (option_->getAsBool(PREF_DRY_RUN) ||
  422. downloadContext_->getTotalLength() == 0) {
  423. createNextCommand(commands, e, 1);
  424. return;
  425. }
  426. auto progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>(
  427. downloadContext_, nullptr, option_.get());
  428. adjustFilename(progressInfoFile);
  429. initPieceStorage();
  430. auto checkEntry = createCheckIntegrityEntry();
  431. if (checkEntry) {
  432. processCheckIntegrityEntry(commands, std::move(checkEntry), e);
  433. }
  434. return;
  435. }
  436. // TODO --dry-run is not supported for multifile download for now.
  437. if (option_->getAsBool(PREF_DRY_RUN)) {
  438. throw DOWNLOAD_FAILURE_EXCEPTION(
  439. "--dry-run in multi-file download is not supported yet.");
  440. }
  441. // TODO file size is known in this context?
  442. // In this context, multiple FileEntry objects are in
  443. // DownloadContext.
  444. if (e->getRequestGroupMan()->isSameFileBeingDownloaded(this)) {
  445. throw DOWNLOAD_FAILURE_EXCEPTION2(
  446. fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  447. downloadContext_->getBasePath().c_str()),
  448. error_code::DUPLICATE_DOWNLOAD);
  449. }
  450. initPieceStorage();
  451. if (downloadContext_->getFileEntries().size() > 1) {
  452. pieceStorage_->setupFileFilter();
  453. }
  454. auto progressInfoFile = std::make_shared<DefaultBtProgressInfoFile>(
  455. downloadContext_, pieceStorage_, option_.get());
  456. removeDefunctControlFile(progressInfoFile);
  457. // Call Load, Save and file allocation command here
  458. if (progressInfoFile->exists()) {
  459. // load .aria2 file if it exists.
  460. progressInfoFile->load();
  461. pieceStorage_->getDiskAdaptor()->openFile();
  462. }
  463. else if (pieceStorage_->getDiskAdaptor()->fileExists()) {
  464. if (!isCheckIntegrityReady() && !option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  465. // TODO we need this->haltRequested = true?
  466. throw DOWNLOAD_FAILURE_EXCEPTION2(
  467. fmt(MSG_FILE_ALREADY_EXISTS, downloadContext_->getBasePath().c_str()),
  468. error_code::FILE_ALREADY_EXISTS);
  469. }
  470. pieceStorage_->getDiskAdaptor()->openFile();
  471. }
  472. else {
  473. pieceStorage_->getDiskAdaptor()->openFile();
  474. }
  475. progressInfoFile_ = progressInfoFile;
  476. processCheckIntegrityEntry(commands,
  477. make_unique<StreamCheckIntegrityEntry>(this), e);
  478. }
  479. void RequestGroup::processCheckIntegrityEntry(
  480. std::vector<std::unique_ptr<Command>>& commands,
  481. std::unique_ptr<CheckIntegrityEntry> entry, DownloadEngine* e)
  482. {
  483. int64_t actualFileSize = pieceStorage_->getDiskAdaptor()->size();
  484. if (actualFileSize > downloadContext_->getTotalLength()) {
  485. entry->cutTrailingGarbage();
  486. }
  487. if ((option_->getAsBool(PREF_CHECK_INTEGRITY) ||
  488. downloadContext_->isChecksumVerificationNeeded()) &&
  489. entry->isValidationReady()) {
  490. entry->initValidator();
  491. // Don't save control file(.aria2 file) when user presses
  492. // control-c key while aria2 is checking hashes. If control file
  493. // doesn't exist when aria2 launched, the completed length in
  494. // saved control file will be 0 byte and this confuses user.
  495. // enableSaveControlFile() will be called after hash checking is
  496. // done. See CheckIntegrityCommand.
  497. disableSaveControlFile();
  498. e->getCheckIntegrityMan()->pushEntry(std::move(entry));
  499. return;
  500. }
  501. entry->onDownloadIncomplete(commands, e);
  502. }
  503. void RequestGroup::initPieceStorage()
  504. {
  505. std::shared_ptr<PieceStorage> tempPieceStorage;
  506. if (downloadContext_->knowsTotalLength() &&
  507. // Following conditions are needed for chunked encoding with
  508. // content-length = 0. Google's dl server used this before.
  509. (downloadContext_->getTotalLength() > 0
  510. #ifdef ENABLE_BITTORRENT
  511. || downloadContext_->hasAttribute(CTX_ATTR_BT)
  512. #endif // ENABLE_BITTORRENT
  513. )) {
  514. #ifdef ENABLE_BITTORRENT
  515. auto ps =
  516. std::make_shared<DefaultPieceStorage>(downloadContext_, option_.get());
  517. if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  518. if (isUriSuppliedForRequsetFileEntry(
  519. downloadContext_->getFileEntries().begin(),
  520. downloadContext_->getFileEntries().end())) {
  521. // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent
  522. // integrated downloads.
  523. A2_LOG_DEBUG("Using LongestSequencePieceSelector");
  524. ps->setPieceSelector(make_unique<LongestSequencePieceSelector>());
  525. }
  526. if (option_->defined(PREF_BT_PRIORITIZE_PIECE)) {
  527. std::vector<size_t> result;
  528. util::parsePrioritizePieceRange(result,
  529. option_->get(PREF_BT_PRIORITIZE_PIECE),
  530. downloadContext_->getFileEntries(),
  531. downloadContext_->getPieceLength());
  532. if (!result.empty()) {
  533. std::shuffle(std::begin(result), std::end(result),
  534. *SimpleRandomizer::getInstance());
  535. auto priSelector =
  536. make_unique<PriorityPieceSelector>(ps->popPieceSelector());
  537. priSelector->setPriorityPiece(std::begin(result), std::end(result));
  538. ps->setPieceSelector(std::move(priSelector));
  539. }
  540. }
  541. }
  542. #else // !ENABLE_BITTORRENT
  543. auto ps =
  544. std::make_shared<DefaultPieceStorage>(downloadContext_, option_.get());
  545. #endif // !ENABLE_BITTORRENT
  546. if (requestGroupMan_) {
  547. ps->setWrDiskCache(requestGroupMan_->getWrDiskCache());
  548. }
  549. if (diskWriterFactory_) {
  550. ps->setDiskWriterFactory(diskWriterFactory_);
  551. }
  552. tempPieceStorage = ps;
  553. }
  554. else {
  555. auto ps = std::make_shared<UnknownLengthPieceStorage>(downloadContext_);
  556. if (diskWriterFactory_) {
  557. ps->setDiskWriterFactory(diskWriterFactory_);
  558. }
  559. tempPieceStorage = ps;
  560. }
  561. tempPieceStorage->initStorage();
  562. if (requestGroupMan_) {
  563. tempPieceStorage->getDiskAdaptor()->setOpenedFileCounter(
  564. requestGroupMan_->getOpenedFileCounter());
  565. }
  566. segmentMan_ =
  567. std::make_shared<SegmentMan>(downloadContext_, tempPieceStorage);
  568. pieceStorage_ = tempPieceStorage;
  569. }
  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->attrs = downloadContext_->getAttributes();
  1018. res->fileEntries = downloadContext_->getFileEntries();
  1019. res->inMemoryDownload = inMemoryDownload_;
  1020. res->sessionDownloadLength = st.sessionDownloadLength;
  1021. res->sessionTime = std::chrono::duration_cast<std::chrono::milliseconds>(
  1022. downloadContext_->calculateSessionTime());
  1023. auto result = downloadResult();
  1024. res->result = result.first;
  1025. res->resultMessage = result.second;
  1026. res->followedBy = followedByGIDs_;
  1027. res->following = followingGID_;
  1028. res->belongsTo = belongsToGID_;
  1029. res->option = option_;
  1030. res->metadataInfo = metadataInfo_;
  1031. res->totalLength = getTotalLength();
  1032. res->completedLength = getCompletedLength();
  1033. res->uploadLength = st.allTimeUploadLength;
  1034. if (pieceStorage_ && pieceStorage_->getBitfieldLength() > 0) {
  1035. res->bitfield.assign(pieceStorage_->getBitfield(),
  1036. pieceStorage_->getBitfield() +
  1037. pieceStorage_->getBitfieldLength());
  1038. }
  1039. #ifdef ENABLE_BITTORRENT
  1040. if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  1041. const unsigned char* p = bittorrent::getInfoHash(downloadContext_);
  1042. res->infoHash.assign(p, p + INFO_HASH_LENGTH);
  1043. }
  1044. #endif // ENABLE_BITTORRENT
  1045. res->pieceLength = downloadContext_->getPieceLength();
  1046. res->numPieces = downloadContext_->getNumPieces();
  1047. res->dir = option_->get(PREF_DIR);
  1048. return res;
  1049. }
  1050. void RequestGroup::reportDownloadFinished()
  1051. {
  1052. A2_LOG_NOTICE(fmt(MSG_FILE_DOWNLOAD_COMPLETED,
  1053. downloadContext_->getBasePath().c_str()));
  1054. uriSelector_->resetCounters();
  1055. #ifdef ENABLE_BITTORRENT
  1056. if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  1057. TransferStat stat = calculateStat();
  1058. int64_t completedLength = getCompletedLength();
  1059. double shareRatio = completedLength == 0
  1060. ? 0.0
  1061. : 1.0 * stat.allTimeUploadLength / completedLength;
  1062. auto attrs = bittorrent::getTorrentAttrs(downloadContext_);
  1063. if (!attrs->metadata.empty()) {
  1064. A2_LOG_NOTICE(fmt(MSG_SHARE_RATIO_REPORT, shareRatio,
  1065. util::abbrevSize(stat.allTimeUploadLength).c_str(),
  1066. util::abbrevSize(completedLength).c_str()));
  1067. }
  1068. }
  1069. #endif // ENABLE_BITTORRENT
  1070. }
  1071. void RequestGroup::setURISelector(std::unique_ptr<URISelector> uriSelector)
  1072. {
  1073. uriSelector_ = std::move(uriSelector);
  1074. }
  1075. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  1076. {
  1077. if (!pieceStorage_ || !lastModifiedTime_.good()) {
  1078. return;
  1079. }
  1080. A2_LOG_INFO(fmt("Applying Last-Modified time: %s",
  1081. lastModifiedTime_.toHTTPDate().c_str()));
  1082. size_t n = pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_);
  1083. A2_LOG_INFO(fmt("Last-Modified attrs of %lu files were updated.",
  1084. static_cast<unsigned long>(n)));
  1085. }
  1086. void RequestGroup::updateLastModifiedTime(const Time& time)
  1087. {
  1088. if (time.good() && lastModifiedTime_ < time) {
  1089. lastModifiedTime_ = time;
  1090. }
  1091. }
  1092. void RequestGroup::increaseAndValidateFileNotFoundCount()
  1093. {
  1094. ++fileNotFoundCount_;
  1095. const int maxCount = option_->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  1096. if (maxCount > 0 && fileNotFoundCount_ >= maxCount &&
  1097. downloadContext_->getNetStat().getSessionDownloadLength() == 0) {
  1098. throw DOWNLOAD_FAILURE_EXCEPTION2(
  1099. fmt("Reached max-file-not-found count=%d", maxCount),
  1100. error_code::MAX_FILE_NOT_FOUND);
  1101. }
  1102. }
  1103. void RequestGroup::markInMemoryDownload() { inMemoryDownload_ = true; }
  1104. void RequestGroup::setTimeout(std::chrono::seconds timeout)
  1105. {
  1106. timeout_ = std::move(timeout);
  1107. }
  1108. bool RequestGroup::doesDownloadSpeedExceed()
  1109. {
  1110. int spd = downloadContext_->getNetStat().calculateDownloadSpeed();
  1111. return maxDownloadSpeedLimit_ > 0 && maxDownloadSpeedLimit_ < spd;
  1112. }
  1113. bool RequestGroup::doesUploadSpeedExceed()
  1114. {
  1115. int spd = downloadContext_->getNetStat().calculateUploadSpeed();
  1116. return maxUploadSpeedLimit_ > 0 && maxUploadSpeedLimit_ < spd;
  1117. }
  1118. void RequestGroup::saveControlFile() const
  1119. {
  1120. if (saveControlFile_) {
  1121. progressInfoFile_->save();
  1122. }
  1123. }
  1124. void RequestGroup::removeControlFile() const
  1125. {
  1126. progressInfoFile_->removeFile();
  1127. }
  1128. void RequestGroup::setDownloadContext(
  1129. const std::shared_ptr<DownloadContext>& downloadContext)
  1130. {
  1131. downloadContext_ = downloadContext;
  1132. if (downloadContext_) {
  1133. downloadContext_->setOwnerRequestGroup(this);
  1134. }
  1135. }
  1136. bool RequestGroup::p2pInvolved() const
  1137. {
  1138. #ifdef ENABLE_BITTORRENT
  1139. return downloadContext_->hasAttribute(CTX_ATTR_BT);
  1140. #else // !ENABLE_BITTORRENT
  1141. return false;
  1142. #endif // !ENABLE_BITTORRENT
  1143. }
  1144. void RequestGroup::enableSeedOnly()
  1145. {
  1146. if (seedOnly_ || !option_->getAsBool(PREF_BT_DETACH_SEED_ONLY)) {
  1147. return;
  1148. }
  1149. if (requestGroupMan_) {
  1150. seedOnly_ = true;
  1151. requestGroupMan_->decreaseNumActive();
  1152. requestGroupMan_->requestQueueCheck();
  1153. }
  1154. }
  1155. bool RequestGroup::isSeeder() const
  1156. {
  1157. #ifdef ENABLE_BITTORRENT
  1158. return downloadContext_->hasAttribute(CTX_ATTR_BT) &&
  1159. !bittorrent::getTorrentAttrs(downloadContext_)->metadata.empty() &&
  1160. downloadFinished();
  1161. #else // !ENABLE_BITTORRENT
  1162. return false;
  1163. #endif // !ENABLE_BITTORRENT
  1164. }
  1165. } // namespace aria2