RequestGroup.cc 40 KB

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