RequestGroup.cc 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. (std::chrono::seconds(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(std::chrono::seconds(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 = std::chrono::duration_cast<std::chrono::milliseconds>(
  1038. downloadContext_->calculateSessionTime());
  1039. res->result = downloadResult();
  1040. res->followedBy = followedByGIDs_;
  1041. res->belongsTo = belongsToGID_;
  1042. res->option = option_;
  1043. res->metadataInfo = metadataInfo_;
  1044. res->totalLength = getTotalLength();
  1045. res->completedLength = getCompletedLength();
  1046. res->uploadLength = st.allTimeUploadLength;
  1047. if(pieceStorage_ && pieceStorage_->getBitfieldLength() > 0) {
  1048. res->bitfield.assign(pieceStorage_->getBitfield(),
  1049. pieceStorage_->getBitfield() +
  1050. pieceStorage_->getBitfieldLength());
  1051. }
  1052. #ifdef ENABLE_BITTORRENT
  1053. if(downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  1054. const unsigned char* p = bittorrent::getInfoHash(downloadContext_);
  1055. res->infoHash.assign(p, p+INFO_HASH_LENGTH);
  1056. }
  1057. #endif // ENABLE_BITTORRENT
  1058. res->pieceLength = downloadContext_->getPieceLength();
  1059. res->numPieces = downloadContext_->getNumPieces();
  1060. res->dir = option_->get(PREF_DIR);
  1061. return res;
  1062. }
  1063. void RequestGroup::reportDownloadFinished()
  1064. {
  1065. A2_LOG_NOTICE(fmt(MSG_FILE_DOWNLOAD_COMPLETED,
  1066. downloadContext_->getBasePath().c_str()));
  1067. uriSelector_->resetCounters();
  1068. #ifdef ENABLE_BITTORRENT
  1069. if (downloadContext_->hasAttribute(CTX_ATTR_BT)) {
  1070. TransferStat stat = calculateStat();
  1071. int64_t completedLength = getCompletedLength();
  1072. double shareRatio = completedLength == 0 ?
  1073. 0.0 :
  1074. 1.0 * stat.allTimeUploadLength / completedLength;
  1075. auto attrs = bittorrent::getTorrentAttrs(downloadContext_);
  1076. if(!attrs->metadata.empty()) {
  1077. A2_LOG_NOTICE(fmt(MSG_SHARE_RATIO_REPORT,
  1078. shareRatio,
  1079. util::abbrevSize(stat.allTimeUploadLength).c_str(),
  1080. util::abbrevSize(completedLength).c_str()));
  1081. }
  1082. }
  1083. #endif // ENABLE_BITTORRENT
  1084. }
  1085. void RequestGroup::setURISelector(std::unique_ptr<URISelector> uriSelector)
  1086. {
  1087. uriSelector_ = std::move(uriSelector);
  1088. }
  1089. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  1090. {
  1091. if (!pieceStorage_ || !lastModifiedTime_.good()) {
  1092. return;
  1093. }
  1094. A2_LOG_INFO(fmt("Applying Last-Modified time: %s",
  1095. lastModifiedTime_.toHTTPDate().c_str()));
  1096. size_t n = pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_);
  1097. A2_LOG_INFO(fmt("Last-Modified attrs of %lu files were updated.",
  1098. static_cast<unsigned long>(n)));
  1099. }
  1100. void RequestGroup::updateLastModifiedTime(const Time& time)
  1101. {
  1102. if (time.good() && lastModifiedTime_ < time) {
  1103. lastModifiedTime_ = time;
  1104. }
  1105. }
  1106. void RequestGroup::increaseAndValidateFileNotFoundCount()
  1107. {
  1108. ++fileNotFoundCount_;
  1109. const int maxCount = option_->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  1110. if (maxCount > 0 && fileNotFoundCount_ >= maxCount &&
  1111. downloadContext_->getNetStat().getSessionDownloadLength() == 0) {
  1112. throw DOWNLOAD_FAILURE_EXCEPTION2(fmt("Reached max-file-not-found count=%d",
  1113. maxCount),
  1114. error_code::MAX_FILE_NOT_FOUND);
  1115. }
  1116. }
  1117. void RequestGroup::markInMemoryDownload()
  1118. {
  1119. inMemoryDownload_ = true;
  1120. }
  1121. void RequestGroup::setTimeout(std::chrono::seconds timeout)
  1122. {
  1123. timeout_ = std::move(timeout);
  1124. }
  1125. bool RequestGroup::doesDownloadSpeedExceed()
  1126. {
  1127. int spd = downloadContext_->getNetStat().calculateDownloadSpeed();
  1128. return maxDownloadSpeedLimit_ > 0 && maxDownloadSpeedLimit_ < spd;
  1129. }
  1130. bool RequestGroup::doesUploadSpeedExceed()
  1131. {
  1132. int spd = downloadContext_->getNetStat().calculateUploadSpeed();
  1133. return maxUploadSpeedLimit_ > 0 && maxUploadSpeedLimit_ < spd;
  1134. }
  1135. void RequestGroup::saveControlFile() const
  1136. {
  1137. if(saveControlFile_) {
  1138. progressInfoFile_->save();
  1139. }
  1140. }
  1141. void RequestGroup::removeControlFile() const
  1142. {
  1143. progressInfoFile_->removeFile();
  1144. }
  1145. void RequestGroup::setDownloadContext
  1146. (const std::shared_ptr<DownloadContext>& downloadContext)
  1147. {
  1148. downloadContext_ = downloadContext;
  1149. if(downloadContext_) {
  1150. downloadContext_->setOwnerRequestGroup(this);
  1151. }
  1152. }
  1153. bool RequestGroup::p2pInvolved() const
  1154. {
  1155. #ifdef ENABLE_BITTORRENT
  1156. return downloadContext_->hasAttribute(CTX_ATTR_BT);
  1157. #else // !ENABLE_BITTORRENT
  1158. return false;
  1159. #endif // !ENABLE_BITTORRENT
  1160. }
  1161. void RequestGroup::enableSeedOnly()
  1162. {
  1163. if(seedOnly_ || !option_->getAsBool(PREF_BT_DETACH_SEED_ONLY)) {
  1164. return;
  1165. }
  1166. if(requestGroupMan_) {
  1167. seedOnly_ = true;
  1168. requestGroupMan_->decreaseNumActive();
  1169. requestGroupMan_->requestQueueCheck();
  1170. }
  1171. }
  1172. } // namespace aria2