RequestGroup.cc 41 KB

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