RequestGroup.cc 40 KB

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