RequestGroup.cc 40 KB

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