RequestGroup.cc 42 KB

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